id
stringlengths
10
10
title
stringlengths
26
192
abstract
stringlengths
172
1.92k
authors
stringlengths
7
591
published_date
stringlengths
20
20
link
stringlengths
33
33
markdown
stringlengths
269
344k
2302.08447
Graph Neural Networks over the Air for Decentralized Tasks in Wireless Networks
Graph neural networks (GNNs) model representations from networked data and allow for decentralized inference through localized communications. Existing GNN architectures often assume ideal communications and ignore potential channel effects, such as fading and noise, leading to performance degradation in real-world implementation. Considering a GNN implemented over nodes connected through wireless links, this paper conducts a stability analysis to study the impact of channel impairments on the performance of GNNs, and proposes graph neural networks over the air (AirGNNs), a novel GNN architecture that incorporates the communication model. AirGNNs modify graph convolutional operations that shift graph signals over random communication graphs to take into account channel fading and noise when aggregating features from neighbors, thus, improving architecture robustness to channel impairments during testing. We develop a channel-inversion signal transmission strategy for AirGNNs when channel state information (CSI) is available, and propose a stochastic gradient descent based method to train AirGNNs when CSI is unknown. The convergence analysis shows that the training procedure approaches a stationary solution of an associated stochastic optimization problem and the variance analysis characterizes the statistical behavior of the trained model. Experiments on decentralized source localization and multi-robot flocking corroborate theoretical findings and show superior performance of AirGNNs over wireless communication channels.
Zhan Gao, Deniz Gunduz
2023-02-16T17:40:23Z
http://arxiv.org/abs/2302.08447v3
# AirGNNs: Graph Neural Networks over the Air ###### Abstract Graph neural networks (GNNs) are information processing architectures that model representations from networked data and allow for decentralized implementation through localized communications. Existing GNN architectures often assume ideal communication links and ignore channel effects, such as fading and noise, leading to performance degradation in real-world implementation. This paper proposes graph neural networks over the air (AirGNNs), a novel GNN architecture that incorporates the communication model into the architecture. AirGNN modifies the graph convolutional operation that shifts graph signals over random communication graphs to take into account channel fading and noise when aggregating features from neighbors, thus, improving the architecture robustness to channel impairments during testing. We propose a stochastic gradient descent based method to train the AirGNN, and show that the training procedure converges to a stationary solution. Numerical simulations on decentralized source localization and multi-robot flocking corroborate theoretical findings and show superior performance of the AirGNN over wireless communication channels. Graph neural networks, decentralized implementation, wireless channel fading, Gaussian noise ## I Introduction Graph neural networks (GNNs) are one of the key tools to extract features from networked data [1, 2, 3, 4], and have found wide applications in wireless communications [5, 6], multi-agent coordination [7, 8, 9] and recommendation systems [10, 11, 12]. GNNs extend conventional convolutional neural networks (CNNs) to graph structures by employing a multi-layered architecture with each layer comprising a graph filter bank and a pointwise nonlinearity [13]. With the distributed nature of graph filters, GNNs can compute output features with local neighborhood information. This makes GNNs suitable candidates for decentralized implementation, where each node takes actions by only sensing its local environment and communicating with its neighboring nodes [14, 15]. On the other hand, when implemented in a decentralized fashion, information exchanges among neighboring nodes of GNNs require wireless transmissions. Existing works often assume ideal communications and ignore channel impairments, such as fading and noise, which affect all wireless transmissions [16, 17, 18]. In real-world wireless networks, each node receives faded/noisy messages from its neighbors and computes its output that mismatches the one assuming ideal communications during training; hence, resulting in performance degradation during testing. The work in [19] studied the privacy-preserving problem in decentralized implementation of GNNs over wireless communication channels and used channel state information (CSI) to design signaling strategies for privacy enhancement, while [20] considered the decentralized power allocation problem and estimated CSI to generate transmitted power with GNNs. However, these works require CSI to design signaling strategies for decentralized implementation, which may be inaccurate or unavailable, and focus on specific problems, which are not applicable for general decentralized tasks. In addition, they apply the message passing mechanism of GNNs based on direct adjacencies, i.e., immediate neighbors, without higher-order/multi-hop information. This paper proposes the AirGNN which incorporates wireless communication channels directly into the GNN architecture. This is inspired by [21], which showed that incorporating channel noise into training can make deep neural networks more robust when network parameters are delivered over noisy communication channels. The AirGNN accounts for channel fading effects and Gaussian noise among the nodes of a GNN during training, where each node generates features based on faded/noisy neighborhood information from multi-hop communications. This yields the learned parameters robust to wireless channel impairments during implementation and improves performance in decentralized tasks without requiring CSI to modulate signals. Our contributions are summarized as follows: 1. We develop the AirGNN framework as a multi-layered architecture where each layer consists of graph filters over the airGFs and a pointwise nonlinearity (Sec. II). The AirGF shifts graph signals over wireless communication channels in an uncoded fashion to collect multi-hop neighborhood information and generates higher-level features by aggregating faded/noisy information. These features are passed to the nonlinearity and subsequently to successive layers to generate the output of the AirGNN. 2. We formulate the cost function with respect to (w.r.t.) channel fading effects and Gaussian noise, and develop a stochastic gradient descent (SGD) based method to train the AirGNN (Sec. III). We show that this training procedure is equivalent to solving an associated stochastic optimization problem with SGD and prove its convergence to a stationary solution at a rate proportional to the inverse square root of the number of iterations (Sec. IV). 3. We evaluate AirGNNs numerically on the decentralized tasks of source localization and multi-robot flocking to corroborate theoretical findings, and show that they consistently outperform the conventional GNN implemented over noisy communication channels, i.e., when channel effects are ignored during training (Sec. V). ## II GNNs over the Air (AirGNNs) Let \(\mathcal{G}=(\mathcal{V},\mathcal{E})\) be a graph with node set \(\mathcal{V}=\{1,\cdots,n\}\) and edge set \(\mathcal{E}\). The graph structure can be represented by an \(n\times n\) matrix \(\mathbf{S}\), referred to as the graph shift operator, with \((i,j)\)th entry \([\mathbf{S}]_{ij}=s_{ij}\) non-zero only if node \(j\) is connected to node \(i\), i.e., \((j,i)\in\mathcal{E}\), or \(i=j\), such as the adjacency matrix and the Laplacian matrix \(\mathbf{L}\)[22]. The graph signal is a vector defined on the nodes \(\mathbf{x}=[x_{1},\ldots,x_{n}]^{\top}\), where the \(i\)th entry \(x_{i}\) is the signal value associated to node \(i\). The graph serves as a mathematical representation of the network topology and the graph signal captures the network states. For example, in a multi-agent system, nodes can correspond to agents, edges to communication links, and signal values to agent states. The graph shift operation \(\mathbf{S}\mathbf{x}\) is one of the key operations in graph signal processing. It assigns to each node \(i\) the aggregated information from its neighboring nodes \([\mathbf{x}^{(1)}]_{i}=[\mathbf{S}\mathbf{x}]_{i}\) and extends the signal shifting from the time/space domain to the graph domain. In the context of real-world networked systems (e.g., sensor networks and multi-agent systems), this corresponds to message exchanges between the neighboring sensors/agents over available communications links. However, \(\mathbf{S}\mathbf{x}\) assumes perfect signal transmissions between nodes and ignores the fact that communication links suffer from channel fading and additive noise in practice. **Communication channel.** We assume that each node exchanges information wirelessly with the neighboring nodes in its communication range. The channel between the nodes \(i\) and \(j\) is modeled as a slow fading channel, the signal value \([\mathbf{x}]_{j}\) is transmitted in an uncoded/analog manner, and the neighborhood information is aggregated at node \(i\) with over-the-air computation, i.e., \[[\mathbf{x}^{(1)}]_{i}=\sum_{j:(i,j)\in\mathcal{E}}h_{ij}^{(1)}[\mathbf{x}]_{ j}+n_{i}^{(1)},\text{ for }i=1,...,n, \tag{1}\] where \(h_{ij}^{(1)}\) is the channel gain from node \(j\) to node \(i\) and \(n_{i}^{(1)}\) is the zero-mean Gaussian noise at node \(i\). The channel fading effects \(\{h_{ij}\}\) are assumed independent across communication links, which are fixed throughout a single transmission but changes from one transmission to the next in an independent and identically distributed (i.i.d.) manner. Hence, each node receives noisy and faded versions of the messages sent by its neighbors, and the graph shift operation becomes \[\mathbf{x}^{(1)}=\mathbf{S}_{\text{air}}^{(1)}\mathbf{x}+\mathbf{n}^{(1)}, \tag{2}\] where \(\mathbf{S}_{\text{air}}^{(1)}\) is the graph shift operator with channel fading effects, i.e., \([\mathbf{S}_{\text{air}}^{(1)}]_{ij}=h_{ij}^{(1)}\) for any \((i,j)\in\mathcal{E}\), and \(\mathbf{n}\) is the Gaussian noise vector with \([\mathbf{n}]_{i}=n_{i}\) for \(i=1,\ldots,n\). Different from its ideal counterpart \(\mathbf{S}\mathbf{x}\), the signal shifting in (2) depends not only on the graph topology, but also on the communication channels, and we refer to the latter as the _graph shift operation over the air_ (AirGSO). **Graph filter over the air (AirGF).** AirGF is a linear combination of multi-shifted signals over the air. Specifically, an AirGSO shifts \(\mathbf{x}\) over \(\mathbf{S}\) through wireless communication channels and obtains the one-shifted signal \(\mathbf{x}^{(1)}\) that aggregates \(1\)-hop neighborhood information [cf. (2)]. By recursively shifting \(\mathbf{x}\), the \(k\)-shifted signal \(\mathbf{x}^{(k)}\) is \[\mathbf{x}^{(k)} =\mathbf{S}_{\text{air}}^{(k)}\Big{(}\mathbf{S}_{\text{air}}^{(k- 1)}\big{(}\cdots+\mathbf{n}^{(1)}\big{)}+\mathbf{n}^{(k-1)}\Big{)}+\mathbf{n} ^{(k)} \tag{3}\] \[=\prod_{\kappa=1}^{k}\mathbf{S}_{\text{air}}^{(\kappa)}\mathbf{x }+\sum_{i=1}^{k-1}\prod_{\kappa=i+1}^{k}\mathbf{S}_{\text{air}}^{(\kappa)} \mathbf{n}^{(i)}+\mathbf{n}^{(k)},\] where \(\mathbf{S}_{\text{air}}^{(k)}\) and \(\mathbf{n}^{(k)}\) are, respectively, the AirGSO and Gaussian noise vector at the \(k\)th graph shift operation.1 The \(k\)-shifted signal \(\mathbf{x}^{(k)}\) accesses farther nodes and aggregates the \(k\)-hop neighborhood information with communication noise. Given a sequence of shifted signals \(\{\mathbf{x},\mathbf{x}^{(1)},\ldots,\mathbf{x}^{(K)}\}\), the AirGF aggregates them with a set of filter coefficients as Footnote 1: For convenience of expression, we assume the summation \(\sum_{0}^{b}=0\) if \(b<a\). \[\mathbf{H}_{\text{air}}(\mathbf{S})\mathbf{x}=\sum_{k=0}^{K} \alpha_{k}\mathbf{x}^{(k)}=\mathbf{P}_{\text{air}}(\mathbf{S},\mathbf{x})+ \mathbf{N}_{\text{air}}(\mathbf{S},\mathbf{n}) \tag{4}\] \[=\sum_{k=0}^{K}\alpha_{k}\prod_{\kappa=1}^{k}\mathbf{S}_{\text{air }}^{(\kappa)}\mathbf{x}+\sum_{k=1}^{K}\alpha_{k}\left(\sum_{i=1}^{k-1}\prod_{ \kappa=i+1}^{k}\mathbf{S}_{\text{air}}^{(\kappa)}\mathbf{n}^{(i)}+\mathbf{n }^{(k)}\right),\] where \(\mathbf{x}^{(0)}=\mathbf{x}\) by default and \(\boldsymbol{\alpha}=[\alpha_{0},\ldots,\alpha_{K}]^{\top}\) are the filter coefficients. The first term in (4) captures the signal information perturbed by the communication channels, referred to as the signal component, while the second term in (4) is the accumulated noise, referred to as the noise component. The AirGF is a shift-and-sum operator that extends graph convolution to wireless communication channels. It aggregates the neighborhood information up to a radius of \(K\) and accounts for channel fading and Gaussian noise when shifting signals over the underlying graph. AirGF reduces to a conventional graph filter in ideal scenarios, where the communication links are perfect, i.e., \(h_{ij}^{(1)}=1\) and \(n_{i}^{(1)}=0\) in (1). **AirGNN.** AirGNN is an information processing architecture that consists of multiple layers, where each layer comprises a bank of AirGFs and a pointwise nonlinearity. Specifically, at layer \(\ell\), we have \(F\) input signals \(\{\mathbf{x}_{\ell-1}^{g}\}_{g=1}^{F}\) generated by the previous layer \(\ell-1\). The latter are processed by a bank of AirGFs \(\{\mathbf{H}_{\text{air},\ell}^{fg}\}_{fg}\), aggregated over the input index \(g\), and passed through a pointwise nonlinearity \(\sigma(\cdot)\) as \[\mathbf{x}_{\ell}^{f}=\sigma\left(\sum_{g=1}^{F}\mathbf{H}_{\text{air},\ell}^{fg }(\mathbf{S})\mathbf{x}_{\ell-1}^{g}\right),\text{ }\forall\text{ }f=1,\ldots,F. \tag{5}\] The outputs \(\{\mathbf{x}_{\ell}^{f}\}_{f=1}^{F}\) are fed into layer \(\ell+1\) until the final layer \(L\). Without loss of generality, we consider a single input \(\mathbf{x}_{0}^{1}=\mathbf{x}\) and a single output \(\mathbf{x}_{L}^{1}\). The AirGNN can be represented as a nonlinear mapping \(\boldsymbol{\Phi}_{\text{air}}(\mathbf{x},\mathbf{S},\mathcal{A})\) of graph signals \(\mathbf{x}\), where \(\mathcal{A}\) are the architecture parameters comprising all filter coefficients. AirGNN reduces to a conventional GNN if assuming ideal communications without channel fading or noise among the neighboring nodes. **Decentralized implementation.** AirGNN and AirGF are ready for decentralized implementation, i.e., each node can compute its own output with local neighborhood information. Specifically, the one-shifted signal \([\mathbf{x}^{(1)}]_{i}\) at node \(i\) can be computed with signal values \(\{[\mathbf{x}]_{j}\}_{j:(i,j)\in\mathcal{E}}\) at neighboring nodes transmitted through wireless communication links in an uncoded fashion [cf. (1)]. Likewise, \(K\) shifted signals \(\{[\mathbf{x}^{(k)}]_{i}\}_{k=0}^{K}\) at node \(i\) can be computed with recursive communications between neighboring nodes. Since the aggregation of the shifted signals \(\{[\mathbf{x}^{(k)}]_{i}\}_{k=0}^{K}\) with the filter coefficients \(\{\alpha_{k}\}_{k=0}^{K}\) does not involve inter-node operations, node \(i\) can compute the filter output \([\mathbf{H}_{\text{air}}(\mathbf{S})\mathbf{x}]_{i}\) locally with neighborhood information and the AirGF allows for a decentralized implementation. AirGNN consists of AirGFs and nonlinearities, where the former is decentralized and the latter is pointwise and local; hence, inheriting the decentralized implementation. This implies that a node does not need signal values of all the nodes and the full knowledge of the graph to compute the AirGNN/AirGF output, but only the ability to communicate local signals in a synchronized manner with their neighbors, in order to allow over-the-air aggregation, similarly to [23, 24]. With the consideration of wireless communication channels, the AirGNN output is a random variable w.r.t. channel state information (CSI) and Gaussian noise [cf. (1)]. It is unclear how to train the AirGNN, whether the training procedure converges to a stationary solution, and what solution it searches for. We address these aspects in the following sections. ## III Training We develop a SGD based method to train the AirGNN. For a specific task with the training set \(\mathcal{R}=\{(\mathbf{x}_{r},\mathbf{y}_{r})\}_{r=1}^{R}\) and loss function \(\ell(\cdot)\), we define the objective function as the expected loss over the training set \[\mathcal{L}(\mathcal{R},\mathbf{S},\mathcal{A})=\frac{1}{R}\sum_{r=1}^{R}\ell (\mathbf{y}_{r},\mathbf{\Phi}_{\mathrm{air}}(\mathbf{x}_{r},\mathbf{S}, \mathcal{A})). \tag{6}\] Since the AirGNN output \(\mathbf{\Phi}_{\mathrm{air}}(\mathbf{x}_{r},\mathbf{S},\mathcal{A})\) is a random variable, the objective \(\mathcal{L}(\mathcal{R},\mathbf{S},\mathcal{A})\) is a random function w.r.t. channel fading effects and Gaussian noise. The goal is to find the optimal architecture parameters \(\mathcal{A}^{*}\) that minimize the objective function \(\mathcal{L}(\mathcal{R},\mathbf{S},\mathcal{A})\) while accounting for channel impairments. We propose to update \(\mathcal{A}\) with gradient descent while incorporating the randomness of the communication channels during training. Specifically, let \(\mathbf{\Phi}_{\mathrm{air}}(\mathbf{x},\mathbf{S},\mathcal{A}|\mathbf{h}, \mathbf{n})\) be a sample of the AirGNN output on the graph signal \(\mathbf{x}\), where \(\mathbf{h}\) and \(\mathbf{n}\) are samples of the CSI and the Gaussian noise, respectively, throughout graph shift operations of all AirGFs in the architecture. The training procedure contains successive iterations to optimize the objective function, where each iteration \(t\) consists of a forward and a backward phase. In the forward phase, it samples the CSI \(\mathbf{h}_{t}\) and the Gaussian noise \(\mathbf{n}_{t}\) for a deterministic AirGNN architecture \(\mathbf{\Phi}_{\mathrm{air}}(\mathbf{x},\mathbf{S},\mathcal{A}_{t}|\mathbf{h} _{t},\mathbf{n}_{t})\) with parameters \(\mathcal{A}_{t}\). The latter processes a random set of the training data \(\mathcal{R}_{t}\in\mathcal{R}\) to approximate the objective function as \[\mathcal{L}(\mathcal{R}_{t},\mathbf{S}_{\nu}\mathcal{A}_{t}|\mathbf{h}_{t}, \mathbf{n}_{t})\!=\!\frac{1}{|\mathcal{R}_{t}|}\!\!\sum_{r=1}^{|\mathcal{R}_{t }|}\!\!\ell(\mathbf{y}_{r},\mathbf{\Phi}_{\mathrm{air}}(\mathbf{x}_{r}, \!\mathbf{S}_{\nu}\mathcal{A}_{t}|\mathbf{h}_{t},\!\mathbf{n}_{t})), \tag{7}\] where \((\mathbf{x}_{r},\mathbf{y}_{r})\in\mathcal{R}_{t}\) and \(|\mathcal{R}_{t}|\) is the number of data samples in set \(\mathcal{R}_{t}\). In the backward phase, the parameters \(\mathcal{A}_{t}\) are updated with SGD as \[\mathcal{A}_{t+1}=\mathcal{A}_{t}-\gamma_{t}\nabla_{\mathcal{A}}\mathcal{L}( \mathcal{R}_{t},\mathbf{S},\mathcal{A}_{t}|\mathbf{h}_{t},\mathbf{n}_{t}), \tag{8}\] where \(\gamma_{t}\) is the step-size. It accounts for the effects of the communication channels by updating the parameters \(\mathcal{H}_{t}\) with a stochastic gradient \(\nabla_{\mathcal{A}}\mathcal{L}(\mathcal{R}_{t},\mathbf{S},\mathcal{A}_{t}| \mathbf{h}_{t},\mathbf{n}_{t})\) at each iteration \(t\). The stochasticity results from the randomness of the CSI \(\mathbf{h}_{t}\), the Gaussian noise \(\mathbf{n}_{t}\), as well as the randomly chosen samples \(\mathcal{R}_{t}\). Algorithm 1 summarizes the proposed training procedure. AirGNN incorporates communication channel impairments into the training procedure, where each node relies on faded and noisy information from its neighbors [cf. (1)]. This matches the fading and noise distributions encountered in the decentralized implementation at the inference phase and renders the trained parameters more robust to transmission perturbations during testing; hence, yielding an improved performance and a robust transference for decentralized tasks. However, it remains unclear if this training procedure converges and what solution it searches for. In the next section, we conduct the convergence analysis and interpret the convergent solution. ``` 1:Input: training set \(\mathcal{R}\), loss function \(\ell\), initial parameters \(\mathcal{A}_{0}\) 2:for\(t=1,\ldots,T\)do 3: Sample CSI \(\mathbf{h}_{t}\) and Gaussian noise \(\mathbf{n}_{t}\) 4: Determine AirGNN architecture \(\mathbf{\Phi}_{\mathrm{air}}(\cdot,\mathbf{S},\mathcal{A}_{t}|\mathbf{h}_{t}, \mathbf{n}_{t})\) 5: Sample \(\mathcal{R}_{t}\subseteq\mathcal{R}\) and compute AirGNN outputs \(\{\mathbf{\Phi}_{\mathrm{air}}(\mathbf{x}_{r},\mathbf{S},\mathcal{A}_{t}| \mathbf{h}_{t},\mathbf{n}_{t})\}_{r=1}^{|\mathcal{R}_{t}|}\) 6: Compute objective \(\mathcal{L}(\mathcal{R}_{t},\mathbf{S},\mathcal{A}_{t}|\mathbf{h}_{t},\mathbf{n} _{t})\) as in (7) 7: Compute stochastic gradient \(\nabla_{\mathcal{A}}\mathcal{L}(\mathcal{R}_{t},\mathbf{S},\mathcal{A}_{t}| \mathbf{h}_{t},\mathbf{n}_{t})\) 8: Update parameters \(\mathcal{A}_{t}\) with step-size \(\gamma_{t}\) as in (8) 9:endfor ``` **Algorithm 1** Training Procedure of AirGNN ## IV Convergence We begin by considering the following stochastic optimization problem as \[\min_{\mathcal{A}}\bar{\mathcal{L}}(\mathcal{A})=\min_{\mathcal{A}}\mathbb{E} _{\mathbf{h},\mathbf{n}}[\mathcal{L}(\mathcal{R},\mathbf{S},\mathcal{A}| \mathbf{h},\mathbf{n})], \tag{9}\] where the expectation \(\mathbb{E}_{\mathbf{h},\mathbf{n}}[\cdot]\) is w.r.t. \(\mathbf{h}\) and \(\mathbf{n}\). The standard method to solve problem (9) is the SGD, which approximates the true gradient with the gradient of some random sample and leverages the latter to update model parameters - see Algorithm 2. Theorem 1 relates the proposed training procedure to this stochastic optimization problem (9). **Theorem 1**.: Performing the proposed training procedure on the AirGNN model [Alg. 1] is equivalent to running SGD on the stochastic optimization problem (9) [Alg. 2]. Proof.: See Appendix A. Theorem 1 provides interpretations for the proposed training procedure, i.e., its goal is to search the solution of the stochastic optimization problem (9). Moreover, the result indicates that we can show the convergence of the proposed training procedure by proving that of the SGD on problem (9). Since AirGNN is a nonlinear parameterization, problem (9) is typically non-convex. This motivates us to consider the convergence criterion as the gradient norm \(\|\nabla_{\mathcal{A}}\bar{\mathcal{L}}(\mathcal{A})\|_{2}^{2}\), which is commonly used to quantify the first-order stationarity in the non-convex setting. To proceed, we need the following assumptions. **Assumption 1**.: The gradient of the expected objective function \(\bar{\mathcal{L}}(\mathcal{A})\) in problem (9) is Lipschitz continuous, i.e., there exists a constant \(C_{L}\) such that \[\|\nabla_{\mathcal{A}}\bar{\mathcal{L}}(\mathcal{A}_{1})-\nabla_{\mathcal{A}} \bar{\mathcal{L}}(\mathcal{A}_{2})\|_{2}\leq C_{L}\|\mathcal{A}_{1}-\mathcal{A}_{ 2}\|_{2} \tag{10}\] for any architecture parameters \(\mathcal{A}_{1}\) and \(\mathcal{A}_{2}\). **Assumption 2**.: The gradient of the objective function \(\mathcal{L}(\mathcal{R},\mathbf{S},\mathcal{A}|\mathbf{h},\mathbf{n})\) in problem (9) is bounded, i.e., there exists a constant \(C_{g}\) such that \[\|\nabla_{\mathcal{A}}\mathcal{L}(\mathcal{R},\mathbf{S},\mathcal{A}|\mathbf{h}, \mathbf{n})\|_{2}\leq C_{g}. \tag{11}\] Assumptions 1-2 are standard in optimization theory [25], which provide a handle to deal with the gradient stochasticity during training. Theorem 2 characterizes the convergence of the proposed training procedure. **Theorem 2**.: Consider the AirGNN operation in (5) with the training procedure in Algorithm 1 and the stochastic optimization problem (9) with the objective function satisfying Assumptions 1-2 w.r.t. \(C_{L}\) and \(C_{g}\). Let \(T\) be the total number of training iterations and \(\mathcal{A}^{*}\) the global optimal solution of problem (9). Then, for any initial parameters \(\mathcal{A}_{0}\) and the step-size \[\gamma_{t}=\gamma=\sqrt{\frac{2\left(\bar{\mathcal{L}}(\mathcal{A}_{0})-\bar{ \mathcal{L}}(\mathcal{A}^{*})\right)}{TC_{L}C_{g}^{2}}}, \tag{12}\] it holds that \[\min_{0\leq t\leq T-1}\mathbb{E}\left[\|\nabla_{\mathcal{A}}\bar{\mathcal{L}}( \mathcal{A}_{t})\|_{2}^{2}\right]\leq\frac{C}{\sqrt{T}} \tag{13}\] with \(C\!=\!\sqrt{2\left(\bar{\mathcal{L}}(\mathcal{A}_{0})\!-\!\bar{\mathcal{L}}( \mathcal{A}^{*})\right)C_{L}C_{g}}\) a constant. Proof.: See Appendix B. Theorem 2 states that the proposed AirGNN training procedure minimizes the stochastic optimization problem (9) and the architecture parameters converge to a stationary solution with a rate on the order of \(\mathcal{O}(1/\sqrt{T})\). The result characterizes the convergence behavior and validates the effectiveness of the proposed training procedure. The selection of the step-size \(\gamma_{t}\) in (12) depends on the total number of iterations \(T\), while it is typically selected as \(\gamma_{t}\propto 1/t\) or \(1/\sqrt{t}\) in practice. It is worth mentioning that Theorem 2 guarantees local convergence because of the non-convexity, i.e., the objective function converges to a local stationary minimum rather than a global one. The latter can be improved by training the AirGNN architecture multiple times and selecting the best solution. ## V Experiments We evaluate AirGNN on the decentralized tasks of source localization (Sec. V-A) and multi-robot flocking (Sec. V-B). The ADAM optimizer is used with decaying factors \(\beta_{1}=0.9\), \(\beta_{2}=0.999\)[26] and the results are averaged over \(10\) simulations. ### _Source Localization_ This experiment considers a signal diffusion process over a stochastic block model (SBM) graph, where the intra- and the inter-community edge probabilities are \(0.8\) and \(0.2\). The graph has \(n=100\) nodes uniformly divided into \(10\) communities and each community has a source node \(s_{c}\) for \(c=1,\ldots,10\). The goal is to find the source community of a diffused signal in a decentralized manner. The initial signal is a Kronecker delta \(\boldsymbol{\delta}_{c}\in\mathbb{R}^{n}\) originated at one of the source nodes \(\{s_{c}\}_{c=1}^{10}\) and is diffused over the graph at time \(\tau\) as \(\mathbf{x}_{c,\tau}=\mathbf{S}^{*}\boldsymbol{\delta}_{c}+\mathbf{n}\) with \(\mathbf{S}=\mathbf{A}/\lambda_{max}(\mathbf{A})\) and \(\mathbf{n}\) a zero-mean Gaussian noise. The dataset consists of \(1.5\times 10^{4}\) samples with the source node \(s_{c}\) and the diffusion time \(\tau\) selected randomly from \(\{s_{1},\ldots,s_{10}\}\) and \(\{1,\ldots,100\}\), which are split into \(10^{4}\) samples for training, \(2.5\times 10^{3}\) for validation, and \(2.5\times 10^{3}\) for testing. The AirGNN has two layers, each comprising \(64\) filters of order \(5\) and ReLU nonlinearity. We consider independent Rayleigh fading channels between the nodes with distribution scale parameter \(\delta\) and the Gaussian noise with signal-to-noise ratio (SNR) \(40\)dB. The learning rate is set to \(10^{-3}\), the batch-size to \(50\), and the performance is measured in terms of the classification accuracy. Fig. 0(a) shows the training procedure of the AirGNN with the scale parameter \(\delta=1\). We see that the training/validation cost decreases with the iteration and approaches a stationary solution, which corroborates the convergence analysis in Theorem 2. The convergence curve fluctuates, because the channel fading effects and mini-batch sampling render the AirGNN output random. Fig. 0(b) depicts the performance of the AirGNN with different scale parameters \(\delta\) corresponding to different channel conditions. We compare with two baselines: (i) GNN without channel fading and noise, and (ii) GNN with channel fading and noise. The first considers a classical GNN with no fading and noise, i.e., \(h_{ij}^{(k)}=1\) and \(n_{i}^{(k)}=0\) for \(k=1,\ldots,K\) [cf. (1)], during both training and inference. This is an ideal communication scenario, which may not hold in real-world wireless applications and serves as an upper bound only for reference. The second considers fading and noise during inference, which is the practical scenario considered in this paper, but ignores them during training. The GNN without fading and noise exhibits the best performance as expected as it does not consider any channel effects. The AirGNN consistently outperforms the GNN with fading and noise. This corroborates the theoretical analysis, i.e., the AirGNN accounts for the stochasticity of the communication channels during training, which provides robustness to channel fading effects during inference. Moreover, the AirGNN maintains a good performance in different channel conditions, while the GNN suffers more degradation in severe channels when \(\delta\) is small or large. The latter highlights the importance of robustness to communication noise. ### _Multi-Robot Flocking_ This experiment considers the robot swarm control over the communication graph. The goal is to learn a decentralized controller that coordinates the robots to move together and avoid collision. The network has \(n=50\) robots with initial velocities sampled randomly in \([-3m/s,3m/s]^{2}\), and robot \(i\) can communicate with robot \(j\) if they are within a communication radius of \(r=1.5m\). The communication graph is \(\mathcal{G}=(\mathcal{V},\mathcal{E})\) with the node set \(\mathcal{V}\) as the robots and the edge set \(\mathcal{E}\) as available communication links, and the graph signal \(\mathbf{x}\) is the relevant features of robot positions and velocities. We use imitation learning to train the AirGNN by mimicking the optimal centralized controller [7]. The dataset consists of \(450\) trajectories of \(100\) time steps, which are split into \(400\) trajectories for training, \(25\) for validation, and \(25\) for testing. We consider a single-layer AirGNN with \(32\) filters of order \(5\) and the hyperbolic tangent nonlinearity. The learning rate is and the batch-size is \(20\). We measure the performance with the variance of robot velocities for a trajectory, which quantifies how far from the consensus the robots are. Fig. (c)c compares the performance of the AirGNN with two baselines in different channel conditions. The AirGNN performs comparably to the GNN without fading and noise with slight degradation. This is because the information loss induced by channel impairments leads to inevitable errors, which cannot be resolved completely by training. The AirGNN exhibits a better performance compared to the GNN with fading and noise, which is particularly significant for small or large values of \(\delta\), i.e., worse channel conditions. We attribute this behavior to the robustness of the AirGNN to fading effects because it accounts for communication channels during training. ## VI Conclusion We proposed AirGNNs in order to improve architecture robustness to wireless channel impairments for decentralized implementation of GNNs. AirGNNs consist of multiple layers with each layer comprising graph filters over the air and a point-wise nonlinearity. They incorporate communication channels into graph signal processing and leverage noisy neighborhood information to extract features, which alleviate the performance degradation caused by channel fading and noise. We account for random channel states in the cost function and developed a SGD based method for training AirGNNs. We showed the proposed training procedure is equivalent to running SGD on an associated stochastic optimization problem and proved its convergence to a stationary solution. Numerical experiments are performed on decentralized tasks of source localization and multi-robot flocking, corroborating the effectiveness of AirGNNs to improve the performance over communication channels.
2303.05262
Fredholm integral equations for function approximation and the training of neural networks
We present a novel and mathematically transparent approach to function approximation and the training of large, high-dimensional neural networks, based on the approximate least-squares solution of associated Fredholm integral equations of the first kind by Ritz-Galerkin discretization, Tikhonov regularization and tensor-train methods. Practical application to supervised learning problems of regression and classification type confirm that the resulting algorithms are competitive with state-of-the-art neural network-based methods.
Patrick Gelß, Aizhan Issagali, Ralf Kornhuber
2023-03-09T13:56:04Z
http://arxiv.org/abs/2303.05262v3
# Fredholm integral equations for function approximation and the training of neural networks ###### Abstract. We present a novel and mathematically transparent approach to function approximation and the training of large, high-dimensional neural networks, based on the approximate least-squares solution of associated Fredholm integral equations of the first kind by Ritz-Galerkin discretization, Tikhonov regularization and tensor-train methods. Practical application to supervised learning problems of regression and classification type confirm that the resulting algorithms are competitive with state-of-the-art neural network-based methods. Key words and phrases:Function approximation, training of neural networks, Ritz-Galerkin methods, Fredholm integral equations of the first kind, Tikhonov regularization, tensor trains ## 1. Introduction Efficient and reliable methods for the training of neural networks are of fundamental importance for a multitude of applications and therefore a flourishing field of mathematical research. Stochastic gradient methods [1, 2] are known and further developed since the sixties. These methods mostly perform very well and therefore are often considered as methods of choice in the field. However, global convergence analysis is complicated and actual convergence might depend on proper parameter tuning [3]. Multilevel trust region methods [4, 5, 6] on the one hand aim at increasing efficiency by Newton-type linearization and on the other hand at increasing reliability by suitable step size control. Multilevel versions [7] are intended to additionally transfer the efficiency of multigrid methods for the minimization of energy functionals associated with elliptic partial differential equations to the minimization of loss functionals. This paper is devoted to a novel and mathematically transparent approach to function approximation and the training of large and high-dimensional shallow neural networks with usual kernel functions \(\psi\), training parameters \((\eta_{i},u_{i})_{i=1}^{N}\) with \(\eta_{i}\in Q\subset\mathbb{R}^{s}\), \(u_{i}\in\mathbb{R}\), \(I=1,\ldots,N\), and intentionally large \(s\) and \(N\). The starting point of our considerations is that such neural networks can be interpreted as Monte-Carlo approximations of integrals over \(Q\), once the parameters \(\eta_{i}\) are assumed to be equidistributed on \(Q\) (see also [8]). Resulting Fredholm integral operators, now acting on parameter functions rather than parameter vectors, give rise to so-called _Fredholm networks_ providing a novel approach to function approximation. Training of such Fredholm networks amounts to least-squares solution of linear Fredholm integral equations of the first kind for a parameter function \(u\colon Q\to\mathbb{R}\), the continuous counterpart of the discrete parameter vector \((u_{i})_{i=1}^{N}\). Fredholm-trained parameters \((\eta_{i},u(\eta_{i}))_{i=1}^{N}\) of the original discrete neural network are then obtained by suitable sampling of \(\eta_{i}\in Q\). A similar approach has been developed for kernel methods in supervised and semi-supervised learning [9, 10, 11] and applied to the covariance shift problem in transfer learning [12]. In general, the solution \(u\) of the continuous Fredholm training problem is not available. After Ritz-Galerkin discretization with suitable ansatz space and Tikhonov regularization [13], the resulting, intentionally large, linear systems are approximately solved by tensor-train methods, such as alternating linear schemes [14, 15]. Approximately Fredholm-trained parameters \((\tilde{\eta}_{i},\tilde{u}(\tilde{\eta}_{i}))_{i=1}^{N}\) of the original neural network are finally obtained from the resulting approximation \(\tilde{u}\) of \(u\) and suitable sampling of \(\tilde{\eta}_{i}\in Q\). While the numerical analysis of this approach is devoted to a forthcoming paper, the goal of this work is to confirm the practical potential of the Fredholm approach by numerical experiments and comparison with state-of-the-art neural network-based methods. The paper is organized as follows. After describing the architecture of the neural networks in question together with the resulting discrete training problem in the next Section 2, we introduce Fredholm networks and Fredholm training problems as their continuous counterparts and briefly discuss ill-posedness in Section 3. Ritz-Galerkin discretization and Tikhonov regularization are presented in Section 4. Utilizing suitable factorizations of the kernel functions \(\psi\) (as derived in the Appendix A), Section 5 is devoted to tensor-train methods for the iterative solution of the large linear systems associated with intentionally high-dimensional parameter domains \(Q\subset\mathbb{R}^{s}\). In Section 6, we harvest the results on the training of Fredholm networks, briefly discuss Monte-Carlo sampling, and introduce a novel inductive importance sampling strategy. In the final Section 7, we apply our methods to three well-established test problems of regression and classification type with different computational complexity. In particular, we consider the UCI banknote authentication data set from [16], concrete compressive strength prediction [17, 18, 19, 20], and the well-known MNIST data set [21]. For all these problems, Fredholm networks and Fredholm-trained neural networks turn out to be highly competitive with state-of-the-art approaches without any problem-specific features or tuning. The efficiency of Fredholm-trained neural networks however seems to rely on a careful choice of sampling strategy: While straightforward quasi-Monte-Carlo sampling appears to work perfectly well for simple problems, more advanced strategies, such as inductive importance sampling, seem to be required in more complicated cases. ## 2. Large single layer neural networks ### Architecture We consider a parametrized single layer neural network of the form \[X\ni x\mapsto F_{N}(x,\zeta)=\frac{1}{N}\sum_{i=1}^{N}\psi(x,\eta_{i})u_{i}\in \mathbb{R} \tag{1}\] defined on a compact hypercube \(X\subset\mathbb{R}^{d}\), for simplicity, with intentionally large number of neurons \(N\in\mathbb{N}\), a suitable kernel function \(\psi:X\times Q\to\mathbb{R}\), and associated parameter vector \[\zeta=(\zeta_{i})_{i=1}^{N},\quad\zeta_{i}=(\eta_{i},u_{i})\in Q\times\mathbb{R},\] where \(Q=Q_{1}\times\cdots\times Q_{s}\subset\mathbb{R}^{s}\). _Ridge kernel functions_ \[\psi(x,\eta)=\sigma(w\cdot x+b),\quad\eta=(w,b)\in Q\subset\mathbb{R}^{s},\;s= d+1, \tag{2}\] are characterized by suitable activation functions \(\sigma:\mathbb{R}\to\mathbb{R}\) and give rise to so-called single hidden layer perceptron models [22]. In the simplest case \(\sigma\equiv\mathrm{Id}\) and \(b=0\), this definition reduces to the Euclidean scalar product \(\psi(x,\eta)=x\cdot\eta\) with \(\eta=w\in\mathbb{R}^{s}\) and \(s=d\). More relevant choices for \(\sigma\) include the (discontinuous) _Heaviside function_ \[\sigma_{\infty}(z)=\left\{\begin{array}{cl}0&\mbox{if }z<0,\\ 1/2&\mbox{if }z=0,\\ 1&\mbox{if }z>0\end{array}\right. \tag{3}\] or suitable regularizations like the _logistic activation function_ \[\sigma_{\kappa}(z)=\frac{\exp(\kappa z)}{1+\exp(\kappa z)} \tag{4}\] with \(\kappa>0\). Note that \(\sigma_{\kappa}(z)\to\sigma_{\infty}(z)\) holds for \(\kappa\to\infty\) and all \(z\in\mathbb{R}\). _Radial kernel functions_[23] are given by \[\psi(x,\eta)=\sigma(\|x-w\|),\quad\eta=w\in Q\subset\mathbb{R}^{s},\;s=d, \tag{5}\] with some vector norm \(\|\cdot\|\) on \(\mathbb{R}^{d}\) and suitable activation functions \(\sigma\). In the case of Gaussian activation functions \[\sigma(z)=\exp\left(-\frac{z^{2}}{2\kappa^{2}}\right) \tag{6}\] and the Euclidean norm \(\|\cdot\|=\|\cdot\|_{2}\), we have \[\psi(x,\eta)=\exp\left(-\frac{\|x-\eta\|_{2}^{2}}{2\kappa^{2}}\right)=\prod_{ k=1}^{d}\exp\left(-\frac{(x_{k}-\eta_{k})^{2}}{2\kappa^{2}}\right). \tag{7}\] ### Function data, loss functional, and training Throughout the following \(L^{2}(X,\pi)\) stands for the Hilbert space of \(\pi\) measurable, quadratically integrable functions on \(X\) with canonical scalar product \((\cdot,\cdot)_{\pi}\) and induced norm \(\|\cdot\|_{\pi}\). We write \(L^{2}(X)=L^{2}(X,\pi)\) and \((\cdot,\cdot)_{X}=(\cdot,\cdot)_{\pi}\), \(\|\cdot\|_{X}=\|\cdot\|_{\pi}\), if \(d\pi(x)=dx\) is the Lebesgue measure. Furthermore, \(L^{2}(Q)\) stands for the Hilbert space of Lebesgue measurable, quadratically integrable functions on \(Q\) with canonical scalar product \((\cdot,\cdot)\) and induced norm \(\|\cdot\|\). We aim at the approximation of a function \(F:X\mapsto\mathbb{R}\) by parametrized ansatz functions \(F_{N}(\cdot,\zeta)\) of the form (1). The parameters \(\zeta\) are determined by minimizing the loss functional \[\mathcal{J}_{N}(\zeta)=\|F-F_{N}(\cdot,\zeta)\|_{\pi}^{2}=\int_{X}(F(x)-F_{N}( x,\zeta))^{2}\;d\pi(x) \tag{8}\] where the measure \(\pi\) is associated with the training data available. We will consider the following two cases of given (9) a) function data \(\;F\in L^{2}(X)\) b) point data \(\;((x_{j},F(x_{j})))_{j=1}^{M}\in(X\times\mathbb{R})^{M}\subset\mathbb{R}^{M (d+1)}\). The case a) of a given function \(F\) is associated with the Lebesgue measure \(d\pi(x)=dx\) while case b) of given point data corresponds to the point measure \(d\pi(x)=d\mu(x)\), \[\mu=\frac{1}{M}\sum_{j=1}^{M}\delta_{x_{j}},\quad x_{1},\ldots,x_{M}\in X. \tag{10}\] Training of the neural network \(F_{N}(\cdot,\zeta)\) amounts to the (approximate) solution of the following discrete, non-convex, large-scale minimization problem. **Problem 2.1**.: _Find \(\zeta^{*}=(\zeta^{*}_{i})_{i=1}^{N},\;\zeta^{*}_{i}=(\eta^{*}_{i},u^{*}_{i}) \in Q\times\mathbb{R}\), such that_ \[\mathcal{J}_{N}(\zeta^{*})\leq\mathcal{J}_{N}(\zeta)\qquad\forall\zeta=(\zeta _{i})_{i=1}^{N},\;\zeta_{i}=(\eta_{i},u_{i})\in Q\times\mathbb{R}. \tag{11}\] Approximation properties of neural networks of the form (1) have quite a history (see, e.g., [24] or the overview of Pinkus [22]). In particular, ridge kernels with any non-polynomial activation function \(\sigma\) and unconstrained parameters \(\zeta\in\mathbb{R}^{N(d+2)}\) provide uniform approximation of continuous functions \(F\) on compact sets \(X\subset\mathbb{R}^{d}\)[22, Theorem 3.1]. While similar results for constrained parameters \(\zeta\in Q\times\mathbb{R}\) seem to be rare, the following proposition is a consequence of [25, Theorem 2.6]. **Proposition 2.2**.: _For the ridge kernel (2) with logistic activation function (4), \(Q\) containing the unit ball in \(\mathbb{R}^{d+1}\), and any function \(F\in C(X)\), we have_ \[\inf_{\zeta\in(Q\times\mathbb{R})^{N}}\,\max_{x\in X}\,|F(x)-F_{N}(x,\zeta)| \to 0\quad\text{for}\quad N\to\infty. \tag{12}\] Hence, assuming existence of a solution \(\zeta^{*}\) for all \(N\in\mathbb{N}\), we have \(\mathcal{J}_{N}(\zeta^{*})\to 0\) as \(N\to\infty\) for \(F\in L^{2}(X)\) in the case (9a) and \(F\in C(X)\) in the case (9b), respectively. ## 3. Continuous approximations of discrete training problems Following the ideas from [8, Section 1.2], we now introduce and investigate the asymptotic limit of \(F_{N}(\cdot,\zeta)\) and of the corresponding Training Problem 2.1 for \(N\to\infty\). ### Asymptotic integral operators Assume that \(\psi(x,\cdot)\in L^{2}(Q)\) for each fixed \(x\in X\). Let \(\eta_{i}\), \(i=1,...,N\), be independent, identically equidistributed random variables. Then, denoting \(|Q|=\int_{Q}1\;dx\), \[\frac{1}{N}\sum_{i=1}^{N}\psi(x,\eta_{i})v(\eta_{i})\;\to\;\frac{1}{|Q|}\int_{ Q}\psi(x,\eta)v(\eta)\;d\eta\quad\text{for}\quad N\to\infty \tag{13}\] holds for all \(v\in L^{2}(Q)\) and each fixed \(x\in X\) by the strong law of large numbers. This observation suggests to consider the Fredholm integral operator \[\mathcal{G}v=\frac{1}{|Q|}\int_{Q}\psi(\cdot,\eta)v(\eta)\;d\eta,\quad v\in L^ {2}(Q), \tag{14}\] Let us recall some well-known properties of \(\mathcal{G}\), cf. [13, 26, 27]. **Proposition 3.1**.: _Assume that_ \[\int_{X}\int_{Q}\psi(x,\eta)^{2}\;d\eta\;dx<\infty. \tag{15}\] _Then the integral operator_ \[\mathcal{G}:L^{2}(Q)\to L^{2}(X)\] _is a compact, linear mapping._ Note that Proposition 3.1 provides compactness of \(\mathcal{G}\), e.g., for the radial and ridge kernel functions mentioned in Section 2.1. ### Fredholm integral equations #### 3.2.1. Function data Let us first consider the case (9a) of a given function \(F\in L^{2}(X)\). In the light of (13), we impose the additional constraints on the unknowns \(\zeta_{i}=(\eta_{i},u_{i})\), \(i=1,\ldots,N\), of the Training Problem 2.1 that \[\eta_{i} \tag{16}\] are samples of i.i. equidistributed random variables and \[u_{i}=u(\eta_{i}),\quad i=1,\ldots,N,\] with some function \(u\in L^{2}(Q)\). Then, for given function \(F\), the asymptotic coincidence (13) of the discrete neural network \(F_{N}(\cdot,((\eta_{i},u_{i})_{i=1}^{N})\) and the integral operator \(\mathcal{G}u\) suggests to consider the loss functional \[\mathcal{J}(v)=\int_{X}(F(x)-\mathcal{G}v(x))^{2}\;dx. \tag{17}\] and the following continuous quadratic approximation of the discrete non-convex Training Problem 2.1. **Problem 3.2**.: _Find \(u\in L^{2}(Q)\) such that_ \[\mathcal{J}(u)\leq\mathcal{J}(v)\quad\forall v\in L^{2}(Q). \tag{18}\] Observe that Problem 3.2 is just the least-squares formulation of the Fredholm integral equation of the first kind \[\mathcal{G}u=\frac{1}{|Q|}\int_{Q}\psi(\cdot,\eta)u(\eta)\;d\eta=F. \tag{19}\] In particular, (18) can be equivalently rewritten as the normal equation \[\mathcal{G}^{*}\mathcal{G}u=\mathcal{G}^{*}F\quad\text{in}\quad L^{2}(Q) \tag{20}\] utilizing the variational formulation of (18), \[(\mathcal{G}u,\mathcal{G}v)_{X}=(F,\mathcal{G}v)_{X}\qquad\forall v\in L^{2}( Q), \tag{21}\] and the adjoint operator of \(\mathcal{G}\), \[L^{2}(X)\ni v\mapsto\mathcal{G}^{*}v=\frac{1}{|Q|}\int_{X}\psi(x,\cdot)v(x)\; dx\in L^{2}(Q).\] This leads to the following well-known existence result (see, e.g., [13, Theorem 2.5]), where \(R(\mathcal{G})\) and \(N(\mathcal{G})\) stand for the range and null space of \(\mathcal{G}\), respectively, \(\oplus\) denotes the direct sum, and the superscript \(\perp\) indicates the orthogonal complement in \(L^{2}(X)\). **Proposition 3.3**.: _Assume that \(F\in R(\mathcal{G})+R(\mathcal{G})^{\perp}\subset L^{2}(X)\). Then (19) has least-squares solutions \(u^{\dagger}\oplus N(\mathcal{G})\), with \(u^{\dagger}=\mathcal{G}^{\dagger}F\) being the unique minimal-norm least squares solution (best-approximate solution), and \(\mathcal{G}^{\dagger}\colon R(\mathcal{G})\oplus R(\mathcal{G})^{\perp} \to N(\mathcal{G})^{\perp}\subset L^{2}(Q)\) denoting the generalised Moore-Penrose inverse of \(\mathcal{G}\)._ If \(\mathcal{G}\) is compact, then \(R(\mathcal{G})\) is closed or, equivalently, \(\mathcal{G}^{\dagger}\) is bounded, if and only if \(R(\mathcal{G})\) has finite dimension (see, e.g., [13, Proposition 2.7]). As a consequence, the integral equation (19) is ill-posed, even in the least-squares sense (18) for usual kernel functions such as the radial and ridge kernels presented in Section 2.1. **Proposition 3.4**.: _Assume that the kernel function \(\psi\) is discriminatory in the sense that_ \[N(\mathcal{G}^{*})=\{0\}. \tag{22}\] _Then \(R(\mathcal{G})\) is dense in \(L^{2}(X)\) and therefore \(\inf_{u\in L^{2}(Q)}\mathcal{J}(u)=0\) holds for all \(F\in L^{2}(X)\)._ For ridge kernels with Heaviside or logistic activation function, we obtain \(v=0\), if \(\mathcal{G}^{*}v(\eta)=0\) holds for all \(\eta\in\mathbb{R}^{s}\) (and not only for all \(\eta\in Q\)) by [28, Lemma 1]. However, similar results for the present case of bounded parameters \(\eta\in Q\) seem to be unknown. **Remark 3.5**.: _In order to relax the constraints (16) on the parameters \(\zeta\) that provide an asymptotic limit of \(F_{N}(\cdot,\zeta)\) of the form (13), one might assume that the parameters \(\zeta_{i}=(\eta_{i},u_{i})\) are independent random variables that are identically distributed with respect to some unknown probability measure \(\nu\in\mathbb{P}(Q\times\mathbb{R})\). Then, the law of large numbers implies_ \[\frac{1}{N}\sum_{i=1}^{N}\psi(x,\eta_{i})u_{i}\longrightarrow\int_{Q\times \mathbb{R}}\psi(x,\eta)u\;d\nu(\eta,u)\quad\text{for }N\longrightarrow\infty\] _in analogy to (13). Replacing \(F_{N}(x,\zeta)\) in the loss functional \(\mathcal{J}_{N}\) by the integral operator_ \[\mathbb{P}(Q\times\mathbb{R})\ni\nu\mapsto\int_{Q\times\mathbb{R}}\psi(\cdot, \eta)u\;d\nu(\eta,u)\in\mathbb{R}\] _the resulting training problem for the parameter measure \(\nu\) amounts to the least squares formulation of the problem to find \(\nu\in\mathbb{P}(Q\times\mathbb{R})\) such that_ \[\int_{Q\times\mathbb{R}}\psi(\cdot,\eta)u\;d\nu(\eta,u)=F. \tag{23}\] _The analysis and numerical analysis of such Fredholm integral equations on measures is the subject of ongoing research._ #### 3.2.2. Point data In the case (9b) of given point values of \(F\), we replace the corresponding point values of \(F_{N}\) in (8) by the point values of the limiting integral operator \(\mathcal{G}\) to obtain the approximation \(J\), \[J(v)=\frac{1}{M}\sum_{j=1}^{M}(F(x_{j})-\mathcal{G}v(x_{j}))^{2},\] of the discrete loss functional \(\mathcal{J}_{N}\) and the following quadratic approximation of the Training Problem 2.1. **Problem 3.6**.: _Find \(u\in L^{2}(Q)\) such that_ \[J(u)\leq J(v)\quad\forall v\in L^{2}(Q). \tag{24}\] Problem 3.6 is the least-squares formulation of the interpolation problem to find \(u\in L^{2}(Q)\) such that \[\mathcal{G}_{M}u=F_{M}\] with \(F_{M}=(F(x_{j}))_{j=1}^{M}\in\mathbb{R}^{M}\) and \(\mathcal{G}_{M}\colon L^{2}(Q)\to\mathbb{R}^{M}\) defined by \(\mathcal{G}_{M}v=(\mathcal{G}v(x_{i}))_{i=1}^{M}\in\mathbb{R}^{M}\). In analogy to (20), Problem 3.6 can be equivalently reformulated as a linear normal equation \(\mathcal{G}_{M}^{*}\mathcal{G}_{M}u=\mathcal{G}_{M}^{*}F_{M}\) in \(L^{2}(Q)\) utilizing the variational formulation \[\sum_{j=1}^{M}(\mathcal{G}u)(x_{j})(\mathcal{G}v)(x_{j})=\sum_{j=1}^{M}F(x_{j })(\mathcal{G}v)(x_{j})\qquad\forall v\in L^{2}(Q), \tag{25}\] of Problem 3.6 with the adjoint operator \(\mathcal{G}_{M}^{*}\) of \(\mathcal{G}_{M}\) given by \[\mathbb{R}^{M}\ni v=(v_{j})_{j=1}^{M}\mapsto\mathcal{G}_{M}^{*}v=\frac{1}{|Q| }\sum_{j=1}^{M}\psi(x_{j},\cdot)v_{j}\in L^{2}(Q).\] Observe that \(R(\mathcal{G}_{M})\) is now finite-dimensional and thus closed. Hence, existence of a best-approximate solution \(u=\mathcal{G}_{M}^{\dagger}\) of Problem 3.6 for any point data \((x_{i},F(x_{i}))\), \(i=1,\ldots,M\), follows from \(R(\mathcal{G}_{M})\oplus R(\mathcal{G}_{M})^{\perp}=\mathbb{R}^{M}\) and the general Theorem 2.5 in [13]. As a consequence, the Moore-Penrose inverse \(\mathcal{G}_{M}^{\dagger}\) is now bounded. However, its norm is expected to increase with increasing \(M\). **Remark 3.7**.: _Assuming \(N(\mathcal{G}_{N}^{*})=\{0\}\), we obtain \(J(u)=0\) in analogy to Proposition 3.4._ ### Fredholm networks The asymptotic coincidence with discrete neural networks \(F_{N}(\cdot,\eta)\) suggests to consider their continuous counterpart \[\mathcal{G}v=\frac{1}{|Q|}\int_{Q}\psi(\cdot,\eta)v(\eta)\;d\eta \tag{26}\] with parameter function \(v\in L^{2}(Q)\) directly for approximation. Observe that the continuous Training Problems 3.2 (function data) or 3.6 (point data) associated with such _Fredholm networks_ are linear, in contrast to the original discrete Problem 2.1. However, linearity comes with the price of infinitely many unknown parameter function values. This suggests suitable discretizations of the continuous Training Problem 3.2 or 3.6 providing computable approximations of the corresponding Fredholm networks. For example, the integral operator \(\mathcal{G}\) has been replaced by a suitable Riemann sum in [9, 10, 11]. ## 4. Ritz-Galerkin discretization and regularization ### Variational formulation Let \(L\subset L^{2}(Q)\) denote a closed subspace. Then the corresponding Ritz-Galerkin discretization of the Fredholm Training Problems 3.2 and 3.6 reads as follows. **Problem 4.1**.: _Find \(u_{L}\in L\) such that_ \[(\mathcal{G}u_{L},\mathcal{G}v)_{\pi}=(F,\mathcal{G}v)_{\pi}\qquad\forall v\in L, \tag{27}\] _with \(\pi\) still denoting the Lebesgue or point measure._ Again, existence of a best-approximate solution \(u_{L}\) follows from Theorem 2.5 in [13], and asymptotic ill-conditioning is expected to be inherited from the continuous case. ### Algebraic formulation Let the ansatz space \(L=L_{n}\) have finite dimension \(n\) and let \(\varphi_{1},\ldots,\varphi_{n}\) be a basis of \(L_{n}\). Then any \(v\in L_{n}\) can be identified with the coefficient vector \(V=(V_{i})_{i=1}^{n}\in\mathbb{R}^{n}\) of its unique basis representation \[v=\sum_{i=1}^{n}V_{i}\varphi_{i}\in L_{n}. \tag{28}\] **Example 4.2**.: _Let \(Q=\bigcup_{i=1}^{n}q_{i}\) be a decomposition of \(Q\) into disjoint rectangles \(q_{i}\) with maximal edge length \(h\). Then_ \[\varphi_{i}(\eta)=\left\{\begin{array}{cl}|q_{i}|^{-1/2}&\mbox{ if }\eta\in q_{i}\\ 0&\mbox{ otherwise}\end{array}\right.\] _is an orthonormal basis of the subspace \(L_{n}\subset L^{2}(Q)\) of piecewise constant functions on \(q_{i}\), and the coefficients \(V_{i}\) of \(v\in L_{n}\) agree with its scaled values on \(q_{i}\), \(i=1,\ldots,n\)._ Introducing the semi-discrete, linear operators \[\begin{array}{rcl}G&=&(\mathcal{G}\varphi_{1},\ldots,\mathcal{G}\varphi_{n})& \in L^{2}(X,\pi)\times\mathbb{R}^{n}\colon&\mathbb{R}^{n}\to L^{2}(X,\pi),\\ G^{*}&=&((\mathcal{G}\varphi_{i},\cdot)_{\pi})_{i=1}^{n}&\in\mathbb{R}^{n} \times L^{2}(X,\pi)\colon&L^{2}(X,\pi)\to\mathbb{R}^{n}\end{array} \tag{29}\] we have \(\mathcal{G}u_{L}=GU\) with \(u_{L}=\sum_{i=1}^{n}U_{i}\varphi_{i}\) and \(U=(U_{i})_{i=1}^{n}\in\mathbb{R}^{n}\). Utilizing \[G^{*}G=((\mathcal{G}\varphi_{i},\mathcal{G}\varphi_{j})_{\pi})_{i,j=1}^{n}\in \mathbb{R}^{n,n} \tag{30}\] the variational equality 27 can be equivalently rewritten as the linear system \[G^{*}GU=G^{*}F \tag{31}\] for the unknown coefficient vector \(U\) of \(u_{L}\). Observe that \(G^{*}G=A^{\top}A\) holds with \[A=(a_{ij})\in\mathbb{R}^{M\times n},\ \ a_{ij}=(\mathcal{G}\varphi_{j})(x_{i }),\ \ i=1,\ldots M,\;j=1,\ldots n, \tag{32}\] in the case (9b) of given point data. ### Tikhonov regularization We only consider the case (9b) of given point data. In order to ensure uniqueness of approximate solutions, we select some \(\varepsilon>0\) and introduce the following Tikhonov regularization of the discretized Problem 4.1. **Problem 4.3**.: _Find a solution \(U_{\varepsilon}\in\mathbb{R}^{n}\) of the regularized linear system_ \[(\varepsilon I+A^{\top}A)U_{\varepsilon}=A^{\top}b \tag{33}\] _with identity matrix \(I\in\mathbb{R}^{n\times n}\), \(b=(F(x_{i}))_{i=1}^{M}\in\mathbb{R}^{M}\), and \(\varepsilon>0\)._ Problem 4.3 is equivalent to minimizing the regularized discrete loss functional \[\mathbb{J}_{\varepsilon}(V)=\|AV-b\|_{2,\mathbb{R}^{M}}^{2}+\varepsilon\|V\|_ {2,\mathbb{R}^{n}}^{2},\quad V\in\mathbb{R}^{n}. \tag{34}\] with \(\|\cdot\|_{2,\mathbb{R}^{M}}\) and \(\|\cdot\|_{2,\mathbb{R}^{n}}\) denoting the Euclidean norm in \(\mathbb{R}^{M}\) and \(\mathbb{R}^{n}\), respectively. Existence and uniqueness of a solution is an immediate consequence of the Lax-Milgram lemma. Moreover, Problem 4.3 is also equivalent with the algebraic formulation of the Ritz-Galerkin discretization of the regularized continuous problem to find \(u_{\varepsilon}\in L^{2}(Q)\) such that \[J_{\varepsilon}(u_{\varepsilon})\leq J_{\varepsilon}(v)\qquad\forall v\in L^ {2}(Q)\] with regularized loss functional \[J_{\varepsilon}(v)=\varepsilon(v,v)+J(v)=\varepsilon(v,v)+\sum_{j=1}^{M}(F(x_ {j})-\mathcal{G}v(x_{j}))^{2}\] provided that \(\varphi_{1},\ldots,\varphi_{n}\) is an orthonormal basis of \(L_{n}\) (see, e.g., Example 4.2). Indeed, we have \(\mathbb{J}_{\varepsilon}(V)=J_{\varepsilon}(v)\) for \(v=\sum_{i=1}^{n}V_{i}\varphi_{i}\) in this case. Utilizing Cea's lemma and the classical theory of Tikhonov regularization, cf., e.g., [13, Section 5.1], the resulting approximation \(u_{\varepsilon,L}\in L_{n}\) is then expected to satisfy an a priori error estimate for the original loss functional of the form \(J(u_{\varepsilon,L})=\mathcal{O}(\varepsilon^{2}+\varepsilon^{-2}h^{2})\) under suitable regularity conditions. ## 5. Algebraic solution by tensor trains In this section we consider the algebraic solution of the regularized linear system (33) in Problem 4.3 for high dimension \(d\) and resulting large number of unknowns \(n\) by tensor train methods. ### Tensor formats Tensors are multilinear mappings that can be represented as functions \(T\colon\{1,\ldots,D_{1}\}\times\cdots\times\{1,\ldots,D_{p}\}\to\mathbb{C}\) or, equivalently, as multidimensional arrays \(\mathbf{T}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}}\) with dimensions or modes \(D_{k}\in\mathbb{N}\), \(k=1,\ldots,p\), and order \(p\) of \(\mathbf{T}\). We will write \(\mathbf{T}\in\mathbb{R}^{D_{1}\times\cdots\times D_{p}}\), if all components \(\mathbf{T}_{i_{1},\ldots,i_{p}}\), \(i_{k}=1,\ldots,D_{k}\), \(k=1,\ldots,p\), are real numbers. Throughout the following, tensors are denoted by bold letters. When certain indices of a tensor are fixed, we use colon notation (cf. Python or Matlab) to indicate the remaining modes, e.g., \(\mathbf{T}_{:,i_{2},\ldots,i_{p-1},:}\in\mathbb{C}^{D_{1}\times D_{p}}\). The sum of tensors and the product with scalars is defined componentwise. Extending usual matrix multiplication, the product or index contraction \(\mathbf{T}\cdot\mathbf{U}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}\times D _{1}^{\prime\prime}\times\cdots\times D_{p^{\prime\prime}}^{\prime\prime}}\) of two tensors \(\mathbf{T}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}\times D_{1}^{\prime} \times\cdots\times D_{p^{\prime}}^{\prime}}\) and \(\mathbf{U}\in\mathbb{C}^{D_{1}^{\prime}\times\cdots\times D_{p^{\prime}}^{ \prime}\times D_{1}^{\prime\prime}\times\cdots\times D_{p^{\prime\prime}}^{ \prime\prime}}\) is defined by \[(\mathbf{T}\cdot\mathbf{U})_{i_{1},\ldots,i_{p},j_{1},\ldots,j_{p^{\prime \prime}}}=\sum_{k_{1}=1}^{D_{1}^{\prime}}\cdots\sum_{k_{p^{\prime}}=1}^{D_{p^ {\prime}}^{\prime}}\mathbf{T}_{i_{1},\ldots,i_{p},k_{1},\ldots,k_{p^{\prime}} }\mathbf{U}_{k_{1},\ldots,k_{p^{\prime}},j_{1},\ldots,j_{p^{\prime\prime}}}.\] Note that the sum of the tensors \(\mathbf{T}_{\ell}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}}\), \(\ell=1,\ldots,r\), can be regarded as an index contraction of \(\mathbf{T}\in\mathbb{C}^{r\times D_{1}\times\cdots\times D_{p}}\) with \(\mathbf{T}_{\ell,i_{1},\ldots,i_{p}}=(\mathbf{T}_{\ell})_{i_{1},\ldots,i_{p}}\) and \(\mathbf{1}\in\mathbb{R}^{r}\) with \(\mathbf{1}_{\ell}=1\), \(\ell=1,\ldots,r\). We will also make use of the tensor product \(\mathbf{T}\otimes\mathbf{U}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}\times D _{1}^{\prime}\times\cdots\times D_{p^{\prime}}^{\prime}}\) of \(\mathbf{T}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}}\) and \(\mathbf{U}\in\mathbb{C}^{D_{1}^{\prime}\times\cdots\times D_{p^{\prime}}^{ \prime}}\) which is defined by \[(\mathbf{T}\otimes\mathbf{U})_{i_{1},\ldots,i_{p},j_{1},\ldots,j_{p^{\prime}} }=\mathbf{T}_{i_{1},\ldots,i_{p}}\mathbf{U}_{j_{1},\ldots,j_{p^{\prime}}}\] and coincides with the dyadic product \(\mathbf{T}\mathbf{U}^{\top}\in\mathbb{C}^{D_{1}\times D_{1}^{\prime}}\) of two vectors \(\mathbf{T}\in\mathbb{C}^{D_{1}}\) and \(\mathbf{U}\in\mathbb{C}^{D_{1}^{\prime}}\) for \(p=p^{\prime}=1\). As the number of elements of a tensor grows exponentially with order \(p\), the storage of high-dimensional tensors may become infeasible, if \(p\) becomes large. This motivates suitable formats for tensor representation and approximation. Obviously, the storage of a _rank-one tensor_\(\mathbf{T}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}}\) that can be written as the tensor product \[\mathbf{T}=\mathbf{T}^{(1)}\otimes\cdots\otimes\mathbf{T}^{(p)} \tag{35}\] of \(p\) vectors \(\mathbf{T}^{(k)}\in\mathbb{C}^{D_{k}}\), \(k=1,\ldots,p\), only grows linearly with \(pD_{\max}\) and \(D_{\max}=\max\{D_{1},\)\(\ldots,D_{p}\}\). As a generalization of (35), a tensor \(\mathbf{T}\in\mathbb{C}^{D_{1}\times\cdots\times D_{p}}\) is said to be in the _canonical format_[29], if it can be expressed as a finite sum of rank-one tensors according to \[\mathbf{T}=\sum_{\ell=1}^{r}\mathbf{T}_{\ell,:}^{(1)}\otimes\cdots\otimes \mathbf{T}_{\ell,:}^{(p)}. \tag{36}\] Here, the tensors \(\mathbf{T}^{(k)}\in\mathbb{C}^{r\times D_{k}}\), \(k=1,\ldots,p\), are called cores and the number \(r\) is called the canonical rank of \(\mathbf{T}\). Note that the required storage grows with order \(\mathcal{O}(rpD_{\max})\). The _tensor train_ (TT) format [30, 31] is a further generalization of (36). Here, the basic idea is to decompose a tensor into a chain-like network of low-dimensional tensors coupled by so-called TT ranks \(r_{0},\ldots r_{p}\) according to \[\mathbf{T}=\sum_{\ell_{0}=1}^{r_{0}}\cdots\sum_{\ell_{p}=1}^{r_{p}}\mathbf{T}_ {\ell_{0},:,\ell_{1}}^{(1)}\otimes\cdots\otimes\mathbf{T}_{\ell_{p-1},:,\ell_{ p}}^{(p)}, \tag{37}\] with TT cores \(\mathbf{T}^{(k)}\in\mathbb{C}^{r_{k-1}\times D_{k}\times r_{k}}\), \(k=1,\ldots,p\), and \(r_{0}=r_{p}=1\). With maximal TT rank \(r_{\max}=\max\{r_{0},\ldots,r_{p}\}\), the storage consumption for tensors in the TT format grows like \(\mathcal{O}(r_{\max}^{2}pD_{\max})\) and thus is still linearly bounded in terms of the maximal dimension and the order \(p\) of \(\mathbf{T}\). The ranks \(r_{0},\ldots,r_{p}\) not only determine the required storage, but also have a strong influence on the quality of best approximation of a given tensor in full format by a tensor train. Note that such a best approximation in TT format with bounded ranks always exists [32] and is even exact for suitably chosen ranks [33, Theorem 1]. For further information about tensor formats, we refer, e.g., to [34, 35]. In order to provide a factorization of the integral operator \(\mathcal{G}\) by factorization of the kernel \(\psi\), we will make use of functional tensor networks with discrete as well as continuous modes. More precisely, a functional tensor with one discrete and one continuous mode is a function \(T\colon\{1,\ldots,D\}\times Q\to\mathbb{C}\), where \(Q\subseteq\mathbb{R}\) denotes the domain of the continuous mode. We write \(\mathbf{T}_{i,\eta}=T(i,\eta)\), \(i=1,\ldots,D\), \(\eta\in Q\), for the components of the corresponding generalized array \(\mathbf{T}\in\mathbb{C}^{D\times Q}\). Replacing summation by integration, index contraction \(\mathbf{T}\cdot\mathbf{U}\in\mathbb{C}^{D\times D^{\prime}}\) of \(\mathbf{T}\) with the functional tensor \(\mathbf{U}\in\mathbb{C}^{Q\times D^{\prime}}\) is defined by \[(\mathbf{T}\cdot\mathbf{U})_{i,j}=\int_{Q}\mathbf{T}_{i,\eta}\mathbf{U}_{\eta,j}\ d\eta.\] Functional tensor trains (FTTs) [36] provide a decomposition of \(\mathbf{T}\in\mathbb{C}^{Q_{1}\times\cdots\times Q_{p}}\) into cores \(\mathbf{T}^{(k)}\in\mathbb{C}^{r_{k-1}\times Q_{k}\times r_{k}}\) in analogy to (37). Figure 1 shows the diagrammatic notation of tensors in rank-one, canonical, TT, and FTT format. We depict vectors, matrices, and tensors as circles with different arms indicating the set of modes. Index contraction of two or more tensors is represented by connecting corresponding arms. ### Tensor decomposition of basis and stiffness matrix As a first step towards a tensor train formulation of the regularized linear system (33), we assume that the basis functions \(\varphi_{1},\ldots,\varphi_{n}\) of the ansatz space \(L_{n}\) utilized in (28) are separable in the sense that \[\varphi_{j}(\eta)=\varphi_{j_{1}}^{(1)}(\eta_{1})\cdot\ldots\cdot\varphi_{j_{ s}}^{(s)}(\eta_{s}),\quad\eta=(\eta_{1},\ldots,\eta_{s})\in Q=Q_{1}\times \cdots\times Q_{s}, \tag{38}\] Figure 1. Graphical notation of tensor formats: (a) A tensor in rank-one format, given by the tensor product of \(p\) vectors. (b) A tensor in the canonical format, given by the contraction of \(p\) matrices on the common rank index. (c) A tensor in TT format, given by a network of pairwise coupled tensors. Here, the first and the last TT core are regarded as matrices, because \(r_{0}=r_{p}=1\). (d) A tensor in FTT format, given by a TT-like network of tensors with one continuous mode. Discrete modes are represented by straight lines and continuous modes by zigzag lines. holds with \(1\leq j_{k}\leq n_{k}\) and some enumeration \[j=j(j_{1},\ldots,j_{s})=1,\ldots,n=n_{1}\cdot\ldots\cdot n_{s},\qquad j_{k}=1, \ldots,n_{k},\quad k=1,\ldots,s. \tag{39}\] **Example 5.1**.: _Let \(Q_{k}=\bigcup_{j=1}^{n_{k}}q_{j}^{(k)}\) be a decomposition of \(Q_{k}\subset\mathbb{R}^{n_{k}}\) into disjoint intervals \(q_{j}^{(k)}\subset\mathbb{R}\), \(j=1,\ldots,n_{k}\). Then the piecewise constant basis functions \(\varphi_{1},\ldots,\varphi_{n}\) introduced in Example 4.2 can be written as a product of the form (38) with_ \[\varphi_{j}^{(k)}(\eta_{k})=\left\{\begin{array}{cl}|q_{j}^{(k)}|^{-1/2}& \mbox{if }\eta_{k}\in q_{j}^{(k)}\\ 0&\mbox{otherwise}\end{array}\right..\] By definition of the tensor product, we have the following proposition. **Proposition 5.2**.: _Assume that the basis functions \(\varphi_{1},\ldots,\varphi_{n}\) of the ansatz space \(L_{n}\) are separable in the sense of (38). Then the functional tensor_ \[\mathbf{\Phi}\in\mathbb{R}^{n_{1}\times\cdots\times n_{s}\times Q_{1}\times \cdots\times Q_{s}},\qquad\mathbf{\Phi}_{j_{1},\ldots,j_{s},\eta_{1},\ldots, \eta_{s}}=\varphi_{j_{1}}^{(1)}(\eta_{1})\cdot\ldots\cdot\varphi_{j_{s}}^{(s) }(\eta_{s}),\] _is a rank-one tensor with the decomposition_ \[\mathbf{\Phi}=\mathbf{\Phi}^{(1)}\otimes\cdots\otimes\mathbf{\Phi}^{(s)} \tag{40}\] _into \(\mathbf{\Phi}^{(k)}\in\mathbb{R}^{n_{k}\times Q_{k}}\) defined by \(\mathbf{\Phi}_{j_{k},\eta_{k}}^{(k)}=\varphi_{j_{k}}^{(k)}(\eta_{k})\), \(j_{k}=1,\ldots,n_{k}\), for \(k=1,\ldots,s\)._ In the next step, we derive a decomposition of the functional tensor \(\mathbf{\Psi}\in\mathbb{R}^{M\times Q_{1}\times\cdots\times Q_{s}}\) with components \[\mathbf{\Psi}_{i,\eta_{1},\ldots,\eta_{s}}=\psi(x_{i},\eta),\qquad i=1,\ldots,M,\quad\eta=(\eta_{1},\ldots,\eta_{s})^{\top}\in Q=Q_{1}\times\cdots\times Q _{s}, \tag{41}\] associated with the actual kernel function \(\psi\) and the given data points \(x_{i}\in X\), \(i=1,\ldots,M\). For ease of presentation, we focus on kernels \(\psi\colon X\times Q\to\mathbb{R}\) with \(X,\;Q\subset\mathbb{R}^{s}\). Obviously, radial kernel functions (5) have this property with \(s=d\), and in the case of ridge kernel functions (2) we can identify \(X\) with its embedding \(\{(x,1)^{\top}\mid x\in X\}\subset\mathbb{R}^{s}\), \(s=d+1\). We further assume that the actual kernel function \(\psi\) can be expressed (or approximated) as a sum of products of univariate functions according to \[\psi(x,\eta)=\sum_{\ell=1}^{r}\psi_{\ell}^{(1)}(x_{1},\eta_{1})\cdot\ldots \cdot\psi_{\ell}^{(s)}(x_{s},\eta_{s}). \tag{42}\] **Example 5.3**.: _The ridge kernel function \(\psi(x,\eta)=\sigma(x\cdot\eta)\) with trivial activation function \(\sigma=\mbox{Id}\) can be written in the form (42) with \(r=s\) and \(\psi_{\ell}^{(k)}(x_{k},\eta_{k})=x_{k}\eta_{k}\) for \(k=\ell\) and \(\psi_{\ell}^{(k)}(x_{k},\eta_{k})=1\) otherwise._ Explicit constructions of approximate factorizations of ridge kernels with more relevant activation functions can be found in Appendix A. Note that even in the case of real-valued kernel functions \(\psi\), the factors \(\psi_{\ell}^{(k)}\) might have complex values (see, e.g. A.3). **Example 5.4**.: _The radial kernel function with Gaussian activation function given in (7) takes the form (42) with \(r=1\) and_ \[\psi_{1}^{(k)}(x_{k},\eta_{k})=\exp\left(-\frac{(x_{k}-\eta_{k})^{2}}{2\kappa^ {2}}\right),\quad k=1,\ldots,d.\] Utilizing the given data points \(x_{i}=(x_{i,k})_{k=1}^{s}\in X\), \(i=1,\ldots,M\), we now introduce the auxiliary functional tensor \(\hat{\boldsymbol{\Psi}}\in\mathbb{C}^{M^{s}\times Q_{1}\times\cdots\times Q_{s}}\) with canonical decomposition \[\hat{\boldsymbol{\Psi}}=\sum_{\ell=1}^{r}\hat{\boldsymbol{\Psi}}_{\ell,:,:}^{(1 )}\otimes\cdots\otimes\hat{\boldsymbol{\Psi}}_{\ell,:,:}^{(s)} \tag{43}\] into cores \(\hat{\boldsymbol{\Psi}}^{(k)}\in\mathbb{C}^{r\times M\times Q_{k}}\) with components \(\hat{\boldsymbol{\Psi}}_{\ell,i,\eta_{k}}^{(k)}=\psi_{\ell}^{(k)}(x_{i,k},\eta_ {k})\). **Proposition 5.5**.: _Assume that the kernel function \(\psi\) allows for the representation (42). Then the functional tensor \(\boldsymbol{\Psi}\in\mathbb{C}^{M\times Q_{1}\times\cdots\times Q_{s}}\) can be decomposed according to_ \[\boldsymbol{\Psi}=\Delta\cdot\hat{\boldsymbol{\Psi}} \tag{44}\] _with the delta tensor \(\Delta\in\mathbb{R}^{M\times M^{s}}\) defined by_ \[\Delta_{i,j_{1},\ldots,j_{s}}=\delta_{i,j_{1}}\cdot\ldots\cdot\delta_{i,j_{s}} \tag{45}\] _and \(\delta_{i,j_{k}}\) denoting the Kronecker delta._ Proof.: The desired identity (44) follows from \[(\Delta\cdot\hat{\boldsymbol{\Psi}})_{i,\eta_{1},\ldots,\eta_{s}} =\sum_{j_{1}=1}^{M}\cdots\sum_{j_{s}=1}^{M}\Delta_{i,j_{1},\ldots,j_{s}}\hat{\boldsymbol{\Psi}}_{j_{1},\ldots,j_{s},\eta_{1},\ldots,\eta_{s}}\] \[=\sum_{\ell=1}^{r}\left(\sum_{j_{1}=1}^{M}\delta_{i,j_{1}}\hat{ \boldsymbol{\Psi}}_{\ell,j_{1},\eta_{1}}^{(1)}\right)\cdots\left(\sum_{j_{s}=1 }^{M}\delta_{i,j_{s}}\hat{\boldsymbol{\Psi}}_{\ell,j_{s},\eta_{s}}^{(s)}\right)\] \[=\sum_{\ell=1}^{r}\hat{\boldsymbol{\Psi}}_{\ell,i,\eta_{1}}^{(1) }\cdots\hat{\boldsymbol{\Psi}}_{\ell,i,\eta_{s}}^{(s)}\] \[=\sum_{\ell=1}^{r}\psi_{\ell}^{(1)}(x_{i,1},\eta_{1})\cdots\psi_{ \ell}^{(s)}(x_{i,s},\eta_{s})=\boldsymbol{\Psi}_{i,\eta_{1},\ldots,\eta_{s}}.\qed\] The construction of the functional tensor \(\boldsymbol{\Psi}\) is illustrated in Figure 2 (a). Note that the auxiliary tensor \(\Delta\) does not explicitly appear in our numerical computations. We will also exploit the FTT format to represent the auxiliary tensor \(\hat{\boldsymbol{\Psi}}\), if it allows for a low-rank decomposition. In particular, monomials of the form \((x\cdot\eta)^{p}\) can be expressed in a compact way using a tensor train-like coupling as we show in Appendix A. Figure 2 (b) shows the corresponding FTT network for \(\boldsymbol{\Psi}\). Now we are in the position to provide a representation of the stiffness matrix \(A=(a_{ij})\in\mathbb{R}^{M\times n}\) defined in (32) as a tensor network. **Proposition 5.6**.: _Assume that the basis functions \(\varphi_{1},\ldots,\varphi_{n}\) of the ansatz space \(L_{n}\) are separable in the sense of (38) and that the kernel function \(\psi\) allows for the representation (42). Then the tensor_ \[\mathbf{A}\in\mathbb{R}^{M\times n_{1}\times\cdots\times n_{s}},\quad\mathbf{ A}_{i,j_{1},\ldots,j_{s}}=a_{i,j(j_{1},\ldots,j_{s})} \tag{46}\] _with enumeration \(j(j_{1},\ldots,j_{s})\) introduced in (39) allows for the factorization_ \[\mathbf{A}=\Delta\cdot\sum_{\ell=1}^{r}\mathbf{A}_{\ell}^{(1)}\otimes\cdots \otimes\mathbf{A}_{\ell}^{(s)},\quad\mathbf{A}_{\ell}^{(k)}=(\hat{\boldsymbol {\Psi}}_{\ell,:,:}^{(k)}\cdot\boldsymbol{\Phi}^{(k)})\in\mathbb{C}^{M\times n _{k}},\,\,\,k=1,\ldots,s, \tag{47}\] _with \(\boldsymbol{\Phi}^{(k)}\), \(\hat{\boldsymbol{\Psi}}^{(k)}\), and \(\Delta\) taken from (40), (43), and (45), respectively._ Proof.: The desired identity follows from \[\mathbf{A}_{i,j_{1},\ldots,j_{s}} =\sum_{i_{1}}^{M}\cdots\sum_{i_{s}}^{M}\Delta_{i,i_{1},\ldots,i_{s}} \sum_{\ell=1}^{r}\mathbf{A}_{\ell,i_{1},j_{1}}^{(1)}\cdots\mathbf{A}_{\ell,i_{s},j_{s}}^{(s)}\] \[=\sum_{\ell=1}^{r}\left(\sum_{i_{1}}^{M}\delta_{i,i_{1}}\mathbf{A }_{\ell,i_{1},j_{1}}^{(1)}\right)\cdots\left(\sum_{i_{s}}^{M}\ \delta_{i,i_{s}}\mathbf{A}_{\ell,i_{s},j_{s}}^{(s)}\right)\] \[=\sum_{\ell=1}^{r}\mathbf{A}_{\ell,i,j_{1}}^{(1)}\cdots\mathbf{A }_{\ell,i,j_{s}}^{(s)}\] \[=\sum_{\ell=1}^{r}\int_{Q_{1}}\psi_{\ell}(x_{i_{1}},\eta_{1}) \varphi_{j_{1}}^{(1)}(\eta_{1})\ d\eta_{1}\cdots\int_{Q_{s}}\psi_{\ell}(x_{i_ {s}},\eta_{s})\varphi_{j_{s}}^{(s)}(\eta_{s})\ d\eta_{s}\] \[=\int_{Q}\left(\sum_{\ell=1}^{r}\psi_{\ell}(x_{i_{1}},\eta_{1}) \cdots\psi_{\ell}(x_{i_{s}},\eta_{s})\right)\ \varphi_{j_{1}}^{(1)}(\eta_{1})\cdots\varphi_{j_{s}}^{(s)}(\eta_{s})\ d\eta\] \[=\int_{Q}\psi(x_{i},\eta)\varphi_{j(j_{1},\ldots,j_{s})}(\eta)\ d \eta=a_{i,j(j_{1},\ldots,j_{s})}.\qed\] Utilizing the enumeration (39), we introduce the tensor representation \[\mathbf{U}\in\mathbb{R}^{n_{1}\times\cdots\times n_{s}},\quad\mathbf{U}_{j_{1 },\ldots,j_{s}}=U_{j(j_{1},\ldots,j_{s})},\] of the unknown solution vector \(U\in\mathbb{R}^{n}\) in (33). Then, the regularized linear system (33) in Problem 4.3 takes the form \[(\varepsilon\mathbf{I}+\mathbf{A}^{\top}\mathbf{A})\mathbf{U}=\mathbf{A}^{ \top}\mathbf{b} \tag{48}\] with unit tensor \(\mathbf{I}\in\mathbb{R}^{n_{1}\times\cdots\times n_{s}}\) and \(\mathbf{b}=b\in\mathbb{R}^{M}\). Solving (48) is equivalent to minimizing the tensor analogue \[\mathbf{J}_{\varepsilon}(\mathbf{V})=\|\mathbf{A}\mathbf{V}-\mathbf{b}\|_{2,\mathbb{R}^{M}}^{2}+\varepsilon\|\mathbf{V}\|_{2,\mathbb{R}^{n_{1}\times \cdots\times n_{s}}}^{2},\quad\mathbf{V}\in\mathbb{R}^{n_{1}\times\cdots \times n_{s}},\] Figure 2. Graphical notation of the functional decomposition of \(\mathbf{\Psi}\) corresponding to the kernel \(\psi(x,\eta)\) and data points \((x_{j})_{j=1}^{M}\): (a) Using the canonical format for \(\hat{\mathbf{\Psi}}\) with cores coupled by a common rank. (b) Using the FTT format with a chain-like coupling. Blue circles represent the cores of \(\hat{\mathbf{\Psi}}\), each having one continuous mode represented by a zigzag line. Contraction with \(\Delta\) (green circle) merges all free modes of \(\hat{\mathbf{\Psi}}\) into one. of the regularized discrete loss functional \(\mathbb{J}_{\varepsilon}\) defined in (34). We now introduce the corresponding tensor-train approximation of the linear system (48). **Problem 5.7**.: _Find cores \(\mathbf{U}^{(k)}\in\mathbb{R}^{r_{k-1}\times n_{k}\times r_{k}}\), \(k=1,\ldots,s\), with \(r_{0}=r_{s}=1\) and prescribed ranks \(r_{k}\), \(k=1,\ldots,s-1\) such that the resulting tensor train_ \[\mathbf{U}_{r}=\sum_{\ell_{0}=1}^{r_{0}}\cdots\sum_{\ell_{s}=1}^{r_{s}} \mathbf{U}^{(1)}_{\ell_{0},:,\ell_{1}}\otimes\cdots\otimes\mathbf{U}^{(s)}_{ \ell_{s-1},:,\ell_{s}}\in\mathbb{R}^{n_{1}\times\cdots\times n_{s}}, \tag{49}\] _is minimizing the regularized discrete loss functional \(\mathbf{J}_{\varepsilon}\) over the submanifold of all tensor trains \(\mathbf{V}\) of the form (49)._ Existence of a solution \(\mathbf{U}_{r}\) of Problem 5.7 follows by compactness arguments. Note that we have \(\mathbf{U}_{r}=\mathbf{U}\), if the selection \(r_{1},\ldots,r_{s-1}\) agrees with the minimal rank of the unique solution \(\mathbf{U}\) of (48), because there exists an exact tensor train representation of \(\mathbf{U}\) in this case (see [33, Theorem 1]). As a consequence of non-uniqueness of tensor train representations, uniqueness of the cores \(\mathbf{U}^{(k)}\in\mathbb{R}^{r_{k-1}\times n_{k}\times r_{k}}\) can not be expected. ### Algebraic solution by alternating linear systems The Tensor-Train Approximation Problem 5.7 allows for a variety of different methods for direct or iterative solution, such as pseudoinversion [15, 37, 38, 39] or core-wise linear updates [14, 15, 40, 41], respectively. Here, we concentrate on iterative solution by _alternating ridge regression_ (ARR), cf. [15], because this approach significantly reduces computational cost and memory consumption in comparison with explicit computation of pseudoinverses (see, e.g., [15] for details). These methods provide successive updates of the cores \(\tilde{\mathbf{U}}^{(k)}\in\mathbb{R}^{r_{k-1}\times n_{k}\times r_{k}}\), \(k=1,\ldots,s\), by solving a sequence of reduced linear problems. More precisely, for given iterate \(\tilde{\mathbf{U}}\) of the form (49) and each fixed \(k\), the cores \(\tilde{\mathbf{U}}^{(1)},\ldots,\tilde{\mathbf{U}}^{(k-1)}\) are _left-orthonormalized_ and \(\tilde{\mathbf{U}}^{(k+1)},\ldots,\tilde{\mathbf{U}}^{(s)}\) are _right-orthonormalized_ by successive singular value decompositions [30] such that the rows and columns, respectively, of certain reshapes of these cores form orthonormal sets. Note that, without truncation, this procedure produces a different but equivalent representation of \(\tilde{\mathbf{U}}\), say \(\tilde{\mathbf{U}}\). The orthonormalized cores then define a retraction operator \[\mathbf{Q}_{\tilde{\mathbf{U}},k}\in\mathbb{R}^{(n_{1}\times\cdots\times n_{s })\times(r_{k-1}\times n_{k}\times r_{k})},\] which satisfies \[\mathbf{Q}_{\tilde{\mathbf{U}},k}\mathbf{V}^{(k)}=\sum_{\ell_{0}=1}^{r_{0}} \cdots\sum_{\ell_{s}=1}^{r_{s}}\bigotimes_{i=1}^{k-1}\tilde{\mathbf{U}}^{(i)}_ {\ell_{i-1},:,\ell_{i}}\otimes\mathbf{V}^{(k)}_{\ell_{k-1},:,\ell_{k}}\otimes \bigotimes_{i=k+1}^{s}\tilde{\mathbf{U}}^{(i)}_{\ell_{i-1},:,\ell_{i}}\] for all \(\mathbf{V}^{(k)}\in\mathbb{R}^{r_{k-1}\times n_{k}\times r_{k}}\) and is orthonormal in the sense that \[\mathbf{Q}^{\top}_{\tilde{\mathbf{U}},k}\cdot\mathbf{Q}_{\tilde{\mathbf{U}},k }=\mathbf{I}\in\mathbb{R}^{(r_{k-1}\times n_{k}\times r_{k})\times(r_{k-1} \times n_{k}\times r_{k})}. \tag{50}\] Minimization with respect to the \(k\)-th core then gives rise to the reduced problem to minimize \[\|\mathbf{A}\mathbf{Q}_{\tilde{\mathbf{U}},k}\mathbf{V}^{(k)}-\mathbf{b}\|_{ 2,\mathbb{R}^{M}}^{2}+\varepsilon\|\mathbf{Q}_{\tilde{\mathbf{U}},k}\mathbf{V} ^{(k)}\|_{2,\mathbb{R}^{n_{1}\times\cdots\times n_{s}}}^{2}\] over all \(\mathbf{V}^{(k)}\in\mathbb{R}^{r_{k-1}\times n_{k}\times r_{k}}\) or, equivalently, to solve the reduced linear system \[\mathbf{Q}^{\top}_{\tilde{\mathbf{U}},k}(\varepsilon\mathbf{I}+\mathbf{A}^{ \top}\mathbf{A})\mathbf{Q}_{\tilde{\mathbf{U}},k}\tilde{\mathbf{U}}^{(k)}_{ \mathrm{new}}=\mathbf{Q}^{\top}_{\tilde{\mathbf{U}},k}\mathbf{A}^{\top} \mathbf{b} \tag{51}\] for the new core \(\tilde{\mathbf{U}}^{(k)}_{\mathrm{new}}\in\mathbb{R}^{r_{k-1}\times n_{k}\times r _{k}}\) (see, e.g. [14, 15, 40, 41] for details). The unique solution \(\tilde{\mathbf{U}}^{(k)}_{\mathrm{new}}\) of (51) can be computed, e.g., by Cholesky decomposition of the symmetric and positive definite coefficient matrix. The corresponding update of cores is typically applied in alternating order, i.e., from \(k=1\) to \(k=s\) and then back to \(k=1\). As the same regularization parameter \(\varepsilon>0\) is used for each core \(k\), the alternating linear systems approach [14] applied to (48) and alternating ridge regression [15] are equivalent in this case. As a consequence of the intrinsic nonlinearity of the overall iterative approach, the convergence analysis is complicated. We refer to [14, 42, 43] for further information. ## 6. Sampling of discrete neural network parameters By construction, an approximate solution \(\tilde{\mathbf{U}}\in\mathbb{R}^{n_{1}\times\cdots\times n_{s}}\) of Problem 5.7 provides an approximate solution \[\tilde{U}=(\tilde{U}_{j})\in\mathbb{R}^{n},\qquad\tilde{U}_{j(j_{1},\ldots,j_{ s})}=\tilde{\mathbf{U}}_{j_{1},\ldots,j_{s}},\] of Problem 4.3 by utilizing the enumeration (39). In turn, \(\tilde{U}\) gives rise to the approximate solution \[\tilde{u}=\sum_{j=1}^{n}\tilde{U}_{j}\varphi_{j}\in L_{n}\subset L^{2}(Q)\] of Problem 2.1 (function data) or Problem 3.6 (point data) and the resulting approximation \[\mathcal{G}\tilde{u}=\sum_{j=1}^{n}\tilde{U}_{j}\int_{Q}\psi(\cdot,\eta) \varphi_{j}(\eta)\;d\eta \tag{52}\] of the trained Fredholm network \(\mathcal{G}u\) introduced in Section 3.3. Note that \(\mathcal{G}\tilde{u}(x)\) can be evaluated in given test or training points by contracting \(\tilde{\mathbf{U}}\) with the corresponding stiffness tensor \(\mathbf{A}\). Figure 3. Graphical notation of tensor-based counterpart of the (underdetermined) system \(AU=b\): The cores of \(\mathbf{\Psi}\) (blue circles) are contracted with the cores of \(\mathbf{\Phi}\) (orange circles) by integrating over common modes. Together with the delta tensor (green circle), this system builds the tensor operator \(\mathbf{A}\). The coefficient tensor \(\mathbf{U}\) (white circles) is approximated in the TT format. Here, \(\hat{\mathbf{\Psi}}\) is given in canonical format but could also be defined as functional tensor train, see Section 5.2. Further approximation of \(\mathcal{G}\tilde{u}\) by classical Monte Carlo sampling of the integral \[\mathcal{G}\tilde{u}=\int_{Q}\psi(\cdot,\eta)\tilde{u}(\eta)\;d\eta \tag{53}\] provides parameters \(\tilde{\zeta}_{i}=(\tilde{\eta}_{i},\tilde{u}_{i})\) with i.i.d. \(\tilde{\eta}_{i}\) and \(\tilde{u}_{i}=\tilde{u}(\tilde{\eta}_{i})\), \(i=1,\ldots,N\), and thus the trained neural network \(F_{N}(\cdot,\tilde{\zeta})\). We would expected higher accuracy from quasi-Monte Carlo integration based on quasi-random sequences in \(\mathbb{R}^{s}\), such as, e.g., Sobol sequences, which fill the space more uniformly than pseudo-random sequences as used for classical Monte Carlo integration. In order to further enhance sampling quality, we now introduce _inductive importance sampling_ that is directly targeting the underlying loss functional \(\mathcal{J}_{N}\) defined in (8). Given a set of quasi-Monte Carlo sample points \((\tilde{\eta}_{i})_{i=1}^{N^{\prime}}\), corresponding parameter function evaluations \((\tilde{u}(\tilde{\eta}_{i}))_{i=1}^{N^{\prime}}\), and some \(N\leq N^{\prime}\), we want to inductively find parameters \((\tilde{\eta}_{i_{j}})_{j=1}^{N}\) such that \(F_{N}(\cdot,\zeta)\) with \(\zeta=(\tilde{\eta}_{i_{j}},\tilde{u}(\tilde{\eta}_{i_{j}}))_{j=1}^{N}\) is reducing the loss functional \(\mathcal{J}_{N}\) sufficiently well. For this purpose, the first sample \(\eta_{i_{1}}\) is chosen according to \[\eta_{i_{1}}=\operatorname*{argmin}_{\eta\in\{\eta_{1},\ldots,\eta_{N^{\prime} }\}}\mathcal{J}_{1}((\eta,\tilde{u}(\eta)))\] and for given samples \(\eta_{i_{1}},\ldots,\eta_{i_{K}}\), \(K<N\), we select \[\eta_{i_{K+1}}=\operatorname*{argmin}_{\eta\in\{\eta_{1},\ldots,\eta_{N^{ \prime}}\}\setminus\{\eta_{i_{1}},\ldots,\eta_{i_{K}}\}}\mathcal{J}_{K+1}\left( (\eta_{i_{1}},\tilde{u}(\eta_{i_{1}})),\ldots,(\eta_{i_{K}},\tilde{u}(\eta_{i_ {K}})),(\eta,\tilde{u}(\eta))\right).\] Note that we use exact kernel and activation functions here and not their approximate factorizations which the Fredholm network is trained on. While quasi-Monte Carlo integration performed reasonably well in simple cases, we found a considerable improvement of efficiency by inductive importance sampling in our numerical experiments to be reported below. ## 7. Numerical experiments In order to demonstrate the practical relevance of our approach, we now consider three well-established test cases of regression and classification type. In particular, we will numerically investigate different aspects of the tensor-based training of neural networks, such as adaptability, accuracy, and robustness. We emphasize that kernel, activation and even basis functions for discretization have been chosen ad hoc, and no profound parameter optimization is performed. Our implementation of ARR and other relevant tensor algorithms are available in Scikit-TT1. Footnote 1: [https://github.com/PGelss/scikit_tt](https://github.com/PGelss/scikit_tt) ### Bank note authentication As a first example, we consider a classification problem to distinguish forged from genuine bank notes, utilizing the UCI banknote authentication data set2 from [16]. It contains 1372 samples of different features that were extracted from images of genuine and forged banknote-like specimens by applying wavelet transforms. Each sample has \(d=4\) different attributes: variance, skewness, curtosis, and entropy of the wavelet transformed images. The data set is randomly divided into \(M=1098\) (\(\approx 80\%\)) training and \(m=274\) test samples. We first apply min-max normalization to the given training data points \(\hat{x}_{i}=(x_{i,k})_{k=1}^{d}\), \(i=1,\ldots,M\), to obtain \[x_{i,k}=\frac{\hat{x}_{i,k}-\min(k)}{\max(k)-\min(k)}\in[0,1],\qquad i=1,\ldots,M,\quad k=1,\ldots,d, \tag{54}\] denoting \(\min(k)=\min_{i\in\{1,\ldots,M\}}\hat{x}_{i,k}\) and \(\max(k)=\max_{i\in\{1,\ldots,M\}}\hat{x}_{i,k}\). Hence, \(X=[0,1]^{d}\). The test data points are normalized in the same way using the same constants. For the neural network \(F_{N}\) of the form (1), we then choose a Gaussian activation function (7) with \(\kappa=1\) and the same parameter set for each dimension, i.e., \(Q=[-1,1]^{s}\) with \(s=d=4\). Discretization of the continuous training Problem 3.2 is performed by piecewise constant finite elements with respect to an equidistant grid with mesh size \(1/4\), see Example 4.2. The resulting ansatz space has the dimension \(n=8^{d}=4096\). We select the Tikhonov regularization parameter \(\varepsilon=10^{-3}\). For the iterative solution of the resulting Problem 5.7 with ranks \(r_{1}=\cdots=r_{s-1}=10\) we apply 20 sweeps of ARR (cf. Section 5.3) with all tensor core entries equal to one as initial guess. From the resulting approximation \(\tilde{\mathbf{U}}\) of the exact solution \(\mathbf{U}_{r}\), we then obtain the approximation \(\tilde{u}\in L_{n}\subset L^{2}(Q)\) of the solution \(u\in L^{2}(Q)\) of Problem 3.2, and the resulting approximately trained Fredholm network \(\mathcal{G}\tilde{u}\) as explained in Section 6. From \(\mathcal{G}\tilde{u}\) we extract discrete parameters \(\tilde{\zeta}=(\tilde{\eta}_{i},\tilde{u}(\tilde{\eta}_{i}))_{i=1}^{N}\) by quasi-Monte Carlo sampling for various numbers \(N\) of neurons to obtain the trained neural network \(F_{N}(x,\tilde{\zeta})\), cf. Section 6. A sample \(x\in X\) is then classified as 0 (genuine), if \(F_{N}(x,\tilde{\zeta})<0.5\) and 1 (forged) otherwise. In order to test the predictability of our trained neural networks for a fixed number \(N\) of neurons, we randomly select training and test sets of as described above, use quasi-Monte Carlo sampling to extract discrete parameters and evaluate the corresponding realization of the classification rate, i.e., the ratio of the number of correct predictions and the size of the selected test set. This procedure is repeated 100 times, in order to obtain expectation and standard deviation of the classification rates together with the number of perfect classifications, i.e., the number of test sets that are correctly classified without an exception. The results are shown in Table 1 for various \(N\). As expected, the predictability is increasing with increasing \(N\). While no test sets are perfectly classified for \(N\leq 256\), we even achieve full optimality for \(N=1024\). Note that predictability deteriorates for even larger \(N\), which might be due to numerical noise caused by round-off errors. \begin{table} \begin{tabular}{c c c} \(N\) & classification rate & perfect classification \\ \hline \(2^{6}=64\) & \(0.9353\pm 0.0147\) & 0 \\ \(2^{7}=128\) & \(0.8653\pm 0.0279\) & 0 \\ \(2^{8}=256\) & \(0.7827\pm 0.0136\) & 0 \\ \(2^{9}=512\) & \(0.9991\pm 0.0022\) & 81 \\ \(2^{10}=1024\) & \(1.0000\pm 0.0000\) & 100 \\ \(2^{11}=2048\) & \(0.9999\pm 0.0007\) & 96 \\ \end{tabular} \end{table} Table 1. Results for the bank note authentication data set: Predictability of trained neural network \(F_{N}(\cdot,\tilde{\zeta})\) for increasing \(N\) in terms of expectation and standard deviation of the classification rates. ### Concrete compressive strength prediction We aim at the description of concrete compressive strength in terms of tolerated mechanical stress as a function \(F\) of the values \(x=(x_{k})_{k=1}^{d}\) of \(d=8\) parameters, i.e., the percentage of cement, fly ash, blast furnace slag, superplasticizer, fine aggregates, coarse aggregates, water, and age. To this end, we make use of a data set with 1030 samples that was collected over several years and has repeatedly been deployed for corresponding training of neural networks, see, e.g., [17, 18, 19, 20]. We randomly split the data set into \(M=824\) (\(80\%\)) training and \(m=206\) test samples. As the output of each sample is distributed between \(2.33\,\mathrm{MPa}\) and \(82.60\,\mathrm{MPa}\), different input variables might be of different orders of magnitude. In order to avoid large values dominating the others, min-max normalization is applied in analogy to (54), and we obtain \(X=[0,1]^{d}\). We consider a neural network of the form (1) with ridge kernel and Heaviside activation function (3) together with the parameter set \(Q=[-1,1]^{s}\subset\mathbb{R}^{s}\), \(s=d+1=9\). For discretization of the continuous training Problem 3.2, we choose the ansatz space \(L_{n}\) spanned by \(n=3^{d}=6561\) tensor products of Chebyshev polynomials of the first kind up to order \(2\). The regularization parameter is set to \(\varepsilon=10^{-8}\). Approximate factorization of the Heaviside activation function is performed as presented in Appendix A.3, and we set \(\ell_{0}=100\). Hence, the decomposition (47) of the corresponding approximate coefficient tensor \(\mathbf{A}\in\mathbb{R}^{M\times n}=\mathbb{R}^{824\times 6561}\) has the canonical rank \(r=201\). We normalize the tensor \(\mathbf{A}\) such that \(\|\mathbf{A}\|_{2,\mathbb{R}^{M\times n}}=1\). The coefficient tensor corresponding to the test set is multiplied by the same normalization constant. For the tensor-train approximation (49) in Problem 5.7 we choose the ranks \(r_{1}=\dots=r_{s-1}=10\) and apply 5 sweeps of ARR (cf. Section 5.3) with all tensor core entries equal to one as an initial guess. From the resulting approximate solution \(\tilde{\mathbf{U}}\) we derive the approximate solution \(\tilde{u}\) of Problem 3.2 which in turn provides the approximately trained Fredholm network \(\mathcal{G}\tilde{u}\) as explained in Section 6. Discrete parameters \(\tilde{\zeta}=(\tilde{\eta}_{i},\tilde{u}(\tilde{\eta}_{i}))_{i=1}^{N}\) providing the corresponding neural network \(F_{N}(\cdot,\tilde{\zeta})\) can finally be obtained by a suitable sampling strategy. In this experiment, we use both standard quasi-Monte Carlo sampling and inductive importance sampling as introduced in Section 6. The prediction accuracy of the Fredholm network \(\mathcal{G}\tilde{u}\) and of neural networks \(F_{N}(\cdot,\tilde{\zeta})\) on given test data \((y_{i},F(y_{i}))\), \(i=1,\dots,m\), are measured by the usual \(R^{2}\) scores \[R_{\mathcal{G}}^{2}=1-\frac{\sum_{i=1}^{m}(F(y_{i})-(\mathcal{G}\tilde{u})(y_ {i}))^{2}}{\sum_{i=1}^{m}(F(y_{i})-\overline{F}(y))^{2}}\quad\text{and}\quad R _{N}^{2}=1-\frac{\sum_{i=1}^{m}(F(y_{i})-F_{N}(y_{i},\tilde{\zeta}))^{2}}{ \sum_{i=1}^{m}(F(y_{i})-\overline{F}(y))^{2}},\] respectively, where \(\overline{F}(y)=\frac{1}{m}\sum_{i=1}^{m}F(y_{i})\) stands for the algebraic mean of the test values. Note that for evaluation of \(F_{N}(y_{i},\tilde{\zeta})\) the exact Heaviside activation function \(\sigma_{\infty}\) is used and not its approximate factorization. Corresponding \(R_{\mathcal{G}}^{2}\) and \(R_{N}^{2}\) scores on training data are computed in the same way using the training data \((x_{i},F(x_{i}))\), \(i=1,\dots,M\), instead. Similar to the previous example, \(R^{2}\) scores are considered as random variables, and we apply standard Monte Carlo with 100 samples each of random training and test data sets to approximately compute its expectation and standard deviation. The resulting scores of the Fredholm network \(\mathcal{G}\tilde{u}\) are \[\text{training sets: }R_{\mathcal{G}}^{2}=0.9154\pm 0.0029\qquad\qquad\text{ test sets: }R_{\mathcal{G}}^{2}=0.8701\pm 0.0180.\] with samples of the \(R_{\mathcal{G}}^{2}\) scores on training sets ranging between \(0.9093\) and \(0.9244\) and on test sets between \(0.8202\) and \(0.9058\). These results indeed match the scores obtained by state-of-the-art ML approaches, cf. [20, 44]. However, in order to achieve similar \(R_{N}^{2}\) scores for discrete neural networks \(F_{N}(\cdot,\tilde{\zeta})\) as obtained by quasi-Monte Carlo sampling, it turned out in our numerical experiments that about \(N=2^{20}\approx 10^{6}\) sampling points were required. This motivates application of more advanced sampling strategies such as inductive importance sampling introduced in Section 6. For this strategy, we obtained a considerable reduction of the number \(N\) of required samples, as illustrated in Table 2. As in the previous example, predictability increases with growing \(N\), both on training and test data. Observe that the \(R_{N}^{2}\) scores on training data are even better than for the Fredholm network \(\mathcal{G}\tilde{u}\) which might be an outcome of the particular importance of training data for the applied sampling strategy. Even though the \(R_{N}^{2}\) scores on test sets are slightly worse, they are still comparable with state-of-the-art ML approaches, cf. [20, 44]. ### MNIST data set In our third experiment, we classify hand-written digits from the MNIST data set [21] that consists of representations of the ten digits \(0,\ldots,9\) as grayscale images of \(28\times 28\) pixels. We slightly modified the MNIST dataset by reducing the size of these images to \(d=14\times 14=196\) pixels in order to lower the computational effort for classification. The data set is divided into \(M=60,000\) training images and \(m=10,000\) test images with associated labels, and we have \(X=[0,1]^{d}\). For the neural network, we choose the ridge kernel \(\psi\) from (2) with logistic activation function \(\sigma_{\kappa}\) from (4) and \(\kappa=1\). More precisely, we use its FTT approximation based on the identification of the sample space \(X\) with its embedding \(\{(x,1)^{\top}\mid x\in X\}\subset\mathbb{R}^{s}\), \(s=d+1=197\) and Taylor approximation (60) at \(z=0\). See Appendix A.2 for details. In order to provide sufficient accuracy of this approximation, we require \(|z|=|x_{i}\cdot\eta|\leq 2\) for all data points \(x_{i}\in X\). This is guaranteed by the choice \(\eta\in Q=[-2/\rho_{X},2/\rho_{X}]^{s}\), denoting \(\rho_{X}=\max_{i\in\{1,\ldots,M\}}\sum_{j=1}^{d+1}x_{i,j}\). As each image \(x\in X\) has to be classified as one of the ten digits, the target function \(F\) is now vector-valued. Utilizing one-hot encoding, we get \(F(x)=(F_{i}(x))_{i=1}^{10}\in\mathbb{R}^{10}\), \(x\in X\), with \[F_{l}(x)=\begin{cases}1&\text{if $x$ represents the digit $l$}\\ 0&\text{otherwise}\end{cases},\quad l=0,\ldots,9. \tag{55}\] Corresponding vector-valued versions of the neural network (1) and of its continuous counterpart (3.6) are obtained by taking coefficients \(u_{i}\in\mathbb{R}^{10}\) and parameter functions \(u\in\left(L^{2}(Q)\right)^{10}\), respectively. Observe that each component \(u_{l}\) of \(u\) can be (approximately) computed separately from the scalar Problem 3.6 with \(F=F_{l}\) and \(F_{l}\) defined in (55). For the Ritz-Galerkin discretization of each of these scalar problems, we choose basis elements \(\varphi_{j}^{(k)}\) of the form (38) with constant and linear functions \(\varphi_{j_{1}}^{(k)}\) and \(\varphi_{j_{2}}^{(k)}\), respectively. \begin{table} \begin{tabular}{c c c} \(N\) & \(R_{N}^{2}\) score (training data) & \(R_{N}^{2}\) score (test data) \\ \hline 200 & \(0.9023\pm 0.0051\) & \(0.8040\pm 0.0244\) \\ 400 & \(0.9406\pm 0.0027\) & \(0.8330\pm 0.0219\) \\ 600 & \(0.9563\pm 0.0023\) & \(0.8473\pm 0.0209\) \\ 800 & \(0.9648\pm 0.0019\) & \(0.8532\pm 0.0204\) \\ 1000 & \(0.9702\pm 0.0019\) & \(0.8586\pm 0.0198\) \\ \end{tabular} \end{table} Table 2. Results for the Concrete compressive strength prediction: Predictability of trained neural network \(F_{N}(\cdot,\tilde{\zeta})\) for increasing \(N\) in terms of expectation and standard deviation of \(R^{2}\) scores. This leads to a subspace \(L_{n}\) of \(L^{2}(Q)\) with dimension \(n=2^{s}=2^{197}\approx 2\cdot 10^{59}\). We choose the Tikhonov regularization parameter \(\varepsilon=10^{-15}\) and fix \(r_{1}=\cdots=r_{d}=20\) in the tensor train approximation Problem 5.7. To the initial iterate of all core entries set to one (before orthonormalization) we apply 5 ARR sweeps to obtain the approximate solution \(\tilde{\mathbf{U}}_{l}\), which provides the corresponding component \(\mathcal{G}\tilde{u}_{l}\) of the (approximately) trained Fredholm network, cf. Section 6. We finally use the softmax function for classification, i.e. for each entry \(x\) the index \(l_{\max}\) of the largest of the components \((\mathcal{G}\tilde{u}_{l})(x)\), \(l=0,\ldots,9\), determines the detected label. For comparison with this trained Fredholm network, we consider single layer neural networks built from the well-established Keras library3. The input layer of the network comprises 196 nodes (one for each pixel), followed by a hidden layer with a varying number of \(N_{K}\) nodes and the logistic activation function. The output layer also uses one-hot encoding and the softmax function. For optimizing of the neural network parameters, 10% of the given training set is used as a validation set. The parameters are then trained for a sufficiently large number of iterations in order to ensure convergence of the validation loss which indicates how well the model fits to unseen data. Footnote 3: [https://keras.io](https://keras.io) Figure 4 shows the classification rates as obtained from our Fredholm network \(\mathcal{G}\tilde{u}\) and of Keras networks of size \(N_{K}=34,64,128,256,512\) on the fixed MNIST test data set of \(m=10,000\) test images over the number \(M\) of utilized training images. For the largest number of \(M=60,000\) training data, the classification rates of the Keras networks are ranging from \(0.9789\) to \(0.9832\) for sufficiently large \(N_{K}\geq 64\) and are thus comparable with the classification rate \(0.9805\) of the Fredholm network. However, Keras networks are clearly outperformed for smaller sets of training data. ## 8. Conclusion and outlook In this work, we have proposed a novel approach to function approximation and the training of large and high-dimensional shallow neural networks, based on their continuous asymptotic limit. Utilizing resulting Fredholm networks for function approximation and also for training Figure 4. Results for the MNIST data set: Classification rates obtained from the Fredholm network over the number \(M\) of training images in comparison with Keras networks with increasing number \(N_{K}\) of nodes in the hidden layer. in the original discrete case, we have thus traded highly nonlinear discrete training problems with finitely many unknown parameters for linear continuous training problems with infinitely many unknown values of a parameter function. Fredholm training problems can be regarded as least-squares formulations of Fredholm integral equations of the first kind. They were solved approximately by Ritz-Galerkin discretization in combination with Tikhonov regularization and tensor train methods. Here, we particularly aimed at a significant reduction of memory consumption as well as computational costs to mitigate the curse of dimensionality as occurring for high-dimensional data. To this end, we described different tensor formats, suitable factorizations of kernel and basis functions as well as an alternating scheme for solving the tensorized linear training problems. Finally, we considered quasi Monte-Carlo sampling of discrete neural network parameters and introduced inductive importance sampling which is directly targeting the loss functional \(\mathcal{J}_{N}\). The predictive quality of the resulting approximatively trained Fredholm and neural networks are illustrated by numerical experiments with three well-established test problems of regression and classification type. The results clearly confirm that our approach is highly competitive with state-of-the-art neural network-based methods concerning efficiency and reliability. The investigations carried out in this work offer a number of further promising developments. In particular, numerical analysis of the whole approach will be subject of future research and will provide error estimates together with problem-oriented ansatz functions, more sophisticated regularization techniques, selection of tensor ranks, and further advanced sampling strategies.
2305.11833
Complexity of Neural Network Training and ETR: Extensions with Effectively Continuous Functions
We study the complexity of the problem of training neural networks defined via various activation functions. The training problem is known to be existsR-complete with respect to linear activation functions and the ReLU activation function. We consider the complexity of the problem with respect to the sigmoid activation function and other effectively continuous functions. We show that these training problems are polynomial-time many-one bireducible to the existential theory of the reals extended with the corresponding activation functions. In particular, we establish that the sigmoid activation function leads to the existential theory of the reals with the exponential function. It is thus open, and equivalent with the decidability of the existential theory of the reals with the exponential function, whether training neural networks using the sigmoid activation function is algorithmically solvable. In contrast, we obtain that the training problem is undecidable if sinusoidal activation functions are considered. Finally, we obtain general upper bounds for the complexity of the training problem in the form of low levels of the arithmetical hierarchy.
Teemu Hankala, Miika Hannula, Juha Kontinen, Jonni Virtema
2023-05-19T17:17:00Z
http://arxiv.org/abs/2305.11833v1
# Complexity of Neural Network Training and ETR: Extensions with Effectively Continuous Functions ###### Abstract We study the complexity of the problem of training neural networks defined via various activation functions. The training problem is known to be \(\exists\mathbb{R}\)-complete with respect to linear activation functions and the ReLU activation function. We consider the complexity of the problem with respect to the sigmoid activation function and other effectively continuous functions. We show that these training problems are polynomial-time many-one bireducible to the existential theory of the reals extended with the corresponding activation functions. In particular, we establish that the sigmoid activation function leads to the existential theory of the reals with the exponential function. It is thus open, and equivalent with the decidability of the existential theory of the reals with the exponential function, whether training neural networks using the sigmoid activation function is algorithmically solvable. In contrast, we obtain that the training problem is undecidable if sinusoidal activation functions are considered. Finally, we obtain general upper bounds for the complexity of the training problem in the form of low levels of the arithmetical hierarchy. ## I Introduction We study the computational complexity of neural network (NN) training problems parameterized by various activation functions. Such a training problem asks, given a neural network architecture, finite training data, a cost function and a threshold, whether there exist real-valued edge weights and neuron biases for the network such that the total training error with respect to the training data is below the given threshold value. Neural network training problems have been studied extensively (see [1] for a comprehensive survey of the history) and recently a version of this problem was shown to be complete for the complexity class \(\exists\mathbb{R}\)[2, 3]. The aforementioned complexity class \(\exists\mathbb{R}\) is defined as the class of decision problems \(P\) that are polynomial-time reducible to the existential theory of the reals, that is, to the corresponding decision problem \(\mathrm{ETR}\)[4]. In other words, there is a polynomial-time computable function \(f\) such that \(x\in P\) if and only if \(f(x)\) is an existential first-order (\(\mathrm{FO}\)) formula that is true over the structure \((\mathbb{R},+,\times,<,=,0,1)\) of the ordered field of the real numbers. The latter question is easily seen to be equivalent to deciding whether a finite system of polynomial equations and inequations with integer coefficients and real unknowns has a solution. The class \(\exists\mathbb{R}\) has turned out to have many interesting complete problems, for instance the so-called art gallery problem [5], two-dimensional packing problems [6], and certain decision problems on symmetric Nash Equilibria [7]. The activation functions in the \(\exists\mathbb{R}\)-complete training problem mentioned above are restricted to linear functions and the rectified linear unit (ReLU) activation function. In practice, there are also other useful activation functions such as the standard logistic sigmoid function, which is defined in terms of the exponential function, and sinusoidal activation functions. However, whereas \(\mathrm{ETR}\) is \(\mathsf{NP}\)-hard and included in \(\mathsf{PSPACE}\)[8], it is a long-standing and influential open problem posed by Alfred Tarski whether exponential arithmetic is decidable. This problem is known to be related to another major open question - _Schanuel's conjecture_ - in transcendental number theory (see, e.g., [9, 10]). On the other hand, the theory of the reals extended by the sine function is known to be undecidable, even under some further restrictions on the allowed syntax of the formulae [11]. In this article, we generalize the connection between \(\mathrm{ETR}\) and the neural network training problem from linear functions and the ReLU activation function to arbitrary real-valued functions. On the \(\mathrm{ETR}\) side, the corresponding activation function is added as a new function symbol to the signature of the underlying structure \((\mathbb{R},+,\times,<,=,0,1)\). We show that the NN training problem using \(f\) as an activation function together with the identity activation function is complete for the extension \(\exists\mathbb{R}_{f}\) of the class \(\exists\mathbb{R}\). In other words, this training problem is polynomial-time many-one bireducible to the existential theory of the reals extended with \(f\). Besides a single activation function \(f\), we allow the use of a set \(\tau\) of activation functions both in the training problem and in the definition of complexity classes of the form \(\exists\mathbb{R}_{\tau}\). Our result implies that the decidability of the training problem of neural networks using the sigmoid activation function is equivalent to the decidability of (the existential fragment of) exponential arithmetic. In fact, due to a certain model theoretic property (i.e., _model completeness_) of the theory of exponential arithmetic, this theory is decidable if and only if its existential fragment is decidable, and for showing decidability, it suffices to show it to be recursively enumerable (\(\Sigma^{0}_{1}\)) (see, e.g., [10] for further discussion). Another immediate consequence is that the neural network training problem is undecidable if the sine function is allowed to be used for neural activation. Interestingly, sinusoidal activation functions have already been observed to be hard to train in simulations, and have been analyzed, for instance, in [12]. Moreover, we establish upper bounds for the complexity of the NN training problem in the case of _effectively continuous_ activation functions. The class of effectively continuous functions (see [10]) contains, for example, the sigmoid function and sinusoidal activation functions. We show, using rational approximations and basic topological properties, that it is possible to place these problems and the theories \(\exists\mathbb{R}_{\tau}\) into \(\Sigma^{0}_{3}\), the third level of the arithmetical hierarchy. We also show that for effectively continuous functions, the complexity of \(\exists\mathbb{R}_{\tau}\) drops to \(\Sigma^{0}_{1}\) if the use of the equality sign is disallowed in the formulae. However, it is not known whether this seeming distinction is real or not, for instance, in the case of the exponential function and \(\exists\mathbb{R}_{\mathrm{exp}}\). As a matter of fact, this question can be shown to be equivalent to Tarski's exponential function problem. Note that disallowing equalities in favour of the strict order relation has no implications in the complexity of \(\mathrm{ETR}\), as has been shown in [4]. In addition, the neural network training problem can be restricted in a manner which is contained in the corresponding strictly ordered variant of the class \(\exists\mathbb{R}_{\tau}\). Under this formulation, the set of weights and biases satisfying an instance of the training problem can be observed to be _stable_ in the sense that it is an open set in the standard Euclidean topology. In the next two sections, we will present model-theoretic definitions and properties of the complexity classes that are obtained by extending \(\mathrm{ETR}\) with new real-valued functions. We give an emphasis on effectively continuous functions and give a short summary of their basic properties, restated from [10]. Next, we formulate such variants of the NN training problem parameterized by different activation functions that are complete for the corresponding extensions of the complexity class \(\exists\mathbb{R}\). In the last section, we formulate some shortcomings of our neural network construction as open questions. ## II Preliminaries For real numbers \(a\) and \(b\), we let \((a,b)\) and \([a,b]\) denote the open and closed intervals with endpoints \(a\) and \(b\), respectively. We write \(|a|\) for the absolute value of \(a\). For sets \(A\) and \(B\), we write \(A^{B}\) to denote the set of all functions with domain \(B\) and co-domain \(A\). We assume familiarity with basic complexity classes such as \(\mathsf{P}\), \(\mathsf{NP}\) and \(\mathsf{PSPACE}\), and briefly review some concepts from computability theory (see, e.g., [13]). In this context, it is customary to assume that finite objects are encoded as natural numbers. A relation of natural numbers \(S\subseteq\mathbb{N}^{n}\), for a fixed \(n\geq 1\), is _computable_ (or _decidable_) if there exists a Turing machine that given any tuple \(x\in\mathbb{N}^{n}\) decides whether or not \(x\in S\). The _arithmetical hierarchy_ is formed by the classes of sets \(\Sigma^{0}_{k}\) and \(\Pi^{0}_{k}\), \(k\in\mathbb{N}\), defined recursively as follows: * The class \(\Sigma^{0}_{0}=\Pi^{0}_{0}\) consists of all computable relations \(S\) over \(\mathbb{N}\). * The class \(\Sigma^{0}_{k+1}\) consists of all relations \(S(x_{1},\ldots,x_{n})\) that are definable by a sentence of the form \(\exists y_{1}\ldots y_{m}R(x_{1},\ldots,x_{n},y_{1},\ldots,y_{m})\), where \(R\) is a relation in \(\Pi^{0}_{k}\). * The class \(\Pi^{0}_{k+1}\) consists of all relations \(S(x_{1},\ldots,x_{n})\) that are definable by a sentence of the form \(\forall y_{1}\ldots y_{m}R(x_{1},\ldots,x_{n},y_{1},\ldots,y_{m})\), where \(R\) is a relation in \(\Sigma^{0}_{k}\). The classes \(\Sigma^{0}_{1}\) and \(\Pi^{0}_{1}\) thus form the sets of _recursively enumerable_ relations and _co-recursively enumerable_ relations, respectively. In addition, a well-known consequence of Post's theorem is that for each natural number \(k\) the strict inclusions \(\Sigma^{0}_{k}\unlhd\Sigma^{0}_{k+1}\) and \(\Pi^{0}_{k}\subsetneq\Pi^{0}_{k+1}\) hold. The first-order language of _real arithmetic_, written \(\operatorname{FO}(+,\times,<,=,0,1)\), is given by the grammar \[\phi::=i<i\mid i=i\mid\phi\wedge\phi\mid\phi\vee\phi\mid\exists x\phi\mid\forall x\phi, \tag{1}\] where \(i\) stands for numerical terms given by the grammar \[i::=0\mid 1\mid x\mid i\times i\mid i+i,\ \ \ \text{where $x$ is a first-order variable.}\] Note that adding negation to (1) does not increase the expressiveness of the language. A negated formula can be expressed positively via a negation normal form transformation and subsequent positive rewriting of negated atomic formulae. Furthermore, we consider various extensions of the first-order language of real arithmetic. For a collection of relation and function symbols \(\mathcal{C}\), we write \(\operatorname{FO}(\mathcal{C})\) to denote the variant of \(\operatorname{FO}(+,\times,<,=,0,1)\) that uses only function symbols and relation symbols in \(\mathcal{C}\). _Existential real arithmetic_\(\exists\operatorname{FO}(+,\times,<,=,0,1)\) is obtained from (1) by dropping universal quantification. The logic \(\exists\operatorname{FO}(\mathcal{C})\) is defined analogously. A formula \(\phi\) is _open_ if some variable appears free in \(\phi\), and otherwise _closed_. Closed formulae are referred to as _sentences_. Given a first-order structure \(\mathfrak{A}\) and a variable assignment \(s\), we write \(\mathfrak{A}\models_{s}\phi\) in the case that \(\phi\) is true in \(\mathfrak{A}\) with respect to \(s\). If \(\phi\) is a sentence, we write \(\mathfrak{A}\models\phi\) if \(\phi\) is true in \(\mathfrak{A}\). The semantics for the language of real arithmetic is defined over the fixed structure \((\mathbb{R},+,\times,<,=,0,1)\) of real arithmetic in the usual way, and similarly for \(\operatorname{FO}(\mathcal{C})\) where the symbols in \(\mathcal{C}\) have their usual interpretations. As a slight abuse of notation, we use \(f\) to denote both a real-valued function and the corresponding function symbol. Moreover, we allow function symbols to be interpreted as partial functions. Any atomic formula with some undefined term with respect to an assignment \(s\) is defined to be false. We use shorthands \(\mathbb{R}\) and \(\mathbb{R}^{<}\) for the models \((\mathbb{R},+,\times,<,=,0,1)\) and \((\mathbb{R},+,\times,<,0,1)\), respectively. For a collection \(\tau\) of additional functions, we write \(\mathbb{R}_{\tau}\) and \(\mathbb{R}_{\tau}^{<}\) for the corresponding extension of the models \(\mathbb{R}\) and \(\mathbb{R}^{<}\), respectively. We define the complexity class \(\exists\mathbb{R}_{\tau}\) as the collection of decision problems that have a polynomial-time many-one reduction to closed formulae of the existential real arithmetic with additional functions from \(\tau\). We also consider a subclass of \(\exists\mathbb{R}_{\tau}\) defined in terms of strict inequalities: the class \(\exists\mathbb{R}_{\tau}^{<}\) is defined otherwise as \(\exists\mathbb{R}_{\tau}\), except that we drop equality atoms \(i=i\) from (1). ## III The Existential Theory of the Reals in the Arithmetical Hierarchy The full first-order theory of the ordered field of the real numbers admits an efficient version of quantifier elimination and thus is decidable, a result first shown by Alfred Tarski. Furthermore, the satisfiability problem of the existential fragment of this theory is known to be in \(\mathsf{PSPACE}\)[8]. In general, though, it is not known if the corresponding existential theory is decidable when new function symbols are added to the underlying model. The addition of the sine function is known to lead to undecidability, whereas Tarski's exponential function problem has been famously open since the 1950s. In this section we show that if the added functions are assumed to satisfy certain fairly general computable topological properties, the satisfiability problem of the resulting existential theories can be bounded from above using low levels of the arithmetical hierarchy. Specifically, to this end, we use the following definition of effectively continuous functions from [10]. **Definition 1** ([10, Definition 4.2.1]).: _A function \(f\colon\mathbb{R}^{n}\to\mathbb{R}\) is called effectively continuous if there exists a computable function \(g\) with the following properties:_ * _To each_ \(n\)_-tuple of open intervals_ \((a_{1},b_{1})\)_,_ \(\ldots\)_,_ \((a_{n},b_{n})\) _with rational endpoints, the function_ \(g\) _associates an open interval_ \((c,d)\) _with rational endpoints such that_ \[\forall x\left(x\in(a_{1},b_{1})\times\cdots\times(a_{n},b_{n})\implies f(x) \in(c,d)\right).\] * \(\forall M>0\ \forall\varepsilon>0\ \exists\delta>0\ \forall a_{i},b_{i}\) _it holds that, if_ \(c,d\) _is the output of_ \(g\) _on input_ \(a_{i},b_{i}\)_, then_ \[\bigwedge_{i\in[n]}(a_{i},b_{i})\subseteq[-M,M]\wedge|a_{i}-b_{i}|<\delta\implies |c-d|<\varepsilon.\] _In this case, it is said that \(g\) computes the function \(f\). In addition, the set of all effectively continuous functions is denoted by \(\mathrm{ECF}\)._ As noted in [10], there is at most one effectively continuous function for each computable function. Thus the set \(\mathrm{ECF}\) is countable, and not every constant function is effectively continuous. On the other hand, rational constant functions, the identity function \(x\mapsto x\), the absolute value function \(x\mapsto|x|\), together with addition, multiplication, division, and the exponential function and basic trigonometric functions are effectively continuous. Using these functions and the following lemma, all rational functions and many neural activation functions, such as the ReLU function and the sigmoid function \(\sigma\colon x\mapsto 1/(1+\exp(-x))\), can be seen to be in \(\mathrm{ECF}\). **Lemma 2** ([10, Lemma 4.2.6]).: _The set \(\mathrm{ECF}\) of all effectively continuous functions is effectively closed under composition, i.e., given computable functions \(g\) and \(g^{\prime}\) which compute two effectively continuous functions \(f\) and \(f^{\prime}\), respectively, we can effectively find a computable function \(g^{\prime\prime}\) which computes the composition \(f\circ f^{\prime}\) (when the latter is defined)._ The following two lemmas state some basic topological properties of effectively continuous functions that are central in our approach. **Lemma 3** ([10, Remark 4.2.2 (rephrased)]).: _Effectively continuous functions are uniformly continuous on every compact cube of the form \([-M,M]^{n}\), where \(M>0\). In particular, effectively continuous functions are continuous in the Euclidean topology._ **Lemma 4** ([10, Proposition 4.2.10 (rephrased)]).: _Let \(T\) be a set of effectively continuous functions. Then the set_ \[\{(g,\bar{x}):\ \bar{x}\in\mathbb{Q}^{n},\ g\in T\text{ and }g(\bar{x})<0\}\] _is recursively enumerable relatively to \(T\), i.e., there is an algorithm which, on input \(\bar{x}\in\mathbb{Q}^{n}\), and a code for \(g\in T\), stops if and only if \(g(\bar{x})<0\)._ This lemma implies that the set of rational solutions \(\bar{x}\in\mathbb{Q}^{n}\) for \(f(\bar{x})<0\) is recursively enumerable when \(f\) is effectively continuous. We utilise some rudimentary notions and knowledge from point-set topology summarised in the following lemma (for basics of point-set topology see, e.g., the monograph [14]). In order to simplify the notation, for a topological space \(X\), we use \(X\) to denote also the underlying set of the space. A set \(D\subseteq A\) is said to be a _dense subset of \(A\)_ (in some topology) if the set \(D\) intersects every non-empty open subset of \(A\). A topological space \(X\) is _compact_ (more specifically, \(\omega\)-compact) if every countable collection \(E\) of open subsets of \(X\) such that \(X\subseteq\bigcup E\) has a finite subset \(F\subseteq D\) so that the condition \(X\subseteq\bigcup F\) holds. **Lemma 5** (Topology toolbox).: _Let \(X\) and \(Y\) be topological spaces, \(f\colon X\to Y\) a continuous function, \(S\) a set in \(X\), \(A\) and \(B\) open sets in \(X\), and \(C\) an open set in \(Y\). Then the following claims hold._ * _The subsets_ \(A\cap B\)_,_ \(A\cup B\)_, and_ \(f^{-1}[C]\) _are open in_ \(X\)_._ * _The product_ \(A^{k}\) _is open in the product space_ \(X^{k}\)_._ * _If_ \(D\) _is a dense subset of_ \(S\) _then_ \(D^{k}\) _is a dense subset of_ \(S^{k}\) _in the corresponding product topology._ * _If_ \(S^{k}\) _is open in_ \(X^{k}\)_, then any projection of_ \(S^{k}\) _is open in the corresponding product space_ \(X^{n}\)_._ * _The product topology of compact spaces is compact._ * _If_ \(X\) _is a compact metric space, then_ \(X\) _is sequentially compact, that is, if_ \((x_{i})_{i\in\mathbb{N}}\)_, is a sequence of elements of_ \(X\)_, then there is a converging subsequence of_ \((x_{i})_{i\in\mathbb{N}}\)_._ The following lemma is an easy consequence of the previous topological facts. **Lemma 6**.: _Let \(\mathfrak{A}\) be a model with a vocabulary \(\tau\), and \(\mathcal{T}\) a topology of the universe \(A\) of \(\mathfrak{A}\) such that_ * _for every_ \(n\)_-ary relation symbol_ \(R\) _in_ \(\tau\)_, the interpretation_ \(R^{\mathfrak{A}}\) _is an open set in the corresponding product topology of_ \(A^{n}\) _obtained from_ \(\mathcal{T}\)_, and_ * _for every_ \(n\)_-ary function symbol_ \(f\) _in_ \(\tau\)_, the interpretation_ \(f^{\mathfrak{A}}\) _is continuous with respect to the product topology of_ \(A^{n}\) _obtained from_ \(\mathcal{T}\)_._ _Let \(\phi(\bar{x})\in\exists\mathrm{FO}(\tau)\) be a formula with free variables in the \(n\)-tuple \(\bar{x}\). Then the set of \(n\)-tuples \(\bar{a}\) satisfying \(\phi(\bar{a})\) in \(\mathfrak{A}\) is an open set in the product topology of \(A^{n}\) based on \(\mathcal{T}\)._ Proof.: The proof proceeds by induction; we utilise topological facts from Lemma 5. First note that the interpretations of terms are continuous functions, since by induction they can be computed by composing continuous functions. The interpretations of atomic formulae are open, for pre-images of open sets of continuous functions are open. Finally, if the interpretation of \(\phi\) and \(\psi\) are open, the interpretations of \(\phi\wedge\psi\) and \(\phi\vee\psi\) are open, for the intersections and unions of open sets are open, and the interpretation of \(\exists x\phi\) is open, for projections of open sets are open. **Lemma 7**.: _Let \(\mathfrak{A}\), \(\tau\) and \(\mathcal{T}\) be as in the previous lemma. Let \(D\) be a dense subset of the universe \(A\) in the topology \(\mathcal{T}\), and let \(\phi(\bar{x})\in\exists\mathrm{FO}(\tau)\) be a formula with free variables in \(\bar{x}\). Then \(\phi\) is satisfiable in \(\mathfrak{A}\) if and only if \(\phi(\bar{a})\) is true in \(\mathfrak{A}\) for some tuple \(\bar{a}\) from the dense set \(D\)._ Proof.: The \(\Leftarrow\) direction is immediate. For the converse, let \(\phi\) be an \(\exists\mathrm{FO}(\tau)\) formula with \(k\) free variables that is satisfied in \(\mathfrak{A}\). By Lemma 6, \(\phi\) defines an open set in \(A^{k}\). Note that, since \(D\) is a dense subset of \(A\) in the topology \(\mathcal{T}\), \(D^{k}\) is a dense subset of \(A^{k}\) in the corresponding product topology. Now by the definition of denseness, the intersection of \(D^{k}\) and the set defined by \(\phi\) is non-empty, and thus \(\phi(\bar{a})\) is true in \(\mathfrak{A}\) for some tuple \(\bar{a}\in D^{k}\). By the density of rational numbers, we can now obtain an upper bound for the satisfiability problem of formulae when function symbols are interpreted using effectively continuous functions. First, if the equality sign is not allowed in the formulae, the remaining strict order relation corresponds to open sets in the Euclidean topology. **Theorem 8**.: _Let \(\phi(\bar{x})\) be an existential formula without identity over the structure \(\mathbb{R}_{\mathrm{ECF}}\). Then the set of rational solutions \(\bar{a}\in\mathbb{Q}^{n}\) for \(\mathbb{R}_{\mathrm{ECF}}\models\phi(\bar{a})\) is recursively enumerable. Moreover, the complexity class \(\exists\mathbb{R}^{<}_{\mathrm{ECF}}\) is contained in \(\Sigma^{0}_{1}\)._ Proof.: The proof proceeds by induction of the structure of \(\exists\mathrm{FO}(\{<\}\cup\mathrm{ECF})\)-formulae. First note that each atomic formula can be equivalently expressed by an inequality of the form \(f(\bar{y})<0\) for some effectively continuous function \(f\) and tuple of variables \(\bar{y}\). Thus, by Lemma 4, rational solution sets for atomic formulae are recursively enumerable. The cases for conjunction and disjunction are immediate, for finite intersections and unions of recursively enumerable sets are recursively enumerable. Finally, consider the case for \(\exists y\psi(\bar{x},y)\). By the induction hypothesis, the rational truth set of \(\psi(\bar{x},y)\) is recursively enumerable; we claim that its projection \(P\) to the variables in \(\bar{x}\) is the recursively enumerable rational truth set of \(\exists y\psi(\bar{x},y)\). Note first that projections of recursively enumerable sets are recursively enumerable, and thus it suffices to show that \(P\) is the rational truth set of \(\exists y\psi(\bar{x},y)\). Assume that \(\phi(\bar{a},b)\), where \(\bar{a}\) is a tuple of rational numbers and \(b\) is a real number, is true in \(\mathbb{R}^{<}_{\mathrm{ECF}}\). Now since, by Lemma 6, the truth set of \(\phi(\bar{x},y)\) is open, there exists a rational number \(c\) such that \(\phi(\bar{a},c)\) is true in \(\mathbb{R}^{<}_{\mathrm{ECF}}\), from which the claim follows. Now \(\exists\mathbb{R}^{<}_{\mathrm{ECF}}\) is in \(\Sigma^{0}_{1}\), since by Lemma 7, non-emptiness of truth sets of \(\exists\mathrm{FO}(\{<\}\cup\mathrm{ECF})\)-formulae are equivalent to checking non-emptiness of their rational truth sets, and \(\Sigma^{0}_{1}\) is clearly closed under polynomial-time reductions. In the following, a \(\tau\)_-polynomial_ is a \(\tau\)-term where, except for the arithmetic operations \(+\) and \(\times\), functions \(g\) can only appear with variable or constant arguments, that is, in the form \(g(x)\) or \(g(c)\). Furthermore, the (total) degree of a polynomial \(P\) is defined as the maximum over the sum of the variable exponents in each monomial term occurring in \(P\). Note that the minus sign can be avoided by shuffling monomial terms from one side of the equations and inequations to the other. **Lemma 9**.: _Let \(\tau\) be a set of function symbols and \(\phi(\bar{x})\in\exists\mathrm{FO}(\{+,\times,<,=,0,1\}\cup\tau)\). Then we can construct in polynomial time with respect to the length of the formula \(\phi(\bar{x})\) a \(\tau\)-polynomial \(P(\bar{x},\bar{y})\) of degree at most \(4\) such that \(\phi(\bar{x})\) is equivalent to_ \[\exists\bar{y}P(\bar{x},\bar{y})=0\] _over the expanded reals \(\mathbb{R}_{\tau}\)._ Proof.: The proof of this lemma is analogous to the proof of [4, Lemma 3.2]. In fact, it suffices to first simplify all subterms of \(\phi\) of the form \(g(t)\) to the required form using new variables: replace \(g(t)\) by \(g(y)\) and add a new conjunct \(y=t\). Then the translation in [4] can be used directly by treating terms \(g(y)\) exactly the same way as in the original proof. Analogously to the \(\exists\mathbb{R}\)-complete decision problem \(4\)-\(\mathrm{FEAS}\) in [4], we define \(4\)-\(\mathrm{FEAS}_{\tau}\) to be the decision problem that asks, given a \(\tau\)-polynomial of degree at most \(4\), if the polynomial is feasible, i.e., has a root in the extended model \(\mathbb{R}_{\tau}\). Using the previous lemma, we obtain a complete problem for the corresponding extension of \(\exists\mathbb{R}\) with the functions in \(\tau\), thus justifying the use of the notation \(\exists\mathbb{R}_{\tau}\). **Corollary 10**.: \(4\)_-\(\mathrm{FEAS}_{\tau}\) is \(\exists\mathbb{R}_{\tau}\)-complete._ Note that for product spaces of the form \(\mathbb{R}^{n}\), the standard Euclidean topology coincides with the product topology and is sequentially compact. With the help of Lemma 9, we can now give an upper bound for complexity class of the existential theory of the reals extended with effectively continuous functions. **Theorem 11**.: \(\exists\mathbb{R}_{\mathrm{ECF}}\) _is contained in \(\Sigma^{0}_{3}\)._ Proof.: Let \(\phi\) be an existential sentence over \(\mathbb{R}_{\mathrm{ECF}}\). By Lemma 9, we may assume that \(\phi\) is of the form \(\exists\bar{x}P_{\tau}(\bar{x})=0\), where \(P_{\tau}\) is a \(\tau\)-polynomial over a vocabulary \(\tau\) that contains function symbols for the effectively continuous functions. By Lemmas 2 and 3, the function defined by \(P_{\tau}\) is effectively continuous. We observe that \(\exists\bar{x}P_{\tau}(\bar{x})=0\) is equivalent over \(\mathbb{R}_{\mathrm{ECF}}\) to the expression \[\exists d>0\ \forall\varepsilon>0\ \exists\bar{x}\in B(\bar{0},d):|P_{\tau}( \bar{x})|<\varepsilon. \tag{2}\] For this claim, \(\exists\bar{x}P_{\tau}(\bar{x})=0\) clearly implies (2). For the converse direction, (2) entails that there is an infinite sequence of tuples \((\bar{x}_{i})_{i\in\mathbb{N}}\) inside some open ball \(B(\bar{0},d)\) such that \(\lim_{i\to\infty}P_{\tau}(\bar{x}_{i})=0\). Since the closure \(\bar{B}(\bar{0},d)\) is compact, the sequence \((\bar{x}_{i})_{i\in\mathbb{N}}\) has a subsequence \((\bar{y}_{j})_{j\in\mathbb{N}}\) that converges to a limit point \(y\in\bar{B}(\bar{0},d)\). Since \(P_{\tau}\) is continuous, and \(\lim_{j\to\infty}P_{\tau}(\bar{y}_{j})=0\), we obtain that \(P_{\tau}(\bar{y})=0\) and, in particular, that the claim \(\exists\bar{x}P_{\tau}(\bar{x})=0\) holds. The parameters \(\varepsilon\) and \(d\) can without loss of generality be assumed to be rational in (2). The innermost existentially quantified part of (2) then describes a predicate that is definable by an existential formula with \(\varepsilon\) and \(d\) as rational constant parameters over \(\mathbb{R}^{<}_{\mathrm{ECF}}\) and thus is in \(\Sigma^{0}_{1}\) by Theorem 8. The full expression (2) hence defines a \(\Sigma^{0}_{3}\) predicate. Since \(\exists\mathbb{R}_{\mathrm{ECF}}\) is defined as the class of problems that can be reduced in polynomial time to sentences of the form of \(\phi\), we conclude that \(\exists\mathbb{R}_{\mathrm{ECF}}\) is contained in \(\Sigma^{0}_{3}\). Now the following results are corollaries of the preceding theorems. **Theorem 12**.: \(\exists\mathbb{R}^{<}_{\mathrm{exp}}\subseteq\Sigma^{0}_{1}\) _and \(\exists\mathbb{R}_{\mathrm{exp}}\subseteq\Sigma^{0}_{3}\)._ In fact, by the model completeness of the first-order theory of \(\mathbb{R}_{\mathrm{exp}}\) (see [9, 10]), the decidability of its existential fragment is equivalent to it being recursively enumerable, and also equivalent to the full first-order theory of \(\mathbb{R}_{\mathrm{exp}}\) being decidable. Thus, the precise relationship of \(\exists\mathbb{R}_{\mathrm{exp}}\) to \(\Sigma^{0}_{1}\) and \(\Sigma^{0}_{3}\) is an open problem. These observations can be generalized to any \(\mathbb{R}_{\tau}\) with a model-complete first-order theory and to any set \(\tau\) of effectively continuous functions. Below, for convenience of stating the theorem, we assume below that \(\exists\mathbb{R}_{\sin}\) and \(\exists\mathbb{R}_{\sin}^{<}\) are closed under computable reductions. **Theorem 13**.: \(\Sigma_{1}^{0}\subseteq\exists\mathbb{R}_{\sin}\subseteq\Sigma_{3}^{0}\) _and \(\exists\mathbb{R}_{\sin}^{<}=\Sigma_{1}^{0}\)._ Proof.: Note that the formula \(\sin(y)=0\wedge 4<y\wedge y<7\) defines \(2\pi\) in \(y\), and that the formula \[\sin(2\pi\times x)=0\wedge(x=0\lor x>0)\] defines natural numbers over the reals, with the help of the previously defined \(2\pi\). Hence \(\Sigma_{1}^{0}\)-hardness follows from the Davis-Putnam-Robinson-Matiyasevich theorem. For the second item, hardness follows from the results of [15]. ## IV The Neural Network Training Problem Under a suitable formulation, the complexity of the neural network training problem is complete for the complexity class \(\exists\mathbb{R}_{\tau}\), where the set \(\tau\) includes all those unary real-valued functions that are being used for neural activation. In the case of effectively continuous activation functions, the complexity of the training problem can be bounded using low levels of the arithmetical hierarchy. We concentrate on _feedforward neural networks_ under the following definitions. **Definition 14**.: _A neural network architecture is a pair \(N=(G,\varphi)\) over a finite directed acyclic graph \(G=(V,E)\) and a function \(\varphi\) with the following definitions and properties:_ * _The vertices of the graph are called_ neurons_. A neuron of the network architecture_ \(N\) _is called an_ input neuron _if there are no incoming edges to it. A neuron is an_ output neuron _if there are no outgoing edges from it. Every other vertex of the graph is called a_ hidden neuron_._ * _The function_ \(\varphi\) _maps each non-input neuron_ \(v\) _to a function_ \(\varphi(v)\colon\mathbb{R}\to\mathbb{R}\)_. The function_ \(\varphi(v)\) _is the_ activation function _of the neuron_ \(v\)_. The value_ \(\varphi(v)\) _is alternatively denoted by_ \(\varphi_{v}\)_._ **Definition 15**.: _A neural network is a triple \(\mathcal{N}=(N,w,b)\) over a neural network architecture \(N\) together with real-valued functions \(w\) and \(b\) with the following properties:_ * _The function_ \(w\) _maps each edge_ \(e\) _of the underlying graph to a real number. The value_ \(w(e)\) _is the_ edge weight _of_ \(e\) _in the neural network and is denoted by_ \(w_{e}\)_._ * _The function_ \(b\) _maps each non-input neuron_ \(v\) _to a real number, called the_ bias _of_ \(v\)_, and denoted in short by_ \(b_{v}\)_._ **Definition 16**.: _A data point for a neural network architecture \(N\) is a function \(d\) that maps a real number to each input neuron and to each output neuron._ **Definition 17**.: _Let \(\mathcal{N}=(N,w,b)\) be a neural network. The neural function of \(\mathcal{N}\) is the unique function \(g\) with the following definitions and properties:_ * _The domain of_ \(g\) _is the set of all possible data points for the network architecture_ \(N\)_. For each data point_ \(d\)_, the value_ \(g(d)\) _is a function mapping each neuron to a real number, called the_ neural value _computed by the network for the given neuron. This function is also referred to as_ \(g_{d}\)_._ * _For each data point_ \(d\in\mathrm{dom}(g)\) _and for each input neuron_ \(v\) _it holds that_ \(g_{d}(v)=d(v)\)_._ * _For each_ \(x\in\mathrm{dom}(g)\) _and for each neuron_ \(v\in V\) _that is not an input neuron it holds that_ \[g_{d}(v)=\varphi_{v}\left(b_{v}+\sum_{u\in P}\left(w_{(u,v)}\times g_{d}(u) \right)\right),\] (3) _where_ \(P\) _is the set of predecessors of_ \(v\) _in the underlying directed acyclic graph._ In other words, the neural function for a fixed data point \(d\) is defined recursively as follows: For each input neuron \(v\), the value given by the neural function for \(v\) is the value \(d(v)\) as given by the data point. For every other neuron \(v\), the neural value \(g_{d}(v)\) is computed by adding the bias value \(b_{v}\) to the sum of the incoming neural values, each multiplied by the corresponding edge weight, and finally this sum is mapped through the activation function \(\varphi_{v}\). The neural function is well-defined, since the network architecture is specifically assumed to be acyclic. In the following definition, to simplify notation, we denote by \(d_{O}\) the tuple consisting of the values of a data point \(d\) for the output neurons of the network architecture, where some fixed order on the output neurons independent of the data points is assumed. **Definition 18**.: _Let \(\tau\) be a set of unary functions. An \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}\) instance is a tuple of the form \((N,A_{E},A_{V},D,c,\prec,\delta)\) for a neural network architecture \(N=(G,\varphi)\) with the following properties:_ * _For each neuron_ \(v\) _of the network architecture_ \(N\)_, the activation function_ \(\varphi_{v}\) _is either the identity function_ \(x\mapsto x\) _or some function_ \(f\in\tau\)_._ * _A subset_ \(A_{E}\) _of the edges of_ \(N\) _are marked as_ active edges _in the training process. Similarly,_ \(A_{V}\) _is a subset of_ active neurons_._ * _A finite set_ \(D\) _of data points that maps neurons to rational numbers._ * \(A\) cost function__\(c\colon\mathbb{R}^{2m}\to\mathbb{R}\)_, where_ \(m\) _is the number of output neurons of_ \(N\)_, is assumed to be definable with an arithmetic expression._ * _The symbol_ \(\prec\) _is one the of relation symbols in the set_ \(\{=,\leq,<\}\)_._ * \(A\) threshold _value_ \(\delta\) _for allowed total training error is given as a rational number._ _A pair \((w,b)\) is a satisfying solution for the training instance \((N,A_{E},A_{V},D,c,\prec,\delta)\), if \((N,w,b)\) is a neural network as in Definition 15 so that for each edge \(e\) of \(G\) not in \(A_{E}\) it holds that \(w(e)=1\) and for each neuron \(v\) not in \(A_{V}\), \(b(v)=0\), and that the neural function \(g\) satisfies the condition_ \[\sum_{d\in D}c\left((g_{d})_{O},d_{O}\right)\prec\delta. \tag{4}\] _Then \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}\) is the decision problem that asks, given an \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}\) instance, if there exists some satisfying solution for it. Furthermore, \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}^{<}\) is defined otherwise as the decision problem \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}\), except that the strict order relation \(<\) is the only allowed choice for the relation symbol \(\prec\). Furthermore, for a single function \(f\), we use the notation \(\mathrm{NN}_{\mathrm{f}}\mathrm{-TRAINING}\) for \(\mathrm{NN}_{\{\mathrm{f}}}\mathrm{-TRAINING}\), and similarly for \(\mathrm{NN}_{\mathrm{f}}\mathrm{-TRAINING}^{<}\)._ If \(c\) is such a cost function that for all \(m\)-tuples \(\bar{a}\) and \(\bar{b}\) it holds that \(c(\bar{a},\bar{b})=0\) if and only if \(\bar{a}=\bar{b}\), then it is called _faithful_. If \(c\) is both faithful and non-negative, threshold value \(\delta=0\) is used, and \(\prec\) is replaced with the equality sign, then 4 is equivalent to all data points \(d\in D\) satisfying the condition \((g_{d})_{O}=d_{O}\), that is, \(g_{d}(v)=d(v)\) for every output neuron of the network. **Lemma 19**.: _For any set \(\tau\) of unary real-valued functions, the problem \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}^{<}\) is in the complexity class \(\exists\mathbb{R}_{\tau\cup\{-,\dot{\tau}\}}^{<}\)._ Proof.: Let \((N,A_{E},A_{V},D,c,\prec,\delta)\) be an \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}\) instance. We show how to construct a formula \(\phi(\bar{w},\bar{b})\) of \(\exists\mathrm{FO}(\{+,-,\times,\dot{\div},<,0,1\}\cup\tau)\) in polynomial time such that there exists some satisfying solution for the given instance of the training problem if and only if \(\mathbb{R}_{\tau}\models\exists\bar{w}\,\exists\bar{b}\,\phi(\bar{w},\bar{b})\), where \(\bar{w}\) and \(\bar{b}\) are finite sequences of variables that in some fixed order encode the weights and biases for the active edges and active neurons, respectively. We use \(g\) to denote the intended neural function for the variables in \(\bar{w}\) and \(\bar{b}\). Let \(m\) be the number of output neurons of \(N\). First we show, that for each data point \(d\in D\) and for each neuron \(v\) of the network, there is a term \(t_{(d,v)}\) which evaluates to \(g_{d}(v)\) over \(\mathbb{R}_{\tau}\). Namely, if \(v\) is an input neuron, we can express \(t_{(d,v)}\) succinctly as the corresponding input value given by \(d\), for instance, in the form of a fraction of two binary expansions of integral values. If \(v\) is a non-input neuron, a suitable \(t_{(d,v)}\) can be obtained as in expression 3 of Definition 17 using the terms \(t_{(d,u)}\) of the predecessors \(u\) of \(v\) and the sets \(A_{E}\) and \(A_{V}\). Note that the underlying graph structure is given as a part of the input, and that the graph is assumed to be acyclic. According to Definition 18, the cost function \(c\) is expressible as an arithmetic expression. Then, for each \(d\in D\), there is some term \(t^{\prime}_{d}\) that evaluates to \(c((g_{d})_{O},d_{O})\) over \(\mathbb{R}_{\tau}\). Furthermore, the given rational threshold value \(\delta\) can be expressed by some constant term \(t_{\delta}^{\prime\prime}\) Now, the relational formula 4 of Definition 18 is expressible as \(\sum_{d\in D}t_{d}^{\prime}<t_{\delta}^{\prime\prime}\), thus yielding the claimed formula \(\phi(\bar{w},\bar{b})\). Note that in the previous proof, \(\phi(\bar{w},\bar{b})\) is a single quantifier-free relational atom. It also defines the set of all satisfying solutions for the given training instance as a subset of \(\mathbb{R}^{|A_{E}|+|A_{V}|}\). If all the functions in \(\tau\) are effectively continuous, this solution set is open in the Euclidean topology by Lemma 6, and its intersection with \(\mathbb{Q}^{|A_{E}|+|A_{V}|}\) is recursively enumerable by Theorem 8. What is more, if the complete first-order theory of the model \(\mathbb{R}_{\tau}\) is _o-minimal_ (see, e.g., [10] for definition and discussion), then the set of satisfying solutions has only a finite number of connected components. In particular, the model \(\mathbb{R}_{\mathrm{exp}}\) is known to be o-minimal, whereas \(\mathbb{R}_{\mathrm{sin}}\) is not o-minimal. However, for example in the case of the sigmoid activation function, it is an open problem whether any positive lower bounds for the radii of open neighbourhoods for solutions in the open solution set can be computed, in general. By the model completeness of \(\mathbb{R}_{\mathrm{exp}}\), this question is connected to Tarski's exponential function problem via the so-called _first root conjecture_ (see, e.g., [9, 10]). **Lemma 20**.: _For any set \(\tau\) of unary real-valued functions, the problem \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}\) is in \(\exists\mathbb{R}_{\tau}\)._ Proof.: Let \((N,A_{E},A_{V},D,c,\prec,\delta)\) be an \(\mathrm{NN}_{\tau}\mathrm{-TRAINING}\) instance and let \(\phi(\bar{w},\bar{b})\) be as in the proof of Lemma 19. It is enough to show that there is some formula \(\phi^{\prime}(\bar{w},\bar{b})\) of \(\exists\mathrm{FO}(\{+,\times,<,=,0,1\}\cup\tau)\) that is equivalent to \(\phi(\bar{w},\bar{b})\) over the structure \(\mathbb{R}_{\tau\cup\{-,\div\}}\). For this, note that if \(\theta(x)\) is a formula with some open variable \(x\), then formulae of the form \(\theta(-y)\) and \(\theta(y/z)\) can be defined existentially as \(\exists x(\theta(x)\wedge x+y=0)\) and \(\exists x(\theta(x)\wedge x\times z=y)\). Repeating these steps, the function symbols \(-\) and \(\div\) can be eliminated from \(\phi(\bar{w},\bar{b})\). Notice that the proof of Lemma 20 and the membership of the training problem in the class \(\exists\mathbb{R}_{\tau}\) can be generalized to the case where all of the data points, activation functions, threshold value and cost function are definable using existential formulae of the alphabet \(\{+,\times,<,=,0,1\}\cup\tau\). The set \(\tau\) may also include other than unary functions. Next we define a decision problem for existential formulae in a certain normal form. The definition is an extension of the problem called ETR-INV in [5], now allowing the use of unary function symbols. **Definition 21**.: _Let \(\tau\) be a set of unary real-valued functions. Then \(\mathrm{ETR}_{\tau}\mathrm{-INV}\mathrm{-FLAT}\) is the following decision problem: Given a finite set \(\mathcal{C}\) of constraints, each of one of the forms_ \[x=1,\quad x+y+z=0,\quad x\times y+1=0,\quad x+f(y)=0, \tag{5}\] _where \(x\), \(y\) and \(z\) are first-order variable symbols and \(f\) is some function symbol in \(\tau\), determine whether the system of constraints of \(\mathcal{C}\) is satisfiable over \(\mathbb{R}_{\tau}\) using a single variable assignment._ The constraint types of 5 are called _unit_ constraints, _addition_ constraints, _inversion_ constraints and _function_ constraints, respectively. **Lemma 22**.: _The problem \(\mathrm{ETR}_{\tau}\mathrm{-INV}\mathrm{-FLAT}\) is \(\exists\mathbb{R}_{\tau}\)-complete._ Proof.: We show that the satisfiability problem of the existential theory of the structure \(\mathbb{R}_{\tau}\) is reducible in polynomial time to \(\mathrm{ETR}_{\tau}\mathrm{-INV}\mathrm{-FLAT}\); the opposite direction is clear. Let \(\phi\) be a sentence of the logic \(\exists\mathrm{FO}(\{+,\times,<,=,0,1\}\cup\tau)\). Simplifying all functional subterms as in the proof of Lemma 9 and proceeding as in the proof of Theorem 16 of [5], the satisfiability of \(\phi\) can be reduced in polynomial time to a finite set \(\mathcal{C}^{\prime}\) of constraints of the following forms: \[x=1,\quad x+y=z,\quad x\times y=1,\quad x=f(y).\] For every choice of first-order variables \(x\), \(y\) and \(z\), the following observation is true for every variable assignment \(s\): \[\mathbb{R}_{\tau}\models_{s}x+y=z\iff\mathbb{R}_{\tau}\models_{s}\exists u \exists v(v+v+v=0\wedge z+u+v=0\wedge x+y+u=0).\] Similarly, for monomial terms \(t\) and \(t^{\prime}\), it holds that \[\mathbb{R}_{\tau}\models_{s}t=t^{\prime}\iff\mathbb{R}_{\tau}\models_{s}\exists u \exists v(v+v+v=0\wedge t+u+v=0\wedge t^{\prime}+u+v=0).\] In particular, each of the constraints in \(\mathcal{C}^{\prime}\) can be expressed equivalently using at most a constant number of \(\mathrm{ETR}_{\tau}\)-\(\mathrm{INV}\)-\(\mathrm{FLAT}\) constraints, producing an equivalent system of constraints. Depending on the functions in the set \(\tau\), some of the constraints in Definition 21 can be left out without losing \(\exists\mathbb{R}_{\tau}\)-completeness. For instance, the exponential function can be used in order to switch between addition and multiplication in existential formulae. The proof of the following theorem is based on the neural network construction of [2], in which it was used to obtain the first known version of an \(\exists\mathbb{R}\)-complete NN training problem. **Theorem 23**.: _Let \(\tau\) be a set of unary real-valued functions. Then the neural network training problem \(\mathrm{NN}_{\tau}\)-\(\mathrm{TRAINING}\) is \(\exists\mathbb{R}_{\tau}\)-complete._ Proof.: By Lemmas 20 and 22 it is enough to show that the problem \(\mathrm{ETR}_{\tau}\)-\(\mathrm{INV}\)-\(\mathrm{FLAT}\) has a polynomial-time reduction to \(\mathrm{NN}_{\tau}\)-\(\mathrm{TRAINING}\). To this end, let \(\mathcal{C}\) be a finite set of \(\mathrm{ETR}_{\tau}\)-\(\mathrm{INV}\)-\(\mathrm{FLAT}\) constraints. We may assume that \(\mathcal{C}\) does not include unsatisfiable constraints of the form \(x\times x+1=0\). Let \(W\) be the set of all variable symbols that appear in any of the constraints of \(\mathcal{C}\). Next, we describe how to construct an \(\mathrm{NN}_{\tau}\)-\(\mathrm{TRAINING}\) instance \((N,A_{E},A_{V},D,c,\prec,\delta)\) in polynomial time so that this instance has a satisfying solution if and only if the system \(\mathcal{C}\) of constraints is satisfiable. First, let \((A_{V},\prec,\delta):=(\varnothing,=,0)\). In particular, biases are assumed to be \(0\) for all neurons. Let \(c\) be any faithful and non-negative cost function. In the sequel, we will refer to the variables of individual constraints also using indices in the set \(\{1,2,3\}\) according to the list \[x_{1}=1,\quad x_{1}+x_{2}+x_{3}=0,\quad x_{1}\times x_{2}+1=0,\quad x_{1}+f(x_ {2})=0. \tag{6}\] Notice that these indices are based on the positions of the variables in the constraints in such a manner that, for example, in a constraint of the form \(x+x+y=0\), indices \(1\) and \(2\) would refer to \(x\) and \(3\) to \(y\). For each \(C\in\mathcal{C}\), let \(l_{C}\) be the appropriate number of these indices for \(C\). We define the underlying graph \(G\) of the network architecture \(N=(G,\varphi)\), case by case, based on the sets \(W\) and \(\mathcal{C}\) of variables and constraints. The resulting substructure of the network for each constraint type is depicted in Figure 1. * For each variable symbol \(x\in W\), there is a unique input neuron \(i_{x}\) and an edge to an immediate successor \(j_{x}\). The intended meaning of these two neurons is to encode the value of the variable \(x\) into the edge weight of \((i_{x},j_{x})\). The number of neurons introduced in this step is \(2|W|\). * For each constraint \(C\in\mathcal{C}\), an output neuron \(o_{C}\) is inserted. In addition, there are unique hidden neurons \(h_{(C,k)}\) and \(q_{(C,k)}\), and a unique input neuron \(p_{(C,k)}\) for each \(k\in\{1,\ldots,l_{C}\}\), and they are incident to the edges of the network as follows: \[(j_{x_{k}},h_{(C,k)}),\quad(h_{(C,k)},o_{C}),\quad(p_{(C,k)},q_{(C,k)})\quad \text{and}\quad(q_{(C,k)},h_{(C,k)}).\] In total, there are at most \(10|\mathcal{C}|\) new neurons introduced in this case. Here, the neurons \(p_{(C,k)}\) and \(q_{(C,k)}\) are intended to cancel out the output value of the neuron \(h_{(C,k)}\) for those data points that in the construction are not intended to directly concern the constraint \(C\) but that still give a non-zero value for the input neuron \(i_{x_{k}}\). * For each constraint of the form \(x\times y+1=0\), an additional input neuron \(e_{C}\) is added and connected with an edge \((e_{C},j_{y})\) to the neuron \(j_{y}\). For this, at most \(|\mathcal{C}|\) new neurons are introduced. As the remaining part of the network architecture \(N\), the function \(\varphi\) is selected so that for each neuron \(v\), the activation function \(\varphi_{v}\) is the identity function except for the case that \(v\) is of type \(h_{(C,2)}\) for some function constraint \(C\) of the form \(x_{1}+f(x_{2})=0\); in this case, the selection \(\varphi_{v}:=f\) is used. The set \(A_{E}\) of active edges is defined to be the set of all edges of \(N\) that are either of the form \[(i_{x},j_{x}),\quad(j_{y},h_{(C,2)})\quad\text{or}\quad(p_{(C^{\prime},k)},q_{ (C^{\prime},k)}),\] where \(x\) and \(y\) are variables that appear in \(W\), \(C\) is an inversion constraint \(z\times y+1=0\) for some variable \(z\in W\), and \(C^{\prime}\in\mathcal{C}\) is a constraint and \(k\in\{1,\ldots,l_{C^{\prime}}\}\) a corresponding index in the sense of 6. In Figure 1, active edges are drawn using thicker arrows than the other edges of the network. Recall that all input neurons are either of the form \(i_{x}\), \(p_{(C,k)}\) or \(e_{C}\), and that \(\{o_{C}\mid C\in\mathcal{C}\}\) is the set of all output neurons. Now, let \(D\) consist of the following data points: * There is a data point \(d_{a}\) in \(D\) that is defined as follows: * For each variable symbol \(x\in W\) it holds that \(d_{a}(i_{x})=1\). * For each constraint \(C\) of the form \(x\times y+1=0\) it holds that \(d_{a}(p_{(C,1)})=1\) and \(d_{a}(p_{(C,2)})=1\). * For every other input neuron \(v\), \(d_{a}(v)=0\). * For every output neuron \(o_{C}\) corresponding to some unit constraint \(C\in\mathcal{C}\), i.e., \(C\) is \(x=1\) for some \(x\in W\), it holds that \(d_{a}(o_{C})=1\). * For every other output neuron \(v\), we have \(d_{a}(v)=0\). * For each constraint \(C\in\mathcal{C}\) of the form \(x\times y+1=0\), two additional data points, \(d_{(C,1)}\) and \(d_{(C,2)}\), are defined in the following steps: * The data point \(d_{(C,1)}\) maps the tuple \((i_{x},i_{y},e_{C},o_{C})\) of neurons to the tuple \((1,0,1,0)\). * In addition, \(d_{(C,1)}\) maps to \(1\) all those input neurons of the form \(p_{(C^{\prime},k)}\) for which the number \(k\in\{1,\ldots,l_{C^{\prime}}\}\) is an index for \(x\) in some constraint \(C^{\prime}\neq C\). * In \(d_{(C,2)}\), the neurons of the tuple \((i_{x},i_{y},e_{C},o_{C})\) are mapped to the values of (\(0,1,0,1\)). * The data point \(d_{(C,2)}\) has value \(1\) for all input neurons of the form \(p_{(C^{\prime},k)}\) for which \(k\in\{1,2,3\}\) is an index for the variable \(y\) in some \(C^{\prime}\in\mathcal{C}\) such that \(C^{\prime}\neq C\). * If \(v\) is any other input neuron or output neuron of \(N\), it holds that \(d_{(C,1)}(v)=d_{(C,2)}(v)=0\). Fig. 1: (a) For a unit constraint \(x=1\), and for every other part of the network, the value assigned to some variable \(x\) is encoded in the weight of the edge from \(i_{x}\) to \(j_{x}\). (b) In the part of the network corresponding to a function constraint \(x+f(y)=0\), the neuron \(h_{(C,2)}\) is activated using the given function \(f\). For every other type of neurons in the network, the identity activation function \(x\mapsto x\) is used. (c) Input neurons \(i_{x}\), \(i_{y}\) and \(i_{z}\), hidden neurons \(j_{x}\), \(j_{y}\), \(j_{z}\) and \(h_{(C,k)}\) for \(k\in\{1,2,3\}\), together with the output neuron \(o_{C}\) enforce an addition constraint \(C\) of type \(x+y+z=0\). For each \(k\in\{1,2,3\}\), the neurons \(p_{(C,k)}\) and \(q_{(C,k)}\) are used to connect the corresponding variable in the constraint with inversion constraints. (d) For an inversion constraint \(C\) of the form \(x\times y+1=0\), an additional input neuron, \(e_{C}\), is introduced. An edge between the hidden levels of the network, from \(j_{y}\) to \(h_{(C,2)}\), is active in the training process. It is intended to carry the negated value of the variable \(x\). These steps introduce at most \(2|\mathcal{C}|\) data points. Note that in the preceding definition of the data points \(d_{(C,1)}\) and \(d_{(C,2)}\), we use the assumption that \(\mathcal{C}\) does not have constraints of the form \(x\times x+1=0\). It remains to show that the \(\mathrm{NN}_{\tau}\)-TRAINING instance \((N,A_{E},A_{V},D,c,\prec,\delta)\) has a satisfying solution if and only if the system \(\mathcal{C}\) is satisfiable. For this, first assume that some edge weight function \(w\) is a solution for the training problem. Let variable assignment \(s\) be such that for each variable \(x\in W\) it holds that \(s(x)=w(i_{x},j_{x})\). We show that \(s\) satisfies \(\mathcal{C}\). For this, let \(C\in\mathcal{C}\) be arbitrary. * If \(C\) is a unit constraint \(x=1\), then by the definition of \(d_{a}\) and the non-negativeness of \(c\), it holds that \(d_{a}(o_{C})=1\). Since \(d_{a}(i_{x})=1\) and \(d_{a}(p_{(C,1)})=0\), we have \(w(i_{x},j_{x})=1\) and so \(s(x)=1\). * In the case that \(C\) is \(x+y+z=0\), we have \(d_{a}(o_{C})=0\) and \(d_{a}(p_{(C,k)})=0\) for each \(k\in\{1,2,,3\}\). Thus, \(w(i_{x},j_{x})+w(i_{y},j_{y})+w(i_{z},j_{z})=0\) or, equivalently, \(s(x)+s(y)+s(z)=0\). * If \(C\) is some inversion constraint \(x\times y+1=0\), the definition of the data point \(d_{(C,1)}\) leads to the following observation: \[0 =d_{(C,1)}(o_{C})\] \[=w(i_{x},j_{x})\times d_{(C,1)}(i_{x})+w(j_{y},h_{(C,2)})\times(w (i_{y},j_{y})\times d_{(C,1)}(i_{y})+d_{(C,1)}(e_{C}))\] \[=w(i_{x},j_{x})\times 1+w(j_{y},h_{(C,2)})\times(w(i_{y},j_{y}) \times 0+1)\] \[=w(i_{x},j_{x})+w(j_{y},h_{(C,2)}).\] Similarly, from the definition of \(d_{(C,2)}\) and the non-negativeness of the cost function \(c\), we get \[1 =d_{(C,2)}(o_{C})\] \[=w(i_{x},j_{x})\times d_{(C,2)}(i_{x})+w(j_{y},h_{(C,2)})\times(w (i_{y},j_{y})\times d_{(C,2)}(i_{y})+d_{(C,2)}(e_{C}))\] \[=w(i_{x},j_{x})\times 0+w(j_{y},h_{(C,2)})\times(w(i_{y},j_{y}) \times 1+0)\] \[=w(j_{y},h_{(C,2)})\times w(i_{y},j_{y}).\] Thus it holds that \(w(j_{y},h_{(C,2)})=-w(i_{x},j_{x})\), and both of the claims \(w(i_{x},j_{x})\times w(i_{y},j_{y})+1=0\) and \(s(x)\times s(y)+1=0\) are true. * If \(C\) is \(x+f(y)=0\), we get \(d_{a}(o_{C})=1\), \(d_{a}(i_{x})=d_{a}(i_{y})=1\) and \(d_{a}(p_{(C,k)})=0\) for \(k\in\{1,2\}\). From these it follows that \(w(i_{x},j_{x})+f(w(i_{y},j_{y}))=0\) and \(s(x)+f(s(y))=0\). Therefore, the preceding assignment \(s\) satisfies all the constraints that belong to \(\mathcal{C}\). For the other direction, let \(s\) be some assignment over the variables in \(W\) such that all constraints of \(\mathcal{C}\) are satisfied. Let \(w\) be an edge weight function defined on the set \(A_{E}\) as follows: * For each variable symbol \(x\in W\), it holds that \(w(i_{x},j_{x})=s(x)\). * For each constraint \(C\) of the form \(x\times y+1=0\), weight value \(-s(x)\) is assigned to the edge \((j_{y},h_{(C,2)})\). The edge \((p_{(C,2)},q_{(C,2)})\) is mapped to the value \(s(x)\times s(y)\). * Every remaining \((p_{(C,k)},q_{(C,k)})\in A_{E}\) is given the weight value \(-s(x_{k})\), where \(x_{k}\) is such that it matches with the index \(k\in\{1,2,3\}\) of constraint \(C\) in the sense of 6. Let \(g\) be the neural function of the neural network \((N,w,\varnothing)\). It remains to show that for every output neuron \(v\) and for every data point \(d\in D\) it holds that \(g_{d}(v)=d(v)\). Recall that for each output neuron \(v\) there is a unique \(C\in\mathcal{C}\) such that \(v=o_{C}\). We will first check the case of the data point \(d_{a}\). If \(C\in\mathcal{C}\) is not an inversion constraint, then for all indices \(k\in\{1,\ldots,l_{C}\}\) as in 6 it holds that \[g_{d_{a}}(h_{(C,k)})=w(i_{x_{k}},j_{x_{k}})\times d_{a}(i_{x_{k}})+w(p_{(C,k)},q_{(C,k)})\times d_{a}(p_{(C,k)})=s(x_{k})\times 1+0=s(x_{k}).\] From this it follows that if \(C\) is a unit constraint, then \(g_{d_{a}}(o_{C})=s(x_{1})=1\), and if \(C\) is an addition constraint, then \(g_{d_{a}}(o_{C})=s(x_{1})+s(x_{2})+s(x_{3})=0\), and furthermore, if \(C\) is a function constraint of the form \(x_{1}+f(x_{2})=0\), then \(g_{d_{a}}(o_{C})=s(x_{1})+f(x_{2})=0\). That is, for each of the preceding cases, it holds that \(g_{d_{a}}(o_{C})=d_{a}(o_{C})\). On the other hand, if \(C\) is an inversion constraint \(x\times y+1=0\), then \[g_{d_{a}}(h_{(C,1)}) =w(i_{x},j_{x})\times d_{a}(i_{x})+w(p_{(C,1)},q_{(C,1)})\times d_ {a}(p_{(C,1)})\] \[=s(x)\times 1+(-s(x))\times 1=0,\] \[g_{d_{a}}(h_{(C,2)}) =\left(w(j_{y},h_{(C,2)})\times(w(i_{y},j_{y})\times d_{a}(i_{y})+d_ {a}(e_{C}))\right)+w(p_{(C,2)},q_{(C,2)})\times d_{a}(p_{(C,2)})\] \[=(-s(x)\times(s(y)\times 1+0)+(s(x)\times s(y))\times 1)=0.\] Thus, it holds that \(g_{d_{a}}(o_{C})=0=d_{a}(o_{C})\). For the remaining cases, let \(C\) be a fixed inversion constraint \(x\times y+1=0\). We will go through the data points \(d_{(C,1)}\) and \(d_{(C,2)}\) simultaneously. First, let \(d\in\{d_{(C,1)},d_{(C,2)}\}\) and \(C^{\prime}\in\mathcal{C}\setminus\{C\}\) be arbitrary. Then, for each \(k\in\{1,\ldots,l_{C^{\prime}}\}\) it holds that \(h_{(C^{\prime},k)}=0\), namely, either it holds that both \(d(x_{k})=0\) and \(d(p_{(C^{\prime},k)})=0\) are true, or that both \(d(x_{k})=1\) and \(d(p_{(C^{\prime},k)})=1\) are true. Therefore, we obtain the result \(g(o_{C^{\prime}})=0=d(o_{C^{\prime}})\). For the inversion constraint \(C\) and neuron \(h_{(C,1)}\), for each \(d\in\{d_{(C,1)},d_{(C,2)}\}\) it holds that \[g_{d}(h_{(C,1)})=w(i_{x},j_{x})\times d(i_{x})+w(p_{(C,1)},q_{(C,1)})\times d( p_{(C,1)})=s(x)\times d(i_{x})+0.\] From this we get \(g_{d_{(C,1)}}(h_{(C,1)})=s(x)\) and \(g_{d_{(C,2)}}(h_{(C,1)})=0\). On the other hand, for the hidden neuron \(h_{(C,2)}\) and \(d\in\{d_{(C,1)},d_{(C,2)}\}\) we have \[g_{d}(h_{(C,2)}) =\left(w(j_{y},h_{(C,2)})\times(w(i_{y},j_{y})\times d(i_{y})+d(e _{C}))\right)+w(p_{(C,2)},q_{(C,2)})\times d(p_{(C,2)})\] \[=-s(x)\times(s(y)\times d(i_{y})+d(e_{C}))+0\] \[=-s(x)\times s(y)\times d(i_{y})-s(x)\times d(e_{C}).\] Then, \(g_{d_{(C,1)}}(o_{C})=s(x)-s(x)=0\) and \(g_{d_{(C,2)}}(o_{C})=0-s(x)\times s(y)=1\), from which it follows that \(g_{d}(o_{C})=d(o_{C})\) for each \(d\in\{d_{(C,1)},d_{(C,2)}\}\). This concludes the proof the theorem. In the previous proof, it is enough to have a single unit constraint in the set \(\mathcal{C}\). Addition constraints can be combined under a unified output neuron, if multiple data points are allowed in order to take separate addition constraints into account. Here, we can use the fact that the indices of the input neurons \(p_{(C,k)}\) are based on the numbers \(k\) instead of the corresponding variable \(x_{k}\); multiple occurrences of a variable in an unified addition constraint can be treated separately. Furthermore, as noted in [2], it can be assumed that each variable is incident to at most one inversion constraint. In this manner, only a constant number of data points is needed for all the inversion constraints that are in \(\mathcal{C}\). As a reminder, the sigmoid activation function \(\sigma\colon\mathbb{R}\to\mathbb{R}\) is defined as \(\sigma(x)=1/(1+\exp(-x))\) for each \(x\in\mathbb{R}\). Using the previous theorem, we can now connect sigmoidal NN training with exponential real arithmetic. **Corollary 24**.: \(\mathrm{NN}_{\sigma}\)_-\(\mathrm{TRAINING}\) is \(\exists\mathbb{R}_{\mathrm{exp}}\)-complete._ Proof.: By Theorem 23, \(\mathrm{NN}_{\sigma}\)-\(\mathrm{TRAINING}\) is \(\exists\mathbb{R}_{\sigma}\)-complete. Furthermore, the sigmoid activation function is existentially definable in \(\exists\mathbb{R}_{\mathrm{exp}}\) and similarly the exponential function is existentially definable in \(\exists\mathbb{R}_{\sigma}\). Thus it follows that \(\mathrm{NN}_{\sigma}\)-\(\mathrm{TRAINING}\) is \(\exists\mathbb{R}_{\mathrm{exp}}\)-complete. **Corollary 25**.: \(\mathrm{NN}_{\mathrm{sin}}\)_-\(\mathrm{TRAINING}\) is undecidable but in \(\Sigma^{0}_{3}\)._ Proof.: The claim follows from Theorems 13 and 23. Similar to the proof of Theorem 13, undecidability can be generalized to other functions having some form of periodic nature that can be used to define natural numbers with existential formulae. ## V Conclusion We have studied the complexity of the neural network training problem. We showed that the training problem corresponding to sets \(\tau\) of activation functions are complete for the complexity classes \(\exists\mathbb{R}_{\tau}\) that extend the reals with the corresponding functions. We also showed that for sets \(\tau\) of effectively continuous functions, these problems reside in \(\Sigma^{0}_{3}\), and even in \(\Sigma^{0}_{1}\) when defined without the equality sign and negation. The following topics deserve further study: * Could our \(\Sigma^{0}_{1}\) upper bound for the identity-free existential theory of the reals with effectively continuous functions be improved or extended. Note that for decidability of the exponential arithmetic it would suffice to establish an \(\Sigma^{0}_{1}\)-upper bound for its existential fragment [9, 10]. * The proof of our main completeness result (Theorem 23) is based on the use of adversarial network architectures (see [3]). It is an open question whether our result holds if the NN architecture is assumed to be a fully connected graph with all edge weights and neuron biases being active, or when restricted to the case that all neurons use the same activation function. * For many non-negative cost functions it is known that the computational complexity of an exact total training error \(0\) is at most the complexity of an error bounded by some positive value (allowing equality), whereas an upper bound given by the strict order relation \(<\) seems to be independent of the two. Recall that these cases correspond to our upper bounds \(\Sigma^{0}_{3}\) and \(\Sigma^{0}_{1}\), and that in the case of the exponential function, they are also connected to Tarski's exponential function problem. * Another topic to study are training problems with limited precision. For example, does the complexity of the training problem decrease for some activation functions if edge weights and biases are assumed to be rational?
2310.19767
Autoregressive Attention Neural Networks for Non-Line-of-Sight User Tracking with Dynamic Metasurface Antennas
User localization and tracking in the upcoming generation of wireless networks have the potential to be revolutionized by technologies such as the Dynamic Metasurface Antennas (DMAs). Commonly proposed algorithmic approaches rely on assumptions about relatively dominant Line-of-Sight (LoS) paths, or require pilot transmission sequences whose length is comparable to the number of DMA elements, thus, leading to limited effectiveness and considerable measurement overheads in blocked LoS and dynamic multipath environments. In this paper, we present a two-stage machine-learning-based approach for user tracking, specifically designed for non-LoS multipath settings. A newly proposed attention-based Neural Network (NN) is first trained to map noisy channel responses to potential user positions, regardless of user mobility patterns. This architecture constitutes a modification of the prominent vision transformer, specifically modified for extracting information from high-dimensional frequency response signals. As a second stage, the NN's predictions for the past user positions are passed through a learnable autoregressive model to exploit the time-correlated channel information and obtain the final position predictions. The channel estimation procedure leverages a DMA receive architecture with partially-connected radio frequency chains, which results to reduced numbers of pilots. The numerical evaluation over an outdoor ray-tracing scenario illustrates that despite LoS blockage, this methodology is capable of achieving high position accuracy across various multipath settings.
Kyriakos Stylianopoulos, Murat Bayraktar, Nuria González Prelcic, George C. Alexandropoulos
2023-10-30T17:38:16Z
http://arxiv.org/abs/2310.19767v1
Autoregressive Attention Neural Networks for Non-Line-of-Sight User Tracking with Dynamic Metasurface Antennas ###### Abstract User localization and tracking in the upcoming generation of wireless networks have the potential to be revolutionized by technologies such as the Dynamic Metasurface Antennas (DMAs). Commonly proposed algorithmic approaches rely on assumptions about relatively dominant Line-of-Sight (LoS) paths, or require pilot transmission sequences whose length is comparable to the number of DMA elements, thus, leading to limited effectiveness and considerable measurement overheads in blocked LoS and dynamic multipath environments. In this paper, we present a two-stage machine-learning-based approach for user tracking, specifically designed for non-LoS multipath settings. A newly proposed attention-based Neural Network (NN) is first trained to map noisy channel responses to potential user positions, regardless of user mobility patterns. This architecture constitutes a modification of the prominent vision transformer, specifically modified for extracting information from high-dimensional frequency response signals. As a second stage, the NN's predictions for the past user positions are passed through a learnable autoregressive model to exploit the time-correlated channel information and obtain the final position predictions. The channel estimation procedure leverages a DMA receive architecture with partially-connected radio frequency chains, which results to reduced numbers of pilots. The numerical evaluation over an outdoor ray-tracing scenario illustrates that despite LoS blockage, this methodology is capable of achieving high position accuracy across various multipath settings. Localization, tracking, dynamic metasurface antennas, deep learning, autoregressive attention networks. ## I Introduction Metasurface-based antennas, such as Reconfigurable Intelligent Surfaces (RISs) [1][2] and Dynamic Metasurface Antenna arrays (DMAs) [3, 4] are key enablers of smart radio environments [5], and can offer benefits across various network objectives, such as localization, sensing, and Radio Frequency (RF) mapping. In many recent cases, RISs have been endowed with receive RF Chains (RFCs) and play the role of large-aperture receivers, or sensors, of uplink signals, either by deploying multiple single-RF metasurfaces [6] or partially-connected multi-RFC architectures with reflecting [7] and hybrid reflecting/sensing [8] meta-elements. When solely reflecting surfaces are considered in bistatic sensing architectures [9, 10, 11, 12], a two-stage procedure is most commonly adopted in estimating channel or environment components (e.g., Angles of Arrivals (AoAs)), and then, performing the position estimation. Typically, the information extraction over the signals is carried out via subspace based algorithms (e.g., MUSIC [13] and its extensions [14, 15]) or Compressed Sensing (CS) approaches (e.g. [9, 11]), while the position estimation can be obtained via minimizing the Cramer-Rao Bound (CRB) [16]. Recent methodologies stemming from Machine Learning (ML) are either designed to augment conventional approaches, such as the Deep-Augmented MUSIC approach [15], or may focus on active sensing setups where the algorithms try to find favorable metasurface configurations that lead to sufficient estimations. To that end, very recently, a Long-Short-Term Memory (LSTM) neural network was proposed in [17] for beamforming toward the static user position, and a similar strategy based on reinforcement learning was used in [18] to localize passive objects. While subspace/CS-based and ML approaches have demonstrated great potential, they often rely on extensive signal sampling to perform estimations (i.e., in the order of the number of RIS elements [6, 19, 20, 21]) that may well exceed the coherence time of the channel. This problem is only exacerbated by the fact that, switching configurations in metasurfaces introduce non-negligible delays (which may be even comparable to the channel coherence frame [22]), and that most of the available techniques have non-linear computational complexity [1]. Besides, the vast majority of localization approaches, even the ones that follow similar ML-based methodologies [23, 24], assume Line-of-Sight (LoS) propagation environments between the receiver/metasurface and the user [23], or may entail large sensing and preprocessing overheads [24, 25]. **Contributions:** Taking the above considerations into account, in this paper, we design a monostatic sensing system for user tracking in multipath non-LoS environments, where a DMA with a limited number of RFCs observes an equal number of pilot signals to perform a noisy estimation of the channel. A novel modified Multi-Head Self-Attention (mMHSA) Neural Network (NN) architecture is proposed that learns a mapping between the channel vectors and the (static) user positions within the considered environment. To perform tracking, we furthermore train an AutoRegressive (AR) model that receives as input the time-agnostic predictions of the mMHSA network along sampled user trajectories, and outputs a smoothed version of the predictions that better fit the mobility patterns of the users. **Notation**: Vectors (matrices) are given in bold lowercase (bold uppercase) typeface and calligraphic letters denote sets. \((\cdot)^{T}\) and \((\cdot)^{H}\) return matrix transposition and hermitian transposition, respectively, while \(\|\cdot\|\) is the Euclidean norm and \(|\cdot|\) provides a set's cardinality. \(\mathcal{CN}(\cdot,\cdot)\) denotes the complex normal distribution and \(j\triangleq\sqrt{-1}\). For a vector \(\mathbf{v}\), \(\mathbf{v}_{i:j}\) denotes the sliced-vector constructed by taking the elements of \(\mathbf{v}\) from the \(i\)-th position up to, and including, the \(j\)-th position. ## II System Model and Objective ### _System Model_ We consider the uplink of a communication system, in which a single-antenna user moves along pseudorandom 2D trajectories and periodically transmits localization requests to a fixed-position planar DMA-based access point comprising \(N\) meta-elements, each with a tunable electromagnetic response (effectively, a phase shift). It is assumed that the DMA meta-elements are attached in groups in \(N_{\mathrm{RF}}\) RFCs, so that all \(N_{E}\triangleq N/N_{\mathrm{RF}}\) elements of each DMA row are connected to a common RFC. By modeling the signal propagation inside the DMA microstrip (assuming negligible attenuation) and adopting a Lorentzian-constrained phase model for its unit elements, the frequency response \(w_{i,j}\) of the element located in the \(i\)-th row (\(i=1,\ldots,N_{\mathrm{RF}}\)) and \(j\)-th column (\(j=1,\ldots,N_{E}\)) of the metasurface's grid can be compactly expressed as follows [26]: \[w_{i,j}\triangleq 0.5\left({{j}+\exp{({j}\phi_{i,j})}}\right)\exp{({j}\rho_{j} \beta)}, \tag{1}\] where \(\phi_{i,j}\in[-\pi/2,\pi/2]\) denotes the _controllable_ phase shift induced by the DMA for the respected element, \(\rho_{j}\) is the horizontal position of the \(j\)-th element in its microstrip, and \(\beta\) is the wavenumber associated with the internal propagation, which is expressed as \(\beta\triangleq(2\pi/\lambda)\sqrt{\epsilon}\) with \(\lambda\) being the wavelength of the carrier signal and \(\epsilon\) denotes the permittivity of the microstrip (usually, \(\epsilon=6\)[26]). For notation purposes, let us denote the concatenated vector of phase shifts as: \[\mathbf{\phi}\triangleq[\phi_{1,1},\phi_{1,2},\ldots,\phi_{2,1},\ldots,\phi_{N_{ \mathrm{RF}},N_{E}}]^{T}, \tag{2}\] and the corresponding vector of the DMA configuration as \[\mathbf{w}\triangleq[w_{1,1},w_{1,2},\ldots,w_{2,1},\ldots,w_{N_{\mathrm{RF}},N_{ E}}]^{T}. \tag{3}\] The phase shift configuration of the overall DMA satisfies the mean power constraint \(\mathbb{E}\left[\|\mathbf{w}\|^{2}\right]\leq P_{\max}\). From now on in this paper, we will be referring to the elements of \(\mathbf{\phi}\) and \(\mathbf{w}\) as \(\phi_{n}\) and \(w_{n}\) (\(n=1,\ldots,N\)), respectively, where \(n=(i-1)N_{E}+j\). At each localization request time slot \(t\), the user is located at a 2D position \(\mathbf{p}^{t}\) and transmits a fixed pilot symbol \(x\) with unit power under a multipath channel. Orthogonal Frequency-Division Multiplexing (OFDM) with \(L\) subcarriers is assumed and the channel at each \(t\)-th time slot and \(l\)-th subcarrier with \(l=1,2,\ldots,L\) is modeled by the vector \(\mathbf{h}^{t,l}\in\mathbb{C}^{N\times 1}\). By using the notation \(\widetilde{\mathbf{w}}_{i}^{t}\triangleq\mathbf{w}_{(i-1)N_{E}+1:iN_{E}}^{H}\in \mathbb{C}^{1\times N_{E}}\) for the sub-vector of the configuration associated with the \(i\)-th DMA RFC at the \(t\)-th time slot, and representing the associated channel sub-vector as \(\widetilde{\mathbf{h}}_{i}^{t,l}\triangleq\mathbf{h}_{(i-1)N_{E}+1:iN_{E}}^{t,l}\in \mathbb{C}^{N_{E}\times 1}\), the received signal at the \(i\)-th RFC of the DMA at the access point at the \(l\)-th subcarrier and \(t\)-th time slot can be expressed as: \[y_{i}^{t,l}\triangleq\widetilde{\mathbf{w}}_{i}^{t}\widetilde{\mathbf{h}}_{i}^{t,l}x+ \widetilde{\mathbf{w}}_{i}^{t}\widetilde{\mathbf{n}}^{t,l}, \tag{4}\] where \(\widetilde{\mathbf{n}}^{t,l}\sim\mathcal{CN}(\mathbf{0}_{N_{E}},\sigma^{2}\mathbf{I} _{N_{E}})\) denotes the thermal noise vector at the receiver with \(\mathbf{0}_{N_{E}}\) and \(\mathbf{I}_{N_{E}}\) being the \(N_{E}\)-element zero vector and \(N_{E}\times N_{E}\) identity matrix, respectively. Let us finally denote the concatenated receive vector from all \(N_{\mathrm{RF}}\) DMA's RFCs as \(\mathbf{y}^{t,l}\triangleq[y_{1}^{t,l},y_{2}^{t,l},\ldots,y_{N_{\mathrm{RF}}}^{t,l }]^{T}\). To accurately model the non-LoS and multipath nature of the considered localization setting, we adopt the urban outdoor "O1 - Blocked" scenario of the DeepMIMO simulator [27] for the carrier frequency \(f_{c}=28\) GHz and \(500\) KHz bandwidth. This simulator provides ray-tracing-derived path details (see [28] for a relevant survey with similar simulators) for user positions along a grid with \(20\) cm separation. A top view of the simulation setup is given in Fig II-A. ### _Tracking Objective_ Let us denote as \(\mathcal{T}\) the trajectory instance within a predefined space containing the \(|\mathcal{T}|\) sequential user positions. In this paper, we make use of the Bezier curves [29] with \(5\) control points for each trajectory by further discretizing each random user position to the closest one appearing on the DeepMIMO data set. The applied localization schemes output an estimated user position \(\mathbf{\hat{p}}^{t}\) at every time slot \(t\) Fig. 1: Top view of the non-LoS tracking scenario “O1” with one blocking and two main reflecting wall surfaces. The receiving DMA is positioned at \((235,485)\). The figure is colored by the received signal strength values, as provided via ray-tracing from [27] using \(3\) non-LOS channel paths. Values shown in normalized units. The red curve illustrates a randomly generated user trajectory of \(100\) location points of \(20\) cm separation. therefore, the instantaneous localization error is given by \(e_{\mathrm{pos}}^{t}\triangleq\sqrt{\|\mathbf{p}^{t}-\hat{\mathbf{p}}^{t}\|^{2}}\) and our proposed tracking objective entails minimizing the mean of this error within a trajectory. In mathematical terms, we consider the optimization problem: \[\mathcal{OP}:\min_{\{\mathbf{p}^{t}\}_{t=1}^{|\mathcal{T}|},\ \frac{1}{|\mathcal{T}|}\sum_{t=1}^{| \mathcal{T}|}e_{\mathrm{pos}}^{t}. \tag{5}\] ## III Proposed User Tracking Methodology In this section, a two-stage approach for online user tracking with a DMA-based receiver is presented. We first describe the channel estimation process, followed by the overall user tracking procedure. Then, the details of the proposed mMHSA NN that maps channel estimates with position estimations, and the considered AR model that leverages the latter estimations to better fit user mobility patterns, are provided. ### _Channel Estimation_ By setting \(\phi_{i,j}=-\pi/2\triangleq\phi^{0}\) in (1), the response of each (\(i,j\))-th DMA element gets zeroed. Using this setting for all indices \(i\) and all \(j\neq j^{\prime}\), while simultaneously letting \(\phi_{i,j^{\prime}}\neq\phi^{0}\), the received signal in (4) at each \(i\)-th DMA RFC at the \(l\)-th subcarrier and \(t\)-th time slot can be expressed as: \[y_{i}^{t,l}=\tilde{w}_{i,j^{\prime}}^{t}\tilde{h}_{i,j^{\prime}}^{t,l}x+\tilde {w}_{i,j^{\prime}}^{t}\tilde{n}_{i,j^{\prime}}^{t,l}, \tag{6}\] which indicates that only the \(j^{\prime}\)-the element of the \(i\)-th microstrip contributes to the received signal. By digitally removing the known effects of \(\tilde{w}_{i,j^{\prime}}^{t}\) and \(x\) from \(y_{i}^{t,l}\), an estimate for \(\tilde{h}_{i,j^{\prime}}^{t,l}\) can be obtained with an associated estimation error given by \(\tilde{w}_{i,j^{\prime}}^{t}x\tilde{n}_{i,j^{\prime}}^{t,l}\). By sequentially setting \(j^{\prime}=1,\ldots,N_{E}\), an estimate of the complete channel vector is attained using \(N_{E}\) repeated pilot signals. We note that for practical purposes, \(N_{E}\) is expected to be \(o(N)\), thus, the overhead of this pilot-assisted channel estimation procedure is limited. ### _Tracking Procedure_ Assume a user moving along its predefined trajectory at some arbitrary time step \(t\). The first stage of the proposed user tracking approach involves training a regression NN, termed modified Multi-Head Self-Attention (mMHSA), that receives a channel measurement matrix as described above and outputs an initial position estimate \(\mathbf{\tilde{p}}^{t}=f_{\mathbf{\theta}}^{\mathrm{mMHSA}}(\mathbf{H}^{t})\), which is parameterized by an arbitrary vector of weights, \(\mathbf{\theta}\). The mMHSA network disregards any temporal correlation appearing in tracking problems. To that end, the second stage of the procedure involves the refinement of those initial estimates by accounting for the user's learned mobility patterns. Concretely, assume that, at time \(t\), mMHSA has provided estimates for all past and current positions \(\{\mathbf{\tilde{p}}^{k}\}_{k=1}^{t}\). An AR model is then applied on those initial predictions to obtain the final output position estimate \(\mathbf{\hat{p}}^{t}\), as \(\mathbf{\hat{p}}^{t}=f_{\gamma,\mathbf{z}}^{\mathrm{AR}}(\{\mathbf{\tilde{p}}^{k}\}_{k=1}^ {t})\), so that correlations between past estimates can be learned. Since this approach falls under supervised learning, both models require a training procedure with known user positions. To that end, assume that \(D\) trajectories of length \(|\mathcal{T}|\) are collected as \(\mathcal{D}=\{\{(\mathbf{H}^{t,d},\mathbf{p}^{t,d})\}_{t=1}^{|\mathcal{T}|}\}_{d=1}^{D}\) and a shuffled version of \(\mathcal{D}\) is compiled as \(\mathcal{D}^{\prime}=\{(\mathbf{H}^{q},\mathbf{p}^{q})\}_{q=1}^{|\mathcal{T}|D}\). The mMHSA is, thus, trained via standard Stochastic Gradient Descent (SGD) [30] over \(\mathcal{D}^{\prime}\) on the loss function \(J_{\mathcal{D}^{\prime}}(\mathbf{\theta})=1/(|\mathcal{T}|D)\sum_{q=1}^{|\mathcal{ T}|D}\sqrt{\|\mathbf{p}^{t}-f_{\mathbf{\theta}}^{\mathrm{mMHSA}}(\mathbf{H}^{q})\|^{2}}\) which minimizes the tracking objective (5). Once mMHSA is trained, it is used to predict the (known) positions for all channel instances in \(\mathcal{D}\), to obtain \(\{\{\mathbf{\tilde{p}}^{t,d}\}_{t=1}^{|\mathcal{T}|}\}_{d=1}^{D}\). Therefore, the AR model is trained via SGD to minimize the error in the estimation between the ground-truth positions and the initial estimates of mMHSA as \(J_{\mathcal{D}}(\gamma,\mathbf{z})=1/(|\mathcal{T}|D)\sum_{d=1}^{D}\sum_{t=1}^{| \mathcal{T}|}\sqrt{\|\mathbf{p}^{t,d}-f_{\gamma,\mathbf{z}}^{\mathrm{AR}}(\{\mathbf{\tilde {p}}^{k,d}\}_{k=1}^{t})\|^{2}}\). ### _Modified Multi-Head Self-Attention Network (mMHSA)_ The mMHSA step aims to map noisy channel estimates to position estimations. Accounting for the \(N\) DMA meta-elements and the \(L\) OFDM subcarriers, and by separating the real and imaginary channel components along a matrix dimension, the estimated channel at each \(t\)-th time slot can be expressed as a 3D matrix \(\mathbf{H}^{t}\in\mathbb{R}^{2\times N\times L}\), which resembles the matrix dimensions commonly appearing in computer vision applications. It is noted that, due to the geometric nature of the considered channel model, the \(\mathbf{H}^{t}\) elements are expected to exhibit high spatial correlation [32]. Under the latter observations, our mMHSA architecture uses components of the state-of-the-art Vision Transformer (ViT), which was originally proposed for image classification tasks [31]. The NN architecture is included in Fig. 2 following the ViT naming and components. In particular, each input \(\mathbf{H}^{t}\) is first rearranged to two dimensions of size \((N,2L)\), which is then sliced into \(\texttt{p}\times\texttt{p}\) smaller patches. The patches are then concatenated and passed through a linear mapping layer to attain the initial embeddings of dimension \(d_{\mathrm{hidden}}\). Two learnable Fig. 2: The proposed mMHSA architecture for position estimation based on noisy channel estimates, inspired by ViT [31]. The design of the patches, estimation token, and positional embeddings have been modified from the original architecture. Red rectangles signify learnable blocks. tokens are appended in the embeddings instead of a single class token, since our architecture is intended for prediction of 2D vectors. Positional embeddings are then added, similar to [31], although the frequency of the embeddings is set to \(2N\) instead of \(10000\) in our architecture. The embeddings are then forwarded to \(\texttt{n}_{\text{blocks}}\) sequential transformer encoder blocks. Each encoder is comprised an mMHSA layer followed by a Multi-Layer Perceptron (MLP), as proposed in [33]. Finally, the 2D estimation tokens are extracted along each embedding dimension and an MLP head is responsible for extracting the position estimation \(\boldsymbol{\tilde{p}}^{t}\) out of them. ### _AR-Model-Based Position Estimation_ This stage receives the estimates \(\{\boldsymbol{\tilde{p}}^{t}\}_{t=1}^{|\mathcal{T}|}\) of the user position along a trajectory of \(\mathcal{T}\) sequential user positions (i.e., \(|\mathcal{T}|\) mMHSA outputs) and feeds an AR model with an exponentially decaying weighting factor to refine the position estimate at each \(t\)-th time slot as: \[\boldsymbol{\tilde{p}}^{t}=f_{\gamma,\boldsymbol{z}}^{\mathrm{AR}}(\{ \boldsymbol{\tilde{p}}^{k}\}_{k=1}^{t})=\sum_{k=1}^{t}\mathrm{pow}(\sigma( \gamma),t-k+1)\boldsymbol{z}\circ\boldsymbol{\tilde{p}}^{k}, \tag{7}\] where \(\gamma\) and \(\boldsymbol{z}\in\mathbb{R}^{2}\) denote the model's parameters, which are optimized through SGD over a data set of collected user trajectories and corresponding mMHSA predictions as described in Section III-B. In this expression, \(\sigma(\cdot)\) denotes the sigmoid function that ensures that the decaying factor resides in \((0,1)\), \(\circ\) indicates element-wise multiplication, and \(\mathrm{pow}(\cdot,\cdot)\) denotes exponentiation. ## IV Numerical Evaluation For the numerical evaluation, we adopt DeepMIMO's "O1 - Blocked" scenario [27], where the base station with index \(3\) plays the role of the receiving DMA positioned at \((235,485,6)\). The geometry is given in Fig. 2, where approximately \(10^{6}\) user positions are sampled at a spacing of \(20\) cm inside a \(110\times 40\) m outdoor urban area. The user travels along \(75000\) randomly generated 2D trajectories of \(|\mathcal{T}|=100\) positions at a mean separation of \(2.5\) m, remaining at a fixed height of \(2\) m. We keep \(N=256\), \(L=4\), and \(N_{\mathrm{RF}}=16\) as fixed values and we set the estimation noise floor power per symbol to \(-60\) dBm. The mMHSA network is built with \(3\) Transformer Encoder blocks with \(2\) heads and a hidden embedding dimension of \(16\). A learning rate of \(0.002\) and a training period of \(60\) epochs were used for both models. Only half the data set was used for training the mMHSA, and the rest was used for testing to limit the number of random trajectory positions that are seen by the network during training, regardless of the internal regularization components. Since typical localization and tracking works assume LoS [15, 16, 17, 9] or more involved systems and procedures that don't facilitate real time user tracking [18, 11], we have implemented a fingerprinting localization scheme [34] as a baseline for position estimation. Disregarding trajectories and estimation errors, the Received Signal Strength Indicators (RSSIs) for all \(N_{\mathrm{RF}}\) RFCs and \(L\) subcarriers corresponding to the data points of the training set are stored in a data base. To make the position estimation, this baseline observes the current RSSI from the user's pilots and outputs the position of the closest RSSI match in the data base (i.e. nearest neighbor heuristic). The position estimation errors along \(25000\) randomly sampled test trajectories are given in Fig. 3 over increasing numbers of signal paths, both for the initial mMHSA estimations, the two-step mMHSA and AR process, and the fingerprinting baseline. It can be inferred that the proposed architecture has substantial overheads over the baseline, especially when fewer reflection paths are present. The performance difference is decreasing as the effects of multipath get more pronounced, with the mMHSA-AR methodology resulting in smaller position errors nonetheless. The addition of the AR step is beneficial to the overall scheme by reducing the estimation error roughly \(1\)-\(2\) m in all cases. When a single reflection path is considered, this approach is able to attain a mean position error of \(2.47\) m. Finally, it is worth stating that while the presence of multipath has an adverse effect in the estimation accuracy, the induced errors nearly plateau after a certain threshold of \(5\) paths. ## V Conclusion In this paper, the problem of online user tracking via a receiving DMA has been considered, dealing specifically with mobile users in non-LoS multipath environments. The DMA architecture was used to provide noisy estimates of the channel with low pilot overheads, which are then fed into a variation of the ViT architecture to map frequency responses to user position estimates. The tracking problem was handled by an AR model over initial estimates along sampled user trajectories to further reduce the estimation error based on mobility patterns. The numerical evaluation has illustrated that this approach is able to attain high localization performance in a large area non-LoS scenario with multipath channels derived from the DeepMIMO ray-tracing simulator. This approach was able to attain a mean position error below \(2.5\) m when a single channel path is present, consistently outperforming the fingerprinting baseline in all cases, while the effects of the increasing number of paths are shown to be bounded. Fig. 3: Localization error of the proposed methodology and baseline over different number of signal paths.
2302.06456
Soft Continuum Actuator Tip Position and Contact Force Prediction, Using Electrical Impedance Tomography and Recurrent Neural Networks
Enabling dexterous manipulation and safe human-robot interaction, soft robots are widely used in numerous surgical applications. One of the complications associated with using soft robots in surgical applications is reconstructing their shape and the external force exerted on them. Several sensor-based and model-based approaches have been proposed to address the issue. In this paper, a shape sensing technique based on Electrical Impedance Tomography (EIT) is proposed. The performance of this sensing technique in predicting the tip position and contact force of a soft bending actuator is highlighted by conducting a series of empirical tests. The predictions were performed based on a data-driven approach using a Long Short-Term Memory (LSTM) recurrent neural network. The tip position predictions indicate the importance of using EIT data along with pressure inputs. Changing the number of EIT channels, we evaluated the effect of the number of EIT inputs on the accuracy of the predictions. The least RMSE values for the tip position are 3.6 and 4.6 mm in Y and Z coordinates, respectively, which are 7.36% and 6.07% of the actuator's total range of motion. Contact force predictions were conducted in three different bending angles and by varying the number of EIT channels. The results of the predictions illustrated that increasing the number of channels contributes to higher accuracy of the force estimation. The mean errors of using 8 channels are 7.69%, 2.13%, and 2.96% of the total force range in three different bending angles.
Amirhosein Alian, George Mylonas, James Avery
2023-02-13T15:35:43Z
http://arxiv.org/abs/2302.06456v2
Soft Continuum Actuator Tip Position and Contact Force Prediction, Using Electrical Impedance Tomography and Recurrent Neural Networks ###### Abstract Enabling dexterous manipulation and safe human-robot interaction, soft robots are widely used in numerous surgical applications. One of the complications associated with using soft robots in surgical applications is reconstructing their shape and the external force exerted on them. Several sensor-based and model-based approaches have been proposed to address the issue. In this paper, a shape sensing technique based on Electrical Impedance Tomography (EIT) is proposed. The performance of this sensing technique in predicting the tip position and contact force of a soft bending actuator is highlighted by conducting a series of empirical tests. The predictions were performed based on a data-driven approach using a Long Short-Term Memory (LSTM) recurrent neural network. The tip position predictions indicate the importance of using EIT data along with pressure inputs. Changing the number of EIT channels, we evaluated the effect of the number of EIT inputs on the accuracy of the predictions. The least RMSE values for the tip position are 3.6 and 4.6 mm in Y and Z coordinates, respectively, which are 7.36% and 6.07% of the actuator's total range of motion. Contact force predictions were conducted in three different bending angles and by varying the number of EIT channels. The results of the predictions illustrated that increasing the number of channels contributes to higher accuracy of the force estimation. The mean errors of using 8 channels are 7.69%, 2.13%, and 2.96% of the total force range in three different bending angles. ## I Introduction Soft robots are widely used in many fields and applications such as minimally invasive surgery (MIS) [1], terrain navigation [2], rehabilitation [3], and industrial grippers [4]. Soft robots provide compliance, facilitate dexterous manipulation, and ensure safe human-robot interaction. Despite considerable benefits associated with the use of soft robotics, certain challenges remain to be addressed. One of these challenges is state estimation during actuation and interaction with the environment. The high compliance of soft robots enables them to deform nonlinearly under external and internal loads, thus making the prediction of their states, such as tip position and backbone shape, demanding. In surgical applications, the presence of anatomical barriers and unstructured environments make state estimation even more challenging. Accurate state estimation contributes to lower pain and discomfort in patients [5] and reduces postoperative complications and adverse events during operations [6, 7]. Estimating exerted forces by soft robots can contribute equally to patients' comfort. A large number of studies have investigated force prediction from shape sensing modules of soft robots [8, 9, 10]. Apart from intraoperative imaging, model-based and sensor-based approaches have been investigated thus far to address the state estimation challenges in the field of soft surgical robots. In sensor-based approaches, Fiber Bragg Gratings (FBGs), ElectroMagnetic (EM) trackers, and stretchable sensors are primarily used for state estimation. FBGs are MRI compatible and biocompatible optical sensors that provide state information of the robot with high sampling rates [7, 11], measuring the wavelength shifts of the emitted light. Although FBGs intrinsically have limited range of motion, recent studies have shown using Nitinol wires in combination with FBGs can enhance their deformability [12]. FBGs require a bulky and expensive optical spectrum interrogator to measure the wavelength shift [13]. Additionally, the distance between the interrogator and optical cores adversely influences the accuracy, thus posing limitations on the application of FBGs in surgical devices [14]. EM trackers have minimum impact on mechanical characteristics of the overall system, however the electromagnetic field of operating rooms can severely impact performance. Generally used in flexible robots with multiple serially connected sections [15], several studies estimated the shape and tip position of flexible robots through fitting Bezier curves to EM tracker data [16, 17]. Stretchable sensors composed of conductive materials are another method used for state estimation of soft robots by measuring resistance [18], capacitance [19], or inductance [20] changes induced by the deformations of the device. The limitations of stretchable sensors are hysteresis, requiring additional wiring, and material biocompatibility concerns [21]. Continuing the study conducted in [22] where EIT was shown effective in deformation detection, this paper evaluates the tip position and force estimation accuracy of a data-driven approach using EIT data. Biocompatibility and MRI compatibility are two potential benefits of this sensing approach in inflatable medical devices. Compared to previously mentioned sensing schemes, EIT shape sensing requires minimal wiring, has negligible effect on system physical characteristics, and minimizes manufacturing and sensing integration costs. To employ this sensing technique, a conductive liquid is used to pressurise the soft actuator, which induces a deformation and volume change within the chamber. Using an array of electrodes embedded inside the actuation chamber, electrical current is injected between different regions and the resultant voltages are recorded. The changes in these voltages are attributed to the changes in the volume of the liquid and shape changes of the actuator. Leveraging the measured voltages in combination with a recurrent neural network, we evaluate the performance of EIT sensing in tip position prediction and contact force estimation. Since EIT images provide no information of the sequence of the data, a data-driven approach was adopted to predict the states based on the arrays of voltage changes. Experiments are executed using a single degree of freedom (DOF) soft bending actuator to validate the accuracy of EIT state estimation in a data-driven manner. An OptiTrack camera system and a 6-axis force transducer are used for training the network and as the ground truth for the EIT state estimation assessment. As voltages are recorded through several pairs of electrodes, the effect of number of measurement pairs on the accuracy of state estimation of EIT is evaluated in this study. The proposed sensing scheme can be potentially used in flexible endoscopy and laparoscopy where the shape changes of the end effector can be measured while meeting safety concerns. ## II Materials and Methods ### _EIT hardware system_ The primary unit of the EIT system utilized here is Quadra impedance spectroscopy developed by Eliko tech [23]. This unit incorporates an alternating current source, voltage acquisition and multiplexer, which enables the recording of impedance data from up to 16 electrodes. An impedance measurement requires current to be injected through a pair of electrodes, and voltage to be recorded through another pair, a sequence of these measurements is referred to as an EIT protocol. In this study, current of magnitude 1 mA at 11 kHz frequency was used in all experiments, which is injected sequentially, known as Time Division Multiplexing (TDM), at a rate of 20 Hz for a complete protocol. To estimate the state of the robot, the recorded voltages can be directly exploited to train the network or EIT reconstructions could be used as in [22]. ### _Fabricating the Soft Actuator_ The soft bending actuator is fabricated through casting Ecoflex 00-50 Silicone rubber into a 3-D printed mold following the same procedure discussed in [24]. The mold is designed such that the actuator has an inflatable chamber with a semi-circle cross-section. Fiber reinforcement and an inextensible polyester layer are added to restrain the radial and axial expansions of the actuator, respectively. Being able to bend in-plane with a single DOF, the fabricated actuator is 100 mm long with a wall thickness of 4 mm and total diameter of 12 mm. Several of the proposed continuum actuator can be concatenated into a tethered endoscopic device for applications such as gastrointestinal endoscopy. Prior to capping the distal end of the actuator, a Flexible Printed Circuit (FPC) containing the injection and measurement electrodes was integrated into the actuation chamber. The FPC contains 13 electrodes placed linearly with constant spacing of 6.5 mm on a Polyamide flexible film. The flexibility and stiffness of the film has a minimum impact on the mechanical behaviour of the actuator. The electrodes were gold coated to minimize the contact impedance between the conductive fluid and the electrodes, thus reducing the noise in the voltage signals. The fluid used for pressuring the actuator is 0.9% saline. To integrate the FPC into the actuator, the Polyamide film is placed on the flat side of the semi-circle cross section of the actuator. To fix the position of the FPC and minimize the noise stemming from the displacement of the electrodes, both ends of the FPC are glued using a silicone epoxy. The fabricated soft bending robot with the integrated FPC is shown in Fig. 1. ### _LSTM Network_ To predict the tip position and the contact force of the soft actuator an LSTM network is trained using a combination of pressure and EIT voltages. LSTM is a dynamic network capable of learning time series events by keeping a memory of data from past events [25]. As soft robots display a time-varying behaviour and the data related to their states is sequential, LSTM is a potential candidate to be used for predicting the tip position and contact force. In the study, the training and predictions are performed by the LSTM used in [26]. Ultimately, an LSTM network with layer size of 50 and dropout rate of 0.1 is used. The ratio of the unseen data for evaluating the prediction accuracy to the training data is 1 to 4. The training data is normalised by the mean and standard Fig. 1: a) The soft continuum actuator and the integrated FPC containing 13 electrodes. The FPC was placed on the flat side of the semi-circle cross-section of the actuator. b) Schematic of the integrated actuator with an 8-electrode FPC, and how the impedances are measured. While current \(I_{17}\) is injected, \(V_{26}\), \(V_{35}\) are recorded simultaneously. Subscripts refer to electrode number, so \(I_{17}\) is the current injected between electrodes 1 and 7. deviation of the training dataset. The network with the same architecture but different training datasets is used for all the predictions in this study. ## III Experimental Setup The experimental setup used for data collection comprises the soft bending robot, two motion capture systems, a hydraulic pressure sensor, actuation and computation units, and a force/torque transducer. Two reflective markers were placed on the rigid structure and at the distal end of the robot for optical tracking of the tip position using OptiTrack motion capture system (see Fig. 2.a). The actuation unit incorporates a hydraulic pump system along with connecting tubes. The hydraulic pump system consists of a leadscrew and stepper motor driven by a uStepper S-lite controller board and a syringe filled with 0.9% saline. An Arduino Due generated the control signals to pressurize the actuator, and recorded the absolute hydraulic pressure as measured by a MS5803-14BA sensor [27]. The pressure data was sampled at 20 Hz and recorded in MATLAB through serial communication. Two cameras (Prime 13 OptiTrack, NaturalPoint, USA) are employed to track the reflective marker at the tip of the actuator and record its coordinates in 3-D space. OptiTrack data collected at 125 Hz is utilized to train the network and as the ground truth for the tip position predictions. For contact force prediction experiments, an 6-axis force/torque transducer (Nano 17, ATI Automation, USA) is employed. The force data sampled at 62.5 Hz is used for training and validation of the LSTM. Impedance changes upon pressurization of the actuator are sampled by Quadra impedance spectroscopy at 20 Hz. Based on the protocol defined with 9 channels, the current is injected between two outlying electrodes (e.g. \(I_{17}\) in Fig 1), and impedance changes are measured through pairs of electrodes in between (e.g. \(V_{26}\) and \(V_{35}\) in Fig 1). Since the sampling rate of the capture motion system and the force sensor exceed that of the EIT system, the force and the tip position data are resampled at 20 Hz. ### _Tip Position Estimation_ To evaluate the reliability of the EIT data to predict the tip position of the soft bending robot, two sets of experiments were conducted. First, the actuator was set to bend with a constant period and amplitude of 4000 steps, using a constant velocity of 1500 steps per minute, which corresponded to minimum and maximum pressures of 1.131 and 1.675 bar respectively. The complete dataset was 10 minutes or 58 repetitions. In the second experiment, the amplitudes between 1000 and 5000 steps were chosen randomly while the slope and the velocity remained the same. It was found in initial testing that the extra complexity in this required additional training data, so 20 minutes or 116 actuations were used in this case. In both experiments, the pressure and EIT data are used as the input to the LSTM network, and Y-Z coordinates of the tip position are defined as the output. The test data used as the ground truth for the predictions incorporates the unseen data from the sampled dataset. To demonstrate the improvements offered by EIT, the tip prediction was performed using pressure data alone, and then in combination with EIT data through four channels. To discover the effect of the number of EIT channels used for training the LSTM, the tip position was estimated by training the network using pressure and 3 different subsets of the original EIT dataset containing 1, 4, and 8 EIT channels. ### _Contact Force Estimation_ To collect the contact force data, the force transducer was placed within the working space of the soft actuator. The position of the sensor in the vertical plane was adjusted using a rigid structure connected to the aluminium stand. The contact force dataset was obtained at three different bending angles of the actuator to evaluate the effect of the shape on the Fig. 2: a) The setup used for tip position estimation using motion capture system. The effect of using pressure and EIT impedance changes in the accuracy of the tip position estimation upon actuation b) with constant peak amplitude, top: pressure only as input, bottom: pressure and EIT impedance as inputs. c) with random peak amplitude, top: pressure only as input, bottom: pressure and EIT impedance as inputs. precision of the predictions (see Fig 4). Before pressurizing the actuator, it was pre-curved such that the tip has slight contact with the sensor. The actuator was pressurized by a triangle wave signal with random peak values. The data collection at each bending angle lasted 10 minutes followed by resampling the data at 20 Hz EIT sampling rate. The feature variables of the LSTM incorporated the pressure and EIT impedance values of 4 channels while the target variable was set to the force data. ## IV Results ### _Tip Position Estimation_ Fig. 2 compares the predicted tip position for the networks trained with pressure and with pressure and EIT. In the first experiment with repetitive actuation, using the pressure alone has approximately the same prediction results as using both the pressure and the EIT data (see Fig. 2.b). This outcome can be intuitively concluded as the data sequence is highly repeatable and thus easier to predict by the network. However, when the pressure signals have random peak amplitudes, the pressure fails to predict the tip position with any accuracy (Fig. 2.c). It is observed that the RMSE of the predictions by the pressure values is smaller than using both the pressure and EIT data in the experiment with non-random pressure. This difference can be explained by the additional noise in the EIT signals, that impacts the accuracy of the predictions. In case of constant peak amplitude, the overall RMSE values in vertical plane are 0.825 and 2.08 mm using pressure only and in combination with EIT data, respectively. However, these values for random peak amplitude are 21.6 and 6.24 mm. Regarding the effect of the number of channels, as shown in Fig. 3, the dataset with 4 EIT channels yielded slightly enhanced predictions than the dataset with 1 channel. However, the prediction accuracy dropped by increasing the number of EIT channels to 8. This can be concluded by calculating the RMSE values. The least RMSE values for the tip position are 3.6 and 4.6 mm in Y and Z coordinates, respectively. These values are 7.36% and 6.07% of the actuator's total range of motion in Y and Z, respectively. The overall RMSE values in vertical plane are 5.84, 6.24, and 7.21 mm in case of using 1 channel, 4, and 8 channels, respectively. The results underline the fact that using a higher number of channels does not necessarily enhance the accuracy of the predictions, as the channels are not linearly independent and thus may not contain much additional information, but may introduce further noise. Optimizing the number of channels is important as the higher number can increase the computational cost of the system, and complexity of wiring and manufacture, while it has no contribution to improving the predictions. ### _Contact Force Estimation_ Using the same LSTM and training to test dataset ratio, the prediction results respective to three bending angles are depicted in Fig. 6. Further predictions were conducted to evaluate the influence of channel numbers on the results. Therefore, the contact force was predicted using three Fig. 3: The effect of the number of EIT channels used for the tip prediction. a) One channel b) Four channels c) Eight channels. The results indicate that while using 4 channels can lead to enhanced estimation compared to 1 channel, increasing this number to 8 may not have the same effect. The RMSE values for tip estimation with 4 channels are 7.36% and 6.07% of the actuator’s total range of motion in Y and Z, respectively. different number of channels similar to ones used in tip position estimation. These predictions were repeated for all three bending angles. The mean and standard deviation of the absolute error between the ground truth data and predictions are illustrated in Fig. 5. The force was predicted most accurately in location b with 8 EIT channels, with a mean error of 2.6 mN, or 1.82% of the maximum force applied. Additionally, regardless of the location of the force sensor, the mean and the standard deviation of the error decline by using higher number of channels for training the network. Higher number of channels provides more detailed information of the actuator's states during the force exertion. Furthermore, the relatively high prediction error in location (a) can be attributed to the lower Signal to Noise Ratio (SNR) of the impedance data measured in this location. The actuator's deformation is close to its rest shape in location (a), hence yielding minimal impedance differentials. ## V Discussion and Conclusion In this paper, the EIT sensing technique with broad applications in the shape sensing and force estimation of medical devices was proposed. Experiments were conducted to evaluate the reliability and effectiveness of EIT in predicting the tip position and contact force of a soft bending actuator. Since the actuator bends in plane, the external force is exerted and estimated in the same plane. However, out of the plane force exertion will be studied in future works with a multi degree of freedom actuator fabricated in [28]. The results showed using pressure data as the only input of the LSTM leads to noticeably less accurate predictions when the continuum robot is actuated by random values of pressure. The prediction RMSE values for using pressure only were 10.1 and 19.1 mm in Y and Z coordinates, respectively. However, the inclusion of the EIT data in the feature variables resulted in RMSE values of 4 and 4.8 mm in the same coordinates. These values are 8.18% and 6.33% of the actuator's range of motion in Y and Z coordinates respectively, which are more promising than some studies such as [26]. Increasing the number of channels used in the tip position predictions can have an undesired effect on the resultant accuracy. Particularly, using only a single channel yielded less erroneous predictions than using 4 and 8 channels in terms of RMSE values. The higher accuracy of a single channel can stem from the fact that one channel is more sensitive to deformations. However, changing the EIT protocol for defining measurement and injection pairs might vary the results. Additionally, higher number of channels is probably required in case of interacting with an obstacle or the exertion of an external load along the length of the actuator. The accuracy of the force prediction increases by using a Fig. 4: Collecting the contact force data for training the network in three different bending angles. Fig. 5: Mean and standard deviation for the contact force estimation respective to the number of channels and the location of the force sensor Fig. 6: The accuracy of the contact force prediction in three different location using 4 channels of EIT. higher number of EIT channels. The mean errors of using 8 channels are 7.8, 2.6, and 4.5 mN, which are 7.69%, 2.13%, and 2.96% of the total force range (improved results compared to [26]). This value for using 1 channel equals to 13.6, 3.8, and 7.3 mN in location (a), location (b), and location (c), respectively. It can be observed that the bending angle at which the external force is exerted can have an impact on the accuracy of the force predictions. This can be attributed to SNR value of the impedance signal which is the lowest in location (a). This result is due to the minimal difference between the actuator's shape in location (a) and its shape in rest position. In future studies, the proposed EIT system will be used to predict the entire shape of the actuator's backbone by using additional markers along the actuator and parameterising the curves. Shape estimation will be conducted using different machine learning models and will be compared to LSTM. The prediction of the shape while external forces are being exerted simultaneously and shape will be explored in future works. Additionally, the Quadra impedance spectroscopy will be replaced by a frequency division multiplexing (FDM) method which enhances the sampling rate of the measurements. ## Acknowledgments This work is partially supported by a research collaboration with the Multi-Scale Medical Robotics Centre, The Chinese University of Hong Kong.
2306.04985
Beyond Probability Partitions: Calibrating Neural Networks with Semantic Aware Grouping
Research has shown that deep networks tend to be overly optimistic about their predictions, leading to an underestimation of prediction errors. Due to the limited nature of data, existing studies have proposed various methods based on model prediction probabilities to bin the data and evaluate calibration error. We propose a more generalized definition of calibration error called Partitioned Calibration Error (PCE), revealing that the key difference among these calibration error metrics lies in how the data space is partitioned. We put forth an intuitive proposition that an accurate model should be calibrated across any partition, suggesting that the input space partitioning can extend beyond just the partitioning of prediction probabilities, and include partitions directly related to the input. Through semantic-related partitioning functions, we demonstrate that the relationship between model accuracy and calibration lies in the granularity of the partitioning function. This highlights the importance of partitioning criteria for training a calibrated and accurate model. To validate the aforementioned analysis, we propose a method that involves jointly learning a semantic aware grouping function based on deep model features and logits to partition the data space into subsets. Subsequently, a separate calibration function is learned for each subset. Experimental results demonstrate that our approach achieves significant performance improvements across multiple datasets and network architectures, thus highlighting the importance of the partitioning function for calibration.
Jia-Qi Yang, De-Chuan Zhan, Le Gan
2023-06-08T07:16:03Z
http://arxiv.org/abs/2306.04985v2
# Beyond Probability Partitions: Calibrating Neural Networks with Semantic Aware Grouping ###### Abstract Research has shown that deep networks tend to be overly optimistic about their predictions, leading to an underestimation of prediction errors. Due to the limited nature of data, existing studies have proposed various methods based on model prediction probabilities to bin the data and evaluate calibration error. We propose a more generalized definition of calibration error called Partitioned Calibration Error (PCE), revealing that the key difference among these calibration error metrics lies in how the data space is partitioned. We put forth an intuitive proposition that an accurate model should be calibrated across any partition, suggesting that the input space partitioning can extend beyond just the partitioning of prediction probabilities, and include partitions directly related to the input. Through semantic-related partitioning functions, we demonstrate that the relationship between model accuracy and calibration lies in the granularity of the partitioning function. This highlights the importance of partitioning criteria for training a calibrated and accurate model. To validate the aforementioned analysis, we propose a method that involves jointly learning a semantic aware grouping function based on deep model features and logits to partition the data space into subsets. Subsequently, a separate calibration function is learned for each subset. Experimental results demonstrate that our approach achieves significant performance improvements across multiple datasets and network architectures, thus highlighting the importance of the partitioning function for calibration. ## 1 Introduction With the advancements in deep learning technology, deep learning models have achieved, and in some cases even surpassed, human-level accuracy in various domains[1; 2]. In safety-critical applications[3; 4] such as self-driving[5] and disease diagnosis[6], it is not only desirable to have high accuracy from models but also to have their predicted probabilities reflect the true likelihood of correctness. For instance, if a model predicts a probability of 0.9 for a particular class, we expect the actual probability of being correct to be close to 0.9. This is known as probability calibration. However, recent research has indicated that while deep models have improved in accuracy, their probability calibration has declined[7; 8; 9]. Typically, deep models tend to overestimate the probabilities of correct predictions, leading to overconfidence. This discrepancy between accuracy and calibration has made model calibration a crucial research direction.[7; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19] Defining an evaluation method for assessing the degree of calibration is crucial to calibrate a model. Currently, most evaluation methods are based on binning model prediction probabilities, followed by analyzing the distribution of true labels within each bin[7; 12; 20; 21]. The calibration error is then estimated by measuring the difference between the predicted probabilities and the empirical distribution. However, such estimation of calibration error fails to reflect the model's accuracy[22]. For instance, consider a binary classification problem where both classes distribute uniformly, and the model consistently outputs a probability of 0.5 for all inputs. Even using the strictest evaluation method for calibration error, this classifier would appear perfectly calibrated[22]. In reality, as long as the evaluation of calibration error is solely based on prediction probabilities, a classifier with a fixed output marginal distribution p(y) would always be perfectly calibrated but useless. This type of calibration error definition may also be counterintuitive to some extent. For example, a recommendation model may be overconfident in one user group and underconfident in another, yet still be considered calibrated overall. However, no user would perceive the model's output probabilities as accurate in such cases. To illustrate this issue, we present a constructed experiment in Figure. 1, which demonstrates the existence of such situations. For calibrating a trained model, existing methods mainly rely on transforming the model's predicted probabilities or logits (inputs to the softmax layer)[7, 10, 11, 23, 24, 25]. For example, histogram binning[7] involves binning the predicted probabilities and calibrating the probabilities within each bin separately. However, as discussed earlier regarding calibration error analysis, if a calibration method relies solely on the model's output probabilities for calibration, it cannot achieve calibration across different semantic contexts because the calibration model itself is completely unaware of semantics. Some studies have analyzed calibration across different categories and proposed corresponding calibration methods. For instance, the Dirichlet calibration method[12] models multiclass probabilities as Dirichlet distributions and transforms the uncalibrated probabilities into calibrated ones. These methods incorporate category information, allowing for calibration across different categories. However, this category information may not be directly available, or the known categories may not be the divisions we are interested in. For example, in a recommendation system, we may want the model to be calibrated across various skin color groups, even if we may not have access to the corresponding category information. **Contribution**. The analysis above has inspired us to propose that a perfectly calibrated model should be calibrated across any data space partition. We present the Partitioned Calibration Error (PCE) as a comprehensive framework for defining semantic-aware calibration errors. By illustrating that various common calibration error metrics are specific instances of PCE under distinct partition functions, we establish a direct correlation between calibration error and model accuracy: PCE converges to accurate score functions of data uncertainty through a bijective grouping function. To discover more effective partition rules, we introduce a technique that incorporates a linear layer onto the deep model's features, enabling the modeling of the partition function. By employing softmax to generate a soft partition, we achieve end-to-end optimization. By generating diverse partition functions, our approach facilitates calibration across different semantic domains, thereby enhancing overall calibration performance without losing accuracy. Experimental results across multiple datasets and network architectures consistently demonstrate the efficacy of our method in improving calibration. Figure 1: We reconstruct CIFAR10 into a binary classification problem (\([0-4]\) as positives, \([5-9]\) as negatives) and train a Resnet152 on it. Initially, the predicted probabilities are severely uncalibrated, as shown in (a). Then we train an Isotonic regression (IR) model (with the test labels) to calibrate outputs, which leads to nearly perfect calibration in (b). However, the partitions defined by original labels may reveal underlining miscalibration. For example, let \(G_{1}=\{0,1,2,5,6,7\},G_{2}=\{3,4,8,9\}\). The outputs of IR turned out to be significantly overconfident on \(G_{1}\) and underconfident on \(G_{2}\). Partitioned calibration error and grouping-based calibration We first present our formulation of PCE, which serves as the foundation for our calibration approach. ### Measuring calibration with partitions We start by defining the partition by a grouping function as follows. **Definition 1** (Grouping function and input space partition).: _A grouping function \(g\) is a mapping from an input \(x\) to a group indicator \(g(x)=G\in\mathcal{G}\), with the following two properties:_ \[\forall x_{1},x_{2},g(x_{1})\neq g(x_{2})\to x_{1}\neq x_{2} \tag{1}\] \[\forall\hat{G}\in\mathcal{G},\exists\hat{x}\in\mathcal{D},g(\hat {x})=\hat{G} \tag{2}\] The group indicator \(G\) is also used to denote the induced subset \(\{x|g(x)=G\}\). **Lemma 1**.: _A partition of the input space \(\mathcal{D}\) is defined by \(P=\{\{x|g(x)=\hat{G}\}|\hat{G}\in\mathcal{G}\}\)._ **Proof**. By definition, the subsets in \(P\) are non-overlapping (by Eq. (1)), and non-empty (by Eq. (2)), which guarantees \(P\) being a valid partition on set \(\mathcal{D}\) of all valid \(x\). With the partition defined above, we can now define the partitioned calibration error. **Definition 2** (**Partitioned calibration error (PCE))**.: \[\mathrm{PCE}(S,g,\mathcal{L},f,\mathcal{D})=\sum_{P\in\mathcal{P}}p(P)\sum_{ G\in P}p(G)\mathcal{L}(S(G),S(f(G)))\] (3) Where \(\mathcal{P}\) is the set of all concerned partitions, \(p(P)\) is the probability of choosing partition \(P\), \(p(G)=\int_{(x,y)\in G}p(x,y)\) is the probability of observing a data sample belonging to group \(G\), \(S(\cdot)\) is a specific statistical magnitude that can be calculated on a group. A straightforward definition of \(S(\cdot)\) is the average function \(S(G)=\int_{x,y}p_{G}(x,y)y\), and \(S(f(G))=\int_{x,y}p_{G}(x,y)f(x)\), where \(y\) is the one-hot label with \(y_{i}=1\) if \(x\in i\) th class and \(y_{i}=0\) otherwise. \(f(x)_{i}\) is the predicted probability of \(x\) being \(i\)th class. \(\mathcal{L}(\cdot,\cdot)\) measures the difference between \(S(G)\) and \(S(f(G))\). \(p_{G}(x,y)\) is the normalized probability density function of \(x\in G\), that is, \[p_{G}(x,y)=\begin{cases}0,&\text{ if }x\notin G\\ \frac{p(x,y)}{p(G)},&\text{ if }x\in G\end{cases} \tag{4}\] We will write \(p_{G}(x,y)\) as \(p_{G}\) in the following contents for simplicity. In summary, the aforementioned Eq. (3) defines PCE, which quantifies the expected disparity between the predicted probabilities and the true probabilities within each subgroup, after randomly selecting a partition. **Example 1** (**Expected calibration error (ECE)[23]**).: _With \(g(x)=\mathrm{Bin}(f(x))\), where \(\mathrm{Bin}(\cdot)\) returns the corresponding Bin ID, \(\mathcal{L}(a,b)=|a-b|\), and keep \(S\) as the average function._ \[\mathrm{PCE}=\sum_{G\in P}p(G)\mathcal{L}(S(G),S(f(G)))=\sum_{G\in P}p(G)|\int_ {x,y}p_{G}f(x)-\int_{x,y}p_{G}y| \tag{5}\] _and its empirical estimation is_ \[PCE=\sum_{G}\frac{|G|}{|D|}|\sum_{(x,y)\in G}\frac{1}{|G|}f(x)-\sum_{(x,y)\in G }\frac{1}{|G|}y| \tag{6}\] _which is exactly the ECE estimator defined in [23] Eq.3._ Note that in the above ECE, there is only one partition. We provide an example of using multiple partitions in the following example. **Example 2** (**Class-wise ECE[12]**).: _There are \(M\) partitions corresponding to \(M\) classes. The partition of class \(u\) is denoted by \(P_{u}\), the corresponding grouping function is defined by \(g_{u}(x)=\mathrm{Bin}(f(x)_{u})\)._ \[\mathrm{Classwise-ECE}=\sum_{P_{u}}\frac{1}{M}\sum_{G\in P_{u}}\frac{|G|}{|D|} |\sum_{(x,y)\in G}\frac{1}{|G|}f(x)-\sum_{(x,y)\in G}\frac{1}{|G|}y| \tag{7}\] _which is exactly the same as Eq. 4 in [12]._ **Example 3** (**Top-label calibration error (TCE)[25]**).: _With \(g(x)=\operatorname{Bin}(\max_{i}f(x)_{i})\), \(S(G)=\frac{1}{|G|}\sum\mathbb{I}(y=\operatorname*{arg\,max}_{i}f(x)_{i})\), and \(S(f(G))=\frac{1}{|G|}\sum_{(x,y)\sim G}\max_{i}f(x)_{i}\). Resulting in the Top-label calibration error defined in [25]._ From the above examples, it can be observed that the sole distinction among the aforementioned calibration metrics lies in the employed grouping function. Hereinafter, we shall delve into two distinctive scenarios of PCE to shed light on the intricate interplay between calibration and accuracy. **Example 4** (**One-to-one grouping function**).: _If the grouping function \(g(\cdot)\) is a bijection, then every different \(x\) belongs to different groups, which corresponds to point-wise accuracy._ \[\operatorname{PCE}=\sum_{P\in\mathcal{P}}p(P)\sum_{G\in P}p(G)\mathcal{L}(S(G ),S(f(G)))=\int_{x,y}p(x,y)\mathcal{L}(y,f(x)) \tag{8}\] Minimizing this PCE with bijective grouping function will converge to \(f(x)=p(y|x)\) if a proper score function \(\mathcal{L}\) (e.g., cross-entropy or Brier score[26]) is used with unlimited data. The uncertainty reflected by \(p(y|x)\) is called aleatoric uncertainty[27] and is the best a model can achieve corresponding to Bayes error[28; 29]. **Example 5** (**Constant grouping function**).: _If the grouping function \(g\) is a constant function with \(\forall x_{1},x_{2},g(x_{1})=g(x_{2})\), then every different \(x\) belongs to a single group._ \[\operatorname{PCE}=\mathcal{L}\left(\int_{x,y}p(x,y)f(x),\int_{x,y}p(x,y)y\right) \tag{9}\] _which is minimized by the model outputs the marginal distribution \(f(x)=\int_{(x,y)}p(x,y)y=p(y)\)._ We provide proofs and further discussion about Example. (4) and Example. (5) in the supplementary materials. The constant grouping function captures the vanilla uncertainty that we do not have any knowledge about \(x\), and we only know the marginal distribution of \(y\). The above analysis demonstrates that by employing finer partitions, PCE becomes a closer approximation to the measure of accuracy. Conversely, coarser partitions align more closely with the traditional calibration metrics utilized in prior research. Since neither extreme partitioning approach applies to practical calibration, selecting an appropriate partitioning method is crucial for calibration performance. ### Calibration with sematic-aware partitions Calibration methods can be designed from the perspective of minimizing the corresponding PCE. For instance, histogram binning[7] adjusts the predicted probabilities within each bin to the mean of the true probabilities in that bin. On the other hand, Bayesian Binning into Quantiles (BBQ)[11] calibration involves setting multiple distinct bin counts and then obtaining a weighted average of the predictions from histogram binning for each bin count, effectively encompassing scenarios with multiple partitions in the PCE. However, existing methods rely on binning and calibration based solely on model output probabilities. Our proposed PCE suggests that the partitioning approach can depend not only on the predicted probabilities but also on the information in input \(x\) itself. This would significantly enhance the flexibility of the partitions. To facilitate implementation, we begin by imposing certain constraints on the range of outputs from the grouping function. We denote the number of partitions by \(U=|\mathcal{P}|\), and we assume that all data can be partitioned into \(K\) groups. The output of the grouping function \(g\) takes the form of a one-hot encoding, where if \(x\) belongs to the \(i\)-th group, \(g(x)_{i}=1\), while all other \(g(x)_{j}=0\). And \(G_{i}=\{x|g(x)_{i}=1\}\) is the \(i\)-th group. Under these conditions, the expression for PCE can be formulated as follows: \[\operatorname{PCE}=\sum_{i}^{K}\frac{|G_{i}|}{|D|}\mathcal{L}(S(G_{i}),S(f_{G_ {i}}(G_{i}))) \tag{10}\] From the above equation, it is evident that for each group \(G_{i}\), we can learn a calibration function \(f_{G_{i}}\) specific to that group, which aims to minimize the calibration error within the group \(G_{i}\). In this paper, we employ the temperature scaling method as the learning approach for the calibration function within each group. Specifically, temperature scaling involves adding a learnable temperature parameter \(\tau\) to the logits \(o(x)\) (i.e., the input to the softmax function) of the model and applying it to a group, resulting in the following form: \[\mathcal{L}(S(G_{i}),S(f_{G_{i}}(G_{i})))=\frac{1}{|G_{i}|}\sum_{x,y\in G_{i}} \log\frac{e^{\frac{o(x)y}{\tau_{i}}}}{\sum_{j}e^{\frac{o(x)_{j}}{\tau_{i}}}} \tag{11}\] where the temperature parameter \(\tau_{i}\) is specific to group \(G_{i}\). In the aforementioned equation, we assume that the groups \(G_{i}\) are known. In order to optimize the partition, we incorporate the grouping function \(g(\cdot)\) into the loss function. By summing the above equation over all groups according to Eq. (10), we can obtain the final optimization objective. \[\mathcal{L}_{GC+TS}=\frac{1}{|D|}\sum_{x,y\in D}\log\sum_{i}g(x)_{i}\frac{e^{ \frac{o(x)y}{\tau_{i}}}}{\sum_{j}e^{\frac{o(x)_{j}}{\tau_{i}}}} \tag{12}\] When the output of \(g(x)\) is in the form of one-hot encoding, the above equation represents a standard grouping loss function. To optimize \(g\), we introduce a smoothing technique that transforms its output into a probability value. Specifically, we add a linear layer on top of the neural network's features \(z\) and follow it with a softmax function as the grouping function \(g\), which takes the following form: \[g_{\phi}(x)=g_{\phi}(z(x))=\mathrm{softmax}(z(x)\phi_{w}+\phi_{b}) \tag{13}\] where \(z\in\mathbb{R}^{|D|\times d_{z}}\), \(\phi_{w}\in\mathbb{R}^{d_{z}\times K}\), \(\phi_{b}\in\mathbb{R}^{1\times K}\). The features \(z(x)\) are fixed, which aligns with the post-calibration setting. The above loss function is the combination of grouping and temperature scaling, which is denoted as Grouping Calibration + Temperature Scaling (GC+TS). **Training \(g_{\phi}(x)\)**. The parameters \(\phi\) of grouping function \(g\) is trained jointly with the calibration function \(f_{\theta}\) on the validation dataset \(D_{val}\) (used in early stopping when training deep models). In the GC+TS method, the trainable parameters of \(f\) is \(\theta=\{\tau_{i}\}\). In a more intuitive sense, equation Eq. (12) necessitates that the grouping function identifies the optimal partitioning, where adjusting \(\tau_{i}\) within each subgroup \(G_{i}\) minimizes the cross-entropy loss. Furthermore, due to the non-uniqueness of the optimal grouping function that satisfies the aforementioned objective function, we can generate multiple distinct partitions by optimizing with different initial values through multiple iterations. To mitigate the potential overfitting caused by the high flexibility of the grouping function \(g\), we have introduced an additional regularization term, and the overall training loss of training \(g_{\phi}\) is \(\mathcal{L}_{GC+TS}+\lambda||\phi_{w}||_{2}^{2}\). **Training \(f_{\theta}(x)\)**. After training of \(g_{\phi}\), we simply apply a calibration method to each group. We can also use temperature scaling in this phase while using hard grouping in Eq. (12). Any other calibration methods are also applicable, for example, we also adopt ETS method to obtain GC+ETS in our experiments. The calibration function \(f_{\theta}\) is trained on the holdout training dataset \(D_{ho}\), while keeping the grouping function fixed. Then the calibration function \(f\) is used on each group of the testing dataset. The overall training and predicting procedure is summarized in Algorithm. 1. ``` 0:\(D_{val}=\{Z_{val},O_{val},Y_{val}\},D_{ho}=\{Z_{ho},O_{ho},Y_{ho}\},D_{test}=\{Z _{test},O_{test}\},U,K,\lambda\) 0: Calibrated \(\hat{Y}_{test}\) 1:for\(u\gets 0\) to \(U-1\)do 2: Randomly initialize \(\phi_{u}\) and \(\theta_{u}\) 3: Optimize \(\phi_{u}\) and \(\theta_{u}\) on \(D_{val}\) to minimize Eq. (12) with L-BFGS[30] 4: Optimize \(\theta_{ui}\) on \(D_{ho}\) to minimize Eq. (10) with base calibration method(e.g., TS) 5: Calculate partition \(P_{u}=\{G_{ui}\}\) with grouping function \(g_{\phi_{u}}\) on \(D_{test}\) 6:for\(i\gets 0\) to \(K-1\)do 7: Calibrate \(G_{ui}\) with \(f_{\theta_{ui}}(\cdot)\) to obtain \(\hat{Y}_{ui}\) 8:endfor 9:Merge predicts in different groups \(\hat{Y}_{u}=\{\hat{Y}_{ui}\}\) 10:endfor 11: Ensemble predicts in different partitions \(\hat{Y}_{test}=\frac{1}{U}\sum_{u}\hat{Y}_{u}\) ``` **Algorithm 1** Train group calibration with temperature scaling (GC+TS) **On the usage of \(D_{val}\) and \(D_{ho}\)**. Guo et al. [7] explicitly states that the validation dataset \(D_{val}\) used for early stopping can be used for calibration, while most researchers use a hold-out dataset \(D_{ho}\) that is not used during training for calibration[12; 23; 25]. Experimentally, we found that calibrating with \(D_{val}\) is significantly worse than \(D_{ho}\) for existing calibration methods. Interestingly, the grouping function trained on the \(D_{val}\) can transfer to \(D_{ho}\) for improving performance, which means the training of \(g_{\phi}\) does not require additional data. We investigate this problem in the supplementary in detail. An essential characteristic of calibration methods is their ability to preserve accuracy[23], ensuring that the classes with the highest probabilities remain unchanged after the calibration process. **Theorem 1** (**Accuracy-preserving of group calibration)**.: _Group calibration with any group-wise accuracy-preserving base calibration method is also accuracy-preserving._ **Proof Sketch.** Since the groups are disjoint, group-wise accuracy-preserving remains overall accuracy-preserving. Ensembles of accuracy-preserving predictions are also accuracy-preserving. The Theorem. 1 guarantees our group calibration method remains accuracy-preserving with accuracy-preserving base methods such as temperature scaling[7] or ensemble temperature scaling [23]. ## 3 Experiments To evaluate the performance of our method under various circumstances, we selected three datasets: CIFAR10, CIFAR100[31], and Imagenet[1]. We employed different models for each dataset to reflect our approach's calibration capability across various model accuracy levels. The models used in our experiments include Resnet[2], VGG[32], Densenet[33], SWIN[34], and ShuffleNet[35]. We randomly partitioned a validation set \(D_{val}\) from the standard training set: CIFAR10 and CIFAR100 adopted 10 We performed 100 different test set splits for each dataset-model combination to obtain reliable results and reported the average performance over 100 trials for each method. We conduct paired t-test[36] to measure the static significance of the improvements. The hyperparameters of the comparative methods were tuned based on the corresponding literature with 5-fold cross-validation on the CIFAR10-Resnet152 dataset. We fixed the number of groups at \(K=2\) and the number of partitions at \(U=20\), although 20 is not necessarily the optimal value. The strength of regularization was set to \(\lambda=0.1\), following a similar tuning approach as the comparative methods. ### Experimental comparison **Accuracy preserving methods**. We compared our approach with methods that offer accuracy assurance, including uncalibrated (Uncal), temperature scaling (TS)[7], Ensemble Temperature Scaling (ETS)[23], and multi-class isotonic regression with accuracy-preserving2 (IRM(AP))[23] methods. From Table. (1), it can be observed that our method achieves the best performance on the majority of datasets, and the improvement is statistically significant. Another noteworthy aspect is the enhancement our method demonstrates when compared to the base methods without partitioning, namely GC+TS compared to TS, and GS+ETS compared to ETS. We have provided the average \begin{table} \begin{tabular}{l l l l l l l l} \hline \hline Dataset & Model & Uncal & TS & ETS & IRM(AP) & GC+TS(ours) & GC+ETS(ours) \\ \hline CIFAR10 & Resnet152 & 0.0249 & 0.0086 & 0.0101 & 0.0115 & **0.0079** & 0.0089 \\ CIFAR10 & Shufflenet & 0.0464 & 0.0107 & 0.0103 & 0.0146 & 0.0099 & **0.0093** \\ CIFAR10 & VGG11 & 0.0473 & 0.0125 & 0.0135 & 0.0157 & **0.0120** & **0.0122** \\ \hline CIFAR100 & Densenet121 & 0.0558 & 0.0418 & 0.0289 & 0.0415 & 0.0411 & **0.0280** \\ CIFAR100 & Resnet50 & 0.0580 & 0.0435 & 0.0292 & 0.0424 & 0.0427 & **0.0269** \\ CIFAR100 & VGG19 & 0.1668 & 0.0485 & 0.0472 & 0.0476 & 0.0414 & **0.0360** \\ \hline Imagenet & Resnet18 & 0.0279 & 0.0178 & 0.0104 & 0.0188 & 0.0173 & **0.0100** \\ Imagenet & Resnet50 & 0.0382 & 0.0182 & **0.0102** & 0.0218 & 0.0174 & **0.0103** \\ Imagenet & Swin & 0.0266 & 0.0367 & 0.0218 & **0.0140** & 0.0366 & 0.0193 \\ \hline \multicolumn{8}{l}{Average improvements} & & & & **-5.03\%** & **-8.92\%** \\ \hline \hline \end{tabular} \end{table} Table 1: Comparison of accuracy-preserving calibration methods. We utilized bold font to highlight the statistically superior (\(p<0.01\)) results. improvement relative to the corresponding base methods in the last row of Table 1. Specifically, GC+TS shows an average improvement of 5.03 **Non-accuracy preserving methods**. We also compared our method with calibration approaches that do not guarantee accuracy, including Histogram Binning(Hist.B)[7], Beta Calibration (Beta)[10], Bayesian Binning into Quantiles (BBQ)[11], Dirichlet calibration with ODIR regularisation (DirODIR)[12], multi-class isotonic regression without accuracy-preserving (IRM(NAP))[23] and Gaussian process calibration(GPC)[24]. The comparative results are presented in Table. (2). It can be observed that our method achieves improved calibration performance while maintaining the same predictive accuracy. On the majority of datasets, our method either meets or surpasses the best non-accuracy-preserving methods. We have also included in Table. (2) the influence of the non-accuracy-preserving method with the lowest ECE on predictive accuracy. It is evident that these methods generally have a noticeable negative impact on model accuracy. In contrast, our proposed method preserves the predictive results, ensuring that the predictive accuracy remains unchanged. We provide all the details and codes of the experiments in the supplementary material, as well as a few additional evaluation metrics (NLL, Birer score) and methods (vector scaling, isotonic regression, etc.)[7], which also supports that our method performs best. ### Verifying effects of grouping functions **Quantitative analysis**. We conduct experiments on the constructed setting described in Figure. 1 with TS and our GC+TS method. TS has ECE=\(0.0157\), and GC+TS has ECE=\(0.0118\). We calculate the PCE with the partitions learned by our GC method, and PCE of TS=\(0.0174\), PCE of GC+TS=\(0.0141\), which indicates that GC+TS does improve the overall calibration performance by minimizing PCE. **Visualization of learned partitions**. To explore the partition functions learned by our method, we visualized the output results of the grouping function on the CIFAR10-Resnet152 dataset. Specifically, \begin{table} \begin{tabular}{l l l l l l l l l} \hline \hline Dataset & Model & Hist.B & Beta & BBQ & DirODIR & GPC & IRM(NAP) & Acc. Dec. & GC+ETS (ours) \\ \hline CIFAR10 & Resnet152 & 0.0172 & 0.0095 & 0.0097 & 0.0101 & 0.0189 & _0.0087_ & -0.079\% & **0.0089** \\ CIFAR10 & Shuffnet & 0.0322 & 0.0137 & 0.0139 & 0.0158 & 0.0341 & _0.0119_ & -0.050\% & **0.0093** \\ CIFAR10 & VGG11 & 0.0279 & 0.0150 & 0.0137 & 0.0156 & 0.0376 & _0.0119_ & -0.129\% & **0.0122** \\ \hline CIFAR100 & Densenet121 & 0.0632 & 0.0520 & 0.0307 & 0.0533 & 0.0306 & _0.0203_ & -0.149\% & **0.0280** \\ CIFAR100 & Resnet50 & 0.0618 & 0.0550 & _0.0334_ & 0.0553 & 0.0346 & 0.0422 & -3.686\% & **0.0269** \\ CIFAR100 & VGG19 & 0.0453 & 0.0642 & _0.0446_ & 0.0932 & 0.1406 & 0.0470 & -5.046\% & **0.0360** \\ \hline Imagenet & Resnet18 & 0.0714 & 0.0690 & 0.0483 & 0.0386 & - & _0.0119_ & -0.027\% & **0.0100** \\ Imagenet & Resnet50 & 0.0502 & 0.0707 & 0.0482 & 0.0326 & - & _0.0107_ & -0.006\% & **0.0103** \\ Imagenet & Swin & 0.0335 & 0.0629 & 0.0478 & 0.0148 & - & _0.0110_ & -0.060\% & 0.0193 \\ \hline \hline \end{tabular} * GPC failed to converge within a day on Imagenet datasets. \end{table} Table 2: Comparison of non-accuracy-preserving calibration methods. Figure 2: Visualization of learned grouping function on CIFAR10. we calculated the proportion of each class within each group and visualized two representative partitions in Figure. 2. In the left figure, group 1 primarily consists of airplanes, cars, birds, frogs, ships, and trucks. These classes may share certain visual characteristics like blue sky and water, which implies that the model's predictions might exhibit systematic overconfidence or underconfidence within these categories. Applying a group-specific calibration function to this group can help mitigate miscalibration issues. In the right figure, group 1 mainly comprises cats, deer, and dogs, which also share some visual features. To conclude, our proposed method can implicitly uncover meaningful partitions from the data despite not directly defining a partitioning approach. ### Ablation study We conducted experiments on the CIFAR10-Resnet152 dataset to investigate the impact of three hyperparameters in our method: the number of partitions, the number of groups within each partition, and the regularization strength used in the grouping function. The results are presented in Figure. 3. We observed that as the number of groups decreases, both NLL (negative log-likelihood) and ECE generally exhibit a monotonic increase. We attribute this trend to the fact that increasing the number of groups leads to fewer data points within each group, exacerbating model overfitting. On the other hand, as the number of partitions increases, the calibration performance consistently improves. This finding suggests that training on multiple distinct partitions can enhance the model's performance across various partitions, thereby improving the model's overall performance. This can be viewed as incorporating prior knowledge into the model, indicating that the model's predictions should be well-calibrated across any partition. The influence of the regularization strength hyperparameter in the grouping function is depicted in Figure. 4. It can be observed that when the regularization strength is too high (i.e., a value of 1), the calibration performance is poorer. This suggests that in such cases, the expressive power of the grouping function is insufficient to learn meaningful groups that aid in calibration. Conversely, when the regularization strength is too low, the performance also deteriorates because the grouping function's expressive power is excessive, leading to the learning of partition functions that are specific to the training set and lack generalization. ## 4 Related Work We provide a concise overview of recent academic research on the definition, evaluation, and advancements in calibration methods. **Measures of calibration**. As discussed in Section. 2.1, calibration, being a collective concept without direct labels, is typically evaluated by binning the predicted probabilities using different binning approaches. Various studies have proposed different binning methods, each focusing on a different aspect. For example, Kumar et al. [25] proposed binning based on the maximum predicted probability, Kull et al. [12] introduced binning using probabilities for all classes, and Zhang et al. Figure 4: Influence of \(\lambda\) Figure 3: The influence of the number of partitions and the number of groups in each partition. [23], Popordanoska et al. [37], Kumar et al. [38] proposed kernel methods, which can be seen as a smoothed binning approach. In our framework, these methods can be considered as applying different grouping functions, where the grouping functions solely utilize the predicted probabilities. Additionally, other studies have explored alternative characteristics of calibration. For instance, Vaicancavicius et al. [22] and Gupta et al. [14] proposed hypothesis testing methods to assess whether the predicted probabilities approximate calibration, which is still defined solely on the predicted probabilities. Proper scoring rules such as likelihoods and Brier scores are also used to evaluate calibration[26; 39], which are typically used as a training loss to improve calibration. The calibration considering fairness[40; 41] is also highly related to this work, where the calibration within different populations is considered. However, our work concentrates on learning a better grouping function to improve holistic calibration performance, rather than calibrating some given groups[41]. **Improving calibration of deep models**. The calibration of deep models can be categorized into two main directions. The first direction involves calibrating the model during the training phase by modifying the training process itself[23; 42; 43; 26; 44]. This may include using specialized loss functions tailored for calibration[45], employing ensemble methods[26; 46], or data augmentation[47], etc. However, such approaches require modifications to the training phase and may entail relatively higher computational costs. The second direction focuses on calibrating the model during the prediction phase. These methods are highly related to the definition of calibration metrics, which involves minimizing the discrepancy between model predictions and aggregated statistics within each bin. The simplest method is histogram binning[7; 48], where predicted probabilities are directly adjusted to match the actual class proportions within each bin. BBQ[11], on the other hand, proposes an ensemble approach that calibrates results obtained with different numbers of bins. This can be seen within our framework as utilizing multiple partitions, where the partitioning method is explicitly defined. The transformation functions applied to predictions can also be improved beyond averaging within bins. For example, Beta distribution can fit the probability transformation for binary classification[10], while Dirichlet distribution can be employed for multi-class transformation[12]. New families of transformation functions have been proposed to preserve the ordering of predicted probabilities while improving calibration performance[13]. Additionally, ensemble methods have been proposed to ensure accuracy guarantees with different families of functions[23]. Our method is orthogonal to existing calibration methods since the underlying motivation of existing methods is to minimize the calibration error within a single group. On the one hand, our method offers greater flexibility as we can employ different calibration functions for different groups. On the other hand, our method goes beyond solely relying on probabilities by utilizing the features of deep neural networks, which enhances the calibration capability and significantly increases the amount of effective information utilized. ## 5 Conclusion and limitations This paper proposes a novel approach to define model uncertainty calibration from the perspective of partitioning the input space, thereby unifying previous binning-based calibration metrics within a single framework. Additionally, we extend the notion of calibration beyond output probabilities, allowing it to be defined on semantically relevant partitions. We establish a connection between calibration and accuracy metrics using semantically relevant partitions. Furthermore, our analysis inspires introducing a method based on learning grouping functions to discover improved partitioning patterns, thus aiding in learning the calibration function. Our framework holds substantial potential for further development, such as optimizing subset selection methods and refining model design, which will be our future work. **Limitations**. Increasing the number of partitions or employing more complex grouping models will result in higher computational complexity, which is a limitation of our method. Nevertheless, when compared to other Bayesian methods[11; 12; 24], our method demonstrates notably faster speed. We present analysis and experimental comparisons of computational complexities in the supplementary material. Due to the reliance of our method on the features extracted from deep models, it is not applicable for calibrating non-deep models such as tree models[49] and SVMs[12; 50].
2305.09729
FedHGN: A Federated Framework for Heterogeneous Graph Neural Networks
Heterogeneous graph neural networks (HGNNs) can learn from typed and relational graph data more effectively than conventional GNNs. With larger parameter spaces, HGNNs may require more training data, which is often scarce in real-world applications due to privacy regulations (e.g., GDPR). Federated graph learning (FGL) enables multiple clients to train a GNN collaboratively without sharing their local data. However, existing FGL methods mainly focus on homogeneous GNNs or knowledge graph embeddings; few have considered heterogeneous graphs and HGNNs. In federated heterogeneous graph learning, clients may have private graph schemas. Conventional FL/FGL methods attempting to define a global HGNN model would violate schema privacy. To address these challenges, we propose FedHGN, a novel and general FGL framework for HGNNs. FedHGN adopts schema-weight decoupling to enable schema-agnostic knowledge sharing and employs coefficients alignment to stabilize the training process and improve HGNN performance. With better privacy preservation, FedHGN consistently outperforms local training and conventional FL methods on three widely adopted heterogeneous graph datasets with varying client numbers. The code is available at https://github.com/cynricfu/FedHGN .
Xinyu Fu, Irwin King
2023-05-16T18:01:49Z
http://arxiv.org/abs/2305.09729v1
# FedHGN: A Federated Framework for Heterogeneous Graph Neural Networks ###### Abstract Heterogeneous graph neural networks (HGNNs) can learn from typed and relational graph data more effectively than conventional GNNs. With larger parameter spaces, HGNNs may require more training data, which is often scarce in real-world applications due to privacy regulations (e.g., GDPR). Federated graph learning (FGL) enables multiple clients to train a GNN collaboratively without sharing their local data. However, existing FGL methods mainly focus on homogeneous GNNs or knowledge graph embeddings; few have considered heterogeneous graphs and HGNNs. In federated heterogeneous graph learning, clients may have private graph schemas. Conventional FL/FGL methods attempting to define a global HGNN model would violate _schema privacy_. To address these challenges, we propose FedHGN, a novel and general FGL framework for HGNNs. FedHGN adopts _schema-weight decoupling_ to enable schema-agnostic knowledge sharing and employs _coefficients alignment_ to stabilize the training process and improve HGNN performance. With better privacy preservation, FedHGN consistently outperforms local training and conventional FL methods on three widely adopted heterogeneous graph datasets with varying client numbers. The code is available at [https://github.com/cymircfu/FedHGN](https://github.com/cymircfu/FedHGN). ## 1 Introduction Graph neural networks (GNNs) [5, 12, 13, 14, 15] combine graph representation learning and deep learning to handle graph-structured data more effectively than traditional methods [16, 17, 18, 19]. GNNs have various applications, such as community detection [14, 15], recommender systems [16, 17, 18, 19, 20, 21], traffic forecasting [12, 22, 23], and text similarity [14, 24]. However, many real-world graphs are _heterogeneous graphs_, which have multiple types of nodes and edges. For instance, a financial network may consist of customers, merchants, transactions, and various relationships among them. Therefore, researchers have developed heterogeneous GNNs (HGNNs), such as RGCN [15], to capture the complex semantics in heterogeneous graph structures. Similar to other deep learning models, GNN performance depends on the size of the training data. If the training data is insufficient, GNNs may overfit and fail to generalize to unseen data. This problem is more severe for HGNNs, which have much larger parameter spaces [15]. Moreover, in reality, adequate training data is often unavailable, which hinders HGNN's performance. One possible solution to data scarcity is to collect and integrate samples from multiple parties to create a large shared dataset for model training. However, this approach raises serious privacy concerns in many application scenarios, which prevent HGNNs from using training data in a centralized way. For instance, banks and insurance companies may want to collaborate on developing an HGNN for better fraud detection. But their data, such as customer information and transaction records, are highly sensitive. They cannot transmit these data to another place for HGNN training. Therefore, there is a trade-off between data availability and data privacy. HGNNs trained separately at each client (e.g., a financial institution in this case) would perform poorly due to limited training data, while centralized training by aggregating data from all clients is not feasible due to commercial or regulatory reasons (e.g., GDPR). This leads to a question: can we train an HGNN that leverages each client's training data without violating local data privacy? Federated learning (FL) is a promising technique to achieve this goal. Instead of sharing private data, FL clients upload model weights to a central server which aggregates them to improve the global model. The collaboratively trained model is expected to outperform the models trained locally at each client. Previous FL frameworks mainly focused on computer vision (CV) and natural language processing (NLP) tasks [15, 16, 17]. Federated graph learning (FGL), i.e., FL on graph-structured data, has just emerged in recent years. Some works have explored FGL in homogeneous graphs [22, 23], recommender systems [24], and knowledge graphs [14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 92, 93, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 76, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 93, 94, 95, 96, 97, 98, 99, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 94, 95, 96, 97, 98, 99, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 72, 73, 74, 75, 76, 78, 79, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, Peng _et al._, 2021]. However, FL with heterogeneous graphs and HGNNs, which have a great need for collaborative training, has received little attention. Real-world federated heterogeneous graph learning faces two unique challenges. First, unlike homogeneous graphs, heterogeneous graphs have special metadata called graph schemas. These are meta templates that describe the node types and edge types of the graph. For example, Figure 1 shows a graph schema of a scholar network. The problem is, _clients may not want to share the schema information_, which is essential to define an HGNN model. The graph schema reveals high-level information about how the graph is constructed, which may be sensitive in some domains, such as pharmaceutical companies and financial institutions. Second, even if schema sharing is allowed among clients, _it is usually difficult to match node/edge types of different graphs with each other_, which is crucial for HGNNs to reduce complexity and share knowledge. In a federated system, different clients may use different pipelines to construct their heterogeneous graphs. For instance, one client may label their paper nodes as _paper_ while another may call them _article_. This matching process may not always have the domain knowledge and human expertise available. Moreover, when a new client joins the federated system, this schema matching process needs to be repeated, and the HGNN may need to be re-defined to include new node/edge types, both of which are undesirable for industrial FL applications. Motivated by the lack of an FGL framework for HGNNs and the challenges above, we propose **FedHGN**, a _Federated learning framework for HGNNs_ that preserves schema privacy and avoids schema matching. The key idea of FedHGN is to eliminate the direct correspondence between graph schemas and HGNN model weights. We achieve this by applying _schema-weight decoupling_ to decompose HGNN weights into shareable schema-agnostic basis weights and confidential schema-specific coefficients. To prevent the potential discrepancy between coefficients of the same/similar schemas at different clients, FedHGN employs _coefficients alignment_ to minimize the distance between coefficients of most similar node/edge types. Thus, FedHGN enables collaborative training for better-performing HGNNs without sacrificing schema privacy or necessitating schema matching. In summary, we make the following main contributions: * We propose FedHGN, a novel FGL framework that enables collaborative HGNN training among clients with private heterogeneous graphs. To our knowledge, this is the first work for general federated HGNN learning. * We propose a schema-weight decoupling (SWD) strategy to achieve schema-agnostic knowledge sharing, which preserves schema-level privacy among clients. * We design a schema coefficients alignment (CA) component via a novel regularization term, which stabilizes FedHGN training and improves HGNN performance. * We conduct extensive experiments on benchmark datasets with varying numbers of clients for node classification. Results show that FedHGN consistently outperforms local training and conventional FL methods. ## 2 Related Work In this section, we review recent studies related to this work. Section 2.1 introduces graph neural networks (GNNs) and especially heterogeneous GNNs. Section 2.2 introduces conventional federated learning (FL) and recent efforts on federated graph learning (FGL). ### Graph Neural Networks Graph neural networks (GNNs) are designed to overcome the limitations of shallow graph embedding methods, such as DeepWalk [1] and node2vec [11]. Taking advantage of the neural network architecture, GNNs can leverage node attributes and benefit from various training paradigms of deep learning. The general idea of GNNs is to characterize each node by its own features and its local neighborhood's information. Following this idea and combined with graph signal processing, spectral-based GNNs like ChebNet [11] and GCN [12] were first developed to perform convolutions in the Fourier domain of a graph. Then, by allowing convolutions in the graph domain, spatial-based GNNs like GraphSAGE [14] and GAT [2] were proposed to improve scalability and generalization ability, with many follow-up studies [21, 22]. **Heterogeneous GNNs** Conventional GNNs assume homogeneous input graphs with single node/edge types. However, real-world graphs are usually heterogeneous, having multiple node/edge types. To capture complex structural and semantic heterogeneity in these graphs, researchers proposed heterogeneous GNNs (HGNNs). As an early attempt, RGCN [1] aggregates neighborhoods using relation-specific weights. Many other HGNNs follow similar ideas to project and aggregate neighborhoods based on node/edge types, including HetGNN [15], HGT [13], Simple-HGN [12], etc. Another line of research considers meta-paths to capture complex high-order relationships between nodes, such as HAN [22], MAGNN [10], and GTN [20]. Although many HGNNs claim to have good performance in real-world applications, none have considered the federated setting with privacy concerns across clients. They simply assume a centralized setting with all data readily available. With privacy restrictions, HGNNs trained with limited local data could suffer from degraded performance and biased predictions. Our proposed FedHGN offers a feasible way to collaboratively train better-performing HGNNs among multiple clients without sharing local graph data and graph schemas. Figure 1: An example graph schema of a scholar network consisting of authors (A), papers (P), and venues (V). ### Federated Learning Federated learning (FL) is a machine learning setting for collaborative cross-client model training without sharing raw data [14, 15]. Instead of gathering data to a central server, FL keeps data localized on each client and only shares model weights or gradients. Multiple FL algorithms have been proposed for regular data in Euclidean space, such as FedAvg [12], FedProx [11], and SCAFFOLD [1]. These FL algorithms are applied in CV and NLP, where data samples are naturally isolated from each other. But for graphs, especially in node-level and link-level tasks, nodes and edges as data samples are associated with each other. Naively migrating conventional FL frameworks might not bring optimal results for graph data. ### Federated Graph Learning Recently, some researchers have proposed FL methods for graphs, which are coined as federated graph learning (FGL). GCFL [13] employs a client clustering mechanism to reduce data heterogeneity in federated graph classification. FedSage [20] generates missing neighbors to mend dropped cross-client links caused by data isolation in an FGL system. FedGNN [20] conducts GNN-based recommendations on user devices with a privacy-preserving FGL framework. FedE [10] and FKGE [21] are federated algorithms for knowledge graph embedding (KGE). FedAlign [11] applies basis alignment and weight constraint on federated RGCN to improve personalization and convergence. However, few FGL algorithms have considered heterogeneous graphs and HGNNs. Aside from graph data (nodes/edges) and optional attributes, heterogeneous graphs also have special metadata called graph schemas. Naively applying existing FGL methods would lead to schema privacy breaches or require schema matching. FedE, FKGE, and FedAlign are the most related research works to our FedHGN, but they still have some notable limitations. Due to the inherent restriction of KGE algorithms, FedE and FKGE assume all or part of the entities/relations are already matched among clients. While our FedHGN does not require any entity/relation matching, reducing privacy concerns and human labor. FedAlign focuses on a particular HGNN model, namely RGCN. On the other hand, our FedHGN is a general framework compatible with almost any HGNN architecture. Moreover, FedHGN is equipped with the coefficients alignment component that can alleviate the discrepancy between same-type schema coefficients at different clients. ## 3 Preliminary This section gives formal definitions of some important graph and FL terminologies related to this work. Table 1 provides a quick reference to the notations used in this work. **Definition 1** (Heterogeneous Graph).: _A heterogeneous graph is defined as a graph \(\mathcal{G}=(\mathcal{V},\mathcal{E})\) associated with a node type mapping function \(\phi:\mathcal{V}\rightarrow\mathcal{A}\) and an edge type mapping function \(\psi:\mathcal{E}\rightarrow\mathcal{R}\). \(\mathcal{A}\) and \(\mathcal{R}\) denote the pre-defined sets of node types and edge types, respectively, with \(|\mathcal{A}|+|\mathcal{R}|>2\). The graph schema of \(\mathcal{G}\) is given by \(\mathcal{T}_{\mathcal{G}}=(\mathcal{A},\mathcal{R})\), which is essentially a graph of node types connected by edge types._ **Definition 2** (Heterogeneous Graph Neural Network).: _A heterogeneous graph neural network (HGNN) is a GNN model designed for representation learning on heterogeneous graphs. Generally, an HGNN layer can be formulated as_ \[\mathbf{h}_{v}=\mathrm{Trans}_{\phi(v)}\left(\mathrm{Reduce}\left(\{\mathrm{ Agg}_{r}(\mathcal{N}_{v}^{r}):r\in\mathcal{R}\}\right)\right), \tag{1}\] _where \(\mathrm{Agg}_{r}(\cdot)\) is an edge-type-specific neighborhood aggregation function parameterized by \(\mathbf{\theta}_{r}\), \(\mathrm{Reduce}(\cdot)\) is a function to combine (e.g., sum) aggregation results from different edge types, and \(\mathrm{Trans}_{\phi(v)}(\cdot)\) is a node-type-specific transformation parameterized by \(\mathbf{\theta}_{\phi(v)}\). Some HGNNs might contain additional schema-irrelevant parameters \(\mathbf{\theta}_{c}\)._ **Definition 3** (Federated Graph Learning).: _A federated graph learning (FGL) framework consists of a server and \(K\) clients. The \(k\)-th client holds its own graph dataset \(\mathcal{D}^{k}=\left(\mathcal{G}^{k},\mathbf{X}^{k}[,\mathbf{Y}^{k}]\right)\), where \(\mathcal{G}^{k}=\left(\mathcal{V}^{k},\mathcal{E}^{k}\right)\) is the graph, \(\mathbf{X}^{k}\) is the node feature matrix and \(\mathbf{Y}^{k}\) is the optional label matrix. The goal of FGL is to collaboratively train a shared graph model without disclosing clients' local data._ **Definition 4** (Federated Heterogeneous Graph Learning).: _Federated heterogeneous graph learning is a sub-category of FGL, where the graph \(\mathcal{G}^{k}\) owned by each client is heterogeneous. The graph schema \(\mathcal{T}_{\mathcal{G}^{k}}=(\mathcal{A}^{k},\mathcal{R}^{k})\) could be different or even kept private across clients._ ## 4 Methodology In this section, we propose FedHGN, a novel FGL framework for heterogeneous graphs and HGNNs. FedHGN aims to achieve improved HGNN performance on each client through collaborative training under a federated framework without sharing graph data, node/edge attributes, and graph schema. To attain this goal, FedHGN needs to separate graph schema from model weights before collecting and aggregating weights on the server side. Therefore, we first propose a schema-weight decoupling (SWD) strategy to enable schema-agnostic knowledge sharing in Section 4.1. Then, to alleviate the adverse side effects introduced by the decoupling \begin{table} \begin{tabular}{l|l} \hline \hline **Notation** & **Definition** \\ \hline \(\mathbb{R}^{n}\) & \(n\)-dimensional Euclidean space \\ \(x\), \(\mathbf{x}\), \(\mathbf{X}\) & Scalar, vector, matrix \\ \(\mathcal{V}^{k}/\mathcal{E}^{k}\) & The set of nodes/edges at client \(k\) \\ \(\mathcal{G}^{k}\) & A graph \(\mathcal{G}^{k}=\left(\mathcal{V}^{k},\mathcal{E}^{k}\right)\) at client \(k\) \\ \(\mathcal{A}/\mathcal{R}\) & The set of node/edge types \\ \(\mathcal{N}_{v}^{r}\) & Type-\(r\) edge connected neighbors of node \(v\) \\ \(\mathbf{h}_{v}\) & Hidden states (embedding) of node \(v\) \\ \(\mathbf{\theta}_{s}\) & Model parameters bound to node/edge type \(s\) \\ \(\mathbf{\theta}_{c}\) & Model parameters not bound to graph schema \\ \(\mathbf{v}\) & Basis weights (bases) \\ \(\mathbf{\beta}_{s}\) & Basis coefficients of node/edge type \(s\) \\ \(|\cdot|\) & The cardinality of a set \\ \hline \hline \end{tabular} \end{table} Table 1: Notations used in this paper. strategy, we design a coefficients alignment (CA) component in Section 4.2. Next, the overall FedHGN framework is depicted in Section 4.3. Finally, a privacy analysis of our proposed framework is conducted in Section 4.4. A graphical illustration of FedHGN is provided in Figure 2. ### Schema-Weight Decoupling If naively combining HGNN and conventional FL methods (e.g., FedAvg), the server and the clients would need to first coordinate for a global graph schema. Taking Figure 3 as an example, the resulting global graph schema is generated by matching the two clients' local schemas, which inevitably breaches schema privacy and involves human expertise. To avoid the privacy-sensitive schema matching process, we propose SWD to remove the correspondence between graph schemas and HGNN weights. For schema-specific weights \(\mathbf{\theta}_{s}^{k}\in\mathbb{R}^{d}\) of any node/edge type \(s\in\mathcal{A}\cup\mathcal{R}\) from an HGNN at client \(k\), one can apply basis decomposition by \[\mathbf{\theta}_{s}^{k}=\sum_{i=1}^{B}\beta_{s,i}^{k}\mathbf{v}_{i}^{k}, \tag{2}\] where \(\beta_{s,i}^{k}\in\mathbb{R}\) are schema-specific coefficients, \(\mathbf{v}_{i}^{k}\in\mathbb{R}^{d}\) are basis weights (or bases), and \(B\) is a hyperparameter specifying the number of bases. Here model weights are treated as flattened vectors for notational brevity. Without loss of generality, SWD can be easily extended to higher-dimensional weights. The bases \(\mathbf{v}_{i}^{k}\) are shared by all node/edge types, and not bound to the graph schema. They can be trained along with schema-irrelevant weights \(\mathbf{\theta}_{c}^{k}\) under the conventional FL paradigm. On the other hand, a small number of coefficients \(\mathbf{\beta}_{s}^{k}\in\mathbb{R}^{B}\) are schema-dependent. They are tuned locally at each client and do not participate in weight aggregation at the server. By applying SWD and sharing only bases, FedHGN achieves schema-agnostic knowledge sharing, which avoids graph schema leakage and manual schema matching. ### Coefficients Alignment Due to the randomness throughout training, the non-convex nature of the objective, and the non-IID heterogeneous graph data among clients, schema-specific coefficients \(\mathbf{\beta}_{s}^{k}\) corresponding to the same node/edge type at different clients might diverge from each other towards distinct directions in the FL training process. This discrepancy between schema coefficients among clients may lead to unstable training, prolonged convergence, and sub-optimal results. Suppose the central server knows the matchings between schema coefficients among clients, this discrepancy issue can be easily resolved by aggregating and synchronizing them between the server and the clients. However, this strong assumption violates schema privacy and requires schema matching, which is not allowed in federated heterogeneous graph learning. To address the discrepancy issue without compromising the setting, we devise a heuristic approach to align the schema coefficients by enforcing a client-side loss constraint onto them. Intuitively, even though schema coefficients of the same node/edge type at different clients may diverge in different directions, there is a high chance of them being closer in the vector space than those of the different or dissimilar node/edge types. During each communication round, in addition to the shareable bases \(\mathbf{v}_{i}^{k}\) and schema-irrelevant weights \(\mathbf{\theta}_{c}^{k}\), the FedHGN server also collects and distributes Figure 3: An example of generating the global graph schema (blue) by matching local ones (green) from two clients. FedHGN does not require this privacy-sensitive operation. Figure 2: The overall architecture of FedHGN, with the number of clients \(K=3\) and the number of bases \(B=2\). Client 1 has edge types \(r1\) and \(r2\); client 2 has edge types \(r1\) and \(r3\); client 3 has edge types \(r1\), \(r2\), and \(r3\). The uploads and downloads of \(\mathbf{\beta}\) are not shown for brevity. the schema-specific coefficients \(\mathbf{\beta}_{s}^{k}\) from/to clients. But instead of aggregating them on the server side, FedHGN introduces a novel regularization term on the client side to penalize the local node/edge types' coefficients deviating from the most similar counterpart from other clients: \[\begin{split}\mathcal{L}_{align}^{k}&=\sum_{a\in \mathcal{A}^{k}}\min_{k^{\prime}\neq k,a^{\prime}}\left\|\mathbf{\beta}_{a}^{k}-\bm {\beta}_{a^{\prime}}^{k^{\prime}}\right\|_{2}^{2}+\\ &\sum_{r\in\mathcal{R}^{k}}\min_{k^{\prime}\neq k,r^{\prime}} \left\|\mathbf{\beta}_{r}^{k}-\mathbf{\beta}_{r^{\prime}}^{k^{\prime}}\right\|_{2}^{2},\end{split} \tag{3}\] where \(\mathbf{\beta}_{s}^{k}\in\mathbb{R}^{B}\) is the schema-specific coefficients of node/edge type \(s\in\mathcal{A}^{k}\cup\mathcal{R}^{k}\) from client \(k\)'s HGNN model. The key here is how to identify the most similar counterpart for \(\mathbf{\beta}_{s}^{k}\). We intuitively select the one with the smallest distance by taking the minimum, which has the highest chance of matching the node/edge type. By minimizing this heuristic regularization term, FedHGN aligns schema coefficients across clients without disclosing actual graph schema. ### Framework Overview Our FedHGN framework largely follows FedAvg, which iteratively conducts local training at multiple clients and weight aggregation at a central server. In addition to the typical operations of FedAvg, FedHGN employs SWD and CA to preserve schema privacy without performance degradation. Before starting the federated training process, the server and the clients would negotiate for the hyperparameters of the HGNN model used, such as the number of bases (\(B\)) in SWD. The primary training process comprises many communication rounds between the server and the clients. The detailed server-side and client-side operations of a single round in FedHGN are described below. Figure 2 illustrates this training process. Complete pseudocode is given in Algorithm 1. ``` 1:\(K\) clients indexed by \(k\); Client sampling fraction \(C\); Number of bases \(B\); Number of local epochs \(E\); Learning rate \(\eta\); Alignment regularization factor \(\lambda\). 2:procedureServerExecution 3: Initialize \([\mathbf{\theta}_{c}]^{0}\), \([\mathbf{v}]^{0}\), and \(\{[\mathbf{\beta}^{k}]^{0}:1\leq k\leq K\}\) (subscripts of \(\mathbf{v}\) and \(\mathbf{\beta}\) omitted for brevity) 4:for round \(t=1,2,\ldots\)do 5:\(\mathcal{S}_{t}\leftarrow\) (random set of \(\max(C\cdot K,1)\) clients) 6:for each client \(k\in\mathcal{S}_{t}\) in parallel do 7:\([\mathbf{\theta}_{c}^{k}]^{t},[\mathbf{v}^{k}]^{t},[\mathbf{\beta}^{k}]^{t}\leftarrow \mathrm{ClientUpdate}(\\ k,[\mathbf{\theta}_{c}]^{t-1},[\mathbf{v}]^{t-1},\{[\mathbf{\beta}^{k}]^{t-1}:k ^{\prime}\neq k\})\) 8:endfor 9:\(([\mathbf{\theta}_{c}]^{t},[\mathbf{v}]^{t})\leftarrow\sum_{k\in\mathcal{S}_{t}} \frac{N_{k}}{N_{\mathcal{S}_{t}}}([\mathbf{\theta}_{c}^{k}]^{t},[\mathbf{v}^{k}]^{t})\) 10:\([\mathbf{\beta}^{k}]^{t}\leftarrow[\mathbf{\beta}^{k}]^{t-1},\forall k\notin\mathcal{ S}_{t}\) 11:endfor 12:endprocedure 13:procedureClientUpdate(\(k\), \(\mathbf{\theta}_{c}\), \(\mathbf{v}\), \(\{\mathbf{\beta}^{k^{\prime}}:k^{\prime}\neq k\}\)) 14:\(\mathbf{\theta}_{s}\leftarrow\sum_{i=1}^{B}\beta_{s,i}^{k}\mathbf{v}_{i},\forall s \in\mathcal{A}^{k}\cup\mathcal{R}^{k}\) 15:for epoch \(i=1,2,\ldots,E\)do 16:for minibatch \(m\) sampled from \(\mathcal{D}^{k}\)do 17:\(\mathcal{L}_{task}^{k}\leftarrow\) (task-specific loss given \(m\)) 18:\(\mathcal{L}_{align}^{k}\leftarrow\) Equation (3) 19:\(\mathbf{\theta}_{c},\mathbf{v},\mathbf{\beta}^{k}\leftarrow(\mathbf{\theta}_{c},\mathbf{v },\mathbf{\beta}^{k})-\eta\nabla\left(\mathcal{L}_{task}^{k}+\lambda\mathcal{L}_{ align}^{k}\right)\) 20:endfor 21:endfor 22: Return \(\mathbf{\theta}_{c}\), \(\mathbf{v}\), and \(\mathbf{\beta}^{k}\) to server 23:endprocedure ``` **Algorithm 1** FedHGN framework. Server Operations.At round \(t\), the server first samples a fraction of clients \(\mathcal{S}_{t}\) for this round of training. The server then sends the latest model parameters to each client \(k\in\mathcal{S}_{t}\), including the aggregated schema-agnostic weights, \([\mathbf{\theta}_{c}]^{t-1}\) and \([\mathbf{v}_{i}]^{t-1}\), and collected schema coefficients \([\mathbf{\beta}_{s}^{k^{\prime}}]^{t-1}\) from the previous round. After client-side local updates, the server receives the updated \([\mathbf{\theta}_{c}^{k}]^{t},[\mathbf{v}_{i}^{k}]^{t}\), and \([\mathbf{\beta}_{s}^{k^{\prime}}]^{t}\) from each \(k\in\mathcal{S}_{t}\). Finally, the server aggregates the schema-agnostic weights by \([\mathbf{\theta}_{c}]^{t}=\sum_{k\in\mathcal{S}_{t}}\frac{N_{k}}{N_{\mathcal{S}_{t} }}[\mathbf{\theta}_{c}^{k}]^{t}\) and \([\mathbf{v}_{i}]^{t}=\sum_{k\in\mathcal{S}_{t}}\frac{N_{k}}{N_{\mathcal{S}_{t} }}[\mathbf{v}_{i}^{k}]^{t}\), where \(N_{k}\) is the number of training samples at client \(k\), and \(N_{\mathcal{S}_{t}}=\sum_{k\in\mathcal{S}_{t}}N_{k}\) is the total number of training samples of this round. The server also sets \([\mathbf{\beta}_{s}^{k}]^{t}=[\mathbf{\beta}_{s}^{k}]^{t-1}\) for \(k\notin\mathcal{S}_{t}\). Client Operations.At round \(t\), each selected client \(k\) receives the latest model parameters from the server, including schema-agnostic weights, \([\mathbf{\theta}_{c}]^{t-1}\) and \([\mathbf{v}_{i}]^{t-1}\), and other clients' schema coefficients \([\mathbf{\beta}_{s}^{k^{\prime}}]^{t-1}\). The schema-specific weights are recreated via Equation (2). Then, the client would conduct local training using local heterogeneous graph data \(\mathcal{D}^{k}\) for several epochs to tune model parameters. The client-side objective function is a sum of the task-specific loss and the CA regularization term: \(\mathcal{L}^{k}=\mathcal{L}_{task}^{k}+\lambda\mathcal{L}_{align}^{k}\), where \(\mathcal{L}_{task}^{k}\) could be cross entropy for node classification tasks or some ranking loss for link prediction tasks. Finally, the client uploads the updated schema-agnostic HGNN weights, \([\mathbf{\theta}_{c}^{k}]^{t}\) and \([\mathbf{v}_{i}^{k}]^{t}\), and schema coefficients \([\mathbf{\beta}_{s}^{k}]^{t}\) back to the server. ### Privacy Analysis In this section, we analyze the communications between the server and the clients and discuss whether FedHGN can preserve the data privacy of local graph schemas. Server-side Analysis.FedHGN server is restricted to collecting limited information that cannot be used to infer graph schemas of any clients. The central server receives only HGNN model weights \(\mathbf{v}_{i}^{k}\), \(\mathbf{\theta}_{c}^{k}\), and \(\mathbf{\beta}_{s}^{k}\) from each client. \(\mathbf{v}_{i}^{k}\) and \(\mathbf{\theta}_{c}^{k}\) are schema-agnostic model weights, revealing no schema information. Although \(\mathbf{\beta}_{s}^{k}\) are schema-specific coefficients, the server can only deduce the number of node/edge types in each client. It still cannot learn other meaningful schema information, like the matching among them or the physical name of their corresponding node/edge types. Client-side Analysis.Data privacy at each client is well protected under the FedHGN framework. Each client \(k\) receives \(\mathbf{v}_{i}\), \(\mathbf{\theta}_{c}\), and \(\mathbf{\beta}_{s}^{k^{\prime}}\) (for \(k^{\prime}\neq k\)) from the server. Similarly, clients cannot infer other clients' graph schemas from \(\mathbf{v}_{i}\) and \(\mathbf{\theta}_{c}\). Since the schema-specific coefficients \(\mathbf{\beta}_{s}^{k^{\prime}}\) are sent to client \(k\) as an unordered set, client \(k\) cannot differentiate the source client of each received \(\mathbf{\beta}_{s}^{k^{\prime}}\). Therefore, neither the HGNN model nor the graph schema of any other client can be derived based on what client \(k\) receives from the server. ## 5 Experiments In this section, we demonstrate the effectiveness of FedHGN on federated learning of HGNNs by conducting experiments for _node classification_ on a series of heterogeneous graph datasets. The experiments are designed to answer the following research questions. **RQ1**: Can FedHGN achieve a better HGNN performance than purely local training? **RQ2**: Can FedHGN outperform conventional FL methods in training HGNNs? **RQ3**: What are the effects of the proposed schema-weight decoupling and coefficients alignment? **RQ4**: How is FedHGN affected by the hyperparameters? ### Experimental Setup **Datasets.** We select widely-adopted heterogeneous graph datasets for our node classification experiments: AIFB, MUTAG, and BGS preprocessed by Deep Graph Library (DGL) [20]. These datasets are highly heterogeneous with more than 50 node/edge types. To simulate the federated setting, we randomly split each dataset into \(K=3\), \(5\), and \(10\) clients. We propose two random splitting strategies for heterogeneous graphs: (1) **Random Edges (RE)** which randomly allocates edges to \(K\) clients and (2) **Random Edge Types (RET)** which randomly allocates edge types to \(K\) clients. RE simulates a scenario where each client owns a part of the complete graph, within which there are overlapping nodes/edges among clients. RET simulates a more complex scenario where clients construct the local heterogeneous graphs differently, resulting in distinct graph schemas. Averaged statistics of the BGS dataset split into \(K\) clients are summarized in Table 2. More details about the datasets and splitting strategies are provided in the appendix. **Baselines.** To assess FedHGN and demonstrate its superiority, we choose the following settings/algorithms as baselines: (1) centralized training, (2) local training, (3) FedAvg, and (4) FedProx. We do not include existing FGL methods as baselines because they cannot be easily adapted to HGNNs. FedAlign is not adopted because its source code is not available and some design details are not disclosed in its paper. **Implementation.** We employ an RGCN-like architecture as the HGNN model. Other details are in the appendix. ### Experimental Results We report results averaged from 5 runs using different random seeds. The accuracy score of each run is computed via a weighted average of the \(K\) clients' local testing scores based on the numbers of their testing samples. **Main Results (RQ1 & RQ2)** To evaluate FedHGN against local training and conventional FL algorithms, we conduct comprehensive experiments on three datasets with varying client numbers. Note that schema sharing is required and allowed in FedAvg and FedProx, but not in FedHGN. Averaged accuracy scores with standard deviations are listed in Table 3. Due to the space limit, we leave the \(K=3\) settings of MUTAG and BGS in the appendix. As shown in the table, FedHGN consistently outperforms local training and conventional FL algorithms in most settings. As expected, HGNN performance deteriorates in local training due to insufficient data, especially on AIFB and BGS. But conventional FL algorithms (FedAvg and FedProx) do not have a noticeable advantage over local training in our experiments. On AIFB (RE), they are even outperformed by the local setting. Although FedProx is designed to alleviate the non-IID data issue, it cannot correctly handle heterogeneous graph data based on our results. Compared to FedAvg and FedProx, FedHGN makes no compromise in schema-level privacy and yet achieves superior results, showing that FedHGN is a better option for federated HGNNs. FedHGN's advantage in preserving HGNN performance might come from the decoupled schema coefficients. They may serve as personalized model parameters to help each client combat the severe non-IID problem of heterogeneous graphs. **Ablation Study (RQ3)** To analyze the effects of the proposed designs, we compare variants of FedHGN on MUTAG (RE) and BGS (RE) in Table 4 by applying different _schema-weight decoupling_ (SWD) strategies and whether employing _coefficients alignment_ (CA) or not. The table shows that CA brings about a 7% improvement compared to the variant without it. We also notice a longer convergence time when removing CA. Therefore, the alignment component is necessary for FedHGN to stabilize training and maintain performance. For SWD, we observe that additionally aggregating schema coefficients at the server side (breaking schema privacy) leads to some performance gain, which can be well compensated by CA. Another interesting observation is that the FedHGN variant that only aggregates schema coefficients achieves decent results. We suspect it may resemble the local setting because the shared coefficients have a small parameter space. We also present the results produced by removing both SWD and CA, which reduces FedHGN to FedAvg. Although outperforming the variant that uses only SWD, FedAvg violates schema privacy and is still inferior to the full version of FedHGN. All these results confirm the effectiveness of SWD and CA. **Hyperparameter Analysis (RQ4)** To investigate how FedHGN is affected by the newly introduced hyperparameters, we conduct pilot tests on AIFB with different choices for the number of bases \(B\) and the alignment \begin{table} \begin{tabular}{r|l r r r} \hline \multicolumn{2}{c}{} & \(K\) & 3 & 5 & 10 \\ \hline \multirow{3}{*}{RE} & \# ntypes & 27.0 & 27.0 & 27.0 \\ & \# types & 120.7 & 122.0 & 120.0 \\ & \# nodes & 80,592.0 & 68,697.6 & 50,238.5 \\ & \# edges & 358,873.3 & 249,948.4 & 142,849.6 \\ \hline \multirow{3}{*}{RET} & \# ntypes & 20.3 & 18.0 & 12.3 \\ & \# types & 66.0 & 52.4 & 26.8 \\ & \# nodes & 77,027.7 & 73,202.4 & 43,735.6 \\ & \# edges & 349,813.3 & 248,125.6 & 138,807.0 \\ \hline \end{tabular} \end{table} Table 2: Averaged statistics of the BGS dataset split into \(K\) clients. regularization factor \(\lambda\). Except for the concerning hyperparameter, all other setups are kept unchanged. From Figure 4, we find that FedHGN is sensitive to the choice of \(B\). The optimal performance is reached at around \(B=35\) and \(B=20\) for AIFB (RE) and AIFB (RET), respectively. Intuitively, \(B\) should be related to the number of edge types involved in the FL system. Since other settings (MUTAG and BGS) contain a similar or smaller number of edge types, we roughly choose \(B=20\) as a sugar point to report the main results. For the alignment regularization factor \(\lambda\), FedHGN performance does not change much when \(\lambda\) is reasonable, i.e., for \(\lambda\leq 5\). But when \(\lambda\) gets larger than 5, the testing accuracy drops dramatically on both AIFB (RE) and AIFB (RET). When \(\lambda\) is too large, the optimization objective is dominated by the CA regularization term \(\mathcal{L}_{align}\). HGNNs cannot learn much knowledge from the task-specific loss \(\mathcal{L}_{task}\) in this case. Hence, we just set \(\lambda=0.5\) for our main experiments. ## 6 Discussion This work aims to avoid schema matching and ensure schema privacy during federated HGNN learning. By carefully examining the HGNN architecture, we notice the crux of the matter is the correspondence between model weights and node/edge types. Our FedHGN is designed to decouple this binding and achieve schema-agnostic weight sharing. This seems unnecessary as one could just apply secure multiparty computation (MPC) techniques like private set operations [14, 15] to match the node/edge types across clients. However, node/edge types' naming conventions may differ across clients. Human labor is usually inevitable to coordinate a set of naming rules, which generally breaks schema privacy. Furthermore, without SWD, the server can derive client schema from received gradient/weight changes between communication rounds. Although gradients can be protected by differential privacy [1], homomorphic encryption [10], secure aggregation [1], or MPC [16], these approaches could affect model performance, increase computational overhead, or impede communication reduction methods [10]. Therefore, we reckon FedHGN as a practical design to reduce schema privacy risks. ## 7 Conclusion This paper proposes FedHGN, a novel federated heterogeneous graph learning framework for HGNNs with schema privacy protection. By decoupling graph schemas and model weights, FedHGN removes the correspondence between node/edge types and HGNN weights to achieve schema-agnostic knowledge sharing. With an alignment regularization term, the discrepancy among same-type schema coefficients across clients is alleviated to stabilize training and boost model performance. Experimental results show that FedHGN can bring consistent performance improvement to HGNNs while preserving both data and schema privacy, outperforming local training and conventional FL algorithms. \begin{table} \begin{tabular}{c c c c c c} \hline \hline \multirow{2}{*}{SWD} & \multirow{2}{*}{CA} & \multicolumn{2}{c}{MUTAG (RE)} & \multicolumn{2}{c}{BGS (RE)} \\ \cline{3-6} & & \(K=5\) & \(K=10\) & \(K=5\) & \(K=10\) \\ \hline B & ✗ & 63.18 & 60.59 & 66.39 & 59.36 \\ C & ✗ & 65.88 & 61.26 & **67.78** & 64.11 \\ B+C & ✗ & 65.29 & 62.83 & 66.53 & 63.76 \\ ✗ & ✗ & 65.06 & 65.47 & 67.36 & 65.04 \\ \hline B & ✓ & **67.87** & **65.59** & 67.52 & **65.73** \\ \hline \hline \end{tabular} \end{table} Table 4: Ablation study on the MUTAG and BGS datasets (RE splitting strategy). B: aggregating basis weights. C: aggregating schema-specific coefficients. The last row is our proposed FedHGN. Figure 4: Hyperparameter analysis of varying \(B\) and \(\lambda\). \begin{table} \begin{tabular}{c|c c c c c c c c} \hline \hline \multicolumn{2}{c}{Dataset} & \multicolumn{2}{c}{AIFB} & \multicolumn{2}{c}{MUTAG} & \multicolumn{2}{c}{BGS} \\ \hline \multicolumn{2}{c}{Central} & \multicolumn{2}{c}{87.78\(\pm\)2.22} & \multicolumn{2}{c}{68.24\(\pm\)3.79} & \multicolumn{2}{c}{81.38\(\pm\)1.69} \\ \hline \multicolumn{2}{c}{\(K\)} & \multicolumn{2}{c}{3} & \multicolumn{2}{c}{5} & \multicolumn{2}{c}{10} & \multicolumn{2}{c}{5} & \multicolumn{2}{c}{10} & \multicolumn{2}{c}{5} & \multicolumn{2}{c}{10} \\ \hline \multirow{4}{*}{RE} & Local & 74.77\(\pm\)5.22 & 71.30\(\pm\)4.30 & 55.08\(\pm\)1.09 & 65.06\(\pm\)1.28 & 64.88\(\pm\)1.12 & 67.04\(\pm\)1.79 & 64.54\(\pm\)1.65 \\ & FedAvg & 74.02\(\pm\)3.09 & 65.18\(\pm\)3.59 & 54.95\(\pm\)1.42 & 65.06\(\pm\)0.34 & 65.47\(\pm\)0.74 & 67.36\(\pm\)2.52 & 65.04\(\pm\)1.26 \\ & FedProx & 72.34\(\pm\)3.37 & 65.29\(\pm\)5.43 & 53.38\(\pm\)2.79 & 65.59\(\pm\)0.69 & **65.62\(\pm\)0.76** & 66.11\(\pm\)3.99 & 63.97\(\pm\)1.66 \\ & FedHGN & **81.87\(\pm\)2.33** & **72.94\(\pm\)3.27** & **59.32\(\pm\)1.42** & **67.87\(\pm\)0.83** & 65.59\(\pm\)0.86 & **67.52\(\pm\)2.58** & **65.73\(\pm\)1.47** \\ \hline \multirow{4}{*}{RET} & Local & 76.11\(\pm\)3.58 & 65.89\(\pm\)2.29 & 59.71\(\pm\)3.06 & 64.78\(\pm\)0.89 & 64.18\(\pm\)3.13 & 67.73\(\pm\)1.19 & 67.11\(\pm\)0.52 \\ & FedAvg & 80.00\(\pm\)1.72 & 66.56\(\pm\)3.47 & 59.59\(\pm\)3.03 & 66.04\(\pm\)0.11 & **66.28\(\pm\)0.15** & 69.10\(\pm\)2.11 & 65.04\(\pm\)0.96 \\ \cline{1-1} & FedProx & 80.93\(\pm\)2.78 & 66.00\(\pm\)2.95 & 60.99\(\pm\)1.95 & 65.92\(\pm\)0.29 & 66.13\(\pm\)0.06 & **70.62\(\pm\)1.42** & 66.07\(\pm\)0.80 \\ \cline{1-1} & FedHGN & **86.55\(\pm\)2.53** & **70.67\(\pm\)2.42** & **66.76\(\pm\)3.22** & **66.21\(\pm\)0.40** & 66.21\(\pm\)0.12 & 69.79\(\pm\)2.07 & **69.03\(\pm\)1.44** \\ \hline \hline \end{tabular} \end{table} Table 3: Experimental results (weighted average of accuracy %) of node classification. ## Acknowledgments The work described here was partially supported by grants from the National Key Research and Development Program of China (No. 2018AAA0100204) and from the Research Grants Council of the Hong Kong Special Administrative Region, China (RGC GRF No. 2151185, CUHK 14222922).
2306.12881
Data-Free Backbone Fine-Tuning for Pruned Neural Networks
Model compression techniques reduce the computational load and memory consumption of deep neural networks. After the compression operation, e.g. parameter pruning, the model is normally fine-tuned on the original training dataset to recover from the performance drop caused by compression. However, the training data is not always available due to privacy issues or other factors. In this work, we present a data-free fine-tuning approach for pruning the backbone of deep neural networks. In particular, the pruned network backbone is trained with synthetically generated images, and our proposed intermediate supervision to mimic the unpruned backbone's output feature map. Afterwards, the pruned backbone can be combined with the original network head to make predictions. We generate synthetic images by back-propagating gradients to noise images while relying on L1-pruning for the backbone pruning. In our experiments, we show that our approach is task-independent due to pruning only the backbone. By evaluating our approach on 2D human pose estimation, object detection, and image classification, we demonstrate promising performance compared to the unpruned model. Our code is available at https://github.com/holzbock/dfbf.
Adrian Holzbock, Achyut Hegde, Klaus Dietmayer, Vasileios Belagiannis
2023-06-22T13:44:40Z
http://arxiv.org/abs/2306.12881v1
# Data-Free Backbone Fine-Tuning for Pruned Neural Networks ###### Abstract Model compression techniques reduce the computational load and memory consumption of deep neural networks. After the compression operation, e.g. parameter pruning, the model is normally fine-tuned on the original training dataset to recover from the performance drop caused by compression. However, the training data is not always available due to privacy issues or other factors. In this work, we present a data-free fine-tuning approach for pruning the backbone of deep neural networks. In particular, the pruned network backbone is trained with synthetically generated images, and our proposed intermediate supervision to mimic the unpruned backbone's output feature map. Afterwards, the pruned backbone can be combined with the original network head to make predictions. We generate synthetic images by back-propagating gradients to noise images while relying on L1-pruning for the backbone pruning. In our experiments, we show that our approach is task-independent due to pruning only the backbone. By evaluating our approach on 2D human pose estimation, object detection, and image classification, we demonstrate promising performance compared to the unpruned model. Our code is available at [https://github.com/holzbock/dfbf](https://github.com/holzbock/dfbf). Data-Free Neural Network Pruning, Data-Free Object Detection Pruning, Data-Free Pose Estimation Pruning ## I Introduction Computer vision tasks like object detection [1, 2] or human pose estimation [3, 4] have long been studied in the literature. Their leading performance though comes at the cost of high computational and memory requirements, making them difficult to deploy on resource-constrained devices. For deep neural networks, the compute and memory demands are often reduced with model compression, e.g. parameter pruning [5] or knowledge distillation [6]. However, most neural network compression techniques normally require the availability of the training set. Due to privacy issues or large dataset size, access to the training dataset cannot always be guaranteed. As an alternative to the data-driven model compression [5, 6, 7], approaches using only a few samples of the training dataset [8] and data-free methods have been developed to overcome the limited access to the original training dataset. The data-free approaches generate synthetic images to regain the knowledge after pruning [9] or transfer the knowledge with knowledge distillation [10] to a smaller model. The synthetic images can be generated with an additional generator network trained with the original model's knowledge [9, 11]. Another method is to optimize noisy images by back-propagating directly onto the pixels [12]. In this work, we focus on neural network pruning similar to [9]. However, we rely on the back-propagation of gradients for image generation instead of employing a generator network. In contrast to existing methods, our approach is not limited to a specific task, but is applicable to different computer vision tasks. We achieve task-independence by only pruning the backbone of the model, keeping the task-dependent head unchanged. We present a **D**ata-**F**ee **B**ackbone **F**ine-tuning approach (DFBF) for pruning the backbone of deep neural networks. In particular, we train the pruned backbone with synthetic images to mimic the output of the unpruned backbone. Later, we can use the pruned backbone with the original network head to make predictions. The synthetic images are generated Fig. 1: Training of the pruned backbone with label-free synthetic images. Besides the backbone’s output feature map, some intermediate feature maps are used to recover the backbone’s knowledge. by back-propagating gradients directly on noise images, while the backbone is pruned by \(\ell_{1}\)-pruning, leaving the parameters of the network head unmodified. Only backbone pruning keeps the pruning approach task-independent, as no training of the task-specific head is required. For the training of the backbone, we introduce an intermediate loss function that adjusts the pruned backbone's intermediate feature maps and output to match it with the original backbone. An overview of the proposed method is given in Fig. 1. After the training, the original network's head can be attached to the pruned backbone for the task-specific output. We examine our approach on three vision tasks, namely object detection, human pose estimation, and image classification. First, we use the Faster R-CNN object detector [1] for object detection and present the results for different pruning ratios on the COCO detection dataset [13] and Pascal VOC dataset [14]. We evaluate pose estimation with the OpenPifPaf pose estimator [3] trained on the COCO keypoint dataset [13]. Additionally, we compare the performance on CIFAR10 [15] for image classification. As backbone, we use ResNet [16] and VGG [17] models in our experiments. To the best of our knowledge, we are the first to introduce a data-free fine-tuning method for pruning that can be applied to complex computer vision tasks like object detection and human pose estimation. The proposed intermediate loss function that applies the prediction of the unpruned model as ground truth enables the task independence of DFBF. ## II Method In the following, we present our data-free fine-tuning method for pruned neural networks, which process input images \(\mathbf{x}\in\mathbb{R}^{3\times W\times H}\), where \(W\) and \(H\) are the width and height, respectively. We assume that the neural network \(\mathbf{y}=f(\mathbf{x};\theta)\) can be divided into a backbone \(\mathbf{z}=b(\mathbf{x};\theta_{b})\) and a head \(\mathbf{y}=h(\mathbf{z};\theta_{h})\), where the head \(h\) is a task-specific output network. \(\mathbf{y}\) is the output prediction, \(\mathbf{z}\) is the output feature map from the backbone forwarded to the task-specific head, while \(\theta\), \(\theta_{b}\), and \(\theta_{h}\) are the model parameters of the whole model, the backbone, and the head, respectively. Since we only prune the model backbone, our approach is independent of the shape of the model prediction \(\mathbf{y}\) and thus can be applied to different computer vision tasks. ### _Preliminaries_ PruningUtilizing pruning algorithms reduces neural networks' resource demand by removing unnecessary or redundant parameters. Pruning convolutional neural networks can be divided into different groups. The parameter pruning only removes single weights [18], leading to sparse kernels and no satisfying reduction in computation. In contrast, filter pruning reduces the computation effort by removing entire filters [19]. To decide which filters are pruned, the methods rely on the knowledge of the model, like in \(\ell_{1}\)-pruning [20] and Batch Normalization pruning [21], or even use additional neural network layers [22]. Because of its simplicity and the fact that no extra neural network layers are needed, we rely on the \(\ell_{1}\)-pruning [20] to get the pruned backbone \(b_{p}(\cdot)\) with its reduced parameters \(\theta_{bp}\). However, every other filter pruning approach can be used to prune the model's backbone for DFBF. The \(\ell_{1}\)-pruning calculates for each filter \(\mathcal{F}_{i}\) of a neural network layer the sum of the filter weights \(w_{i}\) by \(s_{i}=\sum|w_{i}|\) and removes filters with the smallest sum \(s_{i}\) according to the required sparsity. The reduction of the current layer's filters makes it necessary to remove the corresponding input channels of the following layer. Furthermore, the pruning sparsity can be adapted to the number of filters in the layer, i.e. in layers with many filters, percentual more filters are pruned than in layers with fewer filters. Image SynthesisSince the original training set is unavailable, we synthesize training images by transferring knowledge from the model to a noisy image, similar to DeepInversion [23], but without being limited to the classification task. At the beginning of the image generation, a noise image \(\mathbf{\hat{x}}\in\mathcal{R}^{3\times w\times h}\) with width \(w\) and height \(h\) is fed into the backbone, while the synthetic image size can differ from the original \((W\neq w;H\neq h)\). Then, the loss \(\mathcal{L}_{image}\) is propagated back onto the noise image \(\mathbf{\hat{x}}\) to adapt the pixels directly without changing the model parameters. The loss \(\mathcal{L}_{image}\) for optimizing the noise image independent of the underlying task is the weighted sum of the following three parts. The Batch Normalization loss is calculated between the batch statistics of the Batch Normalization layers and the statistics of the actual noise images. The total variance loss is defined by the \(\ell_{2}\)-norm of the differences between horizontally and vertically adjacent image pixels and is calculated on the noise image directly. Additionally, the loss is regularized by penalizing the \(\ell_{2}\)-norm of the entire image. The task independence of \(\mathcal{L}_{image}\) is reached by not using the task-specific outputs of the head, whereby images of different computer vision tasks can be synthesized. To train the pruned model, we generate a synthetic dataset \(\mathcal{D}\) containing \(M\) synthetic images \(\mathbf{\hat{x}}\). ### _Overall Pruning Procedure_ Our method is designed for pruning a neural network of any image-dependent task in a data-free manner. Our main contribution is the fine-tuning step after the pruning without relying on training data. Therefore, we focus on reducing the size of the backbone \(b(\cdot)\) and keeping the head \(h(\cdot)\) as is. We perform the task-independent data-free pruning in the following three steps: 1) image generation with an adapted loss function, 2) network pruning with the \(\ell_{1}\)-pruning, and 3) fine-tuning only the backbone with the proposed intermediate loss function. A systematic overview of the data-free fine-tuning of the backbone is given in Fig.1. ### _Data-Free Training_ During the pruning process, the model loses some of its knowledge which can be recovered in the following training procedure. In data-driven pruning methods, fine-tuning is performed with the original training dataset. In contrast, we use the synthetic dataset \(\mathcal{D}\), which only contains pseudo images \(\mathbf{\hat{x}}\), but no labels. However, the loss calculation in the standard training with the original data needs labels for the parameter update. To overcome the issue of having no ground truth labels for the pseudo images, we introduce a method that generates pseudo labels with the help of the unpruned model and applies them to improve the performance of the pruned model. The final output of a neural network depends on the defined model task. Therefore, we propose not handling the output of the unpruned network's head as pseudo ground truth but instead using the output feature map \(\mathbf{z}\) of the unpruned model's backbone. This design choice makes our approach independent of the task-specific model heads. More precisely, we define the loss as the \(\ell_{1}\)-loss between the output feature map of the unpruned backbone \(\mathbf{z}\) and the pruned backbone \(\mathbf{\hat{z}}\). Our output feature map loss \(\mathcal{L}_{out}\) can be formulated as \[\mathcal{L}_{out}=\frac{1}{w_{o}*h_{o}}\sum_{i=0}^{w_{o}}\sum_{j=0}^{h_{o}}| \mathbf{\hat{z}}_{i,j}-\mathbf{z}_{i,j}|, \tag{1}\] where \(w_{o}\) and \(h_{o}\) are the width and height of the output feature map, respectively. Additionally, we define an intermediate feature map loss \(\mathcal{L}_{inter}\). For \(\mathcal{L}_{inter}\), we calculate the \(\ell_{1}\)-loss between intermediate feature maps of the unpruned model \(\mathbf{a}_{n},n\in[1\dots N]\) and the corresponding feature maps of the pruned model \(\mathbf{\hat{a}}_{n},n\in[1\dots N]\), where \(N\) defines the number of intermediate feature maps. Empirically, we found that the intermediate feature maps after the Batch Normalization layers [24] lead to the best results. Since the feature maps behind the pruned layers differ in their dimensions from the unpruned model ones, it is impossible to calculate the loss between them. Therefore, we propose to skip single layers in the pruning and use them later for the loss calculation. Using \(N\) intermediate feature maps for the loss calculation, \(\mathcal{L}_{inter}\) can be calculated as \[\mathcal{L}_{inter}=\sum_{n=1}^{N}\left(\frac{\mu_{n}}{w_{n}*h_{n}}\sum_{i=0}^{ w_{n}}\sum_{j=0}^{h_{n}}|\mathbf{\hat{a}}_{n,i,j}-\mathbf{a}_{n,i,j}|\right). \tag{2}\] The influence of the different feature maps on the loss \(\mathcal{L}_{inter}\) is defined by the parameter \(\mu_{n}\), which we define as \(\frac{n}{N+1}*\gamma+1\), where the parameter \(\gamma\) is a scaling factor. \(w_{n}\) and \(h_{n}\) are the width and height of the intermediate feature map \(n\). The overall loss \(\mathcal{L}_{DFBF}\) in our data-free training combines \(\mathcal{L}_{out}\) and \(\mathcal{L}_{inter}\): \[\mathcal{L}_{DFBF}=\mu_{out}\mathcal{L}_{out}+\mathcal{L}_{inter}, \tag{3}\] where \(\mu_{out}\) is the weighting factor of the output loss that we define as \(\gamma+1\). Importantly, \(\mathcal{L}_{DFBF}\) is applied to optimize the parameters \(\theta_{bp}\) of the pruned backbone \(b_{p}(\cdot)\) and not to update the parameters \(\theta_{h}\) of the head \(h(\cdot)\). During inference, we combine the optimized pruned backbone \(\mathbf{\hat{z}}=b_{p}(\mathbf{x},\theta_{bp})\) with the pre-trained head \(\mathbf{\hat{y}}=h(\mathbf{\hat{z}},\theta_{h})\) to obtain the pruned model as: \[\mathbf{\hat{y}}=h(b_{p}(\mathbf{x},\theta_{bp}),\theta_{h}). \tag{4}\] For the prediction, we feed original images \(\mathbf{x}\) to the model and get a slightly different model output \(\mathbf{\hat{y}}\) because of the modified backbone weights \(\theta_{p}\). Due to the backbone training with the synthetic images, the output of the original model \(\mathbf{y}\) and the pruned model \(\mathbf{\hat{y}}\) are nearly identical. ## III Experiments We show the effectiveness of our proposed method in three challenging computer vision tasks: object detection, human pose estimation, and image classification. In object detection, we use Faster R-CNN [1] trained on the COCO detection [13] as well as on the Pascal VOC dataset [14]. The base for the human pose estimation is an Open PifPaf pose estimator [3] trained on the COCO keypoint dataset [13]. Both tasks utilize a ResNet50 [16] backbone, and VGG16 [17] is used as an additional backbone in object detection. We prune between 10% and 40% of the backbone filters with \(\ell_{1}\)-pruning during the evaluation. In image classification, we compare with Tang et al. [9] and follow their evaluation protocol using Batch Normalization pruning [21] for the VGG models [17] and \(\ell_{1}\) pruning [20] for the ResNet models [16]. The pruned backbone is trained in each task with 1600 synthetic images using the SGD optimizer with a learning rate of 0.01, a momentum of 0.9, and a weight decay of \(5\times 10^{-4}\). To the best of our knowledge, we are the first to prune an object detection or a human pose estimation model in a data-free manner. Therefore, we cannot make a direct comparison with other methods. We compare DFBF with the unpruned baseline referred to as _Baseline_, the pruned but not fine-tuned model referred to as _w/o fine-tuning_, and the pruned model trained with 1600 random sampled original training images and our intermediate loss \(\mathcal{L}_{DFBF}\) referred to as _orig. img._ Additionally, we report the number of removed filters and parameters, while the parameter count differs from the filter count because of different pruning spars Fig. 3: Synthetic images generated with an OpenPifPaf pose estimator [3] with a ResNet50 [16] backbone trained on the COCO keypoint dataset [13]. Fig. 2: Synthetic images generated with Faster R-CNN object detector [1] with a ResNet50 [16] backbone trained on the COCO detection dataset [13]. ### _Object Detection_ We set the synthetic image resolution for the object detection task to \(250\times 250\) pixels and \(\gamma\) to 1. The results for pruning a Faster R-CNN object detection model [1] in a data-free manner are shown in Tab. I. For both datasets and backbones, the performance evolves similarly during pruning and training. The performance of the object detector after pruning depends on the pruning sparsity and decreases with higher rates. Also, we can see that with DFBF, the performance of the pruned model can recover during training with the synthetic images near the initial results. The model's performance trained with synthetic images is behind the model trained with the original images. Furthermore, the influence of synthetic images at higher pruning rates (30% and 40%) can be seen. Here, the difference between the model trained with the synthetic and the original images increases compared to lower pruning rates (10% and 20%). We show some synthetic images generated from an object detector trained on the COCO detection dataset [13] in Fig. 2. Compared to the original images, no objects can be recognized in the synthetic images. The abstract look of the synthetic images can cause the performance gap between the synthetic and original training image's performance using high pruning sparsities. ### _Human Pose Estimation_ Besides object detection, we evaluate DFBF for human pose estimation which is often the base for gesture recognition [25] or human motion prediction [26]. We use synthetic images with a resolution of \(160\times 160\) and 6 as value for \(\gamma\). The results for the human pose estimation are shown in Tab. I. As for object detection, the performance decreases with a higher pruning rate in human pose estimation. For all pruning rates, DFBF can recover the performance after pruning. In contrast to object detection, we perform better on human pose estimation with the synthetic images than with the original training images. This could be due to the difference between the synthetic images obtained from both tasks. Synthetic images generated with OpenPifPaf trained on the COCO keypoint dataset can be seen in Fig. 3. Compared to the images generated in the object detection task in Fig. 2, the pose images show pose information and pose-related details such as faces. Therefore, the generated images' variation can be broader compared to the original images. Moreover, the synthetic images show only patterns important for human pose estimation, and the pruned model can concentrate on learning the essential shapes. ### _Image Classification_ Unlike the other tasks, we compare image classification with the state-of-the-art approach from Tang et al. [9]. During pruning the image classification model, the resolution of the synthetic training images is \(32\times 32\), and we set the factor \(\gamma\) to 0. Tab. II presents the CIFAR10 [15] results for different ResNet and VGG models fine-tuned with DFBF and the approach of Tang et al. [9]. In the pruning, we remove 30% and 50% of the filters from the baseline models. The results show that our approach is on par with Tang et al. [9], while we are not limited to the classification task due to the proposed task-agnostic loss function. ## IV Ablation Studies An essential part of DFBF is the proposed intermediate loss function \(\mathcal{L}_{DFBF}\) for which we do further investigations. We use the OpenPifPaf settings from Sec. III as standard settings. In \(\mathcal{L}_{DFBF}\), we take the feature map after each residual connection and the output feature map to calculate the loss and get an overall performance of 62.2%. The performance drops by 1.0% AP to 61.2% AP when skipping every second intermediate feature map in the loss calculation. Neglecting all intermediate feature maps and using only the output feature map in the loss calculation decreases the performance to 44.7% AP. These experiments demonstrate the importance of the intermediate feature maps on \(\mathcal{L}_{DFBF}\). Furthermore, we present the effect of the scaling factor \(\gamma\) in Tab. III. We vary the impact of the different feature maps on \(\mathcal{L}_{DFBF}\) by setting \(\gamma\in[2,\dots,8]\). With increasing \(\gamma\), the overall performance improves. ## V Conclusion We presented a data-free backbone fine-tuning approach for pruning the backbone of deep neural networks. Our approach relies on synthetically generated images to fine-tune the backbone of the pruned neural network, where pruning is based on the \(\ell_{1}\) norm. Notably, we proposed an intermediate loss function to match the pruned backbone's output feature map such that the pruned backbone can later be combined with the original network head to perform predictions. Our evaluations showed that our approach is task-independent by evaluating the tasks of object detection, human pose estimation, and image classification.
2310.03918
Unsupervised SFQ-Based Spiking Neural Network
Single Flux Quantum (SFQ) technology represents a groundbreaking advancement in computational efficiency and ultra-high-speed neuromorphic processing. The key features of SFQ technology, particularly data representation, transmission, and processing through SFQ pulses, closely mirror fundamental aspects of biological neural structures. Consequently, SFQ-based circuits emerge as an ideal candidate for realizing Spiking Neural Networks (SNNs). This study presents a proof-of-concept demonstration of an SFQ-based SNN architecture, showcasing its capacity for ultra-fast switching at remarkably low energy consumption per output activity. Notably, our work introduces innovative approaches: (i) We introduce a novel spike-timing-dependent plasticity mechanism to update synapses and to trace spike-activity by incorporating a leaky non-destructive readout circuit. (ii) We propose a novel method to dynamically regulate the threshold behavior of leaky integrate and fire superconductor neurons, enhancing the adaptability of our SNN architecture. (iii) Our research incorporates a novel winner-take-all mechanism, aligning with practical strategies for SNN development and enabling effective decision-making processes. The effectiveness of these proposed structural enhancements is evaluated by integrating high-level models into the BindsNET framework. By leveraging BindsNET, we model the online training of an SNN, integrating the novel structures into the learning process. To ensure the robustness and functionality of our circuits, we employ JoSIM for circuit parameter extraction and functional verification through simulation.
Mustafa Altay Karamuftuoglu, Beyza Zeynep Ucpinar, Sasan Razmkhah, Mehdi Kamal, Massoud Pedram
2023-10-05T21:49:10Z
http://arxiv.org/abs/2310.03918v1
# Unsupervised SFQ-Based Spiking Neural Network ###### Abstract Single Flux Quantum (SFQ) technology represents a groundbreaking advancement in computational efficiency and ultra-high-speed neuromorphic processing. The key features of SFQ technology, particularly data representation, transmission, and processing through SFQ pulses, closely mirror fundamental aspects of biological neural structures. Consequently, SFQ-based circuits emerge as an ideal candidate for realizing Spiking Neural Networks (SNNs). This study presents a proof-of-concept demonstration of an SFQ-based SNN architecture, showcasing its capacity for ultra-fast switching at remarkably low energy consumption per output activity. Notably, our work introduces innovative approaches: (i) We introduce a novel spike-timing-dependent plasticity mechanism to update synapses and to trace spike-activity by incorporating a leaky non-destructive readout circuit. (ii) We propose a novel method to dynamically regulate the threshold behavior of leaky integrate and fire superconductor neurons, enhancing the adaptability of our SNN architecture. (iii) Our research incorporates a novel winner-take-all mechanism, aligning with practical strategies for SNN development and enabling effective decision-making processes. The effectiveness of these proposed structural enhancements is evaluated by integrating high-level models into the BindsNET framework. By leveraging BindsNET, we model the online training of an SNN, integrating the novel structures into the learning process. To ensure the robustness and functionality of our circuits, we employ JoSIM for circuit parameter extraction and functional verification through simulation. Single flux quantum, superconductor electronics, spiking neural network, synapse, STDP ## I Introduction Growing demand for neural networks has led to innovative solutions that combine fundamental biological principles with hardware implementations. These solutions and the developments in computational neuroscience have a notable influence on the paradigm shift from artificial neural networks (ANNs) to the domain of spiking neural networks (SNNs) due to their distinctive properties of energy efficiency and inference capabilities [1]. SFQ circuits with spike-based behavior show great promise in efficient and fast SNN implementation. Neural data represented with spikes intrinsically resembles the data on superconductor devices [2, 3]. Furthermore, the shift from the conventional floating point representation to a binary paradigm of 0s and 1s results in notable simplifications and reduced memory requirements. The inherent sparsity in SNNs, where neurons spend most of their time resting, aligns perfectly with the concept of event-driven processing with asynchronous superconductor circuits. This ultimately leads to substantial power savings by eliminating the need for most of the computational operations. Thus, the utilization of superconductor devices on SNN holds great promise for the performance of neuromorphic computing systems [4]. Superconductor-based SNN designs necessitate the integration of superconductor circuits that accurately replicate the intricate dynamics observed in biological neurons, specifically translating states and actions into neural spikes. Within this paradigm, leveraging the unsupervised learning mechanisms inherent to SNNs, in conjunction with the capabilities of superconductor technology, empowers us to establish a biologically plausible framework for simulating neural networks. Schneider et al. [5] showcased character recognition using an SNN model, explicitly emphasizing the letters 'z,' 'v,' and 'n.' In their study, the authors employed a 3 x 3 input pixel array and implemented a two-layer inference SNN that incorporated Integrate-and-Fire (IF) neurons and Magnetic Josephson Junctions (MJJs). Bozbey et al. [6] extended the SNN research by utilizing superconductor Leaky Integrate-and-Fire (LIF) neurons with CMOS-superconductor synapses for the inference SNN. The training process was executed using genetic algorithms applied to the iris dataset. Furthermore, Zhang et al. [7] contributed to the field by exploring SNNs featuring IF neurons with Quantum Phase-Slip Junctions (QPSJ). They analyzed superconductor SNN training, using the digit '0' from the MNIST dataset as their experimental basis. Of particular interest, Segall et al. [8] introduced a 1-bit resolution Spike-Timing-Dependent Plasticity (STDP) structure, advancing the prospects of unsupervised learning with superconductor devices. Collectively, these papers share a common focus on alternative inference neural networks. However, it is crucial to acknowledge a significant limitation--the immunity of superconductor fabrication technologies for MJJs and QPSJs. Consequently, our contributions primarily center around online training with conventional superconductor elements that can be readily fabricated using available foundry processes. This work focuses on training SNNs utilizing Spike-Timing-Dependent Plasticity (STDP) while providing justifications for integrating superconductor components. Within the scope of our research, we have carefully designed an STDP mechanism tailored for a synaptic finite state machine specifically optimized for Single Flux Quantum (SFQ)-based SNNs. Additionally, we introduce leaky integrate-and-fire (LIF) neurons _with dynamic thresholds_ achieved through self-inhibition. This unique feature empowers LIF neurons to adapt dynamically to input patterns, leveraging the temporal diversity among neurons to enhance overall network performance. We conducted simulations using JoSIM [9] to ensure the functionality and accuracy of our designs. For network analysis, we leveraged the BindsNET framework's capabilities [10] and applied them to an architecture representing an asynchronous SNN with two layers [11]. Throughout our analysis, we maintained an evaluation range aligned with the capabilities of superconductor hardware, yielding high levels of accuracy in our observations and assessments. The key contributions of this paper are as follows. (i) Quantized STDP Mechanism: We introduce a novel STDP mechanism that is quantized and utilizes a leaky non-destructive readout (NDRO); (ii) Dynamic Threshold Behavior: We demonstrate an innovative self-inhibition technique that temporarily modulates LIF neurons' membrane potential, enabling dynamic threshold behavior; (iii) Winner-Take-All Superconductor Structure: We present a novel superconductor structure designed to implement the winner-take-all principle within the context of neural networks; and (iv) Computational Framework: We employ plausible mechanisms within a computational framework to systematically verify and observe the computational behavior of SNNs. ## II Methodology The development of spiking neurons and their computational models are dedicated to faithfully mirroring the behavior of biological neurons. These methodologies focus on capturing spike-based activity, which enables precise temporal information encoding. By integrating these neurons with synaptic plasticity mechanisms, neural networks evolve into powerful tools for facilitating unsupervised learning. To achieve this, Spike-Timing-Dependent Plasticity (STDP) plays a key role, enabling networks with adaptive capabilities by modulating the strengths of synaptic connections based on the precise timing of spikes. In the following subsections, we delve into the network architecture and the crucial role of synaptic adaptability as a foundational feature, effectively emulating the intricate dynamics of biological neural networks. ### _Spiking Neural Network Architecture_ The network architecture that we follow fundamentally consists of two layers: an input layer and a processing layer as an output layer [11]. For the input, neural encoding techniques are applied to transform input pixels into spikes, such as rate coding, temporal coding, and sparse coding. In particular, we focus on the rate coding scheme that converts a pixel value into a rate of spikes using Poisson distribution [12]. In this approach, the source of the input spikes can be any asynchronous input, such as a sensor. The incoming spikes are then propagated to the processing layer after being weighted by synapses. The processing layer consists of excitatory and inhibitory neurons. The overall decision-making is performed by excitatory neurons with the help of inhibitory neurons. After being weighted by synapses, the input spikes are initially provided to the excitatory neurons. The synaptic connections from the input layer to excitatory neurons are established in a fully connected fashion. Inhibitory neurons are incorporated into the structure to introduce competitive dynamics among the excitatory neurons. The connections from excitatory to inhibitory neurons are one-to-one. In contrast, the links from inhibitory to excitatory neurons are fully connected. Here, the excitatory neuron that provides the initial spikes to the inhibitory neuron is excluded. In this approach, if an excitatory neuron generates output, these spikes trigger the corresponding inhibitory neuron. Once the inhibitory neuron generates an output spike, it will prevent the rest of the excitatory neurons from firing. This paradigm is defined as the winner-take-all (WTA) principle [13]. This network configuration resembles recurrent neural networks due to lateral inhibition. In our approach, we utilize a slightly modified version, shown in Fig. 1, of the previously described architecture. For our work, we assigned a single-spike threshold to inhibitory neurons. As a result, these neurons perform just the propagation of spikes with a high fanout back to the excitatory neurons for the operation of inhibition. Therefore, we exclude the inhibitory neurons from the architecture and create a WTA feedback mechanism among the excitatory neurons to establish the same functionality as inhibitory neurons. ### _Spike-timing-dependent plasticity (STDP)_ STDP is a phenomenon in which the timing of spikes in neural networks influences both the direction (sign) and magnitude of changes in synaptic strength. It is considered one of the primary learning rules governing synaptic plasticity and is a biologically plausible mechanism for unsupervised learning, as discussed in reference [14]. Conceptually, STDP is often interpreted as a form of Hebbian learning, which posits that synapses are strengthened when neurons fire together. In STDP, the precise timing of pre-synaptic and post-synaptic neuron spikes within a narrow time window plays a critical role in determining the direction of synaptic changes. When a pre-synaptic neuron spike precedes a post-synaptic neuron spike within this window, it leads to a phenomenon known as long-term potentiation (LTP), which strengthens the synaptic connection. Conversely, if the order is reversed, with the post-synaptic neuron spike preceding the pre-synaptic one, it results in long-term depression (LTD), which weakens the synaptic connection. In experimental settings, researchers often repeatedly evoke pairs of pre-synaptic and post-synaptic spikes with a fixed time Fig. 1: The visualization of rate coding on the MNIST input image pixels and our network architecture. In the processing layer, a single excitatory neuron performs lateral inhibition over the other excitatory neurons, preventing them from firing due to the WTA feedback mechanism. The labels \(I\) and \(E\) represent input and excitatory neuron vertices, respectively. The variable \(K\) corresponds to the number of input pixels, whereas \(N\) shows the number of neurons in the processing layer. interval, denoted as \(\Delta t\). These pairs of spikes are typically repeated at a low frequency, and the resulting changes in synaptic response size are measured. By conducting this experiment for various values of \(\Delta t\), the timing-dependence of plasticity is mapped, creating what is referred to as an _STDP curve_. This curve is a valuable tool for predicting the plasticity outcomes when \(\Delta t\) varies, such as in response to arbitrary sequences of pre-synaptic and post-synaptic neuron spikes under less controlled conditions [15]. The visual representation of neurons and synapses undergoing different weight update scenarios in the context of STDP is depicted in Fig. 2. Let's consider two specific cases. **Case 1:** In this scenario, the input from pre-synaptic neuron 1 triggers the post-synaptic neuron to generate output spikes. This causal relationship increases the synapse's strength that connects the pre and post-synaptic neurons. **Case 2:** In contrast, pre-synaptic neuron 2 does not contribute to the output generation, and its spike arrives later than the output of the post-synaptic neuron. As a result, the strength of the synapse connecting pre-synaptic neuron 2 and the post-synaptic neuron is decreased. The mathematical expression for the weight changes in these scenarios is provided by Eq. 1. This equation quantifies how the synaptic weights are updated based on the timing and causal relationship between pre-synaptic and post-synaptic spikes, reflecting the principles of STDP. \[\Delta W=\left\{\begin{array}{ll}A_{pot}e^{-\Delta t/\tau_{pot}}&\quad \text{if }\Delta t>0\\ A_{dep}e^{+\Delta t/\tau_{dep}}&\quad\text{if }\Delta t<0\end{array}\right. \tag{1}\] The weight modulation in Eq. 1 expresses the principles of the asymmetric learning rule with two regions: LTP for weight increment and LTD for weight reduction. \(\Delta W\) represents the amount of change in synaptic strength. In order to realize this functionality in a circuit, a trace-based method can be implemented [16]. The exponential curve on the LTP region corresponds to the post-synaptic neuron spike-trace, whereas the LTD region curve represents the pre-synaptic neuron spike-trace. These traces capture the spiking activity of the pre-synaptic and post-synaptic neurons. The two variables \(A_{pot}\) and \(A_{dep}\) denote the maximum increment and decrement of synaptic strength on the _STDP curve_, respectively. The direction of \(\Delta W\) depends on the sign value of \(\Delta t\) as determined by the arrival order of pre and post-synaptic neuron spikes corresponding to \(\Delta t=t_{post}-t_{pre}\). Due to the resource constraints on the superconductor hardware, we employed quantized STDP update levels on \(\Delta W\) and synaptic weights that are discussed in the following section. ## III Proposed SFQ-based Online Training This section introduces essential superconductor-based mechanisms for the implementation of SNNs. Firstly, we present an STDP engine that effectively enforces the asymmetric rate STDP learning rule, underlining the motivation for synaptic implementations with a degree of biological plausibility [14]. Our design employs a _modified NDRO circuit_ to monitor pre- and post-synaptic neuron spikes precisely. Furthermore, our framework seamlessly integrates dynamic threshold behavior within LIF neurons, achieved through self-inhibition based on neuron output spikes [17]. Lastly, we propose a novel implementation of feedback interactions between neurons, facilitating our framework's realization of WTA characteristics. These combined mechanisms advance the field of SNNs and provide valuable tools for neuromorphic computing applications. ### _SFQ-based STDP Engine_ The proposed design of the STDP mechanism is tailored to perform both increment and decrement functions, thereby adjusting a finite state machine associated with the synapse structure. To enable STDP using superconductor-based components, we discretized the learning curve. This design, featuring a 1-bit resolution, incorporates two splitters (SPLs) with a fanout of 3, in addition to two leaky Non-Destructive Readout (LNDRO) circuits. The SPLs play a crucial role in internally increasing the fanout of inputs derived from pre- and post-synaptic neuron spikes, which are then assigned to the LNDRO pins. Furthermore, the STDP engine includes two output pins, labeled as _increment_ and _decrement_, as illustrated in Fig. 3. To generate a decrement output spike, one must establish the spike-trace relationship between pre- and post-synaptic neurons. In this operation, incorporating Splitters (SPLs) and a single LNDRO cell proves sufficient to generate decrement Fig. 3: Cell view of the quantized STDP design following the scheme given in Fig. 2. Trace-based spiking activity of pre and post-synaptic neurons is recorded in each leaky NDRO. Fig. 2: Example neuron and synapse scheme with pre and post-synaptic neuron spike cases for the learning curves of STDP. behavior with a 1-bit resolution. A similar setup can be set up to produce spikes on the increment output pin for generating an increment behavior. If a higher bit resolution is desired, the overall design necessitates the incorporation of SPLs with increased fanout, additional LNDROs with varying decay rates, and the inclusion of two merger components for LNDRO outputs. In this design, an NDRO with multi-flux storing characteristics is suitable to create the synapse behavior since the amount of stored flux corresponds to the state of a synapse [18]. The introduction of leaky behavior in the standard NDRO cell is achieved by inserting a resistor into the SFQ storage loop, as illustrated in Fig. (a)a. The LNDRO is simulated using JoSIM, and the waveforms are given in Fig. (d)d. When a spike arrives at the input _in_, the spike is split for the _reset_ and _set_ pins. To recreate the correct spike-trace functionality, the spike from _reset_ initially erases the current in the leaky storing loop (JJ2-L2-R1-L3-L5-JJ4). By applying the spike arriving late due to the _Delay cell_, the spike-trace is updated, and the current gradually decays with a constant time of \(\tau\) due to the inserted resistor. Concurrently, the state of the LNDRO can be read by a spike from the _clock_ pin. Due to the quantization of the STDP curve shown in Fig. (c)c, a spike on _out_ can only be observed until a quantization point, set as 25 ps in the simulation. ### _LIF Superconductor Neurons with Dynamic Threshold_ The threshold value of a neuron determines the firing rate and shapes the computational behavior of a neural network. In this context, relying on a neuron with a fixed threshold can impose challenges in neural processing, such as high sensitivity to input fluctuations and excessive spike firing, resulting in high dynamic power consumption. The adaptability of a neuron with a dynamic threshold contributes to the network stability and contextual responsiveness [19]. For instance, the digits in the MNIST handwritten dataset may share the same pixels. In this case, the multiple neurons in the output layer may have high-valued synaptic weights on these pixels and generate an output spike due to the neurons having the same threshold for the classification, hindering the overall performance. Hence, the implementation of an adaptive threshold behavior becomes indispensable to address this issue effectively. Adjusting the threshold of a superconductor-based neuron is typically achieved by dynamically changing the bias current and critical current of the JJs. Such modifications introduce additional hardware design complexity. Therefore, we utilize the generated output spike as a feedback input, creating self-inhibition behavior as shown in Fig. 5. The membrane state of a neuron plays a pivotal role in determining whether an output spike is generated at a specific moment in time. When the membrane state surpasses a certain threshold, a single spike is triggered at the neuron's output. The resting state of a neuron corresponds to its default state, characterized by the absence of spike activity. Within a neural network, certain neurons may exhibit a high firing rate, exerting a disproportionate influence on decision-making and potentially disrupting the network's balance. Consequently, there is a need for methods to mitigate such behavior and maintain network equilibrium. The proposed self-inhibition technique serves as a mechanism for temporarily preventing a neuron from firing multiple spikes in quick succession. It achieves this by reducing the membrane state below the resting state, as illustrated in Fig. 5. In the context of superconductor circuits, the membrane state corresponds to the amplitude of stored current, and the threshold is determined by the amount of current required to trigger Fig. 4: LNDRO functional verification and its representation for the quantized STDP on the learning curve. Fig. 5: LIF neuron with dynamic threshold using self-inhibition. The membrane state of a superconductor LIF neuron corresponds to the amount of current stored in its leaky loop. The neuron resting state is the baseline condition where no spike is received or generated. the decision-making Josephson junction (JJ). By employing the self-inhibition mechanism, a neuron can momentarily dip below its resting state, thus demanding more input current to reach the threshold level. An example design utilizing \(\alpha\)-Soma [20] is depicted in Fig. 5(a). A similar effect can be achieved for neurons receiving inputs from inductances with mutual couplings [21] by directing the neuron's output spike back into the same neuron's input through an inductance with negative coupling. This generates a current in the opposite direction, counteracting the threshold mechanism. The simplified test case utilizes a soma circuit that acts as an asynchronous threshold gate with a threshold of two spikes within \(\approx\)50 ps i.e., an output spike is generated whenever two input spikes arrive within the designated time frame. Within this configuration employing \(\alpha\)-Soma, the output spike is provided to the following SPL cell. One of the SPL outputs is connected to the input of \(\alpha\)-cell, enabling the spike to propagate back into the soma cell. This operation negatively impacts the loop current due to the opposite direction of the spike. The example demonstration of digital inhibition with \(\alpha\)-Soma preventing the generation of continuous output spikes is shown in Fig. 6. ### _WTA Mechanism with Superconductor Devices_ One of the fundamental computational models in spiking neural networks is a winner-take-all (WTA) principle, establishing a form of competition for activation among the neurons within the same layer [13]. The neuron with a higher activation affects the activity of interconnected neurons by inhibition. As a result, the winner neuron becomes the sole source of output spikes. This selective mechanism enables noise filtering and input focus on the critical data. We present a way that enables interaction among the excitatory neurons to prevent each other from firing, fundamentally implementing the WTA principle. The firing information is obtained from an inductance at the output _Lload_, next to the JJ, that determines the threshold operation. Note that the choice of inductance for coupling can be placed between the threshold junction _JJsoma1_ and the ground node; however, this option requires a balance adjustment between the decay rate of the input side and lateral inhibition since such inductance is a part of the leaky storage loop of the soma circuit [20]. The interaction among neurons is established by inductive coupling \(K\) between an output inductance (Lload) and inductance in a feedback loop (Rwta1-Lwta1-Lwta2-Rwta2) shown in Fig. 6(a). The feedback loop consists of Lwta inductances for each neuron and resistors (Rwta) on each end. Therefore, any activation on a threshold junction will result in a change of current within this loop. Due to the coupling, the current on the feedback loop will affect the other neurons via coupled inductances. Each input spike creates a current determined by a resistor within the leaky storage loop of superconductor LIF neurons. Unlike this input, the inhibition current from a neuron to other neurons mainly depends on the value of the coupling \(K\). Therefore, high inductive coupling results in a higher lateral suppression by a neuron. The JoSIM results of the proposed method with an example of soma circuits are shown in Fig. 7. In our testbench, two soma circuits are designed to have a threshold of 2 spikes and \(\approx\) 50 ps decay time. Initially, these circuits receive spikes with 75 ps time difference. Due to the current decay within the spike-storing loop on the input side of the soma, no output is generated. Next, two spikes with a short time interval are applied to the soma circuits. The first soma receives its inputs before the inputs of the second soma. As a result, the first soma fires earlier than the second one. The late-firing soma is expected to generate an output when no interaction exists among the somas. However, if the WTA mechanism is employed, the first soma inhibits the second soma. Note that there will be no lateral inhibition if the spike frames between the soma circuits do not overlap. ## IV Results In our work, we utilized the BindsNET framework for high-level network modeling. We primarily focused on the intrinsic network properties and performance. We targeted the digits 0 and 1 of the MNIST dataset to evaluate the on-chip training network. The image count was 633 for the training and 105 for the testing images of 0s and 1s, corresponding to 5% of the overall digit images of 0s and 1s within the dataset. Images were randomly selected, and each image was downscaled from 28 by 28 pixels to 14 by 14 pixels. The training epoch count was assigned as 1, and each image was shown for 100 ps to the network. The neuron resting state was 0, and their neuron threshold was set to eight spikes. While threshold decay to the resting state was active, the dynamic threshold increment from the post-synaptic neuron spike was set to 32 inhibitory spikes. In our network structure, this value prevented the firing neurons Fig. 6: Design of LIF neuron with self-inhibition and JoSIM results for \(\alpha\)-Soma. All parameter values of the cells are kept the same, and the self-inhibition is prevented by disconnecting the node between the input of \(\alpha\)-cell and output of SPL. from entering burst mode and gave other neurons a chance to fire. The membrane decay time of neurons was set to 25 ps. For the synaptic characteristics, the increment and decrement in weight adjustments from the STDP mechanism were assigned as two spikes and one spike, respectively. Therefore, the spike generation on the increment side of the proposed STDP engine required a modification to have twice as much impact as the decrement side. For the spike activity of pre- and post-synaptic neurons, we assigned 10 ps to the spike-trace decay rate \(\tau\), keeping it within a reasonable time frame. Two network architectures were considered, including architectures with 4 and 9 excitatory neurons with a weight resolution of 4 bits, corresponding to 16 different synaptic stages. Unlike the conventional implementations, we did not use any weight normalization technique in the on-chip training setting. Accessing all weights to perform such an operation is not hardware-friendly, even though weight normalization gives all neurons a chance to fire and offers a better weight convergence. The dynamic threshold adaptation with decaying fashion temporarily compensates for the weight normalization. Some neurons can rapidly go into a burst mode without this feature and become dominant. However, when the decay time is relatively short compared to the duration of multiple input images, the neuron tends to forget the learned pattern, leading to an increase in the majority of its weights. On the other hand, we kept a weight clipping operation to limit the weight between 0 and 1 (scaled from the range of 0 - 15). For the overall configuration, the estimated JJ count would be \(\approx\) 31k with four neurons and \(\approx\) 85k with nine neurons. In the case of training first architecture (4 excitatory neurons), we acquired an accuracy of 90.32% for training and 81.9% for testing. During the convergence, we observed that the neurons representing digit 1 still have traces of digit 0 and vice versa due to the bit resolution and no weight normalization. We also observed cases where some neurons go into a burst mode due to the random weight initialization. Therefore, a mechanism to thoroughly address this issue in lower-bit resolutions must be investigated. The 2D weight values are illustrated in Fig. 8 for each neuron of the considered architecture. The displayed weight values, arranged from left to right, represent snapshots taken at every one-third interval of the training process, spanning from iteration 0 to 633. The training settings are kept the same for the second network architecture (with nine neurons) to observe the impact of neuron count on the performance. The results showed an accuracy of 96.77% for training and 97.1% for testing, indicating a performance improvement. Therefore, increasing the number of neurons in the network positively influences the overall accuracy with a trade-off of hardware resources, supporting the motivation for large-scale implementations. The 2D weight values of this architecture during the training are illustrated in Fig. 9 ## V Conclusion This paper explored the capabilities of an on-chip training mechanism on superconductor spiking neural networks. We designed a leaky NDRO circuit and simulated its behavior with JoSIM. The leaky NDROs record spike traces to achieve a quantized STDP mechanism. Furthermore, we demonstrate a self-inhibition method for superconductor-based structures to establish the dynamic threshold behavior in LIF neurons. We also implement a superconductor winner-take-all mechanism to support the correct network behavior. The on-chip training capabilities are shown with a computational BindsNET framework, and we achieved \(\approx\)97% accuracy with 9 neurons for the classification of digits 0 and 1. These findings collectively highlight the promise of on-chip training in superconductor-based spiking neural networks. Fig. 8: Network training result using four excitatory neurons. Fig. 7: WTA mechanism and JoSIM results for soma circuits. Fig. 9: Network training result using nine excitatory neurons.
2306.10066
On the Interplay of Subset Selection and Informed Graph Neural Networks
Machine learning techniques paired with the availability of massive datasets dramatically enhance our ability to explore the chemical compound space by providing fast and accurate predictions of molecular properties. However, learning on large datasets is strongly limited by the availability of computational resources and can be infeasible in some scenarios. Moreover, the instances in the datasets may not yet be labelled and generating the labels can be costly, as in the case of quantum chemistry computations. Thus, there is a need to select small training subsets from large pools of unlabelled data points and to develop reliable ML methods that can effectively learn from small training sets. This work focuses on predicting the molecules atomization energy in the QM9 dataset. We investigate the advantages of employing domain knowledge-based data sampling methods for an efficient training set selection combined with informed ML techniques. In particular, we show how maximizing molecular diversity in the training set selection process increases the robustness of linear and nonlinear regression techniques such as kernel methods and graph neural networks. We also check the reliability of the predictions made by the graph neural network with a model-agnostic explainer based on the rate distortion explanation framework.
Niklas Breustedt, Paolo Climaco, Jochen Garcke, Jan Hamaekers, Gitta Kutyniok, Dirk A. Lorenz, Rick Oerder, Chirag Varun Shukla
2023-06-15T09:09:27Z
http://arxiv.org/abs/2306.10066v1
# On the Interplay of Subset Selection and ###### Abstract Machine learning techniques paired with the availability of massive datasets dramatically enhance our ability to explore the chemical compound space by providing fast and accurate predictions of molecular properties. However, learning on large datasets is strongly limited by the availability of computational resources and can be infeasible in some scenarios. Moreover, the instances in the datasets may not yet be labelled and generating the labels can be costly, as in the case of quantum chemistry computations. Thus, there is a need to select small training subsets from large pools of unlabeled data points and to develop reliable ML methods that can effectively learn from small training sets. This work focuses on predicting the molecules' atomization energy in the QM9 dataset. We investigate the advantages of employing domain knowledge-based data sampling methods for an efficient training set selection combined with informed ML techniques. In particular, we show how maximizing molecular diversity in the training set selection process increases the robustness of linear and nonlinear regression techniques such as kernel methods and graph neural networks. We also check the reliability of the predictions made by the graph neural network with a model-agnostic explainer based on the rate-distortion explanation framework. ## 1 Introduction Modelling the relationship between molecules and their properties is of great interest in several research areas, such as computational drug design [37], material discovery [43] and battery development [3]. The field of computational chemistry offers powerful _ab initio_ methods to compute physical and chemical properties of atomic systems. Unfortunately, these approaches are often limited by their high computational complexity, which restricts their practical applicability to only small sets of molecules. Therefore, machine learning (ML) methods for molecular property prediction have recently gained increased attention in molecular and material science because of their computational efficiency and accuracy on par with established first principle methods [4; 5; 11]. However, to effectively employ ML in real-world problems, there is a need for labelled datasets that can effectively represent the chemical space of interest, i.e., sets of molecules for which the target properties have already been computed using ab initio methods. Thus, on the one hand, accurately choosing which data points to label in the analyzed chemical space is crucial to avoid creating a dataset with redundant information and limiting the required amount of ab initio calculations. On the other hand, it is critical to develop data-efficient ML methods that perform accurate predictions. Integrating domain knowledge of physical and chemical principles into the dataset selection process and the development of ML techniques is a primary goal of the chemical and material science ML community [31]. Physical and chemical principles, such as spatial invariances, symmetries, algebraic equations and chemical properties, can increase the robustness, reliability and effectiveness of ML methods while reducing the required training data [6; 58]. This work focuses on predicting the atomization energies of molecules in the QM9 dataset [47; 49] and shows how to exploit domain knowledge to select training sets according to specific criteria and how different ML methods may benefit from training on sets selected through such criteria. Specifically, by using Mordred [42], a publicly available library, we generate knowledge-based vector representations of molecules based on their SMILES representation [59] without requiring any ab initio computations. Further, based on such a molecular vector-based representation, we define a training set selection process and can observe that a diversity in the selected subset can increase the reliability of ML methods, indicated by the reduction of the maximum absolute error of the prediction. The maximum absolute error can be interpreted as a measure of robustness, and it is a helpful metric to evaluate ML methods in chemical and material science [65] since the average error alone gives an incomplete impression [19; 55]. Furthermore, this work shows how diversity reduces the gap between the predictive robustness of linear regression-based approaches relying only on the molecular topological information, such as kernel ridge regression (KRR) [32], and non-linear approaches relying on molecular geometric representations obtained through ab initio computations, such as graph neural networks (GNN) [17; 24; 26]. We compare the effectiveness of a diversity-based selection with that of random sampling and of an alternative selection approach based on domain knowledge that focuses on representativeness, i.e., the distribution of chosen properties of the dataset should be present with the same amount in the selected training sets. Finally, we note that our GNNs are inherently opaque (i.e. the logic flow to the decision-making process of the neural network is obscured). This inherently opaque nature of common deep neural network architectures has led to a rise in demand for trustworthy explanation techniques, which vary in their meaning and validity [48]. Unlike other modalities in computer vision and natural language processing, the non-Euclidean nature of graph-structured data poses a significant challenge to trustworthy and interpretable explanation generation. To this end, there exist a variety of explanation techniques and explanation types [12; 21; 36; 46; 51; 60; 62; 64], the most popular of which are subgraph explanation techniques. We probe the domain knowledge learned/retained by our GNNs for different sampling strategies through the application of a novel _post-hoc_ model-agnostic explanation technique, graph rate-distortion explainer (GRDE). GRDE builds on the existing rate-distortion explanation (RDE) framework [27; 38] to generate _instance-level_ subgraph explanations on the input graphs, which highlight the substructures and features in the graph that are most relevant towards the GNNs' predictions. In the following, we first give an overview on three ML models that are designed for the prediction of molecular properties but are based on different underlying working principles. In this way, we hope that our results yield insights for a variety of methods that are used in practical applications. Following that, we discuss two ways of sampling subsets from a larger dataset, one aiming to maximize the diversity of the selected samples and the other seeking to choose a collection of points representative of the set from which we sample. Afterwards, we test the introduced methods, namely the SchNet, KRR and the spatial 3-hop convolution network which is proposed in this work, by performing numerical experiments on the QM9 dataset while putting special emphasis on the effects of the sampling strategies. After a discussion of the numerical results and a comparison between the different ML models, we seek explanations of the model predictions by applying GRDE to one of the employed graph neural networks. ## 2 Related Work In recent years, there has been growing interest in incorporating domain-specific knowledge into the selection of training data and the development of learning algorithms, which is referred to as informed machine learning [58]. Ideally, the training data selection process should be based purely on the data's features, as labels may be expensive to compute, and should be model-independent so that the selected training data is beneficial for multiple learning models rather than just one. This allows for greater flexibility in model selection and avoids the need for repeating the dataset selection process for each model. Considering these practical aspects, it is clear that a feature-based and model-independent selection process is desirable for efficient and effective machine learning. This section reviews some of the relevant work in this area. Coreset approaches [14] are among the most popular strategies for feature-based and model-independent selection of training datasets. Several of these approaches involve incorporating domain-knowledge into the selection of training data by selecting data points that are representative of the distribution of the target points for which we want to predict the new labels. The simplest and yet one of the most common coreset approaches is uniform sampling, which involves selecting a random subset of data points from the larger dataset. Uniform sampling is also considered a benchmark for every other selection approach. Unfortunately, uniform sampling does not exploit domain knowledge and can lead to biased results if the dataset is imbalanced or if certain data points are more important than others. To address this issue, importance sampling [7] is an approach that exploits domain knowledge to assign weights to each data point based on its importance or relevance to the problem at hand. The weights are then used for a nonuniform selection of the training set that privileges more important data points. Another class of methods are the grid-based approaches [2], which involve dividing the feature space into a grid and selecting one or more representative points from each grid's cell. This can be useful for problems with a high-dimensional feature space or when there is a need for a more structured selection of data points. Greedy constructions are coreset approaches that iteratively select the most informative data points based on a pre-defined criterion. For instance, well-known greedy selection methods are submodular function maximization algorithms [30]. Greedy approaches can be effective for selecting a small subset of highly informative data points, but they may be computationally expensive for large datasets. Overall, the choice of coreset approach depends on the specific problem and dataset characteristics, as well as computational constraints. See [14] for a more detailed review of coreset approaches. Finally, the field of experimental design [61] offers additional sampling strategies to perform a feature-based selection of the training set that can benefit specific regression model classes, e.g., linear models. In this work, incorporating domain knowledge in the learning of algorithms refers to methods which are known as informed graph neural networks. While graph neural networks recently gained increasing attention by the works from Gori et al. [18] and Scarselli et al. [50], the question of how to use domain knowledge to improve the performance of learning methods dates back to the last century (e.g. see [23] or [29]). More recently, physics informed neural networks, which address supervised learning tasks complying with the known laws from physics, are a hot topic in several applications, e.g. to find surface breaking cracks in a metal plate [53] or to solve inverse heat transfer problems [8]. For graph neural networks, based on the message passing principle, i.e. the process of updating so called states or representations attached to each node of a graph using the node's neighbourhood, many different models were proposed (e.g. Graph Attention Networks [57], ChebNet [10], Gated Graph Neural Networks [34]), the most popular being the graph convolutional model by Kipf and Welling [26] which is motivated by an approximation of spectral graph convolutions. Combining incorporating domain knowledge with graph neural networks leads to the very recent informed graph neural networks. In [20] the authors combine theory from thermodynamics with graph neural networks to predict the behaviour of dynamical systems and in [25] combine physical properties of molecules are combined with graph neural networks to predict the cetane number of possible alternative fuels. For more detailed overviews on GNNs or informed neural networks we refer to the book [35] and a recent review [9]. We further build upon the interpretability of graph neural networks in this work by introducing a method akin to perturbation techniques on image data to graph structured data. The main goal of interpretability is to invoke transparency in the otherwise opaque prediction process of neural networks, and is further applicable in the detection of bias as well as to explain incorrect classifications in the predictive model. Previous work in interpretability for other modalities such as audio and images [27; 38] has shown great success in identifying a neural network's sensitivity to specific subsets of the input data. More specifically, among the variety of local and global interpretability techniques, perturbation [27; 28] and gradient-based [54] techniques have been shown to accurately capture a predictive model's sensitivity to some concepts in the input data. These techniques generally seek to optimize a heatmap over the input data such that high-intensity zones are the most relevant to the model's prediction for the given data point. We further discuss this in detail with respect to graphs in section 3.4. Inspired by the exhaustive work on interpretability for other modalities, several methods [36; 46; 51; 60] have also been proposed for graph-structured data, with perturbation techniques such as GNNExplainer [60] being the baseline for comparison. For a detailed overview of GNN interpretability, we refer to [63]. These techniques, however, have been shown to suffer from unfaithfulness on large graphs since they optimise masks only for small graphs as well as manually threshold their relevance scores. See [1] for a detailed review on the current issues with graph interpretability. ## 3 Methods and Sampling Strategies This section introduces the approaches we use for predicting the atomization energy, explaining the GNN output and sampling the training data. Subsection 3.1 introduces the benchmark regression model SchNet, a GNN that uses 3-dimensional positional information to predict chemical properties. Next, subsections 3.2 and 3.3 describe KRR and the spatial 3-hop convolution network, respectively. Both these approaches only exploit topological information encoded in the SMILES to perform the energy prediction task. Subsection 3.4 presents the rate-distortion explanation framework for graph data that we use to showcase the domain knowledge learned by the 3-hop convolution network. Finally, subsection 3.5 introduces the approaches we use for the selection of training sets. ### SchNet SchNet is a symmetry-informed neural network model, designed for the prediction of chemical properties by Schutt et al. [52]. In contrast to the methods presented in sections 3.2 and 3.3, it is trained and evaluated on 3-dimensional structural information describing the atomic systems of interest. Usually, the positional information is obtained from computational methods such as density functional theory (DFT). More formally, for an atomic system with N atoms, SchNet can be used to predict scalar properties as a function \(f\) of \(3N\) atomic coordinates (nuclear positions) and on \(N\) atomic numbers of the corresponding atoms: \[f:\mathbb{R}^{3N}\times\mathbb{N}^{N}\rightarrow\mathbb{R}. \tag{1}\] Internally, SchNet operates on a distance-based neighborhood graph, defined by a cutoff radius \(r_{\text{cut}}\), in which nodes correspond to the atoms in the atomic system. In this scenario, edges do not necessarily correspond to chemical bonds but merely indicate whether two atoms are closer than the chosen cutoff radius. Hence, the chosen cutoff radius has a direct influence on the graph shown to the model. Similar to other GNNs [17; 26], SchNet operates in a layer-wise fashion by iteratively updating feature representations. At the \(l\)-th layer each atom, indexed by \(i\in\{1,2,...,N\}\), is represented by a feature vector \(\mathbf{x}_{i}^{l}\in\mathbb{R}^{F}\) where \(F\) is a hyperparameter. The main layer introduced by Schutt et al. is the continuous-filter convolutional layer: Denoting the atomic positions by \(\mathbf{r}_{i}\in\mathbb{R}^{3}\), this layer updates the atomic features as follows: \[\mathbf{x}_{i}^{l+1}=\sum_{j\in\mathcal{N}(i)}\mathbf{x}_{j}^{l}\circ W^{l}\left(\mathbf{r }_{i}-\mathbf{r}_{j}\right), \tag{2}\] where \(W^{l}:\mathbb{R}^{3}\rightarrow\mathbb{R}^{F}\) is a trainable filter-generating function and \(\circ\) denotes element-wise multiplication. In detail, \(W^{l}\) is given as the composition \(W^{l}=\tilde{W}^{l}\circ\varphi\) of a distance-based radial basis expansion \[\varphi:\mathbf{r}_{i}-\mathbf{r}_{j}\mapsto\bigoplus_{k=1}^{N_{\text{radial}}}\exp \left(-\gamma\left(\|\mathbf{r}_{i}-\mathbf{r}_{j}\|_{2}-\mu_{k}\right)^{2}\right) \tag{3}\] and a trainable neural network \(\tilde{W}^{l}\) where \(0\,\text{A}\leq\mu_{k}\leq 30\,\text{A}\) are equidistributed centers and \(\gamma=10\,\text{A}\). Here, \(\bigoplus\) denotes the direct sum that concatenates the scalar outputs of the radial basis functions to a feature vector in \(\mathbb{R}^{N_{\text{radial}}}\) which is then passed into \(\tilde{W}^{l}\). Note that \(\varphi\) is invariant with respect to actions of the orthogonal group \(O(3)\) which assures that the predictions of SchNet are invariant with respect to translations, rotations and reflections of the input structure as well. Depending on the atomic species, initial embeddings \(\mathbf{x}_{i}^{0}\) are sampled from an \(F\)-dimensional standard normal distribution and optimized during the training process. In addition, non-linear layers such as dense feed-forward neural networks can be applied to the node features in order to increase the expressiveness of the model. By summing over the images of a trainable readout function \(R:\mathbb{R}^{F}\rightarrow\mathbb{R}\), the final node features in the last layer \(L\) are transformed into a prediction of the target property \(\hat{y}\): \[\hat{y}=\sum_{j=1}^{N}R\,\left(\mathbf{x}_{j}^{L}\right) \tag{4}\] Involving only permutation-invariant operations such as the summation over adjacent atoms, the output is invariant with respect to mutual permutations of the atomic positions and atomic species. For more details on the model architecture see [52]. ### Kernel Ridge Regression In kernel ridge regression, a vector-based representation of the molecules is mapped into a high-dimensional space using a non-linear map that is implicitly determined by defining a kernel function, which provides a measure of similarity between the molecular representations. The structure-energy relationship is learned in the high-dimensional space. In this work, we use the so-called Gaussian kernel \[k(\mathbf{x}_{i},\mathbf{x}_{j}):=e^{-\frac{\|\mathbf{x}_{i}-\mathbf{x}_{j}\|_{2}^{2}}{2\nu^{2 }}}, \tag{5}\] where \(\|\cdot\|_{2}\) is the \(L_{2}\)-norm and \(\nu\in\mathbb{R}\) a kernel hyperparameter to be selected through an optimization process. The kernel ridge regression model is constructed using the selected training set \(\{\mathbf{x}_{i},y(\mathbf{x}_{i})\}_{i=1}^{p}\), where \(\{\mathbf{x}_{i}\}_{i=1}^{p}\) are the Mordred [42] based vector representations of the molecules and \(\{y(\mathbf{x}_{i})\}_{i=1}^{p}\) the associated atomization energies. Once the regression model has been constructed, the predicted energies are given by the scalar values \(\tilde{y}(\mathbf{x})\) defined as follows \[\tilde{y}(\mathbf{x}):=\sum_{i=1}^{p}\alpha_{i}k(\mathbf{x},\mathbf{x}_{i}), \tag{6}\] where the vector \(\mathbf{\alpha}=[\alpha_{1},\alpha_{2},\ldots,\alpha_{p}]^{T}\in\mathbb{R}^{p}\) is the solution of the following minimization problem \[\mathbf{\alpha}=\operatorname*{argmin}_{\tilde{\mathbf{\alpha}}}\sum_{i=1}^{p}(\tilde {y}(\mathbf{x}_{i})-y(\mathbf{x}_{i}))^{2}+\lambda\bar{\mathbf{\alpha}}^{T}\mathbf{K}\bar{\bm {\alpha}}. \tag{7}\] Here, \(\mathbf{K}\) is the kernel matrix, i.e., \(\mathbf{K}_{i,j}=k(\mathbf{x}_{i},\mathbf{x}_{j})\), and the parameter \(\lambda\in\mathbb{R}\) is the so-called regularization parameter that penalizes larger weights. The analytic solution to the minimization problem in (7) is given by \[\mathbf{\alpha}=(\mathbf{K}+\lambda\mathbf{I})^{-1}\tilde{\mathbf{y}} \tag{8}\] where \(\tilde{\mathbf{y}}=[\tilde{y}(\mathbf{x}_{1}),\tilde{y}(\mathbf{x}_{2}),\ldots,\tilde{y} (\mathbf{x}_{p})]^{T}\). Once the training process has been concluded and the regression parameters \(\{\alpha_{i}\}_{i=1}^{p}\) have been learned, the energy predictions for molecules not included in the training set can be computed using Equation (6). ### Spatial 3-Hop Convolution Network In addition to the two previous approaches, we propose a third approach which builds on a newly developed spatial graph convolution structure. We call this approach spatial 3-hop convolution network. This approach exploits the graph structure, the node features and optionally edge features for regression or classification but does not need 3-dimensional structural information as is the case for SchNet. A commonly used graph convolutional network by Kipf & Welling [26] is motivated by an approximation of a spectral convolution. Thereby, they consider spectral convolutions as \[\mathbf{w}\star\mathbf{x}=\mathbf{U}\mathbf{w}\mathbf{U}^{\top}\mathbf{x}, \tag{9}\] where \(\mathbf{w}=diag(\theta)\in\mathbb{R}^{n\times n}\) is a filter, \(\mathbf{x}\in\mathbb{R}^{n}\) is a graph signal on a graph with \(n\) nodes, \(\star\) denotes the spectral graph convolution operator and \(\mathbf{U}\) is the matrix of eigenvectors from the eigendecomposition of the normalized graph Laplacian \(\mathbf{I}_{n}-\mathbf{D}^{-\frac{1}{2}}\mathbf{A}\mathbf{D}^{-\frac{1}{2}}\). Moreover, \(\mathbf{A}\) is the adjacency matrix of the underlying graph, \(\mathbf{D}\) is the corresponding degree matrix and \(\mathbf{I}_{n}\) is the \(n\times n\) identity matrix. This convolution is approximated and generalized to matrix-valued graph signals which leads to the update of the graph convolutional network \[\mathbf{H}^{(l+1)}=\sigma(\mathbf{H}^{(l)}\mathbf{W}_{0}+\mathbf{D}^{-\frac{1}{2}}\mathbf{A}\mathbf{D }^{-\frac{1}{2}}\mathbf{H}^{(l)}\mathbf{W}_{1}), \tag{10}\] where \(\mathbf{H}^{(l)}\) is the matrix of hidden representations of the \(l\)-th layer, \(\mathbf{W}_{0}\) and \(\mathbf{W}_{1}\) are learnable parameters and \(\sigma\) denotes the elementwise ReLU function. For the spatial 3-hop convolution layer we do not consider spectral graph convolutions but an intuitive spatial convolution using powers of the graphs adjacency matrix to calculate so called path matrices. Within these, for each node the number of paths of a certain length to every other node is stored. By defining a spatial convolution with path matrices and building a layer of the graph neural network using the convolution, we consider the number of paths of a given length from node \(v\) to node \(u\) as a measure for the impact of node \(v\) on node \(u\). Thus, nodes with more paths to the considered node will be taken into account more during the update. For a graph \(G\) with \(n\) nodes a path is defined as a sequence of nodes \((1,\ldots,k)\) with \(k<n\) such that for any \(i,j\in(1,\ldots,k)\) it is \(i\neq j\), i.e. no node appears twice. With that, we define a spatial \(k\)-hop graph convolution of a graph signal \(\mathbf{x}\in\mathbb{R}^{n}\) with a filter \(\mathbf{w}\in\mathbb{R}^{k}\) on an undirected graph \(G\) with \(n\) nodes as \[\mathbf{w}\star_{k}\mathbf{x}:=\sum_{i=0}^{k}\mathbf{w}_{i}\mathbf{T}^{(i)}x,\] where \(\mathbf{T}^{(i)}\) is a path matrix such that \(\mathbf{T}^{(i)}_{eu}\) is the number of paths of length \(i\) from node \(v\) to node \(u\). An approach to computing the needed path matrices is a recursion that starts with the adjacency matrix. Since the adjacency matrix equals the path matrix for paths of length one it is \(\mathbf{T}^{(1)}=\mathbf{A}\). For every node \(i\) and \(u\) a neighbor of it, the number of paths of length two from node \(i\) to node \(j\) equals the number of paths of length one from \(u\) to \(j\) in which \(i\) is not a part of. More generally, the number of paths of length \(k\) from a node \(i\) to a different node \(j\) equals the sum of all paths from node \(u\) to \(j\) of length \(k-1\) over all \(u\in\mathcal{N}(i)\) in which \(i\) does not appear. Using this, it can be shown that \(\mathbf{T}^{(2)}=\mathbf{A}^{2}-\mathbf{D}\) and \(\mathbf{T}^{(3)}=\mathbf{A}^{3}-\mathbf{\Sigma}\circ\mathbf{A}\), where \(\mathbf{A}\) and \(\mathbf{D}\) are as above and \(\mathbf{\Sigma}\) is an \(n\times n\) matrix with \(\mathbf{\Sigma}_{ij}=\mathbf{D}_{ii}+\mathbf{D}_{jj}\). This shows that the 3-hop spatial graph convolution is given by \[\mathbf{w}\star_{3}\mathbf{x}=(\mathbf{w}_{0}\mathbf{I}_{n}+\mathbf{w}_{1}\mathbf{A}+\mathbf{w}_{2}(\mathbf{A} ^{2}-\mathbf{D})+\mathbf{w}_{3}(\mathbf{A}^{3}-\mathbf{\Sigma}\circ\mathbf{A}))\mathbf{x}.\] Note that the \(\mathbf{w}_{k}\)'s can be seen as weights for the \(k\)-hop neighborhoods. A generalization of the former discussion to a signal \(\mathbf{X}\in\mathbb{R}^{n\times d}\) with \(c\) node features for each node (analogously to Kipf & Welling [26]) leads to \[\mathbf{H}=\mathbf{X}\mathbf{W}_{0}+\mathbf{AX}\mathbf{W}_{1}+(\mathbf{A}^{2}-\mathbf{D})\mathbf{X}\mathbf{W}_{2}+ (\mathbf{A}^{3}-\mathbf{\Sigma}\circ\mathbf{A})\mathbf{X}\mathbf{W}_{3},\] which results in the spatial 3-hop convolution layer, the message passing layer of the spatial 3-hop convolution network, \[\mathbf{H}^{(l+1)}=\sigma(\mathbf{H}^{(l)}\mathbf{W}_{0}+\mathbf{A}\mathbf{H}^{(l)}\mathbf{W}_{1}+( \mathbf{A}^{2}-\mathbf{D})\mathbf{H}^{(l)}\mathbf{W}_{2}+(\mathbf{A}^{3}-\mathbf{\Sigma}\circ\mathbf{A}) \mathbf{H}^{(l)}\mathbf{W}_{3}),\] where \(\sigma\) is, again, the element-wise ReLU function. ### Graph Rate-Distortion Explanations We now present a formulation for the rate-distortion explanation framework [27; 38] for graph data. Given a pre-trained GNN model, \(\Phi:\mathbb{R}^{n\times c}\longrightarrow\mathbb{R}^{m}\) and a set of attributed graphs \(G=\{G_{1},G_{2},...,G_{p}\}\) such that \(G_{i}=(V_{i},E_{i},X_{i})\) for all \(i\in[1,p]\), our task is to explain the model decision over the set \(G\), or more locally, \(\Phi(G_{i})\). This leads us to the two general branches of explanation techniques: global and local explanations. Global explanation techniques focus on explaining the underlying function learned by the model, \(\Phi\). This can be done in a multitude of ways, such as testing the model's sensitivity to a concept [40] or reconstructing graphs from the embedding space learned by the model to reveal important motifs [62]. In general, global explanation techniques, while useful, are hard to construct and are unable to detect finer details on local data points. On the other hand, local explanation techniques, which are the more popular alternative, focus on explaining \(\Phi\) for local instances, i.e. \(\Phi(G_{i})\). Similar to global explanations, there exist a variety of approaches, such as perturbation-based methods [36; 51; 60], surrogate methods [21], gradient-based methods [46], and additive methods [12; 64], each with their benefits and limitations. These techniques aim to extract information from \(G_{i}\) that is most relevant to the local prediction \(\Phi(G_{i})\). More concretely, given a graph \(G_{i}=(A_{i},X_{i})\), local explanation techniques commonly attempt to extract a subgraph \(\hat{G}_{i}=(\hat{A}_{i},\hat{X}_{i})\subseteq G_{i}\) that is most relevant to the model for its prediction \(\Phi(G_{i})\). The rate-distortion framework for explaining graphs is a local, post-hoc, model-agnostic explanation technique that comes under the umbrella of perturbation-based graph explainers. Given the pre-trained model \(\Phi\) and graph \(G_{i}\), GRDE optimizes a binary deletion mask \(S=(S_{A},S_{X})\) over \(G_{i}\) to obtain a subgraph \(\hat{G}_{i}\) such that \(\Phi(\hat{G}_{i})\) approximates \(\Phi(G_{i})\). Mask \(S\) thus retains only the edges and features that are most relevant to the model's prediction on \(G_{i}\). Given \(A_{i}\in\mathbb{R}^{n\times n}\) and \(X_{i}\in\mathbb{R}^{n\times f}\), where \(n\) is the number of nodes and \(f\) is the number of node features, our goal is to optimize masks \(S_{A}\in[0,1]^{n\times n}\) and \(S_{X}\in[0,1]^{n\times f}\). Let \(\mathcal{V}_{S}=(\mathcal{V}_{S_{A}},\,\mathcal{V}_{S_{X}})\) be probability distributions that can either be chosen manually or learned from the graph dataset. Then the obfuscation on \(G_{i}\), i.e. the subgraph \(\hat{G}_{i}\), can be defined as \[\hat{G}_{i}=(\hat{A}_{i},\hat{X}_{i})=(A_{i}\odot S_{A}+(1-S_{A})\odot v_{S_{ A}},X_{i}\odot S_{X}+(1-S_{X})\odot v_{S_{X}}), \tag{11}\] where \(v_{S_{A}}\in\mathcal{V}_{S_{A}}\), \(v_{S_{X}}\in\mathcal{V}_{S_{X}}\), and \(\odot\) denotes element-wise multiplication. Intuitively, this implies that the masks \(S\) keep some of the elements in \(G_{i}\) while the elements that are not selected by \(S\) are replaced with values from the probability distribution \(\mathcal{V}_{S}\) as 'noise'. In general, the choice of \(\mathcal{V}_{S}\) should be such that the resulting subgraph \(\hat{G}_{i}\) remains within the data manifold, provided that the data manifold is known. Depending on the information in \(G_{i}\), we can use a variety of probability distributions for \((\mathcal{V}_{S_{A}},\mathcal{V}_{S_{X}})\). For example, in the case of a binary adjacency matrix, \(\mathcal{V}_{S_{A}}\) can be the Gumbel-Softmax distribution, whereas for real-valued adjacency matrices and node feature matrices, \(\mathcal{V}_{S}\) can be Gaussian distributions. We can also learn the probability distributions \(\mathcal{V}_{S}\) from the data manifold itself, as previous attempts have shown success with inpainting GANs [27] for this strategy on other data modalities. Furthermore, we define the expected distortion on \(G_{i}\) with respect to the masks \(S\) and perturbation distributions \(\mathcal{V}_{S}\) as \[\mathcal{D}(G_{i},S,\mathcal{V}_{S},\Phi)=\underset{v_{S_{A}}\in\mathcal{V}_{S _{A}},v_{S_{X}}\in\mathcal{V}_{S_{X}}}{\mathbb{E}}\left[d(\Phi(G_{i}),\Phi( \hat{G}_{i}))\right], \tag{12}\] where \(d:\mathbb{R}^{m}\times\mathbb{R}^{m}\longrightarrow\mathbb{R}_{+}\) is the measure of distortion between the two model outputs. Commonly, we can set \(d\) as the \(\mathcal{L}^{2}\) distance or the KL-divergence between the two model outputs. Thus, we can define the rate-distortion explanation on \(G_{i}\) as the optimal subgraph \(\hat{G}_{i}\) that solves the minimization problem \[\underset{S=(S_{A},S_{X})}{\min}\mathcal{D}(G_{i},S,\mathcal{V}_{S},\Phi) \quad\text{s.t}\ \ ||S_{A}||_{0}\leq j,||S_{X}||_{0}\leq k, \tag{13}\] where \(j,k\) are the desired levels of sparsity for \(S_{A},S_{X}\) respectively. Note that solving equation (13) is \(\mathcal{NP}\)-hard [38]. Thus, we use an \(l_{1}\) relaxation on equation (13) to get the relaxed optimization problem given by \[\underset{S=(S_{A},S_{X})}{\min}\mathcal{D}(G_{i},S,\mathcal{V}_{S},\Phi)+ \lambda_{A}||S_{A}||_{1}+\lambda_{X}||S_{X}||_{1}, \tag{14}\] where \(\lambda_{A},\lambda_{X}>0\) are hyperparameters to control the sparsity level of the masks. We can further relax the binary masks \(S\) by sampling them from the concrete distribution [39] or Gumbel Softmax distribution [22]. This allows us to solve the optimization problem in equation (14) with differentiable techniques such as stochastic gradient descent. ### Sampling Strategies We now introduce two approaches for sampling a set of points from a large dataset. The first method focuses on maximising the diversity of the selected set, while the second aims to select a set that is representative of the whole dataset. #### Diversity In short, diverse subsets are iteratively selected from \(\Omega\subset\mathbb{R}^{d}\) using the _farthest point sampling_ (FPS) algorithm [13], where the resulting subset is a sub-optimal minimizer of the _fill distance_. We denote this approach by FPS. To maximize diversity of the selection we consider the concept of fill distance. Given a dataset \(\Omega\subset\mathbb{R}^{d}\) consisting of a finite amount of unique points, and \(X=\{\mathbf{x}_{1},\mathbf{x}_{2},\ldots,\mathbf{x}_{p}\}\subset\Omega\) a subset of cardinality \(p=|X|\in\mathbb{N}\) we define the fill distance of \(X\) in \(\Omega\) as \[h_{X,\Omega}:=\max_{\mathbf{x}\in\Omega}\min_{\mathbf{x}_{j}\in X}\|\mathbf{x}-\mathbf{x}_{j} \|_{2}. \tag{15}\] Put differently, we have that any point \(\mathbf{x}\in\Omega\) has a point \(\mathbf{x}_{j}\in X\) not farther away than \(h_{X,\Omega}\). Notice that, if \(X,\bar{X}\subset\Omega\) with \(p=|X|=|\bar{X}|\) and \(h_{X,\Omega}<h_{\bar{X},\Omega}\) then \(X\) consists of data points that are more widely distributed in \(\Omega\), thus more diverse, than those in \(\bar{X}\). Fixing the number of points \(p\in\mathbb{N}\) we want to select from \(\Omega\), we aim to find \(X\subset\Omega\) such that \[X=\operatorname*{argmin}_{\bar{X}\subset\Omega,\,|\bar{X}|=p}h_{\bar{X},\Omega}. \tag{16}\] The naive approach to solve the minimization problem in (16) would first require computing the fill distance for all possible sets \(X\subset\Omega\) with \(|X|=p\) and then choosing one of those sets where the minimum of the fill distance is attained. Unfortunately, such an approach is very time consuming and computationally intractable. Therefore, as an alternative approach we use the FPS algorithm [13]. FPS is a greedy selection method, which means that the points are progressively selected starting from an initial a-priori chosen point, i.e., given a set of selected points \(X^{s}=\{\mathbf{x}_{1},\mathbf{x}_{2},\ldots,\mathbf{x}_{s}\}\subset\Omega\) with cardinality \(|X^{s}|=s<p\), the next chosen point is \[\mathbf{x}_{s+1}=\arg\max_{\mathbf{x}\in\Omega}\min_{\mathbf{x}_{j}\in X^{s}}\|\mathbf{x}-\bm {x}_{j}\|. \tag{17}\] \(\mathbf{x}_{s+1}\) is the point which is farthest away from the points in \(X^{s}\) and it is the point where the fill distance \(h_{X^{s},\Omega}\) is attained. In other words, the next selected sample is the center of the largest empty ball in the dataset. ### Representativeness We say that data points are representatively selected for the entire dataset, when the distribution of properties in the selected subset are as close as possible to the corresponding distribution in the whole dataset. To this aim, we divide \(\Omega\) into clusters and select data points from them so that the distribution of the clusters in the subset resembles that of the whole dataset. For example, if we divide \(\Omega\) into two clusters, each containing 50% of the data points, we aim to select a subset consisting of data points which are also equidistributed in the two clusters. The clustering can be performed by clustering algorithms or be based on properties and criteria stemming from domain knowledge, i.e., in the sense of [58] the training data is selected based on scientific knowledge. Furthermore, data points within each cluster are selected using the farthest point sampling, which ensures that in the various clusters a set of diverse data points is chosen. We call this approach cluster-based farthest point sampling (C-FPS). ## 4 Numerical Experiments ### QM9 Dataset In this work, we analyze the publicly available QM9 dataset [47; 49] containing a diverse set of organic molecules. Precisely, the QM9 consists of 133 885 organic molecules in equilibrium with up to 9 heavy atoms of four different types: C, O, N and F. The dataset provides the SMILES [59] representation of the relaxed molecules, their geometric configurations and 19 physical and chemical properties. To guarantee a consistent dataset, we remove all 3054 molecules that failed the consistency test proposed by [47]. Moreover, we remove the 612 compounds for which the RDKit package [33] can not interpret the SMILES. After this preprocessing procedure, we obtain at a smaller version of the QM9 dataset consisting of 130219 molecules. #### Knowledge Based Molecular Representation The domain knowledge based molecular representation we employ is based on Mordred [42], a publicly available library that exploits the molecules' topological information encoded in the SMILES strings to provide 1826 physical and chemical features. Such molecular features are defined as the "final result of a logical and mathematical procedure, which transforms chemical information encoded within a symbolic representation of a molecule into a useful number or the result of some standardized experiment" [56] and encode scientific knowledge reflecting algebraic equations, logic rules, or invariances [58]. Using the Mordred library, we represent each molecule in the QM9 dataset with a high-dimensional vector where each vector's entry is associated with a distinct feature. To work with a more compact representation, after generating the Mordred vectors, we use the CUR [41] approach to select a subset of relevant features. The CUR algorithm takes as input the Mordred vector representation of each of the molecules in the analyzed dataset and ranks the significance of the features by associating them with an importance score. We select the first 59 top-ranked features and normalize their values in the range (0,1) using the "MinMaxScaler" function provided by the scikit-learn python library [44]. Moreover, to ensure the uniqueness of the representation, we consider an additional set of features representing the atom type distribution within each molecule. Specifically, for each data point, we add five features, each expressing the amount of atoms of a particular type within the molecule, in percentage. The possible atom types are H, C, O, N and F. In conclusion, the Mordred based representation we employ to sample the QM9 dataset consists of 64-dimensional vectors. #### Diverse and Representative Sets of Molecules The knowledge related to the molecules in the QM9 enables us to employ the data sampling strategies introduced in subsection 3.5 to create diverse and representative sets. Diverse sets are constructed using the FPS algorithm on the Mordred-based vector representations of the molecules in the QM9. The Mordred vectors allow the representation molecules as points in \(\mathbb{R}^{d}\), \(d\in\mathbb{N}\), and the definition of a distance between the molecules, the Euclidean distance. Thus, we represent the QM9 as a finite set \(\Omega\subset\mathbb{R}^{d}\) and use the FPS to sample from \(\Omega\) a sub-optimal minimizer of the fill distance. Representative sets are constructed using the procedure introduced in subsection 3.5 consisting of segmenting the QM9 in clusters and then sampling from each cluster so that the distribution of the chosen molecules resembles that of the whole dataset. The segmentation procedure is based on the molecules' topological information and considers their size, atom types and bond types, which following [58], reflects scientific knowledge in the selection of training data so that selected molecular properties are invariant per cluster. Specifically, we define the clusters through a process consisting of three main steps. In the first step, we split the molecules according to their sizes. As a result of this first step, we divided the QM9 dataset into 26 sets. After that, we separate each cluster obtained in the first step into subclusters defined by the different heavy atom types within the molecules. Overall, molecules in the QM9 consist of 4 heavy atom types. Thus, each molecule could consist of 15 different combinations of such atom types, e.g., a molecule can contain up to four distinct heavy atoms, and for each amount of distinct heavy atom types, various combinations are possible. After this second step, each of the initial 26 clusters is divided into 15 subclusters. The third and final step is further splitting the data points in each subcluster into different sets according to the various bond types present in each molecule. We consider four different bond types: single, double, triple and aromatic bonds. Thus, each of the subclusters is further divided into 15 distinct sets. As a result of this clustering procedure, we divide the QM9 in 5850 different clusters that account for molecular size, atom types and bond types. Molecules within the clusters are selected using the farthest point sampling, which ensures that in the various clusters, a set of diverse molecules is chosen. #### Sampling the QM9 Dataset For the experiments, we select training sets of different sizes and according to different strategies from the entire preprocessed QM9 dataset. After that, we test each trained model's predictive accuracy on all the molecules that have not been selected to train it. We construct training sets consisting of 100, 250, 500, 1000 and 5000 samples. Such sets are created following three different selection criteria: random sampling (RDM), as a benchmark, and the two selection strategies introduced in section 3.5, namely, diversity sampling (FPS) and representative sampling (C-FPS). For each sampling strategy and training set size, we run the training set selection process independently five times. For RDM, at each run the points are independently and uniformly selected, while in the case of FPS and C-FPS the initial point to initialize the FPS algorithm is independently selected at random at each run. Thus, for each selection strategy and training set size, each of the analyzed models is trained and tested five times, independently. The test results that follow are averaged over the five runs. We want to point out that sampling the training data non-randomly will lead to a shift between the training and test distribution, as showcased in Fig. 1, where we compare FPS with a random selection. It is not obvious how such a bias effects the different models. Note that for Fig. 1 we performed the selection twice, with different initialization for FPS and different seeds for the random selection, respectively. We find that changing the initialization for FPS does not lead to a significant change in the distribution, for different seeds in the random selection we make the same observation. #### Measuring the Error We evaluate the performances of the employed machine learning methods using three different metrics. Specifically, we consider the mean absolute error (MAE), the root mean squared error (RMSE) and the worst-case error. The mean absolute error (MAE) computes the arithmetic average of the absolute errors between the predicted values \(\{\tilde{y}_{i}\}_{i=1}^{N}\) and the ground truth \(\{y_{i}\}_{i=1}^{N}\), that is, \[\text{MAE}:=\sum_{i=1}^{N}|y_{i}-\tilde{y}_{i}|, \tag{18}\] where \(N\in\mathbb{N}\) is the number of data points in the test set used to evaluate the models. The root mean squared error (RMSE) computes the root of the mean squared error, which is the arithmetic average of the squared errors. It is a measure of how spread out the errors are and it is represented by the formula \[\text{RMSE}:=\sqrt{\sum_{i=1}^{N}(y_{i}-\tilde{y}_{i})^{2}}. \tag{19}\] The worst-case error calculates the maximum absolute error between the predicted values and the ground truths. It is an indicator of the robustness of a model's predictions, and it is defined as \[\text{worst-case error}:=\max_{1\leq i\leq N}|y_{i}-\tilde{y}_{i}|. \tag{20}\] ### SchNet In order to get experimental insights on FPS also for a different class of informed predictive models, we train the publicly available implementation of SchNet from Pytorch Geometric [15] on the defined subsets. In this work, we choose a cutoff radius of 4 A while keeping the other hyperparameters to be the default ones suggested by the Pytorch Geometric implementation (version 2.0.4). Besides the test set that is Figure 1: The distributions of pairwise interatomic distances within a molecule for 5000 molecules sampled with either FPS or randomly (two different splits each) differ. used for final evaluation, we use random 20 % from the training set for evaluation during training and refer to it as validation set. We minimize the \(L2\)-loss function with respect to the model parameters with the Adam optimizer using mini-batches of 32 molecules per iteration and a learning rate of \(7\cdot 10^{-4}\). The learning rate is decayed by a factor of 0.8 if the validation error has not improved for 50 epochs. After each epoch a checkpoint is saved if the model has achieved a smaller validation loss than the current best model. The training process is stopped after the model has not improved for 200 epochs (early stopping). The best model is then used for assessing the model performance on the test set. The first thing we observe is that SchNet does not seem to profit from FPS-based sampling strategies when examining the MAE and RMSE (Fig. 1(a) and 1(b)) alone. Random sampling consistently leads to approximately equal or smaller measurements for the MAE and RMSE for all investigated training set sizes. However, for 100, 250 and 500 training samples, the worst case error is reduced by at least 0.5 eV when employing FPS for the training set selection (Fig. 1(b)). Considering the comparatively small error bars, we expect FPS to be a reliable technique to reduce the worst case error for small (i.e. \(\leq\) 500 data points) training sets of QM9. For larger training sets however, this effect vanishes and FPS leads to worse results in the sense of larger worst-case errors. This is possibly due to the fact that FPS is based on Mordred features which yield a rather global description of a molecule. In this sense, FPS selects samples that are maximally far away with respect to those global features. On the Figure 2: Results for SchNet. contrary, GNNs strongly exploit local information and we believe this discrepancy to be a possible explanation for the merely small effect induced by FPS. However, in absolute numbers, SchNet yields the lowest error metrics of all tested methods. This meets our expectations since it is the only method incorporating geometric information. In fact, the nuclear positions were obtained through DFT calculations and hence the coordinates already encode highly relevant information for predicting the atomization energy. One could argue that SchNet's input is already part of the solution to the problem and view the use of features derived by ab initio methods as some form of information leakage [16], thus making the learning problem easier. ### Kernel Ridge Regression The kernel and regression hyperparameters were optimized in a grid search for each of the randomly selected training sets of 1000 points. Specifically, we varied the kernel parameter '\(\nu\)' in the set \(\{10^{-1},10^{0},10,10^{2},\ldots,10^{7}\}\) and the regularization parameter '\(\lambda\)' in the set \(\{10^{-12},10^{-10},10^{-8},10^{-6},\ldots,10^{0}\}\). We selected \(\nu=10^{5}\) and \(\lambda=10^{-12}\), which is the parameter combination that provides the best performance in terms of the MAE on a randomly chosen test set consisting of 10000 points not considered during training. Of all predictive models that we investigated, Gaussian kernel regression appears to benefit the most from FPS-based sampling strategies in comparison to random sampling. In particular, FPS and C-FPS improve the obtained RMSE on the test set for all training set sizes as seen in Fig. 3b. However, it is noteworthy that random sampling leads to an increasing RMSE when going from 500 to 1000 or even 5000 training samples. For a possible explanation, we consider the MAE (Fig. 3a) and the worst case error (Fig. 3c). Even though we observe a decreasing MAE with an increasing training set size the worst case error becomes larger with more training samples as well, leading to a stagnating RMSE as it gives a higher weight to outliers than the MAE. FPS appears to alleviate this problem as becomes apparent when considering the comparatively small worst case errors. At this point, we can compare the worst case errors of the SMILES-based Kernel ridge regression (KRR) with the worst case error of SchNet. From Fig. 3c it is apparent that FPS significantly reduces the worst-case error of KRR by one order of magnitude compared to random sampling. In order to contextualize this effect better we consider Fig. 4 that shows the worst-case errors of SchNet and KRR side by side for different numbers of training samples. We find KRR to approach the values of SchNet with an increasing number of training samples. In particular, we observe the errors to have the same order of magnitude. This is noteworthy as the KRR only exploits topological information while SchNet requires the atom coordinates obtained from DFT as input. Figure 4: The worst-case error of KRR can be reduced by FPS such that the order of magnitude is comparable to SchNet. Figure 3: Results for Gaussian Kernel Regression. ### Spatial 3-Hop Convolution Network In accordance with the previous sections, we train the method presented in Section 3.3 on subsets of QM9. The network consists of several updates by the spatial 3-hop convolution layer, followed by an aggregation layer to obtain graph features which are further processed by linear layers. During training we minimize the L1-loss function with respect to the models parameters with the Adam optimizer, use a learning rate of \(2\cdot 10^{-4}\) and a batch size of 32 molecules per iteration. We train each model for 500 epochs and choose the best model with respect to a validation set (20% of the training set) for measuring the model performance on a test set. Apart from the model trained on 250 samples, we do not observe significant differences among the different sampling strategies when considering only the MAE (Fig. 4(a)). When training on 250 samples, the FPS-based methods appear to lead to an advantage and reduce the MAE in comparison to random sampling. For larger training sets random sampling seems to catch up and perform on par with FPS-based sampling. Considering the RMSE (Fig. 4(b)), our observations are somewhat different. In particular, we find FPS and C-FPS to outperform random sampling for most sizes of the training set. In line with the other methods, FPS reduces the worst-case error in comparison to random sampling (Fig. 4(c)). We observe comparatively large values for all metrics, especially for small training set sizes. For example, the MAE for 100 training samples obtained with FPS amounts Figure 5: Results for spatial 3-hop convolution network to approximately 5 eV. This is around 4 times larger than what we measure for KRR and more than 10 times larger than the value of SchNet. This was to be expected, since both KRR and SchNet are relatively data efficient. We note that the good performace of SchNet is to be expected as it uses more features than the spatial 3-hop convolution network and especially uses the positions of the atoms (a powerful information which allows to compute the atomization energy explicitely). The KRR has the advantage of being a kernel method which has empirically shown to be effective in the realm of small datasets [45]. However, for larger training sets the relative difference between the methods becomes smaller: For 500 training samples, KRR yields only a two times smaller and SchNet only a 5 times smaller MAE. Moreover, the spatial 3-hop convolution network can benefit the most from larger datasets, i.e. we observe a significant improvement in performance whenever the size of the dataset is increased. ### Explanation With GRDE framework from Section 3.4 we now investigate the domain knowledge learned by the spatial 3-hop convolution network from Section 3.3 using the sampling strategies from Section 3.5. #### Setup of the Experiments For the experiments, we utilize the spatial 3-hop convolution network from Section 3.3 that has been pre-trained using the sampling strategies from Section 3.5. More specifically, we compare explanations on the pre-trained model for the cases of random sampling (RDM) and diversity sampling (FPS) of 5000 samples as the training dataset. We fix the distortion measure \(d\) as the \(L^{2}\) distance for a regression task, and randomly initialize masks \(S\). Furthermore, given the sparsity of the data, we also set a low value on \(\lambda_{A},\lambda_{X}=20\) (which corresponds to choosing 10-15% of the non-zero elements in the respective masks) and set \((v_{S_{A}},v_{S_{X}})\) to null. Since the QM9 dataset possesses edge features, we optimize \(S_{A}=[S_{A_{1}},S_{A_{2}},...,S_{A_{n}}]\) where \(A_{i}\) is the adjacency matrix with respect to the edge feature \(i\)\(\forall i\in\{1,2,...,h\}\); \(h\) being the number of edge features. The results that follow are obtained as an average over 3 independent runs on 100 graphs randomly sampled from the respective test datasets. Since the setup produces positive relevance masks, i.e., the masks only obfuscate features that exist for each node/edge, and do not show the relevance of the lack of a feature for a node/edge), we aggregate and average the node- and edge-wise scores to obtain feature-wise scores. Furthermore, we offset the imbalance in the scores by weighting them with respect to the frequency of their occurrence over the sampled data. Our explanation query is as follows: _For a randomly selected graph unseen by the pre-trained model, which features does the model consider important for its prediction?_ ## Results From Fig. 5(a) and Fig. 5(b), we see that the model trained using FPS places a stronger importance in both edge and node features than in the case of RDM, especially in the case of atomic numbers (Z), double bonds and aromatic rings. In comparison, single bonds, though the most frequent of the bond types in the sampled data are not considered as important. Furthermore, Fig. 5(a) shows that the model requires certain nodes to be specific atom types and have a certain type of neighborhood for its predictions, as can be seen from the atomic number (Z) as well as the importance of carbon (C) and the number of hydrogen atoms (#H) surrounding the node in the case of FPS. In the case of RDM, we also have a clear indication that edge features are not as important as the node features, whereas this is significantly more balanced in the case of FPS. Finally, we find that, though there exist non-zero values for some node features in the sampled graphs such as in the case of Nitrogen (N) and Oxygen (O), GRDE does not attribute any importance to them. This implies that the model treats these features as noise and ignores them regardless of the sampling strategy used. ## 5 Conclusion In this work, we employed three informed ML models to predict the atomization energy of molecules in the QM9 dataset. We used KRR with a kernel obtained from molecular topological features, a geometry-based GNN (SchNet) and a topology-based GNN. We saw that maximizing molecular diversity in the training set selection process improves the accuracy and robustness of those methods. Our main finding is that by training topology-based ML models with sets of diverse molecules, we can significantly reduce their test maximum absolute error, thus increasing their robustness to distribution shifts. For SchNet, this effect was still observable but only for small training sets. Moreover, by maximizing diversity in the training sets, Figure 6: Results for feature-level GRDE. we could substantially reduce the gap between the maximum absolute errors of a topology-based regression method as KRR and the SchNet, which is a geometry-based GNN. This work proposes only an empirical investigation, in the field of molecular property prediction, on the effects of maximizing molecular diversity in the training set selection. Ongoing research seeks to provide a theoretical foundation for the observed empirical results. We believe that reducing the worst-case error is of great importance for applications that require a high degree of robustness but have limited budget for data generation. One example would be the application of Machine Learning Interatomic Potentials (MLPs) for molecular dynamics simulations. In this scenario, the predictions of the model are used to integrate the equations of motion and to compute particle trajectories. Thus, large errors in the predictions could potentially lead to a failure of the simulation and techniques to prevent this are needed. Investigating this scenario in particular, could be a direction of future research. ###### Acknowledgements. This work was supported in part by the BMBF-project 05M20 MaGriDo (Mathematics for Machine Learning Methods for Graph-Based Data with Integrated Domain Knowledge) and in part by the Fraunhofer Cluster of Excellence \(\ast\)Cognitive Internet Technologies*.
2305.04225
LSGNN: Towards General Graph Neural Network in Node Classification by Local Similarity
Heterophily has been considered as an issue that hurts the performance of Graph Neural Networks (GNNs). To address this issue, some existing work uses a graph-level weighted fusion of the information of multi-hop neighbors to include more nodes with homophily. However, the heterophily might differ among nodes, which requires to consider the local topology. Motivated by it, we propose to use the local similarity (LocalSim) to learn node-level weighted fusion, which can also serve as a plug-and-play module. For better fusion, we propose a novel and efficient Initial Residual Difference Connection (IRDC) to extract more informative multi-hop information. Moreover, we provide theoretical analysis on the effectiveness of LocalSim representing node homophily on synthetic graphs. Extensive evaluations over real benchmark datasets show that our proposed method, namely Local Similarity Graph Neural Network (LSGNN), can offer comparable or superior state-of-the-art performance on both homophilic and heterophilic graphs. Meanwhile, the plug-and-play model can significantly boost the performance of existing GNNs. Our code is provided at https://github.com/draym28/LSGNN.
Yuhan Chen, Yihong Luo, Jing Tang, Liang Yang, Siya Qiu, Chuan Wang, Xiaochun Cao
2023-05-07T09:06:11Z
http://arxiv.org/abs/2305.04225v2
# LSGNN: Towards General Graph Neural Network ###### Abstract Heterophily has been considered as an issue that hurts the performance of Graph Neural Networks (GNNs). To address this issue, some existing work uses a graph-level weighted fusion of the information of multi-hop neighbors to include more nodes with homophily. However, the heterophily might differ among nodes, which requires to consider the local topology. Motivated by it, we propose to use the local similarity (LocalSim) to learn node-level weighted fusion, which can also serve as a plug-and-play module. For better fusion, we propose a novel and efficient Initial Residual Difference Connection (IRDC) to extract more informative multi-hop information. Moreover, we provide theoretical analysis on the effectiveness of LocalSim representing node homophily on synthetic graphs. Extensive evaluations over real benchmark datasets show that our proposed method, namely Local Similarity Graph Neural Network (LSGNN), can offer comparable or superior state-of-the-art performance on both homophilic and heterophilic graphs. Meanwhile, the plug-and-play model can significantly boost the performance of existing GNNs. Our code is provided at [https://github.com/draym28/LSGNN](https://github.com/draym28/LSGNN). ## 1 Introduction Graph Neural Network (GNN) has received significant interest in recent years due to its powerful ability in various real-world applications based on graph-structured data, i.e., node classification [13], graph classification [16], and link prediction [15]. Combining convolutional network and graph signal processing, numerous Graph Convolutional Network (GCN) architectures [21, 14, 15, 16] have been proposed and show superior performance in the above application domains. Recent work [1] believes that the success of GCN and its variants is built on the homophily assumption: connected nodes tend to have the same class label [14]. This assumption provides proper inductive bias, raising the general message-passing mechanism: aggregating neighbour information to update ego-node feature--a special form of low-pass filter [1]. However, the homophily assumption does not always hold [15, 16]. In such cases, empirical evidence shows that GCN may even be worse than simple Multi-Layer Perceptrons (MLPs) that use merely node features as input [17] (heterophily issue). A potential explanation is that the low-pass filter is believed to hurt the performance of GCN on heterophilic graph. Recently, the heterophily issue has received the community's interest, and various methods [13, 14, 15, 16] have been proposed to address the issue. Many existing works [14, 15, 16] propose to fuse intermediate representations, i.e., outputs of different layers, for heterophilic graphs learning. However, they only consider graph-level heterophily. Moreover, intermediate representations extracted by traditional propagation methods [13] may drop some important information, which limits the effectiveness of information fusion among neighbors. We show that in real-world datasets the heterophily among nodes can be significantly different (Section 3.3), which suggests that only considering graph-level heterophily is insufficient. Although Liu _et al._ consider node-level heterophily, they simply map each node's representation to its node-level weight, do not take local topology into consideration, yielding suboptimal results. Motivated by the deficiency of existing techniques, we propose to use the local similarity to indicate node homophily to conduct better node-level weighted fusion adaptively. Moreover, we empirically and theoretically show its capabilities on synthetic graphs (Section 4). Furthermore, to obtain more informative intermediate representations for better fusion, we propose a novel Initial Residual Difference Connection (IRDC), which can leverage all the input information. Meanwhile, the IRDC propagation preserves the key property of SGC [20] on removing the nonlinear transformations between propagation, which is time- and GPU-consuming in GCNs. This property makes the feature propagation of LSGNN efficient and deep-learning free. Based on the above novel designs, LSGNN offers high performance and high efficiency in evaluations (Section 6). To summarize, we make the following contributions: **1)** We study the local node homophily of real-world datasets and suggest using LocalSim as an indicator of node homophily. Moreover, we empirically and theoretically show the effectiveness of using LocalSim to indicate node homophily on synthetic graphs. **2)** We propose LSGNN, which contains a LocalSim-aware multi-hop fusion to guide the learning of node-level weight for intermediate representations and an IRDC to extract more informative intermediate representations for better fusion. **3)** LocalSim-based node-level weight is a plug-and-play module and can significantly boost the performance of state-of-the-art models, such as H\({}_{2}\)GCN and GPRGNN. **4)** We conduct extensive experiments to demonstrate the superiority of our method, LSGNN, which can offer comparable or superior performance against 13 other methods over homophilic and heterophilic graphs. ## 2 Preliminaries ### Notations We denote an undirected graph without self-loops as \(\mathcal{G}=(\mathcal{V},\mathcal{E})\), where \(\mathcal{V}=\{v_{i}\}_{i=1}^{n}\) is the node set and \(\mathcal{E}\subseteq\mathcal{V}\times\mathcal{V}\) is the edge set. Let \(\mathcal{N}_{i}\) denotes the neighbours of node \(v_{i}\). Denote by \(\mathbf{A}\in\mathbb{R}^{n\times n}\) the adjacency matrix, and by \(\mathbf{D}\) the diagonal matrix standing for the degree matrix such that \(\mathbf{D}_{ii}=\sum_{j=1}^{n}\mathbf{A}_{ij}\). Let \(\tilde{\mathbf{A}}\) and \(\tilde{\mathbf{D}}\) be the corresponding matrices with self-loops, i.e., \(\tilde{\mathbf{A}}=\mathbf{A}+\mathbf{I}\) and \(\tilde{\mathbf{D}}=\mathbf{D}+\mathbf{I}\), where \(\mathbf{I}\) is the identity matrix. Denote by \(\mathbf{X}=\{\mathbf{x}_{i}\}_{i=1}^{n}\in\mathbb{R}^{n\times d}\) the initial node feature matrix, where \(d\) is the number of dimensions, and by \(\mathbf{H}^{(k)}=\{\mathbf{h}_{i}^{(k)}\}_{i=1}^{n}\) the representation matrix in the \(k\)-th layer. We use \(\mathbf{Y}=\{\mathbf{y}_{i}\}_{i=1}^{n}\in\mathbb{R}^{n\times C}\) to denote the ground-truth node label matrix, where \(C\) is the number of classes and \(\mathbf{y}_{i}\) is the one-hot encoding of node \(v_{i}\)'s label. ### Simple Graph Convolution (SGC) SGC [20] claims that the nonlinearity between propagation in GCN (i.e., the ReLU activation function) is not critical, whereas the majority of benefit arises from the propagation itself. Therefore, SGC removes the nonlinear transformation between propagation so that the class prediction \(\hat{\mathbf{Y}}\) of a \(K\)-layer SGC becomes \[\hat{\mathbf{Y}}=\mathrm{softmax}\left(\mathbf{S}^{K}\mathbf{X}\mathbf{W} \right), \tag{1}\] where \(\mathbf{S}\) is a GNN filter, e.g., \(\mathbf{S}=\tilde{\mathbf{D}}^{-\frac{1}{2}}\tilde{\mathbf{A}}\tilde{\mathbf{D }}^{-\frac{1}{2}}\) is used in the vanilla SGC, and \(\mathbf{W}\) is the learned weight matrix. Removing the nonlinearities, such a simplified linear model yields orders of magnitude speedup over GCN while achieving comparable empirical performance. ### Heterophily Issue Existing GNN models are usually based on the homophily assumption that connected nodes are more likely to belong to the same class. However, many real-world graphs are heterophilic. For example, the matching couples in dating networks are usually heterosexual. Empirical evidence shows that when the homophily assumption is broken, GCN may be even worse than simple Multi-Layer Perceptrons (MLPs) that use merely node features as input [10]. Therefore, it is essential to develop a general GNN model for both homophilic and heterophilic graphs. Pei _et al._[23] introduce a simple index to measure node homophily/heterophily. That is, the homophily \(\mathcal{H}(v_{i})\) of node \(v_{i}\) is the ratio of the number of \(v_{i}\)'s neighbours who have the same labels as \(v_{i}\) to the number of \(v_{i}\)'s neighbours, i.e., \[\mathcal{H}(v_{i})=\frac{|\{v_{j}\mid v_{j}\in\mathcal{N}_{i},\mathbf{y}_{j}=\mathbf{y }_{i}\}|}{|\mathcal{N}_{i}|}, \tag{2}\] Figure 1: An illustration of LSGNN framework. ‘Pre-Computed’ means the part can be pre-computed without training. and the homophily in a graph is the average of all nodes, i.e., \[\mathcal{H}(\mathcal{G})=\frac{1}{n}\sum_{v_{i}\in\mathcal{V}}\mathcal{H}(v_{i}). \tag{3}\] Similarly, the heterophily of node \(v_{i}\) is measured by \(1-\mathcal{H}(v_{i})\), and the heterophily in a graph is \(1-\mathcal{H}(\mathcal{G})\). ## 3 Methodology ### Overview In this section, we present the **L**ocal **S**imilarity **G**raph **N**eural **N**etwork (LSGNN), consisting of a novel propagation method named Initial Residual Difference Connection (IRDC) for better fusion (**Section 3.2**), and a LocalSim-aware multi-hop fusion (**Section 3.4**) and thus cope with both homophilic and heterophilic graphs. We also demonstrate the motivation of using LocalSim as an effective indicator of homophily (**Section 3.3**). Figure 1 shows the framework of LSGNN. ### Initial Residual Difference Connection (IRDC) Simply aggregating representation from the previous layer (as applied by most GNNs) might lose important information and consequently incur over-smoothing issues. To obtain more informative intermediate representations, i.e., outputs of different layers, we propose a novel propagation method, namely Initial Residual Difference Connection (IRDC). **General Form.** Inspired by SGC, we remove nonlinearity between layers and formulate IRDC as follows: \[\begin{split}\mathbf{H}^{(1)}&=\mathrm{IRDC}^{(1)} (\mathbf{S},\mathbf{X})=\mathbf{S}\mathbf{X},\\ \mathbf{H}^{(k)}&=\mathrm{IRDC}^{(k)}(\mathbf{S}, \mathbf{X})=\mathbf{S}\Big{(}(1-\gamma)\mathbf{X}-\gamma\sum_{\ell=1}^{k-1} \mathbf{H}^{(\ell)}\Big{)},\end{split} \tag{4}\] for \(k=2,\ldots,K\). \(\mathbf{S}\) is a GNN filter, and \(\gamma\in[0,1]\) is a hyperparameter. The term \(\sum_{\ell=1}^{k-1}\mathbf{H}^{(\ell)}\) in Equation (4) can be seen as the total information extracted by the previous \(k-1\) layers. In this way, IRDC feeds the information that has never been processed from the original input into the next layer, thus can fully exploit all the information from the initial node features. A normalization operation is conducted following IRDC to handle the potential value scale issue. See Appendix B for comparison between different residual connections. **Parameterization in Practice.** Many GCNs use adjacency matrix with self-loops as the low-pass GNN filter to extract similar information from neighbours. However, the self-loops added in GCNs may not always be helpful [22]. Instead, we use enhanced filters [1] of both low-pass and high-pass (\(\mathcal{F}_{L}+\mathcal{F}_{H}=\mathbf{I}\)) by adding weighted identity matrix \(\mathbf{I}\) (i.e., weighted self-loops), \[\begin{split}\mathcal{F}_{L}&=\beta\mathbf{I}+ \mathbf{D}^{-\frac{1}{2}}\mathbf{A}\mathbf{D}^{-\frac{1}{2}},\\ \mathcal{F}_{H}&=\mathbf{I}-\mathcal{F}_{L}=(1-\beta )\,\mathbf{I}-\mathbf{D}^{-\frac{1}{2}}\mathbf{A}\mathbf{D}^{-\frac{1}{2}}, \end{split} \tag{5}\] where \(\beta\in[0,1]\) is a hyperparameter. Intuitively, combining low-pass and high-pass filters together can learn better representations for both homophilic and heterophilic graphs. In a \(K\)-layer LSGNN, the output \(\mathbf{H}_{L}^{(k)},\mathbf{H}_{H}^{(k)}\in\mathbb{R}^{n\times d}\) of the \(k^{\text{th}}\) low-pass and high-pass graph filter layer are \[\mathbf{H}_{L}^{(k)}=\mathrm{IRDC}^{(k)}(\mathcal{F}_{L},\mathbf{X})\text{ and }\mathbf{H}_{H}^{(k)}=\mathrm{IRDC}^{(k)}(\mathcal{F}_{H},\mathbf{X}),\] where \(k=1,2,\ldots,K\). Next, \(\mathbf{H}_{L}^{(k)}\) and \(\mathbf{H}_{H}^{(k)}\) are transformed into \(z\) dimensions by learnable \(\mathbf{V}_{L}^{(k)},\mathbf{W}_{H}^{(k)}\in\mathbb{R}^{d\times z}\), i.e., \[\tilde{\mathbf{H}}_{L}^{(k)}=\sigma\left(\mathbf{H}_{L}^{(k)}\mathbf{W}_{L}^{ (k)}\right)\text{ and }\tilde{\mathbf{H}}_{H}^{(k)}=\sigma\left(\mathbf{H}_{H}^{(k)}\mathbf{W}_{H }^{(k)}\right),\] where \(\sigma\) is the ReLU function. To leverage the the initial node features, we also obtain a transformation \(\tilde{\mathbf{H}}_{I}\) of \(\mathbf{X}\) such that \[\tilde{\mathbf{H}}_{I}=\sigma\left(\mathbf{X}\mathbf{W}_{I}\right),\] where \(\mathbf{W}_{I}\in\mathbb{R}^{d\times z}\) is a learned weight matrix. In what follows, \(\tilde{\mathbf{H}}_{I},\tilde{\mathbf{H}}_{L}^{(k)},\tilde{\mathbf{H}}_{H}^{ (k)}\in\mathbb{R}^{n\times z}\) (\(k=1,2,\ldots,K\)) are delivered to the LocalSim-aware multi-hop fusion (Section 3.4) to generate the final node representations. ### LocalSim: An Indicator of Homophily Based on the hypothesis that nodes with similar features are likely to belong to the same class, we start out by defining a simple version of Local Similarity (LocalSim) \(\phi_{i}\) of node \(v_{i}\) to indicate its homophily, i.e., \[\phi_{i}=\frac{1}{|\mathcal{N}_{i}|}\sum_{j\in\mathcal{N}_{i}}d_{ij}=\frac{1}{| \mathcal{N}_{i}|}\sum_{v_{j}\in\mathcal{N}_{i}}\mathrm{sim}(\mathbf{x}_{i},\mathbf{x} _{j}), \tag{6}\] where \(\mathrm{sim}(\cdot,\cdot):(\mathbb{R}^{d},\mathbb{R}^{d})\mapsto\mathbb{R}\) is a similarity measure, e.g., \[\mathrm{sim}(\mathbf{x}_{i},\mathbf{x}_{j})=\begin{cases}\frac{\mathbf{x}_{i}^{\top}\mathbf{x} _{j}}{\|\mathbf{x}_{i}\|\|\mathbf{x}_{j}\|},&\text{Cosine similarity},\\ -\|\mathbf{x}_{i}-\mathbf{x}_{j}\|_{2},&\text{Euclidean similarity}.\end{cases}\] Figure 2 shows the relation between node homophily and LocalSim (using Cosine similarity) on Cornell (left column) and Citeseer (right column) datasets. From the upper figures, we observe that the homophily/heterophily among nodes are different. In particular, Cornell is a heterophilic graph, while Citeseer is a homophilic graph. Moreover, the lower figures show a clear positive correlation between node homophily and LocalSim, which indicates that LocalSim can be used to represent node homophily appropriately. Figure 2: Positive relation between node homophily and LocalSim on Cornell (left column) and Citeseer (right column) datasets. The upper figures show the histogram of node homophily, while the lower figures show the result for node homophily vs. LocalSim. ### LocalSim-Aware Multi-Hop Fusion In Section 3.3, we show that LocalSim, leveraging the local topology information, can identify the homophily of nodes. We apply LocalSim to learn the adaptive fusion of intermediate representations for each node. The naive LocalSim in Equation (6) simply averages the similarity between the ego-node and its neighbors. In what follows, we refine the definition of LocalSim by incorporating nonlinearity, i.e., \(d_{ij}^{2}\). Specifically, the refined LocalSim \(\varphi_{i}\) of node \(i\) is given by \[\varphi_{i}=\frac{1}{|\mathcal{N}_{i}|}\sum_{v_{j}\in\mathcal{N}_{i}}\mathrm{ MLP_{ls}}([d_{ij},d_{ij}^{2}]), \tag{7}\] where \(\mathrm{MLP_{ls}}:\mathbb{R}^{2}\mapsto\mathbb{R}\) is a 2-layer perceptron. It is trivial to see that incorporating \(d_{ij}^{2}\) via \(\mathrm{MLP_{ls}}\) can encode the variance of series \(\{d_{ij}\}_{v_{j}\in\mathcal{N}_{i}}\), since \(\mathrm{Var}[d_{ij}]=\mathbb{E}[d_{ij}^{2}]-\mathbb{E}^{2}[d_{ij}]\) with respect to \(v_{j}\in\mathcal{N}_{i}\). As a consequence, \(\varphi_{i}\) can better characterize the real "local similarity" than \(\phi_{i}\). To illustrate, we compare \(\varphi_{i}\) and \(\phi_{i}\) through a simple example. Suppose that node \(v_{1}\) has two neighbours \(v_{2}\) and \(v_{3}\) such that \(d_{12}=0\) and \(d_{13}=1\), while node \(v_{4}\) has two neighbours \(v_{5}\) and \(v_{6}\) such that \(d_{45}=d_{46}=0.5\). Then, \(\phi_{1}=\phi_{4}=0.5\), which cannot characterize the distinct neighbour distributions. On the other hand, by introducing nonlinearity, we can easily distinguish \(\varphi_{1}\) and \(\varphi_{4}\). Finally, we have the LocalSim vector for all nodes \(\mathbf{\varphi}=[\varphi_{1},\varphi_{2},\ldots,\varphi_{n}]\in\mathbb{R}^{n}\). LocalSim can guide the intermediate representations fusion, i.e., using \(\mathbf{\varphi}\) as local topology information when learning weights for fusion. In addition, we also introduce nonlinearity by using \(\mathbf{\varphi}\) and \(\mathbf{\varphi}^{2}\) together to generate weights, i.e., \[[\mathbf{\alpha}_{I},\mathbf{\alpha}_{L},\mathbf{\alpha}_{H}]=\mathrm{MLP}_{\alpha}([\bm {\varphi},\mathbf{\varphi}^{2}]), \tag{8}\] where \(\mathbf{\alpha}_{I},\mathbf{\alpha}_{L},\mathbf{\alpha}_{H}\in\mathbb{R}^{n\times K}\) are the weights for node representation from each channel and \(\mathrm{MLP}_{\alpha}\colon\mathbb{R}^{2}\mapsto\mathbb{R}^{3K}\) is a 2-layer perceptron. Then, the node representations for the \(k\)-th layer is computed as follows: \[\mathbf{Z}^{(k)}=\mathbf{\alpha}_{I}^{(k)}\odot\tilde{\mathbf{H}}_{I}+\mathbf{\alpha }_{L}^{(k)}\odot\tilde{\mathbf{H}}_{L}^{(k)}+\mathbf{\alpha}_{H}^{(k)}\odot\tilde {\mathbf{H}}_{H}^{(k)}, \tag{9}\] where \(\mathbf{Z}^{(k)}\in\mathbb{R}^{n\times z}\) and \(\mathbf{\alpha}_{I}^{(k)},\mathbf{\alpha}_{L}^{(k)},\mathbf{\alpha}_{H}^{(k)}\in\mathbb{R} ^{n}\) for \(k=1,2,\ldots,K\), and \(\mathbf{\alpha}_{I}^{(k)}\odot\tilde{\mathbf{H}}_{I}\) is the \(i\)-th entry of \(\mathbf{\alpha}_{I}^{(k)}\) times the \(i\)-th row of \(\tilde{\mathbf{H}}_{I}\) for \(i=1,2,\ldots,n\) (so do \(\mathbf{\alpha}_{L}^{(k)}\odot\tilde{\mathbf{H}}_{L}^{(k)}\) and \(\mathbf{\alpha}_{H}^{(k)}\odot\tilde{\mathbf{H}}_{H}^{(k)}\)). Then, we obtain the final representation as \(\tilde{\mathbf{H}}_{I}\|\mathbf{Z}^{(1)}\|\mathbf{Z}^{(2)}\|\cdots\|\mathbf{Z }^{(K)}\), where \(\|\) is the concatenation function. Finally, the class probability prediction matrix \(\hat{\mathbf{Y}}\in\mathbb{R}^{n\times C}\) is computed by \[\hat{\mathbf{Y}}=\left[\tilde{\mathbf{H}}_{I}\|\mathbf{Z}^{(1)}\|\mathbf{Z}^{ (2)}\|\cdots\|\mathbf{Z}^{(K)}\right]\mathbf{W}_{\mathrm{out}}, \tag{10}\] where \(\mathbf{W}_{\mathrm{out}}\in\mathbb{R}^{(K+1)z\times C}\) is a learned matrix. ## 4 Case Study of Toy Example In this section, we conduct a case study using a simple synthetic graph to demonstrate the superiority of our LocalSim-based node-level weight. ### Empirical Investigation Inspired by the Featured Stochastic Block Model (FSBM) [1], in the following, we introduce FSBM with mixture of heterophily that can generate a simple synthetic graph with different node heterophily. **Definition 1** (FSBM with Mixture of Heterophily).: _A Stochastic Block Model (SBM) graph \(\mathcal{G}\) with mixture of heterophily has \(n\) nodes partitioned into \(r\) communities \(C_{1},C_{2},\ldots,C_{r}\) and consisting of \(t\) subgraphs \(\mathcal{G}_{1},\mathcal{G}_{2},\ldots,\mathcal{G}_{t}\) where there is no edge between any two subgraphs, with intra-community and inter-community edge probabilities \(p_{k}\) and \(q_{k}\) in subgraph \(\mathcal{G}_{k}\). Let \(\mathbf{c}_{1},\mathbf{c}_{2},\ldots,\mathbf{c}_{r}\in\{0,1\}^{n}\) be indicator vectors for membership in each community, i.e., the \(j\)-th entry of \(\mathbf{c}_{i}\) is \(1\) if the \(j\)-th node is in \(C_{i}\) and \(0\) otherwise. An FSBM is such a graph model \(\mathcal{G}\), plus a feature vector \(\mathbf{x}=\mathbf{f}+\mathbf{\eta}\in\mathbb{R}^{n}\), where \(\mathbf{\eta}\sim\mathcal{N}(0,\sigma^{2}\mathbf{I})\) is zero-centered, isotropic Gaussian noise and \(\mathbf{f}=\sum_{i}\mu_{i}\mathbf{c}_{i}\) for some \(\mu_{1},\mu_{2},\ldots,\mu_{r}\in\mathbb{R}\), which are the expected feature values of each community._ According to Definition 1 and Equation (2), nodes in the same subgraph have identical homophily in expectation, while nodes from different subgraphs have distinct homophily. We consider FSBMs with \(n=1000\), 2 equally-sized communities \(C_{1}\) and \(C_{2}\), 2 equally-sized subgraphs \(\mathcal{G}_{1}\) and \(\mathcal{G}_{2}\), feature means \(\mu_{1}=1\), \(\mu_{2}=-1\), and noise variance \(\sigma=1\). We generate different graphs by varying \(\lambda_{1}=\frac{p_{1}}{p_{1}+q_{1}}\) and \(\lambda_{2}=\frac{p_{2}}{p_{2}+q_{2}}\), where \(\lambda_{1},\lambda_{2}\in[0,1]\) and high \(\lambda_{r}\) means high homophily, with the expected degree of all nodes to 10 (which means \(\frac{1}{4}(p_{r}+q_{r})n=10\) for \(\tau=1,2\)). We employ graph-level weight and LocalSim-based node-level weight to classify the nodes. For LocalSim-based node-level weight, we use the proposed method in Section 3. For graph-level weight, we replace \(\alpha\) in Equation (8) with learnable graph-level value. For the similarity measure, we use \(\mathrm{sim}(x,y)=-(x-y)^{2}\), where \(x\) and \(y\) are scalar values. Finally, considering the simplicity of the synthetic networks, we use the simple LocalSim in Equation (6), and only use adjacency matrix with self-loop \(\tilde{\mathbf{A}}=\mathbf{A}+\mathbf{I}\) and set the layers of IRDC to one. As shown in Figure 3, our LocalSim-based node-level weight consistently outperforms graph-level weight. In particular, when node homophily is significantly different among subgraphs, the graph-level weight performs poorly, while our approach still performs very well which can recognize the node homophily well and adaptively provide suitable filters. ### Theoretical Analysis In addition to the empirical investigation, we theoretically confirm the capabilities of LocalSim node-level weight. For simplicity, we assume the number of inter-community and intra-community edges for all the nodes is the same as their expectation and without self-loop. Suppose that the optimal graph-level weight can provide a global filter that achieves the best average accuracy among all subgraphs (not the best in every subgraph), while the optimal node-level weight can provide the optimal filter for each subgraph which can achieve the best accuracy in every subgraph. However, to achieve the optimal node-level weight, we need to estimate the node homophily \(\lambda\), and LocalSim is used for the aim. Next, we investigate the effectiveness of using LocalSim to indicate \(\lambda\). **Theorem 1** (Effectiveness of LocalSim Indicating \(\lambda\)).: _Consider FSBMs with 2 equally-sized communities and 2 equally-sized subgraphs, and assume that the number of inter-community and intra-community edges for all the nodes is the same as their expectation and without self-loop. Consider that LocalSim is defined as \(\phi(v_{i})=-\frac{1}{|\mathcal{N}_{i}|}\sum_{v_{j}\in\mathcal{N}_{i}}(x_{i}- x_{j})^{2}\). For any node \(v_{i}\) that belongs to \(\mathcal{G}_{\tau}\), for \(\tau=1,2\), we have \(\mathbb{E}[\phi(v_{i})]=-2\sigma^{2}-(1-\lambda_{\tau})(\mu_{1}-\mu_{2})^{2}\), where \(\lambda_{\tau}=\frac{p_{\tau}}{p_{\tau}+q_{\tau}}\). Moreover, for any two nodes \(v_{i}\in\mathcal{G}_{1}\) and \(v_{j}\in\mathcal{G}_{2}\), the expectation of L1-norm distance between \(\phi(v_{i})\) and \(\phi(v_{j})\) is no less than to \(|\lambda_{1}-\lambda_{2}|(\mu_{1}-\mu_{2})^{2}\)._ We defer the proof to Appendix A. Theorem 1 states that \(\mathbb{E}[\phi(v_{i})]\) linearly correlates to \(\lambda_{\tau}\) when \(v_{i}\in\mathcal{G}_{\tau}\), which suggests that LocalSim can represent the homophily \(\lambda_{\tau}\) of node \(v_{i}\) unbiasedly. We can also get that the expectation of L1-norm distance positively correlates to \(|\lambda_{1}-\lambda_{2}|\). This indicates that our estimation is likely to perform better when \(|\lambda_{1}-\lambda_{2}|\) goes up. When the gap between \(\lambda_{1}\) and \(\lambda_{2}\) shrinks, the two subgraphs become similar to each other, so does the optimal filter for each community. These results confirm the effectiveness of LocalSim indicating node homophily, which yields high performance in our empirical investigation. ## 5 Additional Related Work In this section, we discuss some related work that attempts to address the heterophily issue. Mixhop [1] proposes to extract features from multi-hop neighborhoods to get more information. CPGNN [11] modifies feature propagation based on node classes in GCN to accommodate heterophily. Geom-GCN [14] proposes to use the graph structure defined by geometric relationship to perform aggregation process to address heterophily. FAGCN [1] proposes to use the attention mechanism to learn the edge-level aggregation weights of low-pass and high-pass filters to adaptively address the heterophily issue, while we use LocalSim to parameterize the node-level weight which achieves less computation complexity and better performance. H\({}_{2}\)GCN [15] and GPRGNN [1] propose fusing intermediate representation at graph-level based on their analysis of graphs. ACM-GCN [11] divides feature propagation into three channels: low-pass, high-pass, and identity, and then adaptively mix the three channels during propagation but does not fuse different intermediate representations. Compared with H\({}_{2}\)GCN, GPRGNN, and ACM-GCN, our work only needs propagation once which means the propagation can be pre-computed, while their works are trained via back-propagation through repeated feature propagation which yields huge computation costs. ASGC [12] directly uses the least square to filter the features obtained by SGC [1] for classification, while our work involves multiple intermediate information, which is fused by node-level weight. These designs yield better performance based on pre-propagated features. Different from all these methods, our work uses LocalSim to parameterize the node-level weight for better adaptive fusion efficiently, and performs IRDC as an efficient propagation method for better informative representation, thus boosting the performance while keeping high efficiency. Moreover, we show that our designed LocalSim-based node-level weight can be used to improve the performance of H\({}_{2}\)GCN and GPRGNN, which confirms the superiority of our method. ## 6 Experiment ### Datasets and Setups We evaluate LSGNN on nine small real-world benchmark datasets including both homophilic and heterophilic graphs. For homophilic graphs, we adopt three widely used citation networks, Cora, Citeseer, and Pubmed [15, 16]. For heterophilic graphs, Chameleon and Squirrel are page-page Wikipedia networks [17, 1], Actor is a actor network [14], and Cornell, Texas and Wisconsin are web pages networks [14]. Statistics of these datasets can be seen in Appendix D. For all datasets, we use the feature matrix, class labels, and 10 random splits (48%/32%/20%) provided by Pei _et al._[13]. Meanwhile, we use Optuna to tune the hyperparameter 200 times in experiments. For LSGNN, we set the number of layer \(K=5\). There are three types of baseline methods, including non-graph models (MLP), traditional GNNs (GCN, GAT [2], etc.), and GNNs tolerating heterophily (Geom-GCN, GPRGNN, etc.). ### Evaluations on Real Benchmark Datasets As shown in Table 1, LSGNN outperforms most of the baseline methods. On homophilic graphs, LSGNN achieves the SOTA performance on the Cora and Pubmed datasets and Figure 3: Accuracy (higher is better) on the synthetic graphs using graph-level weight and LocalSim-based node-level weight. Node homophily is measured by \(\lambda_{i}\). ‘Raw’ shows the result directly using raw feature. is lower than the best result by only 1.28% on the Citeseer dataset. On heterophilic graphs except Actor, LSGNN significantly outperforms all the other baseline models by 1.77%-11.00%. Specifically, the accuracy of LSGNN is 7.83% and 2.97% higher than GloGNN, the existing SOTA method on heterophilic graphs, on Chameleon and Cornell, is 11.00% higher than LINKX [11] on Squirrel, and is 2.43% and 1.77% higher than ACM-GCN on Texas and Wisconsin. In particular, LSGNN achieves the best average accuracy, higher than the second-best by 3.60%. This demonstrates that LSGNN can achieve comparable or superior SOTA performance on both homophilic and heterophilic graphs. ### Evaluations on Large Benchmark Datasets We also conduct experiments on two large datasets: ogbn-arXiv (homophilic) and arXiv-year (heterophilic), both with 170k nodes and 1M edges but different labels, following settings in [10] and [11], see Appendix D for setting details. Table 2 shows that our method has competitive performance on both homophilic and heterophilic larger graphs. ### Training Cost Comparison LSGNN only needs to propagate once during training, and the networks for node-level weight are small. Thus the efficiency of LSGNN can be close to SGC's. As shown in Figure 4(a), on the average training time over nine datasets, our proposed method is only slower than SGC, a simple and effective model, and is nearly \(2\times\) faster than GCN and GAT. This confirms the high training efficiency of LSGNN. See Appendix C for more setting details and detailed comparisons of training costs on each dataset. ### Alleviate Over-Smoothing Issue To validate whether LSGNN can alleviate the over-smoothing issue, we compare the performance between vanilla GCN and LSGNN under different layers of propagation (Figure 4(b)), see Appendix E for full results. It can be seen that GCN achieves the best performance at 2 layers, and its performance decreases rapidly as layers increase. In contrast, the results of LSGNN keep stable and high. The reasons are two-fold: (i) our IRDC can extract better informative representations, and (ii) our LocalSim-based fusion can adaptively remain and drop distinguishable and indistinguishable representations, respectively. Through these two designs, LSGNN can perform well as layers increase, which indicates the capability of LSGNN to prevent the over-smoothing issue. ### LocalSim-based Node-level Weight as a Plug-and-Play Module LocalSim-based node-level weight (Section 3.4) can be regarded as a plug-and-play module, which can be added to existing GNNs that also fuse intermediate representations without involving extra hyperparameters, such as H\({}_{2}\)GCN, GPRGNN, and DAGNN. H\({}_{2}\)GCN and GPRGNN use learned graph-level weight to fuse the intermediate representations, which is only replaced \begin{table} \begin{tabular}{l c c c c c c c c c c} \hline \hline & **Cora** & **Citeseer** & **Pubmed** & **Chameleon** & **Squirrel** & **Actor** & **Cornell** & **Texas** & **Wisconsin** & **Avg** \\ \hline \({}^{2}\)MLP & 74.75 & 72.41 & 86.65 & 46.36 & 29.68 & 35.76 & 81.08 & 81.89 & 85.29 & 65.99 \\ \({}^{2}\)GCN & 87.28 & 76.68 & 87.38 & 59.82 & 36.89 & 30.26 & 57.03 & 59.46 & 59.80 & 61.62 \\ \({}^{2}\)GAT & 82.68 & 75.46 & 84.68 & 54.69 & 30.62 & 26.28 & 58.92 & 58.38 & 55.29 & 58.56 \\ \({}^{2}\)MixHop & 87.61 & 76.26 & 85.31 & 60.50 & 43.80 & 32.22 & 73.51 & 77.84 & 75.88 & 68.10 \\ \({}^{3}\)GCNII & 88.37 & 77.33 & 90.15 & 63.86 & 38.47 & 37.44 & 77.86 & 77.57 & 80.39 & 70.16 \\ \hline \({}^{1}\)Geom-GCN & 85.27 & **77.99** & 90.05 & 60.90 & 38.14 & 31.63 & 60.81 & 67.57 & 64.12 & 64.05 \\ \({}^{1}\)H\({}_{2}\)GCN & 87.81 & 77.07 & 89.59 & 59.39 & 37.90 & 35.86 & 82.16 & 84.86 & 86.67 & 71.26 \\ \({}^{1}\)WRGNN & 88.20 & 76.81 & 88.52 & 65.24 & 48.85 & 36.53 & 81.62 & 83.62 & 86.98 & 72.93 \\ \({}^{3}\)GPRGNN & 87.95 & 77.13 & 87.54 & 46.58 & 31.61 & 34.63 & 80.27 & 78.38 & 82.94 & 67.45 \\ \({}^{3}\)LINK & 84.64 & 73.19 & 87.86 & 68.42 & 61.81 & 36.10 & 77.84 & 74.60 & 75.49 & 71.11 \\ \({}^{3}\)ACM-GCN & 87.91 & 77.32 & 90.00 & 66.93 & 54.40 & 36.28 & 85.14 & 87.84 & 88.43 & 74.92 \\ \({}^{3}\)GGCN & 87.95 & 77.14 & 89.15 & 71.14 & 55.17 & 37.54 & 85.68 & 84.86 & 86.86 & 75.05 \\ \({}^{1}\)GloGNN & 88.33 & 77.41 & 89.62 & 71.21 & 57.88 & **37.70** & 85.95 & 84.32 & 88.04 & 75.61 \\ \hline **LSGNN** & **88.49** & 76.71 & **90.23** & **79.04** & **72.81** & 36.18 & **88.92** & **90.27** & **90.20** & **79.21** \\ \hline \hline \end{tabular} \end{table} Table 1: Results on real-world benchmark datasets: Mean accuracy (%). **Boldface** and underline numbers mark the top-1 and top-2 results, respectively. \({}^{1}\) denotes results from their respective papers, \({}^{2}\) from the H\({}_{2}\)GCN paper, and \({}^{3}\) from the GloGNN paper. \begin{table} \begin{tabular}{l|c|c c c|c|c} \hline & \(\mathcal{H}(\mathcal{G})\) & GCN & SGC & GCNII & LINKX & GloGNN & **LSGNN** \\ \hline arXiv-year & 0.22 & 46.02 & 32.83 & 47.21 & 56.00 & 54.79 & **56.42** \\ ogbn-arXiv & 0.66 & 71.74 & 69.39 & **72.74** & 54.45 & 49.22\({}^{*}\) & 72.64 \\ Avg & NA & 58.88 & 51.11 & 59.98 & 55.23 & 52.01 & **64.53** \\ \hline \hline \end{tabular} \end{table} Table 2: Average accuracy (%) over 5 runs on large datasets. The field marked \({}^{*}\) denotes our implementation. Figure 4: Comparison of the average Training Cost Time (s) on nine real-world datasets (Left). Average results with various model depth on nine real-world datasets (Right). by LocalSim-based node-level weight here. Note that we only add LocalSim-based node-level weight into H\({}_{2}\)GCN and GPRGNN, but not the enhanced filters or the high-pass filters. As shown in Table 3, the performance of both H\({}_{2}\)GCN and GPRGNN increases significantly, indicating that taking each node's local topology into consideration when fusing intermediate representations is more reasonable and effective than merely considering graph-level structure. DAGNN also fuse intermediate representations by node-level weight, which however is simply mapped from each node's representation and is learned without involving any local topology information, leading to a suboptimal result. We use LocalSim-based node-level weight in DAGNN similarly. The drmatic improving in Table 3 suggests that using LocalSim as local topology information can ensure the weight being learned more effectively. Although DAGNN is not designed for heterophilic graphs, it can also perform well on heterophilic graphs after using LocalSim-based node-level weight, and is even superior to H\({}_{2}\)GCN on Squirrel. ### Ablation Study In what follows, we investigate the effectiveness of LocalSim-based node-level weight, weighted self-loops, and IRDC. Specifically, in the baseline model, we use graph-level weight learned without any local topology information to fuse the intermediate representations, add self-loops when conducting graph filtering, and apply the propagation method used in GCNs. Then, the above components are added one by one to the baseline model for performance comparison. As shown in Table 4, all the components are effective and can bring great benefits to the model in terms of performance improvement. Note that learning node-level weight without any local topology information ('Rand') might even bring negative effect on the model (lower than baseline by 0.39% on average). Once LocalSim is used as local topology information, the model can easily learn an optimal node-level weight (75.16% on average, higher than the baseline by 1.32%), which indicates the superiority of LocalSim-Aware Multi-Hop Fusion. When replacing the fixed self-loops with weighted self-loops, the performance increases significantly (by 2.34% to 77.50% on average), especially on heterophilic graphs, such as Chameleon and Squirrel. This is because self-loops might not always be helpful on heterophilic graphs. IRDC also brings a significant improvement (by an increase of 1.71% to 79.21% on average). This suggests that such a propagation method can extract more informative representation for better performance. ## 7 Conclusion In this paper, LSGNN is proposed for better performance on both homophilic and heterophilic graphs. Many GNNs use graph-level weight to fuse intermediate representations, which does not fully consider the local structure of different nodes. Some GNNs use node-level weight learned without involving topology information, yielding suboptimal results. Our empirical study and theoretical analysis on synthetic graphs demonstrate the importance of node-level weight considering the local topology information of nodes. The proposed LocalSim-aware multi-hop fusion uses local similarity as guidance to generate a more appropriate node-level weight for intermediate representations fusion, and it can also be used as a plug-and-play module to improve the performance of existing GNNs. For better fusion, IRDC is proposed to extract more informative intermediate representations boosting the performance. Evaluations over real-world benchmark datasets show the superiority of LSGNN in handling both homophilic and heterophilic graphs and the effectiveness of all the proposed components. \begin{table} \begin{tabular}{l c c c c c c c c c c c c} \hline \hline & \multicolumn{4}{c}{Components} & \multicolumn{4}{c}{Dataset} \\ & Rand & LocalSim & w-self-loop & IRDC & **Cora** & **Citeseer** & **Pubmed** & **Chameleon** & **Squirrel** & **Actor** & **Cornell** & **Texas** & **Wisconsin** & **Avg** \\ \hline Baseline & & & & 86.33 & 74.53 & 89.99 & 67.28 & 47.73 & 35.27 & 86.47 & 88.92 & 88.04 & 73.84 \\ & ✓ & & & 87.93 & 75.32 & 90.08 & 67.72 & 48.99 & 35.65 & 78.38 & 88.51 & 88.43 & 73.45 \\ & & ✓ & & 87.62 & 76.60 & 90.20 & 69.96 & 49.95 & 35.80 & 87.57 & 88.92 & 89.80 & 75.16 \\ & ✓ & ✓ & & 87.65 & **76.89** & 89.98 & 75.95 & 65.50 & 35.80 & 87.84 & 88.11 & 89.80 & 77.50 \\ \hline **LSGNN** & ✓ & ✓ & ✓ & **88.49** & 76.71 & **90.23** & **79.04** & **72.81** & **36.18** & **88.92** & **90.27** & **90.20** & **79.21** \\ \hline \hline \end{tabular} \end{table} Table 4: Ablation study on 9 real-world benchmark datasets. Cells with ✓ mean that the corresponding components are applied to the baseline model. **Boldface** and underlined mark the top-1 and top-2 results. ‘Rand’ denotes random node-level weight (i.e., learned without any local topology information). ‘LocalSim’ means that the added node-level weight is learned under the guidance of LocalSim. ‘w-self-loop’ denotes weighted self-loops. ‘IRDC’ stands for the propagation via IRDC. \begin{table} \begin{tabular}{l c c c c c c c c c c c} \hline \hline & **Cora** & **Citeseer** & **Pubmed** & **Chameleon** & **Squirrel** & **Actor** & **Cornell** & **Texas** & **Wisconsin** & **Avg** \\ \hline H\({}_{2}\)GCN & 87.81 & **77.07** & 89.59 & 59.39 & 37.90 & 35.86 & 82.16 & 84.86 & 86.67 & 71.26 \\ **w/ LocalSim** & **88.42** & 76.77 & **89.91** & **64.91** & **41.73** & **36.29** & **85.68** & **85.68** & **88.82** & **73.13** \\ \hline GPRGNN & 87.95 & **77.13** & 87.54 & 46.58 & 31.61 & 34.63 & 80.27 & 78.38 & 82.94 & 67.45 \\ **w/ LocalSim** & **88.83** & 76.60 & **90.26** & **65.39** & **51.96** & **35.59** & **85.14** & **87.84** & **87.65** & **74.36** \\ \hline DAGNN & 82.63 & **75.47** & 88.50 & 58.03 & 39.59 & 30.20 & 61.89 & 58.92 & 55.10 & 61.15 \\ **w/ LocalSim** & **84.12** & 75.29 & **89.97** & **61.10** & **44.91** & **34.13** & **79.73** & **77.03** & **85.29** & **70.17** \\ \hline \hline \end{tabular} \end{table} Table 3: LocalSim-based node-level weight as a plug-and-play module added to other models. **w/ LocalSim** denotes the LocalSim-based node-level weight is used, replacing the graph-level weight used in H\({}_{2}\)GCN and GPRGNN, and replacing the random node-level weight (learned without any local topology information) in DAGNN. The best results are in **boldface**. ## Acknowledgements This work is partially supported by the National Key R&D Program of China under Grant No. 2022YFB2703303, by the National Natural Science Foundation of China (NSFC) under Grant No. U22B2060, Grant No. 61972442, Grant No. 62102413, and Grant No. U2001202, by Guangzhou Municipal Science and Technology Bureau under Grant No. 2023A03J0667, by HKUST(GZ) under a Startup Grant, by the S&T Program of Hebei under Grant No. 20350802D, by the Natural Science Foundation of Hebei Province of China under Grant No. F2020202040, and by the Natural Science Foundation of Tianjin of China under Grant No. 20JCYBJC00650.
2306.14566
Estimating Quantum Mutual Information Through a Quantum Neural Network
We propose a method of quantum machine learning called quantum mutual information neural estimation (QMINE) for estimating von Neumann entropy and quantum mutual information, which are fundamental properties in quantum information theory. The QMINE proposed here basically utilizes a technique of quantum neural networks (QNNs), to minimize a loss function that determines the von Neumann entropy, and thus quantum mutual information, which is believed more powerful to process quantum datasets than conventional neural networks due to quantum superposition and entanglement. To create a precise loss function, we propose a quantum Donsker-Varadhan representation (QDVR), which is a quantum analog of the classical Donsker-Varadhan representation. By exploiting a parameter shift rule on parameterized quantum circuits, we can efficiently implement and optimize the QNN and estimate the quantum entropies using the QMINE technique. Furthermore, numerical observations support our predictions of QDVR and demonstrate the good performance of QMINE.
Myeongjin Shin, Junseo Lee, Kabgyun Jeong
2023-06-26T10:26:45Z
http://arxiv.org/abs/2306.14566v2
# Estimating Quantum Mutual Information Through a Quantum Neural Network ###### Abstract We propose a method of quantum machine learning called quantum mutual information neural estimation (QMINE) for estimating von Neumann entropy and quantum mutual information, which are fundamental properties in quantum information theory. The QMINE proposed here basically utilizes a technique of quantum neural networks (QNNs), to minimize a loss function that determines the von Neumann entropy, and thus quantum mutual information, which is believed more powerful to process quantum datasets than conventional neural networks due to quantum superposition and entanglement. To create a precise loss function, we propose a quantum Donsker-Varadhan representation (QDVR), which is a quantum analog of the classical Donsker-Varadhan representation. By exploiting a parameter shift rule on parameterized quantum circuits, we can efficiently implement and optimize the QNN and estimate the quantum entropies using the QMINE technique. Furthermore, numerical observations support our predictions of QDVR and demonstrate the good performance of QMINE. ## I Introduction The concept of quantum mutual information (QMI) in quantum information theory quantifies the amount of information shared between two quantum systems. This extends the classical notion of mutual information to the quantum regime [1; 2; 3]. This information measure is fundamental, because it determines the quantum correlation or entanglement between two quantum systems. The information obtained from quantum mutual information can be applied to various fields of quantum information processing such as quantum computation, quantum cryptography, and quantum communication [2; 3] (particularly in quantum channel capacity problems [4; 5]). They also play a crucial role in quantum machine learning [6; 7], where they measure the information shared between different representations of quantum datasets. Moreover, the gathered information can be used to enhance the efficiency and effectiveness of quantum algorithms in processing quantum data. Quantum mutual information is expressed as the sum of von Neumann entropies, denoted by \(S(\rho)=-\mathrm{Tr}(\rho\ln\rho)\) for a quantum state \(\rho\), making the determination of the von Neumann entropy [8] essential for calculating quantum mutual information. In recent years, the estimation of the von Neumann entropy has garnered significant attention in the field of quantum information theory. Various methods have been proposed to estimate von Neumann entropy, including those exploiting quantum state tomography [9], Monte Carlo sampling [10], and entanglement entropy [11][12; 13; 14; 15; 16; 17; 18]. Several studies [16; 17; 18] have utilized quantum query models for entropy estimation and have demonstrated promising quantum speedups. Specifically, Wang et al. [16] proposed that the von Neumann entropy can be estimated with an accuracy of \(\varepsilon\) by using \(O(\frac{r}{\varepsilon^{2}})\) queries. However, these query model-based algorithms have practical limitations because a quantum circuit that generates the quantum state must be prepared, and the effectiveness of constructing a quantum query model for the input state remains an open question [15]. Thus, we focused on estimating the von Neumann entropy of an unknown quantum state using only identical copies of the state. To the best of our knowledge, no existing quantum algorithms estimate the von Neumann entropy using \(O(\mathrm{poly}(r),\mathrm{poly}(\frac{1}{\varepsilon}))\) copies of the quantum state, where \(r\) represents the rank of the state. A mutual information neural estimation (MINE) method is a novel technique that utilizes neural networks to calculate the classical mutual information between two random variables. More precisely, this method optimizes a neural network to estimate mutual information by minimizing the loss function. The loss function is based on the Donsker-Varadhan representation [19] that provides a lower bound for the well-known Kullback-Leibler (KL) divergence. Quantum neural networks (QNNs) [20; 21], which are among the most powerful quantum machine learning methods, serve as quantum counterparts to conventional neural networks, and offer several advantages. One notable advantage is the ability to use a quantum state as an input, which is particularly advantageous when calculating quantum mutual information or the von Neumann entropy. We identified two types of QNNs in the literature [20; 22] that possess a neural network structure and leverage quantum advantages accompanied by well defined training procedures. In this study, we employed a parameterized quantum circuit [22], which is known for its quantum advantages, despite the presence of the barren plateau problem, which requires further investigation [23]. As a quantum analogue of MINE, we propose a quantum mutual information neural estimation (QMINE), which is method for determining the von Neumann entropy and quantum mutual information through a quantum neural network technique. Similar to the classical case, QMINE uses a quantum neural network to minimize the loss function that evaluates the von Neumann entropy. To generate a loss function that estimates the von Neumann entropy, we present the quantum Donsker-Varadhan representation (QDVR), which is a quantum version of the Donsker-Varadhan representation. QMINE offers the potential for a quantum advantage in estimating the von Neumann entropy facilitated by QDVR. By converting the problem of von Neumann entropy estimation into a quantum machine learning regime, QMINE opens new possibilities. There is also the potential to estimate von Neumann entropy using only \(O(\text{poly}(r),\text{poly}(\frac{1}{\varepsilon}))\) copies of the quantum state. However, we acknowledge that further investigation is required owing to the challenging and well-known barren plateau problem, as well as the need for efficient quantum training methods. The remainder of this paper is organized as follows. In Sec. II, we briefly introduce the basic notions on quantum mutual information, MINE, and parametrized quantum circuits. In Sec. III, we generalize the Donsker-Varadhan representation to a QDVR, which is the main component of QMINE. We also propose an estimation method for von Neumann entropy using quantum neural networks in Sec. IV. This implies that it is possible to efficiently obtain the quantum mutual information, and its numerical simulations under the framework of QMINE in Sec. V. Finally, a discussion and remarks are presented in Sec. VI, and open questions and possibilities are raised for future research. ## II Preliminaries ### Quantum Mutual Information and von Neumann Entropy Quantum mutual information, also known as von Neumann mutual information, quantifies the relationship between two quantum states. This can be calculated by using the formula (See Fig. 1): \[I\left(A:B\right)=S\left(\rho^{A}\right)+S\left(\rho^{B}\right)-S\left(\rho^{ AB}\right). \tag{1}\] Here, \(S(\rho)\) represents the von Neumann entropy [8] of quantum state \(\rho\) in a \(d\)-dimensional Hilbert space, given by \(S\left(\rho\right)=-\text{Tr}\left(\rho\log\rho\right)\). Therefore, estimating the von Neumann entropy enables the estimation of the quantum mutual information. The von Neumann entropy, which is an extension of the Shannon entropy [24] to the quantum domain, can be estimated using quantum circuits and measurements. It is defined as the entropy of the density matrix associated with a quantum state, where the density matrix is a positive semi-definite matrix that represents the state. To estimate the von Neumann entropy, measurements can be performed on multiple copies of the quantum state and the outcomes of these measurements can be utilized. The most straightforward approach is to directly estimate the density matrix and calculate the entropy using its definition. However, estimating the von Neumann entropy can be challenging, particularly for large quantum systems, owing to the difficulty in accurately estimating the density matrix. Furthermore, the estimation accuracy is influenced by the number of measurements conducted and the quality of the quantum hardware employed. However, ongoing research is focused on developing more efficient and precise methods for estimating the von Neumann entropy. Several methods have been employed to estimate von Neumann entropy, particularly those utilizing the quantum query model [15; 17; 18]. In the quantum query model, if the quantum circuit \(U\) produces a quantum state \(\rho\), it utilizes unitary gates such as \(U\), \(U^{\dagger}\), and \(\text{C}U\) (controlled-\(U\)). However, the quantum circuit must be known to use the query model. The effectiveness of constructing a quantum query model for a given input state remains uncertain [15], prompting us to explore the von Neumann entropy estimation without relying on the quantum query model. In the absence of a query model, our approach solely exploits identical copies of quantum states. Previous studies, such as Acharya et al. [13] employed \(O(d^{2})\) copies of the quantum state \(\rho\), where \(d\) denotes the dimension, whereas Wang et al. [15] used \(O\left(\frac{1}{\varepsilon^{5}\lambda^{2}}\right)\) copies of \(\rho\), where \(\lambda\) represents the lower bound on all non-zero eigenvalues. To the best of our knowledge, no existing algorithm provides a high-accuracy estimation of the von Neumann entropy by using only \(O(\text{poly}(r))\) copies of \(\rho\) with rank \(r\). Figure 1: Schematic diagram for the quantum mutual information, \(I(A:B)\), between two quantum states \(\rho^{A}\) and \(\rho^{B}\). ### Mutual Information Neural Estimator The mutual information neural estimator (MINE) [25] is a method for estimating the mutual information of two random variables by using neural networks. This approach involves selecting functions \(T_{\theta}:X\times Y\rightarrow\mathbb{R}\) that are parameterized by neural networks with the parameter \(\theta\in\Theta\). Considering \(n\) samples, we define the empirical joint and product probability distributions as \(p_{XY}^{(n)}\) and \(p_{X}^{(n)}\times p_{Y}^{(n)}\), respectively. The MINE strategy is given by: \[I(\widehat{X:Y})_{n}=\sup_{\theta\in\Theta}\mathbb{E}_{p_{XY}}\left[T_{\theta} \right]-\log\left(\mathbb{E}_{p_{X}\times p_{Y}}\left[e^{T_{\theta}}\right] \right), \tag{2}\] where \(\mathbb{E}\) is the expected value. Additionally, the Donsker-Varadhan representation is defined as follows: For any probability distribution functions \(p\) and \(q\), \[D_{KL}(p||q)=\sup_{T:\Omega\rightarrow\mathbb{R}}\mathbb{E}_{p}[T]-\log\left( \mathbb{E}_{q}\left[e^{T}\right]\right), \tag{3}\] where we take the supremum over all the functions \(T\). Using the Donsker-Varadhan representation [26], it can be proven that \(I\left(X:Y\right)\geq I\left(\widehat{X:Y}\right)_{n}\) and MINE are strongly consistent, meaning that there exists a positive integer \(N\) and a choice of neural network parameters \(\theta\in\Theta\) such that for all \(n\geq N\), \(\left|I(X:Y)-I(\widehat{X:Y})_{n}\right|\leq\varepsilon\). By applying a gradient descent method on the neural network \(T_{\theta}\) to maximize \(\mathbb{E}_{p_{XY}}[T_{\theta}]-\log\left(\mathbb{E}_{p_{X}\times p_{Y}}\left[ e^{T_{\theta}}\right]\right)\), we can obtain \(I(\widehat{X:Y})_{n}\) and estimate the mutual information \(I(X:Y)\). The MINE technique has found applications in various areas of artificial intelligence, such as feature selection, representation learning, and unsupervised learning, using information-theoretic methods. Compared to previous approaches, it provides more accurate and robust estimates of mutual information, leading to significant advancements in the field of artificial intelligence (AI). It is important to recognize that MINE is a relatively new and rapidly evolving field, with ongoing research focused on enhancing and broadening its capabilities. Nonetheless, the MINE technique is widely regarded as a valuable tool in AI and information theory, offering a powerful and flexible approach for estimating the mutual information between variables. ### Parametrized Quantum Circuits Parameterized quantum circuits (PQCs) [22] are quantum circuits that incorporate adjustable parameters, typically represented as real numbers. These parameters can be fine-tuned to control the behavior of the quantum circuit, thereby providing increased flexibility and optimization potential. Parameterized quantum circuits have extensive applications in quantum machine learning and optimization algorithms, enabling computations that are challenging or even infeasible using classical methods. The key concept is to employ a parameterized quantum circuit as a feature extractor or waveform generator, followed by classical optimization algorithms that iteratively adjust the circuit parameters to minimize the objective function. By manipulating circuit parameters, one can efficiently learn and represent quantum systems in a compact and adaptable manner. In quantum optimization, parameterized quantum circuits play a crucial role in global minimum search. By encoding the objective function into circuit parameters, quantum effects such as quantum parallelism and quantum tunneling can be harnessed to explore the search space more effectively than classical optimization algorithms. One of the core techniques used in quantum optimization procedures for parameterized quantum circuits is the parameter shift rule [27]. The parameter shift rule is a powerful tool in quantum machine learning that enables efficient computation of gradients with respect to the parameters of a quantum circuit. The fundamental concept behind the parameter shift rule is to employ a quantum circuit with adjustable parameters to perform the measurements. By utilizing the measurement outcome, it is possible to estimate the gradient of a cost function with respect to the circuit parameters. This rule capitalizes on the notion that small variations in the parameters of a quantum circuit can be used to calculate the derivative of the cost function pertaining to these parameters. The underlying principle involves the preparation of two identical copies of a quantum state, each with slightly different parameter values. By comparing these two quantum states, it was possible to estimate the gradient. More importantly, this method allows the calculation of gradients in a single pass through a quantum circuit, obviating the need for additional measurements. If a parameterized quantum circuit is represented as a sequence of unitary gates, it is denoted as \[U(x;\theta):=\left(\prod_{i=1}^{N}U_{i}(\theta_{i})\right)U_{0}(x),\] The output of the circuit can then be observed using an observable \(\hat{O}\) and the measurement outcome becomes a quantum circuit function. The quantum circuit function is expressed in simplified form as \(f(x;\theta_{i})=\langle\psi_{i}|U_{i}^{\dagger}(\theta_{i})\hat{O}_{i+1}U_{i}( \theta_{i})|\psi_{i}\rangle\) for each \(i\). The gradient of the quantum circuit function can then be calculated using the parameter shift rule, as follows: \[\nabla_{\theta_{i}}f(x;\theta_{i})=c\left(\langle\psi_{i}|U_{i}^{\dagger}(\theta_{i }+s)\hat{O}_{i+1}U_{i}(\theta_{i}+s)|\psi_{i}\rangle-\langle\psi_{i}|U_{i}^{ \dagger}(\theta_{i}-s)\hat{O}_{i+1}U_{i}(\theta_{i}-s)|\psi_{i}\rangle\right). \tag{4}\] The parameter shift rule has been successfully employed in various quantum machine learning algorithms, including quantum neural networks [20, 22] and quantum support vector machines [28, 29], for optimization and training purposes. It is regarded as a valuable tool for developing efficient quantum machine learning algorithms, as it enables the efficient computation of gradients in quantum systems, which is often a challenging task. It is important to note that the parameter shift rule is an approximation, and its accuracy depends on factors such as the choice of parameters, cost function, and the specific quantum circuit. Nevertheless, it has proven to be a useful and efficient technique in the emerging field of quantum machine learning, and our ongoing research focuses on enhancing and expanding its potential capabilities. ## III Quantum Donsker-Varadhan representation The quantum Donsker-Varadhan representation is a mathematical framework that enables quantum neural networks to estimate the von Neumann entropy. It is a quantum counterpart of the original Donsker-Varadhan representation, with the distinction that QDVR focuses solely on the quantum entropy rather than on the relative entropy. QDVR can be considered as a modified version of the Gibbs variational principle [30], which restricts the domain to density matrices. As mentioned previously, MINE [25] exploits the original Donsker-Varadhan representation to estimate classical mutual information using a (classical) neural network. In the context of estimating mutual quantum information, it is natural to consider a quantum version of the Donsker-Varadhan representation. Notably, we need only estimate the components of von Neumann entropy \(S(\rho_{A})\), \(S(\rho_{B})\), and \(S(\rho_{AB})\) to determine the quantum mutual information \(I(A:B)\). A variational formula for von Neumann entropy exists as follows: **Theorem 1** (Gibbs Variational Principle [30]).: _Let \(f:H^{d\times d}\rightarrow\mathbb{R}\) be a function defined on \(d\)-dimensional Hermitian matrices \(T\) and \(\rho\) be a density matrix. Then we have_ \[f(T)=-\mathrm{Tr}(\rho T)+\log\left(\mathrm{Tr}(e^{T})\right). \tag{5}\] _Thus, for \(d\)-dimensional Hermitian matrices \(T\), the von Neumann entropy is given by:_ \[S(\rho)=\inf_{T}f(T), \tag{6}\] _where the infimum is taken over all Hermitian \(T\)._ Our objective is to determine the Hermitian matrix \(T\) that maximizes \(f(T)\). We parameterize \(T\) by using \(t_{i}\in\mathbb{R}\) and \(|\psi_{i}\rangle\in\mathbb{C}^{d}\). We can express \(T=\sum_{i=1}^{r}t_{i}|\psi_{i}\rangle\langle\psi_{i}|\), which gives us \(f(T)=-\sum_{i=1}^{d}t_{i}\langle\psi_{i}|\rho|\psi_{i}\rangle+\log\left(\sum_ {i=1}^{d}e^{t_{i}}\right)\). To compute \(f(T)\), we must measure the quantum state \(\rho\) using the basis \(\{|\psi_{i}\rangle\}_{i=1}^{d}\). Achieving this with an error smaller than \(\varepsilon\) requires \(O(\frac{\sigma^{2}}{\varepsilon^{2}})\) samples of \(\rho\), where \(\sigma:=\mathrm{Var}(\{t_{i}\})\). However, the number of required samples of \(\rho\) can become substantial because of the broad domain of \(T\), which encompasses all Hermitian matrices. Therefore, reducing the size of this domain is imperative. **Lemma 2**.: _For all Hermitian matrices \(T\), the function \(f\) holds that_ \[f(T)=f(T+cI) \tag{7}\] _for a constant \(c\)._ Proof.: For any \(T\in H^{d\times d}\), we have \[f(T+cI) =-\mathrm{Tr}(\rho(T+cI))+\log\left(\mathrm{Tr}(e^{T+cI})\right)\] \[=-\mathrm{Tr}(\rho T)-c\mathrm{Tr}(\rho)+\log\left(e^{c}\mathrm{ Tr}(e^{T})\right)\] \[=-\mathrm{Tr}(\rho T)-\log\left(\mathrm{Tr}(e^{T})\right)\] \[=f(T).\] Thus, \(f(T)=f(T+cI)\) for a constant \(c\). **Proposition 1** (Domain Reduction).: _Let \(f:H^{d\times d}\rightarrow\mathbb{R}\) be a function defined on \(d\)-dimensional Hermitian matrices and let \(\rho\) be a density matrix. Then,_ \[S(\rho)=\inf_{T}f(T) \tag{8}\] _for \(d\)-dimensional 'positive' Hermitian matrices \(T\)._ Proof.: For any Hermitian matrix \(T\in H^{d\times d}\), let \(c=\max_{|\psi_{i}\rangle\in\mathbb{C}^{d}}\langle-\langle\psi_{i}|T|\psi_{i}\rangle\rangle\). From Lemma 2, there exists a _positive_ Hermitian matrix \(T_{0}=T+cI\) such that \(f(T)=f(T_{0})\). Therefore, we can reduce the domain of \(T\) to a positive Hermitian matrix. Now, we only need to search for the space of the positive Hermitian matrices to find the optimal \(T\). The computational complexity of copying \(\rho\) to calculate \(f(T)\) depends on \(T\). To reduce this complexity, we need to specify and limit the trace of \(T\). **Lemma 3**.: _A positive Hermitian matrix \(T_{0}\) with rank \(r\) exists that satisfies \(\mathrm{Tr}(T_{0})\leq 2rn+r\log\left(\frac{1}{\varepsilon}\right)\) such that_ \[|S(\rho)-f(T_{0})|<\varepsilon, \tag{9}\] _where \(\rho\) is an \(r\)-rank density matrix._ Proof.: See the details of the proof in Appendix VII.1. **Proposition 2** (Quantum Donsker-Varadhan Representation).: _Let \(f:H^{d\times d}\rightarrow\mathbb{R}\) be a function defined on \(d\)-dimensional Hermitian matrices, and let \(\rho\) be an \(r\)-rank density matrix._ \[g(T)=-\mathrm{Tr}\left(c\rho T\right)+\log\left(\mathrm{Tr}(e^{cT})\right), \tag{10}\] _where \(c\geq 2rn+r\log\left(\frac{1}{\varepsilon}\right)\). Then,_ \[\left|S(\rho)-\inf(g(T))\right|<\varepsilon \tag{11}\] _for any \(d\)-dimensional \(r\)-rank density matrix \(T\)._ Proof.: Using Lemmas 2 and 3, there exists an \(r\)-rank positive Hermitian matrix \(T_{0}\) with \(\mathrm{Tr}(T_{0})=c\) such that \(\left|S(\rho)-f(T_{0})\right|<\varepsilon\). Thus, \(T_{1}=\frac{T_{0}}{c}\) is an \(r\)-rank density matrix, and \(\left|S(\rho)-g(T_{1})\right|<\varepsilon\). From Theorem 1, \(S(\rho)\geq g(T)\) for all density matrices \(T\). Therefore, \(\left|S(\rho)-\inf(g(T))\right|\leq\left|S(\rho)-g(T_{1})\right|<\varepsilon\). This completes the Proof. According to the quantum Donsker-Varadhan representation in Proposition 2, we only need to search within the space of the density matrices. By calculating \(g(T)\) with an error of \(\varepsilon\), the complexity of copying \(\rho\) is \(O(\frac{c^{2}}{\varepsilon^{2}})\). Next, we plan to determine the optimal density matrix \(T\) that minimizes \(g(T)\). In the next section, we will use quantum neural networks to determine the optimal \(T\). ## IV Von Neumann entropy estimation with quantum neural networks We now explain the estimation of von Neumann entropy using quantum neural networks, specifically focusing on parameterized quantum circuits as an example. Our approach is inspired by the work of Liu et al. [31], who utilized variational autoregressive networks and quantum circuits to address problems in quantum statistical mechanics. To achieve this, specific values are assigned to the variables in \(T\) by defining \(t\) as a set of real numbers, \(\{t_{i}|t_{i}\in\mathbb{R}\}\) and \(\left|\psi_{i}\right\rangle\) as complex vectors in \(\mathbb{C}^{d}\). Additionally, let us assume that the rank of \(\rho\) is denoted by \(r\), and we define \(T=\sum_{i=1}^{r}t_{i}|\psi_{i}\rangle\langle\psi_{i}|\). Consequently, function \(g(T)\) becomes \(g(T)=-c\sum_{i=1}^{r}t_{i}\langle\psi_{i}|\rho|\psi_{i}\rangle+\log\left(d-r+ \sum_{i=1}^{r}e^{ct_{i}}\right)\). We can introduce a unitary operator \(U\) that transforms \(\left|\psi_{i}\right\rangle\) into \(\left|i\right\rangle\), and represent this unitary operator using a set of parameters \(\theta\) as \(U(\theta)\). \[g(T)=-c\sum_{i=1}^{r}t_{i}\langle i|U(\theta)\rho U^{\dagger}(\theta)|i \rangle+\log\left(d-r+\sum_{i=1}^{r}e^{ct_{i}}\right) \tag{12}\] By considering \(U(\theta)\) as a quantum neural network and \(\rho\) as its input, we can obtain the network output by computing \(U(\theta)\rho U^{\dagger}(\theta)\). To accurately calculate \(g(T)\) with an error rate less than \(\varepsilon\), it is necessary to measure the output of the quantum neural network \(O\left(\frac{\mathrm{Var}(ct_{i})^{2}}{\varepsilon^{2}}\right)=O\left(\frac{ c^{2}}{\varepsilon^{2}}\right)\) times. Our objective was to optimize the parameters to determine the supremum of \(g(T)\). For example, let us consider a parameterized quantum circuit [22] with Pauli gates as a quantum neural network \(U(\theta)=\prod_{i=1}^{k}U(\theta_{i})\), where \(U(\theta_{i})=e^{-i\frac{\theta_{i}}{2}P_{i}}\). By applying the parameter shift rule [27], we observe that \[\nabla_{\theta}g(t,\theta)=\frac{1}{2}\left[g\left(t,\theta+\frac{\pi}{2} \right)-g\left(t,\theta-\frac{\pi}{2}\right)\right], \tag{13}\] and \[\frac{\partial g(t,\theta)}{\partial t_{i}}=-c\langle i|U(\theta)\rho U^{ \dagger}(\theta)|i\rangle+\frac{ce^{ct_{i}}}{d-r+\sum_{i=1}^{r}e^{ct_{i}}}. \tag{14}\] To satisfy the conditions \(t_{i}\geq 0\) and \(\sum_{i=1}^{r}t_{i}=1\), we choose \(t_{i}=\left(\prod_{j=1}^{i-1}\sin^{2}\varphi_{j}\right)\left(\cos^{2}\varphi_ {j}\right)\). We can apply gradient descent to \(\varphi_{j}\) and \(\theta_{i}\) to optimize the quantum circuit. To calculate the gradient, we require \(O\left(\frac{c^{2}}{\varepsilon^{2}}\times\left(\#\text{ of parameters in QNN}\right)\right)=O\left(\frac{r^{2}}{\varepsilon^{2}}\left(n^{2}+\log^{2} \left(\frac{1}{\varepsilon}\right)\right)n_{\text{params}}n_{\text{train}}\right)\) copies of \(\rho\). Therefore, to obtain \(\inf\left(g\left(T\right)\right)\) and estimate \(S\left(\rho\right)\) with an error of less than \(\varepsilon\), we require \[O\left(\frac{c^{2}}{\varepsilon^{2}}\times\left(\#\text{ of parameters in QNN}\right)\times\left(\#\text{ of trainings in QNN}\right)\right)=O\left(\frac{r^{2}}{\varepsilon^{2}}\left(n^{2}+\log^{2}\left(\frac{1}{ \varepsilon}\right)\right)n_{\text{params}}n_{\text{train}}\right) \tag{15}\] copies of \(\rho\). Analytic gradient measurements in convex loss functions require \(O(\frac{n^{3}}{\varepsilon^{2}})\) copies of \(\rho\) to converge to a solution with \(O(\varepsilon)\) close to the optimum [32]. In general, situations that involve parameterized quantum circuits may have nonconvex loss functions, but many algorithms still utilize parameterized quantum circuits and achieve quantum speedups. We anticipate that quantum speedup can be achieved by employing parameterized quantum circuits with analytic gradient measurements in QMINE and estimating the von Neumann entropy using \(O(\text{poly}(r))\) copies of \(\rho\). In future research, we will investigate the relationships between \(n_{\text{train}}\) and \(n_{\text{params}}\), and the performance of this approach. The key point is to transform the quantum mutual information estimation problem into a quantum neural network problem. ## V Numerical simulations We demonstrated the performance of QMINE in estimating the quantum mutual information of random density matrices through numerical simulations of a quantum circuit. Our goal is to show that QMINE can estimate quantum mutual information with low error. We also analyze the rank and trainable parameters, and conducted simulations to support the results on QDVR. ### Rank Analysis Based on QDVR, we establish that if the rank of the density matrix \(\rho\) is \(r\), then setting the rank of the parameter matrix \(T\) to \(r\) is sufficient. Thus, we aim to determine the optimal \(T\) that estimates the von Neumann entropy. To investigate the effect of rank, we experimented with the rank of \(T\) by letting \(r=\text{rank}(\rho)\) and \(k=\text{rank}(T)\). In this analysis, we simulate the scenario with \(N=5,D=30,r=8\), and \(c\leq 80\), where \(N\) is the number of qubits, \(D\) is the circuit depth, \(r\) is the rank of the density matrix, \(c\) is calculated using QDVR (details are provided in Appendix VII.2). The Fig. 2 shows that when \(k\geq r\), the result of QMINE converges to the correct value, whereas when \(k<r\), it converges at a high error rate. This phenomenon has also been observed in other cases. These results support the QDVR's claim that the rank of the optimal solution \(T\) is \(r\). Because convergence is faster when \(k=r\) than when \(k>r\), it is best to use QMINE with \(k=r\). ### Number of Trainable Parameters on Quantum Circuit Analysis We analyzed the performance of QMINE by varying the depth of the quantum circuit. In our simulations, we used \(N=5\), \(D=30\), \(r=k=8\), and \(c\leq 80\). The experimental results confirmed that as the depth of the circuit and the number of parameters increased, the estimation accuracy of QMINE improved. Fig. 3 illustrates the results, showing that a circuit depth of 20 achieved the best performance. It converged rapidly with a lower error compared to a depth of 30, which converged at a slower rate despite having a similar error. These findings emphasize the importance of choosing an appropriate circuit depth (i.e., number of parameters) in QMINE. The copy complexity is determined by the number of parameters (\(n_{\text{params}}\)) and the number of training iterations (\(n_{\text{train}}\)). Therefore, when applying QMINE in various situations, it is crucial to select the correct circuit depth. We plan to investigate this aspect in future studies. ### Estimating Quantum Mutual Information We estimated the quantum mutual information of a random density matrix using simulations with \(N=4\) Figure 3: The green line in the graph, representing a circuit depth of 20 with 400 parameters, exhibits the best performance. It converges quickly with a low error-rate. However, the red line, representing a depth of 10 with 200 parameters, converges with a high error-rate. The blue line, corresponding to a depth of 30 with 600 parameters, achieves a low error but it takes a longer-time to converge. Figure 2: We compare the performance of different approaches. The green curve represents QMINE with the exact rank, which exhibited the best performance. It converges rapidly with low error. However, the red curve represents QMINE with a lower rank, which converges with a high error. Finally, the blue curve represents QMINE with a higher rank, which converges with low error but at a slower pace. qubits. For each tested random density matrix, we achieved error rates ranging from \(0.1\%\) to \(1\%\). Additional details can be found in Appendix VII.2. ## VI Conclusions We have addressed the quantum Donsker-Varadhan representation, which is a mathematical framework for estimating von Neumann entropy. The QDVR allows us to find the optimal \(T\) by searching only within the density matrices, resulting in low copy complexity for calculations. By optimizing the quantum neural network using QDVR and the parameter shift rule, we can estimate von Neumann entropy and subsequently estimate the quantum mutual information. The number of copies of \(\rho\) required is approximately \(O\left(\frac{\tau^{2}}{\varepsilon^{2}}\left(n^{2}+\log^{2}\left(\frac{1}{ \varepsilon}\right)\right)n_{\text{params}}\cdot n_{\text{train}}\right)\). Through the numerical simulations, we demonstrated that the quantum mutual information neural estimation (QMINE) performs well, and it aligns with the results of quantum Donsker-Varadhan representation. The rank analysis supported the results of QDVR, whereas the circuit depth analysis emphasized the importance of selecting an appropriate circuit depth. In addition, we estimated the quantum mutual information and achieved a low error rate. The key finding of this study is the conversion of the quantum mutual information and von Neumann entropy estimation problem into a quantum neural network problem. In the future, we suggest investigating the specifics of \(n_{\text{params}}\) and \(n_{\text{train}}\) pertaining to the quantum neural network problem. This will be explored in future studies. ###### Acknowledgements. This work was supported by the National Research Foundation of Korea (NRF) through grants funded by the Ministry of Science and ICT (NRF-2022M3H3A1098237) and the Ministry of Education (NRF-2021R1I1A1A01042199). This work was partially supported by an Institute for Information & Communications Technology Promotion (IITP) grant funded by the Korean government (MSIP) (No. 2019-0-00003; Research and Development of Core Technologies for Programming, Running, Implementing, and Validating of Fault-Tolerant Quantum Computing Systems). ## VII Appendix Here, we provide an explicit proof of Lemma 2 and details of the numerical simulation results. ### Proof of Lemma 3 For given \(\rho=\sum_{i=1}^{r}p_{i}|\psi_{i}\rangle\!\langle\psi_{i}|\), let us define \(T_{0}=\sum_{i=1}^{r}t_{i}|\psi_{i}\rangle\!\langle\psi_{i}|\) with \(t_{i}=\begin{cases}\log(\frac{p_{i}}{k}),&\text{if }\ p_{i}\geq k;\\ 0,&\text{if }\ p_{i}<k\end{cases}\) and \(k=\frac{\varepsilon}{d^{2}}\). Then, the bound on the value of \(|S\left(\rho\right)-f\left(T_{0}\right)|\) can be derived as: \[\left|S\left(\rho\right)-f\left(T_{0}\right)\right| =\left|S\left(\rho\right)+\mathrm{Tr}\left(\rho T_{0}\right)- \log\left(\mathrm{Tr}(e^{T_{0}})\right)\right|\] \[=\left|\sum_{i=1}^{r}p_{i}\log\left(\frac{1}{p_{i}}\right)+\sum_{ p_{i}\geq k}p_{i}\log\left(\frac{p_{i}}{k}\right)-\log\left(\sum_{p_{i}<k}1+ \sum_{p_{i}\geq k}\frac{p_{i}}{k}\right)\right|\] \[=\left|\sum_{p_{i}<k}p_{i}\log\left(\frac{1}{p_{i}}\right)+\sum_{ p_{i}\geq k}p_{i}\log\left(\frac{1}{k}\right)-\log\left(\sum_{p_{i}<k}1+ \sum_{p_{i}\geq k}\frac{p_{i}}{k}\right)\right|\] \[=\left|\sum_{p_{i}<k}p_{i}\log\left(\frac{1}{p_{i}}\right)+\sum_{ p_{i}\geq k}p_{i}\log\left(\frac{1}{k}\right)-\log\left(\frac{1}{k}\right)+\log \left(\frac{1}{k}\right)-\log\left(\sum_{p_{i}<k}1+\sum_{p_{i}\geq k}\frac{p _{i}}{k}\right)\right|\] \[=\left|\sum_{p_{i}<k}p_{i}\log\left(\frac{k}{p_{i}}\right)-\log \left(\sum_{p_{i}<k}k+\sum_{p_{i}\geq k}p_{i}\right)\right|\] \[=\left|\sum_{p_{i}<k}p_{i}\log\left(\frac{1}{p_{i}}\right)+\sum_{ p_{i}<k}p_{i}\log\left(\frac{1}{k}\right)+\log\left(1+\sum_{p_{i}<k}\left(k-p_{i} \right)\right)\right|\] \[\leq 2dk\log\left(\frac{1}{k}\right)+dk=\frac{2\varepsilon^{2} \left(2\log d+\log\left(\frac{1}{\varepsilon}\right)\right)}{d}+\frac{ \varepsilon}{d}\] \[<\varepsilon.\] That is, \(\left|S(\rho)-f(T_{0})\right|<\varepsilon\). Finally, \(\mathrm{Tr}\left(T_{0}\right)\) is estimated as \[\mathrm{Tr}\left(T_{0}\right) =\sum_{p_{i}\geq k}\log\left(\frac{p_{i}}{k}\right)\leq\sum_{p_{i} \geq k}\log\left(\frac{1}{k}\right)\] \[\leq r\log\left(\frac{1}{k}\right)=2r\log d+r\log\left(\frac{1}{ \varepsilon}\right)\] \[=2rn+r\log\left(\frac{1}{\varepsilon}\right).\] Figure 4: Estimation result of the quantum mutual information of a random density matrix This implies that there exists a positive Hermitian matrix \(T_{0}\) such that \(\mathrm{Tr}(T_{0})=O(rn+r\log\left(\frac{1}{\varepsilon}\right))\) and \(\left|S\left(\rho\right)-f\left(T_{0}\right)\right|<\varepsilon\). \(\square\) ### Details on Numerical Simulations To support our observations, we explain the details of the numerical simulations for estimating the quantum mutual information, which can be expressed as the sum of von Neumann entropies as follows: \[I\left(A:B\right) =S(\rho^{A})+S(\rho^{B})-S(\rho^{AB})\] \[=S\left(\rho^{A}\otimes\rho^{B}\right)-S(\rho^{AB}).\] To obtain quantum mutual information, we adopted an alternative and simple strategy. By exploiting QMINE (suggested in Sec. IV), we directly estimate \(S(\rho^{A}\otimes\rho^{B})\) and \(S(\rho^{AB})\). That is, we address \(S(\rho^{A}\otimes\rho^{B})\) rather than estimating \(S(\rho^{A})\) or \(S(\rho^{B})\). This method reduces the number of resource copies required for simulations. We used four-qubit for this simulation and the results of our experiment are summarized in Table 1. To show that QMINE can estimate the quantum mutual information for various density matrices, we present the results of the estimation, where the rank of \(\rho_{AB}\) is different.
2304.12829
Improving Robustness Against Adversarial Attacks with Deeply Quantized Neural Networks
Reducing the memory footprint of Machine Learning (ML) models, particularly Deep Neural Networks (DNNs), is essential to enable their deployment into resource-constrained tiny devices. However, a disadvantage of DNN models is their vulnerability to adversarial attacks, as they can be fooled by adding slight perturbations to the inputs. Therefore, the challenge is how to create accurate, robust, and tiny DNN models deployable on resource-constrained embedded devices. This paper reports the results of devising a tiny DNN model, robust to adversarial black and white box attacks, trained with an automatic quantizationaware training framework, i.e. QKeras, with deep quantization loss accounted in the learning loop, thereby making the designed DNNs more accurate for deployment on tiny devices. We investigated how QKeras and an adversarial robustness technique, Jacobian Regularization (JR), can provide a co-optimization strategy by exploiting the DNN topology and the per layer JR approach to produce robust yet tiny deeply quantized DNN models. As a result, a new DNN model implementing this cooptimization strategy was conceived, developed and tested on three datasets containing both images and audio inputs, as well as compared its performance with existing benchmarks against various white-box and black-box attacks. Experimental results demonstrated that on average our proposed DNN model resulted in 8.3% and 79.5% higher accuracy than MLCommons/Tiny benchmarks in the presence of white-box and black-box attacks on the CIFAR-10 image dataset and a subset of the Google Speech Commands audio dataset respectively. It was also 6.5% more accurate for black-box attacks on the SVHN image dataset.
Ferheen Ayaz, Idris Zakariyya, José Cano, Sye Loong Keoh, Jeremy Singer, Danilo Pau, Mounia Kharbouche-Harrari
2023-04-25T13:56:35Z
http://arxiv.org/abs/2304.12829v1
# Improving Robustness Against Adversarial Attacks with Deeply Quantized Neural Networks ###### Abstract Reducing the memory footprint of Machine Learning (ML) models, particularly Deep Neural Networks (DNNs), is essential to enable their deployment into resource-constrained tiny devices. However, a disadvantage of DNN models is their vulnerability to adversarial attacks, as they can be fooled by adding slight perturbations to the inputs. Therefore, the challenge is how to create accurate, robust, and tiny DNN models deployable on resource-constrained embedded devices. This paper reports the results of devising a tiny DNN model, robust to adversarial black and white box attacks, trained with an automatic quantization-aware training framework, i.e. QKeras, with deep quantization loss accounted in the learning loop, thereby making the designed DNNs more accurate for deployment on tiny devices. We investigated how QKeras and an adversarial robustness technique, Jacobian Regularization (JR), can provide a co-optimization strategy by exploiting the DNN topology and the per layer **JR** approach to produce robust yet tiny deeply quantized DNN models. As a result, a new DNN model implementing this co-optimization strategy was conceived, developed and tested on three datasets containing both images and audio inputs, as well as compared its performance with existing benchmarks against various white-box and black-box attacks. Experimental results demonstrated that on average our proposed DNN model resulted in 8.3% and 79.5% higher accuracy than MLCommons/Tiny benchmarks in the presence of white-box and black-box attacks on the CIFAR-10 image dataset and a subset of the Google Speech Commands audio dataset respectively. It was also 6.5% more accurate for black-box attacks on the SVHN image dataset. Deep Neural Networks (DNNs), QKeras, Jacobian Regularization (JR), Adversarial Attacks. ## I Introduction Deep Neural Networks (DNNs) demonstrate remarkable performance in various tasks such as natural language processing, cybersecurity, computer vision, intelligent applications and many more [1]. However, DNN models are resource intensive with large memory footprint and computational requirements. Moreover, the increasing requirements of edge intelligence have given rise to new optimization strategies in Machine Learning (ML) which strive to reach optimal accuracy while shrinking the DNN model architectures at the same time [2]. The specific sub-discipline of ML that generates constrained ML workloads to be deployed on a target edge device, such as Microcontroller Units (MCUs) and sensors, is called Deeply Quantized Machine Learning (DQML). However, DNN models are often vulnerable to adversarial attacks causing changes to the input imperceptible to the human eye [3]. These vulnerabilities are critical, as they restrict the deployability of DNN models as an effective solution for real world applications such as autonomous cars, smart cities, intelligent applications and responsive Artificial Intelligence (AI) [4]. Two widely used classes of adversarial attacks are _white-box_ and _black-box_ attacks. In white-box, the attacker has full knowledge of the DNN model, its structure and parameters, whereas in the black-box paradigm, the attacker is unaware of the used DNN model. In both scenarios, these attacks aim to cause deliberate mis-classifications or to disrupt the model performance. As such, there is an urgent need of balancing the trade-off between reducing the memory footprint of DNN models for tiny embedded devices while making them robust against adversarial attacks. DQML offers a promise in terms on executing very low bit depth ML models on resource-constrained MCUs with \(\mu\)W power and a memory of only a few MBytes [5]. Various frameworks such as TensorFlow Lite (TFLite) [6] for post-training optimization and Larq [7], Brevitas [8] and QKeras [9] for deep quantization-aware training, are used to optimize ML models resources. Most of these frameworks use quantization to optimize the utilized ML models based on data precision. QKeras is designed to offer quantization as low as a single-bit, and at the same time retaining the model accuracy through introducing quantization error in the form of random noise and learning to overcome it during training [10]. It is based on drop-in replacement functions for Keras, thus providing the freedom to add a quantizer and choose quantization bit-depth separately for activations, biases and weights per layer. This is useful for efficient training of quantized DNN models. Among various deep quantization strategies offered by QKeras, there is stochastic quantization [11], which instead of quantizing all elements (parameters) of a DNN model, quantizes a portion of the elements with a stochastic probability inversely proportional to the quantization error, while keeping the other portion unchanged in full-precision (FP). The quantized portion is gradually increased at each iteration until potentially the entire DNN is quantized. This procedure greatly and incrementally compensates the quantization error and thus yields better accuracy for very low-bit-depth DNN. In parallel, exploring the robustness of DNN models is critical to be integrated within DQML. In fact, enhancing the security while enabling the model's deployment in resource-constrained MCUs is a key challenge. Various defensive techniques and models for DNNs are present in the literature to provide robustness against adversarial attacks [12]. However, such defensive mechanisms may result in an increased model size or accuracy drop for clean sets. Considering DQML models, which require extensive learning computation to reach optimal size and accuracy, with possible vulnerability to adversarial attacks, any addition to the model size or drop in accuracy can affect the deployment performance. In view of that, recent studies [13, 14] have demonstrated that quantization can reduce computational requirements while granting robustness to a certain level of white-box adversarial attacks. Motivated by such an observation, this paper investigates the following hypothesis: _Can a per-layer hybrid quantization scheme inherit robustness against white-box and black-box attacks while maintaining the trade-off between clean set accuracy performance and limited-resources requirements of tiny embedded devices?_ We propose a DQML model that is deployable on tiny devices and highly robust to adversarial attacks, trained using the QKeras framework. Our theoretical investigation shows that QKeras utilizes Jacobian Regularization (JR) as an adversarial attack defensive mechanism. Based on this, we use QKeras to propose a Stochastic Ternary Quantized (STQ) DNN model with accuracy performance suitable for deployment in tiny MCUs, and potentially for image and audio in the same sensor package embodiment. Its ability to provide robustness against various adversarial attacks has been proven. The contributions of this paper are as follows: * Development of an STQ-based model that is less complex and can be deployed on MCUs with minimal memory footprint requirements and an improved accuracy performance on clean sets (Section III). * Analysis of the robustness of the STQ-based model according to its similarity with the JR technique, and demonstration of its resilience against various white and black box adversarial attacks (Sections III and IV). * A comprehensive comparison of the resilience of the STQ-based model to industry endorsed MLCommons/Tiny benchmarks for both image and audio inputs while investigating its performance with \(K\)-fold cross validation (Section IV). ## II Background and Related Work ### _Adversarial Attacks Against Machine Learning Models_ Security considerations are important for sensitive applications like intelligent transportation systems, healthcare and financial systems which utilize image and voice recognition AI-based models [15]. A disadvantage of ML and AI models developed for such tasks is that they can be vulnerable to attacks which can compromise their integrity, confidentiality and privacy in real world applications. In particular, adversarial attacks involve adding a small perturbation to the input to maximize the loss function of a model under a constrainted norm [16]. Equation (1) expresses such a procedure of introducing a perturbation into an input data, where: \(\mathcal{L}(\theta,x^{\prime},y)\) is the loss function, \(\theta\) denotes the model parameters, \(x^{\prime}\) is the perturbed input, \(y\) is the model output, \(\delta\) denotes the perturbation and \(p\) is the perturbation norm [17]. This work considers the two types of attacks defined in Section I, i.e. white-box and black-box attacks. A common adversarial attack technique is the Fast Gradient Sign Method (FGSM) [18]. This is a white-box attack which uses a single-step iteration to estimate the gradient of the model training loss function based on the inputs. An FGSM [18] attack procedure is expressed in (2), where \(\Delta\) represents the gradient and \(\epsilon\) denotes a small constant value that restricts the perturbation. A variation of FGSM is the Projected Gradient Descent (PGD) [18]. This is a more computationally expensive multi-step threat model which runs several iterations to find an adversarial input with the lowest possible \(\delta\), as expressed in (3), where \(i\) is the iteration index, \(\alpha\) denotes the gradient step size and \(S\) represents the perturbation set. \[\max_{||\delta||_{p}}\mathcal{L}(\theta,x^{\prime},y) \tag{1}\] \[x^{\prime}=x+\epsilon\cdot sign(\Delta_{x}\mathcal{L}(\theta,x,y)) \tag{2}\] \[x^{\prime}_{i+1}=\prod_{x+S}(x+\alpha\cdot sign(\Delta_{x}\mathcal{L}(\theta, x,y))) \tag{3}\] An efficient black-box attack is the Square attack [19], which is based on a random search optimization technique with multiple iterations. In each iteration, it changes a small fraction of the input shaped into square at random positions. Similar to gradient-based optimizations, it also relies on step-size reduction, where the size refers to the dimensions of the square [19]. Another form of black-box attack is the Boundary attack [20], where the queries are used to estimate the decision boundaries of the output classes. Starting with a clean image, gradient estimation is performed with queries, moving along the estimated direction in each iteration and projecting a new perturbation until the model decision is changed [20]. Overcoming the white-box and black-box attack methods requires a suitable defensive mechanism. Therefore, it is important to enhance the model performance against different attacks variations to ease its deployment. ### _Robustness against Adversarial Attacks_ Various defense methods have been proposed to increase the robustness of DNNs against adversarial attacks [21]. Some strategies aim at detecting adversarial inputs [22] or performing transformations to remove perturbations [23][24] through an additional network or module. Adversarial training introduces adversarial inputs during the model's learning so that it learns not to misinterpret them [25]. However, these approaches do not guarantee robustness against attacks which are not introduced to the model during training, as they are not learned by the model. Other methods such as [26] decrease the model's sensitivity to small perturbations by adding a regularization term in the loss function. Equation (4) expresses this joint loss function, where \(\mathcal{L}_{reg}\) denotes the regularization term and \(\lambda\) is a hyper-parameter used to allow the adjustment between the regularization and the actual loss. \[\mathcal{L}_{joint}=\mathcal{L}(\theta,x,y)+\lambda L_{reg}, \tag{4}\] ### _Jacobian Regularization_ Jacobian Regularization (JR) is a technique to provide adversarial robustness, where the input gradient regularization normalizes the gradient of the cross-entropy loss, such that \(\mathcal{L}_{reg}=\sum_{k=1}^{K}||\Delta_{x}z_{k}^{L}(x_{i})||_{2}^{2}=||J( \mathbf{x}_{i})||_{F}^{2}\) and \(||J(\mathbf{x}_{i})||_{F}^{2}\) is the Frobenius norm of the model's Jacobian matrix evaluated on the input data [27]. To reduce computational complexity, per-layer JR is proposed in [28]. To demonstrate the robustness of per-layer JR, let's consider a \(D\)-dimensional network input \(X\) consisting of \(N\) training samples. As shown in Figure 1, the network contains \(l=1,2,...,L\) layers. \(z_{l}\) denotes the output at layer \(l\) and \(z_{l}^{k}\) is the output of the \(k^{th}\) neuron of the \(l^{th}\) layer. Consider the softmax operation at the output of the network; the predicted final output for computing the top-1 accuracy for an input \(x_{i}\) is \(f(x_{i})=argmax\{z_{L}^{1},z_{L}^{2},..,z_{L}^{K}\}\), where \(K\) is the dimension of the output vector. The Jacobian matrix of a DNN is computed at \(L^{th}\) layer, i.e. \(J_{L}(x_{i})=\nabla_{x}z_{L}(x_{i})\), and is defined as: \[J_{L}(x_{i})=\begin{bmatrix}\frac{\partial z_{1}^{1}x_{1}}{ \partial z_{1}}&\frac{\partial z_{1}^{1}x_{1}}{\partial z_{2}}&...&\frac{ \partial z_{1}^{1}x_{1}}{\partial x_{D}}\\ \frac{\partial z_{1}^{1}x_{2}}{\partial x_{1}}&\frac{\partial z_{1}^{1}x_{2}}{ \partial x_{2}}&...&\frac{\partial z_{1}^{1}x_{2}}{\partial x_{D}}\\.&.&.&.\\ \frac{\partial z_{1}^{K}x_{2}}{\partial x_{1}}&\frac{\partial z_{1}^{K}x_{2K}}{ \partial x_{2}}&...&\frac{\partial z_{K}^{K}x_{K}}{\partial x_{D}}\\ \end{bmatrix}\epsilon\mathbb{R}^{K\times D}. \tag{5}\] In [27], the JR can form for an input \(x_{i}\) is defined as \[||J(x_{i})||_{F}^{2}=\sum_{d=1}^{D}\sum_{k=1}^{K}\Big{(}\frac{ \partial}{\partial x_{d}}z_{L}^{k}(x_{i})\Big{)}^{2}=\sum_{k=1}^{K}||\nabla_{ x}z_{L}^{k}(x_{i})||_{2}^{2}, \tag{6}\] The standard loss of the training is added with the regularization term in (6) to improve the robustness of the DNN. It is proposed as a post-training, in which the network is re-trained for fewer iterations with the new loss function [27]. As \(i\epsilon\{1,2,...,N\}\), JR requires the computation of \(N\) gradients, whereas in per-layer JR, the Jacobian matrix is computed on only one random \(i\) at each layer [28]. The basic idea is to reduce the Frobenius norm of the Jacobian matrix which results in the expansion of the classification margin, i.e. the distance between an input and the decision boundary induced by a network classifier. ### _Adversarial Robustness of Quantized Models_ Model quantization techniques are widely used in various fields [29]. In [30], it is used for anomaly detection and thwarting cyber attacks in Internet-of-Things (IoT) networks. However, the limitation of a quantized model is the shift of the FP model classification boundary, which may influence how vulnerable the model is to adversarial perturbations [31]. As such, the authors in [31] investigated the use of a boundary-based retraining method to reduce adversarial and quantization losses with the usage of non-linear mapping as a defensive mechanism against white-box adversarial attacks. Other previous studies explored the impact of perturbations on different models. Table I compares some existing works that investigated the robustness of quantized DNN models. These studies investigated the resilience of quantized DNN models without examining their deployment feasibility on resource-constrained devices, such as MCUs or sensors, and most of them considered only white-box attacks. ## III Proposed DNN model This section introduces a new robust and less complex DNN model based on the Stochastic Ternary Quantization (STQ) approach which is conceived to be deployable on tiny MCUs. ### _Adversarial Robustness in QKeras_ QKeras [9] is a DNN framework targeting quantization based on Keras [36], which provides a productive methodology to build and train quantized neural networks, either fractional or integer spanning from 1 to 32 bits. QKeras performs quantization aware training [37]. The background algorithm to train neural networks with \(q\) bit-width weights, activations and gradient parameters is conceptualized in [38]. In particular, the network training in QKeras includes a backward propagation where parameter gradients are stochastically quantized into low bit-width numbers. Figure 2 shows the process flow of training each layer in QKeras. Each training iteration involves a forward propagation step to quantize weights, find output and add quantization error into the output of each layer. Then it includes a backward propagation step where gradients are stochastically quantized into low bit-width numbers. Finally, unquantized weights and gradients are updated for the next iteration. The training process of deeply quantized networks, through QKeras, make them robust to adversarial attacks due Fig. 1: Transformation of input \(x_{i}\) into output \(z_{L}\) by DNN. to the two following reasons: i) a noise function is introduced during quantization of gradients to overcome quantization error during training, which makes a DNN robust to noise and perturbation effect; ii) QKeras involves JR features that are explained below. **Theorem:**_QKeras introduces per-layer JR and therefore increases the robustness of DNNs against adversarial attacks._ **Proof:** Considering the per-layer structure of DNNs, as shown in Figure 1, the output \(z_{L}\) at the last layer \(L\) is \[z_{L}=\phi_{L}((\phi_{L-1}(...\phi_{1}(x_{i},\theta_{1}),...\theta_{L-1}), \theta_{L})), \tag{7}\] where \(\phi_{l}(.,\theta_{l})\) represents the function of the \(l^{th}\) layer, \(\theta_{l}\) denotes the model parameters at layer \(l\), and \(z_{0}=x_{i}\)[28]. The Jacobian matrix of the \(l^{th}\) layer is defined as \[J_{l}(z_{l-1})=\frac{dz_{l}}{dz_{l-1}}, \tag{8}\] which is back-propagated during QKeras training (Step 10-16 of Algorithm 1 in [38]). The derivation expressed in (8) is the Jacobian matrix [28] of the \(l^{th}\) block layers. Thus, QKeras with such patterns incorporates per-layer JR during training. To prove that per-layer JR enhances adversarial robustness, consider a clean input \(x_{c}\) and an adversarial input \(x_{p}\), both close to an input \(x_{i}\) and all belonging to the same class \(k\). Since \(f(x_{i})=f(x_{c})\neq f(x_{p})\), then the \(\ell_{2}\) distance metric of the input and output of the network, as defined in [27], is \[\frac{||x_{p}-x_{i}||_{2}}{||x_{c}-x_{i}||_{2}}\approx 1, \tag{9}\] \[\frac{||z_{L}(x_{p})-z_{L}(x_{i})||_{2}}{||z_{L}(x_{c})-z_{L}(x_{i})||_{2}}>1, \tag{10}\] Combining (9) and (10) and using the Mean Value Theorem [39], it is justified that a lower Frobenius norm makes a network less sensitive to perturbations, i.e., \[\frac{||z_{L}(x_{p})-z_{L}(x_{i})||_{2}^{2}}{||x_{p}-x_{i}||_{2}^{2}}\leq||J(x ^{\prime})||_{F}^{2}, \tag{11}\] where \(x^{\prime}\epsilon[x_{i},x_{p}]\). Similar to (10), for each layer \(l\), we have \[\frac{||z_{l}(x_{p})-z_{l}(x_{i})||_{2}}{||x_{l}(x_{c})-z_{l}(x_{i})||_{2}}>1. \tag{12}\] The misclassification error is propagated at each layer, thus \[\frac{||z_{l}(z_{l-1}(x_{p}))-z_{l}(z_{l-1}(x_{i}))||_{2}}{||z_{l}(z_{l-1}(x_ {c}))-z_{l}(z_{l-1}(x_{i}))||_{2}}>1. \tag{13}\] This error is back-propagated and then adjusted at each layer. Therefore the learning optimization process increases robustness of a DNN model trained by QKeras since it discriminates the error due to the clean versus the perturbed input. Consequently, it can be concluded that QKeras deep quantization-aware process introduces per-layer JR with respect to the previous layer's input that is back propagated, as shown in Figure 2 and Step 11 to 15 of Algorithm 1 in [38]. Although back propagation is intended to quantize parameters, it ultimately results in more robust networks. Its learning process increases the training computation time but its advantage is two-fold, i.e. deep quantization and robustness to adversarial perturbations. ### _Stochastic Ternary Quantized QKeras Architecture_ As the QKeras [37] API serves as an extension of Keras, initially a 32-bit FP DNN model was built with [36]. The FP model consists of six convolutional layers including depth-wise, separable, and three fully connected layers. The former layers are used for capturing channel-wise correlations and can provide more features with less parameters, particularly with image inputs [40]. A multi-branch topology was used with residual connections to refine the feature maps. For better accuracy, batch normalization [41], ReLU [42] and sigmoid [43] activation functions are considered in the hidden layers, while softmax is used in the output layer. The FP model contains 998,824 parameters, of which 997,460 are trainable and 1,364 are non-trainable, as returned by model.summary(). This DNN model is not integrated with JR by default, and is therefore vulnerable to adversarial attacks. However, the model cannot be deployed on tiny MCUs due to its large size (4 MB). Since our target device is the STM32H7, which has a maximal RAM memory of 1 MB, we applied the STQ method to this model using QKeras. Figure 3 shows the architecture of the STQ model visualized using Netwon [44] to render the DNN graph along with its hyperparameters. As we can see, the convolutional, depth-wise, separable layers and activation are appended with \(Q\), which indicates the quantization version of the FP Keras [36] model, while the _quantized_relu_ represents the quantized activation function versions of Keras. The proposed STQ model used the heterogeneous quantization features of QKeras, which supports independent quantization of each layer in the DNN [10]. This is useful in reducing the model memory footprint and complexity with increased performance accuracy. ## IV Evaluation This section describes the evaluation procedure of the proposed STQ model, using image and audio datasets for clean and adversarial samples. Moreover, it compares the top-1 accuracy of our STQ model with other benchmarks for three black-box and three white-box adversarial attacks. Fig. 2: QKeras quantization aware training flow. ### _Experimental Setup_ #### Iv-A1 Datasets and Pre-processing To evaluate the effectiveness of the devised STQ model, the following audio and image benchmark datasets are considered: * **CIFAR-10** consists of 60,000 images belonging to 10 different classes. Each class is divided into 50,000 training images and 10,000 test images [45]. * **Street View House Numbers (SVHN)** is a real-world image dataset obtained from house numbers in Google Street View images. It consists of 10 classes, one for each digit. There are 73,257 and 26,032 digits for training and testing respectively [46]. * **Google Speech Commands (GSC)** consists of 65,000 one-second long utterances of 30 short words by thousands of different people. Its 12 classes comprise words of 'yes', 'no' and digits from 'zero' to 'nine' that were used in the experiment. The number of training and test samples are 31,257 and 15,636 respectively [47]. Note that the input image samples were normalized between 0 and 1 pixel and then converted into gray-scale images before presenting them to the DNN input. This effectively reduced the computational cost of processing the image samples while avoiding the use color which are known to be deceitful. Color processing was out of scope by this work and may be considered in future extensions of it. #### Iv-A2 Model Training Procedure Table II lists the training parameters used to evaluate the full-precision (FP), the proposed STQ and other tested quantized models. A cosine annealing Learning Rate (LR) function [48] was used with the Adamax optimizer for faster convergence. These training parameters were selected to both fine tune each model and reduce its computational complexity, while maintaining better or state-of-the-art performance. Since the proposed STQ model targets images and audio datasets, ResNetv1 and DS-CNN TFLite models were also used and tested for comparison purposes. This is to investigate the robustness of the model against industry adopted MLCommons/Tiny models, which can provide insights into the performance capability of the proposed model across various datasets and other benchmarks. #### Iv-A3 Adversarial Attacks Procedure The proposed STQ model was evaluated against several adversarial attacks to demonstrate its resilience and robustness. Three white-box attacks, FGSM and PGD [18] and Carlini and Wagner (C&W-L2) [49]; and three black-box attacks, Square [19], Boundary attack [20] and Zero Order Optimization (Zoo) [50] were considered. The perturbed data samples for all attacks were generated with the Adversarial Robustness Toolbox (ART) [51] against the tested datasets. For FGSM and PGD samples, an \(\epsilon\) value of 0.6 with an L1 norm was used. For the Square attack, an \(\epsilon\) value of 0.6 with _infinity_ norm was used, while for the Boundary attack, an \(\epsilon\) value of 0.01 with _infinity_ norm was used. The maximum \begin{table} \begin{tabular}{|c|c|} \hline **Parameter** & **Value** \\ \hline Epochs & 1000 \\ \hline Batch Size & 64 \\ \hline Learning Rate & [1 \(\times\)\(10^{-6}\), 1 \(\times\)\(10^{-3}\)] \\ \hline LR Scheduler & Cosine Annealing \\ \hline Loss & Categorical Cross-entropy \\ \hline Optimizer & Adamax \\ \hline \end{tabular} \end{table} TABLE II: Training parameters for QKeras DNN Fig. 3: Proposed architecture of the STQ-based DNN model developed using QKeras. number of iterations used for C&W-L2 and Zoo is 10, and a binary search tree of 10 used for Zoo. The C&W-L2 and Zoo are used with CIFAR-10 data samples. The number of samples used to create the perturbations were 100, 240 and 2400 for CIFAR-10, SVHN and GSC datasets respectively. To further examine the strength of our STQ model against FGSM, PGD [18] and Square [19] attacks, they were crafted under different attack strengths using the 10,000 test samples of CIFAR-10. The FGSM attacks were crafted for \(\epsilon\) ranging in: \(\{0.05,0.1,0.15,0.2,0.25,0.3\}\) as denoted in [14]. Regarding the PGD attack, an iteration \(t=7\) was used along with a step size \(\alpha=2/255\) and an \(\epsilon\) ranging in: \(\{8/255,16/255,32/255\}\). For the Square [19] attacks, the first variation consists of _infinity_ norm, \(\epsilon\) value of 0.05 and maximum iterations of 10,000. The second variation of the square attack uses the \(\ell_{2}\) norm and maximum iterations of 10,000 as denoted in [52]. #### V-A4 \(K\)-fold Cross Validation In order to estimate the variance of the clean and adversarial data samples across each tested model, \(K\)-fold cross validation was used. This technique splits the entire dataset into \(K\) (fold) equal subsets, of which \(K-1\) subsets are used for training and the remaining one subset is used for validation [53]. For each fold, the model is fitted on the training set and predicted on the validation set to estimate the average performance. For implementation purposes, \(K=10\) was considered, because a larger number of folds may increase the predictive performance [54]. In addition, the scikit-learn [55] ML Python API was used. ### _Quantization schemes_ Table III shows the performance (top-1 test accuracy) comparison between different quantized models against the tested datasets using clean inputs from each dataset. In addition, it includes the FLASH MCU memory of each quantized model computed based on the weight profile obtained using the qstats QKeras library. As we can see, the STQ-based model provides the highest accuracy as compared to the FP, Stochastic Binary (S-Binary), and other quantized models. Moreover, this model is lighter than the FP, 8-bit and 4-bit models and can be deployed on MCU devices. These results motivate further investigations on the robustness of the proposed STQ model against adversarial attacks, since the FP model does not have any integrated defensive mechanism, nor better accuracy performance in classifying clean samples. ### _Robustness evaluation against adversarial attacks_ Table IV shows the robustness (top-1 test accuracy) of our STQ model against two white-box attacks (FGSM, PGD) and two black-box attacks (Square, Boundary). The results are compared with two MLCommons/Tiny benchmarks: ResNetv1 for image classifications trained on CIFAR-10 and SVHN datasets; and DS-CNN TFLite for Keyword Spotting trained on GSC dataset [56]. In addition, Figure 4 shows the robustness against another white-box attack (C&W-L2) and a black-box attack (Zoo). The results are compared with ResNetv1 for image classifications trained on the CIFAR-10 dataset. As we can see in Table IV, there is a drop in accuracy for the two MLCommons/Tiny benchmarks against all adversarial attacks, as no defense mechanism is included, which makes STQ with integrated JR an interesting scheme. On average, adversarial attacks have caused an accuracy drop of 15.5%, 3.8% and a massive 74.1% with CIFAR-10, SVHN and GSC datasets respectively. Related to the C&W-L2 and Zoo attacks, we can see in Figure 4 that the average drop of ResNetv1 for the CIFAR-10 dataset is 10.5%. All the previous accuracy drops highlight the importance of robust tiny models. Note that Figure 4 also includes the robustness of our FP model, which is clearly lower than STQ. However, the accuracy of the proposed STQ model was either improved or slightly decreased in the presence of attacks. The largest accuracy drops of 7.0% and 5.6% were observed for the Square and C&W-L2 attacks, respectively, and the CIFAR-10 dataset, although both outperformed the ResNetv1 benchmark. Note that ResNetv1 performs 0.9% better than our STQ model only in the case of FGSM and PGD perturbations for the SVHN dataset. Finally, our model outperforms the DS-CNN model with better accuracy for both clean and adversarial samples of the GSC dataset, for all the experiments. \begin{table} \begin{tabular}{|c|c|c|c|c|c|c|} \hline **Dataset** & **Model** & **Clean** & **FGSM** & **PGD** & **Square** & **Boundary** \\ & & **Ace(\%)** & **Ace(\%)** & **Ace(\%)** & **Ace(\%)** & **Ace(\%)** \\ \hline \multirow{4}{*}{CIFAR-10} & ResNetv1 & 85.0 & 65.6 & 64.1 & 65.5 & 82.9 \\ \cline{2-7} & STQ & 80.6 & **80.8** & **80.8** & **73.6** & **83.8** \\ \cline{2-7} & ResNetv1 & 94.8 & **94.0** & **94.0** & 82.1 & 94.0 \\ \cline{2-7} & STQ & **95.5** & 93.1 & 93.1 & **91.7** & **97.3** \\ \hline \multirow{4}{*}{GSC} & DS-CNN & 89.1 & 15.0 & 15.4 & 15.1 & 14.7 \\ \cline{2-7} & STQ & **94.8** & **94.3** & **94.2** & **94.3** & **95.4** \\ \hline \end{tabular} \end{table} TABLE IV: Models robustness (top-1 test accuracy) comparison for CIFAR-10, SVHN, and GSC datasets. Fig. 4: Models robustness (top-1 test accuracy) comparison against Zoo and C&W-L2 attacks for the CIFAR-10 dataset. \begin{table} \begin{tabular}{|c|c|c|c|c|} \hline **Model** & **Flash** & **CIFAR-10** & **SVHN** & **GSC** \\ & **(KB)** & **Ace. (\%)** & **Ace. (\%)** & **Ace. (\%)** \\ \hline FP & 4496 & 52.73 & 67.94 & 89.50 \\ \hline 8-bit & 1124 & 52.46 & 70.04 & 85.60 \\ \hline 4-bit & 527 & 50.88 & 64.72 & 82.06 \\ \hline Ternary & 410 & 77.35 & 93.11 & 88.30 \\ \hline STQ & 410 & **80.57** & **95.53** & **94.76** \\ \hline 2-bit & 281 & 46.35 & 89.74 & 81.56 \\ \hline Binary & 140 & 39.03 & 56.91 & 77.10 \\ \hline S-Binary & 140 & 52.25 & 63.72 & 82.51 \\ \hline \end{tabular} \end{table} TABLE III: Performance (top-1 accuracy) comparison on CIFAR-10, SVHN and GSC clean datasets. These results demonstrate that the resilience and robustness of the proposed STQ model against several adversarial attacks is better than the MLCommons/Tiny benchmarks tested models. As such, the per-layer JR integration of our STQ model has an advantage of reducing model complexity and in parallel enhancing the robustness of the model, producing an effective performance in comparison with traditional benchmark models. This is an interesting finding when looking at the requirements of MCUs, and other tiny devices that are memory and computational resource-constrained. Table V shows the variance reports of \(K\)-fold cross validation, where \(K=10\). The MLC/T column represents ResNetv1 model for CIFAR-10 and SVHN datasets and DS-CNN model for the GSC dataset. The variance of the benchmark for the STQ model is lower in many samples of CIFAR-10 and all instances of the GSC dataset. For the SVHN, the variance of the ResnetV1 model is lower than that of STQ. Therefore, the \(K\)-fold cross validation results are varying with datasets and types of attacks, although the overall average results demonstrate general consistency of STQ, with categorical cross entropy loss. Particularly for the GSC dataset, at which STQ tends to outperform the MLC/T with both clean and attacks samples. These results demonstrate the performance capability of STQ as a robust and effective model suitable to be deployed into a resource-constrained environment. Finally, Figure 5 shows a comparison between our FP and STQ models against: i) QUANOS [14] baseline model for various FGSM and PGD perturbation strengths; and ii) RND-AT [52] for variations of Square [19] attacks. All attacks used 10,000 testing samples of the CIFAR-10 dataset. As we can see, STQ clearly outperforms QUANOS in detecting FGSM and PGD attacks for various strengths, and is slightly worse than RND-AT for Square attacks. We did not find any previous work for the Boundary attack which we could fairly compare against, and we leave Zoo and C&W-L2 for future work. ## V Conclusion This paper investigated the robustness of a Deeply Quantized Machine Learning (DQML) model against various white-box and black-box adversarial attacks. The deep quantization facilities of QKeras were considered to create a memory optimized, accurate and adversarially robust quantized model. This is due to its similarities with a defense technique, Jacobian Regularization (JR), that was integrated into it. As demonstrated, the proposed Stochastic Ternary Quantized (STQ) model, with quantization-aware training procedure introducing per-layer JR, was more robust than industry adopted MLCommons/Tiny benchmarks when facing several adversarial attacks. In fact, the stochastic quantization scheme was effective for model compression with support for robustness against adversarial attacks. This robustness was experimentally proved by observing its accuracy under various adversarial attacks utilizing two image (CIFAR-10 and SVHN) datasets and one audio (GSC) dataset. This is relevant in the context of deploying efficient and effective models in resource-constrained environments, with limited capabilities. Our initial results suggest further exploration of other sophisticated white-box and black-box attacks with different attack strengths. Future work will further assess the effectiveness of the proposed STQ QKeras model against new and latest attacks. ## Acknowledgment This work has been supported by the PETRAS National Centre of Excellence for IoT Systems Cybersecurity, funded by the UK EPSRC under grant number EP/S035362/1. \begin{table} \begin{tabular}{|c|c|c|c|} \hline **Dataset** & **Procedure** & **STQ** & **MLC/T** \\ \hline \multirow{8}{*}{CIFAR-10} & No Attack & **3.04** & 26.25 \\ \cline{2-4} & FGSM & **5.81** & 6.01 \\ \cline{2-4} & PGD & 3.7 & 3.35 \\ \cline{2-4} & Square & **11.78** & 15.58 \\ \cline{2-4} & Boundary & **1.4** & 5.69 \\ \hline \multirow{8}{*}{SVHN} & No Attack & 0.19 & 0.1 \\ \cline{2-4} & FGSM & 4.27 & 1.99 \\ \cline{2-4} & PGD & 1.64 & 1.40 \\ \cline{2-4} & Square & **4.2** & 5.36 \\ \cline{2-4} & Boundary & **0.39** & 0.45 \\ \hline \multirow{8}{*}{GSC} & No Attack & **0.37** & 0.80 \\ \cline{2-4} & FGSM & **1.57** & 4.45 \\ \cline{1-1} \cline{2-4} & PGD & **3.17** & 5.45 \\ \cline{1-1} \cline{2-4} & Square & **2.96** & 3.64 \\ \cline{1-1} \cline{2-4} & Boundary & **0.24** & 0.34 \\ \hline \multirow{8}{*}{GSC} & Average & **2.98** & 5.39 \\ \cline{1-1} \cline{2-4} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} \\ \end{tabular} \end{table} TABLE V: Variance as a result of \(K\)-fold cross validation. Fig. 5: Robustness comparison of our FP and STQ models against Quanos [14] and RND-AT [52] for various FGSM and PGD perturbation strengths and variations of Square attacks.
2302.01503
LazyGNN: Large-Scale Graph Neural Networks via Lazy Propagation
Recent works have demonstrated the benefits of capturing long-distance dependency in graphs by deeper graph neural networks (GNNs). But deeper GNNs suffer from the long-lasting scalability challenge due to the neighborhood explosion problem in large-scale graphs. In this work, we propose to capture long-distance dependency in graphs by shallower models instead of deeper models, which leads to a much more efficient model, LazyGNN, for graph representation learning. Moreover, we demonstrate that LazyGNN is compatible with existing scalable approaches (such as sampling methods) for further accelerations through the development of mini-batch LazyGNN. Comprehensive experiments demonstrate its superior prediction performance and scalability on large-scale benchmarks. The implementation of LazyGNN is available at https://github.com/RXPHD/Lazy_GNN.
Rui Xue, Haoyu Han, MohamadAli Torkamani, Jian Pei, Xiaorui Liu
2023-02-03T02:33:07Z
http://arxiv.org/abs/2302.01503v2
# LazyGNN: Large-Scale Graph Neural Networks via Lazy Propagation ###### Abstract Recent works have demonstrated the benefits of capturing long-distance dependency in graphs by deeper graph neural networks (GNNs). But deeper GNNs suffer from the long-lasting scalability challenge due to the neighborhood explosion problem in large-scale graphs. In this work, we propose to capture long-distance dependency in graphs by shallower models instead of deeper models, which leads to a much more efficient model, LazyGNN, for graph representation learning. Moreover, we demonstrate that LazyGNN is compatible with existing scalable approaches (such as sampling methods) for further accelerations through the development of mini-batch LazyGNN. Comprehensive experiments demonstrate its superior prediction performance and scalability on large-scale benchmarks. LazyGNN also achieves state-of-art performance on the OGB leaderboard. Machine Learning, ICML ## 1 Introduction Graph neural networks (GNNs) have been widely used for representation learning on graph-structured data (Hamilton, 2020; Ma and Tang, 2021), and they achieve promising state-of-the-art performance on various general graph learning tasks, such as node classification, link prediction, and graph classification (Kipf and Welling, 2016; Gasteiger et al., 2019; Velickovic et al., 2017; Wu et al., 2019) as well as a variety of important applications, such as recommendation systems, social network analysis, and transportation prediction. In particular, recent research in deeper GNNs has generally revealed the performance gains from capturing long-distance relations in graphs by stacking more graph convolution layers or unrolling various fixed point iterations (Gasteiger et al., 2018; Gu et al., 2020; Liu et al., 2020; Chen et al., 2020; Li et al., 2021; Ma et al., 2020; Pan et al., 2020; Zhu et al., 2021; Chen et al., 2020). However, the recursive feature propagations in deeper GNNs lead to the well-known neighborhood explosion problem since the number of neighbors grows exponentially with the number of feature propagation layers (Hamilton et al., 2017; Chen et al., 2018). This causes tremendous scalability challenges for data sampling, computation, memory, parallelism, and end-to-end training when employing GNNs on large-scale graphs. It greatly limits GNNs' broad applications in large-scale industry-level applications due to limited computation and memory resources (Ying et al., 2018; Shao et al., 2022). A large body of existing research focuses on improving the scalability and efficiency of large-scale GNNs using various innovative designs, such as sampling methods, pre-computing or post-computing methods, and distributed methods. Although these approaches mitigate the neighborhood explosion problem, they still face various limitations when they are applied to deeper GNNs. For instance, sampling approaches (Hamilton et al., 2017; Chen et al., 2018; Zeng et al., 2020; Zou et al., 2019; Fey et al., 2021; Yu et al., 2022) usually incur large approximation errors and suffer from performance degradation as demonstrated in large-scale OGB benchmarks or require large additional memory or storage space to store activation values in hidden layers. Pre-computing or post-computing methods (Wu et al., 2019; Rossi et al., 2020; Sun et al., 2021; Zhang et al., 2022; Bojchevski et al., 2020; Zhu, 2005; Huang et al., 2020) lose the benefits of end-to-end training and usually suffer from performance loss. Distributed methods (Chiang et al., 2019; Chai et al., 2022; Shao et al., 2022) distribute large graphs to multiple servers for parallel training, but they either lose the inter-server edges or suffer from expensive feature communication between servers. In this work, we take a substantially different and novel perspective and propose to capture long-distance dependency in graphs by shallower GNNs instead of deeper GNNs. The key intuition comes from the fact that node information has been propagated over the graph many times during the training process so we may only need to propagate information lazily by reusing the propagated information over the training iterations. This intuition leads to the proposed LazyGNN that solves the inherent neighborhood explosion problem by significantly reducing the number of aggregation layers while still capturing long-distance dependency in graphs through lazy propagation. Multiple technical challenges such as the risk of over-smoothing, additional variation due to feature dropout, and back-propagation through historical computation graphs are carefully dealt with by innovative designs in LazyGNN. Moreover, since LazyGNN is a shallow model, it naturally tackles the limitations that existing scalable approaches suffer from when handling large-scale and deeper GNNs. Therefore, various scalable approaches can be used in LazyGNN for further acceleration. We demonstrate this by developing a highly scalable and efficient mini-batch LazyGNN based on sampling methods. To the best of our knowledge, LazyGNN is the first GNN model being versatilely friendly to data sampling, computation, memory space, parallelism, and end-to-end training but still captures long-distance dependency in graphs. Our contributions can be summarized as follows: * We reveal a novel perspective to solve the neighborhood explosion problem by exploiting the computation redundancy in training GNNs; * A novel shallow model, LazyGNN, is proposed to capture long-distance dependency in graphs for end-to-end graph representation learning through lazy forward and backward propagations; * We demonstrate that existing scalable approaches can be compatible with LazyGNN by introducing a highly efficient and scalable mini-batch LazyGNN to handle large-scale graphs based on sampling methods. * Comprehensive experiments demonstrate superior prediction performance and efficiency on large-scale graph datasets. Notably, the proposed LazyGNN also achieves the best performance on OGB leaderboard. ## 2 Preliminaries **Notations.** A graph is represented by \(\mathcal{G}=(\mathcal{V},\mathcal{E})\) where \(\mathcal{V}=\{v_{1},\ldots,v_{N}\}\) is the set of nodes and \(\mathcal{E}=\{e_{1},\ldots,e_{M}\}\) is the set of edges. Suppose that each node is associated with a \(d\)-dimensional feature vector, and the original features for all nodes are denoted as \(\mathbf{X}_{\text{fea}}\in\mathbb{R}^{N\times d}\). The graph structure of \(\mathcal{G}\) can be represented by an adjacency matrix \(\mathbf{A}\in\mathbb{R}^{N\times N}\), where \(\mathbf{A}_{ij}>0\) when there exists an edge between node \(v_{i}\) and \(v_{j}\), otherwise \(\mathbf{A}_{i,j}=0\). The symmetrically normalized graph Laplacian matrix is defined as \(\tilde{\mathbf{L}}=\mathbf{I}-\tilde{\mathbf{A}}\) with \(\tilde{\mathbf{A}}=\mathbf{D}^{-1/2}\mathbf{A}\mathbf{D}^{-1/2}\) where \(\mathbf{D}\) is the degree matrix. Next, we briefly introduce the graph signal denoising and fixed point iteration perspective of GNNs that provide a better understanding of the computation trajectory and long-distance dependency in graphs. Finally, we provide a preliminary study to reveal the computation redundancy in GNNs. ### GNNs as Graph Signal Denoising It is recently established that many popular GNNs can be uniformly understood as solving graph signal denoising problems with various diffusion properties and that the long-distance dependency can be well captured by unrolling various fixed point iterations (Ma et al., 2020; Pan et al., 2020; Zhu et al., 2021; Chen et al., 2020; Gu et al., 2020). For instance, the message passing in GCN (Kipf and Welling, 2016), \(\mathbf{X}_{\text{out}}=\tilde{\mathbf{A}}\mathbf{X}_{\text{in}}\), can be considered as one gradient descent iteration for minimizing \(\operatorname{tr}(\mathbf{X}^{\top}(\mathbf{I}-\tilde{\mathbf{A}})\mathbf{X})\) with the initialization \(\mathbf{X}_{0}=\mathbf{X}_{\text{in}}\). The message passing scheme in APPNP (Klicpera et al., 2018) follows the aggregation \(\mathbf{X}_{l+1}=(1-\alpha)\tilde{\mathbf{A}}\mathbf{X}_{l}+\alpha\mathbf{X}_ {\text{in}}\) that iteratively minimizes \(\|\mathbf{X}-\mathbf{X}_{\text{in}}\|_{F}^{2}+(1/\alpha-1)\,\operatorname{tr }(\mathbf{X}^{\top}(\mathbf{I}-\tilde{\mathbf{A}})\mathbf{X})\) with the initialization \(\mathbf{X}_{0}=\mathbf{X}_{\text{in}}\) where \(l\) is the index of layers. Implicit GNN (Gu et al., 2020) adopts projected gradient descent to solve the fixed point problem \(\mathbf{X}=\phi(\mathbf{W}\mathbf{X}\tilde{\mathbf{A}}+\mathbf{B})\). Please refer to the reference (Ma et al., 2020; Pan et al., 2020; Zhu et al., 2021; Chen et al., 2020) for such understanding of many other popular GNN models. Moreover, a large number of advanced GNN models have been inspired from this perspective (Chen et al., 2022; Liu et al., 2021; Yang et al., 2021; Jia and Benson, 2022; Jiang et al., 2022). ### Computation Redundancy in Training GNNs In the training process of GNNs, the model parameters are updated following gradient descent style algorithms such as Adam (Kingma and Ba, 2014). Therefore, the model as well as hidden features in GNNs changes smoothly, especially in the late stages when both the learning rate and gradient norm diminish. This intuition motivates us to investigate the computation redundancy in GNNs. Specifically, we measure the relative hidden features changes, i.e., \(\|\mathbf{X}^{k+1}-\mathbf{X}^{k}\|_{F}/\|\mathbf{X}^{k}\|_{F}\), over the training iterations on Cora dataset using APPNP. We show two cases in Figure 1: (1) when there is no dropout, the hidden features barely change as the training goes; (2) if we use dropout, it will incur additional variation in the hidden features due to the randomness in dropout layers. Both cases demonstrate that the activation values in hidden layers of GNNs indeed change slowly, indicating the existence of _computation redundancy_: the computation in successive training iterations is highly similar. This observation not only validates the rationality of historical embedding used in existing works such as VRGNN (Chen et al., 2017) and GNNAutoScale (Fey et al., 2021) but also motivates the lazy propagation in this work. ## 3 Lazy Graph Neural Networks In this section, we propose a novel shallow LazyGNN that uses a few aggregation layers to capture long-distance dependency in graphs through lazy forward and backward propagations. Then a mini-batch LazyGNN is introduced to handle large-scale graphs with efficient data sampling, computation, and memory usage. Complexity analyses are also provided to illustrate the superior scalability of LazyGNN. ### GNNs with Lazy Propagation Existing research has demonstrated the benefits of capturing long-distance relations in graphs by stacking more feature aggregation layers or unrolling various fixed point iterations as introduced in Section 1. However, these deeper GNNs are not efficient due to the neighborhood explosion problem. Our preliminary study in Section 2 reveals the computation redundancy in GNNs over the training iterations: the hidden features in GNNs evolve slowly such that the computation of feature aggregations is highly correlated and redundant over training iterations. This observation motivates us to develop a novel shallow LazyGNN that captures long-distance relations in graphs by propagating information lazily with very few message-passing layers. Without loss of generality, we build LazyGNN on the most common graph signal denoising problem: \[\min_{\mathbf{X}}\ \|\mathbf{X}-\mathbf{X}_{\text{in}}\|_{F}^{2}+(1/\alpha-1)\ \mathrm{tr}(\mathbf{X}^{\top}(\mathbf{I}-\tilde{\mathbf{A}})\mathbf{X}), \tag{1}\] where the first term maintains the proximity with node hidden features \(\mathbf{X}_{\text{in}}\) after feature transformation, and the second Laplacian smoothing regularization encodes smoothness assumption on graph representations. We take this as an example to illustrate the main idea of lazy propagation but the idea can be applied to other GNNs inspired by general denoising problems or fixed point iterations with different properties. Next, we illustrate the lazy forward and backward propagations in LazyGNN as well as the technical challenges being solved by innovative designs. **Forward Computation.** From Eq. (1), we derive the high-order graph diffusion as in APPNP (Klicpera et al., 2018) with \(f\) being the feature transformation: \[\mathbf{X}_{\text{in}}^{k} =f(\mathbf{X}_{\text{fea}},\Theta^{k}), \tag{2}\] \[\mathbf{X}_{0}^{k} =\mathbf{X}_{\text{in}}^{k},\] (3) \[\mathbf{X}_{l+1}^{k} =(1-\alpha)\tilde{\mathbf{A}}\mathbf{X}_{l}^{k}+\alpha\mathbf{X}_ {\text{in}}^{k},\forall l=0,\dots,L-1 \tag{4}\] where \(l\) and \(k\) denote the index of layers and training iterations, respectively. The key insight of LazyGNN is that the approximate solution of Eq. (1) (i.e., \(\mathbf{X}_{L}^{k}\)) evolves smoothly since \(\mathbf{X}_{\text{in}}^{k}=f(\mathbf{X}_{\text{fea}},\Theta^{k})\) changes smoothly with model parameters \(\Theta^{k}\). Intuitively, the features have been propagated over the graph many times in previous training iterations so that it suffices to propagate features lazily by reusing existing computation. Formally, we propose LazyGNN to leverage the computation redundancy between training iterations by mixing the diffusion output in iteration \(k-1\) (i.e., \(\mathbf{X}_{L}^{k-1}\)) into the initial embedding of the diffusion process in training iteration \(k\), namely \(\mathbf{X}_{0}^{k}=(1-\beta)\mathbf{X}_{L}^{k-1}+\beta\mathbf{X}_{\text{in}}^ {k}\). This is because, in practice, dropout is commonly used in deep learning to prevent overfitting, which introduces additional variations in the feature embedding as demonstrated in Figure 1. Therefore, we introduce this momentum correction to compensate for such disturbance by mixing current and history features with hyperparameter \(\beta\). To summarize, the forward computation of LazyGNN works as follows: \[\mathbf{X}_{\text{in}}^{k} =f(\mathbf{X}_{\text{fea}},\Theta^{k}), \tag{5}\] \[\mathbf{X}_{0}^{k} =(1-\beta)\mathbf{X}_{L}^{k-1}+\beta\mathbf{X}_{\text{in}}^{k},\] (6) \[\mathbf{X}_{l+1}^{k} =(1-\alpha)\tilde{\mathbf{A}}\mathbf{X}_{l}^{k}+\alpha\mathbf{X} _{\text{in}}^{k},\forall l=0,\dots,L-1 \tag{7}\] By lingering the computation over training iterations as shown in Figure 2, the feature aggregation layers in Eq. (7) solve the denoising problem in Eq. (1) with an implicitly large number of steps although there are only \(L\) layers in each training iteration. Therefore, it only requires a few feature aggregation layers (a small \(L\)) to approximate the fixed point solution \(\mathbf{X}_{*}^{k}\). Note that we find \(L=1\) and \(L=2\) work very well in our experiments in Section 4. In the extreme case when the learning rate and dropout rate are \(0\), the forward computation of LazyGNN is equivalent to running forward propagations \(L\times K\) times continuously with \(K\) being the total number of training iterations. **Remark 1** (Long-distance dependency).: _Through lazy propagation, LazyGNN is able to capture long-distance dependency in graphs with a small number of feature aggregation layers because LazyGNN accumulatively propagates information to distant nodes in the graphs over many training iterations. In contrast, existing works try to capture long-distance dependency in graphs by increasing the number of feature propagation layers, which is less efficient._ Figure 2: LazyGNN with Lazy forward & backward propagation. **Remark 2** (Over-smoothing).: _In contrast to many GNN models such as GCN or GAT that suffer from the over-moothing issue when more layers are stacked, the accumulation of feature aggregations over training iterations in LazyGNN will not cause the over-smoothing issue because the residual connection \(\mathbf{X}_{\text{in}}^{k}\) in Eq. (7) determines the fixed point and prevents the over-smoothed solution._ **Backward Computation.** While it is feasible to leverage the computation from previous training iterations in the forward computation, it is highly non-trivial to compute the gradient for model update in the backward computation since the computation graphs from previous training iterations have been destroyed and released in the memory. In other words, there is no way to directly compute the backpropagation through the history variables \(\{\mathbf{X}_{L}^{k-1},\mathbf{X}_{L}^{k-2},\dots\}\) in current iterations \(k\). Therefore, we choose to compute the gradient indirectly via the implicit function theorem. **Theorem 1** (Implicit Gradient).: _Let \(\mathbf{X}_{*}\) be the fixed point solution of function \(g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})\), i.e., \(g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})=\mathbf{0}\). Given the gradient of loss function \(\mathcal{L}(\mathbf{X}_{*},\mathbf{Y})\) with respect to the fixed point \(\mathbf{X}_{*}\), i.e., \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{*}}\), the gradient of loss \(\mathcal{L}\) with respect to feature \(\mathbf{X}_{\text{in}}\) can be computed as:_ \[\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}}=\frac{\partial \mathcal{L}}{\partial\mathbf{X}_{*}}(\mathbf{J}|_{\mathbf{X}_{*}})^{-1}\frac{ \partial g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})}{\partial\mathbf{X}_{\text{ in}}} \tag{8}\] _where \(\mathbf{J}|_{\mathbf{X}_{*}}=\frac{\partial g(\mathbf{X}_{*},\mathbf{X}_{ \text{in}})}{\partial\mathbf{X}_{*}}\) is the Jacobian matrix of \(g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})\) evaluated at \(\mathbf{X}_{*}\)._ Proof.: Take the first-order derivative on both sides of the fixed point equation \(g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})=0\): \[\frac{\partial g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})}{\partial \mathbf{X}_{\text{in}}}+\frac{\partial g(\mathbf{X}_{*},\mathbf{X}_{\text{in}} )}{\partial\mathbf{X}_{*}}\frac{d\mathbf{X}_{*}}{d\mathbf{X}_{\text{in}}}= \mathbf{0}\] \[\frac{d\mathbf{X}_{*}}{d\mathbf{X}_{\text{in}}}=-\Big{(}\frac{ \partial g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})}{\partial\mathbf{X}_{*}} \Big{)}^{-1}\frac{\partial g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})}{\partial \mathbf{X}_{\text{in}}}\] Using \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}}=\frac{\partial \mathcal{L}}{\partial\mathbf{X}_{*}}\frac{d\mathbf{X}_{*}}{d\mathbf{X}_{\text{ in}}}\), we obtain: \[\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}}=-\frac{\partial \mathcal{L}}{\partial\mathbf{X}_{*}}\Big{(}\frac{\partial g(\mathbf{X}_{*}, \mathbf{X}_{\text{in}})}{\partial\mathbf{X}_{*}}\Big{)}^{-1}\frac{\partial g (\mathbf{X}_{*},\mathbf{X}_{\text{in}})}{\partial\mathbf{X}_{\text{in}}}.\] Specifically, for the problem in Eq. (1), we have the fixed point equation: \[g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})=\mathbf{X}_{*}-\mathbf{X}_{\text{in }}+(\frac{1}{\alpha}-1)(\mathbf{I}-\tilde{\mathbf{A}})\mathbf{X}_{*}=\mathbf{0} \tag{9}\] which gives \(\frac{\partial g(\mathbf{X}_{*},\mathbf{X}_{\text{in}})}{\partial\mathbf{X}_{ \text{in}}}=-\mathbf{I}\) and \(\mathbf{J}|_{\mathbf{X}_{*}}=\frac{1}{\alpha}(\mathbf{I}-(1-\alpha)\tilde{ \mathbf{A}})\). Therefore, according to Theorem 1, the gradient of loss \(\mathcal{L}\) with respect to \(\mathbf{X}_{\text{in}}\) can be computed as follows: \[\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}}=\alpha\frac{ \partial\mathcal{L}}{\partial\mathbf{X}_{*}}\Big{(}\mathbf{I}-(1-\alpha)\tilde{ \mathbf{A}}\Big{)}^{-1}. \tag{10}\] However, it is still infeasible to compute the expensive matrix inversion so we propose to approximate it by the iterative backward gradient propagation: \[\mathbf{G}_{L}=\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{L}} \leavevmode\nobreak\ \Big{(}\approx\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{*}}\Big{)} \tag{11}\] \[\mathbf{G}_{l}=(1-\alpha)\tilde{\mathbf{A}}\mathbf{G}_{l+1}+\alpha \frac{\partial\mathcal{L}}{\partial\mathbf{X}_{L}}\leavevmode\nobreak\ \forall l=L-1,\dots,0 \tag{12}\] where \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{*}}\) is approximated by \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{L}}\), and \(\mathbf{G}_{0}\) provides an approximation for gradient \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}}\). It is clear that the backward computation requires gradient propagation over the graph, which is symmetric to and as expensive as the vanilla forward computation. Similarly, to reduce the number of gradient propagation layers, we propose to propagate the gradient lazily by leveraging the gradient \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}^{k-1}}\) computed in the previous training iteration \(k-1\) as shown in Figure 2: \[\mathbf{G}_{L}^{k}=(1-\gamma)\frac{\partial\mathcal{L}}{\partial \mathbf{X}_{\text{in}}^{k-1}}+\gamma\frac{\partial\mathcal{L}}{\partial \mathbf{X}_{L}^{k}} \tag{13}\] \[\mathbf{G}_{l}^{k}=(1-\alpha)\tilde{\mathbf{A}}\mathbf{G}_{l+1}+ \alpha\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{L}^{k}}\leavevmode \nobreak\ \forall l=L-1,\dots,0 \tag{14}\] where \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}^{k}}\) is approximated by \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{L}^{k}}\), and \(\mathbf{G}_{0}\) provides an approximation for gradient \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}^{k}}\) so that the gradient of model parameters, i.e., \(\frac{\partial\mathcal{L}}{\partial\mathbf{G}^{k}}\), can be further computed by chain rules. Similar to the forward computation, the momentum correction in Eq. (13) compensates the gradient changes over training iterations by mixing the current gradient \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{L}^{k}}\) and history gradient \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}^{k-1}}\) with hyperparameter \(\gamma\). **Remark 3** (Computation and memory efficiency).: _Since LazyGNN uses very few aggregation layers, it significantly reduces the computation and memory cost. Moreover, LazyGNN does not need to store intermediate hidden activation values in the aggregation layers because the computation of implicit gradient is agnostic to the forward propagation trajectory, which further reduces memory cost._ ### Mini-batch LazyGNN with Subgraph Sampling As illustrated in Section 3.1, LazyGNN solves the inherent neighborhood explosion problem so that when handling large-scale graphs, the mini-batch sampling only needs to sample neighboring nodes within a few hop distances. To further demonstrate the superior scalability, we introduce a mini-batch LazyGNN to further improve the computation and memory efficiency with efficient data sampling as shown in Figure 3. In each training iteration \(k\), we sample a target node set \(V_{1}^{k}\) and their \(L\)-hop neighbor set \(V_{2}^{k}\), and we denote the union of these two nodes as \(V^{k}=V_{1}^{k}\cup V_{2}^{k}\). An induced subgraph \(\tilde{\mathbf{A}}_{V^{k}}\) is constructed based on the node set \(V^{k}\). Note that LazyGNN works well with small \(L\in\{1,2\}\) so that the data sampling is extremely efficient. **Forward Computation.** The forward computation of mini-batch LazyGNN works as follows: \[(\mathbf{X}_{\text{in}}^{k})_{V_{k}} =f\big{(}(\mathbf{X}_{\text{fea}})_{V^{k}},\Theta^{k}\big{)}, \tag{15}\] \[(\mathbf{X}_{0})_{V_{k}} =(1-\beta)(\mathbf{M}_{\text{fea}})_{V^{k}}+\beta(\mathbf{X}_{ \text{in}}^{k})_{V_{k}}\] (16) \[(\mathbf{X}_{l+1}^{k})_{V^{k}} =(1-\alpha)\tilde{\mathbf{A}}_{V^{k}}(\mathbf{X}_{l}^{k})_{V^{k}} +\alpha(\mathbf{X}_{\text{in}}^{k})_{V^{k}},\forall l\] (17) \[(\mathbf{M}_{\text{fea}})_{V_{1}^{k}} =(\mathbf{X}_{L}^{k})_{V_{1}^{k}} \tag{18}\] The node features \((\mathbf{X}_{\text{fea}})_{V^{k}}\) for the node set \(V^{k}\) are sampled to form a mini-batch. The corresponding diffused node features \((\mathbf{M}_{\text{fea}})_{V^{k}}\) of the same node set are retrieved from the feature storage \(\mathbf{M}_{\text{fea}}\) and then combined with current node features \((\mathbf{X}_{\text{in}}^{k})_{V_{k}}\) in Eq. (16). The lazy forward propagation runs on the subgraph \(\tilde{\mathbf{A}}_{V^{k}}\) in Eq. (17). Finally, \((\mathbf{X}_{L}^{k})_{V_{1}^{k}}\) provides the prediction for target nodes \(V_{1}^{k}\), which is further maintained in the features storage \(\mathbf{M}_{\text{fea}}\). **Backward Computation.** The backward computation of mini-batch LazyGNN works as follows: \[(\mathbf{G}_{L}^{k})_{V^{k}}=(1-\gamma)(\mathbf{M}_{\text{grad}} )_{V^{k}}+\gamma\frac{\partial\mathcal{L}}{\partial(\mathbf{X}_{L}^{k})_{V^{k}}} \tag{19}\] \[(\mathbf{G}_{l}^{k})_{V^{k}}=(1-\alpha)\tilde{\mathbf{A}}_{V^{k} }(\mathbf{G}_{l+1})_{V^{k}}+\frac{\alpha}{\partial(\mathbf{X}_{L}^{k})_{V^{k}} }\;\forall l\] (20) \[(\mathbf{M}_{\text{grad}})_{V_{1}^{k}}=(\mathbf{G}_{0}^{k})_{V_{1 }^{k}} \tag{21}\] In Eq. (19), \((\mathbf{M}_{\text{grad}})_{V^{k}}\), the history gradient with respect to node features \((\mathbf{X}_{\text{in}}^{k-1})_{V^{k}}\), is retrieved from the gradient storage \(\mathbf{M}_{\text{grad}}\) and then combined with \(\frac{\partial\mathcal{L}}{\partial(\mathbf{X}_{L}^{k})_{V^{k}}}\), the gradient with respect to current node features \((\mathbf{X}_{L}^{k})_{V^{k}}\). The lazy backward propagation runs on the subgraph \(\mathbf{A}_{V^{k}}\) in Eq. (20). Finally, \((\mathbf{G}_{0}^{k})_{V_{1}^{k}}\) provides an estimation for \(\frac{\partial\mathcal{L}}{\partial(\mathbf{X}_{\text{in}}^{k})_{V_{1}^{k}}}\), which is used to compute gradient of parameters \(\Theta^{k}\) by chain rules and then maintained in the gradient storage \(\mathbf{M}_{\text{grad}}\). ### Complexity Analysis As discussed in Section 3.1 and Section 3.2, LazyGNN is scalable due to its efficiency in computation, memory, and data sampling. In this section, we provide complexity analyses to further demonstrate its superior scalability. Since the major efficiency difference lies in feature aggregation layers, we focus on the complexity of feature aggregation. Suppose \(L\) is the number of propagation layers, \(H\) is the size of hidden units, \(N\) is the number of nodes, \(M\) is the number of edges. For simplicity, we assume that \(H\) is the same for all hidden layers. Performing one feature aggregation requires a sparse-dense matrix multiplication that needs \(\mathcal{O}(MH)\) operations. Therefore, the computation complexity for forward feature aggregations and backward gradient aggregations is \(\mathcal{O}(2LMH)\) per epoch. However, the number of layers \(L\) in LazyGNN is much smaller than existing approaches, so it significantly reduces the computation cost. For memory complexity, \(\mathcal{O}(NH)\) space is required for the storage of history feature \(\mathbf{X}_{L}^{k}\) and gradient \(\frac{\partial\mathcal{L}}{\partial\mathbf{X}_{\text{in}}^{k}}\) in LazyGNN. LazyGNN does not store the intermediate state at each feature aggregation layer because the backward gradient computation is agnostic to the forward computation trajectory. Therefore, the total memory complexity for LazyGNN is \(\mathcal{O}(NH)\), which is independent of the number of aggregation layers. In contrast, existing state-of-art history-embedding based models, such as GNNAutoScale (Fey et al., 2021) and GraphFM (Yu et al., 2022), require the storage of feature embeddings in every layer, which leads to the memory complexity \(\mathcal{O}(LNH)\). Moreover, they also require the storage of all intermediate layers for gradient computation. Their memory cost increases linearly with the number of layers, which is essential in capturing long-distance dependency in those models. In fact, because of the large storage requirements, GAS chooses to save the history embedding in CPU memory, but the data movement between CPU and GPU can be dominant compared with the movement in GPU as verified in Section 4.2. Mini-batch LazyGNN further reduces the computation and memory cost by data sampling, which enjoys the same benefits as existing sampling-based methods. Compared to classic sampling-based models, such as GraphSAGE and GraphSAINT, mini-batch LazyGNN only needs to sample neighbors in one hop or two hops distance so that the data sampling is efficient. Above analyses indicate that LazyGNN is highly efficient in computation, memory, and data sampling. The practical running time and memory cost will be discussed in Section 4.2. Note that although we do not investigate the distributed setting in this paper, LazyGNN is promising for its parallelism since it requires fewer communication rounds due to lazy propagation. ## 4 Experiments In this section, we provide comprehensive experiments to validate the superior prediction performance and scalability of LazyGNN. Specifically, we try to answer the following questions: (Q1) Can LazyGNN achieve strong prediction accuracy on large-scale graph benchmarks? (Section 4.1) (Q2) Can LazyGNN handle large graphs more efficiently than existing approaches? (Section 4.2) (Q3) What are the impacts of the hyperparameters in LazyGNN? (Section 4.3) Figure 3: Mini-batch LazyGNN with Feature & Gradient Storage. ### Prediction Performance **Experimental settings.** We conduct experiments on multiple large-scale graph datasets including REDDIT, YELP, FLICKR, ogbn-arxiv, and ogbn-products (Hu et al., 2020). We evaluate the graph representation learning by node classification accuracy in the semi-supervised setting. We provide a performance comparison with multiple baselines including GCN (Kipf and Welling, 2016), GraphSAGE (Hamilton et al., 2017), FastGCN (Chen et al., 2018), LADIES (Zou et al., 2019), VR-GCN (Chen et al., 2017), MVS-GNN (Cong et al., 2020), Cluster- GCN (Chiang et al., 2019), GraphSAINT (Zeng et al., 2020), SGC (Wu et al., 2019), SIGN (Rossi et al., 2020), GAS (Fey et al., 2021). The hyperparameter tuning of baselines closely follows the setting in GNAAutoScale (Fey et al., 2021). For LazyGNN, we set \(\beta=0.5\), and \(\gamma=0.5\). Other hyperparameters are tuned from the following search space: (1) learning rate: \(\{0.01,0.001,0.0001\}\); (2) weight decay: \(\{0.5e-4,5e-5\}\); (3) dropout: \(\{0.1,0.3,0.5,0.7\}\); (4) propagation layers : \(L\in\{1,2\}\); (5) MLP layers: \(\{3,4\}\); (6) MLP hidden units: \(\{256,512\}\); (7) \(\alpha\in\{0.01,0.1,0.2,0.5,0.8\}\). For data sampling, while LazyGNN is compatible with any sampling method, we adopt the subgraph sampling strategy in GNAutoScale to ensure a fair comparison. **Performance analysis.** From the prediction accuracy as summarized in Table 1, we can make the following observations: (1) LazyGNN achieves state-of-art performance on almost all datasets. In particular, LazyGNN achieves \(73.2\%\) and \(81.0\%\) accuracy on ogbn-arxiv and ogbn-products. The only exceptions are that GraphSAINT slightly outperforms LazyGNN by \(0.2\%\) on REDDIT and that GCNII outperforms LazyGNN by \(1.1\%\) on FLICKR. However, LazyGNN is much more efficient than GraphSAINT and GCNII in computation and memory cost. Note that GCNII achieves the reported performance with 10 transformation layers and 8 propagation layers while LazyGNN only uses 4-layer MLP and 2-layer propagation. We believe a stronger performance can be achieved with a more thorough architecture tuning on LazyGNN; (2) Importantly, we observe that full-batch LazyGNN closely matches mini-batch LazyGNN, which indicates that the subgraph sampling in LazyGNN can significantly improve the scalibility (as will be discussed in Section 4.2) but do not heavily hurt the prediction performance. Sometimes, LazyGNN even improves the generalization performance due to sampling (such as for REDDIT); (3) LazyGNN also consistently outperforms APPNP with 10 propagation layers, which indicates the advantage of capturing long-distance dependency in graphs by lazy propagation. The reproduction of GAS+GCN on YELP is much worse than reported, therefore we omit the result. **OGB leaderboard.** To further demonstrate the superior prediction performance of LazyGNN, we also compare LazyGNN with the best-ranked GNN models on the OGB Leaderboard as of Jan. 26, 20231. To make a fair comparison, we only consider the models in the leaderboard that _do not use any external data_ such as the raw text feature. For ogbn-arxiv dataset, we choose AGDN (Sun and Wu, 2020), LGGNN (Ma, 2022), C&S (Huang et al., 2020), EnGCN (Duan et al., 2022) as baselines. For ogbn-products dataset, we compare with SCR (Zhang et al., 2021), SAGN (Sun et al., 2021), GAMLP (Zhang et al., 2022), C&S (Huang et al., 2020), and EnGCN (Duan et al., 2022). Note that these top-ranked models use additional techniques to boost the performance. For instance, AGDN uses Bags of Tricks (BoT) (Wang et al., 2021), self-Knowledge Distillation (self-KD) (Sun and Wu, 2020), and Correct and Smooth (C&S) (Huang et al., 2020); LGGNN uses C&S and Label Reuse (Ma, 2022); GAMLP uses Reliable Label Utilization (RLU) (Zhang et al., 2022) and SCR (Zhang et al., 2021); EnGCN uses self-label enhancement (SLE) (Sun et al., 2021), Label Propagation (LP), and Ensemble with weighted majority voting (MV). LazyGNN is also compatible with these techniques, and we only integrate self label enhancement (SLE) (Sun et al., 2021) to improve LazyGNN. Footnote 1: [https://ogb.stanford.edu/docs/leader_nodeprop/](https://ogb.stanford.edu/docs/leader_nodeprop/) The performance on ogbn-arxiv and ogbn-products is summarized in Table 2 and Table 3, respectively. They clearly demonstrate that LazyGNN (mini-batch) achieves the state-of-art performance compared with these top-ranked GNN models on the highly competitive leaderboard. LazyGNN significantly outperforms many strong baselines such as \begin{table} \begin{tabular}{l c c c c c} \hline \hline **\# nodes** & 230K & 89K & 717K & 169K & 2.4M \\ **\# edges** & 11.6M & 450K & 7.9M & 1.2M & 61.9M \\ **Method** & Reddit & Flickr & Yelp & ogbn- & ogbn- \\ & & & & & & \\ \hline GraphSAGE & 95.4 & 50.1 & 63.4 & 71.5 & 78.7 \\ FastGCN & 93.7 & 50.4 & — & — & — \\ LADIES & 92.8 & — & — & — & — \\ VR-GCN & 94.5 & — & 61.5 & — & — \\ MVS-GNN & 94.9 & — & 62.0 & — & — \\ Cluster-GCN & 96.6 & 48.1 & 60.9 & — & 79.0 \\ GraphSAINT & **97.0** & 51.1 & 65.3 & — & 79.1 \\ SGC & 96.4 & 48.2 & 64.0 & — & — \\ SIGN & 96.8 & 51.4 & 63.1 & — & 77.6 \\ \hline GCN (full) & 95.4 & 53.7 & OOM & 71.6 & OOM \\ APPNP (full) & 96.1 & 53.4 & OOM & 71.8 & OOM \\ GCNII (full) & 96.1 & 55.3 & OOM & 72.8 & OOM \\ \hline GCN (GAS) & 95.4 & 54.0 & — & 71.7 & 76.7 \\ APPNP (GAS) & 96.0 & 52.4 & 63.8 & 71.9 & 76.2 \\ GCNII (GAS) & 96.7 & **55.3** & 65.1 & 72.5 & 77.2 \\ \hline LazyGNN (full) & 96.2 & 54.2 & OOM & **73.2** & OOM \\ LazyGNN (mini) & 96.8 & 54.0 & **65.4** & 73.0 & **82.0** \\ \hline \hline \end{tabular} \end{table} Table 1: Prediction accuracy (\(\%\)) on large-scale graph datasets. “full” and “mini” stand for full-batch and mini-batch respectively. OOM stands for out-of-memory. AGDN, LGGNN, GAMLP, and SAGN, and it slightly outperforms the best-performing EnGCN (Ensemble GCN) with significantly better efficiency (1.5 hours vs 2.4 hours). ### Efficiency Analysis To verify the scalability of LazyGNN, we provide empirical efficient analysis compared with state-of-art end-to-end trainable and scalable GNNs such as GNAAutoScale (GAS) since it has been shown to be the most efficient algorithm for training large-scale GNNs (Fey et al., 2021). Specifically, we measure the memory usage and running time for the training on ogbn-products dataset using the same batch size. We run GAS using the authors' code which stores the feature embedding for each layer in CPU memory. For LazyGNN, the memory for storing two small tensors (i.e., feature and gradient) is required. Although the storage memory for LazyGNN can easily fit into the GPU, we measure the running time for two cases depending on whether the storage is on CPU or GPU memory. Note that all methods use similar number of training epochs as will be verified in Section 4.3, so we compare them using the running time per epoch. For GAS baselines, we use the architecture that can reach the best performance. From the measurements summarized in Table 4, we can make the following observations: (1) LazyGNN (GPU) has a much shorter running time (7.7s) per epoch compared with all baselines; GAS becomes much slower due to the memory movement between GPU and CPU. (2) LazyGNN (GPU+CPU) is faster than APPNP (GAS) because APPNP requires more data movement for feature propagation. This further verifies the computation and memory efficiency of LazyGNN. (3) LazyGNN is memory efficient since only 878 MB additional storage is required to store two small tensors for feature and gradient regardless of the number of layers. In contrast, GAS requires large memory storage due to the feature storage for each layer. These observations verify that LazyGNN is efficient in memory and computation. ### Ablation Study We provide detailed ablation studies on the impacts of hyperparameter settings in LazyGNN using ogbn-arixv dataset. **Lazy Propagation.** We conduct the ablation study to analyze the impact of feature propagation layers. Specifically, we use the same MLP for LazyGNN and APPNP, and we change the number of propagation layers \(K\). The comparison in Table 5 demonstrates that: (1) LazyGNN have much better performance than APPNP when using the same number of propagation layers; (2) LazyGNN archives great performance with even \(1\) propagation layer (\(72.5\%\)), and it already arrives at the best performance (\(73.0\%\)) with \(2\) propagation layers. These results confirm LazyGNN's advantages and capability in capturing long-distance dependency in graphs with very few feature propagation layers. **Sensitivity Analysis.** We provide a detailed sensitivity analysis for the two additional hyperparameters \(\beta\) and \(\gamma\) in LazyGNN. The results in Table 6 show that: (1) \(\{\beta=0,\gamma=0\}\) produces the worst performance (\(71.0\%\)) because it fully trusts the history embedding that might be outdated due to the additional variations caused by dropout as demonstrated in Section 2.2; (2) \(\{\beta=1,\gamma=1\}\) performs slightly better (\(71.7\%\)) even without lazy propagation because 2 propagation layers can provide an approximate solution; (3) \(\{\beta=0.5,\gamma=0.5\}\) performs the best (\(73.0\%\)) because it achieves a good trade-off between historical information and current iteration. It compensates for the staleness in the history storage as designed; (4) The performance of LazyGNN is quite stable for a large range setting of \(\beta\) and \(\gamma\) \begin{table} \begin{tabular}{l c c} \hline \hline **Method** & \begin{tabular}{c} GPU \\ Memory \\ \end{tabular} & \begin{tabular}{c} CPU \\ Memory \\ \end{tabular} & \begin{tabular}{c} Running \\ Time \\ \end{tabular} \\ \hline GCN (GAS) & 2512 & 4783 & 28.8 \\ GCNII (GAS) & 3035 & 4783 & 44.3 \\ APPNP (GAS) & 2142 & 3952 & 84.5 \\ LazyGNN (GPU+CPU) & 2101 & 878 & 44.5 \\ LazyGNN (GPU) & 2981 & — & 7.7 \\ \hline \hline \end{tabular} \end{table} Table 4: Memory usage (MB) and running time for each epoch (seconds per epoch) on ogbn-products. \begin{table} \begin{tabular}{l c} \hline \hline **Method** & \begin{tabular}{c} Accuracy (\%) \\ \end{tabular} \\ \hline GAMLP + RLU + SCR & 85.05 \\ GAMLP + RLU + SCR + C\&S & 85.20 \\ SAGN + SLE & 84.68 \\ SAGN + SLE + C\&S & 84.85 \\ EnGCN + SLE + LP + MV & 87.98 \\ LazyGNN + SLE & **88.05** \\ \hline \hline \end{tabular} \end{table} Table 3: Comparison with top-ranked models on ogbn-products. \begin{table} \begin{tabular}{l c} \hline \hline **Method** & \begin{tabular}{c} Accuracy (\%) \\ \end{tabular} \\ \hline APPNP (K=1) & 70.6 \\ APPNP (K=2) & 71.4 \\ APPNP (K=3) & 71.5 \\ LazyGNN (K=1) & 72.5 \\ LazyGNN (K=2) & 73.0 \\ LazyGNN (K=3) & 73.0 \\ \hline \hline \end{tabular} \end{table} Table 5: Prediction accuracy with different numbers of feature propagation layers on ogbn-arxiv. In fact, we fix \(\beta=\gamma=0.5\) for LazyGNN in all experiments for simplicity. Therefore, it requires almost negligible effort for additional hyperparameter tuning. **Convergence.** We show the convergence of LazyGNN during the training process using ogbn-arxiv dataset. The convergence of validation accuracy in Figure 4 demonstrates that LazyGNN has a comparable convergence speed with GCN (GAS) and GCNII (GAS), and is slightly faster than APPNP (GAS) in terms of the number of training epochs. ## 5 Related Work It has been generally demonstrated that it is beneficial to capture long-distance relations in graphs by stacking more feature aggregation layers or unrolling various fixed point iterations in GNNs (Gasteiger et al., 2018; Gu et al., 2020; Liu et al., 2020; Chen et al., 2020; Li et al., 2021; Ma et al., 2020; Pan et al., 2020; Zhu et al., 2021; Chen et al., 2020). But these works suffer from scalability concerns due to the neighborhood explosion problem (Hamilton et al., 2017). A large body of existing research focuses on improving the efficiency and scalability of large-scale GNNs using various novel designs, such as sampling methods, pre-computing or post-computing methods, and distributed methods. Sampling methods adopt mini-batch training strategies to reduce computation and memory requirements by sampling nodes and edges. They mitigate the neighbor explosion issue by either removing neighbors (Hamilton et al., 2017; Chen et al., 2018; Zeng et al., 2020; Zou et al., 2019) or updating with feature memory (Fey et al., 2021; Yu et al., 2022). Pre-computing or post-computing methods separate the feature aggregation and prediction models into two stages, such as pre-computing the feature aggregation before training (Wu et al., 2019; Rossi et al., 2020; Sun et al., 2021; Zhang et al., 2022; Bojchevski et al., 2020) or post-processing with label propagation after training (Zhu, 2005; Huang et al., 2020). Distributed methods distribute large graphs to multiple servers and parallelize GNNs training (Chiang et al., 2019; Chai et al., 2022; Shao et al., 2022). In retrospect, these existing approaches still suffer from various limitations, such as high costs in computation, memory, and communication as well as performance degradation due to large approximation errors or multi-stage training. Different from existing works, in this work, we propose LazyGNN from a substantially different and novel perspective and propose to capture the long-distance dependency in graphs by shallower models instead of deeper models. This leads to a much more efficient LazyGNN for graph representation learning. Moreover, existing approaches for scalable GNNs can be used to further accelerate LazyGNN. The proposed mini-batch LazyGNN is a promising example. LazyGNN also draws insight from existing research on graph signal processing and implicit modeling. The forward construction of LazyGNN follows the optimization perspective of GNNs (Ma et al., 2020), and it is can be easily generalized to other fixed point iterations with various diffusion properties. LazyGNN is related to recent works in implicit modeling, such as Neural Ordinary Differential Equations (Chen et al., 2018), Implicit Deep Learning (El Ghaoui et al., 2021), Deep Equilibrium Models (Bai et al., 2019), and Implicit GNNs (Gu et al., 2020). LazyGNN focuses on developing shallow models with highly scalable and efficient computation while these implicit models demand significantly more computation resources. ## 6 Conclusions In this paper, we propose LazyGNN, a novel shallow model to solve the neighborhood explosion problem in large-scale GNNs while capturing long-distance dependency in graphs through lazy propagation. We also develop a highly scalable and efficient variant, mini-batch LazyGNN, to handle large graphs. Comprehensive experiments demonstrate its superior prediction performance and efficiency on large-scale graph datasets. We plan to explore lazy propagation for other types of GNN models and its further acceleration based on other scalable techniques in the future. \begin{table} \begin{tabular}{c c} \hline \hline **Hyperparameter settings** & Accuracy (\%) \\ \hline \(\beta=0.0,\;\gamma=0.0\) & 71.0 \\ \(\beta=1.0,\;\gamma=1.0\) & 71.7 \\ \hline \(\beta=0.5,\;\gamma=0.1\) & 72.5 \\ \(\beta=0.5,\;\gamma=0.5\) & 73.0 \\ \(\beta=0.5,\;\gamma=0.9\) & 72.8 \\ \hline \(\beta=0.1,\;\gamma=0.5\) & 72.4 \\ \(\beta=0.5,\;\gamma=0.5\) & 73.0 \\ \(\beta=0.9,\;\gamma=0.5\) & 72.7 \\ \hline \hline \end{tabular} \end{table} Table 6: Prediction accuracy of mini-batch LazyGNN for different hyperparameter settings on ogbn-arxiv. Figure 4: Validation performance versus training epochs.
2309.02422
Maximum Mean Discrepancy Meets Neural Networks: The Radon-Kolmogorov-Smirnov Test
Maximum mean discrepancy (MMD) refers to a general class of nonparametric two-sample tests that are based on maximizing the mean difference over samples from one distribution $P$ versus another $Q$, over all choices of data transformations $f$ living in some function space $\mathcal{F}$. Inspired by recent work that connects what are known as functions of $\textit{Radon bounded variation}$ (RBV) and neural networks (Parhi and Nowak, 2021, 2023), we study the MMD defined by taking $\mathcal{F}$ to be the unit ball in the RBV space of a given smoothness order $k \geq 0$. This test, which we refer to as the $\textit{Radon-Kolmogorov-Smirnov}$ (RKS) test, can be viewed as a generalization of the well-known and classical Kolmogorov-Smirnov (KS) test to multiple dimensions and higher orders of smoothness. It is also intimately connected to neural networks: we prove that the witness in the RKS test -- the function $f$ achieving the maximum mean difference -- is always a ridge spline of degree $k$, i.e., a single neuron in a neural network. This allows us to leverage the power of modern deep learning toolkits to (approximately) optimize the criterion that underlies the RKS test. We prove that the RKS test has asymptotically full power at distinguishing any distinct pair $P \not= Q$ of distributions, derive its asymptotic null distribution, and carry out extensive experiments to elucidate the strengths and weakenesses of the RKS test versus the more traditional kernel MMD test.
Seunghoon Paik, Michael Celentano, Alden Green, Ryan J. Tibshirani
2023-09-05T17:51:00Z
http://arxiv.org/abs/2309.02422v3
# Maximum Mean Discrepancy Meets Neural Networks: ###### Abstract Maximum mean discrepancy (MMD) refers to a general class of nonparametric two-sample tests that are based on maximizing the mean difference between samples from one distribution \(P\) versus another \(Q\), over all choices of data transformations \(f\) living in some function space \(\mathcal{F}\). Inspired by recent work that connects what are known as functions of _Radon bounded variation_ (RBV) and neural networks (Parhi and Nowak, 2021, 2023), we study the MMD defined by taking \(\mathcal{F}\) to be the unit ball in the RBV space of a given smoothness degree \(k\geq 0\). This test, which we refer to as the _Radon-Kolmogorov-Smirnov_ (RKS) test, can be viewed as a generalization of the well-known and classical Kolmogorov-Smirnov (KS) test to multiple dimensions and higher orders of smoothness. It is also intimately connected to neural networks: we prove that the witness in the RKS test--the function \(f\) achieving the maximum mean difference--is always a ridge spline of degree \(k\), i.e., a single neuron in a neural network. We can thus leverage the power of modern neural network optimization toolkits to (approximately) maximize the criterion that underlies the RKS test. We prove that the RKS test has asymptotically full power at distinguishing any distinct pair \(P\neq Q\) of distributions, derive its asymptotic null distribution, and carry out experiments to elucidate the strengths and weaknesses of the RKS test versus the more traditional kernel MMD test. ## 1 Introduction In this paper, we consider the fundamental problem of nonparametric two-sample testing, where we observe independent samples \(x_{i}\sim P\), \(i=1,\ldots,m\) and \(y_{i}\sim Q\), \(i=1,\ldots,n\), all samples assumed to be in \(\mathbb{R}^{d}\), and we use the data to test the hypothesis \[H_{0}:P=Q,\quad\text{versus}\quad H_{1}:P\neq Q.\] Though there are many forms of nonparametric two-sample tests, we will focus on a class of tests based on _maximum mean discrepancy_ (MMD), which measures distance between two sets of samples by taking the maximum difference in sample averages over a function class \(\mathcal{F}\): \[\rho(P_{m},Q_{n};\mathcal{F})=\sup_{f\in\mathcal{F}}\,|P_{m}(f)-Q_{n}(f)|. \tag{1}\] Here \(P_{m}=\frac{1}{m}\sum_{i=1}^{m}\delta_{x_{i}}\) is the empirical distribution and \(P_{m}(f)=\frac{1}{m}\sum_{i=1}^{m}f(x_{i})\) the corresponding empirical expectation operator based on \(x_{i}\), \(i=1,\ldots,m\); and likewise for \(Q_{n}\) and \(Q_{n}(f)\). The discrepancy in (1) is quite general and certain choices of \(\mathcal{F}\) recover well-known distances that give rise to two-sample tests. A noteworthy univariate (\(d=1\)) example is the _Kolmogorov-Smirnov_ (KS) distance (Kolmogorov, 1933; Smirnov, 1948). Though it is more typically defined in terms of cumulative distribution functions (CDFs) or ranks, the KS distance can be seen as the MMD that results when \(\mathcal{F}\) is taken to be the class of functions with at most unit _total variation_ (TV). Some attempts have been made to define a multivariate KS distance based on multivariate CDFs (Bickel, 1969) or ranks (Friedman and Rafsky, 1979), but the resulting tests have a few limitations, such as being expensive to compute or exhibiting poor power in practice. In fact, even the univariate KS test is known to be insensitive to certain kinds of alternatives, such as those \(P\neq Q\) which differ "in the tails" (Bryson, 1974). This led Wang et al. (2014) to recently propose a higher-order generalization of the KS test, which uses the MMD based on a class of functions whose _derivatives_ are of bounded TV. In this work we propose and study a new class of MMDs based on a kind of multivariate total variation known as _Radon total variation_ (RTV). The definition of RTV is necessarily technical, and we delay it until Section 2. For now, we remark that if \(d=1\) then RTV reduces to the usual notion of total variation, which means that our RTV-based MMD--the central focus of this paper--directly generalizes the KS distance to multiple dimensions. We refer to this RTV-based MMD as the _Radon-Kolmogorov-Smirnov_ (RKS) distance, and the resulting two-sample test as the RKS test. We also will consider the MMD defined using a class of functions whose derivatives are of bounded RTV, which in turn generalizes the higher-order KS distance of Wang et al. (2014) to multiple dimensions. Sadhanala et al. (2019) recently showed that the higher-order KS test can be more sensitive to departures in the tails, and we will give empirical evidence that our higher-order RKS test can be similarly sensitive to tail behavior. Our test statistic also has a simple but revealing characterization in terms of _ridge splines_. A ridge spline of integer degree \(k\geq 0\) is defined for a direction \(w\in\mathbb{S}^{d-1}\) and an offset \(b\in\mathbb{R}\) as the truncated polynomial \(f(x)=(w^{\top}x-b)_{+}^{k}\). Here we use \(\mathbb{S}^{d-1}\) to denote the unit \(\ell_{2}\) sphere in in \(\mathbb{R}^{d}\) (the set of vectors in with unit \(\ell_{2}\) norm), and we use the abbreviation \(t_{+}=\max\{t,0\}\). We prove (Theorem 3) that a \(k^{\text{th}}\) degree ridge spline _witnesses_ the \(k^{\text{th}}\) degree RKS distance: there is a \(k^{\text{th}}\) degree ridge spline \(f\) with unit Radon total variation for which \(P_{m}(f)-Q_{n}(f)\) equals the RKS distance. Thus the RKS test statistic can be equivalently written as \[T_{d,k}=\max_{(w,b)\in\mathbb{S}^{d-1}\times[0,\infty)}\,\bigg{|}\frac{1}{m} \sum_{i=1}^{m}(w^{\top}x_{i}-b)_{+}^{k}-\frac{1}{n}\sum_{i=1}^{n}(w^{\top}y_{i }-b)_{+}^{k}\bigg{|}. \tag{2}\] Ridge splines--and in particular the first-degree ridge spline \(f(x)=(w^{\top}x-b)_{+}\), which is also called a rectified linear (ReLU) unit--are fundamental building blocks of modern neural networks. From this perspective, the representation (2) says that the RKS distance is achieved by a single neuron in a two-layer neural network. In fact, the connections between Radon total variation and neural networks run deeper. The RKS distance can be viewed as finding the maximum discrepancy between sample means over all two-layer neural networks (of arbitrarily large width) subject to a weight decay constraint (Section 2). Although we focus throughout on two-layer neural networks, the MMD defined over deeper networks can be viewed the RKS distance in the representation learned by the hidden layers. The representation (2) also hints at several interesting statistical properties. Let \(X\sim P_{m}\) and \(Y\sim Q_{n}\) be random variables drawn from the empirical distributions of \(\{x_{i}\}_{i=1}^{m}\) and \(\{y_{i}\}_{i=1}^{n}\), respectively. The \(0^{\text{th}}\) degree RKS distance finds the direction \(w\in\mathbb{S}^{d-1}\) along which the usual Kolmogorov-Smirnov distance--maximum gap in CDFs--between the univariate random variables \(w^{\top}X\) and \(w^{\top}Y\) is as large as possible. For \(k\geq 1\), the \(k^{\text{th}}\) degree statistic finds the direction \(w\in\mathbb{S}^{d-1}\) along which the higher-order KS distance--maximum gap in truncated \(k^{\text{th}}\) moments--between \(w^{\top}X\) and \(w^{\top}Y\) is maximized. Thus, speaking informally, we expect the RKS test to be particularly sensitive to the case when the laws of \(w^{\top}X\) and \(w^{\top}Y\) differ primarily in just a few directions \(w\) (because we are taking a maximum over such directions in (2)). In other words, we expect the RKS test to be sensitive to _anisotropic_ differences between \(P\) and \(Q\). On the other hand, taking a larger value of \(k\) results in higher-order truncated sample moments, which can be much more sensitive to small differences in the tails. Figure 1 gives an illustrative example. We consider two normal distributions with equal means and covariances differing in just one direction (along the x-axis). The figure displays the witnesses (ridge splines) for the RKS test when \(k=0,1,2\). For larger \(k\), the witness is more aligned with the direction in which \(P\) and \(Q\) vary, and also places more weight on the tails. Summary of contributions.Our main contributions are as follows. * We propose a new class of two-sample tests using a \(k^{\text{th}}\) degree Radon total variation MMD. We prove a representer theorem (Theorem 3) which shows that the MMD is witnessed by a ridge spline (establishing the representation in (2)). This connects our proposal to two-sample testing based on neural networks, and helps with optimization. * Under the null \(P=Q\), we derive the asymptotic distribution of the test statistic (Theorem 5). * Under the alternative \(P\neq Q\), we give upper bounds on the rate at which the test statistic concentrates around the population-level MMD. Using the fact that the population-level MMD is a metric, we then show that the RKS test is _consistent_ against any fixed \(P\neq Q\): it has asymptotic error (sum of type I and type II errors) tending to zero (Theorem 6). * We complement our theory with numerical experiments to explore the operating characteristics of the RKS test compared to other popular nonparametric two-sample tests. Related work.Recently, there has been a lot of interest in multivariate nonparametric two-sample tests using kernel MMDs (Gretton et al., 2012), and energy distances (Baringhaus and Franz, 2004; Szekely and Rizzo, 2005). The latter are in many cases equivalent to a kernel MMD (Sejdinovic et al., 2013). It is worth being clear that the Radon bounded variation space is _not_ an RKHS, and as such, our test cannot be seen as a special case of a kernel MMD. There are also many other kinds of multivariate nonparametric two-sample tests, such as graph-based tests using \(k\)NN graphs (Schilling, 1986; Henze, 1988) or spanning-trees (Friedman and Rafsky, 1979). The RKS test statistic (2) avoids the need to construct a graph over the samples, though we note that one could also use a graph to measure (approximate) multivariate total variation of a different variety (sometimes called _measure-theoretic_ TV, which is not the same as Radon TV), and one could then form a related two-sample test, accordingly. Some literature refers to maximum mean discrepancy (MMD) with respect to an arbitrary function class as an _integral probability metric_ (IPM) (Muller, 1997). While IPMs look at differences in \(\mathrm{d}P-\mathrm{d}Q\), closely related are \(\phi\)-divergences, which look at differences in \(\mathrm{d}P/\mathrm{d}Q\)(Sriperumbudur et al., 2009). In machine learning, two-sample tests play a fundamental role in generative adversarial networks (GANs) (Goodfellow et al., 2014), which have proven to be an effective way to generate new (synthetic) draws that adhere to the distribution of a given high-dimensional set of samples. In short, GANs are trained to produce synthetic data which a two-sample test cannot distinguish from "real" samples. However, optimizing a GAN is notoriously unstable. It has been suggested that the stability of GANs can be improved if the underlying two-sample test is based on an MMD, with constraints on, e.g., the Lipschitz constant (Arjovsky et al., 2017), RKHS norm (Li et al., 2017), or Sobolev norm (Mroueh et al., 2018) of the witness. Unlike Radon TV, these function classes do not have an intrinsic connection to neural networks, which in practice are most commonly used to train the discriminator in a GAN. At a technical level, our paper falls into a line of work exploring neural networks from the functional analytic perspective. The equivalences between weight decay of parameters in a two-layer neural network and first-degree (\(k=1\)) Radon total variation were discovered in Savarese et al. (2019); Ongie et al. (2020), and further formalized and extended by Parhi and Nowak (2021) to the higher-degree case (\(k>1\)). We make use of these equivalences to prove results on the Radon TV MMD. Lastly, we note that the sensitivity of neural networks to variation in only a few directions was observed even earlier, in Bach (2017). ## 2 The Radon-Kolmogorov-Smirnov test For independent samples \(x_{i}\sim P\), \(i=1,\ldots,m\) and \(y_{i}\sim Q\), \(i=1,\ldots,n\), and a given integer \(k\geq 0\), the RKS test statistic \(T_{d,k}\) is defined as in (2). This statistic searches for a marginal (defined by projection onto the direction \(w\)) with the largest discrepancy in a truncated \(k^{\text{th}}\) moment. As with any two-sample test, we can calibrate the rejection threshold for the RKS test statistic using a permutation null. Given any user-chosen level \(\alpha\in[0,1]\), we reject \(H_{0}:P=Q\) if \[\frac{\sum_{j=1}^{B}\mathds{1}\big{\{}T_{d,k}(z_{\pi_{j}})\geq T_{d,k}(z)\big{\}} +1}{B+1}\leq\alpha. \tag{3}\] Here we use \(z=(x_{1},\ldots,x_{m},y_{1},\ldots,y_{n})\in\mathbb{R}^{m+n}\) to denote the original data sequence, and we use \(T_{d,k}(z)\) to emphasize that the statistic in (2) is computed on \(z\). Further, each \(\pi_{j}\) is a permutation of \(\{1,\ldots,n\}\), drawn uniformly at random, and we use \(T_{d,k}(z_{\pi_{j}})\) to denote the test statistic computed on the permuted sequence \(z_{\pi_{j}}=(z_{\pi(1)},\ldots,z_{\pi(m+n)})\). Standard results on permutation tests imply that the test defined by the rejection threshold (3) has type I error control at the level \(\alpha\). Finding the value of \(w\) and \(b\) achieving the supremum in (2) is a nonconvex problem. However, it bears a connection to neural network optimization, which is of course among the most familiar and widely-studied nonconvex problems in machine learning. We show in Appendix I that problem (2) can be equivalently cast as finding the maximum discrepancy between sample means over all two-layer neural networks (of arbitrarily large width) under a weight decay-like constraint. In particular, if we denote by \(f_{(a_{j},w_{j},b_{j})_{j=1}^{N}}\) the \(N\)-neuron two-layer neural network defined by \[f_{(a_{j},w_{j},b_{j})}(x)=a_{j}(w_{j}^{\top}x-b_{j})_{+}^{k}\quad\text{and} \quad f_{(a_{j},w_{j},b_{j})_{j=1}^{N}}(x)=\sum_{j=1}^{N}\,f_{(a_{j},w_{j},b_{ j})}(x), \tag{4}\] then the RKS test statistic is equivalently \[T_{d,k} =\max_{f=f_{(a_{j},w_{j},b_{j})_{j=1}^{N}}} P_{m}(f)-Q_{n}(f)\] (5) subject to \[\sum_{j=1}^{N}\,|a_{j}|\|w_{j}\|_{2}^{k}\leq 1,\] \[(a_{j},w_{j},b_{j})\in\mathbb{R}\times\mathbb{R}^{d}\times[0, \infty),\;j=1,\ldots,N.\] This equivalence holds for any number of neurons \(N\geq 1\), which is why we say that the network can be of "arbitrarily large width". In Section 4, we use a Lagrangian form of this constrained optimization, allowing us to leverage existing deep learning toolkits to compute the RKS distance. As with neural network optimization in general, we cannot prove that any practical first-order scheme--such as gradient descent or its variants--is able to find the global optimum of (5), or its Lagrange form. However, we find empirically that the test statistic resulting from such first-order schemes has favorable behavior in practice, such as stability (with respect to the choice of learning rate) and strong power (with respect to certain classes of alternatives). Finally, we note that in practice we use the permutation threshold (3) to calibrate the statistic computed by first-order optimization, i.e., the same first-order optimization scheme is applied to the original data sequence and to every permuted sequence. In effect, we can view this as _redefining_ the RKS test to be the output of such a first-order scheme, and as the permutation null controls type I error for any measurable function of data, it also controls type I error for a test statistic computed this way. ### Functions of Radon bounded variation The RKS distance, like the univariate KS distance, can be viewed as the maximum mean discrepancy with respect to a function class defined by a certain notion of smoothness. Whereas the univariate KS distance is the MMD over functions with total variation is bounded by 1, the RKS distance is the MMD over functions with Radon total variation bounded by 1, subject to a boundary condition. This will be shown a bit later; first, we must cover preliminaries needed to understand Radon total variation. Heuristically, the \(k^{\text{th}}\) degree Radon total variation of \(f:\mathbb{R}^{d}\to\mathbb{R}\) measures the average smoothness of the "marginals" of \(f\). To be more concrete, consider a function \(f:\mathbb{R}^{d}\to\mathbb{R}\) which is infinitely differentiable, and whose derivatives of any order decay super-polynomially: \(f\in C^{\infty}(\mathbb{R}^{d})\) and \(\sup_{x\in\mathbb{R}^{d}}|x^{\alpha}\partial^{\beta}f(x)|<\infty\). Here \(\alpha=(\alpha_{1},\ldots,\alpha_{d})\) and \(\beta=(\beta_{1},\ldots,\beta_{d})\) are multi-indices (with nonnegative integer elements), and we use the abbreviations \[x^{\alpha}=\prod_{i=1}^{d}x_{i}^{\alpha_{i}},\quad\text{and}\quad\partial^{\beta }f=\partial_{x_{1}}^{\beta_{1}}\cdots\partial_{x_{d}}^{\beta_{d}}f.\] The set of such functions is called the _Schwartz class_, and denoted by \(\mathcal{S}(\mathbb{R}^{d})\). The _Radon transform_ of a function \(f\in\mathcal{S}(\mathbb{R}^{d})\) is itself another function \(\mathcal{R}\{f\}:\mathbb{S}^{d-1}\times\mathbb{R}\to\mathbb{R}\) defined as \[\mathcal{R}\{f\}(w,b)=\int_{w^{\top}x=b}f(x)\,\mathrm{d}x,\] where the integral is with respect to the Lebesgue surface measure on the hyperplane \(\{w^{\top}x=b\}\). As a function of \(b\), the Radon transform can be viewed as the marginal of the function \(f\) in the direction \(w\). The \(k^{\text{th}}\) degree Radon total variation of \(f\) is then defined to be (Parhi and Nowak, 2021, 2023):1 Footnote 1: A remark on notation and nomenclature: we use \(\mathrm{RBV}^{k}\) to refer to the space which Parhi and Nowak (2021); Parhi (2022); Parhi and Nowak (2023) instead call \(\mathrm{RBV}^{k+1}\). That is, we index based on the _degree_ of the underlying ridge spline, whereas the aforementioned papers index based on the _order_, traditionally defined as the degree plus one, \(m=k+1\). \[\|f\|_{\mathrm{RTV}^{k}}=c_{d}\int_{\mathbb{S}^{d-1}\times\mathbb{R}}\big{|} \partial_{b}^{k+1}\Lambda^{d-1}\mathcal{R}\{f\}(w,b)\big{|}\,\mathrm{d}\sigma (w,b),\] where \(\sigma\) is the Hausdorff measure on \(\mathbb{S}^{d-1}\times\mathbb{R}\), \(c_{d}=1/(2(2\pi)^{d-1})\), and \(\Lambda^{d-1}\) is the "ramp filter" defined by \(\Lambda^{d-1}=(-\partial_{b}^{2})^{\frac{d-1}{2}}\) with fractional derivatives interpreted in terms of Riesz potentials (see Parhi and Nowak (2021, 2023) for details). Equivalently, if we define an operator by \(R_{k}\{f\}(w,b)=c_{d}\partial_{b}^{k+1}(-\partial_{b}^{2})^{\frac{d-1}{2}} \mathcal{R}\{f\}(w,b)\), then we can write \(k^{\text{th}}\) degree Radon TV of \(f\) simply as \(\|f\|_{\mathrm{RTV}^{k}}=\|R_{k}\{f\}\|_{L^{1}}\). The mapping \(f\mapsto\|f\|_{\mathrm{RTV}^{k}}\) is a seminorm, which we call the \(\mathrm{RTV}^{k}\) seminorm. Parhi and Nowak (2021, 2023) and Parhi (2022) extend the \(\mathrm{RTV}^{k}\) seminorm beyond Schwartz functions using functional analytic tools based on duality. The space of functions with bounded \(\mathrm{RTV}^{k}\) seminorm is referred to as the \(\mathrm{RBV}^{k}\) space (where \(\mathrm{RBV}\) stands for "Radon bounded variation"). After this extension, one can still think of \(\mathrm{RTV}^{k}\) seminorm as measuring average higher-order smoothness of the marginals of \(f\), but it does not require that all derivatives and integrals exist in a classical sense. We refer the reader especially to Parhi (2022) for the complete functional analytic definition of the \(\mathrm{RBV}^{k}\) space. For our purposes, it is only important that \(\mathrm{RBV}^{k}\) functions enjoy the representation established by the following theorem. Note that in order to define the \(\mathrm{RBV}^{k}\) space, Parhi and Nowak (2021); Parhi (2022) must view it as a space of equivalence classes of functions under the equivalence relation \(f\sim g\) if \(f(x)=g(x)\) for Lebesgue almost every \(x\in\mathbb{R}^{d}\). We denote elements of \(\mathrm{RBV}^{k}\) as \(\mathsf{f}\), and the functions they contain as \(f\in\mathsf{f}\). **Proposition 1** (Adaptation of Theorem 22 in Parhi and Nowak (2021); Theorem 3.8 in Parhi (2022)).: _Fix any \(k\geq 0\). For each \(\mathsf{f}\in\mathrm{RBV}^{k}\), there exists a representative \(f\in\mathsf{f}\) which satisfies for all \(x\in\mathbb{R}^{d}\)_ \[f(x)=\int_{\mathbb{S}^{d-1}\times[0,\infty)}(w^{\mathsf{T}}x-b)_{+}^{k}\, \mathrm{d}\mu(w,b)+q(x),\] _for some finite signed Borel measure \(\mu\) on \(\mathbb{S}^{d-1}\times[0,\infty)\) satisfying \(\|\mu\|_{\mathrm{TV}}=\|\mathsf{f}\|_{\mathrm{RTV}^{k}}\), and some polynomial \(q\) of degree at most \(k\), where we use \(\|\cdot\|_{\mathrm{TV}}\) for the total variation norm in the sense of measures._ Proposition 1 is the key result connecting the \(\mathrm{RBV}^{k}\) space to two-layer neural networks. It states that any \(\mathrm{RBV}^{k}\) functions is equal almost everywhere to the sum of a (possibly infinite-width) two-layer neural network and a polynomial. Furthermore, the \(\ell_{1}\) norm of coefficients in the last layer of this neural network (formally, the total variation norm \(\|\mu\|_{\mathrm{TV}}\) of the measure \(\mu\) defined over the coefficients) equals the \(\mathrm{RBV}^{k}\) seminorm of the function in question. As stated, Proposition 1 is a slight refinement of results in Parhi and Nowak (2021); Parhi (2022), which we show in Appendix A. Parhi and Nowak (2021) consider the nonparametric regression problem defined by minimizing, over all functions \(f\), the squared loss incurred by \(f\) with respect to a given finite data set plus a penalty on \(\|f\|_{\mathrm{RTV}^{k}}\). They show this is solved by the sum of a _finite-width_ two-layer neural network and a polynomial, and hence provide a representation theorem for \(\mathrm{RTV}^{k}\)-penalized nonparametric regression analogous to that for kernel ridge regression (Wahba, 1990). In a coming subsection, we will establish a similar connection in the context of two-sample testing: the MMD under an \(\mathrm{RTV}^{k}\) constraint is realized by a single neuron. Before moving on, it is worth providing some intuition for the results just discussed. First, the operator \(R_{k}\) should be understood as transforming a function \(f\) into the Radon domain: namely, it specifies \(f\) via the higher-order derivatives of its marginals. Then, the \(\mathrm{RTV}^{k}\) acts as the \(L^{1}\) norm in the Radon domain. Lastly, the reason two-layer neural networks and ridge splines emerge as the solutions to nonparametric regression and maximum mean discrepancy problems under an \(\mathrm{RTV}^{k}\) constraint is that ridge splines are _sparse_ in the Radon domain. In particular, for \(f(x)=(w^{\top}x-b)_{+}^{k}\), we have (Parhi and Nowak, 2021): \[R_{k}\{f\}(w,b)=\frac{1}{2}\big{(}\delta_{(w,b)}+(-1)^{k+1}\delta_{(-w,-b)} \big{)},\] where \(\delta_{(\pm w,\pm b)}\) denote point masses at \((\pm w,\pm b)\). Thus, \(\mathrm{RTV}^{k}\)-penalized optimization problems are solved by two-layer neural networks due to the tendency of the \(L^{1}\) norm to encourage sparse solutions. ### Pointwise evaluation of RBV functions Recall, the \(\mathrm{RBV}^{k}\) space contains equivalence classes of functions whose members differ on sets of Lebesgue measure zero. Therefore, at face value, point evaluation is meaningless for elements of the \(\mathrm{RBV}^{k}\) space. This poses a problem for defining an MMD with respect to RBV functions, since the MMD depends on empirical averages, which require function evaluations over samples. Fortunately, we show that there is a natural way to resolve point evaluation over the \(\mathrm{RBV}^{k}\) space: each equivalence class in \(\mathrm{RBV}^{k}\) has, possibly subject to a mild boundary condition, a unique representative which satisfies a suitable notion of continuity. We can then define point evaluation with respect to this representative. For the case \(k=0\), we need to introduce a new notion of continuity, which we call _radial cone continuity_. For \(k\geq 1\), we rely on the standard notion of continuity. Radial cone continuity is defined as follows. **Definition 1**.: _A function \(f\) is said to be radially cone continuous if it is continuous at the origin, and for any \(x\in\mathbb{R}^{d}\setminus\{0\}\), we have \(f(x+\epsilon v)\to f(x)\) whenever (i) \(\epsilon\to 0\) and (ii) \(v\in\mathbb{S}^{d-1}\) and \(v\to x/\|x\|_{2}\)._ Radial cone continuity can be viewed as a generalization of right-continuity to higher dimensions. Indeed a consequence of radial cone continuity is that for every \(v\in\mathbb{R}^{d}\), the restriction of the function \(f\) to the ray emanating from the origin in the direction \(v\) is right-continuous (i.e., \(t\mapsto f(tv)\), \(t>0\) is right-continuous). The concept of radial cone continuity, however, is stronger than right-continuity along rays--it additionally requires continuity along any path which is tangent to and approaches \(x\) from the same direction as the ray that points from the origin to \(x\). The following theorem shows that (subject to a boundary condition for the case \(k=0\)) every equivalence class \(\mathsf{f}\in\mathrm{RBV}^{k}\) contains a unique continuous representative when \(k\geq 1\), and radially cone continuous representative when \(k=0\). **Theorem 1**.: _For \(k=0\), if \(\mathsf{f}\in\mathrm{RBV}^{0}\) contains a function that is continuous at the origin, then it contains a unique representative that is radially cone continuous. Moreover, for \(k\geq 1\), each \(\mathsf{f}\in\mathrm{RBV}^{k}\) contains a unique representative that is continuous and this representative is in fact \((k-1)\)-times continuously differentiable._ We prove Theorem 1 in Appendix B. The theorem motivates the definition of the function spaces: \[\mathrm{RBV}^{0}_{c} =\Big{\{}f\,:\,f\in\mathsf{f}\text{ for some }\mathsf{f}\in \mathrm{RBV}^{0},\,f\text{ radially cone continuous}\Big{\}}, \tag{6}\] \[\mathrm{RBV}^{k}_{c} =\Big{\{}f\,:\,f\in\mathsf{f}\text{ for some }\mathsf{f}\in \mathrm{RBV}^{k},\,f\text{ continuous}\Big{\}},\quad k\geq 1.\] Unlike \(\mathrm{RBV}^{k}\), the space \(\mathrm{RBV}^{k}_{c}\) contains functions rather than equivalence classes of functions, so that point evaluation is well-defined. The Radon total variation of a member \(f\in\mathsf{f}\) is defined in the natural way as the Radon total variation of the function class in \(\mathrm{RBV}^{k}\) to which it belongs. ### The RKS distance is an MMD We are ready to show that the RKS distance is equivalent to the MMD over functions \(f\) with \(\|f\|_{\mathrm{RTV}^{k}}\leq 1\), subject to a boundary condition. In this sense, it can be viewed as a generalization of the classical univariate KS distance, which, as we have mentioned, is the MMD over the space of functions with total variation at most 1. Precisely, the RKS distance is the MMD over the function space \[\mathcal{F}_{k}=\Big{\{}f\in\mathrm{RBV}^{k}_{c}\,:\,\|f\|_{\mathrm{RTV}^{k}} \leq 1,\;\partial^{\alpha}f(0)\text{ exists and equals }0\text{ for all }|\alpha|\leq k\Big{\}}. \tag{7}\] The boundary condition \(\partial^{\alpha}f(0)=0\) for all multi-indices \(\alpha=(\alpha_{1},\dots,\alpha_{d})\) with \(|\alpha|=\sum_{j=1}^{d}\alpha_{j}\leq k\) is needed to guarantee that the MMD is finite. We can interpret this condition intuitively as requiring the polynomial \(q\) to be zero in the representation in Proposition 1. Otherwise, \(q\) would be able to grow without bound under the constraint \(\|f\|_{\mathrm{RTV}^{k}}\leq 1\), which we could then use to drive the MMD criterion to \(\infty\), provided that \(P\) and \(Q\) had any moment differences (in their first \(k\) moments). The following representation theorem proves that the RKS distance is the MMD over (7). **Theorem 2**.: _Fix any \(k\geq 0\). For any \(f\in\mathcal{F}_{k}\), there exists a finite, signed Borel measure \(\mu\) on \(\mathbb{S}^{d-1}\times[0,\infty)\) such that for all \(x\in\mathbb{R}^{d}\),_ \[f(x)=\int_{\mathbb{S}^{d-1}\times[0,\infty)}(w^{\mathsf{T}}x-b)_{+}^{k}\, \mathrm{d}\mu(w,b),\] _and \(\|\mu\|_{\mathrm{TV}}=\|f\|_{\mathrm{RTV}^{k}}\). When \(k=0\), the measure \(\mu\) may be taken to be supported on \(\mathbb{S}^{d-1}\times(0,\infty)\)._ We prove Theorem 2 in Appendix C. Note that the representation provided by Theorem 2 is like that in Proposition 1 except that the integral is restricted to \(b\geq 0\), and the polynomial term is \(q=0\). The latter is a consequence of the boundary condition imposed in the definition of \(\mathcal{F}_{k}\). Finally, the next theorem establishes the equivalence between \(T_{d,k}\) as defined in (2) and the MMD over \(\mathcal{F}_{k}\). Its proof is in Appendix D. **Theorem 3**.: _Fix any \(k\geq 0\). Define_ \[\mathcal{G}_{k}=\Big{\{}(w^{\mathsf{T}}\cdot-b)_{+}^{k}\,:\,(w,b)\in\mathbb{S }^{d-1}\times[0,\infty)\Big{\}},\] _where by convention we take \(t_{+}^{0}=1\{t\geq 0\}\). Then for any \(P\) and \(Q\) with finite \(k^{\text{th}}\) moments, we have_ \[\rho(P,Q;\mathcal{F}_{k})=\rho(P,Q;\mathcal{G}_{k}).\] _In particular, this implies that for the empirical distributions \(P_{m}\) and \(Q_{n}\) over any sets of samples \(\{x_{i}\}_{i=1}^{m}\) and \(\{y_{i}\}_{i=1}^{n}\), we have \(\rho(P_{m},Q_{n};\mathcal{F}_{k})=T_{d,k}\), where the latter is as defined in (2)._ ### The RKS distance identifies the null An important property of the RKS distance for the purposes of two-sample testing is its ability to distinguish any two distinct distributions. In particular, we have the following result, whose proof is in Appendix E. **Theorem 4**.: _For any \(P,Q\) with finite \(k^{\text{th}}\) moments, \(\rho(P,Q;\mathcal{F}_{k})=0\) if and only if \(P=Q\), and is positive otherwise._ Theorem 4 states that the RKS distance, in the population, perfectly distinguishes the null \(H_{0}:P=Q\) from the alternative \(H_{1}:P\neq Q\). Thus, the function space \(\mathcal{F}_{k}\) is rich enough to make the MMD a _metric_ at the population level. As an interesting contrast, we remark that this is not true of the kernel MMD with a polynomial kernel of degree \(k\), as studied in Gretton et al. (2012). Indeed, if \(P\) and \(Q\) have the same moments up to order \(k\) (where "moments" is to be interpreted in the appropriate multivariate sense) then the kernel MMD in the population between \(P\) and \(Q\) is 0. In other words, we can see that the use of _truncated_ moments, as given by averages of ridge splines, is the key to the discrepancy being a metric. ## 3 Asymptotics Given any probability distribution \(P\) on \(\mathbb{R}^{d}\) with finite \((2k+\Delta)\)-moments for some \(\Delta>0\), let us define the corresponding Gaussian process \(\mathbb{G}_{P}=\{G_{w,b}:(w,b)\in\mathbb{S}^{d-1}\times[0,\infty)\}\) by \[G_{w,b}\sim\mathcal{N}\Big{(}0,\,\mathbb{E}_{x\sim P}\big{[}(w^{\top}x-b)_{+}^ {2k}\big{]}\Big{)},\quad\mathrm{Cov}(G_{w,b},G_{w^{\prime},b^{\prime}})= \mathbb{E}_{x\sim P}\Big{[}(w^{\top}x-b)_{+}^{k}(w^{\prime\top}x-b^{\prime})_{+ }^{k}\Big{]}. \tag{8}\] The importance of this Gaussian process is explained in the next result, which shows that its supremum provides the asymptotic null distribution of the RKS test statistic. **Theorem 5**.: _Fix any \(k\geq 0\). Assume that \(P\) has finite \((2k+\Delta)\)-moments for some \(\Delta>0\). If \(k=0\), then additionally assume that \(P\) has bounded density with respect to Lebesgue measure. When \(P=Q\), we have_ \[\sqrt{\frac{mn}{m+n}}\,T_{d,k}\,\stackrel{{ d}}{{\to}}\,\sup_{(w,b)\in\mathbb{S}^{d-1}\times[0,\infty)}\,|G_{w,b}|,\quad\text{as }m,n\to\infty.\] Moreover, with a proper rejection threshold, the RKS test can have asymptotically zero type I error and full power against any fixed \(P\neq Q\). **Theorem 6**.: _Fix any \(k\geq 0\). Assume \(P,Q\) have finite \((2k+\Delta)\)-moments for some \(\Delta>0\). If \(k=0\), then additionally assume that \(P,Q\) have bounded densities with respect to Lebesgue measure. Let \(p=m+n\) and consider any sequence \(t_{p}\) such that \(t_{p}\to 0\) and \(t_{p}\sqrt{p}\to\infty\) as \(m,n\to\infty\). Then the test which rejects when \(T_{d,k}>t_{p}\) rejects with asymptotic probability 0 if \(P=Q\) and asymptotic probability 1 if \(P\neq Q\)._ We prove Theorems 5 and 6 in Appendices F and G. Roughly, Theorem 5 follows from general uniform central limit theorem results in Dudley (2014), after controlling the bracketing number of the function class \(\mathcal{G}_{k}\). Theorem 6 follows from tail bounds that we establish for the concentration of the RKS distance around its population value, combined with the fact that the population distance is a metric (Theorem 4). ## 4 Experiments We conduct experiments to compare the power of the RKS test with other multivariate nonparametric tests in multiple settings (different pairs of \(P\) and \(Q\)), both to investigate the strengths and weaknesses of the RKS test, and to investigate its behavior as we vary the smoothness degree \(k\). ### Computation of the RKS distance First, we discuss computation of the RKS distance, as initially defined in (2). This a difficult optimization problem because of the nonconvexity of the criterion and the unit \(\ell_{2}\) norm constraint on \(w\). Though we will not be able to circumvent the challenge posed by nonconvexity entirely, we can ameliorate it by moving to the overparametrized formulation in (5): this now casts the same computation as an optimization over the \(N\)-neuron neural network \(f\) in (4), subject to a constraint on \(\sum_{j=1}^{N}|a_{j}|\|w_{j}\|_{2}^{k}\) (which is sometimes called the "path norm" of \(f\)). We call this problem "overparametrized" since any individual pair \((w_{j},b_{j})\) would be sufficient to obtain the global optimum in (2), and yet we allow the optimization to search over \(N\) such pairs \((w_{j},b_{j})\), \(j=1,\ldots,N\). Perhaps unsurprisingly, we find that overparametrization (larger \(N\)) generally makes optimization easier--more stable with respect to the initialization and choice of learning rate, discussed in more detail in Appendix K. Problem (5) is still more difficult than we would like it to be, i.e., not within scope for typical first-order optimization techniques, due to the path norm constraint \(\sum_{j=1}^{N}|a_{j}|\|w_{j}\|_{2}^{k}\leq 1\). Fortunately, it is easy to see that any bound here suffices to compute the RKS distance: we can instead use \(\sum_{j=1}^{N}|a_{j}|\|w_{j}\|_{2}^{k}\leq C\), for any \(C>0\), rescale the criterion \(P_{m}(f)-Q_{n}(f)\) by \(1/C\), and then the value of the criterion at its optimum (the MMD value) is unchanged. This motivates us to instead solve a Lagrangian version of (5): \[\min_{\begin{subarray}{c}f=f_{(a_{j},w_{j},b_{j})_{j=1}^{N}}\\ (a_{j},w_{j},b_{j})\in\mathbb{R}\times\mathbb{R}^{d}\times[0,\infty)\end{subarray}} -\log\Big{(}|P_{m}(f)-Q_{n}(f)|\Big{)}+\lambda\sum_{i=1}^{N}|a_{i}|\|w_{i}\|_ {2}^{k}, \tag{9}\] which is the focus in all of our experiments henceforth. The use of a log transform for the mean difference in (9) is primarily used because we find that it leads to a greater stability with respect to the choice of learning rate (Appendix J). Importantly, the choice of Lagrangian parameter \(\lambda>0\) in (9) can be arbitrary, by the same rescaling argument as explained above: given any (local) optimizer \(f^{*}\) in (9), we can simply return the mean difference over the rescaled witness \(f^{*}/\|f^{*}\|_{\mathrm{RTV}^{k}}\), where \(\|f^{*}\|_{\mathrm{RTV}^{k}}=\sum_{i=1}^{N}|a_{i}^{*}|\|w_{i}^{*}\|_{2}^{k}\). For \(k\geq 1\), we apply the Adam optimizer (a variant of gradient descent), as implemented in PyTorch, to (9). In our experiments that follow, we use \(N=10\) neurons and a few hundred iterations of Adam. On the other hand, for \(k=0\), such a first-order scheme is not applicable due to the fact that the gradient of the \(0^{\text{th}}\) degree ridge spline \((w^{\mathsf{T}}x-b)_{+}^{0}=1\{w^{\mathsf{T}}x\geq b\}\) (with respect to \(w,b\)) is almost everywhere zero. Therefore, as a surrogate, we instead approximate the optimum \(w^{*},b^{*}\) in (2) using logistic regression. Appendix I provides further details on the optimization setup, and Appendices J and K present related sensitivity analyses. ### Experimental setup We compare the RKS tests of various degrees across several experimental settings, both to one another and to other all-purpose nonparametric tests: the energy distance test (Szekely and Rizzo, 2005) as well as kernel MMD (Gretton et al., 2012) with a Gaussian kernel. We fix the sample sizes to \(m=n=512\) throughout, and consider four choices of dimension: \(d=2,4,8,16\). For each dimension \(d\), we consider five settings for \(P,Q\), which are described in Table 1. In each setting, the parameter \(v\) controls the discrepancy between \(P\) and \(Q\), but its precise meaning depends on the setting. The settings were broadly chosen in order to study the operating characteristics of the RKS test when differences between \(P\) and \(Q\) occur in one direction (settings 1-4), and in all directions (setting 5). Among the settings in which the differences occur in one direction, we also investigate different varieties (settings 1 and 2: mean shift under different geometries, setting 3: tail difference, setting 4: variance difference). Finally, we note that because the RKS test is _rotationally invariant_,2 the fact that the chosen differences in Table 1 are axis-aligned is just a matter of convenience, and the results would not change if these differences instead occurred along arbitrary directions in \(\mathbb{R}^{d}\). Footnote 2: Meaning, \(\rho(P_{m},Q_{n};\mathcal{F}_{k})\) is invariant to rotations of the underlying samples \(\{x_{i}\}_{i=1}^{m}\) and \(\{y_{i}\}_{i=1}^{n}\) by any arbitrary orthogonal transformation \(U\in\mathbb{R}^{d\times d}\). This is true because the RTV\({}^{k}\) seminorm is itself invariant to rotations of the underlying domain, as can be seen directly from the representation in Proposition 1. For the RKS tests, we examine smoothness degrees \(k=0,1,2,3\); for kernel MMD, we set the Gaussian kernel bandwidth according to a standard heuristic based on the median of all pairwise squared distances between the input samples (Caputo et al., 2002). (The energy distance test has no tuning parameters.) For each setting, we compute these test statistics under the null where each \(x_{i}\) and \(y_{i}\) are sampled i.i.d. from the mixture \(\frac{m}{m+n}P+\frac{n}{m+n}Q\), and under the alternative where \(x_{i}\) are i.i.d. from \(P\) and \(y_{i}\) from \(Q\). We then repeat this 100 times (draws of samples, and computation of test statistics), and trace out ROC curves--true positive versus false positive rates--as we vary the rejection threshold for each test. Python code to replicate our experimental results is available at [https://github.com/100shpaik/](https://github.com/100shpaik/). In Appendix L, we also compare the RKS test to kernel MMD with a polynomial kernel. Importantly, the latter is not actually a nonparametric test, for any finite polynomial order, since the population MMD \begin{table} \begin{tabular}{|c||c|c|c|} \hline Setting & \(P\) & \(Q\) & \(v\) \\ \hline Pancake mean shift & one axis \(\sim\mathcal{N}(0,1)\) & one axis \(\sim\mathcal{N}(v,1)\) & \\ (“pancake-shift”) & the others \(\sim\mathcal{N}_{d-1}(0,16I)\) & the others \(\sim\mathcal{N}_{d-1}(0,16I)\) & 0.3 \\ \hline Ball mean shift & \multirow{2}{*}{\(\mathcal{N}_{d}(0,I)\)} & one axis \(\sim\mathcal{N}(v,1)\) & \\ (“ball-shift”) & & the others \(\sim\mathcal{N}_{d-1}(0,I)\) & 0.2 \\ \hline \(t\) coordinate & \multirow{2}{*}{\(\mathcal{N}_{d}(0,I)\)} & one axis \(\sim t(v)\) & \\ (“t-coord”) & & the others \(\sim\mathcal{N}_{d-1}(0,I)\) & 3 \\ \hline Variance inflation & \multirow{2}{*}{\(\mathcal{N}_{d}(0,I)\)} & one axis \(\sim\mathcal{N}(0,v)\) & \\ in one direction & & the others \(\sim\mathcal{N}_{d-1}(0,I)\) & 1.4 \\ (“var-one”) & & \\ \hline Variance inflation & \multirow{2}{*}{\(\mathcal{N}_{d}(0,I)\)} & \multirow{2}{*}{\(\mathcal{N}_{d}(0,vI)\)} & \multirow{2}{*}{1.2} \\ in all directions & & \\ (“var-all”) & & & \\ \hline \end{tabular} \end{table} Table 1: Experimental settings. Here \(\mathcal{N}(\mu,\Sigma)\) means the normal distribution with mean \(\mu\) and covariance \(\Sigma\), and \(t(v)\) means the \(t\) distribution with \(v\) degrees of freedom. does not define a metric (it cannot distinguish distributions \(P,Q\) that agree up to some number of moments, interpreted in the multivariate sense, but differ otherwise). We include comparisons to polynomial kernels for completeness nonetheless. ### Experimental results Figure 2 displays the ROC curves from all tests across all settings (rows) and all dimensions (columns). We see that in the first four settings (first four rows), the RKS tests exhibit generally strong performance: in each case, one of the \(k^{\text{th}}\) degree RKS tests performs either the best or near-best among the methods considered. This supports the intuition discussed earlier, since in each of these settings, \(P\) and \(Q\) differ in only a small number (in fact, one) direction. Conversely, in the last setting, "var-all", the distributions \(P\) and \(Q\) differ by a small amount in all directions, and the Gaussian kernel MMD and energy distance tests outperform the RKS tests, especially for larger \(d\). Keeping in mind that larger choices of \(k\) correspond to higher-order truncated moments, we can further inspect the first four settings to try to learn from why the different order RKS tests perform better or worse. In the "pancake-shift" setting, the mean shift occurs in a low-variance direction, leading to nearly separable classes, so the smallest choice \(k=0\) performs best, and better than kernel-based tests. In the "var-one" and "t-coord" settings, \(P\) and \(Q\) have the same mean, but different variance or tails, respectively, in one direction. Thus, larger choices of \(k\) perform better: \(k=1\) for "t-coord", and \(k=2,3\) for "var-one". For a mean shift of between isotropic Gaussians, "ball-shift", degrees \(k=0,1,2\) are all reasonably competitive. ## 5 Discussion We proposed and analyzed a new multivariate, nonparametric two-sample test, which is a maximum mean discrepancy (MMD) test with respect to a class of functions having unit Radon total variation, of a given smoothness degree \(k\geq 0\). We call this the Radon-Kolmogorov-Smirnov (RKS) test, and it generalizes the well-known Kolmogorov-Smirnov (KS) test to multiple dimensions and higher orders of smoothness. The RKS test, like any statistical test, is not expected to be most powerful in all scenarios. Roughly, we expect the RKS test to be favorable in settings in which the given distributions \(P\) and \(Q\) differ in only a few directions in the ambient space; and higher orders of smoothness \(k\) can be more sensitive to tail differences along these few directions. When \(P\) and \(Q\) differ in many or all directions, the more traditional kernel MMD test with (say) Gaussian kernel will probably perform better. It is worth revisiting computation of the RKS distance and discussing some limitations of our work and possible future directions. In this paper, we considered _full batch_ gradient descent applied to (9) (we actually used Adam, but the differences for this discussion are unimportant), i.e., in each update the entire data set \(\{x_{i}\}_{i=1}^{m}\cup\{y_{i}\}_{i=1}^{n}\) is used to calculate the gradient. This results in the following complexity: \(T\) iterations of gradient descent costs \(O((n+m)dNT)\) operations, where recall \(N\) is the number of neurons. However, _mini batch_ gradient descent should be also investigated, and is likely to be preferred in large problem sizes. That said, implementing mini batch gradients for (9) is nontrivial due to the nonseparable nature of the criterion across observations (due to the log and the absolute value in the first term), and pursuing this carefully is an important direction for future work. For now, we note that by just subsetting \(P_{m},Q_{n}\) to a mini batch of size \(b\leq n+m\), this results in a \(T\) iteration complexity of \(O(bdNT)\) operations. To compare kernel MMD: this costs \(O((n+m)^{2}d)\) operations, and thus we can see that for large enough problem sizes computation of the RKS statistic via full batch and especially mini batch gradient descent can be more efficient, provided that small or moderate values of \(N,T\) still suffice to obtain good performance. Finally, another direction worth pursuing is the use of deeper networks, which could be interpreted as learning the feature representation in which there is the largest discrepancy in projected truncated moments. This would help further distinguish the RKS test from kernel MMD, because the latter is "stuck with" the representation provided by the choice of kernel, and it cannot learn the representation based on the data. A deep RKS test could dovetail nicely with existing architectures (and even pre-trained networks) for related tasks in areas such as generative modeling, and out-of-distribution detection. Figure 2: ROC curves across the experimental settings described in Table 1. Each row represents a different setting, and each column a different dimension. The RKS, kernel MMD (KMMD), and energy distance tests are compared (each coded by a combination of color and line type). ### Acknowledgments We thank Rahul Parhi and Jonathan Siegel and helpful discussions about Radon bounded variation spaces. This work was supported by NSF SCALE MoDL grant 2134133, ONR MURI grant N00014-20-1-2787, and the Miller Institute for Basic Research in Science at the University of California, Berkeley.
2302.01259
Geometric Deep Learning for Autonomous Driving: Unlocking the Power of Graph Neural Networks With CommonRoad-Geometric
Heterogeneous graphs offer powerful data representations for traffic, given their ability to model the complex interaction effects among a varying number of traffic participants and the underlying road infrastructure. With the recent advent of graph neural networks (GNNs) as the accompanying deep learning framework, the graph structure can be efficiently leveraged for various machine learning applications such as trajectory prediction. As a first of its kind, our proposed Python framework offers an easy-to-use and fully customizable data processing pipeline to extract standardized graph datasets from traffic scenarios. Providing a platform for GNN-based autonomous driving research, it improves comparability between approaches and allows researchers to focus on model implementation instead of dataset curation.
Eivind Meyer, Maurice Brenner, Bowen Zhang, Max Schickert, Bilal Musani, Matthias Althoff
2023-02-02T17:45:02Z
http://arxiv.org/abs/2302.01259v2
Geometric Deep Learning for Autonomous Driving: Unlocking the Power of Graph Neural Networks With CommonRoad-Geometric ###### Abstract Heterogeneous graphs offer powerful data representations for traffic, given their ability to model the complex interaction effects among a varying number of traffic participants and the underlying road infrastructure. With the recent advent of graph neural networks (GNNs) as the accompanying deep learning framework, the graph structure can be efficiently leveraged for various machine learning applications such as trajectory prediction. As a first of its kind, our proposed Python framework offers an easy-to-use and fully customizable data processing pipeline to extract standardized graph datasets from traffic scenarios. Providing a platform for GNN-based autonomous driving research, it improves comparability between approaches and allows researchers to focus on model implementation instead of dataset curation. ## I Introduction Machine learning agents require an accurate understanding of the surrounding traffic context to make safe and effective decisions [1]. This calls for a descriptive representation not only of the various entities within the traffic environment, but also their complex spatial and temporal relationships. When restricted to a fixed-size feature space--a prerequisite for classical neural networks--this is a particularly challenging prospect given the inherent complexity and variability in road geometries and traffic situations. An alternative approach is to model the environment state in the form of a heterogeneous graph, encompassing both the road network topology and the traffic participants present in it. This structured representation allows us to capture a wide range of road networks and traffic scenarios with a variable number of discrete elements. Additionally, it enables the explicit modeling of pairwise relationships or interactions between entities through edge connections. Graph neural networks (GNNs) have recently emerged as the principal deep learning framework for processing graph data [2, 3, 4, 5]. By using GNNs, the graph topology can be exploited as a relational inductive bias [5] during training, aiding generalization. ### _Related work_ Graph-structured representations of traffic proposed in existing works differ based on the objectives of the learning task. In [6], the authors let nodes represent individual road segments with edges forming the overarching road network topology for driving speed estimation and road network classification. Alternatively, [7] and [8] present graph-based traffic forecasting approaches in which nodes are used to model traffic participants and edges are used to capture vehicle interactions. Similarly, [9] and [10] adopt vehicle-to-vehicle GNNs as policy networks for reinforcement learning agents. Additionally considering the temporal dimension, [11] employs a spatiotemporal vehicle graph for capturing time-dependent features. Finally, recent works [12, 13, 14, 15, 16, 17, 18, 19, 20] incorporate both vehicle and map nodes by modelling the environment as a heterogeneous graph, including both inter-vehicle as well as vehicle-road interaction effects. ### _Motivation and contributions_ Despite the vast research interest, there is no software framework that offers an interface for extracting custom graph datasets from traffic scenarios. Although there are plenty of autonomous driving datasets, e.g. [21, 22, 23], researchers have to write considerable amounts of ad-hoc, error-prone conversion code to use them as inputs for GNN models. As evident by the success in other application domains such as bioinformatics and social networks [24, 25], standardized graph datasets would enable autonomous driving researchers to streamline their experiments and ensure comparability and repeatability of their results. To fill this gap, we propose _CommonRoad-Geometric (cr-geo)_: a Python library designed to facilitate the extraction of graph data from recorded or simulated traffic scenarios. Our framework extends the _CommonRoad_[26] software platform and uses its standardized interface for a high-level representation of the traffic environment. As illustrated by Fig. 1, our framework unifies the traffic scene into a single graph entity, encompassing both the traffic participants and the underlying road map. The extracted graph representations are based on the HeteroData class offered by _PyTorch-Geometric_[27], a popular _PyTorch_[28] extension for deep learning on graph-structured data. Our paper offers the following contributions: * we introduce a heterogeneous graph structure for map-aware traffic representations tailored to GNN applications; * we present and outline the software architecture of _CommonRoad-Geometric (cr-geo)_, which offers a bridge from the well-established CommonRoad scenario format to _PyTorch-Geometric (PyG)_; * as a concrete example of the wide range of GNN-based applications facilitated by _cr-geo_, we train a spatiotemporal trajectory prediction model on a real-world graph dataset extracted from NuPlan [23]. ## II Background We first provide some background on heterogeneous graphs and the description of scenarios in CommonRoad. #### Ii-1 Heterogeneous graphs A directed heterogeneous graph \(\mathcal{G=(V,E,A,R,X_{V},X_{E})}\) is defined as a tuple of a set of nodes \(\mathcal{V}\), edges \(\mathcal{E}\), node types \(\mathcal{A}\), edge types \(\mathcal{R}\), and corresponding node and edge features \(\mathcal{X}_{\mathcal{V}}\) and \(\mathcal{X}_{\mathcal{E}}\)[29]. Edges are defined as a 3-tuple \(\mathcal{E\subset V\times R\times V}\). Further, each node \(v\in\mathcal{V}\) is assigned a node type via the mapping \(\tau_{V}(v):\mathcal{V\rightarrow A}\). Analogously, edges \(e\in\mathcal{E}\) are associated with an edge type \(\tau_{\mathcal{E}}(e):\mathcal{E\rightarrow R}\). Finally, \(\mathcal{X}_{\mathcal{V}}\) and \(\mathcal{X}_{\mathcal{E}}\) contain the feature vectors, which we denote as \(\mathbf{x}_{v}\in\mathbb{R}^{D_{\mathcal{V}}}\) for node features and \(\mathbf{x}_{e}\in\mathbb{R}^{D_{\mathcal{E}}}\) for edge features. Fig. 2 illustrates graph features on the node and edge level. #### Ii-2 CommonRoad A CommonRoad _scenario_ contains a set \(\mathcal{V}^{cr}\) of _dynamic obstacles_. For a vehicle \(V\in\mathcal{V}^{cr}\) of rectangular shape \((l_{V},w_{V})\), we represent its time-dependent state by its x-y center position \(\mathbf{p}_{V}\), its orientation \(\theta_{V}\), as well as their time derivatives in the scenario coordinate frame. Further, the map-related information of a scenario is described by its _lanelet network_, containing a set \(\mathcal{L}^{cr}\) of atomic _lanelets_ and their longitudinal and lateral adjacency relations [30]. Lanelets are geometrically defined by their boundary polylines. For a lanelet \(L\in\mathcal{L}^{cr}\), we denote its left and right boundary polylines as \(S_{L,l}\) and \(S_{L,r}\), respectively. Further, we denote the center polyline as \(S_{L,c}\). Each polyline is made up of a sequence of \(N_{L}\) waypoints in the scenario coordinate frame. Using the notation \(\langle\square_{i}\rangle_{i\in 1,\ldots,N}\) to define a sequence of values of length \(N\), we let the polylines be denoted as \(S_{L,l}=\langle\vec{s}_{i,i}\rangle_{i\in 1,\ldots,N_{L}}\), \(S_{L,r}=\langle\vec{s}_{r,i}\rangle_{i\in 1,\ldots,N_{L}}\), and \(S_{L,c}=\langle\vec{s}_{c,i}\rangle_{i\in 1,\ldots,N_{L}}\). With \(\|\|_{2}\) denoting the L2-norm, we further define the lanelet length as \[\|L\|_{2}=\sum_{i=1}^{N_{L}-1}\sqrt{\|\vec{s}_{c,i+1}-\vec{s}_{c,i}\|_{2}}, \tag{1}\] ## III Overview In the following subsections, we define the structure of our traffic graph and outline the software architecture of our framework. ### _Traffic graph structure_ Extending _PyG_'s HeteroData1, _cr-geo_'s CommonRoadData class represents a heterogeneous traffic graph encapsulating nodes of both the vehicle (v) and lanelet (l.) node type, as well as the structural metadata for the specific graph instance. Formally, we have that \(\mathcal{A=\{v,L\}}\) and \(\mathcal{R=\{L2,v2v,v2L,12v\}}\). Footnote 1: [https://pytorch-geometric.readthedocs.io/en/latest/modules/data.html#torch.geometric.data.Heter0data](https://pytorch-geometric.readthedocs.io/en/latest/modules/data.html#torch.geometric.data.Heter0data) In order to capture temporal vehicle interactions with GNN-based message-passing schemes, we further extend the CommonRoadData class by the time dimension with CommonRoadTemporalData, where \(\mathcal{R}\) is augmented by the temporal vtv edge type. The resulting _temporal graph_[31], as shown in Fig. 3, intrinsically encodes the temporal dimension by unrolling the traffic graph over time. Vehicle nodes are repeated to capture vehicle states at past timesteps, and temporal edges encode the time difference between them. Fig. 1: Our package serves as a bridge from CommonRoad to PyTorch-Geometric. The abbreviated graph labels refer to the heterogeneous node and edge entities of our unified traffic graph structure covered in Section III-A. Fig. 2: Illustration of a simple graph structure. Edge types are represented as different colors. Colored squares represent features vectors for nodes (e.g., vehicle speed) and edges (e.g., distance between vehicles). The heterogeneous structure of our graphical data representation is summarized in Tab. II and outlined in the following paragraphs: #### Iii-B1 Lanelet nodes \((\mathcal{V}_{L})\) Lanelet nodes map to the lanelets in \(\mathcal{L}^{cr}\), with each lanelet \(L\) being represented as a graph node. The corresponding node features encode the geometric properties of the respective lanelets. Using the general notation \({}^{L}\square\), we denote the lanelet-local transformed polyline coordinates as \({}^{L}S_{L,l}\), \({}^{L}S_{L,c}\), and \({}^{L}S_{L,r}\). Here, the vertex coordinates are transformed to the lanelet-local coordinate frame according to its origin position \(\mathbf{p}_{L}=\vec{s}_{c,1}\) and its orientation \(\theta_{L}=\mathrm{atan2}\left(\nicefrac{{s_{c,2}}}{{s_{c,1}}}\right)\). In the following, we also let the function interpretations \(\tilde{S}_{L,\square}(\cdot)\) and \(\tilde{\theta}_{L}(\cdot)\) be defined via orthogonal projections onto the polylines, returning the position and orientation at a given arclength, respectively. #### Iii-B2 Lanelet-to-lanelet edges \((\mathcal{E}_{\mathrm{l2L}})\) Lanelet-to-lanelet edges characterize the lanelet network topology and encode the spatial relationship between adjacent lanelets. As illustrated by Fig. 4, we explicitly differentiate between the heterogeneous L2L adjacency types \(\mathcal{R}_{\mathrm{l2L}}\) listed in Tab. I via the edge feature \(\tau_{\mathcal{E}}\). For an edge from \(L\) to \(L^{{}^{\prime}}\), we also include their centerline arclength distance at the point of intersection as edge features, which we denote by \(s_{L}\) and \(s_{L^{\prime}}\). This is highlighted in Fig. 4c for two conflicting lanelets. #### Iii-B3 Vehicle nodes \((\mathcal{V}_{V})\) Vehicle nodes are inserted according to the states of the currently present vehicles and identified by their CommonRoad IDs. As shown in Fig. 3, CommonRoadTemporalData additionally includes past vehicle states in the graph representation: here, a vehicle's state history is captured by time-attributed (but otherwise identical) vehicles nodes inserted at each timestep. #### Iii-B4 Vehicle-to-vehicle edges \((\mathcal{E}_{\mathrm{v2v}})\) Vehicle-to-vehicle edges capture the interaction between vehicles at each timestep. The relative pose of connected vehicles is encoded as edge features according to the vehicle-local coordinate frame originating at the center of the source vehicle. Users can provide a specific implementation of our v2v _edge drawer_ protocol to encode which v2v relations are relevant for their task. Our framework offers developers a set of standard edge drawer implementations, two of which are depicted in Fig. 5. #### Iii-B5 Vehicle-to-lanelet edges \((\mathcal{E}_{\mathrm{v2L}})\) Vehicle-to-lanelet edges relate vehicles to the underlying road infrastructure. Our framework offers two assignment strategies for drawing the edges: 1. **Center**: Each vehicle is connected to all lanelets that contain the vehicle center point. 2. **Shape**: Each vehicle is connected to all lanelets that intersect with the vehicle shape. This constitutes a superset of the edges drawn by the _Center_ strategy. The associated edge features describe the relative pose of the vehicle with respect to the curvilinear lanelet coordinate frame [32]. For a given edge from vehicle \(V\) to lanelet \(L\), we denote the orthogonal distance from the lanelet's left and right boundaries to the vehicle center as \[\begin{split} d^{L}_{V,l}&=\|\tilde{S}_{L,l}(\mathbf{ p}_{V})-\mathbf{p}_{V}\|_{2},\\ d^{L}_{V,r}&=\|\tilde{S}_{L,r}(\mathbf{p}_{V})- \mathbf{p}_{V}\|_{2}.\end{split} \tag{2}\] \begin{table} \begin{tabular}{c c} \hline \hline **Type** & **Interpretation** \\ \hline predecessor & \(L\) continues the driving corridor of \(L^{\prime}\) \\ successor & \(L^{\prime}\) continues the driving corridor of \(L\) \\ adjacent left & \(L\) is left-adjacent to \(L^{\prime}\) \\ adjacent right & \(L\) is right-adjacent to \(L^{\prime}\) \\ merging & \(L\) and \(L^{\prime}\) share a common successor (symmetric) \\ diverging & \(L\) and \(L^{\prime}\) share a common predecessor (symmetric) \\ conflicting & \(L\) and \(L^{\prime}\) cross each other (symmetric) \\ \hline \hline \end{tabular} \end{table} TABLE I: L2L adjacency types for edges \(L\to L^{\prime}\). The considered adjacency types can be individually selected at the user’s preference. Fig. 3: Visualization of Voronoi-based v2v and causal vtv edges for a highway scenario. Opaque colors denote the most recent edges while more transparent shades represent older ones. Further, we define the signed offset from the centerline as \[d_{V,e}^{L}=\frac{d_{V,l}^{L}-d_{V,r}^{L}}{2} \tag{3}\] and let \(s_{V}^{L}\in[0,\|L\|_{2}]\) denote the centerline arclength from the lanelet origin \(\mathbf{p}_{L}\) to \(\tilde{S}_{L,c}(\mathbf{p}_{V})\). Finally, the orientation difference is given by \[\theta_{V,e}^{L}=\tilde{\theta}_{L}(\mathbf{p}_{V})-\theta_{V}. \tag{4}\] #### Iii-A6 Vehicle-temporal-vehicle edges \((\mathcal{E}_{\textsc{vtv}})\) CommonRoadTemporalData additionally contains temporal vehicle edges for encoding temporal dependencies in the traffic graph: Letting \(v_{t}\) and \(v_{t^{{}^{\prime}}}\) denote two vehicle nodes emerging from one vehicle instance, a temporal edge \(e\in\mathcal{E}_{\textsc{vtv}}\) connects the vehicle object to itself at two different timesteps, as illustrated by Fig. 3. The temporal separation between the nodes is defined as the elapsed time \(\Delta t_{e}=t-t^{{}^{\prime}}\). As for v2v, _cr-geo_ lets users specify a custom _temporal edge drawer_ for defining the exact vtv graph structure. The default CausaEdgeDrawer inserts directed temporal edges between a historic vehicle node and its future realization at up to \(T_{max}^{\textsc{vtv}}\) future time steps. This constrains the flow of the vtv edges to be forward in time. ### _Software architecture_ Next, we outline the principal components of our software architecture in a bottom-up approach, by detailing the pipeline for collecting graph datasets from CommonRoad scenarios. An architecture overview is given by Fig. 6. #### Iv-A2 Scenario preprocessing and filtering Our framework supports arbitrary preprocessing and filtering of the input scenarios to ensure that they satisfy the user requirements. As an example, TrafficFilter(min=10) lets users exclude scenarios with less than \(10\) vehicles from the collected graph dataset. Further, suppose that we want a higher-fidelity view of the lanelet network, where no lanelet exceeds \(20\) meters in length: this can be achieved by using _cr-geo_'s built-in SegmentLanelets_preprocessor_, which results in a higher lanelet node density. Using our composition syntax that realizes arbitrary chaining and grouping of preprocessing and filtering operations, these behaviors can be effortlessly combined via TrafficFilter(min=10) > SegmentLanelets(size=20). #### Iv-A3 Feature extraction The extraction of the graph features, i.e., \(\mathcal{X}_{\mathcal{V}}\) and \(\mathcal{X}_{\mathcal{E}}\), is carried out through _feature extractors_ operating on the scenario objects. The feature extractors receive a _simulation_ object, which provides access to inherent and derived state information of the scenario at the current timestep. By maintaining an internal state, feature extractors also support time-dependent features. In our framework, we distinguish between node- and edge-level feature extractors, with the latter operating on pairs of entities according to \(\mathcal{E}\). In accordance with _cr-geo_'s guiding design principles, users can devise their own implementation to augment the extracted graphs by arbitrary custom features without modifying the _cr-geo_ source code. To reduce the initial setup time for new users, _cr-geo_ also offers users a selection of pre-configured feature extractor implementations designed to meet the most common needs and requirements. #### Iv-A4 Postprocessors In contrast to the aforementioned node- and edge-level feature extractors, _postprocessors_ operate directly on the graph instances in a deferred manner. As such, they are intended to supplement the flexibility we concede in the otherwise rigorous graph extraction procedure. User-devised postprocessing procedures can serve numerous practical purposes, e.g., * to complement the functionality of feature extractors by facilitating the computation of graph-global features, e.g., an indicator for whether the current traffic scene corresponds to a traffic jam or not; * to modify the graph structure, e.g., by the removal or insertion of nodes and edges. The postprocessors are executed after the initial graph extraction, but prior to dataset generation. Furthermore, they can also be applied while loading an existing dataset. #### Iv-A5 Traffic graph extraction The execution of edge drawing, feature extraction and postprocessing is orchestrated by a _traffic extractor_, which manages the creation of a CommonRoadData instance at a single timestep \(t\). It also handles the declaration of metadata attributes such as node IDs. The traffic extractor class is complemented by the _temporal traffic extractor_ for the purpose of extracting temporal graph representations. Internally relying on a regular traffic extractor, it maintains a cache of the \(n\) preceding ordinary CommonRoadData instances at all times. When called upon, it returns the CommonRoadTemporalData at the current timestep by merging the cached graph sequence into a single entity. The temporal extractor delegates the temporal edge construction to the provided _temporal edge drawer_ and the computation of custom temporal features to the vtv feature extractors provided by the user. The regular and temporal extraction procedures are summarized by Alg. 1 and Alg. 2, respectively. #### Iv-A6 Dataset creation Based on the provided traffic graph extractor, the _dataset collector_ offers an interface for generating a chronological sequence of graph instances from a specified scenario. The collector iterates over consecutive timesteps until it reaches the end of the scenario lifetime, dynamically returning the extracted graph objects. Whereas the static simulation mode corresponds to a replay of the recorded vehicle trajectories contained within the CommonRoad scenario, the interactive mode leverages an interactive traffic simulator for on-the-fly generation of realistic vehicle behavior. One such implementation is provided by the traffic simulation tool SUMO [36], which we access via our CommonRoad interface [37]. Finally, the creation and accessing of a persistent graph dataset collected from a set of input scenarios is facilitated by the CommonRoadDataset, a full-fledged extension of the powerful Dataset2 class natively offered by _PyG_. As such, Fig. 6: High-level software architecture for _cr-geo_ shown as a UML 2 component diagram [33]. our dataset class allows users to easily perform common data operations such as batching, sampling, and parallelization on the collected dataset during model training. As the individual graph instances inherit from the base data representation used by _PyG_, _cr-geo_ practitioners can effortlessly adopt their wide selection3 of state-of-the-art GNN architectures. The dataset creation procedure is summarized by Alg. 3. Footnote 3: [https://pytorch-geometric.readthedocs.io/en/latest/modules/](https://pytorch-geometric.readthedocs.io/en/latest/modules/) ``` Configuration: ``` ``` Configuration: ``` ``` Configuration: ``` Configuration: ``` ``` Configuration: ``` Configuration: ``` ``` ``` ``` ``` ``` ``` ``` ``` Configuration: ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` ``` \end{tabular} ``` ``` ``` ``` ``` ``` ``` \end{tabular} ``` ``` ``` ``` \end{tabular} ``` \end{tableular} ``` \end{table} ``` ``` \end{table} ``` \end{table} ``` \begin{tabular}{} \end{table} \end{table} \begin{tabular}{} \end{table} \begin{tabular}{} \end{table} \end{table} \begin{tabular}{} \end{table} \end{table} \begin{tabular}{} \end{table} \end{table} \begin{tabular}{} \end{table} \begin{tabular}{} \end{table} \end{table} \begin{tabular}{} \end{table} \end{table} \begin{tabular}{} \end{table} \begin{tabular}{} \end{table} \end{table} \begin{tabular}{} \end{table} \begin{tabular}{} \end{tabular} \end{table} \begin{tabular}{} \end{table} \end{table} \end{table} \begin{tabular}{} \end{table} \end{table} \end{table} \end{table} \begin{tabular}{} \end{table} \end{table} \end{table} \end{table} \begin{tabular}{} \end{table} \end{table} \end{table} \begin{tabular}{} \end{table} \end{table} \end{table} \end{table} \end{table} \end{table} \end{table} \end{table} ## IV Dataset and Experiment To demonstrate the usage of our framework, we published4 a graph-converted dataset with a diverse set of real-world road geometries. With the help of the dataset converter5, we use the NuPlan [23] dataset as our data source, due to the diversity in the incorporated locations and environments. The extracted graph dataset contains _cr-geo_'s default graph features as previously listed in Tab. II. Footnote 4: [https://commonroad.in.tum.de/datasets](https://commonroad.in.tum.de/datasets) Footnote 5: [https://commonroad.in.tum.de/tools/dataset-converters](https://commonroad.in.tum.de/tools/dataset-converters) ### _Experiment_ As an example use case of our framework, we briefly6 introduce a spatiotemporal GNN model for vehicle trajectory prediction based on our CommonRoadTemporalData environment representation. We implement an end-to-end trainable encoder-decoder architecture based on the message passing framework offered by _PyG_: Footnote 6: The model implementation can be found in the _cr-geo_ repository. #### Iv-A1 Encoder component The GNN encoder, for which we use an adapted version of the Heterogeneous Graph Transformer (HGT) architecture proposed in [38], computes a node-level embedding for each vehicle via message passing-based aggregation. This fixed-sized vector encoding summarizes the social and map-related information required to predict its future movement in the current traffic environment. In order to exploit all properties of the graph-structured data, we implement an edge-enhanced HGT architecture that computes attention weights and messages based on both node and edge features. To accelerate learning, we further carry out three (trainable) encoding steps that are applied before the graph convolution layers: * For encoding the delta-time attribute \(\Delta t_{e}\) of the vtv edges, we adopt Time2Vec [39], a learnable vector representation of time that lets us capture periodic and non-periodic time series patterns. * To get fixed-sized node representations for the lanelet geometries, we use a Gated Recurrent Unit (GRU) [40] which encodes the variable-length waypoint sequences \({}^{L}V_{l}\) and \({}^{L}V_{r}\). * Finally, we adopt a learnable vector embedding to encode the l2l adjacency type \(\tau_{\mathcal{E}}\). #### Iv-A2 Decoder component Based on the encoded vehicle representations, a GRU decoder network generates a fixed-length sequence of local position and orientation deltas for each vehicle, which is aggregated to obtain a sequence of predicted vehicles states. This is done by repeatedly updating the decoded vehicle state by a local transition in the coordinate frame of the previous state. The model is trained to minimize the average displacement error (ADE) between the predicted and ground-truth vehicle trajectories. An example of the resulting predictions with a prediction horizon of \(1.0~{}\mathrm{s}\) and a time interval of \(0.2~{}\mathrm{s}\) is shown in Fig. 8, whereas the quantitative results are summarized in Tab. IV. ## V Conclusion This paper presents _cr-geo_, an open-source Python package offering a standardized interface for map-aware graph extraction from traffic scenarios. As a pioneering effort, it serves as a flexible framework that lets users collect custom graphical PyTorch datasets tailored to their research needs. Exemplified by our trajectory prediction implementation, it minimizes the time spent by researchers on writing boilerplate code for dataset collection. _cr-geo_ complements the CommonRoad software platform, which offers a converter tool for popular traffic datasets. With ease of use and extension being our core design goals, _cr-geo_'s flexible interface is achieved by delegating and encapsulating all steps of the traffic graph creation. We invite researchers to contribute to _cr-geo_ to further enhance its capabilities. ## Acknowledgements This research was funded by the German Research Foundation grant AL 1185/7-1 and the Federal Ministry for Digital and Transport through the project KoSi.
2303.07273
Control of synaptic plasticity in neural networks
The brain is a nonlinear and highly Recurrent Neural Network (RNN). This RNN is surprisingly plastic and supports our astonishing ability to learn and execute complex tasks. However, learning is incredibly complicated due to the brain's nonlinear nature and the obscurity of mechanisms for determining the contribution of each synapse to the output error. This issue is known as the Credit Assignment Problem (CAP) and is a fundamental challenge in neuroscience and Artificial Intelligence (AI). Nevertheless, in the current understanding of cognitive neuroscience, it is widely accepted that a feedback loop systems play an essential role in synaptic plasticity. With this as inspiration, we propose a computational model by combining Neural Networks (NN) and nonlinear optimal control theory. The proposed framework involves a new NN-based actor-critic method which is used to simulate the error feedback loop systems and projections on the NN's synaptic plasticity so as to ensure that the output error is minimized.
Mohammad Modiri
2023-03-10T13:36:31Z
http://arxiv.org/abs/2303.07273v1
# Control of synaptic plasticity in neural networks + ###### Abstract The brain is a nonlinear and highly Recurrent Neural Network (RNN). This RNN is surprisingly plastic and supports our astonishing ability to learn and execute complex tasks. However, learning is incredibly complicated due to the brain's nonlinear nature and the obscurity of mechanisms for determining the contribution of each synapse to the output error. This issue is known as the Credit Assignment Problem (CAP) and is a fundamental challenge in neuroscience and Artificial Intelligence (AI). Nevertheless, in the current understanding of cognitive neuroscience, it is widely accepted that a feedback loop systems play an essential role in synaptic plasticity. With this as inspiration, we propose a computational model by combining Neural Networks (NN) and nonlinear optimal control theory. The proposed framework involves a new NN-based actor-critic method which is used to simulate the error feedback loop systems and projections on the NN's synaptic plasticity so as to ensure that the output error is minimized. _Keywords:_ learning rule, neural network, nonlinear control, reservoir computing. Proposed framework In this section, we propose a novel brain-inspired learning rule. The main idea is to use a RL-based method to control synaptic plasticity. Fig. 1 illustrates the main ideas underlying this computational model that applied in a time series classification task. In the proposed framework, synaptic plasticity reformulated as an optimal tracking problem. For this purpose, the one-hot output vector representing the true class of each time series pattern is imitated, similar to the length of each time series pattern, and is considered the reference trajectory as illustrated in Fig. 1 (C) bottom subplot. Since the reservoir is a special class of high-dimensional nonlinear dynamic systems, where both state and time are continuous. Therefore, continuous-time formulation of the HJB equation and ADP can be applied to derive the learning rule (optimal control law). The derived learning rule forces the proposed framework's output (predicted class in classification tasks) to mimic the reference trajectory (true class in classification tasks) that implicitly minimized the cross-entropy. The following subsections elaborate on the network architecture, and the learning rule in further detail. ### Network architecture and dynamics The proposed framework consists of a feedforward and feedback pathway. The main parts of the feedforward module are: * Input data encoding layer. * Recurrent neural network (RNN). * Linear classifier (output function). The feedback module is composed of: * Critic RC. * Actor RC. Fig. 1 shows the block diagram of the proposed framework architecture. The functionality of the proposed architecture is based on the following steps: * The encoding layer projects input patterns \(x(t)\) into the RNN. In spiking neural networks, each real-value of a data vector is converted into discrete spike trains, suitable for processing in the spike network as spike neural networks can only process discrete spike trains. * In the pertaining process, a supervised learning algorithm like Gradient descent, Ridge, etc., is employed to adjust the decoder parameters associated with each training sample. Once the decoder is trained, it is considered constant during the reservoir training process. * In the RNN training process. An RL-based algorithm proposed in subsection 1.2 is applied to make the RNN learn temporal relations between the input patterns \(\mathbf{x(t)}\) and desired output \(\mathbf{y(t)}\) by adjusting the parameters in the RNN using a novel ADP approach. In the proposed ADP mechanism, two RC-based actor and critic are utilized to approximate true reservoir parameters. * Model recall on new data. The feedforward pathway resembles the structure of traditional neural networks, however the methodology of the feedback pathway especially proposed in this study differs significantly from classical artificial intelligence approaches. **Remark 1** For the sake of brevity, time dependence is suppressed while denoting variables of dynamical systems. For instance, the notations \(x(t),\mathbf{y(t)},u(t),\)\(\nu(t)\) and \(e(t)\) are rewritten as \(\mathbf{x},\mathbf{y},\mathbf{u},\mathbf{v}\) and \(e\). As illustrated in Fig. 1, The central element of the proposed framework is a RNN, i.e., a recurrent network with a structure denoted by the adjacency matrix \(W^{r}\in\mathbb{R}^{n^{r}\times n^{r}}\). Here, the RNN consists of \(n^{r}\) neurons, for which the membrane potential dynamics are described as: \[\dot{v}_{i}=\psi(v_{i})+I_{i} \tag{1}\] \[I_{i}=W_{i}^{E}\partial(v^{E})+W_{i}^{r}\partial(v^{r}) \tag{2}\] ,where \(v=[v_{1}.v_{2}.\cdots.v_{n^{r}}]\in\mathbb{R}^{n^{r}}\) is the state or membrane potential of the RNN neurons, \(\partial(\cdot)\) is a Lipschitz nonlinear dendrite such as \(Sigmoid(\cdot).Tanh(\cdot)\), and, \(\psi(v)\colon\mathbb{R}^{n^{r}}\rightarrow\mathbb{R}^{n^{r}}\) is a Lipschitz leak-term where we used \(-\alpha_{l}v\), \(v^{E},v^{r}\) in non-spiking neurons are directly equal to input \(x\) and RNN state \(v\), and in spiking neurons \(v_{l}\) shows the filtered spike activity of neuron \(i\). \(S_{i}\left(t\right)\) is the spike train of the neuron \(i\) and modelled as a sum of Dirac delta-functions: Figure 1: A schematic of the proposed architecture (plastic weights in red). (A) The feedforward pathway consists of an encoding layer with fix and random parameters, a RNN with trainable parameter and a decoder layer, which is trained in the pre-training process and stay constant during the RNN training process. (B) In the feedback pathway, the nonlinear optimal control is applied for estimating RNN parameters. It consists of actor and critic neural networks. (C) The bottom subplot shows the reference trajectories, and the top subplot shows the learned trajectories. \[q_{i}=\big{(}S_{l}\,*\kappa\big{)}(t)=\int_{-\infty}^{t}S_{l}(s)\kappa(t-s)ds \tag{3}\] \[\kappa(t)=\exp(-t/\tau)/\tau \tag{4}\] Moreover, a linear decoder is assumed as: \[\hat{y}=h(v)=W^{D}v \tag{5}\] ### Synaptic plasticity law According to the equations mentioned in subsection 1.1, the RNN synaptic plasticity law can be modeled as a dynamical system. Consequently, principles of optimal control theory can be applied to derive a learning rule (optimal control law). For this purpose, we reformulate the AI tasks as a control problem. Thus, the output error were considered as follows: \[e=\hat{y}-y\in\mathbb{R}^{c} \tag{6}\] , where \(c\) is a number of classes, \(y\in\mathbb{R}^{c}\) denotes the desired output for the input pattern at time \(t\), and \(\hat{y}\in\mathbb{R}^{c}\) is the corresponding predicted output. By derivation of Eq. (6) with respect to \(t\), the error dynamics can be described as: \[\dot{e}=\hat{y}-\hat{y}\ \in\mathbb{R}^{c} \tag{7}\] Given that the decoder weights \(W^{D}\) are assumed constant during the RNN training process, consequently, the classification error dynamics only depend on the RNN neural dynamics. Rewriting the neural space equations (1) and (2) in the form of Eq. (7) gives: \[\dot{e}=W^{D}\dot{v}\ -\dot{y}=W^{D}\big{(}\psi(v)+W^{E}\phi(v^{E})+W^{r} \phi(v^{r})\big{)}-\dot{y} \tag{8}\] \[=f(v)+g(v)u^{r}-f_{d}(v)-g_{d}(v)u_{d}^{r}\] neural space Eq. (8) can be considered as the following affine sate space equation from: \[\dot{e}=f(e)+g(e)u \tag{9}\] Where the control input is considered as part of parameters of the RNN, which the number is selected according to the problem and training data: \[u^{r}=[u^{f};u]=vec(W^{r})\in\mathbb{R}^{N^{r}} \tag{10}\] , in which \(N^{r}=n^{r}\times n^{r}\) is the number of RNN parameters, \(vec(\cdot)\) is vectored form of a matrix, \(u^{f}\in\mathbb{R}^{N^{r}-N}\) is fixed RNN parameters, \(u\in\mathbb{R}^{N}\) is the RNN plastic synapse or the control input and \([u^{f};u]\) is combination of \(u^{f}\)and \(u\). Therefore, we have the following nonlinear continuous-time equations: \[\begin{split}& f_{1}(v)=W^{D}\left(W^{E}\partial(v^{E})+\psi(v)+W^ {f}\partial(v^{f})\right)=f^{E}(v)+f^{f}(v)\\ & f^{E}(v)=W^{D}W^{E}\partial(v^{E})\\ & f^{f}(v)=W^{D}(\psi(v)+W^{f}\partial(v^{f}))\end{split} \tag{11}\] \[g(v)=W^{D}\partial(v) \tag{12}\] , where \(f(e)\colon\mathbb{R}^{c}\to\mathbb{R}^{c}\) is the drift dynamic of the system, and \(g(e)\colon\mathbb{R}^{c}\to\mathbb{R}^{c\times N}\) is the input dynamic of the system. A common and recommended action in this regard is to add noise into \(u\) and \(g(e)\) to realize the Persistence of Excitation (PE) condition [1] to collect sufficient information about the unknown parameters and make \(g(v)\) full rank. In all tasks of AI, the goal of learning is to adapt the RNN's parameters \(W^{r}\) such that the error in each timestamp of the input pattern is minimized and the RNN's parameters or control input remains bounded. Thus, the following cost function was defined: \[\min_{u(\cdot)\in u}\Im\big{(}u(\cdot).e(\cdot)\big{)}=\int_{t}^{t_{f}}\ell \big{(}e(\tau).u(\tau)\big{)}d\tau \tag{13}\] \[\ell(e.u)=\eta e^{T}e+u^{T}Ru \tag{14}\] , wherein \(\ell(\cdot\cdot)\) is the utility function, \(t_{f}\) is the last element of input patterns, \(R\) symmetric positive definite matrix and \(\eta\) is a constant positive hyper-parameter for ensuring that the error in cost function is sufficiently affective. Hence, the optimal value function can be written: \[V(e)=\underset{u(\cdot)\in U}{Inf}\Im(u.e) \tag{15}\] Under typical assumptions, \(f(0)=0\) and \(f(v)+g(v)u\) is Lipschitz continues on a set \(\Omega\,\epsilon\,\mathbb{R}^{n}\) that contains the origin. Ultimately, it is desirable to achieve an optimal input control (weight update law) \(u^{*}\) that stabilizes the system Eq. (11) and minimizes the cost function Eq. (15). This kind of input control \(u\) is called admissible control [2]. Now, the learning rule has been formulated given the error dynamic in Eq. (11) and the cost function Eq. (15). To solve this dynamic optimization problem, the HJB equation is utilized, so the Hamiltonian of the cost function Eq. (15) associated with control input \(u\) is defined as: \[\mathcal{H}(e.u.V_{e}\ )=\ell(e.u)+V_{e}^{T}(\dot{e}) \tag{16}\] , where \(V_{e}=\partial V/\partial e\) is the partial derivative of the cost function, for admissible control policy \(\mu\) we have: \[\mathcal{H}(e.\mu.V_{e}\ )=0 \tag{17}\] The present study assumed that the solution to Eq. (17) is smooth giving the optimal cost function: \[V^{*}(e)=\min_{u}(\int_{t}^{t_{f}}\ell\big{(}u(\tau).e(\tau)\big{)}d\tau) \tag{18}\] , which satisfies the HJB equation \[\underset{u}{min}\ \mathcal{H}(e.u.V_{e}^{*}\ )=0 \tag{19}\] Assuming that the minimum on the left hand side Eq. (19) exists then by applying stationary condition \(\partial\mathcal{H}\left(e.u.V_{e}\ )/\partial\,u=0\), the learning rule (optimal control) can be obtained as: \[u^{*}(e)=-\frac{1}{2}R^{-1}g^{T}(e)\,V_{e}^{*} \tag{20}\] The optimal value function can be obtained as: \[V^{*}(e)=\min_{u}(\int_{t}^{t_{f}}\eta e^{T}e+{u^{*}}^{T}Ru^{*}d\tau) \tag{21}\] Inserting this optimal learning rule Eq. (20) into nonlinear Lyapunov equation Eq.(16) gives the formulation of the HJB equation Eq. (19) in terms of \(V_{e}^{*}\) \[0=\eta e^{T}e+{V_{e}^{*}}^{T}(e)f(v)-\frac{1}{4}{V_{e}^{*}}^{T}(e)g(e)R^{-1}g^ {T}(v)V_{e}^{*}(e) \tag{22}\] Finding the learning rule for the RNN requires solving the HJB equation for the value function and then substituting the solution to obtain the desired learning rule. Although HJB gives the necessary and sufficient condition for optimality of a learning rule (control law) with respect to a loss function; Unfortunately, due to the nonlinear characteristics of the RNN, solving the HJB equation in explicit form is difficult or even impossible to derive for systems of interest in practice. Thus, the proposed framework focuses on the ADP method to approximate its solution. Thus, we will focus on the ADP method to approximate its solution. To address this issue, with the inspiration of the dopaminergic region structure and conformity with the Weierstrass high-order approximation theorem [3], we proposed a novel actor-critic based on the s-RC. Succinctly, the objective of tuning the critic weights is to minimize the Bellman equation error, and the objective of tuning the actor weights is to minimize the approximate value. #### Critic network design In this subsection, a s-RC is exploited as critic NN to approximate the derivatives of the value function as follows: \[\begin{array}{l}V_{e}\left(e\right)=W_{c}^{D}\,z_{c}+\varepsilon_{c}\in \mathbb{R}^{c\times 1}\\ z_{c}\in\mathbb{R}^{n_{c}\times 1}\\ W_{c}^{D}\in\mathbb{R}^{c\times n_{c}}\end{array} \tag{23}\] Where \(z_{c}\) is the new representation of input \(e\), which is generated by the RNN and \(W_{c}^{D}\) is the decoder weight matrix. As far as the weights of critic decoder provide the best approximate solution for the Hamiltonian function Eq. (16) are unknown. So, it estimated with \(\widehat{W}_{c}^{D}\): \[\widehat{V}_{e}(e)=\widehat{W}_{c}^{D}z_{c} \tag{24}\] It is desired to select the weights of the critic network to minimize the loss function of the critic is defined as follows: \[E_{c}\big{(}\widehat{W}_{c}^{D}\big{)}=\frac{1}{2}e_{c}^{T}e_{c} \tag{25}\] Where for given any admissible policy \(u\) the residual error: \[\mathcal{H}(e.u.V_{e})=\mathcal{H}\big{(}e.u.\widehat{W}_{c}^{D}\big{)}=\eta e ^{T}e+u^{T}Ru+(\widehat{W}_{c}^{D}z_{c})^{T}(\hat{e})=e_{c} \tag{26}\] So, \(\widehat{W}_{c}^{D}\to W_{c}^{D}\) and \(e_{c}\rightarrow\varepsilon_{c}\). The weight update law for the critic weights is gradient descent algorithm, that is: \[\begin{split}\hat{W}_{c}^{D}=-\alpha_{c}\frac{\partial E_{c}}{ \partial\widehat{W}_{c}^{D}}&=-\alpha_{c}(f(e)+g(e)u){z_{c}}^{T} e_{c}\\ &=-\alpha_{c}\sigma_{c}({\sigma_{c}}^{T}\widehat{W}_{c}^{D}+\eta e ^{T}e+u^{T}Ru)\end{split} \tag{27}\] Where \(\alpha_{c}>0\) is learning rate and \(\sigma_{c}=(f(e)+g(e)u){z_{c}}^{T}\). #### Actor network design Similar to the critic, another s-RC is used as the actor to approximate the synaptic plasticity rule (feedback control policy): \[\begin{split}& u(e)=W_{a}^{D}\,z_{a}+\varepsilon_{a}\in\mathbb{R}^{N \times 1}\\ &{z_{a}\in\mathbb{R}^{n_{a}\times 1}}\\ & W_{a}^{D}\in\mathbb{R}^{N\times n_{a}}\end{split} \tag{28}\] Let \(z_{a}\) be the new representation of input \(e\), \(\widehat{W}_{a}^{D}\) an estimation of unknown matrix \(W_{a}^{D}\) based on existing training data, so the feedback control policy can be expressed as: \[\widehat{u}(e)=\widehat{W}_{a}^{D}z_{a} \tag{29}\] The loss function for the actor is defined: \[E_{a}\big{(}\widehat{W}_{a}^{D}\big{)}=\frac{1}{2}e_{a}^{T}e_{a} \tag{30}\] Where \(e_{a}\) is define to be the difference between Eq. (29) and Eq. (20) \[e_{a}=\hat{u}-u=\widehat{W}_{a}^{D}z_{a}+\frac{1}{2}R^{-1}g^{T}(e)(\widehat{W}_ {c}^{D}z_{c}) \tag{31}\] By applying the gradient descent, a weight update expression for the actor can be written as follows: \[\hat{\bar{W}}_{a}^{D}=-\alpha_{a}\frac{\partial E_{a}}{\partial\widehat{W}_{a }^{D}}=-\alpha_{a}(\widehat{W}_{a}^{D}z_{a}+\frac{1}{2}R^{-1}g^{T}(e)(\widehat{ W}_{c}^{D}z_{c})){z_{a}}^{T} \tag{32}\] Where \(\alpha_{a}>0\) is learning rate. Finally, the RNN parameters update rule can be derived as follows: \[vec(\widehat{W}^{r})=\hat{u}(e) \tag{33}\] This completes the RNN learning rule. During the RNN learning process, the feedback pathway via actor-critic NNs forces the output of the network (estimated class) to follow the reference trajectory (true class), an effect that is widely used in control theory. After a sufficiently long learning time, the feedforward pathway without feedback can classify input patterns with acceptable accuracy. ### The Analysis of stability and convergence In this subsection, the stability and convergence of the entire proposed framework and classification error will be analyzed. For this purpose, we need to show \(\lim\limits_{t\to\infty}||\widehat{W}_{c}^{D}||=\lim\limits_{n_{e}\to \infty}||\widehat{W}_{c}^{D}||\to 0\), \(\lim\limits_{t\to\infty}||\widehat{W}_{a}^{D}||=\lim\limits_{n_{e}\to\infty}|| \widehat{W}_{a}^{D}||\to 0\) and \(\lim\limits_{t\to\infty}||e||=\lim\limits_{n_{e}\to\infty}||e||\to 0\). In offline problems, \(t=n_{e}n_{l}(n_{s}-1)+i\) where \(n_{e}\) is the number of the epochs, \(n_{s}\) is the number of samples, \(n_{l}\) is the time series length, and \(i\) is the index of the current time series element. Since in offline problems the training dataset \(n_{s}n_{l}\) is fixed so \(t\to\infty\) as \(n_{e}\to\infty\). To prove asymptotically converge of the proposed framework, firstly, we need to show that the classification error \(e\) and the RNN critic and actor decoder weight estimation errors \(\widetilde{W}_{c}^{D}\), \(\widetilde{W}_{a}^{D}\) are uniformly ultimately bounded (UUB). Therefore, we consider the following Lyapunov and, to facilitate the UUB analysis, the following assumption is made, which can reasonably be satisfied under the current problem settings. **Assumption 1** Assume the following conditions: * We assumed \(g(\cdot)\) is bounded to positive constants i.e., \(\underline{g}\leq\|g(\chi)\|\leq\overline{g}\) therefore we have \(\underline{G}\leq G\leq\overline{G}\) where \(G=gR^{-1}g^{T}\). * The ideal weights of the critic and actor RNN decoder are upper bounded so that \(\|W_{c}^{D}\|\leq\overline{W_{c}^{D}}\) and \(\|W_{a}^{D}\|\leq\overline{W_{a}^{D}}\). * The approximation errors are upper bounded i.e., \(\|\varepsilon_{c}\|\leq\overline{\varepsilon_{c}}\), \(\|\varepsilon_{a}\|\leq\overline{\varepsilon_{a}}\). * The outputs of the RNNs critic, actor are bounded i.e., \(\underline{z_{c}}\leq\|z_{c}\|\leq\overline{z_{c}}\), \(\underline{z_{a}}\leq\|z_{a}\|\leq\overline{z_{a}}\). According to PE assumption \(\sigma_{c}=(f+gu){z_{c}}^{T}\) is bounded i.e., \(\underline{\sigma_{c}}\leq||\sigma_{c}||\leq\overline{\sigma_{c}}\). Now, we consider the following Lyapunov function: \[\begin{split} L(t)=L_{\widetilde{W}_{c}^{D}}(t)&+L_ {\widetilde{W}_{a}^{D}}(t)+L_{e}(t)\\ &=\frac{1}{2\alpha_{c}}\,tr\left\{\widetilde{W_{c}}^{D}{}^{T} \widetilde{W}_{c}^{D}\right\}+\frac{\alpha_{c}}{2\alpha_{a}}\,tr\left\{ \widetilde{W_{a}}^{D}{}^{T}\widetilde{W}_{a}^{D}\right\}\\ &+\alpha_{c}\alpha_{a}(e^{T}e+V(e))\end{split} \tag{34}\] Where \(\alpha>0\), and \(\widetilde{W}_{c}^{D}\) is the weight estimation error of the critic decoder, which is defined as: \[\widetilde{W}_{c}^{D}=\widetilde{W}_{c}^{D}-W_{c}^{D} \tag{35}\] In addition, the dynamics of \(\widetilde{W}_{c}^{D}\) is expressed as: \[\widetilde{W}_{c}^{D}=-\alpha_{c}(\sigma_{c}\sigma_{c}{}^{T}\widetilde{W}_{c} ^{D}+\sigma_{c}\varepsilon_{H}) \tag{36}\] Where \[\varepsilon_{H}=-\varepsilon_{c}(f+gu) \tag{37}\] Moreover, the actor weight estimation error is define as: \[\tilde{W}_{a}^{D}=\tilde{W}_{a}^{D}-W_{a}^{D} \tag{38}\] Combining (23) and (28) with (32) yields: \[\begin{split}\tilde{W}_{a}^{D}&=-\alpha_{a}\bigg{(} \tilde{W}_{a}^{D}z_{a}+\varepsilon_{a}+\frac{1}{2}R^{-1}g^{T}(e)\big{(}\tilde{W} _{c}^{D}z_{c}+\varepsilon_{c}\big{)}\bigg{)}{z_{a}}^{T}\\ &\hskip 142.26378pt=-\alpha_{a}\Big{(}\tilde{W}_{a}^{D}z_{a}+ \frac{1}{2}R^{-1}g^{T}(v)\big{(}\tilde{W}_{c}^{D}z_{c}\big{)}+\varepsilon^{ \prime}_{a}\Big{)}{z_{a}}^{T}\end{split} \tag{39}\] Which \(\varepsilon^{\prime}_{a}\) becomes: \[\varepsilon^{\prime}_{a}=-(\varepsilon_{a}+\frac{1}{2}R^{-1}g^{T}(e) \varepsilon_{c}) \tag{40}\] Thus, the time derivative of \(L(t)\) is: \[\begin{split} L(t)&=\dot{L}_{\tilde{W}_{c}^{D}}(t) +\dot{L}_{\tilde{W}_{a}^{D}}(t)+\dot{L}_{e}(t)\\ &\hskip 142.26378pt=\frac{1}{\alpha_{c}}tr\left\{\tilde{W}_{c}^{D }{}^{T}\dot{\tilde{W}}_{c}^{D}\right\}+\frac{\alpha_{c}}{\alpha_{a}}\,tr \left\{\tilde{W}_{a}^{D}{}^{T}\dot{\tilde{W}}_{a}^{D}\right\}+\alpha_{c} \alpha_{a}(2e^{T}\dot{e}\\ &\hskip 142.26378pt+\dot{V}(e))\end{split} \tag{41}\] Substituting Eq. (36) into \(\dot{\tilde{W}}_{c}^{D}\) in Eq. (41), and assume \(\left\|\sigma_{c}{}^{T}\tilde{W}_{c}\right\|>\varepsilon_{H}\) the \(\dot{L}_{\tilde{W}_{c}^{D}}\) becomes: \[\begin{split}\dot{L}_{\tilde{W}_{c}^{D}}(t)&=\frac {1}{\alpha_{c}}tr\left\{\tilde{W}_{c}^{D}{}^{T}\dot{\tilde{W}}_{c}^{D}\right\} \\ &\hskip 142.26378pt=-\frac{1}{\alpha_{c}}\,tr\left\{\alpha_{c} \tilde{W}_{c}^{D}{}^{T}\sigma_{c}\sigma_{c}{}^{T}\tilde{W}_{c}^{D}\right\}- \frac{1}{\alpha_{c}}\,tr\left\{\alpha_{c}\tilde{W}_{c}^{D}{}^{T}\sigma_{c} \varepsilon_{H}\right\}\\ &\hskip 142.26378pt\leq-(\sigma_{c}{}^{2})\left\|\tilde{W}_{c}^{ D}\right\|^{2}+\varepsilon_{H}{}^{2}\end{split} \tag{42}\] Substituting Eq. (39) into \(\dot{\tilde{W}}_{a}^{D}\) in Eq. (41), the second term becomes: \[\begin{split}\dot{L}_{\tilde{W}_{a}^{D}}(t)&=\frac {\alpha_{c}}{\alpha_{a}}\,tr\left\{\tilde{W}_{a}^{D}{}^{T}\tilde{W}_{a}^{D} \right\}\\ &\hskip 142.26378pt=-\frac{\alpha_{c}}{\alpha_{a}}\,tr\left\{ \tilde{W}_{a}^{D}{}^{T}\left[\alpha_{a}\,\Big{(}\tilde{W}_{a}^{D}z_{a}+\frac{1} {2}R^{-1}g^{T}(e)\big{(}\tilde{W}_{c}^{D}z_{c}\big{)}\right.\right.\\ &\hskip 142.26378pt+\left.\left.\varepsilon^{\prime}_{a}\Big{)}{ z_{a}}^{T}\right]\right\}\end{split} \tag{43}\] According to Eq. (20), Eq. (29), and \(\ \widehat{W}_{a}^{D}z_{a}=-\frac{1}{2}R^{-1}g^{T}(e)\big{(}\widehat{W}_{c}^{D}z_{c} \big{)}\),we have: \[L_{\widehat{W}_{a}^{D}}(t)\leq-(\alpha_{c}\underline{z_{a}}^{2})\left\|\widehat {W}_{a}^{D}\right\|^{2}+\frac{\alpha_{c}}{4\alpha_{a}}\left\|R^{-1}\right\|^{2 }\overline{g}^{2}\overline{z}_{c}^{2}\left\|\widehat{W}_{c}^{D}\right\|^{2}+ \frac{\alpha_{c}}{\alpha_{a}}\varepsilon^{\prime}_{a}^{2} \tag{44}\] Substituting Eq. (29) into the error dynamics Eq. (11), and based on Assumption 1 a., third term of Eq. (41) become: \[L_{e}(t)=\alpha_{c}\alpha_{a}(2e^{T}\dot{e}+\dot{V}(e))=2\alpha_{c}\alpha_{a}e ^{T}\dot{e}+2\alpha_{c}\alpha_{a}V_{e}^{T}\dot{e}\] Substituting \(\dot{e}\) with Eq. (9) and \(V_{e}^{T}\dot{e}\) with \(-(\eta e^{T}e+u^{T}Ru)\) and according to Eq. (16) and Eq. (17): \[\dot{L}_{e}(t)=2\alpha_{c}\alpha_{a}e^{T}(f(e)+g(e)u)-\alpha_{c}\alpha_{a}(\eta e ^{T}e+u^{T}u)\] Substituting \(u\) with Eq. (20) and Eq.(24) which will be equal to \(u=-\frac{1}{2}R^{-1}g^{T}(v)\ \widehat{W}_{c}^{D}z_{c}\): \[\dot{L}_{e}(t)=2\alpha_{c}\alpha_{a}e^{T}\left(f(e)-\frac{1}{2}g( e)R^{-1}g^{T}(e)\ \widehat{W}_{c}^{D}z_{c}\right)\] (45) \[\ \ \[\dot{L}_{e}(t)\leq\alpha_{c}\alpha_{a}\|e\|^{2}+\alpha_{c}\alpha_{a}\|f(e )\|^{2}\|e\|+\alpha_{c}\alpha_{a}\overline{Gz_{c}W_{c}^{D}}\ \|e\|\] \[\qquad\qquad\qquad\qquad-\alpha_{c}\alpha_{a}\eta\|e\|^{2}-\alpha_ {c}\alpha_{a}\lambda_{min}(R)\|u\|^{2}\] \[\qquad\qquad\qquad\leq-\alpha_{c}\alpha_{a}(\eta-1)\|e\|^{2}\] \[\qquad\qquad\qquad\qquad+\alpha_{c}\alpha_{a}\left(\overline{Gz_ {c}W_{c}^{D}}\ +\|f(e)\|^{2}\right)\|e\|\] \[\qquad\qquad\qquad\qquad-\alpha_{c}\alpha_{a}\lambda_{min}(R)\|u \|^{2}\] Where \(\lambda_{min}(R)\) is the minimum eigenvalue of \(R\). Combining Eq. (42), Eq. (43) and Eq. (45): \[\dot{L}(t)\leq-K_{\widetilde{W}_{c}^{D}}{}^{2}\big{\|}\widetilde {W}_{c}^{D}\big{\|}^{2}-K_{\widetilde{W}_{a}^{D}}{}^{2}\big{\|}\widetilde{W}_ {a}^{D}\big{\|}^{2}-K_{u^{2}}\|u\|^{2}-K_{e^{2}}\|e\|^{2}+K_{e}\|e\|\] \[\qquad\qquad\qquad\qquad+K_{1}\] \[\qquad\qquad\qquad\qquad-K_{e^{2}}\left(\|e\|-\frac{K_{e}}{2K_{ e^{2}}}\right)^{2}+\frac{K_{e}{}^{2}}{4K_{e^{2}}}+K_{1}\] \[\qquad\qquad\qquad\qquad\leq-K_{\widetilde{W}_{c}^{D}}{}^{2} \big{\|}\widetilde{W}_{c}^{D}\big{\|}^{2}-K_{\widetilde{W}_{a}^{D}}{}^{2} \big{\|}\widetilde{W}_{a}^{D}\big{\|}^{2}-K_{u^{2}}\|u\|^{2}\] \[\qquad\qquad\qquad\qquad-K_{e^{2}}\left(\|e\|-\frac{K_{e}}{2K_{ e^{2}}}\right)^{2}+\overline{K}\] _Where_ \[K_{\widetilde{W}_{c}^{D}}{}^{2}=\frac{\sigma_{c}}{4\alpha_{a}} \|R^{-1}\|^{2}\overline{g}^{2}\overline{z_{c}}{}^{2} \tag{46}\] \[K_{\widetilde{W}_{a}^{D}}{}^{2}=\alpha_{c}z_{a}{}^{2}\] \[K_{e^{2}}=\alpha_{c}\alpha_{a}(\eta-1)\] \[K_{e}=\alpha_{c}\alpha_{a}\left(\overline{Gz_{c}}\overline{W_{c} ^{D}}\ +\|f(e)\|^{2}\right)\] \[K_{u^{2}}=\alpha_{c}\alpha_{a}\lambda_{min}(R)\] \[K_{1}=\varepsilon_{H}{}^{2}+\frac{\varepsilon^{\prime}\ a}{2} \leq\overline{K_{1}}\] \[K=\frac{K_{e}{}^{2}}{4K_{e^{2}}}+K_{1}\leq\overline{K}\] Thus, \(L(t)<0\) if the proposed model hyper-parameters include \(\alpha_{c}\). \(\alpha_{a}\), \(\eta\), R, \(\psi(v)\) leaky term or \(W^{f}\phi(q^{\;f})\) fixed part of RNN's parameters in Eq. (11) are selected to satisfy three following inequalities: \[0<\alpha_{c}<\frac{4\alpha_{a}{\sigma_{c}}^{2}}{\|R^{-1}\|^{2}\overline{g}^{2} \overline{z_{c}}^{2}} \tag{47}\] And \[0<\alpha_{a} \tag{48}\] And \[\eta>1 \tag{49}\] Since all terms of \(K\) are bounded consequently according to [4] the classification error, the critic and the actor errors are semi-globally uniformly ultimately bounded (SGUUB), which is absolutely enough to classification task. Nevertheless, for reaching more stable condition following inequalities could be hold: \[\|e\|>\frac{K_{e}}{K_{e^{2}}}+\sqrt{\frac{K_{1}}{K_{e^{2}}}} \tag{50}\] Or \[\left\|\widetilde{W}_{c}^{\;D}\right\|>\sqrt{\frac{\overline{K}}{K_{\widetilde {W}_{c}}^{2}}} \tag{51}\] Or \[\left\|\widetilde{W}_{a}^{\;D}\right\|>\sqrt{\frac{\overline{K}}{K_{\widetilde {W}_{a}}^{2}}} \tag{52}\] Or \[\|u\|>\sqrt{\frac{\overline{K}}{K_{u}}} \tag{53}\] Thus, according to the Lyapunov theory the classification error \(e\), the RNN critic and actor decoder weight estimation errors \(\widehat{W}_{c}^{D}\), \(\widehat{W}_{a}^{D}\) and RNN parameters \(u\) are UUB. Our aforementioned analysis based on Lyapunov theory implies that \(L_{e}(t)\) is bounded and decreasing. Therefore, we have: \[\begin{split}& L_{e}(t+T)=L_{e}(t)+\int_{t}^{t+T}\dot{L}_{e}(\tau )d\tau\leq\ L_{e}(t)-\gamma T\\ &\implies L_{e}(t)\leq L_{e}(t+T)\end{split} \tag{54}\] Where \(\gamma>0\). By substituting \(T=n_{l}n_{s}\) which is training dataset length and according to the Lyapunov function properties [5] and summing both sides of Eq. (54) we have: \[\begin{split}&\sum_{t=0}^{n_{l}n_{s}}L_{e}(t)\leq\sum_{t=0}^{n_{l}n _{s}}L_{e}(t+T)\end{split} \tag{55}\] Consequently, Eq. (55) guarantee that the classification error in each epoch's is not more than the previous epochs. Thus, as the number of epochs increases, the classification training error tends to zero (i.e. \(\lim\limits_{t\rightarrow\infty}e(t)\to 0\)). In the same way, we can prove that for \(L_{\widehat{W}_{c}^{D}}(t)\) and \(L_{\widehat{W}_{a}^{D}}(t)\). This completes the stability and convergence proof.
2301.02214
Automatic Sound Event Detection and Classification of Great Ape Calls Using Neural Networks
We present a novel approach to automatically detect and classify great ape calls from continuous raw audio recordings collected during field research. Our method leverages deep pretrained and sequential neural networks, including wav2vec 2.0 and LSTM, and is validated on three data sets from three different great ape lineages (orangutans, chimpanzees, and bonobos). The recordings were collected by different researchers and include different annotation schemes, which our pipeline preprocesses and trains in a uniform fashion. Our results for call detection and classification attain high accuracy. Our method is aimed to be generalizable to other animal species, and more generally, sound event detection tasks. To foster future research, we make our pipeline and methods publicly available.
Zifan Jiang, Adrian Soldati, Isaac Schamberg, Adriano R. Lameira, Steven Moran
2023-01-05T18:33:40Z
http://arxiv.org/abs/2301.02214v4
# Automatic Sound Event Detection and Classification of Great Ape Calls Using Neural Networks ###### Abstract We present a novel approach to automatically detect and classify great ape calls from continuous raw audio recordings collected during field research. Our method leverages deep pretrained and sequential neural networks, including wav2vec 2.0 and LSTM, and is validated on three data sets from three different great ape lineages (orangutans, chimpanzees, and bonobos). The recordings were collected by different researchers and include different annotation schemes, which our pipeline preprocesses and trains in a uniform fashion. Our results for call detection and classification attain high accuracy. Our method is aimed to be generalizable to other animal species, and more generally, sound event detection tasks. To foster future research, we make our pipeline and methods publicly available.[1] S000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 00000 0000 0000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 00000 0000 0000 00000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00000 0000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 00000 000 0000 0000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 00000 0000 000 0000 000 0000 0000 0000 0000 0000 0000 0000 0000 0000 000 0000 0000 000 0000 0000 0000 0000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 000 0000 0000 000 0000 000 000 0000 0000 000 0000 0000 0000 000 0000 0000 0000 0000 0000 0000 000 000 0000 0000 0000 0000 0000 000 0000 0000 000 0000 0000 0000 0000 0000 0000 000 0000 000 0000 000 0000 000 0000 000 000 0000 000 0000 0000 000 0000 0000 000 0000 000 000 0000 000 0000 000 0000 000 0000 000 0000 0000 0000 0000 000 0000 entropy classification on frame-level (for SED) or clip-level (for audio tagging), or occasionally CTC [11] for "sequentially labeled data" [12]. **Animal sound classification** involves related research that addresses specifically at animal sounds, e.g., [13, 14] on the classification of general animal species and [15, 16, 17] on species, call types and caller identities of primates. While this line of research uses similar acoustic feature representation techniques as seen in SED tasks, the models tend to work on top of individual short audio units of animal vocalizations that are manually selected from raw audio recordings by human experts, and thus fall short on dealing with a continuous audio signal that contains many audio events as well as noise. Instead, our method detects and classifies great ape calls directly from raw recordings ranging from seconds to minutes (theoretically recurrent models also extend to hours, but it could pose challenges in model training time). **Automatic Speech Recognition (ASR)** on humans - one of the extant five great apes - has seen significant progress [18] (while animal calls remain mysterious to fully decipher), including the recent work wav2vec 2.0 [1]. Wav2vec 2.0 is pretrained on Librispeech [2] in a self-supervised way, and it demonstrates the feasibility of ASR with limited amounts of labeled data. We are interested in whether the speech representation learned by wav2vec 2.0 can be applied successfully to great ape call detection and classification. ## 3 Data Our data consists of recordings of chimpanzee pant-hoots, orangutan long calls, and bonobo high-hoots. Table 1 provides an overview of these data sets. **Chimpanzee pant-hoots** are vocal sequences composed of up to four acoustically distinct phases, typically produced in this order: _introduction_, _build-up_, _climax_, and _let-down_[19]. Most pant-hoots contain two or more phases, although single phases can be produced in specific contexts [20]. The successive nature and well-balanced phase duration facilitate the training of a classifier (SS5.1). We use annotated recordings of isolated pant-hoots (i.e., no temporal overlap with others' calls) produced during feeding, traveling, and resting context. **Orangutan long calls** are composed by a _full pulse_, which is sub-divided into a _sub-pulse transitory element_ and a _pulse body_, or into sequences of _bubble sub-pulse_ or _grumble sub-pulse_[21, 22]. The complex temporal interrelationship between phases and the overlapping and class-unbalanced characteristics (some phases are extremely short) pose challenges for training a multi-class classifier. On the other hand, the duration of calls and non-calls in the data set are well balanced, which opens the gate to a binary call detection model (SS5.2). Annotated recordings include spontaneous long calls and long calls produced in response to other males' vocal presence or environmental disturbances. **Bonobo high-hoots** - which make up the plurality of our bonobo call data set - are loud, tonal vocalizations [23]. Unlike the chimpanzee and orangutan data sets, call types other than the homologous loud calls are also present in the data set but are rather minor and diverse (e.g., peep-yelp, soft barks), which could be challenging to find. The total call duration is relatively short. ## 4 Method This section introduces our method, which is illustrated in Fig. 1. We describe each step in turn. ### Audio Preprocessing First, all audio clips are converted to _.wav_ format and resampled to 16 kHz sample rate. We segment them into 20ms frames and pad with zeros if necessary. ### Feature and Label Extraction Next, we extract three types of acoustic features with the _torchaudio_ Python package. For an audio clip of \(T\) frames, we get a sequence of frame-level features \(I_{1:T}\), in the shape of \(T\times feature\_dim\): \begin{table} \begin{tabular}{l r r r r} \hline \hline **data set** & **\# audio clips** & **mean / call / total duration** & **\# indiv. (\(\sigma\)/ \(\sigma\))** & **\# call types (duration ratio) / units** \\ \hline chimpanzee & 235 & \(\sim\) 8s / 1,955s / 1,964s & 11 (11 / 0) & 4 (6:3:3:1) / 686 \\ orangutan & 65 & \(\sim\) 74s / 2,793s / 4,817s & 10 (10 / 0) & 7 (700:40:200:10:20:1:1) / 9016 \\ bonobo & 28 & \(\sim\) 24s / 62s / 677s & 7 (3 / 4) & 18 (20:40:10:20:...:200:...:5:1) / 356 \\ \hline \hline \end{tabular} \end{table} Table 1: Data set overview and stats. Shown in the table are the number of audio clips, mean duration of each clip, total duration of calls of all clips, total duration of all clips, number of individuals (male and female), number of call types (approximate total duration ratio of them, partially omitted for bonobo due to space limit), and number of individually annotated call units. * **Raw waveform**: the original amplitude values over time. \(feature\_dim=0.02\times 16000=320\). * **Spectrogram**: calculated then from the raw waveform with \(feature\_dim=201\). * **wav2vec 2.0**: inferred from the raw waveform by the _WAV2VEC2_BASE_ model on a CPU device with \(feature\_dim=768\). We then extract frame-level labels from our annotations. For each annotated unit, we mark all frames inside the annotated time span with a positive class index indicating the call type (e.g., 1 for _intro_); unmarked frames are 0s by default, indicating non-calls. The labels' shape of a clip \(L_{1:T}\) is \(T\times 1\). ### Data Split We shuffle the clips (features and labels) of each data set and split them into 80%, 10%, and 10% for training, validation, and test sets, respectively. We make three different splits by three different random seeds 0, 42, and 3407 [24] to allow multiple experiments and study the effect of randomness. ### Sequence Modeling Since our goal is to learn a function \(f\) from \(I_{1:T}\) to \(L_{1:T}\), we first input \(I_{1:T}\) to a sequence modeling function \(f^{m}\) that outputs a hidden sequence \(H_{1:T}\) (\(T\times hidden\_dim\)), which captures inter-frame interaction. \(H_{1:T}\) then goes through a dense linear function \(f^{d}\) (output \(D_{1:T}\)) followed by a Softmax function \(f^{s}\) to produce the probability distribution over target classes, i.e., \(P_{1:T}\) (\(T\times num\_class\)). Specifically, \(f^{m}\) takes the following forms: * **RNN**: a bidirectional LSTM with hidden size 1024. \(hidden\_dim=1024*2=2048\). * **Transformer encoder**: a Transformer encoder with 8 heads and 6 layers. \(hidden\_dim=1024\). * **Autoregressive model**: we optionally add autoregressive connections between time steps to encourage consistent output labels. The output of \(f^{d}\) at time step \(t\), i.e., \(D_{t}\) is concatenated to the next time step's input \(I_{t+1}\). Lastly, a cross-entropy loss is computed between the model output \(P_{1:T}\) and the gold labels \(L_{1:T}\), then backpropagated to train the models. To mitigate the class imbalance problem, we set class weights to the reciprocal of each class's occurrence times. ## 5 Experiments and Results Our experiments were done in PyTorch [25], with Python 3.8 on an Nvidia Tesla V100 GPU (32GB ram). Most models have \(\sim\)40k million parameters and finish the training of up to 200 epochs with early stopping on validation F1-score within one hour (or a few hours because autoregressive recurrent models run slowly on PyTorch). Table 2 presents our results. ### Initial Exploration with Chimpanzee Data We first test the viability of our approach on the chimpanzee data in light of the simplicity of the pant-hood annotation scheme, although phylogenetically orangutans are closer to humans. We start from _E1_, a simple waveform + LSTM baseline, and observe in _E2_ that wav2vec 2.0 outperforms the raw waveform and spectrogram by a large margin, which demonstrates the power of transfer learning from pretraining on human speech. In _E2.1_, we find that the Transformer encoder does not outperform LSTM. Hence, we infer that Figure 1: Our method (bottom-up). The audio clip shown in the figure is from the chimpanzee data set. _(Non-)ar_ stands for (non-)autoregressive. Transformer's ability to capture arbitrary long-range dependency is not beneficial to our task. Next, we explore the hyper-parameters in the second experimental group and we find in _E3.5_ that balancing class weights (SS4.4) has a small impact. Lastly, we show in _E4_ that the autoregressive connections are beneficial for consistent output, as illustrated by the tiny gaps in _non-ar_ output in Fig. 1. ### Extending to Orangutan and Bonobo Data We successfully extend the model in _E4_ to as trained on the orangutan (_E5_) and bonobo (_E6_) data sets. We note that some minority classes perform less well due to data scarcity, in contrast to the well-balanced situation in the chimpanzee data set (see Table 1). We further reduce the task to a binary (call vs. non-call) classification that resembles voice activity detection of human speech. This is a useful tool to automatically extract calls from raw recordings for further bioacoustic analysis (e.g., studying the repertoire of a given species). Finally, to understand the generalizability of our models, we try zero-shot transferring the model trained in _E5.1_ on orangutans directly to unseen bonobo data. The results show that it is promising to build a potential general-purpose sound event detection model for all great ape calls. ## 6 Discussion We have addressed a gap in the bioacoustics research of non-human great apes by developing an approach for automatically identifying sound events and classifying great ape calls using a neural network architecture. Our method successfully and accurately identifies and classifies calls in three species of non-human great apes, and provides a tool for primatologists to bootstrap call identification and analysis from raw unannotated audio recordings. Our method also shows the general applicability of the wav2vec 2.0 model trained on human speech for identifying vocalizations and call types in other species. Future work may apply our approach to more animals, as part of the goal to decode the communication systems of great apes and other non-human animals more broadly.2 \begin{table} \begin{tabular}{l l l c c c c c} \hline \hline **ID** & **data** & **feature** & **model** & **dev acc.** & **dev f1** & **test acc.** & **test f1** & **aucpr** \\ \hline \multicolumn{8}{l}{_Explore the best feature and model combination_} \\ E1 & chimp & waveform & lstm (baseline) & \(51.7\pm 2.1\) & \(35.4\pm 2.5\) & \(51.0\pm 3.6\) & \(34.7\pm 4.3\) & - \\ E1.1 & chimp & spectrogram & lstm & \(60.3\pm 1.5\) & \(55.7\pm 2.3\) & \(58.7\pm 4.7\) & \(53.9\pm 5.4\) & - \\ E2 & chimp & wav2vec2 & lstm & \(81.0\pm 4.0\) & \(79.9\pm 4.6\) & \(79.3\pm 2.3\) & \(77.9\pm 3.6\) & - \\ E2.1 & chimp & wav2vec2 & transformer & \(71.3\pm 0.6\) & \(68.3\pm 0.2\) & \(75.3\pm 0.6\) & \(72.1\pm 0.5\) & - \\ \hline \multicolumn{8}{l}{_Explore the hyper-parameters_} \\ E3.1 & chimp & wav2vec2 & lstm (E2 + \(batch\_size=4\)) & \(69.7\pm 1.5\) & \(71.8\pm 2.6\) & \(67.7\pm 4.0\) & \(69.6\pm 4.0\) & - \\ E3.2 & chimp & wav2vec2 & lstm (E2 + \(batch\_size=8\)) & \(63.3\pm 0.6\) & \(62.6\pm 1.0\) & \(62.0\pm 4.4\) & \(61.5\pm 4.0\) & - \\ E3.3 & chimp & wav2vec2 & lstm (E2 + \(dropout=0.2\)) & \(80.7\pm 3.5\) & \(80.0\pm 4.4\) & \(78.0\pm 1.7\) & \(76.8\pm 2.7\) & - \\ E3.4 & chimp & wav2vec2 & lstm (E2 + \(dropout=0.1\)) & \(81.0\pm 4.0\) & \(80.2\pm 4.8\) & \(78.7\pm 2.9\) & \(77.3\pm 3.9\) & - \\ E3.5 & chimp & wav2vec2 & lstm (E2 - \(balance\_weights\)) & \(81.0\pm 3.6\) & \(79.6\pm 4.4\) & \(79.3\pm 2.3\) & \(78.3\pm 3.6\) & - \\ \hline \multicolumn{8}{l}{_Explore autoregressive modeling_} \\ E4 & chimp & wav2vec2 & lstm (E2 + autoregressive) & \(87.7\pm 1.2\) & \(87.1\pm 1.8\) & \(85.7\pm 2.1\) & \(85.6\pm 2.5\) & - \\ \hline \multicolumn{8}{l}{_Extend to orangutan long calls and a binary setting_} \\ E5 & orange & wav2vec2 & lstm (E4) & \(83.0\pm 1.0\) & \(82.7\pm 1.4\) & \(81.7\pm 3.1\) & \(82.0\pm 2.6\) & - \\ E5.1 & orange & wav2vec2 & lstm (E5 + binary target) & \(92.3\pm 2.5\) & \(92.1\pm 2.5\) & \(92.0\pm 1.0\) & \(91.9\pm 1.1\) & 0.96 \\ \hline \multicolumn{8}{l}{_Extend to bonobo calls and a binary setting_} \\ E6 & bonobo & wav2vec2 & lstm (E4) & \(87.0\pm 4.6\) & \(85.9\pm 6.3\) & \(83.7\pm 3.8\) & \(82.3\pm 2.2\) & - \\ E6.1 & bonobo & wav2vec2 & lstm (E6 + binary target) & \(92.0\pm 3.6\) & \(91.9\pm 3.4\) & \(87.7\pm 3.5\) & \(87.8\pm 2.9\) & 0.87 \\ \hline \multicolumn{8}{l}{_Zero-shot transferring from orangutan to bonobo_} \\ E7 & bonobo & wav2vec2 & lstm (E5.1) & \(63.0\pm 13\) & \(69.2\pm 10\) & \(72.0\pm 4.0\) & \(74.2\pm 3.1\) & 0.55 \\ \hline \hline \end{tabular} \end{table} Table 2: Experimental results. We run all experiments three times based on different random seeds and report the mean and standard deviation. _acc._ stands for frame-level accuracy, _fl_ stands for the frame-level average F1-score weighted by the number of true instances per class, and _aucpr_ stands for the area under the precision-recall curve for the positive class in the binary case at test time when the random seed is set to 0. For hyper-parameters, we start _E1_ with \(batch\_size=1\), \(dropout=0.4\) and keep them by default, if not otherwise specified in the table.
2306.01745
Biomarker Discovery with Quantum Neural Networks: A Case-study in CTLA4-Activation Pathways
Biomarker discovery is a challenging task due to the massive search space. Quantum computing and quantum Artificial Intelligence (quantum AI) can be used to address the computational problem of biomarker discovery tasks. We propose a Quantum Neural Networks (QNNs) architecture to discover biomarkers for input activation pathways. The Maximum Relevance, Minimum Redundancy (mRMR) criteria is used to score biomarker candidate sets. Our proposed model is economical since the neural solution can be delivered on constrained hardware. We demonstrate the proof of concept on four activation pathways associated with CTLA4, including (1) CTLA4-activation stand-alone, (2) CTLA4-CD8A-CD8B co-activation, (3) CTLA4-CD2 co-activation, and (4) CTLA4-CD2-CD48-CD53-CD58-CD84 co-activation. The model indicates new biomarkers associated with the mutational activation of CLTA4-associated pathways, including 20 genes: CLIC4, CPE, ETS2, FAM107A, GPR116, HYOU1, LCN2, MACF1, MT1G, NAPA, NDUFS5, PAK1, PFN1, PGAP3, PPM1G, PSMD8, RNF213, SLC25A3, UBA1, and WLS. We open source the implementation at: https://github.com/namnguyen0510/Biomarker-Discovery-with-Quantum-Neural-Networks.
Nam Nguyen
2023-05-15T08:47:56Z
http://arxiv.org/abs/2306.01745v2
# Biomarker Discovery with Quantum Neural Networks: A Case-study in _Ctla4_-Activation Pathways ###### Abstract **Background:** Biomarker discovery is a challenging task due to the massive search space. Quantum computing and quantum Artificial Intelligence (quantum AI) can be used to address the computational problem of biomarker discovery tasks. **Method:** We propose a Quantum Neural Networks (QNNs) architecture to discover biomarkers for input activation pathways. The Maximum Relevance -- Minimum Redundancy (mRMR) criteria is used to score biomarker candidate sets. Our proposed model is economical since the neural solution can be delivered on constrained hardware. **Results:** We demonstrate the proof of concept on four activation pathways associated with _CTLA4_, including (1) _CTLA4_-activation stand-alone, (2) _CTLA4-CD8A-CD8B_ co-activation, (3) _CTLA4-CD2_ co-activation, and (4) _CTLA4-CD2-CD48-CD53-CD58-CD84_ co-activation. **Conclusion:** The model indicates new biomarkers associated with the mutational activation of _CLTA4_-associated pathways, including 20 genes: _CLJC4_, _CPE_, _ETS2_, _FAM107A_, _GPR116_, _HYOU1_, _LCN2_, _MACF1_, _MT1G_, _NAPA_, _NDUFSS_, _PAK1_, _PFN1_, _PGAP3_, _PPM1G_, _PSMD8_, _RNF213_, _SLC25A3_, _UBA1_, and _WLS_. We open source the implementation at: [https://github.com/namnguyen0510/Biomarker-Discovery-with-Quantum-Neural-Networks](https://github.com/namnguyen0510/Biomarker-Discovery-with-Quantum-Neural-Networks). ## 1 Introduction A biomarker, a molecular marker or signature molecule, refers to a biological substance or characteristic found in body fluids, tissues, or blood that indicates the presence of a condition, disease, or abnormal process. Biomarkers can be measured to assess how well the body responds to treatment for a particular disease or condition [1]. Biomarkers play a crucial role in drug discovery and development by providing essential information on the safety and effectiveness of drugs. These measurable indicators can be categorized into diagnostic, prognostic, or predictive biomarkers, and they are utilized to choose patients for clinical trials or track patient response and treatment efficacy. Despite its valuable role, biomarker discovery is a challenging task for classical-computational platforms due to the massive search space (**Section**2.1). Quantum computing is an emerging technology that utilizes the principles of quantum mechanics to solve problems beyond classical computers' capabilities. Quantum Machine Learning and Quantum Neural Networks are an advanced class of machine intelligence on quantum hardware, which promises more powerful models for myriad learning tasks (**Section**2.2). This work uses a class of Quantum Artificial Intelligence (AI) models to discover biomarkers in biomedical research. We adopt the neural architecture proposed in a contemporary work that addresses the body dynamics modeling problem. Here, we make a non-trivial adaptation of the proposed game-theoric to tackle a different class of problems. The main contribution of this study is summarized as follows: 1. The proposed quantum AI model is a general, cost-efficient, and cost-effective algorithm for biomarker discovery, despite the extensive problem complexity. 2. The model outcomes suggest novel biomarkers for the mutational activation of the notable target in immunotherapy - _CLTA4_, including \(20\) genes: _CLIC4_, _CPE_, _ETS2_, _FAM107A_, _GPR116_, _HYOU1_, _LCN2_, _MACF1_, _MT1G_, _NAPA_, _NDUFS5_, _PAK1_, _PFN1_, _PGAP3_, _PPM1G_, _PSMD8_, _RNF213_, _SLC25A3_, _UBA1_ and _WLS_. ## 2 Preliminary ### Problem Statement The learning task involves identifying the best combinations of biomarkers from a given set of genes (represented as \(\mathcal{G}\)) to select those that are (1) most relevant to a specific pathway (represented as \(\mathbf{Y}\)) and (2) optimal for machine learning algorithms. This criterion is commonly referred to as minimizing redundancy and maximizing relevancy for selected feature sets, as proposed in [43] (See **Appendix** A). In this context, it is worth noting that each individual has unique patterns of mutational alterations that lead to distinct sets of biomarkers. Considering all the possibilities, the number of candidate biomarker sets is the sum of all possible combinations, which can be expressed as \[\sum_{i=0}^{N}\binom{N}{k}=2^{N} \tag{1}\] Since the human genome contains around 20,000 to 25,000 genes, this results in a massive search space of \(3.2019\times 10^{6577}\) candidate biomarker set for any biomarker identification algorithm. This search space grows exponentially with the number of input genes, making it an incredibly challenging problem for conventional computing methods. ### Quantum Neural Networks QNNs represent input data using wavefunction representations, typically using qubits or "qurons" [51], in the form of: \[\ket{\psi}=\alpha\ket{0}+\beta\ket{1},\alpha\text{ and }\beta\in\mathbb{C}. \tag{2}\] This distinguishes QNNs from classical ANNs as they capture physical events discretely [33] and offer insight into representation learning [6]. QNNs have been proposed to offer two advantages over classical ANNs [52]. Firstly, quantum feature maps can represent exponentially larger data sets than classical neural networks, with an \(n\)-qubit system representing \(2^{n}\) bits [40]. Secondly, quantum feature maps inherit wavefunction uncertainty from quantum mechanics, allowing measurements of quantum states to return values of \(0\) or \(1\) with probability values of \(\mathbb{P}(0)=|\alpha|^{2}\) and \(\mathbb{P}(1)=|\beta|^{2}\). In our previous papers, we discuss the role of epistemic uncertainty estimation from quantum maps [38] and the effect of entanglement layouts on the classifier's performance. The typical design for QNNs [5, 19, 27, 47, 53] involves a stack of identical ansatz structures, given by a global unitary transformation: \[U_{\mathbf{\theta}}(\mathbf{x})=\mathcal{U}^{(l)}(\mathbf{\theta}l)\mathcal{V}(\mathbf{x}) \ldots\mathcal{V}(\mathbf{x})\mathcal{U}^{(0)}(\mathbf{\theta}0), \tag{3}\] where \(\mathbf{x}\) represents input features, \(\mathbf{\theta}\) represents model weights, \(\mathcal{U}^{(l)}(.)\) represents identical-parameterized circuits serving as variational (trainable neural) blocks, and \(\mathcal{V}(.)\) represents feature-embedding blocks. From our perspective, QNNs are advanced mathematical models in the language of representation theory (See **Appendix** B); thus, we are using mathematics to enable cancer discoveries. ## 3 Method ### Model Architecture We depict the ansatz structure of our QNN model in **Figure**1. Each neural block in our proposed model includes (1) a parameterized RZ-rotation based on time-domain variables \(t\in[0,2\pi]\), given by \[\mathbf{R}_{Z}(t)=\begin{bmatrix}e^{-i\frac{t}{2}}&0\\ 0&e^{i\frac{t}{2}}\end{bmatrix} \tag{4}\] and (2) trainable RX-rotation and RY-rotation gates \[\mathbf{R}_{X}(\alpha)=\begin{bmatrix}\cos(\frac{\alpha}{2})&-i\sin(\frac{\alpha}{2}) \\ -i\sin(\frac{\alpha}{2})&\cos(\frac{\alpha}{2})\end{bmatrix} \tag{5}\] and \[\mathbf{R}_{Y}(\beta)=\begin{bmatrix}\cos(\frac{\beta}{2})&-\sin(\frac{\beta}{2}) \\ \sin(\frac{\beta}{2})&\cos(\frac{\beta}{2})\end{bmatrix} \tag{6}\] The parameterized wavefunction of the 1-layer model is given \[\ket{\psi_{\Theta}}=\ket{\psi_{(\mathbf{\alpha},\mathbf{\beta})}(\mathbf{t})}=\text{CNOT}( \Lambda)\mathbf{R}_{X}(\mathbf{\alpha})\mathbf{R}_{Y}(\mathbf{\beta})\mathbf{R}_{Z}(\mathbf{t})H\ket{ 0}^{\otimes n}, \tag{7}\] \(n\) is the number of qubits, and \(\Lambda\) is the architecture parameter of the entanglement layout constructed by CNOT gates, illustrated in **Figure**1. ### Algorithm #### 3.2.1 Computations of Gene Scores (GSCORE\({}^{\Theta}\)) We train the proposed QNNs to learn the optimal sampling distribution based on mRMR criteria (See **Appendix** A). In other words, the search algorithm will assign higher probabilities for the more important markers. Thus, the search algorithm will more often select more important biomarkers. Specifically, the output electronic wavefunction of parameterized QML model is given by \[\ket{\psi_{\Theta}}=\mathcal{U}_{n}(\Theta), \tag{8}\] with \(n\) is the number of prepared qubits and \(\Theta\) is the model parameter. The sampled probability density is given by \[p(\Theta)=\ket{\Psi(\Theta)}^{2}=\Psi^{*}\Psi \tag{9}\] where \(\ket{\Psi^{*}}\) is the conjugate-transpose of the output wavefunction. In other words, we compute the probability amplitude; or the square modulus of the wavefunction. We further use the Softmax function with tunable temperature to normalize our density. Besides, using the Softmax function also allows us to control the conservative of the search engine as the low temperature will encourage the model confidence. In contrast, high temperatures encourage less conservative predictions. Thus, the biomarker score is the sampling probability of each gene given by \[\text{GSCORE}^{\Theta}=\hat{p}(\Theta)=\text{SoftMax}\bigg{(}\frac{\sqrt{p( \Theta)}}{\text{temp}}\bigg{)}, \tag{10}\] where temp is the function temperature. Finally, we select the candidate marker set by parameterized thresholding with \(\bar{p}=1\) if \(\hat{p}\geq\tau\), otherwise \(0\). We interpret the GSCORE\({}^{\Theta}\) that the more important genes have a higher chance to be selected by the sampler, resulting in a higher probability over the output of quantum ansatzes. #### 3.2.2 Objective Function We adopt the efficient loss function of the Quadratic Programming Feature Selection (QPFS) method [46], given as \[\min_{\mathbf{\Theta}}\bigg{(}\lambda\mathbf{p}^{\intercal}\mathbf{H}\mathbf{p}-\mathbf{p}\mathbf{F} \bigg{)},\sum_{i=1}^{n}p_{i}=1,p_{i}>0, \tag{11}\] where \(\mathbf{F}_{n\times 1}\) is the relevancy to target variables and \(\mathbf{H}_{n\times n}\) is the pairwise redundancy computed from the feature set. Both natural and normalized quantum distributions \(p(\Theta)\) and \(\hat{p}(\Theta)\) satisfy the conditions for \(p_{i}\) in QPFS. For further analysis, we consider \(\lambda=1\), i.e., the balanced loss between redundant-relevant criteria. Figure 1: **The Ansatz Circuit of Our Proposed QNN Models using Four Qubits with Four Neural Blocks**. We use \(11\)-quit ansatz in the final setting to score \(2^{11}=2,048\) genes. #### 3.2.3 Pseudo-code We implement the proposed model using the quantum simulation package Pennylane [7] with Pytorch 3.7 [41]. The mutual information criteria are computed by Scikit-learn [42], and model optimization is conducted by Optuna [2] with Tree Parzen Estimators [8]. The pseudo-code is given in the following algorithm: ``` 1importpenmylaneasqml 2importtorch 3importnumpyasnp 4q=11#NumberofQubits 5dev=qml.device("default.qubit",wires=q) 6device=torch.device("cuda:0" 7iftorch.cuda.is_available()else"CPU") 8qml.qnode(dev,interface=torch") 9defquantum_sampler(a,b,n): 10t=torch.tensor(np.linspace(0,np.pi,n)) 11foriinrange(q): 12qml.Hadamard(wires=i) 13fork,dtinenumerate(t): 14foriinrange(q): 15qml.RZ(dt,wires=i) 16qml.RY(a,k,i),wires=i) 17qml.RX([k,i],wires=i) 18foriinrange(0,q-1,2): 19qml.CNOT(wires=[i,i+1]) 20foriinrange(1,q-1,2): 21qml.CNOT(wires=[i,i+1]) 22qml.CNOT(wires=[q-1,0]) 23returnqml.state() ``` Listing 1: Model Architecture #### 3.2.4 Hyper-parameter and Training Protocol We report the hyper-parameters for our search engine powered by proposed QNNs in **Table**1. Noteworthy, we adopt the Tree Parzen Estimator with Sequential Model-based Optimization [8] (SMBO) to train our model. We learned from our previous works - CSNAS [37] and BayesianQNN [38] that the used optimization is a cost-efficient algorithm, which enables effective search on a massive search space. ## 4 Results ### Case-study #### 4.1.1 _Ctla4_-activation Pathways _CTL4_ - The gene is part of the immunoglobulin superfamily and produces a protein that transmits a signal to inhibit T cells. Mutations in this gene have been linked to various autoimmune diseases, including insulin-dependent diabetes mellitus, Graves disease, Hashimoto thyroiditis, celiac disease, systemic lupus erythematosus, and thyroid-associated orbitopathy [20]. In this study, we investigate four pathways regarding the co-occurrence of mutational activation, including: \begin{table} \begin{tabular}{|c|c|c|} \hline **Parameters** & **Range** & **Role** \\ \hline Number of Qubits & \(11\) & Sampler for \(2^{11}=2048\) genes \\ \(\mathbf{\alpha}\) & \(-2\pi,2\pi\) & \(\mathbf{R}_{X}\) rotation \\ \(\mathbf{\beta}\) & \(-2\pi,2\pi\) & \(\mathbf{R}_{Y}\) rotation \\ \(\epsilon\) & \([\pi 96,\pi/24]\) & Standard Deviation of Model Weight \\ \(\tau\) & \([0.5,0.7]\) & Threshold Value \\ temp & \([1/10^{3},2\times 10^{3}]\) & SoftMax Temperature \\ \hline \end{tabular} \end{table} Table 1: **Hyper-parameter of Our Model Optimization.** 1. **Pathway 1**: _CTLA4_-activation stand-alone. 2. **Pathway 2**: _CTLA4-CD8A-CD8B_ activated simultaneously. 3. **Pathway 3**: _CTLA4-CD2_ activated simultaneously. 4. **Pathway 4**: _CTLA4-CD2-CD48-CD53-CD58-CD84_ activated simultaneously. Of note, advanced ML or Quantum AI has yet to study these mutational activation pathways to extend our knowledge. We summarize the biological meaning of quantified targets in **Appendix** C. #### 4.1.2 Datasets We use The Cancer Genome Atlas (TCGA [58]) with RNA expression data and Copy Number of Variation (CNV). We score \(2,048\) biomarkers based on its expression, which is equivalent to \(2^{11}\) dimensional embedding generated by \(11\)-qubit system (**Section**3.2.3). The evaluated cohort includes \(9,136\) patients, considered a Big Data in the context of a cancer genetic study. The expression set \(\mathbf{X}\) is normalized using Min-Max normalization, and the mutational signals are created from CNV with \(\mathbf{Y}=1\) if CNV \(\neq 0\), otherwise \(\mathbf{Y}=0\). The evaluated expressions are continuous values, while the activation signals are binary. #### 4.1.3 Experimental Settings All experiments were carried out using Python \(3.7.0\), numpy \(1.21.5\), sci-kit-learn \(1.0.2\), and PyTorch \(1.11\) on an Intel i9 processor (2.3 GHz, eight cores), 16GB DDR4 memory and GeForce GTX \(1060\) Mobile GPU with 6GB memory. Besides, we made our implementation available at: [https://github.com/namnguyen0510/Biomarker-Discovery-with-Quantum-Neural-Networks](https://github.com/namnguyen0510/Biomarker-Discovery-with-Quantum-Neural-Networks); and all experimental history available at [https://tinyurl.com/55x77w4h](https://tinyurl.com/55x77w4h). We train our sampler for \(600\) trials with paralleled computing using ten CPU workers for each pathway. ### Quantum AI-driven Biomarkers for _Ctla4_-activation Pathways We summarize the case-study of _CTLA4_-activation pathways in **Figure**2(A). The full reports for each pathway is given in **SuppFig**1, 2, 3 and 4 in **Appendix** D. We only consider the top 20 biomarkers for further analysis. Of note, the Figure 2: **(A) Activation Pathways Analyzed in Our Case-study. (B) Venn Diagram of Discovered Biomarker Sets regarding The Quantified Targeted Pathways. _MACF1_ is addressed as a common biomarker for _CTLA4_ and _CTLA4_-_CD8A_-_CD8B_; while _HSPA1B_ is the common biomarker for _CTLA4_-_CD8A_-_CD8B_ and _CTLA4_-_CD2_. discovered biomarker sets are distinctive for each studied pathway. Specifically, only one biomarker _MACF1_ is founded as the driver for _CTLA4_ and _CTLA4-CD8A-CD8B_ activation pathways (**Figure**2(B)). Similarly, _HSPA1B_ is addressed as a common biomarker for the pathways _CTLA4-CD8A-CD8B_ and _CTLA4-CD2_. Apart from _MACF1_ and _HSPA1B_, the remaining drivers are distinctively associated with the quantified targets. ### Convergence Analysis We construct an end-to-end explainable quantum AI, illustrated in the results in **SuppFig**1, 2, 3 and 4. Of note, we are addressing a complex problem beyond the capacity of classical computers; thus, our proposed algorithm will likely suggest a sub-optimal solution. We show in these results of **SuppFig**1, 2, 3 and 4 that the proposed algorithm can effectively score genes and sampling biomarker sets as the sampling loss is reducing. Of note, training beyond \(600\) trials does not guarantee better solutions as most of the best loss is found by trial \(400^{th}\). We average top-\(50\%\) models to have a more robust inference of GSCORE\({}^{\Box}\), which shows that higher GSCORE\({}^{\Box}\) tends to have higher score variation since the markers are more frequently sampled by the quantum model. However, the score variation is extremely small with under \(200\mu=2\times 10^{-6}\), indicating the well-convergence of neural solutions. Furthermore, the output panels in **SuppFig**1, 2, 3 and 4 also report the landscape of hyper-optimization protocol, in which model configuration with the lower score is in a darker color (purple) and model configuration with a higher score is in brighter color (yellow). This analysis significantly reduces the cost of model deployment on actual quantum computers, as we can select the optimal design of quantum ansatz circuits based on analytical solutions using classical simulations. ## 5 Significance of Discovered Biomarkers ### Statistical Significance Using the cBioPortal [12] databases from nine projects [9, 25, 35, 45, 48, 50, 59, 64] with a total of \(73,717\) samples, we validated the statistical significance of the top-5 biomarkers for each pathway (**SuppMat-S1**). We found that only a small proportion of the total samples contained mutations in certain biomarkers, with the highest mutated biomarkers being _PAK1_ (\(1.5\%,n=858\)) and _RNF213_ (\(0.3\%,n=62\)). However, the remaining biomarkers accounted for an extremely small proportion of all mutations, making it insufficient to use mutational profiles alone to study the relationship between these biomarkers and targets. We also found co-occurrence of mutations in certain biomarkers with significant statistical evidence regarding the _CTLA4_-activation pathway (SuppDoc-S). Specifically, _UBA1_, _HYOU1_, and _RNF213_ mutations were co-occurring in this pathway. Additionally, mutations in _MAFC1_, _WLS_, _PSMD8_, and _PAK1_ were co-occurring in the _CTLA4-CD8A-CD8B_ pathways, while mutations in _NAPA_, _PGAP3_, _CLIC4_, and _PPM1G_ were co-occurring in the activation of _CTLA4-CD2_. Lastly, the extended activation pathway four was associated only with the co-activation of _LCN2_ and _FAM107A_ mutations. ### Clinical Significance We perform literature mining from the PubMed.gov library regarding \(19\) top-5 biomarkers, excluding CPE due to similar abbreviations (**SuppMat-S2**). The analysis is on publications over the three years from \(2020\) to \(2023\), up to 12/05/2023. **SuppTab**2 shows that \(12\) over \(19\) biomarkers are rarely known in clinical-associated literature but addressed as significant drivers by our proposed model. #### 5.2.1 Pathway 1: _Ctla4_ Hypoxia upregulated protein 1 is a protein that in humans is encoded by the _HYOU1_ gene. The protein encoded by this gene belongs to the heat shock protein 70 family. This gene uses alternative transcription start sites. Using a type of bone-forming cell called MC3T3-E1, the study [70] demonstrated that high levels of glucose decrease the ability of the cells to survive and cause them to undergo programmed cell death. The high glucose levels also cause endoplasmic reticulum stress (ERS) by increasing the movement of calcium and the production of a protein called binding immunoglobulin protein (BiP) in the endoplasmic reticulum. This results in the activation of eukaryotic initiation factor 2 alpha (elF2alpha) downstream of a protein called PKR-like ER kinase (PERK). This, in turn, leads to the activation of a transcription factor called _ATT4_ and an increase in the production of a protein called C/EBP-homologous protein (CHOP), which is involved in the regulation of apoptosis in response to ER stress, as well as other proteins like _DNAJC3_, _HYOU1_, and _CALR_. Besides, the discovered _HYOU1_ and _HSPA1A_ (in the _HSPA1B_ family) and _DNAJB11_, _CALR_, _ERP29_, _GANAB_, _HSP90B1_, _HSPA5_, _LMAN1_, _PDIA4_ and _TXNDC5_ were involved in the endoplasmic reticulum (ER) stress [16]. The analysis of how proteins interact with each other revealed certain genes, such as _PTBP1_, _NUP98_, and _HYOUI_, that are linked to breast cancer brain metastasis [3]. _HYOUI_ plays a role in supporting the growth, spreading, and metabolic activity of papillary thyroid cancer by increasing the stability of _LDHB_ mRNA [56]. Apart from its significant protective function in the formation and progression of tumors, _HYOUI_ can be a promising target for treating cancer. It may serve as an immune-stimulating additive because it can trigger an antitumor immune response. Additionally, it can be a molecular target for treating various endoplasmic reticulum-related ailments [44]. The study [29] found that the secretion of certain substances in response to a communication between lung cancer cells and endothelial cells (ECs) led to an increase in the expression of _HYOUI_ in lung cancer spheroids. Additionally, direct interaction between ECs and lung cancer cells caused an upregulation of _HYOUI_ in multicellular tumor spheroids (MCTSs). When inhibiting _HYOUI_ expression, it reduced the malignant behavior and stemness of the cancer cells, facilitated apoptosis, and made the MCTSs more sensitive to chemotherapy drugs in lung cancer. _ETS2_ is responsible for producing a transcription factor that controls the activity of genes related to both development and apoptosis. The protein it produces is not only a proto-oncogene but has also been found to play a role in regulating telomerase. Additionally, a non-functional copy of this gene, known as a pseudogene, is located on the X chromosome. Due to alternative splicing, various transcript variants of this gene are generated. The transcription factor _ETS2_ controls the expression of genes responsible for various biological processes such as development, differentiation, angiogenesis, proliferation, and apoptosis. The transcription factor _ETS2_ has been shown to downregulate the expression of cytokine genes and HIV-1 in resting T-cells. [15] have investigated whether _ETS2_ also regulates the expression of lymphotropic factors (LFs) that are involved in T-cell activation/differentiation and the kinase _CDK10_, which controls Ets-2 degradation and repression activity. In vitro experiments demonstrated that Ets-2 overexpression increased the expression of certain LFs while decreasing _CDK10_ levels in both stimulated and unstimulated T-cells. These findings suggest that Ets-2 may regulate cytokine gene expression and HIV-1 latency in virus-infected T-cells. The relationship between _CELF1_ and _ETS2_ in colorectal cancer (CRC) and chemoresistance to oxaliplatin (L-OHP) is studied in [55]. _CELF1_ was overexpressed in human CRC tissues and positively correlated with _ETS2_ expression. Overexpression of _CELF1_ increased CRC cell proliferation, migration, invasion, and L-OHP resistance, while knockdown of _CELF1_ improved the response of CRC cells to L-OHP. Similarly, overexpression of _ETS2_ increased malignant behavior and L-OHP resistance in CRC cells. The study concluded that _CELF1_ regulates _ETS2_, resulting in CRC tumorigenesis and L-OHP resistance, and maybe a promising target for overcoming chemoresistance in CRC. _GPR116_ or _ADGRF5_ is the probable G-Protein coupled receptor 116. _GPR116_ has been reported to be involved in cancer progression and predicts poor prognosis in other types of cancer. The study [69] shows that _GPR116_ expression is upregulated in gastric cancer (GC) tissues and is positively correlated with tumor invasion and poor prognosis. _GPR116_ may be a novel prognostic marker and a potential therapeutic target for GC treatment. mRNA and protein expression of _GPR116_ in GC tissues and found that it was significantly upregulated, positively correlated with tumor node metastasis (TNM) staging and tumor invasion, and contributed to poor overall survival in GC patients [26]. _GPR116_ overexpression was also found to be an independent prognostic indicator in GC patients. Enrichment analysis revealed that _GPR116_ co-expression genes were mainly involved in various pathways. The effect of _GPR116_ receptor on NK cells concerning pancreatic cancer is studied in [21], which found that _GPR116_ mice were able to efficiently eliminate pancreatic cancer through enhancing the proportion and function of NK cells in the tumor. The expression of _GPR116_ receptor was decreased upon the activation of NK cells, and _GPR116_ with NK cells showed higher cytotoxicity and antitumor activity in vitro and in vivo. Downregulation of _GPR116_ receptor also promoted the antitumor activity of NKG2D-CAR-NK92 cells against pancreatic cancer. These findings suggest that downregulation of _GPR116_ receptor could enhance the antitumor efficiency of CAR NK cell therapy. #### 5.2.2 Pathway 2: _Ctla4-Cdba-Cdb_ The 26S proteasome (_PSMD2_) is a complex enzyme comprising a 20S core and a 19S regulator arranged in a precise structure. The 20S core consists of four rings with 28 different subunits. Two rings contain 7 alpha subunits each, while the other two contain 7 beta subunits each. The 19S regulator consists of a base with six ATPase subunits and two non-ATPase subunits, as well as a lid with up to ten non-ATPase subunits. Proteasomes are found in high concentrations throughout eukaryotic cells and break down peptides through an ATP/ubiquitin-dependent process outside lysosomes. The immunoproteasome, a modified version, plays a critical role in processing class I MHC peptides. This gene codes for one of the non-ATPase subunits in the lid of the 19S regulator. Besides its involvement in proteasome function, this subunit may also participate in the TNF signaling pathway as it interacts with the tumor necrosis factor type 1 receptor. A non-functional copy of this gene has been found on chromosome 1. Multiple transcript variants of this gene are produced through alternative splicing. _PSMD2_ and _PSMD8_ were significantly over-expressed in bladder urothelial carcinoma (BLCA) more than other cancers [49]. Besides, _PSMD8_ with _AUNIP_, _FANCI_, _LASP1_, and _XPO5_ are potential targets for the creation of an mRNA vaccine to combat mesothelioma [67]. _PAK1_ is responsible for producing a member of the PAK protein family, which are serine/threonine p21-activating kinases. PAK proteins connect RhoGTPases to reorganize the cytoskeleton and nuclear signaling. They act as targets for small GTP-binding proteins such as CDC42 and RAC. This particular family member specifically regulates the movement and shape of cells. Different isoforms of this gene have been identified through alternative splicing, resulting in various transcript variants. Regarding its mechanism, ipomoea batatas polysaccharides specifically encourage the degradation of _PAK1_ through ubiquitination and inhibit its downstream Akt1/mTOR signaling pathway, thereby resulting in an increased level of autophagic flux [11]. _PAK1_ is a serine/threonine kinase gene overexpressed in some human breast carcinomas with poor prognosis, and aberrant _PAK1_ expression is an early event in the development of some breast cancers [18]. The structure of the actin cytoskeleton and protrusions in SW620 cells is related to their ability to move. Ce6-PDT treatment inhibits the migration of SW620 cells by reducing the activity of the _RAC1/PAK1/LIMK1_/cofilin signaling pathway, and this inhibition is improved by decreasing the expression of the _RAC1_ gene [60]. The increased presence of _WLS_ (Wnt Ligand Secretion Mediato) is an important indication of a negative outcome in breast cancer. It may have a vital function in the hormone receptor-positive (HR+) subtype [68]. Reducing the expression of _SNHG17_ in lung adenocarcinoma cells hindered cell growth, migration, and invasion while increasing apoptosis. _SNHG17_ acted as a sponge for miR-485-5p, resulting in increased expression of WLS. Therefore, _SNHG17_ accelerates lung adenocarcinoma progression by upregulating _WLS_ expression through sponging miR-485-5p [30]. _NDUFS5_ belongs to the NADH dehydrogenase (ubiquinone) iron-sulfur protein family. The protein it encodes is a component of the NADH - ubiquinone oxidoreductase (complex I), which is the initial enzyme complex in the electron transport chain situated in the inner membrane of mitochondria. Through alternative splicing, multiple transcript variants of this gene are generated. Additionally, pseudogrees of this gene have been discovered on chromosomes 1, 4, and 17. Machine learning algorithms have been used to classify some cancer types, but not lung adenocarcinoma, in which _NDUFS5_, _P2RY2_, _PRPF18_, _CCL24_, _ZNF813_, _MYL6_, _FLJ41941_, _POU5F1B_, _and SUV420H1_ were associated with alive without disease [17]. The study identified _MACF1_ with _FTSJ3_, _STAT1_, _STX2_, _CDX2_ and _RASSF4_ that can be used as a signature to predict the overall survival of pancreatic cancer patients [62]. The poor response of low-grade serous ovarian carcinoma (LGSOC) to chemotherapy calls for a thorough genomic analysis to identify new treatment options. This study, 71 LGSOC samples were analyzed for 127 candidate genes using whole exome sequencing and immunohistochemistry to assess key protein expression. Mutations in _KRAS_, _BRAF_, and _NRAS_ genes were found in 47% of cases. Several new driver genes were identified, including _USP9X_, _MACF1_, _ARID1A_, _NF2_, _DOTIL_, and _ASH1L_[13]. To improve the treatment of glioblastomas and enhance patient survival, _MACF1_ can be used as a specific diagnostic marker that enhances the effectiveness of radiation therapy while minimizing damage to normal tissues [10]. This approach could potentially lead to the development of new combination radiation therapies that target translational regulatory processes, which are often involved in poor patient outcomes. Another study presented data indicating that reduced _MACF1_ expression inhibited melanoma metastasis in mice by blocking the epithelial-to-mesenchymal transition process. Therefore, _MACF1_ could be a potential target for melanoma treatment [57]. _MACF1_ is responsible for producing a substantial protein that consists of multiple spectrin and leucine-rich repeat (LRR) domains. The encoded protein belongs to a family of proteins that connect various cytoskeletal components. Specifically, this protein plays a role in enabling interactions between actin and microtubules at the outer edges of cells, and it also connects the microtubule network to cellular junctions. Multiple transcript variants of this gene are produced through alternative splicing, although the complete structure of some of these variants has yet to be determined [20]. A study included 695 patients with hepatocellular carcinoma (HCC), divided into a training group of 495 patients and a validation group of 200 patients [24]. A nomogram was developed using T stage, age, and the mutation status of _DOCK2_, _EYS_, _MACF1_, and _TP53_. The nomogram was found to have good accuracy in predicting outcomes and was consistent with the actual data. The study also found that T-cell exclusion may be a potential mechanism for malignant progression in the high-risk group. In contrast, the low-risk group may benefit from immunotherapy and _CTLA4_ blocker treatment. In conclusion, the study developed a nomogram based on mutant genes and clinical parameters and identified the underlying association between these risk factors and immune-related processes. #### 5.2.3 Pathway 3: _Ctla4-cd2_ Fucoxanthin is a natural pigment present in brown seaweeds, and its derivative, fucoxanthin (FxOH), has been shown to effectively induce apoptosis (programmed cell death) in various types of cancer cells. The role of Chloride intracellular channel 4 (_CLIC4_), which plays a crucial role in cancer development and apoptosis, in FxOH-induced apoptosis was also investigated [63]. Treatment with FxOH induced apoptosis in human CRC DLD-1 cells. FxOH treatment downregulated _CLIC4_, integrin beta1, _NHERF2_, and _pSMAD2_ (Ser(465/467)) compared to control cells, without affecting _RAB35_ expression. _CLIC4_ knockdown suppressed cell growth and apoptosis, and apoptosis induction by FxOH was reduced with _CLIC4_ knockdown. The expression levels of _CLIC4_ and _GAS2L1_ were found to be higher in circulating tumor cells (CTCs) from pancreatic cancer patients compared to peripheral blood mononuclear cells [71]. Besides, the overexpression of _CLIC4_ was associated with unfavorable outcomes in multiple cohorts of CN-AML patients [22]. The role of actin-binding proteins, including profiling, fascin, and ezrin, in the metastasis of non-small cell lung cancer (NSCLC) [28]. The study collected tumor and adjacent normal lung tissue samples from 46 NSCLC patients and used real-time PCR and Western blotting to determine the levels of _PFN1_, _FSCN1_, and _EZR_ mRNAs and proteins. The results showed that patients with lymphatic metastasis had higher expression levels of the profilin, fascin, and ezrin mRNAs and profilin and fascin proteins. In contrast, mRNA and protein expression levels increased in patients with distant metastasis. The activation of AKT signaling in the progression of colorectal cancer (CRC) can be influenced by the lncHCPC9/miR-299-3p/_PFN1_[4]. The loss of _PFN1_ leads to the activation of several signaling pathways, including AKT, NF-(k)B, and WNT. On the other hand, overexpression of PFN1 in cells with high levels of SH3BGRL can counteract SH3BGRL-induced metastasis and tumor growth by upregulating _PTEN_ and inhibiting the PI3K-AKT pathway [66]. _PPMIG_ codes for a large protein that contains spectrin and leucine-rich repeat (LRR) domains. It belongs to a family of proteins that act as bridges between different cytoskeletal elements. Specifically, this protein facilitates the interaction between actin and microtubules at the periphery of cells and links the microtubule network to cellular junctions. The level of _PPMIG_ expression in LIHC may be influenced by promoter methylation, CNVs, and kinases and could be linked to immune infiltration. High _PPMIG_ expression was found to be related to mRNA splicing and the cell cycle according to GO terms. These findings suggest that _PPMIG_ could be a prognostic indicator for liver hepatocellular carcinoma patients and may play a role in the tumor immune microenvironment [31]. Besides, the irc-_PGAP3_ plays a significant role in the growth and advancement of triple-negative breast cancer (TNBC), thus making it a potential target for the treatment of TNBC patients. #### 5.2.4 Pathway 4: _Ctla4-CD2-CD48-CD53-CD58-CD84_ _MTIG_ (Metallothioneen 1G) and _MTIH_ have the potential to suppress tumor growth and are regulated by DNA methylation in their promoter regions. In addition, they are associated with serum copper levels and may be linked to the survival rate of patients with hepatocellular carcinoma [54]. Besides, _MTIG_, _CXCL8_, _IL1B_, _CXCL5_, _CXCL11_, and _GZMB_ are over-expressed in colorectal cancer tissues compared to normal tissues [34]. Three genes (_SLC7A11_, _HMOX1_, and _MT1G_) were identified as differentially expressed genes (DEGs) associated with renal cancer prognosis using survival analysis screening [14]. _SLC7A11_ and _HMOX1_ were found to be upregulated in renal cancer tissues, while _MTIG_ was downregulated. The combination of receiver operating characteristic (ROC) curves, Kaplan-Meier analysis, and Cox regression analysis revealed that high expression of _SLC7A11_ was a prognostic risk factor for four different types of renal cancers, low expression of _HMOX1_ was a poor prognostic marker for patients, and increased expression of _MTIG_ increased the prognostic risk for three additional classes of renal cancer patients, except for those with renal papillary cell carcinoma. _FAM107A_ (Family With Sequence Similarity 107 Member A) with _ADAM12_, _CEP55_, _LRFN4_, _INHBA_, _ADHIB_, _DPT_, and _LOC100506388_ were analyzed and evaluated as potential prognostic genes for gastric cancer [23]. Among these genes, _LRFN4_, _DPT_, and _LOC100506388_ were identified as having a potential prognostic role in gastric cancer, as determined through a nomogram. Besides, the interaction pairs of _HCG22/EGOT-hsa-miR-1275-FAM107A_ and _HCG22/EGOT-hsa-miR-1246-_Glycerol-3-phosphate dehydrogenase 1 are likely to have a significant role in laryngeal squamous cell carcinoma. _LCN2_ is responsible for producing a protein classified as a lipocalin family member. Lipocalins are known for their ability to transport small hydrophobic molecules like lipids, steroid hormones, and retinoids. The specific protein encoded by this gene is called neutrophil gelatinase-associated lipocalin (NGAL), and it plays a significant role in innate immunity. NGAL sequesters iron-containing siderophores, which helps limit bacterial growth and infection [20]. Besides, _LCN2_ is an innate immune protein that regulates immune responses by promoting sterile inflammation. _LCN2_ is a biomarker associated with radioresistance and recurrence in nasopharyngeal carcinoma (NPC) [65]. _LCN2_ expression was upregulated in radioresistant NPC tissues and associated with NPC recurrence. Knocking down _LCN2_ enhances the radiosensitivity of NPC cells, while ectopic expression of _LCN2_ confers additional radioresistance. _LCN2_ may interact with _HIF-IA_ and facilitate the development of a radioresistant phenotype. _LCN2_ is a promising target for predicting and overcoming radioresistance in NPC. Moreover, the downregulation of the immune response, influenced by specific metastasis-evaluation genes (_BAMBI_, _F13A1_, _LCN2_) and their associated immune-prognostic genes (_SLIT2_, _CDKN2A_, _CLU_), was found to increase the risk of post-operative recurrence [32]. Higher _LCN2_ expression was associated with poor clinical outcomes and correlated with increased infiltration of various immune cells. _LCN2_ may serve as a biomarker for immune infiltration and poor prognosis in cancers, suggesting potential therapeutic targets for cancer treatment [61]. ## 6 Conclusion To this end, I have introduced the quantum AI model used for biomarker discovery in biomedical research (**Section**3). The proof of concept is demonstrated in four targeted pathways associating with therapeutic-target _CTL4_ in **Section**4. Our model found clinical-relevant and notably potential biomarkers/targets for cancer treatment, which are extensively validated through statistical methods and literature mining (**Section**5). I suggest several research directions that can be extended from the study. First, deploying the proposed quantum AI models on real quantum computers is worth investigating in the future, in which the effect of noise should be addressed toward the model's efficiency and effectiveness. Second, extension to other pathway activation is possible as the proposed algorithm is generalized. Finally, in _vivo_ and in _vitro_, validations of the discovered in _silico_ biomarkers will translate the findings to therapeutic solutions for cancer treatment and prevention.
2304.10031
Architectures of Topological Deep Learning: A Survey of Message-Passing Topological Neural Networks
The natural world is full of complex systems characterized by intricate relations between their components: from social interactions between individuals in a social network to electrostatic interactions between atoms in a protein. Topological Deep Learning (TDL) provides a comprehensive framework to process and extract knowledge from data associated with these systems, such as predicting the social community to which an individual belongs or predicting whether a protein can be a reasonable target for drug development. TDL has demonstrated theoretical and practical advantages that hold the promise of breaking ground in the applied sciences and beyond. However, the rapid growth of the TDL literature for relational systems has also led to a lack of unification in notation and language across message-passing Topological Neural Network (TNN) architectures. This presents a real obstacle for building upon existing works and for deploying message-passing TNNs to new real-world problems. To address this issue, we provide an accessible introduction to TDL for relational systems, and compare the recently published message-passing TNNs using a unified mathematical and graphical notation. Through an intuitive and critical review of the emerging field of TDL, we extract valuable insights into current challenges and exciting opportunities for future development.
Mathilde Papillon, Sophia Sanborn, Mustafa Hajij, Nina Miolane
2023-04-20T01:02:13Z
http://arxiv.org/abs/2304.10031v3
# Architectures of Topological Deep Learning: ###### Abstract The natural world is full of complex systems characterized by intricate relations between their components: from social interactions between individuals in a social network to electrostatic interactions between atoms in a protein. Topological Deep Learning (TDL) provides a comprehensive framework to process and extract knowledge from data associated with these systems, such as predicting the social community to which an individual belongs or predicting whether a protein can be a reasonable target for drug development. TDL has demonstrated theoretical and practical advantages that hold the promise of breaking ground in the applied sciences and beyond. However, the rapid growth of the TDL literature has also led to a lack of unification in notation and language across Topological Neural Network (TNN) architectures. This presents a real obstacle for building upon existing works and for deploying TNNs to new real-world problems. To address this issue, we provide an accessible introduction to TDL, and compare the recently published TNNs using a unified mathematical and graphical notation. Through an intuitive and critical review of the emerging field of TDL, we extract valuable insights into current challenges and exciting opportunities for future development. **Keywords**: deep learning, topology, message passing, graph, hypergraph, simplicial complex, cellular complex, combinatorial complex ## 1 Introduction Many natural systems as diverse as social networks (Knoke and Yang, 2019) and proteins (Jha et al., 2022) are characterized by _relational structure_. This is the structure of interactions between components in the system, such as social interactions between individuals or electrostatic interactions between atoms. In Geometric Deep Learning (Bronstein et al., 2021), Graph Neural Networks (GNNs) (Zhou et al., 2020) have demonstrated remarkable achievements in processing relational data using graphs--mathematical objects commonly used to encode _pairwise relations_. However, the pairwise structure of graphs is limiting. Social interactions can involve more than two individuals, and electrostatic interactions more than two atoms. Topological Deep Learning (TDL) (Hajij et al., 2023; Bodnar, 2023) leverages more general abstractions to process data with higher-order relational structure. The theoretical guarantees (Bodnar et al., 2021, 2021, 2022) of its models, Topological Neural Networks (TNNs), lead to state-of-the-art performance on many machine learning tasks (Long et al., 2020; Hajij et al., 2022; Barbarossa and Sardellitti, 2020; Chen et al., 2022)--and reveal high potential for the applied sciences and beyond. However, the abstraction and fragmentation of mathematical notation across the TDL literature significantly limits the field's accessibility, while complicating model comparison and obscuring opportunities for innovation. To address this, we present an intuitive and systematic comparison of published TNN architectures. Compared to reviews that focus on data representation (Torres et al., 2021), physics-inspired models (Battiston et al., 2021), and topological data analysis for machine learning (Hensel et al., 2021), we contribute: * **A pedagogical resource** accessible to newcomers interested in applying TNNs to real-world problems. * **A unified notational and graphical taxonomy** to intuitively summarize the landscape of TNN architectures. * **A comprehensive and critical review** of TNNs, their implementations and practical applications, with equations rewritten in our notation available at github.com/awesome-tnns. * **A summary of open research questions**, challenges, and opportunities for innovation. By establishing a common and accessible language in the field, we hope to provide newcomers and experienced practitioners alike with a solid foundation for cutting-edge research in TDL. ## 2 Topological Neural Networks Topological Neural Networks (TNNs) are deep learning architectures that extract knowledge from data associated with topologically rich systems such as protein structures, city traffic maps, or citation networks. A TNN, like a GNN, is comprised of stacked layers that transform data into a series of features (Figure 1). Each layer leverages the fundamental concepts of _data and computational domains_, _neighborhoods_, and _message passing_--presented in this section. ### Domains In Topological Deep Learning (TDL), data are features defined on discrete domains. Traditional examples of discrete domains include sets and graphs (Figure 2, Left). A **set** is a collection of points called _nodes_ without any additional structure. A **graph** is a set with _edges_ that encode _pairwise relations_ between nodes, representing either geometric proximity or more abstract relationships. For example, a graph may represent a protein, with nodes encoding its atoms and edges encoding the pairwise bonds between them. Alternatively, a graph may represent a social network, where nodes represent individuals and edges denote social relationships. The domains of TDL go _beyond graphs_, generalizing pairwise relations to _part-whole_ and _set-types_ relations that permit the representation of more complex relational structure (Figure 2, Right). Here, we describe the key attributes of each domain and highlight their suitability for different data types. We refer the reader to Torres et al. (2021) and Hajij et al. (2023) for more extensive discussions. Figure 1: **Topological Neural Network**: Data associated with a complex system are features defined on a _data domain_, which is preprocessed into a _computational domain_ that encodes interactions between the system’s components with _neighborhoods_. The TNN’s layers use _message passing_ to successively update features and yield an output, e.g. a categorical label in classification or a quantitative value in regression. The output represents new knowledge extracted from the input data. **Beyond Graphs: The Domains of Topological Deep Learning** Set + Pairwise Relations **Graph**: A set of points (_nodes_) connected with _edges_ that denote pairwise relationships. Set + Part-Whole Relations **Simplicial Complex** (SC): A generalization of a graph in which three edges can form a _triangular face_, four triangles can form a _tetrahedral volume_, and so on. Edges only connect pairs of nodes. **Cellular Complex** (CC): A generalization of an SC in which _faces, volumes, etc_ are not restricted to be triangles or tetrahedrons but may instead take any shape. Still, edges only connect pairs of nodes. Set + Set-Type Relations **Hypergraph** (HG): A generalization of a graph, in which higher-order edges called _hyperedges_ can connect arbitrary _sets_ of two or more nodes. Set + Part-Whole and Set-Type Relations **Combinatorial Complex** (CCC): A structure that combines features of HGs and CCs. Like an HG, edges may connect any number of nodes. Like a CC, cells can be combined to form higher-ranked structures. **Simplicial complexes (SCs)** generalize graphs to incorporate hierarchical _part-whole relations_ through the multi-scale construction of _cells_. Nodes are _rank 0_ cells that can be combined to form edges (_rank 1_ cells). Edges are, in turn, combined to form faces (_rank 2_ cells), which are combined to form volumes (_rank 3_ cells), and so on. As such, an SC's faces must be triangles, volumes must be tetrahedrons, and so forth. SCs are commonly used to encode discrete representations of 3D geometric surfaces represented with triangular meshes (Figure 3). They may also be used to represent more abstract relations; however, there is a risk of introducing spurious connections if the strict geometric constraints of an SC are not respected by the data--a point we elaborate on in Section 2.1.2. **Cellular complexes (CCs)** generalize SCs such that cells are not limited to simplexes: faces can involve more than three nodes, volumes more than four faces, and so on. This flexibility endows CCs with greater expressivity than SCs (Bodnar et al., 2021b). A practitioner should consider employing this domain when studying a system that features part-whole interactions between more than three nodes, such as a molecule with benzene rings (Figure 3). **Hypergraphs (HGs)** extend graphs in that their edges, called _hyperedges_, can connect more than Figure 2: Domains: Nodes in blue, (hyper)edges in pink, and faces in dark red. Inspired by Hajij et al. (2022a). two nodes. Connections in HGs represent _set-type relationships_, in which participation in an interaction is not implied by any other relation in the system. This makes HGs an ideal choice for data with abstract and arbitrarily large interactions of equal importance, such as semantic text and citation networks. Protein interaction networks (Figure 3) also exhibit this property: an interaction between proteins requires a precise set of molecules--no more and no less. The interaction of Proteins A, B, and C does not imply an interaction between A and B on their own. **Combinatorial complexes (CCCs)** generalize CCs and HGs to incorporate both _part-whole_ and _set-type_ relationships. The benefit of this can be observed in the example of molecular representation. The strict geometric constraints of simplicial and cellular complexes are too rigid for capturing much of hierarchical structure observed in molecules. By contrast, the flexible but hierarchically ranked hyperedges of a combinatorial complex can capture the full richness of molecular structure, as depicted in Figure 3. #### 2.1.1 Terminology Across discrete domains, we use the term _cell_ to denote any node or relation between nodes such as (hyper)edges, faces, or volumes. Cells possess two attributes: _size_--the number of cells it contains--and _rank_--where nodes are said to have rank 0, edges and hyperedges rank 1, faces rank 2, and so on. The part-whole relationships of simplicial and cellular complexes impose a relationship between the _rank_ of a cell and its _size_: cells of rank \(r\) contains exactly (resp. at least) \(r+1\) cells of rank \(r-1\): faces (\(r=2\)) contain exactly (resp. at least) three edges (\(r-1=1\)). By contrast, hypergraph cells do not encode part-whole relations and hyperedges may have any size. However, hypergraph cells are limited to ranks 0 and 1. A combinatorial complex is unrestricted in both rank and size: nodes have rank 0 and cells of any size \(>1\) can have any rank. There is an important distinction between the inherent domain of the data (the _data domain_) and the domain in which the data will be processed within a TNN: the _computational domain_. Data defined on a graph, for example, may be "lifted" (Figure 4) to an alternative domain through a pre-processing stage (Figure 1). For instance, a protein originally given as the graph of its atoms (nodes) and covalent bounds (edges) may be lifted into a CC computational domain that explicitly represents its rings (faces). In this review, _domain_ refers to the computational domain. Additionally, the computational domain may be _dynamic_, changing from layer to layer in a TNN. Figure 3: **Examples of Data on Topological Domains.** (a) Higher-order interactions in protein networks. (b) Limited molecular representation: rings can only contain three atoms. (c) Triangular mesh of a protein surface. (d) More flexible molecular representation, permitting the representation of any ring-shaped functional group. (e) Flexible mesh which includes arbitrarily shaped faces. (f) Fully flexible molecular representation, permitting the representation of the complex nested hierarchical structure characteristic of molecules and other natural systems. (g) Hierarchical higher-order interactions in protein networks. #### 2.1.2 Limitations An important limitation of both SCs and CCs is that faces (and analogous higher-order structures) can only form rings; the nodes on the boundary of the face must be connected in pairs. In many cases, this requirement is too stringent and can introduce artificial connections to the domain (Yang et al., 2022). For instance, lifting a citation network into an SC necessarily requires that any set of three co-authors having written a paper together (A, B, C) are also pairwise connected (A and B, A and C, B and C), even if no paper was ever exclusively authored by authors A and B, authors A and C, or authors B and C. Yang et al. (2022) propose a "relaxed" definition of the SC that remedies this. They show how training a TNN on such a modified domain increases performance. We note that even with artificial connections, SCs and CCs allow TNNs to leverage richer topological structure and avoid computational problems faced by GNNs (Rusch et al., 2023). We further note that any topological domain is mathematically equivalent to a (possibly larger) graph (Velickovic, 2022). We choose to express domains in their form above in order to provide better intuition to newcomers and reflect the widely adopted approaches in the literature. #### 2.1.3 Features on a Domain Consider a domain, denoted \(\mathcal{X}\), encoding relationships between components of a system. Data on the domain are represented as features supported on the domain's cells. Typically, features are vectors in \(\mathbb{R}^{d}\) that encode attributes of each cell. For example, features may encode the atom (node), bond (edge), and functional group (face) types in a molecule. A feature associated with the interaction between a set of drugs (hyperedge) could indicate the probability of adverse reaction. We denote with \(\mathbf{h}_{x}^{t_{(r)}}\) a feature supported on the cell \(x\in\mathcal{X}\) at layer \(t\) of the TNN, with \(r\) indicating the rank of \(x\) (Figure 5). The domain is decomposed into ranks, with \(X^{(r)}\), or \(r\)_-skeleton_, referring to all cells of rank \(r\). Features can be categorical or quantitative. If the feature dimension varies across skeletons, the domain is _heterogeneous_. Figure 4: **Lifting Topological Domains.** (a) A graph is “lifted” to a hypergraph by adding hyperedges that connect groups of nodes. (b) In the process of lifting a graph to a simplicial complex, a pairwise edge must be added in order to form triangular faces. (c) A graph can be converted to a cellular complex by adding faces of any shape. (d) Hyperedges can be added to a cellular complex to lift the structure to a combinatorial complex. Figure adapted from Hajij et al. (2023). **Heterogeneous Domains** **Homogeneity vs. Heterogeneity**: In a _heterogeneous_ domain, the dimension \(d_{r}\) of a feature \(\mathbf{h}_{x}^{(r)}\) depends on the rank \(r\) of the cell \(x\) supporting it. A _homogeneous_ domain uses the same dimensionality \(d\) for all ranks. The features assigned to each cell may come directly from the data or be hand-designed by the practitioner. Alternatively, features can be assigned in a pre-processing stage using _embedding_ methods, which compute cell feature vectors that encode the local structure of the space. For graphs, methods such as DeepWalk (Perozzi et al., 2014) and Node2Vec (Grover and Leskovec, 2016) are commonly used to embed nodes. Recent works have generalized these approaches to topological domains: Hyperedge2Vec (Sharma et al., 2018) and Deep Hyperedge (Payne, 2019) for hypergraphs, Simplex2Vec (Billings et al., 2019) and k-Simplex2Vec (Hacker, 2020) for simplicial complexes, and Cell2Vec (Hajji et al., 2020) for cellular complexes. ### Neighborhood Structure A TNN successively updates cell features throughout its layers by using a notion of _nearness_ between cells: the _neighborhood structure_ (Figure 1). Neighborhood structures are defined by **boundary relations**, which describe how cells of different ranks relate to each other. A cell \(y\) of rank \(r\) is said to be on the **boundary** of cell \(x\) of rank \(R\) if it is connected to \(x\) and rank \(r<R\). This relation is expressed as \(y\prec x\). For example, a node connected to an edge is said to be on the boundary of that edge. Figure 5: **Features on a Domain. Left: Features onto three cells—\(x\), \(y\), and \(z\). Right: Skeletons for the entire complex: \(X^{(0)}\) contains node features, \(X^{(1)}\) contains edge features, and so on.** Figure 6: **Incidence Matrices. Examples of an SC, a CC, an HG, and a CCC with their corresponding boundary matrices \(B_{1}\) which map from 1-cells to 0-cells. The SC and CC maps are signed to encode edge orientation: the node appearing first in the arbitrary ordering (a,b,c,d) is always assigned -1.** Boundary relations are encoded in **incidence matrices**. Specifically, we denote with \(B_{r}\) the matrix that records which (regular) cells of rank \(r-1\) bound which cells of rank \(r\) (Figure 6). Formally, \(B_{r}\) is a matrix of size \(n_{r-1}\cross n_{r}\), with \(n_{r}\) denoting the number of cells of rank \(r\geq 1\), defined: \[(B_{r})_{i,j}=\begin{cases}\pm 1&x_{i}^{(r-1)}\prec x_{j}^{(r)}\\ 0&\text{otherwise},\end{cases} \tag{1}\] where \(x_{i}^{(r-1)}\), \(x_{j}^{(r)}\) are two cells of ranks \(r-1\) and \(r\) respectively. The \(\pm 1\) sign encodes a notion of orientation required for SCs and CCs (Aschbacher, 1996; Klette, 2000), and is always \(+1\) for HGs and CCCs. Incidence matrices can be used to encode the four most common neighborhood structures used in the literature, which we define in the text box below. Here, \(L_{\uparrow,0}\) denotes the typical graph Laplacian. Its higher order generalization, the \(r\)-Hodge Laplacian, is \(H_{r}=L_{\downarrow,r}+L_{\uparrow,r}\)(Barbarossa and Sardellitti, 2020; Schaub et al., 2021). \(D_{r}\in\mathbb{N}^{n_{r}\times n_{r}}\) denotes the degree matrix, a diagonal matrix representing the number of connections of \(r\)-cells with \((r+1)\)-cells. **Neighborhood Structures** **Boundary Adjacent Neighborhood**\(\mathcal{B}(y)=\{x\mid x\prec y\}\): The set of \(y\)-connected \(x\) cells of next lower rank. The neighborhood is specified with the _boundary matrix_\(B_{r}\). _Example: The set of nodes \(x\) connected to edge \(y\)_. **Co-Boundary Adjacent Neighborhood**\(\mathcal{C}(y)=\{x\mid y\prec x\}\): The set of \(y\)-connected \(x\) cells of next higher rank. The neighborhood is specified with the _co-boundary matrix_\(B_{r}^{T}\). _Example: The set of edges \(x\) connected to node \(y\)_. **Lower Adjacent Neighborhood**\(\mathcal{L}_{1}(y)=\{x\mid\exists x\text{ s.t. }z\prec y\text{ and }z\prec x\}\): The set of \(x\) cells that share a boundary \(z\) with \(y\). The neighborhood is specified with either the _lower Laplacian matrix_\(L_{\downarrow,r}=B_{r}B_{r}^{T}\) or the _lower adjacency matrix_\(A_{\downarrow,r}=D_{r}-L_{\downarrow,r}\). _Example: the set of edges \(x\) that connect to any of the nodes \(z\) that touch edge \(y\)_. **Upper Adjacent Neighbors**\(\mathcal{L}_{\uparrow}(y)=\{x\mid\exists z\text{ s.t. }y\prec z\text{ and }x\prec z\}\): The set of \(x\) cells that share a co-boundary \(z\) with \(y\). The neighborhood is specified with either the _upper Laplacian matrix_\(L_{\uparrow,r}=B_{r+1}^{T}B_{r+1}\) or the _upper adjacency matrix_\(A_{\uparrow,r}=D_{r}-L_{\uparrow,r}\). _Example: The set of nodes \(x\) that touch any of the edges \(z\) that touch node \(y\)_. Figure 7: Neighborhood Structures: their neighborhood matrices and illustrations for a cell \(x\) in the neighborhood of a cell \(y\). ### Message Passing _Message passing_ defines the computation performed by a single layer \(t\) of the TNN. During message passing, each cell's feature \(\mathbf{h}_{\mathbf{x}}^{t,(\mathbf{r})}\) is updated to incorporate: (1) the features associated with cells in its neighborhood and (2) the layer's learnable parameters denoted \(\Theta^{t}\). The term "message passing" reflects that a signal is "traveling" through the network, passing between cells on paths laid out by the neighborhood structure. The output \(\mathbf{h}^{t+1}\) of layer \(t\) becomes the input to layer \(t+1\). In this way, deeper layers incorporate information from more distant cells, as information diffuses through the network. #### 2.3.1 The Steps of Message Passing We decompose message passing into four steps, adapted from the framework of Hajij et al. (2022). Each step is represented with a different color--_red_, _orange_, _green_, or _blue_--illustrated in Figure 8. **The Steps of Message Passing** **1. Message:** First, a message \(m_{y\to x}^{(r^{\prime}\to r)}\) travels from a \(r^{\prime}\)-cell \(y\) to a \(r\)-cell \(x\) through a neighborhood \(k\) of \(x\) denoted \(\mathcal{N}_{k}(x)\): \[m_{y\to x}^{(r^{\prime}\to r)}=M_{\mathcal{N}_{k}}\left(\mathbf{h}_{x}^{t,(r) },\mathbf{h}_{y}^{t,(r^{\prime})},\Theta^{t}\right). \tag{2}\] via the function \(M_{\mathcal{N}_{k}}\) depicted in red in Figure 8. Here, \(\mathbf{h}_{x}^{t,(r)}\) and \(\mathbf{h}_{y}^{t,(r^{\prime})}\) are features of dimension \(d_{r}\) and \(d_{r^{\prime}}\) on cells \(y\) and \(x\) respectively, and \(\Theta^{t}\) are learnable parameters. In the simplest case, this step looks like a neighborhood matrix \(M\) propagating a feature \(\mathbf{h}_{y}^{t,(r^{\prime})}\) on \(r^{\prime}\)-cell \(y\) to \(r\)-cell \(x\) as: \[m_{y\to x}^{(r^{\prime}\to r)}=M_{xy}\cdot\mathbf{h}_{y}^{t,(r^{\prime})} \cdot\Theta^{t}, \tag{3}\] where \(M_{xy}\) is the scalar entry of matrix \(M\) at the row corresponding to cell \(x\) and column corresponding to cell \(y\) and \(m_{y\to x}^{(r^{\prime}\to r)}\) and \(\Theta\) is a \(d_{r^{\prime}}\times d_{r}\) matrix. If \(y\) is not in the neighborhood structure of \(x\), then \(M_{xy}\) will be 0, and \(x\) cannot receive any message from \(y\). 2. Within-Neighborhood Aggregation: Next, messages are aggregated across all cells \(y\) belonging to the neighborhood \(\mathcal{N}_{k}(x)\): \[m_{x}^{(r^{\prime}\to r)}=AGG_{y\in\mathcal{N}_{k}(x)}m_{y\to x}^{(r^{\prime} \to r)},\] (4) resulting in the _within-neighborhood aggregated message_\(m_{x}^{(r^{\prime}\to r)}\). Here, \(AGG\) is an aggregation function, depicted in orange in Figure 8, analogous to pooling in standard convolutional networks. **3. Between-Neighborhood Aggregation:** Then, messages are aggregated across neighborhoods in a neighborhood set \(\mathcal{N}\): \[m_{x}^{(r)}=AGG_{\mathcal{N}_{k}\in\mathcal{N}}m_{x}^{(r^{\prime}\to r)}, \tag{5}\] where \(\mathrm{AGG}\) is a (potentially different) aggregation function depicted in green in Figure 8, and \(m_{x}^{(r)}\) is the message received by cell \(x\) that triggers the update of its feature. 4. Update: Finally, the feature on cell \(x\) is updated via a function \(U\) depicted in blue in Figure 8, which may depend on the previous feature \(\mathbf{h}_{x}^{t,(r)}\) on cell \(x\): \[\mathbf{h}_{x}^{t+1,(r)}=U\left(\mathbf{h}_{x}^{t,(r)},m_{x}^{(r)}\right), \tag{6}\] The result \(\mathbf{h}_{x}^{t+1,(r)}\) is the updated feature on cell \(x\) that is input to layer \(t+1\). In this review, we decompose the structure of TNN architectures proposed in the literature into these four message passing steps--a unified notational framework that allows us to contrast existing approaches. Many architectures repeat steps and/or modify their order. We note that this conceptualization of message passing as a local, cell-specific operation is called the _spatial approach_(Gilmer et al., 2017). In GNNs and TNNs alike, message passing can alternatively be expressed in its dual _spectral_ form, using global Fourier analysis over the domain. For this review, we choose to write all equations in spatial form for intuitiveness and generality (Bodnar et al., 2021; Hajji et al., 2022; Heydari and Livi, 2022). #### 2.3.2 Tensor Diagrams We visually represent message passing schemes with an adapted version of the _tensor diagram_ from Hajji et al. (2022), which provides a graphical representation of a TNN architecture. Figure 8 explains the recipe for constructing a tensor diagram from message passing steps. Figure 8: **Message passing steps: 1: Message (red), 2: Within-neighborhood aggregation (orange), 3: Between-neighborhood aggregation (green), 4: Update (blue). The scheme updates a feature \(\mathbf{h}_{x}^{t(r)}\) on a \(r\)-cell \(x\) at layer \(t\) (left column) into a new feature \(\mathbf{h}_{x}^{t+1,(r)}\) on that same cell at the next layer \(t+1\) (right column). Here, the scheme uses four neighborhood structures \(\mathcal{N}_{k}\) for \(k\in\{1,2,3,4\}\) (middle column). Inspired by (Hajji et al., 2023).** Figure 9: **Tensor Diagrams: a graphical notation for the four steps of a message passing scheme. A diagram depicts how a feature on cell \(y\) at layer \(t\), \(\mathbf{h}_{y}^{t(t)}\), becomes a feature on cell \(x\) at layer \(t+1\), \(\mathbf{h}_{x}^{t(t+1)}\).** #### 2.3.3 Types of Message Passing Functions The message passing function \(M_{\mathcal{N}_{k}}\) employed in Step 1 is defined by the practitioner. There are three kinds of functions commonly used in the literature, as outlined in Figure 10(Bronstein, 2022). The variety used determines how layer parameters weight each incoming message from cell \(y\) to cell \(x\). The _standard convolutional_ case multiplies each message by some learned scalar. The _attentional convolutional_ case weights this multiplication depending on the features of the cells involved. The _general_ case implements a potentially non-linear function that may or may not incorporate attention. Some schemes also make use of fixed, non-learned weights to assign different levels of importance to higher-order cells. Figure 10 illustrates each type with tensor diagrams. ## 3 Literature Review We now review the literature on topological neural networks (TNNs) over hypergraphs, simplicial complexes, cellular complexes, and combinatorial complexes, using the conceptual framework of Section 2. We summarize and compare the TNNs in terms of their architectures (Section 3.1), the machine learning tasks to which they have been applied (Section 3.2), and their geometric properties (Section 3.3). ### Architectures Figure 11 summarizes TNN architectures according to the fundamental concepts introduced in Section 2, with the _domain_ on the vertical axis, the _message passing type_ on the horizontal axis, _neighborhood structures_ and _message passing equations_ visually represented with tensor diagrams. We share complete message passing equations for each architecture--decomposed according to the four steps introduced in Section 2.3.1 and rewritten in unifying notations --at github.com/awesome-tnns. #### 3.1.1 Hypergraphs Of the domains considered here, hypergraph neural networks have been most extensively researched, and have been surveyed previously (Ling et al., 2021; Gao et al., 2022; Hu et al., 2021; Wang et al., Figure 10: **Types of Message Passing Functions.** In each case, a cell \(x_{i}\) (an edge) receives information from its various neighbors, cells \(y_{j}\) (two nodes, an edge, and a face). The message received by cell \(x_{i}\) from cell \(y_{j}\) is determined by a specific function \(c(x_{i},y_{j})\), \(a(x_{i},y_{j})\), or \(g(x_{i},y_{j})\). Top: Each neighborhood cell \(y_{j}\) sends a message to cell \(x_{i}\). (Inspired by P. Velickovic and (Bronstein, 2022)). Bottom: Illustration of the message-passing scheme above using tensor diagrams. Figure 11: **Topological Neural Networks (TNNs): A Graphical Literature Review. We organize TNNs according to the _domain_ (rows), the _message passing type_ (columns).** 2021a; Fischer et al., 2021). Many papers in the early literature do not use hypergraphs as the computational domain. Rather, algorithms like clique-expansion (Zien et al., 1999; Agarwal et al., 2005; Zhou et al., 2006) are used to reduce hypergraphs to graphs, which are then processed by the model. This reduction adversely affects performance, as structural information is lost (Hein et al., 2013; Li et al., 2013; Chien et al., 2019). Many such graph-based models--including HGNN (Feng et al., 2019), HyperConv(Bai et al., 2021), HyperGCN (Yadati et al., 2019), and HNHN (Dong et al., 2020)--are used as benchmarks for more recent models that _do_ computationally operate on hypergraphs. Here, we focus on models that preserve hypergraph structure during learning. Many hypergraph models use a message passing scheme comprised of two phases, with information flowing from nodes to their hyperedges and then back to the nodes. We call this the _two-phase scheme_. The scheme appears in many tensor diagrams of Figure 11 where information flows from blue to pink (phase 1) and then from pink to blue (phase 2). The scheme is used in models with both standard and attentional message passing. **Standard** Of those using a standard message passing, the models from Arya et al. (2020), Yi and Park (2020), Wei et al. (2021), and Huang and Yang (2021) use the two-phase scheme. Yi and Park (2020) is unique in using a learnable weight matrix in the first phase of message passing. On the second phase, Wei et al. (2021) and the UniGCN model from Huang and Yang (2021) are unique in using a fixed weight matrix on top of learnable weights. In Arya et al. (2019), Yi and Park (2020), and the UniGNN, UniSAGE, and UniGCNII models from Huang and Yang (2021), the initial feature on each node is recurrently used to update each incoming message--denoted with a looped black arrow in Figure 11. We note that Huang and Yang (2021) systematically generalizes some of the most popular GNN architectures to hypergraphs with its unifying framework: UniGNN. In Dong et al. (2020), fixed weights are used on both the node to hyperedge and hyperedge to node phases. The paper AllSet (Chien et al., 2022) uses a similar structure while incorporating fully learnable multi-set functions for neighborhood aggregation, which imbues its TNNs with high expressivity and generality. EHNN (Kim et al., 2022) (excluded from Figure 11 for its complexity; see written equations) proposes a maximally expressive model using sparse symmetric tensors to process data on hypergraphs with uniformly sized hyperedges. **Attentional / General** The models from Jiang et al. (2019), Ding et al. (2020), Yi and Park (2020), Wang et al. (2021a), and the UniGAT model from Huang and Yang (2021) employ the two-phase scheme in concert with attentional message passing. The architectures of Li et al. (2022) and Li et al. (2022) apply multi-head attention. Heydari and Livi (2022) adapts the two-phase scheme in order to update node features through two parallel paths. Chien et al. (2022) and Kim et al. (2022) offer transformer-based variants of their standard architectures, concurrently with Li et al. (2022). #### 3.1.2 Simplicial Complexes Simplicial complexes were first explored from a signal processing perspective (Battiston et al., 2020), with initial focus on edge flows (Jiang et al., 2011; Schaub and Segarra, 2018), Hodge Laplacians (Barbarossa and Sardellitti, 2020; Schaub et al., 2020), and convolution (Yang et al., 2021, 2022b; Isufi and Yang, 2022). As a precursor to deep learning, Roddenberry and Segarra (2019) introduced \(\mathcal{L}_{\downarrow,1}\) in HodgeNet to learn convolutions on edge features on graphs. This contrasts with former GNN approaches processing node features. **Standard** Ebli et al. (2020) (SNN) and Bunch et al. (2020) (SCCONV) first generalized the convolutional approach of Roddenberry and Segarra (2019) to features supported on faces and cells of higher ranks. Unlike HodgeNet, SNN and SCCONV use both \(\mathcal{L}_{\downarrow,1}\) and \(\mathcal{L}_{\uparrow,1}\). In SNN (Ebli et al., 2020) messages are not passed between adjacent ranks. By contrast, SCCONV uses independent boundary and co-boundary neighborhoods, hence incorporating features from adjacent ranks. Yang et al. (2022c) also makes use of this multi-neighborhood scheme for updating and classifying edge features. They also propose a single neighborhood scheme with an update including the initial cell's feature. Roddenberry et al. (2021) and Yang et al. (2022d) devise schemes where messages coming from \(\mathcal{L}_{\downarrow,1}\) and \(\mathcal{L}_{\uparrow,1}\) are weighted separately, providing greater learning flexibility. Yang et al. (2022d) allows features to travel multiple hops through the domain by using a polynomial form of the neighborhood structures, leveraging the simplicial convolutional filter fromYang et al. (2022b). Yang and Isufi (2023) extend this multiple-hop model with additional neighborhood structures. Keros et al. (2022) used a modified version of \(\mathcal{L}_{\downarrow}\) to find signals coiled around holes in the complex. BSCNet (Chen et al., 2022) combines node and edge-level shifting to predict links between nodes. This was the first model to pass messages between arbitrary ranks, leveraging a pseudo Hodge Laplacian. MPSN (Bodnar et al., 2021a) explicitly details their message-passing scheme in the spatial domain, subsuming previous models described from a spectral approach. Hajji et al. (2022b) introduces High Skip Networks (HSNs), in which each layer updates features through multiple sequential convolutional steps, "skipping" it through higher ranks as a generalization of skip-connections in conventional neural networks. **Attentional / General** SAN (Giusti et al., 2022a), SAT (Goh et al., 2022), and SGAT (Lee et al., 2022) concurrently introduced attentional message passing networks on the simplicial domain. Each model makes use of a unique set of neighborhood structures and attention coefficients. SGAT is the only model as of yet developed for heterogeneous simplicial complexes of general rank. Hajji et al. (2022c) introduces a variety of general message passing schemes with two neighborhood structures. Bodnar et al. (2021a) uses all four neighborhood structures, endowing each with a separate learnable matrix and general aggregation function. #### 3.1.3 Cellular Complexes Just as for simplicial complexes, cellular complex networks have been significantly influenced by work in signal processing (Barbarossa and Sardellitti, 2020; Sardellitti et al., 2021; Roddenberry et al., 2022). These works demonstrated that representing data in the CC domain yields substantially better results than the more rigid SC domain. **Standard** Roddenberry et al. (2022) proposes theoretically possible message passing schemes for CCs inspired by works in the SC domain. As of yet, these models have not been implemented. **Attentional / General** Hajji et al. (2020) introduces the first TNNs to be theoretically defined on the CC domain. Bodnar et al. (2021b) was the first to implement and evaluate such a model, and demonstrated that TNNs on CCs outperform state-of-the-art graph-based models in expressivity and classification tests. The CAN model from (Giusti et al., 2022b) adapts a modified version of the message passing scheme from Giusti et al. (2022a) onto the CC domain. #### 3.1.4 Combinatorial Complexes The combinatorial complex domain was only recently mathematically defined by Hajji et al. (2022a). This work introduces four attentional message passing schemes for CCCs tailored to mesh and graph classification. A more extensive analysis is needed to quantify the advantages of this domain over other topological domains. ### Tasks Table 3.2 reviews the tasks studied by each paper proposing TNNs. Tasks are first categorized into: _node-level_ tasks assigning labels to nodes, as in node classification, regression or clustering; _edge-level tasks_ assigning labels to edges, as in edge classification or link prediction; and _complex-level_ tasks assigning labels to each complex as a whole, as in hypergraph classification. Tasks are additionally labeled according to their purpose (e.g. classification, regression, prediction). We also indicate the extent of benchmarking performed on each model and code availability. \begin{table} \begin{tabular}{l l l l l l} \hline \hline **Domain** & **Model** & **Task Level** & **Task Purpose** & **Comparisons** \\ \hline \hline **HG** & HyperSage Arya et al. (2020) & ✓ & & Classification (Inductive + Transductive) & GNN SOTA \\ \cline{2-5} & AllSet Chien et al. (2022) & ✓ & & Classification & TNN SOTA \\ \cline{2-5} & HyperGat Ding et al. (2020) & ✓ & & Classification & GNN SOTA \\ \cline{2-5} & HNHN Dong et al. (2020) & ✓ & ✓ & Classification, Dimensionality Reduction & GNN SOTA \\ \cline{2-5} & HMPNN* Heydari and Livi (2022) & ✓ & & Classification & TNN SOTA \\ \cline{2-5} & UniGNN Huang and Yang (2021) & ✓ & & Classification (Inductive + Transductive) & TNN SOTA \\ \cline{2-5} & DHGNN Jiang et al. (2019) & ✓ & & Classification (Multimodal) & GNN SOTA \\ \cline{2-5} & EHNN Kim et al. (2022) & ✓ & & Classification, Keypoint Matching & TNN SOTA \\ \cline{2-5} & HHNN Li et al. (2022a) & ✓ & & Link prediction & TNN SOTA \\ \cline{2-5} & HTNN Li et al. (2022b) & ✓ & & Classification & TNN SOTA \\ \cline{2-5} & SHARE* Wang et al. (2021a) & ✓ & & Prediction & GNN SOTA \\ \cline{2-5} & DHGCN* Wei et al. (2021) & & ✓ & Classification & GNN SOTA \\ \cline{2-5} & HGC-RNN* Yi and Park (2020) & ✓ & & Prediction & GNN SOTA \\ \hline **SC** & MPSN Bodnar et al. (2021a) & & ✓ & ✓ & Classification, Trajectory Classification & GNN SOTA \\ \cline{2-5} & SCCONV Bunch et al. (2020) & & ✓ & Classification & Graph \\ \cline{2-5} & BScNet Chen et al. (2022) & ✓ & & Link prediction & GNN SOTA \\ \cline{2-5} & SNN Ebli et al. (2020) & & ✓ & Imputation & None \\ \cline{2-5} & SAN Giusti et al. (2022a) & ✓ & & Classification, Trajectory Classification & TNN SOTA \\ \cline{2-5} & SAT Goh et al. (2022) & & ✓ & ✓ & Classification, Trajectory Classification & TNN SOTA \\ \cline{2-5} & HSN* Hajji et al. (2022b) & ✓ & ✓ & ✓ & Classification, Link prediction, Vector embedding & Graph \\ \cline{2-5} & SCA* Hajji et al. (2022c) & & ✓ & Clustering & Graph \\ \cline{2-5} & Dist2Cycle Keros et al. (2022) & & ✓ & & Homology Localization & GNN SOTA \\ \cline{2-5} & SGAT Lee et al. (2022) & ✓ & & Classification & GNN SOTA \\ \cline{2-5} & SCoNe Roddenberry et al. (2021) & ✓ & & Trajectory Classification & TNN SOTA \\ \cline{2-5} & SCNN* Yang et al. (2022b) & ✓ & & Imputation & TNN SOTA \\ \cline{2-5} & SCCNN Yang and Isufi (2023) & ✓ & & Link prediction, Trajectory Classification & TNN SOTA \\ \cline{2-5} & SCN Yang et al. (2022c) & ✓ & & Classification & TNN SOTA \\ \hline **CC** & CWN Bodnar et al. (2021b) & ✓ & ✓ & Classification, prediction, regression & GNN SOTA \\ \cline{2-5} & CAN Giusti et al. (2022b) & & ✓ & Classification & GNN SOTA \\ \hline **CCC** & HOAN* Hajji et al. (2022a) & ✓ & ✓ & Classification & GNN SOTA \\ \hline \end{tabular} \end{table} Table 1: **Applications of Topological Neural Networks (TNNs).** We organize papers according to domain and task level, task purpose, and extent of benchmark testing (Graph: compared to graph-based models, GNN SOTA: compared to GNN state-of-the-art, TNN SOTA: compared to state-of-the-art on topological domain). We exclude papers without implementation, and use * to indicate that an implementation has not been shared. ### Symmetries and Geometric Properties Topological domains possess symmetries and other geometric properties that should be respected to ensure the quality of the features learned by a TNN (Bronstein et al., 2017). Here, we outline such properties harnessed by models in the literature. Hypergraphs.On hypergraphs, the following symmetries are desirable: 1. _Permutation Invariance:_ Relabeling the nodes and applying the TNN yields an output that is identical to the original output obtained without relabeling. This requires the aggregation functions to be permutation invariant, such as a mean or a sum (Arya et al., 2020; Kim et al., 2022; Chien et al., 2022; Dong et al., 2020; Keros et al., 2022). This is also called _hypergraph isomorphism invariance_. 2. _Global Neighborhood Invariance:_ The network's representation of a node is invariant to hyperedge cardinality: a hyperedge connecting many nodes is weighted the same as a hyperedge connecting less nodes (Arya et al., 2020). Simplicial Complex.For simplicial complexes, the following symmetries have been considered: 1. _Permutation Invariance:_ Invariance to node relabeling; the same as for HGs. (Schaub et al., 2021; Roddenberry et al., 2021; Bodnar et al., 2021) 2. _Orientation Equivariance:_ Changing the orientation of the simplicial complex (i.e. flipping the signs in the incidence matrix) re-orients the output of that network accordingly (Schaub et al., 2021; Roddenberry et al., 2021; Bodnar et al., 2021). 3. _Simplicial Locality (geometric property):_ In each layer, messages are only passed between \(r\)-cells and \((r\pm 1)\)-cells (Schaub et al., 2021). If that property is not verified, and messages can pass between any \(r\)- and \(r^{\prime}\)-cells, then the network has _extended simplicial locality_. In addition, _simplicial awareness_ can be imposed, such that message passing on a simplicial complex with maximum cell rank \(r\) depends on every rank \(r^{\prime}\leq r\)(Roddenberry et al., 2021). Cellular Complex and Combinatorial Complex.Permutation invariance is defined for CCs (Bodnar et al., 2021) and CCCs (Hajij et al., 2022) just as for SCs and HGs. Beyond generalizing global neighborhood invariance to CCC, more research is required to understand the symmetries that can equip this general topological domain. ## 4 Discussion Our literature review has revealed the diversity of TNN architectures as well as their main axes of comparison. Looking to the future, we highlight four salient opportunities for development. Within-Domain and Between-Domain Benchmarking.Table 3.2 shows that the domain choice strongly correlates with a TNN's task level. This necessarily makes within-domain comparisons difficult, regardless of code sharing. We also emphasize that many TNNs are only benchmarked against graph-based models or early models in their respective domain, which makes between-domain comparisons equally difficult. As the field grows, improving within and between-domain benchmarking mechanisms will be critical to better informing model selection and quantifying progress. TNN Architectures on General Domains.The diversity of implementations on HGs and SCs point to a strong potential for similar development in the cellular and combinatorial domains. For instance, only one attentional CC model has been proposed (Giusti et al., 2022). Moreover, any previously developed HG/SC/CC model can be reproduced in the CCC domain and, if desirable, improved with greater flexibility. Evaluating the impact of this added flexibility will directly characterize utility of richer topological structure in deep learning. Connecting to the Graph Literature.The HG field's ties to the graph community has led to GNN-based advancements not yet propagated to other domains. A first example are dynamic domains, successful with HGs for tasks like pose estimation (Liu et al., 2020), rail transit modeling (Wang et al., 2021), and co-authorship prediction (Jiang et al., 2019). No work in other discrete domains has explored dynamism. In addition, outside of the HG domain, TNNs are largely implemented as homogeneous networks. This leaves room for heterogeneous and non-Euclidean generalizations. Going Deeper.Over-smoothing occurs when a network is too effective at aggregating signal over multiple layers. This leads to very similar features across cells and poor performance on the downstream learning task. While this issue draws attention in the graph community (Chen et al., 2020; Oono and Suzuki, 2020; Rusch et al., 2023), little of this work has been generalized to TNNs, causing them to remain mostly shallow. UniGCNII (Huang and Yang, 2021) achieves a 64-layer deep TNN by generalizing over-smoothing solutions from GNNs (Chen et al., 2020) to the HG domain. HSNs (Hajji et al., 2022) generalize skip connections to allow signal to propagate further, but are still implemented as shallow networks. ## 5 Conclusion In this work, we have provided a comprehensive, intuitive and critical view of the advances in TNNs through unifying notations and graphical illustrations. We have characterized each neural network by its choice of data domain and its model, which we further specify through choice of neighboring structure(s) and message-passing scheme. We hope that this review will make this rich body of work more accessible to practitioners whose fields would benefit from topology-sensitive deep learning.
2305.07664
mAedesID: Android Application for Aedes Mosquito Species Identification using Convolutional Neural Network
Vector-Borne Disease (VBD) is an infectious disease transmitted through the pathogenic female Aedes mosquito to humans and animals. It is important to control dengue disease by reducing the spread of Aedes mosquito vectors. Community awareness plays acrucial role to ensure Aedes control programmes and encourages the communities to involve active participation. Identifying the species of mosquito will help to recognize the mosquito density in the locality and intensifying mosquito control efforts in particular areas. This willhelp in avoiding Aedes breeding sites around residential areas and reduce adult mosquitoes. To serve this purpose, an android application are developed to identify Aedes species that help the community to contribute in mosquito control events. Several Android applications have been developed to identify species like birds, plant species, and Anopheles mosquito species. In this work, a user-friendly mobile application mAedesID is developed for identifying the Aedes mosquito species using a deep learning Convolutional Neural Network (CNN) algorithm which is best suited for species image classification and achieves better accuracy for voluminous images. The mobile application can be downloaded from the URLhttps://tinyurl.com/mAedesID.
G. Jeyakodi, Trisha Agarwal, P. Shanthi Bala
2023-05-02T14:20:13Z
http://arxiv.org/abs/2305.07664v2
MAedesID: Android Application for Aedes Mosquito Species Identification using Convolutional Neural Network ###### Abstract Vector-Borne Disease (VBD) is an infectious disease transmitted through the pathogenic female Aedes mosquito to humans and animals. It is important to control dengue disease by reducing the spread of Aedes mosquito vectors. Community awareness plays a crucial role to ensure Aedes control programmes and encourages the communities to involve active participation. Identifying the species of mosquito will help to recognize the mosquito density in the locality and intensifying mosquito control efforts in particular areas. This will help in avoiding Aedes breeding sites around residential areas and reduce adult mosquitoes. To serve this purpose, an android application are developed to identify Aedes species that help the community to contribute in mosquito control events. Several Android applications have been developed to identify species like birds, plant species, and Anopheles mosquito species. In this work, a user-friendly mobile application'mAedesID' is developed for identifying the Aedes mosquito species using a deep learning Convolutional Neural Network (CNN) algorithm which is best suited for species image classification and achieves better accuracy for voluminous images. Convolutional Neural Network Aedes Mosquito Species Identification Community Participation Image Classification ## 1 Introduction World Health Organization (WHO) stated that dengue is considered one of the ten high-priority diseases that pose global public health threats. The dengue virus is recognized as a pathogen for the Aedes genus mosquitoes Aedes aegypti and Aedes albopictus. These mosquitoes transfer the dengue virus to humans and it causes dengue disease. Throughout the world, these mosquitoes are documented as primary and secondary vectors. The distribution of these species also keeps on the increase due to globalization and international travel. There is an enormous increase in dengue cases in India during the past ten years and worldwide it was reported around 125 tropical and subtropical countries [1, 2]. Still, now there is no standard vaccination is available for dengue, the only way to control dengue is through vector control measures. Several automated methods are introduced to identify reliable mosquito species. Some of the examples are the wingbeat frequency analysis, computer vision approaches, and deep Convolutional Neural Networks to predict the appropriate mosquito types using images [3, 4, 5, 6]. It is necessary to develop an Aedes species image identification model that can easily run on android based mobile devices with low latent. There are only limited mobile applications existing related to Aedes genus mosquitoes. The information based on the study, entertainment, alertness, and helpline provisions is explored. The awareness of Aedes species biology, their pathogenic behavior, the disease it spreads, the prevention mechanism, and control measures need to be explored for public access. The major requirement is the complaint notification registration on Aedes species abundance place once it is identified, to the concerned control unit for taking necessary actions for clearing the breeding places of Aedes species. Only genuine complaints have to be accepted by the application. This necessitates the requirement of a mobile application for public participation in Aedes mosquito control by identifying and preventing mosquito abundance areas. DISapp and MOSapp are mobile applications developed in India for collecting and uploading surveillance disease data from the public and field workers [7]. The dengue awareness mobile application has been launched by the Tamil Nadu government to provide information on awareness, causes, and prevention. However, the community involvement in Aedes mosquito control is not included [8]. The mobile Short Message Service (SMS) has been introduced in Nepal for providing dengue prevention details and improving dengue control practices [9]. In Fiji, the mobile application using Global Positioning System (GPS) technology identifies the dengue abundance areas [10]. The Convolutional Neural Network-based deep learning method is proved to be more effective as compared with the conventional feature-based method for classifying mosquito species [5]. J Pablo et. al (2018) developed a system to identify disease-carrying insects based on computer vision technology to facilitate the communities in arbovirus epidemics [11]. Analysis of the different computer-aided technologies to identify skin disease shows that deep learning-based image recognition methods give better results [12]. A pictographic android application is more supportive for entomologists, researchers, and public health workers [13]. The performance evaluation of CNN architectures revealed that MobileNetV2 architecture achieved the best on the verified metrics [14]. An automated system for treating and predicting the early stages of Chagas disease has been developed for healthcare clinicians which can completely cure Chagas disease [15]. Mobile technology has been adapted in ICMR-National Institute for Research in Tribal Health, Jabalpur for dengue disease diagnosis in a prior stage and promoting the mosquito population reduction activity [16]. In Sri Lanka, a mobile application has been used for educating the dengue disease to the community, school children, and field workers. The facility for reporting dengue incidents to Public Health Inspectors is provided for helping them to analyze the dengue case reports [17]. The Aedes mosquito prevention and monitoring technology have been studied by Geovanna Cristine de Souza Silva et al (2018) for building a model for Aedes control [18]. The advancement in different Neural Network algorithms can be used to detect the type of mosquito species without having any morphological characteristics, microscope, and polymerase chain reaction (PCR) test. The image captured by a camera is sufficient to recognize the mosquito genus or species type quickly using artificial intelligence algorithms. A model that uses a deep learning image classification technique can assist the communities in detecting life-threatening Aedes mosquito species. In this work mAedesID, an android application is developed for identifying Ae. aegypti and Ae. albopictus species at the community level. This application is based on a sequential CNN model that identifies certain features and uses them to differentiate between different images and assign labels to them. The model accepts an input image and produces a prediction for the class which it belongs to based on the training. It can also be extended for identifying different mosquito genera such as Anopheles, Culex, and Mansonia by replacing the existing data with new data set and training the model accordingly. The model can also be extended for other image classification problems in which the mobile application can be developed. ## 2 Methodology The methodology design consists of various phases such as Data Collection, Data Preprocessing, Model Building, Model Evaluation, Android Application Development, and Application Testing as depicted in **Fig 1**. Data Collection.The input data is the collection of images of Aedes genus mosquito species Ae. aegypti and Ae. albopictus. The species images were downloaded from the Kaggle repository [19]. The 4803 Aedes images of 20.36 GB were downloaded. The device Aedes Detector was used to capture the images in different angles with high resolution. Data Preprocessing.IThe downloaded images were preprocessed to improve the clarity, highlight the features, and structured the images. The zero-phase component analysis (ZCA) is performed on the dataset to reduce redundancy in the matrix of pixel images. Images were normalized to ensure that all the images contribute more evenly to the total loss and process the input faster. Images were rescaled to 1/255 for converting the pixels from the range [0,255] to [0,1]. Python tensor flow's Keras package was used for image preprocessing. **Fig 2** depicts the data preprocessing code. Model Building.In this phase, a sequential model has been built using Convolutional Neural Network for processing the training data. In a sequential model, multiple layers are stacked such as the output of the previous layer is the input of the new layer. CNN consists of an input layer, hidden layer, and output layer. The input layer is the first layer of the sequential model where the input image is shaped as (180,180,3) since the input images are of (180,180) pixels. Three refers to the Red Green Blue (RGB) channel implying the colored images. After processing the incoming data, it is distributed to the hidden layers that comprise the convolutional layers, major building elements, dense layers, dropout layers, flatten layers, and max-pooling layers. The dense layer connects the neural network layer deeply and the dropout * [3]:from_tensarflow_keras_pysnecesting_image_import_ImageDataGeneratoroc b=28b val_dir=".../ocking/msu/val" train_dir=".../backing/len/vdata" train_datagen_ImagedataGenerator(zca_whitening_True_rescale_1.0/255.0.featurewise_centecaFalse, featurewise_std_necovalid_dontecalizationFalse) valid_datagen=ImageDataGenerator(zca_whitening-True,rescale-_1.0/255.0.featurewise_std_necovalid_dontecalizationFalse)/opt/conda/lib/python3.7/site-packages/keras_pperprocessing/image/image/image_data_generator.py:337: UserWarning: This Ina gobatagenerator specifies 'zca_whitening', which overrides setting of 'featurewise_center'. warnings.warn('this_ImageDataGeneratorspecities') train_generator_a_train_datagen_flow_from_directory(train_dict_batch_sizeba_class_moden:binary'_target_size(180.186 validation_generator_valid_datagen_flow_from_directory(val_dict_batch_sizeba_class_modes:binary'_target_size(180.186. layer is used to prevent the model from overfitting. Flatten layer transforms a 2D matrix of features into a vector of features. The last dense layer is the output layer that uses the sigmoid activation function x is equal to, \[\sigma(x)=1/(1+exp(-x)) \tag{1}\] **Fig 3** represents the code for the CNN model that is built-in Google Cloud Artificial Intelligence (AI) platform through Jupiter Notebook. **Fig 4** shows the code for model compiling and fitting using 30 epochs. Model Evaluation.For better model fitting 30 epochs were used and received two metrics for each epoch acc and val_acc showing the accuracy in prediction obtained from training and validation data respectively. The accuracy of the model is further improved by using appropriate library functions. The developed TensorFlow model helps to predict the images on test data. **Fig 5** shows the code for testing data predictions. Android Application Development.The TensorFlow model developed in the Google Cloud AI platform is converted into Tensorflow Lite flat buffer file (.tflite) using Tensorflow Lite Converter for Firebase storage. mAedesID, the android Figure 4: Code for Image Preprocessing. Figure 3: Code for CNN Model Building. application is developed using android studio in Java. The mobile application identifies the Aedes species type based on the sigmoid value. **Fig 6** shows the use case diagram of mAedesID development. The user can upload either the stored image or capture the image using a mobile camera for species identification. Application Testing.The compatibility testing and functional testing were done on the mobile application. The developed mobile application has been tested with various mobile devices to check whether the mobile application user interface is compatible with all kinds of screen sizes and different kinds of operating systems (OS). It has been found that this mobile application has worked properly in all kinds of screen sizes and android OS versions 6.0 and above. The developed mobile application is tested to check its functionality is working properly or if any problems or issues were raised. But there was no issue and all the functions worked effectively. Figure 5: Code for Test Data Prediction. Figure 6: Use case Diagram of mAedesID. ## 3 Results and Discussion Kaggle dataset has been used to build an image classification model using Convolutional Neural Network to identify the Aedes mosquito species through an android application. **Fig 7** shows the input image dataset that are downloaded from Kaggle. The model was constructed with one input layer, sixteen hidden layers, and one output layer. **Fig 8** shows the summary of the CNN sequential model. The training and validation data was executed for 30 epochs to improve the accuracy. **Fig 9** shows the model fitting accuracy with the accuracy parameters. The model accuracy has been increased from 68.5% to 84.87% using the evaluate_generator function as shown in **Fig 10**. **Fig 11** shows the code for loading the title file and getting predictions for raw \(untested\) data. The mobile application has been developed using android studio. The user can detect the Aedes species type by uploading the image. The sigmoid value nearby zero predicted the image as Ae. aegypti and nearby one is identified as Ae. alopictus. **Fig 12** shows the front page of mobile application and the classified result of the test images Ae. aegypti and Ae. alopopictus. Figure 8: Classification Model Summary. Figure 7: Input Images Dataset. * [['name':'serving_default_conv2d_Input:'0', 'name': 0,'shape':'serving_([ 1, 180, 180, 3], dtype=[[0.3986372]]) Figure 11: Code for Class Prediction on New Data. Figure 10: Accuracy of the Model Figure 9: Model Fitting Accuracy. ## 4 Conclusion The mAedesID, the android application for identifying the mosquito vector Aedes aegypti and Aedes albopictus that is responsible for dengue disease was developed using the Convolutional Neural Network image classification model. The model was built and examined with Kaggle repository Aedes species images and produced valid predictions with good accuracy. Since the model is trained with the high-quality images obtained from the Aedes Detector device, the mobile application requires the same kind of images for Aedes species classification. The mAedesID is user-friendly and helps the community to involve active participation in dengue mosquito control without any background information on the mosquito's physical appearance. In the future, the model will be extended for predicting the mobile captured Aedes images by including them in the training data and labeling unknown images. Currently, the user can download the mobile application from the URL link, after including additional functionalities it will be uploaded to the google play store for easy access. The mobile application will be the resource for dengue disease prevalence and control in dengue epidemic areas.
2304.11461
Recurrent Neural Networks and Long Short-Term Memory Networks: Tutorial and Survey
This is a tutorial paper on Recurrent Neural Network (RNN), Long Short-Term Memory Network (LSTM), and their variants. We start with a dynamical system and backpropagation through time for RNN. Then, we discuss the problems of gradient vanishing and explosion in long-term dependencies. We explain close-to-identity weight matrix, long delays, leaky units, and echo state networks for solving this problem. Then, we introduce LSTM gates and cells, history and variants of LSTM, and Gated Recurrent Units (GRU). Finally, we introduce bidirectional RNN, bidirectional LSTM, and the Embeddings from Language Model (ELMo) network, for processing a sequence in both directions.
Benyamin Ghojogh, Ali Ghodsi
2023-04-22T18:22:10Z
http://arxiv.org/abs/2304.11461v1
# Recurrent Neural Networks and Long Short-Term Memory Networks: Tutorial and Survey ###### Abstract This is a tutorial paper on Recurrent Neural Network (RNN), Long Short-Term Memory Network (LSTM), and their variants. We start with a dynamical system and backpropagation through time for RNN. Then, we discuss the problems of gradient vanishing and explosion in long-term dependencies. We explain close-to-identity weight matrix, long delays, leaky units, and echo state networks for solving this problem. Then, we introduce LSTM gates and cells, history and variants of LSTM, and Gated Recurrent Units (GRU). Finally, we introduce bidirectional RNN, bidirectional LSTM, and the Embeddings from Language Model (ELMo) network, for processing a sequence in both directions. Machine Learning, Neural Networks, LSTM, Deep Learning, Neural Networks, Neural were proposed to process sequences in both directions. The Embeddings from Language Model (ELMo) network (Peters et al., 2018) is a language model which makes use of the bidirectional LSTM. This is a tutorial on RNN, LSTM, and their variants. There exist some other tutorials and surveys about this topic, some of which are (Jaeger, 2002; Jozefowicz et al., 2015; Lipton et al., 2015; Schmidhuber, 2015; Greff et al., 2016; Salehinejad et al., 2017; Staudemeyer and Morris, 2019; Yu et al., 2019; Smagulova and James, 2019). A very good survey on the variants of LSTM is (Greff et al., 2016). ## 2 Recurrent Neural Network ### Dynamical System A dynamical system is recursive and its classical form is as follows: \[\mathbf{h}_{t}=f_{\theta}(\mathbf{h}_{t-1}), \tag{1}\] where \(t\) denotes the time step, \(\mathbf{h}_{t}\) is the state at time \(t\), and \(f_{\theta}(.)\) is a function fixed between the states of all time steps. Figure 1-a shows such a system. Dynamical systems are widely used in chaos theory (Broer and Takens, 2011). We can have a dynamical system with external input signal where \(\mathbf{x}_{t}\) denotes the input signal at time \(t\). This system is modeled as: \[\mathbf{h}_{t}=f_{\theta}(\mathbf{h}_{t-1},\mathbf{x}_{t}). \tag{2}\] This system is depicted in Fig. 1-b. ### Parameter Sharing The state \(\mathbf{h}_{t}\) can be considered as a summary of the past sequence of inputs and states. If a different function \(f_{\theta}\) is defined for each possible sequence length, the model will not have generalization. If the same parameters are used for any sequence length, the model will have generalization properties. Therefore, the parameters are shared for all lengths and between all states. Such a dynamical system with parameter sharing can be implemented as a neural network with weights. Such a network is called a Recurrent Neural Network (RNN), which was proposed in (Rumelhart et al., 1986). RNN is illustrated in Fig. 1-c, where the same weight matrices are used for all time slots. RNN gets a sequence as input and outputs a sequence as a decision for a task such as regression or classification. Suppose the input, output, and state at time slot \(t\) are denoted by \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), \(\mathbf{y}_{t}\in\mathbb{R}^{q}\), and \(\mathbf{h}_{t}\in\mathbb{R}^{p}\), respectively. Let \(\mathbf{W}\in\mathbb{R}^{p\times p}\) be the weight matrix between states, \(\mathbf{U}\in\mathbb{R}^{p\times d}\) be the weight matrix between the inputs and the states, and \(\mathbf{V}\in\mathbb{R}^{q\times p}\) denote the weight matrix between the states and outputs. The bias weights for the state and the output are denoted by \(\mathbf{b}_{i}\in\mathbb{R}^{p}\) and \(\mathbf{b}_{y}\in\mathbb{R}^{q}\), respectively. As shown in Fig. 1-c, we have: \[\mathbb{R}^{p}\ni\mathbf{i}_{t}=\mathbf{W}\mathbf{h}_{t-1}+\mathbf{U}\mathbf{x}_{t}+ \mathbf{b}_{i}, \tag{3}\] \[[-1,1]^{p}\ni\mathbf{h}_{t}=\tanh(\mathbf{i}_{t})\] \[\qquad\qquad\qquad\qquad=\tanh(\mathbf{W}\mathbf{h}_{t-1}+\mathbf{U}\mathbf{x}_{t} +\mathbf{b}_{i}),\] (4) \[\mathbb{R}^{q}\ni\mathbf{y}_{t}=\mathbf{V}\mathbf{h}_{t}+\mathbf{b}_{y}, \tag{5}\] where \(\tanh(.)\in(-1,1)\) denotes the hyperbolic tangent function, which is used as an element-wise activation function for the states. If there is an activation function, such as softmax, at the output layer, we denote the output of activation function by: \[\mathbb{R}^{q}\ni\widehat{\mathbf{y}}_{t}=\text{softmax}(\mathbf{y}_{t})=\frac{\exp(y _{t,1})}{\sum_{j=1}^{q}\exp(y_{t,j})}, \tag{6}\] where \(y_{t,j}\) denotes the \(j\)-th component of \(\mathbf{y}_{t}\). ### Backpropagation Through Time (BPTT) One of the methods for training RNN is Backpropagation Through Time (BPTT), which is very similar to the backpropagation algorithm (Rumelhart et al., 1986) because it is based on gradient descent and chain rule (Ghojogh et al., 2021), but it has also chain rule through time. BPTT was developed by several works (Robinson and Fallside, 1987; Werbos, 1988; Williams, & Zipser, 1995; Mozer, 1995). This algorithm is very solid in theory; however, it does not show the best performance in practice. In BPTT, the loss is considered as a summation of loss functions at the previous time steps until now. As it is im Figure 1: The folded and unfolded structures of (a) a dynamic system without input, (b) a dynamical system with input, and (c) an RNN. Every square on an edge means connection from one time slot before. practical to consider all time steps from the start of training (especially after a long time of training), we only consider the \(T\) previous time steps. In other words, we assume that RNN has \(T\)-order Markov property (Ghojogh et al., 2019b). Therefore, the loss function is: \[\mathbb{R}\ni\mathcal{L}=\sum_{t=1}^{T}\mathcal{L}_{t}, \tag{7}\] where \(\mathcal{L}_{1}\) is the loss function at the current time slot and \(\mathcal{L}_{t}\) denotes the loss function at the previous \((t-1)\) time slot. This loss functions needs to be optimized using gradient descent and chain rule. Therefore, we calculate its gradient with respect to the parameters of RNN. These parameters are \(\boldsymbol{y}_{t}\), \(\boldsymbol{h}_{t}\), \(\boldsymbol{V}\), \(\boldsymbol{W}\), \(\boldsymbol{U}\), \(\boldsymbol{b}_{i}\), and \(\boldsymbol{b}_{y}\), based on Eqs. (3), (4), and (5) and Fig. 1-c. #### 2.3.1 Gradient With Respect to the Output If there is no activation function at the last layer, the gradient of the loss function of RNN with respect to the output at time \(t\) is: \[\mathbb{R}^{q}\ni\frac{\partial\mathcal{L}}{\partial\boldsymbol{y}_{t}} \stackrel{{(a)}}{{=}}\frac{\partial\mathcal{L}}{\partial \mathcal{L}_{t}}\times\frac{\partial\mathcal{L}_{t}}{\partial\boldsymbol{y}_{t }}\stackrel{{(\gamma)}}{{=}}\frac{\partial\mathcal{L}_{t}}{ \partial\boldsymbol{y}_{t}}, \tag{8}\] where \((a)\) is because of the chain rule. The gradient of the loss function at time \(t\) with respect to the output at time \(t\), i.e., \(\partial\mathcal{L}_{t}/\partial\boldsymbol{y}_{t}\), is calculated based on the formula of the loss function. The loss function can be any loss function for classification, regression, or other tasks. If there is an activation function at the last layer (see Eq. (6)), the gradient is: \[\mathbb{R}^{q}\ni\frac{\partial\mathcal{L}}{\partial\boldsymbol{y}_{t}} \stackrel{{(a)}}{{=}}\frac{\partial\mathcal{L}}{\partial \mathcal{L}_{t}}\times\frac{\partial\mathcal{L}_{t}}{\partial\widehat{ \boldsymbol{y}}_{t}}\times\frac{\partial\widehat{\boldsymbol{y}}_{t}}{ \partial\boldsymbol{y}_{t}}\stackrel{{(\gamma)}}{{=}}\frac{ \partial\mathcal{L}_{t}}{\partial\widehat{\boldsymbol{y}}_{t}}\times\frac{ \partial\widehat{\boldsymbol{y}}_{t}}{\partial\boldsymbol{y}_{t}}, \tag{9}\] where \((a)\) is because of the chain rule. The derivative \(\partial\widehat{\boldsymbol{y}}_{t}/\partial\boldsymbol{y}_{t}\) is calculated based on the formula of the activation function. The other derivative, \(\partial\mathcal{L}_{t}/\partial\widehat{\boldsymbol{y}}_{t}\), is calculated based on the formula of the loss as a function of the output of the activation function. #### 2.3.2 Gradient With Respect to the State The gradient of the loss function of RNN with respect to the state at time \(t\) is: \[\mathbb{R}^{p}\ni\frac{\partial\mathcal{L}}{\partial\boldsymbol{h }_{t}}\stackrel{{(a)}}{{=}}\Big{(}\frac{\partial\mathcal{L}}{ \partial\boldsymbol{y}_{t}}\times\frac{\partial\boldsymbol{y}_{t}}{\partial \boldsymbol{h}_{t}}\Big{)}+\Big{(}\frac{\partial\mathcal{L}}{\partial \boldsymbol{h}_{t+1}}\times\frac{\partial\boldsymbol{h}_{t+1}}{\partial \boldsymbol{h}_{t}}\Big{)}\] \[\stackrel{{(\ref{eq:eq slots. The derivative \(\partial\mathcal{L}/\partial\mathbf{h}_{t}\in\mathbb{R}^{p}\) in Eq. (18) was computed in Section 2.3.2. The derivative \(\partial\mathbf{h}_{t}/\partial\mathbf{W}\) in Eq. (18) is: \[\mathbb{R}^{p\times p^{2}}\ni\frac{\partial\mathbf{h}_{t}}{\partial\mathbf{W}}=\frac{ \partial\mathbf{h}_{t}}{\partial\dot{\mathbf{i}}_{t}}\times\frac{\partial\dot{\mathbf{i}} _{t}}{\partial\mathbf{W}},\] because of the chain rule. The first term is: \[\mathbb{R}^{p\times p}\ni\frac{\partial\mathbf{h}_{t}}{\partial\dot{\mathbf{i}}_{t}}= (1-\mathbf{h}_{t}^{\top}\mathbf{h}_{t})\mathbf{I}_{p\times p}, \tag{19}\] according to Eq. (15). Based on the Magnus-Neudecker convention (Ghojogh et al., 2021), the second term is calculated as: \[\mathbb{R}^{p\times p^{2}}\ni\frac{\partial\dot{\mathbf{i}}_{t}}{\partial\mathbf{W}}= \mathbf{h}_{t-1}^{\top}\otimes\mathbf{I}_{p\times p},\] where \(\otimes\) denotes the Kronecker product. #### 2.3.5 Gradient With Respect to \(\mathbf{U}\) The gradient of the loss function of RNN with respect to the weight matrix \(\mathbf{U}\) is: \[\mathbb{R}^{p\times d}\ni\frac{\partial\mathcal{L}}{\partial\mathbf{U}}\overset{ (a)}{=}\sum_{t=1}^{T}\textbf{vec}_{p\times d}^{-1}\Big{(}\big{(}\frac{ \partial\mathbf{h}_{t}}{\partial\mathbf{U}}\big{)}^{\top}\times\frac{\partial\mathcal{ L}}{\partial\mathbf{h}_{t}}\Big{)}, \tag{20}\] where \((a)\) is because \(\mathbf{U}\) exists in all time slots and changing \(\mathbf{U}\) affects the loss \(\mathcal{L}\) in all time slots. The derivative \(\partial\mathcal{L}/\partial\mathbf{h}_{t}\in\mathbb{R}^{p}\) in Eq. (18) was computed in Section 2.3.2. The derivative \(\partial\mathbf{h}_{t}/\partial\mathbf{U}\) in Eq. (18) is: \[\mathbb{R}^{p\times(pd)}\ni\frac{\partial\mathbf{h}_{t}}{\partial\mathbf{U}}=\frac{ \partial\mathbf{h}_{t}}{\partial\dot{\mathbf{i}}_{t}}\times\frac{\partial\dot{\mathbf{i}} _{t}}{\partial\mathbf{U}},\] because of the chain rule. The first term is already calculated in Eq. (19). Based on the Magnus-Neudecker convention (Ghojogh et al., 2021), the second term is calculated as: \[\mathbb{R}^{p\times(pd)}\ni\frac{\partial\dot{\mathbf{i}}_{t}}{\partial\mathbf{U}}= \mathbf{x}_{t}^{\top}\otimes\mathbf{I}_{p\times p}.\] #### 2.3.6 Gradient With Respect to \(\mathbf{b}_{i}\) The gradient of the loss function of RNN with respect to the bias \(\mathbf{b}_{i}\) is: \[\mathbb{R}^{p}\ni\frac{\partial\mathcal{L}}{\partial\mathbf{b}_{i}}\overset{(a)}{ =}\sum_{t=1}^{T}\Big{(}\big{(}\frac{\partial\mathbf{h}_{t}}{\partial\mathbf{b}_{i}} \big{)}^{\top}\times\frac{\partial\mathcal{L}}{\partial\mathbf{h}_{t}}\Big{)}, \tag{21}\] where \((a)\) is because \(\mathbf{b}_{i}\) exists in all time slots and changing \(\mathbf{b}\) affects the loss \(\mathcal{L}\) in all time slots. The derivative \(\partial\mathcal{L}/\partial\mathbf{h}_{t}\) was already calculated in Section 2.3.2. The derivative \(\partial\mathcal{h}_{t}/\partial\mathbf{b}_{i}\) is calculated as: \[\mathbb{R}^{p\times p}\ni\frac{\partial\mathbf{h}_{t}}{\partial\mathbf{b}_{i}}\overset{ (a)}{=}\frac{\partial\mathbf{h}_{t}}{\partial\dot{\mathbf{i}}_{t}}\times\frac{ \partial\dot{\mathbf{i}}_{t}}{\partial\mathbf{b}_{i}}\overset{(3)}{=}\frac{\partial \mathbf{h}_{t}}{\partial\dot{\mathbf{i}}_{t}},\] where \((a)\) is because of the chain rule and the derivative \(\partial\mathbf{h}_{t}/\partial\dot{\mathbf{i}}_{t}\) was already calculated in Eq. (19). #### 2.3.7 Gradient With Respect to \(\mathbf{b}_{y}\) The gradient of the loss function of RNN with respect to the bias \(\mathbf{b}_{y}\) is: \[\mathbb{R}^{q}\ni\frac{\partial\mathcal{L}}{\partial\mathbf{b}_{y}}\overset{(a)}{ =}\sum_{t=1}^{T}\Big{(}\frac{\partial\mathcal{L}}{\partial\mathbf{y}_{t}}\times \frac{\partial\mathbf{y}_{t}}{\partial\mathbf{b}_{y}}\Big{)}\overset{(b)}{=}\sum_{t=1} ^{T}\frac{\partial\mathcal{L}_{t}}{\partial\mathbf{y}_{t}}, \tag{22}\] where \((a)\) is because \(\mathbf{b}_{y}\) exists in all time slots and changing \(\mathbf{b}_{y}\) affects the loss \(\mathcal{L}\) in all time slots. The equation \((b)\) is because of Eqs. (8) and (5). The derivative \(\partial\mathcal{L}_{t}/\partial\mathbf{y}_{t}\in\mathbb{R}^{q}\) is calculated based on the formula of the loss function. #### 2.3.8 Updates by Gradient Descent BPPT updates the parameters of RNN by gradient descent (Ghojogh et al., 2021) using the calculated gradients: \[\mathbf{h}_{t} :=\mathbf{h}_{t}-\eta\frac{\partial\mathcal{L}}{\partial\mathbf{h}_{t}}, \quad\forall t\in\{1,\dots,T\},\] \[\mathbf{V} :=\mathbf{V}-\eta\frac{\partial\mathcal{L}}{\partial\mathbf{V}},\] \[\mathbf{W} :=\mathbf{W}-\eta\frac{\partial\mathcal{L}}{\partial\mathbf{W}},\] \[\mathbf{U} :=\mathbf{U}-\eta\frac{\partial\mathcal{L}}{\partial\mathbf{U}},\] \[\mathbf{b}_{i} :=\mathbf{b}_{i}-\eta\frac{\partial\mathcal{L}}{\partial\mathbf{b}_{i}},\] \[\mathbf{b}_{y} :=\mathbf{b}_{y}-\eta\frac{\partial\mathcal{L}}{\partial\mathbf{b}_{y}},\] where \(\eta>0\) is the learning rate and the gradients are calculated by Eqs. (10), (17), (18), (20), (21), and (22). ## 3 Gradient Vanishing or Explosion in Long-term Dependencies In recurrent neural networks, so as in deep neural networks, the final output is the composition of a large number of non-linear transformations. This results in the problem of either vanishing or exploding gradients in recurrent neural networks, especially for capturing long-term dependencies in sequence processing (Bengio et al., 1993; Bengio et al., 1994). This problem is explained in the following. Recall Eq. (2) for a dynamical system: \[\mathbf{h}_{t}=f_{\theta}(\mathbf{h}_{t-1},\mathbf{x}_{t}).\] By induction, the hidden state at time \(t\), i.e., \(\mathbf{h}_{t}\), can be written as the previous \(T\) time steps. If the subscript \(t\) denotes the previous \(t\) time steps, we have by induction (Hochreiter, 1998; Hochreiter et al., 2001): \[\mathbf{h}_{1}=f_{\theta}\Big{(}f_{\theta}\big{(}\dots f_{\theta}(\mathbf{h}_{T},\mathbf{x}_{ T+1})\dots,\mathbf{x}_{2}\big{)},\mathbf{x}_{1}\Big{)}.\] Then, by the chain rule in derivatives, the derivative loss at time \(T\), i.e., \(\mathcal{L}_{T}\), is: \[\frac{\partial\mathcal{L}_{T}}{\partial\theta} =\sum_{t\leq T}\frac{\partial\mathcal{L}_{t}}{\partial\mathbf{h}_{t}} \frac{\partial\mathbf{h}_{t}}{\partial\theta}\overset{(a)}{=}\sum_{t\leq T}\frac{ \partial\mathcal{L}_{t}}{\partial\mathbf{h}_{T}}\frac{\partial\mathbf{h}_{T}}{ \partial\mathbf{h}_{t}}\frac{\partial\mathbf{h}_{t}}{\partial\theta}\] \[\overset{(2)}{=}\sum_{t\leq T}\frac{\partial\mathcal{L}_{t}}{ \partial\mathbf{h}_{T}}\frac{\partial\mathbf{h}_{T}}{\partial\mathbf{h}_{t}}\frac{ \partial f_{\theta}(\mathbf{h}_{t-1},\mathbf{x}_{t})}{\partial\theta}, \tag{23}\] where \((a)\) is because of the chain rule. In this expression, there is the derivative of \(\mathbf{h}_{T}\) with respect to \(\mathbf{h}_{t}\) which itself can be calculated by the chain rule: \[\frac{\partial\mathbf{h}_{T}}{\partial\mathbf{h}_{t}}=\frac{\partial\mathbf{h}_{T}}{ \partial\mathbf{h}_{T-1}}\times\frac{\partial\mathbf{h}_{T-1}}{\partial\mathbf{h}_{T-2} }\times\cdots\times\frac{\partial\mathbf{h}_{t+1}}{\partial\mathbf{h}_{t}}. \tag{24}\] for capturing long-term dependencies in the sequence, \(T\) should be large. This means that in Eq. (24), and hence in Eq. (23), the number of multiplicand terms becomes huge. On the one hand, if each derivative is slightly smaller than one, the entire derivative in the chain rule becomes very small for multiplication of many terms smaller than one. This problem is referred to as gradient vanishing. On the other hand, if every derivative is slightly larger than one, the entire derivative in the chain rule explodes, resulting in the problem of exploding gradients. Note that gradient vanishing is more common than gradient explosion in recurrent networks. There exist various attempts for resolving the problem of gradient vanishing or explosion (Hochreiter, 1998; Bengio et al., 2013). In the following, some of these attempts are introduced. ### Close-to-identity Weight Matrix As Eq. (4) shows, the state is multiplied by a weight matrix \(\mathbf{W}\) at every time step and if there is long-term dependency, many of these \(\mathbf{W}\) matrices are multiplied. Suppose the eigenvalue decomposition (Ghojogh et al., 2019) of the matrix \(\mathbf{W}\) is \(\mathbf{W}=\mathbf{A}\mathbf{\Lambda}\mathbf{A}^{\top}\) where \(\mathbf{A}\in\mathbb{R}^{p\times p}\) and \(\mathbf{\Lambda}:=\text{\bf diag}([\lambda_{1},\dots,\lambda_{p}]^{\top})\) contain the eigenvectors and eigenvalues of \(\mathbf{W}\), respectively. Eq. (4) is restated as: \[\mathbf{h}_{t}=\tanh(\mathbf{A}\mathbf{\Lambda}\mathbf{A}^{\top}\mathbf{h}_{t-1}+\mathbf{U}\mathbf{x}_{t} +\mathbf{b}_{i}). \tag{25}\] If a change \(\varepsilon\) in some element of the state \(\mathbf{h}_{t-1}\) is aligned with an eigenvector of the weight matrix \(\mathbf{W}\), then the effect of this change in \(\mathbf{h}_{t}\) will be \((\lambda^{t}\,\varepsilon)\) after \(t\) time steps, according to Eq. (25). Two cases may happen: * If the largest eigenvalue is less than one, i.e., \(\lambda<1\), then the change \((\lambda^{t}\,\varepsilon)\) is contrastive because \(\lambda^{t}\ll 1\) for long-term dependencies. In this case, gradient vanishing occurs in long-term dependency and the network forgets very long time ago. * If the largest eigenvalue is less than one, i.e., \(\lambda>1\), then the change \((\lambda^{t}\,\varepsilon)\) is diverging because \(\lambda^{t}\gg 1\) for long-term dependencies. In this case, the gradient network forgets very long time ago. In this case, gradient explosion occurs in long-term dependency and remembering very long time ago dominates the short-term memories. As remembering short-term memories is usually more important than remembering very past time in different tasks, it is recommended to use the weight matrix \(\mathbf{W}\) whose largest eigenvalue is less than one; this makes the RNN have the Markovian property because it forgets very past after some point. However, if the largest eigenvalue of \(\mathbf{W}\) is much less than one, i.e., \(\lambda\ll 1\), gradient vanishing happens very sooner than expected. Therefore, it is recommended to use the weight matrix \(\mathbf{W}\) whose largest eigenvalue is _slightly_ less than one, i.e., \(\lambda\lesssim 1\). This makes the RNN slightly contrastive. One way to have the weight matrix \(\mathbf{W}\) whose largest eigenvalue is slightly less than one is to make this matrix close to the identity matrix (Mikolov et al., 2015). There exist some other ways to determine the weight matrix \(\mathbf{W}\). For example, the wight matrix can be set to be an orthogonal matrix (Arjovsky et al., 2016). Another approach is to copy the previous state exactly to the current state. In this approach, the Eq. (4) is modified to (Hu et al., 2018): \[\begin{split}\mathbf{h}_{t}&=\tanh(\mathbf{W}\mathbf{h}_{t-1}+ \mathbf{h}_{t-1}+\mathbf{U}\mathbf{x}_{t}+\mathbf{b}_{i})\\ &=\tanh\big{(}(\mathbf{W}+\mathbf{I})\mathbf{h}_{t-1}+\mathbf{U}\mathbf{x}_{t}+\mathbf{b}_ {i}\big{)},\end{split} \tag{26}\] where \(\mathbf{I}\) is the identity matrix. This prevents gradient vanishing because it brings a copy of the previous step to the current state. This can also be interpreted as strengthening the diagonal of the weight matrix \(\mathbf{W}\); hence, increasing the largest eigenvalue of \(\mathbf{W}\) for preventing gradient vanishing. ### Long Delays As Eq. (4) and Fig. 1-c show, in the regular RNN, every state \(\mathbf{h}_{t}\) is fed by its previous state \(\mathbf{h}_{t-1}\) through the weight matrix \(\mathbf{W}\). As discussed in Section 3.1, in the regular RNN, the effect of the change \(\varepsilon\) in a state results in \((\lambda^{t}\,\varepsilon)\) after \(t\) time steps, where \(\lambda\) is the largest eigenvalue of \(\mathbf{W}\). As shown in Fig. 1-c, the regular RNN has one-step connections or delays between the states. It is possible to have longer delays between the states in addition to the one-step delays (Lin et al., 1995). In other words, it is possible to have higher levels of Markov property in the network. Let \(\mathbf{W}_{k}\) denote the weight matrix for \(k\)-step delays between the states. Then, Eq. (4) can be modified to: \[\mathbf{h}_{t}=\tanh\Big{(}\sum_{k}\mathbf{W}_{k}\mathbf{h}_{t-k}+\mathbf{U}\mathbf{x}_{t}+\mathbf{b}_ {i}\Big{)}, \tag{27}\] where the summation is over the \(k\) values for the existing delays in the RNN structure. An example for an RNN network with one-step and three-step delays is: \[\mathbf{h}_{t}=\tanh\Big{(}\mathbf{W}_{1}\mathbf{h}_{t-1}+\mathbf{W}_{3}\mathbf{h}_{t-3}+\mathbf{U}\mathbf{x} _{t}+\mathbf{b}_{i}\Big{)},\] which is illustrated in Fig. 2. Having long delays in RNN is one of the attempts for preventing gradient vanishing (Lin et al., 1995). This is justified because every state is having impact not only from the previous state but also from the more previous states. Therefore, in backpropagation through time, there is some skip in gradient flow from a state to more previous states without the need to go through the middle states in the chain rule. ### Leaky Units Another way to resolve the problem of gradient vanishing is leaky units (Jaeger et al., 2007; Sutskever and Hinton, 2010). Let \(h_{t,j}\) denote the \(j\)-th element of the state \(\mathbf{h}_{t}\in[-1,1]^{p}\). In leaky units, Eq. (4) is modified to the following element-wise equation: \[\begin{split} h_{t,j}=&\,(1-\frac{1}{\tau_{j}})\,h_ {t-1,j}\\ &+\frac{1}{\tau_{j}}\tanh(\mathbf{W}_{j};\mathbf{h}_{t-1}+\mathbf{U}_{j};\mathbf{ x}_{t}+b_{i,j}),\end{split} \tag{28}\] where \(1\leq\tau_{j}<\infty\) and \(\mathbf{W}_{j:}\) is the \(j\)-th row of \(\mathbf{W}\) and \(\mathbf{U}_{j:}\) is the \(j\)-th row of \(\mathbf{U}\) and \(b_{i,j}\) is the \(j\)-th element of \(\mathbf{b}_{i}\). When \(\tau_{i}=1\), then Eq. (28) becomes: \[h_{t,j}=\frac{1}{\tau_{j}}\tanh(\mathbf{W}_{j};\mathbf{h}_{t-1}+\mathbf{U}_{j};\mathbf{x}_{t}+b _{i,j}),\] which gives back Eq. (4) in the regular RNN. However, when \(\tau_{i}\gg 1\), then Eq. (28) becomes: \[h_{t,j}=h_{t-1,j},\] which means that the previous state is copied to the current state. The larger the \(\tau_{i}\), the easier the gradient propagates for \(h_{t,i}\). Therefore, by tuning \(\tau_{i}\), it is possible to control how much of the past should be directly copied and how much should be passed through the weight matrix. This can control the amount of gradient vanishing. Note that leaky units use different \(\tau_{i}\)'s because there may be a need to keep some of the directions of states (with \(\tau_{i}=1\)) or forget some of the directions (with \(\tau_{i}\gg 1\)). In other words, it decides about the \(p\) directions of states separately. ### Echo State Networks One of the approaches to handle the problem of gradient vanishing in RNN is to use echo state networks (Jaeger and Haas, 2004; Jaeger, 2007). These networks consider the recurrent neural network as a black box having hidden units with nonlinear activation functions and connections between them. This black box of recurrent connections is called the _reservoir dynamical system_ which models the internal structure of a computer or brain. The connections in the reservoir system are usually sparse and the weights of these connections are considered to be fixed. The output of the reservoir system is connected to an additional linear output layer whose weights are learnable. The echo state network minimizes the mean squared error in the output layer; hence, it performs linear regression in the last layer (Jaeger and Haas, 2004). This network is shown in Fig. 3. Because of not learning the recurrent weights in the reservoir system and sufficing to learn the weights of the output layer, the echo state network does not face the gradient vanishing problem. A tutorial on this topic is (Jaeger, 2002). ### Other methods There exist some other methods for not having gradient vanishing in recurrent networks. For example, hierarchical RNN (Hihi and Bengio, 1995) and deep RNN (Graves, 2013) have been proposed which stack several recurrent networks. Another related category of networks is the time-delay neural networks (Lang et al., 1990; Peddinti et al., 2015) which are used for shift-invariant sequence processing, especially used in speech recognition (Sugiyama et al., 1991). In these networks, every neuron in a layer receives a contextual window of the neurons in the previous layer as well as their delayed outputs in several time slots ago. Moreover, these networks apply backpropagation on several copies of the network shifted across the sequence Figure 3: The echo state network. Figure 2: The (a) folded and (b) unfolded structures of an RNN with long delays. Every square on an edge means connection from one time slot before. (time) so that the network becomes time-invariant. ## 4 Long Short-Term Memory Network As the examples in Section 1 showed, we need short-term relations in some cases and long-term relations in some other cases. RNN learns the sequence based on one or several previous states, depending on its structure and the level of its Markov property (see Fig. 2). Therefore, we need to decide on the structure of RNN to be able to handle short-term or long-term dependencies in the sequence. Instead of manual design of the RNN structure or deciding manually when to clear the state, we can let the neural network learn by itself when to clear the state based on its input sequence. Long Short-Term Memory (LSTM), initially proposed in (Hochreiter & Schmidhuber, 1995; 1997), is able to do this; it learns from its input sequence when to use short-term dependency (i.e., when to clear the state) and when to use the long-term memory (i.e., when not to clear the state). ### LSTM Gates and Cells LSTM consists of several cells, each of which corresponds to a time slot (see Fig. 4). Every LSTM cell contains several gates for learning different aspects of the input time series (see Fig. 5). These gates are introduced in the following. #### 4.1.1 The Input Gate One of the gates in the LSTM cell is the _input gate_, first proposed in (Hochreiter & Schmidhuber, 1995; 1997). This gate takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal \(\mathbf{i}_{t}\in[0,1]^{p}\): \[\mathbf{i}_{t}=\text{sig}\big{(}\mathbf{W}_{i}\,\mathbf{h}_{t-1}+\mathbf{U}_{i}\,\mathbf{x}_{t}+( \mathbf{p}_{i}\odot\mathbf{c}_{t-1})+\mathbf{b}_{i}\big{)}, \tag{29}\] where \(\mathbf{W}_{i}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{i}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{i}\in\mathbb{R}^{p}\) are the learnable weights for the input gate, \(\odot\) denotes the Hadamard (element-wise) product, \(\mathbf{c}_{t-1}\in\mathbb{R}^{p}\) is the final memory of the last time slot (which will be explained in Section 4.1.5), and \(\mathbf{p}_{i}\in\mathbb{R}^{p}\) is the learnable _peephole weight_(Gers & Schmidhuber, 2000) letting a possible leak of information from the previous final memory. The function \(\text{sig}(.)\in(0,1)\) is the sigmoid function which is applied element-wise: \[\text{sig}(x)=\frac{1}{1+\exp(-x)}. \tag{30}\] As Eq. (29) demonstrates, the input gate considers the effect of the input and the previous hidden state. It may also use a leak of information from the previous memory through the peephole. This gate carries the importance of the information of the input at the current time slot. The input gate is depicted in Fig. 5. #### 4.1.2 The Forget Gate Another gate in the LSTM cell is the _forget gate_, first proposed in (Gers et al., 2000). This gate also takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal \(\mathbf{f}_{t}\in[0,1]^{p}\): \[\mathbf{f}_{t}=\text{sig}\big{(}\mathbf{W}_{f}\,\mathbf{h}_{t-1}+\mathbf{U}_{f}\,\mathbf{x}_{t}+( \mathbf{p}_{f}\odot\mathbf{c}_{t-1})+\mathbf{b}_{f}\big{)}, \tag{31}\] where \(\mathbf{W}_{f}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{f}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{f}\in\mathbb{R}^{p}\) are the learnable weights for the forget gate, and \(\mathbf{p}_{f}\in\mathbb{R}^{p}\) is the learnable _peephole weight_(Gers & Schmidhuber, 2000) letting a possible leak of information from the previous final memory. As Eq. (31) shows, the forget gate considers the effect of the input and the previous hidden state, and perhaps a leak of information from the previous memory. This gate controls the amount of forgetting the previous information with respect to the new-coming information. the forget gate is illustrated in Fig. 5. #### 4.1.3 The Output Gate The next gate in the LSTM cell is the _output gate_ first proposed in (Hochreiter & Schmidhuber, 1995; 1997). This gate also takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal \(\mathbf{o}_{t}\in[0,1]^{p}\): \[\mathbf{o}_{t}=\text{sig}\big{(}\mathbf{W}_{o}\,\mathbf{h}_{t-1}+\mathbf{U}_{o}\,\mathbf{x}_{t}+( \mathbf{p}_{o}\odot\mathbf{c}_{t})+\mathbf{b}_{o}\big{)}, \tag{32}\] where \(\mathbf{W}_{o}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{o}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{o}\in\mathbb{R}^{p}\) are the learnable weights for the output gate, and \(\mathbf{p}_{o}\in\mathbb{R}^{p}\) is the learnable _peephole weight_(Gers & Schmidhuber, 2000) letting a possible leak of information from the current final memory. As shown in Eq. (32), the output gate considers the effect of the input and the previous hidden state, and a possible information leak from the current memory. The output gate is shown in Fig. 5. #### 4.1.4 The New Memory Cell (Block Input) The LSTM cell includes a gate named the _new memory cell_. This gate takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal \(\widetilde{\mathbf{c}}_{t}\in[-1,1]^{p}\). This gate considers the effect of the input and the previous hidden state to represent the new information of current input. It is formulated as: \[\widetilde{\mathbf{c}}_{t}=\tanh(\mathbf{W}_{c}\,\mathbf{h}_{t-1}+\mathbf{U}_{c}\,\mathbf{x}_{t}+ \mathbf{b}_{c}), \tag{33}\] where \(\mathbf{W}_{c}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{c}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{c}\) are the learnable weights for the new memory cell. The new memory cell is also referred to as the _block input_ in the literature (Greff et al., 2016). The signal \(\widetilde{\mathbf{c}}_{t}\) is sometimes denoted by \(\mathbf{z}_{t}\) in the literature. The new memory cell is illustrated in Fig. 5. #### 4.1.5 The Final Memory Calculation After computation of the outputs of the input gate \(\mathbf{i}_{t}\), the forget gate \(\mathbf{f}_{t}\), and the new memory cell \(\widetilde{\mathbf{c}}_{t}\), we calculate the _final memory_\(\mathbf{c}_{t}\in\mathbb{R}^{p}\): \[\mathbf{c}_{t}=(\mathbf{f}_{t}\odot\mathbf{c}_{t-1})+(\mathbf{i}_{t}\odot\widetilde{\mathbf{c}}_{t }), \tag{34}\] where \(\mathbf{c}_{t-1}\in\mathbb{R}^{p}\) is the final memory of the previous time slot. As Eq. (34) demonstrates, the final memory considers the effect of the forget gate, the previous memory, the input, and the new memory. In the first term, i.e., \(\mathbf{f}_{t}\odot\mathbf{c}_{t-1}\), the forget gate \(\mathbf{f}_{t}\in[0,1]^{p}\) controls how much of the previous memory \(\mathbf{c}_{t-1}\) should be forgotten. The closer the \(\mathbf{f}_{t}\) is to zero, the more the network forgets the previous memory \(\mathbf{c}_{t-1}\). In the second term, i.e., \(\mathbf{i}_{t}\odot\widetilde{\mathbf{c}}_{t}\), the input gate \(\mathbf{i}_{t}\in[0,1]^{p}\) and the new memory cell \(\widetilde{\mathbf{c}}_{t}\in[-1,1]^{p}\) both control how much of the new input information should be used. The closer the input gate \(\mathbf{i}_{t}\) is to one and the closer the new memory cell \(\widetilde{\mathbf{c}}_{t}\) is to \(\pm 1\), the more the input information is used. In other words, the first and second terms in Eq. (34) determine the trade-off of usage of old versus new information in the sequence. The weights of these gates are trained in a way that they pass or block the input/previous information based on the input sequence and the time step in the sequence. The final memory calculation is depicted in Fig. 5. #### 4.1.6 The Hidden State (Block Output) After computation of the output of the output gate \(\mathbf{o}_{t}\) and the final memory \(\mathbf{c}_{t}\), we calculate the _hidden state_\(\mathbf{h}_{t}\in\mathbf{c}_{t-1}\). The hidden state \(\mathbf{h}_{t}\) is the hidden state \(\mathbf{h}_{t}\). The hidden state \(\mathbf{h}_{t}\) is the hidden state \(\mathbf{h}_{t}\). \([-1,1]^{p}\): \[\mathbf{h}_{t}=\mathbf{o}_{t}\odot\tanh(\mathbf{c}_{t}). \tag{35}\] This hidden state is also considered as the _block output_ of the LSTM cell, depicted in Fig. 5. #### 4.1.7 The Output The output \(\mathbf{y}_{t}\in\mathbb{R}^{q}\) of the LSTM cell is as follows: \[\mathbf{y}_{t}=\mathbf{V}\mathbf{h}_{t}+\mathbf{b}_{y}, \tag{36}\] where \(\mathbf{V}\in\mathbb{R}^{q\times p}\) and the bias \(\mathbf{b}_{y}\in\mathbb{R}^{q}\) are the learnable weights for the output. It is possible to use an activation function, such as Eq. (6), after this output signal. Figure 5 shows the output signal in the LSTM cell. Note that in the literature, the output is sometimes considered to be equal to the hidden state, i.e., \(\mathbf{y}_{t}=\mathbf{h}_{t}\), by setting \(\mathbf{V}=\mathbf{I}\) (the identity matrix) and \(\mathbf{b}_{y}=\mathbf{0}\) (the zero vector). ### History and Variants of LSTM LSTM has gone through various developments and improvements gradually (Greff et al., 2016). Some of the variants of LSTM do not have the peepholes. In this case, the Eqs. (29), (31), and (32) are simplified to: \[\mathbf{i}_{t}=\text{sig}\big{(}\mathbf{W}_{i}\,\mathbf{h}_{t-1}+\mathbf{U}_{i}\, \mathbf{x}_{t}+\mathbf{b}_{i}\big{)}, \tag{37}\] \[\mathbf{f}_{t}=\text{sig}\big{(}\mathbf{W}_{f}\,\mathbf{h}_{t-1}+\mathbf{U}_{f}\, \mathbf{x}_{t}+\mathbf{b}_{f}\big{)},\] (38) \[\mathbf{o}_{t}=\text{sig}\big{(}\mathbf{W}_{o}\,\mathbf{h}_{t-1}+\mathbf{U}_{o}\, \mathbf{x}_{t}+\mathbf{b}_{o}\big{)}, \tag{39}\] respectively. In the following, we review a history of variants of the LSTM networks. #### 4.2.1 Original LSTM LSTM was originally proposed by Hochreiter and Schmidhuber in years 1995 to 1997 (Hochreiter & Schmidhuber, 1995; 1997). We call it the _original LSTM_(Hochreiter & Schmidhuber, 1997). The original LSTM had only the input and output gates, introduced in Sections 4.1.1 and 4.1.3, and it did not have a forget gate. It also did not contain the peepholes; therefore, its gates were Eqs. (37) and (39). The original LSTM trained the network using BPTT (introduced in Section 2.3) and a mixture of real-time recurrent learning (Robinson & Fallside, 1987; Williams, 1989). #### 4.2.2 Vanilla LSTM Later, Gers _et. al._(Gers et al., 2000; Gers & Schmidhuber, 2000) applied some changes to the original LSTM. The forget gate, introduced in Section 4.1.2, was proposed for the first time in (Gers et al., 2000) to let the network forget its previous states either completely or partially. The peephole connections, introduced in Sections 4.1.1, 4.1.2, and 4.1.3, were first proposed in (Gers & Schmidhuber, 2000). The peepholes let a possible leak of information from the previous or current final memory. This lets the memory control the gates. These two papers (Gers et al., 2000; Gers & Schmidhuber, 2000) also incorporated the _full gate recurrence_, in which all gates receive additional recurrent inputs from all gates at the previous time step. In full gate recurrence, the Eqs. (29), (31), and (32) become: \[\begin{split}\dot{\mathbf{i}}_{t}=\text{sig}\big{(}& \mathbf{W}_{i}\,\mathbf{h}_{t-1}+\mathbf{U}_{i}\,\mathbf{x}_{t}+(\mathbf{p}_{i}\odot\mathbf{c}_{t-1})+ \mathbf{b}_{i}\\ &+\mathbf{R}_{ii}\,\dot{\mathbf{i}}_{t-1}+\mathbf{R}_{if}\,\mathbf{f}_{t-1}+\mathbf{R }_{io}\,\mathbf{o}_{t-1}\big{)}.\end{split} \tag{40}\] \[\begin{split}\mathbf{f}_{t}=\text{sig}\big{(}& \mathbf{W}_{f}\,\mathbf{h}_{t-1}+\mathbf{U}_{f}\,\mathbf{x}_{t}+(\mathbf{p}_{f}\odot\mathbf{c}_{t-1})+ \mathbf{b}_{f}\\ &+\mathbf{R}_{fi}\,\dot{\mathbf{i}}_{t-1}+\mathbf{R}_{ff}\,\mathbf{f}_{t-1}+\mathbf{R }_{fo}\,\mathbf{o}_{t-1}\big{)}.\end{split} \tag{41}\] \[\begin{split}\mathbf{o}_{t}=\text{sig}\big{(}& \mathbf{W}_{o}\,\mathbf{h}_{t-1}+\mathbf{U}_{o}\,\mathbf{x}_{t}+(\mathbf{p}_{o}\odot\mathbf{c}_{t})+ \mathbf{b}_{o}\\ &+\mathbf{R}_{oi}\,\dot{\mathbf{i}}_{t-1}+\mathbf{R}_{of}\,\mathbf{f}_{t-1}+\mathbf{R }_{oo}\,\mathbf{o}_{t-1}\big{)},\end{split} \tag{42}\] where \(\mathbf{R}_{ii},\mathbf{R}_{if},\mathbf{R}_{io},\mathbf{R}_{fi},\mathbf{R}_{ff},\mathbf{R}_{fo},\mathbf{R }_{oi},\mathbf{R}_{of},\mathbf{R}_{oo}\in\mathbb{R}^{p\times p}\) are the learnable recurrent weights. Note that the full gate recurrence often disappeared in later papers on LSTM. Later, Graves and Schmidhuber adapted the original LSTM and proposed the _vanilla LSTM_ in 2005 (Graves & Schmidhuber, 2005a), which is one of the most common LSTMs in the literature. The vanilla LSTM incorporated the structures of the original LSTM (Hochreiter & Schmidhuber, 1997) and the papers (Gers et al., 2000; Gers & Schmidhuber, 2000). The full BPTT, introduced in Section 2.3, was used for LSTM in the vanilla LSTM (Graves & Schmidhuber, 2005a). #### 4.2.3 Other LSTM Variants There are other variants of LSTM (Greff et al., 2016; Jozefowicz et al., 2015); although, the most common used LSTM is the vanilla LSTM (Graves & Schmidhuber, 2005a). BPTT was used for LSTM training in (Graves & Schmidhuber, 2005a); however, Kalman filtering was used for its training (Gers et al., 2002) before that. Another training method for LSTM was evolutionary learning (Schmidhuber et al., 2007). Context-sensitive evolutionary learning was also used for LSTM training (Bayer et al., 2009). Later works tried to improve the performance of LSTM. For example, Sak _et. al._ added a linear layer which projects the output of the LSTM to smaller number of parameters before the recurrent connections (Sak et al., 2014). Doetsch _et. al._ converted the slope of activation functions of the LSTM gates to learnable parameters for performance improvement (Doetsch et al., 2014). _Dynamic cortex memory_ was another LSTM variant which added connections between the gates within every LSTM cell (Otte et al., 2014). Finally in 2014, one the biggest improvements of LSTM was proposed, which was named the Gated Recurrent Units (GRU) (Cho et al., 2014). The philosophy of GRU was to simplify the LSTM cell because we may no need to have a very complicated cell to learn the sequence information. In other words, GRU raised the question of whether we need to be that flexible like LSTM to learn the sequence. GRU is less flexible than LSTM but it is good enough for sequence learning. GRU redesigned the LSTM cell by introducing reset gate, update gate, and new memory cell; therefore, the number of gates were reduced from four to three. It was empirically shown in (Chung et al., 2014) that the performance of LSTM improves by using GRU cells. Later in 2017, the GRU was further simplified by merging the reset and update gates into a forget gate (Heck and Salem, 2017). Nowadays, GRU is the most commonly used LSTM structure. Section 4.3 introduces the details of the GRU cell. ### Gated Recurrent Units (GRU) GRU was first proposed in (Cho et al., 2014). As was mentioned in Section 4.2.3, GRU simplified the LSTM cell in order to make the flexibility of LSTM. #### 4.3.1 Fully Gated Unit The main GRU was the _fully gated unit_(Cho et al., 2014), whose gates are introduced in the following. Its gates are illustrated in Fig. 6. **- The Reset Gate:** One of the gates in the GRU cell is the _reset gate_. This gate takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal \(\mathbf{r}_{t}\in[0,1]^{p}\): \[\mathbf{r}_{t}=\text{sig}(\mathbf{W}_{r}\,\mathbf{h}_{t-1}+\mathbf{U}_{r}\,\mathbf{x}_{t}+\mathbf{b}_{ r}), \tag{43}\] where \(\mathbf{W}_{r}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{r}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{r}\in\mathbb{R}^{p}\) are the learnable weights for the reset gate. The reset gate considers the effect of the input and the previous hidden state, and it controls the amount of forgetting/resetting the previous information with respect to the new-coming information. Comparing Eqs. (38) and (43) shows that the reset gate in the GRU cell is similar to the forget gate in the LSTM cell. The reset gate is depicted in Fig. 6. **- The Update Gate:** Another gate in the GRU cell is the _update gate_. This gate also takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal \(\mathbf{z}_{t}\in[0,1]^{p}\): \[\mathbf{z}_{t}=\text{sig}(\mathbf{W}_{z}\,\mathbf{h}_{t-1}+\mathbf{U}_{z}\,\mathbf{x}_{t}+\mathbf{b}_{ z}), \tag{44}\] where \(\mathbf{W}_{z}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{z}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{z}\in\mathbb{R}^{p}\) are the learnable weights for the update gate. The update gate considers the effect of the input and the previous hidden state, and it controls the amount of using the new input data for updating the cell by the coming information of sequence. Comparing Eqs. (37) and (44) shows that the update gate in the GRU cell is similar to the input gate in the LSTM cell. Figure 6 shows the update gate in the GRU cell. **- The New Memory Cell:** The GRU cell includes a gate named the _new memory cell_. This gate takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal Figure 6: The conveyor belt in the GRU cell (the fully gated unit). \(\widetilde{\mathbf{h}}_{t}\in[-1,1]^{p}\): \[\widetilde{\mathbf{h}}_{t}=\tanh\Bigl{(}\mathbf{W}_{c}\left(\mathbf{r}_{t}\odot\mathbf{h}_{t-1} \right)\Bigr{)}+\mathbf{U}_{c}\,\mathbf{x}_{t}+\mathbf{b}_{c}\Bigr{)}, \tag{45}\] where \(\mathbf{W}_{c}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{c}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{c}\) are the learnable weights for the new memory cell. This gate considers the effect of the input and the previous hidden state to represent the new information of current input. Comparing Eqs. (33) and (45) shows that the new memory cell in the GRU cell is similar to the new memory cell in the LSTM cell. Note that, in the LSTM cell, the hidden state (see Eq. (35)) and the new memory cell (see Eq. (33)) were different; however, the hidden state of the GRU cell (see Eq. (45)) replaces the new memory signal in the LSTM cell. The new memory cell is shown in Fig. 6. **- The Final Memory (Hidden State):** After computation of the outputs of the update gate \(\mathbf{z}_{t}\) and the new memory cell \(\widetilde{\mathbf{h}}_{t}\), we calculate the _final memory_ or the _hidden state_\(\mathbf{h}_{t}\in\mathbb{R}^{p}\): \[\mathbf{h}_{t}=\bigl{(}(\mathbf{1}-\mathbf{z}_{t})\odot\mathbf{h}_{t-1}\bigr{)}+(\mathbf{z}_{t} \odot\widetilde{\mathbf{h}}_{t}), \tag{46}\] where \(\mathbf{h}_{t-1}\in\mathbb{R}^{p}\) is the hidden state of the previous time slot. The final memory block is illustrated in Fig. 6. As Eq. (46) demonstrates, the final memory considers the effect of the update gate, the previous memory, and the new memory. In the first term, i.e., \((\mathbf{1}-\mathbf{z}_{t})\odot\mathbf{h}_{t-1}\), the update gate \(\mathbf{z}_{t}\in[0,1]^{p}\) controls how much of the previous state \(\mathbf{h}_{t-1}\) should be used based on the input data. The closer the \(\mathbf{z}_{t}\) is to one (resp. zero), the more the network forgets (resp. considers) the previous state \(\mathbf{h}_{t-1}\). In the second term, i.e., \(\mathbf{z}_{t}\odot\widetilde{\mathbf{h}}_{t}\), the update gate \(\mathbf{z}_{t}\in[0,1]^{p}\) and the new memory cell \(\widetilde{\mathbf{h}}_{t}\in[-1,1]^{p}\) both control how much of the new input information should be used. In other words, it controls how much the information should be updated by the new information. The closer the update gate \(\mathbf{z}_{t}\) is to one and the closer the new memory cell \(\widetilde{\mathbf{h}}_{t}\) is to \(\pm 1\), the more the input information is used. Overall, the first and second terms in Eq. (46) determine the trade-off of usage of old versus new information in the sequence. The weights of these gates are trained in a way that they pass or block the input/previous information based on the input sequence and the time step in the sequence. Comparing Eqs. (34) and (46) shows that the final memory in the GRU cell is in the form of the final memory in the LSTM cell; however, they have somewhat different functionality. #### 4.3.2 Minimal Gated Unit _Minimal gated unit_(Heck & Salem, 2017) is another variant of GRU which has simplified the gate by merging the reset and update gates into a forget gate. This merging is possible because the forget gate can control both the previous and new information of the sequence. **- The Forget Gate:** The _forget gate_ takes the input at the current time slot, \(\mathbf{x}_{t}\in\mathbb{R}^{d}\), and the hidden state of the last time slot, \(\mathbf{h}_{t-1}\in[-1,1]^{p}\), and outputs the signal \(\mathbf{r}_{t}\in[0,1]^{p}\): \[\mathbf{f}_{t}=\text{sig}(\mathbf{W}_{f}\,\mathbf{h}_{t-1}+\mathbf{U}_{f}\,\mathbf{x}_{t}+\mathbf{b}_{ f}), \tag{47}\] where \(\mathbf{W}_{f}\in\mathbb{R}^{p\times p}\), \(\mathbf{U}_{f}\in\mathbb{R}^{p\times d}\), and the bias \(\mathbf{b}_{f}\in\mathbb{R}^{p}\) are the learnable weights for the forget gate. The forget gate considers the effect of the input and the previous hidden state, and it controls the amount of forgetting the previous information with respect to the new-coming information. Therefore, it controls both forgetting or using the previous memory and using the new coming information. **- The New Memory Cell and the Final Memory:** Because the forget gate replaces the reset and the update gate in the minimal gate unit, Eqs. (45) and (46) are changed to: \[\widetilde{\mathbf{h}}_{t} =\tanh\Bigl{(}\mathbf{W}_{c}\left(\mathbf{f}_{t}\odot\mathbf{h}_{t-1}) \right)+\mathbf{U}_{c}\,\mathbf{x}_{t}+\mathbf{b}_{c}\Bigr{)}, \tag{48}\] \[\mathbf{h}_{t} =\bigl{(}(\mathbf{1}-\mathbf{f}_{t})\odot\mathbf{h}_{t-1}\bigr{)}+(\mathbf{f}_{t} \odot\widetilde{\mathbf{h}}_{t}), \tag{49}\] respectively, to be the new memory cell and the final memory in the minimal gate unit. ## 5 Bidirectional RNN and LSTM ### Justification of Bidirectional Processing A bidirectional RNN or LSTM network processes the sequence in both directions; left to right and right to left. In the first glance, online causal tasks such as reading a text or listening to a speech do not have access to the future. Therefore, bidirectional networks seem to violate causality in them. However, in many of these tasks, it is possible to wait for the completion of a part of the sequence such as a sentence and then decide about it. For example, it is normal to wait for the completion of sentence in speech recognition and then recognize it (Graves & Schmidhuber, 2005a;b). In text processing, the text is usually available except in a streaming text. Even in streaming text, it is possible to wait for a sentence to complete. Therefore, it makes sense to use bidirectional networks for processing sequences because, sometimes, the important related word comes after a word and not necessarily before it. An example for such a case is the sentence "The police is chasing the thief" where the word "thief" is a strongly related (opposite) word for the word "police". In this sentence, both the words "thief" and "police" are related and it is worth to process the sentence in both directions. ### Bidirectional RNN The bidirectional RNN was first proposed in (Schuster & Paliwal, 1997) and further exploited in (Baldi et al., 1999). It uses two sets of states each for one of the directions in the sequence. Let the states for left-to-right and right-to-left processing be denoted by \(\overrightarrow{\boldsymbol{h}}_{t}\) and \(\overleftarrow{\boldsymbol{h}}_{t}\), respectively. In the bidirectional RNN, Eq. (4) is replaced by two equations (Graves et al., 2013): \[\overrightarrow{\boldsymbol{h}}_{t}=\tanh(\overrightarrow{ \boldsymbol{W}}\overrightarrow{\boldsymbol{h}}_{t-1}+\overrightarrow{ \boldsymbol{U}}\boldsymbol{x}_{t}+\overrightarrow{\boldsymbol{b}}_{i}), \tag{50}\] \[\overleftarrow{\boldsymbol{h}}_{t}=\tanh(\overleftarrow{ \boldsymbol{W}}\overleftarrow{\boldsymbol{h}}_{t+1}+\overleftarrow{ \boldsymbol{U}}\boldsymbol{x}_{t}+\overleftarrow{\boldsymbol{b}}_{i}), \tag{51}\] and Eq. (5) is replaced by: \[\boldsymbol{y}_{t}=\overrightarrow{\boldsymbol{V}}\overrightarrow{ \boldsymbol{h}}_{t}+\overleftarrow{\boldsymbol{V}}\overleftarrow{ \boldsymbol{h}}_{t}+\boldsymbol{b}_{y}, \tag{52}\] where the arrows show the parameters for each direction of processing. The unfolding schematic of the bidirectional RNN is illustrated in Fig. 7. As this figure shows, the outputs of both directions are connected to an output layer. In some cases, this output layer may be replaced by a third multi-layer neural network. All weights of the bidirectional RNN are trained using backpropagation through time similarly to what was explained in Section 2.3. It is noteworthy that the deep variant of bidirectional RNN has been proposed in (Graves et al., 2013). ### Bidirectional LSTM Bidirectional LSTM was first proposed in (Graves and Schmidhuber, 2005; 20). As obvious from its name, the bidirectional LSTM includes two LSTM networks each of which processes the sequence from one direction. In other words, there are two LSTM networks which are fed with the sequence in opposite orders. This structure is depicted in Fig. 8. Experiments have shown that the bidirectional LSTM outperforms the unidirectional LSTM (Graves and Schmidhuber, 2005; Graves et al., 2005). This is expected according to the justification in Section 5.1. Because of its advantages, various methods have combined the bidirectional LSTM with other methods. For example, a hybrid of the bidirectional LSTM and HMM (Ghojogh et al., 2019) has shown its merit (Graves et al., 2005). Another example is the hybrid of bidirectional LSTM and Conditional Random Fields (CRF) (Lafferty et al., 2001) for the sequence tagging task (Huang et al., 2015). Other extensions of bidirectional LSTM networks exist such as (Peters et al., 2017). ### Embeddings from Language Model (ELMo) The Embeddings from Language Model (ELMo) network, first proposed in (Peters et al., 2018), is a language model which makes use of bidirectional LSTM networks. It is one of the successful context-aware language modeling networks. It has been widely used in various applications such as in medical interview processing (Sarzynska-Wawer et al., 2021). The structure of ELMo is illustrated in Fig. 9. As shown in this figure, ELMo contains \(L\) layers of bidirectional LSTM networks where the output of each bidirectional LSTM is fed to the next bidirectional LSTM. in The bidirectional LSTM networks of ELMo, \(\boldsymbol{V}=\boldsymbol{I}\) is set so that the outputs \(\boldsymbol{y}\) becomes equal to the hidden states \(\boldsymbol{h}\). At time slot \(t\) and layer \(l\), the outputs (or hidden states) of the two directions of LSTM are concatenated together to make \(\boldsymbol{h}_{t}^{(l)}\): \[\boldsymbol{h}_{t}^{(l)}:=[\overrightarrow{\boldsymbol{h}}_{t}^{(l)\top}, \overleftarrow{\boldsymbol{h}}_{t}^{(l)\top}]^{\top}.\] Then, a linear combination of these hidden states of layers is considered to be the embedding vector of ELMo network at time \(t\)(Peters et al., 2018): \[\boldsymbol{y}_{t}^{\text{ELMo}}:=\gamma\sum_{l=1}^{L}s_{l}\, \boldsymbol{h}_{t}^{(l)}, \tag{53}\] where \(\gamma\) and \(\{s_{l}\}_{l=1}^{L}\) are the hyperparameter scalar weights which are determined according to the specific task (e.g., Figure 8: The bidirectional LSTM. Figure 7: The bidirectional RNN. question answering, translation, etc) in natural language processing. ## 6 Conclusion This was a tutorial paper on RNN, LSTM, and its variants. We covered dynamical system, backpropagation through time, LSTM gates and cells, history and variants of LSTM, the GRU cell, bidirectional RNN, bidirectional LSTM, and ELMo network.
2307.07753
Learning Expressive Priors for Generalization and Uncertainty Estimation in Neural Networks
In this work, we propose a novel prior learning method for advancing generalization and uncertainty estimation in deep neural networks. The key idea is to exploit scalable and structured posteriors of neural networks as informative priors with generalization guarantees. Our learned priors provide expressive probabilistic representations at large scale, like Bayesian counterparts of pre-trained models on ImageNet, and further produce non-vacuous generalization bounds. We also extend this idea to a continual learning framework, where the favorable properties of our priors are desirable. Major enablers are our technical contributions: (1) the sums-of-Kronecker-product computations, and (2) the derivations and optimizations of tractable objectives that lead to improved generalization bounds. Empirically, we exhaustively show the effectiveness of this method for uncertainty estimation and generalization.
Dominik Schnaus, Jongseok Lee, Daniel Cremers, Rudolph Triebel
2023-07-15T09:24:33Z
http://arxiv.org/abs/2307.07753v1
# Learning Expressive Priors for Generalization and ###### Abstract In this work, we propose a novel prior learning method for advancing generalization and uncertainty estimation in deep neural networks. The key idea is to exploit scalable and structured posteriors of neural networks as informative priors with generalization guarantees. Our learned priors provide expressive probabilistic representations at large scale, like Bayesian counterparts of pre-trained models on ImageNet, and further produce non-vacuous generalization bounds. We also extend this idea to a continual learning framework, where the favorable properties of our priors are desirable. Major enablers are our technical contributions: (1) the sums-of-Kronecker-product computations, and (2) the derivations and optimizations of tractable objectives that lead to improved generalization bounds. Empirically, we exhaustively show the effectiveness of this method for uncertainty estimation and generalization. Machine Learning, Uncertainty Estimation, Neural Networks ## 1 Introduction Within the deep learning approach to real-world AI problems such as autonomous driving, generalization and uncertainty estimation are one of the most important pillars. To achieve this, Bayesian Neural Networks (BNNs) (MacKay, 1992; Hinton & van Camp, 1993; Neal, 1996) leverage the tools of Bayesian statistics in order to improve generalization and uncertainty estimation in deep neural networks. Due to their potential and advancements so far, BNNs have become increasingly popular research topics (Gawlikowski et al., 2021). However, one of the open problems in BNNs is the prior specifications. While it is widely known that prior selection is a crucial step in any Bayesian modeling (Bayes, 1763), the choice of well-specified priors is generally unknown in neural networks. Consequently, many current approaches have resorted to uninformative priors, like isotropic Gaussian, despite reported signs of prior misspecifications (Wenzel et al., 2020; Fortuin, 2022). To address the problem of prior specification, we propose a prior learning method for BNNs. Our method is grounded in sequential Bayesian inference (Opper, 1999), where the posteriors from the past are used as the prior for the future. We achieve this by relying on Laplace Approximation (LA) (MacKay, 1992) with Kronecker-factorization of the posteriors (Ritter et al., 2018; Daxberger et al., 2021). Within this framework, we devise key technical novelties to learn expressive BNN priors with generalization guarantees. First, we demonstrate the sums-of-Kronecker-product computations so that the posteriors in matrix normal distributions, _i.e_., Gaussian with Kronecker-factorized covariance matrices (Gupta & Nagar, 2000), can be tractably used as expressive BNN priors. Second, to explicitly improve generalization, we derive and optimize over a tractable approximation of PAC-Bayes bounds (McAllester, 1999; Germain et al., 2016) that lead to non-vacuous bounds, _i.e_., smaller than the upper bound of the loss. Finally, as an added benefit of our idea, a Bayesian re-interpretation to a popular continual learning architecture, namely progressive neural networks (Rusu et al., 2016), is provided for uncertainty-awareness, generalization, and resiliency to catastrophic forgetting. By design, our method has many advantages for generalization and uncertainty estimation in neural networks. The proposed method achieves non-vacuous generalization bounds in deep learning models, while potentially avoiding prior misspecification for uncertainty estimation using BNNs. For these features, we provide computationally tractable techniques in order to learn expressive priors from large amounts of data and deep network architectures. We contend that such probabilistic representation at a large scale, e.g., pre-trained BNNs on ImageNet, can be beneficial in downstream tasks for both transfer and continual learning set-ups. Therefore, we further provide ablation studies and various experiments to show the aforementioned benefits of our method within the small and large-scale transfer and continual learning tasks. In particular, we empirically demonstrate that our priors mitigate cold posterior effects (Wenzel et al., 2020) - a potential sign of a bad prior - and further produce generalization bounds. Moreover, within a practical scenario of robotic continual learning (Denninger and Triebel, 2018), and standardized benchmarks of few-shot classification (Tran et al., 2022) for the recent uncertainty baselines (Nado et al., 2021), considerable performance improvements over the popular methods are reported. **Contributions** To summarize, our primary contribution is a novel method for learning scalable and structured informative priors (Section 2), backed up by (a) the sums-of-Kronecker-product computations for computational tractability (Section 2.2), (b) derivation and optimizations over tractable generalization bounds (Section 2.3), (c) a Bayesian re-interpretation of progressive neural networks for continual learning (Section 2.4), (d) exhaustive experiments to show the effectiveness of our method (Section 4). ## 2 Learning Expressive Priors ### Notation and Background Consider a neural network \(f_{\mathbf{\theta}}\) with layers \(l\in[L]:=\{1,\dots,L\}\) which consists of a parameterized function \(\phi_{l}:\Omega_{l-1}\rightarrow\Omega_{l}\) and a non-linear activation function \(\sigma_{l}:\Omega_{l}\rightarrow\Omega_{l}\). We denote an input for a network as \(\mathbf{x}\in\Omega_{0}=:\mathcal{X}\) and all learnable parameters as a stacked vector \(\mathbf{\theta}\). Then the pre-activation \(\mathbf{s}_{l}\) and activation \(\mathbf{a}_{l}\) are recursively applied with \(\mathbf{a}_{0}=\mathbf{x}\), \(\mathbf{s}_{l}=\phi_{l}(\mathbf{a}_{l-1})\) and \(\mathbf{a}_{l}=\sigma_{l}(\mathbf{s}_{l})\). The output of the neural network \(\mathbf{y}\) is given by the last activation \(\mathbf{y}=\mathbf{a}_{L}=f_{\mathbf{\theta}}(\mathbf{x})\). The structure of the learning process is governed by different architectural choices such as fully connected, recurrent, and convolutional layers (Goodfellow et al., 2016). The parameters \(\mathbf{\theta}\) are typically obtained by maximum likelihood principles, given training data \(\mathcal{D}=\left((\mathbf{x}_{i},\mathbf{y}_{i})\right)_{i=1}^{N}\). Unfortunately, these principles lead to the lack of generalization and calibrated uncertainty in neural networks (Jospin et al., 2020). To address these, BNNs provide a compelling alternative by applying Bayesian principles to neural networks. In BNNs, the first step is to specify a prior distribution \(\pi(\mathbf{\theta})\). Then the Bayes theorem is used to compute the posterior distribution over the parameters, given the training data: \(p(\mathbf{\theta}|\mathcal{D})\propto\pi(\mathbf{\theta})\prod_{i=1}^{N}p(\mathbf{y} _{i}|\mathbf{x}_{i},f_{\mathbf{\theta}})\). This means that each parameter is not a single value, but a probability distribution, representing the uncertainty of the model (Gawlikowski et al., 2021). The posterior distribution provides a set of plausible model parameters, which can be marginalized to compute the predictive distributions of a new sample \((\mathbf{x}^{*},\mathbf{y}^{*})\notin\mathcal{D}\) for BNNs: \(p(\mathbf{y}^{*}|\mathbf{x}^{*},\mathcal{D})=\int p(\mathbf{y}^{*}|\mathbf{ x}^{*},f_{\mathbf{\theta}})\rho(\mathbf{\theta})d\mathbf{\theta}\). In the case of neural networks, the posteriors cannot be obtained in closed form. Hence, many of the current research efforts are on accurately approximating the posteriors of BNNs. For this, LA (MacKay, 1992) approximates the BNN posteriors with a Gaussian distributions around a local mode. Here, a prior is first specified as an isotropic Gaussian. With this prior, the maximum-a-posteriori (MAP) estimates of the parameters \(\mathbf{\hat{\theta}}\) are obtained by training the neural networks. Then, the Hessian \(\mathbf{H}=\frac{d^{2}}{d\mathbf{\theta}^{2}}\ln p(\mathbf{\theta}|\mathcal{D})= \mathbf{H}_{likelihood}+\mathbf{H}_{prior}\) is computed to obtain the BNN posteriors. In practice, the covariance matrix is usually further scaled which more generally corresponds to temperature scaling. In summary, the priors-posteriors pairs of LA are: \[\text{Prior:}\quad\pi(\mathbf{\theta})=\mathcal{N}(\mathbf{0}, \gamma\mathbf{I}), \tag{1}\] \[\text{Posterior:}\quad p(\mathbf{\theta}|\mathcal{D})\approx\mathcal{N}( \mathbf{\hat{\theta}},(\mathbf{H}_{likelihood}+\mathbf{H}_{prior})^{-1}).\] As the Hessian is computationally intractable for modern architectures, the Kronecker-Factored Approximate Curvature (KFAC) method is widely adopted (Martens and Grosse, 2015). KFAC approximates the true Hessian by a layer-wise block-diagonal matrix, where each diagonal block is the Kronecker-factored Fisher matrix \(\mathbf{F}_{l}\). Therefore, defining the layer-wise activation \(\mathbf{\bar{u}}_{l}\) and loss gradient w.r.t pre-activation \(\mathcal{D}\mathbf{s}_{l}\), the inverse covariance matrix of the posteriors is (Ritter et al., 2018): \[\mathbf{H}\approx\mathbf{F}=\operatorname{diag}(\mathbf{F}_{1}, \mathbf{F}_{2},\cdots,\mathbf{F}_{L})+\gamma\mathbf{I}, \tag{2}\] \[\text{where}\ \mathbf{F}_{l}\approx\mathbb{E}[\mathcal{D} \mathbf{s}_{l}(\mathcal{D}\mathbf{s}_{l})^{T}]\otimes\mathbb{E}[\mathbf{\bar{u }}_{l}(\mathbf{\bar{u}}_{l})^{T}]=\mathbf{L}_{l}\otimes\mathbf{R}_{l}.\] In this way, using LA, BNN posteriors can be obtained by approximating the Hessian of neural networks. We provide more details on LA and KFAC in Appendix A.1. We note several ramifications of this formulation for learning BNN priors from data. First, the BNN posteriors can be obtained by approximating the Hessian, which can be tractably computed from large amounts of data and deeper neural network architectures (Lee et al., 2020; Ba et al., 2017). Second, the resulting BNN posteriors can capture the correlations between the parameters within the same layer (Ritter et al., 2018). Moreover, several open-source libraries exist to ease the implementations (Daxberger et al., 2021; Humt et al., 2020). All these points result in easily-obtainable BNN posteriors with expressive probabilistic representation from large amounts of data, deep architectures, and parameter correlations. As opposed to isotropic Gaussian, we next demonstrate that these BNN posteriors can be used to learn expressive prior distributions in order to advance generalization and uncertainty estimation within the transfer and continual learning set-ups. ### Empirical Prior Learning with Sums-of-Kronecker-Product Computations Intuitively, the idea is to repeat the LA with the prior chosen as the posterior from Equation (1), similar to Bayesian filtering. Since we use the LA with a Kronecker-factored covariance matrix in both the prior and the posterior, we want to approximate the resulting sum of Kronecker products with a single Kronecker product. We denote the task to compute the prior as source task \(\mathfrak{T}_{0}\) and the task to compute the posterior as target task \(\mathfrak{T}_{1}\), both consisting of a data-set \(\mathcal{D}_{t}\) from a distribution \(P_{t}\), \(t\in\{0,1\}\). Applying LA on \(\mathcal{D}_{0}\), we obtain the model parameters \(\hat{\mathbf{\theta}}^{(0)}\) and the posteriors \(p(\mathbf{\theta}|\mathcal{D}_{0})\) as before (equations 1 and 2). Then, for the target task, we specify the prior using the posteriors from \(\mathcal{D}_{0}\): \(\pi(\mathbf{\theta})=p(\mathbf{\theta}|\mathcal{D}_{0})\). The ultimate goal is to compute the new posteriors on \(\mathcal{D}_{1}\), _i.e._, \(p(\mathbf{\theta}|\mathcal{D}_{1})\propto p(\mathcal{D}_{1}|f_{\mathbf{\theta}})\pi( \mathbf{\theta})\). To achieve this, we train the neural networks on \(\mathcal{D}_{1}\) by optimizing: \[\begin{split}\hat{\mathbf{\theta}}^{(1)}&\in\operatorname* {arg\,max}_{\mathbf{\theta}}\{p(\mathbf{\theta}|\mathcal{D}_{1})\}\\ &=\operatorname*{arg\,min}_{\mathbf{\theta}}\{-\ln\left(p(\mathcal{D }_{1}|f_{\mathbf{\theta}})\right)\\ &\qquad\qquad+\frac{1}{2}(\mathbf{\theta}-\hat{\mathbf{\theta}}^{(0)})^{ T}(\mathbf{F}^{(0)}+\gamma\mathbf{I})(\mathbf{\theta}-\hat{\mathbf{\theta}}^{(0)})\},\end{split} \tag{3}\] where \(\hat{\mathbf{\theta}}^{(1)}\) is the MAP estimate of the model parameters for task \(\mathfrak{T}_{1}\) and \(\mathbf{F}^{(0)}\) is the block-diagonal Kronecker-factored Fisher matrix from task \(\mathfrak{T}_{0}\). The final step is to approximate new Hessian on \(\mathcal{D}_{1}\) using the KFAC method. This results in \[\text{Prior:}\quad\pi=\mathcal{N}(\hat{\mathbf{\theta}}^{(0)},( \mathbf{F}^{(0)}+\gamma\mathbf{I})^{-1}) \tag{4}\] \[\text{Posterior:}\quad\rho=\mathcal{N}(\hat{\mathbf{\theta}}^{(1)}, \tau(\mathbf{F}^{(1)}+\mathbf{F}^{(0)}+\gamma\mathbf{I})^{-1}),\] where \(\tau\) is the temperature scaling (Wenzel et al., 2020; Daxberger et al., 2021). Here, the precision matrix of the new BNN posteriors is represented by the sum-of-Kronecker-products, _i.e._, \(\bar{\mathbf{F}}^{(1)}=\mathbf{F}^{(1)}+\mathbf{F}^{(0)}+\gamma\mathbf{I}= \mathbf{L}^{(0)}\otimes\mathbf{R}^{(0)}+\mathbf{L}^{(1)}\otimes\mathbf{R}^{(1) }+\gamma\mathbf{I}\otimes\mathbf{I}\). ``` 1:Input: left matrices \((\mathbf{L}^{k})_{k\in[K]}\), right matrices \((\mathbf{R}^{k})_{k\in[K]}\), number of steps \(n^{max}=100\), and stopping precision \(\delta=10^{-5}\). 2:Output: The solutions \(\hat{\mathbf{L}}\) and \(\hat{\mathbf{R}}\). 3:\(\operatorname{vec}(\bar{\mathbf{L}}^{(0)})\leftarrow\mathcal{N}(\mathbf{0}, \mathbf{I})\) {initialization of \(\bar{\mathbf{L}}^{(0)}\)} 4:\(\mathbf{L}^{(0)}\leftarrow\frac{\bar{\mathbf{L}}^{(0)}}{\|\bar{\mathbf{L}}^{( 0)}\|_{F}}\) {normalize \(\bar{\mathbf{L}}^{(0)}\)} 5:for\(n=1\) to \(n^{max}\)do 6:\(\bar{\mathbf{R}}^{(n)}\leftarrow\sum_{k=1}^{K}(\mathbf{L}^{k},\mathbf{L}^{(n- 1)})_{F}\mathbf{R}^{k}\) {first power step} 7:\(\mathbf{R}^{(n)}\leftarrow\frac{\mathbf{R}^{(n)}}{\|\bar{\mathbf{R}}^{(n)}\|_ {F}}\) {normalize \(\bar{\mathbf{R}}^{(n)}\)} 8:\(\bar{\mathbf{L}}^{(n)}\leftarrow\sum_{k=1}^{K}(\mathbf{R}^{k},\mathbf{R}^{(n )})_{F}\mathbf{L}^{k}\) {second power step} 9:\(\mathbf{L}^{(n)}\leftarrow\frac{\bar{\mathbf{L}}^{(n)}}{\|\bar{\mathbf{L}}^{( n)}\|_{F}}\) {normalize \(\bar{\mathbf{L}}^{(n)}\)} 10:if\(\|\mathbf{L}^{(n)}-\mathbf{L}^{(n-1)}\|_{F}<\delta\)then 11:break {stopping criterion} 12:endif 13:endfor 14:\(\hat{\mathbf{L}}\leftarrow\mathbf{L}^{(n)}\) 15:\(\hat{\mathbf{R}}\leftarrow\sum_{k=1}^{K}(\mathbf{L}^{k},\mathbf{L}^{(n)})_{F} \mathbf{R}^{k}\) {first power step} ``` **Algorithm 1** Power method for sums of Kronecker products Unfortunately, the sum-of-Kronecker-products is not a Kronecker-factored matrix. As a result, the above formulation loses all the essence of Kronecker factorization for modeling high-dimensional probability distributions. For example, we can no longer exploit the rule: \((\mathbf{L}\otimes\mathbf{R})^{-1}=(\mathbf{L}^{-1}\otimes\mathbf{R}^{-1})\) where \(\mathbf{L}\) and \(\mathbf{R}\) are smaller matrices to store and invert when compared to \((\mathbf{L}\otimes\mathbf{R})\). Even more, the storage and the inverse of \(\bar{\mathbf{F}}^{(1)}\) may not be computationally tractable for modern architectures. To this end, we devise the sum-of-Kronecker-products computations. Concretely, we approximate the sum-of-Kronecker-products as Kronecker-factored matrices by an optimization formulation:12 Footnote 1: For the similar causes to maintain the Kronecker factorization, Ritter et al. (2018b;a) assume \((\mathbf{L}\otimes\mathbf{R}+\gamma\mathbf{I})^{-1}=(\mathbf{L}+\gamma\mathbf{ I})^{-1}\otimes(\mathbf{R}+\gamma\mathbf{I})^{-1}\) which does not hold in general (see Section 4.1). Footnote 2: Our formulation for one single Kronecker-factored matrix is similar to Kao et al. (2021). \[\hat{\mathbf{L}},\hat{\mathbf{R}}\in\operatorname*{arg\,min}_{ \begin{subarray}{c}\mathbf{L}\in\mathbb{R}^{M\times M}\\ \mathbf{R}\in\mathbb{R}^{N\times N}\end{subarray}}\|\sum_{k=1}^{K}\mathbf{L}^{k} \otimes\mathbf{R}^{k}-\mathbf{L}\otimes\mathbf{R}\|_{F}. \tag{5}\] A solution to this problem is not unique, e.g., one could scale \(\hat{\mathbf{L}}\) by \(\alpha\neq 0\) and \(\hat{\mathbf{R}}\) by \(\frac{1}{\alpha}\). Hence, we assume that \(\hat{\mathbf{L}}\) is normalized, \(\|\hat{\mathbf{L}}\|_{F}=1\) (or alternatively, we can also assume \(\|\hat{\mathbf{R}}\|_{F}=1\)). For the solution, we show the equivalence to the well-known best rank-one approximation problem. **Lemma 2.1**.: _Let \(M,N,K\in\mathbb{N}\), \(\mathbf{L}^{k}\in\mathbb{R}^{M\times M}\) and \(\mathbf{R}^{k}\in\mathbb{R}^{N\times N}\) for \(k\in[K]\). Then_ \[\|\sum_{k=1}^{K}\mathbf{L}^{k}\otimes\mathbf{R}^{k}-\mathbf{L} \otimes\mathbf{R}\|_{F} \tag{6}\] \[=\|\sum_{k=1}^{K}\operatorname{vec}(\mathbf{L}^{k})\operatorname{ vec}(\mathbf{R}^{k})^{T}-\operatorname{vec}(\mathbf{L})\operatorname{vec}(\mathbf{R})^{T}\|_{F}.\] Proof.: The proof can be found in Appendix C.1. This result indicates that the solution to equation 5 can be obtained using the power method, which iterates: \[\mathbf{R}^{(n)}\leftarrow\frac{\sum_{k=1}^{K}(\mathbf{L}^{k}, \mathbf{L}^{(n-1)})_{F}\mathbf{R}^{k}}{\|\sum_{k=1}^{K}(\mathbf{L}^{k}, \mathbf{L}^{(n-1)})_{F}\mathbf{R}^{k}\|_{F}}\quad\text{and}\] \[\mathbf{L}^{(n)}\leftarrow\frac{\sum_{k=1}^{K}(\mathbf{R}^{k}, \mathbf{R})_{F}\mathbf{L}^{k}}{\|\sum_{k=1}^{K}(\mathbf{R}^{k},\mathbf{R})_{F} \mathbf{L}^{k}\|_{F}}.\] Given randomly initialized matrices, the power method iterates until the stop criterion is reached. The full procedure is presented in Algorithm 1, whereas in Appendix B, we discuss the computational complexity of the algorithm. Importantly, we can now obtain a single Kronecker factorization from the sum of Kronecker products. Such Kronecker-factored approximations have advantages on tractable memory consumption for the storage and the inverse computations, which enables sampling from the resulting matrix normal distributions (Martens and Grosse, 2015). Therefore, such computations allow us to learn expressive BNN priors from the posterior distributions of previously encountered tasks. Finally, we can also prove the convergence of the power method to an optimal rank-one solution. **Lemma 2.2**.: _Let \(\mathbf{A}=\sum_{k=1}^{K}\operatorname{vec}(\mathbf{L}^{k})\operatorname{vec}( \mathbf{R}^{k})^{T}\) and \(\mathbf{A}=\sum_{i=1}^{r}\sigma_{i}\mathbf{u}_{i}\mathbf{v}_{i}^{T}\) be its singular value decomposition with \(\sigma_{1}\geq\sigma_{2}\geq\cdots\geq\sigma_{r}>0\) and \(\mathbf{u}_{i}^{T}\mathbf{u}_{j}=\mathbf{v}_{i}^{T}\mathbf{v}_{j}=\mathbb{1}[i =j]\). Then there is a solution of Equation 5 with \(\operatorname{vec}(\tilde{\mathbf{L}})=\mathbf{u}_{1}\text{vec}(\tilde{ \mathbf{R}})=\sigma_{1}\mathbf{v}_{1}\). If \(\sigma_{1}>\sigma_{2}\), the solution is unique up to changing the sign of both factors, and our power method converges almost surely to this solution._ Proof.: The proof can be found in Appendix C.2. ### Derivations and Optimizations over Tractable PAC-Bayes Bounds So far, we have presented a method for learning a scalable and structured prior. In this section, we show how generalization bounds for the LA can be adapted to explicitly minimize the generalization bounds with the learned prior. In particular, the proposed approach allows tuning the hyper-parameters of the LA on the training set without a costly grid search. This is achieved by optimizing a differentiable cost function that approximates generalization bounds for the LA. We choose to optimize generalization bounds to trade off the broadness of the distribution and the performance on the training data to improve generalization. A common method in BNNs, and especially in LA, is to scale the covariance matrix by a positive scalar called the temperature \(\tau>0\)(Wenzel et al., 2020; Daxberger et al., 2021). In addition, often either the Hessian (or Fisher matrix) of the likelihood (Ritter et al., 2018; Lee et al., 2020) or the prior (Gawlikowski et al., 2021) is scaled. Including all these terms, the posterior has the following form: \[\rho=\mathcal{N}(\boldsymbol{\hat{\theta}}^{(1)},\tau(\beta\mathbf{F}^{(1)}+ \alpha\tilde{\mathbf{F}}^{(0)})^{-1}), \tag{7}\] where \(\tilde{\mathbf{F}}^{(0)}=\mathbf{F}^{(0)}+\gamma\mathbf{I}\) is the precision matrix of the prior. This reweighting of the three scalars allows us to cope with misspecified priors (Wilson and Izmailov, 2020), approximation errors in the Fisher matrices, and to improve the broadness of the distribution. While these values are usually hyperparameters that have to be manually scaled by hand, we argue that these values should be application-dependent. Therefore, we propose to find all three scales - \(\alpha\), \(\beta\), and \(\tau\) - by minimizing generalization bounds. In the following, we will first introduce our two approaches and then explain how the optimization of PAC-Bayes bounds can be made tractable for the LA. **Method 1: Curvature Scaling**_Previous approaches typically scale only one or two of the scales (Daxberger et al., 2021; Ritter et al., 2018; Lee et al., 2020). With our automatic scaling, we can optimize all three scales for each individual layer, allowing the model to decide the weighting in a more fine-grained way. We can use this method not only to scale the posterior, but also to compute the prior. Thus, the prior and posterior are defined as_ \[\pi=\mathcal{N}(\boldsymbol{\hat{\theta}}^{(0)},(\tilde{\mathbf{F}}^{(0)})^{- 1}),\quad\rho=\mathcal{N}(\boldsymbol{\hat{\theta}}^{(1)},(\tilde{\mathbf{F}}^ {(1)})^{-1}), \tag{8}\] _where the diagonal blocks of the precision matrix corresponding to each layer are defined as \(\tilde{\mathbf{F}}^{(0)}_{l}=\frac{1}{\tau_{l}^{(0)}}(\beta_{l}^{(0)}\mathbf{F }_{l}^{(0)}+\alpha_{l}^{(0)}\gamma\mathbf{I})\) and \(\tilde{\mathbf{F}}_{l}^{(1)}=\frac{1}{\tau_{l}^{(0)}}(\beta_{l}^{(1)}\mathbf{ F}_{l}^{(1)}+\alpha_{l}^{(1)}\tilde{\mathbf{F}}_{l}^{(0)})\), respectively._ _Remark 2.3_.: Although the temperature scaling could be captured within the other curvature scales, we find it easier to optimize the bounds with all three parameters per layer. **Method 2: Frequentist Projection**_Going one step further, we propose to scale not only the curvature but also the network parameters using PAC-Bayes bounds. Since the Fisher matrix is known only after training, we assume the same covariance for the posterior as for the prior when optimizing the network parameters. Since this method does not optimize for the MAP parameters, but only for minimizing the PAC-Bayes bounds, we call it frequentist projection._ Both methods aim at improving the generalization of our model. To do this, we use PAC-Bayes bounds (Germain et al., 2016; Guedj, 2019) to derive a tractable objective that can be optimized without going through the data-set. The main idea of PAC-Bayes theory is to upper bound the expected loss on the true data distribution \(P^{N}\) with high probability. The bounds typically depend on the expected empirical loss on the training data and the KL-divergence between a data-independent prior and the posterior distribution. For \(\varepsilon>0\), that is \[P_{\mathcal{D}\sim P^{N}}( \forall\rho\ll\pi:\ \mathbb{E}_{\boldsymbol{\theta}\sim\rho}[ \mathcal{L}_{P}^{l}(f_{\boldsymbol{\theta}})] \tag{9}\] \[\leq\delta(\mathbb{E}_{\boldsymbol{\theta}\sim\rho}[\hat{ \mathcal{L}}_{\mathcal{D}}^{l}(f_{\boldsymbol{\theta}})],\mathbb{KL}(\rho|\pi),N,\varepsilon))\geq 1-\varepsilon,\] where the loss on the true data distribution is denoted as \(\mathcal{L}_{P}^{l}(f_{\boldsymbol{\theta}})=\mathbb{E}_{(\mathbf{x}, \mathbf{y})\sim P}[l(f_{\boldsymbol{\theta}}(\mathbf{x}),\mathbf{y})]\) and the empirical loss on the training data is \(\hat{\mathcal{L}}_{\mathcal{D}}^{l}(f_{\boldsymbol{\theta}})=\frac{1}{N}\sum_{ i=1}^{N}l(f_{\boldsymbol{\theta}}(\mathbf{x}),\mathbf{y})\). In general, the bounds balance the fit to the available data (empirical risk term) and the similarity of the posterior to the prior (the KL-divergence term), and the bounds hold with a probability greater than \(1-\varepsilon\). Various forms of the \(\delta\) bound can be found in the literature, with varying degrees of tightness. For classification, we rely on the McAllester (McAllester, 1999b) and Catoni (Catoni, 2007) bounds. 3 Footnote 3: This work focuses on classification tasks as PAC-Bayes framework is usually for bounded losses. Yet, using recent theories of PAC-Bayes, we also comment on regression in Appendix D. Since these bounds depend on the expected empirical loss, we have to iterate over the entire training data and sample from the posterior multiple times at each step in order to evaluate the bound once. This makes optimization intractable. Using the error function as a loss, we propose to compute an approximate upper bound by only using quantities that were already computed during the LA, _i.e_. the Fisher matrix \(\operatorname{diag}(\{\mathbf{F}_{l}\}_{l\in[L]})\) and the network parameters \(\tilde{\mathbf{\theta}}\): \[\mathbb{E}_{\mathbf{\theta}\sim\rho}\left[\frac{1}{N}\sum_{i=1}^{N} \mathbbm{1}[\operatorname*{arg\,max}_{\mathbf{y}^{\prime}}p(\mathbf{y}^{\prime}| \mathbf{x}_{i},f_{\mathbf{\theta}})\neq\mathbf{y}_{i}]\right]\] \[\leq\mathbb{E}_{\mathbf{\theta}\sim\rho}\left[\frac{1}{N}\sum_{i=1}^ {N}-\frac{\ln p(\mathbf{y}_{i}|\mathbf{x}_{i},f_{\mathbf{\theta}})}{\ln 2}\right] \tag{10}\] \[\approx\frac{-\ln p(\mathcal{D}|f_{\tilde{\mathbf{\theta}}})+\frac{1 }{2}\sum_{l\in[L]}\tau_{l}\operatorname{tr}\Big{(}\mathbf{F}_{l}(\beta_{l} \mathbf{F}_{l}+\alpha_{l}\tilde{\mathbf{F}}_{l})^{-1}\Big{)}}{N\ln 2},\] where \(\tilde{\mathbf{F}}_{l}\) is from the precision matrix of the prior. Here, we first use a second-order Taylor approximation of around \(\tilde{\mathbf{\theta}}\). Furthermore, the expectation can be converted to a trace by using the cyclic property of the trace together with the fact that the posterior is a multivariate Gaussian. The negative data log-likelihood of the optimal parameters can be computed jointly with the Fisher matrix during the LA. We denote this approximation as \(\operatorname{aer}(\alpha,\beta,\tau)\). On the other hand, the KL-divergence can also be computed in closed form for our prior-posterior pair, since both distributions are multivariate Gaussians. Thus, we can plug both terms into the McAllester bound (Guedj, 2019) to obtain the objective \[ma(\alpha,\beta,\tau)=\operatorname{aer}(\alpha,\beta,\tau)+ \sqrt{\frac{\operatorname{kl}(\alpha,\beta,\tau)+\ln\frac{2\sqrt{N}}{\varepsilon }}{2N}} \tag{11}\] where we write \(\operatorname{kl}(\alpha,\beta,\tau)=\mathbb{KL}(\rho\|\pi)\) for the KL-divergence to emphasize the dependence on the scales. Similarly for the Catoni bound (Catoni, 2007), we obtain \[ca(\alpha,\beta,\tau)=\inf_{c>0}\frac{1-\exp(-c\operatorname{aer}(\alpha, \beta,\tau)-\frac{\operatorname{kl}(\alpha,\beta,\tau)-\ln\varepsilon}{N})}{1 -\exp(-c)}. \tag{12}\] Overall, these objectives can be evaluated and minimized without using any data samples. As opposed to the cross-validated marginal likelihood or other forms of grid searching, we (a) obtain generalization bounds and analysis, (b) do not need a separate validation set, (c) can find multiple hyperparameters, i.e., scale better with the dimensionality of the considered hyperparameters due to the differentiability of the proposed objectives, and (d) the complexity of the optimization is independent of the data set size and the complexity of the forward pass. The last point is because we only use the precomputed terms from the LA. A full derivation of our objective is given in Appendix C. ### Bayesian Progressive Neural Networks Having the essentials of learning BNN priors with generalization guarantees, we now present our extension to continual learning, which shows the versatility of our prior learning method. Here, we use so-called Progressive Neural Networks (PNNs) (Rusu et al., 2016), where a new neural network (column) is added for each new incoming task, and features from previous columns are also added for positive transfer between each task. Thus, PNNs are immune to catastrophic forgetting at the cost of an increase in memory, while being also applicable in transfer learning more generally (Wang et al., 2017; Rusu et al., 2017). As such, we extend the set-up in Section 2.2 by sequentially considering T tasks: \(\mathfrak{T}_{1},\ldots,\mathfrak{T}_{T}\). Moreover, to keep the generality of our method, an additional task \(\mathfrak{T}_{0}\) is defined for the priors. The idea behind our Bayesian re-interpretation of PNNs, dubbed as BPNNs for Bayesian PNNs, is as follows. First, the BNN posteriors are learned at task \(\mathfrak{T}_{0}\) (depicted in Figure 1). Then, for an incoming sequence of tasks, the BNN priors are specified from the BNN posteriors from \(\mathfrak{T}_{0}\). The proposed methods of the sums-of-Kronecker-products and PAC-Bayes bounds are used. For the lateral connections, the BNN posterior from which the lateral connection originates is used. This ensures that the weight distribution from the prior already produces reasonable features given the activations from the previous column. Altogether, the resulting architecture accounts for model uncertainty, generalization, Figure 1: Illustration of our continual learning architecture. BPNNs use the empirically learned prior from task \(\mathfrak{T}_{0}\) (blue) in all columns. The prior for the lateral connections is the posterior from the lateral connection (orange and green). Best viewed in color. and resiliency to catastrophic forgetting. All these properties are desirable to have within one unified framework. We note that BPNN is in line with our PAC-Bayes theory, i.e., we increase the complexity without increasing the PAC-Bayes bounds. This is because we can reuse features from previous columns even though they do not contribute to the bounds due to their a-priori fixed weight distribution. In Appendices B and C, we provide more details such as its full derivations, and its training and testing procedures. ## 3 Related Work There are different work streams related to this paper. The primary area is on BNN priors while we also contribute to Bayesian continual learning and PAC-Bayes theory. **Bayesian Neural Networks Priors** A prior specification is a prerequisite in Bayesian modeling. However, for neural network parameters, the choice of the prior is generally unknown. So far, uninformative priors such as isotropic Gaussian have been the de-facto-standard for BNNs (Fortuin, 2022). Such uninformative priors may cause undesirable effects such as cold posteriors and worse predictive performance than standard neural networks (Wenzel et al., 2020; Fortuin et al., 2021). To this end, recent research efforts have focused on exploiting function-space (Sun et al., 2019), sparsity-inducing weight-space (Carvalho et al., 2009; Ghosh et al., 2018), structured (Louizos and Welling Max, 2016), and learning-based priors (Immer et al., 2021; Fortuin et al., 2021; Wu et al., 2019). Amongst these, we build upon learning-based priors. Learning-based priors can be an alternative to uninformative prior when no useful prior knowledge is available to encode, or when there exists relevant data and tasks to learn from (Fortuin, 2022). The idea of learning a prior distribution on a similar task is certainly not new. In this domain, Bayesian meta-learning (Thrun and Pratt, 1998) and their modern extensions (Rothfuss et al., 2021; Finn et al., 2018) can be viewed as another form of learning the prior from data, although their focus is typically not on advancing BNNs. Empirical prior learning is closely related to our work (Robbins, 1992). For BNNs, Fortuin et al. (2021) learns the empirical weight distributions during stochastic gradient descent. Wu et al. (2019) used a moment-matching approach, while Immer et al. (2021) exploited the so-called Laplace-Generalized-Gauss-Newton method. In (Krishnan et al., 2020), the mean of a Gaussian prior distribution is learned from a relevant data-set. The concurrent approaches of Shwartz-Ziv et al. (2022); Tran et al. (2022) share a similar spirit of learning expressive priors from large-scale data-set and architectures. The former utilizes so-called the SWAG (Maddox et al., 2019) framework with an inspiring idea of combining self-supervised learning, while the latter Figure 2: The results of the ablation studies. The results show that the combination of our approaches can lead to non-vacuous bounds (a) and that the learned prior is more data-efficient (b) and needs less temperature scaling (c) than isotropic priors. builds upon Frequentist batch ensembles (Wen et al., 2019). All these works show the strong relevance of learning-based priors for the current BNNs. Inspired by the aforementioned works, our main idea is to learn scalable and structured posterior as expressive informative priors, like Bayesian foundation models from broader data and models. **Bayesian Continual Learning** Continual learning (Thrun Mitchell, 1995) methods can be broadly divided into replay-based, regularization-based, and parameter-isolation methods (De Lange et al., 2022). We build on parameter-isolation methods, e.g. Rusu et al. (2016), where different model parameters are dedicated to new tasks. Within this branch, Bayesian methods have been investigated (Ebrahimi et al., 2020; Ardywibowo et al., 2022; Kumar et al., 2021), which could benefit from our work on advancing the BNN priors. Rudner et al. (2022) shares a similar spirit of bringing the state-of-the-art BNN priors to Bayesian continual learning by relying on the function space priors (Sun et al., 2019). On the other hand, using learning-based expressive priors, we design a single unified framework of continual learning for generalization, uncertainty-awareness, and resiliency to catastrophic forgetting. **Generalization Theory** In supervised learning, we can obtain models with a bound on the true expected loss from its true data-generating process. Typical early works involved Vapnik-Chervonenkis theory and Rademacher complexity (Vapnik and Chervonenkis, 1968; Shalev-Shwartz and Ben-David, 2014). However, for high-dimensional models like neural networks, these methods often provide vacuous bounds. In recent years, PAC-Bayes theory (McAllester, 1999; Germain et al., 2016) has become an alternative method with wide applications. The seminar paper of (Germain et al., 2016) showed the connection to approximate Bayesian inference. Rothfuss et al. (2021b, a) devise compelling meta-learning priors for BNNs with generalization guarantees. These works form our inspiration to explore PAC-Bayes theory for learning-based BNN priors. We note that our goal is not to advance PAC-Bayes theory, but to investigate a method for scaling the BNN priors with an approximate differentiable objective for generalization. ## 4 Results The goal of the experiments is to investigate whether our approach provides generalization and calibrated uncertainty estimates. To this end, in addition to ablation studies on the presented algorithm, we show its utility for continual learning and uncertainty estimation. Implementation details are presented in Appendix E. The code is released at [https://github.com/DLR-RM/BPNN](https://github.com/DLR-RM/BPNN). ### Ablation Studies Our method is to improve generalization in the LA and also to provide an informative prior for the posterior inference. Therefore, in the ablation studies, we want to investigate the impact of each of our methods on the generalization bounds. Moreover, we want to study the learned prior in the small-data regime and see if it can mitigate the cold posterior effect, _i.e_. phenomena in BNNs where the performance improves by cooling the posterior with a temperature of less than one (Wenzel et al., 2020). This effect highlights the discrepancy of current BNNs, where no posterior tempering should be theoretically needed. For this, we use a LeNet-5 architecture (LeCun et al., 1989), learn the prior on MNIST (LeCun et al., 1998) and compute the posterior on NotMNIST (Bulatov, 2011). In our experiments, we compare the performance of our learned prior against an isotropic Gaussian prior with multiple weight decays, either with a mean zero or using the pre-trained model as the mean. Figure 3: The results of the ablation studies. The results show the accuracy of the proposed sums-of-Kronecker product computations. In Table 2a, one can see the contribution of each method to the final generalization bounds. For this, we report the mean and standard deviation using \(5\) different seeds. We observe that learning the prior improves the generalization bounds, as the posterior can reuse some of the pre-trained weights. The curvature further controls the flexibility of each parameter, leading to a smaller KL-divergence while still providing a small error rate. In addition, we show that scaling the curvature with our approximate bounds reduces the bounds. In particular, the generalization bounds are also better than a thorough grid search. Frequentist projection further leads to a non-vacuous bound of \(0.885\). In the small data regime, we train our method on a random subset of NotMNIST, _i.e_., we vary the number of available samples per class. Figure 2b shows that the learned prior requires a magnitude fewer data to achieve similar accuracy compared to isotropic priors. In Appendix F.2, we further evaluate the impact of using different temperature scalings and weight decays in this experiment. We observe larger improvements when the model is more probabilistic, _i.e_. when the temperature scaling is large, and when the weight decay is small and thus the learned prior is more dominant. Finally, following Wenzel et al. (2020), we examine the cold posterior effect using the learned prior in Figure 2c. Although the optimal value for the temperature scaling is less than one, the temperature scaling can be closer to one compared to the isotropic priors. This suggests that the cold posterior effect is reduced by using a learned prior. Additionally, we further validate the proposed sums-of-Kronecker product computations (see Figure 3). In Appendix F, further experimental results are provided, including qualitative analysis of our tractable approximate bound used to optimize the curvature scales (Appendix F.1). Furthermore, results for a larger cold posterior experiment using ResNet-50 (He et al., 2016), ImageNet-1K (Deng et al., 2009), and CIFAR-10 (Krizhevsky, 2009) are presented in Appendix F.3. Here, the learned prior improves the accuracy but does not reduce the cold posterior effect for all evaluated weight decays. This suggests the use-case of our method. Overall, our results demonstrate the effectiveness of our method in improving the generalization bounds. Furthermore, we show that the learned prior is particularly useful for BNNs when little data is available. ### Generalization in Bayesian Continual Learning Another advantage of our prior is its connection to continual learning. In the following experiments, we, therefore, evaluate our method for continual learning tasks. To do so, we closely follow the setup of Denninger and Triebel (2018), who introduces a practical robotics scenario. This allows us to also obtain meaningful results for practitioners. We do not use the typical MNIST setup here because we also want to test the effectiveness of the expressive prior from ImageNet (Deng et al., 2009). Each continual learning task consists of recognizing the specific object instances of the Washington RGB-D data-set (WRGBD) (Lai et al., 2011), while only a subset of all classes is available at a given time. We neglect the depth information and split the data similar to Denninger and Triebel (2018). The prior is learned with the ImageNet-1K (Deng et al., 2009) and the ResNet-50 (He et al., 2016) is used. We specify a total of four lateral connections, each at the downsampling \(1\times 1\) convolution of the first "bottleneck" building block of the ResNet layers. The baselines are PNNs with several weight decays and using MC dropout (Gal and Ghahramani, 2016). Moreover, we compare to both isotropic priors as in the ablations. Table 1 shows the mean and the standard deviation of the accuracy for each task of the continual learning experiment for \(5\) different random seeds. We report the mean and the standard deviation of two independent runs. Overall, in our experiments, the accuracy averaged over all tasks is improved by \(0.6\) percent points compared to the second best approach PNN with weight decay \(10^{-5}\). In addition, the increase in accuracy is \(1.3\) percent points greater compared to an isotropic prior, and \(2.1\) percent point greater when using zero as the prior mean. Therefore, these experimental results illustrate that with our idea of expressive posterior as BNN prior, we can improve the generalization on the test set for practical tasks of robotic continual learning. ### Few-Shot Generalization and Uncertainty Finally, we consider the task of few-shot learning. Our key hypothesis is that the choice of prior matters more in the small data regime, _i.e_., the prior may dominate over the likelihood term. To this end, closely following Tran et al. (2022), we use a few-shot learning set-up across several data-sets, \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline & Other & Bananaa & Coffee Mug & Stapler & Flashlight & Apple & Average \\ \hline PNN (weight decay \(10^{-3}\)) & \(95.7\pm 0.4\) & \(98.5\pm 2.3\) & \(\mathbf{100.0\pm 0.0}\) & \(91.7\pm 1.0\) & \(93.8\pm 9.1\) & \(93.3\pm 4.7\) & \(95.5\pm 2.9\) \\ PNN (weight decay \(10^{-5}\)) & \(\mathbf{96.7\pm 0.3}\) & \(99.0\pm 1.2\) & \(\mathbf{100.0\pm 0.0}\) & \(90.7\pm 2.3\) & \(99.7\pm 0.4\) & \(94.1\pm 3.2\) & \(96.7\pm 1.2\) \\ MC Dropout & \(96.3\pm 0.1\) & \(\mathbf{90.3\pm 0.9}\) & \(\mathbf{100.0\pm 0.0}\) & \(92.7\pm 0.8\) & \(99.8\pm 0.4\) & \(90.4\pm 5.1\) & \(96.4\pm 1.2\) \\ zero mean \& isotropic & \(96.3\pm 0.3\) & \(95.5\pm 4.2\) & \(\mathbf{100.0\pm 0.1}\) & \(91.9\pm 1.7\) & \(\mathbf{100.0\pm 0.1}\) & \(87.7\pm 7.8\) & \(95.2\pm 2.4\) \\ isotropic & \(96.1\pm 0.3\) & \(98.7\pm 1.0\) & \(\mathbf{100.0\pm 0.0}\) & \(93.1\pm 0.6\) & \(\mathbf{100.0\pm 0.0}\) & \(87.8\pm 6.6\) & \(96.0\pm 1.4\) \\ learned & \(96.2\pm 0.2\) & \(98.4\pm 1.6\) & \(\mathbf{100.0\pm 0.0}\) & \(\mathbf{93.9\pm 0.9}\) & \(\mathbf{100.0\pm 0.0}\) & \(\mathbf{95.1\pm 4.7}\) & \(\mathbf{97.3\pm 1.2}\) \\ \hline \hline \end{tabular} \end{table} Table 1: Continual learning experiment. BPNN with a learned prior (our method) improves the averaged accuracy over all tasks compared to using an isotropic prior around zero or around a learned mean. Our method also improves over PNN with and without MC Dropout. Following Denninger and Triebel (2018), each column represents incoming continual learning tasks, where we receive new objects. namely CIFAR-100, UC Merced, Caltech 101, Oxford-IIIT Pets, DTD, Colorectal Histology, Caltech-UCSD Birds 200, and Cars196. CIFAR-10 is used as an out-of-distribution (OOD) data-set 4. Standardized metrics such as accuracy, ECE, AUROC, and OOD AUROC are examined. The implementations are based on uncertainty baselines (Nado et al., 2021). We use ResNet-50 for the architecture. Footnote 4: Unlike Tran et al. (2022), we did not use few-shot learning on ImageNet since we obtain our prior using the entire training set. For the baselines, we choose MC dropout (Gal and Ghahramani, 2016) (MCD) and additionally include deep ensemble (Lakshminarayanan et al., 2017) (Ens) and a standard network (NN). These uncertainty estimation techniques are often used methods in practice (Gustafsson et al., 2020). We do not use the plex (Tran et al., 2022) due to the lack of industry-level resources to comparably train our Bayesian prior. To increase their competitiveness, we uniformly searched over ten weight decays in the range from \(10^{-1}\) to \(10^{-10}\). We also tried fixed representation or only last-layer fine-tuning. Additionally, we add LA which represents the use of isotropic prior. To facilitate the fair comparison between isotropic and learned prior, we carefully searched the following combinations: (a) curvature scaling without PAC-Bayes, with McAllester and Cantoni, (b) ten temperature scaling ranging from \(10^{-10}\) to \(10^{-28}\), and (c) three weight decays \(10^{-6}\) to \(10^{-8}\) and \(10^{-10}\). For all hyperparameters, we selected the best model using validation accuracy. The results are reported in Figure 4, where we averaged across eight data-sets, closely following Tran et al. (2022). The results per data-set are in Appendix F.4 whereas in Appendix F.1, we also analyze the influence of these weight decays and temperature scales with varying numbers of available samples per class against accuracy. For shots up to 25 per class, we observe that our method often outperforms the baselines in terms of generalization and uncertainty calibration metrics. In particular, in the experiments, our learned prior from ImageNet significantly outperforms the isotropic prior within directly comparable set-ups. We interpret that the prior learning method is effective in this small data regime. This motivates the key idea of expressive posteriors as informative priors for BNNs. Moreover, for isotropic and learned prior, the McAllester bound often resulted in the best model. This also motivates the use of explicit curvature scaling for the generalization bounds. ## 5 Conclusion This paper presents a prior learning method for BNNs. Our prior can be learned from large-scale data-set and architecture, resulting in expressive probabilistic representations with generalization guarantees. Empirically, we demonstrated how we mitigate cold posterior effects and further obtain non-vacuous generalization bound as low as 0.885 in neural networks using LA. In our benchmark experiments within continual and few-shot learning tasks, we further showed advancements over the prior arts. Importantly, we find that the use-case of our prior learning method is more within the small data regime, e.g., when prior may dominate over the likelihood term. Finally, one of the fundamental assumptions of prior learning methods is on the existence of relevant data and tasks to learn the prior from. Moreover, for a valid PAC-Bayes analysis, the data-sets for individual tasks should not share common examples. In the future, we would like to see follow-ups that address this limitation, by either (a) learning prior in larger scale data-set and architectures like foundational models, or (b) combining self-supervised pre-training to quickly fine-tune the prior for the domain of the relevant task (Bommasani et al., 2021). Another direction is to obtain tighter generalization bounds by adapting clever tricks such as optimizing the entire covariance instead of individual scales with our objectives and using a subset of the training data to improve the prior (Perez-Ortiz et al., 2021). **Acknowledgments** The authors would like to thank the anonymous reviewers and area chairs for valuable feedback. This work is also supported by the Helmholtz Association's Initiative and Networking Fund (INF) under the Helmholtz AI platform grant agreement (ID ZT-I-PF-5-1). Figure 4: Few-shot learning experiments. Results are averaged over eight data-sets. Higher is better for accuracy and AUC measures, while lower is better for ECE measures. The results show the benefits of our method in uncertainty calibration and generalization.
2308.11978
Will More Expressive Graph Neural Networks do Better on Generative Tasks?
Graph generation poses a significant challenge as it involves predicting a complete graph with multiple nodes and edges based on simply a given label. This task also carries fundamental importance to numerous real-world applications, including de-novo drug and molecular design. In recent years, several successful methods have emerged in the field of graph generation. However, these approaches suffer from two significant shortcomings: (1) the underlying Graph Neural Network (GNN) architectures used in these methods are often underexplored; and (2) these methods are often evaluated on only a limited number of metrics. To fill this gap, we investigate the expressiveness of GNNs under the context of the molecular graph generation task, by replacing the underlying GNNs of graph generative models with more expressive GNNs. Specifically, we analyse the performance of six GNNs in two different generative frameworks -- autoregressive generation models, such as GCPN and GraphAF, and one-shot generation models, such as GraphEBM -- on six different molecular generative objectives on the ZINC-250k dataset. Through our extensive experiments, we demonstrate that advanced GNNs can indeed improve the performance of GCPN, GraphAF, and GraphEBM on molecular generation tasks, but GNN expressiveness is not a necessary condition for a good GNN-based generative model. Moreover, we show that GCPN and GraphAF with advanced GNNs can achieve state-of-the-art results across 17 other non-GNN-based graph generative approaches, such as variational autoencoders and Bayesian optimisation models, on the proposed molecular generative objectives (DRD2, Median1, Median2), which are important metrics for de-novo molecular design.
Xiandong Zou, Xiangyu Zhao, Pietro Liò, Yiren Zhao
2023-08-23T07:57:45Z
http://arxiv.org/abs/2308.11978v4
# Will More Expressive Graph Neural Networks do Better on Generative Tasks? ###### Abstract Graph generation poses a significant challenge as it involves predicting a complete graph with multiple nodes and edges based on simply a given label. This task also carries fundamental importance to numerous real-world applications, including de-novo drug and molecular design. In recent years, several successful methods have emerged in the field of graph generation. However, these approaches suffer from two significant shortcomings: (1) the underlying Graph Neural Network (GNN) architectures used in these methods are often underexplored; and (2) these methods are often evaluated on only a limited number of metrics. To fill this gap, we investigate the expressiveness of GNNs under the context of the molecular graph generation task, by replacing the underlying GNNs of graph generative models with more expressive GNNs. Specifically, we analyse the performance of six GNNs in two different generative frameworks (GCPN and GraphAF), on six different molecular generative objectives on the ZINC-250k dataset. Through our extensive experiments, we demonstrate that advanced GNNs can indeed improve the performance of GCPN and GraphAF on molecular generation tasks, but GNN expressiveness is not a necessary condition for a good GNN-based generative model. Moreover, we show that GCPN and GraphAF with advanced GNNs can achieve state-of-the-art results across 17 other non-GNN-based graph generative approaches, such as variational autoencoders and Bayesian optimisation models, on the proposed molecular generative objectives (DRD2, Median1, Median2), which are important metrics for de-novo molecular design. ## 1 Introduction Graph generation has always been viewed as a challenging task as it involves the prediction of a complete graph comprising multiple nodes and edges based on a given label. This task, however, holds paramount importance in a wide array of real-world applications, such as de-novo molecule design [1]. In de-novo molecule generation, the chemical space is discrete by nature, and the entire search space is huge, which is estimated to be between \(10^{23}\) and \(10^{60}\)[2]. The generation of novel and valid molecular graphs with desired physical, chemical and biological property objectives should also be considered, these together with the large search space makes it a difficult task, since _these property objectives are highly complex and non-differentiable_[3]. Recently, there has been significant progress in molecular graph generation with graph neural network (GNN)-based deep generative models, such as Graph Convolutional Policy Network (GCPN) [3] and Flow-based Autoregressive Model (GraphAF) [4], and they both use the Relational Graph Convolutional Network (R-GCN) [5] as their inner graph representation model. Meanwhile, several researchers have focused on improving GNN expressiveness by introducing architectural changes [6; 7; 8], leading to the discovery of diverse forms of GNNs that excel in graph classification and regression tasks. Naturally, it is worth considering _will these more expressive GNNs help in molecular graph generation and will they perform better than the de-facto network used in GCPN and GraphAF?_ In addition, nowadays, there are many metrics used in de-novo molecule design (_eg. molecule's bioactivity against its corresponding disease targets: DRD2 and JNK3_) [9]. However, GCPN and GraphAF only consider two molecular generative objectives related to drug design: the Penalized logP and the QED. This brings two major drawbacks. First, there is a lack of consideration of a broader set of generation metrics beyond those related to drug design. Secondly, both Penalized logP and the QED are incapable of effectively distinguishing between various generation models, rendering them disabled for such purpose [9]. In this work, we replace R-GCN in GCPN and GraphAF with more expressive GNNs. Then, we evaluate our proposed models: GCPN variants and GraphAF variants on a wide array of molecular generative objectives (e.g. DRD2, Median1, Median2), which are important metrics for de-novo molecular design, to derive more statistically significant results. We make the following contributions: * Although GNN expressiveness defined by the Weisfeiler-Lehman (1-WL) graph isomorphism test works well on graph classification and regression tasks, it is not a necessary condition for a good GNN-based generative model. We observe empirically that the expressiveness of GNNs does not correlate well with their performance on GNN-based generative models, and GNNs incorporating edge feature extraction can improve GNN-based generative models. * Although Penalised logP and QED are widely used in evaluating goal-directed graph generative models, they are not effective metrics to differentiate generative models. Other metrics, such as DRD2, Median1 and Median2, can better evaluate the ability of a graph generative model. * Our findings reveal that while there is no direct correlation between expressiveness and performance in graph generation, substituting the inner GNNs of GCPN and GraphAF with advanced GNNs like GearNet yields better performance (e.g. \(102.51\%\) better in DRD2 and \(48.96\%\) better in Median2). By doing so, these models surpass or reach comparable performance to state-of-the-art non-graph-based generative methods for de-novo molecule generation. ## 2 Related Work A variety of deep generative models have been proposed for molecular graph generation recently [3; 4; 10; 11; 12; 13; 14; 15; 16; 17]. In this paper, we confine our scope to single-objective approaches for molecular generation. Specifically, our focus centres on the generation of organic molecules that possess a desired scalar metric, encompassing key physical, chemical, and biological properties. ### GNN-based Graph Generative Models Recently, there has been significant progress in molecular graph generation with GNN-based deep generative models, such as GCPN [3] and GraphAF [4]. Both of them use R-GCN [5], the state-of-the-art GNN at that time, as their inner graph representation model. Nevertheless, in recent years, the landscape has witnessed the emergence of increasingly expressive GNNs such as GATv2 [6], GSN [7] and GearNet [8]. These advanced GNN models have showcased superior performance in various tasks, including graph classification and regression, surpassing the capabilities of R-GCN. Furthermore, the methods GCPN and GraphAF only evaluate their performance in goal-directed molecule generation tasks using two commonly employed metrics in drug design: quantitative estimate of drug-likeness score (QED) and penalised octanol-water partition coefficient (Penalized logP). However, it is worth noting that many advanced graph generative approaches, as discussed in Section 2.2, can achieve state-of-the-art results on benchmarks for QED and Penalized logP [9; 15]. _QED is likely to have a global maximum of 0.948 and even random sampling could reach that value. Penalized logP is unbounded and the relationship between Penalized logP values and molecular structures is fairly simple: adding carbons monotonically increases the estimated Penalized logP value [3; 9; 18]._ This is presented in Figure 3 in Appendix E. Consequently, one could argue that these scores have reached a saturation point, making them less meaningful as evaluation metrics. Only using these two metrics relevant to drug design on goal-directed graph generation tasks to assess the graph generative models is not convincing enough and cannot provide insights for distinguishing different algorithms' de-novo molecule generation ability [9]. ### Non-GNN-based Graph Generative Models There are other non-GNN-based graph generative models. Genetic algorithms (GA) are generation approaches by relying on biologically inspired operators such as mutation, crossover and selection. Bayesian Optimization (BO) [19] is an approach that uses a sequential optimization technique that leverages probabilistic models to search for the optimal solution. Variational Autoencoders (VAEs) [20] is a type of generative model in machine learning that combines elements of both autoencoders and probabilistic latent variable models to learn and generate data by mapping it to a latent space with continuous distributions. Monte-Carlo Tree Search (MCTS) constructs a search tree by iteratively selecting actions, simulating possible outcomes, and propagating the results to inform future decisions, ultimately aiming to find the optimal solution. Hill Climbing (HC) is an iterative optimization algorithm that starts with an arbitrary solution to a problem, and then attempts to find a better solution by making an incremental change to the solution. Reinforcement Learning (RL) learns how intelligent agents take actions in an environment to maximize the cumulative reward by transitioning through different states. Details about non-GNN-based graph generative models we used in Section 4 can be found in Appendix A. ## 3 Method In this section, we provide the theoretical background for graph generative models. A GNN-based graph generative model consists of a GNN model and a graph generative framework. The GNN learns the hidden representations of a graph, such as the node feature and the graph feature. The goal of the graph generation framework is to generate realistic molecular graph structures based on a given generative objective. The detail of GCPN is presented in Figure 1, and an illustration of GraphAF is displayed in Figure 2 in Appendix B. ### Preliminaries Let \(G=(V,\mathcal{E})\) define a graph, where \(V\) denotes the set of nodes, and \(\mathcal{E}\subseteq V\times V\) denotes the set of edges. A relational graph can be expressed as \(G=(V,\mathcal{E},\mathcal{R})\) where \(\mathcal{R}\) denotes the set of edge relations or edge types. For example, \((i,j,r)\) means the edge from node \(i\) to node \(j\) with edge type \(r\). A molecular graph can be represented by a tuple of features \((\mathbf{A},\mathbf{H},\mathbf{E},\mathbf{R})\), where * \(\mathbf{A}\in\mathbb{R}^{|V|\times|V|}\) is the adjacency matrix, with each entry \(a_{ij}\) representing an edge (if any) between nodes \(i\) and \(j\); note that this is different from the conventional \(0,1^{|V|\times|V|}\) adjacency matrix format, since there are different types of bonds (_i.e._, single, double, triple, aromatic). * \(\mathbf{H}\in\mathbb{R}^{|V|\times d}\) is the feature matrix, \(\mathbf{h}_{i}\in\mathbb{R}^{d}\) is the \(d\)-dimensional features of node \(i\). * \(\mathbf{E}\in\mathbb{R}^{|\mathcal{E}|\times d_{e}}\) is the edge feature matrix, \(\mathbf{e}_{ij}\in\mathbb{R}^{d_{e}}\) is the \(d_{e}\)-dimensional features of edge \((i,j)\). * \(\mathbf{R}\in\mathbb{N}^{|\mathcal{E}|}\) is a vector containing the edge types of each edge \((i,j)\in\mathcal{E}\) and \(r_{(i,j)}\in\mathcal{R}\). Figure 1: An overview of the GCPN model: this is an example of iterative graph generation from an intermediate graph \(G_{t}\) to an intermediate graph \(G_{t+1}\). Part 1 is the illustration of the graph representation learning process based on a GNN. Part 2 is the illustration of the graph generative procedure based on a reinforcement learning (RL) agent. New nodes or edges are marked in red. The degree matrix \(\mathbf{D}\in\mathbb{R}^{|V|\times|V|}\) of a graph \(G=(V,\mathcal{E})\) is a diagonal matrix with each diagonal entry \(d_{ii}=\text{deg}(v_{i})\), where the \(\text{deg}(v_{i})\) of a vertex counts the number of times an edge terminates at that vertex in an undirected graph. #### 3.1.1 Subgraph & Isomorphism A graph \(G^{\prime}=(V^{\prime},\mathcal{E}^{\prime})\) is a _subgraph_ of a graph \(G=(V,\mathcal{E})\) (denoted \(G^{\prime}\subseteq G\)) if and only if \(V^{\prime}\subseteq V\) and \(\mathcal{E}^{\prime}\subseteq\mathcal{E}\). Two graphs \(G=(V,\mathcal{E})\) and \(G^{\prime}=(V^{\prime},\mathcal{E}^{\prime})\) are _isomorphic_ (denoted \(G\cong G^{\prime}\)) if and only if there exists an adjacency-preserving bijective mapping \(f:V\to V^{\prime}\), i.e., \[\forall i,j\in V,(i,j)\in\mathcal{E}\Longleftrightarrow(f(i),f(j))\in \mathcal{E}^{\prime} \tag{1}\] An _automorphism_ of a graph \(G=(V,\mathcal{E})\) is an isomorphism that maps \(G\) onto itself. ### Graph Neural Networks All the Graph Neural Networks (GNNs) investigated in this paper can be abstracted as Message Passing Neural Networks (MPNNs). A general MPNN operation iteratively updates the node features \(\mathbf{h}_{i}^{(l)}\in\mathbb{R}^{d}\) from layer \(l\) to layer \(l+1\) via propagating messages through neighbouring nodes \(j\in\mathcal{N}_{i}\), which can be formalised by the following equation: \[\mathbf{h}_{i}^{(l+1)}=\text{UPDATE}\left(\mathbf{h}_{i}^{(l)},\bigoplus_{j \in\mathcal{N}_{i}}\text{MESSAGE}\left(\mathbf{h}_{i}^{(l)},\mathbf{h}_{j}^{(l )},\mathbf{e}_{ij}\right)\right) \tag{2}\] where MESSAGE and UPDATE are learnable functions, such as Multi-Layer Perceptrons (MLPs), \(\mathcal{N}_{i}=\{j|(i,j)\in\mathcal{E}\}\) is the (1-hop) neighbourhood of node \(i\), and \(\bigoplus\) is a permutation-invariant local neighbourhood aggregation function, such as sum, mean or max. After \(k\) iterations of aggregation, node \(i\)'s representation \(\mathbf{h}_{i}^{(k)}\) can capture the structural information within its \(k\)-hop graph neighbourhood. Then, the graph embedding \(\mathbf{h}_{G}\in\mathbb{R}^{d}\) can be obtained via a READOUT function: \[\mathbf{h}_{G}=\text{READOUT}_{i\in V}\left(\mathbf{h}_{i}^{(k)}\right) \tag{3}\] which aggregates the node features to obtain the entire graph's representation \(\mathbf{h}_{G}\). Ideally, a maximally powerful GNN could distinguish different graph structures by mapping them to different representations in the embedding space. This ability to map any two different graphs to different embeddings, however, implies solving the challenging graph isomorphism problem. That is, we want isomorphic graphs to be mapped to the same representation and non-isomorphic ones to different representations. Thus, the expressiveness of a GNN is defined as the ability to distinguish non-isomorphic graphs, and can be analysed by comparing to the 1-WL graph isomorphism test, which are summarised in Appendix C. ### Graph Generative Frameworks In this paper, Graph Convolutional Policy Network (GCPN) [3] and Flow-Based Autoregressive Model (GraphAF) [4] are used as graph generative frameworks for molecular graph generation tasks. They formalize the problem of goal-directed graph generation as a sequential decision process through RL, i.e. the decisions are generated from the generation policy network. In GCPN, the iterative graph generation process is formulated as a general decision process: \(M=(S,\mathcal{A},P,R,\gamma)\), where \(S=\{s_{i}\}\) is the set of states that consists of all possible intermediate and final graphs, \(\mathcal{A}=\{a_{i}\}\) is the set of actions that describe the modification made to the current graph at each time step determined by the Graph Convolutional Policy Network (a group of MLPs predicting a distribution of actions), \(P\) is the Markov transition dynamics that specifies the possible outcomes of carrying out an action, \(p(s_{t+1}|s_{t},\cdots,s_{0},a_{t})=p(s_{t+1}|s_{t},a_{t})\). \(R(s_{t})\) is a reward function that specifies the reward after reaching state \(s_{t}\), and \(\gamma\) is the discount factor. GCPN takes the intermediate graph \(G_{t}\) and the collection of proposed scaffold subgraphs \(C\) as inputs, and outputs the action \(a_{t}\), which predicts a new link to be added. GraphAF defines an invertible transformation from a base distribution (e.g. multivariate Gaussian) to a molecular graph structure \(G=(V,\mathcal{E})\) as the generation policy network. Starting from an empty graph \(G_{0}\), in each step a new node \(v_{i}\) is generated based on the current sub-graph structure \(G_{i}\), \(i.e.\), \(p(v_{i}|G_{i})\) by the policy network. Next, the edges between this new node and existing nodes are sequentially generated according to the current graph structure, i.e., \(p(\mathcal{E}_{ij}|G_{i},v_{i},\mathcal{E}_{i,1:j-1},\mathcal{E}_{1:j-1,i})\). This process is repeated until all the nodes and edges are generated. ## 4 Evaluation ### Experimental Setup Dataset.We use the ZINC-250k [21] dataset for both pre-training and fine-tuning proposed models for its pharmaceutical relevance, moderate size, and popularity. All molecules are presented in the kekulised form with hydrogen removed. ZINC-250k contains around 250,000 drug-like molecules with 9 atom types and 3 edge types, and with a maximum graph size of 38 sampled from the ZINC database [21]. The molecules in ZINC are readily synthesisable molecules: _It contains over 120 million purchasable "drug-like" compounds--effectively all organic molecules that are for sale--a quarter of which are available for immediate delivery._[21]. Other datasets, such as QM9 [22], which is a subset of GDB9 [23], contain, at least to some degree, virtual molecules that are likely to be synthesisable but have not been made yet, including many molecules with complex annulated ring systems [15]. In addition, the original works of GCPN, GraphAF and the benchmark [9] we used to compare graph generative models have also been trained on ZINC-250k. Thus, ZINC-250k is well-suited for models to learn representations of drug-like and synthesisable molecules in a de-novo molecule generation task. Implementation details.We use the open-source platform TorchDrug [24] in dataset preparation and graph generative models training. Advanced GNNs are implemented in PyTorch [25] in the MPNN framework aligned with TorchDrug [24]. The basic architectures of GCPN and GraphAF are implemented in TorchDrug. Note that the original GraphAF cannot allow GNN module to aggregate edge features in the message-passing mechanism, since the intermediate molecular graph generated by the autoregressive flow doesn't contain edge features. Therefore, we propose an improved version of GraphAF considering edge features, named GraphAF+e. To conduct a fairly analogous evaluation on GCPN, we considered GCPN without considering edge features, named GCPN-e. A detailed description of how to incorporate edge features is in Appendix D. In the experiments, we replace R-GCN in GCPN (both with and without edge features) and GraphAF (both with and without edge features) with six more expressive GNNs: GIN [26], GAT [27], GATv2 [6], PNA [28], GSN [7] and GearNet [8]. We set all GNNs in the experiments to have 3 hidden layers with batch normalisation [29] and ReLU [30] activation applied after each layer. We find little improvement when further adding GCN layers. Each GNN uses a 1-layer MLP to transform the edge features in the graph to a hidden embedding and concatenates with the node features for message passing. In addition, they use summation as the READOUT function for graph representations. For PNA and GSN, the MESSAGE and UPDATE functions are parameterised by single-layer perceptrons. For GSN, we set the graph substructure set to contain cycle graphs of sizes between 3 and 8 (both inclusive), which are some of the most important substructures in molecules [7]. For GAT and GATv2, we use multi-head attention with \(k=3\) after a manual grid search for attention heads. The GCPN and GraphAF models, with all different GNNs, are pre-trained on the ZINC-250k dataset for 1 epoch, as we do not observe too much performance gain from increasing pre-training epochs. They are then fine-tuned towards the target properties with RL, using the proximal policy optimisation (PPO) algorithm [31]. The models are fine-tuned for 5 epochs for all goal-directed generation tasks with early stopping if all generation results in one batch collapse to singleton molecules. We set the agent update interval for GCPN and GraphAF models to update their RL agents every 3 and 5 batches respectively, as considering the cost of computing resources. During generating process, we allow our RL agents in all models to make 20 resamplings on the intermediate generated graphs if they cannot generate chemically valid molecular graphs. The max graph size is set as 48 empirically. For GCPN, the collection of proposed scaffold subgraphs \(C\) for GCPN are sampled from non-overlapping scaffolds in the ZINC-250k dataset. For GraphAF, we define multivariate Gaussian as our base distribution and use node MLPs and edge MLPs which have two fully-connected layers equipped with tanh non-linearity to generate the nodes and edges respectively. We notice limited improvements in performance when increasing the number of MLP layers. Adam [32] is used as the optimiser for both pre-training and fine-tuning tasks. The experiments were run with a mix of NVIDIA A100 GPU with 40GB memory and NVIDIA V100 (Volta) GPU with 16GB. The total amount of training time for all GCPN and GraphAF variants under all metrics is around 1200 GPU hours. Reward temperature for each metric, the number of neurons in each hidden layer and the learning rate for fine-tuning) for each model on each task through grid search by Optuna [33] independently. All details are provided in Appendix D. Baselines.We compare our proposed models based on the original GCPN (both with and without edge features) and GraphAF (both with and without edge features) on six goal-directed molecule generation tasks: Penalised logP [34], QED [35], synthetic accessibility (SA) [36], DRD2 [1], Median1 and Median2. All generation metrics are taken from the Therapeutic Data Commons (TDC) [37]. Due the practicality of de-novo molecule design, we only consider the single generation objective for all generation tasks. Specifically, SA stands for how hard or how easy it is to synthesize a given molecule. Penalized logP is a logP score that also accounts for ring size and SA, while QED is an indicator of drug-likeness. DRD2 is derived from a support vector machine (SVM) classifier with a Gaussian kernel fitting experimental data to predict the bioactivities against their corresponding disease targets. Median1 [37] measures the average score of the molecule's Tanimoto similarity [38] to Camphor and Menthol. Median2 [37] measures the average score of the molecule's Tanimoto similarity to Tadalafil and Sildenafil. Penalized logP has an unbounded range, while QED, DRD2, Median1, Median2 and SA have a range of \([0,1]\) by definition. Higher scores in Penalized logP, QED, DRD2, Median1 and Median2 and a lower score in SA are desired. Note that all scores are calculated from empirical prediction models. We choose to use DRD2, Median1 and Median2 to evaluate generative models, since they are mature and representative generative metrics [9, 15]. In addition, some other metrics are data-missing or inappropriate and thus cannot reflect the ability of generative models properly. For example, GSK3 cannot evaluate all the generated molecules; multi-property objectives (MPO) measure the geometric means of several scores, which will be 0 if one of the scores is 0; Valsartan Samarts is implemented incorrectly way in TDC: it computes the geometric means of several scores instead of arithmetic means of several scores, which lead to incorrect results in the benchmark [9]. We compare the best GCPN variant and GraphAF variant with eight state-of-the-art approaches for molecule generation [9] on 6 generation metrics: Penalised logP, SA, DRD2, Median1, Median2 and QED. All results of baselines are taken from original papers unless stated. ### Results #### 4.2.1 Improving GNN-based Graph Generative Methods De-novo molecule design with more expressive GNNs.As we re-evaluate the Penalised logP and QED scores of the top-3 molecules found by GCPN, we note that our results turn out to be higher than the results reported in the original GCPN paper. We hypothesise this to be due to our more \begin{table} \begin{tabular}{l c c c c c c c c c} \hline \hline \multirow{2}{*}{Model} & \multicolumn{3}{c}{Penalised logP} & \multicolumn{3}{c}{QED} & \multicolumn{3}{c}{SA} \\ \cline{2-10} & **1st** & **2nd** & **3rd** & **1st** & **2nd** & **3rd** & **1st** & **2nd** & **3rd** \\ \hline ZINC & 4.52 & 4.30 & 4.23 & 0.948 & 0.948 & 0.948 & 1.0 & 1.0 & 1.0 \\ \hline R-GCN (baseline) & 7.98 & 7.85 & 7.80 & 0.948 & 0.947 & 0.946 & - & - & - \\ R-GCN (ours) & 8.67 & 8.67 & 8.67 & 0.948 & 0.948 & 0.948 & **1.0** & **1.0** & **1.0** \\ GIN & **11.19** & **11.19** & **11.19** & 0.942 & 0.926 & 0.923 & 1.2 & 1.2 & 1.2 \\ GAT & 7.70 & 7.47 & 7.44 & 0.926 & 0.911 & 0.911 & **1.0** & **1.0** & **1.0** \\ GATv2 & 8.08 & 7.48 & 7.34 & 0.945 & 0.908 & 0.907 & **1.0** & **1.0** & **1.0** \\ PNA & 8.66 & 8.61 & 8.22 & 0.833 & 0.825 & 0.754 & **1.0** & **1.0** & **1.0** \\ GSN & **11.19** & **11.19** & **11.19** & 0.804 & 0.783 & 0.783 & **1.0** & **1.0** & **1.0** \\ GearNet & **11.19** & **11.19** & **11.19** & **0.948** & **0.948** & **0.948** & **1.0** & **1.0** & **1.0** \\ \hline \hline \end{tabular} \end{table} Table 1: Comparison of the top-3 Penalised logP, QED and SA scores of the generated molecules by GCPN variants, with the top-3 property scores of molecules in the ZINC dataset for reference. extensive hyperparameter searching. In Table 1, we explore a set of simpler generation metrics based on the GCPN framework, such as Penalised logP, QED and SA, which have been widely used as objectives in previous work on GNN-based graph generative models. As summarised in Table 1, after replacing the inner R-GCN in GCPN with more expressive GNNs, we can observe a significant improvement of GCPN in Penalised logP: GCPN with GIN, GearNet and GSN can achieve the saturated \(11.19\) in Penalised logP. Moreover, with GearNet, the performance of the GCPN variants can outperform the original GCPN on all three metrics. However, we find that _these benchmarks are not suited to differentiate between different models_, since we see many GCPN variants with different GNNs achieve similar and saturated results on those metrics. In addition, these metrics are not representative enough to obtain meaningful conclusions, as discussed in Section 2.1. Therefore, _there is a need of better graph generation objectives_. De-novo molecule design with better graph generation objectives.From Table 1, we notice that both Penalised logP and SA are saturating on advanced GNNs, making them inappropriate metrics for distinguishing the capability of different GNN models, and we need better de-novo molecule generation metrics. Therefore, we introduce three more representative metrics: DRD2, Median1 and Median2, as described in Section 4.1, and report the top-3 property scores of molecules generated by each model trained on those three metrics in Table 3 (GCPN) and Table 6 (GraphAF) in Appendix B. The results show that GCPN and GraphAF with more expressive GNNs, such as GearNet, can outperform the original GCPN and GraphAF with R-GCN on all generation tasks by a significant margin. Specifically, on metrics such as DRD2 and Meidan2, GCPN and GraphAF with more expressive GNNs can vastly improve the original performance. This observation further indicates that by combining with more expressive GNNs, GCPN and GraphAF can successfully capture the distribution of desired molecules. Therefore, we suggest that DRD2, Median1, Median2 and QED are better graph generation metrics for differentiating different GNNs. \begin{table} \begin{tabular}{l c c c c c c c c c} \hline \hline \multirow{2}{*}{Model} & \multicolumn{3}{c}{DRD2} & \multicolumn{3}{c}{Median1} & \multicolumn{3}{c}{Median2} \\ \cline{2-10} & **1st** & **2nd** & **3rd** & **1st** & **2nd** & **3rd** & **1st** & **2nd** & **3rd** \\ \hline ZINC & 0.9872 & 0.9815 & 0.9773 & 0.3243 & 0.3096 & 0.3096 & 0.2913 & 0.2765 & 0.2749 \\ \hline R-GCN & 0.8315 & 0.7576 & 0.7551 & 0.3152 & 0.3152 & 0.3001 & 0.1932 & 0.1613 & 0.1592 \\ GIN & 0.2791 & 0.1980 & 0.1752 & 0.3152 & 0.3152 & 0.3152 & 0.1140 & 0.1113 & 0.1069 \\ GAT & 0.1980 & 0.1580 & 0.1580 & 0.3243 & 0.3243 & 0.3175 & 0.1196 & 0.1100 & 0.1098 \\ GATv2 & 0.2992 & 0.2992 & 0.2992 & 0.3281 & 0.3281 & 0.3281 & 0.1042 & 0.1009 & 0.0911 \\ PNA & 0.4448 & 0.4448 & 0.4448 & 0.3243 & 0.3202 & 0.3175 & 0.0911 & 0.0764 & 0.0716 \\ GSN & 0.4790 & 0.4790 & 0.4448 & 0.3175 & 0.3175 & 0.3015 & 0.0982 & 0.0978 & 0.0897 \\ GearNet & **0.9990** & **0.9705** & **0.9574** & **0.3482** & **0.3482** & **0.3482** & **0.2084** & **0.2043** & **0.2037** \\ \hline \hline \end{tabular} \end{table} Table 2: Comparison of the top-3 DRD2, Median1 and Median2 scores of the generated molecules by GCPN–e variants, with the top-3 property scores of molecules in the ZINC dataset for reference. \begin{table} \begin{tabular}{l c c c c c c c c c} \hline \hline \multirow{2}{*}{Model} & \multicolumn{3}{c}{DRD2} & \multicolumn{3}{c}{Median1} & \multicolumn{3}{c}{Median2} \\ \cline{2-10} & **1st** & **2nd** & **3rd** & **1st** & **2nd** & **3rd** & **1st** & **2nd** & **3rd** \\ \hline ZINC & 0.9872 & 0.9815 & 0.9773 & 0.3243 & 0.3096 & 0.3096 & 0.2913 & 0.2765 & 0.2749 \\ \hline R-GCN & 0.4790 & 0.4790 & 0.4790 & 0.3367 & 0.3367 & 0.3242 & 0.1921 & 0.1891 & 0.1891 \\ GIN & 0.3460 & 0.3094 & 0.3094 & 0.3243 & 0.3243 & 0.3235 & 0.1770 & 0.1766 & 0.1730 \\ GAT & 0.4946 & 0.4946 & 0.4946 & 0.3367 & 0.3367 & 0.3328 & 0.1648 & 0.1640 & 0.1637 \\ GATv2 & 0.5101 & 0.4946 & 0.4946 & 0.3367 & 0.3367 & 0.3331 & 0.1759 & 0.1720 & 0.1697 \\ PNA & 0.5828 & 0.4448 & 0.4448 & 0.3472 & 0.3254 & 0.3254 & 0.1629 & 0.1619 & 0.1605 \\ GSN & 0.5363 & 0.4946 & 0.4946 & 0.3243 & 0.3243 & 0.3235 & 0.1770 & 0.1766 & 0.1730 \\ GearNet & **0.9696** & **0.9684** & **0.9404** & **0.3367** & **0.3367** & **0.3367** & **0.2862** & **0.2794** & **0.2794** \\ \hline \hline \end{tabular} \end{table} Table 3: Comparison of the top-3 DRD2, Median1 and Median2 scores of the generated molecules by GCPN variants, with the top-3 property scores of molecules in the ZINC dataset for reference. Comparison with non-GNN-based graph generative methods.We report the top-1 DRD2, Median1, Median2 and QED scores found by all the GNN-based and non-GNN-based graph generative models in Table 4. As displayed in Table 4, original GCPN and GraphAF are not competitive among graph generative models on all the goal-directed molecule generation tasks. However, after modifying their inner GNNs with more advanced GNNs, such as GearNet, they can outperform or match state-of-the-art results across other generative approaches on the de-novo molecule generation task. Specifically, Replacing R-GCN with GearNet can achieve an average of \(50.49\%\) improvement on GCPN and an average of \(12.51\%\) improvement on GraphAF in de-novo molecule design, with the proposed generation metrics. Visualisations of the generated molecules with desired generative metrics by GCPN and GraphAF variants are presented in Figure 4 in Appendix E. In addition, we only report eight selected graph generative methods in the benchmark [9] in Table 4, and GCPN with GearNet can achieve comparable results across 17 other non-GNN-based graph generative methods on the proposed metrics, which are fully reported in Table 8 in Appendix B. #### 4.2.2 Correlation Between GNN Expressiveness and Graph Generation In the pre-training phase, the GNNs are used to predict all node types and edge types in all masked graphs in the training data. We report the graph classification results for all GNNs in Table 5. In the GCPN framework, we can see GSN perform the best with \(93.08\%\) accuracy on the graph classification task. In the GraphAF framework, we can see GearNet perform the best with the lowest edge and node average negative log likelihood: \(-0.9275\) and \(-2.8981\) respectively. Both GSN and GearNet are more expressive GNNs than R-GCN according to the 1-WL test demonstrated in Appendix C. It is not surprising that expressive GNNs can outperform other GNNs on the graph classification task, since the expressivity of a GNN is defined as the ability to distinguish non-isomorphic graphs. However, by comparing Table 5 with Tables 2, 3, 6, 7, it is worth noting that _more expressive GNNs cannot ensure better performance of GNN-based graph generative models in molecular generation \begin{table} \begin{tabular}{l l l l l} \hline \hline Model & DRD2 & Median1 & Median2 & QED \\ \hline GCPN (RGCN) & 0.479 & 0.337 & 0.192 & 0.948 \\ GCPN (GearNet) & 0.970 (+**102.51**\(\%\)) & 0.337 (+**0.00**\(\%\)) & 0.286 (+**48.96**\(\%\)) & 0.948 (+**0.00**\(\%\)) \\ \hline GraphAF (RGCN) & 0.928 & 0.281 & 0.143 & 0.946 \\ GraphAF (GearNet) & 0.987 (+**6.36**\(\%\)) & 0.290 (+**3.20**\(\%\)) & 0.183 (+**27.97**\(\%\)) & 0.947 (+**0.11**\(\%\)) \\ \hline LSTM HC (SMILES) [15] & 0.999 & 0.388 & 0.339 & 0.948 \\ DoG-Gen [16] & 0.999 & 0.322 & 0.297 & 0.948 \\ GP BO [12] & 0.999 & 0.345 & 0.337 & 0.947 \\ SynNet [10] & 0.999 & 0.244 & 0.259 & 0.948 \\ GA+D (11) & 0.836 & 0.219 & 0.161 & 0.945 \\ VAE BO (SMILES) [13] & 0.940 & 0.231 & 0.206 & 0.947 \\ Graph MCTS [14] & 0.586 & 0.242 & 0.148 & 0.928 \\ MolDQN [17] & 0.049 & 0.188 & 0.108 & 0.871 \\ \hline \hline \end{tabular} \end{table} Table 4: Comparison of the top-1 DRD2, Median1, Median2 and QED scores with the selected non-GNN-based generative models. The full table can be found in Table 8 in Appendix B. \begin{table} \begin{tabular}{l c c c c} \hline \hline \multirow{2}{*}{Model} & \multicolumn{2}{c}{GCPN} & \multicolumn{2}{c}{GraphAF} \\ \cline{2-5} & \(NLL_{all}\) & \(Acc\) & \(NLL_{e}\) & \(NLL_{n}\) \\ \hline RGCN & 2.1427 \(\pm\) 0.1326 & 0.8656 \(\pm\) 0.0088 & -1.0674 \(\pm\) 0.0204 & -3.3312 \(\pm\) 0.1557 \\ GIN & 2.1500 \(\pm\) 0.3158 & 0.8680 \(\pm\) 0.0220 & -1.1691 \(\pm\) 0.1167 & -3.6067 \(\pm\) 0.2589 \\ GAT & 2.8705 \(\pm\) 0.2354 & 0.7957 \(\pm\) 0.0211 & -1.2737 \(\pm\) 0.0340 & -3.1541 \(\pm\) 0.0844 \\ GATv2 & 2.8285 \(\pm\) 0.2878 & 0.8013 \(\pm\) 0.0244 & -1.2426 \(\pm\) 0.0370 & -3.1325 \(\pm\) 0.0681 \\ PNA & 2.1172 \(\pm\) 0.0036 & 0.8716 \(\pm\) 0.0003 & -1.1043 \(\pm\) 0.1148 & -3.2840 \(\pm\) 0.2154 \\ GSN & **1.4219 \(\pm\) 0.0026** & **0.9308 \(\pm\) 0.0002** & -1.1319 \(\pm\) 0.0678 & -3.1280 \(\pm\) 0.0566 \\ GearNet & 2.1265 \(\pm\) 0.0017 & 0.8677 \(\pm\) 0.0003 & **-0.9275 \(\pm\) 0.0048** & **-2.8981 \(\pm\) 0.0398** \\ \hline \hline \end{tabular} \end{table} Table 5: Graph classification metrics among GCPN and GraphAF variants. \(NLL_{all}\) means the average negative log likelihood loss for all node and edge classification tasks. \(Acc\) means the average accuracy for all node and edge classification tasks. \(NLL_{e}\) and \(NLL_{n}\) mean the average edge negative log likelihood evaluated on classification tasks for edge and node respectively. tasks_. For example, PNA and GSN perform better than R-GCN on graph classification tasks (Table 5), but GCPN with PNA or GSN cannot surpass the original GCPN on all generation metrics (e.g. Median2 in Table 3). Therefore, we conclude that the graph generation task is a different task from graph classification and requires other abilities of GNNs, such as edge feature extraction. De-novo molecule design with GNNs incorporating edge features.We investigate the performance of GCPN and GraphAF using GNNs with and without edge features. It is worth mentioning that the original GCPN considers edge features but GraphAF does not. The results of the GCPN without edge features (GCPN-e) are summarised in Table 2, and those of the original GCPN are in Table 3. Both sets of results demonstrate that including edge features can significantly improve the top-3 scores on all three metrics for most GNNs. For instance, with the help of edge feature extraction, GCPN with GIN, GAT, GATv2, PNA and GSN can increase by \(24.0\%\), \(149.8\%\), \(70.5\%\), \(31.0\%\) and \(12.0\%\) on the top-1 score on the metric DRD2, compared with GCPN-e. The original GraphAF comes without edge feature extraction and we thus improved it by incorporating the edge features. Table 6 (the orginal GraphAF) and Table 7 (GraphAF+e) in Appendix B summarised the results of both implementations accordingly. The results align with the GCPN case, where GraphAF+e significantly improves the top-3 scores on all three metrics for most GNNs than the original GraphAF. More specifically, with the help of edge feature extraction, GraphAF+e with GIN, GAT, GATv2, PNA and GSN can be improved by \(43.5\%\), \(60.0\%\), \(20.0\%\), \(230.4\%\) and \(312.4\%\) on the top-1 score on the metric DRD2. The results above indicate _the importance of aggregating edge features for GNN-based generative models_. By harnessing the power to extract knowledge from edge information, the potential for generating more refined and accurate graphs is enhanced. We also notice that, when the GNNs used are either R-GCN or GearNet, we find GCPN and GraphAF perform well with and without considering edge information, so we hypothesise the reason is that they absorb the number of edge relations as prior information in the model. In summary, we conclude the following results: 1. More expressive GNN can lead to better results in the graph classification task. However, GNN expressiveness defined by the 1-WL test is not a necessary condition for a good GNN-based generative model. Generation tasks require other abilities of GNNs, such as edge feature extraction and edge relation detection. 2. Although Penalised logP and QED are widely used for generative metrics in evaluating goal-directed graph generative models, they are not effective metrics to differentiate different generative models. Other metrics, such as DRD2, Median1 and Median2, can better evaluate the ability of a graph generative model. Under those metrics, we can see the performance of GCPN and GraphAF can be enhanced by using more robust GNNs. 3. After applying advanced GNN to current GNN-based graph generative methods, such as GCPN and GraphAF, they can outperform or match state-of-the-art results across 17 other generative approaches in the de-novo molecule generation task. ## 5 Limitation and Conclusion Due to computation cost, we acknowledge several limitations of the current study: we cannot exhaustively explore every method, such as other Relational GNNs, and thoroughly tune every hyperparameter; we cannot evaluate all generative models on other complicated datasets besides Zinc 250k, such as ChEMBL [39], and other generation metrics [9]. However, our efforts have still provided valuable insights into investigating the expressiveness of GNN on the graph generation task, because of our focus on many different generative models and diverse generation objectives. After exploring (1) unexplored underlying GNNs and (2) non-trivial generative objectives, we would like to conclude that expressiveness is not a necessary condition for a good GNN-based generative model. By evaluating GCPN variants and GraphAF variants on effective metrics, we demonstrate that GCPN and GraphAF can be improved by using more robust GNNs (e.g. strong edge features extraction and edge relation detection). With more robust GNNs, GNN-based graph generative models can outperform or match state-of-the-art results across 17 other generative approaches on de-novo molecule design tasks [9]. In the future, we plan to explore the necessary conditions for GNN to enhance the performance of GNN-based graph generative models.
2307.05150
A Modal Logic for Explaining some Graph Neural Networks
In this paper, we propose a modal logic in which counting modalities appear in linear inequalities. We show that each formula can be transformed into an equivalent graph neural network (GNN). We also show that each GNN can be transformed into a formula. We show that the satisfiability problem is decidable. We also discuss some variants that are in PSPACE.
Pierre Nunn, François Schwarzentruber
2023-07-11T10:13:25Z
http://arxiv.org/abs/2307.05150v1
# A Modal Logic for Explaining some Graph Neural Networks ###### Abstract In this paper, we propose a modal logic in which counting modalities appear in linear inequalities. We show that each formula can be transformed into an equivalent graph neural network (GNN). We also show that each GNN can be transformed into a formula. We show that the satisfiability problem is decidable. We also discuss some variants that are in PSPACE. ## 1 Introduction Graph neural networks are used to learn a class of graphs or pointed graphs (a graph with a designated vertex). GNNs are used in many applications: social networks [16], chemistry, knowledge graphs etc. (see [25] for an overview of the applications of GNNs). The Saint-Graal for explaning GNNs would be to provide an algorithm for the following problem: **Synthesis of an explanation** * input: a GNN \(A\) * output: a logical formula \(\varphi\) such that \([[A]]=[[\varphi]]\) where \([[A]]\) is the class of pointed graphs recognized by the GNN \(A\), and \([[\varphi]]\) is the class of pointed graphs in which \(\varphi\) holds. In other words, the goal is to compute a formula \(\varphi\) (in modal logic, or in graded modal logic for example) that completely explains the class of graphs recognized by \(A\). For instance, in a social network, a person is recommended by a GNN \(A\) iff that person has at least one friend that is musician (the formula \(\varphi\) being for instance expressed in modal logic by \(\Diamondmusician\), where \(\Diamond\) is the existential modal operator). The synthesis of an explanation in some logic - let say first-order logic, modal logic, or graded modal logic - is highly challenging. In this paper, we tackle a less challenging problem but that goes in the same direction. We provide an algorithmic solution for tackling the following problems: **P1: Verification of an explanation** * input: a GNN \(A\), a logical formula \(\varphi\) * output: yes, if \([[A]]\subseteq[[\varphi]]\) #### 1.0.1 P3: Verification of an explanation P4: Finding a counterexample * input: a GNN \(A\), a logical formula \(\varphi\) * output: yes, if \([[\varphi]]\cap[[A]]\neq\emptyset\) Here are kind of question instances that problems P1-4 are able to solve: * P1: is a recommended person a person that has at least one musician friend? * P2: does any recommended person have a musician friend? * P3: is any person that a musician friend recommended? * P4: is it possible to recommend a person that has at least one musician friend? Our solution is a general methodology to solve the problems P1-4 which consists in representing everything (\(\varphi\) but also the GNN \(A\)) in logic. Interestingly, there is a neat correspondence between graded modal logic and GNNs ([3], [8]). Graded modal logic [6] is a modal logic offering the ability via the construction \(\diamondsuit^{\geq k}\varphi\) to say that a vertex has more that \(k\) successors satisfying a formula \(\varphi\) We know that a GNN that is expressible in first-order logic (FO) is also captured by a formula in graded modal logic [3]. However the use of graded modal logic is problematic because we do not know how to represent _any_ GNN into it (in particular those who are not expressible in FO). That is why we define a logic called \(K^{\#}\) which is more expressive enough to capture a reasonable class of GNNs while being able to express any formula in modal logic or graded modal logic. We then provide an algorithm for the satisfiability problem for \(K^{\#}\). In this article, we capture AC-GNN (aggregation-combination graph neural networks) [3] that are defined by an aggregation function which is the sum of feature vectors, the combination functions being linear functions truncated with the activation function \(max(0,min(1,x))\), and where the classification function is linear too. The \(max(0,min(1,x))\) is called truncated reLU (see [3]) or clipped reLU (see [22]). The logic \(K^{\#}\) we consider is a combination of counting modalities and linear programming. It extends graded modal logic. We provide a translation from any GNN \(A\) to a formula \(tr(A)\) in \(K^{\#}\) so the problems P1-4 reformulate as follows: * P1: is \(tr(A)\leftrightarrow\varphi\) valid? * P2: is \(tr(A)\rightarrow\varphi\) valid? * P3: is \(\varphi\to tr(A)\) valid? * P4: is \(\varphi\wedge tr(A)\) satisfiable? The formula \(\varphi\) can be for instance a formula of modal logic K and graded modal logic. As \(K^{\#}\) subsumes these logics, all the problems P1-4 in fact reduce to the satisfiability problem of \(K^{\#}\) (recall that a formula valid if its negation is unsatisfiable). We prove that the satisfiability problem of \(K^{\#}\) is _decidable_. Interestingly, given a formula, we are able to construct an equivalent GNN. This can be used to _tune_ an existing GNN. Suppose you learnt a GNN \(A\) but you aim at constructing a new GNN that behaves like \(A\) but excludes the pointed graphs that do not satisfy \(\varphi\). More precisely, for the following problem: **Tuning of a GNN** * input: a GNN \(A\), a logical formula \(\varphi\) * output: a new GNN \(A^{\prime}\) such that \([[A^{\prime}]]=[[A]]\cap[[\varphi]]\) we simply take a GNN \(A^{\prime}\) that represents the formula \(tr(A)\wedge\varphi\). More precisely, the contributions of this paper are: * the formal definition of logic \(K^{\#}\); * the construction of a GNN \(A\) equivalent to a \(K^{\#}\)-formula \(\varphi\) (it generalizes the result of Prop 4.1 in [3]) * the construction of a \(K^{\#}\)-formula \(tr(A)\) equivalent to \(A\) * the fact that the satisfiability problem of \(K^{\#}\) is in \(\mathsf{EXPTIME}^{\mathsf{NP}}\) (i.e. \(\mathsf{EXPTIME}\) with an \(\mathsf{NP}\) oracle). * Restrictions of the satisfiability problem that are in \(\mathsf{PSPACE}\). Outline.In Section 2 we recall the definition of AC-GNN. In Section 3, we define the logic \(K^{\#}\). In Section 4.1, we study the correspondence between GNN and logic \(K^{\#}\). In Section 5, we discuss the satisfiability problem of \(K^{\#}\). ## 2 Background on AC-GNN In this paper, we consider aggregate-combine GNN (AC-GNN) [3], also sometimes called message passing neural network (MPNN) [8]. In the rest of the paper, we call a AC-GNN simply a GNN. Definition 1 (labeled graph): A (labeled directed) graph \(G\) is a tuple \((V,E,\ell)\) such that \(V\) is a finite set of vertices, \(E\subseteq V\times V\) a set of directed edges and \(\ell\) is a mapping from \(V\) to a valuation over a set of atomic propositions. We write \(\ell(u)(p)=1\) when atomic proposition \(p\) is true in \(u\), and \(\ell(u)(p)=0\) otherwise. Definition 2 (state): A state \(x\) is a mapping from \(V\) into \(\mathbb{R}^{d}\) for some \(d\). As in [18], we use the term'state' for both denoting \(x\) and also the vector \(x(v)\) at a given vertex \(v\). Suppose that the relevant atomic propositions are \(p_{1},\ldots,p_{k}\). The initial state \(x_{0}\) is defined by: \[x_{0}(u)=(\ell(u)(p_{1}),\ldots,\ell(u)(p_{k}),0,\ldots,0)\] for all \(u\in V\). For simplicity, we suppose that all states are of the same dimension \(d\). Definition 3 (aggregation function/combination function): An aggregation function \(AGG\) is a function mapping finite multisets of vectors in \(\mathbb{R}^{d}\) to vectors in \(\mathbb{R}^{d}\). A combination function \(COMB\) is a function mapping a vector in \(\mathbb{R}^{2d}\) to vectors in \(\mathbb{R}^{d}\). Definition 4 (GNN layer): A GNN layer of input/output dimension \(p\) is defined by an aggregation function \(AGG\) and a combination function \(COMB\). Definition 5 (Gnn): A GNN is a tuple \((\mathcal{L}^{(1)},...\mathcal{L}^{(L)},CLS)\) where \(\mathcal{L}^{(1)},...\mathcal{L}^{(L)}\) are \(d\) GNN layers and \(CLS:\mathbb{R}^{d}\rightarrow\{0,1\}\) is a classification function. When applied to a graph \(G\), the \(t\)-th GNN layer \(\mathcal{L}^{(t)}\) transforms the previous state \(x_{t-1}\) into the next state \(x_{t}\) by: \[x_{t}(u)=COMB(x_{t-1}(u),AGG(\{\{x_{t-1}(v)|uv\in E\}\}))\] where \(AGG\) and \(COMB\) are respectively the aggregation and combination function of the \(t\)-th layer. In the above equation, note that the argument of \(AGG\) is the multiset of the state vectors of the successors of \(v\). Thus, the same vector may occur several times in that multiset. Figure 1 explains how a layer works at each vertex. Figure 2 explains how the overall GNN works: the state is updated at each layer; at the end the fonction \(CLS\) says whether each vertex is positive (1) or negative (0). Definition 6: Let \(A\) be GNN. We define \([[A]]\) as the set of pointed graphs \((G,u)\) such that \(CLS(x_{L}(u))=1\). In the rest of the article, we suppose that the aggregation function is a sum: \[AGG(X)=\sum_{x\in X}x.\] Figure 1: A layer in a GNN transforms the state \(x_{t-1}\) at step \(t-1\) into the state \(x_{t}\) at time \(t\). The figure shows how \(x_{t}(u)\) is computed. First, the function \(AGG\) is applied to the state in the successors of \(u\). Then \(COMB\) is applied to that result and \(x_{t-1}(u)\) to obtain \(x_{t}(u)\). Figure 2: General idea of a GNN with 2 layers applied on a graph with 4 vertices. ## 3 Our proposal: logic \(K^{\#}\) In this section, we describe the syntax and semantics of \(K^{\#}\). We finish the section by defining its satisfiability problem. ### Syntax Consider a countable set \(Ap\) of propositions. We define the language of logic \(K^{\#}\) as the set of formulas generated by the following BNF: \[\varphi ::=p\mid\neg\varphi\mid\varphi\vee\varphi\mid E\geq 0\] \[E ::=c\mid 1_{\varphi}\mid\#\varphi\mid E+E\mid c\times E\] where \(p\) ranges over \(Ap\), and \(c\) ranges over \(\mathbb{Z}\). This logic is an extension of modal logic. Atomic formulas are propositions \(p\), inequalities and equalities of linear expressions. We consider linear expressions over \(1_{\varphi}\) and \(\#\varphi\). The number \(1_{\varphi}\) is equal to \(1\) if \(\varphi\) holds in the current world and equal \(0\) otherwise. The number \(\#\varphi\) is the number of successors in which \(\varphi\) hold. The language seems strict but we write \(E_{1}\leq E_{2}\) for \(E_{2}-E_{1}\geq 0\), \(E=0\) for \((E\geq 0)\wedge(-E\geq 0)\), etc. Example 1: Graded modal logic [6] extends classical modal logic by offering counting modality constructions of the form \(\diamond^{\geq k}\varphi\) which means there are at least \(k\) successors in which \(\varphi\) holds. Logic \(K^{\#}\) is more expressive than Graded modal logic since \(\diamond^{\geq k}\varphi\) is rewritten in \(k\leq\#\varphi\). Example 2: Interestingly, the property 'there are more \(p\)-successors than \(q\)-successors' can be expressed in logic \(K^{\#}\) by \(\#p\geq\#q\), but cannot be expressed in FO, thus not graded modal logic. This is proven via a Ehrenfeucht-Fraisse game. The set of subformulas, \(sub(\varphi)\) is defined by induction on \(\varphi\): \[sub(p) =\{p\}\] \[sub(\neg\varphi) =\{\neg\varphi\}\cup sub(\varphi)\] \[sub(\varphi\vee\psi) =\{\varphi\vee\psi\}\cup sub(\varphi)\cup sub(\psi)\] \[sub(E\geq 0) =\{E\geq 0\}\cup\bigcup\{sub(\psi)\mid 1_{\psi}\text{ or }\#\psi\text{ appears in }E\}\] The modal depth of a formula, \(md(\varphi)\) and the modal depth of an expression, \(md(E)\) are defined by mutual induction on \(\varphi\) and \(E\): \[md(p) =0 md(c) =0\] \[md(\neg\varphi) =md(\varphi) md(1_{\varphi}) =md(\varphi)\] \[md(\varphi\vee\psi) =\max(md(\varphi),md(\psi)) md(\#\varphi) =md(\varphi)+1\] \[md(E\geq 0) =md(E) md(E_{1}+E_{2}) =max(md(E_{1}),md(E_{2}))\] \[md(k*E) =md(E)\] As in modal logic, modalities are organized in levels. Example 3: \(md((1_{p\wedge\#q\leq 4}\leq\#(\#p\geq 2)\leq 4)=2\). The expressions \(\#q\) and \(\#(\#p\geq 2)\) are at the root level (level 1), while the expression \(\#p\) is at level 2. A formula can be represented by a DAG (directed acyclic graph) instead of just a syntactic tree. It allows to share common expressions. For instance \(\#(p\wedge q)\geq 1_{p\wedge q}\) is represented by the following DAG in which \(p\wedge q\) is used twice: ### Semantics As in modal logic, a formula \(\varphi\) is evaluated in a pointed graph \((G,u)\) (also known as pointed Kripke model). Definition 7: We define the truth conditions \((G,u)\models\varphi\) (\(\varphi\) is true in \(u\)) and the semantics \([[E]]_{G,u}\) (the value of \(E\) in \(u\)) of an expression \(E\) by mutual induction on \(\varphi\) and \(E\) as follows. \[\begin{array}{ll}(G,u)\models p&\text{if }\ell(u)(p)=1\\ (G,u)\models\neg\varphi&\text{if it is not the case that }(G,u)\models\varphi\\ (G,u)\models\varphi\wedge\psi&\text{if }(G,u)\models\varphi\text{ and }(G,u)\models\psi\\ (G,u)\models E\geq 0&\text{if }[[E]]_{G,u}\geq 0\end{array}\] \[\begin{array}{ll}[[c]]_{G,u}&=c\\ [[E_{1}+E_{2}]]_{G,u}&=[[E_{1}]]_{G,u}+[[E_{2}]]_{G,u}\\ [[c\times E]]_{G,u}&=c\times[[E]]_{G,u}\\ [[1_{\varphi}]]_{G,u}&=\begin{cases}1&\text{if }(G,u)\models\varphi\\ 0&\text{else}\end{cases}\\ [[\#\varphi]]_{G,u}&=|\{v\in V\mid(u,v)\in E\text{ and }(G,v)\models\varphi\}|\end{array}\] Example 4: Consider the pointed graph \(G,u\) shown in Figure 3. We have \(G,u\models p\wedge(\#\neg p\geq 2)\wedge\#(\#p\geq 1)\leq 1\). Indeed, \(p\) holds in \(u\), \(u\) has (at least) two successors in which \(\neg p\) holds. Moreover, there is (at most) one successor which has at least one \(p\)-successor. Definition 8: \([[\varphi]]\) is the set of the pointed graphs \(G,u\) such that \(G,u\models\varphi\). Figure 3: Example of a pointed graph \(G,u\). We indicate true propositional variables at each vertex. Definition 9: We say that \(\varphi\) is satisfiable when there exists a pointed graph \(G,u\) such that \(G,u\models\varphi\). The satisfiability problem is: given \(\varphi\) in the language of \(K^{\#}\), is \(\varphi\) satisfiable? ## 4 Correspondence We explain how to transform a \(K^{\#}\)-formula into a GNN, and vice versa. ### From logic to GNN Let us show that each \(K^{\#}\)-formula is captured by a GNN. The proof follows the same line that the proof of the fact that each formula of graded modal logic is captured by a GNN (see Prop 4.1 in [3]). However, our first result (point 1 in the following theorem) is a generalisation of their result since logic \(K^{\#}\) is more expressive than graded modal logic. Moreover, point 2 of the following theorem explicitly mentions a bound on the number of layers in the GNN. Theorem 4.1: _For each \(K^{\#}\)-formula \(\varphi\), we can compute a GNN \(A\) such that \([[\varphi]]=[[A]]\). Furthermore, we have:_ 1. _Either the number of layers and the dimension of the states in_ \(A\) _is_ \(|\varphi|\)_;_ 2. _Or the number of layers of_ \(A\) _is_ \(O(md(\varphi))\)_._ Proof: Let \(\varphi\) be a \(K^{\#}\) formula. Let \((\varphi_{1},...\varphi_{L})\) be an enumeration of the sub-formulas of \(\varphi\) such that \(\varphi_{L}=\varphi\). We will construct a GNN \(\mathcal{A}_{\varphi}\) with \(L\) layers. The dimension of the states is \(L\). The goal is that for all \(k\leq n\), the \(k\)-th component of \(x_{\ell}(v)\) is equal to 1 if the formula \(\varphi_{k}\) is satisfied in node \(v\), or 0 otherwise. The aggregation and combination function in each layer are set by: \[AGG(X) =\sum_{x\in X}\mathbf{x}\] \[COMB(x,y) =\boldsymbol{\sigma}(xC+yA+b)\] where \(\boldsymbol{\sigma}\) is the function that applies componentwise the function \(\sigma(x)=min((max(0,x),1)\) and where \(A,C\in\mathbb{R}^{L\times L}\) and \(b\in\mathbb{R}^{L}\) are defined as follows. All cells are zeros, except the cells given in the following table: \begin{tabular}{l l l} \(\varphi_{\ell}\) & \(\ell\)-th columns of \(C\) and \(A\) & \(b_{\ell}\) \\ \hline \(p\) & \(C_{\ell\ell}=1\) & 0 \\ \(\neg\varphi_{i}\) & \(C_{i\ell}=-1\) & 1 \\ \(\varphi_{i}\vee\varphi_{j}\) & \(C_{i\ell}=C_{j\ell}=1\) & 0 \\ \(\varphi_{i}\wedge\varphi_{j}\) & \(C_{i\ell}=C_{j\ell}=1\) & -1 \\ \(c\leq\sum_{i\in I}k_{i}\times 1_{\varphi_{i}}+\sum_{i\in I^{\prime}}k_{i}\times \#\varphi_{i}\) & \(C_{i\ell}=k_{i}\) for \(i\in I\) & \(-c+1\) \\ & \(A_{k\ell}=k_{i}\) for \(i\in I^{\prime}\) & \\ \end{tabular} For proving point 2., the idea is to transform each propositional level of \(\varphi\) into a CNF. We obtain a \(K^{\#}\)-formula \(\varphi^{\prime}\) potentially exponentially larger than \(\varphi\). The advantage is now that each propositional level is a CNF and thus is of depth at most 2. We treat an arbitrary large disjunction or conjunction as a single step of computation. In other words, we now consider an enumeration \((\varphi_{1},...\varphi_{L})\) of subformulas of \(\varphi^{\prime}\) such that \(\varphi_{L}=\varphi^{\prime}\) and with \(L=O(md(\varphi))\). Here are the corresponding \(\ell\)-columns of \(C\) and \(b_{\ell}\) for the cases where \(\varphi_{\ell}\) is an arbitrary large disjunction or conjunction: \[\begin{array}{ll}\frac{\varphi_{\ell}}{\mbox{$\bigvee_{i\in I}\varphi_{i}^{ \prime\prime}\vee\bigvee_{i\in I^{\prime}}$}\,\neg\varphi_{i}^{\prime\prime} \ C_{i\ell}&b_{\ell}\\ \\ \bigwedge_{i\in I}\varphi_{i}^{\prime\prime}&C_{i\ell}&=1\,\mbox{for $i\in I $}&-card(I)+1\end{array}\] Example 5: Consider the formula \(\varphi=p\wedge(8\leq 3\times\#q)\). We define the following GNN \(A\) which is equivalent to \(\varphi\) as follows. The aggregation function at each layer is \(AGG(X)=\sum_{x\in X}x\). The combination function for each layer is \(COMB(x,y)=\boldsymbol{\sigma}(xC+yA+b)\) where \(C=\begin{pmatrix}1&0&0&1\\ 0&1&0&0\\ 0&0&0&1\\ 0&0&0&0\end{pmatrix}\), \(A=\begin{pmatrix}0&0&0&0\\ 0&0&3&0\\ 0&0&0&0\\ 0&0&0&0\end{pmatrix}\), and \(b=\begin{pmatrix}0&0&-7&-1\end{pmatrix}\). The columns in the matrices (from top to bottom) are respectively evaluated the following subformulas in that order: \(p\), \(q\), \(8\leq\#q\), \(\varphi\). ### From GNN to logic In this subsection, we show how to compute a \(K^{\#}\)-formula that is equivalent to a GNN. Note that this direction was already tackled for graded modal logic for the subclass of GNNs that are FO-expressible, but their proof is not constructive [3]. Theorem 4.2: _Let \(A\) be a GNN \(A\) with all aggregation function being \(AGG(X)=\sum_{x\in X}x\), and the classfication function being linear: \(CLS(x)=\sum_{i}a_{i}x_{i}\geq 0\). Then we can compute in poly-time in \(|A|\) a \(K^{\#}\)-formula \(tr(A)\) represented as DAG such that \([[A]]=[[tr(A)]]\)._ Proof: Let us consider a GNN \(A\) of \(L\) layers where the aggregation function is always: \(AGG(X)=\sum_{x\in X}\mathbf{x}\). The idea is that we represent the state \(x_{0}(v)\) at all vertices \(v\) by the truth value of some formulas. Initially, the states is represented by the formulas \((p_{1},\ldots,p_{k},\bot,\ldots,\bot)\). Suppose that states \(x_{t}(v)\) are represented by the formulas \((\varphi_{1},\ldots,\varphi_{d})\). Then if the combination function is \(COMB(x,y)=\boldsymbol{\sigma}(xC+yA+b)\) then the states \(x_{t+1}(v)\) are represented by the formulas \((\varphi_{1}^{\prime},\ldots,\varphi_{d}^{\prime})\) where \(\varphi_{\ell}^{\prime}\) is \[\sum_{i=1..d}1_{\varphi_{i}}C_{i\ell}+\sum_{i=1..d}\#\varphi_{i}A_{i\ell}+b_{ \ell}\geq 1\] Now, we have formulas \((\varphi_{1},\ldots,\varphi_{d})\) to represent \(x_{L}(v)\). As \(CLS\) is linear, the final formula is \(1_{CLS(\varphi_{1},\ldots,\varphi_{d})}\). \(CLS(x_{L}(u))=1\). ## 5 Decidability Let us give an algorithm to solve the satisfiability of \(K^{\#}\), inspired by classical tableau method for modal logic K [7], but taking linear constraints into account. ### Design of the algorithm First constructions \(1_{\psi}\) are easy to treat. Either \(\psi\) holds and we say that \(1_{\psi}=1\), or \(\psi\) does not hold and we say that \(1_{\psi}=0\). However, treating naively \(\#\psi\) as variables in a linear program will unfortunately not work. Let us note \(\#\psi_{1},\ldots\#\psi_{n}\) the variables of the form \(\#\psi\) that appear in \(\varphi\) and that are not in the scope of a \(\#\)-modality. First, some \(\psi_{i}\) may be unsatisfiable, thus \(\#\psi_{i}=0\). But the issue is more subtle. For instance, we always have \(\#p+\#\neg p=\#q+\#\neg q\) (1). The reader may imagine even more involved interactions between the \(\#\psi_{i}\) than equation (1). To take this interactions into account, we consider all possible conjunctions of \(\psi_{i}\) and \(\neg\psi_{i}\). We define for all words \(w\in\{0,1\}^{n}\): \[conj_{w}:=\bigwedge_{i=1..n|w_{i}=1}\psi_{i}\wedge\bigwedge_{i=1..n|w_{i}=0} \neg\psi_{i}.\] Example 6: \(conj_{0100}=\neg\psi_{1}\wedge\psi_{2}\wedge\neg\psi_{3}\wedge\neg\psi_{4}\). We then introduce a variable in the linear program for each word \(w\) that counts the number of successors in which \(conj_{w}\) holds. We have \(\#\psi_{i}=\sum_{w|w_{i}=1}x_{w}\). Example 7: How do we guarantee that \(\#p+\#\neg p=\#q+\#\neg q\)? Suppose that \(\psi_{1}=p,\psi_{2}=\neg p,\psi_{3}=q,\psi_{4}=\neg q\). As \(p\wedge\neg p\) is unsatisfiable, we have \(x_{1100}=x_{1101}=x_{1110}=x_{1111}=0\). We write \(x_{11**}=0\). In the same way, as and \(p\wedge\neg p\) and \(q\wedge\neg q\) are unsatisfiable \(x_{00**}=0\), \(x_{**00}=0\) and \(x_{**11}=0\). Finally: \[\#p =x_{1010}+x_{1001} \#\neg p =x_{0110}+x_{0101}\] \[\#q =x_{1010}+x_{0110} \#\neg q =x_{1001}+x_{0101}\] We see that \(\#p+\#\neg p=x_{1010}+x_{1001}+x_{0110}+x_{0101}=\#q+\#\neg q\). Instead of providing tableau rules, we decided to present a more abstract version with Hintikka sets (see Def. 6.24 in [4]). They can be thought as a possible way to completely apply Boolean rules while keeping consistent. We adapt the definition to our setting. Definition 10 (Hintikka set): A Hintikka set \(\Sigma\) for formula \(\varphi\) is a smallest (for inclusion) set of subformulas such that: 1. \(\varphi\in\Sigma\); 2. if \(\psi_{1}\wedge\psi_{2}\in\Sigma\) then \(\psi_{1}\in\Sigma\) and \(\psi_{2}\in\Sigma\) 3. if \(\psi_{1}\vee\psi_{2}\in\Sigma\) then \(\psi_{1}\in\Sigma\) or \(\psi_{2}\in\Sigma\) 4. for all \(\psi\), \(\psi\not\in\Sigma\) or \(\neg\psi\not\in\Sigma\) 5. \(1_{\psi}\) appears in \(\varphi\), either \(\psi\in\Sigma\) and \(1_{\psi}=1\in\Sigma\), or \(\neg\psi\in\Sigma\) and \(1_{\psi}=0\in\Sigma\). Point 1 says that \(\varphi\) should be true. In point 3, if \(\psi_{1}\vee\psi_{2}\) then one of the formula - \(\psi_{1}\) or \(\psi_{2}\) - should be true, without telling which one. Point 4 is the consistency. Point 5 makes the link between the truth of \(\psi\) and the value of \(1_{\psi}\). Example 8: Consider formula \(\varphi=p\wedge(\#r\geq 1_{q})\). There are two possible Hintikka sets for formula \(\varphi\): \(\{p,\#r\geq 1_{q},1_{q}=1,q\}\) and \(\{p,\#r\geq 1_{q},1_{q}=0,\neg q\}\). The algorithm (see Figure 4) consists in examining all possible Hintikka sets. For each of them, we extract the linear program (line 3). We then compute the integer linear program by considering the variables \(x_{w}\) discussed above (line 6). Line 7: we call recursively the function sat on \(conj_{w}\) and we add the constraint \(x_{w}=0\) in case \(conj_{w}\) is unsatisfiable. ### Soundness and completeness Proposition 1: \(\varphi\) _is \(K^{\#}\)-satisfiable iff \(sat(\varphi)\) returns true._ Proof: We prove the proposition by induction on \(md(\varphi)\). The induction works because \(md(conj_{w})<md(\varphi)\). Suppose that \(\varphi\) is satisfiable: let \(G,v\) such that \(G,u\models\varphi\). Let us prove that \(sat(\varphi)\) returns true. We consider the Hintikka set \(H\) made up of formulas that are true in \(G,v\). The obtained \(S\) is ILP-satisfiable because these equations and inequations are satisfied in \(G,u\). Indeed, here is a solution: we set \(x_{w}\) to be the number of successors of \(u\) in which \(conj_{w}\) hold. By induction, the call \(sat(conj_{w})\) are all correct: so if \(sat(conj_{w})\) returns false, then \(conj_{w}\) is unsatisfiable. Thus there are no \(u\)-successors satisfying \(conj_{w}\), and the constraints \(x_{w}=0\) (added line 8) hold. The number of \(v\)-successors satisfying \(\psi_{i}\) is \(\sum_{w|w_{i}=1}x_{w}\). So \(S\) is ILP-satisfiable, and the algorithm returns true. Conversely, suppose that \(sat(\varphi)\) returns true. First, consider \(S\) the corresponding Hintikka set for which the algorithm returned true. From \(S\) we extract a valuation \(\ell(u)\) for the propositions to be set to true or false at a node \(u\). By induction, for all \(w\in\{0,1\}^{n}\), the call \(sat(conj_{w})\) are all correct. Thus, if \(conj_{w}\) is unsatisfiable, \(x_{w}=0\); otherwise \(x_{w}\) is not constrained. As \(sat(\varphi)\) returned true, Figure 4: Algorithm for checking the satisfiability of a \(K^{\#}\)-formula \(\varphi\). we know that \(S\) is ILP-satisfiable. Consider a solution. If \(x_{w}>0\), we know that \(conj_{w}\) is satisfiable. We consider \(x_{w}\) copies of a pointed graph \(G_{w},u_{w}\) satisfying \(conj_{w}\). We construct a model \(G,u\) for \(\varphi\) as follows. We take \(u\) as the point with valuation \(\ell(v)\). We then link \(u\) to each point of the copies of \(u_{w}\). The inequations in \(S\) are satisfied at \(G,u\). Indeed, the \(u\)-successors satisfying \(\psi_{i}\) are exactly the \(u_{w}\) with \(w_{i}=1\), and \(\#\psi_{i}\) is \(\sum_{w|w_{i}=1}x_{w}\). Thus, the obtained pointed \(G,u\) is a model of \(\varphi\). Figure 5 shows an example of the construction. Note that \(K^{\#}\) has the tree-model property as modal logic K. It can be proven by induction on \(md(\varphi)\), relying on the construction in the \(\Leftarrow\)-direction in the proof above. ### Complexity The recursive depth of our algorithm (Figure 4) is bounded by the modal depth \(md(\varphi)\) of the initial formula \(\varphi\): the recursive tree is of depth \(md(\varphi)\). Its branching factor is exponential in \(|\varphi|\). The number of nodes remains exponential in \(|\varphi|\). At each node, there is an exponential number of steps, provided that the ILP-solver is considered as an NP-oracle since integer linear programming (ILP) is in NP [13] (note that the linear programs computed here are of exponential size in \(|\varphi|\)). Our algorithm runs in exponential time in \(|\varphi|\), by calling a NP-oracle: deciding the satisfiability problem of \(K^{\#}\) is in \(\mathsf{EXPTIME}^{\mathsf{NP}}\). The class \(\mathsf{EXPTIME}^{\mathsf{NP}}\) is defined as the class of decision problems decided by an algorithm running in exponential time (i.e. \(2^{poly(n)}\)) with a NP oracle, typically a SAT oracle or a ILP oracle (note that exponentially long ILP instances may be solved in one step) (see [23], [10]). Note that the complexity class \(\mathsf{EXPTIME}^{\mathsf{NP}}\) is included in the exponential hierarchy which is included in \(\mathsf{EXPSPACE}\). Theorem 5.4: _The satisfiability problem of \(K^{\#}\) is decidable and is in \(\mathsf{EXPTIME}^{\mathsf{NP}}\)._ ### \(\mathsf{PSPACE}\) subcases Let us discuss three types of restrictions to get \(\mathsf{PSPACE}\)-membership. Bounding the number of \(conj_{w}\).If we can limit the number of considered conjonctions \(conj_{w}\), we may obtain a procedure running in polynomial space, making the restricted version of the satisfiability problem of \(K^{\#}\) in \(\mathsf{PSPACE}\). For instance, if we know in advance that at each level of modal depth formulas in the scope of a #-modality are mutually unsatisfiable, then we do not need to consider all the conjunctions \(conj_{w}\): all \(conj_{w}\) are 0 except \(conj_{10\ldots 0}\), \(conj_{010\ldots 0}\), \(...\), \(conj_{0\ldots 01}\). We keep a linear program polynomial in \(|\varphi|\). Bounded the number of modalities.If we artificially make the syntactic restriction where we bound the number \(n\) of #\(\varphi\) at each level, the satisfiability problem is also in \(\mathsf{PSPACE}\). Indeed, \(n\) becomes a constant, thus \(2^{n}\) is a constant too. The size of \(S\) is only polynomial in the size of \(\varphi\). Bounded branching.Many graphs have bounded branching: grid graphs (of degree 4), sparse networks, etc. If we ask whether a formula is satisfiable in a graph whose degree is bounded by a polynomial in the size of the input, then only a polynomial number of variables \(x_{w}\) will be non-zero. The algorithm is then adapted by guessing the polynomial-size subset of variables \(x_{w}\) that are non-zero. Again, we can run the algorithm in polynomial space. Proposition 2: _Let \(k>0\) be an integer. The satisfiability problem of \(K^{\#}\) restricted to graphs of degree at most \(k\) is \(\mathsf{PSPACE}\)-complete._ Proof: \(\mathsf{PSPACE}\)-membership comes from the discussion above. \(\mathsf{PSPACE}\)-hardness holds because the modal logic on graphs with at most 2 successors per worlds is \(\mathsf{PSPACE}\)-hard. Write \(\Box\psi\) as #\(\neg\psi\leq 0\). Interestingly, there are fragments in which if a formula \(\varphi\) is satisfiable then \(\varphi\) is satisfiable in a model of polynomial degree in \(|\varphi|\). Consider the fragment in which inequalities in formulas are of the form #\(\psi\leq\)#\(\psi^{\prime}\) (i.e. no addition, no multiplication by a scalar). Then if there is a solution, we can at each level have an ordering #\(\psi_{1}\leq\cdots\leq\#\psi_{n}\) where some of the \(\leq\) may be strict. But then we can suppose that w.l.o.g. \(0\leq\)#\(\psi_{i+1}-\#\psi_{i}\leq 1\). It means that the number of successors of each \(\psi_{i}\) is \(O(i)\); the number of successors is \(O(n^{2})\). We get: Proposition 3: _The satisfiability problem of \(K^{\#}\) is \(\mathsf{PSPACE}\)-complete when inequalities in formulas are of the form #\(\psi\leq\)#\(\psi^{\prime}\)._ Proof: \(\mathsf{PSPACE}\)-membership comes from the discussion above. \(\mathsf{PSPACE}\)-hardness comes from the fact modal logic K is reducible to it. Write \(\Box\psi\) as #\(\top\)\(\leq\)#\(\psi\). ## 6 Related work Many works combine modal logic and quantitative aspects: counting ([1], [9]), probabilities [20]. Linear programming and modal logic have already been combined to solve the satisfiability problem of graded/probabilistic modal logic [21]. Our logic \(K^{\#}\) can be seen as a'recursification' of the logic used in [17]. They allow for counting successors satisfying a given feature, and not any subformula. Interestingly, they allow for counting also among all nodes in the graph (sort of counting universal modality). Their logic is proven to be undecidable by reduction from the Post correspondence problem. Contrary to our setting, they use their logic only to characterize labelled graphs, but not to give a back and forth comparison with the GNN machinery itself. Modal logic has also been combined with neural network in the so-called _Connectionist modal logic_[5] but it has no direct connection with GNNs. Another solution would be to use directly explainable GNN such as those in [12]. This is of course a deep debate: using models easy to use for learning, versus interpretable models [15]. The choice depends on the target application. Yuan et al. [24] provide a survey on methods used to provide explanations for GNNs by using black-box techniques. According to them, they are instance-level and model-level explanations. Instance-level explanations explain on why a graph has been recognized by an GNN; model-level ones how a given GNN works. For instance, they are also many methods based on Logic Explained Networks and variants to generate logical explanation candidates \(\varphi\)[2]. Once a candidate is generated we could imagine use our problem P1 (given in the introduction) to check whether \([[A]]=[[\varphi]]\), and thus being able to fully synthesize a trustworthy explanation. Our paper is clearly close to model-level explanations. ## 7 Perspectives We aim at considering a larger class of GNNs. This will need to augment the expressivity of the logic, for instance by adding reLU in the language. Fortunately SMT solvers have been extended to capture reLU [11]. Another possible direction would be to consider other classes of graphs. For instance, reflexive, transitive graphs. Restricted types of graphs lead to different modal logics: \(KT\) (validities on reflexive Kripke models), \(KD\) (on serial models), \(S4\) (reflexive and transitive models), \(KB\) (models where relations are symmetric), \(S5\) (models where relations are equivalence relations), etc. [4] The logic \(K^{\#}\) defined in this paper is the counterpart of modal logic K with linear programs. In the same way, we could define \(KT^{\#}\), \(S4^{\#}\), \(S5^{\#}\), etc. For instance, \(KB^{\#}\) would be the set of validities of \(K^{\#}\)-formulas over symmetric models; \(KB^{\#}\) would be the logic used when GNNs are only used to recognize undirected pointed graphs (for instance persons in a social network where friendship is undirected). In the future work, some connections between GNNs and logics designed to express properties over persons in social network, such as [19] could be investigated. A next direction of research would be to build a tool. The main difficulty is the complexity of the algorithm. However, we may rely on heuristics to guide the search (namely SAT solvers for computing only the relevant Hintikka sets, and relaxed linear programs). We could also directly use SMT solvers. Of course, our Saint-Graal is the synthesis of a formula that matches a specification. This problem is close to the formula synthesis problem presented in [14]. An idea would be to represent the set of possible suitable explanation formulas by a grammar \(G\) (for instance, the grammar restricted to graded modal logic) and to compute a formula generated by \(G\) which is equivalent to \(tr(A)\).
2306.07308
Self-Supervised Hyperspectral Inpainting with the Optimisation inspired Deep Neural Network Prior
Hyperspectral Image (HSI)s cover hundreds or thousands of narrow spectral bands, conveying a wealth of spatial and spectral information. However, due to the instrumental errors and the atmospheric changes, the HSI obtained in practice are often contaminated by noise and dead pixels(lines), resulting in missing information that may severely compromise the subsequent applications. We introduce here a novel HSI missing pixel prediction algorithm, called Low Rank and Sparsity Constraint Plug-and-Play (LRS-PnP). It is shown that LRS-PnP is able to predict missing pixels and bands even when all spectral bands of the image are missing. The proposed LRS-PnP algorithm is further extended to a self-supervised model by combining the LRS-PnP with the Deep Image Prior (DIP), called LRS-PnP-DIP. In a series of experiments with real data, It is shown that the LRS-PnP-DIP either achieves state-of-the-art inpainting performance compared to other learning-based methods, or outperforms them.
Shuo Li, Mehrdad Yaghoobi
2023-06-12T13:48:37Z
http://arxiv.org/abs/2306.07308v3
# Self-Supervised Hyperspectral Inpainting with the Optimisation inspired Deep Neural Network Prior ###### Abstract Hyperspectral Image (HSI)s cover hundreds or thousands of narrow spectral bands, conveying a wealth of spatial and spectral information. However, due to the instrumental errors and the atmospheric changes, the HSI obtained in practice are often contaminated by noise and dead pixels(lines), resulting in missing information that may severely compromise the subsequent applications. We introduce here a novel HSI missing pixel prediction algorithm, called Low Rank and Sparsity Constraint Plug-and-Play (LRS-PnP). It is shown that LRS-PnP is able to predict missing pixels and bands even when all spectral bands of the image are missing. The proposed LRS-PnP algorithm is further extended to a self-supervised model by combining the LRS-PnP with the Deep Image Prior (DIP), called LRS-PnP-DIP. In a series of experiments with real data, It is shown that the LRS-PnP-DIP either achieves state-of-the-art inpainting performance compared to other learning-based methods, or outperforms them. Hyperspectral Imaging, Image Inpainting, Plug and Play Denoiser, Self-Supervised Learning. ## I Introduction In hyperspectral imagery, sensor failures and malfunctions of the HSI acquisition system may result in missing pixels/lines or some spectral bands, significantly hindering the subsequent processing of observed HSI [1]. Hyperspectral inpainting is the task of filling in the missing areas with plausible contents. However, the inpainting of HSIs is a more challenging task than RGB images as each pixel to be filled in is a complex vector with rich spatio-spectral information. Traditional methods such as [2, 3, 4] and [5] either fail when the whole spectral bands of pixels are missing, or their performance is severely compromised if there are a large number of missing pixels. In this work, we treat hyperspectral inpainting as a special case of the reconstruction problem, whose objective is to recover the ground truth from the degraded/masked incomplete images. The low rankness and sparsity of the underlying clean HSI are used here as the priors during reconstruction. The sparse representation (SR) and low rankness (LR) priors have been successfully applied in a wide range of hyperspectral imaging applications such as classification [6], denoising [7], and un-mixing [8]. Recently, researchers have found that the missing spectrum of the HSIs can be predicted through learning on a large dataset [9] or learning from the image itself [10]. The latter is an extension of the Deep Image Prior (DIP) [11] applied to HSIs, achieving the state-of-the-art performance. In [11], authors reveal that the structure of a generative network is sufficient to capture plenty of low-level image statistics prior to any learning. The well-designed CNN networks have been tested on a wide range of tasks such as image denoising, super-resolution and image inpainting, showing promising results which are even competitive to the state-of-the-art deep models trained on large datasets. The "free of external training data" property of the DIP, makes it well-suited for HSI inpainting. The very recent works in [12, 13] raised the point that some trained or untrained neural networks can be directly plugged into the iterative solver to achieve better reconstruction accuracy. Keeping this Plug-and-Play (PnP) idea in mind, one may design a better HSI inpainting algorithm by taking advantage of both the traditional and deep learning techniques. Considering the high computational cost of end-to-end training on extensive HSI data, it is here proposed to use DIP, a self-supervised framework that is free of external training data. ### _Contribution_ This paper aims to develop an effective HSI inpainting algorithm that enjoys the specific learning capability of deep networks, called inductive bias, but does not need any external training data, i.e. self-supervised learning. Specific contributions are the following: * A novel self-supervised HSI inpainting method, called Low Rank and Sparsity Constraint Plug and play (LRS-PnP), which is presented to solve the most challenging scenarios where the whole spectral bands are missing. * The use of deep neural networks in replacing the rank constrained-optimisation problem, showing the potential of DIP in learning intrinsic low-rank characteristics of the HSIs. * A deep hyperspectral prior-based model which better exploits the intrinsic characteristics of HSI data, for achieving state-of-the-art performance. * Extensive experiments on real data to verify the superiority of proposed LRS-PnP and LRS-PnP-DIP algorithms over existing inpainting solutions. The rest of paper is organized as follows: section II introduces the proposed framework, section III provides the implementation details and experimental setups, in section IV, the results are discussed. Finally, section V concludes the paper. ## II Proposed Method The HSI inpainting task can be interpreted as the reconstruction of the clean image \(X\) from its noisy and incomplete measurement \(Y\), in the presence of additive noise \(N\) and masking operator \(M\): \[Y=M\{X\}+N \tag{1}\] The clean image \(X\in\mathbb{R}^{q}(q=n_{r}\times n_{c}\times n_{b})\), where \(n_{r},n_{c}\) are the spatial dimension of image, and \(n_{b}\) stands for the total numbers of spectral bands. The operator \(M:\mathbb{R}^{q}\rightarrow\mathbb{R}^{q}\) is the binary mask, with 0 representing the missing pixel and 1 representing the observed and valid pixel. Therefore \(M\) can be presented with a diagonal matrix that has only one per row, which we note it by \(\mathrm{M}\). \(N\) is the additive Gaussian noise of appropriate size. Specifically, \(M\) is often given. The formulation (1) is a linear system which can be written as: \[\mathbf{y}=\mathrm{M}\mathbf{x}+\mathbf{n} \tag{2}\] Where \(\mathbf{x},\mathbf{y},\mathbf{n}\) are the vectorized forms of \(X,Y,N\), respectively, and \(\mathrm{M}\) is a diagonal matrix. We first introduce an operator \(P_{i}(\mathbf{x})\) that extracts each i-th patch from the image \(\mathbf{x}\). \(P_{i}(\mathbf{x})\) may cover only the valid pixels or may include the missing pixels depending on the size of \(P_{i}(\cdot)\). We apply the sparse representation on each image patch \(P_{i}(\mathbf{x})\). The inpainted image \(\mathbf{x}^{\star}\) can be obtained by solving the following optimization problem: \[\begin{split}(\mathbf{x}^{\star},\mathbf{\alpha}^{\star})=& \operatorname*{argmin}_{\mathbf{x},\mathbf{\alpha}}\gamma\|\mathbf{y}-\mathrm{M}\mathbf{x}\|_ {2}^{2}+\mathrm{w}_{\mathrm{lr}}\|\mathbf{x}\|_{*}+\mathrm{w}_{\mathrm{s}}\|\mathbf{ \alpha}\|_{1}\\ &\text{s.t.}\quad\mathbf{x}=\Phi\mathbf{\alpha}\end{split} \tag{3}\] The first term is the data fidelity term, which we weigh with the parameter \(\gamma\). Due to the ill-posed nature of estimating \(\mathbf{x}\) from \(\mathbf{y}\) only using data fidelity term, the solution is often not unique. For this reason, we introduce another two "priors" to regularize the inpainting problem, namely low rank and sparsity constraints. The second term penalizes the solution \(\mathbf{x}\) to be of low rank, which is often used as the surrogate for the rank minimization problem. The third term constrains the missing pixels to be generated from the subspace approximated by the valid pixels. Similarly, we weigh these two terms with parameters \(w_{lr}\) and \(w_{s}\). The sparse representation problem is solved with a known dictionary \(\Phi\) that is learned only from the noisy and incomplete pixels, or it is a sparsifying transform. By adopting the augmented Lagrangian and introducing the auxiliary variable \(\mathbf{u}\)[14], problem (2) can be rewritten as: \[\begin{split}(\mathbf{x}^{\star},\mathbf{\alpha}^{\star})=& \operatorname*{argmin}_{\mathbf{x},\mathbf{\alpha}}\gamma\|\mathbf{y}-\mathrm{M}\mathbf{x}\|_ {2}^{2}+\mathrm{w}_{\mathrm{lr}}\|\mathbf{u}\|_{*}+\mathrm{w}_{\mathrm{s}}\sum_{ \mathrm{i}}\|\mathbf{\alpha}_{\mathrm{i}}\|_{1}\\ &+\frac{\mathbf{\mu}_{1}}{2}\|\sum_{i}(P_{i}(\mathbf{x})-\Phi\mathbf{\alpha}_{ i})+\frac{\mathbf{\lambda}_{1}}{\mathbf{\mu}_{1}}\|_{2}^{2}\\ &\text{s.t.}\quad\mathbf{x}=\mathbf{u}\end{split} \tag{4}\] Where \(\mathbf{\lambda}_{1}\) and \(\mathbf{\mu}_{1}\) are the Lagrangian multiplier and penalty term, respectively. With the help of the alternating direction method of multipliers (ADMM), problem (4) can be solved by the sequential updates of three variables: \(\mathbf{\alpha}\), \(\mathbf{u}\) and \(\mathbf{x}\). 1) _Fixing \(\mathbf{u}\) and \(\mathbf{x}\), and updating \(\mathbf{\alpha}\)_: \[\begin{split}\mathbf{\alpha}^{k+1}=\operatorname*{argmin}_{\mathbf{\alpha }}\frac{\mathbf{\mu}_{1}^{k}}{2}\sum_{i}\|(P_{i}(\mathbf{x}^{k})+\frac{\mathbf{\lambda}_{1} ^{k}}{\mathbf{\mu}_{1}^{k}})-\Phi\mathbf{\alpha}_{i}\|_{2}^{2}\\ +w_{s}\sum_{i}\|\mathbf{\alpha}_{i}\|_{1}\end{split} \tag{5}\] which is a patched-based sparse coding problem which can be solved using iterative solvers. In our algorithm, we adopt the PnP-ISTA [15], which has shown promising results over conventional ISTA [16]. Denote the first term in equation (5) as \(f=\frac{\mathbf{\mu}_{1}^{k}}{2}\sum_{i}\|(P_{i}(\mathbf{x}^{k})+\frac{\mathbf{\lambda}_{1 }^{k}}{\mathbf{\mu}_{1}^{k}})-\Phi\mathbf{\alpha}_{i}\|_{2}^{2}\). The whole process can then be replaced by an off-the-shelf denoiser \(\mathcal{D}\) acting on the gradient of \(f\), as it is proposed in [15]. Every single iterate takes the form: \[\mathbf{\alpha}^{k+1}=\mathcal{D}(I-\nabla f)(\mathbf{\alpha}^{k}) \tag{6}\] 2)_Fixing \(\mathbf{\alpha}\) and \(\mathbf{x}\), and updating \(\mathbf{u}\)_: \[\mathbf{u}^{k+1}=\operatorname*{argmin}_{\mathbf{u}}w_{lr}\|\mathbf{u}\|_{*}+\frac{\mathbf{ \mu}_{2}^{k}}{2}\|(\mathbf{x}^{k}+\frac{\mathbf{\lambda}_{2}^{k}}{\mathbf{\mu}_{2}^{k}})- \mathbf{u}\|_{2}^{2} \tag{7}\] which can be solved by the Singular Value Thresholding (SVT) algorithm. The element-wise soft shrinkage is applied to the singular value of \((\mathbf{x}^{k}+\frac{\mathbf{\lambda}_{2}^{k}}{\mathbf{\mu}_{2}^{k}})\), as follows, \[\mathbf{u}^{k+1}=SVT(\mathbf{x}^{k}+\frac{\mathbf{\lambda}_{2}^{k}}{\mathbf{\mu}_{2}^{k}}) \tag{8}\] In the proposed LRS-PnP-DIP algorithm, update step of (8) is replaced by a untrained randomized weight neural network \(f_{\theta}(\mathbf{z})\), where \(\theta\) represents the network weights to be updated, and the input \(\mathbf{z}\) is set to be \(\mathbf{x}^{k}+\frac{\mathbf{\lambda}_{2}^{k}}{\mathbf{\mu}_{2}^{k}}\). i,e, the latent image from the previous iterations: \[\mathbf{u}^{k+1}=f_{\theta}(\mathbf{x}^{k}+\frac{\mathbf{\lambda}_{2}^{k}}{\mathbf{\mu}_{2}^{k}}) \tag{9}\] 3) _Fixing \(\alpha\) and \(\mathbf{u}\), and updating \(\mathbf{x}\)_: \[\begin{split}\mathbf{x}^{k+1}=\operatorname*{argmin}_{\mathbf{x}}\gamma\| \mathbf{y}-\mathrm{M}\mathbf{x}\|_{2}^{2}+\sum_{\mathrm{i}}\|(\mathrm{P}_{\mathrm{i}}( \mathbf{x})+\frac{\mathbf{\lambda}_{1}^{k}}{\mathbf{\mu}_{1}^{k}})-\Phi\mathbf{\alpha}_{1}^{ \mathrm{k}+1}\|_{2}^{2}\\ +\frac{\mathbf{\mu}_{2}^{k}}{2}\|(\mathbf{x}+\frac{\mathbf{\lambda}_{2}^{k}}{ \mathbf{\mu}_{2}^{k}})-\mathbf{u}^{k+1}\|_{2}^{2}\end{split} \tag{10}\] Closed-form solution for \(\mathbf{x}\) exists as follows: \[\begin{split}\mathbf{x}^{k+1}=(\gamma\mathrm{M}^{\mathrm{T}}\mathrm{M} +\mathbf{\mu}_{1}^{k}\sum_{\mathrm{i}}\mathrm{P}_{\mathrm{i}}^{\mathrm{T}}\mathrm{P }_{\mathrm{i}}+\mathbf{\mu}_{2}^{k}\mathrm{I})^{-1}\\ (\gamma\mathrm{M}^{\mathrm{T}}\mathbf{y}+\mathbf{\mu}_{1}^{k}\sum_{ \mathrm{i}}\mathrm{P}_{\mathrm{i}}\Phi\mathbf{\alpha}_{1}^{\mathrm{k}+1}+\mathbf{\mu}_{2 }^{k}\mathbf{u}^{k+1}-\sum_{\mathrm{i}}\mathrm{P}_{\mathrm{i}}\mathbf{\lambda}_{1}^{k} -\mathbf{\lambda}_{2}^{k}\mathrm{I})\end{split} \tag{11}\] 4) _Lagrangian and penalty terms updating_: \[\begin{split}\mathbf{\lambda}_{1}^{k+1}=\mathbf{\lambda}_{1}^{k}+\mathbf{\mu}_{ 1}^{k}(\mathbf{x}^{k+1}-\Phi\mathbf{\alpha}^{k+1})\\ \mathbf{\lambda}_{2}^{k+1}=\mathbf{\lambda}_{2}^{k}+\mathbf{\mu}_{2}^{k}(\mathbf{x} ^{k+1}-\mathbf{u}^{k+1})\end{split} \tag{12}\] \[\mathbf{\mu}_{1}^{k+1} =\mathbf{\rho}_{1}\mathbf{\mu}_{1}^{k} \tag{13}\] \[\mathbf{\mu}_{2}^{k+1} =\mathbf{\rho}_{2}\mathbf{\mu}_{2}^{k}\] The proposed Low-Rank and Sparsity Plug-and-Play (LRS-PnP) inpainting model is presented in Algorithm 1. ``` 0: masking matrix: \(\mathrm{M}\), noisy and incomplete HSI: \(\mathbf{y}\), learned dictionary: \(\Phi\). denoiser: \(\mathcal{D}\), max iteration: \(It_{max}\). 0:implanted HSI image \(X\). 1:Initialization:\(\mathbf{\lambda}_{1},\mathbf{\lambda}_{2},\mathbf{\mu}_{1},\mathbf{\mu}_{2},\mathbf{\rho}_{1}, \mathbf{\rho}_{2}\). 2:while Not Converged do 3: for \(i=1:It_{max}\) do: \(\mathbf{\alpha}^{k+1}=\mathcal{D}(I-\nabla f)(\mathbf{\alpha}^{k})\) 4:\(\mathbf{u}^{k+1}=SVT(\mathbf{x}^{k}+\frac{\mathbf{\lambda}_{2}^{k}}{\mathbf{\mu}_{2}^{k}})\) 5: update \(\mathbf{x}\) by ((11)). 6: update Lagrangian parameters and penalty terms. 7:endwhile ``` **Algorithm 1** (LRS-PnP) Algorithm By replacing the SVT with DIP \(f_{\theta}\), we end up with an extension of the LRS algorithm, denote as LRS-PnP-DIP, is presented in Algorithm 2: ``` 0: masking matrix: \(\mathrm{M}\), noisy and incomplete HSI: \(\mathbf{y}\), learned dictionary: \(\Phi\). denoiser: \(\mathcal{D}\), max iteration: \(It_{max}\). DIP: \(f_{\theta}\) 0: inpainted HSI image \(\mathbf{x}\). 1:Initialization DIP parameters, \(\mathbf{\lambda}_{1},\mathbf{\lambda}_{2},\mathbf{\mu}_{1},\mathbf{\mu}_{2},\mathbf{\rho}_{1}, \mathbf{\rho}_{2}\). 2:while Not Converged do 3: for \(i=1:It_{max}\) do: \(\mathbf{\alpha}^{k+1}=\mathcal{D}(I-\nabla f)(\mathbf{\alpha}^{k})\) 4: update \(\theta\) in DIP, with the target \(\mathbf{y}\) and input \(\mathbf{x}^{k}+\frac{\mathbf{\lambda}_{2}^{k}}{\mathbf{\mu}_{2}^{k}}\). 5: update \(\mathbf{x}\) by (11). 6: update Lagrangian parameters and penalty terms. 7:endwhile ``` **Algorithm 2** (LRS-PnP-DIP) Algorithm ## III Implementation Details We test the proposed inpainting model on the Chikusei airborne hyperspectral dataset, which was taken by Headwall Hyperspec-VNIR-C imaging sensor [17]. The hyperspectral test image has 128 spectral bands, with each 36x36 pixels. The size of the dictionary \(\Phi\) is 1296x2000 which was learned only based on the noisy and incomplete HS image. All images are corrupted with Gaussian noise with the fixed noise strength \(\sigma=0.12\). The mask \(\mathrm{M}\) is applied to all the spectral bands. We use BM3D and Non-local-Mean (NLM) as the plug-and-play denoiser. The implementation of DIP follows the same structures as in Deep Hyperspectral Prior paper [10]. To prevent over-fitting in DIP, we use the early stopping criterion proposed in [18], which automatically detects the near-peak PSNR point using windowed moving variance (WMV). We set \(w_{s}/w_{lr}\) to be 1 and \(\gamma\) to be 0.5. Note that the choice of \(\gamma\) is highly related to the noise level of \(Y\). If the noise level is low, the recovered image \(X\) should be close to noisy observation \(Y\), then parameter \(\gamma\) should be large, and vice versa. For ADMM parameters, \(\lambda_{1}\) and \(\lambda_{2}\) are set to be 0, \(\mu_{1}\), \(\mu_{2}\) are set to be 1, and \(\rho_{1}\), \(\rho_{2}\) are set to be 1, meaning a fixed update step. We use Adam optimizer, and the learning rate is set to be 0.1. We adopt two widely used indicators: Mean Signal-to-Noise Ratio (MPSNR) and Mean Structural Similarity (MSSIM), to evaluate the performance in all experiments. ## IV Experimental Results The performance of proposed algorithms are compared with the existing traditional methods LRTV [3], and FastHyIn [2], and learning-based method DIP [11], DeepRED [19] and PnP-DIP [20]. The numerical results are reported in Table \(I\) and \(II\). For the DIP, DeepRED, PnP-DIP and the proposed LRS-PnP-DIP, the same U-net in [10] was used as the backbone. For the fairness of comparison, all associated parameters with U-net are kept fixed, including the noise standard deviations and regularization strength. The MPSNR and MSSIM are obtained through running algorithms for 20 times on the same test image. For comparison with FastHyIn and LRTV, 25% of the pixels were randomly masked using a uniform distribution for the missing bands. The inpainting performance is shown in Figure 1. It shows that LRS-PnP algorithm can generate a more consistent and realistic spectrum in the missing region compared to the learning-based methods. LRS-PnP captures local structures, such as a sudden change in the materials, e.g. see the first image. In contrast, methods such as DeepRED and PnP-DIP tend to generate much smoother contents in the non-missing areas. However, there are severe distortions and artefacts of the missing regions. We believe this is due to the nature of DIP which mainly focuses on learning global features and characteristics. For this reason, it is often used with other regularizers such as Total Variation (TV) to preserve more details [21]. It is worth mentioning that the inpainting result of the double deep prior algorithm LRS-PnP-DIP is visually and qualitatively better than those of other inpainters. ## V Conclusion The novel hyperspectral inpainting algorithms called LRS-PnP and its extension self-supervised LRS-PnP-DIP which can effectively handle missing pixels from noisy and incomplete HS images in the most challenging scenario where the whole spectrum bands are missing. The new methods exploit spectral and spatial redundancy of HSIs and require no training data except, the test image. A comparison of LRS-PnP and LRS-PnP-DIP with the state-of-the-art algorithms is conducted on a real HS image, leading to the conclusion that LRS-PnP yields similar while LRS-PnP-DIP yields better performance against other learning-based methods, while not using a pre-training step using a large set of HS images. As the future work, one direction is to accelerate the proposed algorithms to achieve a cost-efficient and real-time HSI inpainting. Another direction of interest is to explore and optimize the training of DIP, especially when it is used in the loop, as mentioned in a lines of DIP-related works [12, 13, 20, 22, 23]. The other direction is to theoretically show the convergence of the algorithm, which we left for a future work.
2307.03910
A Survey of Spiking Neural Network Accelerator on FPGA
Due to the ability to implement customized topology, FPGA is increasingly used to deploy SNNs in both embedded and high-performance applications. In this paper, we survey state-of-the-art SNN implementations and their applications on FPGA. We collect the recent widely-used spiking neuron models, network structures, and signal encoding formats, followed by the enumeration of related hardware design schemes for FPGA-based SNN implementations. Compared with the previous surveys, this manuscript enumerates the application instances that applied the above-mentioned technical schemes in recent research. Based on that, we discuss the actual acceleration potential of implementing SNN on FPGA. According to our above discussion, the upcoming trends are discussed in this paper and give a guideline for further advancement in related subjects.
Murat Isik
2023-07-08T06:02:12Z
http://arxiv.org/abs/2307.03910v1
# A Survey of Spiking Neural Network Accelerator on FPGA ###### Abstract Due to the ability to implement customized topology, FPGA is increasingly used to deploy SNNs in both embedded and high-performance applications. In this paper, we survey state-of-the-art SNN implementations and their applications on FPGA. We collect the recent widely-used spiking neuron models, network structures, and signal encoding formats, followed by the enumeration of related hardware design schemes for FPGA-based SNN implementations. Compared with the previous surveys, this manuscript enumerates the application instances that applied the above-mentioned technical schemes in recent research. Based on that, we discuss the actual acceleration potential of implementing SNN on FPGA. According to our above discussion, the upcoming trends are discussed in this paper and give a guideline for further advancement in related subjects. Neural Networks, Spiking Neural Network, FPGA Implementation, Hardware Accelerator, Survey. ## I Introduction Spiking Neural Network (SNN) has been one of the most extensive research subjects in recent decades. Researchers successfully deployed the related instances in various application scenarios, such as speech recognition, biomedical analysis, and self-driving cars. SNNs are inspired by the biological neural system with the understanding of brain functionalities. The related works are more biologically plausible in both information transmission across neurons and internal neuron signal processing. Therefore, this technique causes a paradigm shift in the field of neural network research. The goal of SNNs is to develop a computational system modeling the behavior of real neurons. However, the complexities of the network model and corresponding computation requirements in SNN inference are rapidly increasing. The trade-off between hardware and power consumption and acceleration performance has become a research topic of importance. This leads to an actual requirement for customized hardware accelerators to achieve higher computing/power efficiency, especially for embedded and lightweight applications. Recent research shows that SNNs have the following excellent hardware implementation features: SNNs communicate across neurons using spikes, which are equivalent to a single bit in terms of logic resources and decrease the logic occupation. Therefore, _Field Programmable Gate Arrays_ (FPGAs) become a potential hardware platform for SNN acceleration, based on its features of logic reconfigurability, high power efficiency, and support of computing parallelization and bit-level operations. Recent research has deployed SNNs on different platforms, such as _Central Processing Units_ (CPUs), _Graphics Processing Units_ (GPUs) and _Application-Specific Integrated Circuits_ (ASICs). However, due to the restricted memory bandwidth, SNNs on CPU/GPU consume high power overhead with limited throughput [1, 2]. To achieve the best performance and energy efficiency, many researchers have focused on building custom ASICs for accelerating network inference workloads. Despite being an attractive solution, ASICs cannot offer sufficient flexibility to accommodate the rapid evolution of _Neural Network_ (NN) models. The emergence of new types of layers within NN, including branching, elementwise addition, and batch normalization layers, has been seen in more recent models that require flexibility. Further, the high _Non-Recurring Engineering_ (NRE) cost and time for design, verification, and fabrication of a large ASIC chip make it difficult to keep pace with the rapid model improvements in this space [3]. Consequently, FPGAs serve as configurable tools, facilitating the creation of unique logic, which may mitigate the limitations on the execution of neural networks. As an outcome, due to the apparent benefits of the SNN on hardware implementation, one of the current research hotspots is the development of hardware systems supporting SNN inference based on FPGA to achieve high throughput and power efficiency [4]. ### _Contributions of Our Survey_ In this manuscript, we survey the upcoming techniques of FPGA-based SNN accelerators and its application instance in various scenarios. The major contributions of our survey are as follows: * We categorize the widely-used spiking neuron models, spiking signal format, currently explored SNNs, SNN training tools, etc. * Based on the above-mentioned background, we survey the feasible techniques for hardware design of SNN accelerator on FPGA and analyze the difficulties in the implementation, including accelerator architectures, optimization, and upcoming solutions. * We enumerated the related application-based SNN acceleration on FPGA. * We examine the research trends and optimization directions in developing FPGA-based SNN accelerators based on the above works. ### _Organization_ This manuscript is structured as following **Section II** introduces the technology background of _Spiking Neural Networks_. **Section III** discusses the popular implementations and solutions for SNN accelerators on FPGA in recent works. **Section IV** briefly emulates the previous FPGA applications in different scenarios based on SNN. **Section V** analyzes the trend of further work and upcoming research for the SNN accelerator on FPGA. **Section VI** concludes the survey. ## II Background ### _Coding Formats of Spiking Signals_ In recent artificial intelligence research, spiking neural networks have become a state-of-the-art topic for further modeling the working principle of bio-neural systems. Therefore, the input data need to be encoded into a spiking signal format. For instance, Figure 1 shows five most popular spiking coding formats in recent research [5, 6]: * _Rate Coding Format:_ Rate coding is the most widely-used format in related works. This format converts the input value to a Poisson spiking train with the corresponding fire rate. As shown in Figure 1a, larger input can be represented as the spiking train with a higher fire rate. * _Time-to-first Spiking Coding Format: Time-to-first Spiking Coding_ is a kind of temporal coding method. Instead of using fire rate to represent different inputs value, Time-to-first coding applies the fire latency in a stimulus duration to convert data as a spike. As shown in Figure 1b, the spike of larger input will be fired earlier. Compared with the rate coding format, time-to-first coding only requires a single spike, data information will be encoded in the temporal latency. * _Phase Coding Format:_ Above two coding methods need a conversion between data value and fire rate/latency. Different conversion solutions will influence the encoded spike trains. As shown in Figure 1c, work [7] explored another spiking encoding method that directly converts the binary format of input value as the spike train. The weight spike in this work will represent the significance of each input bit. * _Burst Coding Format:_ To reduce the transmission duration of spiking signal, work [8][9] explored a burst transmission encoding method as shown in Figure 1d. This method encodes the input value as the number of spikes and the inter-spike interval (ISI) in the burst. More intensive spikes in burst represent a larger input. * _Rank Order Coding Format:_ Figure 1d shows the scheme of _Rank Order Coding_[10]. Instead of applying the spikes latency in stimulus to encode the inputs like _Time-to-first Spiking Coding_ scheme, this encoding method encodes the input information as the spikes fire order ignoring the fire latency. Therefore, for \(N\) pre-neurons, their outputs can be encoded as \(2^{N}\) different data. ### _Spiking Neuron Modelling and the Differences with Classic ANN Neuron_ #### Ii-B1 Spiking Neuron Modelling A bio-inspired artificial intelligence technology called SNN has become a state-of-the-art technology in recent years. Therefore, the implementations of spiking neurons also mimic the actual natural neural cells. Based on the cell structure modelling, there are three widely-explored spiking neuron models on FPGA accelerator implementations: i) _Hodgkin-Huxley (HH) Model_[11], ii) _Izhikevich Model_[12], iii) _Leaky Integrate-and-Fire Model_ (LIF) [13][14]. * _Hodgkin-Huxley (HH) Model:_ This model simplified the neural cell structure as a RC circuit model as shown in Figure 2. In this model, \(C\) represents the capacity of the cell membrane. \(R_{K}\) and \(R_{Na}\) mimic the sodium and potassium ion channels in neurons. \(R_{Leaky}\) simulates the leaky channel to lose the charge in the membrane. Therefore, Equation 1 \[\begin{split} I\left(t\right)=I_{C}\left(t\right)+I_{K}\left(t \right)+I_{Na}\left(t\right)+I_{Leaky}\left(t\right)\\ \Rightarrow C\frac{\mathrm{d}U}{\mathrm{d}t}=I\left(t\right)-I_{K} \left(t\right)-I_{Na}\left(t\right)-I_{Leaky}\left(t\right)\end{split} \tag{1}\] Because the conductance of ion channels in this model is simulated as the function of time and voltage, Equation 1 will be rewritten as: Fig. 1: Five popular spiking coding formats Fig. 2: RC Circuit Modelling of Hodgkin-Huxley Spiking Neuron Model \[I\left(t\right) =C\frac{\mathrm{d}U}{\mathrm{d}t}+g_{K}n\left(t,U\right)^{4}\cdot \left(U-U_{K}\right) \tag{2}\] \[\quad+g_{Na}m\left(t,U\right)^{3}h\left(t,U\right)\cdot\left(U-U_{ Na}\right)\] \[\quad+g_{Leaky}\left(t\right)\cdot\left(U-U_{K}\right)\] \[\begin{cases}\frac{\mathrm{d}n\left(t,U\right)}{\mathrm{d}t}= \alpha_{n}\left(U\right)\cdot\left(1-n\left(t,U\right)\right)-\beta_{n}\left( U\right)\cdot n\left(t,U\right)\\ \frac{\mathrm{d}m\left(t,U\right)}{\mathrm{d}t}=\alpha_{m}\left(U\right) \cdot\left(1-m\left(t,U\right)\right)-\beta_{m}\left(U\right)\cdot m\left(t,U \right)\\ \frac{\mathrm{d}h\left(t,U\right)}{\mathrm{d}t}=\alpha_{h}\left(U\right) \cdot\left(1-h\left(t,U\right)\right)-\beta_{h}\left(U\right)\cdot h\left(t,U \right)\\ \end{cases}\] \[\begin{cases}\alpha_{i}\left(U\right)=p_{\infty}\left(U\right)/\tau_{p} \\ \beta_{i}\left(U\right)=(1-p_{\infty}\left(U\right))/\tau_{p}\end{cases}\] In Equation 2, \(n\), \(m\), and \(h\) are the conductance parameters for sodium and potassium ion channels, \(p\) represent the steady state values for activation. * _Izhikevich Model:_ Considering the parameters and complex computing in Equation 2, work [12] simplified the HH model based on bifurcation methodologies as Equation 3 to reduce the number of parameters. \[v^{\prime} =0.04v^{2}+5v+140-u+I\] (3) \[u^{\prime} =a(bv-u)\] \[if\quad v\geq 30mV,\quad then\quad\begin{cases}v\gets c \\ u\gets u+d\end{cases}\] In Equation 3, \(v\) implies the membrane potential (input). \(u\) means recover parameter. \(a\) means how fast the membrane potential recovers, the typical value is 0.02. \(b\) means the responsibility between \(u\) and input \(v\), typical value is 0.2. \(c\) means the reset potential after spiking, the typical value is \(-65mV\). \(d\) means the increase value of \(u\) after reset, typical value is \(2mV\)[15]. * _Leaky Integrate-and-Five Model:_ To further simplify the spiking neuron model, authors in [13, 14] discussed the simplification of the HH model as _Leaky Integrate-and-Fire_ (LIF) model, which has been the most widely-used model in recent research. As shown in Figure 3, LIF further simplified the HH model, the RC modeling formula is Equation 4: \[C\frac{\mathrm{d}U}{\mathrm{d}t}=I\left(t\right)-\frac{V-V_{rest}}{R}\] (4) #### Ii-B2 Brief introduction of SNN Neurons hardware implementation Figure 4 shows the structure of neuron processing elements in SNNs hardware implementation. For SNN, when networks apply different neuron models and signal encoding schemes, the structures of neuron processing elements will be different. For instance, in the implementations based on LIF model and rate coding schemes, the neurons can consist of the following submodules: 1) _Multiplier_, 2) _Accumulator_, 3) _Thresholds_, and 4) _Spiking Encoder_: * _Multiplier_ and _Accumulator_ compute the product sum of weighted spikes based on different data formats. However, storing network weights consumes a large number of on-chip memory resource on FPGA. Considering the limitation of hardware resources, in addition to the common floating-point and fixed-point formats, some low-precision data formats are widely explored in recent research, such as i) _Quantization_, ii) _Binarization_, iii) _Approximation Computation_, and iv) _Posit-floating Computation_: The authors of _Q-SpiNN_[16] and work [17] implemented a _Quantized Spiking Neural Network_ (QSNN) framework to reduce the memory consumption of network weights based on the low-precision integer scheme. Moreover, work _BS4NN_[18] and work [19] further reduced the weight precision to the _Binarized Spiking Neural Network_ (BSNN). Work _AxSNN_[20] explored the application of approximation computation on SNN. The authors of [21] researched the possibility of applying _Posit_-floating computation [22, 23] on FPGA-based SNN accelerators. * _Thresholds and Spiking Encoding_: As shown in Figure 4, the parameters of thresholds will be the leaky rate, refractory time, fire thresholds, etc. For some coding schemes, such as _Phase Coding_, the encoding module will be necessary. More technique details about the spiking neuron implementation will be discussed in Section III. ### _SNN Model Training and Conversion Tools_ The simulation and evaluation of SNN accelerator implementations on FPGA require trained models. However, Fig. 4: Neuron Structure of Spiking Neural Networks Fig. 3: RC Circuit Modelling of Leaky Integrate-and-Fire Spiking Neuron Model because of the difference between SNN and classic ANN, SNN training is still a challenge in recent research and limits the application of SNNs. Some upcoming toolkits support the SNN model generation-based conversion from trained ANN models or directly SNN training. #### Ii-A1 ANN Model Conversion Because of the difficulties in synaptic weight learning on SNN training, some works explored the solution that converts an ANN model to SNN. _Spiking Neural Network Conversion Toolbox_[24] implemented one python-based conversion tool from ANN to SNN supporting various ANN training libraries, such as _Keras_, _PyTorch_, _Caffe_, etc. It also supports the SNN model export for evaluation based on SNN simulation tools, like _pyNN_[25], _Brain2_[26], _sPyNNaker_[27], etc. #### Ii-A2 SNN Model Training Compared with the ANN conversion, direct training of SNN can achieve higher accuracy. Some researchers explored the related SNN training algorithms [28, 29, 30]. Based on previous works, snnTorch [31] implemented a PyTorch-based SNN training acceleration library. This library supports the training of _Spiking Convolution Neural Network_ (SCNN) and _Spiking Long-Short Term Memory Network_ (SLSTM) based on the LIF neuron model and rate/latency coding. The training based on this work can also be accelerated by applying the GPU platform through PyTorch. ## III Techniques ### _Topology Conversion_ Spiking neural networks are biologically inspired _Artificial Neural Networks_ (ANN), which are more power-efficient, but the discrete nature of the spikes makes it difficult to train an SNN. Thus, much work has been done to convert the topology of a trained network from ANN or CNN to SNN while copying the trained weights and adjusting the spiking threshold potential in SNN. In one such work [32], Deng et al. analyze the ANN to SNN conversion error and propose a method to transfer weights with no loss of accuracy. The authors modify the ReLU function on the source ANN by thresholding the maximum activation and reducing the simulation time to 1/10th of a typical SNN simulation time. Followed by a shifting operation to balance the output frequency is termed as the threshold balancing mechanism [33]. The ANN-SNN conversion techniques have managed to achieve deeper architectures but most of these techniques are based on the assumption that spike patterns of SNN a time-sampled ANN. Thus, the temporal properties of SNN are ignored. Some training algorithms like _Backpropagation Through Time_ (BPTT) could solve this by training through time but it introduces vanishing gradients. Samadzadeh et al. in [34] instead initialize the weights with non-spiking training data. For the first few epochs, the SNN is trained like an ANN where the output activation function is changed to leaky ReLU. After which the activation function is modeled as a step function with the LIF neuron. By utilizing the skip connections in _ResNet_ architecture a _Spiking ResNet_ (STS-ResNet) architecture is proposed for testing the conversion accuracy and temporal feature extraction on _CIFAR10-DVS_, _NMNIST_ and _DVS-Gesture_. The spatial and temporal properties of the SNN can be preserved to a greater extent with the use of recurrent convolution SNN. A sampling window in recurrent architecture captures the temporal correlations in event-based sequences. In [35], Xing et al. use a supervised _Spike Layer Error Reassignment_ (SLAYER) training mechanism for ANN-SNN conversion. The SCRNN architecture is a combination of single SCRNN cells that process input sequences separately to maintain the temporal dimension. The spatial complexity is handled with decomposed input processed in cells at every time step. Each SCRNN cell accepts an input feature map, a fused feature map of previous states, and an output feature map of the current input. Thus, the network was made recurrent and evaluated on the _Dynamic Vision Sensor_ (DVS) gesture dataset, achieving an accuracy of \(96.59\%\) for a 10-class gesture recognition task. The elimination of all matrix multiplications in SNN makes them more energy-efficient than CNN. In [36], Wu et al. develop a unified framework that supports weight normalization, threshold balancing and an _Explicit Current Control_ (ECC) method that controls the number of spikes passed to the SNN and reduces the residual membrane potential. The residual current in the neurons causes accuracy loss for shorter inference. The ECC also enables the conversion of _Batch Normalization_ (BN) layer that many of the recent works fail to include. The role of the BN layer is to normalize the previous layer's output, which accelerates the CNN's convergence. This is implemented in the conversion by a numerical constant dependent on the training platform that updates the weight and bias to a normalized version of the same. ### _Neuron models on FPGA_ A biological neuron can be implemented in either of the neuron models as discussed in section II. In [37], Juneeth et al. develop a spiking neuron model of _Hodgkin-Huxley_ on an FPGA. The hardware architecture is based on a series of adder and multiplier blocks to implement the first-order differential equations in Verilog on _Xilinx Virtex-5_. Each of the neuron parameters is represented in a fixed point with chosen bit lengths. However, the physical justification for the bit optimization strategies is inconsistent. The use of multiplier blocks increases the number of LUTs and eventually, power consumption. On the contrary, in [38], Farzin et al. propose a multiplier-less _Hodgkin-Huxley_ model. The model approximates hyperbolic functions as piece-wise linear terms implement all multiply operations as logical shifts and adds. This is made possible with equations modified to power-2-based functions. Considering the high accuracy of a HH neuron, a multiplier-less design furthermore reduces the operational cost and increases the frequency. Two simplified two-dimensional versions of the HH neuron model are the _FitzHugh-Nagumo_ and _Morris-Lecar_ neuron models [39]. In [40], Nouri et al. investigate the _FitzHugh-Nagumo_ neuron model in terms of its digital implementation feasibility and computation overhead. The model is a cubical approximation with no auxiliary reset equations. The area and power numbers of the proposed design with _Euler_ discititization are lower than a HH model apparatus. In [41], Mellal et al. study the behavior of the Morris-Lecar neuronal model on a _Xilinx Zynq UltraScale+_ board. The simulated and hardware results of the original and discrete implementations have a high correlation. One of the basic building blocks of the human body is the _Central Nervous System_ comprised of neurons, synapses, and glial cells. In [42], Abdulaziz et al. evaluate a model based on its complexity and hardware resources required to realize it on an FPGA. The two-neuron coupled _Izhikevich_ model while satisfying the above parameters regenerates all the different dynamics of the human brain. The authors use a LUT-based approach to the quadratic equations instead of an approximation technique to replace the non-linear terms. As the size of the LUT increases to 1000 points the model becomes closer to the mathematical equations. Another unique technique involving the _Izhikevich_ neuron model is discussed in [43]. According to the authors, the _Izhikevich_ neuron is practically more suitable for electrical realization due to its chaotic behavior. A modified version of the model is compared with the original coupled neuron dynamics through numerical simulations and FPGA device demonstration. The modified model has a longer processing time (2 clock cycles) but with no multiplier usage. This design characteristic has significantly reduced the utilization number while maintaining the accuracy of the model. Along with the spinal network these neuron models have been altered for use. In [44], Niu et al. the motoneurons in the motor nervous system are emulated with the _Izhikevich_ model on an FPGA to analyze pediatric neurological diseases. In [45], Panchapakesan et al. proposed a novel synchronous SNN execution divided into layers for each input, hidden, and output layers. The input is executed layer-by-layer as shown in Figure 5 synchronously to avoid frequent off-chip memory communication. Further, the internal parameters like membrane potential can be immediately used, reducing the on-chip resources utilized. Each layer is composed of modules that implement the functionality of integrating and fire neuron structure as discussed in section II. Such layer network depiction can also be observed in [46]. Khodamoradi et al. propose a streaming SNN accelerator architecture that utilizes the concept of layer modules for generating output spikes. However, this architecture is made more specific to edge devices with sparse input data. Highly sparse events can still utilize significant memory to store null information. This is mitigated with the use of binary tensors as input buffers. The hardware layer network is also observed in [47] where Fang focuses their work to retain the temporal information in a sequence of spikes in the architecture. The leaky integrate and fire neuron-based hardware avails a series of _Infinite Impulse Response_ (IIR) filters to represent SNN. The time-encoded spikes provide the time information to interpret neurons as filters. Further, the suggested model incorporates synapse dynamics adding flexibility to the system. Each layer has a processing element that updates the neuron and synapse state variables. An optimized framework of end-to-end neuromorphic systems is described with reduced inference latency. The results compared to a CPU has better performance metrics. Additionally, the LIF model has been holistically modified to several other forms. In [48], Heidarpour et al present a _CORDIC_ implementation of an _Adaptive exponential integrate and fire_ (AdEx) neuron model. The primary difference to Equation 4 is that the potential difference integrates exponentially in the current equation. In a biological neuron, the increase in action potential with an input spike is non-linear. Thus, non-linear LIF neuron models depict the biological behavior rather closely although the implementation cost of non-linear behavior on hardware is always higher. The authors in [48] discretized the differential equations explicitly with the Euler method and implement it on a _Xilinx Spartan 6_ using simple add and shift operations only. Similarly, in [49], Basham et al demonstrate a _quadratic integrate and fire_ (QIF) neuron model where the current equation integrates the square of potential difference. The design utilizes a fixed-point multiplier to evaluate the square of the voltage. Lastly, in [50], Nallathambi et al instrument a probabilistic integrate and fire neuron model. In a deterministic approach when a neuron i spikes, the applied weight of the postsynaptic neuron is \(w_{ij}\).For a set of \(N_{i}\) spikes with a probability of \(p_{ij}\) the new weight updates to \(N_{i}\times p_{ij}\times w_{ij}\).In stochastic processing, the number of memory fetches can be reduced significantly. By sorting the synaptic weights the authors report a reduction of \(90\%\) off-chip memory accesses. ### _Optimization techniques_ _Spiking Neural Networks_ can be divided in two different categories of optimization strategies. One, to make more biologically plausible neural models with better plasticity and second, to devise tuning algorithms that can transcend performance. More plasticity is accomplished with a trainable spiking network. Backpropagation is one such learning mechanism that has shown significant accuracy in ANN but it is not realizable for a biological spiking network. Thus, much work has been done to create the equivalent spiking backpropagation. #### Iii-C1 Training SNN Training deep spiking Neural networks have shown a great requirement for optimized gradient-based approaches. One of the reasons for facing difficulty in achieving deeper DNN is its complex _Spatio-Temporal Dynamics_. _Converting ANN to SNN_ and _Backpropagation with Surrogate Gradient_ are two ways to get deep SNN. Converted SNNs need a longer training time for similar precision as ANN. Most popularly, _Backpropagation Through Time_ (BPTT) is implemented by unfolding the gradient over a simulation time. Fig. 5: Layer-by-layer architecture with LIF neuron in Processing Unit (PU). In [51], Fang et al propose _Spike-Element-wise_ (SEW) _ResNet_ to resolve exploding gradient with identity mapping. In _Spiking ResNet_, the adaptation of residual learning from _ResNet_, the ReLU activation block is replaced by spiking neurons which is incapable to replicate the identity mapping for all neuron models. However, in _SEW ResNet_ element-wise function "g" facilitates identity mapping. When "g" is chosen to be an ADD function it avoids the infinite outputs problem by restricting the output. Apart from a purely algorithmic perspective of improvement in spiking realizable Backpropagation, some work has been done by Shrestha et al to develop a biologically plausible algorithm that can fit the constraints of neuromorphic hardware. In [52], the authors have shown in-hardware supervised learning demonstrated on _Intel's Loihi_ chip. The supervised learning is based on _Error modulated Spike-Timing Dependent Plasticity_ (EMSTDP) with _Direct Feedback Alignment_ (DFA) that reduces the number of neuron updates in the feedback path. The hardware realization of the algorithm is designed by creating two replicas of the same neuron with each of them functional in feed-forward and feedback paths respectively. Further in [53], Heidarpur et al propose on-FPGA online STDP. Based on _CORDIC_ an iterative algorithm all hyperbolic and exponential functions can be implemented with shift and addition operations. A _Izhikevich_ neuron behaviour was replicated with qualitative error analysis between the _CORDIC_ model compared to the original model of operation to achieve maximum precision.The proposed algorithm is tested for a two-layer network of 21 neurons with one output neuron.To demonstrate STDP learning on _Xilinx Spartan-6_ FPGA, all the exponential terms were approximated with a negative power of 2 terms which can be synthesized in fast and low-cost hardware. In STDP the weight update depends on the timing difference between the presynaptic and postsynaptic neuron pair. On the other hand, _Triplet STDP_ (TSTDP) considers three consecutive spikes, one presynaptic and two post synaptic spikes for potentiation and depression respectively. In [54], Gomar et al could reproduce the learning curve by approximating the two variable TSTDP equations to one variable piecewise linear term where exponentials are converted to base-2 functions. The discrete values of the lines are stored in LUT memory whose size is optimized as per the design. The design is driven through a _Finite State Machine_ (FSM) of 4 states with 2 states representing the Learning unit of the system. Compared to the LUT model this model is less accurate but consumes less than \(1\%\) on-chip resources. So far we have discussed _Hebbian_ learning applications, however, in [55], Liu et al explored non-Hebbian on-chip learning IP on recurrent SNN. The _Liquid State Machine_ (LSM) based recurrent SNN consists of a reservoir which maps the input pattern to a multi-dimensional response in the reservoir. The output of the reservoir is then passed to the readout layer. The focus of this work is to develop learning rules with _SpiKL-IP_ algorithm based on neural plasticity. _SpiKL_ is a _Intrinsic Plasticity_ (IP) rule whose key idea is to maximize the input to output information transfer. The algorithm is modified to reduce the complexity of hardware implementation with LUTs and series expansion techniques. Moreover, the LIF neuron model is discretized to surpass differential equations. Compared to baseline LSM the current model has outperformed by \(8\%\) for speech recognition _TIMIT_ dataset. Although a hardware resource utilization trade-off with extra energy overhead could be observed. #### Iii-D2 Tuning SNN Since SNN architectures are resource-constrained, compression methods like pruning are an essential optimization to tune the performance. Nonetheless, most of the pruning approaches are ANN-specific and not compatible with SNN. This factor lingers the performance of a pruned SNN. In [56], Chen et al formulate a learning algorithm of connectivity and weight that defines gradient as a different parameter called _Gradient Rewiring_ (Grad R). The combined learning and pruning algorithm change the synaptic connections based on the synaptic gradient parameter introduced. The algorithm is evaluated on _MNIST_ and _CIFAR-10_ datasets with a maximum of \(73\%\) connectivity. Although the techniques discussed in this section are the new frontiers of SNN optimization innovation, most of them have not made their way to a physical hardware implementation. ### _Technique Discussion_ The design and implementation of deep learning algorithms, particularly SNN hardware implementation, has been a hot topic during the previous decade [57]. SNN is hungry for computing power. Because of the rapid improvements in integrated circuit technology, it is now feasible to build high-performance chips at a low cost and with efficient energy consumption. This allowed for the deployment of inference at the edge. Along with, SNN can be executed on any device with adequate capability. There are some examples: i) CPUs, ii) GPUs, iii) FPGAs, iv) ASICs. Diverse technologies have a different throughput, performance, design flexibility, and power efficiency. Firstly, we partially consider traditional computing platforms to provide a comparison overview of the latest SNN accelerators targeting low-power and high-performance. As depicted in Table I, after developing circuits for edge computing, energy and performance efficiency are the most important criteria to consider. CPUs [47][58] are the most adaptable gadgets, and as such, have the lowest performance and energy efficiency. Furthermore, ASICs [59, 60, 61, 62, 63] provide the highest performance and energy efficiency, but with very little flexibility attainable primarily by additional hardware logic. It has reached a peak performance of \(100Kimg/sec\) and \(7.89TOPS/W\) mean that are very energy efficient. ASIC circuits are specifically built for neural networks to improve performance and power efficiency. Modern GPUs incorporate single-precision computation modules capable of performing several half-precision floating-point calculations. Thus, they seem to be the perfect basis for both learning and prediction. However, due to their multi-core structure, GPUs present a challenge with high power usage. Studies [47, 58] have shown power consumption figures markedly higher than those for FPGAs. FPGAs combine hardware and software (processing) in a single device, where software ensures programmability and hardware is utilized to implement specialized accelerators. GPUs have the higher performance among programmable or configurable devices and are less expensive than FPGAs. Researchers have demonstrated that FPGAs may efficiently implement Spiking Neural Networks (SNN) in both hardware and software/hardware contexts [64, 65, 66, 67, 58, 47, 68, 69, 70]. They showed that their FPGA-based design had the highest performance of 2124 frame/sec and the lowest power of \(0.40W\). This corresponds to an energy efficiency of \(16.80mOPs/W\). The same platform may then be upgraded with an SNN without any board modifications just by reconfiguring the device. In this section, key ideas for SNN implementation in equipment are shown, along with a comparison to different techniques in Table II. The table combines the most important information received from the available sources from among the numerous structures specified from now on. Without being exhaustive, this chart allows for a quick representation of the show status of the advanced systems. This work [76], the usage of the _NeuroFlow_ which FPGA architecture for SNN that was suggested approach aims for a real-time execution time of \(0.1ms\). _NeuroFlow_ may be further reduced by adjusting the size of the arrangement or guessing on the network within this architecture. Moreover, the huge quantity of simulated neurons made available by _NeuroFlow_ may be achieved using six FPGAs in a toroidal network design. The configuration restricts the number of synapses to a range of 1,000-10,000, where the chance of connection is based on a Gaussian probability of synaptic disconnection, with a standard deviation varying from 32 to 512. In this spectrum, a direct comparison might be challenging and potentially unfair to other SNN models. Another approach in this direction has been implemented by Han [66], which highlights crossover upgrade algorithms that integrate the points of interest of current algorithms to improve equipment planning and execution. Thus, this design, capacitively supports 16 384 neurons and 16.8 million synapses but uses fewer hardware resources and has a very low power consumption (\(0.477\)W) and the performance for processing neuron activation events is \(6.72ms\). For a modest to large scale SNNs on sophisticated equipment should be computationally simple and simultaneously capable of communicating to the large range of termination patterns displayed by various organic neurons. For this reason, several designs employ simpler custom neural models [71], and much more with the LIF model [73, 72]. Fig. 6: SNN on Different Heterogeneous Devices Spikes collection is performed at \(32bits\) to maintain as much accuracy as conceivable. In [75], the authors demonstrate a comparable technique capable of simulating up to 167 neurons. In comparison to the one suggested, due to increased information exactness and synaptic current preparation which is more sophisticated to a certain degree such a task employs a greater number of assets. The FPGA architectures by [74] and [65] simulate a fully-connected network of 1024 neurons, 1440 neurons, based on the biologically plausible _Izhikevich_ spiking model. The reported time resolutions are 10.0 \(\upmu\)s and \(0.1ms\). These implementations have low latency, despite the fact that simplified resource utilization is employed for it. An alternate notable design is that by Gupta et al. [77], which offers a simulation of a simpler and more computationally efficient model using FPGA infrastructure. This was engineered to leverage the sparsity of the network and generate each time unit corresponding to network activities. A network comprising 784 input and 16 output neurons, along with 12,544 synapses, was realized on hardware, thereby facilitating the creation of a hardware accelerator with minimal resource consumption. In another study by Liu et al. [67], a neuron computing module was used, designed to replicate both _LIF_ and _Izhikevich_ neurons using the concurrent spike caching and scheduling strategy while simulating 16,384 neurons and 16.8 million synapses. They structured two distinct three-layer SNN networks applied for recognition tasks on the suggested platform. The employment of Slice LUTs, Slice Registers, and DSP of the SNN acceleration unit stands at \(6.0\%\), \(2.5\%\), and \(7.6\%\) respectively. It is noteworthy that their design exhibits the highest occupancy ratio in BRAM. As a consequence, the parameters of the LIF and IZH neurons, along with the event buffer and synaptic delays, are produced using the on-chip storage resource BRAM. Hence, the BRAM is significantly employed, leading to increased power usage. Ma et al. [68] established an embedded auxiliary processor to hasten the inference mechanism of SNNs. By time-sharing the physical neuron components, and developing a reconfigurable memory subsystem, the design realizes high hardware efficiency, fitting for resource-limited embedded applications. It also permits a customizable quantity of neurons, synapses, and synaptic delays, yielding significant flexibility. Moreover, work by Fang H et al [79], Asgari et al [78], and Li et al [69] proposed to utilize their design on the identical neuron model (_LIF_) and targeting the same dataset (_MNIST_). Recently, Carpegna et al [70] presented Spiker, which employs a clock-driven neuron design wherein the membrane potential is modified at each clock cycle absent any spikes. Nevertheless, inputs are only processed when there's at least one spike present at the input of a layer. This approach uses more power than purely event-driven designs but allows for the utilization of fewer hardware resources. The FPGA usage is of 1384 neurons and 313600 synapses are around \(55\%\) for the LUTs, and \(25\%\) for the FFs. Considering the number of instantiated neurons, this is a major finding. ## IV Applications ### _Image and Audio Processing_ In [80], authors presented an application of animal behavior recognition using an SNN-based sound recognition system associated with animal movements. The spiking neural network was built on an FPGA device, and the neuromorphic auditory system employed in this study creates a representation similar to the spike outputs of the biological cochlea. Even when the sound was accompanied by the white noise of the same strength, the detection system based on SNN achieved an accuracy of over 91%. In [81], the authors proposed a continuous voice recognition system that employs a _Delta Recurrent Neural Network_ (DeltaRNN) on a _Xilinx Zynq-7100_ FPGA to provide low latency _Recurrent Neural Network_ (RNN) processing. This system is suitable for _Internet of Thing_ (IoT) applications since FPGA uses just \(70mW\) and can process each feature frame in microseconds. Edge detection is a prominent machine learning job that necessitates the use of a large number of neurons as well as software simulations. As a result, scalability suffers, and computational time increases. This research [82] proposed a scalable FPGA implementation strategy with several innovations to shorten calculation times. Within this scenario, given spatial constraints, the time-division multiplexing structure proposes a balance between acceleration performance and the dimensions of SNN simulations. Furthermore, a study by Louis-Charles Caron et al. [83] accomplished image segmentation and monophonic audio source separation utilizing _Oscillatory Dynamic Link Matcher_ (ODLM) protocols for motif recognition. The authors in [84] developed a character identification model for multicore architectures relying on two SNN models. The selection of the _Izhikevich_ and _Hodgkin-Huxley_ neuron models over the integrate and fire models were motivated by their biological accuracy. All 48 visuals in the learning datasets were accurately distinguished within \(14ms\) and 3.75ms, respectively. Moreover, the authors of [85] employed SNN for image clustering using FPGA. The _Gaussian Receptive Field_ (GRF) is the most commonly used method for encoding data, with Hebbian learning being used for neural models. Not only did [85] use the _Receptive Field_ (RF) for data encoding, but [86] also applied the T.Iakymchuk model. To examine an image in its spatial domain form, the authors also utilized the Gabor filter, a bandpass filter. A biologically driven, rotationally invariant visual identification system, executed using a pixel camera on FPGA, was deployed in [87]. The structure merged the _Ripple Pond Network_ (RPN), a neural network proficient in fundamental 2D to 1D image conversion, rotationally invariant _Temporal Patterns_ (TPs), and the _Synaptic Kernel Adaptation Network_ (SKAN). By using the event-driven _Spike-timing dependent plasticity_ (STDP) rule, Zaibo Kuang and Jiang Wang [88] trained the MNIST dataset for digital categorization on a _Stratix-3_ FPGA processor with \(93\%\) precision. As a result, the cost-effective network demonstrated great efficiency and can readily be scaled to a larger size. ### _Biomedical Applications_ The manuscript [89] presents a freely available FPGA-centric emulation environment for delving into the neuromorphic computation. The authors implemented the _MNIST_[90] dataset and_Vector-Matrix Multiplication_ (VMM), comparing their accuracy with analogous architectures generated by IBM's Compass simulation infrastructure. Considering the substantial computational intricacy of spiking neural networks, it's arduous to actualize them on hardware necessitating proficiency. Thus, QingXiang Wu [91] unveiled a straightforward, effective, and swift strategy to instantiate SNN employing a customized toolkit. Thus, participants in this investigation seamlessly engineered and modeled various spiking neural networks on FPGA, enhancing the execution speed. In a different study, Junxiu Liu [92] proposed a novel biologically-derived gas identification technique with minimal hardware footprints. This method utilized spiking neural pathways and neurons to recognize the abnormal frequency of the input spike generation by adjusting the discharge likelihood of the inhibitory neural linkage under diverse input situations. In [93], a neuromorphic system on a _Virtex-2 pro_ FPGA was shown how neuronal elements from this construction kit can be deployed in parallel. The neuromorphic system mirroring the known architecture of the early olfactory pathway when coupled spontaneously produces rhythmic, limit-cycle dynamics resembling biology. Thus, The findings of this work show how these attractors may be read from the network to recognize previously experienced learned fragrances without confusion. The authors [94] present a neuromorphic system that combines a neural recording headstage with an SNN processing core on the same die for processing _iElectroencephalography_ (iEEG), and demonstrate how it can reliably detect _High-Frequency Oscillations_ (HFO), achieving state-of-the-art accuracy, sensitivity, and specificity. This is the first feasibility research aimed at finding significant characteristics in iEEG in real-time utilizing mixed-signal neuromorphic computing Technologies on a custom board _XEM7360_ FPGA. In [95], The researchers wanted to construct an artificial intelligence signal identification system in a _PYNQ-Z_ FPGA Fig. 8: Block diagram of the neuromorphic platform (a) and _Functional magnetic resonance imaging_ (fMRI) brain image (b) Fig. 7: System architecture of microphone board that can detect patterns of bio-signals such as _Electrocardiography_ (ECG) in battery-powered edge devices. Despite the increase in classification accuracy, deep learning models need expensive processing resources and power. Therefore, it makes deep neural network mapping a time-consuming process and deployment on wearable devices difficult to achieve. SNNs have been used to overcome these constraints. ### _Control Systems_ In [96], proposed a procedure that permits the usage of analog-like spike-based _Proportional-Integral-Derivative_ (PID) controllers on low-cost _Virtex-3_ FPGA. Spike-based PID controllers have been logically analyzed and characterized, demonstrating that they are exceptionally near to nonstop controller models unless they are actualized in a totally computerized gadget as FPGAs. In [97], biological neuron model-generated spiking waveforms were utilized as substitutes for sawtooth waveforms to effectuate _Pulse-Width Modulation_ (PWM), a modulation strategy that produces variable-width pulses to symbolize the amplitude of an analog input signal. This study proposes a signal generator on the FPGA platform, grounded in the _Izhikevich_ neuron model, prized for its simplicity and precision. An innovative stride in the realm of prosthetics is the bioelectric upper limb prosthesis serving as an actuator's control. The authors of [98] adopted the _Izhikevich_ neuron model and an FPGA-oriented LIF to mimic the behavior of biological neurons. Moreover, _PWM_ has surged in its acceptance as a governing technique in both analog and digital circuits. In [99], a spike-oriented proportional-integral-derivative engine speed controller was modified to govern the position of the 4 joints of a lightweight and _safe physical human-robot interaction_ (pHRI) robotic arm, referred to as _event-driven BioRob_ (ED-BioRob). These _spiking PID_ (sPID) controllers were deployed on two _Spartan-3_ FPGA platforms, that is, the _address-event representation Robot_ (AER-Robot). The robot furnishes address-event-representation interfacing for spiking systems and is capable of driving DC motors with Pulse Frequency Modulation signals, reflecting the motor neurons of mammals. ### _Autonomous Systems_ FPGAs are gaining popularity because of their reconfigurability and hardware efficiency, and have been proposed for robotic vision. The publication [100] introduced the _Efficient Large-scale Stereo_ (ELAS) based stereo vision system that is completely implemented on FPGA and is intended for real-time and energy-efficient applications. The _ELAS_ which is shown in Figure 9 calculation is reformulated as a standard design with a back focus introduction for hardware execution. Within the examination at [101] the bound-together compute bottleneck of different localization frameworks is distinguished. Therefore, an _Oriented-Fast and Rotated-BRIEF_ (ORB) based visual frontend design is displayed for real-time and energy-efficient localization and assessed on the FPGA platform. Authors illustrated [102] an end-to-end usage on a genuine, high-_Degrees of Freedom_ (DOF) mechanical arm, and the quickening agent was able to unravel energetic pick-and-place scenarios with a high rate of success. This sub-millisecond speed is adequate with a few limitations to empower already the infeasible automated applications, such as real-time arranging in energetic situations. ### _Robotics_ Due to their handy and beneficial assistance, robots are increasingly being integrated into our society. The authors of [103] aimed to leverage FPGA to create a cerebellum model capable of learning and adjusting conversational robot timing. The _Central Pattern Generator_ (CPG), a locomotion mechanism for multi-legged robots, is an SNN application as well. The research conducted in [104] applied advanced hippocampal pyramidal neuron models to construct hardware-spiking neural networks for navigation purposes. J.Parker Mitchell [105] utilized a _Dynamic Adaptive Neural Network Array_ (DANNA) framework for Autonomous Robotic Navigation. The DANNA framework comprises a grid of adaptable neuromorphic computing components, each capable of behaving like a neuron and connected to its adjacent counterpart in the grid. A modular hardware execution of a spiking neural network with real-time adjustable connections is presented in [106], framed within an autonomous robot impediment evasion schema. The structure is situated in a conventional 2D matrix of cells, each operating as a spiking neuron with unique functions. Another study [107] likewise tackled the robot Fig. 9: Overview of ELAS obstacle avoidance dilemma. Inspired by the robustness and adaptability of biological systems, this research offered a uniquely flexible neural network model. The network observed a reduction of up to \(75\%\) of the initial synaptic inputs to a cell. In [108], a neuromorphic framework was established on a _Spartan-6_ FPGA to enable locomotion for three types of robots: bipedal, quadrupedal, and hexapods. In this exploration, the researcher conceived a fast, compact, and configurable FPGA architecture that hinged on the _CPG_, the movement mechanism for multi-legged robots. ### _Event vision sensors_ A fault injection experiment and fault resilience analysis for an SNN hardware accelerator were given in the study at [109]. They created a fault injection framework that builds and maps SNN faulty instances into the hardware. The framework is allowing the researchers to expedite fault injection and analyze fault criticality on _ZCU104_ FPGA development board. This research described [110] one of the first end-to-end neuromorphic frameworks for real-time object tracking and categorization shown utilizing a low-power hardware implementation on _Trenz TE0720_ FPGA. To take use of the low latency and asynchronous nature of _Neuromorphic Vision Sensors_ (NVS) as an optional paradigm. The framework's integral operation includes gathering occurrences from the camera, handling these occurrences to isolate surveilled entities, forwarding these observed coordinates to the neuromorphic chip for sorting, and the entity detection illustration, as demonstrated in Figure 10. ### _Communication_ The authors of the work [111] describe a hybrid-mode router architecture for large-scale neuromorphic simulation by merging two types of router schemes. These router schemes are proposed to allow chip-to-chip transmission of spike and non-spike data. This work is being tested on a neuromorphic platform constructed using an chip _Artix-7_ FPGA. In Table IV displays the comparison of data transmission exists similar works. The proposed routers separate themselves from prior efforts by supporting both source-driven and destination-driven packet representations. The FPGA implemented method has a spike processing rate of \(200MSpikes/s\). The research found that their algorithm, routing strategies, and router design improved communication efficiency in the specified multichip network. ## V Trend Based on the above surveyed related works, we can conclude the following four potential topics in further FPGA-based SNN accelerator research: * _Approximation Computing in SNN:_ Considering the hardware resource limitation on FPGA platforms, further compressing the memory consumption of weights and parameters in SNN models is necessary. The approximation computing methods and _Posit_ computing methods applied in work [114][115] are the upcoming techniques that can be applied in SNN accelerators on FPGA. Besides, the application of quantization and binarization techniques on SNN accelerators can also be potential. * _Implementation Toolchain/Framework for SNN on FPGA:_ Considering the complexity of FPGA development, as the python-based hardware generation framework shown in HLS4ML [116][117][118] and FINN [119][120][121], an automatic hardware design generation framework/library/toolchain, will highly benefit the implementation and deployment of SNN acceleration on FPGA platforms. These frameworks/libraries/toolchains should be able to cooperate with the training/accelerating software libraries and convert the trained SNN model to the suitable hardware design for targeting platforms. * _Automatic Network Generation of SNN on FPGA:_ The automatic network model generation techniques, such as _Network Architecture Search_ (NAS) are the upcoming topic in recent research. Work [122] explored the application of NAS on FPGA, which could also be one potential research and application idea for SNN acceleration on FPGA. * _Upcoming Network Models of SNN on FPGA:_ Recent work of FPGA-based SNN acceleration focus on the classic MLP, CNN, and LSTM models. Some state-of-the-art works, such as [123][124][125], explored the application of SNN on _Transformer_ and _Graph Neural Networks_ (GNNs). The implementation of FPGA-based accelerators for the above networks can extend the application scenarios of related research. Fig. 10: System flow diagram of the neuromorphic vision sensor ## VI Conclusions We have provided a survey on the hardware implementation of SNN that, in particular, covers recent trends in deploying FPGAs in different applications. The field of FPGA has proven that, despite the already apparent exceptional results, various researchers have illustrated the advantages of reconfigurable hardware implementations over other heterogeneous devices. In addition, we explained how different neural networks perform on FPGAs. With this survey, we proposed to summarize state-of-the-art work and highlight critical directions of inquiry about that such as image/audio processing, robotics, autonomous systems, event vision sensor, and biomedical applications.
2304.13935
Bitcoin Double-Spending Attack Detection using Graph Neural Network
Bitcoin transactions include unspent transaction outputs (UTXOs) as their inputs and generate one or more newly owned UTXOs at specified addresses. Each UTXO can only be used as an input in a transaction once, and using it in two or more different transactions is referred to as a double-spending attack. Ultimately, due to the characteristics of the Bitcoin protocol, double-spending is impossible. However, problems may arise when a transaction is considered final even though its finality has not been fully guaranteed in order to achieve fast payment. In this paper, we propose an approach to detecting Bitcoin double-spending attacks using a graph neural network (GNN). This model predicts whether all nodes in the network contain a given payment transaction in their own memory pool (mempool) using information only obtained from some observer nodes in the network. Our experiment shows that the proposed model can detect double-spending with an accuracy of at least 0.95 when more than about 1% of the entire nodes in the network are observer nodes.
Changhoon Kang, Jongsoo Woo, James Won-Ki Hong
2023-04-27T03:04:55Z
http://arxiv.org/abs/2304.13935v1
# Bitcoin Double-Spending Attack Detection using Graph Neural Network ###### Abstract Bitcoin transactions include unspent transaction outputs (UTXOs) as their inputs and generate one or more newly owned UTXOs at specified addresses. Each UTXO can only be used as an input in a transaction once, and using it in two or more different transactions is referred to as a double-spending attack. Ultimately, due to the characteristics of the Bitcoin protocol, double-spending is impossible. However, problems may arise when a transaction is considered final even though its finality has not been fully guaranteed in order to achieve fast payment. In this paper, we propose an approach to detecting Bitcoin double-spending attacks using a graph neural network (GNN). This model predicts whether all nodes in the network contain a given payment transaction in their own memory pool (mempool) using information only obtained from some observer nodes in the network. Our experiment shows that the proposed model can detect double-spending with an accuracy of at least 0.95 when more than about 1% of the entire nodes in the network are observer nodes. Bitcoin, double-spending, deep learning, graph neural network + Footnote †: publicationid: pubid: 978.8-3503-1019-1/23/831.00 ©2023 IEEE ## I Introduction Bitcoin [1] transactions use the concept of unspent transaction output (UTXO). UTXO is the Bitcoin balance received by transactions included in the blockchain in the past. An owner of this UTXO can send bitcoins by using it as an input when creating a new transaction. At this time, attempting to use the same UTXO more than once in multiple transactions is called a double-spending attack [2]. For convenience, in this paper, we refer to a transaction generated for fast payment and known to the merchant as \(\textbf{tx}_{pay}\), and a transaction to double-spend UTXOs that have already been used as inputs of \(\textbf{tx}_{pay}\) as \(\textbf{tx}_{attack}\). Eventually, double-spending is impossible in Bitcoin because only one chain with the longest block extension is recognized as valid according to Bitcoin's longest chain rule. For fast payment, if the merchant approves \(\textbf{tx}_{pay}\) without sufficient confirmation, and the attacker creates \(\textbf{tx}_{attack}\), the merchant may not be paid. In this paper, we propose an approach to detect Bitcoin double-spending attacks using a graph neural network (GNN) [3]. The Bitcoin P2P network can be considered as an undirected graph where peer nodes are vertices and their connections are edges. We use GNN to predict whether there is a \(\textbf{tx}_{attack}\) across the network for \(\textbf{tx}_{pay}\), using only information obtained from a few observer nodes that we can find in their mempools all unconfirmed transactions. We assume that double-spending does not occur if all nodes have \(\textbf{tx}_{pay}\). To the best of our knowledge, this work is a novel approach that uses GNN to predict the propagation status of an unconfirmed transaction in the Bitcoin P2P network. ## II Related Work Many attempts are being made to achieve fast Bitcoin payments while preventing double-spending attacks. For instance, the Lightning network [4] uses a Layer-2 payment protocol to improve payment speed. Additionally, many other studies have proposed methods that require partial modification of the Bitcoin protocol [5, 6, 7, 8, 9]. However, it would be difficult to modify the Bitcoin protocol solely for this purpose. Furthermore, most attempts are difficult for ordinary people who do not know much about blockchain, such as merchants. They would not be able to operate a payment channel for the Lightning network or manage peer connections of their own Bitcoin nodes to remain connected to arbitrary samples of nodes to make it difficult for attackers to successfully execute double-spending. In contrast, a platform called GAP600 [10] provides real-time guarantee service for fast payment through risk scoring for each unconfirmed transaction through network monitoring. However, specific risk analysis and evaluation methods are not disclosed at all. ## III Method In this paper, we construct virtual Bitcoin networks to generate data through transaction propagation simulations. Although a GNN model is learned through graph structures that are different from the real Bitcoin network topology, it is possible to apply the learned model to the real Bitcoin network thanks to the characteristic of GNN. In this work, we do not use the topology of the actual Bitcoin network, but instead create virtual Bitcoin networks with a similar structure. The number of nodes in the virtual Bitcoin networks is fixed at 14,000 by referring to the website bitnodes.io [11], which captures and displays reachable Bitcoin nodes in real-time. Additionally, according to [12], the Bitcoin network is not a random graph and has some community structures. Therefore, we assume that the Bitcoin network is similar to a scale-free network [13]. A characteristic of the scale-free network is that a node with a higher degree gets more new connections. We use the Barabasi-Albert model [14] to create virtual Bitcoin networks. Our GNN task is graph classification, which predicts whether every node on the graph has a given transaction (\(\mathbf{tx}_{pay}\)) in its mempool. Given information about whether some nodes, which are observers on the graph, possess \(\mathbf{tx}_{pay}\), we predict whether all the nodes on the graph have \(\mathbf{tx}_{pay}\) in their mempool. Observer nodes are randomly selected for each generated data. Our model uses two GNN layers, and after each GNN layer, a ReLU activation function to provide non-linearity and a dropout to prevent overfitting are added. In the last part, for graph classification, the softmax value of each node embedding is aggregated by calculating the mean value, and it is passed through a fully connected layer to produce an output for classification. In our case, the input graph uses the Bitcoin network as it is. We also use cross-entropy loss to train the model and existing three popular GNN algorithms for GNN layers: GCN [15], GraphSAGE [16], and GAT [17]. In addition, we design node features to include information around the nodes on the graph. The number of neighboring nodes of each label (Non-Observers: 0.5, Observers with \(\mathbf{tx}_{pay}\): 1, Observers without \(\mathbf{tx}_{pay}\): 0) is used as features, and we also added the number of each combination consisting of the neighboring node label and the label of a node one hop further away from it as features. ## IV Experiment We conducted experiments on a total of six cases by varying the number of observer nodes. For each case, we generated 1,000 datasets where the number of observer nodes was 10, 50, 100, 150, 200, and 250 out of the total 14,000 nodes. We split each dataset into 700 for training and 300 for testing. We also evaluated the model using 5-fold cross-validation on the training dataset. ### _Observer Nodes: 150, 200, and 250_ Table I presents the average accuracy of cross-validation for each model when the number of observer nodes is 150, 200, and 250, as well as the accuracy, precision, recall, and F1-score values for the test set. All three types of GNN layers demonstrated similar performance under the same number of observer nodes, and the higher the number of observer nodes, the higher the accuracy. In all cases, the accuracy was at least 0.95, and it is interesting to note that the recall had a value of 1.0. In our experiment, recall indicates how accurately the model predicted that there was no double-spending attack when there was no actual attack. In other words, the models trained in this experiment accurately predicted that there was no attack for all cases where there was no double-spending attack. Precision refers to the ratio of cases where there is actually no attack among those predicted by the model in our experiment that there is no double-spending attack. It is an essential indicator of the efficiency of double-spending attack detection for Bitcoin fast payment because the higher the precision value, the higher the rate of predicting that there is no attack only when there is actually no double-spending attack. As expected, the precision had a larger value as the number of observer nodes increased, and values of at least about 0.91 or higher were obtained. ### _Observer Nodes: 10, 50, and 100_ When the number of observer nodes is 10, 50, and 100, we could not train the model. We found that train loss does not decrease even after repeated learning steps. We concluded that this is because the number of nodes with information, i.e., observer nodes, is too small to predict the state of the entire graph consisting of 14,000 nodes. In this experiment, it was possible to detect a double-spending attack with high accuracy only when the mempool data of at least about 1% or more of the nodes was known. ## V Conclusion This paper proposes a GNN-based approach to detect Bitcoin double-spending attacks by predicting attempts to double-spend UTXOs in payment transactions. The model achieved an accuracy of at least 0.95 by monitoring 150 or more observer nodes' mempool in a 14,000-node P2P network. However, training was inadequate with less than 100 observer nodes. ## Acknowledgements This work was supported by Coinone and Smart HealthCare Program(www.kipot.or.kr) funded by the Korean National Police Agency(KNPA, Korea) [Project Name: Development of an Intelligent Big Data Integrated Platform for Police Officers' Personalized Healthcare / Project Number: 220222M01]
2302.07416
Deep Convolutional Neural Network for Plume Rise Measurements in Industrial Environments
Estimating Plume Cloud (PC) height is essential for various applications, such as global climate models. Smokestack Plume Rise (PR) is the constant height at which the PC is carried downwind as its momentum dissipates and the PC and the ambient temperatures equalize. Although different parameterizations are used in most air-quality models to predict PR, they have yet to be verified thoroughly. This paper proposes a low-cost measurement technology to monitor smokestack PCs and make long-term, real-time measurements of PR. For this purpose, a two-stage method is developed based on Deep Convolutional Neural Networks (DCNNs). In the first stage, an improved Mask R-CNN, called Deep Plume Rise Network (DPRNet), is applied to recognize the PC. Here, image processing analyses and least squares, respectively, are used to detect PC boundaries and fit an asymptotic model into the boundaries centerline. The y-component coordinate of this model's critical point is considered PR. In the second stage, a geometric transformation phase converts image measurements into real-life ones. A wide range of images with different atmospheric conditions, including day, night, and cloudy/foggy, have been selected for the DPRNet training algorithm. Obtained results show that the proposed method outperforms widely-used networks in smoke border detection and recognition.
Mohammad Koushafar, Gunho Sohn, Mark Gordon
2023-02-15T00:41:36Z
http://arxiv.org/abs/2302.07416v2
# Deep Convolutional Neural Network for Plume Rise Measurements in Industrial Environments ###### Abstract Estimating Plume Cloud (PC) height is essential for various applications, such as global climate models. Smokestack Plume Rise (PR) is the constant height at which the PC is carried downwind as its momentum dissipates and the PC and the ambient temperatures equalize. Although different parameterizations are used in most air-quality models to predict PR, they have yet to be verified thoroughly. This paper proposes a low-cost measurement technology to monitor smokestack PCs and make long-term, real-time measurements of PR. For this purpose, a two-stage method is developed based on Deep Convolutional Neural Networks (DCNNs). In the first stage, an improved Mask R-CNN, called Deep Plume Rise Network (DPRNet), is applied to recognize the PC. Here, image processing analyses and least squares, respectively, are used to detect PC boundaries and fit an asymptotic model into the boundaries centerline. The y-component coordinate of this model's critical point is considered PR. In the second stage, a geometric transformation phase converts image measurements into real-life ones. A wide range of images with different atmospheric conditions, including day, night, and cloudy/foggy, have been selected for the DPRNet training algorithm. Obtained results show that the proposed method outperforms widely-used networks in smoke border detection and recognition. plume rise; deep learning; plume cloud recognition + Footnote †: journal: Computer Vision and Pattern Recognition 0 Footnote 0: Citation:**Koushafar, M.; Sohn, G.; Gordon, M. Deep Convolutional Neural Network for Plume Rise Measurements in Industrial Environments. _Preprints_**2023**, \(I\), 0. [https://doi.org/](https://doi.org/) **Copyright:** © 2023 by the authors. Submitted to _Preprints_ for possible open access publication under the terms and conditions of the Creative Commons Attribution (CC BY) license ([https://creativecommons.org/licenses/by/4.0/](https://creativecommons.org/licenses/by/4.0/)). ## 1 Introduction Smokestack Plume Cloud (PC) rises due to momentum and buoyancy. Finally, the PC dissipates and is carried downwind at a constant height. This height is called plume rise height or Plume Rise (PR). PR calculation is not straightforward, and it is a substantial problem in predicting the dispersion of different harmful effluents into the air [1]. PR contributes to 1) the distance pollutants carried downwind, 2) their concentration at the surface, where they are deposited in the green environment or inhaled by people, and 3) the amounts of greenhouse gases mixed into the upper troposphere. Therefore, accurate measurement of the PR is of concern for research and operational applications such as air-quality transport models, local environment assessment cases and global climate models [2]. The parameterizations of PR prediction were developed in the 1960s by Briggs [3, 4]. Dimensional analysis was used to estimate the PR based on smokestack parameters and meteorological measurements in different atmospheric conditions. Early observations of PR were used to test and rectify the parameterizations developed using dimensional analysis [5]. Wind tunnel studies and field observations using technologies including film photography, theodolites, and cloud-height searchlights [6] were several calibration techniques utilized in this domain. There are also three-dimensional air-quality models, using parameterizations equations including GEM-MACH [7], CAMx [8], and CMAQ [9]. Some studies tested the parameterizations of PR prediction in the 1970s and 1980s by comparing them to actual observations and demonstrated that the Briggs equations overestimate the PR [10, 11, 12, 13]. In 1993, an aircraft-based measurement was done to measure SO\({}_{2}\) emissions of a power plant which indicated an overestimation of about 400 m [14]. Although these earlier studies showed some degree of overestimation, in 2002, Webster et al. [15] performed surface measurements and concluded that the Briggs parameterizations tend to underestimate PR. In 2013, as part of the Canada-Alberta Joint Oil Sands Monitoring (JOSM) Plan, an aerial measurement study was done in the Athabasca oil sands region of northern Alberta to study dispersion, and chemical processing of emitted pollutants [16; 17; 18]. The project consisted of 84 flight hours of an instrumented Convair aircraft over 21 flights designed to measure pollutants emissions, study the transformation of chemicals downwind of the industry, and verify satellite measurements of pollutants and greenhouse gases in the region. Using aircraft-based measurements and reported smokestack parameters and meteorological data, it was demonstrated that the Briggs equations significantly underestimate PR at this location. Given the results of [16; 17; 18] and the gap of more than 30 years since the Briggs equations were developed and previously tested, there is a need for further testing and possible modification of the Briggs equations based on modern observation techniques. In recent decades, there have been many significant advancements in environmental monitoring activities over industrial regions for safety and pollution prevention [19; 20; 21; 22]. Moreover, several smoke border detection and recognition models have been introduced recently using digital image analysis, such as wavelet and support vector machines [23], LBP and LBPV pyramids [24], multi-scale partitions with AdaBoost [25], and high-order local ternary patterns [26] which are well-performed and impressive. These improvements have led to the development of instrumentation which can be deployed near any smokestack to give information on pollutant dispersion and potential exposure to people downwind. This information will be based on actual real-time observation, i.e. digital images, as opposed to potentially erroneous and decades-old parameterizations. Due to the similarity of our work to smoke recognition on the one hand, and on the other, the unavailability of plume cloud recognition research, smoke recognition studies will be reviewed in the following. To find the smoke within an image or a video frame, either a rough location of smoke is identified using bounding boxes called smoke border detection [27; 25], or pixels are identified and classified in detail, called smoke recognition [28; 29]. Due to the translucent edges of smoke clouds, the recognition task needs far more accuracy than border detection. Traditional smoke recognition methods utilize manual features, which lead to low accuracy recognition results due to a large variety of smoke appearances. These low-level features consist of motion characteristic analysis of the smoke [30; 31], smoke colour [32; 33; 34], and smoke shape [35]. In another research, [36; 37] took advantage of the Gaussian Mixture Model (GMM) to detect the motion region of the smoke and [38] combined rough set and region growing methods as a smoke recognition algorithm which seems to be a time-consuming algorithm due to the computational burden of the region growing process. Since using colour information is less effective due to the similarity of smoke colour to its surrounding environment, the combination of motion and colour characteristics is considered for smoke recognition [39; 40; 41]. Some algorithms utilize infrared images, and video frames in their experiments [42], which are not easily accessible and can increase the project's costs. Moreover, using digital images makes the algorithm more flexible as it can be used with more hardware. On the other hand, some smokes are too close to the background temperature to be captured by the near red-channel wavelength. A higher-order dynamical system was introduced in 2017, which used particle swarm optimization for smoke pattern analysis [43]. However, this approach had a low border detection rate and high computational complexity. In recent years, deep learning-based methods, especially Convolutional Neural Network (CNN) based methods, have led to significant results in semantic segmentation [44; 45; 46; 47] and object recognition [48; 49; 50; 51; 52]. Similarly, these methods are widely used in smoke border detection, and recognition [53; 54; 55] with different architectures such as three-layer CNN [56], generative adversarial network (GAN) [57] and two-path Fully Convolutional Network (FCN) [28]. Recently, a count prior embedding method was proposed for smoke recognition to extract information about the counts of different pixels (smoke and non-smoke) [58]. Experimental results showed an improvement in the recognition performance of these studies. However, the high computational complexities of these huge models are an obstacle to their use in PR real-time observations. We have proposed a novel method using DCNN algorithms to measure PR. Our approach comprises two parts, 1) PC border detection and recognition based on an improved Mask R-CNN [59], and 2) geometric transformation [60] to migrate from image scale measurements to real-life. This method accurately recognizes the PC and measures PR in real-time. Here, we reinforce the bounding box loss function in Region Proposal Network (RPN) [61; 62; 63] through engaging a new regularization to the loss function. This regularizer restricts the search domain of RPN to the smokestack exit. In other words, it minimizes the distance between the proposed bounding boxes and the desired smokestack exit, which is called smokestack exit loss (\(L_{seg}\)). The proposed method is also computationally economical because it generates only a limited number of anchor boxes swarmed across the desired smokestack exit. Consequently, the main contributions of this paper can be summarized as follows: * Proposing "DPRNet" (a deep learning framework for PR measurements) by incorporating PC recognition and image processing-based measurements. We have provided a relatively low-cost and reproducible algorithm to accurately recognize plume clouds using an automated digital image capturing software adaptable to utilize RGB widescreen images. * A pixel-level recognition dataset, Deep Plume Rise Dataset (DPRD), containing 2500 fine annotations, is presented. As is expected, the DPRD dataset includes one class, namely PC. Widely-used DCNN-based smoke recognition methods are employed to evaluate our dataset. Furthermore, this newly generated dataset was used for PR measurements. This paper is organized as follows--section 2 briefly explains the theoretical information used in our proposed method. In section 3, we describe our proposed framework for the PR measurement of a desired smokestack. Then, section 4 presents our dataset collection procedure, under-study site, experimental results of the proposed method and evaluation results using different metrics, and calculations of the PR. Finally, this research's conclusions, findings, and future studies are described in section 5. ## 2 Theoretical background ### Briggs PR prediction The PR calculation is an ill-posed problem used to predict the dispersion of harmful effluents in atmospheric science [1]. PR is affected by two phenomena, buoyancy and momentum. Typically, the PCs are buoyant, which means they are hotter than the ambient air. Therefore, they rise since they are less dense than the surrounding air. Also, the PCs have a vertical velocity and momentum when they exit the smokestack, which again causes them to rise. PCs can also fall due to the gravitational force when cold and dense and when some surrounding obstacles cause them to move downwind [64]. In 1975 Briggs proposed an equation for the maximum distance of the PR, which was practically suitable for calculating PR. Considering both momentum and buoyancy in calculations, PR (\(\Delta z\)) in horizontal distance \(x\) from the smokestack exit can be obtained as [4], \[\Delta z=\left(\frac{3\,F_{m}x}{0.6^{2}\,\bar{u}^{2}}+\frac{3\,F_{b}x^{2}}{2 \times 0.6^{2}\,\bar{u}^{3}}\right)^{1/3} \tag{1}\] where 0.6 is an entrainment rate (the mean rate of increase of PC in the wind direction) and \(\bar{u}\) is the mean horizontal wind speed. Also, Momentum flux parameter (\(F_{m}\)) and Buoyancy flux parameter (\(F_{b}\)) are defined as below, \[F_{m}=[\frac{\bar{\rho_{s}}}{\bar{\rho}}]\,r_{s}^{2}\bar{w_{s}}^{2} \tag{2}\] \[F_{b}=[1-\frac{\bar{\rho_{s}}}{\bar{\rho}}]\,gr_{s}^{2}\bar{w_{s}}^{2} \tag{3}\] where \(\bar{\rho_{s}}\) is smokestack gas density, \(\bar{\rho}\) is atmospheric air density, \(r_{s}\) is smokestack radius, \(\bar{w_{s}}\) is vertical velocity of the smokestack gas, and \(g\) is acceleration due to gravity. It should be noted that if we evaluate the wind speed at the local PC height and not the source height, the calculations should be operated iteratively [65; 66]. PC buoyancy and horizontal momentum movements and consequently PR are strongly affected by the wind [1]. Moreover, in stable conditions with low turbulence, PR is unaffected by wind speed fluctuations, making the measurements difficult. However, significant PR variations in unstable conditions have been witnessed at a fixed distance downwind. ### CNN and convolutional layer CNNs are special types of neural networks suitable for processing grid data, such as image data with a two-dimensional or three-dimensional mesh structure of pixels. The name given to a CNN is derived from the convolutional layers used in it. Each convolutional layer contains several kernels and biases that are locally applied to the input and produces a feature map or an activation map according to the number of filters. If this convolutional layer is applied to the input image in a two-dimensional manner, its \(j^{th}\) feature map \(O_{j}\), which is obtained by applying the \(j^{th}\) kernel, is calculated at the position \((x,y)\) as [71], \[O_{j}^{xy}=B_{j}+\sum_{k}\sum_{m=0}^{M-1}\sum_{n=0}^{N-1}w_{j}^{mn}z_{k}^{(x+m )(y+n)} \tag{4}\] where \(k\) moves along the depth dimension of input \(z\in\mathbb{R}^{p\times q\times r}\) and \(w_{j}^{mn}\) is the two-dimensional kernel weight \(W\in\mathbb{R}^{M\times N}\) at position \((m,n)\). \(B_{j}\) is the bias matrix. ### Mask R-CNN Mask R-CNN is a region-based CNN family member, proposed in [59] and is used widely in different identification tasks, including COCO dataset recognition. Firstly, RCNN was presented in [75], where computer vision techniques generated region proposals. Then in [63], Fast RCNN was introduced with a CNN before region proposals to reduce running time. In 2017, Faster RCNN continued this evolution and offered the RPN to propose regions of interest (ROIs) [76]. Finally, Mask R-CNN, as an extension of Faster RCNN, added a CNN for pixel-level recognition of the border-detected objects. Mask R-CNN is a relatively simple model and easy to generalize to other similar tasks [59]. Therefore, Mask R-CNN can create pixel-level masks for the objects besides object localization and classification tasks. #### 2.3.1 Rpn An RPN is a deep FCN that proposes regions and is crucial to the Mask R-CNN. RPN helps selectively focus on valuable aspects within the input images. This network takes an image and gives a set of region proposals beside their scores for being an object. It slides a window over the convolutional feature map (backbone output) and maps it to a lower-dimension feature. The generated feature is then fed into two fully-connected layers to obtain the proposed regions class (object vs. non-object), and four corresponding coordinates [76]. For each sliding window location, there are a maximum of \(k\) possible proposals which are parameterized relative to \(k\) reference boxes or anchors. RPN is trained end-to-end by back-propagation and stochastic gradient descent. Figure 1 depicts a scheme of RPN in which the proposed regions are generated as the module outputs. #### 2.3.2 Loss function Mask R-CNN loss function is a weighted summation of other losses related to different sections of this comprehensive model. As a definition based on [59], a multi-task loss function is proposed on each sampled ROI as, \[L=L_{cls}+L_{reg}+L_{msk} \tag{5}\] where \(L_{cls}\) recognizes the class type of each object, while \(L_{reg}\) attempts to find the optimum anchor box for each object. Note that, in this study, we have one class, PC. \(L_{msk}\) tries to recognize the optimum object's segment in each bounding box. ## 3 Methodology The proposed method for PR measurement is represented in Figure 2. The images containing PC(s) are fed to DPRNet for PC border detection and recognition. PR is then measured on DPRNet's output based on estimating the critical point (\(R\)) [81]. For this purpose, an asymptotic function [81] is fitted into the PC centerline, extracted by image processing analysis (e.g. morphological operators) [82]. The measured image coordinates of \(R\) are combined with the wind direction information to be processed by geometric transformation calculations. The main output of the system will reveal the PR as a physical height and the distance downwind at which the PR occurs. ### Structure of DPRNet This research aims to precisely recognize the PC of the desired smokestack from a wide range of image datasets captured from the study area. DPRNet is an adapted Mask R-CNN Figure 1: Region proposal network. Figure 2: PR measurement system framework. \(x_{R}\) and \(z_{R}\) are PR distance and PR in the image scale. Similarly, \(X_{R}\) and \(Z_{R}\) represent PR distance and PR, respectively, in real-life scale, and \(WD\) shows the wind direction. version with two novel smokestack PR measurement modules. These modules are 1) the physical module and 2) the loss regularizer module. These modules can improve RPN performance in locating the most probable proposal PCs. Mask R-CNN is the base of our proposed method, one of the widespread border detection and recognition methods. This robust framework can consider the irregular shapes of the PC, its translucent edges, and similar pixel values of the PC to its background [59]. As seen from Figure 3, DPRNet is an application-oriented version of Mask R-CNN to which two new modules have been added. In this architecture, ResNet50 [78] is used as the backbone network to extract feature maps of the input images. Feature Pyramid Network (FPN) uses all these feature maps to generate multi-scale feature maps, which carry more helpful information than the regular feature pyramid. Then, RPN detects the PC by sliding a window over these feature maps to predict whether there is a PC and locate the existing PC by creating bounding boxes. Therefore, we have a set of PC proposals from RPN and the generated feature map by the backbone network. The ROI Align module works to scale the proposals to the feature map level and prevent misalignment by standardizing the aspect ratios of the proposals. Finally, these refined feature maps are sent to three different outputs. The first is a classification block that decides whether the ROI is the foreground (PC). The second one is a regression block which predicts the bounding boxes based on the provided ground truth. And the last block indicates a recognition mask for the detected PC using an FCN [79]. Two modules are added to Mask R-CNN to improve its efficiency and reduce the computational burden. The first module, a simple image processing one, approximates smokestack. The second module attempts to improve the loss related to \(L_{reg}\) by adding a regularizer loss, elaborated in Section 3.1.2. These modules are explained in detail in the following subsections. #### 3.1.1 Physical module Given either an estimated binary image (during inference time) or ground truth binary image (during training time), the smokestack exit can be detected by image processing techniques [82]. It stands to reason that the smokestack exit is the feasible region of the plume rise. As a result, proposed regions can be considered around this point (Figure 3). Thanks to this module, Figure 3: DPRNet architecture. the method does not detect small PC pieces, sometimes seen in different parts of images other than the smokestack exit. #### 3.1.2 Loss regularizer module Based on Section 2.3.2, it is a crucial problem to set an efficient loss function, which can make the model stable as it can get. In this regard, a new regularizer is added to the loss function, which dictates the coordinates of the most attainable PC regions. Indeed, we try to minimize the distance of proposed bounding boxes by RPN and the smokestack exit. If a box with coordinates of \((x,y,w,h)\) is defined here, the regression loss related to the smokestack exit can be defined as, \[L_{seg}=R(u-u^{*}), \tag{6}\] in which, \[\begin{split} u_{x}=\frac{x-x_{a}}{w_{a}},\ \ u_{y}=\frac{y-y_{a}}{h_{a}},\ \ u_{w}=\log{(\frac{w}{w_{a}})},\ \ u_{h}=\log{(\frac{h}{h_{a}})},\\ u_{x}^{*}=\frac{x^{*}-x_{a}}{w_{a}},\ \ u_{y}^{*}=\frac{y^{*}-y_{a} }{h_{a}},\ \ u_{w}^{*}=\log{(\frac{w^{*}}{w_{a}})},\ \ u_{h}^{*}=\log{(\frac{h^{*}}{h_{a}})}\end{split} \tag{7}\] where \(u\) and \(u^{*}\) represent the coordinates of our predicted and ground truth smokestack exit, and \(R\) is the robust loss function. Note that variables with subscript \(a\) and superscript \(*\) represent the anchor coordinate and the ground truth coordinates, respectively, while the rest are defined as the predicted coordinates. The point \((x,y)\) indicates the position of the bounding box's top-left edge and the parameters \(w\) and \(h\) are, respectively, the width and height of the bounding box. Unlike the Mask R-CNN model, in DPRNet, the loss regularizer module (\(L_{seg}\)) minimizes the recognition task errors of a specific PC, which copes with the main problems of this model, such as missing the desired smokestack exit and multi-box proposal for a single PC. \(L_{seg}\) helps us avoid spanning the whole image pixels, causing high training time and computational complexities. ### Geometric transformation To convert the image measurement results to real-world ones, we need to perform some calculations to transform the PR (\(\Delta z\)) and the PR distance (\(X_{max}\)) on an image to real-life measurement using wind direction. The PR distance can be defined as the horizontal distance between the smokestack exit and the point \(R\), discussed in Section 3. Figure 4 shows PR and PR distance definitions on a sample PC image. Figure 4: PR, PR distance, and the point \(R\) on a sample image. \(\theta\) represents the PC deviation due to the wind, and \(S\) shows the smokestack position. As observed in Figures 5 and 6, the PC representative point \(R\) is affected by wind direction and is out of the image plane. Wind direction is always reported as degrees from the north, represented by \(\varphi\). For instance, \(\varphi=90^{\circ}\) is wind from the east, and \(\varphi=180^{\circ}\) is wind from the south. For the configuration used in this study, wind direction relative to the image plane can be obtained as \(\theta=|\varphi-252|\) (Figure 5). Accordingly, \(X_{R}\) can be calculated by the following equation, \[X_{R}=\begin{cases}\dfrac{D}{\tan\theta+\frac{1}{\tan\gamma}}&\text{if }\theta\geq 0\\ \dfrac{D}{\tan\gamma}-\tan\theta&\text{otherwise}\end{cases} \tag{8}\] where \(\gamma\) and \(\theta\) are additional parameters which help us define equations as concisely as we can get. \(D\) indicates the distance between the camera and the smokestack. We define \(G_{R}\) as the value of the ground sample distance at the location of \(R\). Consequently, based on [60], \[G_{R} =\dfrac{X_{R}}{x_{R}} \tag{9}\] \[Z_{R} =G_{R}\times z_{R}\] \[Z_{st} =G\times z_{st}\] where \(Z_{st}\) and \(z_{st}\) are the distance between the smokestack exit and the image center, respectively, in real-life and on image. Thus, the PR and the PR distance for each PC can be calculated as, \[\Delta z=\begin{cases}|Z_{R}|-|Z_{st}|,&\text{if }|Z_{R}|\geq|Z_{s}t|\\ |Z_{st}|-|Z_{R}|,&\text{otherwise}\end{cases} \tag{10}\] \[X_{max}=\sqrt{X_{R}^{2}+Y_{R}^{2}} \tag{11}\] Figure 5: Schematic top view of the region. ## 4 Experimental results and discussion In this section, we describe our image datasets and the industrial area in which these image datasets have been collected and shared. Also, we will explain the validation metrics used to compare our proposed method with the other competitive methods in smoke border detection and recognition. Then, our discussion falls into two last sections, named comparison with existing smoke recognition methods and plume rise measurement, in which the performance of the proposed method is evaluated, and the PR is calculated based on our "DPRNet," respectively. To validate the performance of our proposed method, we used a computer equipped with Core i9, 3.70 GHz/4.90 GHz, 20 MB cache CPU, 64GB RAM and NVIDIA GeForce RTX 3080,10 GB graphic card. The total training time of the network was about one hour using Python 3.8 with PyTorch Deep Learning framework. Finally, for the geometric transformation and image processing analysis, we used MATLAB R2022b software. ### Site description The imaging system was deployed on a meteorological tower with a clear sightline to the desired smokestack operated by the Wood Buffalo Environment Association (WBEA). It is located outside the Syncrude oil sands processing facility north of Fort McMurray, Alberta, Canada. Figure 7 represents the satellite images, the location of the camera, and the desired smokestack. WBEA operates a 10-meter-tall meteorological tower with a clear sightline to the smokestack at Syncrude ([https://wbea.org/stations/buffalo-viewpoint](https://wbea.org/stations/buffalo-viewpoint)). The camera system is mounted on this tower above the tree canopy because they are on a hill slop Figure 6: Smokestack location schemes. Smokestack location, \(S\); image center, \(O\); desired point, \(R\); PC centerline, \(CL\); point horizontal distance from the image center, \(x_{R}\); the point vertical distance from the image center, \(z_{R}\); the point distance from the image center, \(z_{st}\); depth of the point in the real world, \(Y_{R}\); wind direction angle relative to the image plane, \(\theta\); and the yellow arrow shows the wind direction. Figure 7: Imaging situation. Camera station, \(C\); and smokestack position, \(S\). The _abc_ coordinate system is only for differentiating the side and camera views and is not used as a coordinate reference system. location, and the biggest smokestack and its PC are always visible. The system consists of a digital camera with shutter control and a camera housing for weather protection with interior heating for window defrost and de-icing. The station powers the camera activation, and the images are recorded on a laptop. The Syncrude processing facility has six main smokestacks. The tallest one is about 183 m, and the heights of the other five are between 31 m to 76 m. To isolate a single smoke plume rise, we have concentrated on the area's tallest one, which can help find the PR for one plume source. All six smokestacks are listed in Table 1. Wind directions during the capturing period were determined from the Mildred lake Air Monitoring Station ([https://wbea.org/stations/mildred-lake](https://wbea.org/stations/mildred-lake)), which is located at the Mildred Lake airstrip (AMS02: Latitude: 57.05\({}^{\circ}\), Longitude: \(-111.56^{\circ}\)), approximately 5 km from the Syncrude facility. ### Dprd The greatest challenge in using deep learning for PC recognition is inadequate annotated images for training. Hence, creating image datasets for PC recognition for research and industry purposes is invaluable. For this study, 96 images were captured every day, and for the first part of the project, **35K** images were collected from **January 2019** to **December 2019**. The collected images demonstrated various types of plume shapes in different atmospheric conditions. Dataset has been classified into day, night, and cloudy/foggy conditions. The collected dataset revealed that among 96 images captured daily, we have 48 day and 48 night images. There were some outlier images for different reasons, such as camera handle shaking, auto-focus problems, disturbing smoke and severe snow and hair. Furthermore, some PCs could not be recognized from their background, even by visual image inspection. As a consequence, among **35K** collected images, **10684** images were valid. Note that, among **10684** collected valid images, the facility is not working in **2374** images. For this paper, a new benchmark, DPRD including a 2500 annotated dataset is introduced. 60% of DPRD is considered as training data, and 40% is used for validation and testing purposes. Rows (a) and (b) in Figure 11 shows sample images from the region and their corresponding ground truth, which are generated by the "Labelme" graphical image annotation tool at [https://github.com/wkentaro/labelme](https://github.com/wkentaro/labelme). We tried to select images of different atmospheric conditions, such as clear daytime, nighttime, cloudy, and foggy, to represent the results of different situations. ### Model validation metrics The performance of the methods in question is evaluated using the metrics of accuracy, recall, precision and F1 score. These metrics are defined using four values of True Positive (TP), True Negative (TN), False Positive (FP), and False Negative (FN) obtained from the confusion matrix of each introduced method [83]. The accuracy validation metric is the ratio \begin{table} \begin{tabular}{c c c c c c c} \hline \hline **Reported** & **Latitude** & **Longitude** & \(h_{s}\)**(m)** & \(d_{s}\)**(m)** & \(\omega_{s}\)**(ms\({}^{-1}\))** & \(T_{s}\)**(K)** \\ **ID** & **Latitude** & **Longitude** & \(h_{s}\)**(m)** & \(d_{s}\)**(m)** & \(\omega_{s}\)**(ms\({}^{-1}\))** & \(T_{s}\)**(K)** \\ \hline Syn. 12908 & 57.041 & -111.616 & 183.0 & 7.9 & 12.0 & 427.9 \\ Syn. 12909 & 57.048 & -111.613 & 76.2 & 6.6 & 10.1 & 350.7 \\ Syn. 13219 & 57.296 & -111.506 & 30.5 & 5.2 & 8.8 & 355.0 \\ Syn. 16914 & 57.046 & -111.602 & 45.7 & 1.9 & 12.0 & 643.4 \\ Syn. 16915 & 57.046 & -111.604 & 31.0 & 5.0 & 9.0 & 454.5 \\ Syn. 16916 & 57.297 & -111.505 & 31.0 & 5.2 & 9.2 & 355.0 \\ \hline \hline \end{tabular} \end{table} Table 1: Syncrude smokestacks information, including location, smokestack height (\(h_{s}\)), smokestack diameter (\(d_{s}\)), effluent velocity at the smokestack exit (\(\omega_{s}\)), and effluent temperature at the smokestack exit (\(T_{s}\)). The velocities and temperatures are averages for the entire capturing period. of observations predicted correctly to the total observations. In our application, the model's accuracy represents how accurately our model can recognize the PC pixels. This criterion is valid as long as the values of FP and FN are almost the same [83]. Otherwise, other validation metrics should be considered. The foreground pixel coverage of the sample images are shown in Figure 8, which confirms the fact that accuracy is not suitable for this study. Recall or sensitivity is the ratio of positive observations predicted correctly to all actual observations. Recall shows how many PC pixels are labelled among all the actual PC pixels. The recall is obtained as follows, \[Recall=\frac{TP}{TP+FN} \tag{12}\] Precision is the ratio of positive observations which are predicted correctly to all observations which are predicted as positive. This metric represents how many PC pixels exist among all the pixels labelled as PC. Therefore, a low rate of FP can achieve high precision. This validation metric is obtained as follows, \[Precision=\frac{TP}{TP+FP} \tag{13}\] As it is implied from the Equations 4.3 and 4.3, precision and recall take either FP or FN into account. The last validation measure in this paper, the F1 score, considers both FP and FN as a weighted average of recall and precision metrics. Unlike accuracy, this metric is more useful when FP and FN are not the same as in our study. Our FP is less than FN, or the amount of non-actual PC pixels predicted as PC pixels is less than that of actual PC pixels predicted as non-PC pixels. Therefore, the F1 score helps us look at both recall and precision validation metrics as follows, \[F1score=\frac{2\times Recall\times Precision}{Recall+Precision} \tag{14}\] ### Comparison with existing smoke recognition methods In this section, we evaluate the performance of DPRNet and compare it with several competitors. To choose suitable smoke recognition methods for comparison, we considered both identification accuracy and computational complexity of the reviewed methods, which led to the selection of DeepLabv3+ [80], FCN [79], and regular Mask R-CNN. Our proposed DPRNet is evaluated using three metrics introduced in Section 4.3. The confusion matrix of DPRNet recognition is given in Table 2 for three specific conditions of daytime, nighttime, and cloudy & foggy. Figure 8: Sample images (up) and their corresponding ground truth (down) from our DPR dataset listed as (a) Clear daytime, (b)&(c) cloudy day, and (d)&(e) clear nighttime. As is clear from Table 3, DPRNet has much better performance than competitive methods in terms of all validation metrics. In detail, the recall and precision metrics express the reasonable difference between the models, which shows the effectiveness of the proposed model in recognizing the actual PC pixels. Compared to the rivals, the more considerable value of the F1 score guarantees that DPRNet outperforms the other three methods and shows the efficacy of this method. Among our competitive methods, DeepLabv3 performed better regarding all validation metrics, and Mask R-CNN had the worst performance. Besides these average values, the detailed statistics for each model are given in Figure 9 in terms of each used validation metrics for 90 test images selected from various day, night, foggy, and cloudy conditions. At a glance, it is observed that our proposed method shows the most robustness in all circumstances. Of competitors, Mask R-CNN and FCN have the worst performance, whereas, DeepLabv3 has the best efficiency slightly. To further validate our DPRNet performance, we compared the models over the day, night and foggy & cloudy datasets in terms of different validation metrics, which is given in Figure 10. It can be observed that all methods, except Mask R-CNN, have acceptable performance using day and night datasets. Even with night precision, FCN is better than our proposed method. However, as discussed in Section 4.3, this metric can not completely convey the merit of a model individually, and it needs to be analyzed with the F1 score. Our proposed DPRNet seems to outperform the other rival methods by recognizing roughly all of the PC pixels correctly. Most datasets are related to cloudy and foggy conditions and are frequently seen within image batches. The strength of our DPRNet is its powerful performance in this case, which is of paramount importance in our application. The DPRNet could improve the recall metric by %66, %58, and %87 on average in cloudy and foggy conditions relative to FCN, DeepLabv3, and Mask R-CNN frameworks, respectively, which means that the proposed method is able to find the PC regions appropriately, using \(L_{seg}\). This capability produces high-quality image recognition with a more complicated mixture of PCs and the sky behind. These high recall values help us meet our research application requirement, in which we should identify the entire PC stream for PR distance measurement. To demonstrate the qualitative results of the proposed method, we show some visual results to compare competitive methods. Figure 11 depicts these recognition results. The first \begin{table} \begin{tabular}{c c c c c c} \hline & **P-D (\%)** & **NP-D (\%)** & **P-N (\%)** & **NP-N (\%)** & **P-CF (\%)** & **NP-CF (\%)** \\ \hline \(\mathbf{P^{1}}\)**-\(\mathbf{D^{2}}\)** & 99.2 & 0.04 & - & - & - & - \\ \(\mathbf{NP^{3}}\)**-\(\mathbf{D}\)** & 0.12 & 0.68 & - & - & - & - \\ \(\mathbf{P}\)**-\(\mathbf{N^{4}}\)** & - & - & 99.06 & 0.09 & - & - \\ \(\mathbf{NP}\)**-\(\mathbf{N}\)** & - & - & 0.09 & 0.76 & - & - \\ \(\mathbf{P}\)**-\(\mathbf{CF^{5}}\)** & - & - & - & - & 99.09 & 0.05 \\ \(\mathbf{NP}\)**-\(\mathbf{CF}\)** & - & - & - & - & 0.13 & 0.72 \\ \hline \end{tabular} * \({}^{\dagger}\)Plume 2 Day 3 Non-plume 4 Night 5 Cloudy and foggy \end{table} Table 2: Average confusion matrix of our DPRNet recognition model. \begin{table} \begin{tabular}{c c c c} \hline \hline **Model** & **Recall** & **Precision** & **F1 score** \\ \hline Mask R-CNN & 0.556 & 0.727 & 0.607 \\ FCN & 0.591 & 0.859 & 0.599 \\ DeepLabv3 & 0.654 & 0.892 & 0.721 \\ DPRNet & \(\mathbf{0.846}\) & \(\mathbf{0.925}\) & \(\mathbf{0.881}\) \\ \hline \hline \end{tabular} \end{table} Table 3: Comparison of different methods for plume cloud recognition using average validation metrics values. two rows represent the input images and their corresponding ground truths, respectively, and the other rows give the output of different models. We tried to visualize samples from all classes such that the first two images are related to cloudy/foggy conditions, the second two are from the nighttime dataset, and the last two are obtained from our daytime dataset. It is observed that DPRNet outperformed the other methods by attaining high accuracy of PC localization and, consequently, correctly recognizing the desired smokestack PC. ### Plume rise measurement As we discussed in Section 3, DPRNet gives PC border detection and recognition. Then, an asymptotic function is fitted to the smokestack PC centerline to measure PR using the critical point \(R\)[81]. Taking advantage of point \(R\) image coordinate and the wind direction information from the meteorological tower, real-life PR measurement is obtained through geometric transformations. Figure 12 illustrates the asymptotic curve for four plume cloud images and the automatically chosen point \(R\) where the PC reaches neutral buoyancy. Also, the PR and PR distance values of each sample PC are given in Table 4, as well as the averaged hourly measured wind directions at the image sampling times. Figure 9: Performance of different methods regarding some test images (**a**) recall, (**b**) precision and (**c**) F1 score metrics. ## 5 Conclusion To measure the PR through remote sensing images, PC border detection and recognition is of the essence as the first step. In this regard, a novel deep learning-based method, inspired by \begin{table} \begin{tabular}{c c c c c c c} \hline \hline \multirow{2}{*}{**Image**} & \multirow{2}{*}{\begin{tabular}{c} **Date** \\ **(Y-M-D)** \\ \end{tabular} } & \multirow{2}{*}{\begin{tabular}{c} **Time** \\ **(H-M-S)** \\ \end{tabular} } & \multirow{2}{*}{\begin{tabular}{c} **\(\boldsymbol{\varphi}\) (deg.)** \\ \end{tabular} } & \multirow{2}{*}{\begin{tabular}{c} **\(\boldsymbol{\theta}\) (deg.)** \\ \end{tabular} } & \multirow{2}{*}{\begin{tabular}{c} **\(\boldsymbol{\Delta z}\) (m)** \\ \end{tabular} } & \multirow{2}{*}{ \begin{tabular}{c} **\(\boldsymbol{X_{max}}\) (m)** \\ \end{tabular} } \\ \hline I1 & 2019-11-08 & 18-00-13 & 12.16 & -239.8 & 177 & 1685 \\ I2 & 2019-11-09 & 15-00-13 & 3.46 & -248.5 & 450.3 & 3287 \\ I3 & 2019-11-14 & 10-00-16 & 10.41 & -241.6 & 266.8 & 2280 \\ I4 & 2019-11-16 & 11-00-12 & 10.83 & -241.1 & 300.5 & 2905 \\ \hline \hline \end{tabular} \end{table} Table 4: PR and PR distance values of each of four PC images and the averaged hourly measured wind directions based on the monitoring station information. Figure 12: DPRNet and image measurement results. In column (c), the red curve represents the meandering of the PC. The cyan and yellow lines, respectively, illustrate the upper and lower boundaries of the PC. Green dashes show the asymptotic curve, and the magenta point represents the point \(R\). Figure 10: Detailed comparison of methods over three datasets employing (a) recall, (b) precision and (c) F1 score metrics. the nature of the problem, is proposed in this paper to detect and recognize the PC accurately. In the next stage, image processing analysis is leveraged to extract the PC centerline. Afterward, the critical point of this curve is estimated, the y-component coordinate of which is equivalent to PR. Lastly, this image measurement is transformed into real-life world under the geometric transformation stage. Experimental results indicate that the proposed method significantly outperformed its rivals. The proposed method face difficulty in the scene where there are several smokestacks. Our future studies focus on multi-source PCs, which frequently occur in industrial environments. ## 6 Acknowledgements We want to acknowledge Wood Buffalo Environmental Association (WBEA) for assistance with the camera installation and maintenance at the air-quality monitoring site in the Syncrude facility in northern Alberta, Canada. The project is funded by the "Lassonde School of Engineering Strategic Research Priority Plan" and "Lassonde School of Engineering Innovation Fund," York University, Canada, and "Natural Sciences and Engineering Research Council of Canada - NSERC (grant no. RGPIN 2015-04292)."
2306.09866
Advanced discretization techniques for hyperelastic physics-augmented neural networks
In the present work, advanced spatial and temporal discretization techniques are tailored to hyperelastic physics-augmented neural networks, i.e., neural network based constitutive models which fulfill all relevant mechanical conditions of hyperelasticity by construction. The framework takes into account the structure of neural network-based constitutive models, in particular, that their derivatives are more complex compared to analytical models. The proposed framework allows for convenient mixed Hu-Washizu like finite element formulations applicable to nearly incompressible material behavior. The key feature of this work is a tailored energy-momentum scheme for time discretization, which allows for energy and momentum preserving dynamical simulations. Both the mixed formulation and the energy-momentum discretization are applied in finite element analysis. For this, a hyperelastic physics-augmented neural network model is calibrated to data generated with an analytical potential. In all finite element simulations, the proposed discretization techniques show excellent performance. All of this demonstrates that, from a formal point of view, neural networks are essentially mathematical functions. As such, they can be applied in numerical methods as straightforwardly as analytical constitutive models. Nevertheless, their special structure suggests to tailor advanced discretization methods, to arrive at compact mathematical formulations and convenient implementations.
Marlon Franke, Dominik K. Klein, Oliver Weeger, Peter Betsch
2023-06-16T14:28:03Z
http://arxiv.org/abs/2306.09866v1
# Advanced discretization techniques for hyperelastic physics-augmented neural networks ###### Abstract In the present work, advanced spatial and temporal discretization techniques are tailored to hyperelastic physics-augmented neural networks, i.e., neural network based constitutive models which fulfill all relevant mechanical conditions of hyperelasticity by construction. The framework takes into account the structure of neural network-based constitutive models, in particular, that their derivatives are more complex compared to analytical models. The proposed framework allows for convenient mixed Hu-Washizu like finite element formulations applicable to nearly incompressible material behavior. The key feature of this work is a tailored energy-momentum scheme for time discretization, which allows for energy and momentum preserving dynamical simulations. Both the mixed formulation and the energy-momentum discretization are applied in finite element analysis. For this, a hyperelastic physics-augmented neural network model is calibrated to data generated with an analytical potential. In all finite element simulations, the proposed discretization techniques show excellent performance. All of this demonstrates that, from a formal point of view, neural networks are essentially mathematical functions. As such, they can be applied in numerical methods as straightforwardly as analytical constitutive models. Nevertheless, their special structure suggests to tailor advanced discretization methods, to arrive at compact mathematical formulations and convenient implementations. **Keywords:** finite element analysis, dynamic simulations, energy momentum scheme, mixed methods, hyperelasticity, physics-augmented neural networks ## 1 Introduction In continuum mechanics, the motion of solid bodies is described by field equations, comprised of kinematic relations and balance laws which both are valid in general, and material specific constitutive models [103]. These field equations reflect our understanding of how material bodies behave and carefully fulfill important physical conditions. However, when applying standard numerical methods such as the widely used Newmark scheme or midpoint rule, which are well-established for linear problems, the discretization usually influences the physics in the nonlinear regime and is inclined to numerical instabilities. This is particularly the case in dynamic simulations, where the temporal discretization does not preserve necessary physical properties of their continuous counterparts [32, 35]. To address this problem, an abundant number of structure-preserving methods, also known as geometric integrators, were proposed. These methods are designed to preserve the physics of the continuous system during the time discretization process and thereby enhance the numerical stability. There is a great variety of structure-preserving methods in the literature, which roughly can be divided into symplectic methods and energy-momentum schemes (EMS) [38, 96]. These methods can be distinguished by preserving different invariants of the system, where for instance the simultaneous preservation of the invariants, i.e. total energy, momentum maps and simplecticity, is in general not possible [68, 111]. Here we restrict our consideration to the established EMS, in particular to the discrete gradient versions thereof, which preserve both linear and angular momentum maps, and the total energy of the system. The mechanism behind the EMS can be understood as an explicit [99] or, in case of the discrete gradients, implicit [32, 33] momentum-preserving projection of the midpoint rule onto the surface of constant energy [96, 98]. EMS are promising since they fulfill most design criteria for a practical time-stepping scheme as suggested by [8]. In that regard, the EMS is applicable for elastic and inelastic problems, it does not use additional variables (e.g. Lagrange multipliers) or parameters to be provided by the analyst, it is second-order accurate, and exhibits similar stability properties in large deformations and long term simulations for coarse time step sizes as energy-conserving integrators in linear analysis. The only drawbacks associated with the EMS are that the method leads to unsymmetric tangent stiffness matrices and that the implementation is more involved by different time point evaluations of stresses and remaining parts of the equations. The development of EMS can be traced back to the early works of [35, 63, 64, 65], which provide energy and momentum conserving methods for particle dynamics. Especially the work of [35] provided a formula which conserves both momentum maps and total energy for energy densities with only scalar dependencies. In the pioneering work [99] the so-called discrete energy-momentum method has been proposed, which has been improved and properly reformulated in [67]. A milestone in the development of EMS, which circumvents the use of the mean value algorithm and its associated solution of a nonlinear equation on quadrature point level used in [99], is related to the work [32, 33] where the discrete gradient EMS has been proposed. It is applicable to arbitrary nonlinear hyperelastic material models, leading to a projection-based algorithmic stress formula, and as a special case contains both the midpoint averaging of the strains for quadratic potentials [99] and the Greenspan formula [35] for scalar dependencies of the energy density. Other areas of successful developments of EMS are located in the fields of structural mechanics for nonlinear beams and shells [10, 11, 90, 98], inelasticity [37, 44, 76, 79], elastodynamical contact problems [18, 45, 66], and systems with (non-)holonomic constraints [17, 34], to name but a few. An extension of EMS to dissipative systems is based on the general equation for non-equilibrium reversible irreversible coupling (GENERIC) formulation, which provides a systematic framework facilitating the design of energy-momentum and even entropy consistent schemes [12, 36, 60, 75, 84, 92]. Recently, in [9] a new family of partioned discrete gradients has been proposed which is inspired by polyconvex strain energies [6, 7], leading to a new algorithmic stress formula based on three partioned discrete gradients which represent the algorithmic counterparts of the work conjugates of the right Cauchy-Green strain tensor, its cofactor, and its determinant. The formulation in [9] benefits from the so-called tensor cross-product, first published in [21] and kind of rediscovered in the field of computational nonlinear elasticity in [13], which is based on a Hu-Washizu type mixed variational formulation and leads to a remarkably simple structure for the algorithmic stress. This work has given rise to several polyconvexity-inspired works in the field of coupled problems, in particular for finite thermo-elastodynamics [28, 83], nonlinear electro-elastodynamics [26, 82], and nonlinear thermo-electro-elastodynamics [27, 29]. In addition to the above mentioned sophisticated temporal discretization methods, significant progress has been made in the development of advanced spatial discretization techniques over the past few decades. In partiuclar, an abundant number of mixed finite element (FE) formulations in elasticity based on Hu-Washizu variational functionals [107] have been developed [4, 9, 13, 95, 97]. These formulations aim to address the issue of locking which standard displacement-based formulations are prone to. Shifting the focus to constitutive modeling, the mechanical conditions underlying hyperelasticity were extensively discussed in the last decades [20, 103], and sophisticated analytical models were formulated to fulfill all constitutive conditions by construction [22, 94]. While the constitutive conditions that these models fulfill have a sound mechanical motivation, their explicit choice of functional relationship usually does not. Rather, it is heuristically motivated, such as the polynomial form of the Ogden model [81]. This human choice of functional relationship easily restricts the function space that a model can represent, thus introducing an undesired _model uncertainty_[50]. This is a major drawback of analytical constitutive models. On the other side, artificial neural networks (NN) are highly flexible functions, in fact, they are universal approximators [47]. However, when applied to mechanical problems, standard NNs easily violate physical conditions and require large amounts of calibration data. Hyperelastic physics-augmented neural networks (PANNs)1 aim to combine the best of both worlds. Here, NN-based models are formulated which fulfill all mechanical conditions of hyperelasticity by construction. This yields highly flexible yet reliable constitutive models. Furthermore, the constitutive conditions included in the model formulation serve as an _inductive bias_[41], which highly improves the models generalization properties and allows for a calibration with moderately sized datasets that could stem from experimental material characterization. Footnote 1: Following [69], we denote physics-augmented neural networks (PANNs) as NN-based constitutive models which fulfill all relevant mechanical conditions by construction. Basically, NNs are applied to represent hyperelastic potentials, which benefit from the excellent flexibility of NNs. In the same manner as analytical constitutive models [22, 94], NN-based potentials can be formulated in terms of invariants [52, 55, 56, 71, 102], thus ensuring several mechanical conditions by construction. Other approaches formulate potentials directly in terms of the components of strain tensors [5, 23, 55, 100, 105]. For the formulation of polyconvex potentials, several approaches exist [19, 55, 72, 101, 102], where the most noteworthy approaches are based on input-convex neural networks (ICNNs). Proposed in a pioneering work by [3], this special network architecture is attractive for, e.g., physical applications which require convexity [48] and convex optimization [14, 15]. While the aforementioned NN-based models fulfill some constitutive conditions in an exact way, other conditions are only approximated. E.g., the model proposed by [55] fulfills several conditions including polyconvexity in an exact way, but only approximates the stress-free reference configuration. Indeed, in the framework of NN-based constitutive models, it is possible to fulfill constitutive conditions only in an approximate fashion [78, 108, 109], e.g., the NN can learn to approximate a condition through data augmentation [70], or the loss function can include physical conditions [53]. For some applications this is even necessary, e.g., when a formulation in invariants leads to a loss of information, which is the case for some anisotropy classes [55]. However, since fulfilling a mechanical condition by construction is the only way to be absolutely sure about its fulfillment, if possible, this should be preferred over approximations. Finally, in the works of [72] and [69], NN-based models were proposed which fulfill all common mechanical conditions of hyperelasticity by construction. While the work of [72] is restricted to incompressible material behavior, the work of [69] is formulated for general, compressible material behavior. In the present work, the model proposed by [69] is applied, which is an extension of the polyconvex model proposed by [55]. The model fulfills mechanical conditions in several ways, first of all, by a cautious _choice of inputs_ for the NN (i.e., polyconvex invariants). Furthermore, the _special choice of network architecture_ (i.e., ICNNs) preserves the polyconvexity of the invariants. In addition, _analytical growth terms_ and _invariant-based normalization terms_ ensure a physically sensible energy and stress behavior. In that light, one could argue that the PANN model proposed by [69] is actually quite close to analytical constitutive models, with the only difference being the choice of ansatz function for the constitutive model. By using ICNNs as ansatz functions, the flexibility of the model can be increased to an arbitrary amount, while even for large number of model parameters, their calibration is still straightforward. The most obvious reason to apply PANN models is their extraordinary flexibility in conjunction with their physically well motivated basis. In particular, PANN constitutive models can represent the highly challenging homogenized behavior of microstructured materials, for which analytical models may not be flexible enough [55]. This allows for very efficient simulation of microstructured materials [31, 52, 78]. The flexibility has another implication, namely, PANNs can represent a variety of analytical constitutive models. In fact, for a wide range of applications, analytical constitutive models are flexible enough. However, there is a vast number of analytical constitutive models, and finding a suitable one can be very demanding and requires a lot of expert knowledge in both the choice and calibration of the model [89]. This can be bypassed by NN-based constitutive models, which automatically find the best function out of a very rich function space. Another noteworthy approach for this is the data-driven framework proposed by [24, 25], where an approach for the automated discovery of analytical constitutive models is introduced. On the downside, the flexibility of PANNs goes along with a lack of traceability. Indeed, some analytical constitutive models base their choice of functional relationship on physical reasoning, such as the hyperelastic Hencky model [42, 43, 74]. For such models, the material parameters have a clear physical interpretation. This is in contrast to NN-based models, which have a large amount of parameters which are generally inaccessible to a clear interpretation [55, Sect. 6]. However, it should be noted that this is also the case for moderately flexible analytical models such as the Ogden model [81]. Finally, with data-driven approaches it is also possible to circumvent the formulation of an explicit, analytical constitutive model [16, 54, 88]. To close, in the era of artificial intelligence and big data, it is indeed possible to largely abandon the formulation of models and let ML methods purely work on data [87]. However, it is broadly accepted that including scientific knowledge in ML methods has a multitude of advantages in many scientific fields [53, 61, 73, 85, 106]. Overall, the scientific knowledge developed in the last centuries is not to be omitted, instead, the use of ML methods allows to apply them in a new light, and thereby, to exploit the advantages of up-to-date techniques. From a formal point of view, NNs are nothing more but mathematical functions. As such, they can be applied in standard numerical methods as straightforwardly as analytical constitutive models. However, compared to analytical constitutive models, NN-based constitutive models comprise far more complicated functional relationships. Thus, while applying standard methods is indeed possible, it potentially leads to demanding mathematical formulations and implementations. This can be circumvented by tailoring numerical methods to the special structure of NN-based constitutive models. In the present work, advanced spatial and temporal discretization techniques are tailored to the special structure of hyperelastic PANN constitutive models. In particular, inspired by [9, 13, 59], the polyconvex structure of PANN models is taken into account. Furthermore, the numerical methods are formulated to conveniently handle the - possibly very complex - functional relationships of NN-based constitutive models. This is done by setting the focus on invariant-based formulations. Based on these ideas, a new Hu-Washizu like mixed formulation is proposed which uses scalar-valued strain invariants as additional unknowns. Furthermore, a novel discrete gradient EMS is designed, which mostly relies on scalar-valued formulations in terms of strain invariants. To the best knowledge of the authors, both mixed spatial methods and discrete gradient integration schemes have not yet been tailored to PANN constitutive models so far. The outline of the manuscript is as follows. In Sect. 2, the basics of hyperelasticity are introduced, which are relevant for the PANN constitutive model introduced in Sect. 3. In Sect. 4, continuum formulation and variation tailored to PANN models are introduced. This is followed by the energy- and momentum consistent time discretization introduced in Sect. 5 and the spatial FE discretization discussed in Sect. 6. Stability and robustness of the proposed framework are examined in representative numerical examples in Sect. 7. After the conclusion in Sect. 8, the appendices provide some additional information on the proposed EMS. NotationThroughout this work, tensor composition and contraction are denoted by \(\left(\mathbf{A}\,\mathbf{B}\right)_{ij}=A_{ik}B_{kj}\) and \(\mathbf{A}:\mathbf{B}=A_{ij}B_{ij}\), respectively, with vectors \(\mathbf{a}\), \(\mathbf{b}\) and second order tensors \(\mathbf{A}\), \(\mathbf{B}\). Note that the Einstein summation convention is applied if not otherwise stated. The tensor product is denoted by \(\otimes\), the second order identity tensor by \(\mathbf{I}\). Transpose and inverse of a second order tensor \(\mathbf{A}\) are denoted as \(\mathbf{A}^{\mathrm{T}}\) and \(\mathbf{A}^{-1}\), respectively. The tensor cross product as introduced by [21] is defined as \(\mathbf{A}\bigstar\mathbf{B}=\varepsilon_{ijk}\,\varepsilon_{\alpha\beta \gamma}\,A_{j\beta}\,B_{k\gamma}\,\mathbf{e}_{i}\otimes\mathbf{e}_{\alpha}\), where \(\varepsilon_{ijk}\) denotes the third-order permutation tensor. For a discussion of the properties of the tensor cross product, see [13]. Furthermore, trace, determinant and cofactor are denoted by \(\mathrm{tr}\,\mathbf{A}\), \(\det\mathbf{A}\) and \(\mathrm{cof}\,\mathbf{A}:=\det\left(\mathbf{A}\right)\,\mathbf{A}^{-\mathrm{T}}\), respectively. The space of second order tensors is denoted as \(\mathbb{T}^{3}:=\left\{\mathbf{A}\in\mathcal{L}(\mathbb{R}^{3},\mathbb{R}^{3})\right\}\), the set of invertible second order tensors with positive determinant is denoted by \(\mathbb{T}^{3}_{+}:=\left\{\mathbf{A}\in\mathbb{T}^{3}\,|\,\det(\mathbf{A})>0\right\}\), and the set of symmetric invertible second order tensors with positive determinant is denoted by \(\mathbb{S}^{3}_{+}:=\left\{\mathbf{A}\in\mathbb{T}^{3}_{+}\,|\,\mathbf{A}= \mathbf{A}^{\mathrm{T}}\right\}\). The orthogonal and special orthogonal group in \(\mathbb{R}^{3}\) are denoted by \(\mathrm{O}(3):=\left\{\mathbf{A}\in\mathbb{T}^{3}\,|\,\,\mathbf{A}^{\mathrm{T }}\mathbf{A}=\mathbf{I}\right\}\) and \(\mathrm{SO}(3):=\left\{\mathbf{A}\in\mathbb{T}^{3}\,|\,\,\mathbf{A}^{\mathrm{ T}}\mathbf{A}=\mathbf{I},\,\,\det\mathbf{A}=1\right\}\), respectively. The space of positive and negative real numbers are denoted by \(\mathbb{R}_{+}:=\left\{x\in\mathbb{R}\,\,|\,\,x>0\right\}\) and \(\mathbb{R}_{-}:=\left\{x\in\mathbb{R}\,\,|\,\,x<0\right\}\), respectively. The first Frechet derivative of a function \(f\) w.r.t. \(\mathbf{X}\) is denoted by \(\partial_{\mathbf{X}}f\), while discrete gradients are denoted by \(D_{\mathbf{X}}f\). ## 2 Basics of hyperelasticity In this section, the kinematic relationships of nonlinear solid mechanics are introduced in Sect. 2.1, followed by the constitutive conditions of hyperelasticity in Sect. 2.2. In Sect. 2.3, the formulation of hyperelastic potentials in terms of strain invariants is discussed. ### Kinematics Let us consider the motion of a solid body. The reference configuration \(\mathcal{B}_{0}\subset\mathbb{R}^{3}\) and the current, deformed configuration \(\mathcal{B}\subset\mathbb{R}^{3}\) are connected via the bijective deformation mapping \(\boldsymbol{\varphi}:\mathcal{B}_{0}\to\mathbb{R}^{3}\), linking material particles \(\mathbf{X}\in\mathcal{B}_{0}\) to \(\mathbf{x}=\boldsymbol{\varphi}(\mathbf{X})\in\mathcal{B}\). The material gradient of the deformation field \(\boldsymbol{\varphi}\), which is denoted as the deformation gradient \(\mathbf{F}:\mathcal{B}_{0}\to\mathbb{T}^{3}_{+}\), is defined as \[\mathbf{F}=\partial_{\mathbf{X}}\boldsymbol{\varphi}(\mathbf{X})\,. \tag{1}\] Then, its determinant \(J:\mathcal{B}_{0}\to\mathbb{R}_{+}\) and its cofactor \(\mathbf{H}:\mathcal{B}_{0}\to\mathbb{T}^{3}_{+}\) follow as \[\begin{split} J&=\det(\mathbf{F})=\frac{1}{3}\, \mathbf{H}:\mathbf{F}=\frac{1}{6}\left(\mathbf{F}\boldsymbol{\Phi}\mathbf{F} \right):\mathbf{F}\,,\\ \mathbf{H}&=\mathrm{cof}(\mathbf{F})=\frac{1}{2}\, \mathbf{F}\boldsymbol{\Phi}\mathbf{F}\,.\end{split} \tag{2}\] Let us furthermore introduce the symmetric Cauchy-Green strain tensor \(\mathbf{C}:\mathcal{B}_{0}\rightarrow\mathbb{S}_{+}^{3}\) as \[\mathbf{C}=\mathbf{F}^{\mathrm{T}}\,\mathbf{F}\,, \tag{3}\] with the corresponding determinant \(C:\mathcal{B}_{0}\rightarrow\mathbb{R}_{+}\) and cofactor \(\mathbf{G}:\mathcal{B}_{0}\rightarrow\mathbb{S}_{+}^{3}\) defined as \[\begin{split} C&=\det(\mathbf{C})=\frac{1}{3}\, \mathbf{G}:\mathbf{C}=\frac{1}{6}\left(\mathbf{C}\boldsymbol{\Psi}\mathbf{C} \right):\mathbf{C}\,,\\ \mathbf{G}&=\operatorname{cof}(\mathbf{C})=\frac{1}{ 2}\,\mathbf{C}\boldsymbol{\times}\mathbf{C}\,.\end{split} \tag{4}\] Based on the above symmetric kinematic set, we introduce the isotropic invariants \(I_{\mathbf{C}}:\mathcal{B}_{0}\rightarrow\mathbb{R}_{+}\), \(II_{\mathbf{C}}:\mathcal{B}_{0}\rightarrow\mathbb{R}_{+}\) and \(III_{\mathbf{C}}:\mathcal{B}_{0}\rightarrow\mathbb{R}_{+}\) as \[I_{\mathbf{C}}=\operatorname{tr}(\mathbf{C})\,,\qquad II_{\mathbf{C}}= \operatorname{tr}(\mathbf{G})\,,\qquad III_{\mathbf{C}}=C\,. \tag{5}\] ### Constitutive conditions The specific mechanical behavior of a hyperelastic material can be expressed by a potential \[W^{\mathrm{F}}\colon\mathbb{T}_{+}^{3}\rightarrow\mathbb{R}\,,\qquad\mathbf{F }\mapsto W^{\mathrm{F}}\left(\mathbf{F}\right)\,, \tag{6}\] which corresponds to the strain energy density stored in the body due to deformation [20, 40, 46]. With the first Piola-Kirchhoff (PK1) stress given as the gradient field \[\mathbf{P}=\partial_{\mathbf{F}}W^{\mathrm{F}}\left(\mathbf{F}\right)\,, \tag{7}\] the **(i) second law of thermodynamics** is fulfilled by construction. The second Piola-Kirchhoff (PK2) stress is given by \[\mathbf{S}=\mathbf{F}^{-1}\mathbf{P}\,. \tag{8}\] The **(ii) balance of angular momentum** implies that \(\mathbf{S}\) is symmetric. Furthermore, the principle of **(iii) objectivity** states that a model should be independent on the choice of observer, which is formalized as \[W^{\mathrm{F}}\left(\mathbf{Q}\,\mathbf{F}\right)=W^{\mathrm{F}}\left(\mathbf{ F}\right)\quad\forall\,\mathbf{Q}\in\mathrm{SO}(3)\,. \tag{9}\] Throughout this work, isotropic material behavior is considered, which is taken into account by the **(iv) material symmetry condition** \[W^{\mathrm{F}}(\mathbf{F}\,\mathbf{Q}^{\mathrm{T}})=W^{\mathrm{F}}\left( \mathbf{F}\right)\quad\forall\,\mathbf{Q}\in\mathrm{O}(3)\,. \tag{10}\] Furthermore, we consider **(v) polyconvex** potentials which allow for a representation \[W^{\mathrm{F}}\left(\mathbf{F}\right)=\hat{W}^{\mathrm{F}}\left(\mathbf{F}, \,\mathbf{H},\,J\right)\,, \tag{11}\] with the kinematical quantities as introduced in Eq. (2) and the function \(\hat{W}^{\mathrm{F}}\) which is convex in the components of \(\mathbf{F}\), \(\mathbf{H}\), and \(J\). The notion of polyconvexity as introduced by Ball [6, 7] stems from a quite theoretical context and is linked to the existence of solutions in finite elasticity. However, it is also the most straightforward way of fulfilling the ellipticity condition [80, 110] \[\left(\mathbf{a}\otimes\mathbf{b}\right):\frac{\partial^{2}W^{\mathrm{F}}\left( \mathbf{F}\right)}{\partial\mathbf{F}\partial\mathbf{F}}\colon\left(\mathbf{a }\otimes\mathbf{b}\right)\geq 0\quad\forall\,\mathbf{a},\mathbf{b}\in \mathbb{R}^{3}\,. \tag{12}\] Also known as material stability, this condition leads to a favorable behavior in numerical applications. Furthermore, a physically sensible energy and stress behavior requires fulfillment of the **(vi) growth condition** \[W^{\rm F}\to\infty\quad\mbox{as}\quad J\to 0^{+}\,, \tag{13}\] as well as that the reference configuration \({\bf F}={\bf I}\) is energy- and stress-free, i.e., \[W^{\rm F}({\bf I})=0\,,\qquad{\bf P}({\bf I})={\bf 0}\,, \tag{14}\] also referred to as **(vii) energy normalisation** and **(viii) stress normalisation**. ### Invariant-based modeling To conclude on the previous section, while in hyperelasticity the **(i) second law of thermodynamics** is fulfilled by construction, the remaining conditions require further considerations in the model formulation. In a first step, by formulating the potential in terms of invariants of the right Cauchy-Green tensor \({\bf C}\), cf. Eq. (5), conditions **(ii-iv)** can be fulfilled. In particular, as isotropic material behavior is assumed, the hyperelastic potential is formulated in terms of isotropic invariants, allowing for the representation \[W^{\rm I}\colon\mathbb{R}_{+}\times\mathbb{R}_{+}\times\mathbb{R}_{+}\to \mathbb{R}\,,\qquad{\boldsymbol{\mathcal{I}}}^{0}\mapsto W^{\rm I}\left({ \boldsymbol{\mathcal{I}}}^{0}\right) \tag{15}\] with \[{\boldsymbol{\mathcal{I}}}^{0}:=(I_{\bf C},\,II_{\bf C},\,J). \tag{16}\] The isotropic invariants introduced in Eq. (5) are polyconvex, in particular, \(I_{\bf C}\) is convex in \({\bf F}\) and \(II_{\bf C}\) is convex in \({\bf H}\). To preserve the polyconvexity of the invariants, the potential \(W^{\rm I}\) is chosen as a convex function in \({\boldsymbol{\mathcal{I}}}^{0}\) and furthermore as _non-decreasing_ in \(I_{\bf C},\,II_{\bf C}\), which overall ensures fulfillment of the **(v) polyconvexity condition**. The non-decreasing condition is owed to the fact that \(I_{\bf C}\), \(II_{\bf C}\) are already non-linear functions of the arguments of the polyconvexity condition, cf. Eq. (11) and Eq. (5), see also [55, Rem. A.10] for an explicit proof and [57, Sect. 2] for a simple 1D example. In contrast to that, \(J\) is the only invariant quantity in the arguments of the polyconvexity condition, meaning that the potential must be convex in \(J\), but may indeed be non-decreasing in \(J\). This additional flexibility of the model in \(J\) is also the reason to not use \(III_{\bf C}\), which would again be a non-linear function in \(J\), and is furthermore essential for the model to represent negative stress values at all, cf. [55]. The subsequent NN-based model formulation is simplified with the slightly adapted version \[\hat{W}^{\rm I}\colon\mathbb{R}_{+}\times\mathbb{R}_{+}\times\mathbb{R}_{+} \times\mathbb{R}_{-}\to\mathbb{R}\,,\qquad{\boldsymbol{\mathcal{I}}}\mapsto \hat{W}^{\rm I}\left({\boldsymbol{\mathcal{I}}}\right)\,, \tag{17}\] with \[{\boldsymbol{\mathcal{I}}}:=(I_{\bf C},\,II_{\bf C},\,J,\,J^{*})\,\qquad J^{*}:=-J\,. \tag{18}\] By this adaption, the function \(\hat{W}^{\rm I}\) can be chosen as a convex function in \({\boldsymbol{\mathcal{I}}}\) and a non-decreasing function in all of its arguments. Note that this general form of the potential does not yet fulfill conditions **(vi-viii)**, which ensure a physically sensible energy and stress behavior of the model. For a formulation of the potential in isotropic invariants, the second Piola-Kirchhoff stress follows as \[{\bf S}=2\partial_{\bf C}\,W^{\rm I}=2\partial_{I_{\bf C}}W^{\rm I}\,{\bf I}+2 \partial_{II_{\bf C}}W^{\rm I}\,{\bf I}\bigstar{\bf C}+\partial_{J}W^{\rm I}\, J^{-1}{\bf G}\,, \tag{19}\] where we made use of the tensor generators [51] \[\partial_{\bf C}I_{\bf C}={\bf I}\,,\qquad\partial_{\bf C}II_{\bf C}={\bf I} \bigstar{\bf C}\,,\qquad\partial_{\bf C}J=\frac{1}{2}J^{-1}{\bf G}\,. \tag{20}\] n analytical example for hyperelastic potentials is the Mooney-Rivlin model, given by \[W^{\rm MR}=a\left(I_{\bf C}-3\right)+b\left(II_{\bf C}-3\right)+\frac{c}{2}\left( J-1\right)^{2}-d\,\log(J)\,,\qquad a,b,c\geq 0\,, \tag{21}\] which is formulated such that it fulfills the remaining conditions **(vi-viii)**. In particular, the stress normalization condition is ensured by the additional constraint \(d=2(a+2b)\). ## 3 Physics-augmented neural network constitutive model In this section, the constitutive equations of the neural network (NN) constitutive model applied throughout this work are introduced in Sect. 3.1, followed by a description of the model calibration process in Sect. 3.2. Afterwards, in Sect. 3.3, the derivatives of the NN-based constitutive model required throughout this work are introduced. ### Constitutive equations As discussed in Sect. 2.3, hyperelastic potentials are usually formulated in terms of invariants of the right Cauchy-Green tensor. When polyconvex invariants are considered and the hyperelastic potential is a convex and non-decreasing function of the invariants, the overall potential is polyconvex. The simple structure and recursive definition of feed-forward neural networks (FFNNs) [2, 58] make them a very natural choice for the construction of convex and non-decreasing functions [3], which suggests to use them for the formulation of polyconvex hyperelastic potentials [55]. Still, the NN is only a part of the overall physics-augmented neural network (PANN) constitutive model proposed by [69], which is given by \[W^{\rm PANN}\left(\boldsymbol{\mathcal{I}}^{0}\right)=W^{\rm NN}\left( \boldsymbol{\mathcal{I}}\right)+W^{\rm stress}\left(J\right)+W^{\rm energy }+W^{\rm growth}\left(J\right)\,, \tag{22}\] with \(\boldsymbol{\mathcal{I}}^{0}\), \(\boldsymbol{\mathcal{I}}\) as defined in Sect. 2.3. Here, \(W^{\rm NN}\) denotes the NN part of the model, which provides the model with its excellent flexibility, while the remaining terms ensure a physically sensible stress and energy behavior of the model, cf. Sect. 2.2. The overall flow and structure of the PANN model is visualized in Fig. 1. In the present work, without loss of generality, neural networks with only one hidden layer are applied, which has shown to be sufficient for the representation of most isotropic hyperelastic potentials [56, 69]. For an introduction to multilayered PANN architectures, the reader is referred to [69]. In the present work, the NN takes the form \[W^{\rm NN}(\boldsymbol{\mathcal{I}})=\mathbf{w}^{2}\cdot\mathcal{SP}\left( \mathbf{w}^{1}\cdot\boldsymbol{\mathcal{I}}+\mathbf{b}\right)\,, \tag{23}\] Figure 1: Illustration of the PANN based constitutive model. Note that the hidden layer (yellow) of the NN may be multilayered. where \(\mathcal{SP}(x)=\log(1+e^{x})\) denotes the _Softplus_ function, which is applied component-wise. This non-linear function is referred to as activation function, while \(\mathbf{w}^{1}\in\mathbb{R}_{\geq 0}^{n\times 4},\,\mathbf{w}^{2}\in\mathbb{R}_{ \geq 0}^{n}\) are referred to as weights, and \(\mathbf{b}\in\mathbb{R}^{n}\) is referred to as bias. When all weights are greater or equal to zero, and the activation function is a convex and non-decreasing function, the overall function Eq. (23) is convex and non-decreasing in \(\boldsymbol{\mathcal{I}}\), thus leading to a polyconvex potential [55]. This is the motivation for using the _Softplus_ activation function, which is convex and non-decreasing, where it should be noted that also other suitable activation functions exist [3, 5]. In general, NNs which are convex in the input are referred to as input-convex neural networks (ICNNs) [3]. Together, weights and bias form the set of model parameters, here denoted as \(\boldsymbol{\mathcal{P}}\), which are optimized in the calibration process to fit the model to a given dataset. For a given input dimension, the size of the weights and bias matrices is determined by \(n\), which specifies the number of nodes / neurons in the NN. This is a hyperparameter of the NN, which is fixed before the model calibration. By increasing \(n\), the model flexibility is increased. The polyconvex stress normalization term as proposed by [69] is given by \[W^{\text{stress}}(J):=-\mathfrak{n}\left(J-1\right)\,, \tag{24}\] where the constant \[\mathfrak{n}:=2\left(\partial_{I\mathbf{C}}\,W^{\text{NN}}+2\partial_{II \mathbf{C}}\,W^{\text{NN}}+\frac{1}{2}\partial_{J}\,W^{\text{NN}}-\frac{1}{2} \partial_{J^{*}}\,W^{\text{NN}}\right)\bigg{|}_{\mathbf{F}=\mathbf{I}}\in \mathbb{R} \tag{25}\] is a weighted sum of derivatives of the NN potential with respect to the invariants for the undeformed state \(\mathbf{F}=\mathbf{I}\). The stress correction term preserves polyconvexity as it is linear in \(J\). The energy normalization term is given by \[W^{\text{energy}}:=-W^{\text{NN}}\Big{|}_{\mathbf{F}=\mathbf{I}}\in\mathbb{R}\,. \tag{26}\] Finally, the volumetric growth term is chosen as the analytical, polyconvex function \[W^{\text{growth}}(J)=(J+J^{-1}-2)^{2}\,. \tag{27}\] Setting aside the nomenclature of machine learning, one could consider Eq. (22) as a classical constitutive model, which uses linear transformations in combination with the _Softplus_ function as an ansatz for hyperelastic potentials, cf. Eq. (23). Then, two benefits compared to other hyperelastic constitutive models become obvious. First of all, the function \(W^{\text{NN}}\) allows for a strong interrelation between the different invariants, which becomes even more clear when considering the derivatives of the potential, cf. Sect. 3.3. This is in contrast to most analytical polyconvex constitutive models. For such models, the strain energy function is usually additively decomposed in the invariants [22], see e.g. Eq. (21). This is due to the fact that multiplication of polyconvex invariants does not preserve polyconvexity [39]. The NN-potential in Eq. (23), however, allows for a strong interrelation between the invariants, while also preserving their polyconvexity. The second benefit is the immediate possibility to increase the model flexibility, basically to an arbitrary amount [47]. While analytical constitutive models generally can become also very flexible, e.g., by considering enough terms in the polynomial ansatz of the Ogden model [81], their calibration quickly becomes infeasible. In contrast, the NN ansatz in Eq. (23) has proven to be very stable in the calibration, even for large number of parameters [55]. In this regard, it should be mentioned that the PANN model does not suffer from phenomena such as overfitting, since the inclusion of physics provides the model with a pronounced mathematical structure [69]. ### Model calibration After fixing the model architecture, here, the number of nodes \(n\), the model parameters \(\mathbf{\mathcal{P}}\) can be optimized to fit the model to a given dataset. Throughout this work, datasets of the form \[\mathcal{D}=\left\{\left({}^{1}\mathbf{C},\,{}^{1}\mathbf{S}\right),\ldots, \left({}^{m}\mathbf{C},\,{}^{m}\mathbf{S}\right)\right\}\,, \tag{28}\] are considered, consisting of \(m\) strain-stress tuples in the right Cauchy-Green deformation tensor \(\mathbf{C}\) and the second Piola-Kirchhoff stress \(\mathbf{S}\). Thereby, two distinct datasets are created. A calibration dataset \(\mathcal{D}_{c}\), which is used to calibrate the model, and a test dataset \(\mathcal{D}_{t}\), which is used to examine the models generalization, i.e., its capability to predict load cases not included in the calibration process. To this end, the test dataset \(\mathcal{D}_{t}\) should consist of fairly general load cases. Then, the loss function given as the mean squared error \[\mathcal{MSE}\left(\mathbf{\mathcal{P}}\right)=\frac{1}{9\text{Pa}^{2}}\frac{1}{m_ {c}}\sum_{i=1}^{m_{c}}\left\|{}^{i}\mathbf{S}-\mathbf{S}^{\text{PANN}}\left({} ^{i}\mathbf{C};\,\mathbf{\mathcal{P}}\right)\right\|^{2}\,, \tag{29}\] is minimized, where \(m_{c}=|\mathcal{D}_{c}|\) denotes the number of tuples in \(\mathcal{D}_{c}\) and \(\left\|\cdot\right\|\) denotes the Frobenius norm. Note that the model proposed by [69] is independent of the choice of loss function and also other loss functions could be applied for calibration. As can be seen from Eq. (29), the PANN model is calibrated only through its gradients \(\mathbf{S}^{\text{PANN}}=\partial_{\mathbf{C}}W^{\text{PANN}}\), which is referred to as Sobolev training [104, 105]. In general, also values of the potential itself could be included in the loss function. However, while synthetic datasets can yield information about energies, this is generally not the case for real-world experiments. Thus, including energy values in the loss function would lead to a less general formulation and not even lead to significant benefits in the calibrated models [23]. ### Derivatives of the neural network potential For the FE implementation of the PANN model, both first and second derivatives of the potential w.r.t. the invariants are required. For FFNN architectures with a large number of hidden layers, calculating derivatives in an explicit way quickly leads to huge expressions. However, for the single-layered FFNN used in this work, the explicit derivatives are very manageable. For the convenience of the reader, the derivatives of the NN part of the PANN model are provided here. Note that for the calibration process, cf. Sect. 3.2, the derivatives of the NN are not implemented in an explicit way, but the automatic differentiation provided by TensorFlow is applied. The first derivative is given by \[\partial_{(\mathbf{\mathcal{I}})_{i}}\,W^{\text{NN}}=\sum_{a=1}^{n}w_{a}^{2}\, \frac{e^{h_{a}}}{1+e^{h_{a}}}\,w_{ai}^{1}\,,\qquad\text{with}\ \ \mathbf{h}:=\mathbf{w}^{1}\cdot\mathbf{\mathcal{I}}+\mathbf{b}\,, \tag{30}\] where we made use of the derivative of the _Softplus_ function \[\partial_{x}\,\mathcal{SP}(x)=\frac{e^{x}}{1+e^{x}}\,. \tag{31}\] Actually, \(\partial_{x}\,\mathcal{SP}(x)\) is the widely used _Sigmoid_ activation function. This shows another benefit of applying the _Softplus_ activation function for the representation of hyperelastic potentials. Since also its derivative is a commonly used activation function, the derivatives of the NN potential benefit from the properties of activation functions [48], which are specifically chosen for the application in NNs. Note that in Eq. (30), the derivatives of the NN potential w.r.t. each single invariant also depends on the remaining invariants. The second derivative follows as \[\partial_{(\mathbf{\mathcal{I}})_{i}(\mathbf{\mathcal{I}})_{j}}^{2}\,W^{\text{NN}}= \sum_{a=1}^{n}w_{a}^{2}\,\frac{e^{h_{a}}}{(1+e^{h_{a}})^{2}}\,w_{ai}^{1}\,w_{aj }^{1}\,. \tag{32}\] Continuum formulation of finite deformation elasticity While in the previous section, material specific constitutive models were discussed, in this section, general balance laws of finite deformation elasticity are introduced. For this, we consider the potential energy \(\Pi\), which is comprised of an internal part \(\Pi^{\rm int}\) and an external part \(\Pi^{\rm ext}\), respectively, such that \[\Pi(\boldsymbol{\varphi})=\Pi^{\rm int}+\Pi^{\rm ext}\,, \tag{33}\] where the external part is given by \[\Pi^{\rm ext}=-\int_{\mathcal{B}_{0}}\bar{\mathbf{B}}\cdot\boldsymbol{\varphi }\ {\rm d}V-\int_{\partial\mathcal{B}_{0}^{T}}\bar{\mathbf{T}}\cdot\boldsymbol{ \varphi}\ {\rm d}A\,. \tag{34}\] Therein, \(\bar{\mathbf{B}}:\mathcal{B}_{0}\to\mathbb{R}^{3}\) is the prescribed body force and \(\bar{\mathbf{T}}:\partial\mathcal{B}_{0}^{T}\to\mathbb{R}^{3}\) denotes the prescribed Piola-Kirchoff traction vector on \(\partial\mathcal{B}_{0}^{T}\subset\partial\mathcal{B}_{0}\), where the boundary is comprised of a Dirichlet boundary \(\partial\mathcal{B}_{0}^{\boldsymbol{\varphi}}\) with prescribed deformations \(\bar{\boldsymbol{\varphi}}:\partial\mathcal{B}_{0}^{\boldsymbol{\varphi}}\to \mathbb{R}^{3}\) and a Neumann boundary \(\partial\mathcal{B}_{0}^{T}\) with prescribed tractions \(\bar{\mathbf{T}}:\partial\mathcal{B}_{0}^{T}\) such that \(\partial\mathcal{B}_{0}=\partial\mathcal{B}_{0}^{T}\cup\partial\mathcal{B}_{0 }^{\boldsymbol{\varphi}}\) and \(\partial\mathcal{B}_{0}^{T}\cap\partial\mathcal{B}_{0}^{\boldsymbol{\varphi}}=\emptyset\). Furthermore, in Eq. (33), \(\Pi^{\rm int}\) basically denotes the elastic energy stored internally by the deformed body. This can be a purely displacement-based version \[\Pi^{\rm int}=\int_{\mathcal{B}_{0}}W^{\rm F}(\mathbf{F})\ {\rm d}V\,, \tag{35}\] which itself depends on the hyperelastic potential introduced in Eq. (6). In the above, the solution function \(\boldsymbol{\varphi}\in\mathbb{V}_{\boldsymbol{\varphi}}\) is subject to the space \[\mathbb{V}_{\boldsymbol{\varphi}}=\{\boldsymbol{\varphi}:\mathcal{B}_{0}\to \mathbb{R}^{3}\,|\,\varphi_{i}\in H^{1}(\mathcal{B}_{0})\wedge\boldsymbol{ \varphi}=\bar{\boldsymbol{\varphi}}\ {\rm on}\ \partial\mathcal{B}_{0}^{ \boldsymbol{\varphi}}\wedge\det(\mathbf{F}_{\boldsymbol{\varphi}})>0\ {\rm in}\ \mathcal{B}_{0}\}\,, \tag{36}\] where \(H^{1}\) denotes the Sobolev space. The principle of stationary potential energy requires the satisfaction of the stationary condition, such that \[\delta\Pi=\delta\Pi^{\rm int}+\delta\Pi^{\rm ext}\stackrel{{!}}{{= }}0\,, \tag{37}\] which has to hold for arbitrary \(\delta\boldsymbol{\varphi}\in\mathbb{V}_{\boldsymbol{\varphi}}^{0}\) with the space \[\mathbb{V}_{\boldsymbol{\varphi}}^{0}=\{\delta\boldsymbol{\varphi}:\mathcal{ B}_{0}\to\mathbb{R}^{3}\,|\,\delta\varphi_{i}\in H^{1}(\mathcal{B}_{0})\wedge \delta\boldsymbol{\varphi}=\mathbf{0}\ {\rm on}\ \partial\mathcal{B}_{0}^{ \boldsymbol{\varphi}}\}\,, \tag{38}\] where the variation of \(\Pi^{\rm ext}\) leads to \[\delta\Pi^{\rm ext}=-\int_{\mathcal{B}_{0}}\bar{\mathbf{B}}\cdot\delta \boldsymbol{\varphi}\ {\rm d}V-\int_{\partial\mathcal{B}_{0}^{T}}\bar{\mathbf{T}}\cdot\delta \boldsymbol{\varphi}\ {\rm d}A\,. \tag{39}\] The variation of the internal potential \(\Pi^{\rm int}\) will be dealt with subsequently after discussing different displacement-based and mixed formulations. ### Displacement-based formulations In solid mechanics, the primary strain measure is the deformation gradient \(\mathbf{F}\). As already pointed out in Sect. 2.2, the notion of polyconvexity introduced by Ball [6, 7] suggests to not only consider the deformation gradient \(\mathbf{F}\) in advanced numerical methods, but also its cofactor \(\mathbf{H}\) and determinant \(J\), cf. Eq. (11). In particular, hyperelastic potentials are usually formulated in this extended set of arguments of \(\mathbf{F}\), i.e., they are formulated in (\(\mathbf{F}\), \(\mathbf{H}\), \(J\)). Considering this suggests to use the tensor cross product firstly introduced by [21], which facilitates both the analytical expressions and the implementation of advanced numerical methods, as it leads to neat derivatives of (**F**, **H**, \(J\)) w.r.t. **F**. This has already been realized in purely displacement-based and mixed methods [13], as well as energy-momentum schemes [9]. Starting with the former, [13] proposed a new computational framework based on polyconvex hyperelastic potentials of the form \[\hat{W}^{\mathrm{F}}\colon\mathbb{T}_{3}^{+}\times\mathbb{T}_{3}^{+}\times \mathbb{R}_{+}\to\mathbb{R}\,,\qquad(\mathbf{F},\mathbf{H},J)\mapsto\hat{W}^{ \mathrm{F}}(\mathbf{F},\mathbf{H},J)\,. \tag{40}\] The above stored energy function inspired the objective version thereof, given by \[\hat{W}^{\mathrm{C}}\colon\mathbb{S}_{+}^{3}\times\mathbb{S}_{+}^{3}\times \mathbb{R}_{+}\to\mathbb{R}\,,\qquad(\mathbf{C},\mathbf{G},C)\mapsto\hat{W}^{ \mathrm{C}}(\mathbf{C},\mathbf{G},C)\,. \tag{41}\] Introduced by [9], this formulation facilitates the design of an energy-momentum scheme (EMS). Furthermore, as has been outlined in Sect. 2.3, hyperelastic potentials are usually formulated in terms of strain invariants, which basically are nonlinear functions of (**F**, **H**, \(J\)). Thus, the invariant-based formulation \[W^{\mathrm{I}}\colon\mathbb{R}_{+}\times\mathbb{R}_{+}\times\mathbb{R}_{+}\to \mathbb{R}\,,\qquad(I_{\mathbf{C}},II_{\mathbf{C}},J)\mapsto W^{\mathrm{I}}(I_ {\mathbf{C}},II_{\mathbf{C}},J)\,, \tag{42}\] can be seen as a consecutive development of established polyconvexity-inspired numerical methods [9, 13], now setting the focus directly on invariants. Variation of the displacement-based potential energy \({}^{W^{\mathrm{I}}}\Pi^{\mathrm{int}}\), which depends on the strain energy \(W^{\mathrm{I}}\) as defined in Eq. (42), yields \[\begin{split}\delta(^{W^{\mathrm{I}}}\Pi^{\mathrm{int}})& =\int_{\mathcal{B}_{0}}\delta W^{\mathrm{I}}(I_{\mathbf{C}},\,II_{ \mathbf{C}},\,J)\,\,\mathrm{d}V\\ &=\int_{\mathcal{B}_{0}}2\,\left(\partial_{I_{\mathbf{C}}}W^{ \mathrm{I}}\,\mathbf{I}+\partial_{II_{\mathbf{C}}}W^{\mathrm{I}}\,\mathbf{I} \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\! To circumvent this issue, a variety of mixed formulations have been proposed. The purpose of the present study is not only to demonstrate the ability of the PANN constitutive model to be employed within a mixed formulation, but also to develop a mixed method which is tailored for the PANN model. As in the previous section, the mixed formulations discussed here are inspired by the notion of polyconvexity, in the sense that they consider the arguments of the polyconvexity condition as additional unknowns, cf. Eq. (11). In this regard, the Hu-Washizu like 7-field mixed formulation from [13] corresponding to the displacement-based version Eq. (40) is worth mentioning. There, the consistency of \((\mathbf{F},\mathbf{H},J)\) with \(\boldsymbol{\varphi}\) is enforced by means of the Lagrange multipliers \((\boldsymbol{\Lambda}^{\mathbf{F}},\boldsymbol{\Lambda}^{\mathbf{H}},\Lambda^ {J})\), respectively, and the total set of unknowns is \((\boldsymbol{\varphi},\mathbf{F},\mathbf{H},J,\boldsymbol{\Lambda}^{\mathbf{F} },\boldsymbol{\Lambda}^{\mathbf{H}},\Lambda^{J})\). A further notable version is proposed by [9], which corresponds to the displacement-based version Eq. (41). There, the consistency of \((\mathbf{C},\mathbf{G},C)\) is enforced by means of the Lagrange multipliers \((\boldsymbol{\Lambda}^{\mathbf{C}},\boldsymbol{\Lambda}^{\mathbf{G}},\Lambda^ {C})\), with the total set of unknowns \((\boldsymbol{\varphi},\mathbf{C},\mathbf{G},C,\boldsymbol{\Lambda}^{\mathbf{ C}},\boldsymbol{\Lambda}^{\mathbf{G}},\Lambda^{C})\) employed. The extension to enhanced assumed strain (EAS) variants of the above mentioned 7-field mixed formulation should be mentioned and can also be employed in a straight forward manner, cf. [86]. Here, we restrict our consideration without loss of generality to the 5-field mixed formulation \({}^{W}\Gamma_{5}^{\text{int}}\) proposed by [59], which the authors in [59] claim to be robust, efficient and locking-free. It is given by2 Footnote 2: In this subsection, the subscript \(\boldsymbol{\varphi}\) indicates that a quantity is calculated through the displacement field rather than being an additional unknown. \[{}^{W}{}^{\text{G}}\Pi_{5}^{\text{int}}=\int_{\mathcal{B}_{0}}W^{\text{G}}( \mathbf{C}_{\boldsymbol{\varphi}},\mathbf{G},J)+\boldsymbol{\Lambda}^{\mathbf{ G}}:(\operatorname{cof}(\mathbf{C}_{\boldsymbol{\varphi}})-\mathbf{G})+ \Lambda^{J}\left(\operatorname{det}(\mathbf{F}_{\boldsymbol{\varphi}})-J \right)\,\mathrm{d}V\,, \tag{44}\] where \(\boldsymbol{\varphi}\in\mathds{V}_{\boldsymbol{\varphi}}\). Furthermore, \(\mathbf{G}\in\mathds{V}_{\boldsymbol{\Lambda}}\) and \(J\in\mathds{V}_{A}\) are enforced by means of Lagrange multipliers \(\boldsymbol{\Lambda}^{\mathbf{G}}\in\mathds{V}_{\boldsymbol{\Lambda}}\) and \(\Lambda^{J}\in\mathds{V}_{A}\) with generalized spaces \[\mathds{V}_{\boldsymbol{\Lambda}}=\mathds{V}_{\boldsymbol{\Lambda}}^{0}=\{ \mathbf{A}:\mathcal{B}_{0}\to\mathbb{S}_{+}^{3}\,|\,A_{ij}\in\mathds{L}_{2}( \mathcal{B}_{0})\},\quad\mathds{V}_{A}=\mathds{V}_{A}^{0}=\{A:\mathcal{B}_{0} \to\mathbb{R}_{+}\,|\,A\in\mathds{L}_{2}(\mathcal{B}_{0})\}\,. \tag{45}\] The corresponding variation yields \[\begin{split}\delta({}^{W}{}^{\text{G}}\Pi_{5}^{\text{int}})=\int _{\mathcal{B}_{0}}& 2\,(\partial\mathbf{C}_{\boldsymbol{\varphi}}W^{ \text{G}}+\boldsymbol{\Lambda}^{\mathbf{G}}\,\boldsymbol{\Re}\,\mathbf{C}_{ \boldsymbol{\varphi}}+\tfrac{1}{2}\,\Lambda^{J}\,J_{\boldsymbol{\varphi}}^{-1 }\,\mathbf{G}_{\boldsymbol{\varphi}}):\tfrac{1}{2}\,\delta\mathbf{C}_{ \boldsymbol{\varphi}}\\ &+(\partial_{\mathbf{G}}W^{\text{G}}-\boldsymbol{\Lambda}^{ \mathbf{G}}):\delta\mathbf{G}\\ &+(\partial_{J}W^{\text{G}}-\Lambda^{J})\,\delta J\\ &+(\operatorname{cof}(\mathbf{C}_{\boldsymbol{\varphi}})-\mathbf{ G}):\delta\boldsymbol{\Lambda}^{\mathbf{G}}\\ &+(\operatorname{det}(\mathbf{F}_{\boldsymbol{\varphi}})-J)\, \delta\Lambda^{C}\,\,\mathrm{d}V\,,\end{split} \tag{46}\] which has to hold for arbitrary \(\delta\boldsymbol{\varphi}\in\mathds{V}_{\boldsymbol{\varphi}}^{0}\), \(\delta\mathbf{G},\delta\boldsymbol{\Lambda}^{\mathbf{G}}\in\mathds{V}_{ \boldsymbol{\Lambda}}^{0}\), and \(\delta J,\delta\Lambda^{J}\in\mathds{V}_{A}^{0}\). Based on the above newly proposed displacement formulation in Eq. (42), we also suggest a new Hu-Washizu like 7-field mixed formulation \({}^{W}{}^{\text{I}}\Pi_{7}^{\text{int}}\) given by3 Footnote 3: The initial idea to use a strain energy depending solely on the invariants of \(\mathbf{C}\), i.e. \(W=W(I_{\mathbf{C}},II_{\mathbf{C}},III_{\mathbf{C}})\) resulted in the occurrence of hourglassing phenomena for nearly incompressible materials under shear loading conditions. Consequently, this approach was deemed unsuitable and subsequently discarded. \[\begin{split}{}^{W}{}^{\text{I}}\Pi_{7}^{\text{int}}=\int_{ \mathcal{B}_{0}}W^{\text{I}}(I_{\mathbf{C}},II_{\mathbf{C}},J)&+ \lambda^{I_{\mathbf{C}}}\left(\operatorname{tr}\mathbf{C}_{\boldsymbol{\varphi}} -I_{\mathbf{C}}\right)\\ &+\lambda^{II_{\mathbf{C}}}\left(\operatorname{tr}(\operatorname{ cof}\mathbf{C}_{\boldsymbol{\varphi}})-II_{\mathbf{C}}\right)\\ &+\lambda^{J}\left(\operatorname{det}\mathbf{F}_{\boldsymbol{ \varphi}}-J\right)\,\mathrm{d}V\,,\end{split} \tag{47}\] with \(\boldsymbol{\varphi}\in\mathds{V}_{\boldsymbol{\varphi}}\) and \(I_{\mathbf{C}},II_{\mathbf{C}},J,\lambda^{I_{\mathbf{C}}},\lambda^{I_{\mathbf{I }}}\mathrm{C},\lambda^{J}\in\mathds{V}_{A}\). The above formulation can also be regarded as tailor made for the employed PANN constitutive model. Variation of this Hu-Washizu like 7-field mixed formulation yields \[\begin{split}\delta(^{W^{\mathrm{I}}}\Pi_{7}^{\mathrm{int}})= \int_{\mathcal{B}_{0}}& 2\,(\lambda^{I_{\mathbf{C}}}\,\mathbf{I}+\lambda^{I \mathrm{I}\mathrm{C}}\,(\mathbf{I}\boldsymbol{\$}\,\mathbf{\$}\,\mathbf{C}_{ \boldsymbol{\varphi}})+\tfrac{1}{2}\,\lambda^{J}\,J_{\boldsymbol{\varphi}}^{- 1}\,\mathbf{G}_{\boldsymbol{\varphi}}):\tfrac{1}{2}\,\delta\mathbf{C}_{ \boldsymbol{\varphi}}\\ &+(\partial_{I_{\mathbf{C}}}W^{\mathrm{I}}-\lambda^{I_{\mathbf{C} }})\,\delta I_{\mathbf{C}}\\ &+(\partial_{II_{\mathbf{C}}}W^{\mathrm{I}}-\lambda^{I_{\mathbf{ C}}})\,\delta II_{\mathbf{C}}\\ &+(\partial_{J}W^{\mathrm{I}}-\lambda^{J})\,\delta J\\ &+(\mathrm{tr}\,\mathbf{C}_{\boldsymbol{\varphi}}-I_{\mathbf{C} })\,\delta\lambda^{I_{\mathbf{C}}}\\ &+(\mathrm{tr}\,\mathbf{G}_{\boldsymbol{\varphi}}-II_{\mathbf{C} })\,\delta\lambda^{I_{\mathbf{C}}}\\ &+(\mathrm{det}\,\mathbf{F}_{\boldsymbol{\varphi}}-J)\,\delta \lambda^{J}\,\,\mathrm{d}V\,,\end{split} \tag{48}\] which has to hold for arbitrary \(\delta\boldsymbol{\varphi}\in\mathds{V}_{\boldsymbol{\varphi}}^{0}\) and \(\delta I_{\mathbf{C}},\delta II_{\mathbf{C}},\delta J,\delta\lambda^{I_{ \mathbf{C}}},\delta\lambda^{II_{\mathbf{C}}},\delta\lambda^{J}\in\mathds{V}_{ A}^{0}\). ### Dynamic formulation For the dynamic formulation, we restrict our consideration to the displacement-based formulation given in Eq. (43). In so doing, we introduce the time interval of interest with range \(\mathcal{R}=[0,T]\), where \(T\in\mathbb{R}_{+}\). The motion of the deformation field \(\boldsymbol{\varphi}_{t}\in\mathds{V}_{\boldsymbol{\varphi}}\) denotes the placement of a particle at \(\mathbf{X}\in\mathcal{B}_{0}\) at time \(t\in\mathcal{R}\). We introduce the velocity field \(\mathds{V}_{\mathbf{v}}\ni\mathbf{v}_{t}:\mathcal{B}_{0}\times\mathcal{R} \rightarrow\mathbb{R}^{3}\) with space \[\mathds{V}_{\mathbf{v}}=\left\{\mathbf{v}:\mathcal{B}_{0}\times\mathcal{R} \rightarrow\mathbb{R}^{3}\,|\,v_{i}\in\mathds{L}_{2}(\mathcal{B}_{0})\right\}, \tag{49}\] and the mass density in the reference configuration \(\rho_{0}:\mathcal{B}_{0}\rightarrow\mathbb{R}^{+}\). With that we are able to introduce the action functional \[S(\boldsymbol{\varphi}_{t},\mathbf{v}_{t})=\int_{t_{0}}^{t_{e}}\int_{\mathcal{ B}_{0}}(\boldsymbol{\dot{\varphi}}_{t}-\tfrac{1}{2}\,\mathbf{v}_{t})\cdot \mathbf{v}_{t}\,\rho_{0}\,\,\mathrm{d}V-\left({}^{W^{\mathrm{I}}}\Pi^{\mathrm{ int}}+\Pi^{\mathrm{ext}}\right)\,\mathrm{d}V\,\,\mathrm{d}t\,. \tag{50}\] By means of Hamilton's principle, the stationary conditions of the action \(S\) w.r.t. the variations yield \[\begin{split}\int_{\mathcal{B}_{0}}\delta\mathbf{v}_{t}\cdot( \boldsymbol{\dot{\varphi}}_{t}-\mathbf{v}_{t})\,\rho_{0}\,\,\mathrm{d}V& =0\\ \int_{\mathcal{B}_{0}}\delta\boldsymbol{\varphi}\cdot\rho_{0}\, \dot{\mathbf{v}}_{t}+\mathbf{S}_{t}:\tfrac{1}{2}\,\delta\mathbf{C}\,\, \mathrm{d}V+\Pi^{\mathrm{ext}}(\delta\boldsymbol{\varphi})&=0\,, \end{split} \tag{51}\] which have to hold for arbitrary \(\delta\mathbf{v}\in\mathds{V}_{\mathbf{v}}^{0}\) and \(\delta\boldsymbol{\varphi}\in\mathds{V}_{\boldsymbol{\varphi}}\) with space \[\mathds{V}_{\mathbf{v}}^{0}=\left\{\mathbf{v}:\mathcal{B}_{0}\to \mathbb{R}^{3}\,|\,v_{i}\in\mathds{L}_{2}(\mathcal{B}_{0})\right\}. \tag{52}\] In the above equation, due to Eq. (43), the PK2 stress tensor is defined as \[\mathbf{S}_{t}=2\,\left(\partial_{I_{\mathbf{C}}}W^{\mathrm{I}}\,\mathbf{I}+ \partial_{II_{\mathbf{C}}}W^{\mathrm{I}}\,\mathbf{I}\boldsymbol{\$}\,\mathbf{ \$}\,\mathbf{\$}\,\mathbf{C}_{t}+\tfrac{1}{2}\,\partial_{J}W^{\mathrm{I}}\,J_{ t}^{-1}\,\mathbf{G}_{t}\right)\,. \tag{53}\] The verification of the balance laws for the time-continuous system is detailed in Appx. A, which serves as a comprehensive reference for ensuring the validity and consistency of the sytem's fundamental principles. Time discretization with consistent energy-momentum scheme Regarding the time discretization, the use of the midpoint rule in nonlinear continuum mechanics typically introduces a violation of the energy consistency solely due to the discretization of the variation of the (strain) energy within the weak form, while all other terms involved do not give rise to any issue. In order to circumvent this issue and to obtain an energy and momentum consistent time integration scheme, a midpoint-type discretization with application of the concept of the discrete gradient, as defined in [33], is employed. Specifically, for the weak form in Eq. (51) the following steps are pursued to ensure energy and momentum consistency: * substitution of time rates (\(\dot{\bullet}\)) with \(\frac{(\bullet)_{n+1}-(\bullet)_{n}}{\Delta t}=\frac{\Delta(\bullet)}{\Delta t}\), * algorithmic evaluation of the variation of the (strain) energy \(W^{\rm I}\), which leads to an algorithmic PK2 stress tensor \(\mathbf{S}_{\rm algo}\) based on the concept of the discrete gradients in the sense of [33], * midpoint evaluation of remaining terms, i.e. \(\big{(}\bullet\big{)}_{n+\frac{1}{2}}=\frac{1}{2}\left((\bullet)_{n}+(\bullet )_{n+1}\right)\). Employing the above steps to the weak form Eq. (51) yields the semi-discrete weak form as \[\begin{split}\int_{\mathcal{B}_{0}}\delta\mathbf{v}\cdot\frac{ \Delta\boldsymbol{\varphi}}{\Delta t}\,\rho_{0}\ \mathrm{d}V&=\int_{\mathcal{B}_{0}}\delta\mathbf{v}\cdot \mathbf{v}_{n+\frac{1}{2}}\,\rho_{0}\ \mathrm{d}V\\ \int_{\mathcal{B}_{0}}\delta\boldsymbol{\varphi}\cdot\rho_{0} \,\frac{\Delta\mathbf{v}}{\Delta t}\ \mathrm{d}V&=-\int_{\mathcal{B}_{0}}\mathbf{S}_{\rm algo}: \frac{1}{2}\left(\delta\mathbf{F}^{\rm T}\,\mathbf{F}_{n+\frac{1}{2}}+ \mathbf{F}_{n+\frac{1}{2}}^{\rm T}\,\delta\mathbf{F}\right)\ \mathrm{d}V-\Pi_{n+\frac{1}{2}}^{\rm ext}(\delta \boldsymbol{\varphi})\,.\end{split} \tag{54}\] Therein, the particular form of the algorithmic version of the PK2 stress tensor \(\mathbf{S}_{\rm algo}\) follows from the so-called directionality property, which is a sufficient condition for energy consistency. The directionality property itself serves as a time-discrete representation of the continuum stress power \(\dot{W^{\rm I}}=\mathbf{S}:\frac{1}{2}\,\dot{\mathbf{C}}\), acting as a sufficient criterion for energy conservation, cf. [91]. In that regard, the directionality property for the present system yields \[\begin{split}\mathbf{S}_{\rm algo}:\frac{1}{2}\,\Delta\mathbf{C}& =\mathrm{D}_{I_{\mathbf{C}}}W^{\rm I}\,\Delta I_{\mathbf{C}}+ \mathrm{D}_{II_{\mathbf{C}}}W^{\rm I}\,\Delta II_{\mathbf{C}}+\mathrm{D}_{J}W ^{\rm I}\,\Delta J_{\boldsymbol{\varphi}}\\ &=W^{\rm I}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}},J_{n+1})-W ^{\rm I}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n})\,.\end{split} \tag{55}\] The satisfaction of this condition motivates for proposing the algorithmic PK2 stress tensor as \[\mathbf{S}_{\rm algo}=2\,\left(\mathrm{D}_{I_{\mathbf{C}}}W^{\rm I}\,\mathbf{ I}+\mathrm{D}_{II_{\mathbf{C}}}W^{\rm I}\,\mathbf{I}\boldsymbol{\Phi}\, \mathbf{C}_{\rm algo}+\frac{1}{2}\,\mathrm{D}_{J}W^{\rm I}\,(J_{\rm algo})^{-1 }\mathbf{G}_{\rm algo}\right)\,, \tag{56}\] which serves as consistent time-discrete variant of Eq. (53) and ensures energy consistency while maintaining the second-order accuracy of the midpoint rule. In case of midpoint time integration, the only difference compared to the EM scheme is the evaluation of the PK2 stress tensor. In particular, instead of Eq. (56) we would evaluate the PK2 stress tensor as follows \[\begin{split}\mathbf{S}_{n+\frac{1}{2}}&=2\,(\partial _{I_{\mathbf{C}}}W^{\rm I}(\mathbf{F}_{n+\frac{1}{2}})\,\mathbf{I}+\partial _{II_{\mathbf{C}}}W^{\rm I}(\mathbf{F}_{n+\frac{1}{2}})\,\mathbf{I} \boldsymbol{\Phi}\mathbf{C}((\mathbf{F}_{n+\frac{1}{2}})\\ &\quad+\frac{1}{2}\,\partial_{J}W^{\rm I}(\mathbf{F}_{n+\frac{1}{ 2}})\,(J((\mathbf{F}_{n+\frac{1}{2}}))^{-1}\mathbf{G}(\mathbf{F}_{n+\frac{1}{ 2}}))\,.\end{split} \tag{57}\] The algorithmic form of the PK2 stress tensor in Eq. (56) is the basic feature of the energy-momentum method and contains the subsequently introduced partitioned discrete derivatives \(\mathrm{D}_{I_{\mathbf{C}}}W^{\rm I},\mathrm{D}_{II_{\mathbf{C}}}W^{\rm I}\), \(\mathrm{D}_{J}W^{\rm I}\) in replacement of the partial derivatives of the strain energy from Eq. (53). The construction of these particular discrete gradients is provided by Appx. C, which eventually yields the final Greenspan-like versions \[\begin{split} D_{I\mathbf{C}}W^{1}=&\left(W^{\mathrm{I} }(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n}},J_{n})-W^{\mathrm{I}}(I_{\mathbf{C} _{n}},II_{\mathbf{C}_{n}},J_{n})\right.\\ &\left.+W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}}, J_{n+1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n+1}},J_{n+1})\right)/(2\, \Delta I_{\mathbf{C}})\,,\\ D_{II\mathbf{C}}W^{1}=&\left(W^{\mathrm{I}}(I_{ \mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}},J_{n})-W^{\mathrm{I}}(I_{\mathbf{C}_{n +1}},II_{\mathbf{C}_{n}},J_{n})\right.\\ &\left.+W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n+1}}, J_{n+1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n+1})\right)/(2\, \Delta II_{\mathbf{C}})\,,\\ D_{J}W^{1}=&\left(W^{\mathrm{I}}(I_{\mathbf{C}_{n+1 }},II_{\mathbf{C}_{n+1}},J_{n+1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{ \mathbf{C}_{n+1}},J_{n})\right.\\ &\left.+W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n +1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n})\right)/(2\, \Delta J)\,.\end{split} \tag{58}\] As shown in Eq. (56), algorithmic versions of the kinematic relations \(\mathbf{C}_{\mathrm{algo}}\), \(\mathbf{G}_{\mathrm{algo}}\), \(J_{\mathrm{algo}}\) are employed, which directly follows from the directionality condition Eq. (C.17). Alternatively, the algorithmic PK2 tensor from Eq. (56) with its algorithmic kinematic relations can be kind of naturally achieved when deriving it from the corresponding dynamic Hu-Washizu like mixed formulation given based on Eq. (41), see [9] for more details. In any case, the algorithmic kinematic relations \(\mathbf{C}_{\mathrm{algo}}\), \(\mathbf{G}_{\mathrm{algo}}\), \(J_{\mathrm{algo}}\) are chosen as \[\begin{split}\mathbf{C}_{\mathrm{algo}}&=\frac{1}{2} \left(\mathbf{C}_{n+1}+\mathbf{C}_{n}\right)\\ \mathbf{G}_{\mathrm{algo}}&=\frac{1}{3}\left(\mathbf{ C}_{\mathrm{algo}}\boldsymbol{\Psi}\mathbf{C}_{\mathrm{algo}}+\widetilde{ \mathbf{G}}_{\mathrm{algo}}\right)\text{,\quad with \ }\widetilde{\mathbf{G}}_{\mathrm{algo}}=\frac{1}{2}\left(\mathbf{G}_{n+1}+ \mathbf{G}_{n}\right),\\ J_{\mathrm{algo}}&=\frac{1}{2}\left(J_{n+1}+J_{n} \right),\end{split} \tag{59}\] and fulfill the necessary directionality property of Eq. (55). It is important to remark that the discrete gradients possess the following properties, see [33] for more information. In particular, the discrete gradients * satisfy the directionality property Eq. (C.17), which serves as sufficient condition for energy consistency, * are well defined in the limit \(\|\Delta\Pi^{i}\|\to 0\) where \(\|\Delta\Pi^{i}\|=\sqrt{\langle\Delta\Pi^{i},\Delta\Pi^{i}\rangle}\), \(\Delta\Pi^{i}=\Pi^{i}_{n+1}-\Pi^{i}_{n}\), here \(\boldsymbol{\Pi}=(\Pi^{1},\Pi^{2},\Pi^{3})=(I_{\mathbf{C}},II_{\mathbf{C}},J)\), cf. Appx. C, and \(\langle\bullet,\bullet\rangle\) denotes the inner product, * are a second-order approximation of the corresponding midpoint evaluations of the partial derivatives, * and are undefined for handling zero magnitude \(\|\Delta\Pi^{i}\|=0\), which regarding the implementation occurs e.g. within a very first iteration of Newton's method, and can be avoided by midpoint-type evaluation of the partial derivatives \(\mathrm{D}_{\Pi^{i}}W^{\mathrm{I}}=\partial_{\Pi^{i}}W^{\mathrm{I}}(\Pi^{i}_{n +\frac{1}{2}})\), * results with the aforementioned algorithmic stress evaluation in the generation of a tangent stiffness matrix that exhibits non-symmetry. **Remark 1**.: _As becomes obvious in Appx. D, the choice of the strain energy \(\hat{W}^{C}(\mathbf{C},\mathbf{G},C)\) in Eq. (41) leads to far more complex versions of the discrete gradients \(\mathrm{D}_{\mathbf{C}}\hat{W}^{C}\), \(\mathrm{D}_{\mathbf{G}}\hat{W}^{C}\) and \(\mathrm{D}_{C}\hat{W}^{C}\) when compared to the choice of strain energy \(W^{I}(I_{\mathbf{C}},II_{\mathbf{C}},J)\) in Eq. (42) with just Greenspan versions of the partitioned discrete gradients \(\mathrm{D}_{I\mathbf{C}}W^{I}\), \(\mathrm{D}_{II\mathbf{C}}W^{I}\) and \(\mathrm{D}_{J}W^{I}\) in Eq. (58). Also the traditional, projection-based discrete gradient \(\mathrm{D}_{\mathbf{C}}W^{C}(\mathbf{C})\) associated with strain energy \(W^{C}(\mathbf{C})\) from Eq. (41) provided by Appx. E can be employed. However, the consistent linearization of the tensor-valued discrete gradient \(\mathrm{D}_{\mathbf{C}}W^{C}(\mathbf{C})\) and the application of the chain rule become more complex when employing the PANN constitutive model with its inputs \(\boldsymbol{\mathcal{I}}\) in comparison to the proposed version outlined in Eq. (58)._ Standard integrators like the 2nd order accurate midpoint rule usually violate the conserving properties, particularly the balance of angular momentum and total energy. However, the proposed EM scheme ensures that these balance laws are preserved in the time-discrete system. The verification and detailed analysis of the balance laws for the time-discrete system can be found in Appx. B. ## 6 Spatial discretization with the finite element method In the following, we focus on the semi-discrete displacement-based system from Sect. 5, which makes a variety of spatial discretizations possible. Here, we employ the finite element (FE) method for the spatial discretization of Eq. (54). To this end, the body \(\mathcal{B}_{0}\) is subdivided into \(n_{e}\in\mathbb{N}\) finite elements \[\mathcal{B}_{0}\approx\mathcal{B}_{0}^{\mathrm{h}}=\bigcup_{e=1}^{n_{e}} \mathcal{B}_{0}^{e}\,, \tag{60}\] where \(e=1,...,n_{e}\) denotes the respective element. In particular, we use the isoparametric concept, cf. [49], by using the same shape functions for the approximation of the geometry with \[\mathbf{X}^{\mathrm{h}}\big{|}_{\mathcal{B}_{0}^{e}}=\sum_{a=1}^{n_{\mathrm{ node}}}N^{a}\,\mathbf{X}^{a}\,, \tag{61}\] and the deformation field \(\boldsymbol{\varphi}_{t}^{h}\in\mathds{V}_{\boldsymbol{\varphi}}^{\mathrm{h} }\subset\mathds{V}_{\boldsymbol{\varphi}}\) and the velocity field \(\mathbf{v}_{t}^{h}\in\mathds{V}_{\mathbf{v}}^{\mathrm{h}}\subset\mathds{V}_ {\mathbf{v}}\) with spaces \[\mathds{V}_{\boldsymbol{\varphi}}^{\mathrm{h}}=\left\{\boldsymbol{\varphi}_{t }\in\mathds{V}_{\boldsymbol{\varphi}}\,:\,\boldsymbol{\varphi}_{t}^{\mathrm{ h}}\big{|}_{\mathcal{B}_{0}^{e}}=\sum_{a=1}^{n_{\mathrm{node}}}N^{a} \boldsymbol{\varphi}_{t}^{a}\right\},\quad\mathds{V}_{\mathbf{v}}^{\mathrm{h} }=\left\{\mathbf{v}_{t}\in\mathds{V}_{\mathbf{v}}\,:\,\mathbf{v}_{t}^{\mathrm{ h}}\big{|}_{\mathcal{B}_{0}^{e}}=\sum_{a=1}^{n_{\mathrm{node}}}N^{a}\mathbf{v}_{t}^{a} \right\}\,, \tag{62}\] where \(N^{a}:\mathcal{B}_{0}\to\mathbb{R}\) denote nodal shape functions with corresponding nodal values \(\mathbf{X}^{a}\in\mathbb{R}^{3}\), \(\boldsymbol{\varphi}_{a}:\mathcal{R}\to\mathbb{R}^{3}\), and \(\mathbf{v}_{a}:\mathcal{R}\to\mathbb{R}^{3}\). According to a Bubnov-Galerkin FE ansatz, we employ the same Ansatz functions for solution and variations \(\delta\boldsymbol{\varphi}\in\mathds{V}_{\boldsymbol{\varphi}}^{0,\mathrm{h} }\subset\mathds{V}_{\boldsymbol{\varphi}}^{0}\), and \(\delta\mathbf{v}\in\mathds{V}_{\mathbf{v}}^{0,\mathrm{h}}\subset\mathds{V}_{ \mathbf{v}}^{0}\) with spaces \[\mathds{V}_{\boldsymbol{\varphi}}^{0,\mathrm{h}}=\left\{\delta\boldsymbol{ \varphi}\in\mathds{V}_{\boldsymbol{\varphi}}^{0}\,:\,\delta\boldsymbol{ \varphi}^{\mathrm{h}}\big{|}_{\mathcal{B}_{0}^{e}}=\sum_{a=1}^{n_{\mathrm{ node}}}N^{a}\,\delta\boldsymbol{\varphi}^{a}\right\},\quad\mathds{V}_{ \mathbf{v}}^{0,\mathrm{h}}=\left\{\delta\mathbf{v}\in\mathds{V}_{\mathbf{v}}^{ 0}\,:\,\delta\mathbf{v}^{\mathrm{h}}\big{|}_{\mathcal{B}_{0}^{e}}=\sum_{a=1}^{ n_{\mathrm{node}}}N^{a}\delta\mathbf{v}^{a}\right\}\,. \tag{63}\] We insert the above discretized solution and variations into the semi-discrete weak form Eq. (54) and obtain \[\begin{split}\boldsymbol{\bigwedge}_{e=1}^{n_{e}}\sum_{a=1}^{n_{ \mathrm{node}}}\delta\mathbf{v}^{a}\cdot\mathbf{R}_{\mathbf{v}}^{a,e}& =0\,,\\ \boldsymbol{\bigwedge}_{e=1}^{n_{e}}\sum_{a=1}^{n_{\mathrm{ node}}}\delta\boldsymbol{\varphi}^{a}\cdot\mathbf{R}_{\boldsymbol{\varphi}}^{a,e}& =0\,,\end{split} \tag{64}\] where \(\mathbf{A}_{e=1}^{n_{e}}\) denotes the assembly operator. In the above, the nodal residuals \(\mathbf{R}_{\mathbf{v}}^{a,e}\in\mathbb{R}^{3}\) and \(\mathbf{R}_{\boldsymbol{\varphi}}^{a,e}\in\mathbb{R}^{3}\) are defined as \[\begin{split}\mathbf{R}_{\mathbf{v}}^{a,e}&=\mathbf{ M}^{ab,e}\,\left(\frac{1}{\Delta t}\Delta\boldsymbol{\varphi}^{b}-\mathbf{v}_{n+ \frac{1}{2}}^{b}\right)\,,\\ \mathbf{R}_{\boldsymbol{\varphi}}^{a,e}&=\mathbf{M}^{ ab,e}\,\frac{1}{\Delta t}\Delta\mathbf{v}^{b}+\int_{\mathcal{B}_{0}^{e}} \mathbf{B}a^{\mathrm{T}}(\boldsymbol{\varphi}_{n+\frac{1}{2}}^{b})\mathbf{S}_{ \mathrm{algo}}^{\mathrm{h,V}}\,\mathrm{d}V-\int_{\mathcal{B}_{0}^{e}}N^{a} \bar{\mathbf{B}}^{\mathrm{h}}(\boldsymbol{\varphi}_{n+\frac{1}{2}}^{b})\, \mathrm{d}V\,,\end{split} \tag{65}\] where \(\mathbf{B}^{a}\in\mathbb{R}^{6\times 3}\) denotes the standard nodal operator matrix, \((\bullet)^{\mathrm{V}}\) symbolizes Voigt's vector notation and \(\mathbf{M}^{ab,e}\) denotes the elemental mass matrix defined as \[\mathbf{M}^{ab,e}=\int_{\mathcal{B}^{e}_{0}}\rho_{0}\,N^{a}\,N^{b}\;\mathrm{d}V \,\mathbf{I}\,. \tag{66}\] In order to pursue an efficient implementation, cf. [9], Eq. (65)\({}_{1}\) can be rewritten as \[\mathbf{v}^{b}_{n+1}=\frac{2}{\Delta t}\Delta\mathbf{\varphi}^{b}_{n+1}-\mathbf{v }^{b}_{n}\,, \tag{67}\] and inserting it into Eq. (65)\({}_{2}\) yields the nodal residual vector \(\widehat{\mathbf{R}}^{a,e}_{\mathbf{\varphi}}\in\mathbb{R}^{3}\) given by \[\widehat{\mathbf{R}}^{a,e}_{\mathbf{\varphi}}=\frac{2}{\Delta t}\,\left(\frac{1}{ \Delta t}\,\mathbf{M}^{ab,e}\,\Delta\mathbf{\varphi}^{b}-\mathbf{M}^{ab,e}\, \mathbf{v}^{b}_{n}\right)+\mathbf{B}^{a^{\mathrm{T}}}_{n+\frac{1}{2}}\mathbf{ S}^{\mathrm{h,V}}_{\mathrm{algo}}\,\mathrm{d}V-\int_{\mathcal{B}^{e}_{0}}N^{a} \bar{\mathbf{B}}^{\mathrm{h}}(\mathbf{\varphi}^{h}_{n+\frac{1}{2}})\,\mathrm{d}V\,. \tag{68}\] Accordingly, the velocity field is condensed out and we have a pure displacement-based formulation. Note that, for the midpoint rule, the algorithmic PK2 stress tensor \(\mathbf{S}^{\mathrm{h}}_{\mathrm{algo}}\) is simply replaced with the midpoint evaluated PK2 stress tensor from Eq. (57). It is important to remark that the discretization of the mixed approaches in Sect. 4.2 is straight forward, where of course the additional fields have to be discretized with suitable spaces considering the inf-sup conditions for the particular choice of approximation formulas, see [59] for more information. ## 7 Numerical examples In this section, stability and robustness of the proposed framework are examined in representative finite element simulations. In Sect. 7.1, the PANN constitutive model is calibrated to data generated with an analytical potential. Afterwards in Sect. 7.2 and in Sect. 7.3, the PANN constitutive model is applied in both static and dynamic numerical examples. ### Preparation of the neural network-based constitutive model The PANN constitutive model is now calibrated to data generated with an analytical potential. Details on the data generation are presented in Sect. 7.1.1, while details on the model calibration are presented in Sect. 7.1.2. #### 7.1.1 Data generation For the following investigations, the PANN model introduced in Sect. 3 is calibrated to data generated with the analytical Mooney-Rivlin model, cf. Eq. (21). For this, two sets of material parameters are considered, which lead to a compressible and a nearly incompressible model, respectively, cf. Table 1. If not stated otherwise, the parameter set for a compressible material behavior is applied. In the following, the Mooney-Rivlin model is referred to as the ground truth (GT) model, to which the results obtained with the calibrated PANN model are compared. Following [23], the calibration dataset consists of (i) a uniaxial tension stress state, (ii) an equibiaxial tension stress state, and (iii) a simple shear deformation state, which are applied on the analytical Mooney-Rivlin model. The uniaxial tension is applied in \(x\)-direction with \(F_{11}\in[0.75,\,1.75]\), the equibiaxial tension is applied in \(x-y\)-direction with \(F_{11}=F_{22}\in[0.75,\,1.755]\), and simple shear is applied with \(F_{12}\in[-0.25,\,0.75]\). In addition, for the test dataset, a mixed shear-tension deformation is applied ("test 3" in [23]), which represents a fairly general deformation mode, cf. Fig. 2. Each load case consists of 100 datapoints, which makes 300 strain-stress tuples in the calibration dataset. It should be mentioned that besides these experimentally motivated load cases, it is also possible to sample the deformation states either by analytical considerations on physically admissible deformation states [62] or by investigating the deformation states which occur in the engineering component under investigation [52]. #### 7.1.2 Model calibration For the PANN model calibration, six different network architectures with \(n\in\{4,\,8,\,16,\,32,\,64,\,128\}\) nodes in the hidden layer are considered for the compressible material behavior, which corresponds to \(|\mathbf{\mathcal{P}}|=24,\,48,\,96,\,192,\,384,\,768\) NN model parameters. In this way, the computational performance of the algorithms can be examined, and furthermore, it is demonstrated that the choice of nodes \(n\) in the hidden layer is generic for the approach introduced in this work. In general, this also holds for the number of hidden layers, of which the proposed framework is also independendent, with the caveat that the explicit derivatives of the NN, cf. Sect. 3.3, must be adapted when more than one hidden layer is considered. For the nearly incompressible material behavior, \(n=8\) nodes are considered. At this point, it should be noted that even the smallest NN architecture with 4 nodes is flexible enough to perfectly represent the Mooney-Rivlin model, and, furthermore, calibrating a PANN model to such a simple analytical potential should be considered as an academic example. In the following examples, PANN\(n\) denotes a PANN model with \(n\) nodes in the hidden layer. For the calibration, the models are implemented in TensorFlow 2.5.0 using Python 3.9.9. The optimization is carried out using the ADAM algorithm with default settings. Therefore, the full batch of calibration data is used for 5000 calibration epochs. Each model architecture is calibrated one time. For the reproducibility of the results, the calibrated model parameters are provided in the GitHub repository [https://github.com/CPShub/sim-data](https://github.com/CPShub/sim-data). All model architectures perform excellent, both on the calibration and the test dataset, and both for the compressible and the nearly incompressible material behavior, cf. Table 2, where the losses of the calibrated models are provided. While there is a general trend for a decreasing loss for larger model architectures, it should be noted that even the small architectures are able to nearly perfectly represent the GT models, which becomes evident in Fig. 2, where the test case is evaluated for the PANN8 models. \begin{table} \begin{tabular}{l|l l l} compressible case & \(a\) & 831.25 & Pa \\ & \(b\) & 166.25 & Pa \\ & \(c\) & 10000 & Pa \\ & \(d\) & 2327.5 & Pa \\ mass density (static/transient examples) & \(\rho_{0}\) & 0/100 & kg m\({}^{-3}\) \\ \hline \hline nearly incompressible case & \(a\) & 126 & Pa \\ & \(b\) & 252 & Pa \\ & \(c\) & 81512 & Pa \\ & \(d\) & 1260 & Pa \\ mass density & \(\rho_{0}\) & 0 & kg m\({}^{-3}\) \\ \end{tabular} \end{table} Table 1: Mooney-Rivlin material parameters employed for the numerical examples. ### Static deformation of Cook's membrane Here, a static example is investigated. In Sect. 7.2.1, compressible material behavior is assumed, and the computation time of the PANN constitutive model compared to the GT model is examined. In Sect. 7.2.2, nearly incompressible material behavior is assumed, and the performance of the mixed formulations is demonstrated. #### 7.2.1 Compressible case As a first example, a three-dimensional version of the well-known Cook's membrane with compressible material behavior is considered, see e.g. [9]. With this example, the spatial performance of the PANN constitutive model compared to the GT model in a purely static, large deformation solid mechanical scenario is examined. Furthermore, a detailed investigation of the computation times for both PANN and GT models is carried out. The geometry of the membrane is provided by Fig. 3 (left). The membrane is subject to a clamping on its left side while a pressure load is applied to shear the membrane on the right side, as illustrated in Fig. 3 (right). The resultant force of the pressure load has the magnitude of \(p=200\) Pa and shows into the positive \(\mathbf{e}_{3}\)-direction. For the discretization, displacement-based trilinear hexahedron elements based on to Eq. (42) are employed. In Fig. 4, typical deformed configurations for both the GT and the PANN8 model are provided. The mesh convergence study in Fig. 5 (left) shows a practically identical behavior for the GT model and the PANN model for all choices of nodes. Unsurprisingly, the PANN model is able to perfectly \begin{table} \begin{tabular}{c|c c|c c} & \multicolumn{2}{c|}{compressible model} & \multicolumn{2}{c}{nearly incompressible model} \\ & calibration & test & calibration & test \\ \hline PANN & 4 & 1.70 & 0.89 & \\ & 8 & 0.84 & 0.61 & 1.05 & 0.23 \\ & 16 & 0.93 & 0.61 & \\ & 32 & 0.25 & 0.15 & \\ & 64 & -0.23 & 0.17 & \\ & 128 & -0.11 & 0.10 & \\ \end{tabular} \end{table} Table 2: \(\log_{10}(\mathcal{MSE})\) according to Eq. (29) for the calibrated PANN models. Figure 2: Mixed shear-tension test evaluated for the GT models (marks) and the calibrated PANN8 models (continous lines) for both the compressible (left) and the nearly incompressible (right) case. Stress in MPa. represent the behavior of the GT model, even for small numbers of nodes. This is also reflected in the Newton iterations required to solve the system of nonlinear equations, which are visualized in Fig. 5 (right) for a typical mesh and load step. For all choices of nodes in the PANN model, the required Newton iterations and the corresponding norm of the residual are equal to the GT model. This shows that the PANN model is not only able to excellently predict the stress behavior of the GT model, which is closely related to the first derivative of the hyperelastic potential, but also excellently predicts the second derivative, which is essential for the solution of the nonlinear FEA, although the second derivative was not included in the calibration process, cf. Sect. 3.2. In Fig. 6 and Fig. 7, the percentage computation times for the simulation of Cook's membrane with 14406 degree of freedom (DOFs) on one single core are presented for the GT model and the PANN128 model, respectively. On the element level of the GT model, the evaluation of the derivatives of the analytical Mooney-Rivlin potential ("GT derivatives") only makes up 5% of the computation time and takes even less time than operations such as the evaluation of the tensor cross product. For the PANN128 model, however, the evaluation of the NN potential is significantly more expensive and takes over 50% of the computation time on element level. Thus, the overall simulation time is increased. In Fig. 8, the computation time for the GT model and the PANN model with different numbers of nodes on one single core are visualized. Depending on the number Figure 4: Deformed configuration with von Mises stress distribution \(\sigma_{vM}\) [Pa] with a typical mesh and load step for compressible GT model (left) and the corresponding PANN8 model (mid). Figure 3: 2D projection of the geometry (left) and 3D illustration of the boundary conditions (right) of the Cook’s membrane. of nodes in the NN, the computation time of the PANN model is more than twice as long compared to the GT model, when the simulation is carried out on a single core. However, when the FEA is parallelised on 24 cores, the computation time of the PANN model is equal to the computation time of the analytical GT model, and, within the examined bounds, even independent of the number of nodes in the hidden layer. The parallelization is employed within the research code moofeKIT [30] written in Matlab using the Parallel Computing Toolbox. In particular, the element routine is parallelized within a parallel for loop environment parfor. Obviously, the computation time is highly influenced by many factors, such as computer hardware and programming language. Still, our findings suggest that with a suitable implementation of the NN-based constitutive model, computation times comparable to analytical constitutive models can be achieved. #### 7.2.2 Nearly incompressible case In the next step, Cook's membrane is simulated with a nearly incompressible material behavior of both the GT and the PANN model. Thereby, the performance of the PANN constitutive model Figure 5: Convergence plot with vertical displacement of point A (see Fig. 3) vs. mesh refinement (left) and Newton iterations for a typical mesh and load step (right). Figure 6: Percentage computation time of the GT model on global level (left) with 1.6% assembly of \(\mathbf{K}\) included in the slice “other”, and percentage computation time on element level (right), where the operator matrix \(\mathcal{D}(\mathbf{A})\) is employed (see [9, Appx. B]). Evaluated for the simulation of Cook’s membrane with 14406 DOFs on one core. when applied in mixed formulations, which avoid the locking effect, is investigated. The resultant force of the pressure load has the magnitude of \(p=100\) Pa and shows into the positive \(\mathbf{e}_{3}\)-direction, see Fig. 3. Typical deformed configurations with von Mises stress are provided in Fig. 9. A convergence study is provided in Fig. 10 (left), where different material models and element types are examined. The solutions for both the GT and the PANN8 model are almost indistinguishable for all elements employed. As to be expected in this nearly incompressible, shear-loaded problem, the locking effect becomes obvious for both displacement-based models with trilinear hexahedron elements (GT - H1 and PANN8 - H1). In contrast to that, the 5-field mixed formulation presented in Eq. (44) with trilinear / constant hexahedron elements (G-J) and the new Hu-Washizu like 7-field mixed formulation in Eq. (47) with trilinear / constant hexahedron elements (I-II-J) exhibit fast, locking-free convergence. In particular, although the I-II-J element only considers the _scalar_ quantities \(I_{\mathbf{C}}\), \(II_{\mathbf{C}}\), and \(J\) as additional kinematic unknowns, it shows the same excellent spatial performance as the G-J element, which, in contrast, includes an additional _tensor-valued_ unknown. Figure 8: Computation times with 1 and 24 core setup for GT and different PANN models, evaluated for the simulation of Cook’s membranan with 36015 DOFs. Figure 7: Percentage computation time of the PANN128 model on global level (left) with 0.5% assembly of \(\mathbf{K}\) included in the slice “other”, and percentage computation time on element level (right). Evaluated for the simulation of Cook’s membrane with 14406 DOFs on one core. ### Dynamics of L-shaped body The objective of this investigation is to demonstrate the discrete conservation properties of the proposed EM integrator, particularly applied in the context of the PANN model. In addition to that, the robustness and long-term stability of the midpoint (MP) and the EM integrator are compared for the PANN model. The initial boundary value problem of an L-shaped body is considered, which is inspired by [9, 99] (in case of pure mechanics) and [26, 27] (in case of thermo-mechanics and electro-thermo-mechanics, respectively). The geometry of the L-shaped body and the initial setting with boundary conditions are depicted in Fig. 11. Therein the applied dead load pressures \(\mathbf{P}_{1}:\mathcal{T}\rightarrow\mathds{R}^{3}\) and \(\mathbf{P}_{2}:\mathcal{T}\rightarrow\mathds{R}^{3}\) Figure 10: Convergence plot with displacement vs. mesh refinement for the nearly incompressible Cook’s membrane. Different material models (GT and PANN8) and elements (H1: displacement-based trilinear hexahedron, G-J – H1H0: 5-field mixed formulation according to Eq. (44) with trilinear / constant hexahedron elements, and I-II-J – H1H0: new Hu-Washizu like 7-field mixed formulation according to Eq. (47) with trilinear / constant hexahedron elements) are employed. Note that the two alternative constitutive model formulations under investigation essentially lead to the same results for each finite element formulation. Figure 9: Deformed configuration with von Mises stress distribution \(\sigma_{vM}\) [Pa] with a typical mesh and load step for the nearly incompressible GT model (left) and the corresponding PANN8 model (mid). follow the functions \[\mathbf{P}_{1}(t)=f(t)\begin{pmatrix}256/9\\ 512/9\\ 768/9\end{pmatrix}\frac{\mathrm{N}}{\mathrm{m}^{2}}=-\mathbf{P}_{2}(t),\quad \text{with}\quad f(t)=\begin{cases}t&\text{for}\quad t\leq 2.5\ \mathrm{s}\\ 5-t&\text{for}\quad 2.5\ \mathrm{s}\leq t\leq 5\ \mathrm{s}\\ 0&\text{for}\quad t>5\ \mathrm{s}\end{cases}. \tag{69}\] In Fig. 12 and Fig. 13 snapshots of the motion of the L-shaped body with von Mises stress distribution for the compressible GT and PANN8 models, respectively, are shown. As can be observed, both stress plots show a remarkable similarity. The total energy and the energy difference of both the GT model and corresponding PANN8 model are shown in Fig. 14 and Fig. 15, respectively. Apparently, the midpoint rule aborts due to energy blow ups for both GT and PANN8 model, even when the time step size is reduced. In contrast, the EMS is stable for both the GT and PANN8 model during this long-term simulation and preserves the total energy after the loading phase (\(t>5\) s). Furthermore, it is important to note that the energy results obtained for the GT and the PANN8 model are practically identical. Furthermore, in Fig. 16 the components of the angular momentum of the L-shaped body for both the GT and the PANN8 model in case of the EMS are shown. As evident from the observation, the components of the angular momentum are preserved after the loading phase (\(t>5\) s). Similar to the energy results, the components of the angular momentum exhibit practically identical results for both models. ## 8 Conclusion In this contribution, advanced spatial and temporal discretization techniques are tailored to hyperelastic PANN constitutive models, i.e., NN-based constitutive models which fulfill all relevant mechanical conditions of hyperelasticity by construction [69]. One of the benefits of PANN-based constitutive models is their extraordinary flexibility, which is achieved by using NNs as highly flexible functions. Actually, the feed-forward neural networks applied for this have a quite simple structure, which is based on only a few ingredients. Furthermore, from a formal point of view, NNs are nothing more but mathematical functions, and thus, constitutive models based on NNs can be applied in numerical methods just like their analytical counterparts. Still, the explicit mathematical formulation of the NN, and even more its derivatives often required for numerical applications, are quite extensive Figure 11: 2D projection of the geometry (left) and 3D illustration of the boundary conditions (right) of the L-shaped body with \(t=3m\). Figure 12: Snapshots with von Mises stress distribution \(\sigma_{vM}\) [Pa] of the GT model at times \(t\in\{4.0,8.0,12.0,16.0,20.0,24.0\}s\). Figure 13: Snapshots with von Mises stress distribution \(\sigma_{vM}\) [Pa] of the PANN8 model at times \(t\in\{4.0,8.0,12.0,16.0,20.0,24.0\}s\). Figure 16: Components of angular momentum of the L-shaped body for the GT model (marks) and for the PANN8 model (continuous lines), both in case of the energy momentum scheme. Figure 14: Total energy of the L-shaped body (left) for the energy-momentum scheme (EM) and the midpoint rule (MP), and energy difference (right) for the EM scheme. Evaluated for the GT model. Figure 15: Total energy of the L-shaped body (left) for the energy-momentum scheme (EM) and the midpoint rule (MP), and energy difference (right) for the EM scheme. Evaluated for the PANN8 model. compared to analytical constitutive models. This suggests to tailor advanced discretization methods for NN-based constitutive models, to arrive at compact mathematical formulations and convenient implementations with superior stability and robustness in static and dynamic analysis. In the present work, this is achieved by setting the focus of the numerical methods on the scalar-valued strain invariants that hyperelastic stored energy functions depend on, rather than considering the full tensorial strain measures. Thereby, the evaluation of the hyperelastic potential and its derivatives w.r.t. the strain invariants is separated from the derivatives of the strain invariants w.r.t. the primal tensorial strain measures. This is a very natural choice, since for NN-based constitutive models, the derivatives of the hyperelastic potential w.r.t. the invariants become more complex, while the derivatives of the invariants remain the same as in the analytical theory. In this regard, an elegant 7-field Hu-Washizu like mixed formulation is proposed, where the additional unknowns are only strain invariants. This novel mixed formulation is applicable for nearly incompressible material behavior, in particular, to avoid locking phenomena. Furthermore, a novel energy-momentum scheme (EMS) is designed, which is applicable in dynamical simulations to preserve energy and momentum in the discretized version of the weak form. At the same time, the EMS highly improves the numerical stability in transient simulations. For this, a new algorithmic stress formula is proposed, which, again, only depends on strain invariants. Here, the required discrete gradients are formulated in scalar-valued invariants, therefore only consisting of Greenspan formulas. The employed Greenspan formulas are by far less complex for both consistent tangent computation and implementation when compared to the usually employed projection-based discrete gradients. Both the mixed method and the EMS are applied in finite element analysis. For this, the hyperelastic PANN model proposed by [69] is calibrated to data generated with an analytical Mooney-Rivlin potential. Unsurprisingly, due to the simple nature of the analytical potential, the results obtained with the PANN model are practically identical to the results obtained with the Mooney-Rivlin model in all simulations. The newly proposed mixed 7-field Hu-Washizu like formulation showed excellent performance in a scenario where purely displacement-based formulations extensively suffer from locking phenomena. Also, it showed similar results when compared to a state-of-the-art mixed, polyconvex 5-field approach [59] which considers tensor-valued quantities as additional unknowns. Furthermore, in a benchmark example, it could be shown that with a suitable parallelization strategy, the computation time of the NN-based model is practically the same as for the analytical constitutive model. In a dynamical simulation, the tailored EMS showed a remarkable stability and robustness even for coarse time steps when compared to the symplectic midpoint-rule. Overall, the numerical examples demonstrate the superior stability and robustness of the proposed numerical methods. Finally, future work should be concerned with the extension of the proposed methods towards multiphysics [56, 112], inelasticity [1, 77, 93], and structural mechanics. Furthermore, while the present work only considers isotropic material behavior, the extension to further symmetry groups is straightforward [22, 69]. **Conflict of interest.** The authors declare that they have no conflict of interest. **Software.** The source code used for the finite element computations is implemented in Matlab under MIT license and is available at [https://github.com/kit-ifm/moofeKIT](https://github.com/kit-ifm/moofeKIT). Version 1.XX of the code, used in this paper, is archived at [30]. **Acknowledgement.** M. Franke acknowledges the financial support provided by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation, project number 443238377). D.K. Klein and O. Weeger acknowledge the financial support provided by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation, project number 492770117), the Graduate School of Computational Engineering at TU Darmstadt, and Hessian.AI. ## Appendix A Continous balance laws The verification of the time-continuous balance laws, i.e., balance of angular momentum and balance of total energy for the weak form given in Eq. (51), will be dealt with in the following. ### Balance of angular momentum In order to verify the balance of angular momentum, we introduce the angular momentum \[\mathbf{J}_{t}=\int_{\mathcal{B}_{0}}\boldsymbol{\varphi}_{t}\times\rho_{0} \,\mathbf{v}_{t}\,\,\mathrm{d}V\,,\] (A.1) and the external momentum \[\mathbf{M}_{t}^{\mathrm{ext}}=\int_{\mathcal{B}_{0}}\boldsymbol{\varphi}_{t} \times\mathbf{B}_{t}\,\,\mathrm{d}V+\int_{\partial\mathcal{B}_{0}^{T}} \boldsymbol{\varphi}_{t}\times\mathbf{T}_{t}\,\,\mathrm{d}A\,.\] (A.2) Furthermore, we choose the admissible variations \[\delta\boldsymbol{\varphi}=\boldsymbol{\xi}\times\boldsymbol{\varphi}_{t}\,, \quad\delta\mathbf{v}=\boldsymbol{\xi}\times\dot{\boldsymbol{\varphi}}_{t}\,,\] (A.3) where \(\mathds{R}^{3}\ni\boldsymbol{\xi}=\mathrm{const}\). For further considerations, we anticipate \[\mathbf{F}(\delta\boldsymbol{\varphi}=\boldsymbol{\xi}\times\boldsymbol{ \varphi}_{t})=\boldsymbol{\hat{\xi}}\,\mathbf{F}_{t}\,,\] (A.4) where \(\boldsymbol{\hat{\xi}}\) is skew-symmetric, such that \[\boldsymbol{\hat{\xi}}\,\mathbf{a}=\boldsymbol{\xi}\times\boldsymbol{\varphi }_{t}\quad\forall\mathbf{a}\in\mathds{R}^{3}\,.\] (A.5) Recall Eq. (51)\({}_{1}\) and substitute Eq. (A.3)\({}_{2}\), which finally yields \[\boldsymbol{\xi}\cdot\int_{\mathcal{B}_{0}}(\dot{\boldsymbol{\varphi}}_{t} \times\mathbf{v}_{t})\,\rho_{0}\,\,\mathrm{d}V=0\,,\] (A.6) where therein the identity \(\dot{\boldsymbol{\varphi}}\times\dot{\boldsymbol{\varphi}}=\mathbf{0}\) has been employed. Consider the integrand of the 2nd term in Eq. (51)\({}_{2}\) and substitute Eq. (A.3)\({}_{1}\) \[\mathbf{S}_{t}:\tfrac{1}{2}\,\delta\mathbf{C}_{t}=\mathbf{S}_{t}:\frac{1}{2} \left(\mathbf{F}_{t}^{\mathrm{T}}\left(\boldsymbol{\hat{\xi}}^{\mathrm{T}}+ \boldsymbol{\hat{\xi}}\right)\mathbf{F}_{t}\right)=0\,,\] (A.7) which is due to skew-symmetry of \(\boldsymbol{\hat{\xi}}\), i.e. \(\boldsymbol{\hat{\xi}}^{\mathrm{T}}=-\boldsymbol{\hat{\xi}}\). Recall Eq. (51)\({}_{2}\) and substitute Eq. (A.3)\({}_{1}\) \[\boldsymbol{\xi}\cdot\int_{\mathcal{B}_{0}}\boldsymbol{\varphi}_{t}\times \dot{\mathbf{v}}_{t}\,\rho_{0}\,\,\mathrm{d}V+\Pi^{\mathrm{ext}}(\boldsymbol {\xi}\times\boldsymbol{\varphi}_{t})=0\,,\] (A.8) for the above we finally obtain with Eq. (A.6) the desired balance of angular momentum \[\boldsymbol{\xi}\cdot\left(\frac{\,\mathrm{d}}{\,\mathrm{d}t}\, \int_{\mathcal{B}_{0}}\boldsymbol{\varphi}_{t}\times\mathbf{v}_{t}\,\rho_{0} \,\,\mathrm{d}V-\int_{\mathcal{B}_{0}}\boldsymbol{\varphi}_{t}\times\mathbf{ B}_{t}\,\,\mathrm{d}V-\int_{\partial\mathcal{B}_{0}^{T}}\boldsymbol{\varphi}_{t} \times\mathbf{T}_{t}\,\,\mathrm{d}V\right) =0\] \[\Leftrightarrow\quad\boldsymbol{\xi}\cdot\left(\frac{\,\mathrm{d} }{\,\mathrm{d}t}\,\mathbf{J}_{t}-\mathbf{M}_{t}^{\mathrm{ext}}\right) =0\,.\] ### Balance of total energy With the definition of the kinetic energy \[T_{t}=\frac{1}{2}\,\int_{\mathcal{B}_{0}}\rho_{0}\,\mathbf{v}_{t}\cdot\mathbf{v}_ {t}\ \mathrm{d}V\,,\] (A.9) at hand, we choose the admissible variations \[\delta\boldsymbol{\varphi}=\dot{\boldsymbol{\varphi}}_{t},\qquad\delta\mathbf{v }=\dot{\mathbf{v}}_{t}\,,\] (A.10) and substitute Eq. (A.10)\({}_{2}\) into Eq. (51)\({}_{1}\), such that \[\int_{\mathcal{B}_{0}}\dot{\boldsymbol{\varphi}}_{t}\cdot\dot{\mathbf{v}}_{t} \,\rho_{0}\ \mathrm{d}V=\int_{\mathcal{B}_{0}}\mathbf{v}_{t}\cdot\dot{\mathbf{v}}_{t}\, \rho_{0}\ \mathrm{d}V=\frac{\mathrm{d}}{\mathrm{d}t}\,\left(\frac{1}{2}\,\int_{ \mathcal{B}_{0}}\mathbf{v}\cdot\mathbf{v}_{t}\,\rho_{0}\ \mathrm{d}V\right)=\dot{T}_{t}\,.\] (A.11) Consider the derivative w.r.t. time of the internal potential \[\frac{\mathrm{d}}{\mathrm{d}t}\,w^{1}\Pi_{t}^{\mathrm{int}} =\frac{\mathrm{d}}{\mathrm{d}t}\,\int_{\mathcal{B}_{0}}W^{1}(I_{ \mathbf{C}_{t}},II_{\mathbf{C}_{t}},III_{\mathbf{C}_{t}})\ \mathrm{d}V\] \[=\int_{\mathcal{B}_{0}}\partial_{I\mathbf{C}}W^{1}\mathbf{I}: \dot{\mathbf{C}}_{t}+\partial_{II_{\mathbf{C}}}W^{1}\mathbf{I}:\dot{\mathbf{G} }_{t}+\partial_{J}W^{1}\dot{J}_{t})\ \mathrm{d}V\] \[=\int_{\mathcal{B}_{0}}2\,\left(\partial_{I_{\mathbf{C}}}W^{1} \mathbf{I}+\partial_{II_{\mathbf{C}}}W^{1}\mathbf{I}\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\! Considering the integrand of the first term of the right-hand side of Eq. (54)\({}_{2}\) and plugging in Eq. (B.1)\({}_{1}\) yields \[\mathbf{S}_{\text{algo}}:\frac{1}{2}\,\mathbf{F}_{n+\frac{1}{2}}{}^{\text{T}}\,( \hat{\boldsymbol{\xi}}+\hat{\boldsymbol{\xi}}{}^{\text{T}})\,\mathbf{F}_{n+ \frac{1}{2}}{}^{\text{T}}=0\,.\] (B.4) With the above in mind, plugging Eq. (B.1)\({}_{1}\) into the whole Eq. (54)\({}_{2}\) and adding Eq. (B.3) yields after some algebra the desired semi-discrete balance of angular momentum \[\boldsymbol{\xi}\cdot\left(\frac{1}{\Delta t}\,\int_{\mathcal{B}_{ 0}}(\Delta\boldsymbol{\varphi}\times\mathbf{v}_{n+\frac{1}{2}}+\boldsymbol{ \varphi}_{n+\frac{1}{2}}\times\Delta\mathbf{v})\,\rho_{0}\,\,\mathrm{d}V \right)=\boldsymbol{\xi}\cdot\left(\int_{\mathcal{B}_{0}}\boldsymbol{\varphi} _{n+\frac{1}{2}}\times\mathbf{B}_{n+\frac{1}{2}}\,\,\mathrm{d}V\] \[\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad+\int_{\partial \mathcal{B}_{0}^{\text{T}}}\boldsymbol{\varphi}_{n+\frac{1}{2}}\times \mathbf{T}_{n+\frac{1}{2}}\,\,\mathrm{d}A\right)\] \[\Leftrightarrow\qquad\boldsymbol{\xi}\cdot\frac{1}{\Delta t}\, \int_{\mathcal{B}_{0}}(\rho_{0}\,\boldsymbol{\varphi}_{n+1}\times\mathbf{v}_ {n+1}-\rho_{0}\,\boldsymbol{\varphi}_{n}\times\mathbf{v}_{n})\,\,\mathrm{d}V =\boldsymbol{\xi}\cdot\mathbf{M}_{n,n+1}^{\text{ext}}\] \[\Leftrightarrow\qquad\boldsymbol{\xi}\cdot\left(\frac{1}{\Delta t }\,\Delta\mathbf{J}-\mathbf{M}_{n,n+1}^{\text{ext}}\right)=0\,.\] (B.5) Accordingly, the proposed EM scheme consistently reproduces the balance of angular momentum for the time-discrete system which is e.g. in contrast to the 2nd order accurate trapezoidal rule. ### Balance of total energy To verify the balance of energy in the semi-discrete weak form Eq. (54), we choose admissible variations \[\delta\boldsymbol{\varphi}=\boldsymbol{\varphi}_{n+1}-\boldsymbol{\varphi}_{n }=\Delta\boldsymbol{\varphi},\quad\delta\mathbf{v}=\mathbf{v}_{n+1}-\mathbf{v} _{n}=\Delta\mathbf{v}\,,\] (B.6) plug Eq. (B.6)\({}_{2}\) into Eq. (54)\({}_{1}\): \[\int_{\mathcal{B}_{0}}\Delta\boldsymbol{\varphi}\,\frac{1}{\Delta t }\,(\boldsymbol{\varphi}_{n+1}-\boldsymbol{\varphi}_{n})\,\rho_{0}\,\,\mathrm{d}V =\int_{\mathcal{B}_{0}}\Delta\mathbf{v}\cdot\frac{1}{2}\,(\mathbf{ v}_{n+1}-\mathbf{v}_{n})\,\rho_{0}\,\,\mathrm{d}V\] \[=\frac{1}{2}\,\int_{\mathcal{B}_{0}}\rho_{0}\,(\mathbf{v}_{n+1} \cdot\mathbf{v}_{n+1}-\mathbf{v}_{n}\cdot\mathbf{v}_{n})\,\,\mathrm{d}V\] \[=T_{n+1}-T_{n}=\Delta T\,.\] (B.7) and plug Eq. (B.6)\({}_{1}\) into the integrand of the first term of the right-hand side of Eq. (54)\({}_{2}\): \[\mathbf{S}_{\text{algo}}:\text{sym}(\Delta\mathbf{F}^{\text{T}}\,\mathbf{F}_ {n+\frac{1}{2}})=\mathbf{S}_{\text{algo}}:(\Delta\mathbf{F}^{\text{T}}\, \mathbf{F}_{n+\frac{1}{2}})=\mathbf{S}_{\text{algo}}:\frac{1}{2}(\mathbf{C}_{n +1}-\mathbf{C}_{n})=\mathbf{S}_{\text{algo}}:\frac{1}{2}\Delta\mathbf{C}\,.\] (B.8) Here, the symmetry property \(\mathbb{S}^{3}\cap\mathds{K}^{3}=\{0\}\) has been taken into account, where \(\mathbb{S}^{3}=\{\mathbf{A}\in\mathbb{T}^{3}\,|\,\mathbf{A}=\mathbf{A}^{\text{ T}}\}\) and \(\mathds{K}^{3}=\{\mathbf{A}\in\mathbb{T}^{3}\,|\,\mathbf{A}=-\mathbf{A}^{\text{ T}}\}\) denote spaces of symmetric and skew-symmetric, quadratic second order tensors, respectively. Furthermore, for Eq. (B.8) we insert Eq. (56), which yields after some algebra, cf. Eq. (C.17): \[\mathbf{S}_{\text{algo}}:\frac{1}{2}\Delta\mathbf{C} =\Big{(}\mathrm{D}_{I\mathbf{C}}W^{1}\mathbf{I}+\mathrm{D}_{II \mathbf{C}}W^{1}\mathbf{I}\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\! Plugging Eq. (B.6)\({}_{1}\) into the whole Eq. (54)\({}_{2}\), considering the above results Eq. (B.7) and Eq. (B.9), and employing the directionality property Eq. (C.17) yields the desired semi-discrete balance of total energy \[\Delta T=-\int_{\mathcal{B}_{0}}W^{\mathrm{I}}(I_{\mathbf{C}_{n+1} },II_{\mathbf{C}_{n+1}},J_{\mathbf{C}_{n+1}})-W^{\mathrm{I}}(I_{\mathbf{C}_{n} },II_{\mathbf{C}_{n}},J_{\mathbf{C}_{n}})\ \mathrm{d}V+W^{\mathrm{ext}}_{n,n+1}\] (B.10) \[\Leftrightarrow \Delta T+\Delta^{W^{\mathrm{I}}}\Pi^{\mathrm{int}}=W^{\mathrm{ ext}}_{n,n+1}\,,\] where \[W^{\mathrm{ext}}_{n,n+1} =-\left(\Pi^{\mathrm{ext}}_{n+\frac{1}{2}}(\mathbf{\varphi}_{n+1})- \Pi^{\mathrm{ext}}_{n+\frac{1}{2}}(\mathbf{\varphi}_{n})\right)\] (B.11) \[=-\Pi^{\mathrm{ext}}_{n+\frac{1}{2}}(\Delta\mathbf{\varphi})=\int_{ \mathcal{B}_{0}}\Delta\mathbf{\varphi}\cdot\mathbf{B}_{n+\frac{1}{2}}\ \mathrm{d}V+\int_{\partial\mathcal{B}_{0}^{T}}\Delta\mathbf{\varphi}\cdot \mathbf{T}_{n+\frac{1}{2}}\ \mathrm{d}A\,.\] As shown above the proposed EM scheme consistently reproduces the balance of total energy for the time-discrete system. This achievement can be attributed to the algorithmic stress evaluation, as demonstrated in Eq. (B.9). In contrast, standard integrators such as the 2nd order accurate midpoint rule fail to maintain this discrete energy balance. ## Appendix C Partioned discrete gradients of \(W^{\mathrm{I}}\) Introducing the tuple \(\mathbf{\Pi}=(\Pi^{1},\Pi^{2},\Pi^{3})=(I_{\mathbf{C}},II_{\mathbf{C}},J)\), the partitioned discrete gradients \(\mathrm{D}_{I_{\mathbf{C}}}W^{\mathrm{I}}\), \(\mathrm{D}_{II_{\mathbf{C}}}W^{\mathrm{I}}\), and \(\mathrm{D}_{J}W^{\mathrm{I}}\) with final presentation in Eq. (58) are computed with \[D_{\Pi^{i}}W^{\mathrm{I}}=\frac{1}{2}\left(\mathrm{D}_{\Pi^{i}}W ^{\mathrm{I}}|_{\Pi^{J}_{n+1},\Pi^{K}_{n}}+\mathrm{D}_{\Pi^{i}}W^{\mathrm{I}} |_{\Pi^{J}_{n},\Pi^{K}_{n+1}}\right),\] (C.1) \[\forall i\in Y,\quad j\in J<Y>K\ni k\,:\,J\ni j<i<k\in K\,,\] where in general for tensor-valued quantities \(\Pi^{i}\) we have \[\mathrm{D}_{\Pi^{i}}W^{\mathrm{I}}|_{\Pi^{J}_{n+1},\Pi^{K}_{n}}= \partial_{\Pi^{i}}W^{\mathrm{I}}(\Pi^{i}_{n+\frac{1}{2}})|_{\Pi^{ J}_{n+1},\Pi^{K}_{n}}\] (C.2) \[+\frac{W^{\mathrm{I}}(\Pi^{i}_{n+1})|_{\Pi^{J}_{n+1},\Pi^{K}_{n}} -W^{\mathrm{I}}(\Pi^{i}_{n})|_{\Pi^{J}_{n+1},\Pi^{K}_{n}}-<\partial_{\Pi^{i}}W ^{\mathrm{I}}(\Pi^{i}_{n+\frac{1}{2}})|_{\Pi^{J}_{n+1},\Pi^{K}_{n}},\Delta\Pi^ {i}>}{<\Delta\Pi^{i},\Delta\Pi^{i}>}\Delta\Pi^{i}\,,\] and \[\mathrm{D}_{\Pi^{i}}W^{\mathrm{I}}|_{\Pi^{J}_{n},\Pi^{K}_{n+1}}= \partial_{\Pi^{i}}W^{\mathrm{I}}(\Pi^{i}_{n+\frac{1}{2}})|_{\Pi^ {J}_{n},\Pi^{K}_{n+1}}\] (C.3) \[+\frac{W^{\mathrm{I}}(\Pi^{i}_{n+1})|_{\Pi^{J}_{n},\Pi^{K}_{n+1}} -W^{\mathrm{I}}(\Pi^{i}_{n})|_{\Pi^{J}_{n},\Pi^{K}_{n+1}}-<\partial_{\Pi^{i}}W ^{\mathrm{I}}(\Pi^{i}_{n+\frac{1}{2}})|_{\Pi^{J}_{n},\Pi^{K}_{n+1}},\Delta\Pi^ {i}>}{<\Delta\Pi^{i},\Delta\Pi^{i}>}\Delta\Pi^{i}\,,\] whereas for scalar-valued invariants \(\Pi^{i}\) the above simplifies to the so-called Greenspan formulas (cf. [35]) \[\mathrm{D}_{\Pi^{i}}W^{\mathrm{I}}|_{\Pi^{J}_{n+1},\Pi^{K}_{n}}=\frac{W^{ \mathrm{I}}(\Pi^{i}_{n+1})|_{\Pi^{J}_{n+1},\Pi^{K}_{n}}-W^{\mathrm{I}}(\Pi^{i}_ {n})|_{\Pi^{J}_{n+1},\Pi^{K}_{n}}}{\Delta\Pi^{i}}\,,\] (C.4) and \[\mathrm{D}_{\Pi^{i}}W^{\mathrm{I}}|_{\Pi^{J}_{n},\Pi^{K}_{n+1}}=\frac{W^{ \mathrm{I}}(\Pi^{i}_{n+1})|_{\Pi^{J}_{n},\Pi^{K}_{n+1}}-W^{\mathrm{I}}(\Pi^{i} _{n})|_{\Pi^{J}_{n},\Pi^{K}_{n+1}}}{\Delta\Pi^{i}}\,.\] (C.5) This finally leads to 1. the partioned discrete gradient \(\mathrm{D}_{I_{\mathbf{C}}}W^{\mathrm{I}}\) \[D_{I_{\mathbf{C}}}W^{\mathrm{I}}=\frac{1}{2}\left(\mathrm{D}_{I_{\mathbf{C}}}W^{ \mathrm{I}}|_{\Pi_{n+1}^{J},\Pi_{n}^{K}}+\mathrm{D}_{I_{\mathbf{C}}}W^{\mathrm{I }}|_{\Pi_{n}^{J},\Pi_{n+1}^{K}}\right)\] (C.6) with being \(i=1\), \(J=\emptyset\), \(K=\{2,3\}\) we have \(\Pi^{1}=I_{\mathbf{C}}\), \(\Pi^{J}=\emptyset\), \(\Pi^{K}=(II_{\mathbf{C}},III_{\mathbf{C}})\) and thus \[\mathrm{D}_{I_{\mathbf{C}}}W^{\mathrm{I}}|_{\Pi_{n+1}^{J},\Pi_{n}^{K}} =\frac{W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n}},J_ {n})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n})}{\Delta I_{ \mathbf{C}}}\] (C.7) \[\mathrm{D}_{I_{\mathbf{C}}}W^{\mathrm{I}}|_{\Pi_{n}^{J},\Pi_{n+1}^{K}} =\frac{W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}}, J_{n+1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n+1}},J_{n+1})}{ \Delta I_{\mathbf{C}}}\] 2. the partioned discrete gradient \(\mathrm{D}_{II_{\mathbf{C}}}W^{\mathrm{I}}\) \[D_{II_{\mathbf{C}}}W^{\mathrm{I}}=\frac{1}{2}\left(\mathrm{D}_{II_{\mathbf{C}}}W^{ \mathrm{I}}|_{\Pi_{n+1}^{J},\Pi_{n}^{K}}+\mathrm{D}_{II_{\mathbf{C}}}W^{ \mathrm{I}}|_{\Pi_{n}^{J},\Pi_{n+1}^{K}}\right)\] (C.8) with being \(i=2\), \(J=1\), \(K=3\) we have \(\Pi^{2}=II_{\mathbf{C}}\), \(\Pi^{J}=I_{\mathbf{C}}\), \(\Pi^{K}=III_{\mathbf{C}}\) and thus \[\mathrm{D}_{II_{\mathbf{C}}}W^{\mathrm{I}}|_{\Pi_{n+1}^{J},\Pi_{n}^{K}} =\frac{W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}}, J_{n})-W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n}},J_{n})}{ \Delta II_{\mathbf{C}}}\] (C.9) \[\mathrm{D}_{II_{\mathbf{C}}}W^{\mathrm{I}}|_{\Pi_{n}^{J},\Pi_{n+1}^{K}} =\frac{W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n+1}}, J_{n+1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n+1})}{ \Delta II_{\mathbf{C}}}\] 3. the partioned discrete gradient \(\mathrm{D}_{J}W^{\mathrm{I}}\) \[D_{J}W^{\mathrm{I}}=\frac{1}{2}\left(\mathrm{D}_{J}W^{\mathrm{I}}|_{\Pi_{n+1}^{J },\Pi_{n}^{K}}+\mathrm{D}_{J}W^{\mathrm{I}}|_{\Pi_{n}^{J},\Pi_{n+1}^{K}}\right)\] (C.10) with being \(i=3\), \(J=\{1,2\}\), \(K=\emptyset\) we have \(\Pi^{3}=J\), \(\Pi^{J}=(I_{\mathbf{C}},II_{\mathbf{C}})\), \(\Pi^{K}=\emptyset\) and thus \[\mathrm{D}_{J}W^{\mathrm{I}}|_{\Pi_{n+1}^{J},\Pi_{n}^{K}} =\frac{W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}}, J_{n+1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}},J_{n})}{ \Delta J}\] (C.11) \[\mathrm{D}_{J}W^{\mathrm{I}}|_{\Pi_{n}^{J},\Pi_{n+1}^{K}} =\frac{W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n +1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n})}{\Delta J}\] For the above partioned discrete gradients \((\mathrm{D}_{I_{\mathbf{C}}}W^{\mathrm{I}},\mathrm{D}_{II_{\mathbf{C}}}W^{ \mathrm{I}},\mathrm{D}_{J}W^{\mathrm{I}})\), conveniently shown in Eq. (58), the directionality property \[\mathrm{D}_{I_{\mathbf{C}}}W^{\mathrm{I}}\,\Delta I_{\mathbf{C}}+ \mathrm{D}_{II_{\mathbf{C}}}W^{\mathrm{I}}\,\Delta II_{\mathbf{C}}+\mathrm{D} _{J}W^{\mathrm{I}}\,\Delta III_{\mathbf{C}}\] (C.12) \[= \frac{1}{2}\left(W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C} _{n}},J_{n})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n})\right.\] \[+W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}},J_{n+1} )-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n+1}},J_{n+1})\right)\] (C.13) \[+W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n+1}},J_{n+1} )-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n+1})\] (C.14) \[+\frac{1}{2}\left(W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C} _{n+1}},J_{n+1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}},J_{n})\right.\] (C.15) \[+W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n+1})-W^{ \mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n})\right)\] (C.16) \[= \quad W^{\mathrm{I}}(I_{\mathbf{C}_{n+1}},II_{\mathbf{C}_{n+1}},J_{n +1})-W^{\mathrm{I}}(I_{\mathbf{C}_{n}},II_{\mathbf{C}_{n}},J_{n})\] (C.17) is obviously fulfilled. Partioned discrete gradients of \(\hat{W}^{\text{C}}\) In analogy to Eq. (C.1)-Eq. (C.5) the partitioned discrete gradients \(\text{D}_{\text{C}}\hat{W}^{\text{C}}\), \(\text{D}_{\text{G}}\hat{W}^{\text{C}}\), and \(\text{D}_{C}\hat{W}^{\text{C}}\) of the strain energy \(\hat{W}^{\text{C}}(\text{C},\,\text{G},\,C)\) eventually are 1. the partioned discrete gradient \(\text{D}_{\text{C}}W^{\text{C}}\) \[\begin{split}&(\text{D}_{\text{C}}\hat{W}^{\text{C}})_{ij}=\frac{1} {2}(\partial_{\text{C}}\hat{W}^{\text{C}}(\text{C}_{n+\frac{1}{2}},\text{G}_{n },C_{n})\\ &+\partial_{\text{C}}\hat{W}^{\text{C}}(\text{C}_{n+\frac{1}{2}}, \text{G}_{n},C_{n}))_{kl}\,(\delta_{ki}\delta_{lj}-\frac{(\Delta\text{C})_{kl} (\Delta\text{C})_{ij}}{(\Delta\text{C})_{mn}\,(\Delta\text{C})_{mn}})\\ &+\frac{\hat{W}^{\text{C}}(\text{C}_{n+1},\text{G}_{n},C_{n})+ \hat{W}^{\text{C}}(\text{C}_{n+1},\text{G}_{n+1},C_{n+1})-\hat{W}^{\text{C}}( \text{C}_{n},\text{G}_{n},C_{n})-\hat{W}^{\text{C}}(\text{C}_{n},\text{G}_{n+ 1},C_{n+1})}{2\,(\Delta\text{C})_{mn}\,(\Delta\text{C})_{mn}}(\Delta\text{C})_{ ij}\end{split}\] (D.1) 2. the partioned discrete gradient \(\text{D}_{\text{G}}\hat{W}^{\text{C}}\) \[\begin{split}&(\text{D}_{\text{G}}\hat{W}^{\text{C}})_{ij}= \frac{1}{2}(\partial_{\text{G}}\hat{W}^{\text{C}}(\text{C}_{n+1},\text{G}_{n+ \frac{1}{2}},C_{n})\\ &+\partial_{\text{C}}\hat{W}^{\text{C}}(\text{C}_{n},\text{G}_{n +\frac{1}{2}},C_{n+1}))_{kl}\,(\delta_{ki}\delta_{lj}-\frac{(\Delta\text{G})_{ ij}(\Delta\text{G})_{kl}}{(\Delta\text{G})_{mn}\,(\Delta\text{G})_{mn}})\\ &+\frac{\hat{W}^{\text{C}}(\text{C}_{n+1},\text{G}_{n+1},C_{n})+ \hat{W}^{\text{C}}(\text{C}_{n},\text{G}_{n+1},C_{n+1})-\hat{W}^{\text{C}}( \text{C}_{n+1},\text{G}_{n},C_{n})-\hat{W}^{\text{C}}(\text{C}_{n},\text{G}_{ n},C_{n+1})}{2\,(\Delta\text{G})_{mn}\,(\Delta\text{G})_{mn}}(\Delta\text{G})_{ ij}\end{split}\] (D.2) 3. the partioned discrete gradient \(\text{D}_{C}\hat{W}^{\text{C}}\) \[\begin{split}\text{D}_{C}\hat{W}^{\text{C}}=& \frac{1}{2}\,\left(\frac{\hat{W}^{\text{C}}(\text{C}_{n+1},\text{G}_{n+1},C_{n+ 1})-\hat{W}^{\text{C}}(\text{C}_{n+1},\text{G}_{n+1},C_{n})}{\Delta C}\right. \\ &+\left.\frac{\hat{W}^{\text{C}}(\text{C}_{n},\text{G}_{n},C_{n+ 1})-\hat{W}^{\text{C}}(\text{C}_{n},\text{G}_{n},C_{n})}{\Delta C}\right)\,. \end{split}\] (D.3) In comparison to an analytical Mooney-Rivlin model as proposed in [9] the above discrete gradients are pretty challenging to handle for the consistent linearization, since for the PANN constitutive model employed the discrete gradients \(\text{D}_{\text{C}}\hat{W}^{\text{C}}\), \(\text{D}_{\text{G}}\hat{W}^{\text{C}}\) are not constant and furthermore are dependend from all its dependencies \((\text{C},\text{G},C)\). ## Appendix E Discrete gradient of \(W^{\text{C}}\) The projection-based discrete Gradient for \(W^{\text{C}}(\text{C})\) is given by \[\text{D}_{\text{C}}W^{\text{C}}=\partial_{\text{C}}W^{\text{C}}(\text{C}_{n+ \frac{1}{2}})+\frac{W^{\text{C}}(\text{C}_{n+1})-W^{\text{C}}(\text{C}_{n})- \partial_{\text{C}}W^{\text{C}}(\text{C}_{n+\frac{1}{2}}):\Delta\text{C}}{ \Delta\text{C}:\Delta\text{C}}\,\Delta\text{C}\] (E.1) where despite the chain rule which is necessary for the PANN constitutive model with its inputs \(\boldsymbol{\mathcal{I}}\) the discrete gradient is tensor-valued and therefore is by far complex when compared to the proposed version in Eq. (58).
2308.02509
Robust vertebra identification using simultaneous node and edge predicting Graph Neural Networks
Automatic vertebra localization and identification in CT scans is important for numerous clinical applications. Much progress has been made on this topic, but it mostly targets positional localization of vertebrae, ignoring their orientation. Additionally, most methods employ heuristics in their pipeline that can be sensitive in real clinical images which tend to contain abnormalities. We introduce a simple pipeline that employs a standard prediction with a U-Net, followed by a single graph neural network to associate and classify vertebrae with full orientation. To test our method, we introduce a new vertebra dataset that also contains pedicle detections that are associated with vertebra bodies, creating a more challenging landmark prediction, association and classification task. Our method is able to accurately associate the correct body and pedicle landmarks, ignore false positives and classify vertebrae in a simple, fully trainable pipeline avoiding application-specific heuristics. We show our method outperforms traditional approaches such as Hungarian Matching and Hidden Markov Models. We also show competitive performance on the standard VerSe challenge body identification task.
Vincent Bürgin, Raphael Prevost, Marijn F. Stollenga
2023-07-27T09:10:27Z
http://arxiv.org/abs/2308.02509v1
# Robust verteb identification using simultaneous node and edge predicting Graph Neural Networks ###### Abstract Automatic vertebra localization and identification in CT scans is important for numerous clinical applications. Much progress has been made on this topic, but it mostly targets positional localization of vertebrae, ignoring their orientation. Additionally, most methods employ heuristics in their pipeline that can be sensitive in real clinical images which tend to contain abnormalities. We introduce a simple pipeline that employs a standard prediction with a U-Net, followed by a single graph neural network to associate and classify vertebrae with full orientation. To test our method, we introduce a new vertebra dataset that also contains pedicle detections that are associated with verteb bodies, creating a more challenging landmark prediction, association and classification task. Our method is able to accurately associate the correct body and pedicle landmarks, ignore false positives and classify vertebrae in a simple, fully trainable pipeline avoiding application-specific heuristics. We show our method outperforms traditional approaches such as Hungarian Matching and Hidden Markov Models. We also show competitive performance on the standard VerSe challenge body identification task. Keywords:graph neural networks spine localization spine classification deep learning. ## 1 Introduction Vertebra localization and identification from CT scans is an essential step in medical applications, such as pathology diagnosis, surgical planning, and outcome assessment [6, 3]. This is however a tedious manual task in a time-sensitive setting that can benefit a lot from automation. However, automatically identifying and determining the location and orientation of each vertebra from a CT scan can be very challenging: (i) scans vary greatly in intensity and constrast, (ii) metal implants and other materials can affect the scan quality, (iii) vertebrae might be deformed, crushed or merged together due to medical conditions, (iv) vertebrae might be missing due to accidents or previous surgical operations. Recently, public challenges like the VerSe challenge [24] have offered a common benchmarking platform to evaluate algorithms to automate this task, resulting in a boost in research on this topic. However, these challenges focus on finding the position of vertebrae, ignoring the orientation or direction. Additionally, practically all methods employ manual heuristic methods to identify landmarks and filter out false positives. In this paper, we introduce a trainable method that performs vertebrae localization, orientation estimation and classification with a single architecture. We replace all hand-crafted rules and post-processing steps with a single trainable Graph Neural Network (GNN) that learns to filter out, associate and classify landmarks. We apply a generalized Message Passing layer that can perform edge and node classification simultaneously. This alleviates the need for sensitive hand-tuned parameter tuning, and increases robustness of the overall pipeline. The main contributions of our work are: (1) introducing a pipeline that uses a single Graph Neural Network to perform simultaneous vertebra identification, landmark association, and false positive pruning, without the need for any heuristic methods and (2) building and releasing a new spine detection dataset that adds pedicles of vertebrae to create a more complex task that includes orientation estimation of vertebrae, which is relevant for clinical applications. ## 2 Related Work **Spine Landmark Prediction and Classification** The introduction of standardised spine localization and classification challenges [10, 24] resulted in a boost in research on this problem. Convolutional Neural Networks (CNN) became a dominant step in most approaches shortly after their introduction [7]. Most modern methods process the results of a CNN using a heuristic method to create a 1-dimensional sequence of vertebra detections, before applying classification: [27] generate heatmaps for body positions, and refine it into a single sequence graph that uses message passing for classification. [14] generate heatmaps, extract a 1-dimensional sequence and use a recurrent neural network for classification. [18] produce a heatmap using a U-Net [21], but use a simpler approach by taking the local maxima as landmarks, and forming a sequence by accepting the closest Figure 1: Summary of the proposed method. A CNN generates a heatmap from which local maxima are connected using k-nearest neighbours to form a graph. Then a single GNN associates the keypoints, performs classification and filters out false postives. The full pipeline is trained and does not require hand-tuned post-processing. vertebra that is within a defined distance range. [16] uses a directional graph and Dynamic Programming to find an optimal classification. **Graph Neural Networks** In recent years, Graph Neural Networks (GNN) have surged in popularity [11], with a wide and growing range of applications [26]. A prominent task in the literature is node-level representation learning and classification. A less prominent task is edge classification, for which early work used a dual representation to turn edge- into node representations [1]. Other approaches model edge embeddings explicitly, such as [12] and [4]. The most general formulation of GNNs is the message-passing formulation [5] which can be adapted to perform both edge and node classification at the same time. We use this formulation in our method. Various methods have applied GNNs to keypoint detection, however they all apply to 2-dimensional input data. In [20] GNNs are used to detect cars in images. An edge classification task is used to predict occluded parts of the car. However, the GNN step is ran individually for every car detection and the relation between cars is not taken into account, unlike our task. Also there is no node classification applied. In [15] a GNN is used to group detected keypoints for human-pose estimation on images. Keypoints are grouped using edge prediction where edge-embeddings are used as input the the GNN. A separate GNN processes node embeddings to facilitate the final grouping. However, the node and edge embeddings are processed separately from each other. ## 3 Method In this paper we tackle vertebra localization and classification, but unlike other methods that only focus on detecting the body of the vertebrae, we also detect the pedicles and associate them with their corresponding body. This allows us to also define the _orientation_ of the vertebra defined by the plane passing through the body and pedicles 1. To this end we introduce a new dataset that includes pedicles for each vertebra, described in Section 4.1, creating a challenging keypoint detection and association task. Footnote 1: Another common way to define the orientation is using the end-plates of the vertebra body; however end-plates can be irregular and ill-defined in pathological cases Our method consists of a two-stage pipeline shown in Figure 1: we detect keypoints from image data using a _CNN stage_, and form a connected graph from these keypoints that is processed by a _GNN stage_ to perform simultaneous node and edge classification, tackling classification, body to pedicle association as well as false positive detection with a single trainable pipeline without heuristics. **CNN stage** The CNN stage detects candidate body, left pedicle and right pedicle keypoints and provides segment classifications for the body keypoints as either cervical, thoracic, lumbar or sacral. We use a UNet2 CNN [19] and select all local maxima with an intensity above a certain threshold \(\tau\), in this paper we use \(\tau=0.5\). These keypoints are connected to their \(k\) nearest neighbours, forming a graph. In rare cases this can result in unconnected cliques, in which case the nearest keypoint of each clique is connected to \(\frac{k}{3}\) nearest points in the other cliques, ensuring a fully connected graph. All nodes and edges are associated with information through embeddings, described below. **GNN stage** The second stage employs a generalized message-passing GNN following [5] to perform several prediction tasks on this graph simultaneously: 1. **keypoint association prediction:** we model association between body keypoints and their corresponding pedicle keypoints as binary edge classification on the over-connected \(k\)-NN graph. 2. **body keypoint level prediction:** for body keypoints, we model the spine level prediction as multi-class node classification. 3. **keypoint legitimacy prediction:** to filter out false-positive keypoints, we additionally compute an binary legitimacy prediction for each node. To perform these task, our message-passing GNN maintains edge and node embeddings which are updated in each layer. A message-passing layer performs a node update and edge update operation. Denoting the feature vector of a node \(v\) by \(x_{v}\), and the feature vector of a directed edge \((u,v)\) by \(x_{uv}\), the node and edge features are updated as follows: \[\underbrace{x_{u}^{\prime}=\bigoplus_{v\in\mathcal{N}_{u}\cup\{u\}}\psi_{ \text{node}}(x_{u},x_{v},x_{uv})}_{\text{Node update}},\qquad\underbrace{x_{uv}^{ \prime}=\psi_{\text{edge}}(x_{u},x_{v},x_{uv})}_{\text{Edge update}} \tag{1}\] Here \(\bigoplus\) denotes a symmetric pooling operation (in our case max pooling) over the neighborhood \(\mathcal{N}_{u}\). \(\psi_{\text{node}}\) and \({}_{\text{edge}}\) are trainable parametric functions: in our case, two distinct two-layer MLPs with ReLU nonlinearities. After \(N\) such message-passing layers we obtain an embedding vector for each node and edge. Each node/edge embedding is passed through a linear layer (distinct for nodes and edges) to obtain a vector of node class logits or a single edge prediction logit, respectively. The last entry in the node prediction vector is interpreted as a node legitimacy prediction score: nodes predicted as illegitimate are discarded for the output. The node input features \(x_{u}\in\mathbb{R}^{7}\) consist of the one-hot encoded keypoint type (body, left or right pedicle) and the segment input information (a pseudo-probability in \([0,1]\) for each of the four spine segments of belonging to that segment, computed by applying a sigmoid to the heatmap network's output channels which represent the different spine segments). The edge input features \(x_{uv}\in\mathbb{R}^{4}\) consist of the normalized direction vector of the edge and the distance between the two endpoints. The output of the GNN contains finer spine-level classification (i.e. C1-C7, T1-T13, L1-L6, S1-S2), keypoint-level legitimacy (legitimate vs. false-positive detection) and body-pedicle association via edge prediction, implicitly defining the orientation of each vertebra. Prediction scores of corresponding directed edges \((u,v)\) and \((v,u)\) are symmetrized by taking the mean. In our experiments we consider variations to our architecture: weight sharing between consecutive GNN layers, multiple heads with a shared backbone (jointly trained) and dedicated networks (separately trained) for edge/node prediction. ## 4 Experiments ### Dataset Our main dataset consists of 2118 scans, of which 1949 form the training dataset, and 169 the validation dataset. This includes 360 scans from the VerSe datasets [24], 1676 scans from the CT Colonography dataset [25] and 82 scans from the CT Pancreas dataset [22]. Of these datasets, only VerSe has labels for spine levels, and none of the datasets have labels for the pedicles of vertebrae. The labeling was done in a two-step process with initial pedicle locations determined through post-processing of ground truth segmentations, then transfered to other datasets via bootstrapping. For each verteb, the verteb level is labeled, including the position of the body and the right and left pedicles. This keypoint dataset is publicly available at [https://github.com/ImFusionGmbH/VID-vertebra-identification-dataset](https://github.com/ImFusionGmbH/VID-vertebra-identification-dataset). Additionally, we also perform the VerSe body classification task on the original VerSe dataset [24] which contains 160 scans in an 80/40/40 split. ### Training Heatmap networkThe heatmap is generated by a UNet\({}^{2}\) network [19], with 4 layers and 32 channels. The network is trained on crops of \(128^{3}\) voxels with 1.5mm spacing. The target data consists of Gaussian blobs (\(\sigma=6\)mm) at the landmark positions. We sample 70% of the crops around landmark locations, and 30% randomly from the volume. Additionally we apply 50% mirror augmentations, and 20 degree rotations around all axes. We use the MADGRAD optimizer [8] with a learning rate of \(10^{-3}\). We use a binary cross-entropy loss, with an 80% weighting towards positive outputs to counter the data's balancing. Graph Neural NetworkThe GNN is implemented in _PyTorch Geometric_2.0.4 [9]. The three predictions of the graph neural network - edge classification, node classification and node legitimacy prediction - are trained via cross-entropy losses which are weighted to obtain the overall loss: \[\mathcal{L}=\alpha\mathcal{L}_{\text{edge}}^{\text{BCE}}+\beta\mathcal{L}_{ \text{node}_{\text{class}}}^{\text{CE}}+\gamma\mathcal{L}_{\text{node}_{ \text{legit}}}^{\text{BCE}} \tag{2}\] Figure 2: Examples of challenging cases for the Hungarian Matching edge detection baseline, and corresponding correct detections by our GNN architecture (red = false positive, blue = false negative detection). We only make edge predictions on edges that run between a body and a pedicle keypoint - the other edges are only used as propagation edges for the GNN. Similarly, we only make spine level predictions on body keypoints. Solely these subsets of nodes/edges go into the respective losses. As input data, we use the predicted keypoints of the heatmap network on the training/validation set. The ground-truth keypoints are associated to this graph to create the target of the GNN. We include three synthetic model spines during training (keypoints in a line spaced 30mm apart) to show the network typical configurations and all potential levels (with all levels/without T13, L6, S2/without T12, T13, L6, S2). We tune various hyperparameters of our method, such as network depth and weight sharing, the \(k\) of the \(k\)-NN graph, the loss weighting parameters \(\alpha,\beta,\gamma\) and the number of hidden channels in the message-passing MLP. We use a short notation for our architectures, such as (5x1, 4, 1) for 5 independent message-passing layers followed by 4 message-passing layers with shared weights and another independent message-passing layer. Various data augmentations are used to make our network more robust to overfitting: (i) rotation of the spine by small random angles, (ii) mirroring along the saggital axis (relabeling left/right pedicles to keep consistency), (iii) perturbation of keypoints by small random distances, (iv) keypoint duplication and displacement by a small distance (to emulate false-positive duplicate detections of the same keypoint), (v) keypoint duplication and displacement by a large distance (to emulate false-positive detections in unrelated parts of the scan) and (vi) random falsification of spine segment input features. We define four levels of augmentation strength (no/light/default/heavy augmentations) and refer to the supplementary material for precise definitions of these levels. ### Evaluation We evaluate our method on two tasks. The first one is the full task consisting of node and edge classification for vertebra level and keypoint association detection. We evaluate this on the 2118 scan dataset which comes with pedicle annotations. The second task consists only of vertebra localization, which we evaluate on the VerSe 2019 dataset [24]. Unless otherwise specified, we use \(k=14\), the (13x1) architecture, batch size 25 and reapparent every 25 epochs for the full task, and \(k=4\), the (9x1) architecture, batch size 1 and reapparent every epoch for the VerSe task. In both cases we use the default augmentation level and \(\alpha=\beta=1\). As evaluation metrics we use the VerSe metrics _identification rate_ (ratio of ground-truth body keypoints for which the closest predicted point is correctly classified and within 20mm) and \(d_{mean}\) (mean distance of correctly identified body keypoints to their 1-NN predictions) [24]. Furthermore we evaluate the edge and illegitimacy binary predictions by their \(F_{1}\) scores. Since the identification rate is largely unaffected by false-positive predicted keypoints, we disable legitimacy predictions unless for specific legitimacy prediction experiments to help comparability. We compare our methods to two baselines: For node prediction, we use a Hidden Markov Model (HMM) [2] that is fitted to the training data using the Baum-Welch algorithm using the _pomegranate_ library [23]. The HMM gets the predicted segment labels in sequence. Dealing with false-positive detection outliers is very difficult for this baseline, therefore we filter out non-legitimate detections for the HMM inputs to get a fairer comparison, making the task slightly easier for the HMM. For the VerSe challenge, we also compare our results to the top papers reported in the VerSe challenge [24]. For edge prediction, we compare our method to Hungarian matching on the keypoints from the CNN pipeline. ### Results The results on our introduced dataset are shown in Table 1. Our method outperforms the baseline methods, both in identification rate and edge accuracy. We also show results on a 'hard' subset, selected as the data samples where either of the methods disagree with the ground truth. This subset contains 47 scans and represents harder cases where the association is not trivial. We give \(p\)-values of the Wilcoxon signed-ranked test against the respective baseline for numbers that are better than the baseline. Figure 2 shows a qualitative example where the baseline method fails due to false-positive and false-negative misdetections in the input (these errors in the input were generated by augmentations and are more extreme than usual, to demonstrate several typical baseline failures in one example). The GNN correctly learns to find the correct association and is not derailed by the misdetections. The examples where our architecture fails typically have off-by-one errors in the output from the CNN: for example, the last thoracic vertebra is detected as a lumbar vertebra (usually in edge cases where the two types are hard to distinguish). Hence the GNN classifications of the lumbar segment, and possibly the thoracic segment, will be off by one (see Figure S2 in the supplementary). Table 2 shows the performance differences of various GNN architectures. The single-head architecture with 13 individual layers performs the best on identi \begin{table} \begin{tabular}{c c|c c c} \hline \hline & Method & identification rate & edge \(F_{1}\) score & \(d_{\text{mean}}\) \\ \hline \multirow{4}{*}{Edge vs. node classification} & Joint node/edge & \(\begin{array}{c}\textbf{97.19}\,/\,\textbf{89.88}\\ (p\,=\,0.080)\end{array}\) & \(\begin{array}{c}\textbf{98.81}\,/\,\textbf{96.22}\\ \end{array}\) & \(\textbf{1.68}\,/\,\textbf{1.95}\) \\ & Node only & \(\begin{array}{c}\textbf{96.91}\,/\,\textbf{88.90}\\ (p\,=\,0.109)\end{array}\) & — & \(\begin{array}{c}\textbf{1.68}\,/\,\textbf{1.96}\\ \end{array}\) \\ & Edge only & — & \(\begin{array}{c}\textbf{99.31}\,/\,\textbf{97.77}\\ (p\,=\,0.019)\end{array}\) & — \\ \hline \multirow{2}{*}{Baselines} & Hidden Markov & \(\begin{array}{c}\textbf{94.29}\,/\,\textbf{79.46}\\ \end{array}\) & — & \(\begin{array}{c}\textbf{1.81}\,/\,\textbf{2.52}\\ \end{array}\) \\ & Hungarian matching & — & \(\begin{array}{c}\textbf{98.93}\,/\,\textbf{96.56}\\ \end{array}\) & — \\ \hline \hline \end{tabular} \end{table} Table 1: Results on the 2118 spine dataset (full validation set / hard subset). Comparing best GNN architectures with the baselines. Wilcoxon signed-rank test \(p\)-values are given for GNN numbers that outperform the baseline (by the test’s construction, \(p\)-values agree between the full and hard subset). fication rate, although the 13-layer architecture with 11 shared layers performs very similarly. The architectures with fewer layers perform slightly better in edge accuracy since this task is less context dependent. Multi-head architectures perform slightly worse on identification, but retain a good edge accuracy. Training a model solely directed to edge classification does yield the highest edge accuracy, as expected. Enabling legitimacy predictions slightly degrades the performance, likely due to two facts: for one, an extra loss term is added, which makes the \begin{table} \begin{tabular}{c c|c c c} \hline \hline \multicolumn{1}{c|}{Method} & identification rate & edge \(F_{1}\) score & illegitimacy \(F_{1}\) \\ \hline \multirow{4}{*}{Single-head architectures} & (7x1) & 96.74 & 98.86 & — \\ & (13x1) & **97.19** & 98.81 & — \\ & (1,5,1) & 96.75 & 98.91 & — \\ & (1,11,1) & 97.10 & 98.67 & — \\ \hline Multi-head architectures: backbone, edge/node head & (1x1), (4x1), (12x1), (10x1) & 96.94 & 99.16 & — \\ & (3x1), (2x1), (10x1) & 96.87 & 99.00 & — \\ & (5x1), (—), (8x1) & 96.79 & 98.88 & — \\ \hline \multirow{4}{*}{Dedicated edge architectures} & (3x1) & — & 99.28 & — \\ & (5x1) & — & 99.28 & — \\ & (1,3,1) & — & **99.35** & — \\ \hline \multirow{4}{*}{With legitimacy prediction: different logit. loss weights} & \(\gamma=0.1\) & 95.61 & **98.96** & 56.00 \\ & \(\gamma=1.0\) & **96.50** & 98.75 & 62.41 \\ & \(\gamma=5.0\) & 96.35 & 98.18 & 61.67 \\ & \(\gamma=10.0\) & 96.42 & 98.96 & **62.78** \\ \hline \multirow{4}{*}{Augmentations} & None & 95.27 & 96.83 & — \\ & Light & 97.18 & **98.83** & — \\ & Default & **97.19** & 98.81 & — \\ & Heavy & 97.03 & 98.67 & — \\ \hline \hline \end{tabular} \end{table} Table 2: Hyperparameter comparisons on the 2118 spine dataset. Comparing GNN architectures, influence of enabling legitimacy predictions and of different augmentation strengths. Best values within each group highlighted in bold. \begin{table} \begin{tabular}{c c|c c} \hline \hline \multicolumn{1}{c|}{Method} & identification rate & \(d_{\text{mean}}\) & illegitimacy \(F_{1}\) \\ \hline Single-head GNN & (9x1) & \(\begin{array}{c}93.26\,/\,93.02\\ (p=3.1e-6/p=5.2e-7)\end{array}\) & \(\begin{array}{c}1.28\,/\,1.43\\ \end{array}\) & — \\ \hline With legitimacy prediction & \(\gamma=10.0\) & \(\begin{array}{c}90.75\,/\,87.51\\ (p=4.8e-6/p=9.4e-7)\end{array}\) & \(\begin{array}{c}\textbf{1.23}\,/\,\textbf{1.32}\\ \end{array}\) & 77.67\(\,/\,81.69\) \\ \hline Baseline & Hidden Markov & \(48.59\,/\,49.06\) & \(1.32\,/\,1.45\) & — \\ \hline \multirow{2}{*}{VerSe challenge entries [24]} & Payer C. [17] & \(95.65\,/\,\textbf{94.25}\) & \(4.27\,/\,4.80\) & — \\ & Lessmann N. [13] & \(89.86\,/\,90.42\) & \(14.12\,/\,7.04\) & — \\ & Chen M. [24] & **96.94**\(\,/\,86.73\) & \(4.43\,/\,7.13\) & — \\ \hline \hline \end{tabular} \end{table} Table 3: Results on the VerSe 2019 dataset (validation/test set). We compare our GNN architecture, our Hidden Markov baseline, and the reported numbers of the three top VerSe challenge entries [24]. Best values highlighted in bold. model harder to train. Also, the identification rate metric is not majorly affected by having additional false-positive detections, hence there is little to be gained in terms of this metric by filtering out false positives. An optimal legitimacy loss weighting seems to be \(\lambda=1.0\). Finally, augmentations help generalization of the model, but the amount of augmentations seems to have little effect. Table 3 shows the result on the traditional VerSe body-identification task. Our method yields a competitive performance despite not being optimized on this task (identification rate slightly lower than the leaders but a better average distance to the landmarks). ## 5 Conclusion We introduced a simple pipeline consisting of a CNN followed by a single GNN to perform complex verteba localization, identification and keypoint association. We introduced a new more complex verteba detection dataset that includes associated pedicles defining the full orientation of each verteba, to test our method. We show that our method can learn to associate and classify correctly with a single GNN that performs simultaneous edge and node classification. The method is fully trainable and avoids most heuristics of other methods. We also show competitive performance on the VerSe body-identification dataset, a dataset the method was not optimized for. We believe this method is general enough to be usable for many other detection and association tasks, which we will explore in the future.
2308.15061
AIoT-Based Drum Transcription Robot using Convolutional Neural Networks
With the development of information technology, robot technology has made great progress in various fields. These new technologies enable robots to be used in industry, agriculture, education and other aspects. In this paper, we propose a drum robot that can automatically complete music transcription in real-time, which is based on AIoT and fog computing technology. Specifically, this drum robot system consists of a cloud node for data storage, edge nodes for real-time computing, and data-oriented execution application nodes. In order to analyze drumming music and realize drum transcription, we further propose a light-weight convolutional neural network model to classify drums, which can be more effectively deployed in terminal devices for fast edge calculations. The experimental results show that the proposed system can achieve more competitive performance and enjoy a variety of smart applications and services.
Yukun Su, Yi Yang
2023-08-29T06:50:04Z
http://arxiv.org/abs/2308.15061v1
# AIoT-Based Drum Transcription Robot using Convolutional Neural Networks ###### Abstract With the development of information technology, robot technology has made great progress in various fields. These new technologies enable robots to be used in industry, agriculture, education and other aspects. In this paper, we propose a drum robot that can automatically complete music transcription in real-time, which is based on AIoT and fog computing technology. Specifically, this drum robot system consists of a cloud node for data storage, edge nodes for real-time computing, and data-oriented execution application nodes. In order to analyze drumming music and realize drum transcription, we further propose a light-weight convolutional neural network model to classify drums, which can be more effectively deployed in terminal devices for fast edge calculations. The experimental results show that the proposed system can achieve more competitive performance and enjoy a variety of smart applications and services. Drum Robot, Transcription, AIoT, Convolutional Neural Network. ## I Introduction The Artificial Intelligence of Things (AIoT) system [1, 2] is a multi-dimensional, complex system that integrates computing, networking, and physical environments. AIoT data is exchanged between different sensors, terminal cloud devices and edge/fog devices, enhancing the professionalism and pertinence of intelligent services through distributed computing design and network architecture. In recent years, with the continuous advancement of human society, robot technology has achieved unprecedented development, and the scope of its application fields is further expanded, which is manifested in the wider range of areas such as traditional industries, manufacturing, people's livelihood and so on. As a component of AIoT, drum robot [3, 4] is a hot topic in recent years, where the core problem is drum transcription. The goal of drum transcription is to generate drum events from audio signals [5]. While this is the first step for full analysis and fetching more music information of drum track, which plays an important role in automated drum education and entertainment systems. In some previous relevant works [3, 6, 7], they are more likely dependent on the preset sequence to play drums, which fail to analyze the online music and are lack of widespread use. In addition, although some approaches propose the algorithms to extract and conduct the music transcription [8, 9, 10], the models they use are usually computational-costly and are hard to deploy in the smart devices like the chips. To this end, it is essential to combine AI [11] and IoT [12, 13] devices to improve the effectiveness and efficiency of drum transcription robot. Among them, AI algorithms can save human resources and improve efficiency, achieving higher accuracy and precision. At the same time, AI helps drumming robots to learn common rules and features of music from humans. The IoT enables objects to be sensed and controlled remotely across existing network infrastructure, including the Internet, thereby creating opportunities for more direct integration of the physical world into the cyber world. The IoT becomes an instance of cyber physical systems with the incorporation of sensors and actuators in IoT devices. Various IoT clusters generate huge amounts of data from diverse locations, which creates the need to process these data more efficiently. In this paper, we introduce an AIoT-based drum transcription drum robot, which consists of a cloud node for data storage, edge nodes for real-time computing, and data-oriented execution application nodes. The cloud stores the required audio sequences and network files which attempts to schedule computationally demanding tasks with low communication requirements due to its abundant computing resources. To meet real-time performance in the real world, we use fog computing method, through which the communication intensive tasks with low computational demands can be processed in the fog at a fast speed without excessive reliance on cloud nodes. In order to employ our drum transcription algorithm into the robot, we further propose a light-weight convolutional neural network for computing. By using the AI chip and embedded board with neural computation acceleration stick, we can deal with some methods in real-time on the fog node and enable the drumming robot to process the tasks of drum extraction and classification. Our main contributions are as follows: 1. We propose an AIot-based drum transcription robot prototype, which consists of a cloud node for data storage, edge nodes for real-time computing, and data-oriented execution application nodes. 2. To meet the demand of real-time computing, we further propose a light-weight convolutional neural network. Compared to the standard convolution operation, we can reduce the network parameters and network complexity. 3. The experimental results show that the proposed system can achieve more competitive performance. ## II Related Work ### _AIoT Computing_ Fog computing and related edge calculations have become a system model for reducing network congestion and latency for fog devices and applications, offloading some of the data originally located in the cloud to fog computers, thus improving real-time performance. The combination of every available resource (Cloud, Clusters, low-cost devices, and Smartphones) can result in a significant decrease in the execution time and expenses [14, 15]. In [16], Stavrinides et al. propose a hybrid approach to scheduling real-time IoT workflows in fog and cloud environments in a three-tiered architecture. Currently, there is no common paradigm for fog computing. However, this idea has led to many domain-specific computing architectures. [17] proposes a framework for a distributed summarization of surveillance videos over the fog network. The network itself is composed of multiple regions combined as clusters of Raspberry Pi. [18] presents a creative IoT agriculture platform for cloud fog computing. The use of multiple Raspberry Pi devices creates a simulated decentralized environment. The platform allows farmland with limited network information resources to be integrated and automated, including agricultural monitoring automation, pest management image analysis, and monitoring. ### _Drum Robot_ Sui [4] proposed an intelligent human interaction robot by using SVM classifier [19]. In [6], Kotosaka presented a network of nonlinear oscillators for their robot system to synchronize with the human drummer. Crick et al. [3] also designed a multi-sensor data fusion method, including visual and auditory data, which enables a robot to drum in synchrony with human performers. In another study, Ince et al. [7] presented a framework for drum stroke detection and recognition by using auditory cues. Based on turn-taking and imitation principles, they designed an interactive drumming game, in which the participants improved their ability to imitate by using the proposed framework. Using a remote server with powerful computing resources to process the machine and learning method and then deploy it back to the robot is the approach taken by most cloud-based computing robots [20, 21] nowadays. However, the audio processing on a remote server takes longer to consume in the transmission of the network than fog computing. ### _Deep Learning Network_ Deep neural networks are widely used in classification [22, 23], detection [24, 25] and segmentation [26, 27] However, deep neural network acceleration is moving toward smaller [28]. Unlike other methods of model compression and acceleration, compact networks can be trained from the scratch without the need for fine-tuning and retraining to achieve convergence. In addition, other methods of model compression can be continued on the basis of lightweight networks, which can be compressed and accelerated at a deeper level. In view of these advantages, various lightweight network architectures are proposed. The increasing need for running high-quality deep neural networks on limited computational devices is the heat trend on efficient model designs [29]. SqueezeNet [30] reduces parameters and computation significantly using 1\(\times\)1 and 3\(\times\)3 convolutional filter concating while maintaining accuracy. Compared to merely increasing the depth and width of the network, GoogLeNet [31] introduces a module with dimension reductions within lower complexity. SENet [32] utilizes the efficient block to achieve impressive performance at a slight computation cost. Group convolution was first introduced in AlexNet [33] for distributing the model over two GPUs. Later it has been well revealed its effectiveness in ResNeXt [34]. As a special kind of group convolution, depthwise separable convolution was initially introduced in [35] and subsequently used in Inception [36, 37]. Currently, MobileNet [38, 39] and ShuffleNet [40, 41] utilizes these convolutional methods and gains state-of-the-art results among lightweight models. ## III Drumming Robot System The proposed AIoT-based drum transcription robot system is shown in Figure 1. The bottom layer of the framework is the device layer, which contains hardware devices such Fig. 1: The overview system of the drum robot. as robots, sensors, and actuators. The middle layer is a fog layer consisting of a distributed embedded board and a neural computing stick as well as an AI chip. These three types of devices form the fog computing platform. We use multiple embedded boards and AI chips as nodes for fog calculation to implement a distributed computing architecture. At the same time, these intelligent embedded boards on the fog side can also provide some computing resources as decision nodes of the system. Embedded boards must have high computational performance and low power consumption, which is responsible for sensor information processing and actuator control. The system uses deep neural network algorithms for drum transcription. Current algorithms consume a lot of computation power. As a result, the we propose a light-weight neural convolutional network that can accelerate deep network reasoning with lower computation power consumption. The top layer of the framework is the cloud side, which consists of large databases that store data such as models and music. ## IV Methodology ### _Audio Extraction_ First, the input audio is converted into a spectrogram using short-time Fourier transform (STFT). The STFT is calculated with librosa [42] using a Hanning window with 2048 samples window size and 512 samples hop length. Then, the spectrogram is computed using a Mel-filter [43] in a frequency range of 20 to 20000 Hz with 128 Mel bands, resulting in a 128 \(\times\)\(n\) power-spectrogram. ### _Overall Architecture_ As shown in Fig 2, the overall architecture of our proposed method takes the converted 2D power-spectrogram audio data as input. Then, we encode the data by leveraging the deep neural learning networks such as CNN [22] or RNN [44]. Note that in our method, we use CNN as our network since the input data is in 2D image form, and the designed light-weight CNN model is more widely used. For comparison, we also depict the RNN in Fig 2. ### _Light-weight Convolution_ A standard convolutional [45] layer takes as input a \(D_{H}\)\(\times\)\(D_{W}\)\(\times\)\(D_{M}\) feature map \(F\) and produces a \(D_{H}\)\(\times\)\(D_{W}\)\(\times\)\(D_{N}\) feature map where \(D_{H}\) and \(D_{W}\) is the spatial height and width of a square input feature map, \(D_{M}\) is the number of input channels (input depth), \(D_{N}\) is the number of output channel (output depth), \(D_{K}\) is the kernel size. Therefore the total computational cost at this layer \(L\) can be given as: \[F_{L_{Standard}}=D_{H}\cdot D_{W}\cdot D_{K}\cdot D_{K}\cdot D_{M}\cdot D_{N} \tag{1}\] Common CNNs adopt a spatially layered architecture. With the spatial dimensions of the next feature map reduced by downsampling, the feature information can be extracted to avoid over-fitting while reducing the amount of calculation. Due to limited computing resources, compact networks are affected by both weak feature representations and limited information capacity. Different downsampling strategies give a compromise between the detailed feature representation of the CNNs and the large information capacity. Slow downsampling strategy performs in later layers of the network, so more layers have large spatial dimensions. Instead, downsampling is performed at the beginning of the network in a fast downsampling strategy, which significantly reduces computational costs. Thus, given a fixed computational budget, slow downsampling strategies tend to generate more detailed features, while fast downsampling strategies can increase the number of channels and allow more information to be encoded. When computing resources are extremely limited, information capacity plays a more important role in network performance. Traditionally, the number of channels can be reduced to accommodate a compact network architecture to some complexity. With a slow Fig. 2: An overview of drum transcription. We first extract the audio and convert it into the power-spectrogram, then the network learns from the 2D image information. Specifically, we here compared two different deep neural networks: CNN and RNN. downsampling scheme, the network becomes too narrow to encode enough information, which results in severe performance degradation. Noticing Eq 1 and it can be clearly seen that the computational cost depends on the kernel size (\(D_{K}\)), the feature map size (\(D_{H}\) and \(D_{W}\)), the input channel \(D_{M}\) and the output channel \(D_{N}\). In general, the size of the filter \(D_{K}\) of the convolutional neural network is 3\(\times\)3, and changing the number of channels of the feature input and output arbitrarily will change the representation ability of the network. Therefore here we take a fast downsampling approach. By downsampling at the previous network's layers, the input feature map size (\(D_{H}\) and \(D_{W}\)) is reduced, which results in a decrease in the amount of calculation. To this end, in this paper, we propose a **Parallel Conv** operation in our network and replace the standard convolution in each layer in the network to reduce the model parameters. As shown in the Fig-3, compared to the traditional standard convolution, which performs convolution using all the input channels with all the 3\(\times\)3 filters, by contrast, the convolution kernels in parallel convolution execute 3\(\times\)3 convolution and 1\(\times\)1 convolution at the same time, which can be regarded as a combination product of 3\(\times\)3 group convolution and 1\(\times\)1 point-wise convolution. Formally, for each input channel, we make it undergo one 1\(\times\)1 and one 3\(\times\)3 and then yield the output channel. The main purpose of 1\(\times\)1 kernel is to apply nonlinearity. After each layer of the neural network, we can apply an activation layer. To increase the number of nonlinear layers without significantly increasing the parameters and computation, we can apply a 1\(\times\)1 kernel and add an activation layer after it, which can help to add more layers of depth to the network. Table I also shows us the network architecture. Fig. 3: Different convolution operation structure diagram. (a) Standard convolution uses all three input channels with all the 3\(\times\)3 filters for operation, which is computational-costly. (b) Our proposed Parallel convolution simply replaces the 3\(\times\)3 filters with one 3\(\times\)3 and one 1\(\times\)1 filters, and then these two filters are responsible for each input channel. More specifically, in the case of parallel convolution with the group size of \(g\), the total computational cost for layer \(L\) can be computed as: \[F_{L_{Parallel}}=D_{H}\cdot D_{W}\cdot D_{K}\cdot D_{K}\cdot\frac{D_{M}}{g} \cdot D_{N}+D_{H}\cdot D_{W}\cdot D_{M}\cdot D_{N} \tag{2}\] Therefore the total reduction (\(R\)) in the computation as compared to the standard convolution: \[\begin{split} R_{Parallel/Standard}&=\frac{F_{L_ {Parallel}}}{F_{L_{Standard}}}\\ &=\frac{1}{g}+\frac{1}{K^{2}}<1\end{split} \tag{3}\] ## V Experiments **Datasets:** For the files of the drums audio, we collected various categories of sounds (Tom, Kick, Snare, Close-Hat, Ride, Crash and Open-hat) in the various open-source databases [46, 47] on the Internet. Then we divided them into the training sets and verification sets. **Performance:** For the comparison of the results, we conducted experiments on the verification set. The experimental results are shown in Table II. The results show that CNN works best. This shows that CNN has been successfully applied not only in image processing but also in many other deep learning tasks. Though CNN has no memory function to process time series, the spectral context allows CNN to access surrounding information in the same way that it processes images during training and classification. In the meantime, CNN can provide translation invariance convolution in time and space, as well as the advantage that pitches invariant kernels can be easily learned by CNN, so convolution can be used to overcome the diversity of audio signal and it is well-equipped to learn an acoustic model task. In this work, the input will be treated as a specific image, then the convolutional layer, max-pooling layer, and drop-out layer finish the task of extracting and learning feature maps. We also compare the performance between the standard CNN and our proposed light-weight CNN. As shown in Table III, our method can achieve competitive performance while reducing a large amount of network parameters and complexity. Furthermore, in the fog computing model, we also conduct a number of experiments comparing the overall speed of the same task between the two computing nodes on the cloud side and the fog side. In the cloud, we use CPU and GPU in the PC separately. On the fog side, we use Raspberry Pi equipped with neural processing unit (NPU) to accelerate the calculation and RK3399pro AI chip which integrated neural network processor NPU. Its computing power can be up to 3.0Tops, compatible with a variety of AI frameworks, and it can be combined with the backplane to form a complete industrial application board. At the same time, we define the number of frames of the input file to be consistent (10 frames), and define T-time as the transmission time, and C-time as the computing time. The comparison results are shown in Table IV. It can be seen that the calculation at the cloud side can achieve the fastest speed on the GPU, but the delay of the network transmission has a negative impact on the total processing time. In the calculation of the fog side, by using the NPU accelerator stick on the Raspberry Pi and the AI chip, their processing speed is no less than that of the CPU on the PC, and they have no delay in the network transmission, and the final total processing speed can reach real-time. The results in Fig 4 show the processing time of tasks with different input frames on different computing devices at different fog nodes. All the above results show that computing in the fog node is better than the other two methods, and the real-time processing effect can be achieved. ## VI Conclusion In this paper, we present a novel drum transcription robot using fog computing, which consists of a cloud node for data storage, edge nodes for computing, and data-oriented execution application nodes. To further meet the demands of real-time computing, we propose a light-weight convolutional Fig. 4: Histogram of performance with different input frames. neural network to reduce the network parameters and complexity. In our future work, more resources on smartphone and other mobile devices will be more considered and utilized, and the algorithms for audio processing needs to be further improved.
2305.16594
A Hybrid Neural Coding Approach for Pattern Recognition with Spiking Neural Networks
Recently, brain-inspired spiking neural networks (SNNs) have demonstrated promising capabilities in solving pattern recognition tasks. However, these SNNs are grounded on homogeneous neurons that utilize a uniform neural coding for information representation. Given that each neural coding scheme possesses its own merits and drawbacks, these SNNs encounter challenges in achieving optimal performance such as accuracy, response time, efficiency, and robustness, all of which are crucial for practical applications. In this study, we argue that SNN architectures should be holistically designed to incorporate heterogeneous coding schemes. As an initial exploration in this direction, we propose a hybrid neural coding and learning framework, which encompasses a neural coding zoo with diverse neural coding schemes discovered in neuroscience. Additionally, it incorporates a flexible neural coding assignment strategy to accommodate task-specific requirements, along with novel layer-wise learning methods to effectively implement hybrid coding SNNs. We demonstrate the superiority of the proposed framework on image classification and sound localization tasks. Specifically, the proposed hybrid coding SNNs achieve comparable accuracy to state-of-the-art SNNs, while exhibiting significantly reduced inference latency and energy consumption, as well as high noise robustness. This study yields valuable insights into hybrid neural coding designs, paving the way for developing high-performance neuromorphic systems.
Xinyi Chen, Qu Yang, Jibin Wu, Haizhou Li, Kay Chen Tan
2023-05-26T02:52:12Z
http://arxiv.org/abs/2305.16594v2
# A Hybrid Neural Coding Approach for Pattern Recognition with Spiking Neural Networks ###### Abstract The biological neural systems evolved to adapt to ecological environment for efficiency and effectiveness, wherein neurons with heterogeneous structures and rich dynamics are optimized to accomplish complex cognitive tasks. Most of the current research of biologically inspired spiking neural networks (SNNs) are, however, grounded on a homogeneous neural coding scheme, which limits their overall performance in terms of accuracy, latency, efficiency, and robustness, etc. In this work, we argue that one should holistically design the network architecture to incorporate diverse neuronal functions and neural coding schemes for best performance. As an early attempt in this research direction, we put forward a hybrid neural coding framework that integrates multiple neural coding schemes discovered in neuroscience. We demonstrate that the proposed hybrid coding scheme achieves a comparable accuracy with the state-of-the-art SNNs with homogeneous neural coding on CIFAR-10, CIFAR-100, and Tiny-ImageNet datasets with less than eight time steps and at least \(3.90\times\) fewer computations. Furthermore, we demonstrate accurate, rapid, and robust sound source localization on SoClas dataset. This study yields valuable insights into the performance of various hybrid neural coding designs and hold significant implications for designing high performance SNNs. Spiking Neural Network, Neuromorphic Computing, Hybrid Coding Framework, Layer-wise Learning, Neural Coding. ## 1 Introduction Human brains are the most sophisticated yet energy-efficient computational system. Spiking neural networks (SNNs), with rich neuronal dynamics and sparse spiking activities, are designed to mimic the remarkable information processing mechanism of biological neural systems _in silico_. The higher degree of biological details encompassed endows these artificial neural systems with a greater potential to reach the unprecedented accuracy, efficiency, and robustness of their biological counterparts. However, the state-of-the-art (SOTA) SNNs used in pattern recognition are primarily bootstrapped from homogeneous neurons and uniform network structures, and rely on extended learning with large-scale datasets to reach high performance. The findings in biological neural systems prompt us to look into diversified neural coding schemes and network structures in neural computation. Over the last few decades, growing biological evidence indicates that perception and cognition are supported by diversified neural codes, which are believed to play an essential role in signal processing, learning, and memory in neural systems [1]. The earliest research on neural coding can be traced back to 1926 when Adrian and Zotterman first revealed that sensory nerves innervating the muscle discharge action potentials at a rate that is correlated with the weights hung from the muscle [2]. Since then, substantial evidence was accumulated from different neural systems and led to the conclusion that the firing rate of neurons is the key information carrier. However, the rate coding failed to describe many important features of neural computation. Temporal coding schemes have been proposed as a complementary approach to explain the limitations of rate coding. For example, in the human visual system, object recognition can be accomplished within 150 ms since the stimulus onset [3], during which signals need to travel across multiple interconnected stages. The rank order coding has been proposed to account for how rapid information processing occurs in the visual system, which suggests the sensory information is represented as the chronological order of single spikes and more important features will be conveyed earlier [4]. Additionally, the spiking activities are found to be phase-correlated with the ongoing neural oscillations during memory formulation in the hippocampus [5]. Motivated by this, phase coding is introduced to explain how temporally correlated information has been stored and retrieved reliably in the memory system [6]. Moreover, as observed in the thalamus, hippocampus, and auditory systems, neurons are capable of firing a burst of spikes with a small inter-spike interval for rapid information transmission, which has led to the development of burst coding [7]. The large body of research on neural coding has provided a wealth of inspiration for the SNN design. Nevertheless, most of the existing SNNs are still grounded on a single, homogeneous neural coding schemes and rely on extensive learning to achieve task-related objectives. However, this design methodology typically leads to sub-optimal performance for the targeted tasks. For instance, direct coding uses the real value for the input or output layer, which is the least biological plausible scheme and identical to the coding scheme used in ANNs. The majority of research on ANN-to-SNN conversion uses the rate coding and approximate the output of the ReLU activation function with the firing rate of spiking neurons [8, 9, 10, 11, 12]. As a more reliable coding scheme, burst coding encodes information into the inter-spike interval (ISI) and allows a burst of spikes to be transmitted within a short time interval for robust information transmission [13]. Despite superior performance, implementing burst coding comes at a high computational cost. Some recent studies are looking at more efficient coding schemes. Phase coding, for example, embed information into the spike-phase based neural oscillations, which remarkably reduces the spike density [14]. However, the primitive phase coding is hard to represent a highly dynamical information stream. The time-to-first-spike (TTFS) coding, on the other hand, encodes information via the first spike time [15, 16, 17]. However, these TTFS-based SNNs face gradient instability and dead neuron problems during training [16], which limits the scale of networks. In this paper, we argue that SNNs should be designed with multiple neural coding schemes to achieve optimal performance. To this end, we propose a hybrid coding and learning framework. As illustrated in Fig. 1, the proposed framework incorporates a neural coding zoo formed by a collection of bio-inspired neural coding schemes. According to the task requirements, the neural coding scheme is assigned for each network layer that provides the desired information representation basis. Moreover, we introduce a layer-wise learning method to ensure the desired neural representation can be achieved efficiently at each network layer with high levels of efficacy. We verify the effectiveness of the proposed framework on both image and audio perception tasks, and demonstrate desired attributes of high accuracy and robustness, as well as low latency and energy consumption. The main contributions of this paper are summarized as follows: * We present a novel hybrid neural coding framework, which takes a holistic approach to designing the neural coding schemes of a SNN based on specific task requirements and environmental conditions. * We propose a layer-wise learning method that can efficiently achieve the desired neural coding schemes with high levels of efficacy. * We showcase the superiority and versatility of the proposed hybrid neural coding framework in performing image classification and sound localization tasks. * Our research yields valuable insights into the performance of various hybrid neural coding designs and hold significant implications for designing optimal hybrid coding SNNs. The remainder of this paper is organized as follows. In Section II, we present the proposed hybrid coding framework in detail. In Sections III and IV, we evaluate the performance of the proposed hybrid coding framework on image classification and sound localization tasks, respectively. Additionally, we conduct a series of ablation studies in Section IV to compare different hybrid coding designs. Finally, we conclude our findings in Section V. ## 2 A Hybrid Neural Coding Framework for Spiking Neural Networks In this section, we will present our proposed hybrid neural coding framework that provides a holistic network representation basis design. As illustrated in Fig. 1, our framework consists of three key components: neural coding Fig. 1: Illustration of the proposed hybrid neural coding framework for image classification task. According to the task requirements and environmental conditions, heterogeneous neural coding schemes are selected from the neural coding zoo and assigned to the Input, Hidden, and Output Layer. A layer-wise learning method is introduced to achieve the desired hybrid neural codes, where \(y^{L}\) represents the predicted outputs of the hybrid coding SNN, \(y^{label}\) denotes the one-hot labels, \(\hat{y}^{l}\) is the hidden states of the teacher ANN layer \(l\). zoo, hybrid coding assignment strategy, and hybrid learning method. Firstly, we will provide a brief introduction of SNNs and then describe the collection of bio-inspired neural coding schemes that form our neural coding zoo. Secondly, we will introduce our proposed hybrid coding assignment strategy, with a focus on practical design for image classification and sound localization tasks. Finally, we will introduce a layer-wise learning method that can efficiently train hybrid coding SNNs. ### _Neural Coding Zoo_ Spiking neurons, unlike traditional artificial neurons, simulate the rich dynamic behaviors of biological neurons. Electrical impulses, or spikes, act as information carriers to transmit information between neurons. Spiking neurons generally transform input spike trains into their internal neuronal states and subsequently produce output spike trains according to specified neuronal functions. The frequency, precise spike timing, or synchrony patterns of spike trains could all be utilized to represent information, and the appropriate assignment of neural coding schemes could significantly impact the information processing efficiency, efficacy, and robustness of a SNN. Inspired by the rich biological neural representation discovered in neuroscience, various neural coding schemes, with different merits and weaknesses, have been studied for SNNs. The neural coding zoo is a comprehensive collection of the most representative neural coding schemes, which provides a wealth of candidate options for designing hybrid coding SNNs. We selected direct coding, rate coding, phase coding, burst coding, and TTFS coding for our neural coding zoo to enable the construction of flexible and versatile SNNs that can be customized to meet specific task requirements and environmental conditions. In the following, we provide a summary of each selected neural code, with their merits and weaknesses depicted in Fig. 2. It is worth noting that our neural coding zoo can easily include other newly discovered or developed neural codes. * **Direct coding** has been widely used in SNN input and output layers, which directly employs analog values to encode input stimuli or to decode outputs [18, 19]. Given its analog nature, it is the least biologically plausible and energy efficient neural code, as it abandons the binary spike-based information representation. Nevertheless, direct coding could avoid sampling errors and delays in other coding schemes as well as provide convenience for output decoding. * **Rate coding** utilizes the mean firing rate within the given time window to represent the signal amplitude. Due to the similarity between ReLU activation values and firing rates of spiking neurons, rate coding has been widely adopted in ANN-to-SNN conversion methods [8, 9, 10, 11, 12] to construct SNNs that can well approximate the ReLU activation values. While rate coding is biologically plausible and can provide superior information representation capability, it is often criticized for high latency, poor energy efficiency, and being ineffective in representing fast-changing signals. * **Phase coding** represents information by the phase of spiking activities with respect to the underlying neural oscillations [20]. It is proven to be more efficient in information transmission than rate coding and offers higher noise robustness than TTFS coding [21]. However, the representation capacity of phase coding is constrained by the frequency of underlying neural oscillations, which reduces performance when representing rapidly changing stimuli [14, 22]. * **Burst coding** makes effective use of the ISI to represent information [23] and is highly efficient in information transmission [24]. However, to keep track of the ISI has a high computational complexity. To address this issue, recent works propose using the neuron model that can emit multiple spikes within a single time step to represent graded ISIs [25, 13], resulting in a simple yet robust neural coding scheme. * **TTFS coding** represents information using the timing of the first spike, where earlier spikes encode more significant information. TTFS coding leads to the favorable properties of fast inference, low spike density, and low energy consumption [26, 27]. However, the TTFS coding suffers from the notorious dead neuron problem that affects the training stability. Furthermore, spike timing is highly sensitive to the neuronal noise, which is pervasive in neural systems and analog computing substrates. ### _Hybrid Coding Assignment Strategy_ As discussed earlier, each homogeneous neural coding scheme has its own unique merits and weaknesses, and if applied alone, it will significantly impact the overall performance of SNNs. Inspired by the rich and hybrid Fig. 2: Comparison of computational performance and biological plausibility among different candidate neural coding schemes. neural codes observed in biological neural systems, we propose constructing hybrid coding SNNs with heterogeneous neural coding schemes. This can be achieved by selecting the neural coding schemes from the neural coding zoo and assign them to different parts of the network according to varying task requirements and environmental conditions. However, this will lead to a complex combinatory optimization problem that is intractable for large-scale networks. To reduce the design effort and accelerate training, we organize the network layers into three blocks and adopt a homogeneous neural coding scheme throughout each block. Specifically, three network blocks are considered in this work that correspond to the Input Layer, Hidden Layers, and Output Layer. In the following, we describe the key considerations when assigning neural coding schemes to these network blocks. * **Input Layer** plays a significant role as the interface between the SNN and its external environment. It is imperative that this layer provides an efficient, real-time, and high-fidelity representation of the input stimuli. Therefore, to achieve these objectives, the input coding scheme must be chosen based on the nature of the input and the prevailing environmental conditions. This ensures a fast response while minimizing information loss during sampling and encoding. * **Hidden Layers** play a crucial role in extracting rich and hierarchical feature representations from the input stimuli. Consequently, it is imperative that the chosen neural codes not only facilitate efficient feature extraction but also exhibit a degree of resource parsimony and robustness to neuronal noise. * **Output Layer** functions as the output interface for for generating decisions and action, underscoring the need for a neural coding scheme that is both effective in facilitating accurate decision-making and swift in producing responses. It is noteworthy that the proposed hybrid coding assignment strategy has the potential to provide guidance in the construction of a diverse range of models aimed at addressing various pattern recognition tasks, as well as designing task-specific models based on distinct objectives. To illustrate the efficacy of this approach in integrating the strengths of different coding schemes, we will use image classification and sound localization tasks as examples in the subsequent discussion. ### _Hybrid Coding Design for Image Classification_ #### 2.3.1 Direct Coding for High-Fidelity Input Representation For image classification tasks, a high-fidelity representation of input images is typically required. However, rate coding may require a large sampling time window with high firing rates, leading to slow and inefficient during runtime. On the other hand, temporal coding schemes (e.g., TTFS coding) may suffer from dead neuron and gradient instability issues, negatively impacting the ease of training [16]. To address these challenges, we adopt a direct coding scheme that treats the intensity value of image pixels as the input current and directly injects it into post-synaptic neurons in the hidden layers [18, 19]. This approach bypasses the analog-to-spike conversion process required in other neural encoding schemes, eliminating the information loss during rate-based sampling as well as the quantization errors during temporal encoding. #### 2.3.2 Burst Coding for Reliable and Rapid Hidden Feature Representation In this task, we utilize burst coding to ensure rapid and efficient transfer of spike-based feature representation to subsequent layers. Unlike rate coding, which restricts neurons to emit at most one spike at a time, the bursting neurons can generate up to \(\Gamma\) spikes. This enables faster transmission of important information with greater robustness. In this work, \(\Gamma\) is set to five following the discovery that biological neurons rarely emit a spike burst with more than five spikes [28]. Specially, we use the bursting neuron model introduced in [25], which is defined as: \[\mathbf{m}^{l}(t)=\mathbf{v}^{l}(t-1)+\mathbf{W}^{l}\mathbf{x}^{l-1}(t), \tag{1}\] where \(\mathbf{x}^{l-1}(t)\) is the input current from layer \(l-1\). \(\mathbf{m}^{l}(t)\) and \(\mathbf{v}^{l}(t)\) are the membrane potential before and after spike generation, respectively. \(\mathbf{W}^{l}\) represents the weight matrix of layer \(l\). Once the membrane potential exceeds the firing threshold \(V_{th}^{l}\), an output spike is generated, and the membrane potential is reset to the resting potential using the reset-by-subtraction scheme [29]. This approach ensures that no information is lost during the resetting process. Mathematically, the spike generation process of bursting neurons can be expressed as: \[\mathbf{s}^{l}(t) =\min\left(\max\left(\lfloor\frac{\mathbf{m}^{l}(t)}{V_{th}^{l}} \rfloor,0\right),\Gamma\right), \tag{2}\] \[\mathbf{v}^{l}(t) =\mathbf{m}^{l}(t)-\mathbf{s}^{l}(t)V_{th}^{l},\] where \(\mathbf{s}^{l}(t)\) is an integer-valued vector that taken values from range \([0,\Gamma]\). For each input spike burst, it is transduced into the post-synaptic current as per: \[\mathbf{x}^{l}(t)=\mathbf{s}^{l}(t)V_{th}^{l}. \tag{3}\] #### 2.3.3 TTFS Coding for Fast and Efficient Output Decision-making Ideally, the classification decision could be made as soon as sufficient evidence has been accumulated at the output layer \(L\). To achieve this objective, we adopt the TTFS decoding that reaches a decision once the first output spike has been detected, without waiting for all simulation time steps to finish. It thus leads to a significant reduction in inference time. Specifically, we adopt the leaky integrate-and-fire (LIF) neuron model [30] for the output layer, which offers richer temporal dynamics than the bursting neuron model used in hidden layers. The membrane potential of LIF neurons is defined as: \[\mathbf{v}^{L}(t)=\mathbf{W}^{L}K^{L}\left(t\right), \tag{4}\] where \(K^{L}(t)\) is the post-synaptic potential (PSP) kernel, which is induced from pre-synaptic spikes and iterated as follows: \[\begin{split} K^{L}(t)&=K_{0}(\mathbf{m}^{L}(t)-\mathbf{I}^{L} (t)),\\ \mathbf{m}^{L}(t)&=\exp(-\frac{1}{\tau_{m}})\cdot(\mathbf{m} ^{L}(t-1)+s^{L-1}(t)),\\ \mathbf{I}^{L}(t)&=\exp(-\frac{1}{\tau_{s}})\cdot(\mathbf{I} ^{L}(t-1)+s^{L-1}(t)),\end{split} \tag{5}\] where \(K_{0}\) is a normalization constant that ensures the maximum value of PSP kernel is equal to \(V_{th}^{L}\). \(\tau_{m}\) and \(\tau_{s}\) are the integration time constant of the membrane potential and the decay time constant of synaptic currents, respectively. The \(i^{th}\) output neuron fires when \(\mathbf{v}_{i}^{L}(t)\) crosses the set firing threshold \(V_{th}^{L}\). For classification problems with \(n\) classes, we treat the label \(i\) of the neuron that generates the first output spike as the classification result. Moreover, if multiple neurons fire at the same time, the result is defined as: \[y^{L}=\max_{i}(\mathbf{v}_{i}^{L}(t_{f})). \tag{6}\] Finally, in cases where no neuron fires until the end of the time window, we treat the last time step as the decision time and determine the classification result according to Eq. (6). ### _Hybrid Coding Design for Sound Localization_ #### 2.4.1 Phase Coding for High-fidelity Input Representation Mammalian auditory systems possess a remarkable capability to localize the sound source from the time difference of arrival (TDOA) between their sensory receptors (i.e., ears) [31]. To be specific, the sound propagates through the air and reaches two ears with different time delays and energy attenuation. The peripheral auditory system first encodes the sound source into phase-locked spikes at each unilateral cochlea. Subsequently, the spike timing difference between bilateral cochleas is detected by the coincidence detection neurons in the medial superior olive (MSO), providing the important cue for localizing the sound source [32]. Considering the temporal characteristics of the sound localization task and the biological information transformation process described above, phase coding is an ideal candidate for extracting and encoding the localization cues. In particular, we adopted the Multi-Tone Phase Coding (MTPC) [33] for high-fidelity input representation in our model. As described in Fig. 3, MTPC first decomposes the received audio into single tone sinusoidal signals, with the first-peak of each single tone sinusoidal signal being encoded as a spike that represent the arrival time of the sound. Furthermore, the coincidence detection neurons detect the time delay between two microphones, triggering an output spike if a particular time delay is detected. Finally, the output spikes generated from sub-bands are aggregated based on the center frequency and bandwidth of Constant Q Transform (CQT). #### 2.4.2 Burst Coding for Robust Hidden Feature Representation In sound localization task, rapid information transmission and robust information representation are two desirable attributes when selecting a neural code for hidden layers. On the one hand, mammals need to respond rapidly to avoid moving predators or catch preys. On the other hand, phase-encoded inputs are sensitive to pervasive neuronal noises. To address these challenges, we select burst coding for hidden layers, as it demonstrate superior performance in these two aspects as shown in Fig. 2. #### 2.4.3 TTFS Coding for Fast and Efficient Output Decision-Making In addition to high localization accuracy, fast response to the moving sound source and high energy efficiency are crucial aspects of any auditory interface. These factors motivated our choice of TTFS coding for the output layer of the localization network. In Section 3.2, we will illustrate how TTFS decoding effectively reduces inference time without compromising the localization accuracy. Furthermore, in Section 4.2, we will compare TTFS coding with other coding schemes to validate its superiority in the context of sound localization tasks. Fig. 3: Illustration of the neural encoding front-end designed for the sound localization task. a) The received audio is decomposed into \(n\) single tone sinusoidal signals by Fast Fourier Transform (FFT); b) The first-peak of each sinusoidal signal is encoded into a single spike to represent the arrival time of the sound; c) The coincidence detection network with \(N_{\tau}\) neurons is applied to detect the phase difference between two microphones. An output spike is trigger if a particular time delay is detected; d) The outputs of \(n\) single tones are grouped into \(N_{c}\) channels, following the Constant Q Transform (CQT), to reduce the computational cost of post-processing. ### _A Layer-wise Learning Method for Hybrid Coding_ The utilization of hybrid neural coding across various network stages renders the conventional end-to-end direct training approach unsuitable. To address this issue, we propose a novel layer-wise training method for the hidden and output layers, aimed at achieving the desired neural codes. #### 2.5.1 Hidden Layer We adopt the Teacher-Student learning approach that was initially introduced for training rate-based SNNs [34] and extend this training method to support other neural coding schemes. Specifically, our layer-wise learning method leverages a pre-trained ANN to supervise the training of a student SNN. We consider the intermediate feature representations of the ANN as the target and train the SNN to generate equivalent spike-count-based feature representations. For this purpose, we use mean square error (MSE) as the local loss function for each hidden layer, which is defined as: \[\mathcal{L}^{l}\left(\hat{y}^{l},c^{l}(T)\right)=\left|\left|\hat{y}^{l}-r^{l} \cdot\frac{c^{l}(T)}{T}\right|\right|_{2}^{2}, \tag{7}\] where \(\hat{y}^{l}\) denotes the activation of ANN layer \(l\). \(T\) is the simulation time window and \(c^{l}(T)=\sum_{t=1}^{T}s^{l}(t)\) is the total spike count. \(r^{l}\) is a layer-wise scaling factor that ensures the firing rate of spiking neurons (i.e., \(c^{l}(T)/T\)) matches the activation value of ANN neurons [10]. To eliminate the mismatch between training and testing, we train each hidden layer by taking into consideration the temporal dynamics of input spike trains rather than only considering the mean firing rate as in [10]. Specifically, we employ the backpropagation through time (BPTT) algorithm to perform temporal credit assignments at each layer. The weight gradients can be derived as follows: \[\begin{split}\frac{\partial\mathcal{L}^{l}}{\partial w_{ij}^{l}}& =\sum_{t=1}^{T}\frac{\partial\mathcal{L}^{l}}{\partial m_{i}^{l}( t)}\frac{\partial m_{i}^{l}(t)}{\partial w_{ij}^{l}}\\ &=\sum_{t=1}^{T}\frac{\partial\mathcal{L}^{l}}{\partial m_{i}^{l} (t)}x_{j}^{l-1}(t),\end{split} \tag{8}\] For the ease of expression, we let \(\delta_{i}^{l}(t)=\frac{\partial\mathcal{L}^{l}}{\partial s_{i}^{l}(t)}\) and yield \[\frac{\partial\mathcal{L}^{l}}{\partial m_{i}^{l}(t)}=\begin{cases}\delta_{i}^ {l}(t+1)\frac{\partial s_{i}^{l}(t+1)}{\partial m_{i}^{l}(t+1)}+\delta_{i}^{l} (t)\frac{\partial s_{i}^{l}(t)}{\partial m_{i}^{l}(t)},&\text{ if }t<T,\\ \delta_{i}^{l}(T)\frac{\partial s_{i}^{l}(T)}{\partial m_{i}^{l}(T)},&\text{ if }t=T,\end{cases} \tag{9}\] where \[\delta_{i}^{l}(t)=\begin{cases}-V_{th}^{l}\delta_{i}^{l}(t+1)\frac{\partial s_ {i}^{l}(t+1)}{\partial m_{i}^{l}(t+1)}+\delta_{i}^{l}(T),&\text{ if }t<T,\\ -\frac{2}{T}\left(\hat{y}_{i}^{l}-r^{l}(\frac{1}{T}\Sigma_{t=1}^{T}s_{i}^{l}(t) )\right),&\text{ if }t=T.\end{cases} \tag{10}\] For burst neurons, we adopt the straight-through estimator [35] (i.e., \(d\lfloor x\rfloor/dx=1\)) to address the discontinuity in Eq. (2) and result in \[\frac{\partial s_{i}^{l}(t)}{\partial m_{i}^{l}(t)}=1. \tag{11}\] We refer to this local learning method as local tandem learning (LTL) from here onwards. #### 2.5.2 Output Layer In order to achieve fast and yet accurate decision-making, the output layer is trained to make correct classification decisions based on the first output spike, which is referred to as TTFS learning hereafter. The TTFS learning is accomplished by carefully balancing two learning objectives. On the one hand, the weights of the target neuron should be adjusted to fire as early as possible. On the other hand, all the other neurons should fire later than the target one. These two learning objectives are achieved by adjusting the weights of output layer according to the following two loss functions, while all other hidden layer weights remain fixed. To achieve the first objective, we select the cross-entropy (CE) loss as the first loss function, which can advance the first spike time of the target neuron by forcing the membrane potential to increase at that time. This learning process can be described by the following equation: \[\mathcal{L}_{1}(y_{i},p_{i})=-\sum_{i=1}^{n}y_{i}^{label}\ln p_{i}, \tag{12}\] where \(p_{i}=exp(\mathbf{v}_{i}^{L}(t_{f}))/\sum_{i=1}^{n}exp(\mathbf{v}_{i}^{L}(t_{f}))\) and \(y_{i}^{label}\) is the one-hot encoded target vector. Considering the fixed firing threshold and growing postsynaptic membrane potential resulted from minimizing \(\mathcal{L}_{1}\), the decision time will continuously decrease until every decision is made at the earliest possible time step. This may, however, lead to the overfitting problem as the available input information is inadequately exploited.To address this issue, we introduce another loss function, \(\mathcal{L}_{2}\), which delays incorrect decisions to balance classification accuracy and decision speed. Specifically, long-term depression (LTD) is triggered when any other neuron fires earlier than the target one: \[\mathcal{L}_{2}=\theta(t_{f})\cdot(\mathbf{v}^{L}(t_{f})-V_{th}^{L}), \tag{13}\] where \(\theta(t_{f})\) is a scaling factor of LTD that is defined as: \[\theta(t_{f})=max\left(1-\frac{acc(t_{f})}{acc(T)},0\right), \tag{14}\] where \(acc(t_{f})\) and \(acc(T)\) correspond to the test accuracy at the first spike time and the last time step, respectively, whose value is updated at the end of each training epoch. For incorrect decisions chadie too early, the firing time will be delayed to later time steps depending on whether the accuracy can be improved if the decision is made later, that is \(\theta(t_{f})>0\). The combination of the above two loss functions ensures those easy decisions can be made earlywhile difficult decisions are postponed to later and more informative time steps. The weight gradients can be derived as follows: \[\frac{\partial\mathcal{L}}{\partial w^{L}}=\frac{\partial\mathcal{L}}{\partial \mathbf{v}^{L}(t_{f})}K^{L}(t_{f}). \tag{15}\] where the total loss \(\mathcal{L}=\alpha\mathcal{L}_{1}+\beta\mathcal{L}_{2}\) is tuned by two hyperparameters \(\alpha\) and \(\beta\). The network parameters of hidden and output layers can be updated according to the stochastic gradients decent or their adaptive variants. ## 3 Accurate and Rapid Image classification with Hybrid coding In image classification tasks, classification accuracy and inference speed serve as the two primary performance indicators. In this section, we compare the image classification accuracy and the required inference time of the proposed hybrid coding approach to other SOTA SNN implementations on CIFAR-10 [42], CIFAR-100 [42], and Tiny-ImageNet [43] datasets. For all datasets, we utilize VGG-16 [44] and ResNet-20 [45] network structures. Subsequently, we validate the effectiveness and training speed of our proposed layer-wise learning method. Lastly, we demonstrate that the proposed hybrid coding approach can achieve SOTA classification accuracy while significantly reducing the computational cost. For simplicity, direct, rate, burst, phase, and TTFS coding schemes are denoted as D, R, B, P, and T hereafter. ### _Superior Image Classification Performance_ In Tab. I, we report our results and compare them against other SOTA SNN models. To ensure a fair comparison, we select competitive SNN benchmarks based on their conversion errors for network conversion methods and classification accuracy for direct training methods. Overall, as the inference curves illustrated in Fig. 4(a) and 4(b), the proposed hybrid coding approach attains competitive classification accuracy while significantly reducing inference time across all model architectures and datasets. For CIFAR-10 dataset, our VGG-16 model requires only \(5.21\) time steps on average to reach \(95.67\%\) classification Fig. 4: Test accuracy as a function of inference time. The experiments are conducted on CIFAR-10, CIFAR-100, and Tiny ImageNet dataset with VGG-16 (a,c,e) and ResNet-20 (b,d,f). Note that for the proposed hybrid coding approach, we only report the average latency as the decision is made as soon as the first output spike is generated. accuracy. Whereas the QCFS [9], considered the best among all ANN-to-SNN conversion methods, can only achieve a comparable accuracy with \(16\) time steps. Similar conclusions can be drawn from the converted ResNet-20 models. Furthermore, our ResNet-20 model outperforms other direct trained models, such as STBP-tdBN [39] and TET [40]. For the more challenging CIFAR-100 dataset, our model reaches a satisfactory accuracy of \(75.75\%\) and \(75.39\%\) using average inference time steps of \(6.88\) and \(3.94\) for VGG-16 and ResNet-20, respectively. As presented in Fig. 4(c) and 4(d), although the classification accuracy of our models is slightly worse than Calibration [10], Burst+LIPooling [25], and QCFS models, it is worth noting that their results are achieved with at least 16 time steps. Consequently, our models are more favorable in terms of inference time and energy consumption. Additionally, we evaluate our method on a large-scale Tiny-ImageNet dataset. Due to a lack of benchmarks on this dataset, we reproduce the results for Calibration, Burst+LIPooling, and QCFS methods using their publicly available codes. As the results are shown in Fig. 4(e) and 4(f) as well as Tab. 1, it is obvious that our proposed models are capable of achieving superior results with a shorter inference time. To elucidate how early decision-making is accomplished with the proposed hybrid coding framework, we display the distribution of decision time for D+B+T and D+R+T models in Fig. 5. It is evident that the first spike time is densely distributed around 4 and 8 for D+B+T and D+R+T models, respectively. This result indicates that burst coding facilitates faster information transmission across hidden layers, which forms the basis for early decision-making by the TTFS classifier. Additionally, it is noteworthy that decisions made \begin{table} \begin{tabular}{l l l c c c c} \hline \hline **Dataset** & **Method** & **Architecture** & **ANN Acc. (\%)** & **SNN Acc. (\%)** & \(\Delta\)**Acc. (\%)** & **Avg. Inference Time** \\ \hline \hline \multirow{8}{*}{CIFAR-10} & Burst Spikes [13] & VGG-16 & 91.41 & 91.41 & 0 & 793 \\ & RMP [36] & VGG-16 & 93.63 & 93.04 & -0.59 & 256 \\ & TSC [37] & VGG-16 & 93.63 & 93.27 & -0.36 & 128 \\ & Calibration [10] & VGG-16 & 95.72 & 95.14 & -0.58 & 64 \\ & Burst+LIPooling [25] & VGG-16 & 95.74 & 95.58 & -0.16 & 32 \\ & QCFS [9] & VGG-16 & 95.52 & 95.40 & -0.12 & 16 \\ & Diet-SNN [38] & VGG-16 & 93.72 & 93.44 & -0.28 & 10 \\ & **Ours (Hybrid Coding)** & **VGG-16** & **95.84** & **95.67** & **-0.17** & **5.21** \\ & RMP [36] & ResNet-20 & 91.47 & 91.36 & -0.11 & 2048 \\ & TSC [37] & ResNet-20 & 91.47 & 91.42 & -0.05 & 2048 \\ & Calibration [10] & ResNet-20 & 95.46 & 94.78 & -0.68 & 32 \\ & Burst+LIPooling [25] & ResNet-20 & 96.56 & 96.11 & -0.45 & 32 \\ & QCFS [9] & ResNet-20 & 91.77 & 91.62 & -0.15 & 16 \\ & Diet-SNN [38] & ResNet-20 & 92.79 & 92.54 & - & 10 \\ & STBP-tdBN [39] & ResNet-19* & - & 93.16 & - & 6 \\ & TET [40] & ResNet-19* & - & 94.50 & - & 6 \\ & **Ours (Hybrid Coding)** & **ResNet-20** & **95.45** & **95.24** & **-0.21** & **5.04** \\ \hline \multirow{8}{*}{CIFAR-100} & Burst Spikes [13] & VGG-16 & 68.77 & 68.69 & -0.08 & 3000 \\ & RMP [36] & VGG-16 & 71.22 & 70.93 & -0.29 & 2048 \\ & TSC [37] & VGG-16 & 71.22 & 70.97 & -0.25 & 2048 \\ & Calibration [10] & VGG-16 & 77.89 & 76.64 & -1.25 & 64 \\ & Burst+LIPooling [25] & VGG-16 & 78.49 & 78.26 & -0.23 & 64 \\ & QCFS [9] & VGG-16 & 76.28 & 76.24 & -0.04 & 16 \\ & Diet-SNN [38] & VGG-16 & 71.82 & 69.67 & -2.15 & 5 \\ & **Ours (Hybrid Coding)** & **VGG-16** & **77.15** & **75.75** & **-1.40** & **6.88** \\ & RMP [36] & ResNet-20 & 68.72 & 67.82 & -0.90 & 2048 \\ & TSC [37] & ResNet-20 & 68.72 & 68.18 & -0.54 & 2048 \\ & Calibration [10] & ResNet-20 & 77.16 & 76.32 & -0.84 & 32 \\ & Burst+LIPooling [25] & ResNet-20 & 80.69 & 79.83 & -0.86 & 64 \\ & QCFS [9] & ResNet-20 & 69.94 & 69.82 & -0.12 & 32 \\ & Diet-SNN [38] & ResNet-20 & 64.64 & 64.07 & -0.57 & 5 \\ & TET [40] & ResNet-19* & - & 74.72 & - & 6 \\ & **Ours (Hybrid Coding)** & **ResNet-20** & **76.56** & **75.39** & **-1.17** & **3.94** \\ \hline \multirow{8}{*}{Tiny-ImageNet} & Spike-thrift [41] & VGG-16 & 56.56 & 51.92 & -4.64 & 150 \\ & Calibration [10] & VGG-16\({}^{+}\) & 60.95 & 53.96 & -6.99 & 32 \\ \cline{1-1} & Burst+LIPooling [25] & VGG-16\({}^{+}\) & 61.80 & 55.56 & -6.24 & 64 \\ \cline{1-1} & QCFS [9] & VGG-16\({}^{+}\) & 54.91 & 54.92 & 0.01 & 16 \\ \cline{1-1} & **Ours (Hybrid Coding)** & **VGG-16** & **58.75** & **56.95** & **-1.80** & **7.11** \\ \cline{1-1} & Calibration [10] & ResNet-20\({}^{+}\) & 58.29 & 52.79 & -5.5 & 32 \\ \cline{1-1} & QCFS [9] & ResNet-20\({}^{+}\) & 55.81 & 52.32 & -3.49 & 16 \\ \cline{1-1} & **Ours (Hybrid Coding)** & **ResNet-20** & **58.34** & **56.50** & **-1.84** & **6.54** \\ \hline \hline \end{tabular} * Only the results of ResNet-19 are reported in these works, which has comparable model capacity to other ResNet-20 models. + Our reproduced results using publicly available codes. \end{table} TABLE I: Comparison of classification accuracy and inference time on CIFAR-10, CIFAR-100, and Tiny-ImageNet datasets. \(\Delta\)Acc. = SNN Acc. = ANN Acc. at earlier time steps exhibit higher accuracy than those made later, as indicated by the wrong decision rates. This implies early decisions correspond to easy samples and TTFS decoding has the capability to decide when sufficient evidence has been accumulated for different samples. Compared with direct decoding which makes all decisions at the final time step, TTFS decoding can significantly reduce average inference time yet achieve high classification accuracy. ### _Effective and Rapid Training with Layer-wise Learning Method_ To further explore the effectiveness and training speed of the proposed layer-wise learning method, we conduct a series of studies in this section. All experiments are performed on CIFAR-10 dataset using VGG-16 architecture. Firstly, to assess the effectiveness of the LTL rule in producing the desired neural representation as specified by the neural coding scheme, we execute experiments by converting the hidden layers of teacher ANN into SNN layers, while maintaining the input and output layers with direct coding. In this set-up, the LTL-trained D+R+D and D+B+D models achieve minimal accuracy drops of \(0.56\%\) and \(0.31\%\) from the teacher ANN, suggesting the LTL rule is highly effective in producing rate- and burst-based neural representations. In the same vein of research, the Calibration method [10] proposes to fine-tune the hidden layer representations layer-wise to follow rate coding. However, this method neglects the temporal dynamics of spike trains and only performs training at the spike-train-level. As a result, their trained D+R+D model encounters a larger accuracy drop of \(1.21\%\). For a more detailed analysis, we calculate the normalized MSE losses (i.e., Eq. (7)) between the convolutional layers of teacher ANN and student SNN and provide the results in Fig. 6(a). As expected, the LTL-trained D+R+D model achieves significantly lower MSE losses than those of the Calibration trained model. This finding suggests that fine-tuning the temporal dynamics of each hidden layer is crucial for achieving the desired neural representation. Furthermore, the D+B+D model outperforms the D+R+D models, indicating the burst coding can better approximate the neural representation of teacher ANN. By leveraging the knowledge from teacher ANN, the layer-wise LTL rule can achieve faster training convergence compared to other end-to-end training rules. To illustrate this, we compare the learning curves of the LTL rule with the end-to-end TET rule [40]. As depicted in Fig. 6(b), our model reaches the accuracy of \(95.19\%\) rapidly within only \(5\) training epochs, whereas the TET model does not converge even at epoch \(100\). Coupling with the early decision-making capability as discussed earlier, our hybrid coding and learning framework significantly reduces the cost of training and deployment of SNNs. In general, the quality of the decision improves when a longer decision time is provided to an SNN. To demonstrate how the proposed TTFS learning rule effectively balances the latency and classification accuracy, we plot the learning curves of the TTFS classifier in Fig. 6(c) and 6(d). The model performance is evaluated by considering both latency and accuracy. In particular, we use \(\Delta\)Acc.\(*\)\(t_{inf}\) as the evaluation criteria, where \(t_{inf}\) refers to the average inference time. As shown in Fig. 6(c), the average decision time is sharply advanced at the beginning, accompanied by a degree of accuracy loss due to overfitting. The learning dynamics during this period are mainly driven by the long-term potentiation (LTP) effect of loss function \(\mathcal{L}_{1}\) as described in Fig. 6(d). Fortunately, the training begins to be dominated by \(\mathcal{L}_{2}\) after the convergence of \(\mathcal{L}_{1}\), which improves the classification accuracy by slightly delaying wrong decisions, allowing more evidence to accumulate. The learning dynamics at these two stages perfectly align with the two objectives specified in the TTFS learning rule. Therefore, this ensures that an early yet accurate decision is made. ### _Superior Energy Efficiency with Hybrid Coding_ In the previous section, we demonstrated that the proposed hybrid coding framework can achieve rapid decision-making. Here, we analyze whether this attribute can translate into energy savings. To this end, we follow the convention of the Neuromorphic Computing community [46, 47] and calculate the synaptic operations (SynOps) ratio between equal-structured ANN and SNN use Multiply-and-Accumulate (MAC) and Accumulate (AC) operations, respectively. The total SynOps required in the ANN model can be calculated as below: \[SynOps(ANN)=\sum_{l}^{L}f_{in}^{l}N^{l}, \tag{16}\] where \(L\) is the total number of layers, \(f_{in}^{l}\) denotes the fan-in connections to the neuron in layer \(l\) from the previous layer, and \(N^{l}\) is the total number of neurons in layer \(l\). As the SNN model has an additional temporal dimension and only operates when spikes occur, the total SynOps calculation is different from its counterpart ANN model's. Hence, the total SynOps is formulated as below: \[SynOps(SNN)=\sum_{t}^{T}\sum_{l}^{L-1}\sum_{j}^{N^{l}}f_{out,j}^{l}s_{j}^{l}(t), \tag{17}\] where the \(T\) is the total inference time window, \(f_{out}^{l}\) represents the fan-out connections from neuron \(j\) in layer \(l\) to the Fig. 5: The distribution of decision-making time for D+B+T and D+R+T models. next layer, and \(s_{j}^{l}(t)\) denotes the spike occurrence in neuron \(j\). To facilitate a fair comparison with other SOTA SNN models, we find recent works whose codes are publicly available and reproduce their results on CIFAR-10 dataset using VGG-16. Particularly, we report the SynOps ratios at the time step when a comparable classification accuracy has been achieved. As the results summarised in Tab. II, our model achieves the lowest SynOps ratio of \(0.49\), which is at least 3.90\(\times\) lower than the other SOTA models. Notably, the total SynOps required by our model is much lower than that of the network conversion method QCFS, which achieves a SynOps ratio of 1.91 at T=16. This result again validates our earlier finding that the reduced inference time is not due to the compressed time window provided by burst coding. Instead, burst coding allows important information to be transmitted earlier, leading to early and efficient decision-making. Surprisingly, the SynOps ratio of the TET direct trained model is significantly higher than ours even at a comparable inference time. We suspect this is due to the high firing rate resulting from the activity regularization in TET training. According to a recent study [48] on 45 \(nm\) CMOS technology, the \(32\)-bit float MAC and AC operations consume 4.6 \(pJ\) and 0.9 \(pJ\) energy. As such, our SNN model can yield an order of magnitude energy saving over its ANN counterpart. The saving can be further boosted to 65.31\(\times\) when the cheaper \(32\)-bit int operations are used (3.1 \(pJ\) and 0.1 \(pJ\) for corresponding MAC and AC operations). ## 4 Efficient and Robust Sound Localization with Hybrid Coding In this section, we evaluate the proposed hybrid coding approach on the SLoClas dataset [49] which is designed for real-world sound localization and classification tasks. Particularly, we perform a comprehensive comparison of the proposed hybrid coding SNN against other SOTA models based on factors such as localization precision, inference speed, energy consumption, and noise robustness. Moreover, an ablation study is carried out to gain insight into the impact that distinct hybrid neural coding designs exert on the model's overall performance. The detailed configurations of data preprocessing, MTPC front-end, and SNN architecture are summarized in Supplementary materials. \begin{table} \begin{tabular}{l c c c c c} \hline \hline **Model** & **SNN Acc. (\%)** & \(\Delta\)**Acc. (\%)** & **Avg. Inference Time** & **Ratio** & **Energy Saving** \\ \hline Calibration [10] & 95.04 & -0.65 & 64 & 2.10 & 2.43 (15.24) \\ QCFS [9] & 93.43 & -0.15 & 16 & 1.91 & 2.68 (11.94) \\ Burst+LIPooling [25] & 93.71 & -0.40 & 64 & 4.81 & 1.06 (6.65) \\ TET [40] & 94.94 & - & 6 & 2.06 & 2.48 (15.53) \\ **Ours (Hybrid Coding)** & **95.67** & **-0.17** & **5.21** & **0.49** & **10.43 (65.31)** \\ \hline \hline \end{tabular} \end{table} TABLE II: Comparison of energy efficiency with other SNN implementations when achieving a comparable classification accuracy. \(\Delta\)**Acc**: the accuracy difference between equal-structured ANN and SNN. **Ratio**: SynOps(SNN)/SynOps(ANN). **Energy Saving**: Estimated energy saving of SNN against ANN using 32-bit float operations (32-bit int operations). Fig. 6: (a) Comparison of final layer-wise MSE losses optimized by LTL and Calibration rules. (b) Learning curves of different training methods. (c) Illustration of learning dynamics during TTFS training. \(t_{inf}\) refers to the average inference time, and \(\Delta\)Acc. refers to the accuracy drop from baseline ANN. (d) The evolution of the two loss functions used for TTFS training. ### _Precise, Rapid, and Robust Sound Localization_ To furnish a comprehensive assessment of the localization precision, we report the mean absolute error (MAE) and the azimuth classification accuracy. As defined in Eqs. 18 and 19, the former computes the average difference between the predicted and the true azimuth angle, while the latter represents the proportion of accurately predicted test samples. \[MAE(^{\circ})=\frac{1}{N_{t}}\sum_{i=1}^{N_{t}}|\hat{\theta}_{i}-\theta_{i}|, \tag{18}\] \[Acc(\%)=\frac{1}{N_{t}}\sum_{n=1}^{N_{t}}(|\hat{\theta}_{i}-\theta_{i}|<\eta), \tag{19}\] where \(\hat{\theta}_{i}\) and \(\theta_{i}\) are the estimated and the ground truth azimuth angle of sample \(i\). \(\eta\) is the acceptable absolute error when determining whether a sample has been correctly classified. \(N_{t}\) represents the total number of test samples. Since the SLoClas dataset is recorded at a resolution of \(5^{\circ}\), we set \(\eta\) to 2.5\({}^{\circ}\) and round the estimated angles to the nearest increment of 5 degrees in the classification task. As presented in Tab. III, our hybrid coding SNN achieves an MAE of 0.60\({}^{\circ}\) with an average inference time of only 4.37 time steps, outperforming all other competitive baseline models. Furthermore, we compare the noise robustness of the proposed hybrid coding SNN with other baseline models using the directional background noises provided in the SLoClas dataset. To create noisy data samples, we randomly select a noise fragment from the SLoClas dataset and add it to the clean test samples at different signal-to-noise ratios (SNRs). As the results provided in Fig. 7, our hybrid coding SNN consistently outperform other models regardless of the noise levels. These results demonstrate the effectiveness and efficiency of the proposed hybrid coding approach. ### _Ablation Study of Hybrid Coding Design_ To understand why the proposed hybrid coding design can improve localization performance, we further conduct a series of ablation studies to investigate different hybrid coding designs. #### 4.2.1 Localization Precision, Latency, and Energy Consumption We first look into two sets of designs to investigate the impact of TTFS decoding: 1. P+B+T vs. P+B+D; 2. P+R+T vs. P+R+D. As the results presented in Tab. IV, direct decoding and TTFS decoding yield nearly identical MAEs; however, TTFS decoding requires only about one-third to one-half of the average inference time. Consequently, these results suggest that TTFS coding can maintain high localization precision while leading to reduced inference latency and energy consumption. It is worth noting that the energy efficiency index SynOps shows a similar ratio between the two output coding schemes regardless of what coding scheme used in hidden layers. These findings suggest that early decision-making supported by TTFS decoding contributes to energy saving. Furthermore, the results offer valuable insights into the function of burst coding within our hybrid coding design. Our findings indicate that burst coding outperforms rate coding by 0.22 MAE and leads to a decision being made 3.25 time steps earlier. However, it is worth noting that burst coding is associated with a higher spike density. Interestingly, when burst coding is combined with TTFS coding, the energy consumption can be reduced by one-third, resulting in only half the energy consumption of an ANN. These findings suggest that choosing between burst coding and rate coding will depend on the specific requirements of the task at hand. For instance, if energy efficiency is a top \begin{table} \begin{tabular}{l c c c} \hline \hline **Model** & **MAE(\({}^{\circ}\))** & **Avg. Inference Time** & **SynOps (Millions)** \\ \hline ANN & 1.12 & - & 5.15 \\ \hline P+R+D & 0.83 & 16 & 2.06 \\ \hline P+B+D & 0.61 & 16 & 10.70 \\ \hline P+R+T & 0.82 & 7.62 & 0.94 \\ \hline P+B+T & 0.60 & 4.37 & 2.86 \\ \hline \hline \end{tabular} \end{table} TABLE IV: Comparison of MAE, inference time, and SynOps among different neural coding combinations. \begin{table} \begin{tabular}{l l c c c c c} \hline \hline **Dataset** & **Method** & **ANN MAE(\({}^{\circ}\))** & **ANN Acc. (\%)** & **SNN MAE(\({}^{\circ}\))** & **SNN Acc.** & **Avg. Inference Time** \\ \hline \multirow{4}{*}{SLoClas} & GCC-PHAT-CNN [49] & 4.39 & 86.94 & - & - & - \\ & MTPC-CSNN [33]\({}^{*}\) & - & - & 1.34 & 93.16 & 2 \\ \cline{1-1} & MTPC-CSNN [33]\({}^{*}\) & - & - & 1.23 & 93.95 & 4 \\ \cline{1-1} & MTPC-CSNN [33]\({}^{*}\) & - & - & 1.02 & 94.72 & 8 \\ \cline{1-1} & MTPC-RSNN [33]\({}^{*}\) & - & - & 1.48 & 94.30 & 51 \\ \cline{1-1} & **Ours (Hybrid Coding)** & **1.12** & **95.19** & **0.60** & **95.61** & **4.37** \\ \hline \hline \multicolumn{8}{l}{* Our reproduced results.} \\ \end{tabular} \end{table} TABLE III: Comparison of sound localization accuracy, MAE and inference time on SLoClas Dataset. Fig. 7: Comparison of localization precision at different SNRs. priority, P+R+T coding could be selected. Alternatively, if minimizing MAE and latency are key concerns, burst coding may be a better option, given its optimal balance between precision, latency, and energy consumption. #### 4.2.2 Environmental Noise In order to investigate the impact of hybrid coding design on the noise robustness of a model, two forms of environmental noise, specifically factory noise and babble noise, are employed to generate noise-corrupted test samples. The training is carried out on clean data samples, while the effect of noise is evaluated on noise-corrupted test samples at varying SNRs. The results of different hybrid coding designs are presented in Fig. 8(a) and 8(b). In general, the P+B+T hybrid coding design demonstrates superior noise robustness under most noise conditions, except for the factory noise with an SNR of 0, where P+B+D performs slightly better than ours P+B+T. This observation can be attributed to the fact that TTFS coding, which requires only about one-third of the time for decision-making, is less susceptible to cumulative noises when the noise level is low. However, in situations where environmental noise significantly impairs acoustic information, TTFS decoding becomes more susceptible to noise due to the limited evidence that can be leveraged, thereby hindering its performance. Furthermore, our findings suggest that the hybrid coding design employed in this study performs better under babble noise than under factory noise, owing to the latter's greater prevalence in dynamic frequency components. #### 4.2.3 Neuronal Noise We further conduct a detailed analysis of the impact of neuronal noise on the hybrid coding design. Neuronal noise is known to be ubiquitous in human brains. Investigating the performance of the hybrid coding design under such conditions provides an opportunity to identify the most promising design that closely mimics the human auditory system. In our experiments, we simulate neuronal noise by introducing spike deletion operations, whereby a fraction of hidden neurons are randomly contaminated by neuronal noise, thereby failing to generate output spikes. We present the localization results as a function of spike deletion rate in Fig. 8. Our findings indicate that TTFS coding is more reliable than direct coding, which is consistent with our observations on environmental noises. Interestingly, when a large percentage of information fails to transfer (\(>60\%\)), P+R+T outperforms P+B+T. This can be attributed to the fact that the decision time of P+B+T is approximately half that of P+R+T, which significantly impacts the amount of information delivered. Therefore, our design of P+B+T may not accumulate sufficient evidence during inference, hence trading noise robustness for inference speed. ## 5 Conclusion In this paper, we proposed a hybrid neural coding approach to solve pattern recognition tasks with SNNs. In particular, we demonstrated that by holistically designing the SNN to encompass hybrid neural coding schemes, we could leverage the benefits of different neural codes to achieve optimal performance according to task requirements and environmental conditions. To overcome the challenges associated with training hybrid coding SNNs, we proposed a layer-wise learning method that was both highly effective and efficient in producing the desired neural coding schemes over existing SNN learning methods. Our extensive experiments demonstrated that state-of-the-art image classification accuracies and sound localization precision could be achieved with significantly improved inference speed, energy efficiency, and noise robustness compared to other SNNs constructed using homogeneous neural coding. While our study primarily examined image classification and sound localization tasks, we emphasized that the design principles and training methods proposed in this work could be extended to other pattern recognition tasks and diverse environmental conditions. Notably, the successful implementation of our hybrid coding approach necessitated a comprehensive understanding of the strengths and limitations of various neural coding schemes as well as task-specific requirements. In future research, we aimed to develop a neural coding search method that could automatically identify the optimal hybrid neural coding scheme for each individual spiking neuron according to task demands and environmental conditions, thereby reducing the requisite level of expertise. Fig. 8: The sound localization results under different noise conditions (a) babble noise, (b) factory noise, (c) neuronal noise. \(\delta\)**MAEs** is the MAE difference between noisy and clean conditions.
2305.18552
Learning Linear Groups in Neural Networks
Employing equivariance in neural networks leads to greater parameter efficiency and improved generalization performance through the encoding of domain knowledge in the architecture; however, the majority of existing approaches require an a priori specification of the desired symmetries. We present a neural network architecture, Linear Group Networks (LGNs), for learning linear groups acting on the weight space of neural networks. Linear groups are desirable due to their inherent interpretability, as they can be represented as finite matrices. LGNs learn groups without any supervision or knowledge of the hidden symmetries in the data and the groups can be mapped to well known operations in machine learning. We use LGNs to learn groups on multiple datasets while considering different downstream tasks; we demonstrate that the linear group structure depends on both the data distribution and the considered task.
Emmanouil Theodosis, Karim Helwani, Demba Ba
2023-05-29T18:29:11Z
http://arxiv.org/abs/2305.18552v1
# Learning Linear Groups in Neural Networks ###### Abstract Employing equivariance in neural networks leads to greater parameter efficiency and improved generalization performance through the encoding of domain knowledge in the architecture; however, the majority of existing approaches require an a priori specification of the desired symmetries. We present a neural network architecture, Linear Group Networks (LGNs), for learning linear groups acting on the weight space of neural networks. Linear groups are desirable due to their inherent interpretability, as they can be represented as finite matrices. LGNs learn groups without any supervision or knowledge of the hidden symmetries in the data and the groups can be mapped to well known operations in machine learning. We use LGNs to learn groups on multiple datasets while considering different downstream tasks; we demonstrate that the linear group structure depends on _both_ the data distribution and the considered task. ## 1 Introduction Convolutional neural networks (LeCun et al., 1989, 1998) were one of the first architectures that introduced the concept of equivariance to neural networks. By exploiting translation symmetry, networks can greatly reduce their number of learnable parameters compared to fully connected networks, while at the same time resulting in models that generalize better. While equivariance to translations is a natural choice for image classification or speech recognition, it is not the only one; planar rotations of objects leave the class identity unchanged and variations in pitch do not alter the spoken utterance. Moreover, certain data modalities, such as graphs, do not utilize translational symmetries and instead require other symmetries. Equivariant convolutional networks (Cohen and Welling, 2016) were proposed as a method to design equivariant neural networks. However, encoding symmetries poses certain challenges: most architectures require an explicit specification of the desired symmetry, lack a general framework and require special treatment for every group, and only allow for _unidirectional_ knowledge flow. Indeed, baseline frameworks do not allow learning the symmetries from the data and instead they need to be specified during construction. At the same time, they are not generalizable as the network architecture needs to change fundamentally in order to account for the different groups, depending on the desired symmetry. Finally, it is possible to embed known symmetries in the model (creating a knowledge path from the designer to the network), but it is not possible to uncover symmetries in the data and extract them. This step is crucial as in many modalities we lack a clear understanding of the present symmetries. Ideally, the equivariant structure would be learnt from the data, for the specific task. At the center front of this equivariant structure is the operation that characterizes the group: its group action. However, isomorphisms between groups can inhibit interpretability, as two groups can have the same structure but their actions transform the data in different manners. In that context, recovering a group structure that is isomorphic to a known group, for example \(\mathcal{D}_{4}\) offers little insight without knowing how the elements operate in the data domain. We would like to recover the specific group that is interesting for the data and the task. The _linear group_, the group of invertible transformations, is an extensive group that encapsulates a vast variety of groups as subgroups, including rotations, reflections, translations, and more. Under this group, group actions are clearly understood and can be visualized giving insights on how the matrices interact with the signals from the data domain. We propose Linear Group Networks (LGNs) that learn elements of the linear group and uses them to construct cyclic groups on the weight space of neural networks. Our main contributions can be summarized as follows: * We propose a computational framework that learns elements of the _general linear group_\(\mathrm{GL}_{d}(K)\) and use them to construct sets of filters that belong to a (finite) cyclic group whose action is a linear operator. The framework is constructive and requires minimal changes to existing architectures, training procedures, and pipelines. * We apply the framework on datasets of natural images and recover the group structure of the filter sets. We discover multiple structures of interest, including groups whose actions are _skew-symmetric_, _Toeplitz_, or act on _multiple scales_. * We analyze the learned actions via ablation studies and draw connections to well-known operations in machine learning. We show that certain sets of groups have actions that have a high correlation with compositions of rotations and median filtering (related to the popular pooling operations in neural networks). Finally, we emphasize that a main contribution of our work is analyzing the learned group actions for the different filter sets when the architecture is trained on natural images, and drawing interepretable analogues to well-known operations in machine learning. Prior work focused on the ability of their networks to learn carefully curated (and well-studied) known symmetries; instead, we analyze the group structures that organically arise in ubiquitous datasets as an effort to inform our understanding of important symmetries for data modalities and different tasks, rather than provide an architecture purely for symmetry learning. ## 2 Related work In recent years there has been a resurgence in interest for equivariant neural networks following the concurrent works of Cohen and Welling (2016) and Dieleman et al. (2016), where convolutional frameworks that were equivariant with respect to elementary rotations and reflections were introduced. The work of Kondor and Trivedi (2018) showed that linear equivariant maps are intertwined with group convolutions and inspired a vast array of practical architectures for encoding equivariances, including architectures equivariant to arbitrary rotations (Worrall et al., 2017); steerable representations (Cohen and Welling, 2017); avoiding interpolation artifacts by modeling equivariances on the sphere (Esteves et al., 2020); and extensions to vector fields (Marcos et al., 2017). A growing body of work has studied the process of learning symmetries: Cohen and Welling (2014); Dehmamy et al. (2021); Moskalev et al. (2022) consider learning Lie groups by utilizing the corresponding Lie algebras; Benton et al. (2020) learn distributions over data augmentations to recover invariances from the data; Romero and Lohit (2022) consider approximate symmetries over exact ones, as exact symmetries might be restrictive for natural data; and Zhou et al. (2021) propose a meta-learning scheme for learning equivariances by reparametrizing the weight matrices. Our work is most closely related to that of Zhou et al. (2021), however our method doesn't rely on a meta-learning framework and learns the filter sets and the corresponding group actions at the same time. Most importantly, we address one of the main limitations of Zhou et al. (2021), where symmetry discovery was not possible in single-task settings. Recently, Sanborn et al. (2023) proposed the use of the bispectrum to learn groups and their orbits. However, their framework acts directly on the _input_ space, whereas ours acts on the _weight_ space. Preliminaries In this section we introduce the necessary background for our method, which relies on equivariance, cyclical and linear groups, and unfolded networks. Unfolded architectures have been used in the literature for their parameter efficiency and principled derivation from optimization problems. Moreover, they have been used with great success for compressive sensing (Gregor and LeCun, 2010), state-of-the-art denoising (Tolooshams et al., 2021), downstream tasks and rank-minimization (Rolfe and LeCun, 2013; Jing et al., 2020), and for deep representations (Sulam et al., 2020). We note that our method does not rely on unrolling and is compatible with any network architecture as it acts directly on the weights of each layer. For the bulk of our experiments in Section 5, we opted for unfolded networks because of the residual estimation at every layer: the input is approximately reconstructed at every layer to compute the next representation. As our work considers group actions as the centerpiece of group learning, having filters that act on the data space allows us to learn human-interpretable group actions, which becomes challenging when the group acts on a space of high-dimensional feature maps. At the same time, acting on the data space allows us to maintain moderate model sizes, making our presented networks efficient and scalable. **Equivariance.** Consider an operator \(f:V\to W\) and a family of actions \(\mathcal{T}\). We call \(f\)_equivariant_ with respect to the family \(\mathcal{T}\) if for \(T\in\mathcal{T}\) and any \(x\in V\) it holds \[f(T(x))=T^{\prime}(f(x)), \tag{1}\] for some transformation \(T^{\prime}\in\mathcal{T}^{\prime}\). Note that in general the action \(T\) and transformation \(T^{\prime}\) are not the same; this can be directly seen since \(\mathrm{dom}(T)=V\) and \(\mathrm{dom}(T^{\prime})=W\) (however, even when \(\mathrm{dom}(T)=\mathrm{dom}(T^{\prime})\) the operations need not be the same). **Cyclic groups.** Consider a non-trivial set \(G\) and an operation \(*\). We call \((G,*)\) a _group_ if \(*\) is associative on \(G\), \(G\) contains an identity element \(e\) with respect to \(*\), and for any \(g\in G\) there exists an inverse element \(g^{-1}\in G\) such that \(g*g^{-1}=e\). We call the group a cyclic group if every element in the group can be generated via consecutive applications of a basis element \(g\) (i.e., any element of \(G\) can be expressed as \(g^{k}\) for \(k\in\mathbb{Z}\)), and we call \(g\) the _generator_ of \(G\). When the cyclic group is finite and has order \(p\) it can be denoted as \[G=\{e,g,g^{2},\ldots,g^{p-1}\}, \tag{2}\] where higher order exponents get mapped to the \(p\) canonical elements, i.e. for \(l\geq p\) it holds \(g^{l}=g^{l\mod p}\). **Linear groups.** For our purposes, linear groups will refer to subgroups of the _general linear group_\(\mathrm{GL}_{d}(K)\) of \(d\times d\) invertible matrices over the field \(K\). Considering a collection of \(C\) of elements of \(\mathrm{GL}_{d}(K)\), the subgroup generated by \(C\) is a linear group. A special case of interest for our work arises when \(C\) contains only a single element \(c\); then \(C\) becomes a cyclic group generated by \(c\). **Unrolled sparse autoencoders.** Unrolled networks temporally unroll the steps of optimization algorithms, mapping algorithm iterations to network layers. In that way, the output of the neural network can be interpreted as the output of the optimization algorithm, with theoretical guarantees under certain assumptions. The _Iterative Soft Thresholding Algorithm_ (ISTA), an algorithm for sparse coding, has inspired several architectures (Gregor and LeCun, 2010; Simon and Elad, 2019; Sulam et al., 2020; Tolooshams et al., 2021), due to the desirability of sparse representations for interpretation purposes and also the connection between ReLU and soft thresholding. Within that framework, the representation at layer \(l+1\) is given by \[\mathbf{z}^{(l+1)}=\mathcal{S}_{\lambda}\left(\mathbf{z}^{(l)}+\alpha\mathbf{W}_{l}^{T}( \mathbf{x}-\mathbf{W}_{l}\mathbf{z}^{(l)})\right), \tag{3}\] where \(\mathbf{x}\) is the _original_ input, \(\mathbf{z}^{(l)}\) is the representation at the previous layer, \(\mathbf{W}_{l}\) are the weights of layer \(l\), \(\alpha\) is a constant such that \(\frac{1}{\alpha}\geq\sigma_{\max}(\mathbf{W}_{l}^{T}\mathbf{W}_{l})\), and \(\mathcal{S}_{\lambda}\) is the _soft thresholding_ operator defined as \[\mathcal{S}_{\lambda}(u)=\mathrm{sign}(u)\cdot\mathrm{ReLU}(|u|-\lambda). \tag{4}\] A one-sided version of (4) arises if we enforce \(u>0\). Then, the soft thresholding operator becomes a shifted version of ReLU, i.e. \(\mathcal{S}_{\lambda}(u)=\mathrm{ReLU}(u-\lambda)\) (and the bias \(\lambda\) can be incorporated to the weights of the network prior the activation). If the weights of all the \(L\) layers are equal, i.e. \(W_{1}=\ldots=W_{L}\), we call the network _tied_. As a final remark, Equation (3) can be rewritten as \[\mathbf{z}^{(l+1)}=\mathcal{S}_{\lambda}\left((I-\alpha\mathbf{W}_{l}^{T}\mathbf{W}_{l}) \mathbf{z}^{(l)}+\alpha\mathbf{W}_{l}^{T}\mathbf{x}\right)=\mathcal{S}_{\lambda}\left( \mathbf{W}_{z}\mathbf{z}^{(l)}+\mathbf{W}_{x}\mathbf{x}\right),\] where we let \(\mathbf{W}_{z}=(I-\alpha\mathbf{W}_{l}^{T}\mathbf{W}_{l})\) and \(\mathbf{W}_{x}=\alpha\mathbf{W}_{l}^{T}\), which can be interpreted as a residual network (He et al., 2016), with a residual connection to the input. Convolutional extensions of (3) can be readily derived by replacing the matrix-vector products with correlation/convolution operations. ## 4 Group learning framework We propose a framework for learning linear groups acting on the filters of neural networks. We consider cyclic linear groups generated by a single element of the generalized linear group; to that end, we will allow \(K\) groups of size \(p\) at every layer \(l\) (all of which are design choices of the model). This implies that at every layer the architecture learns \(K\) filter sets of exactly \(p\) elements each, such that the filter sets are generated via a generating element \(g_{(k,l)}\). Then, the weights of each group are related via the application of the group action \[[\mathbf{W}_{l}^{k}\quad g_{(k,l)}\mathbf{W}_{l}^{k}\quad\dots g_{(k,l)}^{p-1}\mathbf{W}_{l }^{k}]. \tag{5}\] Let \(\mathbf{W}_{l}^{k}\in\mathbb{R}^{n\times m}\), i.e., the weights of every group at every layer are real-valued matrices of size \(n\times m\). An initial approach would be to model \(g_{(k,l)}\) as an element of \(\mathrm{GL}_{n}(\mathbb{R})\), however we will see that this has significant limitations. **Limitations of matrices in the weight space.** Consider using matrices \(\mathbf{A}\in\mathbb{R}^{n\times n}\) to represent the generators \(g_{(k,l)}\) of each group at every layer. Then, assuming a _basis_ filter \(\mathbf{W}_{l}^{k}\in\mathbb{R}^{n\times m}\) for each filter set, generate the rest of the filters by applying the group action on the basis filter of each group \[[\mathbf{W}_{l}^{k}\quad\mathbf{A}_{(k,l)}\mathbf{W}_{l}^{k}\quad\dots\mathbf{A}_{(k,l)}^{p-1} \mathbf{W}_{l}^{k}].\] This is a natural model since, if \(\mathrm{rank}(A)=n\) (assuming \(m\geq n\) for now), this linear operator can generate any vector in \(\mathbf{x}\in\mathbb{R}^{n}\), as it is a basis for \(\mathbb{R}^{n}\). However, while such an approach would be able to learn generators that can produce any vector in \(\mathbb{R}^{n}\), it would ignore any spatial relations in the basis filters (or, more generally, any co-dependence or correlation between different columns). Indeed, matrices (and by extension, convolutional neural network filters) cannot be used to represent _any_ linear operator on their own set, as we prove by providing a short counter-example below. **Proposition 1**.: _There are linear operators on the space of \(n\times m\) matrices that can't be represented via an \(n\times n\) matrix._ Proof.: Assume that every linear operator on \(n\times m\) matrices can be represented by a \(n\times n\) matrix and consider an operator \(f:V\to V\) (with \(V\equiv\mathbb{R}^{n\times m}\)) that swaps the top left with the bottom right element, i.e. \[\left(f(\mathbf{W})\right)_{ij}=\begin{cases}W_{nm},&\text{ if }(i,j)=(1,1),\\ W_{11},&\text{ if }(i,j)=(n,m),\\ W_{ij},&\text{ otherwise}.\end{cases}\] This operator is linear since \(f(\alpha\mathbf{X}+\beta\mathbf{Y})=\alpha f(\mathbf{X})+\beta f(\mathbf{Y})\). However, this operator can't be represented by a \(n\times n\) matrix since these matrices, as linear operators, act on \(n\)-dimensional vectors (i.e., treat every column of the input independently). This follows since, assuming \(f\) is parametrized by \(\mathbf{A}\in\mathbb{R}^{n\times n}\), we have \[\left(f(\mathbf{W})\right)_{ij}=\sum_{k}A_{ik}W_{kj}.\] In the above equation the operator has a strict dependence on column \(j\) of the input and the computation is independent of all other columns; therefore, swapping the corner most elements columns \(1\) and \(m\) is not feasible using this parametrization. Note that a simpler example would be an operator such that \(\mathbf{W}\mapsto\mathbf{W}^{T}\), as transposition is a linear map. However, if \(n\neq m\) then the group elements would belong in different linear spaces (\(\mathbb{R}^{n\times m}\) versus \(\mathbb{R}^{m\times n}\)). While this is not prohibitive, it would complicate the notation for the group definition and hence we presented a slightly more involved example. **Employing vectorization.** As we showed above, modeling the group actions \(g_{(k,l)}\) as \(n\times m\) matrices leads to restrictive groups where simple linear operators are excluded. Instead, we propose the modeling of the group actions \(g_{(k,l)}\) via vectorization. We first define the vectorization operator along with its inverse. **Definition 1**.: _Consider a matrix \(\mathbf{A}\in\mathbb{R}^{n\times m}\). Define the vectorization operator, denoted as \(\operatorname{vec}\), as follows_ \[\operatorname{vec}: \mathbb{R}^{n\times m}\to\mathbb{R}^{n\cdot m} \tag{6}\] \[\mathbf{A}\mapsto[A_{11},\dots,A_{n1},A_{12},\dots,A_{n2},\dots,A_{1 m},\dots,A_{nm}]^{T}.\] _The vectorization operator can also be expressed as a linear sum using the Kronecker product: \(\operatorname{vec}(\mathbf{A})=\sum_{i=1}^{m}\mathbf{e}_{i}\otimes\mathbf{A}\mathbf{e}_{i}\), where \(\mathbf{e}_{i}\in\mathbb{R}^{m}\) denotes the \(i\)-th basis vector of \(\mathbb{R}^{m}\). The inverse map \(\operatorname{vec}^{-1}_{n\times m}\), where the subscript \(n\times m\) will be dropped for conciseness, is also defined via Kronecker products_ \[\operatorname{vec}^{-1}: \mathbb{R}^{n\cdot m}\to\mathbb{R}^{n\times m} \tag{7}\] \[\mathbf{a}\mapsto\left(\operatorname{vec}^{T}(\mathbf{I}_{m})\otimes\bm {I}_{n}\right)(\mathbf{I}_{m}\otimes\mathbf{a}),\] _where \(\mathbf{I}_{n}\in\mathbb{R}^{n\times n}\) denotes the identity matrix of \(\mathbb{R}^{n}\)._ Using those definitions, we will parametrize each group action of every layer as a linear operator on vectors in \(\mathbb{R}^{n\cdot m}\). Any linear operator on vectors can be uniquely parametrized (up to similarity) via a matrix \(\mathbf{A}\in\mathbb{R}^{n\cdot m\times n\cdot m}\); then, the group action acting on each filter set \(k\) at every layer \(l\), \(g_{(k,l)}\), will be instantiated via the map \[\phi_{\mathbf{A}}: \mathbb{R}^{n\times m}\to\mathbb{R}^{n\times m} \tag{8}\] \[\mathbf{X}\mapsto\operatorname{vec}^{-1}(\mathbf{A}\operatorname{vec}( \mathbf{X})).\] Using the formulation of (8), and denoting consecutive compositions with the same function via \(f^{n}=f\circ f^{n-1}\) with \(f\circ f=f^{2}\), we can finally express the weights of each filter set as a function of the group action \(\mathbf{A}_{(k,l)}\in\mathbb{R}^{n\cdot m\times n\cdot m}\) \[\mathbf{W}_{l_{k}}=[\mathbf{W}_{l}^{k}\quad\phi_{\mathbf{A}_{(k,l)}}(\mathbf{W}_{l}^{k})\quad \dots\phi_{\mathbf{A}_{(k,l)}}^{p-1}(\mathbf{W}_{l}^{k})]. \tag{9}\] While simple in its inception, the operator of (8) is expressive and can model _all_ linear operators in its domain. Note that \(\operatorname{dom}(\phi_{\mathbf{A}_{(k,l)}})=\mathbb{R}^{n\times m}\) which is different from the domain of \(\mathbf{A}_{(k,l)}\) (\(=\mathbb{R}^{n\cdot m\times n\cdot m}\)) when viewed as an operator (which is trivially linear with respect to its domain). **Proposition 2** (Linearity).: _Let \(\phi_{\mathbf{A}_{(k,l)}}\) be the map defined in (8); \(\phi_{\mathbf{A}_{(k,l)}}\) is linear. Moreover, any linear map \(\phi:\mathbb{R}^{n\times m}\to\mathbb{R}^{n\times m}\) can be parametrized by \(\phi_{\mathbf{A}_{(k,l)}}\)._ Proof.: \(\phi_{\mathbf{A}_{(k,l)}}\) is a composition of linear maps and therefore is itself linear. Indeed, \(\phi_{\mathbf{A}_{(k,l)}}\) comprises the composition of \(\operatorname{vec}\), matrix multiplication, and \(\operatorname{vec}^{-1}\). Following (6) and (7) in Definition 1, both operators are linear as compositions of linear operations, and therefore \(\phi_{\mathbf{A}_{(k,l)}}\) is itself linear. For the second part, consider the vector spaces \(\mathbb{R}^{n\times m}\) and \(\mathbb{R}^{n\cdot m}\). The linear map \(\operatorname{vec}\) is an isomorphism from \(\mathbb{R}^{n\times m}\) to \(\mathbb{R}^{n\cdot m}\) since * \(\operatorname{vec}(\alpha\mathbf{W})=\alpha\operatorname{vec}(\mathbf{W})\), for any \(\alpha\in\mathbb{R},\mathbf{W}\in\mathbb{R}^{n\times m}\), and * \(\operatorname{vec}(\mathbf{W}+\mathbf{V})=\operatorname{vec}(\mathbf{W})+\operatorname {vec}(\mathbf{V})\), for any \(\mathbf{W},\mathbf{V}\in\mathbb{R}^{n\times m}\), with the inverse map \(\operatorname{vec}^{-1}\). Since the spaces are isomorphic, parametrizing the a linear map in \(\mathbb{R}^{n\times m}\) reduces to parametrizing a linear map in \(\mathbb{R}^{n\cdot m}\). However, all linear transformations in \(\mathbb{R}^{n\cdot m}\) can be expressed by matrices \(\mathbf{A}\in\mathbb{R}^{n\cdot m\times n\cdot m1}\), which is precisely the parametrization of \(\phi_{\mathbf{A}_{(k,l)}}\). Therefore, any linear map \(\phi\) can be parametrized by \(\phi_{\mathbf{A}_{(k,l)}}\). **Architecture.** Composing the contents of this section, we apply our method to an unfolded network. Our building block consists of a _cyclical group layer_, a convolutional layer which utilizes unfolding \[\mathbf{z}^{(l+1)}=\mathcal{S}_{\lambda}\left(\mathbf{z}^{(l)}+\alpha\mathbf{W}_{l}^{T}*( \mathbf{x}-\mathbf{W}_{l}*\mathbf{z}^{(l)})\right), \tag{10}\] where \(*\) denotes convolution (correlation) and the weights of each layer \(l\) have \(K\) groups of filter sets such that \[\mathbf{W}_{l}=[\mathbf{W}_{l_{1}}\quad\mathbf{W}_{l_{2}}\quad\dots\quad\mathbf{W}_{l_{K}}], \tag{11}\] with \(\mathbf{W}_{l_{k}}\) being defined by (9). ### Invertibility loss To train the architecture, we consider the loss function best applicable to the downstream task of interest, which would result in the simultaneous, unsupervised learning of the basis filters \(\mathbf{W}_{l}^{k}\) and the group action \(\mathbf{A}_{(k,l)}\) via backpropagation. However, without any regularization, \(\mathbf{A}_{(k,l)}\) are unlikely to be elements of the linear group \(\mathrm{GL}_{n\cdot m}(\mathbb{R})\). The group membership is defining in our work, as otherwise \(\mathbf{A}_{(k,l)}\) do not define a cyclic group. To that end, we introduce an _invertibility loss_. This loss encourages the elements of the cyclic groups to be invertible and thus are elements of \(\mathrm{GL}_{n\cdot m}(\mathbb{R})\): \[L=\mu\|\mathbf{A}_{(k,l)}\widetilde{\mathbf{A}}_{(k,l)}-\mathbf{I}\|_{F}, \tag{12}\] where \(\widetilde{\mathbf{A}}_{(k,l)}\) are matrices only used in training to encourage invertibility and \(\mu\) is the a regularization parameter controlling the tradeoff between the performance on the downstream task and the enforcement of the invertibility. More discussions about the invertibility loss, and alternatives, can be found in Appendix B. ## 5 Experiments We used the architecture introduced in Section 4 in order to learn filter sets governed by different group actions in order to uncover latent symmetries in natural datasets. For our experimental setting, we learned basis filters \(\mathbf{W}_{l}^{k}\in\mathbb{R}^{6\times 6}\). Our architecture consists of \(L=4\) layers, each having \(K=5\) cyclic groups of \(p=4\) elements each. For complete information about hyperparameter values, datasets, training procedures, and the architecture see Appendix C. ### Recovered group structures We trained an unfolded network using our method introduced in Section 4 on the CIFAR10 dataset for the task of classification and learned the group actions \(\mathbf{A}_{(k,l)}\) and the basis filters \(\mathbf{W}_{l}^{k}\). During our experiments our networks learned multiple interesting group actions; we note three main structures that are of interest and we present them in Figure 1. **Skew-symmetric structure.** Observing the first column of Figure 1 we notice a skew-symmetric structure. Considering a single row of these matrices, most of them implement a _causal averaging_: the value of each pixel is updated according to a weighted sum of the pixels following it. This is an interesting emerging structure as it corresponds broadly to two very well known operations: _filtering_ (or smoothing) from Computer Vision and _average pooling_ in deep learning. Figure 1: Emerging group structures when learning group actions for classification on CIFAR10. **Toeplitz structure.** In the second column, the group actions have a Toeplitz (or approximately circulant) structure. Circulant matrices are of particular interest because of their ties to convolution, indicating a scheme of weight sharing or permutation operation being performed. Moreover, they are diagonalized by the Discrete Fourier Transform, which we explore in Appendix D. **Multi-scale structure.** Finally, the group actions in the third column have a multi-scale structure. Indeed, examining the recovered matrices at the quadrant level, we observe each quadrant having a dominant sign signature, either positive or negative (for example, in both figures, the lower left quadrant contains mostly positive values). However, "zooming" into specific blocks that describe the relation between rows and columns of the original filter (\(6\times 6\) blocks) we observe significantly different structures, both within quadrants (for example, the last and third to last block in the first "block-row" of the bottom figure) and across quadrants (the first and last blocks in the same "block-row"). #### 5.1.1 Effect of the group actions To gain better intuition and evaluate our analysis of the recovered structures, we applied the group actions to \(\mathbf{I}_{6}\in\mathbb{R}^{6\times 6}\), the identity matrix of \(\mathbb{R}^{6}\). Due to its simple structure, it allows us to understand the effect of the linear operations defined by \(\mathbf{A}_{(k,l)}\). Note that this is not trivial, as \(\mathbf{A}_{(k,l)}\) acts on the vectorization of \(\mathbf{I}_{6}\). We applied the group actions of the bottom row of Figure 1 on \(\mathbf{I}_{6}\) and we visualize the effects of the group actions in Figure 2. The effect of the skew-symmetric operator aligns with our intuition from Section 5.1: the earlier pixels have higher intensities compared to the later ones. This is expected, as the average is over more pixels in the upper rows of the relevant group actions. This translates to more elements of the diagonal of \(\mathbf{I}_{6}\) being included in the average, resulting in this gradient-like transformation on the input. For the Toeplitz structure, the diagonal has been slightly rotated towards the lower-left part of the matrix and has been significantly smoothed out. As we will further argue in Section 5.2.1, this behavior is not surprising as the structure of the group actions resembles a composition of known operators. Finally, the multi-scale structure is harder to interpret; however, we note that considering the pixels above the antidiagonal we observe significantly lower values compared to the pixels below the antidiagonal. Examining the upper or lower parts in a different scale, we see different structures (positive values in the upper part and negative values in the lower part), in line with the multi-scale interpretation. ### Group structures in the wild To further interpret the recovered groups of Section 5.1, we created synthetic experiments where we control the group action that is being performed. To that end, we considered the CIFAR10 dataset and we designed the following experiment * For every image \(i\) in the dataset, we extract a random patch \(\mathbf{x}_{p_{i}}\) of size \(6\times 6\). * We apply a transformation on the extracted patch to get \(\mathbf{y}_{p_{i}}\) and consider the tuple \((\mathbf{x}_{p_{i}},\mathbf{y}_{p_{i}})\) as a training point. The transformations we apply are rotations over a fixed angle and average pooling of a fixed radius2. Footnote 2: We used a variation Ross Wightman’s implementation of median filtering for PyTorch. * We train a single layer linear network with no nonlinearity such that \(\mathbf{\hat{y}}=\mathbf{A}\mathbf{x}\) and train using the MSE loss. The above experimental setup simulates the application of the group action on the filter groups. By successfully learning \(\mathbf{A}\) in this sterile setting where we control the action between successive elements we can interpret the recovered actions of Section 5.1. Figure 2: Effect of the group actions of Figure 1 on identity matrices. The results are presented in Figures 3 and 4 for average pooling and rotating the patches, respectively. We observe that the learned matrices have the "expected" structure: rotation matrices of \(90^{\circ}\) have a familiar grid structure, and the structure of the interpolations aligns with that reported, for example, in (Dehmamy et al., 2021). For average pooling, we again see a diagonal structure that respects the interactions between the pixels. However, we see that both structures differ from the exact observed structure of Figure 0(b), which we discuss below. #### 5.2.1 Compositions of actions While average pooling and rotations might not directly translate to the structures of Figure 1, we see that they do have some correlation. This lead us to design another experiment, where we consider a composition of pooling and rotation3. The resulting actions can be seen in Figure 5. We observe that by composing the two operations, the learned group action has the blocks of median filtering at the location grid defined by the rotation action. Reinterpreting the learned actions of Figure 1 under this new knee, we argue that the Toeplitz structure that we uncovered interpolates rotations and simultaneously applies pooling. Figure 4: Learned group actions when rotating patches using an angle \(\theta\in\{30^{\circ},45^{\circ},60^{\circ},90^{\circ}\}\). Figure 5: Learned group actions when composing rotations and average pooling using a radius \(r\in\{4,5,6\}\) (with a fixed angle \(\theta=60^{\circ}\)). Figure 3: Learned group actions when performing average pooling using a radius \(r\in\{3,4,5,6\}\). ### Dependence on data distribution and task One of our theses was that the element of \(\mathrm{GL}_{n\cdot m}(\mathbb{R})\) that our method learns for each group depends on both the data distribution and the downstream task. We evaluate these hypotheses below. #### 5.3.1 Group actions on MNIST To evaluate the dependence of the group actions on the data distribution, we applied our method on a classification task on MNIST, an image dataset consisting of handwritten digits. In Figure 6 we recovered the same structures as we did on CIFAR10, indicating that data coming from the same distribution (in this case, natural images) result in the same group actions. #### 5.3.2 Reconstruction Finally, to test our hypothesis that group actions depend on the downstream task, we evaluated our method on the task of reconstructing the input. We present learned actions in Figure 7 for both CIFAR10 and MNIST. We find that the actions for both datasets bear similarity, indicating further the dependence on the data distribution, and the emerging structures are distinctly different: contrary to actions for classification, actions for reconstruction exhibit multiple concentrated blocks. ## 6 Conclusion We proposed a method, Linear Group Networks (LGNs) for learning linear groups acting on the weights of neural networks. We showed that matrices in the weight space are unable to learn interesting group actions and propose a formulation where the groups act on the lifted space of the vectorized weights, providing theoretical guarantees. In our experiments, we applied our framework on datasets of natural images for different downstream tasks. We discover several interesting groups whose actions are _skew-symmetric_, _Toeplitz_, or _multi-scale_. We drew analogues between these actions and well-known operations in machine learning, such as average pooling and planar rotations. Our work provides a simple, minimal, and extensible framework for symmetry learning by considering linear groups in the weight space. Importantly, we addressed limitations of prior work, namely the inability of existing architectures to learn group structure from single-task data, and our framework is compatible with existing architectures and pipelines with minimal alterations. Figure 6: Group actions learned on MNIST for classification. Figure 7: Group actions learned on CIFAR and MNIST when trained for reconstruction.
2310.18928
A transfer learning approach with convolutional neural network for Face Mask Detection
Due to the epidemic of the coronavirus (Covid-19) and its rapid spread around the world, the world has faced an enormous crisis. To prevent the spread of the coronavirus, the World Health Organization (WHO) has introduced the use of masks and keeping social distance as the best preventive method. So, developing an automatic monitoring system for detecting facemasks in some crowded places is essential. To do this, we propose a mask recognition system based on transfer learning and Inception v3 architecture. In the proposed method, two datasets are used simultaneously for training including the Simulated Mask Face Dataset (SMFD) and MaskedFace-Net (MFN) This paper tries to increase the accuracy of the proposed system by optimally setting hyper-parameters and accurately designing the fully connected layers. The main advantage of the proposed method is that in addition to masked and unmasked faces, it can also detect cases of incorrect use of mask. Therefore, the proposed method classifies the input face images into three categories. Experimental results show the high accuracy and efficiency of the proposed method; so, this method has achieved an accuracy of 99.47% and 99.33% in training and test data respectively
Abolfazl Younesi, Reza Afrouzian, Yousef Seyfari
2023-10-29T07:38:33Z
http://arxiv.org/abs/2310.18928v1
# A transfer learning approach with convolutional neural network for Face Mask Detection ###### Abstract Due to the epidemic of the coronavirus (Covid-19) and its rapid spread around the world, the world has faced a huge crisis. To prevent the spread of the coronavirus, the World Health Organization (WHO) has introduced the use of masks and keeping social distance as the best preventive method. So, developing an automatic monitoring system for detection of facemask in some crowded places is essential. To do this, we propose a mask recognition system based on transfer learning and Inception v3 architecture. In the proposed method, two datasets are used simultaneously for training including: Simulated Mask Face Dataset (SMFD) and MaskedFace-Net (MFN),this paper tries to increase the accuracy of the proposed system by optimally setting hyper-parameters and accurately designing the fully connected layers. The main advantage of the proposed method is that in addition to masked and unmasked face, it can also detect cases of incorrect use of mask. Therefore, the proposed method classifies the input face images into three categories. Experimental results show the high accuracy and efficiency of the proposed method; so that, this method has achieved to accuracy of 99.47% and 99.33% in training and test data respectively. M 2021 177
2305.07300
Learning Quadruped Locomotion using Bio-Inspired Neural Networks with Intrinsic Rhythmicity
Biological studies reveal that neural circuits located at the spinal cord called central pattern generator (CPG) oscillates and generates rhythmic signals, which are the underlying mechanism responsible for rhythmic locomotion behaviors of animals. Inspired by CPG's capability to naturally generate rhythmic patterns, researchers have attempted to create mathematical models of CPG and utilize them for the locomotion of legged robots. In this paper, we propose a network architecture that incorporates CPGs for rhythmic pattern generation and a multi-layer perceptron (MLP) network for sensory feedback. We also proposed a method that reformulates CPGs into a fully-differentiable stateless network, allowing CPGs and MLP to be jointly trained with gradient-based learning. The results show that our proposed method learned agile and dynamic locomotion policies which are capable of blind traversal over uneven terrain and resist external pushes. Simulation results also show that the learned policies are capable of self-modulating step frequency and step length to adapt to the locomotion velocity.
Chuanyu Yang, Can Pu, Tianqi Wei, Cong Wang, Zhibin Li
2023-05-12T08:10:31Z
http://arxiv.org/abs/2305.07300v1
# Learning Quadruped Locomotion using Bio-Inspired Neural Networks with Intrinsic Rhythmicity ###### Abstract Biological studies reveal that neural circuits located at the spinal cord called central pattern generator (CPG) oscillates and generates rhythmic signals, which are the underlying mechanism responsible for rhythmic locomotion behaviors of animals. Inspired by CPG's capability to naturally generate rhythmic patterns, researchers have attempted to create mathematical models of CPG and utilize them for the locomotion of legged robots. In this paper, we propose a network architecture that incorporates CPGs for rhythmic pattern generation and a multi-layer perceptron (MLP) network for sensory feedback. We also proposed a method that reformulates CPGs into a fully-differentiable stateless network, allowing CPGs and MLP to be jointly trained with gradient-based learning. The results show that our proposed method learned agile and dynamic locomotion policies which are capable of blind traversal over uneven terrain and resist external pushes. Simulation results also show that the learned policies are capable of self-modulating step frequency and step length to adapt to the locomotion velocity. ## I Introduction Animals are able to adapt their locomotion gait pattern to suit the locomotion velocity and ground condition. Efforts have been put into discovering the underlying mechanism of animal locomotion, and have obtained evidence that legged locomotion is rhythmic in nature. Findings have revealed evidence of special neurons called central pattern generators in the animal spinal cord. CPGs are a series of coupled oscillatory neurons capable of producing rhythmic signals internally without external sensory input. The rhythmic signals produced by CPGs are necessary for activities that involve periodic movement, such as breathing, walking, running, swimming, flying, etc. [1, 2]. In recent years, there has been significant progress in using deep reinforcement learning (DRL) to train artificial neural networks for legged locomotion. Multi-expert neural networks can be designed to perform various different locomotion tasks [3]. Robust control policy has also been trained to successfully traverse over extreme terrain in the wild [4]. The neural networks from both works rely on an external periodic phase input to produce rhythmic motor patterns. Apart from a single global phase, multiple local phases can be provided, e.g. providing four phases as input to match the four individual legs of the quadruped [5]. Instead of providing external periodic phase input, there have been attempts in designing network structures capable of self-generating phases. One approach is to add an additional phase increment output to the policy. The phase increment is added to the current phase and is used as the phase for the next timestep in a bootstrap manner [6, 7, 4]. To reproduce the agile locomotion behaviors of animals in legged robots, researchers have looked into animals for inspiration. Inspired by findings of CPGs within the animal nervous system, there have also been attempts in utilizing the intrinsic rhythmicity of CPGs to generate rhythmic motor patterns for locomotion controllers in robotics, eliminating the need for external phase input [8, 9, 10]. This work aims to utilize the natural rhythmicity of CPGs to generate agile and dynamic locomotion behaviors for quadruped robots. While CPGs by themselves are capable of generating open-loop rhythmic signals, sensory feedback has to be integrated to enable the CPGs to react to external environment. We propose a framework that combines MLP networks and CPGs, where the CPGs are responsible for generating rhythmic patterns, and the MLP receives sensory information and provides feedback to modulate the CPGs' behavior. Our proposed framework reformulates CPGs by exposing the internal states as inputs and outputs of the network, essentially turning CPGs into a fully-differentiable stateless network. The parameters of the MLP and CPGs are optimized in conjunction via DRL. The contributions of this paper are: * We proposed a network architecture that combines CPGs and MLP network to generate rhythmic motions intrinsically without relying on external phase input. We name the network architecture as MLP-CPG. * We proposed an approach that reformulates CPGs into Fig. 1: Depiction of the agile and dynamic locomotion learned by the MLP-CPG network architecture. fully-differentiable networks. The CPG parameters and MLP parameters within the MLP-CPG network architecture can be jointly optimized with DRL. * We implemented the network architecture on a simulated quadruped robot and demonstrated the policy's capability to track user targets, and the robustness to environmental uncertainties. * The proposed network architecture is interpretable. Locomotion characteristics such as step frequency, step length, and gait pattern can be inferred from the CPG parameters. ## II Related Work ### _CPG-Based Locomotion for Legged Robots_ CPGs have gained interest within the robotics field due to their oscillatory and rhythmic nature. To study the rhythmic mechanism of biological CPGs, researchers have proposed different CPG models with varying levels of complexity, from detailed biophysical models, connectionist models, to abstract models based on mathematical oscillators [2, 11]. Researchers have attempted to leverage the natural rhythmic behaviors of CPGs by incorporating CPGs into the controller to achieve animal-like locomotion for all kinds of legged robots, including bipeds, quadrupeds, and hexapods. Various abstract models of mathematical oscillators such as SO(2) oscillator, Matsuoka oscillator, and Hopf oscillator have been employed within the locomotion controller for different robots [12, 13, 14]. ### _Learning CPG-Based Controllers with DRL_ DRL has proven to be effective in learning robust and complex locomotion skills for legged robots in simulation and real world. There are many works that have combined CPGs together with MLP networks and trained using the DRL paradigm. However, due to the intrinsic recurrent nature of CPG networks, back-propagation through time (BPTT) is required to obtain the parameters of CPGs while trained with gradient-based learning, which is computationally more expensive [15, 10]. One approach of dealing with the recurrent nature of CPGs is to treat the CPG controller as part of the environment dynamics. Such approach is referred to as CPG-Actor-Critic, where the CPG controller, the robot, and the environment are treated as a single dynamic system called CPG-coupled system. The action space of the policy is the CPG parameters. The policy controls the robot by adjusting the CPG parameters of the CPG-coupled system. [8, 9, 10]. Another approach of dealing with the recurrent nature of CPGs is to optimize the parameters of CPGs and MLP network separately. The parameters of the neural network can be optimized with DRL, while the parameters of CPG are optimized using non-gradient based approaches such as evolutionary strategy (ES) [16], genetic algorithm (GA) [17], or a biologically plausible learning rule [18, 19]. Wang et al. proposed a hierarchical control structure with a high-level neural network and a low-level CPG controller. The high-level network generates latent variables that are fed into the CPGs to regulate their behaviors. The CPG controller is optimized using GA, while the neural network is trained using DRL [17]. Shi et al. used ES to train a CPG-based foot trajectory generator. A separate neural network is trained using DRL to generate residual joint angles that correct the generated foot trajectory [16]. Campanaro et al. proposed an approach that dealt with the recurrent properties of CPGs by reformulating the CPG into a fully-differentiable stateless network, and thus allowing end-to-end training of CPGs alongside MLP. Campanaro et. al. have only validated the approach on a simple example of a single two degrees-of-freedom (DoF) hopping leg [15]. We extended upon the idea of reformulating CPG network into a stateless network and proposed our MLP-CPG framework. Furthermore, we have successfully implemented on a 12-DOF simulated quadruped robot. ## III Method ### _Robot Platform and Simulation setup_ The Jueying quadruped robot is used as the robot platform (Table I). Pybullet is chosen as the physics engine for the simulation environment. ### _CPG Controller_ The CPGs within this work are modelled using Hopf oscillators [14]. \[\begin{split}\dot{\theta}_{i}^{t}&=2\pi f^{t}+\sum _{j}\epsilon_{ij}sin(\theta_{j}^{t-1}-\theta_{i}^{t-1}-\phi_{ij})+\xi_{i}^{t} \\ \dot{r}_{i}^{t}&=\gamma r_{i}^{t-1}\big{(}(\eta_{i} +\kappa_{i}^{t})^{2}-(r_{i}^{t-1})^{2}\big{)}\\ \psi_{i}^{t}&=r_{i}^{t}cos(\theta_{i}^{t})+\chi_{i} ^{t}+o_{i},\end{split} \tag{1}\] w Fig. 2: An example consisting of 2 coupled CPG oscillators. The values within \(\epsilon_{ij}\), \(\gamma\), and \(dt\) are set to 6.0, 5.0, and 0.01. The values within \(\eta,\chi,o,\phi\) are set to 0. (A) and (B) illustrate how the phase and amplitude of the CPG can be adjusted by feedback component \(\xi\) and \(\kappa\). where \(\theta_{i}^{t}\) and \(r_{i}^{t}\) represent the phase and amplitude of the i-th oscillator at timestep \(t\), \(\dot{\theta}_{i}^{t}\) and \(\dot{r}_{i}^{t}\) are their corresponding derivative, \(\epsilon_{ij}\) and \(\phi_{ij}\) are the coupling weight and phase bias between i-th and j-th oscillator, \(\eta_{i}\) is the desired amplitude, \(o_{i}\) is a constant offset of the oscillation setpoint, \(\gamma\) is a constant that determines the rising time for \(r\), \(\psi_{i}^{t}\) represents the output signal. Finally, \(\kappa_{i}^{t}\), \(\chi_{i}^{t}\), \(\xi_{i}^{t}\), \(f^{t}\) are the feedback components, where \(\kappa_{i}^{t}\) adjusts the amplitude, \(\xi_{i}^{t}\) adjusts the phase, \(\chi_{i}^{t}\) adjusts the oscillation setpoint, \(f^{t}\) adjusts the frequency of the oscillator at timestep \(t\). The phase and amplitude \(\theta_{i}^{t}\) and \(r_{i}^{t}\) are obtained from their derivative values \(\dot{\theta}_{i}^{t}\) and \(\dot{r_{i}^{t}}\) using the following equation. \[\theta_{i}^{t}=\theta_{i}^{t-1}+\dot{\theta}_{i}^{t}dt,\ r_{i}^{t}=r_{i}^{t-1}+ \dot{r}_{i}^{t}dt, \tag{2}\] where \(dt\) is the duration of the timestep. ### _Reformulating Hidden States in CPGs_ Within Recurrent Neural Networks (RNN), the hidden states of the previous timestep has to be passed to the current timestep and combined with the input of the current timestep to compute the current output. RNN requires BPTT to be trained. CPGs can be viewed as a type of RNN, as they require hidden states to propagate information through time. The transition between consecutive hidden states of a CPG is determined by eq (1) and eq (2). We dealt with the recurrent nature of CPGs by proposing a reformulation approach that exposes the hidden states through network inputs and outputs. The previous hidden states will be passed as network inputs, and the current hidden states will be passed as network outputs. With our proposed reformulation approach, the CPG network is essentially transformed into a fully-differentiable stateless feedforward network (Fig. 3C). In contrast to previous work where the parameters of the CPG controllers and MLP network are optimized with separate algorithms, our reformulated CPG network is differentiable and can be optimized jointly with MLP network within the same DRL paradigm without BPTT [17, 16]. ### _Network Architecture_ The MLP-CPG network consists of two separate modules, one rhythmic module responsible for generating rhythmic signals, and another non-linear feedback module responsible for processing sensory feedback (Fig. 4). #### Iv-D1 Rhythmic module The rhythmic module contains 12 CPG neurons, each neuron represents a joint. The values of the CPG parameters are shown in Table II. #### Iv-D2 Feedback module The feedback module is an MLP network with 2 hidden layers of size 256 with \(\tanh\) activation function. The MLP receives state inputs and regulates the CPG network via feedback components \(f\), \(\mathbf{\kappa}\), \(\mathbf{\xi}\), \(\mathbf{\chi}\). The MLP also outputs the covariance of the stochastic policy \(\mathbf{\sigma}\). The output of the MLP-CPG network \(\mathbf{\psi}\) is bounded within \((-1,1)\) using \(\tanh\), and re-scaled to the corresponding joint limits to be used as the target joint angles. ### _Training Setup_ #### Iv-E1 Soft Actor Critic We select Soft Actor Critic (SAC) as the DRL algorithm for the training of our policy. SAC learns Fig. 4: Control framework overview. The MLP-CPG network generates target joint positions at 25Hz. The PD controller functions at 1000Hz and converts the joint angles to joint torques. Fig. 3: Illustration of RNN and CPGs. (A) Unfolded RNN. (B) Unfolded CPGs. (C) Our reformulation approach transforms CPGs into stateless networks by exposing the hidden states as network inputs and outputs. a policy by maximizing the expected return and the entropy. The optimization objective can be expressed as follows: \[J_{SAC}(\pi)=\sum_{t=0}^{T}\mathbb{E}_{(s_{t},a_{t})\sim\rho_{\pi}}[r(s_{t},a_{t}) +\alpha H(\pi(\cdot|s_{t}))] \tag{3}\] where \(\pi\) is the policy, \(\rho_{\pi}\) is the sample distribution, \(r\) is the reward, \(s_{t}\) and \(a_{t}\) are the state and action at time step \(t\) within the sample distribution, \(\alpha\) is the temperature parameter, and \(H(\pi)\) is the entropy. The temperature parameter determines the stochasticity of the policy and is tuned automatically during training to balance exploration and exploitation. The hyperparameters can be seen in Table III #### Iii-B2 Generating smooth action We introduce temporal and spatial regularization terms to encourage the learning of smoother actions [20]. We only regularize the setpoint feedback component \(\chi\) of the network output. \[L_{T}=\left\|\chi(s_{t})-\chi(s_{t+1})\right\|_{2}^{2},L_{S}=\left\|\chi(s_{t} )-\chi(\hat{s}_{t})\right\|_{2}^{2} \tag{4}\] The spatial regularization loss minimizes the difference between the action generated under observed state \(s_{t}\) and perturbed state \(\hat{s}_{t}\sim\mathcal{N}(s_{t},\delta)\), where \(\delta\) is the standard deviation. The temporal regularization loss minimizes the difference between the action under current state \(s_{t}\) and the next state \(s_{t+1}\). #### Iii-B3 Step frequency Multiple researches have shown that animals adjust their step frequency for different locomotion velocities [21, 22]. Prior knowledge of the step frequency can be embedded into the controller. Lee et al. manually designed a state machine that switches between different base frequencies depending on user velocity command [4]. We provided prior knowledge of step frequency using the curve function \(f_{ref}=a+b\ln v\) calculated from real animal data, where \(f_{ref}\) is the step frequency, \(v\) is the locomotion velocity, \(a=1.314\) and \(b=0.762\) are the parameters [21]. We fitted a new curve that passes through the origin, as we want zero frequency at zero velocity (Fig. 5): \[\begin{split} f_{ref}&=a+b\cdot\ln{(v+c)},a=1.066,b= 0.876,c=0.289\\ v&=(\hat{v}_{x}^{2}+\hat{v}_{y}^{2})^{0.5}\end{split} \tag{5}\] where \(\hat{v}_{x}\) and \(\hat{v}_{y}\) are the target forward and lateral velocity, respectively. The step frequency \(f\) is bounded within \([0,3]\). We introduce loss function \(L_{f}\) to encourage the MLP network to track the reference frequency \(f_{ref}\). \[L_{f}=\left\|f(s_{t})-f_{ref}\right\|_{2}^{2} \tag{6}\] The frequency loss \(L_{f}\), the temporal regularization loss \(L_{T}\), and spatial regularization loss \(L_{S}\) are added to the loss function of the SAC \(L_{SAC}=-J_{SAC}\). \[L=L_{SAC}+\lambda_{T}L_{T}+\lambda_{S}L_{S}+\lambda_{f}L_{f}. \tag{7}\] Fig. 5: Red dashed curve is obtained from animal data [21]. Green solid curve is obtained by fitting a new curve that passes through the origin. ### _Reward Design_ Radial basis function (RBF) kernels are used in the reward design. The output range of RBF is bounded within \((0,1)\). The formulation of the RBF kernel is shown as follows: \[K(x,\widehat{x},c)=\exp\left(c(\hat{x}-x)^{2}\right) \tag{8}\] where \(x\) is the physical quantity for the evaluation, \(\hat{x}\) is the desired value, and \(c\) is the parameter that controls the width of the RBF. The reward is the weighted sum of individual reward terms, each governing a different physical aspect (Table IV and Table V). The Swing and stance foot reward penalizes the movement of the stance foot close to the ground while encouraging the movement of the swing foot far from the ground. The body placement reward encourages the Center of Mass (COM) of the robot to be placed close to the center of the support polygon. The foot placement reward encourages the feet to be placed close beneath the hip joint. ### _State Space and Action Space_ The state space consists of the observations from the environment \(S_{O}\), the internal states of the CPGs \(S_{I}\), and the goal states provided by the user \(S_{G}\). The robot observation states consist of base linear velocity in robot heading frame \(\mathbf{v}_{xyz}\), base angular velocity \(\mathbf{\omega}_{rpy}\), orientation vector \(\mathbf{\varphi}_{b}\), joint position \(\mathbf{q}\), and joint velocity \(\hat{\mathbf{q}}\). The goal states consist of the target forward velocity \(\hat{v}_{x}\), target lateral velocity \(\hat{v}_{y}\), and the target yaw turning rate \(\hat{\omega}_{z}\). The internal states consist of the amplitude \(\mathbf{r}\) and phase \(\mathbf{\theta}\) of the 12 CPG oscillators. A mod operation is used to bound the phase within the range \([0,2\pi]\). The observation states \(S_{O}\) are filtered by a low-pass Butterworth filter with a cut-off frequency of 10\(Hz\). The action space \(a_{t}\) contains the target joint angles \(\hat{q}\). A low-pass Butterworth filter with a cut-off frequency of 5\(Hz\) is applied to the target joint angles to encourage smooth actions. PD controllers are used to calculate joint torques \(\tau\) from the target joint angles \(\hat{q}\), measured joint angles \(q\), and measured joint velocities \(\hat{q}\) using the following equation \(\tau=K_{p}(\hat{q}-q)+K_{d}(0-\hat{q})\), where \(K_{p}=300\), \(k_{d}=10\). ### _Exploration Setup_ #### Iii-H1 Initialization The initial forward velocity, lateral velocity, and yaw rate are sampled from \(U(-1,5)\), \(U(-1,1)\), and \(U(-\pi,\pi)\) respectively. The initial joints angles are sampled from \(\mathcal{N}(\tilde{q},\frac{\pi}{4})\), where \(\tilde{q}\) is the joint angle during nominal standing posture. The CPG amplitude and phase are initialized from \(U(0,\frac{\pi}{4})\) and \(U(0,2\pi)\), respectively. The target forward velocity, target lateral velocity, and target turning rate are initialized from \(U(-1,5)\), \(U(-1,1)\), \(U(\frac{\pi}{2},\frac{\pi}{2})\), respectively. #### Iii-H2 Early termination We terminate and restart the training episode when the robot reaches undesirable fail states. We define the fail state as the state where the body of the robot comes into contact with the ground or when the robot has a large body tilt. We also set a time limit of 10\(s\) to terminate the episode early. ## IV Results ### _Effect of Step Frequency_ Step frequency modulation behaviors have been observed within animals, where the step frequency increases alongside the locomotion velocity. We conduct a comparison study to investigate the effect of step frequency modulation on locomotion performance by comparing the following configurations: 1) _Fixed 1.5Hz_: The intrinsic frequency of the 12 CPGs are fixed to 1.5Hz. 2) _Fixed 3.0Hz_: The intrinsic frequency of the 12 CPGs are fixed to 3Hz. 2) _Adaptive Curve_: Prior knowledge of frequency is provided to encourage the policy to track the reference frequency calculated from eq (5). 3) _Adaptive Free_: No prior knowledge of frequency is provided. #### Iv-B1 Locomotion velocity Policies from all four configurations are able to perform successful locomotion while tracking user commanded velocity (Fig. 6A). However, the policy from _Fixed 1.5Hz_ configuration fails to track 4m/s target velocity, which might be due to the relatively low step frequency (Fig. 6D1). Figure 6D2 shows the frequency modulation signal \(f\) provided by the MLP network. Both policies from _Adaptive Curve_ and _Adaptive Free_ configurations learned to increase their step frequency to reach higher locomotion velocity (Fig. 6C). While frequency modulation behavior naturally emerges without providing prior knowledge, providing prior knowledge of step frequency through a loss function leads to a smoother frequency modulation behavior. #### Iv-B2 Energy efficiency We utilize Cost of Transport (CoT) to measure the energy efficiency of the policies under different locomotion velocities. After comparing the policies from four configurations, we observed that policies with fixed frequency exhibit significantly higher CoT within the low-velocity region compared to policies capable of self-modulating frequency (Fig. 6B). This is due to unnecessarily high-frequency stepping. #### Iv-B3 Step length Animals adjust their step length to regulate their locomotion velocity [22]. We observed similar emergent behavior of step length modulation among all four policies. All policies have learned to increase the step length to reach higher locomotion velocities (Fig. 7A). Policies modulate the step length via the adjustments of the amplitude of the joint CPGs. The amplitude of the hip and knee CPG oscillators within all policies changes accordingly with locomotion velocity (Fig. 6D3 & D4). The change in amplitude will have a direct impact on the step length as can be seen in Fig. 7B and Fig. 7C, where larger CPG oscillation amplitude results in a larger step length. The step length for policy _Fixed 1.5Hz_ is higher compared to the other three policies to compensate for the relatively lower step frequency. ### _Interpretability of MLP-CPG Architecture_ A side benefit of our MLP-CPG network architecture is the additional interpretability compared to vanilla neural networks. The frequency, amplitude, and phase of the CPG neurons are parameters that can be directly retrieved from the MLP-CPG network. As can be seen from Fig. 7 and Fig. 8, the frequency, amplitude, and phase of the CPGs correlate with the frequency of the neurons. The frequency of the neurons is \(2. with step frequency, step length, and foot contact pattern, which are three important aspects of legged locomotion. By analyzing the values of the frequency, amplitude, and phase of the CPG neurons, we can easily interpret the locomotion characteristics of the robot. ### _Performance Benchmark_ #### Iv-C1 Target following We design 4 sets of trajectories with varying difficulties for the robot to follow (Fig. 9). The robot is tasked to follow the trajectory by tracking a moving target. The relative position of the moving target is translated into velocity command for the robot. The policy from _Adaptive Curve_ is evaluated. Given the target position and robot base position, we calculate the velocity commands as follows: \[\hat{v}_{x}=-x_{target}^{base},\hat{v}_{y}=-y_{target}^{base},\hat{\omega}_{ yaw}=-\arctan(\frac{y_{target}^{base}}{x_{target}^{base}}), \tag{9}\] where \(x_{target}^{base}\) is the x coordinate of the target in robot base frame, and \(y_{target}^{base}\) is the y coordinate of the target in robot base frame. The velocity targets are bounded within \([-1,4]\)\(m/s\), \([-0.75,0.75]\)\(m/s\), \([-1.0,1.0]\)\(rad/s\) for forward velocity, lateral velocity, and yaw angular rate. The learned _Adaptive Curve_ policy is able to follow all four trajectories. ### _Robustness Tests_ We design four sets of test scenarios to evaluate the robustness of the learned policies (Fig. 10). 1) Blind traversal over Uneven terrain. The uneven terrain consists of small bumps with height ranging from 0\(m\) to 0.1\(m\). 2) Persistent perturbation. External perturbation forces are applied to the robot every 4s through the impact of small cubes with mass of 5\(kg\). 3) Blind traversal over stairs. The stair consists of steps with height of 0.05m. 4) Carrying external load. A load with mass of 20\(kg\) (50% of the robot's own mass) is placed on the robot. Policies from all four training configurations are able to traverse over uneven terrain and stairs, carry external load, and resist external perturbations (See accompanying video). The policies exhibit highly dynamic motions while reacting to external uncertainties in the environment. Note Fig. 10: Overlaid snapshots of the _Adaptive Curve_ policy. (A) Uneven terrain. (B) External disturbance. (C) Stairs. (D) External load. Fig. 9: (A1-A4) Trajectory following performance of policy _Adaptive Curve_. (A1) Square Wave. (A2) Cosine Wave. (A3) Eight Curve. (A4) Four-leaved Clover Curve. (B1-B4) The velocity tracking performance while following trajectory A1-A4. that the policies are trained on flat ground and encountered no perturbations during the training phase. ## V Discussion and Future work While our work demonstrated robust locomotion in simulation, it has not yet been implemented on a real robot. For future work, we plan to transfer the policy to a real robot system. Additionally, high-speed locomotion on real robot systems is challenging. Even though our policy is capable of achieving velocities up to 4m/s in simulation while satisfying motor constraints, having the joint torques and velocities constantly reaching the motor limits will inevitably cause a lot of stress and also overheat the motors. Mechanical stress and motor overheating need to be considered during sim-to-real transfer. This paper has only focused on achieving rhythmic motor task of locomotion for quadruped robots. For future work, we will investigate the feasibility of using our proposed MLP-CPG network to achieve multi-tasking of both rhythmic motor tasks such as locomotion and non-rhythmic motor tasks such as fall recovery. ## VI Conclusion In this paper, we proposed a bio-inspired network architecture called MLP-CPG that utilizes the intrinsic rhythmicity of CPGs to generate rhythmic motor patterns for locomotion without relying on external phase input. We proposed a reformulation approach that transforms CPGs into stateless networks by exposing the internal states. With our approach, the parameters of CPGs can be optimized jointly with the MLP network using DRL. Our MLP-CPG has the advantage of interpretability. Locomotion characteristics such as step frequency, step length, gait pattern of the robot can be inferred by analyzing the values of the frequency, amplitude, and phase of the CPGs. Our MLP-CPG network demonstrates emergent behaviors of step frequency and step length modulation. We observed that the learned policies increase the step frequency and step length accordingly as the locomotion velocity increases, demonstrating that the policy can actively alter locomotion patterns. The learned policy is not only capable of successfully performing the task of target following, but also capable of robustly traversing over uneven terrain and stairs, carrying external load, and resisting external perturbations.
2303.09935
Alternate Loss Functions for Classification and Robust Regression Can Improve the Accuracy of Artificial Neural Networks
All machine learning algorithms use a loss, cost, utility or reward function to encode the learning objective and oversee the learning process. This function that supervises learning is a frequently unrecognized hyperparameter that determines how incorrect outputs are penalized and can be tuned to improve performance. This paper shows that training speed and final accuracy of neural networks can significantly depend on the loss function used to train neural networks. In particular derivative values can be significantly different with different loss functions leading to significantly different performance after gradient descent based Backpropagation (BP) training. This paper explores the effect on performance of using new loss functions that are also convex but penalize errors differently compared to the popular Cross-entropy loss. Two new classification loss functions that significantly improve performance on a wide variety of benchmark tasks are proposed. A new loss function call smooth absolute error that outperforms the Squared error, Huber and Log-Cosh losses on datasets with significantly many outliers is proposed. This smooth absolute error loss function is infinitely differentiable and more closely approximates the absolute error loss compared to the Huber and Log-Cosh losses used for robust regression.
Mathew Mithra Noel, Arindam Banerjee, Geraldine Bessie Amali D, Venkataraman Muthiah-Nakarajan
2023-03-17T12:52:06Z
http://arxiv.org/abs/2303.09935v2
# Alternate Loss Functions Can Improve the Performance of Artificial Neural Networks ###### Abstract All machine learning algorithms use a loss, cost, utility or reward function to encode the learning objective and oversee the learning process. This function that supervises learning is a frequently unrecognized hyperparameter that determines how incorrect outputs are penalized and can be tuned to improve performance. This paper shows that training speed and final accuracy of neural networks can significantly depend on the loss function used to train neural networks. In particular derivative values can be significantly different with different loss functions leading to significantly different performance after gradient descent based Backpropagation (BP) training. This paper explores the effect on performance of new loss functions that are more "liberal" or "strict" compared to the popular Cross-entropy loss in penalizing incorrect outputs. Eight new loss functions are proposed and a comparison of performance with different loss functions is presented. The new loss functions presented in this paper are shown to outperform Cross-entropy loss on computer vision and NLP benchmarks. keywords: Loss Function, Artificial Neural Network, Convolutional Neural Network, Deep Learning + Footnote †: journal: journal ## 1 Introduction Artificial Neural Networks (ANNs) are a class of universal function approximators that learn a parametrized approximation to the target function through a Gradient Descent (GD) based optimization process [1]. Thus learning in ANNs is reduced to the problem of learning a finite set of real parameters namely the weights and biases in the ANN model. Good parameters that result in a good approximation to the target function are computed by minimizing a loss (also known as cost) function that measures the difference average error between ANN outputs and targets. An important aspect of the loss function is that it distills the performance of a ANN model over the entire dataset into a single scalar value [2]. Thus the loss function is a single continuously differentiable real-valued function of all the parameters of the ANN model. The loss function must be continuously differentiable for GD to work. It is reasonable to choose a loss function inspired by statistical estimation theory to compute the most probable parameters given the dataset. Historically the Mean Square Error (MSE) and Cross-entropy from Maximum Likelihood Estimation theory (MLE) are almost universally used to train ANNs. MLE theory assigns to unknown parameters values that maximize the probability of observing the experimental data [3]. The logarithm of the probability of observing the data is often used for convenience and results in the Cross-entropy loss. Thus MLE estimation proceed by maximizing the logarithm of the probability of the observed data as a function of the unknown parameters. MSE is used for regression problems where continuous real values have to be predicted and Cross-entropy is used for classification problems where the predicted outputs are discrete. Both MSE and Cross-entropy loss functions are derived from MLE theory as already described. MSE is a maximum-likelihood estimate when the model is linear and the noise is Gaussian. However it is frequently used in practice even when these assumptions cannot be justified. For classification problems both MSE and Cross-entropy losses can be used, but learning is generally faster with Cross-entropy as the gradient is larger due to the log function in Cross-entropy loss. ### Mathematical Formalism Consider a dataset consisting of N training examples: \(D=\{x^{i},y^{i}:i=1..N\}\). Where \(x\in R^{m},y\in R^{n}\) in general for some natural numbers m and n. In the following we motivate and discuss possible loss functions for binary classification problems. For binary classification problems \(y\in\{0,1\}\). For the binary classification problem, the final layer consists of a single sigmoidal neuron which outputs the probability \(P(y=1|x)\). This probability depends on all the weights and biases in the ANN and is hence denoted by \(h_{\theta}(x)\). To compute the unknown parameters using maximum likelihood estimation theory the probability of the data given the parameters should be first computed. Assuming that each training pair in the dataset is independent: \[P(D|\theta)=\prod_{i=1}^{N}P(x^{i},y^{i};\theta)\] \(\prod_{i=1}^{N}P(x^{i},y^{i};\theta)=\prod_{i=1}^{N}P(y^{i}|x^{i};\theta)P(x^{i})\) by the definition of conditional probability. Since \(P(x^{i})\) is independent of \(\theta\), maximizing \(P(D|\theta)\) is same as maximizing \(\log(\prod_{i=1}^{N}P(y^{i}|x^{i};\theta))\). Thus the log-likelihood function to be maximized is \[\log(\prod_{i=1}^{N}P(y^{i}|x^{i};\theta))=\sum_{i=1}^{N}P(y^{i}|x^{i};\theta)\] But \(P(y^{i}|x^{i};\theta)=h_{\theta}(x^{i})^{y^{i}}(1-h_{\theta}(x^{i}))^{1-y^{i}}\). Instead of maximizing the log-likelihood, the negative log-likelihood can be minimized. This negative log-likelihood after simplification is the loss \[L(\theta)=-\sum_{i=1}^{N}(y^{i}\log(h_{\theta}(x^{i}))+(1-y^{i})\log(1-h_{ \theta}(x^{i})))\] Scaling with any positive number does not change the minimum, so for numerical convenience we can divide by N to obtain \[L(\theta)=-\frac{1}{N}\sum_{i=1}^{N}(y^{i}\log(h_{\theta}(x^{i}))+(1-y^{i}) \log(1-h_{\theta}(x^{i}))))\] \[L(\theta)=-\frac{1}{N}(\sum_{i=1}^{N}y^{i}\log(\hat{y}^{i})+(1-y^{i})\log(1- \hat{y}^{i})) \tag{1}\] For notational convenience \(h_{\theta}(x)\) which is an approximation to the random variable y is denoted by \(\hat{y}\). The above binary Cross-entropy loss for a single training pair \((x,y)\) is \[l(y,\hat{y})=-[y\log(\hat{y})+(1-y)\log(1-\hat{y})] \tag{2}\] The target assumes exactly one of two possible values namely 0 or 1, so only one term in Eq. 2 is nonzero. When \(y=1\), \(l(y,\hat{y})=-\log(\hat{y})\) and when \(y=0\), \(l(y,\hat{y})=-\log(1-\hat{y})\). Figures 1 and 2 show the variation of BCE loss with final ANN output \(\hat{y}\) when the target y is 0 and 1 respectively. It is observed that the loss is exactly zero when target is equal to the output. Further the loss is differentiable, convex and tends to infinity as the output approaches the incorrect target value. Convexity is desirable Figure 1: Plot of Binary Cross-entropy loss when the target y = 0. Figure 2: Plot of Binary Cross-entropy loss when the target y = 1. to avoid introducing unnecessary local minima and differentiability is required for gradient based BP learning. In the following we propose new loss functions with the following desirable attributes: * \(l(y,\hat{y})=0\) and \(\hat{y}=y\) * \(l(0,\hat{y})\) and \(l(1,\hat{y})\) are convex and differentiable functions of \(\hat{y}\) * \(l(0,0)=l(1,1)=0\) * \(\lim_{\hat{y}\to 1}l(0,\hat{y})=\infty\) and \(\lim_{\hat{y}\to 0}l(1,\hat{y})=\infty\) In the above \(0<\hat{y}<1\) since \(\hat{y}\) is the probability \(P(y=1|x)\). For multiclass classification problems \(\hat{y}\) will be a vector with as many dimensions as classes. For C classes, the final layer will a softmax layer with C neurons and the loss function is the sum of the loss functions for each output: \(-\frac{1}{N}\sum_{j=1}^{C}\sum_{i=1}^{N}y_{j}^{i}\log(\hat{y_{j}}^{i})+(1-y_{j }^{i})\log(1-\hat{y_{j}}^{i})\). To compare different loss functions we introduce the following definition. **Definition**: Consider two loss functions \(l_{1}\) and \(l_{2}\) defined for a single (output,target) pair \((\hat{y},y)\), where \(\hat{y}\) and \(y\) are vectors with C components. We define \(l_{1}\) to be stricter than \(l_{2}\) for some set of values of \(\hat{y}\) and \(y\) if \(\nabla l_{1}(\hat{y},y)\geq\nabla l_{2}(\hat{y},y)\). In the above definition the inequality between gradient vectors is to be interpreted componentwise. We define \(l_{2}\) to be more lenient than \(l_{1}\), if \(l_{1}\) is stricter than \(l_{2}\). In the following we introduce alternate loss functions that penalize network errors differently than BCE and explore the effect on performance of using stricter and lenient loss functions. The paper attempts to address a fundamental question pertaining to ML algorithms on whether stricter penalties lead to improved performance for the same dataset or whether stricter penalties beyond a certain point lead to reduced performance. The main contributions of this work are: * Eight new loss functions that provide better performance than Cross-entropy on benchmarks are proposed * The effects of using "stricter" and "lenient" loss functions compared to Cross-entropy is explored * The distinguishing features and advantages of different loss functions are discussed Hyperparameter tuning is a trick that can be used to improve the performance of ANNs and does not require extra data. However tuning hyperparameters require more computational resources. An alternative is to use state-of-the-art models that are known to provide better performance apriori. For example new activation functions that are known to perform better than popular activation functions like ReLu can be used [4], [5]. ## 2 New loss functions Next we explore alternate loss functions that satisfy properties listed in 1.1. Considering the binary classification problem and assuming that \(0<\hat{y}<1\) and \(y\in\{0,1\}\), the following new loss functions are proposed: * **M Loss:**\(M(y,\hat{y})=y\left(\frac{1}{\hat{y}}-1\right)\) * **L Loss:**\(L(y,\hat{y})=\frac{y}{\sqrt{1-(1-\hat{y})^{2}}}-1\) * **Parametrized M Loss:**\(M_{\alpha}(y,\hat{y})=y\left(\frac{1}{\hat{y}^{\alpha}}-1\right)\) * **Tan Loss:**\(T(y,\hat{y})=y\tan(\frac{\pi(1-\hat{y})}{2})\) * **Parametrized L Loss:**\(L_{\alpha}(y,\hat{y})=\frac{y}{\sqrt{1-(1-\hat{y})^{\alpha}}}-1\) * **Two parameter L Loss:**\(L_{\alpha,\beta}(y,\hat{y})=\frac{y}{\left(1-(1-\hat{y})^{\alpha}\right)^{ \beta}}-1\) * **Parametrized Log Loss:**\(-y\log_{\alpha}(\hat{y})\) In the above the loss is zero if y=0 and the ANN is penalized for errors only when y=1. Modified versions of the above losses that penalize the ANN for errors even when y = 0 are given below. **Full loss functions:** * **M Loss:**\(M(y,\hat{y})=\frac{y}{\hat{y}}+\frac{1-y}{1-\hat{y}}-1\) * **L Loss:**\(L(y,\hat{y})=\frac{y}{\sqrt{1-(1-\hat{y})^{2}}}+\frac{1-y}{\sqrt{1-\hat{y}^{2}}}-1\) * **Tan Loss:**\(T(y,\hat{y})=y\tan(\frac{\pi(1-\hat{y})}{2})+(1-y)\tan(\frac{\pi\hat{y}}{2})\) * **Sec Loss:**\(S(y,\hat{y})=y\csc(\frac{\pi\hat{y}}{2})+(1-y)\sec(\frac{\pi\hat{y}}{2})-1\) * **Parametrized M Loss:**\(M_{\alpha}(y,\hat{y})=\frac{y}{\hat{y}^{\alpha}}+\frac{1-y}{(1-\hat{y})^{ \alpha}}-1\) * **Parametrized L Loss:**\(L_{\alpha}(y,\hat{y})=\frac{y}{\sqrt{1-(1-\hat{y})^{\alpha}}}+\frac{1-y}{ \sqrt{1-\hat{y}^{\alpha}}}-1\) * **Two parameter L Loss:**\(L_{\alpha,\beta}(y,\hat{y})=\frac{y}{(1-(1-\hat{y})^{\alpha})^{\beta}}+ \frac{1-y}{(1-\hat{y}^{\alpha})^{\beta}}-1\) * **Parametrized Cross-entropy Loss:**\(-(y\log_{\alpha}(\hat{y})+(1-y)\log_{\alpha}(1-\hat{y}))\) In the above definitions of new loss functions the constant factor of -1 can be safely ignored since it does not change the derivative of the loss. This bias of -1 has been included only to fix the loss value to be zero when the output is equal to the target and is optional. Figure 2 shows the difference between Cross-entropy and other loss functions proposed in this paper. To apply the above loss functions to multiclass classification problems, the losses for each output are added together. In particular if \(l(y_{j}^{i},\hat{y}_{j}^{i})\) is the loss for the jth output and ith training pair, the overall loss is \(\frac{1}{N}\sum_{j=1}^{C}\sum_{i=1}^{N}l(y_{j}^{i},\hat{y}_{j}^{i})\) where N is the size of the mini-batch for mini-batch gradient descent. ## 3 Comparison of performance on benchmark datasets We tested both versions of the M-loss and the L-loss with deep neural networks on different benchmark datasets. We compared the results with the same experiments performed with cross-entropy loss too. We tested these losses on a VGG19 model with Imagenette and CIFAR10 datasets. The Adam optimizer with learning rate of 1e-5 was used for training the model. The model was trained on a Google Colab environment with 50 epochs and 100 steps per epoch. We compared the results among five loss functions - i) Cross Entropy loss, ii) L-loss, iii) M-loss, iv) Full L-loss, and v) Full M-loss. The training and test accuracy values for these five loss functions are shown in Table 1. Figure 3: Plot of different loss functions when the target y = 1. We tested the five losses on text datasets and gauged the performance of the models. We used an LSTM-based model to classify text from the Consumer Financial Protection Bureau (CFPB) dataset. The target variable has 10 possible classes. The model contains an embedding layer followed by a spatial dropout, an LSTM layer of 100 units, and a dense layer to output 10 possible classes. We also developed a sentiment analysis model using BERT to classify movie reviews as positive or negative, based on the text of the review. We used the Large Movie Review Dataset [6] that contains the text of 50,000 movie reviews from the Internet Movie Database (IMDB). We used the Smaller BERT model from TensorFlow Hub having 4 hidden layers (Transformer blocks), a hidden size of 512, and 8 attention heads. Adam optimizer was used with this BERT model. The test accuracy values for these five loss functions are shown in Table 2. \begin{table} \begin{tabular}{l l l l l} **Dataset** & **Model** & **Loss** & **Train Acc.** & **Test Acc.** \\ \hline Imagenette & VGG19 & Cross Entropy loss & 0.73 & 0.74 \\ Imagenette & VGG19 & L-loss & 0.75 & **0.77** \\ Imagenette & VGG19 & M-loss & 0.74 & **0.78** \\ Imagenette & VGG19 & Full L-loss & 0.72 & **0.78** \\ Imagenette & VGG19 & Full M-loss & 0.74 & **0.76** \\ CIFAR10 & VGG19 & Cross Entropy loss & 0.5806 & 0.5668 \\ CIFAR10 & VGG19 & L-loss & 0.5791 & **0.5684** \\ CIFAR10 & VGG19 & M-loss & 0.5745 & 0.5666 \\ CIFAR10 & VGG19 & Full L-loss & 0.5827 & **0.571** \\ CIFAR10 & VGG19 & Full M-loss & 0.5762 & **0.5668** \\ \end{tabular} \end{table} Table 1: Results on image datasets The experimental results show that both the variants of the proposed L-loss and M-loss can outperform the cross-entropy loss in most of the cases. \begin{table} \begin{tabular}{l l l l} \multicolumn{1}{c}{**Dataset**} & \multicolumn{1}{c}{**Model**} & \multicolumn{1}{c}{**Loss**} & \multicolumn{1}{c}{**Test Acc.**} \\ \hline \hline CFPB & LSTM & Cross Entropy loss & 0.822 \\ CFPB & LSTM & L-loss & **0.843** \\ CFPB & LSTM & M-loss & **0.827** \\ CFPB & LSTM & Full L-loss & **0.839** \\ CFPB & LSTM & Full M-loss & **0.825** \\ IMDB movie review & BERT & Cross Entropy loss & 0.8551 \\ IMDB movie review & BERT & L-loss & **0.8557** \\ IMDB movie review & BERT & M-loss & **0.8539** \\ IMDB movie review & BERT & Full L-loss & **0.8577** \\ IMDB movie review & BERT & Full M-loss & **0.8555** \\ \end{tabular} \end{table} Table 2: Results on text datasets Figure 4: Variation of accuracy with epochs for the Imagenette dataset. Figure 5: Variation of loss with epochs for the Imagenette dataset. Figure 6: Variation of accuracy with epochs for the CIFAR10 dataset. ## 4 Conclusion This paper explored the possible advantages of using alternate loss functions for training ANNs. Eight new loss functions were proposed. Preliminary results were obtained with two of the proposed loss functions. The M and L loss functions proposed in this paper are shown to outperform cross-entropy loss in most of the scenarios for both image and text classification. The fundamental question of whether more aggressive punishments and rewards can significantly improve the performance of ML algorithms remains unanswered and will be considered in future works.
2302.00386
EfficientRep:An Efficient Repvgg-style ConvNets with Hardware-aware Neural Network Design
We present a hardware-efficient architecture of convolutional neural network, which has a repvgg-like architecture. Flops or parameters are traditional metrics to evaluate the efficiency of networks which are not sensitive to hardware including computing ability and memory bandwidth. Thus, how to design a neural network to efficiently use the computing ability and memory bandwidth of hardware is a critical problem. This paper proposes a method how to design hardware-aware neural network. Based on this method, we designed EfficientRep series convolutional networks, which are high-computation hardware(e.g. GPU) friendly and applied in YOLOv6 object detection framework. YOLOv6 has published YOLOv6N/YOLOv6S/YOLOv6M/YOLOv6L models in v1 and v2 versions.
Kaiheng Weng, Xiangxiang Chu, Xiaoming Xu, Junshi Huang, Xiaoming Wei
2023-02-01T11:46:04Z
http://arxiv.org/abs/2302.00386v1
# EfficientRep: An Efficient Repvgg-style ConvNets with Hardware-aware Neural Network Design ###### Abstract We present a hardware-efficient architecture of convolutional neural network, which has a repvgg-like architecture. Flops or parameters are traditional metrics to evaluate the efficiency of networks which are not sensitive to hardware including computing ability and memory bandwidth. Thus, how to design a neural network to efficiently use the computing ability and memory bandwidth of hardware is a critical problem. This paper proposes a method how to design hardware-aware neural network. Based on this method, we designed EfficientRep series convolutional networks, which are high-computation hardware(e.g. GPU) friendly and applied in YOLOv6 object detection framework. YOLOv6 has published YOLOv6N/YOLOv6S/YOLOv6M/YOLOv6L models in v1 and v2 versions. Our YOLOv6 code is made available at [https://github.com/meituan/YOLOv6](https://github.com/meituan/YOLOv6). neural-network-design, hardware-aware ## I Introduction Since VGG achieved success in image classification tasks, convolutional neural network design has attracted huge attentions in academy and industry. Currently, amounts of classical networks have been proposed, like Inception [1] and Resnet [2]. These well-designed architectures make the accuracy of image classification increasingly higher. Besides manually design, recently neural architecture search also automatically designed several representative networks, such as Nasnet [3] and AmoebaNet [4]. Though complexed networks bring successes to vision tasks like image classification, object detection and segmentation, these networks may not get suitable accuracy-speed balance on deployed hardware. Deep learning network design and deployment for hardware efficiency has been consistently studied [5][6]. Traditional evaluation metrics for inference effciency are floating-point operations (FLOPs) and parameter count. However, such metrics can not represent the relationships with hardware, such as memory access cost and I/O throughput. Fig 3 shows the relationships between computing ability with memory resources. Hence, an important question is raised to us: _how to design a hardware-friendly network to perform better accuracy-speed balance?_ To solve this problem, we explored some novel architectures that show competitive and applied in YOLOv6 object detection framework. RepVGG [7] is a novel network with 3x3 convolutional kernel highly optimized by winograd algorithm on GPU or CPU. Single-path models can train and infer fast on devices like GPU. Fig 4. shows the transformation between training state and infenrece state for rep conv. In training state, with extra 1x1 conv and identity, rep conv can guarantee the accuracy during training. In inference state, re-parameterization structure can be equally converted to inference status. In YOLOv6-1.0, based on basic rep conv, we designed pure regvgg-style architectures named EfficientRep backbone and Rep-PAN neck to efficiently utilize the computing resources of GPU. In YOLOv6-2.0, to balance the computing and memory resources, we explored a kind of novel structure named Rep(Beer-mug) unit and RepC3(or named CSPStackRep) block. Compared with rep conv, we found that Rep unit is a more efficient basic neural network unit at some states. Though RepVGG proposed that rep-style multi-branch training can reach comparable performance as an original multi-branch training like resnet, we discovered that the accuracy-speed trade-off of rep-style network degraded at large scale which will be shown in Section III. Hence, we designed CSPRep backbone and CSPRepPAN neck applied in YOLOv6-2.0, with above structures of Rep unit and RepC3 block. With above considerations, we apply hybrid strategy to YOLOv6 that we select single-branch models in small size and multi-branch models in large size. Fig 1 and Fig 2 describe the comparable accuracy-speed trade-off as other object detectors. Fig. 1: Metrics of YOLOv6-v1. Fig. 2: Metrics of YOLOv6-v2. ## II Related Work ### _Neural Network Design_ VGG [8] network achieved the top-1 accuracy of ImageNet Classification to above 70%, many related innovations have been proposed, e.g. GoogLeNet [9] and Inception [1] network are designed in multi-branch architecture. ResNet [2] is a representative two-branch network and widely used in industry. Until repvgg [7] is proposed, single-path network shows high efficiency on some devices. ### _Neural Architecture Search_ Neural architecture search (NAS) is a novel technique, aiming to automatically design network compared with manual designing. With manual-designing space design, NAS can automatically generate numbers of networks with huge resource cost. Currently, to save computing resources, low-cost neural network search has been proposed, e.g. One-For-All [10] et al. ### _Hardware-aware Neural Network Design_ Recently, serveral novel networks like MobileOne [5] and TRT-VIT [6] have been proposed. These networks are manually designed, considering the performance on devices. Except for the metrics about accuracy or params, the inference speed is taken into accounts simultaneously, which is called hardware-aware neural network design. #### Our contributions are summarized as follows. * We proposed novel structures of Rep unit, Reblock and RepC3 block. * We proposed novel network of EfficientRep, Rep-PAN, CspBep and CSPRepPAN. * We proposed novel network design with computing ability and memory bandwidth balance, with various strategies for different size of models. ## III Approach In this section, we describe the details of hardware-aware neural network design applied in YOLOv6. The novel structures and networks we proposed will be presented with hybrid strategy for different size of models. ### _Pure Repvgg-style Efficient Design_ Repvgg-style [7] conv has the structure of 3x3 conv followed by ReLU, which can efficiently utilize the hardware computation. At training state, Repvgg-style conv consists of 3x3 branch, 1x1 branch and identity(Fig 4). Through re-parameterization, multi-branch structure is transformed to single-branch 3x3 conv at inference state. As shown in Fig 5 and Fig 6, we designed Repvgg-style network called EfficientRep backbone and Rep-PAN neck which are GPU-friendly, and applied in YOLOv6 detection framework(YOLOv6-v1) [11]. However, when YOLOv6-v1 grows to medium size, the inference speed slows down too fast and the accuracy is not competitive, compared with csp-style YOLO-series [12][13][14][15][16][17][18]. As shown in Table I, pure repvgg-style YOLOv6m can not achieve comparable accuracy-speed trade-off. Hence, we explored novel structure like multi-path for large size models. Fig. 4: Design of Rep Conv. Fig. 5: Design of EfficientRep. Fig. 3: Introduction of Roofline Model. ### _Multi-path Efficient Design_ To solve the problem that pure repvgg-style network can not get accuracy-speed trade-off as expected, we proposed a novel structure of Bep unit. The details of Bep unit is shown in Fig 7, numbers of rep convs are connected linearly with extra shortcut. With Bep unit, we designed a novel backbone and neck, separately named CSPBep and CSPRepPAN. We applied the above structures in YOLOv6-v2 and achieved better accuracy-speed trade-off. CSP-style [20] is an efficient design widely used in YOLOverse framework, like YOLOv5 [16], PPYOLOE [17] and so on. CSP-style structure uses Cross Stage Partial Network which achieves a richer gradient combination while reducing the amount of computation. We combined Bep unit with CSP-style structure to design a novel structure named BepC3 block to balance accuracy and inference speed. The design of BepC3 is described in Fig 8, which is composed of CSP-style structure and Rephlock of Bep units. As Table I shows the improvements of BepC3 block, the accuracy and speed is balanced as expected. Based on BepC3 block, we separately designed CSPRep backbone and CSPRepPAN neck which result in the YOLOv6-v2 models. For CSP-style network in YOLO-series, the partial ratio is 1/2 by default. In our design for YOLOv6-v2, we applied partial ratio of 2/3 for YOLOv6m and 1/2 for YOLOv6l, aiming to get better performance. ### _Scaling Strategy_ Following with YOLOv5, we use scale strategy of depth multiplier and width multiplier to generate various size of models. In YOLOv6-v1 and YOLOv6-v2, the depth settings of basic backbones are both [1, 6, 12, 18, 6]. Besides, the width settings are [64, 128, 256, 512, 1024]. The depth setting of basic necks are both [12, 12, 12, 12] and the width settings are [256, 128, 128, 256, 512, 512]. Table II shows the specific depth multiplier and width multiplier applied in YOLOv6. ## IV Experimental Results In this section, we show experimental results and details. For object detection, experiments are trained on MS COCO-2017 training set with 80 classes and 118k images. We use standard COCO AP metric on MS COCO-2017 validation set with 5000 images. ### _Experiments Details for Object Detection_ For our network design applied in YOLOv6, we train the models for a total of 300 epochs with 3 epochs warmup on Fig. 8: Design of BepC3. Fig. 6: Design of Rep-PAN. Fig. 7: Design of Bep Unit. COCO train2017. Our training strategy is stochastic gradient descent (SGD) for training and an initial lr of 0.01 with the cosine lr scheduler. In our setting, the weight decay is 5e-4. For 8-GPU device, the batch size is 256 by default. We also adopt Mosaic and Mixup data augmentations and exponential moving average (EMA) during training. ### _Comparision with Other Detectors_ To present the effects of our network design, Table III shows the performance of YOLOv6 models, compared with other state-of-the-art object detectors on MS-COCO test split. With our optimized models and other improvements, YOLOv6-N/S/M/L models present better accuracy-speed trade-off. We evaluate inference speed on NVIDIA Tesla T4 GPU with TensorRT version 7.2, with FP16 precision. ## V Conclusion In this report, we present our optimization for neural networks applied in YOLOv6. We designed Bep unit, RepC3-block/Repl block, EfficientRep/CspBep backbone and RepPAN/CSPRepPAN neck. Joined with other improvements, we achieved YOLOv6-N/S/M/L models better than other object detectors. Meanwhile, we proposed a hybrid network-design strategy applied in various size of models, aiming to achieve better accuracy-speed trade-off. Moreover, we proposed a novel hardware neural network design with computing and memory balance, which is applied in YOLOv6 framework development. We hope that the above proposals can provide inspirations for develops and researchers.
2308.06960
Search to Fine-tune Pre-trained Graph Neural Networks for Graph-level Tasks
Recently, graph neural networks (GNNs) have shown its unprecedented success in many graph-related tasks. However, GNNs face the label scarcity issue as other neural networks do. Thus, recent efforts try to pre-train GNNs on a large-scale unlabeled graph and adapt the knowledge from the unlabeled graph to the target downstream task. The adaptation is generally achieved by fine-tuning the pre-trained GNNs with a limited number of labeled data. Despite the importance of fine-tuning, current GNNs pre-training works often ignore designing a good fine-tuning strategy to better leverage transferred knowledge and improve the performance on downstream tasks. Only few works start to investigate a better fine-tuning strategy for pre-trained GNNs. But their designs either have strong assumptions or overlook the data-aware issue for various downstream datasets. Therefore, we aim to design a better fine-tuning strategy for pre-trained GNNs to improve the model performance in this paper. Given a pre-trained GNN, we propose to search to fine-tune pre-trained graph neural networks for graph-level tasks (S2PGNN), which adaptively design a suitable fine-tuning framework for the given labeled data on the downstream task. To ensure the improvement brought by searching fine-tuning strategy, we carefully summarize a proper search space of fine-tuning framework that is suitable for GNNs. The empirical studies show that S2PGNN can be implemented on the top of 10 famous pre-trained GNNs and consistently improve their performance. Besides, S2PGNN achieves better performance than existing fine-tuning strategies within and outside the GNN area. Our code is publicly available at \url{https://anonymous.4open.science/r/code_icde2024-A9CB/}.
Zhili Wang, Shimin Di, Lei Chen, Xiaofang Zhou
2023-08-14T06:32:02Z
http://arxiv.org/abs/2308.06960v2
# Search to Fine-tune Pre-trained Graph Neural Networks for Graph-level Tasks ###### Abstract Recently, graph neural networks (GNNs) have shown its unprecedented success in many graph-related tasks. However, GNNs face the label scarcity issue as other neural networks do. Thus, recent efforts try to pre-train GNNs on a large-scale unlabeled graph and adapt the knowledge from the unlabeled graph to the target downstream task. The adaptation is generally achieved by fine-tuning the pre-trained GNNs with a limited number of labeled data. Despite the importance of fine-tuning, current GNNs pre-training works often ignore designing a good fine-tuning strategy to better leverage transferred knowledge and improve the performance on downstream tasks. Only few works start to investigate a better fine-tuning strategy for pre-trained GNNs. But their designs either have strong assumptions or overlook the data-aware issue for various downstream datasets. Therefore, we aim to design a better fine-tuning strategy for pre-trained GNNs to improve the model performance in this paper. Given a pre-trained GNN, we propose to search to fine-tune pre-trained graph neural networks for graph-level tasks (S2PGNN), which adaptively design a suitable fine-tuning framework for the given labeled data on the downstream task. To ensure the improvement brought by searching fine-tuning strategy, we carefully summarize a proper search space of fine-tuning framework that is suitable for GNNs. The empirical studies show that S2PGNN can be implemented on the top of 10 famous pre-trained GNNs and consistently improve their performance. Besides, S2PGNN achieves better performance than existing fine-tuning strategies within and outside the GNN area. Our code is publicly available at [https://anonymous.4open.science/r/code_jcdc2024-A9CB/](https://anonymous.4open.science/r/code_jcdc2024-A9CB/). graph neural network, fine-tuning, pre-training graph neural networks ## I Introduction As one of the most ubiquitous data structures, graph is a powerful way to represent diverse and complex real-world systems, e.g., social networks [1], protein interactions [2], and molecules [3, 4, 5]. Graph representation learning [6] maps the original graph into the low-dimensional vector space to handle various graph scenarios. Recently, Graph Neural Networks (GNNs) [7, 8, 9, 10, 11, 12, 13, 14], which follow the message-passing schema [15] to learn representations via iteratively neighboring message aggregation, have become the leading approaches towards powerful graph representation learning. GNNs have demonstrated state-of-the-art performances in a variety of graph tasks. e.g., node classification [7, 8, 9, 13], link prediction [16, 17, 18, 12], and graph classification [3, 4, 5, 10, 15, 19]. Despite the revolutionary success of GNNs on graph data, they are mainly trained in an end-to-end manner with task-specific supervision, which generally requires abundant labeled data. However, in many realistic graph scenarios, high-quality and task-specific labels can be scarce, which seriously impedes the application of GNNs on many graph scenarios [20]. The label scarcity issue is mainly caused by requiring extensive and laborious expert knowledge for adequate annotation, which can be even more exacerbated in some scientific fields, e.g., medicine, chemistry, and biology. Therefore, some recent efforts [20, 21, 22, 23, 24, 25, 26] investigate the pre-training [27] in GNNs so as to tackle this challenge and improve the generalization performances of GNNs. These works mainly follow the self-supervised way to pre-train GNNs on large-scale unlabeled graph data by exploiting various self-supervised learning (SSL) [28] strategies, including Autoregressive Modeling (AM) [29, 23], Masked Component Modeling (MCM) [20, 30], and Contrastive Learning (CL) [21, 22, 25, 21]. Then, the invariant knowledge captured by the pre-trained GNNs can be transferred to the downstream graph tasks. However, due to domain discrepancy [32], the _fine-tuning_ strategy [33, 34] is required to adapt the transferred knowledge from pre-trained GNNs to the downstream task by training the model with smaller-scale and limited labels. Although tremendous efforts have been put into the designs of various SSL strategies to attain more powerful pre-trained GNNs, how to leverage these models and conduct fine-tuning on downstream datasets is still under exploration. Currently, the most common strategy is vanilla fine-tuning [35], where the downstream model is initialized by the pre-trained parameters and continually trained on the target dataset. Unfortunately, the vanilla fine-tuning for pre-trained GNNs may be inadequate and problematic. Generally, the success of vanilla fine-tuning heavily relies on the consistency between the pre-training and downstream data structures and properties [20, 36], which however may not always hold. For example, in the context of molecular graphs, downstream datasets usually encompass novel substructures (a.k.a., _scaffold_[37]), which have not been encountered during pre-training. Besides, downstream graph scenarios in real world are often complex and diverse. Blindly utilizing the vanilla strategy to fine-tune the pre-trained GNNs under various downstream scenarios may be inflexible and insufficient. A few recent efforts [38, 39, 32] dedicate to designing novel GNN fine-tuning strategies so as to improve the vanilla solution and mitigate potential issues. AUX-TS [32] augments downstream objectives with SSL objectives in an adaptive manner to improve the flexibility and effectiveness. WordReg [38] develops smoothness-inducing regularization built on dropout [40] to constrain the representation distance induced by pre-trained and fine-tuned models. GTOT-Tuning [39] considers graph structures and proposes optimal transport-based regularization to preserve invariant knowledge. However, there are still some obvious problems exist among existing solutions. Firstly, some improved solutions may be infeasible in practice, e.g., AUX-TS, which takes the auxiliary SSL tasks as prerequisite but they are often inaccessible for downstream graph tasks. Secondly, WordReg and GTOT-Tuning focus on sophisticated regularization to fine-tune GNN parameters. But they neglect the fundamental fact that variations in best-performing architectures may generally exist between pre-training and downstream dataset. Such a data-aware issue [41] has been demonstrated crucial in GNN architecture design literatures [42, 43, 44, 45]. Therefore, how to leverage pre-trained GNNs to achieve better adaption for downstream graph tasks seems still a challenging problem that need to be resolved. To fully unleash the potential of pre-trained GNNs on various graph tasks, we propose a novel idea that adaptively designs a suitable fine-tuning framework for the given pre-trained GNN and downstream dataset, namely searching to fine-tune pre-trained graph neural networks for graph classification (S2PGNN). Specifically, we first investigate the existing fine-tuning works and carefully summarize a search space of fine-tuning frameworks that is suitable for GNNs, which incorporate influential design dimensions and powerful candidates of the existing fine-tuning works. Then, we leverage an efficient search algorithm to search a concrete fine-tuning strategy from the proposed search space. The main contributions of this work are summarized as follows: * In this paper, we present a novel view that systemically exploring GNN fine-tuning strategies, an important yet seriously under-investigated problem, to improve the utilization of pre-trained GNNs. * To further improve pre-trained GNNs, we present a new work S2PGNN that adaptively designs a suitable fine-tuning strategy for the given pre-trained GNN and downstream dataset, which broadens the perspective of the GNN fine-tuning works. * We propose a novel search space of fine-tuning strategies in S2PGNN, which identifies key factors that affect GNN fine-tuning results and presents improved strategies. The S2PGNN framework is model-agnostic and can be readily plugged into existing GNN backbone models and pre-trained GNNs for better downstream performances. * The empirical studies demonstrate that S2PGNN can be implemented on the top of 10 famous pre-trained GNNs and consistently improve their performance. Besides, S2PGNN achieves better performance than existing fine-tuning strategies within and outside the GNN area. ## II Related Work A graph typically can be represented as \(G=(V,E,\mathbf{A},\mathbf{X}^{V},\mathbf{X}^{E})\), where \(V=\{v_{1},\ldots,v_{n}\}\) is the node-set, \(E=\{(v_{i},v_{j})|v_{i},v_{j}\in V\}\) is the edge-set, \(\mathbf{A}\in\{0,1\}^{|V|\times|V|}\) is the adjacency matrix to define graph connectivity and \(\mathbf{A}_{ij}=1\) iff \((v_{i},v_{j})\in E\), \(\mathbf{X}^{V}=[X_{v_{1}}^{\top},X_{v_{2}}^{\top},...]\in\mathbb{R}^{|V| \times d}\) (\(\mathbf{X}_{v}\in\mathbb{R}^{d}\) for the node \(v\)) is the node attribute matrix with feature dimension \(d\), and \(\mathbf{X}^{E}\in\mathbb{R}^{|E|\times d}\) (\(\mathbf{X}_{uv}\in\mathbb{R}^{d}\) for edge \((u,v)\)) is the edge attribute matrix. In general, the learning on graph data first requires a graph encoder \(f_{\mathbf{\theta}}(\cdot)\) parameterized by \(\mathbf{\theta}\) to map the original graph \(G\) into the low-dimensional vector space \(\mathbb{R}^{d}\): \(\mathbf{H}=f_{\mathbf{\theta}}(G)\), where \(\mathbf{H}\in\mathbb{R}^{d}\) can be the learned representation of node, edge, or graph, depending on the prediction level of downstream tasks. Then, \(\mathbf{H}\) can be fed into an additional prediction head \(g_{\mathbf{\omega}}(\cdot)\) parameterized by \(\mathbf{\omega}\) (e.g., linear classifier, multi-layer perceptron) to generate predicted labels: \(y_{pred}=g_{\mathbf{\omega}}(\mathbf{H})\). After that, the entire model \(g_{\mathbf{\omega}}(f_{\mathbf{\theta}}(\cdot))\) can be trained in an end-to-end manner under the guidance of task-specific supervision: \[\mathbf{\theta}^{*},\mathbf{\omega}^{*}=\arg\min_{\mathbf{\theta},\mathbf{\omega}}\mathcal{L} _{sup}(g_{\mathbf{\omega}}(f_{\mathbf{\theta}}(\cdot));\mathcal{D}^{tra}), \tag{1}\] where \(\mathcal{L}_{sup}(\cdot)\) is the supervised loss function (e.g., cross entropy). As for the training data \(\mathcal{D}^{tra}\), it represents the graph data with labels and also depends on the down-streaming task, e.g., \(\mathcal{D}^{tra}=\{(G,y)\}\) for the graph classification. ### _Graph Neural Networks (GNNs)_ Recent years have witnessed the unprecedented success of GNNs for modeling graph data and dealing with various graph tasks. As one of powerful graph encoders \(f_{\mathbf{\theta}}(\cdot)\), GNNs typically leverage the graph topology \(\mathbf{A}\) as well as features \(\mathbf{X}^{V}\) \begin{table} \begin{tabular}{l|l} \hline **Notation** & **Definition** \\ \hline \(\mathbb{R}^{d}\) & The \(d\)-dimension real space. \\ \hline \(G\!=\!(V,E,\mathbf{A},\mathbf{X}^{V},\mathbf{X}^{E})\) & An attributed graph with node-set \(V\), edge-set \(E\), adjacency matrix \(\mathbf{A}\), and attribute matrices \(\mathbf{X}^{V}\) and \(\mathbf{X}^{E}\). \\ \hline \(V\), \(E\) & \(V=\{v_{1},\ldots,v_{n}\}\), \\ & \(E=\{(v_{i},v_{j})|v_{i},v_{j}\in V\}\). \\ \hline \(\mathbf{X}^{V}\in\mathbb{R}^{|V|\times d},\mathbf{X}_{v}\in\mathbb{R}^{d}\) & Node attribute matrix and vector. \\ \hline \(\mathbf{X}^{E}\in\mathbb{R}^{|E|\times d},\mathbf{X}_{uv}\in\mathbb{R}^{d}\) & Edge attribute matrix and vector. \\ \hline \(k\), \(K\) & The current and maximum GNN layer index, \(1\leq k\leq K\). \\ \hline \(\mathbf{H}_{k}^{(k)}\!\in\!\mathbb{R}^{d}\) & The node representation at \(k\)-th layer. \\ \hline \(\mathbf{H}_{G}\!\in\!\mathbb{R}^{d}\) & The graph representation. \\ \hline \(f_{\mathbf{\theta}}(\cdot)\) & The GNN encoder with parameters \(\mathbf{\theta}\). \\ \hline \(g_{\mathbf{\omega}}(\cdot)\) & The prediction head with parameters \(\mathbf{\omega}\). \\ \hline \(\pi_{\mathbf{\alpha}}(\cdot)\) & The GNN fine-tuning controller with parameters \(\mathbf{\alpha}\). \\ \hline \(\mathbf{\Phi}_{ft}\) & The GNN fine-tuning strategy. \\ \hline \(f_{aug}(\cdot)\), \(f_{fuse}(\cdot)\), \(f_{read}(\cdot)\) & The GNN fine-tuning dimension of identity augmentation, multi-scale fusion, graph-level readout. \\ \hline \(\mathcal{O}_{aug}\), \(\mathcal{O}_{fuse}\), \(\mathcal{O}_{read}\) & The candidate-set of \\ & \(f_{aug}(\cdot)\), \(f_{fuse}(\cdot)\), \(f_{read}(\cdot)\). \\ \hline \(\mathcal{D}_{ssl}\), \(\mathcal{D}_{sup}\) & The pre-training and downstream dataset. \\ \hline \(\mathcal{L}_{ssl}(\cdot)\), \(\mathcal{L}_{sup}(\cdot)\) & The pre-training and downstream loss. \\ \hline \end{tabular} \end{table} TABLE I: A summary of common notations. and \(\mathbf{X}^{E}\) to achieve the graph representation \(\mathbf{H}\). The majority of GNNs [7, 8, 9, 10] follow the message passing paradigm [15] to learn the representation of node \(v\) by iteratively aggregating messages from \(v\)'s neighbors \(N(v)\). Formally, the intra-layer message passing for given node \(v\) can be formulated as: \[\mathbf{M}_{v}^{(k)}=AGG^{(k)}(\{(\mathbf{H}_{u}^{(k-1)},\mathbf{ H}_{v}^{(k-1)},\mathbf{X}_{uv})|u\in N(v)\}), \tag{2}\] \[\mathbf{H}_{v}^{(k)}=COMB^{(k)}(\mathbf{H}_{v}^{(k-1)},\mathbf{M }_{v}^{(k)}), \tag{3}\] where \(\mathbf{H}_{v}^{(k)}\) is the representation of node \(v\) at \(k\)-th iteration (usually \(\mathbf{H}_{v}^{(0)}=\mathbf{X}_{v}\)), \(\mathbf{X}_{uv}\) is the attribute of edge \((u,v)\), \(\mathbf{M}_{v}^{(k)}\) is the intermediate representation collected from neighbors via aggregation function \(AGG(\cdot)\), \(COMB(\cdot)\) function combines information from neighbors and center node itself to update representation from \(\mathbf{H}_{v}^{(k-1)}\) to \(\mathbf{H}_{v}^{(k)}\). Obviously, after \(k\) (\(1\leq k\leq K\)) iterations/layers of aggregation, each node captures information from their \(k\)-hop neighbors. Note that \(N(v)\), \(AGG(\cdot)\), and \(COMB(\cdot)\) are crucial functions to determine the message passing process. They mainly differentiate various GNNs and may affect model expressiveness substantially. We next present several classic GNNs with specific instantiations of Eq. (2) and (3), which are adopted in later experiments. * Graph Convolutional Network (GCN) [7] adopts \(MEAN(\cdot)\) as its mean aggregation function and the non-linear activation function \(\sigma(\cdot)\) e.g., \(ReLU(\cdot)\). It proposes to transform intermediate embeddings into representation by the trainable matrix \(\mathbf{W}\): \[\mathbf{M}_{v}^{(k)}=MEAN(\{\mathbf{H}_{u}^{(k-1)}|u\in N(v)\cup\{ v\}),\] (4) \[\mathbf{H}_{v}^{(k)}=\sigma(\mathbf{W}^{(k)}\mathbf{M}_{v}^{(k)}).\] (5) * GraphSAGE (SAGE) [8] concatenates the intermediate embedding \(\mathbf{M}_{v}^{(k)}\) with the representation of last layer \(\mathbf{H}_{v}^{(k-1)}\) before the transformation: \[\mathbf{M}_{v}^{(k)}=MEAN(\{\mathbf{H}_{u}^{(k-1)}|u\in N(v)\}),\] (6) \[\mathbf{H}_{v}^{(k)}=\sigma(\mathbf{W}^{(k)}[\mathbf{M}_{v}^{(k)} |\mathbf{H}_{v}^{(k-1)}]).\] (7) * Graph Isomorphism Network (GIN) [10], as one of the most expressive GNN architectures, adopts \(SUM(\cdot)\) as the sum aggregation function and the multi-layer perceptron \(MLP(\cdot)\) to transform the combined messages. Besides, it adds the scalar \(\epsilon\) to balance the messages weights from center node itself and neighbors: \[\mathbf{M}_{v}^{(k)}=SUM(\{\mathbf{H}_{u}^{(k-1)}|u\in N(v)\}),\] (8) \[\mathbf{H}_{v}^{(k)}=MLP^{(k)}((1+\epsilon^{(k)})\mathbf{H}_{v}^{ (k-1)}+\mathbf{M}_{v}^{(k)}).\] (9) * Graph Attention Network (GAT) [9] introduce the attentive function \(ATT(\cdot)\)[46] as its aggregation function: \[\mathbf{M}_{v}^{(k)}=ATT(\{\mathbf{H}_{u}^{(k-1)}|u\in N(v)\},\] (10) \[\mathbf{H}_{v}^{(k)}=\sigma(\mathbf{W}^{(k)}\mathbf{M}_{v}^{(k)}).\] (11) Furthermore, for the graph-level task, a permutation-invariant readout function \(READOUT(\cdot)\) is required to obtain the graph-level representation \(\mathbf{H}_{G}\) of the entire graph \(G\): \[\mathbf{H}_{G}=READOUT(\{\mathbf{H}_{v}^{(K)}|v\in V\}), \tag{12}\] where \(READOUT(\cdot)\) can be simple non-parameterized function, e.g., sum pooling and mean pooling, or other more advanced methods [47, 48, 49]. ### _Pre-training and fine-tuning (P&F) in GNNs_ As introduced in Sec. I, labeling graph data can be time-consuming, expensive, and sometimes even infeasible in many realistic graph scenarios (e.g., molecule graphs). The lack of label information severely impedes GNN capacities, thereby posing challenges to graph learning in those fields. To alleviate the data scarcity issue, recent efforts [20, 21, 23] try to generalize the self-supervised pre-training and fine-tuning (P&F) paradigm to GNNs. Generally, they first follow the self-supervised learning (SSL) way to train a pre-trained GNN model on the large scale of unlabeled data \(\mathcal{D}_{ssl}\): \[\boldsymbol{\theta}^{init}=\arg\min_{\boldsymbol{\theta}}\mathcal{L}_{ssl}(f_{ \boldsymbol{\theta}}(\cdot);\mathcal{D}_{ssl}) \tag{13}\] where \(\mathcal{L}_{ssl}(\cdot)\) is the SSL loss Then, to achieve the knowledge transfer from \(\mathcal{D}_{ssl}\), the down-streaming model is initialized by the pre-trained parameter \(\boldsymbol{\theta}^{init}\) and fine-tuned with a small fine-tuning data \(\mathcal{D}_{ft}\): \[\boldsymbol{\theta}^{*},\boldsymbol{\omega}^{*}=\arg\min_{\boldsymbol{\theta}, \boldsymbol{\omega}}\mathcal{L}_{ft}((g_{\boldsymbol{\omega}}(f_{\boldsymbol{ \theta}}(\cdot));\mathcal{D}_{ft}), \tag{14}\] where the initialization model \(f_{\boldsymbol{\theta}^{init}}(\cdot)\) is optimized by the fine-tuning objective \(\mathcal{L}_{ft}(\cdot)\). We next introduce several ways to instantiate the strategies of self-supervised pre-training in Eq. (13) and fine-tuning in Eq. (14), respectively. #### Iii-B1 Self-supervised pre-training strategies The literature design novel self-supervised pre-training objectives \(\mathcal{L}_{ssl}(\cdot)\) to empower the pre-trained GNNs. Due to the space limit, we here briefly introduce several well-known and representative methods (please refer to [28, 54, 55, 56] for more details), which can be roughly categorized into generative and contrastive based. The former pre-train GNNs to predict a graph or subgraph that is similar to the original input graph, while the latter aims to distinguish between pairs of similar and dissimilar graphs. * AutoEncoding (AE): Given the partial access to graph, AE methods (e.g., EdgePred [8] and GraphMAE [26]) propose to reconstruct the input graph via autoencoder architecture Fig. 1: The illustration of overall GNN P&F framework. [57]. Let \(\tilde{G}\) be reconstructed graph, they formulate the objective \(\mathcal{L}_{ssl}(\cdot)\) as: \[\mathcal{L}_{ssl}(\cdot)=-\sum_{G\in\mathcal{D}_{ssl}}\log p(\tilde{G}|G).\] (15) * Autoregressive Modeling (AM): AM methods (e.g., MGSSL [23]) factorize the input graph \(G\) as a sequence of components \(\mathcal{C}=\{C_{1},C_{2},\dots\}\) (e.g., nodes, edges, and subgraphs) with some preset ordering and perform graph reconstruction in an autoregressive manner: \[\mathcal{L}_{ssl}(\cdot)=-\sum_{G\in\mathcal{D}_{ssl}}\sum_{i=1}^{|\mathcal{C }|}\log p(C_{i}|C_{<i}).\] (16) * Masked Component Modeling (MCM): MCM works (e.g., AttrMasking [20] and Mole-BERT [30]) masks out some components of the input graphs (e.g., nodes, edges, and subgraphs), then recover those masked ones \(m(G)\) through the remaining ones \(G\backslash m(G)\): \[\mathcal{L}_{ssl}(\cdot)=-\sum_{G\in\mathcal{D}_{scl}}\sum_{\hat{G}\in m(G)} \log p(\hat{G}|G\backslash m(G)).\] (17) * Context Prediction (CP): CP works explore graph structures and utilize contextual information to design pre-training objectives. Let \(t=1\) if subgraph \(C_{1}\) and surrounding context \(C_{2}\) share the same center node, otherwise \(t=0\). ContextPred [20] leverages subgraphs to predict their surrounding context structures: \[\mathcal{L}_{ssl}(\cdot)=-\sum_{G\in\mathcal{D}_{ssl}}\log p(t|C_{1},C_{2}).\] (18) * Contrastive Learning (CL): CL approaches perform pre-training via maximizing the agreement between a pair of similar inputs, including Cross-Scale Contrastive Learning and Same-Scale Contrastive Learning. The former one (e.g., Infomax [58]) contrasts a pair of graph and its local sub-structure \((G,C)\) against negative pairs \((G,C^{-})\): \[\mathcal{L}_{ssl}(\cdot)\!=\!-\!\sum_{G\in\mathcal{D}_{scl}}[\log s(G,C)\!-\! \sum_{C^{-}}\log s(G,C^{-})]],\] (19) where \(s(\cdot,\cdot)\) is the similarity function. The latter ones (e.g., GraphCL [21], SimGRACE [25], and GraphLoG [22]) maximize the agreement between the augmented graph and its anchor graph \((G,G^{+})\) and repel negative pairs \((G,G^{-})\): \[\mathcal{L}_{ssl}(\cdot)\!=\!-\!\sum_{G\in\mathcal{D}_{scl}}[\log s(G,G^{+}) \!-\!\!\sum_{C^{-}}\log s(G,G^{-})]].\] (20) #### Iii-B2 Fine-tuning strategies Despite the development of self-supervised GNN pre-training strategies (see Sec. II-B1), the design of GNN fine-tuning strategies, i.e., how to instantiate Eq. (14), is still under exploration. So far, there are only a few fine-tuning methods proposed specifically for pre-trained GNNs. As summarized in Tab. II, here we first review 2 mainstream strategies in GNN domains: * Standard Tuning (ST): ST is the most prevalent fine-tuning strategy among existing GNN P&F literatures [20, 21, 23, 25]. Under this schema, all parameters \((\boldsymbol{\theta}_{init},\boldsymbol{\omega})\) of the GNNs are further fine-tuned under the supervision \(\mathcal{L}_{sup}(\cdot)\) for downstream tasks. \[\boldsymbol{\theta}^{*},\boldsymbol{\omega}^{*}=\arg\min_{\boldsymbol{\theta} _{init},\boldsymbol{\omega}}\mathcal{L}_{ssp}((g_{\boldsymbol{\omega}}(f_{ \boldsymbol{\theta}_{init}}(\cdot));\mathcal{D}_{ft}).\] (21) * Regularized Tuning (RT): RT methods generally introduce a regularizer loss \(\mathcal{L}_{reg}(\cdot)\) into \(\mathcal{L}_{ft}(\cdot)\): \[\mathcal{L}_{ft}(\cdot)=\mathcal{L}_{ssl}(\cdot)+\mathcal{L}_{reg}(\cdot),\] (22) where different models varies in the way to instantiate \(\mathcal{L}_{reg}(\cdot)\). In literature, GTOT-Tuning [39] is specifically designed for fine-tuning GNNs, which considers the topology information in graph and presents an optimal transport-based feature regularizer. In Sec. IV-C, we also discussed several RT methods that are initially developed for fine-tuning CNNs, including \(L^{2}\)-SP [50], DELTA [51], BSS [52], and StochNorm [53]. Except for above ST and RT methods, we investigate the performance of more fine-tuning strategies from other domains on the pre-training GNN tasks (see Sec. IV-C for more details). \begin{table} \begin{tabular}{l|l|c c|c c c|c} \hline \hline \multirow{2}{*}{**Strategy Name**} & \multicolumn{3}{c|}{**Fine-tuning Scenario**} & \multicolumn{3}{c|}{**Fine-tuning Dimension**} & \multirow{2}{*}{**Automated**} \\ \cline{3-4} \cline{6-7} & & GNN/Other & Graph Task & Architecture & Identity & Fusion & Readout \\ \hline Standard Tuning (ST) & \(\surd\surd\) & \(\surd\)/ & Node/EdgeGraph & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \hline \multirow{6}{*}{Regularized Tuning (RT)} & \(L^{2}\)-SP [50] & \(\times\)/ & - & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \cline{2-7} & DELTA [51] & \(\times\)/ & - & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \cline{2-7} & BSS [52] & \(\times\)/ & - & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \cline{2-7} & StochNorm [53] & \(\times\)/ & - & \(\surd\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \cline{2-7} & GTOT-Tuning [39] & \(\surd\)/ & Graph & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \cline{2-7} & AUX-TS [32] & \(\surd\)/ & Node/Edge & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \cline{2-7} & WordReg [38] & \(\surd\)/ & Graph & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \hline Parameter-Efficient Tuning (PET) & \(\times\)/ & - & \(\surd\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \hline Feature Extractor (FE) & \(\times\)/ & - & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \hline Last-\(k\) Tuning (LKT) & \(\times\)/ & - & \(\times\) & \(\times\) & \(\times\) & \(\times\) & \(\times\) \\ \hline S2PGNN & \(\surd\)/ & Graph & \(\surd\) & \(\surd\) & \(\surd\) & \(\surd\) & \(\surd\) \\ \hline \hline \end{tabular} \end{table} TABLE II: Overview of common fine-tuning strategies in GNN and other domains. Fine-tuning Scenario presents the application scenario of the fine-tuning strategies, including whether is designed for GNN or other neural networks and which graph task the strategy can be applied to. Fine-tuning Dimension presents what aspects they focus on during fine-tuning. ### _Automated GNNs (AutoGNNs)_ Despite the great success, many existing GNNs rely heavily on expert knowledge to manually design GNN model architectures. In most cases, the well-performing GNNs on some graphs may not be suitable on other graphs due to the divergence in graph structures or properties as well as task-specific requirements. And real-world graph datasets and tasks usually exhibit complex and diverse patterns. Besides, out-of-distribution predictions may also prevalent. Therefore, the conventional way to simply apply the fixed GNN architectures to all graph scenarios may be suboptimal, Instead, data/task-specific GNN architecture designs are much demanded. Recent works argue that such hand-crafted GNNs are prone to suffer from the well-known data-aware issue [41], i.e., the optimal GNN architecture for different graphs may be quite different. To alleviate the data-aware issue and better handle versatile graph applications, Automated GNNs (AutoGNNs) [42, 43, 44, 45] have been recently developed and demonstrate promising results. AutoGNNs leverage GNN controllers to achieve automated GNN architecture designs for the specific given graph data and task. Typically, AutoGNNs first design a unified and comprehensive GNN search space, which include various key design dimensions (functions) in the message passing process. Each design dimension may contain multiple candidate choices (operations) that can be selected by the controller to constitute the optimal model. Then, various search algorithms, e.g., Reinforcement Learning (RL)-based methods [59], Evolutionary Algorithm (EA)-based methods [60], and differentiable methods [61], can be leveraged to instantiate the controller and achieve the search objective. Novel GNN architectures identified by AutoGNN approaches have demonstrated superior results than their hand-crafted counterparts on a wide range of graph scenarios, e.g, node classification [42, 43, 44, 62], link prediction [43], and graph classification [43, 64, 63]. However, existing AutoGNNs neglect important design dimensions for fine-tuning pre-trained GNNs, which makes them incapable to handle various downstream fine-tuning scenarios. ## III Methodology As introduced in Sec. I, recent developed pre-trained GNNs have demonstrated promising to tackle the data scarcity issue and facilitate downstream learning. Despite the importance of fine-tuning, current pre-trained GNN works often ignore designing a good fine-tuning strategy to better leverage transferred knowledge and the improve downstream performance. Only few works start to investigate this problem, but their designs either have strong assumptions or overlook the data-aware issue for various downstream datasets. Therefore, in this work, we aim to design a better fine-tuning strategy S2PGNN for pre-trained GNNs to improve the model performance. S2PGNN adaptively designs a suitable fine-tuning framework for the given labeled data on the downstream task. To ensure the improvement brought by searching fine-tuning strategy, we carefully design a novel search space of fine-tuning that is suitable for GNNs, which identifies key factors that affect GNN fine-tuning results and presents improved strategies. The S2PGNN framework is model-agnostic and can be readily plugged into existing GNN backbone models and pre-trained GNNs. In Sec. III-A, we formulate our search problem and provide the overall optimization objective. In Sec. III-B, we present the proposed GNN fine-tuning search space. In Sec. III-C, we demonstrate how we leverage a controller to search the optimal fine-tuning strategy from the defined search space. In Sec. III-D, we provide the overall optimization. ### _Problem Formulation_ Given a pre-trained GNN and downstream dataset \(\mathcal{D}_{ft}\), the problem of S2PGNN is to design a GNN fine-tuning strategy on top of the given pre-trained GNN that can achieve good performance on \(\mathcal{D}_{ft}\). Formally, it can be formulated as: \[\boldsymbol{\alpha^{*}},\boldsymbol{\theta^{*}},\boldsymbol{\omega^{*}}\!=\! \arg\min_{\boldsymbol{\alpha},\boldsymbol{\theta},\boldsymbol{\omega}}\!\! \mathbb{E}_{\boldsymbol{\Phi}_{ft}\sim\pi_{\boldsymbol{\alpha}}(\cdot)}\mathcal{ L}_{ft}[g_{\boldsymbol{\omega}}(f_{\boldsymbol{\theta}}(\cdot));\mathcal{D}_{ft}], \tag{23}\] where \(\pi_{\boldsymbol{\alpha}}(\cdot)\) parameterized by \(\boldsymbol{\alpha}\) (light-weight) is the controller that leveraged to search the optimal strategy \(\boldsymbol{\Phi}_{ft}\) (i.e., \(\boldsymbol{\Phi}_{ft}\sim\pi_{\boldsymbol{\alpha}}(\cdot)\)) from proposed search space (see Sec. III-B) to fine-tune the downstream model \(g_{\boldsymbol{\omega}}(f_{\boldsymbol{\theta}}(\cdot))\) with parameters \((\boldsymbol{\theta},\boldsymbol{\omega})\), and \(\mathbb{E}(\cdot)\) is the expectation function. ### _GNN Fine-tuning Search Space_ To ensure the improvement brought by searching fine-tuning strategy, we identify that identity augmentation \(f_{aug}(\cdot)\), multi-scale fusion \(f_{fuse}(\cdot)\), and graph-level readout \(f_{read}(\cdot)\) operations within the message passing procedure are key Fig. 2: Illustration of GNN fine-tuning strategies (refer to Fig. 3 for the legend). factors that affect GNN fine-tuning results and summarize a proper search space of fine-tuning framework that is suitable for GNNs. As illustrated in Fig. 3, the improved message functions in S2PGNN built on top of GIN can be represented as: \[\begin{split}\mathbf{H}_{v}^{(k)}\!=\!f_{g\_conv}^{(k)}(\{\mathbf{H }_{u}^{(k-1)},\mathbf{H}_{v}^{(k-1)},\mathbf{X}_{uv}|u\in N(v)\}),\\ \mathbf{Z}_{v}^{(k)}\!=\!f_{aug}^{(k)}(\mathbf{H}_{v}^{(k-1)}, \mathbf{H}_{v}^{(k)}),\quad 1\leq k\leq K,\end{split} \tag{24}\] \[\mathbf{H}_{v}=f_{fuse}(\{\mathbf{Z}_{v}^{(1)},\mathbf{Z}_{v}^{(2)},\dots, \mathbf{Z}_{v}^{(K)}\}), \tag{25}\] \[\mathbf{H}_{G}=f_{read}(\{\mathbf{H}_{v}|v\in V\}), \tag{26}\] where \(f_{g\_conv}(\cdot)\) (denoted as _GINConv_ in Fig. 3) is the intra-layer message aggregator. Note that \(f_{g\_conv}(\cdot)\) is the most basic building block in both pre-trained and fine-tuned model, which can be replaced by other GNN backbone models or pre-trained framework. We here utilize GIN to demonstrate an example. Besides, \(f_{aug}(\cdot)\) is the identity augmentation operation that enhance the information from node itself before the next iteration of aggregation, \(f_{fuse}(\cdot)\) is the multi-scale fusion operation that comprehensively combines the multi-scale informations from different GNN layers, and \(f_{read}(\cdot)\) is the graph-level readout operation that adaptively aggregate node representations for graph representation. Next, we provide detailed illustrations towards key dimensions in GNN fine-tuning \(\{f_{aug}(\cdot),f_{fuse}(\cdot),f_{read}(\cdot)\}\) and according candidate-set \(\{\mathcal{O}_{aug},\mathcal{O}_{fuse},\mathcal{O}_{read}\}\) that allows the optimal strategy \(\mathbf{\Phi}_{ft}=\{f_{aug}(\cdot)=?,f_{fuse}(\cdot)=?,f_{read}(\cdot)=?\}\) to be adaptively designed (marked with orange ovals in Fig. 3). Note that in S2PGNN \(\mathbf{\theta}=\{\mathbf{\theta}_{g\_conv}\}\cup\{\mathbf{\theta}_{aug}, \mathbf{\theta}_{fuse},\mathbf{\theta}_{read}\}\) (marked with blue \(\cup\) orange in Fig. 3). #### Iii-B1 Identity Augmentation \(\mathcal{O}_{aug}\) Augmenting the identity information \(\mathbf{H}_{v}^{(k-1)}\) from center node itself can be indispensable for GNN fine-tuning due to several reasons. Firstly, in some downstream cases, node-specific information may be more important than messages from neighbors, since the latter sometimes can be missing, noisy, or unreliable in real-world datasets. Besides, in some GNN backbone architectures, node-specific information may be easy to lose and representations may be prone to become indistinguishable (a.k.a., over-smoothing [65]) with the increase of GNN layers. This can happen if the adopted aggregation function in pre-trained backbones only considers the information of neighboring nodes (e.g., GCN). Unfortunately, existing GNN fine-tuning works tend to ignore the importance of preserving node-specific identity information and lack of corresponding designs as shown in Tab. II. Therefore, we propose to incorporate identity augmentation into the GNN fine-tuning design space and allows suitable augmentation to be adaptively searched from the following candidates in Eq. (24): * **No augmentation.** We do not perform additional identity augmentation and keep consistent as in pre-trained backbone with \(zero\_aug\) operation: \(\mathbf{Z}_{v}^{(k)}=\mathbf{H}_{v}^{(k)}\). * **Additive augmentation.** We allow direct skip-connection as in [] with \(identity\_aug\) operation: \(\mathbf{Z}_{v}^{(k)}=\mathbf{H}_{v}^{(k-1)}+\mathbf{H}_{v}^{(k)}\). We also allow transformed augmentation with \(trans\_aug\) operation: \(\mathbf{Z}_{v}^{(k)}=\phi^{(k)}(\mathbf{H}_{v}^{(k-1)})+\mathbf{H}_{v}^{(k)}\), where \(\phi^{(k)}(\cdot)\) is a parameterized neural network with bottleneck architecture \(\mathbb{R}^{d}\rightarrow\mathbb{R}^{m}\rightarrow\mathbb{R}^{d}\) (we let \(m\ll f\) for parameter-efficient similar as Adapter [34]). #### Iii-B2 Multi-scale Fusion \(\mathcal{O}_{fuse}\) Immediate information from different pre-trained GNN layers \(\{\mathbf{Z}_{v}^{(1)},\mathbf{Z}_{v}^{(2)},\dots,\mathbf{Z}_{v}^{(K)}\}\) may be better suited for capturing graph information at different scales, e.g., local or global [11]. Besides, different downstream graph datasets and tasks may also have their specific and variant requirements in terms of the most suitable number of GNN layers [13, 66]. However, existing strategies to fine-tune pre-trained GNNs simply leverage the last-layer output to induce final representations, i.e., \(\mathbf{H}_{v}=0\cdot\mathbf{Z}_{v}^{(1)}\!+\!0\cdot\!\mathbf{Z}_{v}^{(2)}\!+ \!\dots\!+\!1\!\cdot\!\mathbf{Z}_{v}^{(K)}\), which may be suboptimal and cause unsatisfactory fine-tuning performances. Therefore, we incorporate the multi-scale fusion as novel dimension into the GNN fine-tuning space, which allows flexibly information fusion and utilization for better downstream performances. Fusion process can be roughly represented as \(\mathbf{H}_{v}=w_{v}^{(1)}\cdot\mathbf{Z}_{v}^{(1)}+w_{v}^{(2)}\cdot\mathbf{Z}_ {v}^{(2)}+\dots+w_{v}^{(K)}\cdot\mathbf{Z}_{v}^{(K)}\), where \(w_{v}^{(k)}\) is importance weights of information at \(k\)-th layer for node \(v\), which is to be assigned or adaptively learned depending on specific fusion choices. We include candidate fusion operations from diverse categories: * **Non-parametric fusion.** Non-parametric methods to attain \(w_{v}^{(k)}\) are simple and computational efficient. Among candidates listed in Tab. III, \(\{last(\cdot),concat(\cdot),max(\cdot),mean(\cdot),ppr(\cdot)\}\) are from this category, where \(last(\cdot)\) Fig. 3: Illustration to the framework of S2PGNN built on top of pre-trained 5-layer GIN. The orange part indicates the search dimensions in S2PGNN. PT., FT., and Id.Aug. are abbreviations for pre-training, fine-tuning, and identity augmentation. disables fusion and directly takes the last-layer output as learned representations, \(concat(\cdot)\) conducts multi-scale concatenation as \(\mathbf{H}_{v}=[\mathbf{Z}_{v}^{(1)}]|\ldots||\mathbf{Z}_{v}^{(K)}]\), \(max(\cdot)\) takes the maximum value from each channel to induce fused representations, \(mean(\cdot)\) assigns equal importance weights for each layer, and \(ppr(\cdot)\) assigns decayed importance weights with Personalized PageRank method as in [67]. * **Attentive fusion.** Attentive fusion methods adaptively learn importance weights \(w_{v}^{(k)}\) via the attention mechanism, which generally have \(w_{v}^{(k)}\in[0,1]\) and \(\sum_{k}w_{v}^{(k)}=1\). We adopt the powerful \(lstm\) fusion that is similar as in [11]. * **Gated fusion.** Gated fusion methods use gating functions to selectively filter information at different layers. We use \(gpr\) method for this category similar as in [13], which allows the adaptive scale as well as the sign of information, i.e., \(w_{v}^{(k)}\in[-1,1]\). #### Iii-B3 Graph-level Readout \(\mathcal{O}_{read}\) Graph-level readout aggregates representations across all nodes to attain the graph-level representation, which is a compulsory function for graph-level downstream tasks, e.g., graph classification or regression. Different readout methods may focus on capturing different aspects of node features or graph topology [68]. Besides, they may also be more or less suitable for handling downstream graphs with variant structures and properties. Thus, it is important to carefully consider the data characteristics and task-specific requirements to adaptively determine the most suitable readout function for the specific downstream task. However, existing GNN fine-tuning works largely ignore the importance of adaptive readout methods and lack of according designs, which may hinder their performances on diverse downstream scenarios. Therefore, we integrate the graph-level readout into S2PGNN's fine-tuning space so that the optimal readout method can be adaptively selected. We include multiple candidates from various categories: * **Simple readout.** Simple readout methods are parameter-free and computationally efficient, which may be effective for scenarios where the overall structure of the graph is less important than the individual node features. We include \(sum\_pooling(\cdot)\), \(mean\_pooling(\cdot)\), and \(max\_pooling(\cdot)\) readouts for this type. * **Adaptive readout.** Other readout methods, such as adaptive readout, focus on identifying and capturing the most informative nodes or substructures via more sophisticated designs. They may be more effective for scenarios where specific nodes or substructures in the graph are more crucial. We carefully review existing readout literatures and cover powerful candidates \(set2set\)[69], \(sort\_pooling\)[70], \(multiset\_pooling\)[49], and \(neural\_pooling\)[71] for this category. ### _GNN Fine-tuning Controller_ Based on proposed search space \(\{\mathcal{O}_{aug},\mathcal{O}_{fuse},\mathcal{O}_{read}\}\) for dimensions \(\{f_{aug}(\cdot),f_{fuse}(\cdot),f_{read}(\cdot)\}\), we then leverage the light-weighted controller \(\pi_{\boldsymbol{\alpha}}(\cdot)\) to allow the selection of most suitable GNN fine-tuning strategy \(\boldsymbol{\Phi}_{ft}=\{f_{aug}(\cdot)=?,f_{fuse}(\cdot)=?,f_{read}(\cdot)=?\}\) for each downstream task. We decompose the fine-tuning strategy search procedure into sub-steps and decisions are to be made for each proposed design dimension via their respective controllers. For the given design dimension with candidate-set \(\mathcal{O}\) (e.g., \(\mathcal{O}_{fuse}\)), we let the one-hot vector \(\boldsymbol{\Phi}_{ft}^{\mathcal{O}}\in\{0,1\}^{|\mathcal{O}|}\) record the optimal strategy for \(\mathcal{O}\). We let \(\pi_{\boldsymbol{\alpha}^{\mathcal{O}}}(\cdot)\) denote its controller parameterized by \(\boldsymbol{\alpha}^{\mathcal{O}}\), which records the importance weights of each candidate in \(\mathcal{O}\) that to be selected: \[\boldsymbol{\Phi}_{ft}^{\mathcal{O}}\sim\pi_{\boldsymbol{\alpha}^{\mathcal{O} }}(\cdot). \tag{27}\] Then, given some intermediate representation \(\mathbf{Z}_{in}\) as input, the output from this dimension can be calculated as: \[\mathbf{Z}_{out}=\sum_{i=1}^{|\mathcal{O}|}\boldsymbol{\Phi}_{ft}^{\mathcal{O} }[i]\cdot\mathcal{O}[i](\mathbf{Z}_{in}). \tag{28}\] \(\boldsymbol{\alpha}^{\mathcal{O}}\) need to be optimized such that the controller can yield improved fine-tuning strategy. However, the controller selection step in Eq. (27) is intrinsically discrete, which makes the entire model non-differentiable and thereby infeasible be optimized via back-propagation. To tackle this, we leverage the re-parameterization technique in [72], [73] to make the discrete process to be differentiable so that the entire S2PGNN model can be optimized via general gradient descend. Specifically, during forward-propagation stage, the selection (sampling) step in Eq. (27) is achieved via: \[\boldsymbol{\Phi}_{ft}^{\mathcal{O}}=onehot(\arg\max_{i}[\log \boldsymbol{\alpha}^{\mathcal{O}}[i]-\log(-\log(\boldsymbol{U}[i]))]), \tag{29}\] where \(\boldsymbol{U}\in\mathbb{R}^{|\mathcal{O}|}\) has same size as \(\boldsymbol{\alpha}^{\mathcal{O}}\) and each entry of it is sampled from the uniform distribution, i.e., \(\boldsymbol{U}[i]\sim Uniform(0,1)\). The induced \(-\log(-\log(\boldsymbol{U}[i]))\) is known as _Gumbel_ random variable [73]. Then, to approximate and back-propagate gradient \(\frac{\partial\boldsymbol{\Phi}_{ft}^{\mathcal{O}}}{\partial\boldsymbol{ \alpha}^{\mathcal{O}}}\), we follow [73] to unitize softmax as continuous relaxation towards \(\arg\max\): \[\boldsymbol{\Phi}_{ft}^{\mathcal{O}}=\frac{\exp((\log\boldsymbol{\alpha}^{ \mathcal{O}}[i]-\log(-\log(\boldsymbol{U}[i])))/\tau)}{\sum_{j=1}^{|\mathcal{O }|}\exp((\log\boldsymbol{\alpha}^{\mathcal{O}}[j]-\log(-\log(\boldsymbol{U}[ j])))/\tau)}, \tag{30}\] where \(\tau\) is the softmax temperature that controls discreteness. Note that \(\tau\to 0\) makes the continuous output from softmax Eq. (30) almost indistinguishable with the one-hot vector from \(\arg\max\) Eq. (29), which thereby ensures the continuous relaxation unbiased once converged. In this way, the controller can be jointly optimized with GNN model weights to solve the optimization objective in Eq. (23). \begin{table} \begin{tabular}{c|c|c|c} \hline \hline Type & Design Dimension & Candidate-set \(\mathcal{O}\) \\ \hline \hline \multirow{2}{*}{Inter-layer} & Identity Augmentation & \(f_{aug}(\cdot)\) & \(\{zero\_aug,identity\_aug,trans\_aug\}\) \\ \cline{2-4} & Multi-scale Fusion & \(f_{fuse}(\cdot)\) & \(\{last,concat,max,mean,ppr,lstm,gpr\}\) \\ \hline Graph-level & Graph-level Readout & \(f_{read}(\cdot)\) & \(\{sum\_pooling,mean\_pooling,max\_pooling,set2set,sort\_pooling,neural\_pooling\}\) \\ \hline \hline \end{tabular} \end{table} TABLE III: The GNN fine-tuning design space in S2PGNN: design dimensions and candidate-sets. ### _Optimization_ Empirically, we focus on the graph-level classification and regression tasks for the downstream molecular property prediction MPP (see more details for MPP task in Sec. IV-A3). To achieve the optimization goal in Eq. (23), we follow common practices to choose proper loss functions \(\mathcal{L}_{ft}(\cdot)\) for downstream graph dataset with labels \(\mathcal{D}_{ft}=\{(G,y)\}\). For the graph classification task, we leverage cross-entropy loss as Eq. (31), where \(C\) denotes the total number of graph classes in downstream dataset \(\mathcal{D}_{ft}\), \(\mathbf{Z}_{i}\in\mathbb{R}^{C}\) is the prediction results for \(i\)-th graph instance, and \(y_{i}\in\mathbb{R}\) is its true label. \[\mathcal{L}_{ft}(\cdot)=\frac{1}{|\mathcal{D}_{ft}|}\sum_{i=1}^{|\mathcal{D}_{ft }|}-log(\frac{\exp(\mathbf{Z}_{i}[y_{i}])}{\sum_{j=0}^{C-1}\exp(\mathbf{Z}_{i} [j])}). \tag{31}\] For the graph regression task, we utilize MSE loss as Eq. (32), where \(\hat{y}_{i}\in\mathbb{R}\) is the predicted value for \(i\)-th graph instance. \[\mathcal{L}_{ft}(\cdot)=\frac{1}{|\mathcal{D}_{ft}|}\sum_{i=1}^{|\mathcal{D}_ {ft}|}(y_{i}-\hat{y}_{i})^{2}. \tag{32}\] ## IV Experiments As presented in Sec. II, the GNN pre-training approach generally contains a GNN backbone model (e.g., GCN [7], SAGE [8]), a GNN pre-training strategy (e.g., MCM [20, 30], CL [58]) to transfer knowledge from a large scale of unlabeled graph data \(\mathcal{D}_{ssl}\), a GNN fine-tuning strategy (e.g., ST [20], RT [39]) to adapt the pre-trained GNNs to the domain-specific data with labels \(\mathcal{D}_{ft}\). In this paper, we mainly investigate the improvement from the perspective of automatically designing a suitable fine-tuning strategy for the given data \(\mathcal{D}_{ft}\). Thus, to validate the effectiveness of the proposed S2PGNN, we need to answer the following questions: * **Q1**: Can S2PGNN be built on the top of different GNN backbone and pre-training methods and consistently improve their performance? (see Sec. IV-B and Sec. IV-E) * **Q2**: On the same configuration of GNN backbone model and pre-training strategy, can S2PGNN be more effective than other GNN fine-tuning strategies? (see Sec. IV-C) * **Q3**: As discussed in Sec. II-B2, there are several classic fine-tuning strategies in other domains that are not included in our search space. Will these models perform well on the GNN area? (see Sec. IV-C) * **Q4**: What are the effect of each design dimensions in S2PGNN? (see Sec. IV-D) * **Q5**: Is there a risk that the fine-tuning search method will consume more computing resources to achieve improved performance? (see Sec. IV-F) ### _Experimental Settings_ S2PGNN 1 is implemented based on PyTorch [74] and PyTorch Geometric [75] libraries. All experiments are conducted with one single NVIDIA Tesla V100 GPU. Footnote 1: Code and data are available at [https://anonymous.4open.science/rcode_icde2024-A9CB](https://anonymous.4open.science/rcode_icde2024-A9CB). #### Iv-A1 GNN backbone models For GNN backbone architectures, we mainly adopt classic and promising GNNs in recent years, including (5-layer) GCN [7], SAGE [8], Graph Isomorphism Network (GIN) [10], and GAT [9] (see more details in Sec. II-A). But due to the limited space, the experiments in sections Sec. IV-B, Sec. IV-C, Sec. IV-D, and Sec. IV-F are conducted on GIN. And we report the performance on other backbone models in Sec. IV-E. #### Iv-A2 GNN pre-training methods and datasets \(\mathcal{D}_{ssl}\) To demonstrate the effectiveness of S2PGNN, we implement S2PGNN on top of 10 well-known and publicly available pre-training methods, including Infomax [58], EdgePred [8], ContextPred [20], AttrMasking [20], GraphCL [21], GraphLoG [22], MGSSL [23], SimGRACE [25], GraphMAE [26], and Mole-BERT [30]. As summarized in Tab. V, they cover a wide spectrum of various SSL strategies \(\mathcal{L}_{ssl}(\cdot)\) (see more details in Sec. II-B1). Due to the space limit, the fine-tuning experiments in Sec. IV-B are conducted on top of all 10 pre-trained models, and experiments in Sec. IV-C, Sec. IV-D, Sec. IV-F, and Sec. IV-F are built on top of the pioneering pre-training work ContextPred [20]. \begin{table} \begin{tabular}{l|l|l} \hline \hline **Method** & **SSL Strategy \(\mathcal{L}_{ssl}(\cdot)\)** & **SSL Data \(\mathcal{D}_{ssl}\)** \\ \hline \hline Infomax & Contrastive Learning (CL) & ZINC15 (2M) \\ \hline EdgePred & Autoencoding (AE) & ZINC15 (2M) \\ \hline ContextPred & Context Prediction (CP) & ZINC15 (2M) \\ \hline AttMasking & Masked Component Modeling (MCM) & ZINC15 (2M) \\ \hline GraphCL & Contrastive Learning (CL) & ZINC15 (2M) \\ \hline GraphLoG & Contrastive Learning (CL) & ZINC15 (2M) \\ \hline MGSSL & Autoregressive Modeling (AM) & ZINC15 (150K) \\ \hline SimGRACE & Contrastive Learning (CL) & ZINC15 (2M) \\ \hline GraphMAE & Autoencoding (AE) & ZINC15 (2M) \\ \hline Mole-BERT & Masked Component Modeling (MCM) & ZINC15 (2M) \\ \hline \hline \end{tabular} \end{table} TABLE V: Summary of base GNN pre-training methods. \begin{table} \begin{tabular}{l|l l l l l} \hline \hline **Dataset** & **\#Molecules** & **\#Tasks** & **Task Type** & **Metric** & **Domain** \\ \hline \hline BBBP & 2039 & 1 & Classification & ROC-AUC (\%) (\(\uparrow\)) & Pharmacology \\ \hline Tox21 & 7831 & 12 & Classification & ROC-AUC (\%) (\(\uparrow\)) & Pharmacology \\ \hline ToxCast & 8575 & 617 & Classification & ROC-AUC (\%) (\(\uparrow\)) & Pharmacology \\ \hline SIDER & 1427 & 27 & Classification & ROC-AUC (\%) (\(\uparrow\)) & Pharmacology \\ \hline ClinTox & 1478 & 2 & Classification & ROC-AUC (\%) (\(\uparrow\)) & Pharmacology \\ \hline BACE & 1513 & 1 & Classification & ROC-AUC (\%) (\(\uparrow\)) & Biophysics \\ \hline ESOL & 1128 & 1 & Regression & RMSE (\(\downarrow\)) & Physical Chemistry \\ \hline Lipophilicity (Lipo) & 4200 & 1 & Regression & RMSE (\(\downarrow\)) & Physical Chemistry \\ \hline \hline \end{tabular} \end{table} TABLE IV: Summary of downstream GNN fine-tuning datasets \(\mathcal{D}_{ft}\). In this paper, we follow the literature to adopt ZINC15 (150K) for MGSSL [23], which contains 150K unlabeled molecules collected from the ZINC15 database [76]. We use the larger version ZINC15 with 2 million molecules for methods other than MGSSL [23]. #### V-A3 GNN fine-tuning tasks and datasets \(\mathcal{D}_{ft}\) In this paper, we mainly conduct graph-level experiments on the downstream molecular property prediction (MPP), which is an important task for a variety of domains (e.g., physics, chemistry, and materials science). In MPP, a molecule is represented as a graph, where nodes and edges denote atoms and bonds, and labels are related to molecular toxicity or enzyme binding properties. The aim of MPP is to predict the properties for unlabeled molecule. We employ ROC-AUC and RMSE for evaluating the classifier and regressive MPP tasks, respectively. For datasets with multiple prediction tasks (see Tab. IV), we report average results over all their tasks. As shown in Tab. VI, we follow the related literature [20, 77] to adopt 8 popular benchmark datasets: BBBP [78], Tox21 [79], ToxCast [80], SIDER [81], ClinTox [82], BACE [83], ESOL [84], and Lipophilicity (Lipo) [85] that are provided in MoleculeNet [86]. The selected datasets are from several domains, including pharmacology, biophysics, and physical chemistry. Among them, ESOL and Lipo are used for graph regression, while the rest are for graph classification. As for data split, we utilize _scaffold-split_[37] to split molecular datasets according to their substructures as suggested by [20, 77]. It provides a more challenging yet more realistic split to deal with real-world applications (where out-of-distribution predictions are often required) compared with random-split. #### V-A4 Implementation details For GNN pre-training methods, we employ their officially released pre-trained models to conduct the next stage fine-tuning. Readers may refer to the original papers for their detailed pre-training settings. S2PGNN and other fine-tuning baselines are evaluated with the same protocol for rigorously fair comparisons. We follow pioneering literature [20] to setup fine-tuning configurations. Specifically, we leverage the simple linear classifier as downstream prediction head. To fine-tune the whole model, we use Adam optimizer with a learning rate of 1e-3. We set batch size as 32 and dropout rate as 50%. We perform fine-tuning for 100 epochs with early stopping based on validation set. The ratio to split train/validation/test set is 80%/10%/10%. We run all experiments for 10 times with different random seeds and report the mean results (standard deviations). ### _The implementation S2PGNN with Pre-trained GNNs and comparison with standard fine-tuning_ Despite the blooming development of GNN pre-training methods, the specific strategies for GNN fine-tuning (Eq. (14)) is still scarce. As discussed in Sec. II-B2, standard fine-tuning is probably still the most prevalent strategy to leverage pre-trained GNNs among existing literatures. Thus, we first implement and compare the gains of S2PGNN over standard fine-tuning on top of 10 GNN pre-training methods. The main results on 8 downstream datasets are reported in Tab. VI. When equipped with S2PGNN, the pre-trained GNNs consistently demonstrate better fine-tuning performances on the graph classification and graph regression tasks than the standard fine-tuning. The gains are consistent on different datasets with diverse characteristics (see Tab. IV). Moreover, we also observe the superiority of S2PGNN is agnostic to GNN pre-training configurations, such as SSL strategy, SSL data, and attained pre-trained models (see Sec. IV-A2 and Tab. V). To summarize, observations from Tab. VI validate that \begin{table} \begin{tabular}{c|c c c c c c c c|c} \hline \hline & \multicolumn{6}{c|}{**Classification (ROC-AUC (\%)) \(\uparrow\)**} & \multicolumn{3}{c|}{**Regression (RMSE) \(\downarrow\)**} & **Avg.** \\ \hline **Dataset** & BBBP & Tox21 & ToxCast & SIDER & ClinBox & BACE & ESOL & Lipo & **Gain** \\ \hline Infomax [58] & 68.4 \(\pm\) 1.7 & 75.6 \(\pm\) 0.5 & 62.5 \(\pm\) 0.8 & 58.3 \(\pm\) 0.7 & 71.3 \(\pm\) 2.6 & 75.5 \(\pm\) 2.3 & 2.6 \(\pm\) 0.1 & 1.0 \(\pm\) 0.1 & \multirow{2}{*}{\(+17.7\%\)} \\ Infomax + S2PGNN & **69.9 \(\pm\) 1.4** & **76.7 \(\pm\) 0.5** & **65.8 \(\pm\) 0.4** & **62.3 \(\pm\) 1.3** & **74.8 \(\pm\) 3.8** & **82.3 \(\pm\) 1.3** & **1.5 \(\pm\) 0.3** & **0.8 \(\pm\) 0.0** & \\ \hline EdgePred [8] & 67.2 \(\pm\) 2.9 & 75.8 \(\pm\) 0.9 & 63.9 \(\pm\) 0.4 & 60.5 \(\pm\) 0.8 & 65.7 \(\pm\) 4.1 & 79.4 \(\pm\) 1.4 & 2.8 \(\pm\) 0.0 & 1.0 \(\pm\) 0.1 & \\ EdgePred + S2PGNN & **69.1 \(\pm\) 0.8** & **77.1 \(\pm\) 0.8** & **66.2 \(\pm\) 0.3** & **62.3 \(\pm\) 0.5** & **71.9 \(\pm\) 1.1** & **82.2 \(\pm\) 1.1** & **1.7 \(\pm\) 0.2** & **0.9 \(\pm\) 0.0** & \\ \hline ContextPred [20] & 69.0 \(\pm\) 0.9 & 76.0 \(\pm\) 0.4 & 63.5 \(\pm\) 0.4 & 60.7 \(\pm\) 0.6 & 69.7 \(\pm\) 1.4 & 80.6 \(\pm\) 0.8 & 2.8 \(\pm\) 0.4 & 1.1 \(\pm\) 0.0 & \multirow{2}{*}{\(+15.1\%\)} \\ ContextPred + S2PGNN & **70.9 \(\pm\) 1.3** & **76.3 \(\pm\) 0.4** & **67.0 \(\pm\) 0.5** & **62.8 \(\pm\) 0.3** & **75.9 \(\pm\) 2.2** & **82.6 \(\pm\) 0.7** & **1.7 \(\pm\) 0.2** & **0.9 \(\pm\) 0.0** & \\ \hline AttrMasking [20] & 65.1 \(\pm\) 2.3 & 76.7 \(\pm\) 0.6 & 64.4 \(\pm\) 0.3 & 60.6 \(\pm\) 0.9 & 72.0 \(\pm\) 4.2 & 79.5 \(\pm\) 0.7 & 2.8 \(\pm\) 0.1 & 1.1 \(\pm\) 0.0 & \multirow{2}{*}{\(+15.6\%\)} \\ AttrMasking + S2PGNN & **71.9 \(\pm\) 1.1** & **77.3 \(\pm\) 0.4** & **66.8 \(\pm\) 0.5** & **62.9 \(\pm\) 0.4** & **74.8 \(\pm\) 3.1** & **82.7 \(\pm\) 0.8** & **1.7 \(\pm\) 0.1** & **0.9 \(\pm\) 0.0** & \\ \hline GraphCL [21] & 68.3 \(\pm\) 1.6 & 74.1 \(\pm\) 0.8 & 62.6 \(\pm\) 0.5 & 59.7 \(\pm\) 1.1 & 71.4 \(\pm\) 6.2 & 75.8 \(\pm\) 2.7 & 2.5 \(\pm\) 0.1 & 1.0 \(\pm\) 0.0 & \multirow{2}{*}{\(+10.1\%\)} \\ GraphCL + S2PGNN & **70.8 \(\pm\) 1.1** & **76.8 \(\pm\) 0.5** & **66.6 \(\pm\) 0.3** & **62.4 \(\pm\) 1.2** & **75.2 \(\pm\) 3.4** & **82.6 \(\pm\) 2.3** & **1.9 \(\pm\) 0.1** & **0.9 \(\pm\) 0.0** & \\ \hline GraphCLoG [22] & 66.5 \(\pm\) 2.3 & 75.3 \(\pm\) 0.3 & 63.3 \(\pm\) 0.5 & 57.8 \(\pm\) 1.2 & 69.6 \(\pm\) 5.8 & 80.1 \(\pm\) 2.4 & 2.5 \(\pm\) 0.1 & 1.0 \(\pm\) 0.0 & \multirow{2}{*}{\(+9.1\%\)} \\ GraphLod + S2PGNN & **69.9 \(\pm\) 1.5** & **76.8 \(\pm\) 0.3** & **66.1 \(\pm\) 0.2** & **62.0 \(\pm\) 1.0** & **75.8 \(\pm\) 2.1** & **85.1 \(\pm\) 1.3** & **2.0 \(\pm\) 0.1** & **0.9 \(\pm\) 0.0** & \\ \hline MGSSL [23] & 67.4 \(\pm\) 1.8 & 75.0 \(\pm\) 0.6 & 63.1 \(\pm\) 0.5 & 58.0 \(\pm\) 1.2 & 68.1 \(\pm\) 5.4 & 81.2 \(\pm\) 3.3 & 2.4 \(\pm\) 0.1 & 1.0 \(\pm\) 0.0 & \multirow{2}{*}{\(+9.6\%\)} \\ MGSSL + S2PGNN & **69.4 \(\pm\) 1.8** & **77.0 \(\pm\) 0.6** & **66.3 \(\pm\) 0.4** & **62.8 \(\pm\) 1.2** & **76.7 \(\pm\) 2.4** & **85.2 \(\pm\) 1.2** & **1.9 \(\pm\) 0.2** & **0.9 \(\pm\) 0.0** & \\ \hline SimGRACE [25] & 67.9 \(\pm\) 0.6 & 73.9 \(\pm\ S2PGNN fine-tuning provides a promisingly better solution than the standard strategy to achieve the better utilization of various pre-trained GNNs. ### _Comparison with other fine-tuning strategies_ As discussed in Sec. II-B2, we first investigate the standard fine-tuning and regularized fine-tuning strategies since they have already been adapted to the GNN area. Then, we explore more fine-tuning methods on other domains (e.g., computer vision) but have not been discussed in the GNN community. #### Iv-C1 GNN Fine-tuning Baselines Apart from the standard strategy (see main results in Sec. IV-B), we also compare S2PGNN with another GNN fine-tuning work GTOT-Tuning [39], which belongs to regularized fine-tuning. We exclude AUX-TS [32] and WordReg [38] for baseline comparisons because: AUX-TS targets on different downstream tasks, and WordReg uses different data split with [20] but its code is not publicly available for reproducing results. Besides, we additionally report the results of several regularized fine-tuning baselines tailored from the computer vision domain (that are originally designed to fine-tune CNNs), including \(L^{2}\)-_SP_[50], DELTA [51], BSS [52], and StochNorm [53]. \(L^{2}\)-_SP_ regularizes on model parameters to induce the fine-tuned weights to be close to pre-trained weights. DELTA imposes regularization on representations via the attention mechanism. BSS penalizes small eigenvalues of learned representations to suppress untransferable components. StochNorm regularizes on the encoder architecture in a dropout-like way. Please refer to Sec. II-B2 and Tab. II for more technical discussions. The comparisons on 6 classic MPP datasets have been summarized in Tab. VII. As shown in Tab. VII, we first observe the non-negligible improvement brought by S2PGNN compared with all baselines. Among baselines, regularized techniques (DELTA, BSS) from computer vision domain sometimes yield slightly better results than the standard fine-tuning strategy. However, in several cases (\(L^{2}\)-_SP_, StochNorm), the performance gains are not significant. This is probably due to their ignorance of characteristics in graph data (e.g., graph topology) and specific requirements in fine-tuning GNNs. By taking the graph topology into consideration, the method GTOT-Tuning, which is designed specifically to fine-tune GNNs, demonstrates higher performances than regularized variants extended from other domains. However, even the most competitive baseline GTOT-Tuning is still inferior to S2PGNN in 5 out of 6 datasets, indicating that the design dimensions proposed in S2PGNN (see Sec. III-B and Tab. II) may be indispensable and crucial designs towards more effective GNN fine-tuning. Furthermore, we note that various regularized strategies, such as GTOT-Tuning, is orthogonal to the proposed S2PGNN. Therefore, it may be promising to combine S2PGNN with other advanced regularized methods, i.e., combine an additional regularization term in S2PGNN's loss function Eq. (31) and (32) to further boost its performances, which we leave as future works. #### Iv-C2 Exploration of Other Fine-tuning Strategies As discussed in Sec. II-B2, fine-tuning has been well explored in the domains beyond GNNs. Therefore, we try to investigate the performance of more fine-tuning strategies that are promising in other domains. However, we conclude that they may not be suitable for fine-tuning GNNs, thereby we discard them from our search space. Overall, we explore following fine-tuning strategies: * Feature Extractor (FE): FE [87] proposes to reuse pre-trained model parameters to achieve better knowledge preservation. Once the pre-training is finished, all pre-trained layers are frozen and the pre-trained model works as a pure feature extractor for downstream data. Only a small amount of additional parameters in the task-specific prediction head are further tuned to perform downstream predictions. * Last-\(k\) Tuning (LKT): With LKT [88], only parameters in last-\(k\) layers of the pre-trained models are further tuned, while the other initial layers are frozen and keep unchanged. LKT resides between ST and FE, and is popular in the computer version area [88]. In our experiments, we consider \(k\in\{1,2,3\}\), which means we use around \(20\%\sim 60\%\) tunable parameters of the original model (where \(k=5\)) * Adapter-Tuning (AT): AT [34] proposes to fine-tune only a small number of extra model parameters to attain the competitive performance, which is promising to achieve faster tuning and alleviate the over-fitting issue in natural language process and computer vision areas. More specifically, it adds small and task-specific neural network modules, called adapters, to pre-trained models. These adapters involve feature transformation \(\mathbb{R}^{d}\rightarrow\mathbb{R}^{m}\rightarrow\mathbb{R}^{d}\) via the bottleneck architecture, where \(m\ll d\) is to ensure parameter-efficient. Adapters are inserted between pre-trained layers and trained on the specific task, while the pre-trained layers remain \begin{table} \begin{tabular}{c|c c c c c c|c} \hline \hline & \multicolumn{6}{c|}{**Classification (ROC-AUC (\%))**} & \multirow{2}{*}{**Avg.**} \\ \cline{2-2} \cline{5-7} **Dataset** & BBBP & Tox21 & ToxCast & SIDER & ClinTox & BACE \\ \hline Vanilla tuning & 68.0 \(\pm\) 2.0 & 75.7 \(\pm\) 0.7 & 63.9 \(\pm\) 0.6 & 60.9 \(\pm\) 0.6 & 65.9 \(\pm\) 3.8 & 79.6 \(\pm\) 1.2 & 69.0 \\ \hline \(L^{2}\)-_SP_[50] & 68.2 \(\pm\) 0.7 & 73.6 \(\pm\) 0.8 & 62.4 \(\pm\) 0.3 & 61.1 \(\pm\) 0.7 & 68.1 \(\pm\) 3.7 & 82.2 \(\pm\) 2.4 & 69.3 \\ DELTA [51] & 67.8 \(\pm\) 0.8 & 75.2 \(\pm\) 0.5 & 63.3 \(\pm\) 0.5 & 62.2 \(\pm\) 0.4 & 73.4 \(\pm\) 3.0 & 81.8 \(\pm\) 1.1 & 70.6 \\ BSS [52] & 68.1 \(\pm\) 1.4 & 75.9 \(\pm\) 0.8 & 63.9 \(\pm\) 0.4 & 60.9 \(\pm\) 0.8 & 70.9 \(\pm\) 5.1 & 82.4 \(\pm\) 1.8 & 70.4 \\ StochNorm [53] & 69.3 \(\pm\) 1.6 & 74.9 \(\pm\) 0.6 & 63.4 \(\pm\) 0.5 & 61.0 \(\pm\) 1.1 & 65.5 \(\pm\) 4.2 & 80.5 \(\pm\) 2.7 & 69.1 \\ \hline GTOT-tuning [39] & 70.0 \(\pm\) 1.7 & 75.2 \(\pm\) 0.9 & 63.0 \(\pm\) 0.5 & **63.1 \(\pm\) 0.6** & 71.8 \(\pm\) 5.4 & 82.6 \(\pm\) 2.0 & 71.0 \\ \hline S2PGNN & **70.9 \(\pm\) 1.3** & **76.3 \(\pm\) 0.4** & **67.0 \(\pm\) 0.5** & 62.8 \(\pm\) 0.3 & **75.9 \(\pm\) 2.2** & **82.6 \(\pm\) 0.7** & **72.6** \\ \hline \hline \end{tabular} \end{table} TABLE VII: The performance comparison between proposed S2PGNN fine-tuning and other fine-tuning strategies with fixed ContextPred pre-training objective and GIN backbone architecture. fixed and unchanged to preserve the knowledge learned during pre-training. In our empirical explorations, we tailor the adapter design in [34] and consider adapter size \(m\in\{2,4,8\}\) to use only around \(1.3\%\sim 5.2\%\) tunable parameters of the original model (where \(d=300\)). The results on classic MPP tasks are summarized in Tab. VIII. Clearly, S2PGNN demonstrates consistent superior results than other approaches. Directly using the pre-trained GNN as pure feature extractor (equivalent to \(k=0\)) can reduce the total number of tunable parameters during fine-tuning, but it leads to the severe performance degradation on all 6 datasets. This indicates that the fixed model may impede sufficient adaption when dealing with various downstream datasets. By gradually increasing the tunable layers \(k\) (\(1\to 3\)), the performance drop caused by insufficient adaption is mitigated. However, by tuning only partial model parameters, Last-\(k\) still yield inferior results than the standard strategy (equivalent to \(k=5\)). Adapter method, although has demonstrated competitive fine-tuning capacity with the standard strategy when fine-tuning language models in natural language processing domain, fails to yield satisfactory results when fine-tuning GNNs for graph data. To summarize, by investigating more fine-tuning strategies that are promising in other domains, we conclude that they may not be suitable for fine-tuning GNNs, which is probably due to the divergence among different domains. Instead, specific and innovative designs to fine-tune GNNs in graph domain is much more demanded. The performance comparison in Tab. VIII also indicates that the design dimensions in S2PGNN's search space may be more validated for searching the suitable fine-tuning strategy in pre-trained GNNs. ### _Ablation study on S2PGNN's design dimensions_ To investigate S2PGNN's important design dimensions (see Sec. III-B) regarding GNN fine-tuning strategy: identity augmentation, multi-scale fusion, and adaptive graph-level readout, we further propose S2PGNN variants with degraded space and conduct ablation studies: S2PGNN-\(\backslash id\_aug\) disables identity augmentation when aggregating messages from neighbors; S2PGNN-\(\backslash fuse\) discards the multi-scale fusion and directly uses the last-layer output as learned node representations as most existing works does; S2PGNN-\(\backslash read\) uses the simple and fixed mean pooling as [20] and follow-up works. The man results of S2PGNN's variants are shown in Tab. IX. Significant performances drop are observed in each S2PGNN variant with degraded space, which provide empirical vali Fig. 4: Illustration to other fine-tuning strategies (refer to Fig. 3 for the legend). \begin{table} \begin{tabular}{c|c c c c c c|c} \hline \hline & \multicolumn{6}{c|}{**Classification (ROC-AUC (\%)) \(\uparrow\)**} & **Avg.** \\ \hline **Dataset** & BBBP & Tox21 & ToxCast & SIDER & ClinTox & BACE \\ \hline Vanilla tuning & 68.0 \(\pm\) 2.0 & 75.7 \(\pm\) 0.7 & 63.9 \(\pm\) 0.6 & 60.9 \(\pm\) 0.6 & 65.9 \(\pm\) 3.8 & 79.6 \(\pm\) 1.2 & 69.0 \\ \hline Feature extractor & 58.9 \(\pm\) 0.4 & 68.7 \(\pm\) 0.4 & 59.3 \(\pm\) 0.2 & 59.9 \(\pm\) 0.3 & 40.5 \(\pm\) 2.7 & 61.6 \(\pm\) 4.5 & 58.2 \\ \hline Last-\(k\) (\(k=3\)) & 68.1 \(\pm\) 0.9 & 75.1 \(\pm\) 0.4 & 64.0 \(\pm\) 0.5 & 60.7 \(\pm\) 0.5 & 63.9 \(\pm\) 4.5 & 79.1 \(\pm\) 1.2 & 68.5 \\ Last-\(k\) (\(k=2\)) & 65.3 \(\pm\) 1.0 & 74.5 \(\pm\) 0.5 & 63.0 \(\pm\) 0.7 & 61.6 \(\pm\) 0.6 & 64.0 \(\pm\) 3.5 & 80.6 \(\pm\) 1.2 & 68.2 \\ Last-\(k\) (\(k=1\)) & 64.6 \(\pm\) 1.3 & 73.0 \(\pm\) 0.5 & 61.4 \(\pm\) 0.5 & 60.8 \(\pm\) 0.5 & 66.1 \(\pm\) 2.4 & 76.6 \(\pm\) 0.8 & 67.1 \\ \hline Adapter (\(m=2\)) & 61.2 \(\pm\) 0.4 & 71.4 \(\pm\) 0.3 & 60.6 \(\pm\) 0.1 & 59.6 \(\pm\) 0.3 & 45.3 \(\pm\) 3.1 & 71.1 \(\pm\) 0.9 & 61.6 \\ Adapter (\(m=4\)) & 62.5 \(\pm\) 0.7 & 71.7 \(\pm\) 0.3 & 60.6 \(\pm\) 0.2 & 59.6 \(\pm\) 0.3 & 47.4 \(\pm\) 2.2 & 74.4 \(\pm\) 1.8 & 62.7 \\ Adapter (\(m=8\)) & 63.9 \(\pm\) 0.7 & 71.8 \(\pm\) 0.3 & 60.5 \(\pm\) 0.4 & 59.9 \(\pm\) 0.3 & 50.0 \(\pm\) 1.0 & 76.8 \(\pm\) 0.9 & 63.8 \\ \hline S2PGNN & **70.9 \(\pm\) 1.3** & **76.3 \(\pm\) 0.4** & **67.0 \(\pm\) 0.5** & **62.8 \(\pm\) 0.3** & **75.9 \(\pm\) 2.2** & **82.6 \(\pm\) 0.7** & **72.6** \\ \hline \hline \end{tabular} \end{table} TABLE VIII: The performance of more fine-tuning strategies that are excluded from S2PGNNX’s design space with fixed ContextPred pre-training objective and GIN backbone architecture. Second best results are marked with underline. dation that the proposed design dimensions in S2PGNN are key factors that affect GNN fine-tuning results and should be incorporated during fine-tuning to achieve the optimal downstream results. ### _Effect of GNN backbone architectures_ Recent works [89] have identified that GNN backbone architectures also play a crucial role in GNN pre-training. Therefore, here we further provide additional results of S2PGNN when built on top of other classic GNN backbone architectures other than the GIN. Tab. X summarizes the performance of S2PGNN based on several pre-trained GNNs, including GCN, SAGE, and GAT models via the SSL strategy ContextPred [20]. We observe that pre-trained GNNs with all these backbone architectures can benefit from S2PGNN fine-tuning and achieve better performances than the vanilla strategy. This verifies that S2PGNN is agnostic to the base GNN architectures and is capable to achieve the consistent improvement. ### _Efficiency_ Apart from the effectiveness results provided in previous subsections, here we further report the concrete running time comparisons among several fine-tuning baselines. As shown in Tab. XI, we observe that the running time of S2PGNN is comparable with fine-tuning baselines, which eliminates the concern that the fine-tuning search method in S2PGNN may consume more computing resources to achieve improved performance. ## V Conclusion In this paper, to bridge the missing gap between better fine-tuning strategies with pre-trained GNNs, we propose to search to fine-tune pre-trained graph neural networks for graph classification, named S2PGNN. To improve the utilization of pre-trained GNNs, S2PGNN adaptively designs a suitable fine-tuning strategy for the given pre-trained GNN and downstream dataset. S2PGNN presents a novel search space for fine-tuning strategies, which identifies key factors that affect GNN fine-tuning results. S2PGNN is model-agnostic and can be plugged into existing GNN backbone models and pre-trained GNNs. Empirical studies demonstrate that S2PGNN can consistently improve 10 classic pre-trained GNNs and achieve better performance than other fine-tuning works. Therefore, we expect S2PGNN may shed light on potential future directions towards better GNN fine-tuning innovation. \begin{table} \begin{tabular}{c|c c c c c c|c} \hline \hline & \multicolumn{6}{c|}{**Classification (ROC-AUC (\%)) \(\uparrow\)**} & \multicolumn{2}{c|}{**Regression (RMSE) \(\downarrow\)**} & **Avg.** \\ \hline **Dataset** & BBBP & Tox21 & ToxCast & SIDER & ClinTox & BACE & ESOL & Lipo & **Gain** \\ \hline ContextPred (GCN) & 64.6 \(\pm\) 2.2 & 73.0 \(\pm\) 0.5 & 61.9 \(\pm\) 1.1 & 56.8 \(\pm\) 0.6 & 69.0 \(\pm\) 1.3 & 79.9 \(\pm\) 1.7 & 2.4 \(\pm\) 0.1 & **1.0 \(\pm\) 0.0** & \(+\)4.6\(\%\) \\ ContextPred (GCN) + S2PGNN & **68.3 \(\pm\) 1.0** & **75.7 \(\pm\) 0.5** & **66.5 \(\pm\) 0.3** & **62.3 \(\pm\) 0.4** & **71.6 \(\pm\) 1.3** & **81.5 \(\pm\) 0.5** & **2.3 \(\pm\) 0.1** & **1.0 \(\pm\) 0.0** & \(+\)4.6\(\%\) \\ \hline ContextPred (SAGE) & 6.0 \(\pm\) 3.0 & 74.7 \(\pm\) 0.5 & 63.4 \(\pm\) 0.2 & **62.0 \(\pm\) 0.6** & 61.1 \(\pm\) 3.1 & 78.8 \(\pm\) 1.4 & 2.5 \(\pm\) 0.1 & **1.0 \(\pm\) 0.0** & \(+\)6.0\(\%\) \\ ContextPred (SAGE) + S2PGNN & **69.0 \(\pm\) 1.4** & **75.1 \(\pm\) 0.4** & **66.4 \(\pm\) 0.6** & 61.6 \(\pm\) 0.4 & **67.1 \(\pm\) 1.6** & **79.1 \(\pm\) 0.7** & **2.0 \(\pm\) 0.2** & **1.0 \(\pm\) 0.0** & \(+\)6.0\(\%\) \\ \hline ContextPred (GAT) & 64.9 \(\pm\) 1.2 & 69.6 \(\pm\) 0.7 & 59.5 \(\pm\) 0.8 & 52.5 \(\pm\) 3.4 & 58.2 \(\pm\) 6.9 & 60.5 \(\pm\) 3.5 & 3.2 \(\pm\) 0.1 & 1.1 \(\pm\) 0.0 & \(+\)19.7\(\%\) \\ ContextPred (GAT) + S2PGNN & **69.6 \(\pm\) 0.9** & **75.0 \(\pm\) 0.4** & **65.3 \(\pm\) 0.3** & **61.8 \(\pm\) 1.1** & **66.7 \(\pm\) 3.2** & **80.4 \(\pm\) 1.3** & **1.8 \(\pm\) 0.1** & **1.0 \(\pm\) 0.0** & \(+\)19.7\(\%\) \\ \hline \hline \end{tabular} \end{table} TABLE X: The performance comparison between proposed S2PGNN fine-tuning and standard fine-tuning strategies with fixed ContextPred pre-training objective and other popular GNN backbone architectures. \begin{table} \begin{tabular}{c|c c c c c c|c c} \hline \hline & \multicolumn{6}{c|}{**Classification (ROC-AUC (\%)) \(\uparrow\)**} & \multicolumn{2}{c|}{**Regression (RMSE) \(\downarrow\)**} & **Avg.** \\ \hline **Dataset** & BBBP & Tox21 & ToxCast & SIDER & ClinTox & BACE & ESOL & Lipo & **Drop** \\ \hline S2PGNN\(\shortdownarrow\)_aug_ & 69.5 \(\pm\) 2.0 & 75.9 \(\pm\) 0.3 & 66.3 \(\pm\) 0.4 & 61.3 \(\pm\) 0.7 & 69.4 \(\pm\) 6.3 & 79.5 \(\pm\) 1.6 & 2.0 \(\pm\) 0.3 & 0.9 \(\pm\) 0.0 & \(-\)5.2\(\%\) \\ S2PGNN\(\shortuparrow\)_base_ & 69.0 \(\pm\) 1.5 & 75.7 \(\pm\) 0.6 & 65.7 \(\pm\) 0.4 & 61.6 \(\pm\) 0.7 & 61.6 \(\pm\) 4.4 & 82.0 \(\pm\) 1.0 & 2.5 \(\pm\) 0.1 & 1.0 \(\pm\) 0.0 & \(-\)12.1\(\%\) \\ S2PGNN\(\shortmid\)_read_ & 70.3 \(\pm\) 1.6 & 75.2 \(\pm\) 0.3 & 63.9 \(\pm\) 0.3 & 62.2 \(\pm\) 0.7 & 73.7 \(\pm\) 4.4 & 80.3 \(\pm\) 1.7 & 2.7 \(\pm\) 0.0 & 1.0 \(\pm\) 0.0 & \(-\)12.3\(\%\) \\ S2PGNN & **70.9 \(\pm\) 1.3** & **76.3 \(\pm\) 0.4** & **67.0 \(\pm\) 0.5** & **62.8 \(\pm\) 0.3** & **75.9 \(\pm\) 2.2** & **82.6 \(\pm\) 0.7** & **1.7 \(\pm\) 0.2** & **0.9 \(\pm\) 0.0** & - \\ \hline \hline \end{tabular} \end{table} TABLE IX: The performance comparison among S2PGNN’s variants with degraded space. \begin{table} \begin{tabular}{c|c c c c c|c} \hline \hline & \multicolumn{6}{c|}{**Classification (ROC-AUC (\%)) \(\uparrow\)**} & \multicolumn{2}{c|}{**Regression (RMSE) \(\downarrow\)**} & **Avg.** \\ \hline **Dataset** & BBBP & Tox21 & ToxCast & SIDER & ClinTox & BACE & ESOL & Lipo & **Gain** \\ \hline **ContextPred (GCN)** & 64.6 \(\pm\) 2.2 & 73.0 \(\pm\) 0.5 & 61.9 \(\pm\) 1.1 & 56.8 \(\pm\) 0.6 & 69.0 \(\pm\) 1.3 & 79.9 \(\pm\) 1.7 & 2.4 \(\pm\) 0.1 & **1.0 \(\pm\) 0.0** & \(+\)4.0\(\%\) \\ ContextPred (GCN) + S2PGNN & **68.3 \(\pm\) 1.0** & **75.7 \(\pm\) 0.8** & **66.5 \(\pm\) 0.3** & **62.3 \(\pm\) 0.4** & **71.6 \(\pm\) 1.3** & **81.5 \(\pm\) 0.5** & **2.3 \(\pm\) 0.1** & **1.0 \(\pm\) 0.0** & \(+\)4.6\(\%\) \\ \hline ContextPred (SAGE) & 6.0 \(\pm\) 3.0 & 74.7 \(\pm\) 0.5 & 63.4 \(\pm\) 0.2 & **62.0 \(\pm\) 0.6** & 61.1 \(\pm\) 3.1 & 78.8 \(\pm\) 1.4 & 2.5 \(\pm\) 0.1 & **1.0 \(\pm\) 0.0** & \(+\)6.0\(\%\) \\ ContextPred (SAGE) + S2PGNN & **69.0 \(\pm\) 1.4** & **75.1 \(\pm\) 0.4** & **66.4 \(\pm\) 0.6** & 61.6 \(\pm\) 0.4 & **67.1 \(\pm\) 1.6** & **79.1 \(\pm\) 0.7** & **2.0 \(\pm\) 0.2** & **1.0 \(\pm\) 0.0** & \(+\)6.0\(\%\) \\ \hline Context
2303.02874
Adversarial Sampling for Fairness Testing in Deep Neural Network
In this research, we focus on the usage of adversarial sampling to test for the fairness in the prediction of deep neural network model across different classes of image in a given dataset. While several framework had been proposed to ensure robustness of machine learning model against adversarial attack, some of which includes adversarial training algorithm. There is still the pitfall that adversarial training algorithm tends to cause disparity in accuracy and robustness among different group. Our research is aimed at using adversarial sampling to test for fairness in the prediction of deep neural network model across different classes or categories of image in a given dataset. We successfully demonstrated a new method of ensuring fairness across various group of input in deep neural network classifier. We trained our neural network model on the original image, and without training our model on the perturbed or attacked image. When we feed the adversarial samplings to our model, it was able to predict the original category/ class of the image the adversarial sample belongs to. We also introduced and used the separation of concern concept from software engineering whereby there is an additional standalone filter layer that filters perturbed image by heavily removing the noise or attack before automatically passing it to the network for classification, we were able to have accuracy of 93.3%. Cifar-10 dataset have ten categories of dataset, and so, in order to account for fairness, we applied our hypothesis across each categories of dataset and were able to get a consistent result and accuracy.
Tosin Ige, William Marfo, Justin Tonkinson, Sikiru Adewale, Bolanle Hafiz Matti
2023-03-06T03:55:37Z
http://arxiv.org/abs/2303.02874v1
# Adversarial Sampling for Fairness Testing in Deep Neural Network ###### Abstract In this research, we focus on the usage of adversarial sampling to test for the fairness in the prediction of deep neural network model across different classes of image in a given dataset. While several framework had been proposed to ensure robustness of machine learning model against adversarial attack, some of which includes adversarial training algorithm. There is still the pitfall that adversarial training algorithm tends to cause disparity in accuracy and robustness among different group. Our research is aimed at using adversarial sampling to test for fairness in the prediction of deep neural network model across different classes or categories of image in a given dataset. We successfully demonstrated a new method of ensuring fairness across various group of input in deep neural network classifier. We trained our neural network model on the original image, and without training our model on the perturbed or attacked image. When we feed the adversarial samplings to our model, it was able to predict the original category/ class of the image the adversarial sample belongs to. We also introduced and used the separation of concern concept from software engineering whereby there is an additional standalone filter layer that filters perturbed image by heavily removing the noise or attack before automatically passing it to the network for classification, we were able to have accuracy of 93.3%. Cifar-10 dataset have ten categories of dataset, and so, in order to account for fairness, we applied our hypothesis across each categories of dataset and were able to get a consistent result and accuracy. Adversarial machine learning, adversarial attack; adversarial defense; machine learning fairness; fairness testing; adversarial sampling; deep neural network Vol. 14, No. 2, 2023 ## I Introduction With some of the latest advances in artificial intelligence, deep learning (DL) can now be applied in areas as diverse as, face recognition system [19], fraud detection system [20], and natural language processing (NLP) [21]. As deep neural network model continues to be increasingly associated with important decision in our daily life, we cannot just view it as only a mathematical abstraction but also as a technical system for the modern society[22],[18][17]. Apart from looking at the various metrics to better understand and evaluate the logic behind the prediction of machine learning model, it is also imperative to look at the ethics in order not to infringe on people's privacy in which the ability to ensure fairness across all groups without bias in dnn model prediction is of serious concern to the community[23], while it is possible to have intentional or unintentional discriminatory pattern in dataset[24] which are being used to train a dnn model, it is imperative and to have some mechanism to identify such discrimination in dataset before training model with it as such discrimination in dataset are eventually passed onto the trained model when the model is trained with discriminatory dataset especially when the discrimination is among the minority and the vulnerable in the society. There are several forms in which discrimination can exists in dataset set, some of the forms includes group discrimination [25], [26] and individual discrimination [27], [28],[29]. Some of this discrimination can also be defined over a set of certain attributes such as gender, race age and so on., and when a machine learning model is trained with a discriminatory dataset, such discrimination in dataset is always passed to the trained model which make the model to make bias prediction over the same group being discriminated against in the dataset and this can be seen when ML model makes different decisions for different individuals (individual discrimination) or subgroups (group discrimination). Note that the set of protected attributes is often application-dependent and given in advance. Our research work is focussed on the usage of adversarial sampling to test for the fairness in the prediction of deep neural network model across different classes of image in a given dataset. We are not dealing with the problem of individual discrimination or samples that differs only by some protected features. We aimed to use adversarial sampling to test for fairness in a dnn model, while also making an avenue for scaling the fairness through the misclassification rate across all group of image. Several adversarial samples were generated from the original image through several adversarial sampling techniques which includes Calini & Wagner, fast gradient sign method (FGSM), adversarial patch, gradient base evasion, and projected Gradient Descent (PGD). Although proposals and conceptual framework had been researched and formulated to address the issue of fairness in ML model [30], [31], [32]. One example is THEMIS randomly samples each attribute within its domain and identifies those discriminative samples [30], and also AEQUITAS which aims to improves the testing effectiveness with a two-phase (global and local) search [31] while SG [32] combines the local explanation of model [33] along with the symbolic execution [34] to cause an increment both in the discriminatory samples and diversity ## II Background Adversarial machine learning deals with the study of attacks on machine learning algorithms, and of the defenses against such attacks.[1].Many years ago, the focus of machine learning engineers and scientist was on obtaining high accuracy for correct prediction, and while this had greatly been resolve in the past few years. The new challenge had focused on adversarial attack and defense against machine learning model there had been series of research survey which establish the need for protecting machine learning model against various forms of attach which make it to misclassify [2]. During the training of machine learning model, it is usually assumed that the training and test data are generated from the same statistical distribution. This assumption makes the final model vulnerable to various forms of attack, majority of which includes evasion attacks, [3] data poisoning attacks, [4] Byzantine attacks [5] and model extraction [6]. ### _Current Adversarial Techniques_ #### Iii-A1 Gradient-based evasion attack In gradient base evasion attack, a perturbed image which seems like untampered to human eyes is made to be misclassified by neural network model (Fig. 1)[35]. We can carry out this type of attack by trial and error method as we don't know in advance, the exact data manipulation that will break the model and make it to classify. Let say we want to probe the boundaries of a machine learning model designed to filter out spam emails, it is possible for us to experiment by sending different emails to see what gets through. And so, a model has been trained for certain words like "momentum", and now we want to make an exceptions for emails that contains other words, if we want to attack, we can craft email with enough extraneous words which will eventually make the model to misclassify it. ### _Fast Gradient Sign Method (FGSM)_ Let's assume we want to produce an adversarial sample x' = x + \(\eta\) such that x' is misclassified by the neural network. For us to make x' and x produce different outputs, \(\eta\) should be greater than the precision of the features. Let's represent pixel of an image by 8 bits, and we want any information below 1/255 of the dynamic range to be discarded. Here, the input is perturbed with the gradient of the loss with respect to the input which gradually increases magnitude of the loss until the input is eventually misclassified. While \(\varepsilon\) decides both the size and sign of each and every element of the perturbation vector which might be matrix or tensor which are being determined by the sign of the input gradient. Here, we just have to linearize the cost function and find the perturbation that maximizes the cost subject to an L\(\infty\) constraint. This technique causes varieties of models to misclassify input and is also faster than other methods #### Iii-A1 Projected gradient descent (PGD) PGD initializes the sample to a random point in the ball of interest which is being decided by the L\(\infty\) norm and does random restarts. This applies the same step as FGSM multiple times with a small step size while at the same time clipping the pixel values of intermediate results of each step to ensure that they are in an \(\varepsilon\)-neighborhood of the original image the value of \(\alpha\) used is 1 which means that pixel values are changed only by 1 at each step while the number of iterations were heuristically chosen. This made it sufficient enough for the adversarial example to reach the edge of the \(\varepsilon\) max-norm ball. #### Iii-A2 Carlini and wagner (C&W) attack Berkeley, Nicholas Carlini and David Wagner in 2016 propose a faster and more robust method to generate adversarial examples [7]. The attack proposed by Carlini and Wagner begins with trying to solve a difficult non-linear optimization equation. However instead of directly the above equation, Carlini and Wagner propose using a different function and then propose the use of the below function in place of f using z, a function that determines class probabilities for given input x. With the use of stochastically gradient descent, we can use the above equation to produce a very strong adversarial sample especially when we compare it to fast gradient sign method which can effectively bypass a defensive distillation technique which was previously proposed for adversarial defense [7, 8, 9, 10]. #### Iii-A3 Adversarial patch attack Adversarial patch can be devised to fool a machine learning models. They work by causing physical obstruction in an image or by randomizing images with algorithm. Since computer vision models are trained on images that are straight forward. It is inevitable that Fig. 1: Adversarial sampling based on addition of perturbation [35] any alteration to the input image can make the model to misclassify depending on the severity of the alteration. We could define a patch function p corresponding to every transformation t ET which applies the transformed patch onto the image and Hadamard product, and the final adversarial perturbed image \(\hat{\mathbf{x}}\) which must satisfy \(\hat{\mathbf{x}}=\mathrm{p_{t}}(\mathbf{x};\hat{\mathbf{Z}})\) in order to trained patch z and some t ET. For us in order to train patch \(\hat{\mathbf{z}}\), we could use a variant of the Expectation over Transformations (EOT) framework of Athalye et al. [3]. Let's assume a family of transformations T, a distance metric d in the transformed space, and the objective is to find a perturbed image \(\hat{\mathbf{x}}\) As the image is expected to be within \(\Theta\)ball in anticipation for transformations T. The attack could find some unconstrained optimization problem. The adversarial patch exploits the way machine learning model are trained for image classification by producing more salient inputs than real world objects. Such salient inputs are misclassified when fed to a machine learning model ### _Current Defense Strategy and Limitation_ #### Ii-C1 Adversarial training Adversarial training is a form of brute force supervised learning technique where several adversarial examples are fed into the model and are explicitly labeled as threatening. The approach is similar to a typical antivirus software, which is constantly being updated on a regular basis. As effective as adversarial training may be in defense against adversarial attack, it still requires continuous maintenance or update in order to be effective in combating new threats and it is still suffering from the fundamental problem of the fact that it can only successfully defend against threats or attack that has already happened and is already trained against. #### Ii-C2 Randomization Several adversarial defense methods relied on randomization as a technique for mitigating the effects of adversarial Perturbations in the input and/or feature domain [11]. The idea behind this defense technique is the robustness of deep neural network model to random perturbation. The aim of randomization-based defense is to randomize the adversarial effects of the adversarial sampling into several random effects which is a very ok and normal thing for varieties of deep neural network models. High success had been achieved by successful defense of Randomization-based defense technique against both black-box and gray-box based attacks, but it is still vulnerable white-box based attack, for example, the EoT method [12] can be easily attacked and compromised simply by considering the randomization process during attack. #### Ii-C3 Denoising In denoising several research works had pointed to both input denoising and feature denoising as a technique for an effective adversarial defense. While input denoising is aimed at complete of partial removal of perturbation from the adversarial samplings or input, feature denoising is aimed at alleviating, reducing or mitigating effects of adversarial perturbation on important features i.e features that are more impactful on the decision of deep neural network model. Several methods had been proposed for denoising as a technique for adversarial defense such as conventional input denoising, GAN-based input denoising, auto encoder-based input denoising, feature denoising. Each of these methods of denoising had been shown to be vulnerable to one form of adversarial attack or another. For instance, Sharma and Chen [13] had shown that input squeezing can bypass by EAD, While good performance was achieved on Testbed by APE-GAN techniques[14], it is easily defeated by white-box based attack[16], As for auto encoder-based input denoising, Carlini and Wagner [15],[16] successfully demonstrated that it is vulnerable to the adversarial samples generated by attack, but with feature denoising, research had shown that it merely increase accuracy by 3% which makes it vulnerable to PGD attack. ## III Research Methodology Fairness when using adversarial sampling as input had shown to cause disparity in accuracy and robustness among different groups [16]. Our method of approach is such as to investigate the cause and offer a solution. The methodologies were in three(s) phases of activities; ### _Phase-1: Development and Optimization of DNN Model from Scratch_ We created a python project in jupyter notebook and created a deep neural network model (DNN) for image classification. We used cifar-10 dataset which consists of 60000 colored images with each image having 32x32 dimensions and categorized into 10 classes of image [Airplane, Automobile, Bird, Cat, Deer, Dog, Frog, Horse, Ship, Truck], with each category containing 6000 colored images. The whole 50000 images in the training dataset folder of cifar-10 was used for training our DNN model while the 10000 images in the test folder of cifar-10 dataset was used to validate our model. With an initial accuracy of 72%, we needed a higher accuracy and hence, we did some hyper parameter turning by adjusting the learning rate, the number of convolusional layers, and adding some regularization until we are able to get a good accuracy that we can work with, after which we decide to compile and save our new model with KERAS being a high level neural network library that runs on tensorflow. ### _Phase-2: Generation of Adversarial Sampling_ Another python class was created in jupyter notebook in which we wrote algorithms for several adversarial attacks. We wrote adversarial algorithm for adding various kind of noise perturbation to all the images in the training folder (adversarial sampling) (Fig. 2). The algorithm automatically creates new folder and then puts all the adversarial sampling into the new folder. The adversarial folder which contains all the perturbed image or adversarial sampling is named **doga** (Fig. 3). At this point, it was needful for us to test our model with the newly created adversarial sampling to see if it will misclassify those images, having satisfied the criteria of misclassification, it was needful for us to test for fairness across each of the 10 categories of images in the cifar-10 dataset. To actualize this, we separated each category of image in the cifar-10 dataset as separate entity and then observe the accuracy of misclassification across each entity to see if the accuracy of misclassification for each entity will be close, and indeed the accuracy of misclassification for each of the 10 categories of images were closely called which ensure fairness across each group. ### _Phase-3: Evaluation and Removal of perturbation_ This is a very tricky part, as several methods had been proposed with little or no effectiveness. Here, we write algorithm to remove the perturbation, considering the existence of several adversarial attack, we wrote an algorithm to remove all forms of perturbation while at the same trying to maintain the original property of the image. The algorithm iterate through all the images in the adversarial folder where we have our adversarial samplings and remove perturbation in each of them, and in the process creating a new folder name **dogscan** where all the clean images from the adversarial folder are saved (Fig. 4). ### _Phase-4: Evaluation and Removal of perturbation_ This is a very tricky part, as several methods had been proposed with little or no effectiveness. Here, we write algorithm to remove the perturbation, considering the existence of several adversarial attack, we wrote an algorithm to remove all forms of perturbation while at the same trying to maintain the original property of the image. The algorithm iterate through all the images in the adversarial folder where we have our adversarial samplings and remove perturbation in each of them, and in the process creating a new folder name **dogscan** where all the clean images from the adversarial folder are saved (Fig. 4). Fig. 4: Images in the dogsa-clean folder after passing through the new separation of concern layer from software engineering concept Fig. 3: Generated adversarial sampling in the dogsa folder after iteration and noise attack Fig. 2: Creation and addition of random gaussian noise distribution to image having image path and position as argument At this point, we wrote few lines of python code to load our model through keras, and iterating through each of the images in the **dogsa-clean** folder where the cleaned images are saved and observe the result. After this, each categories of image were treated as separate entity to account for fairness across each group of images. ## IV Result and Discussion On iterating through each category of adversarial samplings in our adversarial folder to see the rate of misclassification across each image, it was found that there is unfairness as some of classes have high rate of positive misclassification than the others. The rate of misclassification was not consistent as Airplane, Automobile, and truck (Fig. 5) has very low rate of misclassification compared with other groups, calini & wagner form of adversarial attack were added to them, while also updating the learning rate and regularization of our initial model and rebuild. The purpose of this is to ensure fairness and consistency across all the classes of image through consistence rate of misclassification (Fig. 6). With some consistencies in the rate of misclassification, series of algorithms were written to remove greater part of the noises and perturbation for better accuracy. Rather than labeling the attacked images as invalid input, we want the model to be able to predict the attacked images correctly and classify them to the category of images they belonged to. We wrote an algorithm to iterate through all the images in our adversarial folder, remove as much pertubation and denoise as possible while creating a new folder **dogsa-clean** to store all the new images. Substantial lines of python codes where written to iterate through various classes of cleaned and denoised images in our dogsa-clean folder, and feeding them to the DNN model. To our surprise and amazement, without making any further hyper-parameter tuning, we were able to have high rate of fairness and consistency across each of the classes of clean images while still maintaining a very good accuracy of prediction in our classifier. ## V Conclusion In this research, we successfully demonstrate a new method of ensuring fairness across various group of input in deep neural network classifier. Rather than the existing method of training the model on the adversarial sample and label them as invalid. We trained our neural network model on the original image, and without training our model on the perturbed or attacked image. When we feed the adversarial samplings to our model, it was able to predict the original category' class of the image the adversarial sample belong to. Through our, method we were able to achieve fairness across all the categories of images in the cifar-10 dataset. We also introduce Separation of Concern (SOC) method from full stark software engineering which ensures that we can manage the filter layer as separate entity at any point in the development life cycle without re-training the model. Surprisingly, we tried to compare the true rate and false rate of fairness for the adversarial sampling across each of the classes of image with that of the cleaned images. We found that the fairness rate was high, consistent and almost the same without any hyper parameter tuning or modification to the filter layer. ## VI Limitation and Future Research In this research, we use the existing forms of adversarial attack for the images. However, we envisage that there will be more sophisticated forms of attack in the future. It is for this reason that we adopt the model of separation of concern from software engineering for our filter layer. In the event of a more robust and sophisticated attack, rather than going back to development to retrain our model, we only need to improve the filter layer. In addition, the filter layer can be made into a cloud based handy toolbox library. In that case, the filter layer can be managed in the cloud against any future robust attack and be automatically available to all existing deployed model. ### _Material and Source_ We use python 3.9 for this project, pip version 22.3.1, tensorflow, keras to save, load and consume our model and a host of other python libraries. Our source code for the hypothesis and experiment on this research had been uploaded to github and is made available to the public, and can be accessed through the Uniform Resource Locator (URL) below: [https://github.com/IGETOSIN1/Research-Adversarial-Sampling-for-Fairness-Testing](https://github.com/IGETOSIN1/Research-Adversarial-Sampling-for-Fairness-Testing)
2305.13349
Multiclass classification for multidimensional functional data through deep neural networks
The intrinsically infinite-dimensional features of the functional observations over multidimensional domains render the standard classification methods effectively inapplicable. To address this problem, we introduce a novel multiclass functional deep neural network (mfDNN) classifier as an innovative data mining and classification tool. Specifically, we consider sparse deep neural network architecture with rectifier linear unit (ReLU) activation function and minimize the cross-entropy loss in the multiclass classification setup. This neural network architecture allows us to employ modern computational tools in the implementation. The convergence rates of the misclassification risk functions are also derived for both fully observed and discretely observed multidimensional functional data. We demonstrate the performance of mfDNN on simulated data and several benchmark datasets from different application domains.
Shuoyang Wang, Guanqun Cao
2023-05-22T16:56:01Z
http://arxiv.org/abs/2305.13349v2
# Multiclass classification for multidimensional functional data through deep neural networks ###### Abstract The intrinsically infinite-dimensional features of the functional observations over multidimensional domains render the standard classification methods effectively inapplicable. To address this problem, we introduce a novel multiclass functional deep neural network (mfDNN) classifier as an innovative data mining and classification tool. Specifically, we consider sparse deep neural network architecture with rectifier linear unit (ReLU) activation function and minimize the cross-entropy loss in the multiclass classification setup. This neural network architecture allows us to employ modern computational tools in the implementation. The convergence rates of the misclassification risk functions are also derived for both fully observed and discretely observed multidimensional functional data. We demonstrate the performance of mfDNN on simulated data and several benchmark datasets from different application domains. P 62G05, 62G08; secondary 62G35. [table]capposition=top **MSC2020 subject classifications:** Primary 62G05, 62G08; secondary 62G35. Functional data analysis, Deep Neural networks, Multiclass classification, Rate of convergence, Multidimensional functional data. ## 1 Introduction Functional data classification has wide applications in many areas such as machine learning and artificial intelligence [19, 10, 17, 5]. While the majority of the work on functional data classification focuses on one-dimensional functional data cases, for example, temperature data over a certain period [16], and speech recognition data (log-periodogram data) [11, 23], and there are few results obtained for multidimensional functional data classification, for example, 2D or 3D images classification. To the best of our knowledge, there is only one recent work [22] where binary classification for general non-Gaussian multidimensional functional data was considered. However, their proposed classifier is designed for fully observed functional data and only able to conduct binary classification. There is also a lack of literature working on multiclass classification for functional data. [11] investigated a Bayesian approach to estimate parameters in multiclass functional models. However, their method is still only suitable for fully observed one-dimensional functional data classification. The availability of massive databases resulted in the development of scalable machine learning methods to process these data. In this paper, we are interested in multiclass classification for multidimensional functional data, including but not limited to 2D and 3D imaging data classification, in the framework of DNN. The existing statistical and machine learning methods belong to the general framework of multivariate analysis. That is, data are treated as vectors of discrete samples and permutation of components will not affect the analysis results, hence the ordering of the pixels or voxels is irrelevant in these analyses and the imaging data were treated as high-dimensional data. In recent years, many sparse discriminant analysis methods have been proposed for i.i.d. high-dimensional data classification and variable selection. Most of these proposals focus on binary classification and they are not directly applicable to multiclass classification problems. A popular multiclass sparse discriminant analysis proposal is the \(\ell_{1}\) penalized Fisher's discriminant [24]. However, [24] does not have theoretical justifications. It is generally unknown how close their estimated discriminant directions are to the true directions, and whether the final classifier will work similarly as the Bayes rule. More recently, [14] proposed a multiclass sparse discriminant analysis method that estimates all discriminant directions simultaneously with theoretical justification for high-dimensional data setting. We compare our method with both [24] and [14] carefully on numerical performance in Sections 5 and 6. An efficient way to handle multi-dimensional functional data, for example, imaging data, is to incorporate the information that is inherent in order and smoothness of processes over pixels or voxels. In this paper, we propose a novel approach, called as multi-class functional deep neural network (mfDNN, multiclass-functional+DNN), for multidimensional functional data multiclass classification. We extract the functional principal components scores (FPCs) of the data functions, and then train a DNN based classifier on these FPCs as well as their corresponding class memberships. Given these FPCs as inputs and their corresponding class labels as outputs, we consider sparse deep ReLU network architecture and minimize the cross-entropy (CE) loss in the multiclass classification setup. CE loss is a standard tool in machine learning classification, but the technique has not been utilized to its fullest potential in the context of functional data classification, especially regarding the study of theoretical properties of DNN classifiers. A recent work [2], has an example of multiclassification by minimizing CE loss in sparse DNN for cross-sectional data setting. While the powerful capabilities of DNN and CE loss have been clearly demonstrated for i.i.d. data, how to best adapt these models to functional data remains under-explored. We apply the same loss function in [2] but develop it in the context of multidimensional functional multiclassification. Furthermore, convergence rates and the conditional class probabilities are developed under both fully observed and discretely observed multi-dimensional functional data setting, respectively. The rest of this article is organized as follows. In Section 2, we introduce the \(K\)-class functional data classification models and propose the multiclass functional deep neural network classifiers. In Section 3, we establish theoretical properties of mfDNN under suitable technical assumptions. Section 4 provides two progressive examples to demonstrate the validity of these technical assumptions. In Section 5, performances of mfDNN and its competitors are demonstrated through simulation studies. The corresponding R programs for implementing our method are provided on GitHub. In Section 6, we apply mfDNN to the zip code dataset and Alzeheimer's Disease data. Section 7 summarizes the conclusions. Technical proofs are provided in Appendix. ## 2 Methodology ### \(K\)-class functional data classification models Suppose we observe \(n\) i.i.d. functional training samples \(\{(X_{i}(s),\mathbf{Y}_{i}):1\leq i\leq n,s\in\left[0,1\right]^{d}\}\), which are independent of \(X(s)\) to be classified, and class label \(\mathbf{Y}_{i}=(Y_{i1},\ldots,Y_{iK})^{\mathsf{T}}\), such that \(Y_{ik}=1\) if the sample is in the \(k\)-th group, \(k=1,2,\ldots,K\), and \(0\) otherwise. Throughout the entire paper, we consider the number of class \(K\) is a universal constant not depending on sample size \(n\). In multiclass classification with \(K\geq 2\) classes, we are interested in grouping a newly observed continuous curves \(X(s)\) to one of the \(K\) classes given the training data. If \(Y_{ik}=1\), \(X_{i}(s)\) presumably has some unknown mean function \(\mathbb{E}X_{i}(s)=\mu_{k}(s)\) and unknown covariance function \(\Omega_{k}(s,s^{\prime})=\mathbb{E}\left[\left(X_{i}(s)-\mu_{k}(s)\right)(X_{ i}(s^{\prime})-\mu_{k}(s^{\prime}))\right]\), for \(s,s^{\prime}\in\left[0,1\right]^{d}\) and \(1\leq k\leq K\). Suppose the covariance function \(\Omega_{k}(\cdot,\cdot)\) satisfies the Karhunen-Loeve decomposition: \[\Omega_{k}(s,s^{\prime})=\sum_{j=1}^{\infty}\lambda_{kj}\psi_{kj}(s)\psi_{kj} (s^{\prime}),s,s^{\prime}\in\left[0,1\right]^{d}, \tag{1}\] where \(\psi_{kj}\), \(j\geq 1\) is an orthonormal basis of \(L^{2}(\left[0,1\right]^{d})\) with respect to the usual \(L^{2}\) inner product, and \(\lambda_{k1}\geq\lambda_{k2}\geq\cdots>0\) are nonincreasing positive eigenvalues. For any \(X(s)\in L^{2}(\left[0,1\right]^{d})\) under the \(k\)-th class, write \(X(s)=\sum_{j=1}^{\infty}\xi_{j}\psi_{kj}(s)\), where \(\xi_{j}\)'s are pairwise uncorrelated random coefficients. By projecting the function space to vector space, we define the conditional probabilities \[\pi_{k}(\mathbf{x})=\mathrm{P}(\mathbf{Y}=\mathbf{e}_{k}|\mathbf{\xi}=\mathbf{x}),\ \ k\in\{1,\ldots,K\},\] where \(\mathbf{e}_{k}=(0,\ldots,0,1,0,\ldots,0)^{\mathsf{T}}\) is a \(K\)-dimensional standard basis vector denoting the label of the k-th class is observed and \(\mathbf{\xi}=(\xi_{1},\xi_{2},\ldots)^{\mathsf{T}}\) is an infinite dimension random vector. Notably, \(\sum_{k=1}^{K}\pi_{k}(\mathbf{x})=1\) for any \(\mathbf{x}\in\mathbb{R}^{\infty}\). ### Multiclass functional deep neural network classifier For \(k\in\{1,\ldots,K\}\), define sample covariance function \[\widehat{\Omega}_{k}(s,s^{\prime})=\frac{1}{n_{k}}\sum_{i\in I_{k}}(X_{i}(s)- \bar{X}_{k}(s))(X_{i}(s^{\prime})-\bar{X}_{k}(s^{\prime})),\ \ s,s^{\prime}\in\left[0,1\right]^{d},\] where \(I_{k}\) is the collection of \(i\) such that \(Y_{ik}=1\), \(n_{k}=|I_{k}|\) is the sample size, and \(\bar{X}_{k}(s)=n_{k}^{-1}\sum_{i\in I_{k}}X_{i}(s)\) is the sample mean function of class \(k\). The Karhunen-Loeve decomposition for \(\widehat{\Omega}_{k}\) is \[\widehat{\Omega}_{k}(s,s^{\prime})=\sum_{j=1}^{\infty}\widehat{\lambda}_{kj} \widehat{\psi}_{kj}(s)\widehat{\psi}_{kj}(s^{\prime}),s,s^{\prime}\in\left[0,1 \right]^{d}.\] The sample data function \(X_{i}(s)\), \(i=1,\ldots,n\), under \(Y_{ik}=1\), can be represented as \(X_{i}(s)=\sum_{j=1}^{\infty}\widehat{\xi}_{ij}\widehat{\psi}_{kj}(s)\). Intuitively, \(\widehat{\boldsymbol{\xi}}^{(i)}:=(\widehat{\xi}_{i1},\widehat{\xi}_{i2},\ldots)\) is an estimator of \(\boldsymbol{\xi}^{(i)}:=(\xi_{i1},\xi_{i2},\ldots)\), in which \(\xi_{ij}\)'s are unobservable random coefficients of \(X_{i}\) with respect to the population basis \(\psi_{kj}\). Hence, it is natural to design classifiers based on \(\widehat{\boldsymbol{\xi}}^{(i)}\)'s. Let \(\widehat{\boldsymbol{\xi}}_{J}^{(i)}=(\widehat{\xi}_{i1},\ldots,\widehat{\xi }_{iJ})^{\intercal}\) be the \(J\)-dimensional truncation of \(\widehat{\boldsymbol{\xi}}^{(i)}\) for \(i=1,\ldots,n\). Denote \(h_{k}(\cdot)\) as the conditional probability densities of \(\boldsymbol{\xi}\) given \(\boldsymbol{Y}=\boldsymbol{e}_{k}\), such that \(\pi_{k}(\boldsymbol{x})=\frac{h_{k}\mathbf{P}(\boldsymbol{Y}=\boldsymbol{e}_ {k})}{\sum_{\ell=1}^{K}h_{\ell}\mathbf{P}(\boldsymbol{Y}=\boldsymbol{e}_{\ell })}\). When \(X_{i}\)'s are some random processes with complex structures, such as non-Gaussian processes, one major challenge is the underlying complicated form of \(\{h_{k}\}_{k=1}^{K}\) so that estimation of \(\{\pi_{k}\}_{k=1}^{K}\) is typically difficult. In this section, inspired by the rich approximation power of DNN, we propose a new classifier so-called mfDNN, which can still approach Bayes classifiers closely even when \(h_{k}\)'s are non-Gaussian and complicated. Let \(\sigma(x)=(x)_{+}\) be the ReLU activation function, and \(K\)-dimensional softmax activation function \(\boldsymbol{\sigma}^{*}(\boldsymbol{y})=\left(\frac{\exp{(y_{1})}}{\sum_{k=1} ^{K}\exp{(y_{k})}},\ldots,\frac{\exp{(y_{K})}}{\sum_{k=1}^{K}\exp{(y_{k})}}\right)\) for \(\boldsymbol{y}=(y_{1},\ldots,y_{K})\in\mathbb{R}^{K}\). For any real vectors \(\boldsymbol{V}=(v_{1},\ldots,v_{w})^{\intercal}\) and \(\boldsymbol{z}=(z_{1},\ldots,z_{w})^{\intercal}\), define the shift activation function \(\sigma_{\boldsymbol{V}}(\boldsymbol{z})=(\sigma(z_{1}-v_{1}),\ldots,\sigma(z _{w}-v_{w}))^{\intercal}\). For \(L\geq 1\), \(\boldsymbol{p}=(p_{1},\ldots,p_{L})\in\mathbb{N}^{L}\), let \(\mathcal{F}(L,J,\boldsymbol{p})\) denote the class of fully connected feedforward DNN with \(J\) inputs, \(L\) hidden layers and, for \(l=1,\ldots,L\), \(p_{l}\) nodes on the \(l\)-th hidden layer. Equivalently, any \(f\in\mathcal{F}(L,J,\boldsymbol{p})\) has an expression \[f(\boldsymbol{x})=\boldsymbol{\sigma}^{*}\mathbf{W}_{L}\sigma_{\mathbf{V}_{L} }\mathbf{W}_{L-1}\sigma_{\mathbf{V}_{L-1}}\ldots\mathbf{W}_{1}\sigma_{\mathbf{ V}_{1}}\mathbf{W}_{0}\boldsymbol{x},\ \ \ \boldsymbol{x}\in\mathbb{R}^{J}, \tag{2.2}\] where \(\mathbf{W}_{l}\in\mathbb{R}^{p_{l+1}\times p_{l}}\), for \(l=0,\ldots,L\), are weight matrices, \(\boldsymbol{V}_{l}\in\mathbb{R}^{p_{l}}\), for \(l=1,\ldots,L\), are shift vectors. Here, we adopt the convention that \(p_{0}=J\) and \(p_{L+1}=1\). Due to the large capacity of the fully connected DNN class and to avoid overparameterization, we consider the following sparse DNN class: \[\mathcal{F}(L,J,\boldsymbol{p},s)= \tag{2.3}\] \[\left\{f\in\mathcal{F}(L,J,\boldsymbol{p}):\sum_{l=0}^{L}\| \mathbf{W}_{l}\|_{0}+\|\mathbf{V}_{l}\|_{0}\leq s,\max_{0\leq l\leq L}\|\mathbf{ W}_{l}\|_{\infty}\vee\|\mathbf{V}_{l}\|_{\infty}\leq 1\right\},\] where \(\|\cdot\|_{\infty}\) denotes the maximum-entry norm of a matrix/vector, which is controlled by \(1\), \(\|\cdot\|_{0}\) denotes the number of non-zero elements of a matrix/vector, and \(s\) controls the total number of active neurons. Given the training data \((\boldsymbol{\xi}_{J}^{(1)},\boldsymbol{Y}_{1}),\ldots,(\boldsymbol{\xi}_{J}^ {(n)},\boldsymbol{Y}_{n})\), let \[\widehat{\boldsymbol{f}}_{\phi}(\cdot)=\left(\widehat{f}_{\phi}^{(1)},\ldots, \widehat{f}_{\phi}^{(K)}\right)^{\intercal}=\arg\min_{\boldsymbol{f}\in \mathcal{F}(L,J,\boldsymbol{p},s)}-\frac{1}{n}\sum_{i=1}^{n}\phi(\boldsymbol{Y }_{i},\boldsymbol{f}(\boldsymbol{\tilde{\xi}}_{J}^{(i)})), \tag{2.4}\] where \(\phi(\boldsymbol{x}_{1},\boldsymbol{x}_{2})=\boldsymbol{x}_{1}^{\intercal}\log {(\boldsymbol{x}_{2})}\) denotes the CE loss function. We then propose the following mfDNN classifier: for \(X\in L^{2}([0,1]^{d})\), \[\widehat{G}^{mfDNN}(X)=k,\ \ \text{if}\ \widehat{f}_{\phi}^{(k)}(\boldsymbol{\xi}_{J} )\geq\widehat{f}_{\phi}^{(k^{\prime})}(\boldsymbol{\xi}_{J}),\ \ \text{for all}\ \ 1\leq k^{\prime}\neq k\leq K. \tag{2.5}\] The detailed implementation for the proposed mfDNN classifier is explained in Algorithm 1. The tuning parameters include \(J,L,\boldsymbol{p}\), and \(s\), which theoretically contribute to the performance of classification. We discuss the related theories in Section 3. In practice, we suggest the following data-splitting approach to select \((J,L,\mathbf{p},s)\). Note that the sparsity is not directly applicable by assigning the number of active neurons. Instead, we use dropout technique to achieve sparse network. ``` Input: Collection of samples \(\left\{\left\{X_{i}(s_{j})\right\}_{j=1}^{m},\mathbf{Y}_{i}\right\}_{i=1}^{n}\), training index set \(\mathcal{I}_{1}\), testing index set \(\mathcal{I}_{2}\), \(|\mathcal{I}_{1}|=\left\lfloor 0.7n\right\rfloor\), \(|\mathcal{I}_{2}|=\left\lfloor 0.3n\right\rfloor\), candidates for number of projection scores \(\left\{J_{0},\ldots,J_{N_{1}}\right\}\), candidates for depth \(\left\{L_{0},\ldots,L_{N_{2}}\right\}\), candidates for width \(\left\{p_{0},\ldots,p_{N_{3}}\right\}\), candidates for dropout rates \(\left\{s_{0},\ldots,s_{N_{4}}\right\}\), number of epochs, batch size, learning rate Output:\(\left\{\widehat{G}^{mHDNN}(X_{i})\right\}_{i=1}^{n}\) 1 Extract \(\widehat{\mathbf{\xi}}_{J}^{(i)}\) from \(\left\{X_{i}(s_{j})\right\}_{i,j=1}^{n,m}\) by integration, and \(J=\max\{J_{0},\ldots,J_{N_{1}}\}\) 2 For all candidates, (i) Train \(\widehat{\mathbf{f}}_{J\ell_{1},L_{\ell_{2}},p_{\ell_{3}},s_{\ell_{4}}}\) by Equation (2.4) with \(\left(\{X_{i}(s_{j})\}_{j=1}^{m},\mathbf{Y}_{i}\right)_{i\in\mathcal{I}_{1}}\). (ii) Compute \(\text{err}(\ell_{1},\ell_{2},\ell_{3},\ell_{4}):=\frac{1}{|\mathcal{I}_{2}|} \sum_{i\in\mathcal{I}_{2}}I(\widehat{\mathbf{f}}_{J\ell_{1},L_{\ell_{2}},p_{\ell_ {3}},s_{\ell_{4}}}\neq\mathbf{Y}_{i})\) Obtain \(\left(J_{\ell_{1}^{\star}},L_{\ell_{2}^{\star}},p_{\ell_{3}^{\star}},s_{\ell_ {4}^{\star}}\right)=\arg\min_{\ell_{1},\ell_{2},\ell_{3},\ell_{4}}\text{ err}(\ell_{1},\ell_{2},\ell_{3},\ell_{4})\) Train \(\widehat{\mathbf{f}}_{J\ell_{1}^{\star},L_{\ell_{2}^{\star}},p_{\ell_{3}^{\star}},s _{\ell_{4}^{\star}}}\) by Equation (2.4) with \(\left(\{X_{i}(s_{j})\}_{j=1}^{m},\mathbf{Y}_{i}\right)_{i=1}^{n}\) ``` **Algorithm 1**Training algorithm for mfDNN ## 3 Theoretical properties ### Functional data space #### 3.1.1 Assumptions for functional multi-classification setup To formulate our classification task, we first introduce two mild assumptions for \(\pi_{k}(\cdot)\). Without further notice, \(c\), \(C\), \(C_{1}\), \(C_{2}\),..., represent some positive constants and can vary from line to line. **Assumption 1**.: _(Boundary condition) There exist an absolute constant \(C>0\) and some positive vector \(\mathbf{\alpha}=(\alpha_{1},\ldots,\alpha_{K})^{\intercal}\) such that_ \[\mathrm{P}\left(\pi_{k}(\mathbf{\xi})\leq x\right)\leq Cx^{\alpha_{k}},\qquad \forall x\in\left(0,1\right],\forall k\in\{1,\ldots,K\}. \tag{3.1}\] Assumption 1 describes the behaviour of \(\pi_{k}\) around \(0\). Trivially, when \(\alpha_{k}=0\) for \(k=1,\ldots,K\), the condition holds universally only if \(C\geq 1\). Similar conditions can be found for multi-class classification for multivariate data in [2] and binary classification in [15] and [20]. **Assumption 2**.: _(Uniform lower bound) There exists a relatively small \(\epsilon\in(0,1)\), such that_ \[\mathrm{P}\left(\pi_{k}(\mathbf{\xi})>\epsilon\right)=1\] _for all \(k=1,\ldots,K\)._ Assumption 2 provides a uniform lower bound of \(\pi_{k}\), indicating that \(\pi_{k}\) is bounded away from \(\epsilon\) in probability. **Remark 1**.: _Assumptions 1 and 2 both depict the characteristic of \(\pi_{k}\) around zero in different aspects. Specifically, Assumption 1 controls the decay rate of the probability measure of \(\{\pi_{k}(\boldsymbol{\xi}):0\leq\pi_{k}(\boldsymbol{\xi})\leq x\}\). Assumption 2 truncates the probability measure below \(\epsilon\) to be zero. It can be seen that Assumptions 1 and 2 are closely related in certain circumstances. For example, given some \(\epsilon>0\), Assumption 2 implies Assumption 1 for arbitrary \(\boldsymbol{\alpha}\) and \(C=\max_{k}\epsilon^{-\alpha_{k}}\), and Assumption 1 implies Assumption 2 when \(C=0\) in a trivial case. However, they are not equivalent in most scenarios when \(C\), \(\{\boldsymbol{\alpha}_{k}\}_{k=1}^{K}\), and \(\epsilon\) are all universally positive constants._ Essentially, functional data have intrinsically infinite dimension. Owing to this unique phenomenon, we introduce the following finite approximation condition for \(\boldsymbol{\pi}\). For any positive integer \(J\), define \(\boldsymbol{\xi}^{(J)}=(\xi_{1},\ldots,\xi_{J})^{\intercal}\) and \(\boldsymbol{\pi}_{J}(\boldsymbol{x}_{J})=\left(\pi_{1}^{(J)}(\boldsymbol{x}_{ J}),\ldots,\pi_{K}^{(J)}(\boldsymbol{x}_{J})\right)^{\intercal}\), where \(\pi_{k}^{(J)}(\boldsymbol{x}_{J})=\mathrm{P}(\boldsymbol{Y}_{k}=\boldsymbol{ e}_{k}|\boldsymbol{\xi}_{J}=\boldsymbol{x}_{J})\), \(k=1,\ldots,K\). **Assumption 3**.: _(Approximation error of \(\pi_{k}^{(J)}\)) There exist a constant \(J_{0}\geq 1\) and decreasing functions \(\zeta(\cdot):[1,\infty)\to\mathbb{R}_{+}\) and \(\Gamma(\cdot):[0,\infty)\to\mathbb{R}_{+}\), with \(\sup_{J\geq 1}J^{\varrho}\zeta(J)<\infty\) for some \(\varrho>0\) and \(\int_{0}^{\infty}\Gamma(x)dx<\infty\), such that for any \(J\geq J_{0}\), \(k=1\ldots,K\) and \(x>0\),_ \[\mathrm{P}\left(|\pi_{k}(\boldsymbol{\xi})-\pi_{k}^{(J)}(\boldsymbol{\xi}_{J}) |\geq x\right)\leq\zeta(J)\Gamma(x). \tag{3.2}\] Assumption 3 provides a uniform upper bound on the probability of \(\pi_{k}\) differing from \(\pi_{k}^{(J)}\) by at least \(x\), which approaches zero if either \(J\) or \(x\) tends to infinity, implying that when dimension is reduced, there exists some large enough \(J\), such that \(\pi_{k}^{(J)}\) is an accurate approximation of \(\pi_{k}\). All three assumptions can be verified in concrete examples included in Section 4. #### 3.1.2 Conditional probability \(\pi_{k}\) with complex structure In the following, we impose composition structures on \(\pi_{k}(\cdot)\). For \(t\geq 1\), a measurable subset \(D\subset\mathbb{R}^{t}\), and constants \(\beta,R>0\), define \[\mathcal{C}^{\beta}(D,R) = \left\{f:D\mapsto\mathbb{R}\big{|}\sum_{\boldsymbol{\alpha}:| \boldsymbol{\alpha}|<\beta}\|\partial^{\boldsymbol{\alpha}}f\|_{\infty}f\right.\] \[\left.+\sum_{\boldsymbol{\alpha}:|\boldsymbol{\alpha}|=\lfloor \beta\rfloor}\sup_{\boldsymbol{z},\boldsymbol{z}^{\prime}\in D,\boldsymbol{z }\neq\boldsymbol{z}^{\prime}}\frac{|\partial^{\boldsymbol{\alpha}}f( \boldsymbol{z})-\partial^{\alpha}f(\boldsymbol{z}^{\prime})|}{\|\boldsymbol{z }-\boldsymbol{z}^{\prime}\|_{\infty}^{\beta-\lfloor\beta\rfloor}}\leq R\right\},\] where \(\partial^{\boldsymbol{\alpha}}\) = \(\partial^{\alpha_{1}}\ldots\partial^{\alpha_{t}}\) denotes the partial differential operator with multi-index \(\boldsymbol{\alpha}\) = \((\alpha_{1},\ldots,\alpha_{t})\in\mathbb{N}^{t}\), \(|\boldsymbol{\alpha}|=\alpha_{1}+\cdots+\alpha_{t}\). Equivalently, \(\mathcal{C}^{\beta}(D,C)\) is the ball of \(\beta\)-Holder smooth functions on \(D\) with radius \(R\). A function \(f:\mathbb{R}^{t}\to\mathbb{R}\) is said to be locally \(\beta\)-Holder smooth if for any \(a,b\in\mathbb{R}\), there exists a constant \(C\) (possibly depending on \(a,b\)) such that \(f\in\mathcal{C}^{\beta}([a,b]^{t},C)\). For \(q\geq 0,J\geq 1\), let \(d_{0}=J\) and \(d_{q+1}=1\). For \(\mathbf{d}=(d_{1},\ldots,d_{q})\in\mathbb{N}_{+}^{q}\), \(\mathbf{t}=(t_{0},\ldots,t_{q})\in\mathbb{N}_{+}^{q+1}\) with \(t_{u}\leq d_{u}\) for \(u=0,\ldots,q\), \(\mathbf{\beta}:=(\beta_{0},\ldots,\beta_{q})\in\mathbb{R}_{+}^{q+1}\), let \(\mathcal{G}(q,J,\mathbf{d},\mathbf{t},\mathbf{\beta})\) be the class of functions \(g\) satisfying a modular expression \[g(\mathbf{z})=g_{q}\circ\cdots\circ g_{0}(\mathbf{z})\in(0,1)\,,\ \forall\mathbf{z}\in \mathbb{R}^{d_{0}}, \tag{3.3}\] where \(g_{u}=(g_{u1},\ldots,g_{ud_{u+1}}):\mathbb{R}^{d_{u}}\mapsto\mathbb{R}^{d_{u +1}}\) and \(g_{uv}:\mathbb{R}^{t_{u}}\mapsto\mathbb{R}\) are locally \(\beta_{u}\)-Holder smooth. The \(d_{u}\) arguments of \(g_{u}\) are locally connected in the sense that each component \(g_{uv}\) only relies on \(t_{u}(\leq d_{u})\) arguments. Similar structures have been considered by [18, 1, 13, 21, 2, 9, 8] in multivariate regression or classification to overcome high-dimensionality. Generalized additive model [7] and tensor product space ANOVA model [12] are special cases; see [13]. We define the class of \(\mathbf{h}=\{h_{1},\ldots,h_{K}\}\) as \[\mathcal{H}\equiv \mathcal{H}\left(K,\{q^{(k)}\}_{k=1}^{K},\{\mathbf{d}^{(k)}\}_{k=1}^{ K},\{\mathbf{t}^{(k)}\}_{k=1}^{K},\{\mathbf{\beta}^{(k)}\}_{k=1}^{K},\{\alpha_{k}\}_{k= 1}^{K},\{\pi_{k}(\cdot)\}_{k=1}^{K},\right.\] \[\left.\zeta(\cdot),\Gamma(\cdot),C,\rho,\epsilon\right),\] such that for any \(J\geq 1\), \(\pi_{k}^{(J)}\in\mathcal{G}\left(q^{(k)},J,\mathbf{d}^{(k)},\mathbf{t}^{(k)},\mathbf{ \beta}^{(k)}\right)\), where \(\mathbf{d}^{(k)}=(d_{1}^{(k)},\ldots,d_{q^{(k)}}^{(k)})\)\(\in\mathbb{N}_{+}^{q^{(k)}}\), \(\mathbf{t}^{(k)}=(t_{0}^{(k)},\ldots,t_{q^{(k)}}^{(k)})\in\mathbb{N}_{+}^{q^{(k)}+1}\) with \(t_{u}^{(k)}\leq d_{u}^{(k)}\) for \(u=0,\ldots,q^{(k)}\), \(\mathbf{\beta}^{(k)}:=(\beta_{0},\ldots,\beta_{q^{(k)}}^{(k)})\in\mathbb{R}_{+}^{q ^{(k)}+1}\). Note that this density class \(\mathcal{H}\) includes many popular models studied in literature, both Gaussian and non-Gaussian; see Section 4. Throughout the paper, we explore \(\pi_{k}\) in some complicated \(\mathcal{G}\) with group-specific parameters \(q^{(k)},\mathbf{d}^{(k)},\mathbf{t}^{(k)}\) and \(\mathbf{\beta}^{(k)}\). The selection range of the truncation parameter \(J\) is based on the asymptotic order provided in Assumptions 4 and 5 in the next section. Although \(\pi_{k}^{(J)}\) has \(J\) arguments, it involves at most \(t_{0}^{(k)}d_{1}^{(k)}\) effective arguments, implying that the two population densities differ by a small number of variables. Relevant conditions are necessary for high-dimensional classification. For instance, in high-dimensional Gaussian data classification, [4, 3] show that, to consistently estimate Bayes classifier, it is necessary that the mean vectors differ at a small number of components. The modular structure holds for arbitrary \(J\), which may be viewed as a extension of [18] in the functional data analysis setting. ### Convergence of Kullback-Leibler divergence #### 3.2.1 Kullback-Leibler divergence For the true probability distribution \(\mathbf{\pi}(\mathbf{x})=(\pi_{1}(\mathbf{x}),\ldots,\pi_{K}(\mathbf{x}))^{\mathsf{T}}\) and any generic estimation \(\widehat{\mathbf{\pi}}(\mathbf{x})=(\widehat{\pi}_{1}(\mathbf{x}),\ldots,\widehat{\pi}_{K }(\mathbf{x}))^{\mathsf{T}}\), define the corresponding discrete version Kullback-Leibler divergence \[\text{KL}\left(\mathbf{\pi}(\mathbf{x}),\widehat{\mathbf{\pi}}(\mathbf{x})\right)=\sum_{k=1}^{ K}\pi_{k}(\mathbf{x})\log\left(\frac{\pi_{k}(\mathbf{x})}{\widehat{\pi}_{k}(\mathbf{x})} \right).\] For any \(\widehat{\pi}\) trained with \(\left\{(X_{i}(s),\mathbf{Y}_{i})\right\}_{i=1}^{n}\), we evaluate its performance by the log-likelihood ratio \[\mathbb{E}\left[\sum_{k=1}^{K}Y_{k}\log\left(\frac{\pi_{k}(\mathbf{\xi})}{\widehat{ \pi}_{k}(\mathbf{\xi})}\right)\right]=\mathbb{E}\left[\mathit{KL}\left(\pi(\mathbf{\xi} ),\widehat{\pi}(\mathbf{\xi})\right)\right].\] Note that the estimation risk is associate with the well-known CE loss in Section 2.2. Different from the popular least square loss, the CE loss is the expectation with respect to the input distribution of the Kullback-Leibler divergence of the conditional class probabilities. If anyone of the conditional class probabilities has zero estimation while the underlying conditional class probability is positive, the risk can even become infinite. To avoid the infinite risk, we truncate the CE loss function and derive convergence rates without assuming either the true conditional class probabilities or the estimators away from zero. Instead, our misclassification risks depend on an index quantifying the behaviour of the conditional class probabilities near zero. Given an absolute constant \(C_{0}\geq 2\), for any classifier \(\widehat{\pi}\), define the truncated Kullback-Leibler risk for some density \(\mathbf{h}\) as \[R_{\mathbf{h},C_{0}}\left(\widehat{\pi}\right)=\mathrm{E}_{\mathbf{h}}\left\{\sum_{k =1}^{K}\pi_{k}(\mathbf{\xi})\left[C_{0}\wedge\log\left(\frac{\pi_{k}(\mathbf{\xi})}{ \widehat{\pi}_{k}(\mathbf{\xi})}\right)\right]\right\}. \tag{3.4}\] **Remark 2**.: \(C_{0}\) _is commonly introduced to avoid infinity value of the ordinary Kullback-Leibler risk. It is trivial to show that \(C_{0}\) can only be abandoned when \(\widehat{\pi}_{k}\) is lower bounded by \(\exp\left(-C_{0}\right)\) for all \(k\). When \(\widehat{\pi}_{k}\) has a large deviation from \(\pi_{k}\) for some \(k\), the Kullback-Leibler risk explodes to infinity, which makes it is infeasible to evaluate the performance of \(\widehat{\pi}\)._ #### 3.2.2 Convergence rate for fully observed functional data In this section, we provide the non-asymptotic Kullback-Leibler risk of mfDNN classifier. Let \[(\widehat{k},\widehat{u})=\arg\max_{\begin{subarray}{c}(k,u),k=1\ldots,K,\\ u=0,\ldots,q^{(k)}\end{subarray}}\frac{t_{u}^{(k)}}{\widehat{\beta}_{u}^{(k )}}, \tag{3.5}\] where \(\widehat{\beta}_{u}^{(k)}=\beta_{u}^{(k)}\prod_{\ell=u+1}^{q^{(k)}}\beta_{ \ell}^{(k)}\wedge 1\), and \[(\widehat{l},\widehat{v})=\arg\max_{\begin{subarray}{c}(k,u),k=1\ldots,K,\\ u=0,\ldots,q^{(k)}\end{subarray}}\frac{t_{u}^{(k)}}{\widehat{\beta}_{u}^{(k )}(1+\alpha_{k})}.\] Let \(\theta=\frac{(1+\alpha_{\widehat{l}})\widehat{\beta}_{\widehat{v}}^{(\widehat {l})}}{(1+\alpha_{\widehat{l}})\widehat{\beta}_{\widehat{v}}^{(l)}+t_{\widehat {v}}^{(l)}}\) and \(\nu=\frac{\theta t_{\widehat{v}}^{(\widehat{k})}}{\widehat{\beta}_{\widehat{u} }^{(k)}(1+\widehat{\alpha})}\), where \(\widetilde{\alpha}=\min_{k}\alpha_{k}\wedge 1\). **Assumption 4**.: _There exist some constants \(C_{1},C_{2}^{\prime},C_{2},C_{3}\), only depending on \(\mathcal{H}\) and \(C_{0}\), such that the DNN class \(\mathcal{F}(L,J,\mathbf{p},s)\) satisfies_ 1. \(L\leq C_{1}\log n\)_;_ 2. \(C_{2}^{\prime}n^{\theta/\rho}\leq J\leq C_{2}n^{\nu}\)_;_ 3. \(\max_{1\leq\ell\leq L}p_{\ell}\leq C_{2}n^{\nu}\)_;_ 4. \(s\leq C_{3}n^{\nu}\log n\)_._ Assumption 4 provides exact orders on \((L,\mathbf{p},s)\) for network, respectively. Assumption 4 provides the precise range on \(J\). It is worth mentioning this condition implies \(\varrho\geq\theta\nu^{-1}\), i.e., the function \(\zeta(J)\) converges to zero in a relatively fast rate when \(J\to\infty\). In the following, we provide the convergence rate in the ideal case when the entire functional curve is fully observed. **Theorem 3.1**.: _There exist a positive constant \(\omega_{1}\), only depending on \(\mathcal{H}\) and \(C_{0}\), such that_ \[\sup_{\mathbf{h}\in\mathcal{H}}R_{\mathbf{h},C_{0}}\left(\widehat{\mathbf{\pi}}\right) \leq\omega_{1}n^{-\theta}\log^{3}n,\] _where network classifier \(\widehat{\mathbf{\pi}}\) belongs to \(\mathcal{F}(L,J,\mathbf{p},s)\) in Assumption 4._ **Remark 3**.: _Theorem 3.1 provides the upper bound of the KL misclassification risk of the proposed mfDNN. When \(K=2\), the multiclass classification downgrades to the binary classification problem. Compared with the minimax excess misclassification risk derived in [22] for the binary classification, the upper bound rate in Theorem 3.1 provides a slightly larger order, Specifically, the leading term of the upper bound rate in Theorem 3.1 is \(n^{-\theta}\) with \(\theta=\frac{(1+\alpha)\beta}{(1+\alpha)\beta+t}\), while the leading terms in Theorem 1 in [22] is \(n^{-S_{0}}\) with \(S_{0}=\frac{(\alpha+1)\beta}{(\alpha+2)\beta+t}\). Hence, when \(\beta\)'s, i.e. the degrees of Holder smooth functions in the class \(\mathcal{H}\), are large enough, the discrepancy between these two bounds are rarely negligible. Hence, to reduce potential slightly larger risks, we recommend [22] for the binary classification problems and when the distribution functions are not smooth enough. Meanwhile, we recommend the mfDNN classifier for multiclassification problems regardless the smoothness of the conditional distribution functions._ #### 3.2.3 Convergence rate for discretely observed functional data Practically, it is usually unrealistic to observe the full trajectory of each individual, thus the rate in Theorem 3.1 can only be reached if sampling frequency is dense enough. Hence, it is interesting to discuss the upper bound of the risk of mfDNN classifier when functional data are discretely observed at \(m\) occasions for each subject. Let \(\widetilde{\beta}=\max_{k=1\ldots,K}\left(\widetilde{\beta}_{0}^{(k)}\wedge 1\right)\), \(\theta^{\prime}=\tau\widetilde{\beta}\), and \(\nu^{\prime}=\frac{\theta^{\prime}t_{\widehat{\sigma}}^{(\widehat{k})}}{ \widetilde{\beta}_{\widehat{u}}^{(\widehat{k})}(1+\widetilde{\alpha})}\), where \(\widehat{k}\) is defined in (3.5) and \(\tau\) is a positive universal constant. **Assumption 5**.: _There exist some constants \(C_{1},C_{2}^{\prime},C_{2},C_{3}\), \(\widetilde{C}_{1},\widetilde{C}_{2}^{\prime},\widetilde{C}_{2},\) and \(\widetilde{C}_{3}\) only depending on \(\mathcal{H}\), \(C_{0}\) and \(\tau\), and a phase transition point \(m^{*}\in\mathbb{N}^{+}\), such that the DNN class \(\mathcal{F}(L,J,\mathbf{p},s)\) satisfies_ 1. \(L\leq C_{1}\log n\mathbb{I}(m\geq m^{*})+\widetilde{C}_{1}\log m\mathbb{I}(m<m ^{*})\) _;_ 2. \(C_{2}^{\prime}n^{\theta/\rho}\mathbb{I}(m\geq m^{*})+\widetilde{C}_{2}^{\prime}m^{ \theta^{\prime}/\rho}\mathbb{I}(m<m^{*})\leq J\leq C_{2}n^{\nu}\mathbb{I}(m\geq m ^{*})+\widetilde{C}_{2}m^{\nu^{\prime}}\mathbb{I}(m<m^{*})\)_;_ 3. \(\max_{1\leq\ell\leq L}p_{\ell}\leq C_{2}n^{\nu}\mathbb{I}(m\geq m^{*})+ \widetilde{C}_{2}m^{\nu^{\prime}}\mathbb{I}(m<m^{*})\)_;_ 4. \(s\leq C_{3}n^{\nu}\log n\mathbb{I}(m\geq m^{*})+\widetilde{C}_{3}m^{\nu^{ \prime}}\log m\mathbb{I}(m<m^{*})\)_._ Similar to Assumption 4, Assumption 5 provides exact orders on \(L,\mathbf{p},s\), and range of \(J\) when sampling frequency \(m\) is involved. When \(m\geq m^{*}\), Assumption 5 coincides with Assumption 4 for dense functional data. The following theorem provides the phase transition rate when functional data are discretely observed on \(m\) locations at a certain rate with respect to \(\tau\). **Theorem 3.2**.: _When \(E|\xi_{j}-\widehat{\xi}_{j}|\lesssim m^{-\tau}\) for all \(j=1,\ldots,J\), there exists positive constants \(\omega_{1},\omega_{2}\) and \(\omega_{3}\) only depending on \(\mathcal{H}\), \(C_{0}\) and \(\tau\), such that_ \[\sup_{\mathbf{h}\in\mathcal{H}}R_{\mathbf{h},C_{0}}\left(\widehat{\mathbf{\pi}}\right) \leq\omega_{1}n^{-\theta}\log^{3}n\mathbb{I}(m\geq m^{*})+\omega_{2}m^{-\theta^ {\prime}}\mathbb{I}(m<m^{*}),\] _where \(m^{*}=\lfloor\left(\omega_{3}n^{\theta}/\log^{3}n\right)^{1/\theta^{\prime}}\rfloor\), and \(\widehat{\mathbf{\pi}}\in\mathcal{F}(L,J,\mathbf{p},s)\) defined in Assumption 5._ **Remark 4**.: _When functional curves are discretely observed, Theorem 3.2 provides the convergence rate of truncated KL risk when the biases of projection scores are uniformly bounded by \(m^{-\tau}\). This assumption does not hold universally for all scenarios. Nevertheless, it can be satisfied in various examples._ _For any empirical process on \([0,1]\), if we use Fourier basis with \(m\) terms to decompose the curve, we can show that \(E|\xi_{j}-\widehat{\xi}_{j}|\leq O\left(\max_{k=1,\ldots,K}\sqrt{\sum_{j=m+1}^ {\infty}\left(\lambda_{kj}+\mu_{kj}^{2}\right)}\right)\), where \(\mu_{kj}=\operatorname{E}\xi_{j}\) in the \(k\)-th group. As \(\left\{\lambda_{kj}\right\}_{j=1}^{\infty}\) and \(\left\{\mu_{kj}^{2}\right\}_{j=1}^{\infty}\) are both convergent, when \(\lambda_{kj}\) and \(\mu_{kj}^{2}\) are decreasing no faster than some polynomial order, the assumption easily follows._ _Another well-known example is the FPCA provided by [6]. According to Theorem 1 in [6], for all \(j=1,\ldots,J\), the estimators of projection scores satisfy \(\operatorname{E}|\xi_{j}-\widehat{\xi}_{j}|\leq\max_{k}\left(\int_{[0,1]^{d} \times[0,1]^{d}}\left(\Omega_{k}-\widehat{\Omega}_{k}\right)^{2}(s,s^{\prime}) dsds^{\prime}\right)^{1/2}\). Hence, \(E|\xi_{j}-\widehat{\xi}_{j}|\lesssim m^{-\tau}\) holds easily when \(\max_{k}\left(\int_{[0,1]^{d}\times[0,1]^{d}}\left(\Omega_{k}-\widehat{\Omega} _{k}\right)^{2}(s,s^{\prime})dsds^{\prime}\right)\) is bounded properly._ ## 4 Examples In this section, we provide two examples of exponential families to justify the validation of our model assumptions, and emphasize the necessity of applying DNN approach owing to the complicated structure of data population. For simplicity, we assume the prior probability satisfies \(\mathbb{P}(\mathbf{Y}=\mathbf{e}_{k})=k^{-1}\) for all \(k\) throughout the section. ### Independent exponential family We first consider independent projection scores, which are from exponential families. For some collection of unknown parameters \(\left\{\theta_{kj}\right\}_{k=1,j=1}^{K,\infty}\), and unknown collections of functions \(\left\{\eta_{kj}\right\}_{k=1,j=1}^{K,\infty}\), \(\left\{U_{kj}\right\}_{k=1,j=1}^{K,\infty}\), and \(\left\{W_{kj}\right\}_{k=1,j=1}^{K,\infty}\), we consider the \(k\)-th class conditional density, such that \[\boldsymbol{\xi}|\left\{\theta_{kj}\right\}_{j=1}^{\infty},\boldsymbol{Y}= \boldsymbol{e}_{k}\sim h_{k}(\boldsymbol{x})=\exp\left(\sum_{j=1}^{\infty} \eta_{kj}(\theta_{kj})U_{kj}(x_{j})+W_{kj}(x_{j})\right).\] For all \(1\leq k,k^{\prime}\leq K\), let \(A_{kk^{\prime}}=\left\{j:\eta_{kj}(\theta_{kj})U_{kj}(x_{j})\neq\eta_{k^{\prime }j}(\theta_{k^{\prime}j})U_{k^{\prime}j}(x_{j}),\forall x_{j}\in\mathbb{R}\right\}\) and \(B_{kk^{\prime}}=\left\{j:W_{kj}\neq W_{k^{\prime}j}\right\}\) be the two sets identifying the difference between \(h_{k}\) and \(h_{k^{\prime}}\). Therefore, we have the pairwise log likelihood \[\log\left(h_{k}/h_{k^{\prime}}\right) = \sum_{j\in(A_{kk^{\prime}}\bigcup B_{kk^{\prime}})}\left\{[\eta_{ kj}(\theta_{kj})U_{kj}(x_{j})-\eta_{k^{\prime}j}(\theta_{k^{\prime}j})U_{k^{ \prime}j}(x_{j})]\right.\] \[\left.+\left[W_{kj}(x_{j})-W_{k^{\prime}j}(x_{j})\right]\right\}.\] Given some universal constant \(N_{kk^{\prime}}\), when \(|A_{kk^{\prime}}\bigcup B_{kk^{\prime}}|\leq N_{kk^{\prime}}\), there exists a positive integer \(J_{max}=\max\bigcup_{k,k^{\prime}}\left(A_{kk^{\prime}}\bigcup B_{kk^{\prime}}\right)\), such that \(\pi_{k}=\pi_{k}^{(J)}\) for all \(J\geq J_{max}\). By definition, Assumption 1 holds for \(\alpha=1\). Assumption 2 holds when \(h_{k}/h_{k^{\prime}}\) is bounded for all pairs. Note that it is trivial when \(\{h_{k}\}_{k=1}^{K}\) share the same \(\left\{U_{kj}\right\}_{k=1,j=1}^{K,\infty}\) and \(\left\{W_{kj}\right\}_{k=1,j=1}^{K,\infty}\), such as Gaussian distribution, student's t distribution and exponential distribution, whose density ratio of their kind is always bounded. Assumption 3 holds for \(J_{0}=J_{max}\), and for arbitrary function \(e(\cdot)\) with exponential tails and density \(\pi(\cdot)\). Since \(\pi_{k}=\left[1+\sum_{k^{\prime}\neq k}\log(h_{k}/h_{k^{\prime}})\right]^{-1}\), the smoothness is determined by \(\left\{\eta_{kj}\right\}_{k=1,j=1}^{K,\infty}\), \(\left\{U_{kj}\right\}_{k=1,j=1}^{K,\infty}\), and \(\left\{W_{kj}\right\}_{k=1,j=1}^{K,\infty}\), thus \(\boldsymbol{h}\) is trivially in some \(\mathcal{H}\). ### Exponential family with in-block interaction In this example, we consider \(\xi_{j}\) are dependent with each other in a block, but independent across blocks, which is an extension of the example in Section 4.1. Given a sequence of positive integers \(\left\{\ell_{p}\right\}_{j=1}^{\infty}\), such that \(0=\ell_{1}<\ell_{2}<\ldots\), we define the \(p\)-th group index set \(\mathcal{E}_{p}=\left\{\ell_{p}+1,\ldots,\ell_{p+1}\right\}\), such that the cardinality \(|\mathcal{E}_{p}|=\ell_{p+1}-\ell_{p}\), therein grouping are based on adjacent members for simplicity. For a collection of unknown parameters \(\left\{\boldsymbol{\theta}_{kj}\right\}_{k=1,p=1}^{K,\infty}\), and unknown collections of functions \(\left\{\widetilde{\eta}_{kp}\right\}_{k=1,p=1}^{K,\infty}\), \(\left\{\widetilde{U}_{kp}\right\}_{k=1,p=1}^{K,\infty}\), and \(\left\{\widetilde{W}_{kp}\right\}_{k=1,p=1}^{K,\infty}\), where \(\widetilde{U}_{kp}\) and \(\widetilde{W}_{kp}\) are functions from \(\mathbb{R}^{|\mathcal{E}_{p}|}\) to \(\mathbb{R}\). Consider the joint conditional density \[h_{k}(\boldsymbol{x})=\exp\left(\sum_{p=1}^{\infty}\eta_{kp}(\boldsymbol{ \theta}_{kp})\widetilde{U}_{kp}(\boldsymbol{x}_{p})+\widetilde{W}_{kp}( \boldsymbol{x}_{p})\right)\] for class \(k\), where \(\boldsymbol{x}_{p}=(x_{j})_{j=\ell_{p}+1,\ldots,\ell_{p+1}}\). For any \(1\leq k,k^{\prime}\leq K\), define the density difference sets \[\widetilde{A}_{kk^{\prime}}=\left\{p:\widetilde{\eta}_{kp}(\boldsymbol{\theta }_{kp})\widetilde{U}_{kp}(\boldsymbol{x}_{p})\neq\eta_{k^{\prime}p}(\boldsymbol{ \theta}_{k^{\prime}p})\widetilde{U}_{k^{\prime}p}(\boldsymbol{x}_{p}),\forall \boldsymbol{x}_{p}\in\mathbb{R}^{|\mathcal{E}_{p}|}\right\}\] and \(\widetilde{B}_{kk^{\prime}}=\left\{p:\widetilde{W}_{kp}\neq\widetilde{W}_{k^{ \prime}p}\right\}\), and the pairwise log likelihood is thus given by \[\log\left(h_{k}/h_{k^{\prime}}\right)\] \[= \sum_{p\in\widetilde{A}_{kk^{\prime}}\bigcup\widetilde{B}_{kk^{ \prime}}}\left\{\left[\widetilde{\eta}_{kp}(\boldsymbol{\theta}_{kp}) \widetilde{U}_{kp}(\boldsymbol{x})-\widetilde{\eta}_{k^{\prime}p}(\boldsymbol {\theta}_{k^{\prime}p})\widetilde{U}_{k^{\prime}p}(\boldsymbol{x})\right]+ \left[\widetilde{W}_{kp}(\boldsymbol{x})-\widetilde{W}_{k^{\prime}p}( \boldsymbol{x})\right]\right\}.\] Given some finite positive number \(N_{kk^{\prime}}\), such that \(|A_{kk^{\prime}}\bigcup B_{kk^{\prime}}|\leq N_{kk^{\prime}}\), the verification can be similarly derived from Section 4.1. ## 5 Simulation studies In this section, we provide numerical evidences to demonstrate the superior performance of mfDNN. In all simulations, we generated \(n_{k}=200,350,700\) training samples for each class, and testing sample sizes \(100,150,300\), respectively. Based on the fact that there is no existing multi-classification method specifically designed for multidimensional functional data, for comparison, we include the sparse discriminate analysis and \(\ell_{1}\) penalized Fisher's discriminant analysis (MSDA) approach introduced in [14] and penalized linear discriminant analysis (PLDA) classifier in [24]. In fact, MSDA and PLDA are efficient classifiers designed for high-dimensional i.i.d. observations. To make these two methods directly applicable to functional data, we first pre-processed 2D or 3D functional data by vectorization. The realization is via the R packages msda and PenalizedLDA, where the tuning parameter candidates for the penalty term are generated by default. We use the default five-fold and six-fold cross-validation to tune MSDA and PLDA, respectively. For mfDNN, we use tensor of Fourier basis to extract projection scores by integration. The structure parameters \((L,J,\boldsymbol{p},s)\) are selected by Algorithm 1, where the candidates are given based on Theorem 3.2. We summarize R codes and examples for the proposed mfDNN algorithms on GitHub ([https://github.com/FDASTATAUBURN/mfdnn](https://github.com/FDASTATAUBURN/mfdnn)). ### 2D functional data For \(k=1,2,3\), we generated functional data \(X_{i}^{(k)}(s,s^{\prime})=\sum_{j=1}^{5}\xi_{ij}^{(k)}\psi_{j}(s,s^{\prime}),s,s^{\prime}\in[0,1]\). Let \(\psi_{1}(s,s^{\prime})=s\), \(\psi_{2}(s,s^{\prime})=s^{\prime}\), \(\psi_{3}(s,s^{\prime})=ss^{\prime}\), \(\psi_{4}(s,s^{\prime})=s^{2}s^{\prime}\), \(\psi_{5}(s,s^{\prime})=ss^{\prime}^{2}\). Define \(\mathbf{1}_{k}\) be a \(k\times 1\) vector with all the elements one. We specify the distribution of \(\xi_{ij}^{(k)}\)'s as following. _Model 1_ (2D Gaussian): Let \(\left(\xi_{i1}^{(k)},\ldots,\xi_{i5}^{(k)}\right)^{\intercal}\sim N( \boldsymbol{\mu}_{k},\boldsymbol{\Sigma}_{k})\), where \(\boldsymbol{\mu}_{1}=(4,4,3,3,3)^{\intercal}\), \(\boldsymbol{\Sigma}_{1}^{1/2}=\text{diag}\left(8,7,6,5,4\right)\), \(\boldsymbol{\mu}_{2}=-\mathbf{1}_{5}\), \(\boldsymbol{\Sigma}_{2}^{1/2}=\text{diag}\left(5,4,3,2,1\right)\), \(\boldsymbol{\mu}_{3}=\mathbf{0}_{5}\), \(\boldsymbol{\Sigma}_{3}^{1/2}=\text{diag}\left(2.5,2,1.5,1,0.5\right)\). _Model 2_ (2D Mixed 1): Let \(\left(\xi_{i1}^{(k)},\ldots,\xi_{i5}^{(k)}\right)^{\intercal}\sim N( \boldsymbol{\mu}_{k},\boldsymbol{\Sigma}_{k})\) for \(k=1,2\), and \(\xi_{ij}^{(3)}\sim t_{2j+1}(\nu_{j})\), where \(\boldsymbol{\mu}_{1}=-\mathbf{1}_{5}\), \(\boldsymbol{\Sigma}_{1}^{1/2}=\text{diag}\left(5,4,3,2,1\right)\), \(\boldsymbol{\mu}_{2}=\mathbf{0}_{5}\), \(\boldsymbol{\Sigma}_{2}^{1/2}=\text{diag}\left(\frac{5}{2},2,\frac{3}{2},1, \frac{1}{2}\right)\), \((\nu_{1},\ldots,\nu_{5})^{\intercal}=3\cdot\mathbf{1}_{5}\). _Model 3_ (2D Mixed 2): Let \(\left(\xi_{i1}^{(1)},\ldots,\xi_{i5}^{(1)}\right)^{\intercal}\sim N(\mathbf{\mu}_{k}, \mathbf{\Sigma}_{k})\), \(\xi_{ij}^{(2)}\sim t_{j+1}(\nu_{2j})\), \(\xi_{ij}^{(2)}\sim t_{2j+1}(\nu_{3j})\), where \(\mathbf{\mu}_{1}=\mathbf{0}_{5}\), \(\mathbf{\Sigma}_{1}^{1/2}=\text{diag}\left(\frac{5}{2},2,\frac{3}{2},1,\frac{1}{2}\right)\), \((\nu_{21},\ldots,\nu_{25})^{\intercal}=\mathbf{1}_{5}\), \((\nu_{31},\ldots,\nu_{35})^{\intercal}=3\cdot\mathbf{1}_{5}\). _Model 4_ (2D Mixed 3): Let \(\xi_{ij}^{(1)}\sim\text{{Exp}}(r_{1j})\), \(\xi_{ij}^{(2)}\sim t_{2j+1}(\nu_{2j})\), and \(\left(\xi_{i1}^{(3)},\ldots,\xi_{i5}^{(3)}\right)^{\intercal}\)\(\sim N(\mathbf{\mu}_{3},\mathbf{\Sigma}_{3})\), where \((r_{11},\ldots,r_{15})^{\intercal}=(0.1,0.3,0.5,0.7,0.9)^{\intercal}\), \((\nu_{21},\ldots,\nu_{25})^{\intercal}=3\times\mathbf{1}_{5}\), \(\mathbf{\mu}_{3}=\mathbf{0}_{5}\), \(\mathbf{\Sigma}_{3}^{1/2}=\text{diag}\left(2.5,2,1.5,1,0.5\right)\). For each model, we observe the functional data on \(3\times 3\), \(5\times 5\), \(10\times 10\), and \(20\times 20\) grid points over \(\left[0,1\right]^{2}\), respectively. As a result, the sampling frequency \(m=9,25,100,400\), which indicates that the functional observations are from sparse to dense. Tables 1 and 2 demonstrate the results of \(100\) simulations. For mfDNN, it can be seen that the misclassification risks decrease as the sample size \(n\) increasing, as well as the increase of the sampling frequency \(m\). This founding further confirms Theorem 3.2. Given the relatively sparse sampling frequency, i.e., \(m=9\), MSDA has slightly better performance than mfDNN does. However, despite the increase of \(m\) in Table 2, there is no improvement of both MSDA and PLDA methods in terms of misclassification risks. This finding indicates that MSDA and PLDA classifiers can not be improved with more gathered information. In summary, the simulation results illustrate that the proposed mfDNN method outperforms the existing sparse and penalized discriminant analysis when classifying 2D dense functional data. ### 3D functional data For \(k=1,2,3\) and \(s_{1},s_{2},s_{3}\in[0,1]\), we generate 3D functional data \(X_{i}^{(k)}(s_{1},s_{2},s_{3})=\sum_{j=1}^{9}\xi_{ij}^{(k)}\psi_{j}(s_{1},s_{ 2},s_{3})\) where \(\psi_{1}(s_{1},s_{2},s_{3})=s_{1}\), \(\psi_{2}(s_{1},s_{2},s_{3})=s_{2}\), \(\psi_{3}(s_{1},s_{2},s_{3})=s_{3},\psi_{4}(s_{1},s_{2},s_{3})=s_{1}s_{2}\), \(\psi_{5}(s_{1},s_{2},s_{3})=s_{1}s_{3}\), \(\psi_{6}(s_{1},s_{2},s_{3})=s_{2}s_{3}\), \(\psi_{7}(s_{1},s_{2},s_{3})=s_{1}^{2}\), \(\psi_{8}(s_{1},s_{2},s_{3})=s_{2}^{2}\), \(\psi_{9}(s_{1},s_{2},s_{3})=s_{3}^{2}\), and the distribution of \(\xi_{ij}^{(k)}\)'s are specified as below. _Model 5_ (3D Gaussian): Let \(\left(\xi_{i1}^{(k)},\ldots,\xi_{i9}^{(k)}\right)^{\intercal}\sim N(\mathbf{\mu}_{ k},\mathbf{\Sigma}_{k})\), where \(\mathbf{\mu}_{1}=2\times\mathbf{1}_{9}\), \(\mathbf{\Sigma}_{1}^{1/2}=\mathbf{\Sigma}_{2}^{1/2}=\text{diag}\left(9,8,7,6,5,4,3,2,1\right)\), \(\mathbf{\mu}_{2}=\mathbf{\mu}_{3}=\mathbf{0}_{9}\), \(\mathbf{\Sigma}_{3}^{1/2}=1/3\times\mathbf{\Sigma}_{1}^{1/2}\). _Model 6_ (3D Mixed 1): Let \(\left(\xi_{i1}^{(k)},\ldots,\xi_{i9}^{(k)}\right)^{\intercal}\sim N(\mathbf{\mu}_{ k},\mathbf{\Sigma}_{k})\) for \(k=1,2\), and \(\xi_{ij}^{(3)}\sim t_{j+1}(\nu_{j})\), where \((\nu_{1},\ldots,\nu_{5})^{\intercal}=3\times\mathbf{1}_{5}\), \(\mathbf{\mu}_{1}=-\mathbf{1}_{9}\), \(\mathbf{\Sigma}_{1}^{1/2}=\text{diag}(5.5,5,4.5,4,\)\(3.5,3.2,5.2,1.5)\), \(\mathbf{\mu}_{2}=\mathbf{0}_{9}\), \(\mathbf{\Sigma}_{2}^{1/2}=\text{diag}\left(4.5,4,3.5,3,2.5,2,1.5,1,0.5\right)\). _Model 7_ (3D Mixed 2): Let \(\left(\xi_{i1}^{(1)},\ldots,\xi_{i9}^{(1)}\right)^{\intercal}\sim N(\mathbf{\mu}_{ k},\mathbf{\Sigma}_{k})\), \(\xi_{ij}^{(2)}\sim t_{j+1}(\nu_{2j})\), where \(\mathbf{\mu}_{1}=\mathbf{0}_{9}\), \(\mathbf{\Sigma}_{1}^{1/2}=\text{diag}\left(4.5,4,3.5,3,2.5,2,1.5,1,0.5\right)\), \((\nu_{21},\ldots,\nu_{29})^{\intercal}=-\mathbf{1}_{9}\), \((\nu_{31},\ldots,\nu_{39})^{\intercal}=0.5\times\mathbf{1}_{9}\). _Model 8_ (3D Mixed 3): Let \(\xi_{ij}^{(1)}\sim\text{{Exp}}(r_{1j})\), \(\xi_{ij}^{(2)}\sim t_{j+1}(\nu_{2j})\), and \(\left(\xi_{i1}^{(3)},\ldots,\xi_{i9}^{(3)}\right)^{\intercal}\)\(\sim N(\mathbf{\mu}_{3},\mathbf{\Sigma}_{3})\), where \((r_{11},\ldots,r_{19})^{\intercal}=0.1\times(1,3,5,7,9,11,13,15,17)^{\intercal}\), \((\nu_{21},\ldots,\nu_{29})^{\intercal}=0.6\times\mathbf{1}_{9}\), \(\mathbf{\mu}_{3}=\mathbf{0}_{9}\), \(\mathbf{\Sigma}_{3}^{1/2}=\text{diag}\left(4.5,4,3.5,3,2.5,2,1.5,1,0.5\right)\). For the 3D functional data, we apply similar setups as 2D cases. We observe the functional data on \(2\times 2\times 2\), \(3\times 3\times 3\), \(4\times 4\times 4\), and \(5\times 5\times 5\) grid points over \(\left[0,1\right]^{3}\), respectively, and the sampling frequency \(m=8,27,64,125\). Tables 3 and 4 demonstrate the results of \(100\) simulations. The proposed mfDNN classifier is superior to its counterparts for all 3D functional data cases. Meanwhile, there also exists the phase transition patterns for mfDNN method. However, the performance of MSDA and PLDA methods lacks of improvement with the increase of \(m\). It can be seen that when \(m=125\), the misclassification error rates of mfDNN are almost one third of MSDA's and one forth of PLDA's in Gaussian case, and almost a half of either MSDA's or PLDA's error rates in Models 7 and 8. A plausible reason is that given the functional data framework, our proposed mfDNN can properly accommodate the repeatedly observed data over pixels or voxels, while other competitors only treat those information as common high-dimensional covariates and ignore the underlining smoothing structures. By efficiently extracting the projection scores of the continuum, the proposed mfDNN has full potential to discover the underlying distributions of the functional data clusters. This again demonstrates our proposed classifier has a distinct advantage over these competitors in complex imaging data classification problems. \begin{table} \begin{tabular}{c c c c c c c c} \hline \hline \multirow{2}{*}{Model} & \multirow{2}{*}{\(n_{k}\)} & \multicolumn{4}{c}{\(m=9\)} & \multicolumn{4}{c}{\(m=25\)} \\ \cline{3-8} & & mfDNN & MSDA & PLDA & mfDNN & MSDA & PLDA \\ \hline \multirow{4}{*}{2D Gaussian} & 200 & 0.259 & **0.246** & 0.323 & **0.205** & 0.245 & 0.325 \\ & & (0.031) & (0.027) & (0.028) & (0.026) & (0.028) & (0.028) \\ \cline{2-8} & 350 & **0.232** & 0.243 & 0.325 & **0.200** & 0.243 & 0.328 \\ & & (0.020) & (0.022) & (0.022) & (0.020) & (0.021) & (0.022) \\ \cline{2-8} & 700 & **0.227** & 0.241 & 0.323 & **0.196** & 0.241 & 0.325 \\ & & (0.014) & (0.014) & (0.016) & (0.014) & (0.015) & (0.016) \\ \hline \multirow{4}{*}{2D Mixed 1} & 200 & 0.158 & **0.150** & 0.227 & **0.100** & 0.150 & 0.229 \\ & & (0.020) & (0.021) & (0.026) & (0.018) & (0.022) & (0.025) \\ \cline{2-8} & 350 & 0.153 & **0.144** & 0.227 & **0.085** & 0.144 & 0.229 \\ & & (0.015) & (0.016) & (0.020) & (0.012) & (0.016) & (0.019) \\ \cline{2-8} & 700 & **0.152** & 0.156 & 0.229 & **0.081** & 0.123 & 0.231 \\ & & (0.011) & (0.014) & (0.014) & (0.010) & (0.014) & (0.014) \\ \hline \multirow{4}{*}{2D Mixed 2} & 200 & 0.166 & **0.152** & 0.198 & **0.140** & 0.153 & 0.200 \\ & & (0.023) & (0.022) & (0.025) & (0.020) & (0.020) & (0.025) \\ \cline{2-8} & 350 & 0.165 & **0.152** & 0.200 & **0.135** & 0.152 & 0.202 \\ & & (0.016) & (0.016) & (0.022) & (0.016) & (0.016) & (0.022) \\ \cline{2-8} & 700 & 0.163 & **0.148** & 0.197 & **0.123** & 0.148 & 0.199 \\ & & (0.011) & (0.012) & (0.013) & (0.010) & (0.012) & (0.013) \\ \hline \multirow{4}{*}{2D Mixed 3} & 200 & 0.168 & **0.115** & 0.264 & 0.136 & **0.116** & 0.264 \\ & & (0.030) & (0.018) & (0.023) & (0.022) & (0.018) & (0.024) \\ \cline{1-1} \cline{2-8} & 350 & 0.164 & **0.115** & 0.265 & 0.132 & **0.115** & 0.265 \\ \cline{1-1} & & (0.024) & (0.014) & (0.021) & (0.019) & (0.014) & (0.021) \\ \cline{1-1} \cline{2-8} & 700 & 0.156 & **0.114** & 0.264 & 0.123 & **0.114** & 0.264 \\ \cline{1-1} \cline{2-8} & & (0.014) & (0.011) & (0.016) & (0.014) & (0.011) & (0.016) \\ \hline \hline \end{tabular} \end{table} Table 1: Averaged misclassification rates with standard errors in brackets for 2D simulations when \(m=9\) and \(m=25\) over \(100\) replicates. \begin{table} \begin{tabular}{c c c c c c c c} \hline \hline \multirow{2}{*}{Model} & \multirow{2}{*}{\(n_{k}\)} & \multicolumn{3}{c}{\(m=100\)} & \multicolumn{3}{c}{\(m=400\)} \\ \cline{3-8} & & mfDNN & MSDA & PLDA & mfDNN & MSDA & PLDA \\ \hline \multirow{4}{*}{2D Gaussian} & 200 & **0.147** & 0.244 & 0.326 & **0.145** & 0.245 & 0.329 \\ & & (0.024) & (0.027) & (0.029) & (0.025) & (0.027) & (0.029) \\ \cline{2-8} & \multirow{2}{*}{350} & **0.139** & 0.242 & 0.328 & **0.139** & 0.242 & 0.331 \\ & & (0.017) & (0.021) & (0.023) & (0.017) & (0.021) & (0.022) \\ \cline{2-8} & \multirow{2}{*}{700} & **0.132** & 0.241 & 0.327 & **0.131** & 0.241 & 0.329 \\ & & (0.011) & (0.014) & (0.016) & (0.011) & (0.014) & (0.016) \\ \hline \multirow{4}{*}{2D Mixed 1} & 200 & **0.090** & 0.150 & 0.229 & **0.089** & 0.150 & 0.232 \\ & & (0.018) & (0.021) & (0.025) & (0.017) & (0.022) & (0.026) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.076** & 0.144 & 0.229 & **0.075** & 0.144 & 0.232 \\ & & (0.010) & (0.016) & (0.020) & (0.010) & (0.016) & (0.019) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.070** & 0.142 & 0.232 & **0.069** & 0.142 & 0.235 \\ & & (0.009) & (0.011) & (0.014) & (0.008) & (0.011) & (0.015) \\ \hline \multirow{4}{*}{2D Mixed 2} & 200 & **0.121** & 0.152 & 0.201 & **0.119** & 0.152 & 0.204 \\ & & (0.019) & (0.022) & (0.025) & (0.018) & (0.022) & (0.025) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.116** & 0.152 & 0.202 & **0.114** & 0.151 & 0.206 \\ & & (0.014) & (0.016) & (0.021) & (0.013) & (0.016) & (0.021) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.108** & 0.148 & 0.199 & **0.069** & 0.148 & 0.203 \\ & & (0.009) & (0.012) & (0.012) & (0.009) & (0.012) & (0.013) \\ \hline \multirow{4}{*}{2D Mixed 3} & 200 & **0.107** & 0.116 & 0.264 & **0.099** & 0.116 & 0.264 \\ & & (0.024) & (0.018) & (0.023) & (0.020) & (0.019) & (0.024) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.098** & 0.116 & 0.265 & **0.090** & 0.115 & 0.267 \\ & & (0.012) & (0.014) & (0.021) & (0.012) & (0.014) & (0.021) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.097** & 0.114 & 0.265 & **0.085** & 0.114 & 0.265 \\ & & (0.012) & (0.011) & (0.016) & (0.010) & (0.011) & (0.016) \\ \hline \hline \end{tabular} \end{table} Table 2: Averaged misclassification rates with standard errors in brackets for 2D simulations when \(m=100\) and \(m=400\) over \(100\) replicates. \begin{table} \begin{tabular}{c c c c c c c c} \hline \hline \multirow{2}{*}{Model} & \multirow{2}{*}{\(n_{k}\)} & \multicolumn{3}{c}{\(m=8\)} & \multicolumn{3}{c}{\(m=27\)} \\ \cline{3-8} & & mfDNN & MSDA & PLDA & mfDNN & MSDA & PLDA \\ \hline \multirow{8}{*}{3D Gaussian} & 200 & **0.374** & 0.465 & 0.485 & **0.234** & 0.367 & 0.491 \\ & & (0.024) & (0.037) & (0.045) & (0.020) & (0.030) & (0.046) \\ \cline{2-8} & \multirow{2}{*}{350} & **0.373** & 0.474 & 0.495 & **0.233** & 0.369 & 0.500 \\ & & (0.020) & (0.029) & (0.042) & (0.020) & (0.023) & (0.041) \\ \cline{2-8} & \multirow{2}{*}{700} & **0.363** & 0.472 & 0.488 & **0.232** & 0.374 & 0.493 \\ & & (0.014) & (0.025) & (0.041) & (0.013) & (0.018) & (0.041) \\ \hline \multirow{8}{*}{3D Mixed 1} & 200 & **0.215** & 0.224 & 0.238 & **0.168** & 0.164 & 0.242 \\ & & (0.022) & (0.024) & (0.022) & (0.021) & (0.022) & (0.022) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.200** & 0.221 & 0.236 & **0.151** & 0.156 & 0.240 \\ & & (0.018) & (0.019) & (0.020) & (0.017) & (0.016) & (0.020) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.188** & 0.220 & 0.237 & **0.149** & 0.152 & 0.241 \\ & & (0.011) & (0.014) & (0.012) & (0.010) & (0.011) & (0.013) \\ \hline \multirow{8}{*}{3D Mixed 2} & 200 & **0.311** & 0.325 & 0.346 & **0.277** & 0.294 & 0.348 \\ & & (0.018) & (0.025) & (0.026) & (0.020) & (0.022) & (0.025) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.307** & 0.328 & 0.345 & **0.268** & 0.289 & 0.348 \\ & & (0.018) & (0.021) & (0.022) & (0.018) & (0.018) & (0.022) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.253** & 0.326 & 0.347 & **0.234** & 0.286 & 0.350 \\ & & (0.014) & (0.015) & (0.015) & (0.013) & (0.014) & (0.015) \\ \hline \multirow{8}{*}{3D Mixed 3} & 200 & **0.272** & 0.308 & 0.315 & **0.268** & 0.292 & 0.313 \\ & & (0.026) & (0.031) & (0.030) & (0.026) & (0.026) & (0.029) & (0.030) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.268** & 0.303 & 0.309 & **0.239** & 0.286 & 0.310 \\ & & (0.019) & (0.023) & (0.024) & (0.018) & (0.024) & (0.023) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.253** & 0.302 & 0.311 & **0.234** & 0.286 & 0.312 \\ & & (0.014) & (0.017) & (0.017) & (0.013) & (0.015) & (0.017) \\ \hline \hline \end{tabular} \end{table} Table 3: Averaged misclassification rates with standard errors in brackets for 3D simulations when \(m=8\) and \(m=27\) over \(100\) replicates. \begin{table} \begin{tabular}{c c c c c c c c} \hline \hline \multirow{2}{*}{Model} & \multirow{2}{*}{\(n_{k}\)} & \multicolumn{3}{c}{\(m=64\)} & \multicolumn{3}{c}{\(m=125\)} \\ \cline{3-8} & & mfDNN & MSDA & PLDA & mfDNN & MSDA & PLDA \\ \hline \multirow{4}{*}{3D Gaussian} & 200 & **0.135** & 0.369 & 0.493 & **0.134** & 0.369 & 0.494 \\ & & (0.018) & (0.029) & (0.048) & (0.017) & (0.029) & (0.048) \\ \cline{2-8} & \multirow{2}{*}{350} & **0.123** & 0.369 & 0.502 & **0.118** & 0.370 & 0.501 \\ & & (0.015) & (0.022) & (0.042) & (0.012) & (0.022) & (0.042) \\ \cline{2-8} & \multirow{2}{*}{700} & **0.114** & 0.374 & 0.495 & **0.108** & 0.374 & 0.495 \\ & & (0.010) & (0.019) & (0.04) & (0.009) & (0.019) & (0.042) \\ \hline \multirow{4}{*}{3D Mixed 1} & 200 & **0.130** & 0.163 & 0.243 & **0.127** & 0.162 & 0.244 \\ & & (0.021) & (0.022) & (0.022) & (0.020) & (0.022) & (0.023) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.109** & 0.156 & 0.241 & **0.106** & 0.155 & 0.241 \\ & & (0.014) & (0.016) & (0.020) & (0.014) & (0.016) & (0.020) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.098** & 0.153 & 0.243 & **0.098** & 0.152 & 0.242 \\ & & (0.010) & (0.011) & (0.013) & (0.009) & (0.011) & (0.013) \\ \hline \multirow{4}{*}{3D Mixed 2} & 200 & **0.166** & 0.294 & 0.350 & **0.154** & 0.295 & 0.348 \\ & & (0.020) & (0.022) & (0.025) & (0.019) & (0.024) & (0.026) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.147** & 0.289 & 0.349 & **0.135** & 0.289 & 0.349 \\ & & (0.015) & (0.018) & (0.023) & (0.013) & (0.018) & (0.023) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.141** & 0.286 & 0.351 & **0.126** & 0.286 & 0.351 \\ & & (0.012) & (0.015) & (0.014) & (0.011) & (0.014) & (0.014) \\ \hline \multirow{4}{*}{3D Mixed 3} & 200 & **0.184** & 0.292 & 0.312 & **0.176** & 0.292 & 0.312 \\ & & (0.022) & (0.029) & (0.030) & (0.021) & (0.028) & (0.030) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{350} & **0.171** & 0.287 & 0.310 & **0.162** & 0.286 & 0.310 \\ & & (0.016) & (0.023) & (0.024) & (0.016) & (0.024) & (0.023) \\ \cline{1-1} \cline{2-8} & \multirow{2}{*}{700} & **0.160** & 0.286 & 0.312 & **0.151** & 0.285 & 0.312 \\ & & (0.011) & (0.015) & (0.017) & (0.012) & (0.015) & (0.017) \\ \hline \hline \end{tabular} \end{table} Table 4: Averaged misclassification rates with standard errors in brackets for 3D simulations when \(m=64\) and \(m=125\) over \(100\) replicates. ## 6 Real data analysis ### Handwritten digits The first benchmark data example was extracted from the MNIST database ([http://yann.lecun.com/exdb/mnist/](http://yann.lecun.com/exdb/mnist/)). This classical MNIST database contains 60,000 training images and 10,000 testing images of handwritten digits (\(0,1,\ldots,9\)), and the black and white images were normalized to fit into a \(28\times 28\) pixel bounding box and anti-aliased. We used tensor of Fourier basis for data processing. According to our numerical experience, we choose candidates for \((L,J,\mathbf{p},s)\), such that \(L=(2,3,4)^{\intercal}\), \(J=(300,500,800)^{\intercal}\), \(\|\mathbf{p}\|_{\infty}~{}=~{}(500,1000,2000)^{\intercal}\), and \(s=(0.01,0.1,0.5)\) for dropout rate. Here we abuse the notation of \(s\), as the dropout is the technique we choose to sparsify the neural network. With the optimal parameters \(L_{opt}=3\), \(J_{opt}=500\), \(\|\mathbf{p}_{opt}\|_{\infty}~{}=1000\), \(s_{opt}=0.01\) through validation, we demonstrate the misclassification risk in Table 5. We estimate the rules given by MSDA, PLDA and our proposal on the training set. As most observations for each subject are zeros, PenalizedLDA reports errors and does not work any more. It can be seen that our proposal achieves the higher accuracy with the sparsest classification rule. This again shows that our method is a competitive classifier and has more broader applications. ### ADNI database The dataset used in the preparation of this article were obtained from the ADNI database ([http://adni.loni.usc.edu](http://adni.loni.usc.edu)). The ADNI is a longitudinal multicenter study designed to develop clinical, imaging, genetic, and biochemical biomarkers for the Figure 1: Samples from MNIST data. early detection and tracking of Alzheimer's Disease (AD). From this database, we collect PET data from \(79\) patients in AD group, \(45\) patients in Early Mild Cognitive Impairment (EMCI) group, and \(101\) people in Control (CN) group. This PET dataset has been spatially normalized and post-processed. These AD patients have three to six times doctor visits and we select the PET scans obtained in the third visits. People in EMCI group only have the second visit, and we select the PET scans obtained in the second visits. For AD group, patients' age ranges from \(59\) to \(88\) and average age is \(76.49\), and there are \(33\) females and \(46\) males among these \(79\) subjects. For EMCI group, patients' age ranges from \(57\) to \(89\) and average age is \(72.33\), and there are \(26\) females and \(19\) males among these \(45\) subjects. For CN group, patients' age ranges from \(62\) to \(87\) and average age is \(75.98\), and there are \(40\) females and \(61\) males among these \(101\) subjects. All scans were reoriented into \(79\times 95\times 68\) voxels, which means each patient has \(68\) sliced 2D images with \(79\times 95\) pixels. For 2D case, it means each subject has \(N=79\times 95=7,505\) observed pixels for each selected image slice. For 3D case, the observed number of voxels for each patient's brain image observation is \(N=79\times 95\times 68=510,340\). We randomly split the datasets with a \(7:3\) ratio in a balanced manner to form the training set and the testing set, with \(100\) repetitions. We choose candidates for \((L,J,\boldsymbol{p},s)\), such that \(L=(2,3)^{\intercal}\), \(J=(50,100,200)^{\intercal}\), \(\|\boldsymbol{p}\|_{\infty}\ =(200,500,800)^{\intercal}\), and \(s=(0.01,0.1,0.5)\) for dropout rate. We still compare our method with MSDA. For 2D case, it means each subject has \(N=79\times 95=7,505\) observed pixels for each selected image slice. Table 6 displays the misclassification rates for 2D brain imaging data of AD, EMCI and CN. For 3D case, the observed number of voxels for each patient's brain sample is \(N=79\times 95\times 68=510,340\). Unfortunately, given more than a half million covariates, MSDA method crashed down as such gigantic covariance matrix (almost million by million dimension) needs around 2TB RAM to store. It easily exceeds the memory limit of the common supercomputer. Hence, MSDA for 3D data results are unavailable. Meanwhile, as PLDA recasts Fisher's discriminant problem as a biconvex problem that can be optimized using a simple iterative algorithm, PLDA avoids the heavy computation burden of the covariance matrix and it still works for this 3D case. Table 7 presents the empirical misclassification risk for mfDNN and PLDA. There are several interesting findings in Tables 6 and 7. First, our proposed classifier has better performance than other competitors in any 2D slice data or 3D data cases. Second, from Table 7, we can conclude that given a single slice of 2D imaging data, the misclassification rates are consistently larger than using the 3D data. It indicates that 3D data contains more helpful information to label the brain images among three stages of the disease. Third, the \(10\)-th and the \(20\)-th slices provide the lowest ones among all 2D data. As a matter of fact, it is well known that Alzheimer's disease destroys neurons and their connections in hippocampus, the entorhinal cortex, and the cerebral cortex. The related regions are corresponding to the first \(25\) slices. This is a promising finding for neurologists, as this smallest risk indicates this particular slice presents useful information to distinguish the CN, EMCI and AD groups. Further medical checkups are meaningful for this special location in the brain. \begin{table} \begin{tabular}{l c c c c c c} \hline \hline methods & \(10\)-th & \(20\)-th & \(30\)-th & \(40\)-th & \(50\)-th & \(60\)-th \\ \hline mfDNN & **0.341** & **0.325** & **0.409** & **0.359** & **0.365** & **0.452** \\ & (0.057) & (0.049) & (0.049) & (0.050) & (0.041) & (0.055) \\ \hline MSDA & 0.347 & 0.374 & 0.444 & 0.366 & 0.385 & 0.453 \\ & (0.038) & (0.034) & (0.035) & (0.034) & (0.039) & (0.040) \\ \hline PLDA & 0.354 & 0.339 & 0.440 & 0.376 & 0.424 & 0.474 \\ & (0.057) & (0.059) & (0.067) & (0.060) & (0.068) & (0.064) \\ \hline \end{tabular} \end{table} Table 6: Averaged misclassification rates with standard errors in brackets for ADNI 2D brain images. \begin{table} \begin{tabular}{l c} \hline \hline methods & Misclassification rates \\ \hline mfDNN & **0.274 (0.044)** \\ \hline MSDA & – (–) \\ \hline PLDA & 0.295 (0.056) \\ \hline \end{tabular} \end{table} Table 7: Averaged misclassification rates with standard errors in brackets for ADNI 3D brain images. Figure 2: Averaged images of the the \(20\)-th, the \(40\)-th and the \(60\)-th slices of EMCI (left column) group and AD group (right column). ## 7 Summary In this paper, we propose a new formulation to derive multiclass classifiers for multidimensional functional data. We show that our proposal has a solid theoretical foundation and can be solved by a very efficient computational algorithm. Our proposal actually gives a unified treatment of both one-dimensional and multidimensional classification problems. In light of this evidence, our proposal is regarded as an efficient multiclass and generalization of the multiclassification methods from i.i.d. data to multidimensional functional data cases. To the best of our knowledge, the present work is the first work on multiclassification for multidimensional functional data with theoretical justification. ## Acknowledgements ADNI data used in preparation of this article were obtained from the Alzheimer's Disease Neuroimaging Initiative (ADNI) database (adni.loni.usc.edu). As such, the investigators within the ADNI contributed to the design and implementation of ADNI and/or provided data but did not participate in analysis or writing of this report. A complete listing of ADNI investigators can be found at: [http://adni.loni.usc.edu/wp-content/uploads/how_to_apply/ADNI_Acknowledgement_List.pdf](http://adni.loni.usc.edu/wp-content/uploads/how_to_apply/ADNI_Acknowledgement_List.pdf).
2307.00228
InferTurbo: A Scalable System for Boosting Full-graph Inference of Graph Neural Network over Huge Graphs
GNN inference is a non-trivial task, especially in industrial scenarios with giant graphs, given three main challenges, i.e., scalability tailored for full-graph inference on huge graphs, inconsistency caused by stochastic acceleration strategies (e.g., sampling), and the serious redundant computation issue. To address the above challenges, we propose a scalable system named InferTurbo to boost the GNN inference tasks in industrial scenarios. Inspired by the philosophy of ``think-like-a-vertex", a GAS-like (Gather-Apply-Scatter) schema is proposed to describe the computation paradigm and data flow of GNN inference. The computation of GNNs is expressed in an iteration manner, in which a vertex would gather messages via in-edges and update its state information by forwarding an associated layer of GNNs with those messages and then send the updated information to other vertexes via out-edges. Following the schema, the proposed InferTurbo can be built with alternative backends (e.g., batch processing system or graph computing system). Moreover, InferTurbo introduces several strategies like shadow-nodes and partial-gather to handle nodes with large degrees for better load balancing. With InferTurbo, GNN inference can be hierarchically conducted over the full graph without sampling and redundant computation. Experimental results demonstrate that our system is robust and efficient for inference tasks over graphs containing some hub nodes with many adjacent edges. Meanwhile, the system gains a remarkable performance compared with the traditional inference pipeline, and it can finish a GNN inference task over a graph with tens of billions of nodes and hundreds of billions of edges within 2 hours.
Dalong Zhang, Xianzheng Song, Zhiyang Hu, Yang Li, Miao Tao, Binbin Hu, Lin Wang, Zhiqiang Zhang, Jun Zhou
2023-07-01T05:23:28Z
http://arxiv.org/abs/2307.00228v1
InferTurbo: A Scalable System for Boosting Full-graph Inference of Graph Neural Network over Huge Graphs ###### Abstract With the rapid development of Graph Neural Networks (GNNs), more and more studies focus on system design to improve training efficiency while ignoring the efficiency of GNN inference. Actually, GNN inference is a non-trivial task, especially in industrial scenarios with giant graphs, given three main challenges, i.e., scalability tailored for full-graph inference on huge graphs, inconsistency caused by stochastic acceleration strategies (e.g., sampling), and the serious redundant computation issue. To address the above challenges, we propose a scalable system named InferTurbo to boost the GNN inference tasks in industrial scenarios. Inspired by the philosophy of "think-like-a-vertex", a GAS-like (Gather-Apply-Scatter) scheme is proposed to describe the computation paradigm and data flow of GNN inference. The computation of GNNs is expressed in an iteration manner, in which a vertex would gather messages via in-edges and update its state information by forwarding an associated layer of GNNs with those messages and then send the updated information to other vertexes via out-edges. Following the schema, the proposed InferTurbo can be built with alternative backends (e.g., batch processing system or graph computing system). Moreover, InferTurbo introduces several strategies like shadow-nodes and partial-gather to handle nodes with large degrees for better load balancing. With InferTurbo, GNN inference can be hierarchically conducted over the full graph without sampling and redundant computation. Experimental results demonstrate that our system is robust and efficient for inference tasks over graphs containing some hub nodes with many adjacent edges. Meanwhile, the system gains a remarkable performance compared with the traditional inference pipeline, and it can finish a GNN inference task over a graph with tens of billions of nodes and hundreds of billions of edges within 2 hours. Graph Neural Networks, Distributed System, Full-graph Inference, Big Data ## I Introduction Graph Neural Networks (GNNs) generalize deep learning over regular grids (e.g., images) to highly unstructured data and have emerged as a powerful learning tool for graph data. Recently, GNNs have demonstrated impressive success on various tasks, ranging from traditional graph mining tasks (e.g., node classification [1, 2, 3, 4] and link prediction [5, 6]) to the fields of natural language processing [7] and computer vision [8]. Meanwhile, graph data forms the basis of innumerable industrial systems owing to its widespread utilization in real-world applications (e.g., recommendation [9, 10, 11, 12, 13], marketing [14, 15], fraud detection [16, 17]), further facilitating the flourishing of GNNs in industrial communities. The key idea of current GNNs is taking advantage of information aggregation schema, which can effectively summarize multi-hop neighbors into representations via stacking multiple GNN layers. Essentially, the high computation cost exponentially growing with the number of GNN layers poses the non-trivial challenges for _GNN Training and Inference_ in industrial scenarios with huge graphs, containing billions of nodes and trillions of edges. With the aim of the possibility of performing the highly scalable and efficient GNN training in real industrial scenarios, several recent efforts have been made in industrial-purpose graph learning systems, including single-machine systems with the cooperation between GPUs and CPUs (i.e., DGL [18, 19] and PyG [20]), distributed systems based on localized convolutions (i.e., Aligraph [21]) and pre-processed information-complete sub-graphs (i.e., AGL [22]). Unfortunately, the main focus of these systems is training GNNs efficiently on graphs at scale, while few attention has been paid to the inference phase of GNNs 1, which is also the core of an industrial graph learning system. Footnote 1: Different from online inference whose goal is guaranteeing the low latency of real-time online serving [25, 26], the focus of GNN inference in our paper aims at efficiently performing full-graph inference in the offline environment, which is ubiquitous in financial applications. In current graph learning systems [18, 19, 20, 21], the inference phase is conducted by blindly imitating the pipeline of the training phase. However, the inference phase of GNN has its unique characteristics, making it distinct from the training phase, such that the pure design of inference stage in current graph learning systems is unsuitable for performing large-scale inference tasks in industrial scenarios. * _The large gap of data scale between training and inference phases._ In a general graph learning task, only a small number of nodes (e.g., 1% or even less in actual scenarios) are labeled for GNN training, while the inference tasks are usually expected to be taken over the entire graph. Such a gap is steadily worsening in the industrial scenarios with huge graphs, containing hundreds of millions or even billions of nodes [22, 27, 28] (e., Facebook2, Ant Group3). Both observations encourage us to re-consider the scalability issue encountered in the inference tasks with the careful thought of memory storage and communication bandwidth. Footnote 2: [https://en.wikipedia.org/wiki/Facebook_Inc](https://en.wikipedia.org/wiki/Facebook_Inc). Footnote 3: [https://en.wikipedia.org/wiki/Alipay](https://en.wikipedia.org/wiki/Alipay) * _No guarantee for the consistency of predictions in inference phase._ As a basic requirement in industrial scenarios, the prediction score for a certain node should keep consistency at multiple runs, which unfortunately gets no guarantee in the GNN inference of current systems. To extend GNNs to large-scale graphs, the \(k\)-hop neighbor sampling strategy is widely adopted in current graph learning systems [18, 19, 20, 21, 22, 23]. Although the training phase could greatly benefit from the efficiency-oriented strategy for generalized GNNs, the inherent stochasticity for prediction is unacceptable in inference phase, especially for financial applications (e.g., fraud detection and loan default prediction [16, 17]). * _Serious redundant computation issue in the inference phase._ Current graph learning systems [18, 19, 20, 21] follow the procedure that performs forward and backward of GNNs over \(k\)-hop neighborhoods in a mini-batch manner, and would obtain a well-trained GNN by repeating this procedure enough times. In spite of its potential capability of enjoying mature optimization algorithms and data-parallelism in training phase, \(k\)-hop neighbor sampling with the mini-batch training manner would introduce the undesirable redundant computation issue in the inference phase since only one forward pass of GNNs is required. Addressing the limitations of current graph learning systems, we aim to facilitate GNN inference in industrial scenarios through a collaborative setting of mini-batch-based training and full-batch-based inference. The significance of the cooperative setting is not trivial considering two major challenges that are not explored in current graph learning systems: * _C1: How to unify the mini-batch based training and full-batch based inference in a graph learning system?_ As mentioned above, the mini-batch strategy is the promising way for efficient GNNs training, while the full-batch strategy is suitable for inference to alleviate computation issues. To combine those two advantages, it is impressive to abstract a new schema of graph learning that a GNN trained in the mini-batch manner could naturally perform inference in the full-batch manner. * _C2: How to efficiently perform GNN inference in distributed environments, especially for huge graphs with extremely skew degree distribution?_ To ensure the consistency of prediction in inference tasks, we discard the strategies related to neighbor sampling, which put forward the urgent request for efficient GNN inference on huge graphs. In addition, due to the ubiquity of Power-Law, it is critically important to handle long-tailed nodes with extremely large degrees in terms of time cost and resource utilization, as well as avoiding the unexpected Out Of Memory (OOM) issues. To this end, we design a system named **InferTurbo** to boost the inference tasks on industrial-scale graphs. We propose a GAS-like (Gather-Apply-Scatter) schema [30] together with an annotation technique to describe different stages of the data flow and the computation flow of GNNs, which could be used to unify the mini-batch training and full-graph inference phases. The training and inference phases share the same computation flow but use different implementations of data flow. The data flow parts are made as built-in functions currently, and users would only focus on how to write models in our computation flow. Moreover, to handle the corner cases in natural graphs in industrial scenarios, such as nodes with extremely large amount of in-edges or out-edges, a set of strategies without any sampling like _partial-gather_, _broadcast_, and _shadow-nodes_ are proposed to balance the load of computation and communication and mitigate the long tail effect caused by those nodes. As a result, consistency prediction results could be guaranteed at different runs, and the system enjoys a better load-balancing. At last, the system is implemented on both the batch processing system [31, 32] and the graph process system [33], which makes it gain good system properties (e.g., scalability, fault tolerance) of those mature infrastructures. The main contributions of this work are summarized as follows: * We propose a GAS-like schema together with an annotation technique to describe the data and computing flow of GNNs, and make it possible to hierarchically conduct the inference phase over a full graph. In this way, the redundant computation caused by k-hops neighborhood is eliminated in inference phase. * We describe implementation details of the system on both batch processing system [31, 32] and graph computing system [33], which are mature infrastructures and widely available in industrial communities. * We design a set of strategies such as _partial-gather_, _broadcast_, and _shadow-nodes_ for inference tasks to handle the power-law problem in industrial graphs. * Compared with some state-of-the-art GNN systems (DGL, PyG), the proposed system demonstrates remarkable results in efficiency and scalability while achieving comparable prediction performance, and it could finish a node classification task over a graph with tens of billions of nodes and hundreds of billions of edges within 2 hours. ## II Preliminaries ### _K-hop Neighborhood and Sampling_ A _directed_, _weighted_, and _attributed_ graph is denoted as \(\mathcal{G}=\{\mathcal{V},\mathcal{E},\mathbf{X},\mathbf{E}\}\), where \(\mathcal{V}\) and \(\mathcal{E}\subseteq\mathcal{V}\times\mathcal{V}\) are the node set and edge set of \(\mathcal{G}\), respectively. \(\mathbf{X}\) and \(\mathbf{E}\) are node features and edge features. The \(k\)-hop neighborhood \(\mathcal{G}_{v}^{k}\) of node \(v\), is defined as the _induced attributed subgraph_ of \(\mathcal{G}\) whose node set is \(\mathcal{V}_{v}^{k}=\{v\}\cup\{u|d(v,u)\leq k\}\), where \(d(v,u)\) denotes the length of the shortest path from \(u\) to \(v\), and edge set is \(\mathcal{E}_{v}^{k}=\{(u,u^{\prime})|(u,u^{\prime})\in\mathcal{E}\wedge u\in \mathcal{V}_{v}^{k}\wedge u^{\prime}\in\mathcal{V}_{v}^{k}\}\). Additionally, \(\mathcal{G}_{v}^{k}\) also contains the feature vectors of the nodes and edges. Without loss of generality, node \(v\) itself is treated as its \(0\)-hop neighborhood. It is proved that \(k\)-hop neighborhood would provide sufficient and necessary information for \(k\)-layer GNNs [22]. However, the size of k-hop neighborhood grows exponentially with the number of hops, making the computations performed on it memory-intensive and time-consuming. _K-hop sampling_ is proposed to address those problems. It would sample neighbors in a top-down manner, i.e., sample neighbors in the \(k\)-th hop given the nodes in the \((k-1)\)-th hop recursively. In particular, different sampling approaches [23, 24, 10, 22] employ different ways to select the neighbors, and one typical method is to randomly choose a fixed number of neighbors in each iteration. ### _Graph Neural Networks_ Graph neural network is a popular way to learn over graph data, and it aggregates neighbors' information for a certain node in an iterative way. Given an attributed graph \(\mathcal{G}\), a GNN layer can be formulated in a **message passing paradigm**[18, 20, 34], which first computes _messages_ via edges and then _updates_ the state of the target node with those messages: \[\begin{split}\text{message:}&\quad m_{v,u}^{k+1}= \mathcal{M}(\mathbf{h}_{v}^{k},\mathbf{h}_{u}^{k},e_{v,u}),\\ \text{update:}&\quad\mathbf{h}_{v}^{k+1}=\mathcal{U}( \mathbf{h}_{v}^{k},\mathcal{R}(\{m_{v,u}^{k+1}\}_{u\in\mathcal{N}_{v}^{+}})), \end{split} \tag{1}\] where \(\mathbf{h}_{v}^{k}\) denotes intermediate embedding of node \(v\) at the \(k\)-th layer and \(\mathbf{h}_{v}^{0}=\mathbf{x}_{v}\), \(e_{v,u}\) and \(m_{v}^{k+1}\) indicate edge features and messages associated with \(v\)'s in-edge from \(u\) respectively, \(\mathcal{M}\) represents the _message_ function that generates messages according to adjacent node features and edge features on each edge, \(\mathcal{U}\) means the _update_ function that updates node embedding by aggregating incoming messages based on the _reduce_ function \(\mathcal{R}\). The _message_ function and _update_ function are usually neural networks, while the _reduce_ function could be a certain pooling function (such as sum, mean, max, min) or neural networks. Most GNN algorithms (e.g., GCN [1], GraphSAGE [4], GAT [3]) could be expressed in this paradigm with a few changes in those functions. For example, _message_ functions for GCN, GraphSAGE, and GAT, only take the source node's hidden state (or with edge features) as input. In addition, _reduce_ functions for GCN and GraphSAGE are set to pooling functions, while for GAT, the reduce function would perform a weighted sum over messages based on the attention mechanism. ## III Related Works ### _Graph Processing System_ The idea of message passing could be traced back to the graph processing field, which focuses on understanding the structure properties or topology of graphs, such as finding out the most important vertices (e.g., PageRank [35]), seeking the shortest path between nodes (e.g., SSSP [36]), and so on. In the following, some gifted works will be introduced as they motivate our work a lot. In the graph processing field, with the rapid growth of graph data, many efforts [37, 38] have been paid to conduct graph processing tasks distributedly to handle extremely large graphs. Pregel [33] adopts a "think like a vertex" programming model, in which each node receives messages from its neighbors in the previous iteration, modifies its own state or mutates the graph topology, and sends messages to other nodes via its out-edges. PowerGraph [30] further develops the vertex-centric programming model with three fine-grained conceptual phases to describe the data flow, i.e., Gather, Apply, and **S**catter (**GAS**). The _gather_ and _scatter_ are a pair of symmetrical operations that demonstrate the information flowing in and out a node and perform edge-wise processing on the corresponding in-edges and out-edges. The _apply_ stage is used to update the state of the node itself. It enables a node-level paralleling by assigning nodes to partitions, along with their states and adjacent edges. Many graph processing algorithms (e.g., PageRank, SSSP) could be expressed in this paradigm. The following works [39, 40, 41, 42] expand the abstraction and propose many talented strategies to optimize graph processing systems such as partitioning, communication, and so on. The key difference between graph processing algorithm and GNN is that the former mainly focuses on graph structure, while the latter usually models graph structure and rich attribute information together and is optimized by gradient-based algorithms (e.g., SGD [43]). That is, GNNs are more compute-intensive and communication-intensive, and data dependency exists in both forward and backward pass. ### _Graph Learning System_ Inspired by the development in deep learning communities, researchers also design and build systems to perform graph learning algorithms based on some deep learning frameworks, such as TensorFlow [44] and PyTorch [45]. Many works [18, 19, 20, 22] build graph learning systems following the message-passing paradigm to unify different GNN variants, which help researchers design new GNN algorithms in an easy way. The development of graph learning systems evolves from optimizing systems on a single machine [18, 19, 46, 47] to providing an efficient way to learn over large graphs distributedly [19, 20, 21, 22]. Inspired by the k-hop sampling strategy [4, 10], recent works [19, 20, 21, 22] perform localized convolutions on sampled k-hop neighborhoods to mitigate the inherent data dependency problem and enjoy the mature data-parallelism architecture in graph learning. Specially, Aligraph [21] implements distributed in-memory graph storage engine, and workers will query subgraphs for a batch of training samples and do the training workloads. DGL [19] proposes to use a partitioning algorithm when building the graph storage engine to reduce the number of edge cuts between different partitions, which is helpful to reduce the communication overhead when querying subgraphs of training samples. PyG [20] provides lightweight, user-friendly sampling APIs, whereas users usually need to prepare an extra graph storage engine for distributed training. AGL [22] proves that the k-hop neighborhood could provide sufficient and necessary information for k-layer GNN models and pre-generates the k-hop neighborhoods with a MapReduce pipeline to solve the inherent data dependency problem. It also provides a way to estimate the errors caused by random sampling strategy, and errors would decrease as the sampling number increases. Users might trade off computing speed and prediction accuracy by changing the number of neighbors for each layer. However, little attention has been paid to the inference phase of GNNs. Many works thought that inference tasks could be perfectly conducted in the same way as the training phase, which is hard to meet the requirements of inference tasks in industrial scenarios. The inference should be efficiently conducted over huge graphs with skewed degree distribution, and the prediction result should keep consistent at different runs. A few existing works [48, 49] mainly focus on the efficiency problem in the inference phase on a single machine and propose some techniques, such as operation fusion and graph-specific caching, to reduce intermediate results and achieve better IO speed. AGL [22] proposes a full-graph inference module to mitigate the redundant computation problem caused by k-hop neighborhoods but misses to solve the consistency problem and straggler problems caused by 'hub' nodes in industrial scenarios. It is still challenging to build an efficient and scalable inference system for industrial applications. ## IV System This section will first provide an overview of the InferTurbo inference system. The system is then detailed from three aspects: the programming model abstraction, implementations using various backends, and large-graph optimization techniques. ### _System Overview_ The key motivation of the work is to build an efficient GNN inference system on top of scalability for huge graphs in industrial scenarios. Therefore, instead of designing and optimizing inference system over a single monster machine, we'd rather build the system on mature, scalable infrastructures with high throughput capacity, such as batch processing systems and graph processing systems. In addition, to boost the inference efficiency, the system is expected to address the following issues: serious redundant computation caused by inferring on \(k\)-hop neighborhoods and the straggler problem brought on by skewed degree distribution. Furthermore, as the consistency of prediction results at different runs is a fundamental requirement for industrial applications, some optimization strategies with randomness should be avoided. To this end, we propose InferTurbo to boost the inference tasks over industrial graphs. The overall architecture is illustrated in Fig. 1. First, a GAS-like abstraction is proposed to describe the data flow and computation flow of GNNs by combining the classical message-passing schema in (1) and the GAS schema in graph processing system. This abstraction is utilized to integrate the mini-batch training phase and full-batch inference phase. In this way, the inference phase would not rely on k-hop neighborhoods and thus avoids redundant computation, while we could still enjoy the mature optimization algorithms in mini-batch manner and the data parallelism in training phase. In addition, by designing and implementing adaptors, a well-trained GNN model in our abstraction could be deployed on batch processing systems or graph processing systems, which are mature industrial infrastructures with properties of high throughput and scalability. Applications could choose one of them as the backend by trading off the efficiency and resource cost. Furthermore, a set of strategies without dropping any information are proposed to handle problems caused by nodes with a large degree, since the degree distribution could be skewed for industrial graphs. With those strategies, our system could achieve consistent prediction results at different runs and gain better load-balancing by mitigating the stragglers caused by those "hub" nodes. ### _InferTurbo Abstraction_ In industrial scenarios, there are some key distinctions between the training and inference phases of GNN algorithms. In the training phase, the labeled nodes may be one percent of all nodes or even less, and the optimization procedure would be repeated several times on them to obtain a converged model. It is a wise decision to conduct localized GNNs on those labeled nodes based on their k-hop neighborhoods since we can benefit from data parallelism and sophisticated optimization methods in the mini-batch setting. The cost is also reasonable since labeled nodes would be scattered throughout the whole graph, and there would not be many overlaps between k-hop neighborhoods of corresponding labeled nodes. On the contrary, inference tasks usually should be conducted on the entire graph. Forwarding localized GNNs over the k-hop neighbors of all those nodes might result in the redundant computation problem. A good way to solve it is to design a full-batch distributed inference pipeline and bridge the gap Fig. 1: System overview. between those two different modes in training and inference phases. Inspired by the philosophy [33] of "think-like-a-vertex" in the graph processing field, we re-express the classical message-passing schema of GNNs to a GAS-like abstraction to unify the mini-batch training and full-graph inference phases. As shown in Fig. 2, for a certain GNN layer, the GAS-like abstraction can be defined as follows: * _gather_nbrs (Data Flow)_: A "vertex" receives messages from its in-edges and then vectorizes the collected information into tensors. * _aggregate (Computation Flow)_: The "vertex" would preliminarily process the messages from its in-edges, which is quite similar to the reduce function in \(\mathcal{R}\) in (1). The difference is that this process should obey the commutative law and associative law (like max/min/sum/mean pooling or union) for further optimization in inference phase. Otherwise, the computation should be placed in the next stage. * _apply_node (Computation Flow)_: The "vertex" then updates its state information by combing the former state of itself and the "gathered" message from the former stage. * _apply_edge (Computation Flow)_: The "vertex" would generate messages according to the updated state information together with edge features. * _scatter_nbrs (Data Flow)_: The "vertex" sends messages via out-edges. Those five stages are used to describe the data flow and computation flow in GNNs, and their roles are emphasized by underlining and annotating the corresponding part. Compared with the classical GAS schema, both the _Gather_ and _Scatter_ are expanded to two sub-stages to distinguish the data flow and computation flow in those stages. In general, _gather_nbrs_ and _scatter_nbrs_, a pair of symmetry operations in the data flow, are used to receive and send messages via in-edges or out-edges, respectively. We make them as built-in methods since they are the same among a variety of commonly used GNNs. Computation stages would vary for different GNNs, and users should override those stages according to their specific requirements. Specially, a rule is defined to set a boundary between _aggregate_ and _apply_node_ stages: the computation of the _aggregate_ should obey the commutative law and associative law. Otherwise, related operations should be placed in the _apply_node_ stage. For example, many pooling functions (such as sum, mean, max, min), used as the reduce function in GCN and GraphSAGE, should be placed in the _aggregate_ stage following the rule. For GAT, the computation of attention would break the rule, and thus, we simply union messages in the _aggregate_ stage and perform the reduce function in the _apply_node_ stage. This rule also facilitates further optimizations, which will be detailed in the next several sections. The mini-batch training and full-graph inference are unified with such abstraction: #### Iii-B1 Training In the training phase, following the traditional training-inference pipeline, the system still takes k-hop neighborhoods as input and train GNNs in the mini-batch manner. As shown in Fig. 3, we take two widely used GNN algorithms (i.e., GraphSAGE, GAT) as examples to demonstrate how to organize codes in such abstraction. The data flow in training phase is quite simple. Since k-hops neighborhoods provide sufficient information for \(k\)-layer GNNs [22] and are locally available for a certain training worker, the data flow is just accessing and updating related local tensors. Meanwhile, a model doesn't need much change and only should be expressed in our schema. As shown in Fig. 3, a certain GNN algorithm should override three methods (_gather_, _apply_node_, and _apply_edge_) from the base class. In addition, we also provide an interface named _scatter_and_gather_ in case the _scatter_ and _gather_ stages could be fused together to avoid storing intermediate edge-level messages in training phase [18]. For example, the scatter and gather processes in GraphSAGE are fused by a generalized sparse-dense matrix multiplication operation. It's worth noting that since the _gather_nbrs_ is just accessing local tensors in training phase, it is ignored here for simplicity. The _gather_ interface in Fig. 3 represents the computation of _aggregate_ stage. Furthermore, some function decorators are developed to mark the beginning point and end point of functions, as shown in Fig. 3. Meanwhile, we would generate layer-wise signature files to record those information at the time to save a well-trained model (parameters and so on). In this way, different parts of the computation flow could be reorganized and deployed in corresponding stages in the inference phase. Note that parameters in those decorators indicate whether to enable optimization strategies and also would be recorded in signature files. Those information would be loaded in the inference phase to avoid excessive manual configurations. Fig. 2: InferTurbo abstraction #### Iv-B2 Inference Different from the training phase, the inference task is conducted in the full-graph manner. Since the InferTurbo abstraction is expressed from the perspective of a node, the forward pass of GNNs could be treated as a "vertex" program over a certain node. By partitioning nodes in a graph into different machines, the total inference task could be conducted distributedly. The data flow in the inference phase is quite different from that in the training phase. Neighbors of a certain node could be placed on different machines, and data should be exchanged among those machines to prepare sufficient information to perform the computation flow on the node. Therefore, rather than simply accessing local tensors, the data flow in inference phase mainly plays a role in communicating with other nodes on remote machines: the _gather_nbrs_ would receive information from remote nodes via in-edges and vectorize those information into adjacency matrix, node/edge feature matrix, and so on. The _scatter_nbrs_ would send messages to other machines according to the destination node's id for the next iteration. In contrast, the computation flow could be shared in training and inference phases. In general, a certain computation stage of a well-trained model would be attached to the corresponding part in inference phase. Specially, the computation flow would be reorganized for optimization. For example, the _aggregate_ function may be performed in the _Scatter_ stage in advance to reduce messages sent to the same destination node. The implementation details about how to conduct the inference tasks with specific backends and the optimization strategies will be presented in the following sections. ### _Alternative Backends and Implementation Details_ Scalability is the key property that should be taken into consideration when implementing the InferTurbo in the inference phase. Except for scalability, different industrial applications also have some specific requirements. Inference tasks for some time-sensitive applications should be finished as fast as possible, even with relatively high costs on expensive and exclusive resources (like memory). Others may be cost-sensitive and seek a way to conduct the inference over large graphs with limited commodity computation resources since the resource cost is also critical in industrial scenarios. InferTurbo provides two alternative backends on graph processing systems (i.e., Pregel-like systems) and batch processing systems (i.e., MapReduce, Spark) to trade off computation efficiency and resource cost. In general, InferTurbo on the graph processing system could be more efficient than that on batch processing system but with more strict requirements on stable and exclusive resources, such as, memory, CPU cores. In contrast, InferTurbo on batch processing systems is more flexible in memory and CPU requirements as it processes data from external storage. For example, the batch processing system could handle large graphs even with a single reducer if sufficient external storage is available. The implement details of those two backends are introduced respectively as follows: #### Iv-C1 InferTurbo on Graph Processing System We implement the InferTurbo abstraction on a Pregel-like graph processing system, which is one of the most popular distributed graph processing systems. Note that it could be easily migrated to other graph processing systems as the abstraction originates from the graph processing field. **Graph Partition.** Following Pregel [33], a graph is divided into partitions according to node ids by a partitioning function (like, mod N), and each partition contains a set of nodes and all out-edges of those nodes. Each partition is assigned to a worker to perform the "vertex" program (i.e., a layer of GNN). As shown in Fig. 4, a certain node would also maintain the node state and edge state (out-edges), such as raw features, Fig. 3: GraphSAGE, GAT in InferTurbo abstraction intermediate embeddings, or even historical embeddings. In this way, structure information and feature information could be stored in one place to avoid redundant storage. It's worth mentioning that, with this partitioning strategy, the forward pass for a layer of GNNs over a certain node could be finished in one superstep by receiving messages from other nodes (maybe on other machines), which avoids synchronizing between different workers within a superstep. **Execution.** As shown in Fig. 4, we mainly perform the computation flow of GNN models in the _compute()_ function of the Pregel-like system. At first, we implement the _gather_ stage based on the _message iterator_ in Pregel, which is used to collect all messages sent to a certain node. Meanwhile, we provide a built-in _vectorization_ function to transfer the messages and local state information into tensors, including structure information (i.e., adjacent matrix), node-level information (i.e., node state), and edge-level information (i.e., edge-wise messages or state). Then, we perform the computation flow based on those matrices and provide functions to update node and edge states maintained in the machine. At last, the messages generated by the model would be sent to other nodes via the _send_message_ function in Pregel. Specially, we design an optimization strategy for performing the aggregation part of the GNN model in the combiner stage of Pregel to reduce the communication cost, as shown in Fig. 4. After \(k\) iterations (supersteps), we would finally get the result of a \(k\)-layer GNN model. Note that the first and the last supersteps play special roles in the full pipeline. The _first_ superstep could be treat as an initialization step since there are no messages received at this stage. It mainly transforms the raw node states and edge features into initial embeddings and then calls the _Scatter_ stage to send those information to other nodes to start the following supersteps. For the _last_ superstep, we attach a prediction part after the _apply_node_ stage to get prediction scores for nodes (if needed) and then output the results (node embeddings or scores). #### Iii-B2 InferTurbo on MapReduce We also provide an alternative backend on MapReduce (or Spark), as shown in Fig. 5. Compared with the backend on the graph processing system, the MapReduce backend could not maintain some information (e.g., node states, out-edges) in memory. Owing to this, the communication between different "supersteps" could be quite different: all necessary information should be treated as messages and sent to the next round. The MapReduce pipeline takes a _node table_ and an _edge table_ as input. The _node table_ consists of node id, node features, and ids of all out-edge neighbors, while the _edge table_ contains source node id, destination node id, and edge features. The overall pipeline on MapReduce is as follows: * _Map._ The phase acts as the initialization step. At first, it transforms the raw features of nodes and edges to initial embeddings. Then, for a certain mapper, the initial embeddings of a certain node would be sent to itself and all its out-edge neighbors, while the edge information would be sent to both the source and the destination nodes. In short, the _Map_ phase generates three kinds of information for each node: self-state information, in-edge information (i.e., edge features of in-edges, node features of the in-edge neighbors), and out-edge information (i.e., edge features of out-edges). * _Reduce._ The reduce phase performs the forward pass for a certain GNN layer. Compared with the backend on graph processing system, the input and output in this phase are a little different. In the _Gather_ stage, a node needs to receive edge messages and its own state. However, in the _Scatter_ stage, the node also sends the updated state as an additional message to itself. That is, messages (e.g., node state, updated edge embeddings via out-edges) would be sent not only to destination nodes but also to itself. The shuffle keys for those messages are set as ids of destination nodes or itself, respectively. Messages for destination nodes represent in-edge information in the next round, while for itself, indicate new self-state information and out-edge information. Similar to the implementation on Pregel, the prediction slice of a well-trained model will be merged to the last reduce phase, and after \(k\) times _Reduce_ stages, we could finish the forward propagation of a \(k\)-layer GNN. Though the number of messages could be larger than that in the backends of graph processing system, this backend is promising for industrial applications since messages and state information usually are stored and exchanged with external Fig. 4: The backend of a Pregel-like graph processing system Fig. 5: The backend of MapReduce storage (HHD or SSD). As a result, a reducer could load a part of nodes together with their information into memory instead of loading all the data in the partition. The peak usage of memory could be far less than that in the backends of graph processing system, as the latter backend usually should maintain all necessary information belonging to it in memory. Therefore, it could be more suitable for scaling to extremely large graphs. Moreover, many applications would leverage the ability of the powerful GNNs on various specific graphs in industrial scenarios. The solution based on graph processing system is strict on stable and exclusive resources and may lead to resource competition for different applications. The implementation on the batch processing system could release the heavy resource competition by sacrificing a little efficiency. ### _Optimization Strategies_ It is still challenging to conduct GNN inference tasks for industrial applications on those implementations since a hallmark property of graphs is _skewed_ power-law degree distribution [22, 30]. The power law means a few nodes act as hubs and have many neighbors, while most nodes have few neighbors. Those "hub" nodes could increase the cost of computation and communication in inference phase, and substantially slow down the machines that contain them. What's worse, the inference pipeline could crash as those nodes may lead to the OOM problem. The neighbor-sampling strategy [4] may mitigate those problems but lead to unstable embeddings or prediction scores, which is unacceptable for industrial applications. By diving into those problems, we classify them into two categories: problems caused by the skewed in-degree and the skewed out-degree, and propose several strategies to address them respectively: Partial-GatherFor nodes with many in-edges, the time cost of receiving and computing over messages could increase significantly and lead workers containing them in the long tail. We propose a _partial-gather_ strategy to address this problem, and the schematic diagram is illustrated in Fig. 6. The basic idea of this strategy is to conduct the _Gather_ stage in advance to balance the computation of messages on the sender side while reducing the total amount of messages to be sent out. In addition, the five-stage GAS-like abstraction and the annotation technique described above make it possible to call related computation modules at any time in the pipeline. Therefore, in a certain round, the _aggregate_ part of the model (i.e., gather function, partial=True) could be conducted using partially available messages when they are sent to the same destination. Then in the next round, the receiver receives those aggregated messages from different workers and conducts the _Gather_ stage as usual. Since the _aggregate_ function satisfies the commutative law and associative law, this strategy would not lead to any difference in final results. We implement the strategy on both the Pregel-like system and the MapReduce (Spark) system with their built-in "combining" function. With this strategy, the communication complexity for a particular node is reduced to a constant level and only depends on the number of workers. Additionally, the computation of _Gather_ is carried out relatively uniformly across source workers, which also avoids the computation hubs and may reduce the long-tail effect caused by large in-degree nodes. This strategy involves almost no overhead and can be applied to all nodes regardless of their degrees. BroadcastFor many GNN algorithms, all or part of messages sent via out-edges are usually the same. For example, the intermediate embeddings of a certain source node could be sent to all its neighbors via out-edges, which leads to overhead in communication. For nodes with many out-edges, the communication would be the bottleneck, which should be avoided by "compressing" those repeated messages. To address this problem, we propose a _broadcast_ strategy as shown in Fig. 6. In detail, instead of sending edge-level messages, nodes will send "one" unique message to each machine together with a unique identifier (e.g., UUID or the source node id) as the index. Meanwhile, identifiers would be sent as messages via out-edges. Then, in the next round, the receiver should look up real messages by those identifiers and then perform the inference tasks as usual. We implement this strategy with the built-in "aggregator" class in batch processing systems and graph processing systems. Furthermore, this strategy could be easily migrated on the latest graph processing systems which provide a native "broadcast" mechanism. It's obvious that the _broadcast_ could mitigate the overhead caused by the repeated messages and thus release the heavy communication pressure for nodes with large out-degree. Shadow NodesA strategy named _shadow nodes_ is designed as an alternative solution for nodes with large out-degree, since the _broadcast_ strategy may not work well when messages vary with out-edges and cannot be compressed. The basic idea of this strategy is to average the communication load caused by out-edges, as shown in Fig. 6. First, the out-edges of a node are divided into \(n\) groups evenly. Then the node is duplicated \(n\) times, and each mirror is associated with a group of out-edges and all in-edges. Note that the id of each mirror would be appended with the group information. This process would be conducted in the preprocessing phase, and out-edges will be averaged to each mirror which could be placed on different machines. Since each mirror holds all the in-edges of the original node and the out-edges of all the duplicates are equal to that of the original node, conducting GNN algorithms with this strategy is just the same as the original pipeline and would not change the result. This strategy is simple but more general than the _Broadcast_ strategy. It could re-balance the computation load whether messages could be compressed or not. Note that, in those two strategies for large out-degree problems, a heuristic formula is designed to estimate the threshold: \(threshold=\lambda\times total\_edges/total\_workers\). That is, those strategies should be activated when the number of out-edges for a node exceeds a certain percentage of edges on the worker. In our experiment, the hyper-parameter \(\lambda\) is set to an empirical value of 0.1. ## V Experiment In this section, we conduct extensive experiments to evaluate our inference system and compare it with two state-of-the-art GNN systems, PyG [20] and DGL [18]. ### _Experiment Settings_ **Datasets.** Four datasets are used in the experiments, including PPI [50], OGB-Products [51], OGB-MAG240M [52], and Power-Law, whose data scales range from small, medium, large, to extremely large. The properties of those datasets are shown in Tab. I. The first three datasets are collected from the real world, and following the experimental settings in [3, 4, 22, 53], they are divided into three parts as the training, validation, and test sets. Note that settings of MAG240M follow the baseline examples provided by OGB team4, and only a part of the graph is used in the examples, and thus we count what we used in Tab. I. Footnote 4: [https://ogb.stanford.edu/](https://ogb.stanford.edu/) The Power-Law dataset is synthesized following the power-law [30] for the following two considerations. Firstly, to verify the scalability of the system, graphs at different scales with the same degree distribution should be used in experiments, since the time cost could be affected a lot by different degree distributions even with the same scale. Secondly, experiments for analyzing large in-degree and out-degree problems should be conducted on datasets with in-degree and out-degree following the power law respectively, for variable-controlling purposes. In our experiment, we synthesize datasets following the same rule with different scales and Tab. I only records the largest one we used. Specially, all nodes in Power-Law datasets are used in inference task, while millesimal are used in training phase. **Evaluation.** We design a series of experiments to evaluate our system in terms of effectiveness, efficiency, consistency, and scalability. We first evaluate two widely used GNNs (GraphSAGE [4], GAT [3]) on three real-world datasets to verify the effectiveness of our system. Then, some experiments are conducted to show the unstable prediction scores caused by neighbor-sampling and prove the consistency of our inference system. Moreover, we also record the time cost and compare it with traditional inference pipelines to see the efficiency of our system. We verify the scalability of the system and analyze the effectiveness of optimization strategies on the Power-Law dataset. We use _cpu*min_ to measure the usage of resources and record it at different data scales to prove the scalability of the system. The data scales range from 100 million nodes (about 1 billion edges), 1 billion nodes (10 billion edges), to 10 billion nodes (100 billion edges). Specially, when analyzing the effectiveness of different optimization strategies individually, power-law datasets are generated with in-degree and out-degree following the power-law, respectively. The different backends of our system are deployed on different clusters. The backend on graph processing system consists of about 1000 instances, and each is powered by 2 CPU (Intel Xeon E5-2682 [email protected]) and 10GB memory, while the one on MapReduce contains about 5000 instances (2-CPU, 2GB memory). The network bandwidth is about 20 Gb/s. For fairness, only 1000 instances are used in experiments to compare those two backends. ### _Results and Analysis_ #### V-B1 Comparisons We conduct a set of experiments to compare the system with traditional training-inference pipelines and present experimental results to demonstrate the effectiveness, efficiency, consistency, and scalability of the system. **Effectiveness.** Effectiveness is always in the first place. Table II illustrates comparisons of performance between our system and traditional training-inference pipelines powered by PyG and DGL. We report the results of GraphSAGE and Fig. 6: Optimization strategies GAT on PPI, OGB-Product, and OGB-MAG240M in different inference pipelines. Configurations of those GNN algorithms follow examples in OGB leaderboard5. Footnote 5: [https://ogb.stanford.edu/docs/lsc/leaderboards/](https://ogb.stanford.edu/docs/lsc/leaderboards/) In general, results achieved by our system are comparable with those on PyG and DGL across different datasets and algorithms. It's reasonable since our system just changes the way to perform the inference but never changes the formula of GNNs or introduces any approximation strategy in inference phase. As those two algorithms represent the two most widely used algorithms while the scale of datasets ranges from small, medium, and large, those comparisons and results prove the effectiveness of our system in different scenarios. **Efficiency.** We evaluate the efficiency of our system by comparing it with the traditional inference pipelines powered by PyG and DGL, and record the resource cost measured by _cpu*min_ together with time cost on the OGB-MAG240M dataset. Note that, in traditional pipelines, we use a distributed graph store (20 workers) to maintain the graph data and 200 workers (10-CPU, 10G memory) for inference tasks. Increasing the number of workers would exacerbate the communication problem between workers and the graph store, reducing the efficiency of traditional pipelines. For fairness, the total CPU cores of inference workers are equal to our system with different backends, and the CPU utilization remains 90%+ during the inference tasks. Table III demonstrates the experimental results compared with traditional inference pipelines. Generally, both the two backends of our system demonstrate superior efficiency. Our system achieves 30\(\times\sim\) 50\(\times\) speedup compared with traditional inference pipelines, while in terms of the total resource cost, traditional inference pipelines take about 40\(\times\sim\) 50\(\times\) more than our system. Those results show that our system is quite promising for industrial scenarios: it not only could finish inference tasks faster but also is more economy friendly for industrial applications as it takes fewer resources. The results we achieved mainly benefit from the new inference pattern in our system. That is, with the InferTurbo abstraction, it could conduct layer-wise inference over the entire graph while enjoying the good property of parallelism. In this way, redundant computation caused by \(k\)-hop neighborhoods could be avoided. Notably, even ignoring the bottleneck of communication in traditional pipelines and assuming they could achieve \(5\times\) speedup by scaling up \(5\times\) resource (i.e., 1000 workers), our system still gains up to \(10\times\) speedup over them. In addition, we also design a set of experiments to demonstrate the relationship between time cost and the number of GNN layers for further analysis, and results are presented in Tab. IV. Without loss of generality, the comparisons are mainly conducted between PyG (traditional pipeline) and the MapReduce backend. _nbr50_ and _nbr10000_ mean the number of neighbors for a certain node is limited to 50 and 10000 respectively with neighbor-sampling strategy for experiments on PyG, while there is no sampling for our system. Both the time cost and resource usage of our system increase nearly linearly by varying hops of GNNs, while they increase exponentially in the traditional pipeline. Specially, the traditional pipeline even crashes with the OOM problem when the number of neighbors is set to 10000. Because, in the forward pass of the traditional pipeline, the k-hop neighborhoods of nodes increase exponentially with the hop count, resulting in the exponential growth of communication and computation. However, k-hops neighborhoods for different target nodes could overlap with each other, and the communication and computation on the overlaps are unnecessary. Our system avoids those redundant problem by conducting inference tasks over the entire graph in the full-batch manner. For each node on each layer, it will be used only once in our system. Therefore, the time cost and resources are only related to the hop count. **Consistency.** We take the GraphSAGE model in PyG on the OGB-MAG240M dataset as baselines to verify the consistency of our system and traditional pipelines. The number of neighbors for a node in traditional pipelines is limited to 10, 50, 100, 1000 in different experiments. We count the number of node classes predicted in the traditional pipeline at 10 runs and summarize such information for about 130,000 nodes to see whether predicting scores would keep unchanged. The statistical results are presented in Fig. 7. The x-axis denotes how many classes a certain node belongs to, while the y-axis indicates how many nodes would be predicted to a certain number of classes at 10 runs. For example, when the number of neighbors is set to 10, 30840 nodes are predicted into 2 different classes at 10 runs. In all, about 30% nodes would be predicted to at least 2 different classes when the sampling number is set to 10, which indicates that the prediction score is not trusted. Even increasing the sampling number to 1000, there are still about 0.1% nodes in trouble, which is unacceptable in industrial scenarios, especially in financial applications. Note that when the sampling number increases to 10000, such risk is mitigated, but the time cost increases a lot and even causes the OOM problem as shown in Tab. IV. In contrast, our system achieves the same results at different runs since it conducts the inference phase over the full graph without sampling. And we propose a series of strategies to avoid the OOM problem caused by nodes with a large degree. Therefore, the system is suitable for inference tasks on large graphs, even with skewed degree distribution. **Scalability.** Scalability is a key issue for industrial scenarios. We design a series of experiments and illustrate the relationship between the resource usage (cpu*min) and the data scale to evaluate the scalability of our system. The experiments are conducted over Power-Law datasets, and the data scale includes three orders of magnitude as mentioned in Sec. V-A. A 2-layer GAT model with an embedding size of 64 is conducted on those datasets, and we record the time and resource cost to see how they vary with different data scales. Note that the backend of our system is set to MapReduce as the resource on the cluster for graph processing backend is not enough for the largest dataset. Figure 8 demonstrates the experimental results. The y-axis on the left and right represent resource usage (cpu*min) and time cost (s), respectively, while the x-axis is the data scale. Both the resource and the time-cost curves demonstrate a nearly linear relationship between them and the data scale, which proves the linear scalability of our system. It is worth noting that our system could finish the inference task for all 10 billion nodes (with about 100 billion edges) within 2 hours (6765 seconds), which shows that our system could scale to extremely large graphs and finish inference tasks efficiently. #### V-A2 Analysis for Optimization Strategies For further analysis of our systems, we also design a set of experiments to verify the effectiveness of the optimization strategies for hub nodes proposed in Sec. IV-D. We enable those strategies on the GraphSAGE model over Power-law datasets (about 100 million nodes, 1.4 billion edges) respectively for variable-controlling purposes. Figure 9 illustrates experimental results on the large in-degree problem and the effect of the _partial-gather_ strategy. The x-axis indicates the number of in-edges for nodes in one instance, while the y-axis denotes the instance latency, and each point represents an instance. Results show that latency is positively associated with the number of in-edges. It's reasonable since the time cost for receiving messages and the computation to aggregate those messages are related to the number of in-edges. Therefore, nodes with large in-degree would lead the time cost of the related instance in the long tail and become the bottleneck of the whole inference task. In contrast, the _partial-gather_ strategy helps release the stress caused by a large number of in-edges: the variance of time cost on different instances shrinks a lot, and points are close to the mean line. The reason is from two aspects: firstly, with the _partial-gather_ strategy, messages would be partially aggregated on the sender side, which brings down the time cost in communication. Secondly, the computation of in-edge messages is uniformly conducted in advance on different instances, which balances the computation load for hub nodes. We also make an analysis of the large out-degree problem, and the results are illustrated in Fig. 10. _Base_ denotes the experiment without optimization strategy, while _SN_, _BC_, and _SN+BC_ indicate experiments with _shadow node_ strategy, _broadcast_ strategy, and the combination of them respectively. The y-axis represents the variance of time cost in all instances. Compared with the baseline, both the _shadow node_ and _broadcast_ strategies are helpful in mitigating the problem caused by nodes with large out-edges, and the latter one is slightly better than the former one since _shadow node_ strategy would lead to some overhead by duplicating in-edges to average the communication over different mirror nodes. Specially, for GraphSAGE, we could achieve better results by combining the two strategies since messages for different out-edges are the same. Furthermore, we develop some experiments to evaluate our system's IO costs. Figures 11, 12, and 13 show the results of strategies for large in- and out-degree problems, respectively. Their y-axises show the input or output bytes of each instance. For Fig. 11 and 12, x-axises show the initial number of input or output records for different instances. Specially, the x-axis for Fig. 13 is worker index sorted according to the output bytes since the _shadow node_ strategy would re-arrange the placement of records. degree since there is no overhead involved. The _partial-gather_ strategy reduces the total communication cost of all works by roughly 25% while saving up to 73% IO cost for the 10% workers in the tail. The reason is that each instance would only send one message for a particular node in the upcoming round since the messages have already been pre-aggregated. Each node would only receive as many as instance-number messages in the following round. Moreover, we also vary the threshold for those strategies to verify the heuristic formula in Sec. IV-D. The hyper-parameter \(\lambda\) is set to 0.1 in our system, and the threshold to distinguish whether a node is a 'hub' node then becomes 100,000 (1 billion edges, 1000 workers). Compared with the baselines, both the _broadcast_ and _shadow nodes_ strategies in this setting could decrease the IO cost for "hub" nodes significantly. For instance, the communication costs for the last 10% workers are reduced by 42% and 53% when activating those two techniques, respectively. Furthermore, the efficacy of those strategies would increase as the threshold decreases. However, there is no significant difference for the threshold in the range of [10,000, 100,000], and the difference in IO cost is less than 5%. This is because a low threshold would enable more nodes to benefit from those techniques, but their overhead could not be disregarded. For example, the memory cost is nearly doubled. Therefore, although the threshold determined by the heuristic formula may not be the optimal one, it is reasonable to use it to quickly estimate the threshold, and in this setting, those strategies successfully reduce the IO cost for straggler workers. In summary, the experimental results demonstrate that those strategies proposed in Sec. IV-D help eliminate the stragglers caused by the power law, and as a result, our system achieves better load-balancing. ## VI Conclusion In this paper, we propose InferTurbo, to boost the inference tasks at industrial-scale graphs. The design follows the GAS-like paradigm underlying the computation of GNNs, with which we could specify the data flow and computation flow of GNNs and hierarchically conduct the inference phase in full-graph manner. In this way, our system could avoid the redundant computation problem. We provide alternative backends of MapReduce and Pregel for different industrial applications, and both could scale to large graphs. Furthermore, a set of strategies without dropping any information is used to solve problems caused by nodes with large in-degree or out-degree. The experimental results demonstrate that our system achieves \(30\times\sim 50\times\) speedup compared with some state-of-the-art graph learning systems. Our system could finish the inference task over a graph with 10 billion nodes and 100 billion edges within 2 hours, which shows the superior efficiency and scalability of our system. Fig. 11: IO cost for partial gather strategy Fig. 12: IO cost for broadcast strategy Fig. 13: IO cost for shadow node strategy
2303.02876
Metaheuristic conditional neural network for harvesting skyrmionic metastable states
We present a metaheuristic conditional neural-network-based method aimed at identifying physically interesting metastable states in a potential energy surface of high rugosity. To demonstrate how this method works, we identify and analyze spin textures with topological charge $Q$ ranging from 1 to $-13$ (where antiskyrmions have $Q<0$) in the Pd/Fe/Ir(111) system, which we model using a classical atomistic spin Hamiltonian based on parameters computed from density functional theory. To facilitate the harvest of relevant spin textures, we make use of the newly developed Segment Anything Model (SAM). Spin textures with $Q$ ranging from $-3$ to $-6$ are further analyzed using finite-temperature spin-dynamics simulations. We observe that for temperatures up to around 20\,K, lifetimes longer than 200\,ps are predicted, and that when these textures decay, new topological spin textures are formed. We also find that the relative stability of the spin textures depend linearly on the topological charge, but only when comparing the most stable antiskyrmions for each topological charge. In general, the number of holes (i.e., non-self-intersecting curves that define closed domain walls in the structure) in the spin texture is an important predictor of stability -- the more holes, the less stable is the texture. Methods for systematic identification and characterization of complex metastable skyrmionic textures -- such as the one demonstrated here -- are highly relevant for advancements in the field of topological spintronics.
Qichen Xu, I. P. Miranda, Manuel Pereiro, Filipp N. Rybakov, Danny Thonig, Erik Sjöqvist, Pavel Bessarab, Anders Bergman, Olle Eriksson, Pawel Herman, Anna Delin
2023-03-06T04:04:19Z
http://arxiv.org/abs/2303.02876v2
# Metaheuristic conditional neural network for harvesting skyrmionic metastable states ###### Abstract We present a metaheuristic conditional neural-network-based method aimed at identifying physically interesting metastable states in a potential energy surface of high rugosity. To demonstrate how this method works, we identify and analyze spin textures with topological charge \(Q\) ranging from \(1\) to \(-13\) (where antiskyrmions have \(Q<0\)) in the Pd/Fe/Ir(111) system, which we model using a classical atomistic spin Hamiltonian based on parameters computed from density functional theory. To facilitate the harvest of relevant spin textures, we make use of the newly developed Segment Anything Model (SAM). Spin textures with \(Q\) ranging from \(-3\) to \(-6\) are further analyzed using finite-temperature spin-dynamics simulations. We observe that for temperatures up to around \(20\,\mathrm{K}\), lifetimes longer than \(200\,\mathrm{ps}\) are predicted, and that when these textures decay, new topological spin textures are formed. We also find that the relative stability of the spin textures depend linearly on the topological charge, but only when comparing the most stable antiskyrmions for each topological charge. In general, the number of holes (i.e., non-self-intersecting curves that define closed domain walls in the structure) in the spin texture is an important predictor of stability - the more holes, the less stable is the texture. Methods for systematic identification and characterization of complex metastable skyrmionic textures - such as the one demonstrated here - are highly relevant for advancements in the field of topological spintronics. + Footnote †: These two authors contributed equally + Footnote †: These two authors contributed equally ## I Introduction In systems with many interacting entities, e.g., a chain of amino acids forming a protein [1], a metal cluster [2], or a system of spins [3], the Hamiltonian and its corresponding potential energy surface (PES) can quickly become highly convoluted as the number of interacting particles increases. This complexity is expressed in the form of rugosity of the PES, which in the case of coupled spins is driven by frustration or competing spin-spin interactions. In such cases, finding the global minimum is usually a challenging task due to the non-convexity of the high-dimensional function that represents the PES [4]. However, not only the global minimum, but also the numerous local minima in the PES can provide important information about a given system. In fact, many of the states corresponding to local minima can be long-lived at finite temperatures and have significant consequences for the physical behavior of the system. Magnetic topological spin textures, e.g. skyrmions, are prime examples of such states. Depending on the intrinsic properties (interactions, geometry, anisotropy) and external conditions (field, temperature), skyrmions can emerge as metastable (excited) states in the configuration space, as confirmed by previous experiments [5; 6; 7; 8]. Recently, more complex metastable skyrmionic textures such as skyrmion bags, skyrmionium, and skyrmion bundles have been observed experimentally [9; 10; 11; 12; 13]. From the theory side, it is clear that chiral magnetic skyrmions with arbitrary topological charge should exist [14]. This current interest in more complex metastable skyrmionic textures stems from that such structures may open the door to new topologically inspired spintronic and information-storage concepts. For example, combinations of several different types of skyrmionic structure might prove very useful to make the concept of a skyrmionic bit applicable in practice [15]. Another example is skyrmion-based artificial synapses for skyrmion-based neuromorphic computing [16]. In addition, the skyrmion Hall, skyrmion Seebeck, and skyrmion Nernst effects depend strongly on the topological charge.[17] From theory and computer simulations, some high-order topological spin textures have been identified [14; 18; 19; 20; 21; 22], but a vast flora with novel and potentially very interesting properties remains to be discovered and analyzed. This has motivated us to develop a computational method that can systematically harvest metastable skyrmionic spin textures, given a spin Hamiltonian defining the PES. Here, we present and use a metaheuristic algorithm based on gradient-descent optimization within a conditional neural network, driven by random perturba tions. A conceptual illustration of our method is given in Fig. 1(a). The goal of our method is to efficiently explore the rugged PES and its multiple energy minima, and in this way identify metastable and possibly long-lived states represented by the Hamiltonian. We demonstrate our method by investigating higher-order antiskyrmions within a model of a well-known frustrated system of interacting spins - the Pd/Fe/Ir(111) film. This system has been very thoroughly characterized experimentally and was one of the first studied systems containing two-dimensional magnetic skyrmions [23], and has somewhat attained the status of "fruit fly" in the research on topological spin textures. ## II Method ### Metaheuristic conditional neural network Our method consists essentially of two main ingredients: stochastic gradient-descent (SGD) optimization of the Hamiltonian parameterized in a shallow neural network framework, and a condition directing the global exploration of the PES. Both are described in more detail below. For the first ingredient - i.e., the shallow neural network, in the following called NN-SGD, whose role is to identify local minima of the Hamiltonian - we use the AdamW [24; 25] implementation of SGD within a single-layer feedforward NN to minimize a loss function \(\mathscr{L}(X,W,b)\). Here, \(X\) is an input vector defining the starting point of the SGD optimization, whereas \(W\) and \(b\) are the weights and biases within the NN. The value of the loss function \(\mathscr{L}(X,W,b)\) is provided by the Hamiltonian, i.e., the total energy of the system. We use a Heisenberg-type classical atomistic spin Hamiltonian of the form \[\begin{split}\mathscr{L}(X,W,b)&=\mathscr{H}( \mathbf{S}_{1},\mathbf{S}_{2},\ldots,\mathbf{S}_{n})=\\ &-\sum_{i\neq j}J_{ij}\mathbf{S}_{i}\cdot\mathbf{S}_{j}-\sum_{i \neq j}\mathbf{D}_{ij}\cdot(\mathbf{S}_{i}\times\mathbf{S}_{j})\\ &-\sum_{i}\mu_{i}\mathbf{B}^{\mathrm{ext}}\cdot\mathbf{S}_{i}- \sum_{i}K_{i}^{\mathrm{U}}\left(\mathbf{S}_{i}\cdot\mathbf{e}_{z}\right)^{2}, \end{split} \tag{1}\] where \(\mathbf{S}_{i}\) is the normalized spin moment at site \(i\) and the total number of spins is \(n\). \(J_{ij}\), \(\mathbf{D}_{ij}\), \(K_{i}^{\mathrm{U}}\), \(\mu_{i}\), \(\mathbf{e}_{z}\) and \(\mathbf{B}^{\mathrm{ext}}\) are Heisenberg exchange interactions, Dzyaloshinskii-Moriya (DM) interactions, uniaxial anisotropy, the magnetic moment length of site \(i\), the easy axis vector, and the applied field, respectively. Thus, to employ SGD for optimization we parameterize the neural network's feed-forward mapping as computation of a spin configuration \((\mathbf{S}_{1},\mathbf{S}_{2},\ldots,\mathbf{S}_{n})\). The structure of the NN-SGD is illustrated in Fig.1(b). To initialize the NN, values for \(X\), \(W\), and \(b\) are randomly assigned from a Gaussian distribution with a mean of 0 and a standard deviation of 1. The corresponding spin configuration \((S_{1},S_{2},\ldots,S_{n})\) can then be computed from \(X\), \(W\), and \(b\) using \[M=\mathrm{Norm}\left(\mathrm{LeakyReLU}\left(XW^{T}+b\right)\right) \tag{2}\] where \(W^{T}\) is the transpose of \(W\), and \(M=(m_{1},m_{2},m_{3},\ldots,m_{3n})\) is a vector containing the components of all spins so that the \(x\), \(y\), and \(z\) components of \(\mathbf{S}_{1}\) are \(m_{1}\), \(m_{2}\), and \(m_{3}\), and the components of \(\mathbf{S}_{2}\) are \(m_{4}\), \(m_{5}\) and \(m_{6}\), etc. Furthermore, Norm is the normalization operation so that each spin retains unit length, and LeakyReLU is the activation function, defined in [26]. In our implementation, \(X\) is a vector of length \(k\) and the number of spins \(n\), is \(10^{4}\). Typically, \(k\) is much smaller than \(n\). The role of the NN-SGD is to iteratively converge toward a local minimum of the loss function by adjusting the weights and biases. Convergence is achieved when the stopping condition \[\left|\mathscr{L}^{(i)}-\mathscr{L}^{(i-1)}\right|<T_{s}, \tag{3}\] is met, i.e., the difference in the loss function between two consecutive checkpoints is small enough. Here, \(\mathscr{L}^{(i)}\) is the value of the loss function at the \(i\)-th checkpoint and \(T_{s}\) is the convergence criterion hyperparameter. In our implementation, typically every 50th optimization step is a checkpoint. Although the NN-SGD optimisation is conducted with respect to \(W\) and \(b\), we use an input \(X\) to drive the process of the loss function minimisation, as \(X\) determines the initial conditions for the SGD and thus it influences which local minimum the NN-SDG converges to. In particular, we use a random vector \(X\) and to facilitate "jumping around" over the PES we define new initial conditions by adding random perturbations \(P\) to \(X\), where \(P\) is a vector where some elements are randomly set to zero, and the remaining elements are random numbers taken from a Gaussian distribution. This leads us to the second ingredient in our algorithm - the condition we impose, directing the global exploration of the PES. For each random input vector \(X\) generated (i.e., for each new "jump" over the PES), we first compute the value of the DM-term \(\sum_{i\neq j}\mathbf{D}_{ij}\cdot(\mathbf{S}_{i}\times\mathbf{S}_{j})\) in Eq. (1) of the corresponding spin configuration. Only if its value is within a certain predefined range, we proceed with the NN-SGD optimization. This means that we will only investigate local minima pertaining to specific regions of the PES selected by the imposed condition. In more general terms, the approach can be expressed as follows. The imposed condition is \[T_{\mathrm{C}}^{\mathrm{low}}<\mathscr{H}_{\mathrm{C}}<T_{\mathrm{C}}^{\mathrm{ high}}, \tag{4}\] where \(\mathscr{H}_{\mathrm{C}}\) is some in principle arbitrary combination of spin-Hamiltonian terms, and \(\mathscr{H}_{\mathrm{C}}\) as well as the thresholds \(T_{\mathrm{C}}^{\mathrm{low}}\) and \(T_{\mathrm{C}}^{\mathrm{high}}\) are selected based on physical insight. In practice, the values of \(T_{\mathrm{C}}^{\mathrm{low}}\) and \(T_{\mathrm{C}}^{\mathrm{high}}\) are found through trial and error. Also within the SGD loop, we perform occasional checks that the condition Eq. (4) is still valid, in order to minimise the risk of spending the compute time on converging toward an uninteresting local minimum. In order to sample as many different parts as possible of the PES, we further impose an additional condition that the SGD starting point spin configurations we use be dissimilar to each other. In practice, this is done by creating a large number of randomized spin configurations (typically about 200, all fulfilling the condition in Eq. (4)) and, from these, select the one that is most dissimilar to the previously used starting point spin configuration. When the optimization has converged to a local minimum, the corresponding spin texture is analyzed, for instance by computing its topological charge \(Q\). The algorithm keeps generating new sets of \(X\) and explore the PES as already described above, until the preset maximum execution time is reached. The main parts of the workflow are summarized in a flowchart in Fig.1(c). Finally, let us briefly return to the issue of convergence, Eq. (3). We stated previously that the optimization toward the local minimum was performed using SGD. Naturally, this optimization can be done in several ways and there may be methods that are faster than SGD in certain Figure 1: (a) Conceptual illustration of the overall problem. In a complex PES (the middle picture), we wish to efficently identify local minima containing interesting skyrmionic spin textures (top picture) and avoid converging toward minima with uninteresting spin textures (bottom picture). The yellow and red stars show the initial and final positions for the corresponding NN-SGD optimizations. (b) Chart of the fully connected feed-forward NN-SGD. A random vector \(X\) of length \(k\) is used to select the starting point of the SGD optimization. The values \(m_{i}\) on the output nodes define the spin configuration, see Eq. (2). The loss function \(\mathscr{L}\) is the spin Hamiltonian, Eq. (1). (c) Flow chart showing the main features of the algorithm. For more details, see Section II.1. regimes. In this work, we have therefore selected to use not only SGD but also augment it with a non-gradient method based on Metropolis Markov Chain Monte Carlo (MMCMC) when sufficiently close to convergence. We will in the following denote the first approach as the _SGD-only mode_ and the latter approach as the _hybrid mode_. The SDG-only mode is named this way because it simply uses the SGD inherent in the NN algorithm. In the hybrid mode, we also start out by using SGD, but at a later stage, as convergence is approached, we switch to MMCMC. In essence, the MMCMC optimizer (as implemented in the Uppsala Atomistic Spin Dynamics, UppASD, package [27, 28]) performs energy minimization under finite temperatures by using the transition probability \(P_{t}\) between two spin configurations in a Markov chain: \[P_{t}=\begin{cases}\exp\left(-\frac{\Delta E}{k_{B}T}\right),&\text{ if }\Delta E>0\\ 1,&\text{otherwise}\end{cases}, \tag{5}\] where \(\Delta E\) is the energy difference between the spin configurations, \(k_{B}\) is the Boltzmann constant, and \(T\) is the temperature of the system. The hybrid mode has certain advantages, which we discuss in more detail in Section II.5. In all MMCMC simulations in the present work, the temperature was set to \(1\,\mu\)K. We note that in [29] a neural-network-based method is described and used to identify the spin spiral state in a model system. However, that method contains neither any condition directing the global exploration of the PES, nor any perturbation scheme for \(X\). In fact, the goal of the method in [29] is to identify the global minimum. That is orthogonal to our goal, which is to harvest a large number of metastable textures. ### Metastable spin texture isolation The local minima identified using the method described above usually correspond to several well separated spin textures within the simulation cell. Therefore, for practical reasons, each spin texture that we wish to analyze further needs to be isolated and embedded into a ferromagnetic background. Doing this "by hand" is cumbersome and time consuming. To solve the problem, we designed a pipeline that takes advantage of an AI-driven segmentation model. This approach greatly simplifies the process of harvesting the spin textures we want to analyze further. In the current pipeline, since we are working with a 2D system, we decided to use the state-of-the-art pre-trained Segment Anything Model (SAM), which is designed for image segmentation but can be easily transferred to work for our purposes, i.e., identifying complex spin textures in 2D spin systems, due to its zero-shot generalization property [30]. The workflow can be described as follows: 1. Translate the contents of the entire simulation cell (i.e, a normalized \(3\times n\) matrix corresponding to a spin configuration) to an image by mapping the direction of each spin vector onto RGB color space. 2. Generate spin texture masks using SAM. 3. Isolate a selected spin texture with coordination information contained in the mask. 4. Calculate the topological charge of the isolated spin texture and embed it into a ferromagnetic background. 5. Store the embedded spin texture. ### Computation of the spin Hamiltonian parameters and topological charges The electronic structure calculations of the fcc-Pd/Fe/Ir(111) multilayer system were performed using Density Functional Theory (DFT). We employed the self-consistent real-space linear muffin-tin orbital method in the atomic-sphere approximation (RS-LMTO-ASA) [31, 32] with the local spin density approximation (LSDA) exchange-functional [33]. The resulting ab-initio magnetic moments, as well as coupling parameters \(J_{ij}\) and \(\mathbf{D}_{ij}\), used in Eq. (1), are described in detail in [34]. To avoid effects coming from anticipated truncation, the coupling coefficients were considered up to 360 neighbors (within a distance of \(\sim 7a\) from the reference site, where \(a=3.84\,\)A is the experimental lattice parameter of the Ir host). Furthermore, the experimental value (0.4 meV/Fe [35]) is here assumed for the \(K^{\mathrm{U}}\) uniaxial anisotropy constant. Concerning the Zeeman term in Eq. (1), we set the external field to be \(B^{\mathrm{ext}}=3.5\,\)T and applied in the out-of-plane direction ([001]). At this field, similarly to situation depicted in [36], the skyrmion lattice and ferromagnetic (single-domain) solutions are energetically almost degenerate [34], being isolated skyrmions characterized as metastable structures. Finally, for the Gilbert damping parameter in SLLG, we used the value \(\alpha\sim 0.01\), which is in the order of magnitude of the intrinsic \(\alpha\) in thin films (lower limit) [37]. In the approximation where the Pd-induced spin moments are treated as independent degrees of freedom [38], the Pd layer (when considered explicitly in the ASD simulations) reproduces the Fe layer spin texture [34]. Therefore, we restrict ourselves to the analysis of the Fe layer. As it is widely known, skyrmionic structures are characterized by the topological number \(Q\), which in the limit of a two-dimensional continuum reads: \[Q=\frac{1}{4\pi}\int\mathbf{S}\cdot\left(\partial_{x}\mathbf{S}\times \partial_{y}\mathbf{S}\right)dxdy, \tag{6}\] that measures the winding number of \(\mathbf{S}\). As we consider a discrete medium, the total topological charge, \(Q_{\mathrm{tot}}\), of each spin configuration was calculated using the method proposed by Berg and Luscher [39], with periodic boundary conditions. The quantity \(Q_{\rm tot}\) accounts for all topological structures with individual topological charge (or winding number) \(Q_{i}\) in the spin system (\(Q_{\rm tot}=\sum_{i}Q_{i}\)). Following the same reasoning, each of such structures can be isolated (e.g., in a ferromagnetic background) for the evaluation of the respective topological charges \(Q_{i}\). ### Atomistic spin dynamics simulations To perform the stability analysis of the textures found by the algorithm presented in this work, we solve the stochastic Landau-Lifshitz-Gilbert (sLLG) equation [28], which is implemented in the UppASD package, and is given as: \[\begin{split}\frac{d\mathbf{S}_{i}}{dt}=&-\gamma_{ \rm L}\mathbf{S}_{i}\times\left(\mathbf{B}_{i}+\mathbf{B}_{i}^{\rm f}\right) \\ &-\gamma_{\rm L}\alpha\mathbf{S}_{i}\times\left[\mathbf{S}_{i} \times\left(\mathbf{B}_{i}+\mathbf{B}_{i}^{\rm f}\right)\right].\end{split} \tag{7}\] Here, \(\mathbf{B}_{i}=-\frac{1}{\mu_{i}}\frac{\partial\mathscr{H}}{\partial\mathbf{S} _{i}}\) is the effective field on site \(i\), related to the Hamiltonian defined in Eq. (1) and parametrized by the ab-initio quantities described in Section II.3. The dimensionless (and isotropic) Gilbert damping parameter is here denoted by \(\alpha\), while \(\gamma_{\rm L}=\gamma/\left(1+\alpha^{2}\right)\) is the renormalized gyromagnetic ratio (as a function of the bare one, \(\gamma\)). In turn, \(\mathbf{B}_{i}^{\rm f}\) is the stochastic field arising from the thermal fluctuations. This term describes how temperature effects are considered in the spin dynamics, in a Langevin approach [27]. More specifically, \(\mathbf{B}_{i}^{\rm f}\) is modelled by an uncorrelated Gaussian white noise, so that the time-averages \(\left\langle\mathbf{B}_{i}^{\rm f}(t)\right\rangle=0\) and \(\left\langle B_{i\mu}^{\rm f}(t)B_{i\nu}^{\rm f}(t^{\prime})\right\rangle=2D \delta_{ij}\delta_{\mu\nu}\delta(t-t^{\prime})\) for the site indices \(i\) and \(j\) and the Cartesian coordinates \(\mu,\nu=\{x,y,z\}\). In the second relation, the parameter \(D\) can be obtained via the fluctuation-dissipation theorem [40] as \(D=\alpha k_{B}T/(\gamma\mu_{i})\), for a given temperature \(T\), where \(k_{B}\) is the Boltzmann constant. In Eq. (7), the first term expresses the precessional motion of atomistic magnetic moments in a given system, and the second term describes the damped motion (both in the adiabatic approximation, i.e., \(d\left|\mathbf{S}_{i}\right|/dt=0\)). Besides the dynamics, in the absence of thermal effects, the solution of Eq. (7) with \(\alpha>0\) corresponds to the relaxation process of finding the nearest energy minimum in the PES. Throughout the text, we define the typical simulation times of 200 ps (for the stability of the topological charge) and 2 ns (for the calculation of the average energy/spin with \(T>10^{-4}\) K). The numerical solution of Eq. (7) is obtained with a time step of \(\Delta t=10^{-16}\) s. ### Comparison of the SGD-only and hybrid modes From the user perspective, it is important that the computations converge quickly. Although we cannot directly compare the efficiency of the two optimization algorithms (NN-SGD and MMCMC) since, among other reasons, practically, in our implementation they use different architectures (GPU and CPU parallelized by OpenMP, respectively), and are written in different programming languages, we can compare the execution times of the SGD-only and hybrid modes from the user perspective. To achieve this practical comparison, we introduce an intermediate convergence hyperparameter \(T_{s}^{\rm int}\) in the context of Eq. (3). When the optimization has reached the intermediate level of precision defined by \(T_{s}^{\rm int}\), we either continue with the NN-SGD optimizer (the SGD-only mode), or switch to the MMCMC optimizer (the hybrid mode) until the stopping condition Eq. (3) is fulfilled for our final convergence hyperparameter \(T_{s}^{\rm final}\). In the present benchmark, we have used \(T_{s}^{\rm int}=10^{-3}\) mRy/atom and \(T_{s}^{\rm final}=10^{-6}\) mRy/atom. For both modes, the magnetic texture eventually converges to the same configuration on the PES, but with distinct execution times. Typical optimization procedures for the SGD-only and hybrid modes, for different initial spin configurations, are illustrated in Fig. 2(a) and (b), respectively. In Fig. 2 (c), we compare the execution times of the two modes for ten randomly selected initial spin configurations. In order to produce a fair comparison, both algorithms (NN-SGD and MMCMC) start at \(T_{s}^{\rm int}\) from the same point within each case, and the minimization procedure is stopped at \(T_{s}^{\rm final}\). The red (green) dots show the execution times, counted from the intermediate threshold, for the SGD-only (hybrid) mode. Clearly, the hybrid scheme shows consistently shorter execution times from the user perspective. ## III Results ### Textures with higher-order \(Q\) We applied our algorithm in the hybrid mode to systematically harvest topological spin textures in the fcc-Pd/Fe/Ir(111) system. Overall, given the right conditions such as for instance an appropriate magnitude of the applied magnetic field, we find that this system can hold many types of spin textures including skyrmions, skyrmionium, antiskyrmions, rings and bags comparable to the ones obtained in other systems [41, 43, 42, 36, 9, 40]. For the remainder of this work, we have selected to focus our analysis on antiskyrmion textures. We found an abundance of such textures, and, curiously, they have been less discussed in the literature compared to, e.g., skyrmion bags. In Fig. 3, we show 15 selected spin textures that have been identified to be metastable by our algorithm, with the topological charge \(Q\) varying from \(1\) to \(-13\). Note that throughout this work we use the convention that the skyrmion has topological charge \(+1\), and antiskyrmions have negative topological charge. The first row in Fig. 3 shows a \(Q=1\) skyrmion, skyrmion ium (\(Q=0\)), an three simpler antiskyrmions. As \(|Q|\) increases, the number of limbs and/or rings in the textures increase, see rows 2 and 3 in Fig. 3. For large \(|Q|\), we find very convoluted textures with several rings and limbs combined. ### Stability analysis and binding energies Generally speaking, for a given topological charge \(Q\), several spin textures are typically possible, with varying number of holes and chiral kinks. Here, holes are defined as non-self-intersecting curves that define closed domain walls in the structure. Chiral kinks are described in more detail in [43]. To elucidate how the stability of the spin textures vary with \(Q\), we have for each \(Q\) selected the lowest-energy spin texture found in our simulations. In Fig. 4, we show the computed energy difference with respect to the ferromagnetic single-domain state (\(Q=0\)), \(\Delta E=E-E_{\rm FM}\) for these selected spin textures. We see that the energy difference, \(\Delta E\), is almost linear with respect to \(Q\). As \(Q\) decreases one unit, the energy per spin increases on average \(\sim 0.6\)\(\mu\)Ry. Consequently, the antiskyrmion states with \(|Q|\geq 1\) are relatively close in energy. To gain a more detailed understanding of the stability and lifetimes of these topological spin textures, we have analyzed them further using the concept of skyrmionic Figure 2: Illustration of (a) SGD-only mode (NN-SGD), (b) hybrid mode (NN-SGD followed by MMCMC), and (c) comparison of the execution times of the two modes from the user perspective. Panels (a) and (b) show schematically the optimization procedures for the two modes. Note that the two optimizations in (a) and (b) start from different (random) spin configurations, and cannot be compared directly. The red dashed circle is the starting point (a random spin texture). At the green dashed circle, a spin configuration that does not fulfill Eq. (4) is encountered. Therefore, the algorithm creates a new starting point by adding Gaussian noise to \(X\), and restarts the optimization toward another local minimum. The yellow dashed circle indicates the point at which the intermediate convergence criterion is fulfilled. At this point, the hybrid mode switches from using NN-SGD to MMCMC. Finally, the blue dashed circle points out the final converged solution. The parallelogram insets in both plots (a/b) show the magnetic textures of the system at different times during the minimization procedure. Illustrative movies of the optimization processes can be found in the Supplementary Material. Panel (c) shows the execution times of both algorithms, for ten randomly selected cases. The NN-SGD optimization was performed on a single Nvidia A100 GPU, whereas the MMCMC optimization used an Intel Xeon Gold 6130 CPU, parallelized with OpenMP. binding energy \(E_{b}(Q)\) developed in [42], in combination with results from atomistic spin dynamics simulations using the UppASD software package [28]. In[42], the skyrmion binding energy \(E_{b}(Q)\) is defined as (respecting our \(Q\) sign convention) \[E_{b}(Q)=E(Q)-\left|Q\right|E(\operatorname{sign}Q)-mE(Q=0), \tag{8}\] where \(E(\operatorname{sign}Q)=\begin{cases}E(Q=-1),&\text{if }Q<0\\ E(Q=1),&\text{if }Q>0\end{cases}\), and \(m\) is the number of \(Q=0\) structures that compose the complex skyrmionic configurations. Here, an underlying assumption is that the higher-order spin textures can be described as an excited state consisting of multiple bounded \(Q=\pm 1\) (and eventually \(Q=0\)) structures. Using this definition, in Table 1 we show the computed binding energies of higher-order antiskyrmions with \(Q\in[-5,-3]\), where \(m=0\). The negative \(E_{b}\)'s obtained for these antiskyrmions mean that it is energetically favorable for lower-\(\left|Q\right|\) structures to combine together and form these more complex structures with higher total \(\left|Q\right|\). For comparison, we also computed the binding energy of a \(Q=2\) texture, in which two skyrmions are trapped inside skyrmionium, i.e., a skyrmion bag, see the last row in Table 1. Note that for this case, Eq. (8) must account also for the skyrmionium energy, so that \(m=1\). We find that the binding energy of this skyrmion bag is positive. Similarly, skyrmions bags with \(Q>2\) were also found to have positive binding energies. Thus, the given \((B,T)\) conditions disfavor lower-\(Q\) structures to generate more complex structures with a higher positive-\(Q\). Figure 5 depicts the results from our spin-dynamics simulations for selected topological spin textures with a \(Q\) ranging from \(-3\) to \(-6\). Specifically, we have mapped out how the topological charge, decay time \(\tau\), and total magnetic moment changes with temperature and applied magnetic field. Here, the decay time \(\tau\) is the time it takes for the spin texture to unpack, i.e., change its topological charge. Based on the decay time, final topological charges, and final magnetic moment (per site), and also visual inspection, we divided the charts into four basic zones. Thus, zone I indicates the region in field and temperature in which the topological particle-like structures are long-lived (here taken to mean a life time exceeding \(\tau>200\) ps), keeping their initial real-space structure intact. When \(B\) and/or \(T\) become sufficiently high to reduce the binding energy (see Eq. (8)) by favoring the FM state or due to thermal fluctuations, these higher-order antiskyrmions unpack into lower-\(\left|Q\right|\) textures. These lower-\(\left|Q\right|\) structures can either be relatively stable or survive for just a few picoseconds, depending on the energy Figure 3: A subset of identified topological metastable spin textures in the Pd/Fe/Ir(111) system with \(B^{\text{ext}}=3.5\,\text{T}\). (a) skyrmion, (b) skyrmionium, (c) antiskyrmion, (d) to (o): isolated magnetic textures, with higher-order topological charge varying between \(Q=-2\) and \(Q=-13\). The distance between neighboring spins (cones) is \(a\frac{\sqrt{2}}{2}\sim 2.72\,\text{\AA}\). Blue and red colors indicate opposite spin directions. barrier height. This characterizes the transition region (zone II), where the initial higher-order antiskyrmions are unstable but topological particle-like structures are still present. With further increased temperature, even the lower-\(|Q|\) textures become unstable, gradually shifting to a mostly FM spin configuration (note that here \(T\lesssim T_{C}\)[34]), which defines zone III. Finally, in zone IV we find metastable configurations that resemble domain structures. In that zone, the sufficiently low \(B\) either drives the spin-spiral to be the dominant state, or there is a mix of a spin-spiral state and a skyrmion lattice. As a general trend, we notice that the region where the higher-order antiskyrmions are long-lived (zone I) diminishes with increasing initial \(|Q|\). These observed patterns agree well with the information in Table 1. \(E_{b}\) increases with temperature, enhancing also the probability that high-\(|Q|\) structures separate into lower-\(|Q|\) (or \(Q=-1\)) constituents due to thermal effects. The above analysis, together with the facts that (_i_) single antiskyrmions are long-lived up to sizable temperatures (\(T\sim 32\) K at \(B^{\rm ext}=3.5\) T), which makes the population of these metastable states more likely (with a finite probability given by the Boltzmann factor); and (_ii_) higher-order antiskyrmions are relatively close in energy (Fig. 4), suggests that some high-\(Q\) states in Pd/Fe/Ir(111) can be formed experimentally, at their critical temperatures, by merging \(Q=-1\) textures, as similarly proposed in [44]. The process of bound states generation, however, must overcome an energy barrier. ### Geometry-topology analysis Our method is able to harvest numerous metastable topological spin textures. This opens the door for analyzing whole families of spin textures with the same \(Q\). It is for instance interesting to gain insight into how the stability is affected by the internal structure of spin textures with a given \(Q\). In Fig. 6, the relative energies of seven spin textures, all with \(Q=-5\), are plotted. We see that the spin textures have different energies even though all of them have the same topological charge. This also implies that Eq.(8) is indeed a simplification. The structures can be classified into three different groups. The textures shown in Figs. 6 (b)-(d) can all be described as a skyrmion ring (or hole) with limbs of varying number and lengths attached, whereas the texture in Fig. 6 (e) consists of several rings directly attached to each other. The remaining textures (Figs. 6(f)-(h)) represent hole-free antiskyrmions. Overall, the textures with holes have higher energy and are, consequently, less stable than the ones without holes inside. This result agrees well with what can be observed from Figs. 3 and 4, i.e., spin textures with holes tend to be less stable as compared to \begin{table} \begin{tabular}{c c c} \(Q\) & \(E(Q)\) & \(E_{b}(Q)\) \\ & \(0.04\) (\(<10^{-4}\) K) & \\ \(+1\) & \(0.04\) (\(3\) K) & n.d.1 \\ & \(0.04\) (\(20\) K) & \\ & \(0.67\) (\(<10^{-4}\) K) & \\ \(-1\) & \(0.67\) (\(3\) K) & n.d. \\ & \(0.67\) (\(20\) K) & \\ & \(1.78\) (\(<10^{-4}\) K) & \(-0.22\) \\ \(-3\) & \(1.79\) (\(3\) K) & \(-0.21\) \\ & \(1.80\) (\(20\) K) & \(-0.20\) \\ & \(2.36\) (\(<10^{-4}\) K) & \(-0.31\) \\ \(-4\) & \(2.36\) (\(3\) K) & \(-0.30\) \\ & \(2.42\) (\(20\) K) & \(-0.25\) \\ & \(2.95\) (\(<10^{-4}\) K) & \(-0.39\) \\ \(-5\) & \(2.95\) (\(3\) K) & \(-0.37\) \\ & \(3.02\) (\(20\) K) & \(-0.31\) \\ \(+2\) & \(1.76\) (\(<10^{-4}\) K) & \(0.94\) \\ & \(1.76\) (\(3\) K) & \(0.95\) \\ \end{tabular} \end{table} Table 1: Energies \(E(Q)\) of the topological structures with respect to the ferromagnetic (single-domain) background, and binding energies \(E_{b}(Q)\) of higher-order antiskyrmions (see Eq. (8)), both given in \(\mu\)Ry/atom. The out-of-plane applied field is \(B=3.5\) T, at the temperatures indicated in parenthesis. Figure 4: Relative energy per atom of isolated spin textures with topological charge \(Q\) ranging from \(-13\) to \(1\). (For completeness we have also included the \(Q=+2\) and \(Q=+3\) cases in the plot). The total energy is calculated by embedding each topological excited state in an fcc-Pd/Fe/Ir(111) supercell i.e., a single-domain ferromagnetic background with size \(23.6\times 27.2\) nm\({}^{2}\). The energy scale in the figure is set so that the lowest energy (i.e., the \(Q=1\) skyrmion state) is zero, for visibility. The black dots are computed energies and the blue dashed line is a linear fit to the data. The horizontal red dashed line shows the energy of the ferromagnetic state. The inset shows the energy gap between the \(Q=-1\) spin texture and the ferromagnetic state. the textures without holes. We stress that the textures in Fig. 6 do not cover the whole diversity of solutions for \(Q=-5\) (some other possible metastable states with \(Q=-5\) are given in Ref. [43]). ## IV Discussion and Conclusions Several factors may influence the results obtained with the computational approach we have presented and used in this work. Which metastable spin textures (i.e., local minima) our method finds of course depends on which starting points we allow for the optimization. Thus, tuning the condition in Eq. (4) will strongly affect the results. In this work, we have selected to impose a simple condition on the DM interaction strength, i.e., \(T_{\rm C}^{\rm low}\) > 0.01. Many other options are possible, including imposing several different conditions simultaneously. A condition that would select on exchange frustration may tip the balance in favor of other types of local minima [41; 21]. An important issue is the shape of the energy barriers surrounding each local minimum. The probability for a starting point \(X\) to end up on a wider energy barrier is higher than for it to end up on a more narrow energy barrier. Thus, our method will naturally select for local minima with wide (but perhaps low) energy barriers, unless this is remedied by imposing a condition to specifically select for narrow energy barriers. In addition, the stability of the high-order topological spin textures may depend quite sensitively on the parameters used in the spin Hamiltonian. As an example, we mention that our \(|Q|>6\) textures have a sensitive dependence on the exchange frustration. In our case, the major source of frustration is the next-nearest neighbor interaction shell, so that the relation \(J_{3}/J_{1}\) (see Appendix VII.2) - where \(J_{n}\) denotes the Fe-Fe interaction from a reference site to its \(n\)-th neighboring shell - plays a significant role. Indeed, a change of \(\sim 10\%\) in \(J_{3}/J_{1}\) can lift the theoretical metastability of those configurations. In the context of stability analysis, it is worth noting that there exist additional higher-order interactions that have not been taken into account in this study. These higher-order interactions can influence the energy barrier height as has been demonstrated in recent investigations on skyrmions Figure 5: Magnetic field versus temperature stability maps of antiskyrmions with topological charge varying from \(Q=-6\) up to \(Q=-3\). Columns 1 to 3 show the final topological charge, topological charge decay time and the normalized magnitude of the final magnetic moment, respectively. The top row is for \(Q=-6\), the second row is for \(Q=-5\), the third row is for \(Q=-4\) and the bottom row is for \(Q=-3\). In the right-most column we show typical final magnetic textures in each zone (I, II, III and IV). [45; 46]. Optimizing the condition (4) for various scenarios and performing additional sensitivity analysis will be the subject of future work. To conclude, we have presented a new computational approach based on a conditional neural network, aimed at identifying large numbers of higher-order topological spin textures. Using the Pd/Fe/Ir(111) model system as an example, we have harvested numerous hitherto unidentified antiskyrmion spin textures. The identified spin textures have in turn enabled us to perform a systematic analysis of how the relative stability of spin textures depends on temperature, external magnetic field, the topological charge as well as the number of holes in the texture. ## V Data availability All data is available from the authors upon request. ## VI Code availability All the relevant code is available from the authors upon request. ###### Acknowledgements. This work was financially supported by the Knut and Alice Wallenberg Foundation (grant numbers 2018.0060, 2021.0246, and 2022.0108), Vetenskapsradet (grant numbers 2017-03832, 2019-03666, 2016-05980, and 2019-05304), the European Research Council (grant number 854843-FASTCORR), the foundation for Strategic Research SSF, and China Science Council (CSC) grant number 201906920083. Support from STandUP and eSENCE is also acknowledged. Computations/data handling were enabled by resources provided by KAW (Berzelius-2022-259) and the Swedish National Infrastructure for Computing (SNIC), partially funded by the Swedish Research Council through grant agreement No. 2018-05973. The authors also acknowledge discussions with Zhuanglin Shen.
2304.06321
EEG Cortical Source Feature based Hand Kinematics Decoding using Residual CNN-LSTM Neural Network
Motor kinematics decoding (MKD) using brain signal is essential to develop Brain-computer interface (BCI) system for rehabilitation or prosthesis devices. Surface electroencephalogram (EEG) signal has been widely utilized for MKD. However, kinematic decoding from cortical sources is sparsely explored. In this work, the feasibility of hand kinematics decoding using EEG cortical source signals has been explored for grasp and lift task. In particular, pre-movement EEG segment is utilized. A residual convolutional neural network (CNN) - long short-term memory (LSTM) based kinematics decoding model is proposed that utilizes motor neural information present in pre-movement brain activity. Various EEG windows at 50 ms prior to movement onset, are utilized for hand kinematics decoding. Correlation value (CV) between actual and predicted hand kinematics is utilized as performance metric for source and sensor domain. The performance of the proposed deep learning model is compared in sensor and source domain. The results demonstrate the viability of hand kinematics decoding using pre-movement EEG cortical source data.
Anant Jain, Lalan Kumar
2023-04-13T08:00:18Z
http://arxiv.org/abs/2304.06321v1
# EEG Cortical Source Feature based Hand Kinematics Decoding using Residual CNN-LSTM Neural Network ###### Abstract Motor kinematics decoding (MKD) using brain signal is essential to develop Brain-computer interface (BCI) system for rehabilitation or prosthesis devices. Surface electroencephalogram (EEG) signal has been widely utilized for MKD. However, kinematic decoding from cortical sources is sparsely explored. In this work, the feasibility of hand kinematics decoding using EEG cortical source signals has been explored for grasp and lift task. In particular, pre-movement EEG segment is utilized. A residual convolutional neural network (CNN) - long short-term memory (LSTM) based kinematics decoding model is proposed that utilizes motor neural information present in pre-movement brain activity. Various EEG windows at 50 ms prior to movement onset, are utilized for hand kinematics decoding. Correlation value (CV) between actual and predicted hand kinematics is utilized as performance metric for source and sensor domain. The performance of the proposed deep learning model is compared in sensor and source domain. The results demonstrate the viability of hand kinematics decoding using pre-movement EEG cortical source data. ## I Introduction Brain-computer interface (BCI) system utilizes brain activation signals to control external devices. In particular, electroencephalogram (EEG) signals are utilized for non-invasive BCI systems due to mobility and low-cost. EEG-based motor intention decoding is addressed in [1] for motor classification. Classification based BCI system can also be utilized to command robotic devices [2] and control rehabilitation prosthesis [3]. However, continuous kinematics decoding based motor intention detection can provide efficient control of BCI systems. EEG-based motor kinematics decoding (MKD) has been employed for upper limb motor tasks [4, 5]. The multiple linear regression (mLR) is commonly used for kinematics decoding [5]. Deep learning based decoding models for MKD are explored in [6, 7]. EEG signals suffer with the volume conduction effect [8], which distorts the neuroelectric signals while transmission from cortical surface to the scalp. EEG source imaging (ESI) is utilized for projecting the scalp EEG potentials onto a cortical source space that represent brain geometry. For BCI, the EEG source localization transforms the input features from "sensor-domain" to "source-domain". In comparison to EEG-based motor intention detection, ESI based motor imagery (MI) classification have achieved better performance [9, 10, 11]. However, reliable decoding of motion trajectory from cortical source domain needs to be investigated. ESI based hand motion decoding is addressed for reach-to-target task in [12] and for snake trajectory tracking in [13]. mLR decoder was utilized for hand, elbow and shoulder trajectories estimation during target-reaching experiment in [12] with ESI signals. For actual movement execution, an average correlation of \(0.36\pm 0.13\) was reported across all trajectories. In [13], hand trajectory estimation was performed using a combination of partial least square (PLS) regression model and square-root unscented Kalman filter (SR-UKF) during random snake trajectory tracking. The highest average correlation of \(0.31\pm 0.09\) and \(0.35\pm 0.09\) was reported for hand position and velocity, respectively. In this work, a residual convolutional neural network - long short-term memory (CNN-LSTM) based kinematics decoding model is proposed for MKD. The source-space based input features are taken for hand kinematics estimation for grasp and lift task. The neural information regarding the motor activity reflects on the motor-cortex region approximately 300ms prior to the movement execution [14]. Hence, various time lag windows are utilized to incorporate the pre-movement motor activation for efficient MKD. The EEG windows are considered at 50 ms prior to the movement onset. Further, the source-domain and sensor-domain MKD results are compared. A comparable performance is observed when deep learning model combined with pre-movement EEG data is utilized. ## II Methodology In this Section, the description of grasp and lift database, data processing steps, EEG cortical source estimation, and deep learning based kinematics estimation framework are included. Fig. 1 shows the flowchart of the proposed kinematics estimation framework. ### _Experimental Setup_ In this work, a publicly available WAY-EEG-GAL [15] database is utilized for hand kinematics estimation. Simultaneous EEG and kinematics data was collected for twelve participants during grasp and lift task. A 32-channel EEG system (Brainproducts ActiCap) is used for EEG signal recording, and 3D hand position is recorded using position sensor. The EEG signals and 3D hand position are recorded with a sampling frequency of 500 Hz. The experiment is performed to grasp and lift the object with different weights and surfaces. Each trial initiates with turning the LED ON, placed in front of the participant. The participant moves the hand to reach for the object, grasp it, and then lift it for a couple of seconds. With the LED turned OFF, the participant lowers the hand, puts the object on the initial position, and takes the hand back to the resting position. ### _Data Preprocessing_ EEG data is band-pass filtered in the frequency range of 0.1-40 Hz with zero-phase FIR filter to remove baseline drifts. Average re-referencing is employed on the filtered EEG data. Independent component analysis is utilized for removing eye movement artifacts. Data down-sampling form 500 Hz to 100 Hz is performed for the reduction of computational cost. EEGLAB [16] toolbox is utilized for EEG data preprocessing. A zero-phase low-pass FIR filter (cutoff frequency 2 Hz) is utilized for smoothing of hand kinematic data. Further, the smoothed data is normalized in the range of \([0,1]\) using min-max normalization. Normalized data is down-sampled to 100 Hz to match EEG data sampling rate. ### _EEG cortical source Estimation_ Transformation of EEG data from sensor space to source space requires the solution of EEG forward and inverse modeling. Solution of EEG forward modeling gives lead field matrix, that maps the activation at source space with sensor space. The relationship for EEG potential \(\mathbf{E}\) for I (=32) sensors, K source dipoles and \(N_{s}\) samples, can be expressed as \[\left[\mathbf{E}\right]_{I\times N_{s}}=\left[\mathbf{A}\right]_{I\times K} \left.\left[\mathbf{S}\right]_{K\times N_{s}}+\left[\eta\right]_{I\times N_{s}} \tag{1}\] where, \(\mathbf{E}\) represents scalp EEG data, \(\mathbf{A}\) is lead-field matrix, \(\mathbf{S}\) denotes source activity, and \(\eta\) is the measured noise. In present study, the numerical Boundary Element Method (BEM) is employed, with ICBM152 MRI template [17] as default subject anatomy, to compute head model using OpenMEEG [18]. EEG inverse modeling solution provides the cortex source distribution based on scalp EEG potential and head model. With the given lead-field matrix, the inverse modeling solution computes \(\mathbf{S}\). EEG inverse modeling is a highly under-determined problem, since the number of dipole sources is far more than the scalp EEG sensors. EEG inverse modeling is performed using standardized low-resolution electromagnetic tomography (sLORETA) method [19]. EEG cortical source estimation for the analysis is performed in Brainstorm toolbox [20]. ### _Mindboggle Atlas_ The brain cortical area is sub-grouped into different regions by incorporating Mindboggle atlas [21]. Using Mindboggle atlas, anatomical labels are assigned to cortical structures in MRI data. It labels the cortical brain area into 62 regions. The mean activation of each region is computed to utilize it as input signal for hand kinematics estimation. A total of 62 time-series source signals are obtained for hand kinematics decoding. The selection of regions with Mindboggle atlas is performed using the Brainstorm toolbox [20]. Further, the mean EEG source signals are normalized using z-score normalization. ### _Data Preparation_ For hand kinematics data, the data is segmented from movement onset until the end of the trial. Time lag EEG windows are utilized to consolidate the neural information prior to the actual movement. Various window sizes (150 ms - 300 ms) are utilized for the analysis. EEG cortical source data segment with 150 ms window size will consider EEG data between -200 ms to -50 ms on the time scale, where 0 ms is movement onset. It is to note that pre-movement source data considers 50 ms prior to the actual movement. EEG cortical source matrix with dimension \(T\times(M\times N)\) is utilized as input to movement decoder, where \(T\) is the data segment, \(M\) is total number of scouts, and \(N\) is time lag window. For sensor domain analysis, total number of scouts, Fig. 1: Flowchart of proposed kinematics decoding framework for Grasp-and-Lift task. \(M\), is replaced with total EEG sensors (\(I\) = 32) in the input matrix. ### _Proposed Residual CNN-LSTM architecture_ A deep neural structure with residual convolution neural network (CNN) is proposed for hand kinematics estimation. Since, the EEG cortical source signal is time-series signal, 1D-CNN based residual neural network is utilized. The proposed MKD model consists of ConvBlock, LSTM layer and ResBlock. The structures of ConvBlock and ResBlock are shown in Fig. 2(a) and 2(b), respectively. ConvBlock includes a 1D-CNN layer (\(C_{1}\) filters and kernel size \(=3\)), followed by batch normalization layer, ReLU activation layer, drop-out layer (drop rate \(=0.5\)) and 1D-Average pooling layer (pool size \(=3\)). ResBlock comprises of three 1D-CNN layers with \([F_{1},F_{2},F_{3}]\) filters, batch normalization layers, drop-out layers and ReLU activation layers, along with a skip connection as shown in Fig. 2(b). The proposed residual CNN-LSTM based neural decoder has been shown in Fig. 2(c). It comprises three ConvBlock, two ResBlock, a LSTM layer, a flatten layer and a dense layer. The dense layer outputs the hand kinematics values in x, y, z-directions. ### _Training and Evaluation_ For training and performance evaluation of the proposed neural decoders, the database is divided into distinct sets of training, validation and test data. The training and validation data are used to train the model efficiently. The performance evaluation of trained model is performed on test data. The mean square error is used as loss function with adaptive movement estimation (Adam) optimizer for training the decoding model. The early stopping technique (patience\(=5\)) is utilized to avoid model overfitting. For each participant, a total of 294 trials of grasp-and-lift task are utilized in the analysis from WAY-EEG-GAL dataset. 234, 30 and 30 trials data samples are utilized as training data, validation data, and test data, respectively. ## III Results Correlation value (CV) is taken as performance metric to measure efficiency of the proposed decoding model. The CVs are presented in Table I for different EEG windows. EEG input to the model is taken as detailed in Section II-E. Sensor-domain analysis makes use of 32-channel EEG as input. The mean CV is computed for each time lag window. For source-domain analysis, the proposed residual CNN-LSTM decoding model has overall best performance with the window size of 300 ms. The mean CV of the proposed decoding model with 300 ms time lag window are \(0.59\pm 0.07\), \(0.61\pm 0.07\), and \(0.56\pm 0.06\) in x, y, and z-directions, respectively. It is to note that maximum correlation reported for movement execution in source domain is \(0.36\) for a target-reaching task [12]. Application of deep learning model \begin{table} \begin{tabular}{|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{2}{|c|}{**Participants**} & \multicolumn{2}{|c|}{**Detection**} & \multicolumn{2}{|c|}{**Sources**} & \multicolumn{2}{|c|}{**Sources**} \\ \cline{3-10} \multicolumn{2}{|c|}{} & **100 ms** & **200 ms** & **250 ms** & **300 ms** & **150 ms** & **200 ms** & **200 ms** & **300 ms** \\ \hline \hline \multirow{3}{*}{**P1**} & **s** & 0.35 & 0.38 & 0.59 & 0.60 & 0.68 & 0.68 & 0.72 & 0.71 \\ \cline{2-10} & **s** & 0.35 & 0.38 & 0.59 & 0.61 & 0.68 & 0.70 & 0.77 & 0.70 \\ \cline{2-10} & **s** & 0.59 & 0.59 & 0.59 & 0.53 & 0.65 & 0.66 & 0.72 & 0.66 \\ \cline{2-10} & **s** & 0.46 & 0.54 & 0.58 & 0.51 & 0.61 & 0.69 & 0.43 & 0.51 \\ \cline{2-10} & **s** & 0.47 & 0.57 & 0.52 & 0.54 & 0.54 & 0.53 & 0.47 & 0.57 \\ \cline{2-10} & **s** & 0.38 & 0.54 & 0.51 & 0.52 & 0.52 & 0.53 & 0.54 & 0.59 \\ \cline{2-10} & **s** & 0.46 & 0.48 & 0.53 & 0.53 & 0.45 & 0.56 & 0.54 & 0.51 \\ \cline{2-10} & **s** & 0.46 & 0.51 & 0.56 & 0.57 & 0.57 & 0.47 & 0.56 & 0.51 \\ \cline{2-10} & **s** & 0.53 & 0.56 & 0.57 & 0.51 & 0.51 & 0.59 & 0.50 & 0.56 \\ \cline{2-10} & **s** & 0.70 & 0.59 & 0.59 & 0.59 & 0.57 & 0.53 & 0.57 & 0.54 \\ \cline{2-10} & **s** & 0.72 & 0.77 & 0.57 & 0.57 & 0.72 & 0.75 & 0.56 & 0.76 \\ \cline{2-10} & **s** & 0.64 & 0.63 & 0.64 & 0.61 & 0.67 & 0.65 & 0.66 & 0.66 \\ \cline{2-10} & **s** & 0.47 & 0.49 & 0.31 & 0.48 & 0.53 & 0.54 & 0.54 & 0.57 \\ \cline{2-10} & **s** & 0.48 & 0.53 & 0.53 & 0.51 & 0.59 & 0.60 & 0.65 & 0.65 \\ \cline{2-10} & **s** & 0.53 & 0.61 & 0.56 & 0.56 & 0.51 & 0.60 & 0.56 & 0.57 \\ \cline{2-10} & **s** & 0.37 & 0.44 & 0.47 & 0.51 & 0.40 & 0.52 & 0.59 & 0.61 \\ \cline{2-10} & **s** & 0.38 & 0.46 & 0.54 & 0.40 & 0.51 & 0.57 & 0.57 & 0.59 \\ \cline{2-10} & **s** & 0.46 & 0.46 & 0.46 & 0.49 & 0.58 & 0.47 & 0.51 & 0.57 \\ \cline{2-10} & **s** & 0.41 & 0.52 & 0.53 & 0.55 & 0.57 & 0.59 & 0.59 \\ \cline{2-10} & **s** & 0.42 & 0.50 & 0.52 & 0.54 & 0.58 & 0.58 & 0.51 & 0.59 \\ \cline{2-10} & **s** & 0.53 & 0.53 & 0.54 & 0.52 & 0.51 & 0.58 & 0.54 & 0.58 \\ \cline{2-10} & **s** & 0.58 & 0.57 & 0.72 & 0.72 & 0.68 & 0.72 & 0.75 & 0.74 \\ \cline{2-10} & **s** & 0.59 & 0.59 & 0.59 & 0.73 & 0.71 & 0.73 & 0.76 & 0.76 \\ \cline{2-10} & **s** & 0.64 & 0.68 & 0.63 & 0.68 & 0.69 & 0.69 & 0.60 & 0.70 & 0.70 \\ \cline{2-10} & **s** & 0.56 & 0.62 & 0.69 & 0.69 & 0.64 & 0.66 & 0.71 & 0.71 \\ \cline{2-10} & **s** & 0.58 & 0.66 & 0.69 & 0.72 & 0.58 & 0.71 & 0.74 & 0.75 \\ \cline{2-10} & **s** & 0.53 & 0.53 & 0.53 & 0.54 & 0.58 & 0.54 & 0.56 & 0.59 \\ \cline{2-10} & **s** & 0.67 & 0.47 & 0.51 & 0.57 & 0.53 & 0.54 & 0.54 & 0.59 \\ \cline{2-10} & **s** & 0.70 & 0.50 & 0.54 & 0.51 & 0.53 & 0.59 & 0.54 & 0.59 \\ \cline{2-10} & **s** & 0.51 & 0.46 & 0.47 & 0.56 & 0.57 & 0.53 & 0.58 & 0.54 & 0.59 \\ \cline{2-10} & **s** & 0.54 & 0.54 & 0.57 & 0.55 & 0.59 & 0.58 & 0.51 & 0.56 \\ \cline{2-10} & **s** & 0.57 & 0.59 & 0.54 & 0.57 & 0.55 & 0.58 & 0.51 & 0.60 \\ \cline{2-10} & **s** & 0.51 & 0.56 & 0.61 & 0.61 & 0.51 & 0.66 & 0.65 & 0.65 \\ \cline{2-10} & **s** & 0.52 & 0.57 & **0.59** & **0.59** & 0.59 & 0.52 & **0.62** & **0.62** \\ \hline \end{tabular} \end{table} TABLE I: Hand kinematics decoding analysis of neural decoder with time lag windows of 150 ms, 200 ms, 250 ms, and 300 ms. Fig. 2: ( combined with pre-movement EEG data contribute to the performance enhancement in the present work. For sensor-domain analysis, the best decoding performance is found with 300 ms window size with mean CV of \(0.62\pm 0.08\), \(0.65\pm 0.08\), and \(0.59\pm 0.07\) in x, y, and z-directions, respectively. The mean correlation is plotted in Fig. 3. It may be noted that MKD performance in source domain is comparable with sensor domain counterparts at larger window size. ## IV Discussion and Conclusions In this study, a residual CNN-LSTM based neural decoder is proposed for kinematics decoding using pre-movement neural information in source domain. WAY-EEG-GAL dataset is utilized for this purpose. The performance evaluation of the proposed model is presented using correlation values (CVs) between actual and predicted trajectories in source and sensor domain. The mean activation of the labeled cortical regions is taken as source-domain features for kinematics decoding. A significant correlation is observed in both the domain with the proposed decoding model. Further improvement needs to be explored for better kinematics decoding.
2307.09542
Can Neural Network Memorization Be Localized?
Recent efforts at explaining the interplay of memorization and generalization in deep overparametrized networks have posited that neural networks $\textit{memorize}$ "hard" examples in the final few layers of the model. Memorization refers to the ability to correctly predict on $\textit{atypical}$ examples of the training set. In this work, we show that rather than being confined to individual layers, memorization is a phenomenon confined to a small set of neurons in various layers of the model. First, via three experimental sources of converging evidence, we find that most layers are redundant for the memorization of examples and the layers that contribute to example memorization are, in general, not the final layers. The three sources are $\textit{gradient accounting}$ (measuring the contribution to the gradient norms from memorized and clean examples), $\textit{layer rewinding}$ (replacing specific model weights of a converged model with previous training checkpoints), and $\textit{retraining}$ (training rewound layers only on clean examples). Second, we ask a more generic question: can memorization be localized $\textit{anywhere}$ in a model? We discover that memorization is often confined to a small number of neurons or channels (around 5) of the model. Based on these insights we propose a new form of dropout -- $\textit{example-tied dropout}$ that enables us to direct the memorization of examples to an apriori determined set of neurons. By dropping out these neurons, we are able to reduce the accuracy on memorized examples from $100\%\to3\%$, while also reducing the generalization gap.
Pratyush Maini, Michael C. Mozer, Hanie Sedghi, Zachary C. Lipton, J. Zico Kolter, Chiyuan Zhang
2023-07-18T18:36:29Z
http://arxiv.org/abs/2307.09542v1
# Can Neural Network Memorization Be Localized? ###### Abstract Recent efforts at explaining the interplay of memorization and generalization in deep over-parametrized networks have posited that neural networks _memorize_ "hard" examples in the final few layers of the model. Memorization refers to the ability to correctly predict on _atypical_ examples of the training set. In this work, we show that rather than being confined to individual layers, memorization is a phenomenon confined to a small set of neurons in various layers of the model. First, via three experimental sources of converging evidence, we find that most layers are redundant for the memorization of examples and the layers that contribute to example memorization are, in general, not the final layers. The three sources are _gradient accounting_ (measuring the contribution to the gradient norms from memorized and clean examples), _layer rewinding_ (replacing specific model weights of a converged model with previous training checkpoints), and _retraining_ (training rewound layers only on clean examples). Second, we ask a more generic question: can memorization be localized _anywhere_ in a model? We discover that memorization is often confined to a small number of neurons or channels (around 5) of the model. Based on these insights we propose a new form of dropout--_example-tied dropout_ that enables us to direct the memorization of examples to an a priori determined set of neurons. By dropping out these neurons, we are able to reduce the accuracy on memorized examples from \(100\%\to 3\%\), while also reducing the generalization gap.1 Footnote 1: School of Computer Science, Carnegie Mellon University 2Google Research, Mountain View, CA. Correspondence to: Pratyush Maini ¡[email protected]¿. ## 1 Introduction Deep neural networks are capable of memorizing randomly labeled data (Zhang et al., 2017) yet generalize remarkably well on real world data. Theories have been developed to understand this puzzling phenomenon. For example, _implicit regularization_ argues that the training algorithms, i.e., SGD and its variants, implicitly encourage the trained model to converge to generalizable solutions when the underlying data distribution is well-behaved (Soudry et al., 2018; Smith et al., 2021). Alternatively, the theory of _benign overfitting_ argues that when a neural network is sufficiently overparameterized, it generalizes to the majority of the dataset using a _simple_ component of the input, and memorizes mislabeled and irregular data using a _complex_ component of the input data (Bartlett et al., 2020). These components do not interfere, making such overfitting benign. Another theory of label memorization suggests that when the data follows a long-tailed distribution, memorizing rare examples in the tail is necessary for achieving optimal generalization (Feldman, 2020; Feldman and Zhang, 2020). One common notion of memorization is the 'leave-one-out' memorization--does the prediction of an (atypical) example change significantly if it was removed from the training set? Since this is computationally expensive, multiple prior works operationalize memorization via mislabeled examples, which _must_ be memorized for correct prediction. In our study, we consider both types--mislabeled and atypical example memorization. The practical implication of memorization in deep neural networks has also been widely studied, especially from a privacy and security perspective. For example, Carlini et al. (2021) shows that it is possible to extract training data from large language models. Other work has attempted to reconstruct training examples from output activations (Teterwak et al., 2021) or even parameters (Haim et al., 2022) of _discriminatively_ trained neural networks. However, previous studies have largely focused on the implications of memorization and/or identifying memorized examples. The question of _where memorization happens_ in a neural network remains unclear with only anecdotal observations. In particular, it is _commonly_ believed that memorization of training examples happens in the last (or final few) layers of a deep network (Baldock et al., 2021; Stephenson et al., 2021). In this work, we show that memorization is confined to a small subset of neurons distributed across all layers, as opposed to a fixed set of (such as the final few) layers. We conduct a systematic study to understand the mechanism of memorization in neural networks, in particular, whether there are specific locations in which this phenomenon materializes. Then, we propose a simple dropout modification that enables directing memorization to a fixed set of network neurons. We perform our investigation in two stages. In Stage I, to verify previous beliefs that memorization is confined to the last (few) layers, we design two experiments to detect memorization at the layer level. First, by measuring the influence of memorized (noisy) examples on model weights via gradient accounting (Section 4) we make two key discoveries: (i) the average contribution to gradient norms by memorized examples is an order of magnitude larger than that by typical (clean) examples; and (ii) gradient contribution from the two groups of examples (clean and noisy) have an extremely negative cosine similarity throughout training, at every layer of the model. This suggests that at a layer level, the learning of noisy examples opposes the learning of clean examples, and indicates that mislabeled example overfitting may not be benign in practical settings. Interestingly, the last layer, or any other individual layer, does not stand out as receiving more influence from the memorized examples than from the typical examples. Second, to understand the functional influence of these weight updates, we draw inferences via weight rewinding and retraining (Section 5). In _weight rewinding_, we replace weights of individual layers of the converged model with earlier training checkpoints, and measure the accuracy on the training set. We find that the final layers are not critical to the correct prediction of noisy examples. Moreover, as the model and problem complexity change, we find that the critical layers of the model begin to change, suggesting the critical layers, if any, may be dependent on the particular problem instance. To build on the experiment of layer rewinding, keeping the rest of the model frozen, we retrain the re-initialized layers only on clean examples, and make a surprising discovery--for most layers (including the last few layers), training on clean examples confers nearly 100% accuracy on the (now unseen) mislabeled examples--i.e., the model predicts the randomly assigned (incorrect) label even without seeing that example, indicating the redundance of these layers for memorization. In Stage II, we move away from the hypothesis of layer-level example memorization and inspect memorization at a neuron level, akin to the "grandmother cell" of Barlow (1972) (Section 6). By iteratively removing important neurons with respect to a sample, we determine the minimum number of neurons required to flip an example's predictions. We find that memorized (noisy) examples on average require significantly fewer neurons (by a factor of \(1/3\)) for flipping the predictions, as opposed to clean examples. Moreover, we make the observation that the neurons chosen as most important by our greedy search algorithm are scattered over multiple layers of the model, and the distribution of such neurons for both clean and mislabeled examples are similar. Inspired by this observation, we develop a training mechanism that enables us to intentionally direct the memorization of examples to a predetermined set of neurons. Specifically, we propose a new form of dropout that we call _exampled dropout_ (Section 6.2). We keep a fraction of (generalization) neurons always active during training. A complimentary small fraction of example-specific (memorization) neurons are only activated when that example is sampled in a mini-batch. Using this training scheme, we are able to strongly concentrate the memorization of examples to the memorization neurons. In particular, dropping out these neurons during evaluation brings down the accuracy on mislabeled examples from 100% to 0.1% in the case of the MNIST dataset and from 99% to 3% on the CIFAR10 dataset, with a minor impact on the accuracy on clean training examples. Moreover, we note that the clean examples that get misclassified upon dropping out of the memorization neurons are in fact atypical or ambiguous examples. In summary, our findings suggest that memorization of examples by neural networks can not be localized to the last, or any few layers, but is often determined by a small set of neurons that may be distributed across layers. Moreover, we can perform training time modifications to restrict the model's memorization to a predefined set of neurons. ## 2 Related Work **Learning mechanism.** The learning dynamics of neural networks and their interplay with properties or characteristics of the underlying data is central to various schools of thought--(i) simplicity bias (Shah et al., 2020; Arpit et al., 2017), neural networks have a strong bias towards learning'simpler' features as compared to ones that require a more complex representation; (ii) long-tailed nature of datasets (Feldman, 2020; Feldman and Zhang, 2020)-- ML datasets have a large fraction of singleton examples with features that occur only once in the training set. As a result, the neural network must memorize these examples to be able to correctly predict them; and (iii) early learning phenomenon (Frankle et al., 2020; Liu et al., 2020), suggesting that simpler examples are learned fast. **Atypical Example Memorization.** Inspired by the early learning phenomenon, recent work has used metrics inspired by the learning time of an example to determine which examples are memorized by a neural network (Carlini et al., 2019; Jiang et al., 2021). Other works have focussed on notions of forgetting time, suggesting that examples forgotten frequently during training (Toneva et al., 2019) or forgotten quickly when held out (Maini et al., 2022) are memorized. **Location of Memorization.** Motivating our inquiry, recent works have argued that hard examples are learned in the last few layers of a model. Baldock et al. (2021) investigate the _prediction depth_ of various examples, defined as the earliest layer in a neural network, whose representations can successfully predict the label of an example when probed using a k-nearest neighbor search. They find that the prediction of mislabeled examples occurs in the final few layers of the model, and conclude that "early layers generalize while later layers memorize". Other works have attempted at measuring the manifold complexity and shattering capability (Stephenson et al., 2021) of various layers to once again argue that mislabeled examples must be memorized in the last few layers of the model. They also propose regularization of the final layer of the model as a remedy for alleviating memorization. **Modifying neural networks.** Recent works have attempted to change the neural network predictions by modifying only a small fraction of the neurons. Such investigations have been primarily focused on understanding where are facts stored in a neural network (Zhu et al., 2021; Meng et al., 2022). Sinitsin et al. (2020) investigated methods for pathing mistakes of a neural network by modifying a small number of neurons. In our experiments on neuron-level memorization, we investigate the opposite idea, what are the minimum number of neurons required to flip the prediction of a neural network to a _different_ class, and contrast the model behaviour on clean and memorized examples based on this. **Task specific neurons.** Prior work in the space of multitask learning has studied the use of designated gates for the task of continual learning to avoid forgetting (Jacobs et al., 1991; Aljundi et al., 2017). Follow-up work also studied the idea of specialization at a synapse level, rather than having individual gates for different tasks (Zenke et al., 2017; Cheung et al., 2019). Recent work on training under noisy data assigned a new parameter to each example that learns the correct label for that example. This learning adapts the class label simultaneously as the model learns to predict correctly on the adapted label (Liu et al., 2022). These ideas are related to the concept of example-tied dropout that we introduce in Section 6.2. In our work, we propose a new dropout scheme that aims to select specialized memorization neurons and use it to direct all example memorization to them. This idea of specialization is akin to that in multitask learning but in a totally different, example-level regime. ## 3 Problem Setup **Preliminaries.** Consider a \(d\)-layer feed-forward neural network \(\mathcal{F}_{d}\) parametrized by weights \(\theta=(\theta_{1},\dots,\theta_{d})\). We use \(z_{l}\) to denote the activations from neurons in the \(l^{\text{th}}\) layer of the model, and refer to the equations of the network as: \[z_{l}=\mathcal{F}^{l}(z_{l-1};\theta_{l}) \tag{1}\] where \(\mathcal{F}^{l}\) denotes the function of the \(l^{\text{th}}\) layer. When referring to a single neuron (or in the case of a convolutional network, to a single channel) we use the notation \([z_{l}]_{j}\) to refer to the \(j^{\text{th}}\) individual neuron/channel. We consider the supervised classification paradigm where we train \(\mathcal{F}_{d}\) on a dataset \(\mathcal{S}=\{\mathbf{x}_{i},\mathbf{y}_{i}\}^{n}\). The model is trained using Stochastic Gradient Descent (SGD) to minimize the empirical risk given by \(\mathcal{L}(\mathcal{S},\mathcal{F}_{d})=\sum_{i}\ell(\mathcal{F}_{d}( \mathbf{x}_{i}),\mathbf{y}_{i})\). We denote the model parameters after the \(t^{\text{th}}\) epoch of training by \(\theta^{t}=(\theta^{t}_{1},\dots,\theta^{t}_{d})\). For experiments with label noise, we randomly change the label of a fixed fraction of examples to an incorrect label. \(\mathcal{S}=\mathcal{S}_{c}\bigcup\mathcal{S}_{n}\), where \(\mathcal{S}_{c}\) and \(\mathcal{S}_{n}\) are mutually exclusive subsets containing clean and mislabeled examples respectively. **Datasets and Models Used.** We perform experiments on three image classification datasets, CIFAR-10 (Krizhevsky, 2009), MNIST (Deng, 2012), and SVHN (Netzer et al., 2011). We use two sizes of the ResNet model, namely, ResNet-9, and ResNet-50 (He et al., 2016), and also the Vision Transformer (ViT) small model (Dosovitskiy et al., 2021). Results for gradient accounting and weight rewinding of ResNet models are averaged over 3 seeds. **Combining Layers.** For our analysis of ResNet-50 and ViT models, we combine the influence of multiple layers of the model to simplify our visualizations. This is done by combining all layers that belong to the same block in the case of ResNet-50. The blocks are differentiated by the image size that they encode and can be identified by the layer name (layerX.[module]) in the standard PyTorch implementation. Similarly, for ViT, we group multiple layers into a single module based on the transformer blocks, which can be identified by the layer name (transformer.layers.X.[module]) in PyTorch. **Training Parameters.** We use the one-cycle learning rate (Smith, 2017) and train our models for 50 epochs using SGD optimizer. The peak learning rate for the cyclic scheduler is set to 0.1 at the 10th epoch, and the training batch size is 512. Unless specified, we add 10% label noise to the dataset: that is, we change the label of 10% examples to an _incorrect_ class chosen at random. ## 4 Gradient Accounting When training a model, at the \(t^{\text{th}}\) epoch, \(\mathcal{F}_{d}(\theta^{t})=(\theta^{t}_{1},\dots,\theta^{t}_{d})\) using gradient descent, the parameter update to any layer \(l\) for a learning rate \(\eta\) is given by: \[\theta^{t+1}_{l}=\theta^{t}_{l}-\eta\frac{d\mathcal{L}(\mathcal{S},\mathcal{F} _{d})}{d\theta_{l}}\] The quantity \(\nicefrac{{d\mathcal{L}(\mathcal{S},\mathcal{F}_{d})}}{{d\theta_{l}}}\) determines the update to the weights of the model. If knowledge were to be encoded in model weights, this quantity is an indication of the memorization potential of a layer. ### Layer-wise norm contribution In order to assess the contribution of gradients from clean and mislabeled examples respectively, we measure \(\left\|\nicefrac{{d\mathcal{L}(\mathcal{S}_{e},\mathcal{F}_{d})}}{{d\theta_{1}}}\right\|_ {2}\) and \(\left\|\nicefrac{{d\mathcal{L}(\mathcal{S}_{n},\mathcal{F}_{d})}}{{d\theta_{1}}} \right\|_{2}\) on clean and noisy data subsets per epoch. We normalize them by the square root of the number of parameters in \(\theta_{1}\). To combine results over multiple epochs or layers, we take the average of the individual normalized gradient norms. **Observations and Inference.** We observe that no layer receives significantly more contribution from memorized examples than from clean examples (Figure 1). However, we do notice an interesting the phenomenon in our results--even though the mislabeled data accounts for only 10% of examples in the training data, their overall contribution to the gradient norms, and consequently to the model weights is the same as that of all the clean examples together. This suggests that while mislabeled examples may not be learned in particular layers of the model, they do have a large influence on all layers of the model. This implies that mislabeled example gradient norms are an order of magnitude higher than that for clean examples. Results on other noise rates, datasets, and architectures can be found in Appendix A. ### Clean and Noisy example gradient similarity Notice that the norms of total gradient contribution in Figure 1 are significantly smaller than both the gradients of clean and noisy examples respectively. This suggests that the gradient contribution from the two subsets may be canceling out each other, implying the detrimental impact of mislabeled examples on clean example training. To evaluate the same, we compute the cosine similarity between the average gradients of clean and mislabeled examples for every layer at every epoch during training. **Observations and Inference.** We observe that the gradients of clean and mislabeled examples have an extremely negative cosine similarity. This suggests that the clean and mislabeled examples are detrimental to each other at a layer level. However, based on the analysis of gradient similarities at a layer level, it is not possible to assert if (a) at every neuron within the layer as well, the gradients are misaligned, or (b) this is an aggregate phenomenon only occurring at the macroscopic layer level. When contrasted with the learning curves in Figure 3, we note that the region of interest when the mislabeled examples are learnt belongs to epochs \(10\)-\(30\), and the cosine similarities of the clean and mislabeled examples stay below -0.75 for all epochs and layers during the majority of this time. This indicates that overfitting to mislabeled examples may not be benign, especially when analyzed at a layer level. Results on other noise rates, datasets, and architectures can be found in Appendix A. ## 5 Functional Criticality of Layers Zhang et al. (2022) studied the importance of different layers of a neural network by categorizing them into robust and critical based on the robustness of the layers to re-initialization to weights from an intermediate training checkpoint. In this work, we perform this analysis in the context of memorized (mislabeled) and clean examples. We checkpoint the model parameters \(\theta^{t}\) for every epoch of training (\(t\in[T]\)). The parameters \(\theta^{0}\) represent the model weights at initialization. ### Layer Rewinding For a converged model \(\mathcal{F}_{d}\) parametrized by \(\left(\theta_{1}^{T},\dots,\theta_{d}^{T}\right)\) trained for \(T\) epochs, we replace the weights of a single layer of the converged model with that of the corresponding layer in a model that was checkpointed at an earlier epoch during training. We repeat the procedure for every layer (or Figure 1: Gradient norm contribution from noisy examples closely follows that for clean examples even when they constitute only 10% of the dataset. Results depicted for epochs \(15\)-\(20\) for a ResNet-9 model trained on the CIFAR-10 dataset with 10% label noise. Figure 2: Cosine similarity between the average gradients of clean and mislabeled examples per layer, per epoch for ResNet9 model on the CIFAR10 dataset with 10% label noise. The memorization of mislabeled examples happens between epochs \(10\)–\(30\) (Figure 3). layer group) in the model. That is, if layer \(l\) is reinitialized to epoch \(t\), the new model \(\tilde{\mathcal{F}}_{d}\) is would be parametrized by \(\left(\theta_{1}^{T},\ldots,\theta_{l-1}^{T},\theta_{l}^{t},\theta_{l+1}^{T} \ldots\theta_{d}^{T}\right)\). Then, we evaluate the model on the training set to assess the change in training accuracy as a result of the weight rewinding. **Observations and Inference.** In Figure 3 we present the accuracy upon reinitialization for clean (mid) and noisy (right) examples. We find that rewinding the final layers to earlier epochs has low impact on the classification accuracy of the memorized examples. If contrasted with learning dynamics of the memorized examples (Figure 3 (left)), we observe that the model accuracy on noisy examples stays below 20% until the 30th epoch. Despite this, rewinding individual model layers to a checkpoint before the 30th epoch does not reduce accuracy on memorized examples. This seemingly contradicts the hypothesis that memorization happens in the last (few) layer(s). Secondly, on comparing the critical layers of the three architectures, we notice that the depth of critical layers for the noisy examples is different for different models. These together suggest that the location of memorization of an example (a) is distributed across layers, (b) may depend on the exact problem instance (complexity of the model and the task), and (c) is similar to layers that are critical for clean examples as well. ### Layer Retraining The experiment on layer rewinding helps us determine which layers are critical for the correct prediction of memorized examples. However, we note that the layers important for the correct prediction of mislabeled examples were also important for the prediction of clean examples. Further, the rate of learning of different layers may be an additional confounder in these results. To remove such a confounder, we study the impact of layer memorization by retraining individual layers after rewinding that layer back to its initialization, but only training on clean examples from there on. When retraining layer \(l\) of model Figure 3: Change in model accuracy on rewinding individual layers to a previous training epoch for clean examples (left) and mislabeled examples (right). The dataset has 10% random label noise. Epoch 0 represents the model weights at initialization. \(\left(\theta_{1}^{T},\dots,\theta_{l-1}^{T},\theta_{l}^{0},\theta_{l+1}^{T}\dots \theta_{d}^{T}\right)\). We then train the model for a maximum of 20 epochs using a one-cycle learning schedule with a maximum learning rate of 0.1 at the \(10^{\text{th}}\) epoch (Smith, 2017). All other model layers are kept frozen, but the batch norm running statistics are allowed to be updated as the model trains on the clean dataset. **Observations and Inference.** Results of retraining individual layers show that training models on only clean examples also confers large accuracy on noisy examples (Figure 4). When a particular layer was reset to its initialization, keeping the rest of the model frozen, if the optimization objective can still achieve high accuracy on noisy examples (unseen by that layer), this confirms that the information required to predict correctly on memorized examples is already contained in the other layers of the model. Therefore, the layer under question is redundant in terms of memorization. It is also important to note that this experiment is conclusive _only_ in the case when retraining on clean examples succeeds in simultaneously attaining high accuracy on mislabeled examples, making it a one-way implication that the layer was redundant for memorization. However, if the retraining objective does not yield high accuracy on mislabeled examples, we cannot claim that it is because the layer was important for memorization, since multiple minima to the problem may exist, and the retraining objective did not reach the same minima in this instance of optimization. An example of the same can be seen in case of the MNIST dataset (Figure 4.b) where in Layer 5, even though the model achieves over 70% accuracy on the mislabeled examples during the training, it finally converges at a solution that offers less than 10% accuracy. ## 6 Memorization by Individual Neurons Experiments in the previous section highlight that it is not hard to localize the memorization of examples to particular layers of the model. This observation points to an even more fundamental question--_is the memorization of examples localized to any subset of model weights?_ If this answer is in the affirmative, only then, can any attempts at localizing the memorization at a layer-level succeed. ### How many neurons does it take to predict an example? Through a gradient-based greedy search, we iteratively find the most important neurons for a model's prediction on a given candidate example. Then, in the case of linear layers, we zero-out a single weight in the layer. In the case of convolution layers, we zero-out a complete channel. For simplicity, we will use the term neurons to represent both scenarios. In order to robustly find neurons critical to the prediction of an example, we enforce the following: (a) Preserve the prediction on the sample data by reducing the average loss on a random batch from the training set, but maximizing the loss on the input to be flipped. (b) Gaussian Noise is added to the input, and predictions are made based-off the Figure 4: The impact of retraining individual layers from scratch on only clean examples, while keeping the rest of the model frozen. The results shown are for ResNet-9 model on the CIFAR10 (left) and MNIST (right) datasets with 10% random label noise. average output over 5 random noise values. This is done to avoid gradient-based search to exploit the prevalence of adversarial examples for finding critical neurons. We refer to this classifier as \(\overline{\mathcal{F}_{d}}\). Finally, for each example, we average the number of iterations required for flipping in over 30 different random training runs to make the statistic more robust. The objective to find the most critical neuron with respect to example \((\mathbf{x}_{i},\mathbf{y}_{i})\) in the dataset can be written as: \[[z_{l}]_{j}^{*}=\arg\max_{l,j}\left[\nabla_{\theta_{l}}\left(\ell(\overline{ \mathcal{F}_{d}}(\mathbf{x}_{i}),\mathbf{y}_{i})-\frac{1}{n}\mathcal{L}\left( \mathcal{S},\overline{\mathcal{F}_{d}}\right)\right)\,\right]_{j}\] As defined in Section 3, in case of convolution layers, \([z_{l}]_{j}\) represents the activations from an entire channel, whereas those from a single neuron in the case of linear layers. We zero-out the activation before propagating to the next layer. This procedure is repeated iteratively until the prediction on the example in question is flipped to an incorrect class. Observations and InferenceWe observe that the number of neurons required to be zero-ed out in order to flip the prediction of clean examples is significantly larger than the corresponding number for noisy examples. This suggests that there is a very small number of neurons that are responsible for the correct prediction of mislabeled examples. In our experiments, for more than 90% of memorized examples less than 10 neurons are responsible for memorization. The average of this value for the entire set of noisy and clean examples is 5.1 and 15.7 respectively (Figure 5.a). We also calculate the accuracy of the model on the remaining training set post-removal of neurons critical to the prediction of the example in question. The neurons corresponding to the mislabeled examples typically have a much lower impact on the population accuracy as compared to clean examples (Figure 5.b). The average post-removal accuracy for mislabeled examples is 10% higher than that for clean examples. Figure 5.c showcases how the critical neurons selected for both clean and mislabeled examples most often belong to a similar set of layers, and it is not the case that important neurons for clean and mislabeled examples belong to specialized layers. This suggests that certain layers may in general be important to the model. Further, the neurons chosen are scattered over multiple layers, suggesting that it is hard to localize memorization to a particular few layers. Rather, memorization is a phenomenon confined to a select few neurons dispersed over multiple layers. Moreover, future work may benefit by using _critical neuron removal_ as a metric for finding mislabeled examples from the dataset. Given any trained model, and suspect data point, find the number of neurons to be zero-ed in order to flip its prediction. If this number is lower than a pre-defined threshold, classify the example as memorized (or mislabeled). By using the same procedure, we are able to obtain an AUC of 0.89 in identifying mislabeled examples on the CIFAR10 dataset with artificially added 10% label noise. This is competitive with existing baseline methods that achieve 0.87 (learning time (Jiang et al., 2021)) and 0.93 (forgetting time (Maini et al., 2022)) AUC respectively. ### Example-Tied Dropout: Directing Memorization to Specific Neurons Based on our observations from Section 6.1, we know that the information required to correctly predict on mislabeled examples is typically encoded in far fewer neurons than for clean examples. More interestingly, changing the prediction of clean examples by zero-ing out individual activations comes with a significantly higher cost on overall model accuracy on the same training set, and also on the test set. These findings motivate attempts to direct the memorization of examples to neurons that are fixed apriori. Example-Tied DropoutTo operationalize the idea of connecting a subset of neurons to every example, we assign Figure 5: For each example in a subset of 1000 clean and 1000 noisy examples, we iteratively remove the most important neurons from a ResNet-9 model trained on the CIFAR-10 dataset with 10% random label noise, until the example’s prediction flips. (a) Memorized examples need fewer neurons to flip their prediction. (b) Upon flipping the prediction, the drop in accuracy on the sample is much lower. (c) The most important neurons are distributed across layers in a similar way for both clean and mislabeled examples. a fixed fraction \(p_{\text{gen}}\) of neurons per layer that are never dropped out. We call these the generalization neurons. In the case of convolutional layers, in order to preserve the channel structure, we similarly select a fixed fraction \(p_{\text{gen}}\) of channels that are never dropped out. From the remaining fraction, we assign a small subset of \(p_{\text{mem}}\) neurons per example that are activated whenever a particular example is sampled. The goal is to direct all the feature learning to the \(p_{\text{gen}}\) set of neurons, and the example specific memorization neurons to the \(p_{\text{mem}}\) set of neurons. At test time, we drop out the neurons corresponding to \(p_{\text{mem}}\), that is zero-out their activations, in order to adapt the model in such a way that the influence of memorization can be removed. The experiments of example-tied dropout demonstrate that it is indeed possible to confine the memorization of examples to a pre-determined set of neurons. After each layer of a ResNet 9 model, we append a layer of 'example-tied dropout' and train the model on the MNIST, SVHN, and CIFAR10 datasets in a setting with 10% uniformly random label noise. Upon dropping the memorization neurons, the accuracy on the mislabeled examples reduced to 0.1%, 1.4%, and 3.1% for the three datasets respectively, even though the model almost perfectly fits on all the noisy data at training time. In all cases, the effective impact on the clean examples is only 0.8%, 4.2%, and 9.2% respectively, also lowering the generalization gap between train and test performance. This suggests that the \(p_{\text{gen}}\) fraction of (generalization) neurons already contained the features required to classify the prototypical examples of the dataset. Analysis of clean examples forgottenTo understand the reason for the drop in accuracy on clean examples on removing the memorization neurons, we find that most of the examples that the model no longer correctly predicts are in fact either mislabeled and ambiguous or exceptional and unique examples from the dataset that the model must memorize in order to correctly predict on (Figure 7). Impact of Hyperparameter TuningTo assess the impact of the choice of values of \(p_{\text{gen}}\) and \(p_{\text{mem}}\) on the ability of example-tied dropout to localize memorization in neurons, we run a grid search on 12 different parameter combinations. Results for the change in the efficacy of the method with a change in these values are presented in Table 2. We find that the method is robust to a large range of values (and combinations) of \(p_{\text{gen}}\) and \(p_{\text{mem}}\). In general, we observe the trend that as we increase the capacity of the generalization neurons, the localization of memorization in the memorization neurons keeps decreasing (that is, the noisy example accuracy upon dropping out the memorization neurons increases). At the same time, this also results in an increase in clean example accuracy after dropping out of memorization neurons. Benchmarking with other baselinesFor a given value of \(p_{\text{gen}}\), we select two equivalent models that (a) use standard dropout with p = \(p_{\text{gen}}\), and (b) use a sparse network with remaining parameter fraction = \(p_{\text{gen}}\). Then, we finally compare the accuracy of the model on clean and noisy training examples after training for 50 epochs on the CIFAR-10 dataset, using the ResNet-9 model. In the case of example-tied dropout, we drop the memorization neurons while measuring the accuracy in Table 3. We see that at the same sparsity level when example-tied dropout is able to direct memorization to a chosen set of neurons, sparse and standard dropout methods are still capable of overfitting to the training set (including mislabeled examples). \begin{table} \begin{tabular}{l c c c c c c} \hline \hline \multirow{2}{*}{Dataset} & \multicolumn{4}{c}{Before Dropout} & \multicolumn{2}{c}{After Dropout} \\ \cline{2-7} & Clean & Noisy & Test & Clean & Noisy & Test \\ \hline CIFAR10 & 99.9\% & 99.3\% & 79.3\% & 90.8\% & 3.1\% & 82.7\% \\ MNIST & 100\% & 100\% & 99.0\% & 99.2\% & 0.1\% & 99.3\% \\ SVHN & 99.9\% & 99.6\% & 89.5\% & 95.8\% & 1.4\% & 89.6\% \\ \hline \hline \end{tabular} \end{table} Table 1: Dropping out memorization neurons leads to a sharp drop in accuracy on mislabeled examples with a minor impact on prediction on clean and unseen examples. Figure 6: (a) A schematic diagram explaining the difference between the generalization and memorization neurons. At test time, we dropout all the memorization neurons. (b) Forward propagation for input tied to the \(i^{\text{th}}\) memorization neuron Figure 7: Most of the clean examples that are forgotten when dropping out the neurons responsible for memorization in the case of Example-tied dropout were either mislabeled or inherently ambiguous and unique requiring memorization for correct classification. ## 7 Memorization of Atypical Examples The experiments until now operationalize memorization through'mislabeled examples'. Since the label for these examples does not obey the class semantics, it is convenient to categorize any 'correctly' predicted mislabeled example as'memorized'. However, this is a very strong notion of memorization and prior work has observed the existence of 'atypical examples' that also end up getting memorized (Feldman and Zhang, 2020). Such a definition of memorization utilizes the 'leave-one-out' form of memorization. An example is said to be memorized if its prediction changes significantly when it is present versus absent in the training set of the model. Jiang et al. (2021) approximated a consistency score (C-score) for each example by bootstrapping the leave-one-out memorization. In particular, a low C-score (in the [0,1] range) implies that the model will need to memorize an example. We use a threshold of 0.5 and select all examples below the threshold to construct the'memorized set'. This set is of the size \(\sim 5000,~{}\sim 1000\) examples for the MNIST and CIFAR10 datasets respectively. We do not add any label noise in this set of experiments. **Gradient Accounting.** We find that the results are consistent with past results that study the memorization of mislabeled examples. In particular, the aggregate gradient contribution from atypical examples is similar to typical examples despite their significantly smaller size (Figure 8). **Layer Rewinding.** Rewinding plots in Figure 9 suggest that memorization of atypical examples is dispersed across various layers of the model, which is also consistent with the results for mislabeled examples. **Layer Retraining.** We find that in the retraining experiment, all layers can be retrained by seeing only examples with C-score \(>0.5\) such that the "memorized" examples also achieve 100% accuracy. This suggests how the localization of memorization is even more challenging in such OOD/atypical example settings (Appendix B.2, Figure 19). ## 8 Discussion In this work, we perform a systematic study to identify if the memorization of examples is confined to particular locations within a network. Contrary to previous hypotheses, our results show that memorization is often dispersed across multiple layers. In particular, our results have important implications for both the privacy and the generalization of neural networks. From a privacy point of view, unlearning specific layers _may not_ help the model forget memorized examples; and for generalization, rewinding or strongly regularizing only a small set of layers may be sub-optimal since memorization can not be localized to a few layers. On the other hand, our work showed that memorization is localized to a few neurons dispersed across different model layers. We introduce a novel mechanism to direct memorization to a predetermined subset of neurons, using example-tied dropout. At test time, practitioners may throw away such'memorized' neurons. This has positive implications in the field of machine unlearning and training with noisy data. \begin{table} \begin{tabular}{c c c c c c c} \hline \hline \(p_{\text{mem}}/p_{gen}\) & 0.1 & 0.2 & 0.3 & 0.4 & 0.5 & 0.6 \\ \hline 0.1 & \(84.2\%\), 2.9\% & \(86.9\%\), 2.8\% & \(87.1\%\), 2.9\% & \(89.9\%\), 3.1\% & \(92.0\%\), 3.9\% & \(93.0\%\), 4.9\% \\ 0.2 & \(86.9\%\), 2.8\% & \(88.2\%\), 3.0\% & \(90.8\%\), 3.1\% & \(91.7\%\), 3.4\% & \(93.6\%\), 4.7\% & \(95.0\%\), 6.9\% \\ \hline \hline \end{tabular} \end{table} Table 2: Impact on final clean and noisy example accuracy (training set) when changing the values of \(p_{\text{mem}}\) and \(p_{\text{gen}}\). Each cell represents the clean, noisy example accuracy after dropping out all the memorization neurons during test time. \begin{table} \begin{tabular}{l c} \hline \hline Method & Accuracy \\ \hline Standard Dropout (p = 0.4) & \(100\%\), \(99.5\%\) \\ Sparse Network (s = 0.4) & \(100\%\), \(99.8\%\) \\ Example-Tied (\(p_{\text{gen}}\) = 0.4, \(p_{\text{mem}}\) = 0.2) & \(90.8\%\), \(3.10\%\) \\ \hline \hline \end{tabular} \end{table} Table 3: Comparison of Accuracy on clean, noisy training examples after training with various methods that activate only a small fraction of the network during training time. Figure 8: Gradient Accounting for Atypical Examples when training a ResNet-9 model on CIFAR-10 (left) and MNIST (right). Figure 9: Layer Rewinding for Atypical Examples in CIFAR-10 ## Acknowledgements We gratefully acknowledge the NSF (FAI 2040929 and IIS2211955), UPMC, Highmark Health, Abridge, Ford Research, Mozilla, the PwC Center, Amazon AI, JP Morgan Chase, the Block Center, the Center for Machine Learning and Health, and the CMU Software Engineering Institute (SEI) via Department of Defense contract FA8702-15-D-0002, for their generous support of ACMI Lab's research. Pratyush Maini is supported by funding from the DARPA GARD program.
2306.06558
Refractive index tomography with a physics based optical neural network
The non-interference three-dimensional refractive index(RI) tomography has attracted extensive attention in the life science field for its simple system implementation and robust imaging performance. However, the complexity inherent in the physical propagation process poses significant challenges when the sample under study deviates from the weak scattering approximation. Such conditions complicate the task of achieving global optimization with conventional algorithms, rendering the reconstruction process both time-consuming and potentially ineffective. To address such limitations, this paper proposes an untrained multi-slice neural network(MSNN) with an optical structure, in which each layer has a clear corresponding physical meaning according to the beam propagation model. The network does not require pre-training and performs good generalization and can be recovered through the optimization of a set of intensity images. Concurrently, MSNN can calibrate the intensity of different illumination by learnable parameters, and the multiple backscattering effects have also been taken into consideration by integrating a "scattering attenuation layer" between adjacent "refractive index" layers in the MSNN. Both simulations and experiments have been conducted carefully to demonstrate the effectiveness and feasibility of the proposed method. Experimental results reveal that MSNN can enhance clarity with increased efficiency in RI tomography. The implementation of MSNN introduces a novel paradigm for RI tomography.
Delong Yang, Shaohui Zhang, Yao Hu, Qun Hao
2023-06-11T01:51:37Z
http://arxiv.org/abs/2306.06558v1
# Refractive index tomography with a physics based optical neural network ###### Abstract The non-interference three-dimensional refractive index(RI) tomography has attracted extensive attention in the life science field for its simple system implementation and robust imaging performance. However, the complexity inherent in the physical propagation process poses significant challenges when the sample under study deviates from the weak scattering approximation. Such conditions complicate the task of achieving global optimization with conventional algorithms, rendering the reconstruction process both time-consuming and potentially ineffective. To address such limitations, this paper proposes an untrained multi-slice neural network(MSNN) with an optical structure, in which each layer has a clear corresponding physical meaning according to the beam propagation model. The network does not require pre-training and performs good generalization and can be recovered through the optimization of a set of intensity images. Concurrently, MSNN can calibrate the intensity of different illumination by learnable parameters, and the multiple backscattering effects have also been taken into consideration by integrating a "scattering attenuation layer" between adjacent "refractive index" layers in the MSNN. Both simulations and experiments have been conducted carefully to demonstrate the effectiveness and feasibility of the proposed method. Experimental results reveal that MSNN can enhance clarity with increased efficiency in RI tomography. The implementation of MSNN introduces a novel paradigm for RI tomography. ## 1 Introduction Remarkable three-dimensional(3D) visualization of biological processes is of paramount importance for biological research. This is particularly challenging due to the transparent or semi-transparent characteristics of numerous biological cells. Direct microscopic observation often results in a low imaging contrast, missing much information. For improving the imaging contrast and signal-to-noise ratio(SNR) of 3D distributed bio-samples, fluorescence microscopy is one of the most widespread solutions [1, 2, 3, 4], and has inspired several representative super-resolution methods, such as Super-resolution microscopy(STED) [5, 6], Stochastic optical reconstruction microscopy(STORM) [7, 8], Photoactivation localization microscopy(PALM) [9], et al. Combined with necessary mechanical position scanning techniques, confocal designs [10], multi-photon microscopy [11] and light sheet microscopy [12] can be implemented, fluorescence microscopy enables the achievement of high-resolution 3D imaging of typical biological samples, with both high signal-to-noise ratio(SNR) and spatial resolution. Nevertheless, fluorescence microscopy necessitates exogenous labeling. And since some cellular characteristics or structures may not be detectable using fluorescence, it is unable to probe the total internal structure of biological samples. Unlike fluorescent labeling methods, phase imaging by measuring the change in the optical path difference of light is another approach that can effectively observe the structure information of transparent and semi-transparent samples. Combining with angularly-resolved measurements and tomography reconstruction algorithms, 3D refractive index(RI) imaging can be achieved, termed optical projection tomography [13, 14, 15]. Although optical tomography can produce high-quality 3D images, the interferometry-based method for obtaining phase distribution under each angular projection is highly sensitive to environmental conditions and prone to speckle noise. Therefore the corresponding system construction cost is high, and the system is less robust. Besides interferometry, phase retrieval with intensity images utilizing optimization algorithms is also a widely used phase imaging technique. Such methods are not affected by laser speckle noise and are robust to environmental disturbances, so the implementation and operation costs of the systems are also relatively low. Nevertheless, phase imaging from intensity images is not trouble-free. The ability of an optimization algorithm to find a satisfactory global solution depends on the inverse problem's complexity, the physical constraints used, and the chosen initial value. RI tomography from intensity images, referred to as intensity diffractive tomography(IDT) [16, 17, 18, 19, 20, 21], is a complex inverse problem involving a large number of unknown parameters and complex multiple scattering physical processes. Conventional IDT approaches, whether they utilize the multi-slice model in the space domain or Ewald's diffractive sphere model in the Fourier domain, have the problems of being seriously time-consuming, slow convergence, and easy to fall into local minima traps [23]. In recent years, many researchers have been actively exploring appropriate deep-learning methods to achieve better performance in computational imaging including tomography. While deep learning has been demonstrated to improve the speed and quality of tomography across various modalities [24, 25, 26, 27, 28, 29], conventional deep learning approaches remain unsuitable for certain measurement applications, especially RI tomography of biological samples. Since the conventional deep learning methods are mostly data-driven schemes, the inferential capabilities of the convolution neural networks(CNNs) are from the "experience" gleaned from huge datasets [30, 31, 32]. However, constructing a comprehensive dataset for biological tomography remains a significant challenge. Although a physics-based simulator has been proposed to generate training datasets for CNNs in biological tomography, the results are still limited by the mismatch between simulation and experimental data. [33]. Moreover, the accuracy of results from conventional CNNs, when applied to completely novel samples, remains questionable. [34, 35]. To address the aforementioned challenges, researchers have proposed the use of neural networks, integrated with physical models, to enhance the accuracy of imaging. In 2020, Horstmeyer Roarke proposed the deep prior diffraction tomography [16] which employs neural networks as the phase retrieval algorithm and uses a light scattering model as the physical verification to improve the authenticity of the imaging. Guohai Situ practiced a similar scheme in coherent diffraction imaging [37] in the same year. In 2022, Ulugbek S. Kamilov proposed the deep continuous artefact-free RI field, which uses the neural field network to implement phase retrieval. The sparse representation capability of neural field networks significantly reduces memory usage and addresses the issue of missing cones in intensity diffraction tomography [38]. However, these physics-based methods still employ conventional neural network structures as inverse operation networks. The optimization process essentially involves searching for the optimal inverse problem model within the vast parameter space of CNNs, a process that remains time-consuming. In this work, we remodel the structure of conventional neural networks [39] to incorporate both the beam propagation model and the scattering model, as opposed to solely relying on conventional architectures. The beam propagation method [40, 41, 42], dividing the RI of the sample into layers, is adapted within the structure of our neural network [43, 44, 45]. The beam propagation model imposes constraints on the backward gradient and helps verify the authenticity of the imaging results. The neural network we propose, which incorporates an optical structure, is designated as the multi-slice neural network(MSNN). To enhance imaging quality, we incorporate dark field raw data into the optimization [46]. We extend the MSNN connection for learnable parameters [47] to calibrate the intensity between different LEDs, reducing the requirements for acquisition hardware and the need for image preprocessing. The exceptional fitting capability of MSNN even offers the potential to take the higher-order scattering within the sample into phase retrieval. We take into account the backscattering field as predicted by the scattering model. The multiple backscattering effects have also been taken into consideration by integrating a "scattering attenuation layer" between adjacent "refractive index" layers in the MSNN. This approach ensures that our network architecture more accurately mirrors the actual process of light field propagation within the sample. We demonstrate that the implementation of adaptive recovery of backscatter intensity using MSNN during C. elegans imaging can enhance the quality of the images. ## 2 method ### The principle of the multi-slice neural network(MSNN) Multi-slice beam propagation method separates 3D objects into a series of thin layers, where the light wave through the sample is modeled by sequential layer-to-layer propagation of the light field. The structure of the beam propagation model is very similar to the hierarchical structure of the Deep Neural Networks(DNNs). And there are many optimizers [48] for DNNs to quickly converge to the global optimum. In MSNN, We model the \(m\)th layer of the 3D object as \(L_{m}(r)=n(r,m\Delta z)-n_{media}\). Mathematically, the diffraction propagation in MSNN can be recursively written as: \[P(r,\Delta z)=exp(j2\pi\Delta z(\frac{n_{media}}{\lambda}^{2}- \|u\|^{2})^{1/2}) \tag{1}\] \[t_{m}(r,\Delta z)=exp(j2\pi\Delta z\frac{n(r,m\Delta z)-n_{ media}}{\lambda})\] (2) \[U_{m+1}(r)=t_{m}(r,\Delta z)\cdot\mathscr{F}^{-1}\{P(r,\Delta z )\cdot\mathscr{F}\{U_{m}(r)\}\} \tag{3}\] where \(P(r,\Delta z)\) denotes the angular spectrum diffraction equation that propagates a light field by distance \(\Delta z,r\) denotes the 2D spatial position vector, \(u\) denotes the 2D spatial frequency space coordinates vector, \(t_{m}(r,\Delta z)\) denotes the phase modulation by the \(m\)th layer, \(U_{m}\) and \(U_{m+1}\) are the input and output light field of \(m\)th layer in MSNN. The boundary condition to initialize the recursively Eq.(3) is the incident plane wave illuminating the sample, \(U_{0}(r)=exp(jk_{illu}r)\) where \(k_{illu}\) is the illumination wave vector at a particular angle. The experiment system and the principle of MSNN are shown in Fig.8. Simultaneously, based on the 1st Born approximation, the scattering model that suggests the light field through the 3D sample including the incident field and scattered field stimulated by the 3D scattering potential \(V(r,z)=k_{0}^{2}(n_{media}^{2}-n^{2}(r,z))\). The total light field through the 3D sample can be expressed as: Figure 1: The principle of MSNN. (a)The optical system of the RI tomography. (b)The beam propogation model with estimate of backscattering. The lighting mode can be selected array lighting or spiral lighting. The bright-field and dark-field images are simulation captured images of a cell phantom.(c)The backscattering of different layers in the sample is predicted in MSNN with Learnable Intensity Attenuation Coefficient(LIAC). The inconsistency in intensity of various incident plane waves is corrected by Learnable Intensity Compensation Coefficient(LICC) in MSNN. (d)The structure of multi-slice neural network(MSNN). After the optimization, we will extract the internal parameters of the neural network as the RI reconstruction results of the sample. (e)The reconstruction result of the head of a C.elegan. The image is a two-dimensional projection of the reconstruction result on the x-y plane. \[U_{total}(r,z)=U_{in}(r,z)+U_{s}^{(born)}(r,z) \tag{4}\] \[U_{in}(r,z)=\mathscr{F}^{-1}\{P(r,\Delta z)\cdot\mathscr{F}\{U_{ in}(r,z-\Delta z)\}\}\] (5) \[U_{s}^{(born)}(r,z)=\iiint G(r-r^{\prime},\Delta z)U_{in}(r^{ \prime},z-\Delta z)V(r^{\prime},z)d^{3}r^{\prime} \tag{6}\] \(U_{s}^{(born)}(r,z)\) denotes the scattered field under the 1st Born approximation. The beam propagation model and the 1st Born approximation scattering model both consider the propagation of the input field according to the angular spectrum diffraction method, but they are different in the prediction of the scattering field. And the previous work has verified that both models are effective for 3D imaging of weakly scattered thick samples [41, 49]. In scattering model, Eq.(6) suggests that the superposition field of spherical waves computed by the Green function is actually the total scattering field including the forward scattering field and backscattering field, and we proved that when the layer is thin enough, the forward field and backscattering field can be approximate have same distribution in phase but different in intensity(Supplementary 2). We transferred the conclusion to the beam propagation model and got better imaging results in the experiments. So we still employ the beam propagation model to predict the backscattering field and attenuate the incident field in the layer of the forward propagation in MSNN, we set learnable parameters \(\omega_{m}\) to predict the intensity of backscattering field to attenuate forward field, the parameters \(\omega_{m}\) which we called Learnable Intensity Attenuation Coefficient(LIAC) are optimized by MSNN. The forward propagation in MSNN can be expressed as: \[U_{m+1}(r)=t_{m}(r,\Delta z)\cdot\mathscr{F}^{-1}\{P(r,\Delta z)\cdot\mathscr{ F}\{U_{m}\}\}/\omega_{m} \tag{7}\] The exit electric-field, \(U_{M}(r)\), accounts for the light field passing through the sample. When the imaging system is focus at the center of the sample, we need to refocus the exit light field \(U_{M}(r)\) to the center of the sample, where \(M\) denotes the total layers of the model. The final light field and intensity distributions at the image plane are: \[U_{predict}(r)=U_{M}(r)\mathscr{F}^{-1}\{C(u,k_{0})\cdot P(r,- \frac{M\Delta z}{2})\cdot\mathscr{F}\{U_{M}\}\} \tag{8}\] \[I_{predict}(r)=|U_{predict}(r)|^{2} \tag{9}\] where \(C(u,k_{0})\) denotes the coherent transfer function of the system. The light field captured by the objective \(U_{predict}(r)\) accounts for the accumulation of the diffraction and multiple-scattering processes(including the backscattering) that occurred during optical propagation through the \((-\frac{M\Delta z}{2},\frac{M\Delta z}{2})\) around the focal plane. ### Adaptive intensity calibration between different input fields in MSNN In practical experiments, to enhance lateral and axial resolution and improve the success rate of 3D imaging, we need to provide plane waves \(k_{i}\) from various angles. When \(k_{i}>NA_{obj}\), the camera captures dark-field images which require longer exposure times to enhance the signal-to-noise ratio. During the image capture process, we set distinct exposure times for different illumination angles. However, the relationship between exposure time length and sensor responsiveness is not strictly linear. Despite raw data preprocessing according to exposure times, this discrepancy could potentially introduce complications in solving the inverse problem. ``` 1Input:The illuminate \(k_{illu}\) of \(N\) LEDs, \(M\) layers of imaging axial size \(M\Delta z\). 2Data:Measured intensities \(\{I^{n}_{measure}(r)\}_{n=1}^{N}\). 3Hyperparameters:The parameters of the microscope system, the step size of optimization \(\alpha\), the TV regularization coefficient \(\beta\), the learning rate of **LIAC**\(\omega_{m}\) and **LICC**\(\gamma_{n}\), max number of iteration \(I\) 4Initialization:The RI in the layer of MSNN \(\{L_{m}(r)\}_{m=1}^{M}=0\). 5Return:3D RI of the sample. 6for\(i=1:I\)do 7for\(n=1:N\)do 8\(k_{illu}=k_{n}\), \(I_{gt}(r)=I^{n}_{measure}(r)\) 9\(U_{0}(r)=\gamma_{n}\cdot exp(jk_{illu}r)\) 10for\(m=1:M\)do 11\(L_{m}(r)\leftarrow\) mth layer of MSNN 12\(t_{m}(r,\Delta z)\gets exp(j2\pi\Delta z\frac{L_{m}(r)}{\lambda})\) 13\(U_{m+1}(r)\gets t_{m}(r,\Delta z)\cdot\mathscr{F}^{-1}\{P(r,\Delta z) \cdot\mathscr{F}\{U_{m}(r)\}\}/\omega_{m}\) 14 end for 15\(I_{predict}(r)\leftarrow|U_{M}(r)\mathscr{F}^{-1}\{C(u,k_{0})\cdot P(r,-\frac{ M\Delta z}{2})\cdot\mathscr{F}\{U_{M}\}\}|\) 16\(Loss\gets L_{1}(I_{predict}(r),I_{gt}(r))\) 17\(Loss.autograd().backward()\) by optimizer \(Adam(\alpha)\) 18 end for 19\(RI\leftarrow\) layers of MSNN 20\(RI_{reg}\gets TV_{3D}(RI,\beta)\) 21MSNN \(\gets RI_{reg}\) ``` **Algorithm 1**3D Intensity-based RI imaging with MSNN Furthermore, due to limitations in the accuracy of the experimental system, the intensity of the high-order diffracted input light field(provides illumination for darkfield) - which is used as an initial condition of MSNN - may be inaccurate. To address discrepancies in the response gray value in raw data caused by varying sensor exposure time settings at different illumination angles, and to compensate for the intensity of higher-order diffracted light, we introduce learnable parameters \(\gamma_{n}\) for each illumination angle. Consequently, the incident wave can be expressed as follows: \[U_{0}^{n}(r)=\gamma_{n}\cdot exp(jk_{illu}r) \tag{10}\] We define \(\gamma_{n}\) as the Learnable Intensity Compensation Coefficient(LICC) for the nth incident plane wave. In our model, LEDs in different positions each have independent coefficients. These coefficients can be learned and optimized within the Multi-Slice Neural Network(MSNN) during imaging. Consequently, the MSNN identifies the optimal set of LLCCs \((\gamma_{1}...,\gamma_{n}...,\gamma_{N})\) for the LEDs, thereby enhancing the 3D imaging process. ### RI tomography with MSNN MSNN is employed to solve the following optimization with an objective consisting of a measurement loss \(\mathcal{L}\) and regularizer \(\mathscr{R}\): \[argmin\{\mathcal{L}(MSNN(k_{i}llu),I_{gt}(r))+\beta\cdot\mathscr{R}(MSNN)\} \tag{11}\] where \(\mathcal{L}\) denotes the L1 loss. \(\mathscr{R}\) denotes the regularization term. We use the 3D total variation(TV) norm as the regularization loss within the MSNN. The parameter \(\beta\) is manually adjusted to optimize the strength of the regularization, with a larger punishment in the axial direction typically yielding better results. For the MSNN updates, we employ the Adam optimizer [50], which adaptively adjusts the learning rate based on raw data. This process for 3D Intensity-based RI imaging with MSNN is summarized in Algorithm 1. ``` 1Input:The illuminate \(k_{illu}\) of \(N\) LEDs, \(M\) layers of imaging axial size \(M\Delta z\). 2Data:Measured intensities \(\{I^{n}_{measure}(r)\}_{n=1}^{N}\). 3Hyperparameters:The parameters of the microscope system, the step size of optimization \(\alpha\), the TV regularization coefficient \(\beta\), the learning rate of **LIAC**\(\omega_{m}\) and **LICC**\(\gamma_{n}\), max number of iteration \(I\) 4Initialization:The RI in the layer of MSNN \(\{L_{m}(r)\}_{m=1}^{M}=0\). 5Return:3D RI of the sample. 6for\(i=1:I\)do 7for\(n=1:N\)do 8\(k_{illu}=k_{n}\), \(I_{gt}(r)=I^{n}_{measure}(r)\) 9\(U_{0}(r)=\gamma_{n}\cdot exp(jk_{illu}r)\) 10for\(m=1:M\)do 11\(L_{m}(r)\leftarrow\) mth layer of MSNN 12\(t_{m}(r,\Delta z)\gets exp(j2\pi\Delta z\frac{L_{m}(r)}{\lambda})\) 13\(U_{m+1}(r)\gets t_{m}(r,\Delta z)\cdot\mathscr{F}^{-1}\{P(r,\Delta z)\cdot \mathscr{F}\{U_{m}(r)\}\}/\omega_{m}\) 14 end for 15\(I_{predict}(r)\leftarrow|U_{M}(r)\mathscr{F}^{-1}\{C(u,k_{0})\cdot P(r,-\frac{ M\Delta z}{2})\cdot\mathscr{F}\{U_{M}\}\}|\) 16\(Loss\gets L_{1}(I_{predict}(r),I_{gt}(r))\) 17\(Loss.autograd().backward()\) by optimizer \(Adam(\alpha)\) 18 end for 19\(RI\leftarrow\) layers of MSNN 20\(RI_{reg}\gets TV_{3D}(RI,\beta)\) 21MSNN \(\gets RI_{reg}\) ``` **Algorithm 2**3D Intensity-based RI imaging with MSNN ## 3 Simulations To assess its capability for quantitative 3D RI reconstruction, we initially create a pure phase phantom composed of microspheres of varying radius. These microspheres have a RI of 1.59, while the medium has an RI of 1.56. The ideal microspheres, with diameters ranging from 1 to 4 \(\upmu\)m and an RI of 1.59, are immersed in a medium matching the RI of 1.56. The numerical aperture(NA) of both the objective(Magnification 40X) and the illumination in the simulation is 0.7. We sequentially illuminate angle-varied plane waves, with a center wavelength of 532 nm, through the sample and generate 225 captured intensity images. Each image contains \(100\times 100\) pixels, with a sensor pixel size of 4\(\upmu\)m. Figure 2 shows the 3D imaging results of the microspheres, with MSNN producing a satisfactory quantitative 3D RI. However, larger radius microspheres demonstrate larger axial artifacts, attributable to the problem of low-frequency missing cones in the frequency domain(detailed in Supplementary 1). Subsequently, we create a synthetic cell phantom containing intricate details for 3D RI recovery, with an RI that ranges from 1.33 to 1.38. Figure 3 depicts the imaging results of the cell phantom by MSNN, using 225 measurements. Even though it is subjected to the missing cone problem and compromises axial resolution for low spatial frequencies, MSNN manages to reconstruct a satisfactory quantitative 3D RI. Simulation was performed with PyTorch running on a desktop computer equipped with Intel(R) Core(TM) i5-10500 CPU at 4GHz 32GB RAM CPU and NVIDIA's GeForce GTX 3090 GPU. The total imaging time to complete 10 iterations for a volume of 100\(\times\)100\(\times\)100 voxels was 40 seconds. ## 4 Quantitative verification ### System setup To demonstrate the improvement of MSNN, we use a two-slice test sample consisting of two resolution targets, one placed above the focal plane and the other axially spaced apart and rotated relative to the first one. We build a microscope system as shown in Fig.8 with a 4x objective(NA\(\approx\)0.1). We use a LED array(15\(\times\)15) for varied-angle illuminations. The LED array is located 100mm from the sample plane and emits a light with a wavelength of 473nm and a bandwidth of 20nm. The LED array is controlled by an stm32 microcontroller and is synchronized with the camera to scan through the LEDs at camera-limited speeds. Our camera is capable of 50 frames per second at full frame(2448\(\times\)2048 pixels, Figure 2: The reconstruction results for 4 microspheres of varying sizes (a)This panel depicts the 3D ground truth of the microspheres, with radius of 4um, 3um, 2um and 1um. (b)The 3D reconstruction results of the microspheres. (c)The reconstructions at depths of 1um, 2um, 3um and 4um in both the x-y and y-z planes. pixel size 3.45um) and with 8-bit data. However, for dark-field images, we opt for longer exposure times. The raw data, constrained to a small 360x360 pixel resolution region, is used to recover a high-resolution complex field with a 4X increase in pixel quantity. The computing platform is aligned with the simulation. The total imaging time to complete 50 iterations of a 720\(\times\)720\(\times\)2 voxels volume was 1 minutes. ### Experiment results The low-resolution raw images captured consist of 9 brightfield and 216 darkfield images. Since the USAFchart serves as an intensity modulation sample, we employ a complex RI matrix to represent the object. The imaginary parts of the complex RI sections, representing the absorption of the light field at different depths within the sample, are shown in Fig.4(d). MSNN successfully isolates the intensity modulation information at various depths from the raw data. However, without the LICC, MSNN fails to achieve the theoretical lateral resolution even after 500 optimization iterations, and the imaging quality across depth sections is unsatisfactory. The compromised quality also suggests the presence of system deviations, such as pupil aberration, illumination deviation, and exposure time differences [51, 52]. When using the LICC, we manage to reconstruct the sample at an enhanced resolution in as few as 50 iterations. With extended optimization, the lateral resolution improves steadily. However, our experiments show that the optimal learning rate for LICC varies across training iterations. As shown in Fig.4(c), sudden drops in loss occur at marked positions within different loss curves, resulting in a degradation of imaging. Therefore, it's necessary to halt optimization early by observing the loss trend. The early stop point loss within the different curves further supports the notion that LICC improves imaging quality. ### Analysis of resolution The LED array provides various illumination angles to improve the lateral resolution [53, 54]. As expected, the lateral bandwidth \(\Delta fx\) is determined by the sum of objective \(NA(NA_{obj})\) and illuminate \(NA(NA_{illu})\): \[\Delta fx=\frac{2(NA_{obj}+NA_{illu})}{\lambda} \tag{12}\] The axial resolution, however, does not follow this trend. Its bandwidth, \(\Delta fx\), is neither that of the objective nor is it that would result from using an objective having the sum of the two NA. Instead, it is somewhere in between the NA of the objective and the sum of two NAs(\(NA_{obj}andNA_{illu}\)), and can be estimated with a formula: \[\Delta fz=\frac{2-\sqrt{1-NA_{obj}^{2}}-\sqrt{1-NA_{illu}^{2}}}{\lambda} \tag{13}\] Figure 3: The middle slice of x-y,x-z,y-z plane of the ground truth and imaging with MSNN. And the 3D projection views in a tilt angle are present. Nonetheless, the calculated result using this formula represents the maximum axial resolution achievable across various lateral resolutions. The 3D Fourier diffraction theorem [55] suggests the lateral resolution and axial resolution in the Fourier Ptychography system for RI tomography are not independent [56]. We propose a digital simulation method for more accurate analysis of axial resolution in microscopy systems(details in Supplementary 1). In the USAFchart illuminated by our system, the 5-3 line has 44um theoretical maximum axial resolution, and the 4-3 line pair has 70um theoretical maximum axial resolution. In the green ROI of Fig.4, the information regarding the separation of the 4-3 line pairs at an axial distance of 100um is distinct in different depth sections. In order to further analyze the difference between the axial resolution of our system and the theoretical limit, we narrowed the distance of USAFchart for further experiments(details in Supplementary 1). ## 5 Experimental of biological sample ### System setup The raw data of C.elegan were obtained from Laura Waller's Computational Imaging Lab at UC Berkeley [41]. Since the diameter of C.elegans usually does not exceed 30um, high-NA microscope objectives are used for high axial resolution. Consequently, all acquired images are brightfield images, and the raw data were applied HDR combined to calibrate the intensity between different illumination. Therefore, we do not use LICC for adaptive intensity calibration. Simultaneously, we divide the imaging depth of 24um or 30um into 121 layers, where the impact of backscattering Figure 4: Absorption imaging of a two-slice sample consisting of two resolution targets placed at different depths (-50 and 50 μm), with one rotated laterally with respect to the other. (a)Low-resolution full FoV image from 4\(\times\) 0.1NA objective. (b)The imaging for 5-3(12.41um) and 4-3(24.80um) in two slice. (c)The loss curve for different learning rates of light calibration. The overfittings during the optimization are labeled, and the training should be stopped before the overfitting. (d)The captured raw data and the reconstructed results with different learning rates of LICC becomes more pronounced. So we employ LIAC to estimate the attenuation of the forward propagation field caused by backscattering. The computing platform is aligned with the simulation. The total imaging time to complete 50 iterations of a 1200\(\times\)1200\(\times\)121 voxels volume was 3 hours. ### Experiment results The captured raw data includes 120 images with illumination angles scanned on a spiral trajectory. Our biological experiment generates a high-resolution RI tomography of an adult C.elegans worm's head region(1200\(\times\)1200\(\times\)60 voxels), with voxel size 0.12\(\times\)0.12\(\times\)0.5\(\upmu m^{3}\).We note that 8-20 iterations are sufficient for visualizing the C.elegan's 3D tomographic structure, taking 25-70 minutes(Visualization 1). MSNN can balance the time required with the quality of 3D imaging. Additionally, as we can utilize various propagation models by substituting the connections within the layers in MSNN, we also conducted experiments for applying the multi-layer Born model [49] in MSNN framework(Supplementary 2). To quantitatively visualize the worm's 3D biological RI, we present RBG-colored cross-sectional images of all ROIs at various axial and lateral positions. In Fig.5(a1)-(a3), we show two lateral slices through reconstruction volume at the axial position of z=-7, -0.5, +5um. The digestive system including the mouth, pharynx, and pharyngeal lumen, are identified. Behind the pharynx, we can observe the nematode's intestinal lumen, which contains many microsphere-like details. Fig.5(a6) and (a7) show the axial cross-section of the pharyngeal lumen and pharynx, respectively. In Fig.5(b1)-(b4), the lateral slice clearly show the pharyngeal lumen, pharynx,and other micron-sized structure at different axial Figure 5: RI tomography of a C.elegan worm’s head. (a1)-(a3) Lateral slices through the 3D imaging volume at various axial positions. Major components of the digestive system are labeled. (a4)-(a5)The captured raw data illuminate by the positive incidence. Axial slice through the pharynx (a6), and axial slice through the pharyngeal lumen (a7) are shown. (b1)-(b4),(c1)-(c4) Lateral slices of the ROIs 1�1�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�2�1�21�2�1�2�1�2�1�21�2�1�2�1�21�2�1�2�1�21�2�1�21�2�1�21�21��21�21��21�21��21�21��21�21��21�21��21��21�21��21��21�21��21��21�21��21��21�21��21��21��21��21��21���212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212212121212121212121212121212121212121212121212121212121212121212121212121212121212122121212121212121212121212121212121212121212121212122121212121212121212121212121212122121212121212121212121212121221212121212121212121212121212212121212121212212121212121212121221212121212121212121212121212121212121212121212121212121212121221212121212121212122121212121221212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121221212121212121212121221212122122122122121212121222121212212122212121221212122122122212221221221222122122221222212 position. We can also see the phenomenon of C.elegan feeding in Fig.5(c1)-(c4). The microspheres in front of the mouth of C.elegan are E.coli bacteria, a food source for the worm(3D RI Tomography results in Visualization 2). Since the 3D RI of samples are separated into many slices, even for weakly scattered samples, backscattering at such long axial distances is still not negligible, so we conducted comparative experiments with and without LIAC. The results are shown in Fig.5(b5)-(b8) and (c5)-(c8). As observed, the results with LIAC demonstrate enhanced clarity and higher contrast. During optimization, the implementation of LIAC also resulted in a smaller L1 loss compared to raw data(Supplementary 2). Fig.5(d1)-(d4) and Fig.5(e1)-(e4) show 3D visualizations from various viewing angles. To emphasize the 3D structure, we have obscured parts with an RI of less than 1.33. Usually, visualizing this morphology requires cross-sectional slicing and viewing by electron microscopy. We demonstrate that we can achieve non-invasive imaging to obtain 3D microscopic structures(Visualization 3). ## 6 Discussion and Conclusion An untrained physical based network termd as MSNN is proposed and demonstrated in this paper. It is an implementation of the paradigm of remodeling neural networks with optical principles. The scalability of MSNN provides a way to solve the constraints for RI tomography. To enhance the clarity of RI tomography, darkfield images information is also very important. The implement of LICC can effectively calibrate the intensity between brightfield and darkfield, further, LICC can calibrate the intensity between different positions when using various LEDs(light sources) as illumination, the application of LICC has the ability to reduce hardware requirements and the need for preprocessing of raw data in RI tomography. Furthermore, due to the complexity of multiple scattering, RI tomography is often limited to imaging samples with weak backscatter under the 1st Born or Rytov approximation. In the future, replacing the backscatter intensity estimation LIAC with a more accurate optical model may enable MSNN to account for higher-order scattering processes, showing promise in reconstructing samples with a broader RI range or extended axial distances. In this paper, we have introduced MSNN, a neural network for efficient and accurate RI tomography. Compared to the widely used conventional deep learning methods, MSNN reconfigures the conventional CNN with the physical beam propagation model to confirm the authenticity of the 3D RI information. Moreover, it accelerates RI tomography compared to CNNs that employ physical method verification. MSNN introduces a novel paradigm for RI tomography, enabling to image biological samples(C.elegans) that are both thicker and exhibit higher scattering properties than were achievable with earlier methods. The implementation of LICC and LIAC also improved the robustness and imaging clarity and present its scalability. We provide link to datasets and an open-source implementation of MSNN at GitHub repository available at [https://github.com/yang980130/Physics-based-3D-tomography-Multi-slice-neural-network](https://github.com/yang980130/Physics-based-3D-tomography-Multi-slice-neural-network). See also the Supplementary Material for supporting content. ## 7 Refractive index tomography with a physics based optical neural network: supplemental document 1 This document provides supplementary information to "Refractive index tomography with a physics based optical neural network". It first elucidates the concept of the Ewald sphere used in analyzing axial resolution. Following this, it establishes the axial resolutions corresponding to various lateral resolutions, based on the parameters derived from the actual system. To validate the congruence between the experiment of multi-slice neural network(MSNN) and the theoretical in axial resolution values, we used an microscope fitted with a 4x objective. We conducted a reconstruction of distinct depth slices, which were formed by a stacking of two USAF charts with a 50-micrometer gap. ### The formulation of Ewald sphere The three-dimensional Fourier diffraction theorem suggests the lateral resolution and axial resolution in the intensity diffractive tomography(IDT) system are not independent, but the structures in the biomedical sample with large lateral size usually have a large axial size, we usually ignored studying the relationship between the axial resolution and lateral resolution in our experiment system. To analyze both lateral resolution and axial resolution theoretically, we use the three dimensional(3D) coherent transfer function(CTF) of the imaging system. As illustrated in Fig.8(a), the 3D spatial frequency(k-space) is formed by the 3D Fourier transform of the object's refractive index(RI) [57, 58]. This spherical k-space representation, known as the Ewald sphere, has a radius determined by the wave vector \(k_{0}=\frac{2\pi}{\pi}\). By sequentially activating each light-emitting-diode(LED) at different positions on the LED array, which in turn provides plane waves \(k_{i}\) at varying angles, we can explore different regions of the k-space. As \(k_{i}\) changes with the illumination angle, the maximum probed k-space falls within a spherical shell with radius \(k_{0}\). The center of this shell shifts along a second spherical shell(of the same radius \(k_{0}\)) determined by the incident angle of the plane wave \(k_{i}\)(as depicted by the gray circle in Fig.8(a)). However, in actual experiment systems, The Fourier diffraction theorem suggests that, limited by illumination and microscopy, only partial spherical cap bounded by the generalized aperture can be probed. Illuminating the object at different angles will shift different regions of the object's k-space into a fixed microscope objective lens with fixed numerical aperture(NA). Ultimately, only a portion of the Ewald sphere can be reconstructed. [17, 20]. We employ matrices to digitally simulate the 3D CTF based on our system setup. The 3D k-space bandwidth in the x-z section(which is equivalent to the bandwidth in the y-z section) is depicted in Fig.8(b). From this, we can compute the theoretical axial resolution by assessing the k-space bandwidth of the x-z region. The results suggest that different lateral resolutions correspond to varying axial resolutions. This implies that the imaging quality for line pairs on a USAF chart will differ across the depth(z) section due to these resolution disparities. ### Analysis of axial resolution for the system of quantitative experiment Since the lines with the different lateral sizes in USAFchart have the same axial size, the stacked resolution targets provide a convenient way to experimentally characterize lateral resolution at multiple depths. At the same time, we can transform the various linewidth which represents various lateral resolutions into the spectrum and view the reconstruction of depth(z) section to analyze the axial resolutions. According to the axial bandwidth in Fig.8(b1) which uses sparse illumination, the maximum axial resolution is 9.6um in 1.9um lateral resolution(8-1 line pair). The 5-3 line pair with 12.41um in Fig.8(b) has 57um axial resolution, the 4-3 line pair with 24.8um in Fig.8(b) has 97um axial resolution. In dense illumination, the maximum axial resolution is 9.3um in 2um lateral resolution. The 5-3 line has 44um axial resolution, and the 4-3 line pair has 70um axial resolution. The difference between axial resolutions in low-resolution lines is mainly caused by numerical simulation errors(The numerical error can be reduced by expanding the matrix scale), but the analysis still can be used as a reference. The actual axial resolution should lie between the above two sets of data, taking into account the density of the illumination. To confirm whether the axial resolution of a 4-3 or 5-3 pair aligns with the theoretical analysis value, we present the reconstruction results of a pair of USAF charts, reconstructed by MSNN, with a placement spacing of 54 um. As observed in Fig.9, ROI(1) with smaller lateral sizes demonstrate better layering compared to ROI(2) and ROI(3), which have larger lateral sizes. And due to the axial bandwidth not being symmetrical, ROI(2) and ROI(3), which have the same lateral size, also exhibit different layering effects in planes at varying depths. Figure 6: Fourier diffraction theorem in finite-aperture optical systems. (a)The 3D sample is illuminated by plane waves from various angles. The forward scattering wave captured by the aperture of the objective with fixed NA. (b1)The bandpass on the Ewald sphere and the axial bandwidth in different lateral resolutions by the sparse illumination of (a). (b2)The bandpass on the Ewald sphere and the axial bandwidth in different lateral resolutions by the dense illumination Figure 7: Absorption reconstruction of a two-slice sample consisting of two resolution targets placed at different depths(-27 and 27 μm), with one rotated laterally with respect to the other. ## 8 Refractive index tomography with a physics based optical neural network: supplemental document 2 This document provides supplementary information to "Refractive index tomography with a physics based optical neural network". In this supplementary material, we elaborate on how to approximate backscattering between layers following the scattering principle. We present experimental comparisons of results produced by the multi-slice neural network(MSNN) with and without the use of adaptively adjusted backscatter(LIAC), specifically in scenarios without the employment of Total Variation(TV) regularization. Furthermore, we conducted the application of the multi-layer Born model within the MSNN framework. This supplementary concludes with a comparison between the imaging of the multi-layer Born model and beam propagation model both applied to the MSNN. ### The formulation of Ewald sphere In 3D RI imaging, modeling the multi-scattering of light field in the sample is highly challenging. The discrepancy between the model and the actual physical process will manifest as noise in the 3D RI results. So researchers usually use the scattering model with the 1st Born approximation or employ the beam propagation model [40, 41] for the prediction of the field in weakly scattered samples. However, even with these methods, only a partial prediction of the scattering field is possible. In the MSNN, we divide the 3D RI of samples into slices, assuming that each slice is thin enough to disregard the scattering within it. The scattering model suggests that the phases of the forward and backscattering fields are identical [49] when the slices are extremely thin: \[U_{s}^{(born)}(r,z) =\tilde{G}(u,\Delta z)\iint since(\daldal(u^{\prime})+\dal(u)) \Delta z)\tilde{U}_{n}(u^{\prime})\tilde{V}_{n}(u-u^{\prime})\Delta zd^{2}u^{\prime} \tag{14}\] \[U_{bs}^{(born)}(r,z) =\tilde{G}(u,\Delta z)\iint since(\dal(u^{\prime})-\dal(u)) \Delta z)\tilde{U}_{n}(u^{\prime})\tilde{V}_{n}(u-u^{\prime})\Delta zd^{2}u^{\prime}\] (15) \[\dal(u)=(\sqrt{\frac{n_{m}}{\lambda}-||u||^{2}}) \tag{16}\] where \(\Delta z\) is the thickness of the slice, allowing us to approximate the \(sinc\) function to one. By applying this conclusion to the beam propagation model, we can consider that the backscattering field attenuates the forward scattering field, although the intensity of this attenuation remains unknown. To make the beam propagation model more closely resemble the actual propagation of the light field, we employ LIAC to predict the intensity of the backscattering field and attenuate the forward scattering fields, thereby enhancing the RI image quality. To analyze the impact of LIAC on the RI image quality for samples, we used MSNN to optimize 200 iterations without applying TV regularization. The total imaging time to complete 200 iterations of a 420\(\times\)420\(\times\)60 voxels volume(The mouth of C.elegan) was 44 minutes. And the imaging results are shown in Fig.8. As observed, the loss curves indicate that the imaging results incorporating LIAC for predicted intensity align more closely with the captured raw data in the majority of iterations. Furthermore, the LIAC-enhanced results exhibit high-frequency noise which can be eliminated by many effective method, and we think that the high-frequency noise is caused by higher-order scattering fields. Imaging results without LIAC show more speckle-like noise, which would be difficult to remove, and we think that this noise is caused by not considering low-order scattering such as backscattering [59, 60]. ### The comparison of total field-of-view imaging with total variation regularization Considering the challenge of separating information and noise in the reconstructed image without regularization, we present the total field-of-view reconstructed image using TV regularization with or without LIAC. Furthermore, the MSNN allows for the easy exchange of field-propagation models by defining the connections between layers. We also employ the multi-layer Born model within the Deep Neural Network(MLB-NN) for imaging the sample [49], as described in the methodology chapter of the text. As shown in Fig.9, the imaging utilizing MLB-NN shows a similar RI distribution to MSNN, albeit with lower contrast, and the loss converges at a slower pace. With the same level of TV regularization applied, the reconstructed image using MSNN with LIAC exhibits a quicker convergence speed and superior image granularity in the lateral slices and axial slices, which may reveal more details(labeled in Fig.9) in the tomography.
2310.08287
A Symmetry-Aware Exploration of Bayesian Neural Network Posteriors
The distribution of the weights of modern deep neural networks (DNNs) - crucial for uncertainty quantification and robustness - is an eminently complex object due to its extremely high dimensionality. This paper proposes one of the first large-scale explorations of the posterior distribution of deep Bayesian Neural Networks (BNNs), expanding its study to real-world vision tasks and architectures. Specifically, we investigate the optimal approach for approximating the posterior, analyze the connection between posterior quality and uncertainty quantification, delve into the impact of modes on the posterior, and explore methods for visualizing the posterior. Moreover, we uncover weight-space symmetries as a critical aspect for understanding the posterior. To this extent, we develop an in-depth assessment of the impact of both permutation and scaling symmetries that tend to obfuscate the Bayesian posterior. While the first type of transformation is known for duplicating modes, we explore the relationship between the latter and L2 regularization, challenging previous misconceptions. Finally, to help the community improve our understanding of the Bayesian posterior, we will shortly release the first large-scale checkpoint dataset, including thousands of real-world models and our codes.
Olivier Laurent, Emanuel Aldea, Gianni Franchi
2023-10-12T12:45:13Z
http://arxiv.org/abs/2310.08287v1
# A Symmetry-Aware Exploration of Bayesian Neural Network Posteriors ###### Abstract The distribution of the weights of modern deep neural networks (DNNs) - crucial for uncertainty quantification and robustness - is an emimently complex object due to its extremely high dimensionality. This paper proposes one of the first large-scale explorations of the posterior distribution of deep Bayesian Neural Networks (BNNs), expanding its study to real-world vision tasks and architectures. Specifically, we investigate the optimal approach for approximating the posterior, analyze the connection between posterior quality and uncertainty quantification, delve into the impact of modes on the posterior, and explore methods for visualizing the posterior. Moreover, we uncover weight-space symmetries as a critical aspect for understanding the posterior. To this extent, we develop an in-depth assessment of the impact of both permutation and scaling symmetries that tend to obfuscate the Bayesian posterior. While the first type of transformation is known for duplicating modes, we explore the relationship between the latter and L2 regularization, challenging previous misconceptions. Finally, to help the community improve our understanding of the Bayesian posterior, we will release shortly the first large-scale checkpoint dataset, including thousands of real-world models, along with our codes. ## 1 Introduction Despite substantial advancements in deep learning, Deep Neural Networks (DNNs) remain black box models. Various studies have sought to explore DNN loss landscapes (Li et al., 2018; Fort and Jastrzebski, 2019; Fort and Scherlis, 2019; Liu et al., 2022) to achieve a deeper understanding of these models. Recent works have, for instance, unveiled the interconnection of the modes obtained with Stochastic Gradient Descent (SGD) via narrow pathways that link pairs of modes, or through tunnels that connect multiple modes simultaneously (Garipov et al., 2018; Draxler et al., 2018). This Figure 1: **Weight-space symmetries greatly impact the estimated Bayesian posterior**. Permutation symmetries very clearly increase the number of modes of the posterior distribution in the case of a 2-hidden neuron perceptron. mode connectivity primarily arises from scale and permutation invariances, which imply that numerous weights can represent the same exact function (e.g., Entezari et al. (2022)). Several studies have delved into the relationship between these symmetries and the characteristics of the loss landscape (Entezari et al., 2022; Neyshabur et al., 2015; Brea et al., 2019). Our work investigates the connections between these symmetries and the distribution of DNN weights, a crucial aspect for uncertainty quantification. As shown in Figure 1, it is apparent that these symmetries also exert influence on DNN posterior distributions. Uncertainty quantification plays a pivotal role in high-stakes industrial applications - such as autonomous driving (Levinson et al., 2011; McAllister et al., 2017; Sun et al., 2019) - where reliable predictions and informed decision-making are paramount. In such critical domains, understanding and effectively managing uncertainties, particularly the model-related epistemic uncertainties (Hora, 1996) arising from incomplete knowledge, is essential. Among the various methods proposed to address these challenges, Bayesian Neural Networks (BNNs) (Tishby et al., 1989) offer a principled and theoretically sound approach. BNNs quantify uncertainty by modeling our beliefs about parameters and outcomes probabilistically (Tishby et al., 1989; Hinton and Van Camp, 1993). However, this perspective faces significant hurdles when applied to deep learning, primarily related to scalability (Izmailov et al., 2021) and the precision of approximations (MacKay, 1995). Due to their very high dimension, BNNs struggle to estimate the posterior distribution, i.e., the probability density of converging towards any particular set of model parameters \(\omega\), given the observed data \(\mathcal{D}\). Diverging from methods such as the Maximum Likelihood Estimate or Maximum A Posteriori (also in Tishby et al. (1989)), which we typically derive through gradient descent optimization of cross-entropy (with L2 regularization for the latter), BNNs assign a probability to each possible model (or hypothesis) and offer predictions considering the full extent of possible models. In mathematical terms, when we denote the target as \(y\), the input vector as \(\mathbf{x}\), and the weight space as \(\Omega\), we can express this approach through the following intractable formula, often referred to as the marginalization on the parameters of the model (Tishby et al., 1989; Rasmussen et al., 2006): \[p(y\mid\mathbf{x},\mathcal{D})=\int\limits_{\mathbf{\omega}\in\Omega}p(y\mid\mathbf{x}, \mathbf{\omega})p(\mathbf{\omega}\mid\mathcal{D})d\mathbf{\omega}. \tag{1}\] The posterior distribution \(p(\mathbf{\omega}|\mathcal{D})\) assumes a central and arguably the most critical role in BNNs. Many successful methods for quantifying uncertainty can be viewed as attempts to approximate this posterior, each with its own trade-offs in terms of accuracy and computational efficiency, as illustrated in previous research (Blundell et al., 2015; Gal and Ghahramani, 2016; Lakshminarayanan et al., 2017). Prior work (Kuncheva and Whitaker, 2003; Fort et al., 2019; Ortega et al., 2022) has established the importance of achieving _diversity_ in the sampled DNNs drawn from the posterior, particularly when dealing with uncertain input data. However, the presence of permutation symmetries and scale symmetries among hidden units in neural networks may lead to an increased number of local minima (Zhao et al., 2023) with no diversity. In the context of BNNs, this phenomenon can result in a proliferation of modes within the posterior distribution. In this paper, we delve into the impact of weight symmetries on the posterior distribution. While there have been numerous efforts to visualize the loss landscape, we explore the possibility of conducting similar investigations for the posterior distribution. Additionally, we introduce a protocol for assessing the quality of posterior estimation and examine the relationship between posterior estimation and the accuracy of uncertainty quantification. Specifically, our contributions are as follows: **(1)** We build a new mathematical formalism to highlight the different impacts of the permutation and scaling symmetries on the posterior and on uncertainty estimation in deep neural networks. Notably, we explain the seeming equivalence of the marginals in Figure 1. We also perform the first in-depth exploration of the existence of scaling symmetries and their overlooked effect. **(2)** We evaluate the quality of various methods for estimating the posterior distribution on real-world applications using the Maximum Mean Discrepancy, offering a practical benchmark to assess their performance in capturing uncertainty. **(3)** We release a new dataset that includes the weights of thousands of models across various computer vision tasks and architectures, ranging from MNIST to TinyImageNet. This dataset is intended to facilitate further exploration and collaboration in the field of uncertainty in deep learning. **(4)** Our investigation delves into the proliferation of modes in the context of posterior symmetries and exhibits the capacity of ensembles to converge toward non-functionally equivalent modes. Furthermore, we discuss the influence of symmetries in the training process. Related work Epistemic uncertainty, Bayesian inference, and posteriorEpistemic uncertainty (Hora, 1996; Hullermeier & Waegeman, 2021) plays a crucial role in accurately assessing predictive model reliability. However, despite ongoing discussions, estimating this uncertainty remains a challenge. BNNs (Goan & Fookes, 2020) predominantly shape the landscape of methodologies that tackle epistemic uncertainties (Gawlikowski et al., 2023). Given the complexity of dealing with posterior distributions, these approaches have mostly been tailored for enhanced scalability. For instance, Hernandez-Lobato & Adams (2015) proposed an efficient probabilistic backpropagation, and Blundell et al. (2015) developed BNNs by Backpropagation to learn diagonal Gaussian distributions with the reparametrization trick. Similarly, Laplace methods (Laplace, 1774; MacKay, 1992; Ritter et al., 2018) characterize the posterior distribution of weights, often focusing on the final layer (Ober & Rasmussen, 2019; Watson et al., 2021), again for scalability. On a different approach, Monte Carlo Dropout, introduced by Gal & Ghahramani (2016) and Kingma et al. (2015), is a framework that models the posterior as a mixture of Dirac distributions when applied on fully-connected layers. Broadening the spectrum, Deep Ensembles (Lakshminarayanan et al., 2017), arguably along with their more efficient alternatives (Lee et al., 2015; Wen et al., 2019; Maddox et al., 2019; Franchi et al., 2020; Bavasai et al., 2021; Laurent et al., 2023), have been interpreted by Wilson & Izmailov (2020) as Monte Carlo estimates of Equation 1. Markov-chain-based Bayesian posterior estimationNeal et al. (2011) introduced HMC as an accurate method for estimating the posterior of neural networks, but its application to large-scale problems remains challenging due to the very high computational demands. Izmailov et al. (2021) managed to scale full-batch HMC to CIFAR-10 (Krizhevsky, 2009) with ResNet-20 (He et al., 2016) thanks to 512 TPUv3. In response to these challenges, stochastic approximations of MCMC have gained attention for their ability to provide computationally more feasible solutions. A prominent example is the Langevin dynamics-based approach proposed by Welling & Teh (2011). By introducing noise into the dynamics, Langevin dynamics allows for more practical implementation on large datasets. In addition to Langevin dynamics, other stochastic gradient-based methods have been introduced to improve the efficiency of MCMC sampling. Chen et al. (2014) presented Stochastic Gradient Hamiltonian Monte Carlo (SGHMC), integrating stochastic gradients into HMC. Likewise, Zhang et al. (2020) proposed C-SGLD and C-SGHMC (Cyclic Stochastic Gradient Langevin Dynamics and Hamiltonian Monte Carlo), introducing controlled noise via cyclic preconditioning. While stochastic approximation methods offer computational convenience, they come with the trade-off of slowing down the convergence and potentially introducing bias into the resulting inference (Bardenet et al., 2017; Zou & Gu, 2021). As such, the suitability of these approaches depends on the specific application and the level of acceptable bias in the analysis. Symmetries in neural networksThe seminal work from Hecht-Nielsen (1990) established a foundational understanding by investigating permutation symmetries and setting a lower bound on symmetries in multi-layer perceptrons. Albertini et al. (1993) extended this work and studied flip sign symmetries in networks with odd activation functions. This work was further generalized to a broader range of activation functions by Kurkova & Kainen (1994), who proposed symmetry removal to streamline evolutionary algorithms. Recent advancements have generalized symmetries to modern neural architectures. Neyshabur et al. (2015) explored the scaling symmetries that arise in architectures containing non-negative homogeneous activation functions, including Nair & Hinton (2010)'s ubiquitous Rectified Linear Unit (ReLU). This perspective extends our understanding of symmetries to ReLU-powered architectures, e.g., AlexNet (Krizhevsky et al., 2012), VGG (Simonyan & Zisserman, 2015), and ResNet networks (He et al., 2016). This paper focuses on scaling and permutation symmetries, but other works, such as Rolnick & Kording (2020); Grigsby et al. (2023), unveil less apparent symmetries. Closest to our work, Wiese et al. (2023) demonstrated that taking weight-space symmetries into account could reduce the Bayesian posterior support and improve Monte-Carlo Markov Chains posterior estimation. Symmetries increase the complexity of Bayesian posteriors We propose to study the most influential weight-space symmetries and their properties related to the Bayesian posterior. Firstly, weight-space symmetries transform the parameters of the neural networks while keeping the networks functionally invariant; in other words, **Definition 3.1**.: Let \(f_{\mathbf{\omega}}\) be a neural network of parameters \(\mathbf{\omega}\) taking \(n\)-dimensional vectors as inputs. We say that the transformation \(\mathcal{T}\) modifying \(\mathbf{\omega}\) is a weight-space symmetry operator, iff \[f_{\mathcal{T}(\mathbf{\omega})}=f_{\mathbf{\omega}},\text{ or }\forall\mathbf{x}\in \mathbb{R}^{n},f_{\mathcal{T}(\mathbf{\omega})}(\mathbf{x})=f_{\mathbf{\omega}}(\mathbf{x}). \tag{2}\] With the notation \(f_{\mathcal{T}(\mathbf{\omega})}(\mathbf{x})\), we apply the symmetry operator \(\mathcal{T}\) on the weights \(\mathbf{\omega}\), resulting in a set of modified weights. In this paper, we show that scaling and permutation symmetries have different impacts on the posterior of neural networks. They can, for instance, complicate Bayesian posteriors, creating artificial functionally equivalent modes. ### A gentle example of artificial symmetry-based posterior modes To illustrate the considerable impact of symmetries on the Bayesian posterior, we propose a small-scale example in Figure 1. We generate this example by training two-hidden-neuron perceptrons on linearly separable data. Figure 1 presents the estimation of the posterior of the output weights with 10,000 checkpoints. In this figure, the most important mode is duplicated due to the permutation symmetry, which appears to symmetrize the graph. On the other hand, scaling symmetries seem to regroup some points around the modes. We detail this toy experiment in Appendix A. In the following, we develop a new mathematical framework tailored to help understand the impact of these symmetries on the posterior, devise mathematical insights explaining these intuitions, and propose empirical explorations. ### Background and definitions The full extent of this formalism (including sketches of proofs, other definitions, properties, and propositions) is developed in Appendix C. We deem that the following properties are the minimal information necessary to understand the impact on the Bayesian posterior of the two main types of symmetries: the scaling and permutation symmetries. This part summarizes the most important results for multi-layer perceptrons, but we provide leads for generalizing our results to modern deep neural networks such as convolutional residual networks (He et al., 2016) in Appendix D.4. ### Scaling symmetries For clarity, we propose the following definitions and properties for two-layer fully connected perceptrons without loss of generality. Please refer to Appendix C and D.4 for extensions. We start with two new operators between vectors and matrices to define scaling symmetries. **Definition 3.2**.: We denote the line-wise product as \(\bigtriangledown\) and the column-wise product as \(\rhd\). Let \(\mathbf{\omega}\in\mathbb{R}^{n\times m}\), \(\mathbf{\lambda}\in\mathbb{R}^{m}\), and \(\mathbf{\mu}\in\mathbb{R}^{n}\), with \(n,m\geq 1\), \[\forall i\in\llbracket 1,n\rrbracket,\forall j\in\llbracket 1,m\rrbracket, \ (\mathbf{\lambda}\bigtriangledown\mathbf{\omega})_{i,j}=\lambda_{j}\omega_{i,j}\text{ and }(\mathbf{\mu}\rhd\mathbf{\omega})_{i,j}=\mu_{i}\omega_{i,j}. \tag{3}\] Given that the rectified linear unit \(r\) is non-negative homogeneous - i.e., for all non-negative \(\lambda\), \(r(\lambda x)=\lambda r(x)\) - we have the following core property for scaling symmetries (Neyshabur et al., 2015), trivially extendable to additive biases: **Property 3.1**.: _For all \(\mathbf{\theta}\in\mathbb{R}^{\times m}\), \(\mathbf{\omega}\in\mathbb{R}^{m\times n}\), \(\mathbf{\lambda}\in\left(\mathbb{R}_{>0}\right)^{m}\),_ \[\forall\mathbf{x}\in\mathbb{R}^{n},\ (\mathbf{\lambda}^{-1}\bigtriangledown\mathbf{ \theta})\times r(\mathbf{\lambda}\rhd\mathbf{\omega}\mathbf{x})=\mathbf{\theta}\times r(\mathbf{ \omega}\mathbf{x}). \tag{4}\] When defining \(\mathcal{T}_{s}\) by the transformation Equation 4 - in the case of a two-layer perceptron - the core property directly follows, with the set of parameters \(\Lambda=\{\mathbf{\lambda}\}\): **Property 3.2** (Scaling symmetries).: _The scaling operation \(\mathcal{T}_{s}\) with a set of non-negative parameters \(\Lambda\) is a symmetry for all neural network \(f_{\mathbf{\omega}}\), i.e._ \[\forall\mathbf{x}\in\mathbb{R}^{n},\ f_{\mathcal{T}_{s}(\mathbf{\omega}, \Lambda)}(\mathbf{x})=f_{\mathbf{\omega}}(\mathbf{x}). \tag{5}\] ### Permutation symmetries We also propose a simple and intuitive formalism for permutation symmetries, multiplying the weights by permutation matrices. We have the following property for two-layer perceptions, with \(P_{m}\) the set of \(m\)-dimensional permutation matrices: **Property 3.3**.: _For all \(\mathbf{\theta}\in\mathbb{R}^{\times m}\), \(\mathbf{\omega}\in\mathbb{R}^{m\times n}\), and permutation matrices \(\mathbf{\pi}\in P_{m}\),_ \[\forall\mathbf{x}\in\mathbb{R}^{n},\;\mathbf{\theta}\mathbf{\pi}^{\intercal}\times r\left( \mathbf{\pi}\times\mathbf{\omega}\mathbf{x}\right)=\mathbf{\theta}\times r(\mathbf{\omega}\mathbf{x}). \tag{6}\] The left term of Equation 6 is the definition of the permutation symmetry operator of parameter \(\Pi=\{\mathbf{\pi}\}\) for a network with two layers. In general, we have the following property: **Property 3.4** (Permutation symmetries).: _The permutation operation \(\mathcal{T}_{p}\) with a set of parameters \(\Pi\) is a symmetry for all neural networks \(f_{\mathbf{\omega}}\), i.e.,_ \[\forall\mathbf{x}\in\mathbb{R}^{n},\;f_{\mathcal{T}_{p}(\mathbf{\omega},\Pi)}(\mathbf{x}) =f_{\mathbf{\omega}}(\mathbf{x}). \tag{7}\] ### The Bayesian posterior as a mixture of distributions With this formalism, we can establish the following proposition, clarifying the impact of weight-space symmetries on the Bayesian posterior. **Proposition 1**.: _Define \(f_{\omega}\) a neural network and \(f_{\tilde{\omega}}\) its corresponding identifiable model - a network transformed for having sorted unit-normed neurons. Let us also denote \(\Pi\) and \(\mathbb{\Lambda}\), the sets of permutation sets and scaling sets, respectively, and \(\tilde{\Omega}\) the random variable of the sorted weights with unit norm. The Bayesian posterior of a neural network \(f_{\omega}\) trained with stochastic gradient descent can be expressed as a continuous mixture of a discrete mixture:_ \[p(\Omega=\mathbf{\omega}\mid\mathcal{D})=\int\limits_{\Lambda\in\Lambda}|\Pi|^{-1 }\underset{\Pi\in\Pi}{\sum}\;p(\tilde{\Omega}=\mathcal{T}_{p}(\mathcal{T}_{s}( \mathbf{\omega},\Lambda),\Pi),\Lambda\mid\mathcal{D})d\Lambda. \tag{8}\] Proposition 1 provides an expression of the Bayesian posterior that highlights the redundancy of the resulting distribution, explaining the symmetry in Figure 1 (left). Interestingly, a direct corollary of this formula is that _all the layer-wise marginal distributions are identical_. In Equation 8, the permutations play a transparent role, being independent of \(\mathbf{\omega}\) (except for strongly quantized spaces for \(\mathbf{\omega}\), but we leave this particular case for future works). On the other hand, the part played by scaling symmetries is more complex and we discuss their impact in the following section. ### On the effective impact of scaling symmetries The equiprobability of permutations in Equation 8 leads to a balanced mixture of \(|\Pi|\) permuted terms. We have no such result on scaling symmetries since the standard L2-regularized loss is not invariant to scaling symmetries (contrary to permutations). This absence of invariance obscures the impacts of scaling symmetries, which mostly remains to be addressed, although their "reduction" due to regularization was mentioned in, e.g., Godfrey et al. (2022). To the best of our knowledge, we provide the first analysis of the reality of scaling symmetries and their impact on the Bayesian posterior. With this objective in mind, we propose the following problem. **Definition 3.3**.: Let \(f_{\omega}\) be a neural network and \(\tilde{\omega}\) its weights without the biases. We define the minimum scaled network mass problem (or _the min-mass problem_) as the minimization of the L2-regularization term of \(f_{\omega}\) (the "mass") under scaling transformations. In other words, \[m^{*}=\min_{\Lambda\in\Lambda}\;\left|\mathcal{T}_{s}(\tilde{\omega},\Lambda) \right|^{2}. \tag{9}\] This problem has interesting properties. Notably, we show in Appendix C.7 that the _min-mass_ problem is log-log strictly convex (Boyd & Vandenberghe, 2004; Agrawal et al., 2019): **Proposition 2**.: _The minimum scaled network mass problem is log-log strictly convex. As such, it is equivalent to a strictly convex problem on \(\mathbb{R}^{|\Lambda|}\) and admits a global minimum attained in a single point denoted \(\Lambda^{*}\)._ It follows from Proposition 2 that, if not already optimal at convergence, there is an infinite number of equivalent networks with training loss lower than the original network. We put the proposition into practice in Figure 2 using trained OptuNets (see Appendix B.2). We measure their mass distribution and compare it to the masses of the optimal networks found with convex optimization. In practice, the effect of scaling symmetries remains present even with weight decay: neural networks always seem subject to scaling symmetries. For completeness, we report the values of the largest elements of each layer, showing that the minimization tends to increase the maxima of the layers with fewer parameters yet does not seem to promote unfeasible values. In this section, we provided theoretical insights on the contrasted impacts of both scaling and permutation symmetries. In the following, we perform more empirical studies and propose to evaluate the link between posterior quality and experimental performance. ## 4 Comparing the estimations of the posterior by approximate Bayesian methods In this section, we leverage symmetries to compare popular single-mode methods, namely, Monte Carlo Dropout (Gal & Ghahramani, 2016), Stochastic Weight Averaging Gaussian (SWAG) proposed by Maddox et al. (2019), Bayes by backpropagation BNNs (Blundell et al., 2015), and Laplace methods (Ritter et al., 2018). We also include their multi-modal variations, corresponding to the application of these methods on 10 different independently trained models, as well as SGHMC (Chen et al., 2014) and Deep Ensembles (DE) highlighted by Lakshminarayanan et al. (2017) and proposed earlier by Hansen & Salamon (1990). We compare these methods on 3 image classification tasks with different levels of difficulty, ranging from MNIST (LeCun et al., 1998) with our OptuNet (392 parameters) to CIFAR-100 (Krizhevsky, 2009) and Tiny-ImageNet (Deng et al., 2009) with ResNet-18 (He et al., 2016). To this extent, we propose leveraging maximum mean discrepancy (MMD) to estimate the dissimilarities between the high-dimensional posterior distributions. We estimate the target distribution with 1000 checkpoints and compare it to 100 samples extracted from each of the previously-mentioned techniques. We detail these experiments in Appendix B. ### Evaluating the quality of the estimation of the Bayesian posterior One approach to assess the similarities between distributions involves estimating the distributions and subsequently quantifying the distance between these estimated distributions (Smola et al., 2007; Sriperumbudur et al., 2010). However, these methods can become impractical when dealing with distributions in extremely high-dimensional spaces, such as the posterior of DNNs. An alternative solution is to embed the probability measures into a Reproducing Kernel Hilbert Space (RKHS) developed by, e.g., Bergmann (1922); Aronszajn (1950); Schwartz (1964). Within this framework, a distance metric MMD (Song, 2008) - defined as the distance between the respective mean elements within the RKHS - is used to quantify the dissimilarity between the distributions. Gretton et al. (2012) proposed to leverage MMD for efficient two-sample tests in high dimensions. For better Figure 2: **OptuNet trained with weight decay never converges towards the _minimum mass_.** We note that the maxima of the weights of scaled OptuNets at the minimum mass tend to be greater for lighter layers than in the original networks. efficacy, MMDs are computed on RKHS that allow for comparing all of their moments. In Table 1, we propose to compute the median of the aggregated MMDs (Schrab et al., 2023) with multiple Gaussian and Laplace kernels, with and without symmetries. For tractability, we report the mean - weighted by the number of parameters of each layer - of the median over the twenty MMD kernels between the layer-wise estimated posterior and the posterior approximated by each method. The estimated posterior includes 1000 independently trained checkpoints, and the posterior approximation of each method includes 100 samples. Please refer to Appendix B for extended details (including the means and maxima of the MMDs). ### Performance metrics and OOD datasets On top of the MMD quantifying the difference between the posterior estimations, we measure several empirical performance metrics. We evaluate the overall performance of the models using the accuracy and the Brier score (Brier, 1950; Gneiting et al., 2007). Furthermore, we choose the binned Expected Calibration Error (ECE) (Naeini et al., 2015) for top-label calibration and measure the quality of the out-of-distribution (OOD) detection using the area under the precision-recall curve (AUPR) and the false positive rate at \(95\%\) recall (FPR95), as recommended by Hendrycks & Gimpel (2017), as a measure of OOD detection abilities, that are supposed to correlate with the quality of the estimated posterior. Finally, we report the mean diversity of the predictions in each ensemble through the mutual information (MI) (e.g., Ash (1965)), often used to measure epistemic uncertainty (Kendall & Gal, 2017; Ovadia et al., 2019). We use FashionMNIST (Xiao et al., \begin{table} \begin{tabular}{c c c c c c c c c c c} \hline \hline & Method & MMD \(\downarrow\) & NS \(\downarrow\) & Acc \(\uparrow\) & ECE \(\downarrow\) & Brier \(\downarrow\) & AUPR \(\uparrow\) & FPR95 \(\downarrow\) & IDMI \(\downarrow\) & OODMI \(\uparrow\) \\ \hline \multirow{8}{*}{**OOD**} & \multirow{2}{*}{OODMI} & Dropout & 15.0 & 14.3 & 83.3 & 33.4 & 26.1 & 96.4 & 98.6 & 26.1 & 22.2 \\ & & BNN & 18.8 & 17.1 & 78.1 & 74.4 & 30.9 & 67.9 & 93.7 & **0.1** & 0.1 \\ & & SGHMC & 16.7 & 17.7 & 95.1 & 7.6 & **2.8** & 73.7 & 98.4 & 4.3 & 14.5 \\ & & SWAG & 16.0 & 14.6 & 88.3 & 17.7 & 4.9 & 73.4 & 68.6 & 4.0 & 8.7 \\ & & Laplace & 10.6 & 9.5 & 87.9 & 18.1 & 48.8 & 48.2 & 74.6 & 6.2 & 5.9 \\ \cline{2-11} & & Dropout & 2.1 & 2.1 & 92.1 & 29.2 & 36.8 & **97.2** & 78.2 & 36.6 & 52.5 \\ & & BNN & 2.8 & 2.5 & 86.5 & 17.5 & 24.4 & 96.9 & 27.2 & 21.1 & 52.3 \\ & & SWAG & 1.8 & 1.3 & 95.0 & 13.1 & 17.5 & 88.7 & 24.6 & 27.6 & 62.2 \\ & & Laplace & 1.8 & 0.8 & 94.8 & 12.8 & 15.8 & 95.4 & 32.1 & 21.1 & 52.2 \\ \cline{2-11} & & DE & **0.0** & **0.9** & **95.8** & 10.7 & 13.5 & 95.7 & **12.8** & 19.3 & **62.6** \\ \hline \multirow{8}{*}{**OOD**} & \multirow{2}{*}{OODMI} & Dropout & 4.5 & 7.5 & 69.3 & 12.1 & 44.3 & 80.1 & 64.0 & 6.0 & 9.6 \\ & & BNN & 9.0 & 10.2 & 57.6 & 21.8 & 62.5 & 81.7 & 62.6 & 0.8 & 2.2 \\ & & SGHMC & 7.5 & 7.9 & 69.3 & 4.3 & 41.5 & 87.5 & 41.4 & **0.0** & 0.1 \\ & & SWAG & 6.7 & 7.2 & 66.7 & 1.7 & 43.8 & 30.7 & 17.1 & 2.7 & 14.7 \\ & & Laplace & 5.7 & 7.0 & 70.7 & 1.4 & 40.0 & 84.5 & 40.6 & 31.3 & 70.6 \\ \cline{2-11} & & Dropout & 0.7 & 4.5 & 75.5 & 4.8 & 64.2 & 93.5 & 23.7 & 23.8 & 77.0 \\ & & BNN & 6.1 & 5.6 & 66.3 & 1.3 & 45.6 & 91.0 & 30.9 & 44.5 & 110.4 \\ & & SWAG & 5.0 & 5.4 & 68.4 & 2.3 & 42.1 & **97.9** & 17.1 & 7.5 & 33.0 \\ & & Laplace & 0.6 & 4.3 & 75.2 & 7.8 & 35.2 & 95.1 & 20.1 & 50.5 & **128.3** \\ & & DE & **0.0** & **0.5** & **15.9** & 2.3 & **33.3** & 97.1 & **16.1** & 26.5 & 90.1 \\ \hline \multirow{8}{*}{**OOD**} & \multirow{2}{*}{OODMI} & Dropout & 9.5 & 4.9 & 56.4 & 14.2 & 60.3 & 70.8 & 87.6 & 9.5 & 13.5 \\ & & BNN & / & / & / & / & / & / & / & / & / \\ & & SGHMC & 9.8 & 5.3 & 54.4 & 2.3 & 58.9 & 78.1 & 74.4 & **0.1** & 0.2 \\ & & SWAG & 9.1 & 3.9 & 61.7 & 10.0 & 51.8 & 84.6 & 66.7 & 3.3 & 9.0 \\ & & Laplace & 5.5 & 6.1 & 29.7 & 7.4 & 81.3 & 62.3 & 82.3 & 211.7 & 254.8 \\ \cline{2-11} & & Dropout & 4.3 & 1.8 & 65.3 & 10.5 & 48.2 & 90.9 & 57.7 & 41.9 & 93.2 \\ \cline{2-11} & & BNN & / & / & / & / & / & / & / & / & / \\ \cline{2-11} & & SWAG & 6.7 & 5.4 & 64.8 & 2.3 & **46.6** & **98.4** & 53.6 & 20.5 & 55.2 \\ \cline{2-11} & & Laplace & 0.5 & 3.1 & 34.4 & 13.0 & 79.3 & 64.4 & 77.2 & 227.4 & **267.2** \\ \cline{2-11} & & DE & **0.0** & **0.0** & **65.4** & 8.5 & 47.3 & 94.2 & **41.6** & 44.7 & 108.5 \\ \hline \hline \end{tabular} \end{table} Table 1: **Comparison of popular methods approximating the Bayesian posterior.** All scores are expressed in %, except the MMDs for ResNet-18 networks, expressed in %. Acc stands for accuracy, and **IDMI** and **OODMI** are the in-distribution and out-of-distribution mutual information. NS is the MMD computed after the removal of the symmetries, and DE stands for Deep Ensembles. Multi-mode methods use ten independently trained models. 2017), SVHN (Netzer et al., 2011), and Textures (Cimpoi et al., 2014) as OOD datasets for MNIST, CIFAR-100, and TinyImageNet, respectively. ### Results In our examination of Table 1 emerges that multi-mode techniques consistently demonstrate superior performance in terms of MMD when compared to their single-mode counterparts. This trend holds true in accuracy and negative log-likelihood. However, an intriguing divergence arises when considering the ECE, where techniques focusing solely on estimating a single mode often exhibit superior performance. Turning our attention to the assessment of epistemic uncertainty, as quantified by AUPR and FPR95, multi-mode techniques, notably multi-SWAG, and Deep Ensembles, consistently outperform other methods. This underscores the strong connection between posterior estimation and the accuracy of epistemic uncertainty quantification. However, we note that the quality of aleatoric uncertainty quantification does not consistently correlate with that of the posterior distribution estimation. The final two columns of the table shed light on the diversity of the models sampled from the posterior. The objective here is to minimize in-distribution mutual information (IDMI) while concurrently maximizing out-of-distribution mutual information (OODMI). An analysis shows that mono-mode methods tend to yield lower values for both IDMI and OODMI than multi-mode methods, which tend to exhibit higher IDMI and OODMI values, suggesting greater _diversity_. ## 5 Discussions We develop further insights on the posterior of Bayesian Neural Networks in relationship with symmetries. Notably, we evaluate the risk of _functional collapse_, i.e., of training very similar networks in Section 5.1 and we discuss the frequency of weights permutations in 5.2. We expand these discussions, add observations on the evaluation of the number of modes of the posterior, and propose visualizations in Appendix D. ### Functional collapse in ensembles: a study of ID and OOD disagreements Given the potentially very high number of equivalent modes due to permutation symmetries (see Section 3.5), we support broadening the concept of collapse in the parameter-space (e.g., in D'Angelo and Fortuin (2021)) to _functional collapse_ to account for the impact of symmetries on the posterior. Parameter-space collapse is more restrictive and may not be formally involved when ensemble members lack diversity. It is also much harder to characterize as it would require an analysis of the loss landscape, at the very least. We propose here to quantify functional collapse as a potential ground for the need for more complex repulsive ensembling methods (Masegosa, 2020; Rame and Cord, 2021). To this extent, we randomly select 1000 ResNet-18 (trained to estimate the Bayesian posterior in Section 4) and compute the mean over the test set of their pairwise mutual information, quantifying the divergence between the single models and their average. We make these measures on in-distribution and out-of-distribution data (CIFAR-100 (ID) and SVHN (OOD)). In Figure 3 (left), we see that the in-distribution MI Figure 3: **Experiments show no hint of a functional collapse between couples of independently trained ResNet-18 on CIFAR-100. Moreover, the in-distribution and out-of-distribution mutual information (IDMI, resp. OODMI) exhibit different variances but do not seem correlated.** between any two networks has a very low variance. There is, therefore, an extremely low probability of training two similar networks. This may be explained by the high complexity of the network (here, a ResNet-18), and we refer to Appendix D.2 for results on a smaller architecture. In Figure 3 (center), we see that the variance of the out-of-distribution MI is higher. However, we also note in Figure 3 (right) that in contrast to common intuition (and to results for simpler models), we have, in this case, no significant correlation between the in-distribution and the out-of-distribution MI. This highlights that measuring the in-distribution _diversity_ (here with the MI) may be, in practice, a very poor indicator of the OOD detection performance of a model. Moreover, these results indicate that the complexity of the posterior is orders of magnitude higher than what we understand when taking symmetries into account. ### Frequency of weight permutations during training We propose a new protocol to evaluate if a network tends to permute during training. Given a DNN \(f_{\mathbf{\omega}}\), we can compute, for each step \(s\) of the training, the permutation set \(\Pi_{s}\) sorting its weights (and removing the symmetries). If the DNN tends to permute during the training, this implies a variation in the \(\Pi_{s}\). We suggest to measure the extent of the variations using the Kendall's \(\tau\) correlation coefficient (Kendall, 1938) between successive permutations \(\Pi_{s}\) and \(\Pi_{s+1}\). We plot the variation of the mean over several training instances and the elements of the permutation sets of Kendall's \(\tau\) in Figure 4. We see that on MNIST (left), the variations of the permutation set are scarce yet gathered around points of instability. These instabilities are due to the sorting mechanism based on the maximum values of the weights of the neurons. We have tried other statistics on the values of the weights, but taking the maximum seems the most stable. We see that the weights nearly never permute in the last phase of the training. The results differ for the ResNet-18 (right) since the number of degrees of freedom is much higher. We see a lot of variation during the phases with a high learning rate (reduced after 25 and 50 epochs). However, as for the first case, we do not see any particular sign of permutations in the last part of the training. ## 6 Conclusion In this study, we have examined Bayesian neural network posteriors, which are pivotal for understanding uncertainty. Our findings suggest that part of the complexity in these posteriors can be attributed to the non-identifiability of modern neural networks viewing the posterior as a mixture of permuted distributions. To explore this further, we have introduced the _min-mass_ problem to investigate the real impact of scaling symmetries. Using real-world applications, we have proposed a method to assess the quality of the posterior distribution and its correlation with model performance, particularly in terms of uncertainty quantification. While considering symmetries has provided valuable insights, our discussions hint at a deeper complexity going beyond weight-space symmetries. In future work, we plan to continue our exploration of this intriguing area. Figure 4: **Evolution during training of the mean Kendall’s \(\tau\) correlation between the permutations towards the identifiable model for all successive steps**: The correlation between successive permutations increases when the learning rate decreases. ## 7 Reproducibility statement We use publicly available datasets, including MNIST, FashionMNIST, CIFAR100, SVHN, ImageNet-200, and Textures, to ensure transparency and accessibility. Please refer to Appendix B.3 for details on these datasets. Our detailed experimental methods are outlined in Appendices A and B, and the proofs for all theoretical results are provided in Appendix C. To help the replication of our work, we will share the source code for our experiments on GitHub shortly. Notably, we will release a library that tackles the non-identifiability of neural networks. For our experiments in Section 4, we rely exclusively on open-source libraries, such as the GitHub repository Bayesian-Neural-Networks for SGHMC, BLiTZ (Esposito, 2020) for variational Bayesian neural networks, and Laplace (Daxberger et al., 2021). For the SWAG method, we also use the publicly available code from the original paper (Maddox et al., 2019). Finally, we estimate the maximum mean discrepancies with a torch version of the code from Schrab et al. (2023) and solved our convex optimization problems (see Definition C.6) with cvxpy(Diamond and Boyd, 2016; Agrawal et al., 2018). The statistical experiments, such as Pearson's \(\rho\) and Kendall's \(\tau\), are performed with SciPy (Virtanen et al., 2020). ## 8 Ethics Our primary goal in this paper is to improve our comprehension of the Bayesian posterior, which we argue is a fundamental element to understand to contribute to the reliability of machine-learning methods. We note that training a substantial number of checkpoints for estimating the posterior, especially in the case of the thousand models trained on TinyImageNet, was energy intensive (around 3 Nvidia V100 hours per training). To mitigate the environmental impact, we opted for a carbon-efficient cluster.
2302.08928
Highly connected dynamic artificial neural networks
An object-oriented approach to implementing artificial neural networks is introduced in this article. The networks obtained in this way are highly connected in that they admit edges between nodes in any layers of the network, and dynamic, in that the insertion, or deletion, of nodes, edges or layers of nodes can be effected in a straightforward way. In addition, the activation functions of nodes need not be uniform within layers, and can also be changed within individual nodes. Methods for implementing the feedforward step and the backpropagation technique in such networks are presented here. Methods for creating networks, for implementing the various dynamic properties and for saving and recreating networks are also described.
Clint van Alten
2023-02-17T15:05:29Z
http://arxiv.org/abs/2302.08928v1
# Highly connected dynamic artificial neural networks ###### Abstract An object-oriented approach to implementing artificial neural networks is introduced in this article. The networks obtained in this way are highly connected in that they admit edges between nodes in any layers of the network, and dynamic, in that the insertion, or deletion, of nodes, edges or layers of nodes can be effected in a straightforward way. In addition, the activation functions of nodes need not be uniform within layers, and can also be changed within individual nodes. Methods for implementing the feedforward step and the backpropagation technique in such networks are presented here. Methods for creating networks, for implementing the various dynamic properties and for saving and recreating networks are also described. ## 1 Introduction Artificial neural networks typically have a static architecture that consists of a sequence of layers, with each layer containing a fixed number of nodes and with edges that connect nodes between neighbouring layers. In this article we present an approach to implementing artificial neural networks that are more flexible in their architectures, which we call _dynamic artificial neural networks_ (for short, _networks1_). In particular, the networks may be highly connected in that they admit edges between nodes in any layers in the network, and dynamic, in the sense that new nodes, edges or layers of nodes may be inserted into the network, and existing nodes, edges or layers may be removed. Further dynamic features include the ability to change properties of individual nodes. Nodes of different types, e.g., with different activation functions, may occur within the same layer. The approach to implementing networks that we present in this article is an object-oriented one that uses two main types of object, namely, node objects and edge objects. Internal properties of a node such as the activation function and bias value are stored as attributes in the node object, as are a running total of inputs received by the node and the activation value of the node. Each node also has a pointer to the head of a list of edges that all share this node as their source; each edge object has as attributes its weight and a pointer to its target node. The networks have a layered structure in which each layer consists of a linked list of nodes. Objects called layernodes are used to mark the head of each list of nodes and these are connected in a doubly-linked list. The structure of such networks is described in detail in Section 2. The computation of the network output given some input values, i.e., the feedforward step, proceeds layer-by-layer and uses the layernodes in the flow control. A method for implementing the feedforward step in these networks is described in Section 3. Thereafter, in Section 4, we present a method for implementing the backpropagation technique for training these networks. The method we present is a basic version of backpropagation that implements stochastic gradient descent; more complex versions of backpropagation may be implemented following the style of the basic method.2 The layernodes are also used in the backwards flow control during backpropagation. Footnote 2: Sample code that implements various methods for dynamic artificial neural networks can be found at [https://github.com/cvanalten/dyann](https://github.com/cvanalten/dyann) In Section 5 we discuss methods for creating networks and for applying the dynamic features of insertion and deletion in networks. In Section 6 we outline methods for saving and recreating networks. We assume that the reader is familiar with the basics of artificial neural networks. An extensive introduction to such structures can be found, for example, in [1] and [2]. ## 2 Network structure We describe here the structure of a _dynamic artificial neural network_, or just _network_, for short. The general structure of a network is pictured in Figure 1. A network consists of a doubly-linked list of objects called layernodes, with the _input-layernode_ at the head and the _output-layernode_ at the tail. Layernodes are shown as squares in Figure 1. The layernode class is shown below; the _next_ attribute points to the adjoining layernode in the direction of the _output-layernode_, while _prev_ points to the adjoining layernode in the opposite direction. Every layernode has an attribute that is a pointer to the first node in singly-linked list of nodes, as indicated in Figure 1, where nodes are shown as circles. Network layernode _input-layernode_, _output-layernode_ The node and edge classes are shown below. The _sum_ attribute in the node class is a running total of inputs received by the node via edges connected to it. The remaining node attributes are either self-explanatory or their purpose will become clear in the following sections. Edges connect one node, called the edge's _source_, to another node, called the edge's _target_. Every node has a pointer to the first edge in a singly-linked list of edges that all share that node as their source node; every edge has a pointer to its target node. In Figure 1, some edges with node \(n\) as source are illustrated with thicker arrows. Node double _bias_, _sum_, _actvalue_, _delta_ function _actfunction_ edge _firstedge_ (first edge in list of edges with this node as source) node _next_ (next node in this layer of nodes) Edge double _weight_ node _target_ (node receiving impulse via this edge) edge _next_ (next edge in list of edges with the same source node) Observe that every node has its activation function stored as an attribute, so different nodes in the same layer may have different activation functions. In addition, the activation function of a given node may be changed quite easily. We shall refer to nodes in the list at the _input-layernode_ as _input nodes_ and nodes in the list at the _output-layernode_ as _output nodes_. By an _internal node_ we shall mean any node that is not an input or output node. We assume that an internal node's activation value, i.e., _actvalue_, is obtained by applying its activation function to the sum of its _sum_ and _bias attribute values. Thus, an internal node's activation value depends only on its own attributes. Typical examples of activation functions that such nodes could use include linear, relu, sigmoid and tanh. Output nodes may obtain their activation values in the same way as internal nodes, but we allow for the option that output nodes use activation functions that depend on the attributes of all output nodes; examples of such activation functions include max and softmax. For input nodes, biases and activation functions are not used, and we may assume that they have _bias_ of 0 and use linear activation functions. In regard to edges, we observe that an edge from a given node may have as its target a node in any layer in the network; that is, edges need not only connect to nodes in subsequent layers, but may also connect to nodes in previous layers or nodes in its own layer. Such edges are amenable to the feedforward process, however, the backpropagation algorithm, as presented in Section 4, will not train such edges. We shall assume, therefore, that each edge connects its source node to a target node that is in a subsequent layer. We shall assume, also, that for any two nodes there exists at most one edge that connects them. This assumption is not essential, but facilitates backpropagation. ## 3 Feedforward In this section we describe the forward computation of a dynamic artificial neural network on a given input, which we refer to as the feedforward step. In this step, a network, say Net, takes an input array, say \(\underline{A}\), of length equal to the number of nodes in the input layer in Net, and computes the output values following the algorithm FeedForward given below. In the first step of FeedForward the values in \(\underline{A}\) are assigned to the _actualue_ attributes of the input nodes. Next, each input node \(n\) is 'fired', meaning that _n.actvalue_ is propagated along each edge in _n_'s edge list. That is, for each such edge \(e\), starting with _n.firstedge_, the product _n.actvalue\(*\)e.weight_ is added to _e.target.sum_, as shown in FireNode. Thereafter, the layernodes are traversed in forward sequential order up to the layer preceding the output layer. For each such layernode \(x\) and every node in the list at \(x\), the node's _actvalue_ is computed and the node is fired. Note that we reset the node's _sum_ to 0 after firing in preparation for the next forward pass. Lastly, the _actualue_ attributes at the output nodes are computed using FireOutputNode. The output layer is treated separately as we allow for activation functions such as max or softmax in this layer. The values stored in the _actualue_ attributes of the output nodes comprise the output of the network. FeedForward(Net, \(\underline{A}\)) 1 Assign values in \(\underline{A}\) to _actualue_ attributes of nodes in the input layer. 2\(x\) = Net._input-layernode_ 3\(n\) = _x.firstnode_ 4while\(n\)\(\neq\) null 5 FireNode(_n_) 6\(n\) = _n.next_ 7\(x\) = _x.next_ 8while(_x.next_\(\neq\)null) 9\(n\) = _x.firstnode_ 10while(_n_\(\neq\)null) 11\(n.\)_actualue_ = _n.actfunction_(_n.sum_\(+\)_n.bias_) 12 FireNode(_n_) 13\(n.\)_sum_\(=0\) 14\(n\) = _n.next_ 15\(x\) = _x.next_ 16 FireOutputLayer(_x_) FireNode(_n_) 1\(e\) = _n.firstedge_ 2while\(e\)\(\neq\)null 3\(e.\)_target.sum_\(=\)_e.target.sum_\(+\)_n.actualue\(\ast\)e.weight_ 4\(e\) = _e.next_ FireOutputLayer(_x_) Apply activation function at each node in output layer. ## 4 Backpropagation In this section, we describe how the backpropagation technique using stochastic gradient descent may be implemented for training dynamic artificial neural networks. To facilitate discussion of backpropagation in this setting, it is useful to introduce some notation and recall some definitions. We assume that a network, say Net, uses a loss function \(L\) that takes as arguments the output values of the network that are stored in the _actualue_ attributes of output nodes and the target values corresponding to the input values. Let \(\underline{W}\) be the list of all current edge weights and bias values in Net, let \(\underline{A}\) be an input array and \(\underline{T}\) the corresponding array of target values. Suppose that FeedForward\((\text{Net},\underline{A})\) has been completed. The gradient descent method is used to adjust the weights and biases in the network to reduce the loss between the output values and target values. For each weight \(w\) in the network, the following update rule is applied: \[w=w-\eta\,\Big{(}\tfrac{\partial L}{\partial w}\big{|}_{\underline{ATW}}\Big{)}, \tag{4.1}\] where \(\eta\) is the learning rate and \(\tfrac{\partial L}{\partial w}\big{|}_{\underline{ATW}}\) denotes the evaluation of the partial derivative \(\tfrac{\partial L}{\partial w}\) using the values in \(\underline{A},\underline{T}\) and \(\underline{W}\). Backpropagation (see, e.g., [1]), as described below, is used to obtain \(\tfrac{\partial L}{\partial w}\big{|}_{\underline{ATW}}\) for each weight \(w\). We use \(n\), \(m\) and \(\ell\) as names for nodes. If an edge exists with node \(m\) as its source and node \(n\) as its target then we say that \(m\) is _connected_ to \(n\) and denote this by \(m\to n\); we use \(w_{mn}\) as the variable for the weight of this edge. For each node \(n\) in the network we use \(b_{n}\) as the variable for the bias at \(n\), \(y_{n}\) as the variable for the activation value at \(n\) and \(z_{n}\) as the variable for the sum of inputs to the node \(n\) plus the bias. Thus, \[z_{n}=\sum_{m:\,m\to n}w_{mn}y_{m}+b_{n},\] where \(m\) ranges over all nodes that are connected to \(n\). If \(n\) is an internal node, then \(y_{n}=g_{n}(z_{n})\), where \(g_{n}\) is \(n\)'s activation function, and if \(n\) is an output node, then \(y_{n}=g_{n}(z_{n_{1}},\ldots,z_{n_{r}})\), where \(g_{n}\) is \(n\)'s activation function and \(n_{1},\ldots,n_{r}\) are the output nodes (one of which is \(n\)). For each node \(n\), the _delta_ value at \(n\), denoted by \(\delta_{n}\), is defined as \[\delta_{n}=\tfrac{\partial L}{\partial z_{n}}\big{|}_{\underline{ATW}}.\] If a node \(m\) is connected to node \(n\), then \(\tfrac{\partial L}{\partial w_{mn}}=\tfrac{\partial L}{\partial z_{n}}\tfrac{ \partial z_{n}}{\partial w_{mn}}=\tfrac{\partial L}{\partial z_{n}}\,y_{m}\), so \[\tfrac{\partial L}{\partial w_{mn}}\big{|}_{\underline{ATW}}=\tfrac{\partial L }{\partial z_{n}}\big{|}_{\underline{ATW}}\,y_{m}\big{|}_{\underline{ATW}}= \delta_{n}\,\Big{(}y_{m}\big{|}_{\underline{ATW}}\Big{)}. \tag{4.2}\] For the _bias_ at \(n\), we have that \(\frac{\partial L}{\partial b_{n}}=\frac{\partial L}{\partial z_{n}}\frac{ \partial z_{n}}{\partial b_{n}}=\frac{\partial L}{\partial z_{n}}\), hence \[\frac{\partial L}{\partial b_{n}}\big{|}_{\underline{ATW}}=\frac{\partial L}{ \partial z_{n}}\big{|}_{\underline{ATW}}=\delta_{n}. \tag{4.3}\] By (4.2), the gradient descent update rule in (4.1) for edge weights is \[w_{mn}=w_{mn}-\eta\,\delta_{n}\left(y_{m}\big{|}_{\underline{ATW}}\right) \tag{4.4}\] and, using (4.3), the gradient descent update rule for biases is \[b_{n}=b_{n}-\eta\,\delta_{n}. \tag{4.5}\] Next, we show how the delta values backpropagate through the network. If node \(n\) is connected to node \(\ell\), then \(\frac{\partial z_{\ell}}{\partial y_{n}}=w_{n\ell}\), hence \[\frac{\partial L}{\partial z_{n}}=\sum_{\ell:\,n\to\ell}\frac{\partial L}{ \partial z_{\ell}}\frac{\partial z_{\ell}}{\partial z_{n}}=\sum_{\ell:\,n\to \ell}\frac{\partial L}{\partial z_{\ell}}\frac{\partial z_{\ell}}{\partial y _{n}}\frac{dy_{n}}{dz_{n}}=\left(\sum_{\ell:\,n\to\ell}\frac{\partial L}{ \partial z_{\ell}}w_{n\ell}\right)\frac{dy_{n}}{dz_{n}}.\] Thus, \[\delta_{n}=\frac{\partial L}{\partial z_{n}}\big{|}_{\underline{ATW}}=\left( \sum_{\ell:\,n\to\ell}\delta_{\ell}\Big{(}w_{n\ell}\big{|}_{\underline{ATW}} \Big{)}\right)\left(\frac{dy_{n}}{dz_{n}}\big{|}_{\underline{ATW}}\right). \tag{4.6}\] Using (4.6), the gradient descent update of the weights in the network Net can be done as shown in the algorithm BackPropagate below. Recall that the current weights and biases of Net are in \(\underline{W}\), that \(\underline{T}\) is the array of target values corresponding to the input array \(\underline{A}\), and that FeedForward(Net, \(\underline{A}\)) has been completed. Then, for every node \(n\), the value \(y_{n}|_{\underline{ATW}}\) is stored in \(n.\)_actvalue_. The learning rate is denoted by _eta_. The algorithm BackPropagate starts by computing the _delta_ value at each output node using UpdateOutputNodes. In addition, the _bias_ value at each output node is updated according to (4.5). Next, proceeding backwards along layernodes, UpdateNode is applied to each internal node. UpdateNode loops over all edges in the edge list at a given node \(n\) and does two jobs - it computes the summation in expression (4.6) and performs the gradient descent update rule in (4.4) on each edge's weight. At the end of the loop, the final value for _n.delta_ is obtained by multiplying by the modifier \(\frac{dy_{n}}{dz_{n}}\big{|}_{\underline{ATW}}\), as in (4.6). Then, using _n.delta_, the value of _n.bias_ is updated according to (4.5). In the last part of BackPropagate, the nodes in the input layer are updated. A separate algorithm for updating input nodes is used since neither the _delta_ values nor the _bias_ values are needed at these nodes. BackPropagate(Net, \(\underline{T},L,\mathit{eta}\)) 1 UpdateOutputNodes(Net, \(\underline{T},L,\mathit{eta}\)) 2\(x\) = Net._output-layernode.prev_ 3**while** (_x.prev_\(\neq\)null) 4\(n\) = _x.firstnode_ 5**while** (_n_\(\neq\)null) 6 UpdateNode(_n_, \(\mathit{eta}\)) 7\(n\) = _n.next_ 8\(x\) = _x.prev_ 9\(n\) = _x.firstnode_ 10**while** (_n_\(\neq\)null) 11 UpdateInputNode(_n_, \(\mathit{eta}\)) 12\(n\) = _n.next_ UpdateOutputNodes(Net, \(\underline{T},L,\mathit{eta}\)) 1 compute _n.delta_ at each output node \(n\) using _n.delta_ = \(\frac{\partial L}{\partial z_{n}}\big{|}_{\underline{ATW}}\) and update _n.bias_ using _n.bias_ = _n.bias_ \(-\)_eta\(\ast\)_n.delta_ UpdateNode(_n_, \(\mathit{eta}\)) 1\(n\).delta = 0 2\(e\) = _n.firstedge_ 3**while** (_e_\(\neq\)null) 4\(n\).delta = _n.delta_ + _e.target.delta\(\ast\)e.weight_ 5\(e\).weight = _e.weight_ \(-\)_eta\(\ast\)e.target.delta\(\ast\)n.actvalue_ 6\(e\) = _e.next_ 7\(n\).delta = _n.delta_\(\ast\frac{dy_{n}}{dz_{n}}\big{|}_{\underline{ATW}}\) 8\(n\).bias = _n.bias_ \(-\)_eta\(\ast\)n.delta_ UpdateInputNode(_n_, \(\mathit{eta}\)) 1\(e\) = _n.firstedge_ 2**while** (_e_\(\neq\)null) 3\(e\).weight = _e.weight_ \(-\)_eta\(\ast\)e.target.delta\(\ast\)n.actvalue_ 4\(e\) = _e.next_ We note that in UpdateNode, it is necessary to compute \(\frac{dy_{n}}{dz_{n}}\big{|}_{\mathit{ATW}}\), i.e., \(g^{\prime}_{n}(z_{n})|_{\mathit{ATW}}\). In the case of linear, relu, sigmoid and tanh activation functions, \(\frac{dy_{n}}{dz_{n}}\big{|}_{\mathit{ATW}}\) can be computed from the value \(y_{n}|_{\mathit{ATW}}\), that is, from \(n.\mathit{actvalue}\). Other activation functions may require the value of \(z_{n}|_{\mathit{ATW}}\), i.e., \(\mathit{n.sum}+\mathit{n.bias}\). However, since \(\mathit{n.sum}\) has been reset to 0 in the feedforward step, the value of \(z_{n}|_{\mathit{ATW}}\) is no longer available. To circumvent this, an additional node attribute may be used, say \(\mathit{n.pastum}\), that stores the value of \(\mathit{n.sum}\) in the feedforward step before it is reset to 0. Variations on the basic backpropagation algorithm that make use of various types of regularisation and optimisation techniques may be incorporated in the setting here. Additional attributes may be added to nodes if required. ## 5 Creating and modifying dynamic artificial neural networks In this section we describe how to create dynamic artificial neural networks and how to implement the various dynamic properties of the networks. A network may be created according to a given specification by first creating the linked lists of layernodes and nodes and then adding the linked list of edges to each node. Alternately, a network may be created by first creating the input and output layers, and then inserting new layers of nodes into the network, together with new edges that have one of the newly inserted nodes either as source or as target. A network may also be recreated from a saved description of the network, as discussed in Section 6. It is worth mentioning some simpler variations of networks that may offer savings on time or space complexity. First, if every node in a layer of nodes has the same activation function, then this activation function can be stored as an attribute in the corresponding layernode object instead of in each node. In this setup, some (straightforward) changes are required to the FeedForward and BackPropagate algorithms. Secondly, if all internal nodes use the same activation function (e.g., relu), then no activation function attribute is required in either the nodes or layernodes, as the activation function can be built directly into the FeedForward and BackPropagate algorithms. Inserting a new node into an existing layer of a network can be done by inserting the node at the head of the list of nodes of the corresponding layernode, using the standard method of inserting into a linked list. Thereafter, edges can be added that have the new node as their source and any node in a subsequent layer as target. In addition, edges can be added that have the new node as target and any node in a previous layer as source. In the worst case, a pass over every node in the network is required to complete this step. A new layer of nodes may be inserted between two consecutive layers by first inserting a new layernode into the doubly-linked list of layernodes and then inserting a list of new nodes according to the specifications. The addition of edges can be done as for inserting a single node. The method of inserting a new layer of nodes may be used in the initial creation of a network. The input and output layers are first created and connected by edges if required, and then the internal layers are inserted one-by-one. A possible advantage to creating a network in this way is that some training epochs may be interposed between the insertion of new layers. Next, we discuss methods for deleting nodes or edges from a network. One reason for deleting an edge from a network is that the edge's weight may be sufficiently close to zero that it has no significant impact on the execution of the network. Another reason is that the target node of the edge may have been deleted. Similarly, a reason for deleting a node is if all of its edges have been deleted. There may be other reasons for deleting a node; for example, the number of times a node has fired a nonzero value may be sufficiently small in comparison to the number of times the network has been used (although this requires nodes to have an additional attribute that keeps track of the rate of firings). Deleting an edge can be done simply by removing the edge from the linked list of edges where it occurs. Deleting a node can be done similarly by removing it from the list of nodes where it occurs, however, the deletion of a node requires that we delete all the edges that have that node as their target node. To do that, we give each node an additional Boolean attribute, which we call _markedfordeletion_. Given a node \(n\) that we wish to delete, we set _n.markedfordeletion_ = True. Then, prior to removing the node, a pass over all nodes and corresponding edge lists is required in order to remove all edges \(e\) for which _e.target.markedfordeletion_ is True. Of course, only nodes in layers that precede node _n_'s layer need be considered. If a number of nodes have been selected for deletion, then a single pass over the network will suffice for all nodes. Thereafter, a pass over all nodes may be done in which all nodes marked for deletion are removed from their lists. Lastly, a pass over the list of layernodes may be performed to remove layernodes that have empty node lists. Saving and recreating networks In this section, we outline methods for saving and recreating dynamic artificial neural networks. To save a network, we require that nodes have additional integer attributes called _layerindex_ and _nodeindex_ that describe the position of the node within the network. We use the convention that nodes in the input layer have _layerindex_ equal to 0 and _layerindex_ increments in the direction of the output layer. Similarly, the head node of the node list at each layer has _nodeindex_ equal to 0 and values increment along the list. To save a network, a pass over the nodes of the network is done to assign _n.layerindex_ and _n.nodeindex_ to each node \(n\). The number of layers in the network and the number of nodes in each layer is saved. Then, a second pass over the nodes of the network is done and the following information on each node is saved: 1. the values of attributes _bias_, _actvalue_, _actfunction_, _layerindex_, _nodeindex_ (and possibly more); 2. for every edge in the edge list of the node, the edge's _weight_ and its _target_, which is described by the _layerindex_ and _nodeindex_ attributes of the target node. The above information allows for the recreation of the original network as follows. First, the layernode and node lists are constructed according to saved information, and _layerindex_ and _nodeindex_ attributes are assigned to each node. Next, each stored node is matched up with the new node with the same _layerindex_ and _nodeindex_ values, to which the stored attributes in (i) may then be assigned. An edge list for the node is then created using the stored edge information in (ii) to find and assign the _target_ node for each edge. In the above construction, matching up the saved nodes with the new nodes can be done in one pass over the network if the stored nodes are sorted in lexicographical order according to (_layerindex_, _nodeindex_). Creating the edge list for a single node can be done in one pass over the network if the node's edges are sorted in lexicographic order according to (_layerindex_, _nodeindex_) of their targets. Thus, assuming the correct sorting of information, the creation of edge lists can be done using two nested loops over the nodes of the network. Conclusion In this article we have described an approach to implementing artificial neural networks that are highly connected and dynamic. The main differences between the networks described here and standard neural networks is that edges may connect a source node to a target node in any subsequent layer of the network, that new nodes, edges and layers may be inserted into the network, or deleted from the network, and that nodes within a layer need not be of a uniform type. The method uses an object-oriented approach with separate classes for nodes, edges, layernodes and networks themselves. We have shown how the feedforward and backpropagation methods can be implemented, and discussed methods for creating networks, implementing various dynamic properties and saving and recreating networks. It is worth noting that standard neural networks may also be implemented as dynamic artificial neural networks. As such, comparisons in terms of performance between the approaches are possible. We make no claims about improved performance in terms of efficiency of training the networks. Rather, the potential advantages of the approach in this article lie in the variety of networks that can be implemented and the dynamic properties of the networks. There is substantial scope for experimentation with different types of networks in various applications. It may also be interesting to try incorporate other neural network architectures such as convolutional neural networks into the approach here, or to consider a combination of different approaches. Lastly, our approach has used standard types of nodes, however, by adding appropriate attributes to the node class, nodes with more complex behaviour may also be used.
2301.11929
Training Full Spike Neural Networks via Auxiliary Accumulation Pathway
Due to the binary spike signals making converting the traditional high-power multiply-accumulation (MAC) into a low-power accumulation (AC) available, the brain-inspired Spiking Neural Networks (SNNs) are gaining more and more attention. However, the binary spike propagation of the Full-Spike Neural Networks (FSNN) with limited time steps is prone to significant information loss. To improve performance, several state-of-the-art SNN models trained from scratch inevitably bring many non-spike operations. The non-spike operations cause additional computational consumption and may not be deployed on some neuromorphic hardware where only spike operation is allowed. To train a large-scale FSNN with high performance, this paper proposes a novel Dual-Stream Training (DST) method which adds a detachable Auxiliary Accumulation Pathway (AAP) to the full spiking residual networks. The accumulation in AAP could compensate for the information loss during the forward and backward of full spike propagation, and facilitate the training of the FSNN. In the test phase, the AAP could be removed and only the FSNN remained. This not only keeps the lower energy consumption but also makes our model easy to deploy. Moreover, for some cases where the non-spike operations are available, the APP could also be retained in test inference and improve feature discrimination by introducing a little non-spike consumption. Extensive experiments on ImageNet, DVS Gesture, and CIFAR10-DVS datasets demonstrate the effectiveness of DST.
Guangyao Chen, Peixi Peng, Guoqi Li, Yonghong Tian
2023-01-27T02:33:40Z
http://arxiv.org/abs/2301.11929v1
# Training Full Spike Neural Networks via Auxiliary Accumulation Pathway ###### Abstract Due to the binary spike signals making converting the traditional high-power multiply-accumulation (MAC) into a low-power accumulation (AC) available, the brain-inspired Spiking Neural Networks (SNNs) are gaining more and more attention. However, the binary spike propagation of the Full-Spike Neural Networks (FSNN) with limited time steps is prone to significant information loss. To improve performance, several state-of-the-art SNN models trained from scratch inevitably bring many non-spike operations. The non-spike operations cause additional computational consumption and may not be deployed on some neuromorphic hardware where only spike operation is allowed. To train a large-scale FSNN with high performance, this paper proposes a novel Dual-Stream Training (DST) method which adds a detachable Auxiliary Accumulation Pathway (AAP) to the full spiking residual networks. The accumulation in AAP could compensate for the information loss during the forward and backward of full spike propagation, and facilitate the training of the FSNN. In the test phase, the AAP could be removed and only the FSNN is remained. This not only keeps the lower energy consumption but also makes our model easy to deploy. Moreover, for some cases where the non-spike operations are available, the APP could also be retained in test inference and improve feature discrimination by introducing a little non-spike consumption. Extensive experiments on ImageNet, DVS Gesture, and CIFAR10-DVS datasets demonstrate the effectiveness of DST. Machine Learning, ICML ## 1 Introduction In the past few years, Artificial Neural Networks (ANNs) have achieved great success in many tasks (Krizhevsky et al., 2012; Simonyan and Zisserman, 2015; Szegedy et al., 2015; Girshick et al., 2014; Liu et al., 2016; Redmon et al., 2016; Chen et al., 2021, 2020; Ma et al., 2022; Chen and Chen, 2018). However, with ANNs getting deeper and larger, computational and power consumption are growing rapidly. Hence, Spiking Neural Networks (SNNs), inspired by biological neurons, have recently received surging attention and are regarded as a potential competitor of ANNs due to their high biological plausibility, event-driven property, and low power consumption (Roy et al., 2019) on neuromorphic hardware. To obtain an effective SNN, several works (Kim et al., 2018; Xing et al., 2019; Hwang et al., 2021; Hu et al., 2018; Sengupta et al., 2019; Han et al., 2020; Lee et al., 2020; Zheng et al., 2021; Samadzadeh et al., 2020; Rathi and Roy, 2020; Rathi et al., 2020) are proposed to convert the trained ANN to SNN by replacing the raw activation layers (such as ReLU) with spiking neurons. Although this type of method could achieve state-of-the-art accuracy on many image classification datasets, they often require a large number of time steps which causes high computational consumption and also limit the application of SNN, and the direct promotion of exploring the characteristics of SNN is limited. Hence, a series of methods are proposed to train SNN from scratch. Based on the surrogate gradient backpropagation method (Tavanaei et al., 2019), several recent works train deep SNN by improving the Batchnorm (Zheng et al., 2021) or residual connection structure (Fang et al., 2021; Zhou et al., 2023; Xiao et al., 2022; Deng et al., 2022), and narrow the gap between SNN and ANN effectively. To obtain high performance, several SOTA SNN models (Fang et al., 2021; Zheng et al., 2021; Zhou et al., 2023) inevitably bring many non-spike operations with ADD residual connections. Although effective, these methods may suffer two main drawbacks: Firstly, the energy efficiency advantage of SNNs mainly comes from the fact that the binary spike signals make converting the traditional high-power multiply-accumulation (MAC) into a low-power accumulation (AC) available, the non-spike operations don't fit this characteristic and will bring high computation consumption. Secondly, several neuromorphic hardware only supports spiking operation, and these models cannot be deployed directly (Horowitz, 2014). Hence, it is necessary to develop a full-spike neural network (FSNN) that only contains spike operations. However, the binary spike propagation with limited time steps is prone to significant information loss, and limits the performance of FSNN. For example, the Spiking ResNet in Figure 1 is prone to vanishing gradient problems in deep networks (Fang et al., 2021). To compensate for the loss of information forward and backward from full spike propagation, we propose a novel Dual-stream Training (DST) method, where the whole network contains a _full spike propagation_ stream and a _auxiliary spike accumulation_ stream. The former includes full-spike inference of FSNN, while the latter is a plug-and-play Auxiliary Accumulation Pathway (AAP) to the FSNN. In training, the AAP is able to compensate for the loss of information forward and backward from full spike propagation by spike accumulation, which could help alleviate the vanishing gradient problem of the Spiking ResNet and improve the performance of the FSNN. Although the accumulation in APP causes non-spike operation, the AAP could be removed and only the FSNN remains in the test phase. In other words, our model could act as an FSNN inference in practical application. This not only keeps the lower energy consumption but also makes our model easy to deploy in the neuromorphic hardware. Moreover, for some cases where the non-spike operations are available, the AAP could also be retained in test inference and further improve feature discrimination by introducing a small number of non-spike MAC operations. It is notable that FSNN+AAP only brings a linear rise in the non-spike AC computation with the model depth, resulting in less computational consumption. We evaluate DSNN on both the static ImageNet dataset (Deng et al., 2009) and the neuromorphic DVS Gesture dataset (Amir et al., 2017), CIFAR10-DVS dataset (Li et al., 2017), CIFAR100 (Krizhevsky et al., 2009). The experiment results are consistent with our analysis, indicating that the DST could improve the previous ResNet-based and Transformer-based FSNNs to higher performance by simply increasing the network's depth, and keeping efficient computation consumption simultaneously. ## 2 Related Work ### Spiking Neural Networks To train deep SNNs, ANN to SNN conversion (ANN2SNN) (Hunsberger and Eliasmith, 2015; Cao et al., 2015; Rueckauer et al., 2017; Sengupta et al., 2019; Han et al., 2020; Han and Roy, 2020; Deng and Gu, 2021; Stockl and Maass, 2021; Li et al., 2021) and backpropagation with surrogate gradient (Neftici et al., 2019) are the two mainstream methods. For ANN2SNN, an ANN with ReLU activation is first trained, then converts the ANN to an SNN by replacing ReLU with spiking neurons and adding scaling operations like weight normalization and threshold balancing. Recently, several ANN2SNN methods (Han et al., 2020; Han and Roy, 2020; Deng and Gu, 2021; Li et al., 2021) have achieved near loss-less accuracy for VGG-16 and ResNet. However, the converted SNN needs longer time steps to rival the original ANN, and increases the SNN's computational consumption (Rueckauer et al., 2017). One of the backpropagation methods (Kim et al., 2020) computes the gradients of the timings of existing spikes with respect to the membrane potential at the spike timing (Comsa et al., 2020; Mostafa, 2017; Kheradpisheh and Masquelier, 2020; Zhou et al., 2021; Zhang and Li, 2020). Another kind of backpropagation method gets the gradient by unfolding the network over the simulation time-steps (Lee et al., 2016; Huh and Sejnowski, 2018; Wu et al., 2018; Shrestha and Orchard, 2018; Lee et al., 2020; Neftci et al., 2019). As the gradient with respect to the threshold-triggered firing is non-differentiable, the surrogate gradient is often used. ### Spiking Residual Networks For ANN2SNN with ResNet, several methods made specific normalizations for conversion. The residual structure in ANN2SNN with scaled shortcuts is applied in SNN to match the activations of the original ResNet (Hu et al., 2018). Previous ANN2SNN methods noticed the distinction between plain feedforward ANNs and residual ANNs, and made specific normalizations for conversion. Then, Spike-Norm (Sengupta et al., 2019) is proposed to balance the threshold of the Spiking Neural Model and verified their method by converting ResNet to SNNs. Moreover, existing backpropagation-based methods use nearly the same structure as ResNet. Several custom surrogate methods (Sengupta et al., 2019) are evaluated on shallow ResNets. Threshold-dependent batch normalization (td-BN) is proposed to replace naive batch normalization (BN) (Ioffe and Szegedy, 2015) and successfully trained Spiking ResNet-34/50 directly with surrogate gradient by adding td-BN in shortcuts. SEW ResNet is the first method to increase the SNNs to more than 100 layers, but its use of additive operations in residual connections leads to a none-spike structure in the deep layer of the network bringing higher computational consumption. (Deng et al., 2022) introduces the temporal efficient training approach to compensate for the loss of momentum in the gradient descent with SG so that the training process can converge into flatter minima with better generalizability. (Xiao et al., 2022) proposes online training through time for SNNs, which enables forward-in-time learning by tracking presynaptic activities and leveraging instantaneous loss and gradients. Recently, (Zhou et al., 2023) considers leveraging both self-attention capability and biological properties of SNNs and proposes the Spiking Transformer (Spikformer). ## 3 Preliminaries ### Spiking Neuron Model The spiking neuron is the fundamental computing unit of SNNs. The dynamics of all kinds of spiking neurons can be described as follow: \[H_{t} =SN(V_{t-1},X_{t}), \tag{1}\] \[S_{t} =\Theta(H_{t}-V_{th}),\] (2) \[V_{t} =H_{t}\ \left(1-S_{t}\right)+V_{reset}\ S_{t}, \tag{3}\] where \(X_{t}\) is the input at time-step \(t\), \(H_{t}\) and \(V_{t}\) denote the membrane potential after neuronal dynamics and after the trigger of a spike at time-step \(t\), respectively. \(V_{th}\) is the firing threshold, \(\Theta(x)\) is the Heaviside step function and is defined by \(\Theta(x)=1\) for \(x\geq 0\) and \(\Theta(x)=0\) for \(x<0\). \(S_{t}\) is the output spike at time-step \(t\), which equals 1 if there is a spike and 0 otherwise. \(V_{reset}\) denotes the reset potential. The function \(SN(\cdot)\) in Eq. (1) describes the neuronal dynamics and takes different forms for different spiking neuron models, which include the Integrate-and-Fire (IF) model (Eq. (4)) and Leaky Integrate-and-Fire (LIF) model (Eq. (5)): \[H_{t} =V_{t-1}+X_{t}, \tag{4}\] \[H_{t} =V_{t-1}+\frac{1}{\tau}(X_{t}-(V_{t-1}-V_{reset})), \tag{5}\] where \(\tau\) represents the membrane time constant. Eq. (2) and Eq. (3) describe the spike generation and resetting processes, which are the same for all kinds of spiking neuron models. ### Computational Consumption With the sparsity of firing and the short simulation period, SNN can achieve the calculation with about the same number of synaptic operations (SyOPs) (Rueckauer et al., 2017) rather than FLOPs, The number of synaptic operations per layer of the network can be easily estimated for an ANN from the architecture of the convolutional and linear layers. For the ANN, a multiply-accumulate (MAC) computation takes place per synaptic operation. On the other hand, specialized SNN hardware would perform an accumulated computation (AC) per synaptic operation only upon the receipt of an incoming spike. Hence, the total number of AC operations occurring in the SNN would be represented by the dot-product of the average cumulative neural spike count for a particular layer and the corresponding number of synaptic operations. With the deepening of SNN and ANN, the relative energy ratio gradually approaches a fixed value, which could be calculated as follows: \[\frac{E(\mathrm{SNN})}{E(\mathrm{ANN})}\approx T\cdot fr\cdot\frac{E_{ac}}{E_{ mac}}, \tag{6}\] where \(T\) and \(fr\) represent the simulation time and the average firing rate. Eq. (6) assumes the SNN only contains \(\{0,1\}\) spike AC operators. However, several SOTA SNNs employ many non-spike MAC and their computation consumption could not be estimated by Eq. (6) accurately. To estimate the computation consumption of different SNNs more accurately, we calculate the number of computations required in terms of AC and MAC synaptic operations, respectively. The main energy consumption of non-spike signals comes from the MAC between neurons. The contribution from one neuron Figure 1: Residual blocks and Dual-stream blocks in Spiking ResNet (Fang et al., 2021) and Spike Transformer (Zhou et al., 2023). (a) the Spiking ResNet by replacing ReLU activation layers with spiking neurons. (b) The Spiking ResNet with Dual-stream training. (c) The input of the Spike Transformer with Spiking Self-Attention (SSA) is non-spike data due to residual addition between blocks, which brings additional multiply accumulative computation to SNN. (d) Spike Transformer with a dual-stream structure is divided into a spike propagation pathway and a plug-and-play auxiliary accumulation pathway (AAP), which could compensate for full spike propagation. Note AAP could be either retained or removed in model inference. to another requires a MAC for each timestep, multiplying each non-spike activation with the respective weight before adding it to the internal sum. In contrast, a transmitted spike requires only an accumulation at the target neuron, adding weight to the potential, and where spikes may be quite sparse. Therefore, for any SNN network \(\mathcal{F}\), the theoretical computational consumption can be determined by the number of AC and MAC operations (\(O_{ac},O_{mac}\)): \[\mathrm{E}(\mathcal{F})=T\cdot(fr\cdot E_{ac}\cdot O_{ac}+E_{mac}\cdot O_{mac}). \tag{7}\] Moreover, we developed and open-sourced a tool to calculate the dynamic consumption of SNNs as **syops-counter1**, which can compute the theoretical amount of AC and MAC operations. Footnote 1: github.com/iCGY96/syops-counter ### Spiking Residual Blocks There are two main types of residual blocks for existing SNNs. The one replaces ReLU activation layers with spiking neurons, which constructs FSNN but is prone to vanishing gradient problems. The second uses the same addition operation as the ANN, but leads to additional computation consumption due to the appearance of non-spike signals. Vanishing Gradient Problems of Spiking ResNet.Consider a Spiking ResNet with \(k\) sequential blocks to transmit \(s_{l}^{t}\), and the identity mapping condition is met by using the IF neurons for residual connection with \(0<V_{th}\leq 1\), then we have \(s_{l}^{t}=s_{l+1}^{t}=...=s_{l+k-1}^{t}=o_{l+k-1}^{t}\). The gradient of the output of the \((l+k-1)\)-th residual block with respect to the input of the \(l\)-th residual block could be calculated layer by layer: \[\begin{split}\frac{\partial o_{l+k-1}^{t}}{\partial s_{l}^{t}}& =\prod_{i=0}^{k-1}\frac{\partial o_{l+i}^{t}}{\partial s_{l+i}^{t} }=\prod_{i=0}^{k-1}\Theta^{\prime}(s_{l+i}^{t}-V_{th})\\ &\rightarrow\begin{cases}0,\text{if}\;0<\Theta^{\prime}(s_{l}^{t} -V_{th})<1\\ 1,\text{if}\;\Theta^{\prime}(s_{l}^{t}-V_{th})=1\end{cases},\end{split} \tag{8}\] where \(\Theta(x)\) is the Heaviside step function and \(\Theta^{\prime}(x)\) is defined by the surrogate gradient. The second equality hold as \(o_{l+i}^{t}=\mathrm{SN}(s_{l+i}^{t})\). In view of the fact that \(s_{l}^{t}\) could only take 0 or 1 with identity mapping, \(\Theta^{\prime}(s_{l}^{t}-V_{th})=1\) is not satisfied for commonly used surrogate functions mentioned in (Nefci et al., 2019). When using the common \(Sigmoid\)(Nefci et al., 2019) function as the Heaviside step function, the gradient vanishing problem would be prone be happen. Spiking Residual Blocks with ADD.As illustrated in Figure 1(c), the residual block for SNN can be formulated with an ADD function (Fang et al., 2021; Zhou et al., 2023), which can implement identity mapping and overcome the vanishing and exploding gradient problems. \[o_{l}^{t}=\mathrm{SN}(f_{l}(o_{l-1}^{t}))+o_{l-1}^{t}=s_{l}^{t}+o_{l-1}^{t}, \tag{9}\] where \(s_{l}^{t}\) denotes the residual mapping learned as \(s_{l}^{t}=\mathrm{SN}(f_{l}(o_{l-1}^{t}))\). While this design brings performance improvements, it inevitably brings in non-spike data and thus MAC operations. In particular, for the ADD function, if both \(s_{l}^{t}\) and \(o_{l-1}^{t}\) are spike signals, its output \(o_{l}^{t}\) will be a non-spike signal whose value range is \(\{0,1,2\}\). As the depth of the network increases, the range of signals transmitted to the next layer of the network will also expand. Convolution requires much more computational overhead of multiplication and addition when dealing with these non-spiking signals as shown in Figure 1(b). In this case, the network will incur additional high computational consumption. ## 4 Dual-stream Training ### Dual-stream SNN Basic Block.Instead of the residual Block containing only one path with respect to the input spike \(x\), we initialize the input to two consistent paths \(s_{0}^{t}=a_{0}^{t}=x\), where \(s_{l}^{t}\) represents the spike signal propagated between blocks, and \(a_{l}^{t}\) represents the spike accumulation carried out on the output of each block. As illustrated in Figure 1(b) and (d), the Dual-Stream Block can be formulated as: \[\begin{split} o_{l}^{t}&=\begin{cases}\mathrm{SN}(f_ {l}(o_{l-1}^{t})+o_{l-1}^{t})=SN(s_{l}^{t}+o_{l-1}^{t})\\ g(\mathrm{SN}(f_{l}(o_{l-1}^{t})),o_{l-1}^{t})=g(s_{l}^{t},o_{l-1}^{t})\end{cases} \\ a_{l}^{t}&=s_{l}^{t}+a_{l-1}^{t},\end{split} \tag{11}\] where \(g\) represents an element-wise function with two spikes tensors as inputs. Note that here we restrict \(g\) to be only the corresponding _logical operation function_ as shown in Table 1, so as to ensure that the input and output of \(g\) function are spike trains. Here, Eq.(10) is the full-spike propagation pathway, which could be either of two types of spiking ResNet. Eq.(11) denotes the plug-and-play Auxiliary Accumulation Pathway (AAP). During the inference phase, the auxiliary accumulation could be removed as needed. Downsampling Block.Remarkably, when the input and output of one block have different dimensions, the shortcut is set as convolutional layers with stride \(>1\), rather than the identity connection, to perform downsampling. The Spiking ResNet utilize {Conv-BN} without ReLU in the shortcut. SEW ResNet (Fang et al., 2021) adds an SN in shortcut as shown in Figure 2(b). Figure 2(b) shows the downsampling of auxiliary accumulation, that the overhead of multiply accumulation in Dual-stream Blocks mainly comes from the downsampling of the spike accumulation signal. Fortunately, the number of downsampling in a network is always fixed, so the MAC-based downsampling operation of the spike accumulation pathway will not increase with the increase of network depth. Therefore, the increased computational overhead of DSNN with the increase of network depth mainly comes from the accumulation calculation. **Training.** For backpropagation, the gradient could be back-propagated to these spiking neurons through the auxiliary accumulation to prevent the vanishing gradient caused by deeper layers. Therefore, in the training phase, the outputs of both auxiliary accumulation and spike propagation are used as the final output and the gradient is calculated according to a consistent objective function \(\mathcal{L}_{c}\): \[\mathcal{L}(x,y)=\mathcal{L}_{c}(\mathcal{O}_{s},y)+\mathcal{L}_{c}(\mathcal{O }_{a},y), \tag{12}\] where \(\mathcal{O}_{s}\) and \(\mathcal{O}_{a}\) are the final outputs of auxiliary accumulation and spike propagation respectively. ### Identity Mapping As stated in (He et al., 2016), satisfying identity mapping is crucial to training a deep network. **Auxiliary Accumulation Pathway.** For auxiliary accumulation of Eq.(11), identity mapping is achieved by when \(s_{l}^{t}\equiv 0\), which can be implemented by setting the weights and the bias of the last BN layer in \(f_{l}\) to zero. The Spiking Neurons Residuals.The first spike propagation of Eq.(10) based on Spiking ResNet could implement identity mapping by partial spiking neurons. When \(f_{l}(o_{l}^{t-1})\equiv 0\), \(o_{l}^{t}=\mathrm{SN}(o_{l}^{t-1})\neq o_{l}^{t-1}\). To transmit \(o_{l}^{t-1}\) and make \(\mathrm{SN}(o_{l}^{t-1})=o_{l}^{t-1}\), the last spiking neuron (SN) in the \(l\)-th residual block needs to fire a spike after receiving a spike and keep silent after receiving no spike at time-step \(t\). It works for IF neurons described by Eq. (4). Specifically, we can set \(0<V_{th}\leq 1\) and \(V_{t-1}=0\) to ensure that \(o_{t}=1\) leads to \(H_{t}\geq V_{th}\), and \(o_{t}=0\) leads to \(H_{t}<V_{th}\). Hence, we replaced all the spiking neurons at the residual connections with IF neurons. The Element-wise Logical Residuals.For the second spike propagation of Eq.(10), different element-wise functions \(g\) in Table 1 satisfy identity mapping. Specifically, for \(\mathrm{IAND}\), \(\mathrm{OR}\) and \(\mathrm{XOR}\) as element-wise functions \(g\), identity mapping could be achieved by setting \(s_{l}^{t}\equiv 0\). Then \(o_{l}^{t}=g(s_{l}^{t},o_{l-1}^{t})=g(\mathrm{SN}(0),o_{l-1}^{t})=g(0,o_{l-1}^{ t})=o_{l-1}^{t}\). This is consistent with the conditions for auxiliary accumulation Eq.(11) to achieve identity mapping and is applicable to all neuron models. In contrast, for \(\mathrm{AND}\) as the element-wise function \(g\), \(s_{l}^{t}\) should be ones to get identity mapping. Then \(o_{l}^{t}=1\wedge o_{l-1}^{t}=o_{l-1}^{t}\). Although the input parameters of spiking neuron models can be adjusted to practice identity mapping, it is conflicted with the auxiliary accumulation pathway for identity mapping. This is not conducive to maintaining the consistency of signal propagation between the two pathways, thus affecting the effects of training and final recognition. Meanwhile, it is hard to control some spiking neuron models with complex neuronal dynamics to generate spikes at a specified time step. ### Vanishing Gradient Problem Auxiliary Accumulation Pathway.The gradient for the auxiliary accumulation pathway is calculated as \(\frac{\partial a_{l+k-l}^{t}}{\partial a_{l}^{t}}=\frac{\partial a_{l}^{t}}{ \partial a_{l}^{t}}=1\) with identity mapping. Since the above gradient is a constant, the auxiliary accumulation path of Eq. (11) could also overcome the vanishing gradient problems. The Spiking Neurons Residuals.Moreover, consider a Spiking ResNet with AAP, the gradient of the output of the \((l+k-1)\)-th residual block with respect to the input of the \(l\)-th residual block with identity mapping could be calculated: \[\begin{split}\frac{\partial o_{l+k-1}^{t}}{\partial s_{l}^{t}}& +\frac{\partial a_{l+k-1}^{t}}{\partial a_{l}^{t}}=\prod_{i=0}^{k- 1}\frac{\partial o_{l+i}^{t}}{\partial s_{l+i}^{t}}+\frac{\partial a_{l}^{t }}{\partial a_{l}^{t}}\\ &=\prod_{i=0}^{k-1}\Theta^{\prime}(s_{l+i}^{t}-V_{th})+\frac{ \partial a_{l}^{t}}{\partial a_{l}^{t}}\\ &\rightarrow\begin{cases}1,\text{if}\;0<\Theta^{\prime}(s_{l}^{t }-V_{th})<1\\ 2,\text{if}\;\Theta^{\prime}(s_{l}^{t}-V_{th})=1\end{cases},\end{split} \tag{13}\] Since the above gradient is a constant, the Spiking ResNet with AAP could alleviate the vanishing gradient problems. \begin{table} \begin{tabular}{c l} \hline \hline Operator & \(g(x_{l}^{t},s_{l}^{t})\) \\ \hline \(\mathrm{AND}\) & \(s_{l}^{t}\wedge x_{l}^{t}=s_{l}^{t}\cdot x_{l}^{t}\) \\ \(\mathrm{IAND}\) & \((\neg s_{l}^{t})\wedge x_{l}^{t}\) = \((1-s_{l}^{t})\cdot x_{l}^{t}\) \\ \(\mathrm{OR}\) & \(s_{l}^{t}\lor x_{l}^{t}=s_{l}^{t}+x_{l}^{t}-(s_{l}^{t}\cdot x_{l}^{t})\) \\ \(\mathrm{XOR}\) & \(s_{l}^{t}\oplus x_{l}^{t}=s_{l}^{t}\cdot(1-x_{l}^{t})+x_{l}^{t}\cdot(1-s_{l}^{ t})\) \\ \hline \hline \end{tabular} \end{table} Table 1: List of element-wise functions \(g\). Figure 2: The SEW Block (Fang et al., 2021) and its Downsample blocks with a dual-stream structure. The Element-wise Logical Residuals.When the identity mapping is implemented for the spiking propagation path of Eq.(10), the gradient of the output of the \((l+k)\)-th dual-stream block with respect to the input of the \(l\)-th DSNN block could be calculated layer by layer: \[\frac{\partial{o_{l+k-1}^{t}}}{\partial{x_{l}^{t}}} =\prod_{i=0}^{k}\frac{\partial{g(s_{l+i}^{t};x_{l+i}^{t})}}{ \partial{x_{l+i}^{t}}} \tag{14}\] \[=\begin{cases}\prod_{i=0}^{k}\frac{\partial{(1+\tau_{i+i}^{t})}}{ \partial{x_{l+i}^{t}}},\text{if }\ g=\mathrm{AND}\\ \prod_{i=0}^{k}\frac{\partial{((1-0)\cdot x_{l+i}^{t})}}{\partial{x_{l+i}^{t}} },\text{if }\ g=\mathrm{IAND}\\ \prod_{i=0}^{k}\frac{\partial{((1+0)\cdot x_{l+i}^{t})}}{\partial{x_{l+i}^{t}} },\text{if }\ g=\mathrm{OR}\\ \prod_{i=0}^{k}\frac{\partial{((1+0)\cdot x_{l+i}^{t})}}{\partial{x_{l+i}^{t} }},\text{if }\ g=\mathrm{XOR}\end{cases}=1.\] The second equality holds as identity mapping is achieved by setting \(s_{l+i}^{t}\equiv 1\) for \(g=\mathrm{AND}\), and \(s_{l+i}^{t}\equiv 0\) for \(g=\mathrm{IAND}/\mathrm{OR}/\mathrm{XOR}\). Since the gradient in Eq. (14) is a constant, the spiking propagation path of Eq.(10) overcomes the vanishing gradient problems. ## 5 Experiments ### Computational Consumption To estimate the computational consumption of different SNNs, we calculate the number of computations required in terms of AC and MAC synaptic operations, respectively. Moreover, (Rueckauer et al., 2017) integrates batch normalization (BN) layers into the weights of the preceding layer with loss-less conversion. Therefore, we ignore BN operations when calculating the number of MAC operations, resulting in a more efficient inference consumption. See Appendix A for details of the fusion process of convolution with BN. To quantitatively estimate energy consumption, we evaluate the computational consumption based on the number of AC and MAC operations and the data for various operations in \(45nm\) technology (Horowitz, 2014), where \(\mathrm{E_{MAC}}\) and \(\mathrm{E_{AC}}\) are \(4.6pJ\) and \(0.9pJ\) respectively. Here, we calculate the **D**ynamic **C**ansumption (DC) of the SNN by Eq.(8) based on its spike firing rate on the target dataset. Moreover, we use the **E**stimated **C**onsumption (EC) to estimate the theoretical consumption range from \([0,100\%]\) spike firing rate, that is \[\mathrm{E}(\mathcal{F})\in[T\cdot E_{mac}\cdot O_{mac},T\cdot(E_{ac}\cdot O_{ ac}+E_{mac}\cdot O_{mac})]. \tag{15}\] ### ImageNet Classification We validate the effectiveness of our Dual-stream Training method on image classification of ImageNet (Deng et al., 2009) dataset. The IF neuron model is adopted for the static ImageNet dataset. For a fair comparison, all of our training parameters are consistent with SEW ResNet (Fang et al., 2021). As shown in Table 2, two variations of our DST are evaluated: "FSNN (DST)" means the FSNN is trained by the proposed DST and AAP is removed in the test phase, and "DSNN" means the APP is retained to improve the discrimination of features. "FSNN-18" and "DSNN-18" represents the SNN is designed based on ResNet-18, and so on. Three types of methods are compared respectively: "A2S" represents ANN2SNN methods, "FSNN" and "MPSNN" means Full Spike Neural Networks and Mixed-Precision Spike Neural Networks respectively. These notations keep the same in the below. As shown in Table 2, we can obtain 3 following key findings: First, the SOTA ANN2SNN methods (Li et al., 2021; Hu et al., 2018) achieve higher accuracies than FSNN as well as other SNNs trained from scratch, but they use 64 and 87.5 times as many time-steps as FSNN respectively, which means that they require more computational consumption. Since most of these methods do not provide the trained models and their DCs are not available, we only used EC to evaluate the consumption. From Table 2, these models with larger time steps also have larger computational consumption. (Meng et al., 2022) also achieves good performance with ResNet-18, but its SNN acquisition process is relatively complex. It needs ANN to pre-train the model first and then retrain the SNN. Although its time steps are less than other ANN2SNN methods, it is still 12.5 times that of DSNN. Due to ANN2SNN being a different type of method from ours, the comparisons are listed just for reference. Second, for full-spike neural networks, FSNN (DST) outperforms Spiking ResNet (Zheng et al., 2021; Deng et al., 2022) even with lower computational consumption. The performance of FSNN (DST) has a major advantage over other FSNNs and also improves with the increasing depth of the network. It indicates that the proposed DST is indeed helpful to train FSNN. Finally, the performance of DSNN is further improved when AAP is added to FSNN at the inference phase. At the same time, the DSNN offers superior performance compared to the mixed-precision SEW ResNet (Fang et al., 2021). Note that the performance gap between SEW ResNet-34 and SEW ResNet-50 is not big, and the computational consumption of SEW ResNet-34 is higher than SEW ResNet-50. This phenomenon comes from that ResNet-34 and ResNet-50 use BasicBlock (He et al., 2016) and Bottleneck (He et al., 2016) as blocks respectively. As shown in Figure 1 (b), the first-layer convolution of each block is regarded as a MAC computation operation due to the non-spike data generated by ADD function. However, the first-layer convolution of BasicBlock is much larger than the synaptic operation of Bottleneck, which causes the computational consumption of SEW ResNet-34 to be greater than that of ResNet-50. In contrast, DSNN ensures that the input and output of each block are spike data through the dual-stream mechanism, so that the theoretical computational consumption increases linearly with the increase of network depth. ### DVS Classification Dvs Gesture.We also compare our method with SEW ResNet-7B-Net (Fang et al., 2021) on the DVS Gesture dataset (Amir et al., 2017), which contains 11 hand gestures from 29 subjects under 3 illumination conditions. We use the similar network structure 7B-Net in (Fang et al., 2021). As shown in Table 3, FSNN-7 (DST) with \(\mathrm{IAND}\) obtains better performance than other FSNN methods, such as SEW with \(\mathrm{IAND}\) and td-BN, demonstrating the DST is effective to train FSNN. In addition, even though SEW utilizes \(\mathrm{IAND}\) as \(g(\cdot)\) which brings non-spike operations, our FSNN-7 (DST) still achieves comparable performance, and only requires a tenth of the computational consumption of SEW. Cifar10-Dvs.We also evaluate Spiking ResNet models on the CIFAR10-DVS dataset (Li et al., 2017), which is obtained by recording the moving images of the CIFAR-10 dataset on an LCD monitor by a DVS camera. We use Wide-7B-DSNN which is a similar network structure Wide-7B-Net in (Fang et al., 2021). As shown in Table 3, FSNN-7 (DST) achieves better performance and lower computational consumption than the previous Spiking ResNet (Zheng et al., 2021) and SEW ResNet (Fang et al., 2021). ### Further Analysis Computational ConsumptionHere, we analyze the computational consumption advantages of DSNN. First, the networks in most ANN2SNN methods are full-spike, where few MAC operations are from batch normalization and conversion of images to spikes. However, their computational consumption is still very large due to the large time steps. DSNN and FSNN has fewer time steps than ANN2SNN methods, which means that its theoretical maximum consumption is much smaller than ANN2SNN as shown in Table 2. Second, the DSNN has lower EC and DC than Spiking ResNet based on addition (SEW ResNet), and achieves better performance. The additive-based SEW ResNet will increase its AC and MAC as the network gets deeper, which will bring about a multifold increase in com \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline Network & Methods & Acc@1 & \(T\) & EC(mJ) & \(O_{ac}\)(G) & \(O_{mac}\)(G) & DC(mJ) \\ \hline PreAct-ResNet-18 (Meng et al., 2022) & A2S & 67.74 & 50 & \([1.43,77.84]\) & - & - & - \\ Spiking ResNet-34 (Rathi et al., 2020) & A2S & 61.48 & 250 & \([7.31,805.79]\) & - & - & - \\ Spiking ResNet-34 (Li et al., 2021) & A2S & 74.61 & 256 & \([7.45,825.29]\) & - & - & - \\ \hline Spiking ResNet-34 with td-BN (Zheng et al., 2021) & FSNN & 63.72 & 6 & \([0.69,19.85]\) & 5.34 & 0.15 & 5.50 \({}^{\dagger}\) \\ Spiking ResNet-50 with td-BN (Zheng et al., 2021) & FSNN & 64.88 & 6 & \([1.10,22.59]\) & 6.01 & 0.24 & 6.52 \({}^{\dagger}\) \\ Spiking ResNet-34 (Deng et al., 2022) & FSNN & 64.79 & 6 & \([0.69,19.85]\) & 5.34 & 0.15 & 5.50 \({}^{\dagger}\) \\ FSNN-18 (DST) & FSNN & 62.16 & 4 & \([0.55,4.31]\) & 1.69 & 0.12 & 2.07 \\ FSNN-34 (DST) & FSNN & 66.45 & 4 & \([0.55,7.64]\) & 3.42 & 0.12 & 3.63 \\ FSNN-50 (DST) & FSNN & 67.69 & 4 & \([0.55,10.42]\) & 3.14 & 0.12 & 3.38 \\ FSNN-101 (DST) & FSNN & 68.38 & 4 & \([0.55,20.64]\) & 4.42 & 0.12 & 4.53 \\ \hline SEW ResNet-18 (ADD) (Fang et al., 2021) & MPSNN & 63.18 & 4 & \([12.65,16.40]\) & 0.51 & 2.75 & 13.11 \\ SEW ResNet-34 (ADD) (Fang et al., 2021) & MPSNN & 67.04 & 4 & \([29.72,36.78]\) & 0.86 & 6.46 & 30.50 \({}^{\dagger}\) \\ SEW ResNet-50 (ADD) (Fang et al., 2021) & MPSNN & 67.78 & 4 & \([23.64,33.50]\) & 2.01 & 5.14 & 25.45 \\ SEW ResNet-34 (ADD) (Deng et al., 2022) & MPSNN & 68.00 & 4 & \([29.72,36.78]\) & 0.86 & 6.46 & 30.50 \({}^{\dagger}\) \\ SEW ResNet-101 (ADD) (Fang et al., 2021) & MPSNN & 68.76 & 4 & \([39.88,59.97]\) & 3.07 & 8.67 & 42.65 \\ DSNN-18 & MPSNN & 63.46 & 4 & \([0.92,4.67]\) & 1.69 & 0.20 & 2.44 \\ DSNN-34 & MPSNN & 67.52 & 4 & \([0.92,8.00]\) & 3.42 & 0.20 & 4.00 \\ DSNN-50 & MPSNN & 69.56 & 4 & \([6.30,16.17]\) & 3.20 & 1.37 & 9.18 \\ DSNN-101 & MPSNN & 71.12 & 4 & \([6.30,26.39]\) & 4.48 & 1.37 & 10.33 \\ \hline \hline \end{tabular} \end{table} Table 2: Comparison with previous Spiking ResNet on ImageNet. \(\dagger\) denotes the estimated dynamic consumption based on the spike firing rate provided in the corresponding paper. A2S represents ANN2SNN methods, FSNN and MPSNN mean Full Spike Neural Networks and Mixed-Precision Spike Neural Networks respectively. FSNN (DST) represent the FSNN is trained by the proposed DST and DSNN means APP is retained in the test phase. \begin{table} \begin{tabular}{l c c c c} \hline \hline Networks & \(g(\cdot)\) & DVS Gesture & CIFAR10-DVS & \(T\) \\ & & ACC/DC(mJ) & & \\ \hline SEW (Fang et al., 2021) & ADD & **97.92**/17.09 & 74.4/16.71 & 16 \\ \hline SEW (Fang et al., 2021) & IAND & 95.49/1.48 & - & 16 \\ td-BN (Zheng et al., 2021) & - & 96.87/- & 67.8/- & 40/10 \\ \hline FSNN-7 (DST) & \(\mathrm{AND}\) & 55.56/2.59 & 70.9/3.57 & 16 \\ FSNN-7 (DST) & OR & 96.18/1.04 & 74.8/3.51 & 16 \\ FSNN-7 (DST) & XOR & 96.53/1.19 & 74.0/3.41 & 16 \\ FSNN-7 (DST) & IAND & 97.57/1.10 & 73.14/6.65 & 16 \\ \hline \hline \end{tabular} \end{table} Table 3: Comparison with Spiking ResNet methods on DVS Gesture and CIFAR10-DVS. Once the ADD function is used as \(g(\cdot)\), it will bring non-spiking operation to SEW (Fang et al., 2021). The comparison with it is listed just for reference. putational consumption. In contrast, the main MAC operation for DSNN comes from the downsampling process of accumulated signals in spike accumulation. Therefore, a deeper DSNN only increases the AC operation, and its MAC operation is constant as shown in Table 2. Finally, it also reveals for the first time the positive relationship between computational consumption and the performance of SNNs. In addition, the performance of DSNN increases gradually with the increase in computational consumption. It indicates the added computational consumption of deeper DSNN is meaningful. Vanishing Gradient Problem.As mentioned in Section 3.3, Spiking ResNet suffers from a vanishing gradient problem. As shown in Figure 3, the performance of the Spiking ResNet gradually decreases as the number of network layers increases. Network depth did not bring additional gain to the original Spiking ResNet. With the addition of DST, the performance of the Spiking ResNet gradually increases with increasing network depth. Also, the performance is superior with the addition of AAP. As demonstrated in Eq.(13), DST could help alleviate the vanishing gradient problem of the Spiking ResNet. Feature Enhancement.Here, we analyze the effects of auxiliary accumulation in terms of improving feature discrimination. Moreover, AAP increases the feature discriminant of forward as shown in Figure 4. Under fewer time steps, the spike feature is almost a binary feature, because its discrete property limits the discriminant of its feature. The discrimination of features from spike propagation is not enough, which affects the overall performance. On the other hand, we could increase the number of deep spike features by increasing time steps, so as to improve the discrimination by increasing the number of features, which often leads to too high computational consumption as shown in Table 2. More importantly, AAP separates the computation of AC operations from the MAC computation of recognition, allowing SNN to take full advantage of its low computational consumption. Spike Transformer.We also test the role of DST on the Transformer on CIFAR100. The latest method Spikeformer Zhou et al. (2023) utilizes \(\mathrm{ADD}\) as its residual connection and achieve SOTA performance. However, the \(\mathrm{ADD}\) introduces additional computational consumption from non-spike data. As shown in Table 4, once the \(\mathrm{IAND}\) is replaced by \(\mathrm{IAND}\), the performance of the full-spike Spikeformer will drop. After introducing APP as shown in Figure 1, the Spikeformer with a full-spike signal achieves similar performance to the original mixed-precision Spikeformer. Notably, there is no downsampling in the Spikeformer, which further exploits the advantages of AAP while not introducing additional MAC operations. The small amount of MAC operations comes mainly from the image-to-spike conversion and the classifier operations. ## 6 Conclusion & Outlook In this paper, we point out that the main contradiction of FSNNs comes from information loss of full spike propagation. Therefore, we propose the Auxiliary Accumulation Pathway with consistent identity mapping which is able to compensate for the loss of information forward and backward from full spike propagation, so as to keep computationally efficient and high-performance recognition simultaneously. The experiments on the ImageNet, DVS Gesture, and CIFAR10-DVS indicate that DST could improve the ResNet-based and Transformer-based SNNs trained from scratch in both accuracy and computation consumption. Looking forward, this SNN with a dual-stream structure may provide a reference for the design of neuromorphic hardware, which \begin{table} \begin{tabular}{l c c c} \hline \hline Networks & Method & Acc & DC(mJ) \\ \hline Spikformer (ADD) & MPSNN & 77.21 & 5.27 \\ \hline Spikformer (IAND) & FSNN & 75.54 & 0.82 \\ Spikformer (IAND) w/ DST & FSNN & 76.96 & 0.84 \\ \hline \hline \end{tabular} \end{table} Table 4: Learning Spike Transformer Zhou et al. (2023) with DST. ADD will bring additional computational consumption from non-spike data. Spikformer (IAND) is the full-spike version of Spikformer, and Spikformer (IAND) w/ DST means the full-spike Spikformer is trained by our DST. Figure 4: The the t-SNE Maaten and Hinton (2008) plots of embedding features on DVS Gesture. Figure 3: Training Spiking ResNet from scratch on ImageNet with/without Dual-Stream Training. could improve computational efficiency by separating spike and non-spike computation. In addition, the proposed dual-streams mechanism is similar to the dual-streams object recognition pathway in the human brain, which may provide a new potential direction for SNN structure design.
2303.06379
TaylorAECNet: A Taylor Style Neural Network for Full-Band Echo Cancellation
This paper describes aecX team's entry to the ICASSP 2023 acoustic echo cancellation (AEC) challenge. Our system consists of an adaptive filter and a proposed full-band Taylor-style acoustic echo cancellation neural network (TaylorAECNet) as a post-filter. Specifically, we leverage the recent advances in Taylor expansion based decoupling-style interpretable speech enhancement and explore its feasibility in the AEC task. Our TaylorAECNet based approach achieves an overall mean opinion score (MOS) of 4.241, a word accuracy (WAcc) ratio of 0.767, and ranks 5th in the non-personalized track (track 1).
Weiming Xu, Zhihao Guo
2023-03-11T11:12:49Z
http://arxiv.org/abs/2303.06379v1
# TaylorAECNet: A TaylorStyle Neural Network for Full-Band Echo Cancellation ###### Abstract This paper describes aecx team's entry to the ICASSP 2023 acoustic echo cancellation (AEC) challenge. Our system consists of an adaptive filter and a proposed full-band Taylor-style acoustic echo cancellation neural network (TaylorAECNet) as a post-filter. Specifically, we leverage the recent advances in Taylor expansion based decoupling-style interpretable speech enhancement [1] and explore its feasibility in the AEC task. Our TaylorAECNet based approach achieves an overall mean opinion score (MOS) of 4.241, a word accuracy (WAcc) ratio of 0.767, and ranks 5th in the non-personalized track (track 1). Weiming Xu\({}^{1,*}\), Zhihao Guo\({}^{2}\)\({}^{1}\)Audio, Speech and Language Processing Group (ASLP@NPU), Northwestern Polytechnical University, Xi'an, China \({}^{2}\)Elevoc, Shenzhen, China Acoustic echo cancellation, noise suppression, Taylor expansion ## 1 Introduction The acoustic echo cancellation (AEC) challenge series has provided a common platform to benchmark modern AEC techniques. The fourth edition of this challenge held in ICASSP2023 particularly addresses full-band signals with general AEC track and personalized AEC track. We submit a hybrid system to the general AEC track, which integrates a DSP based adaptive filter with a neural network based post filter. Recently, there has been a trend in interpretable speech enhancement by decoupling the difficult task into easier interpretable sub-tasks. Following this direction, TaylorSENet [1] imitates the form of Taylor expansion to split the denoising task into a combination of zero-order derivatives (in the real-valued domain) and multiple higher-order derivatives (in the complex-valued domain), achieving promising denoising performance. Inspired by this work, we propose a full-band Taylor-style acoustic echo cancellation neural network _TaylorAECNet_ as a post-filter cascaded with an adaptive filter to solve the full-band echo cancellation task. To reduce complexity, we design the Taylor-style decoupling network with only zero-order and first-order modules and made the following modifications to better fit the full-band residual echo removal task. * In order to utilize phase information for the zero-order module, a gated version of the phase encoder [2] is used instead of modulo operation to get the magnitude feature as zero-order module input. * Pseudo quadrature mirror filter bank (PQMF) is used to reduce the complexity caused by full-band signal processing. * Temporal and frequency convolution module (TFCM) [2] is introduced to improve the receptive field. Similar to [3], auxiliary voice activity detection (VAD) task is added and echo weighted loss is introduced. According to the challenge results, our system ranked 5th in the general AEC track. ## 2 Proposed Method The AEC task can be described as: \[d(n)=s(n)+h(n)*x(n)+v(n). \tag{1}\] The near-end microphone signal \(d(n)\) is composed of the near-end speech \(s(n)\), the background noise \(v(n)\), and the echo signal \(h(n)*x(n)\). The echo signal is generated by far-end signal \(x(n)\) propagated through echo path \(h(n)\), where \(n\) denotes the sample index. The AEC task is to cancel \(h(n)*x(n)\) from \(d(n)\) given \(x(n)\). As shown in Fig. 1, our system consists of a time delay estimation (TDE) module, an adaptive filter, and a full-band Taylor-style acoustic echo cancellation neural network (TaylorAECNet) as a post-filter. \(d(n)\) and \(x(n)\) are first aligned using GCC-PHAT as the TDE module to obtain the time-aligned reference signal \(x^{\prime}(n)\). The error signal \(e(n)\) is generated using \(x^{\prime}(n)\) and \(d(n)\) by an adaptive filter which is a partitioned-block-based frequency domain Kalman filter (PBFDKF). Finally, \(d(n)\), \(e(n)\) and \(x^{\prime}(n)\) are stacked and fed to the TaylorAECNet post-filter. ### TaylorAECNet post-filter TaylorAECNet consists of three modules, zero-order module (ZOM), first-order module (FOM) and voice activity detection (VAD) module shown as Fig. 2(a). As shown in Fig. 2(b), ZOM is designed as a classical UNet-style structure and it accepts the magnitude feature from the gated phase encoder. The encoder is a stack of Convolution-TFCM Block (CTBlocks), and each CTBlock contains a convolution layer followed by a batch normalization layer, leakyReLU layer and TFCM [2]. The decoder has the same structure as the encoder, but the convolution layer is replaced by the transpose convolution layer. We use dual path RNN (DPRNN) and squeezed temporal convolution module (STCM) [4] to further improve ZOM performance. Fig. 2(c) shows the detail of FOM which consists of several STCM layers and two convolution layers - a complex-to-real convolution layer and a complex-to-imaginary convolution layer. Figure 1: System diagram. The structure of the gated phase encoder is shown in Fig. 2(e), which is an improved version of phase encoder [2] with an additional gated convolution. Specifically, the gated phase encoder has three complex-valued convolution layers to receive \(D(t,f),E(t,f)\), and \(X(t,f)\) respectively. The complex-to-real layer consists of a complex-valued convolution layer and a modulo operation. We use a gated phase encoder instead of directly performing modulo operations on \(D(t,f)\), \(E(t,f)\), and \(X(t,f)\). We introduce a voice activity detection (VAD) module to improve the echo suppression performance. The VAD module is the same as that in [3]. By learning the VAD state of the microphone signal, the model will be more inclined to preserve near-end speech. ### Loss function We use echo weighted loss [3] with an extra asymmetric loss \(\mathcal{L}_{\text{asym}}\)[5]. The final loss function is \[\mathcal{L}=\mathcal{L}_{\text{echo-weighted}}+\mathcal{L}_{\text{asym}}+0.2 *\mathcal{L}_{\text{mask}}+0.1*\mathcal{L}_{\text{vad}}. \tag{2}\] The definition of \(L_{\text{mask}}\), \(L_{\text{echo-weighted}}\), and \(\mathcal{L}_{\text{vad}}\) remains the same as [3]. \(\mathcal{L}_{\text{echo-weighted}}\) makes the model pay more attention to the suppression of echoes by echo weighting but may cause distortion of the near-end speech. So, we add \(\mathcal{L}_{\text{asym}}\) to alleviate the distortion problem and constrain the spectrum. ## 3 Experiments ### Dataset We use the clean speech provided by the 5th deep noise suppression (DNS5) as the near-end signal and the reference signal. The noise set in DNS5 is used as the noise signal. For the echo signal, we use all the synthetic echo signals and real far-end single-talk recordings provided by the AEC challenge, which covers a variety of voice devices and echo signal delay. Furthermore, we also use speech in the DNS5 dataset to simulate echo data by convolving with 100,000 simulated room impulse responses (RIR) generated by the image method. The training set has 600 hours of data in total, consisting of 300 hours of data with simulated echo and 300 hours of data with real-recorded echo. The development and test sets share the same aforementioned generation method, which contains 10 and 5 hours of data, respectively. ### Experimental setup The proposed model uses a 20ms window length with a 10ms frame shift for STFT. Noam is adopted as the learning rate decreasing method described as \[lr=d^{-0.5}\cdot\min(\text{step}^{-0.5},\text{step}\cdot\text{warmup\_step}^{ -1.5}) \tag{3}\] where \(d=1e-3\) and warm_up=5000. All the models are trained with Adam optimizer for 10 epochs. The PQMF splits the signal into 4 sub-band signals. Each TFCM has 6 layers. The STCM in ZOM has 1 layer and 128 hidden channels while the STCM in FOM has 2 layers and 64 hidden channels. ### Results and analysis Table 1 shows the experimental results on the simulated test set. Ablation is studied on models trained using a subset with 100 hours of simulated data. Here base-TaylorAECNet is a simplified version for ablation, which removes TFCM and gate PE parts. When adding TFCM to base-TaylorAECNet, all our metrics on the test set are improved. Further adding the gated phase encoder, which results in the complete TaylorAECNet, the metrics for ST-FE and DT are improved, but the metric for ST-NE is slightly decreased. We finally train the complete TaylorAECNet using the entire 600 hours of data and the metrics on the simulated test set are shown in the last row of Table 1. We use this model to process the blind test clips and the challenge results are shown in Table 2. Our proposed TaylorAECNet approach surpasses the baseline by a large margin in both Overall MOS and WAcc. The Final Score of our system is 0.803 which outperforms the baseline with a 0.067 gain, leading to the 5th in the general AEC track. We perform ONNX implementation to the post filter for speed-up, the RTF of our proposed system is 0.224 tested on Intel(R) Xeon(R) Gold 5218 CPU @ 2.30GHz and the number of its parameters is 19.18M. ## 4 Conclusions In this paper, we introduce our system for ICASSP 2023 AEC Challenge. We combine a partitioned-block-based frequency domain Kalman filter (PBFDKF) with a proposed TaylorAECNet to suppress echo and noise. Gated phase encoder and TFCM are used for better latent feature extraction. A VAD module and echo-weighted loss are introduced to suppress residual echo and preserve near-end speech quality as well. According to the final results, the proposed system ranked 5th in the general AEC track.
2305.06785
Alternating mixed-integer programming and neural network training for approximating stochastic two-stage problems
The presented work addresses two-stage stochastic programs (2SPs), a broadly applicable model to capture optimization problems subject to uncertain parameters with adjustable decision variables. In case the adjustable or second-stage variables contain discrete decisions, the corresponding 2SPs are known to be NP-complete. The standard approach of forming a single-stage deterministic equivalent problem can be computationally challenging even for small instances, as the number of variables and constraints scales with the number of scenarios. To avoid forming a potentially huge MILP problem, we build upon an approach of approximating the expected value of the second-stage problem by a neural network (NN) and encoding the resulting NN into the first-stage problem. The proposed algorithm alternates between optimizing the first-stage variables and retraining the NN. We demonstrate the value of our approach with the example of computing operating points in power systems by showing that the alternating approach provides improved first-stage decisions and a tighter approximation between the expected objective and its neural network approximation.
Jan Kronqvist, Boda Li, Jan Rolfes, Shudian Zhao
2023-05-11T13:19:24Z
http://arxiv.org/abs/2305.06785v2
Alternating mixed-integer programming and neural network training for approximating stochastic two-stage problems+ ###### Abstract The presented work addresses two-stage stochastic programs (2SPs), a broadly applicable model to capture optimization problems subject to uncertain parameters with adjustable decision variables. In case the adjustable or second-stage variables contain discrete decisions, the corresponding 2SPs are known to be NP-complete. The standard approach of forming a single-stage deterministic equivalent problem can be computationally challenging even for small instances, as the number of variables and constraints scales with the number of scenarios. To avoid forming a potentially huge MILP problem, we build upon an approach of approximating the expected value of the second-stage problem by a neural network (NN) and encoding the resulting NN into the first-stage problem. The proposed algorithm alternates between optimizing the first-stage variables and retraining the NN. We demonstrate the value of our approach with the example of computing operating points in power systems by showing that the alternating approach provides improved first-stage decisions and a tighter approximation between the expected objective and its neural network approximation. Keywords:Stochastic Optimization Neural Network Power Systems. ## 1 Introduction The area of mathematical optimization often assumes perfect information on the parameters defining the optimization problem. However, in many real-world applications, the input data may be uncertain. The uncertain parameters when optimizing power systems can, e.g., be the power output of wind and solar power units or hourly electricity demands. To address this challenge, two major approaches have been developed in the current literature, namely, robust optimization (RO), see, e.g., [1] for further details and stochastic optimization (SO), see, e.g., the seminal surveys [3] and [21]. In RO, only limited information on the underlying distribution of uncertainties is available, e.g., that the uncertain parameter vector belongs to a polyhedron, and the goal is to protect against the worst possible outcome of the uncertainty. In SO, it is typically assumed that the underlying probability distribution of the uncertain parameters is known, or at least that representative samples are available. Here, often the goal is to optimize over the expectation of the uncertain parameters, which results in less conservative solutions compared to RO. The ability to handle uncertainties makes both methods valuable in power-system-related optimization. A comparison between RO and SO for unit commitment with uncertain renewable production is presented in [13]. However, SO tends to be more prevalent in power system operation optimization, as operating scenarios are readily available. Applications of SO include the optimal operation of high-proportion renewable energy systems [23, 32, 38], pricing of energy and reserves in electricity markets [35, 7, 39] or day-ahead power scheduling [36, 30, 24] - to name a few. Moreover, in some real-world applications, not all the decisions have to be taken before the uncertainty realizes. Here, we distinguish between _first-stage_ or here-and-now decisions and _second-stage_ or wait-and-see decisions. These _stochastic two-stage_ problems or _2SP_s have drawn significant attention over the last years, both due to the practical applicability and computational challenges. Methods for dealing with 2SPs include L-shaped methods [20], Lagrangian relaxation-based methods [6], and the sample average approach of Kleywegt et al. [15]. For more information on 2SP and algorithmic approaches, we refer to [33, 19, 8] and the references therein. Here, we focus on 2SPs, where the uncertainties either belong to a bounded discrete distribution or can be approximated sufficiently close by such a distribution. Consequently, we can restrict ourselves to a finite set of scenarios. Furthermore, we are assuming some of the second-stage variables are restricted to integer values and that all constraints are linear. For such problems, it is possible to represent the 2SP as a classical single-stage mixed-integer linear program (MILP) through the so-called deterministic equivalent [3]. The deterministic equivalent formulation creates one copy of the second-stage variables and constraints for each scenario, thus resulting in a potentially huge MILP problem. Especially if the second stage involves many integer variables, it may be computationally intractable to consider a large number of scenarios. To overcome this issue, Dumouchelle et al. [8] proposed the so-called Neur2SP approach,where the value function, i.e., the optimal objective value of the second stage, is approximated by a neural network (NN). By selecting a MILP representable NN architecture, e.g., ReLU activation functions [22, 9, 34], the NN approximation of the second-stage problem along with the first-stage problem can then be integrated into a single stage MILP. The advantage of this approach is that the MILP presentation of the NN can require far fewer variables and constraints than forming the deterministic equivalent. The potential drawback is that we only utilize an approximation of the expected value of the second-stage problem. We build upon the approach presented by Dumouchelle et al. [8] and investigate the proposed algorithm for an application in optimizing power systems. We show that proper training of the NN is crucial, and we propose a dynamic sampling as a training method. Here, we directly train a NN to approximate the expected value function. Our approach can be viewed as a surrogate-based optimization [2, 10] approach for 2SPs, as we are iteratively forming a surrogate of the expected value function which is globally optimized to find a new solution and to improve the approximated expected value function. The proposed algorithm is not limited to the specific application in Section 3, but applicable to any 2SP of suitable structure, e.g., see the applications used in [8]. For the application of finding optimal operating points of a power grid considered in the present article, the existing approaches in the power system literature usually approximate the integer variables in the second stage, e.g. by ignoring the action variable of energy storage, see [5] or only search for a local optimum of the model, e.g. by applying an augmented Benders decomposition algorithm, see [4]. Thus, the Neur2SP approach keeps the underlying integral structure of the second-level, while at the same time aims for a global optimum. The outline of the present article is as follows. In Section 2, we present the stochastic programming formulation [8] and discuss our methodology. Then, we connect this modeling to achieve data-driven operating states of smart converters in power systems in Section 3. Subsequently, we present a numerical comparison between these data-driven results with a baseline algorithm based on the Neur2SP framework in Section 4. ## 2 Replacing the second-stage in stochastic programming by a neural network The two-stage stochastic programming consists of two types or _levels_ of decision variables. The _first-level_ variables, denoted by \(x\in\mathcal{X}\), describe an initial planning approach. Then, a random vector \(\xi\in\Omega\) supported on a compact domain \(\Omega\subseteq\mathbb{R}^{I}\) and distributed by a probability distribution \(\mathbb{P}\in\mathcal{P}(\Omega)\) affects the outcome of this initial planning. However, one can adjust the initial planning \(x\) after the random vector \(\xi\) realizes by choosing the _second-level or recourse_ variables \(y\in\mathcal{Y}(x,\xi)\), wherein the present article, we suppose that \(\mathcal{Y}(x,\xi)\subseteq\mathbb{R}^{n}\times\{0,1\}^{l}\) is assumed to be defined through linear constraints. Thus, we can summarize a _stochastic two-stage problem_ as follows: \[\min_{x\in\mathcal{X}}\;G(x)+\mathbb{E}_{\mathbb{P}}\left(\min_{y\in\mathcal{Y }(x,\xi)}c^{\top}y\right), \tag{1}\] where in this article \(\mathcal{X}\) and \(\Omega\) are assumed to be polytopes, \(c\) denotes the objective coefficients, and \(\mathcal{Y}(x,\xi)\) a polytope intersected with an integer lattice. Note, that (1) is considered to be a challenging problem as it contains the NP-complete MIP \(\min_{y\in\mathcal{Y}(x,\xi)}c^{\top}y\) as a subproblem. Moreover, stochastic two-stage problems are in general notoriously challenging, see e.g., Section 3 in [21] for an overview. In the present article, we restrict ourselves to the estimated expected value \[\min_{x\in\mathcal{X}}\ G(x)+\frac{1}{m}\sum_{j=1}^{m}\left(\min_{y\in\mathcal{Y}( x,\xi_{j})}c^{\top}y\right), \tag{2}\] where \(\xi_{j}\) denote scenarios sampled from \(\mathbb{P}\). For the numerical experiments in Section 4, we limit the number of scenarios to \(m=400\). We then aim to learn the mapping \[Q(x)\coloneqq\frac{1}{m}\sum_{j=1}^{m}\left(\min_{y\in\mathcal{Y}(x,\xi_{j})}c ^{\top}y\right)\] by training a series of neural networks inspired by the Neur2SP framework developed in [8]. However, in contrast to the approach in [8], we aim to learn the mapping \(x\mapsto Q(x)\), by training a series of neural networks with iteratively generated training data instead of predefined data, see Algorithm 1. ### Embedding the neural network into 2SP We approximate the map \(x\to Q(x)\) by training a fully-connected neural network with 2-hidden layers, where both layers have 40 neurons, denoted as NN \(2\times 40\). Hence, the relation between \(l\)-th layer input \(x^{l}\in\mathbb{R}^{n_{l}}\) and output \(x^{l+1}\in\mathbb{R}^{n_{l+1}}\) in such neural network with the ReLu activation function is \[x^{l+1}=\max\{0,W^{l}x^{l}+b^{l}\}, \tag{3}\] where \(W^{l}\in\mathbb{R}^{n_{l+1}\times n_{l}}\) is the weight matrix and \(b^{l}\in\mathbb{R}^{n_{l+1}}\) is the bias vector. The ReLu activation function is piece-wise linear and the big-M formulation was the first presented to encode it and is still common [9, 22]. In this way, with binary variable \(\sigma^{l}\in\mathbb{R}^{n_{l+1}}\), (3) is equivalent to \[\begin{split}(w_{i}^{l})^{\top}x^{l}+b_{i}^{l}& \leq x_{i}^{l+1},\\ (w_{i}^{l})^{\top}x^{l}+b_{i}^{l}-(1-\sigma_{i}^{l})LB_{i}^{l+1}& \geq x_{i}^{l+1},\\ x_{i}^{l+1}&\leq\sigma_{i}^{l}UB_{i}^{l+1},\\ \sigma_{i}^{l}&\in\{0,1\},\ x_{i}^{l+1}\geq 0, \forall i\in[n_{l+1}],\end{split} \tag{4}\] where \(w_{i}^{l}\) is the \(i\)-th row vector of \(W^{l}\), \(b_{i}^{l}\) is the \(i\)-th entry of \(b^{l}\), \(LB_{i}^{l+1}\) and \(UB_{i}^{l+1}\) are upper and lower bounds on the pre-activation function over \(x_{i}^{l+1}\), such that \(LB_{i}^{l+1}\leq(w_{i}^{l})^{\top}x^{l}+b_{i}^{l}\leq UB_{i}^{l+1}\). Encoding ReLu functions has been an active research topic in recent years, as it enables a wide range of applications of mixed-integer programming to analyze and enhance NNs, such as generating adversarial examples [9], selecting optimal inputs of the training data [18, 40], lossless compression [29], and robust training [28]. By encoding the trained NN as (4), we can approximate (1) by the following MIP: \[\min G(x^{1})+x^{L}\] (5a) s.t. \[W^{l}x^{l}+b^{l}\leq x^{l+1}, \forall\ l\in[L-1], \tag{5b}\] \[W^{l}x^{l}+b^{l}-\mathrm{diag}(LB^{l+1})(\mathbf{1}-\sigma^{l+1}) \geq x^{l+1}, \forall\ l\in[L-1],\] (5c) \[x^{l}\leq\mathrm{diag}(UB^{l})\sigma^{l}, \forall\ l\in\{2,\ldots,L\},\] (5d) \[x^{L}=W^{L-1}x^{L-1}+b^{L-1},\] (5e) \[\sigma^{l}\in\{0,1\}^{n_{l}}, \forall\ l\in\{2,\ldots,L\},\] (5f) \[x^{l}\in\mathbb{R}_{+}^{n_{l}}, \forall\ l\in[L-1],\] (5g) \[x^{1}\in\mathcal{X},x^{L}\in\mathbb{R}, \tag{5h}\] where \(x^{1}\coloneqq x\) is the input-layer variable that belongs to the polytope \(\mathcal{X}\), and \(x^{L}\) is the output of the neural network which approximates the expected value \(Q(x^{1})\). ### Alternating MIP and NN training Since the approximation quality of (5) with regards to (2) highly depends on the accuracy of the neural network, the approach has significant drawbacks for problems with high dimensional first-level decisions, i.e., high-dimensional \(\mathcal{X}\). This drawback becomes even more significant as optimal solutions for (2) are often attained at the boundary or even vertices of \(\mathcal{X}\). Here, the approximation by the neural network tends to be worse due to a lack of training data around the vertices. Note that, sampling around each vertex is typically computationally intractable as there are potentially exponentially many such vertices. The approach we propose in the present article uses intermediate solutions of (5) to inform the retraining of neural networks. To this end, after training the NN with an initial uniformly distributed sample of \(\mathcal{X}\), we solve (5) and add sample points around the computed optimal solution \(x_{k}^{*}\) to our training data. Algorithm 1 illustrates our approach. We would like to stress, that the number of additional datapoints in every iteration \(k\) as well as the parameter \(\alpha\) towards \(x_{k}^{*}\) are chosen arbitrarily. Thus, more careful choices of these parameters may give room for significant improvement of the performance of Algorithm 1. Here, we would like to briefly comment on the relative computational expenses of the different parts of Algorithm 1. We specify the considered application as well as our computational ressources in Section 4. The most time-consuming computation of Algorithm 1 includes solving optimization problems (5) and \(\min_{y\in\mathcal{Y}(x,\xi)}c^{\top}y\). With the default settings, Gurobi [11] can solve (5) encoding an NN \(2\times 40\) within 5 seconds on a standard notebook. Moreover, the generation of new training data (see line 6-10), i.e., the optimization for each scenario \(\xi\), can be solved in parallel, where solving the problem \(\min_{y\in\mathcal{Y}(x,\xi)}c^{\top}y\) with a pair \(x\) and \(\xi\) only takes 0.03 seconds. ``` 1:Input Initial training data \(\tilde{\mathcal{X}}\), \(\alpha=0.99\) 2:Output Approximately optimal solution \(x_{100}^{*}\) for (1) 3: Train a NN \(2\times 40\) with training data set \(\tilde{\mathcal{X}}\) 4:for\(k=1,\ldots,100\)do 5:\(x_{k}^{*}\leftarrow\operatorname*{argmin}\eqref{eq:x_k}\) 6:for\(i=1,\ldots,50\)do 7: Sample \(x_{i}\in X\) uniformly 8:\(x_{i}\leftarrow\alpha x_{k}^{*}+(1-\alpha)x_{i}\) 9:\(\tilde{\mathcal{X}}\leftarrow\tilde{\mathcal{X}}\cup\{x_{i}\}\) 10:endfor 11: Retrain NN with \(\tilde{\mathcal{X}}\) 12:endfor ``` **Algorithm 1** Alternating MIP-NN Algorithm for 2SP (MIP-NN 2SP) ## 3 Application to smart converters in power system networks In order to assess the practical value of the above approach, we apply it to a power system with smart inverters and energy storage. Its effects include reducing power generation costs and improving operational performance are then observed. Since the proposed heuristic given by Algorithm 1 may compute first-stage decisions \(x\) that lead to an empty second-stage, i.e., \(\mathcal{Y}(x,\xi)=\emptyset\), we assume in the remainder of this article that every feasible \(x\in\mathcal{X}\) leads to non-empty \(\mathcal{Y}(x,\xi)\) for every scenario \(\xi\). In particular, this assumption is valid whenever, we discuss a value function \(Q:\mathcal{X}\times\Omega\to\mathbb{R},Q(x,\xi)\coloneqq\min_{y\in\mathcal{Y} (x,\xi)}c^{\top}y\) as is often the case in the existing literature, see e.g. [8], and also justified as the discussion in Section 2.1 in [31] illustrates. Nevertheless, it is crucial to verify whether this assumption actually holds. For the power system application studied below however, numerical experiments indicate, that a feasible, but potentially costly \(y\in\mathcal{Y}(x,\xi)\), exists and thus the use of neural networks will not have an adverse impact on the feasibility of the problem. Moreover, from an engineering perspective, the power system has a slack node, see \(b_{1}\) in Figure 1, that ensures stable operation when the system deviates from the set points, although again the operating cost may increase significantly. On the contrary, it can effectively improve the computational efficiency of the solution. The reasons are as follows: 1. This paper establishes a two-stage optimization model to solve the day-ahead scheduling strategy of the power system (i.e., the first-stage strategy). We only use neural networks to replace the optimization model in the second stage. The first-stage decisions still satisfy the corresponding hard constraints (e.g., power balance). 2. The second-stage optimization model corresponds to the intra-day operation of the power system. In the cases studied by this paper, the system is connected to the external grid and has energy storage inside as a buffer to balance the energy. From the perspective of practical engineering experience, when the decisions of the first stage are within a reasonable range, the operation strategy of the second stage is usually feasible. Therefore, it is reasonable to use the first-stage decision variables to estimate the operating cost of the second stage through a neural network. 3. In practical operations, the day-ahead operation (i.e., the first stage) needs to obtain results within tens of minutes. When there are a large number of integer variables in the second stage of the 2SP (energy storage requires frequent changes in operational states, which introduces a large number of binary variables into the second stage), this runtime requirement is difficult to guarantee. However, since replacing the second stage of (2) by a neural network can significantly reduce the runtime, Algorithm 1 has the potential to be applicable in practice. A simplified DC power flow model, following Kirchhoff laws, is adopted to describe the energy balance and power flow in the power system. We follow closely the notations by [37] and the presentation in [16] in order to specify the parameters present in (1). Consider a power grid equipped with a set of buses \(\mathcal{B}\) and a set of lines/branches \(\mathcal{L}\). Within the grid, power is generated by a set of conventional (fossil fuel) generators denoted by \(\mathcal{N}_{G}\) or by a set of distributed (renewable) generators denoted by \(\mathcal{N}_{DG}\). The _system operator_ (SysO) may decide, whether to * store or release power to/from a set of batteries \(\mathcal{N}_{S}\) * purchase or sell power on the day-ahead market or intra-day, this power enters/leaves the power system through a trading node with the main grid The amount of power traded day-ahead, i.e., on the day-ahead or _first-level market_ is denoted by \(P_{fl}\) and the corresponding market price by \(p_{fl}\). Similarly, the amount of power and the market price traded intra-day is denoted by \(P_{sl}\) and \(p_{sl}\), respectively. A positive value for \(P_{fl},P_{sl}\) is interpreted as a purchase, negative values as a sell \(P_{fl},P_{sl}\) of energy. The SO's initial planning, refers to deciding the first-level variables \(x=(P_{G}^{\top},P_{fl})^{\top}\in\mathbb{R}^{\mathcal{N}_{G}}\times\mathbb{R}\) based on the estimated renewable energy production \(P_{DG,forecast}\in\mathbb{R}^{\mathcal{N}_{DG}}\) in order to ensure that a given total demand \(\sum_{i\in\mathcal{B}}P_{d_{i}}\) is met. Hence, \[\mathcal{X}=\{x\in\mathbb{R}^{n}:\ \eqref{eq:pfl}\ \&\ \eqref{eq:pfl}\},\] where \[P_{fl}^{t}=\sum_{i\in\mathcal{B}}P_{d_{i}}^{t}-\sum_{i\in \mathcal{N}_{G}}P_{G_{i}}^{t}-\sum_{i\in\mathcal{N}_{DG}}P_{DG_{i},forecast} \forall t\in T, \tag{6a}\] \[P_{G_{i},\min}^{t}\leq P_{G_{i}}^{t}\leq P_{G_{i},\max} \forall i\in\mathcal{N}_{G},t\in T, \tag{6b}\] with given parameters \(P_{G,\min},P_{G,\max}\in\mathbb{R}^{\mathcal{N}_{G}\times T}\). Note that the _market-clearing condition_ (6a) ensures the active power balance in the whole system. The objective of the first level in (1) is then given by \[G(x)=x^{\top}\text{Diag}(c_{2})x+c_{1}^{\top}x+c_{0},\] where \(c_{2},c_{1}\in\mathbb{R}^{\mathcal{N}_{G}},c_{0}\in\mathbb{R}\) are given generator cost parameters. Since the uncertainties will impact the initial planning and may jeopardize the power balance, we consider the capacity of the renewable generators as uncertain, i.e., we denote the second-level variable by \(\xi=P_{DG,\max}\in\mathbb{R}^{\mathcal{N}_{DG}\times T}\). As these generators are dependent on weather conditions, which are highly uncertain, this is one of the most common uncertainties faced by modern power grids with a high proportion of renewable energies [27, 12]. To this end, we draw samples from the following domain \[\Omega=\left\{P_{DG,\max}\in\mathbb{R}^{\mathcal{N}_{DG}\times T}:\ 0\leq P_{DG_{i},\max}^{t}\leq P_{i}^{+}\ \forall\ i\in\mathcal{N}_{DG},t\in T\right\}, \tag{7}\] where \(P_{i}^{+}\) denotes the technical limit of the renewable generator, i.e. its capacity under optimal conditions. In particular, since the capacity of the renewable generators is further limited by the weather conditions. For our computational results in Section 4, we assume that without these limitations \(P_{DG_{i},\max}\) are independently distributed according to a normal distribution, i.e. \(P_{DG_{i},\max\text{-}\text{vol}}\sim\mathcal{N}(P_{DG_{i},forecast},0.1\cdot P _{DG_{i},forecast})\). Consequently, every realization of \(P_{DG_{i},\max\text{-}\text{vol}}\) leads naturally to a sample point \[\xi_{DG_{i}}=P_{DG_{i},\max}=\begin{cases}0&\text{if }P_{DG_{i},\max\text{-} \text{vol}}\leq 0\\ P_{DG_{i},\max\text{-}\text{vol}}&\text{if }P_{DG_{i},\max\text{-}\text{vol}} \in(0,P_{i}^{+})\\ P_{i}^{+}&\text{if }P_{DG_{i},\max\text{-}\text{vol}}\geq P_{i}^{+}.\end{cases}\] On the third level, the SysO adjusts the initial planning according to this realization. In particular, the SysO might regulate the energy output of the conventional generators \(P_{G}\) to \(P_{G,\text{reg}}\) by either increasing the production by adding \(P_{G}^{+}\geq 0\) at a cost \(r^{+}\) or decreasing the production by adding \(P_{G}^{-}\leq 0\) at a cost \(r^{-}\). Similarly, \(P_{DG}\in[0,\xi_{DG}]\) is the adjusted energy production that deviates from its forecast by \(P_{DG}^{+}\) or \(P_{DG}^{-}\) with deviations penalized by \(f^{+},f^{-}\) respectively. Moreover, the SysO might also trade power intra-day (\(P_{sl}\)) or decide to use the batteries by setting \((\mu_{ch},\mu_{dch}\in\{0,1\}^{\mathcal{N}_{S}})\) and change the charging/discharging quantity \(P_{ch},P_{dch}\) in order to balance a potential power deficiency or surplus. Based on these decisions, the following variables vary accordingly: The _state of charge_ of a storage, denoted by soc, the power on a line \((k,l)\in\mathcal{L}\), denoted by \(p_{kl}\) and the phase angles of the system, denoted by \(\theta\). Thus, the SysO adjusts the vector \(y=(P_{G_{i},\text{reg}},P_{G_{i}}^{+},P_{G_{i}}^{-},P_{DG_{i}},P_{DG_{i}}^{+}, P_{DG_{i}}^{-},P_{sl},P_{ch_{i}},P_{dch_{i}},p_{kl},\theta,\text{soc},\mu_{ ch},\mu_{dch})^{\top}\) in order to satisfy \[y\in\mathcal{Y}(x,h)\coloneqq\left\{y\in\mathbb{R}^{m}:\ \text{(\ref{eq:p_1})}- \text{(\ref{eq:p_2})}\right\},\] where the constraints (8a)-(12g) are given below: 1. First, we consider the _Generator and DG output constraints_: \[P^{t}_{G_{i},\mathrm{reg}}=P^{t}_{G_{i}}+P^{t,+}_{G_{i}}+P^{t,-}_{G_ {i}} \forall i\in\mathcal{N}_{G},t\in T,\] (8a) \[P^{t}_{G_{i},\min}\leq P^{t}_{G_{i},\mathrm{reg}}\leq P^{t}_{G_{i },\max} \forall i\in\mathcal{N}_{G},t\in T,\] (8b) \[P^{t}_{DG_{i}}=P^{t}_{DG_{i},\mathrm{forecast}}+P^{t,+}_{DG_{i}}+ P^{t,-}_{DG_{i}} \forall i\in\mathcal{N}_{DG},t\in T,\] (8c) \[P^{t}_{DG_{i},\min}\leq P^{t}_{DG_{i}}\leq P^{t}_{DG_{i},\max} \forall i\in\mathcal{N}_{DG},t\in T,\] (8d) \[P^{t}_{sl}-P^{t}_{fl}=-\mathbb{1}^{\top}(P^{t,+}_{G}+P^{t,-}_{G}) -\mathbb{1}^{\top}(P^{t,+}_{DG}+P^{t,-}_{DG})\] \[-\mathbb{1}^{\top}(P^{t}_{dch}-P^{t}_{ch}) \forall t\in T.\] (8e) Here, Constraints (8a)-(8d) describe the output range of the conventional and renewable generators. In particular, (8d) shows that the third-level variables \(P^{t}_{DG_{i}}\) are restricted by the uncertainties realized in the second level (\(P^{t}_{DG_{i},\max}\)). The market clearing on the intra-day market, i.e., the actual power demand-supply relations, is reflected by Constraint (8e). 2. Second, we consider the _operation constraints_: \[0\leq P^{t,+}_{G_{i}}\leq P^{t,+}_{G_{i},\max} \forall i\in\mathcal{N}_{G},t\in T,\] (9a) \[P^{t,-}_{G_{i},\min}\leq P^{t,-}_{G_{i}}\leq 0 \forall i\in\mathcal{N}_{G},t\in T,\] (9b) \[P^{t,+}_{DG_{i}}\geq 0 \forall i\in\mathcal{N}_{DG},t\in T,\] (9c) \[P^{t,-}_{DG_{i}}\leq 0 \forall i\in\mathcal{N}_{DG},t\in T,\] (9d) where Constraints (9a) -(9d) limit the real output derivations of conventional and renewable generators. 3. Third, we consider the _power flow constraints_. To this end, we apply a DC approximation for a given line reactance (\(x_{ij}>0\)) and demand in active power (\(P^{d,t}_{k}\)) at every time step \(t\) and bus \(k\): \[\sum_{l\in\delta(k)}p^{t}_{kl}= \sum_{i\in\mathcal{N}_{G}:i\sim k}P^{t}_{G_{i},\mathrm{reg}}+\sum _{i\in\mathcal{N}_{DG}:i\sim k}P^{t}_{DG_{i}}\] \[+\sum_{i\in\mathcal{N}_{S}:i\sim k}(P^{t}_{dch_{i}}-P^{t}_{ch_{i} })-P^{d,t}_{k} \forall k\in\mathcal{B}\setminus\{0\},t\in T,\] (10a) \[\sum_{l\in\delta(k)}p^{t}_{0l}= \sum_{i\in\mathcal{N}_{G}:i\sim 0}P^{t}_{G_{i},\mathrm{reg}}+\sum _{i\in\mathcal{N}_{DG}:i\sim 0}P^{t}_{DG_{i}}\] \[+\sum_{i\in\mathcal{N}_{S}:i\sim 0}(P^{t}_{dch_{i}}-P^{t}_{ch_{i} })+P^{t}_{sl}-P^{d,t}_{0} \forall t\in T,\] (10b) \[p^{t}_{ij}= \frac{1}{x_{ij}}(\theta^{t}_{i}-\theta^{t}_{j}) \forall\{i,j\}\in\mathcal{L},t\in T,\] (10c) where (10a) establishes the nodal power flow balance for every node except the root node, which is addressed separately in (10b). The branch power flow is modeled through (10c). 4. Fourth, we consider the _branch thermal constraints_ that guarantee, that the power flow does not exceed the branch's capacities: \[p^{t}_{ij}\leq s_{ij,\max} \forall\{i,j\}\in\mathcal{L},t\in T.\] (11a) 5. Fifth, we consider the _storage constraints_. To this end, note that the storage operation involves two actions, the storage action is represented by two binary variables \(\mu_{ch},\mu_{dch}\in\{0,1\}^{\mathcal{N}_{S}\times T}\), whereas the quantity of the charging/discharging is represented by continuous variables \(P^{t}_{ch_{i}},P^{t}_{dch_{i}}\). Thus, we have the following constraints: \[\operatorname{soc}^{t}_{i,\min}\leq\operatorname{soc}^{t}_{i} \leq\operatorname{soc}^{t}_{i,\max} \forall i\in\mathcal{N}_{S},t\in T,\] (12a) \[\operatorname{soc}^{t}_{i}=\operatorname{soc}^{t-1}_{i}+\frac{( P^{t}_{ch_{i}}-P^{t}_{dch_{i}})}{E_{i}}\Delta T \forall i\in\mathcal{N}_{S},t\in T,\] (12b) \[P^{t}_{ch_{i}},P^{t}_{dch_{i}}\geq 0 \forall i\in\mathcal{N}_{S},t\in T,\] (12c) \[\mu^{t}_{ch_{i}},\mu^{t}_{dch_{i}}\in\{0,1\} \forall i\in\mathcal{N}_{S},t\in T,\] (12d) \[\mu^{t}_{ch_{i}}P^{t}_{ch_{i},\min}\leq P^{t}_{ch_{i}}\leq\mu^{t} _{ch_{i}}P^{t}_{ch_{i},\max} \forall i\in\mathcal{N}_{S},t\in T,\] (12e) \[\mu^{t}_{dch_{i}}P^{t}_{dch_{i},\min}\leq P^{t}_{dch_{i}}\leq\mu^{t }_{dch_{i}}P^{t}_{dch_{i},\max} \forall i\in\mathcal{N}_{S},t\in T,\] (12f) \[\mu^{t}_{ch_{i}}+\mu^{t}_{dch_{i}}\leq 1 \forall i\in\mathcal{N}_{S},t\in T.\] (12g) Here, the upper/lower bounds of \(\operatorname{soc}\), as well as the relationships between \(\operatorname{soc}\) and charging/discharging actions, are given by Constraints (12a) and (12b). The connection between the storage actions and the respective quantity is reflected by Constraints (12c) - (12g). Lastly, the third-level cost function aims to both, minimize the electricity cost as well as reduce the deviation between the intra-day system operation strategy and the day-ahead planning. Thus, the whole adjustment can be summarized as solving \[\min_{y\in\mathcal{Y}(x,\xi)}c^{\top}y, \tag{13}\] where \[c^{\top}y\coloneqq\sum_{t\in T}\sum_{i\in\mathcal{N}_{G}}(r^{+,t}_{i}P^{+,t}_ {G_{i}}+r^{-,t}_{i}P^{-,t}_{G_{i}})+p^{t}_{sl}(P^{t}_{sl}-P^{t}_{fl})+\sum_{i \in\mathcal{N}_{DG}}(f^{+}_{i}P^{t,+}_{DG_{i}}+f^{-}_{i}P^{t,-}_{DG_{i}}).\] After having established the model parameters for (1), we continue with a case study in order to demonstrate the practical value of Algorithm 1. ## 4 Computational results In this section, we present a case study, where we consider the daily power distribution of a 5-bus instance, based on the "case5.m" instance from the matpower library [41]. Here, the day is divided into hourly (24 period) time intervals. The MIP problems in Algorithm 1 are solved by Gurobi [11], which is the state-of-art MIP solver. The computations were executed via Gurobi 10.0.0 under Python 3.7 on a Macbook Pro (2019) notebook with an Intel Core i7 2,8 GHz Quad-core and 16 GB of RAM. The neural network is trained with PyTorch [25]. The network topology of "case5.m" is illustrated in Figure 1, where we assume bus 1 to be the slack node, i.e., the trading node connected to other grids. Since the type of generators is not specified in [41] and this study solely serves as an academic example, we chose whether a generator in "case5.m" is a conventional/renewable one or a storage in the following convenient way: The conventional (fossil fuel) generators are connected to the buses 1 and 4, i.e. \(\mathcal{N}_{G}=\{1,4\}\), two distributed generators are connected to buses 1 and 5, i.e., \(\mathcal{N}_{DG}=\{1,5\}\) and an energy storage unit is connected to bus 3, i.e. \(\mathcal{N}_{S}=\{3\}\). In order to aid reproducibility and encourage further research on this topic, we provide the underlying system data for public use, see [17]. Incorporating the instance data closely follows the methodology used in [16]. Hence, both, the day-ahead and intra-day market prices \(p_{fl},p_{sl}\) were taken as averages from the Pecan street database's [26] "miso" data set for March 3rd, June 3rd, October 3rd and December 2nd, 2022. Daily deviations in \(P^{d}\), denoted by \(\Delta^{t}_{d}\), or daily deviations in \(P^{t}_{DG,\max}\), denoted by \(\Delta^{t}_{DG}\) were taken from the Pecan street database's "california_iso" dataset for the same days, 2022 in the same way. In particular, we also provide the underlying weather data for public use, see [17]. Figure 1: The case5.m network with its corresponding generators and an exemplary power flow. \(P^{d}=0\) at buses 1 and 5 Consequently, we model the daily varying demand by \(P^{d}=P^{d}\cdot\Delta_{d}^{t}\) and the varying potential renewable energy production by \[P_{DG,\text{forecast}}^{t}\coloneqq\min\left\{\frac{P_{DG,\min}+P_{DG,\max}}{2} \cdot\Delta_{DG}^{t},P_{i,t}^{+}\right\}.\] After incorporating this data, we compare the solutions given by Algorithm 1 to a baseline experiment, where we replace line 6-10 by adding 50 uniformly distributed sample points drawn from \(\mathcal{X}\) in each iteration \(k\). This algorithm is inspired by [8] and simply creates the same amount of sample points, but does not incorporate targeted information around \(x_{k}^{*}\). We chose 3000 uniformly distributed datapoints from \(\mathcal{X}\) as a starting dataset for both algorithms. We use trained neural networks with the same architecture for both experiments, i.e., NN \(2\times 40\). In Figure 2, MIP-NN_2SP_NN (resp. Baseline_NN) denotes the objective function value of (5) solved by Algorithm 1 (resp. the baseline experiment) at Figure 2: Comparison of Algorithm 1 (in green and red) to successively adding batches of 50 uniformly distributed data points (in blue and orange) with respect to operating costs in $ for weather data of different seasons. each iteration. In particular, we include \(G(x_{k}^{*})+\frac{1}{400}\sum_{j=1}^{400}Q(x_{k}^{*},\xi_{j})\), denoted by MIP-NN_2SP_E (resp. Baseline_E), with optimal solutions \(x_{k}^{*}\) of line 5 from Algorithm 1 (resp. the baseline experiment). In this way, the difference between MIP-NN_2SP_NN (resp. Baseline_NN) and MIP-NN_2SP_E (resp. Baseline_E) measures the quality of the approximation by the neural networks at each iteration. Observe, that after \(100\) iterations, the baseline experiment cannot close the gap between the estimated expected value of the second stage (i.e., Baseline_E) and its neural network approximation (i.e., Baseline_NN) since a gap of \(80,000\$\) remains. In other words, the difference between the NN approximation and the expected value is \(80,000\$\). While including targeted datapoints in the proposed sampling approach significantly reduces the gap between MIP-NN_2SP_NN and MIP-NN_2SP_E. Thus, showing that the dynamic sampling in Algorithm 1 clearly outperforms sampling uniformly distributed and results in a much more accurate approximation of the expected value. Moreover, the results indicate, that the operating state of the conventional generators computed from the baseline experiment is not optimal, and approximately \(20,000\$\) may be saved by using the operating states computed by Algorithm 1. The results, thus, show the importance of obtaining an accurate approximation of the expected value function. ## 5 Conclusion and Outlook We have presented an algorithm for solving 2SP problems with integer second-stage variables by iteratively constructing a NN that approximates the expected value of the second-stage problem. This approach is inspired by the work of [8]. In the algorithm, we propose a dynamic sampling and retraining of the NN to improve the approximation in regions of interest. We numerically evaluate the algorithm in a case study of optimizing a power system. The numerical results highlight the importance of obtaining an accurate approximation of the expected value function and show that a poor approximation can lead to a suboptimal solution. The results strongly support the proposed sampling and retraining approach, and by the smart selection of data points we are able to obtain a much better approximation in the regions of interest compared to a simple uniform sampling. For the baseline, using uniform sampling, the accuracy does not seem to improve even after doubling the number of data points. Whereas, the proposed algorithm quickly obtains an NN that seems to closely approximate the expected value function, at least in the neighborhood of the minimizer of the NN approximated 2SP (5). The results, thus, support the idea of approximating the expected value function by an NN and using a MILP encoding of the NN to form a single-stage problem, but clearly show the importance of efficiently training a NN to high accuracy in the regions of interest. As Algorithm 1 delivers promising numerical results on the considered power system, it is natural to ask, whether these results extend to the benchmark problems given in [8], i.e. Capacitated Facility location, Investment, Stochastic server location and pooling problems. Moreover, also extensions to ACOPF models similarly to the ones in [14] may pose interesting challenges for future research. #### Acknowledgements We would like to thank the anonymous referees for their very valuable comments, that helped to significantly improve the quality of this article.
2305.17688
Amplification trojan network: Attack deep neural networks by amplifying their inherent weakness
Recent works found that deep neural networks (DNNs) can be fooled by adversarial examples, which are crafted by adding adversarial noise on clean inputs. The accuracy of DNNs on adversarial examples will decrease as the magnitude of the adversarial noise increase. In this study, we show that DNNs can be also fooled when the noise is very small under certain circumstances. This new type of attack is called Amplification Trojan Attack (ATAttack). Specifically, we use a trojan network to transform the inputs before sending them to the target DNN. This trojan network serves as an amplifier to amplify the inherent weakness of the target DNN. The target DNN, which is infected by the trojan network, performs normally on clean data while being more vulnerable to adversarial examples. Since it only transforms the inputs, the trojan network can hide in DNN-based pipelines, e.g. by infecting the pre-processing procedure of the inputs before sending them to the DNNs. This new type of threat should be considered in developing safe DNNs.
Zhanhao Hu, Jun Zhu, Bo Zhang, Xiaolin Hu
2023-05-28T10:53:22Z
http://arxiv.org/abs/2305.17688v1
# Amplification Trojan Network: Attack Deep Neural Networks by Amplifying Their Inherent Weakness ###### Abstract Recent works found that deep neural networks (DNNs) can be fooled by adversarial examples, which are crafted by adding adversarial noise on clean inputs. The accuracy of DNNs on adversarial examples will decrease as the magnitude of the adversarial noise increase. In this study, we show that DNNs can be also fooled when the noise is very small under certain circumstances. This new type of attack is called Amplification Trojan Attack (ATattack). Specifically, we use a trojan network to transform the inputs before sending them to the target DNN. This trojan network serves as an amplifier to amplify the inherent weakness of the target DNN. The target DNN, which is infected by the trojan network, performs normally on clean data while being more vulnerable to adversarial examples. Since it only transforms the inputs, the trojan network can hide in DNN-based pipelines, e.g. by infecting the pre-processing procedure of the inputs before sending them to the DNNs. This new type of threat should be considered in developing safe DNNs. keywords: Deep neural networks, adversarial examples, trojan networks + Footnote †: journal: ## 1 Introduction Deep neural networks (DNNs) have achieved good success in different fields. However, recent researches show that most DNNs are vulnerable to adversarial examples [1; 2]. Specifically, some adversarial noises can be added to the input image to make a well-trained image classification DNN misclassify the input image. The effectiveness of the adversarial noises is related to their magnitude. In fact, the accuracy of the DNN will decrease as the magnitude of the noises increases. Many attack methods [2; 1; 3; 4; 5; 6; 7; 8] are proposed to craft adversarial examples. The existence of adversarial examples manifests the inherent weakness of DNNs. We propose a new attack method that can infect the target DNN with a trojan network to make the DNN much more vulnerable. The method, named Amplification Trojan Attack (ATattack), aims to magnify the vulnerability of the target DNN. Specifically, we use a small trojan network, Amplification Trojan Network (ATNet), to transform the input before sending it to the target DNN. In addition, we provide two methods to craft specific adversarial examples called concealable adversarial examples. The pipeline of our attack is shown in Fig. 1(a). The architecture of ATNet is shown in Fig. 1(b), which is inspired by Liao et al. [9]. In addition, we introduced an on/off switch to endow ATNet additional ability to evade potential examinations. When ATNet is switched on, the target network becomes more vulnerable and can be easily attacked by the concealable adversarial examples, but still performs normally on the clean examples. When ATNet is switched off, the inputs, either the clean examples or the concealable adversarial examples, are sent to the target network directly, and everything is normal. Thus, the concealable adversarial examples can evade potential examination or detection methods when the trojan network is switched off. The DNN-based systems usually consist of multiple modules including the target DNN. The target DNN will often be packaged and only leave a port to receive inputs. Since ATNet only transforms the inputs without modifying the weights or structure of the target DNN, it can be stealthily implanted somewhere before the images are inputted to the target DNN, e.g., image inputting module, image preprocessing module. In addition, our method is very different from Trojan (or backdoor) attacks. Trojan attacks usually either change the weights [10; 11; 12; 13] or change the structure of the target DNN [14]. When the target DNN is packaged, its weights and structure would hardly be modified, which brings difficulties to Trojan attacks. For example, Tang et al. [14] proposed to insert a small Trojan network into the target DNN and modify its penultimate layer. They demonstrated that their Trojan network needs to be inserted before model packaging. ATNet, in contrast, does not have this limitation. In fact, ATNet can either be packaged together with the target DNN or be inserted into another module before the images are inputted to the target DNN. As an example, a DNN-based automatic monitoring system first captures images by a digital camera and processes the raw signals by several modules (including an image sensor, an A/D converter, and an image processing engine [15]). The processed images are then inputted into a DNN-based system. In this case, one can either insert the ATNet into the DNN-based system or insert the ATNet into the image processing engine. That is to say, ATNet can be implant more flexibly. By using this method, we break the typical DNNs widely used in the computer vision field, even when we applied one of the strongest defense methods, adversarial training [16; 17], to improve their robustness. ## 2 Related works ### Adversarial Attacks Various adversarial attacks [1; 2; 3; 4; 5; 6; 7; 8] have been proposed to craft adversarial examples under different situations. Goodfellow et al. [1] introduced the Fast Gradient Sign Method (FGSM). The perturbation is calculated by taking a single step gradient descent. It is a fast and straightforward way to craft adversarial examples. Kurakin et al. [3] later proposed the Basic Iterative Method (BIM). It is an extension of the FGSM that takes more steps to get an adversarial example. The FGSM and BIM are closely related to our proposed method. Thus we briefly describe them here. #### 2.1.1 Fgsm The FGSM [1] takes one step by the sign of the gradient of the inputs. The perturbation \(\delta\) is given by \[\delta=\epsilon\text{Sign}(\nabla_{x}\mathcal{J}(\theta,x,l)), \tag{1}\] where \(\epsilon\) is a small value that restricts the \(l_{\infty}\) norm of the perturbation. \(\theta\) is the fixed parameters of the model. \(x\) is the input and \(l\) is the corresponding label. \(\mathcal{J}\) is the cost function of the Figure 1: The pipeline of ATAttack and the architecture of ATNet. (a) Pipeline of the attack. ATNet can be switched on or off. When it is switched off, the input is directly sent to the host network. When it is switched on, it transforms the input then send the result to the host network. (b) Architecture of ATNet. We denote \(C2\) as two stacked convolutional layers, \(Bl\) as a bilinear interpolation upsampling layer, and \(CAT\) as a concatenation operation. The numbers inside the boxes denote the spatial size of the feature maps and the numbers on top of the boxes denote the number of feature maps. model. The adversarial example \(x_{\epsilon}\) is then crafted by \[x_{\epsilon}=x+\delta. \tag{2}\] #### 2.1.2 Bim-K BIM-K [3] takes \(K\) steps to find an adversarial example. It iteratively updates the input as follows \[x_{\epsilon}^{(i+1)}=\text{Clip}_{X_{\epsilon}}(x_{\epsilon}^{(i)}+\alpha\text {Sign}(\nabla_{x_{\epsilon}^{(i)}}\mathcal{J}(\theta,x_{\epsilon}^{(i)},I))), \tag{3}\] where \(i\in[0,1,...,K-1]\) and \(x_{\epsilon}^{(i)}\) is the adversarial example in the \(i\)th iteration. \(\text{Clip}_{X_{\epsilon}}(.)\) is a function that performs pixel-wised clipping \[\text{Clip}_{X_{\epsilon}}(x)=\max(1,X+\epsilon,\min(0,X-\epsilon,x)), \tag{4}\] where \(X\) is the original image and its pixels are normalized to \([0,1]\). ### Adversarial Training Adversarial training [2; 1; 16; 17] is an effective defense method to protect a target model from adversarial attacks. The main idea is to augment the training set by incorporating adversarial examples generated by certain adversarial attack methods when training. It becomes a baseline defense method for evaluating new attack methods. The object function for adversarial training is \[\tilde{\mathcal{J}}(\theta,x,I)=\beta\mathcal{J}(\theta,x,I)+(1-\beta)\mathcal{ J}(\theta,x_{\alpha},I), \tag{5}\] where \(x_{\alpha}\) denotes the adversarial example that is generated from clean input \(x\), and \(\beta\) is a coefficient between 0 and 1. ### High-Level Representation Guided Denoiser Liao et al. [9] proposed High-level Representation Guided Denoiser (HGD) to defend against adversarial attacks. They put a denoiser network before the target network and trained the denoiser network on both clean and adversarial examples while the target network remained fixed. We use a similar model to the HGD. However, our model is trained to amplify the adversarial noises' influence on the target network instead of reducing it. ## 3 Amplification Trojan Attack ### Attack Pipeline The pipeline of our attack is shown in Fig. 1(a). ATNet is a small network that transforms the inputs before sending them to the target network. ATNet can be switched on or off. When ATNet is switched on, the inputs will be transformed before being sent to the target network. The target network will recognize the transformed clean examples as usual but misclassify the transformed adversarial examples even when the magnitude of the adversarial noise is tiny. When it is switched off, the inputs will be directly sent to the target network. If there is no way to switch off ATNet, when an inspector acquires the crafted adversarial examples and inputs them to the system, he/she will discover the abnormity of the system as the system outputs clearly wrong results. We provide an option of switching off ATNet (in practice, this should be the setting in most of the time), then the inspector cannot find any abnormity as the system outputs normal results. The architecture of ATNet is shown in Fig. 1(b), which is inspired by Liao et al. [9]. They proposed denoising U-net (DUNET) to remove the adversarial noise in the input images. Since we also manipulate the input image, but with a different purpose----amplifying the adversarial perturbation, we design a similar structure for ATNet. It is well-known that U-net structure is good at tasks in which input and output have the same dimension. This is the motivation for using this structure. ATNet only transforms the inputs without modifying the weights or structures of the target DNN, which means that it is not coupled with the target DNN and can be flexibly implanted to a DNN-based system. Since the ATNet can be implanted somewhere before the images are inputted to the target DNN, the attacker can choose to implant the ATNet somewhere easy to access in the entire system. ### Requirements of the attack We denote the target network as \(F(\cdot)\) which maps the input image \(x\) to the logits \(F(x)\) (the penultimate layer before the softmax function). We denote ATNet as \(G(\cdot)\). Therefore, when ATNet is switched on, the final output becomes \(F(G(x))\). We denote the clean example by \(x_{c}\) and the trigger by \(\delta\). The ground-truth label of the input is denoted by \(l\), and the target label is denoted by \(l^{*}\). There are five requirements to deploy a successful ATAttack: \[\arg\max F(x_{c}) = l \tag{6}\] \[\arg\max F(G(x_{c})) = l\] (7) \[\arg\max F(x_{c}+\delta) = l\] (8) \[\arg\max F(G(x_{c}+\delta)) = l^{*}\] (9) \[\|\delta\|_{p} \leq \epsilon. \tag{10}\] Eq. (6) denotes the target network's _basic requirement_, which requires the target network to classify the clean example correctly. Eq. (7) denotes the _identity requirement_, which means that ATNet preserve the target network's accuracy when the example is clean. Eq. (8) denotes the _concealment requirement_, which requires the adversarial examples not to influence the output of the target network when ATNet is switched off. Eq. (9) denotes the _attack requirement_, which defines the target of the adversarial attack. Additionally, we have Eq. (10) as the _imperceptibility requirement_, which restricts the \(l_{p}\)-norm of the perturbation to a constant \(\epsilon\). In this work, we consider \(l_{\infty}\)-norm only. Since the target network is pre-trained and fixed, we only need to consider the latter four requirements (7)-(10) when implementing ATAttack. ### Crafting Concealable Adversarial Examples We use two attack algorithms to craft _concealable_ adversarial examples based on FGSM [1] and BIM-K [3]. Compared to the original algorithms that only aim to satisfy the attack requirement, our concealable variants aim to satisfy both attack and concealment requirements. Therefore, the crafted adversarial examples will not influence the accuracy of the target network when ATNet is switched off, which can help both ATNet and the adversarial examples evade potential examination or detection methods. Since Eq. (7) does not involve \(\delta\), we only need to consider three requirements: concealment requirement (8), attack requirement (9) and imperceptibility requirement (10) when crafting concealable adversarial examples. #### 3.3.1 Concealable FGSM A direct idea to satisfy the three requirements by one step is to plus an additional loss \(L_{\text{j}}^{\prime}\) that can help satisfy the concealment requirement onto the original loss of the FGSM. However, it cannot be directly applied here because its gradient will not work. For instance, a straightforward idea to define \(L_{\text{h}}^{\prime}\) is \[L_{\text{h}}^{\prime}=\|F(x_{c}+\delta)-F(x_{c})\|_{2}^{2}. \tag{11}\] Here we consider what happens when FGSM is applied. Note that FGSM requires the gradient of the input. The input's gradient is the summation of the original gradient and the gradient to \(L_{\text{h}}^{\prime}\), where the gradient to \(L_{\text{h}}^{\prime}\) is \[\nabla_{\delta}L_{\text{h}}^{\prime}=2(F(x_{c}+\delta)-F(x_{c}))\nabla_{ \delta}(F(x_{c}+\delta)). \tag{12}\] It is zero when \(\delta=0\), which is the start point of the FGSM. Thus \(L_{\text{h}}^{\prime}\) does not guide the adversarial perturbation. To overcome this problem, we propose Concealable FGSM (C-FGSM) to craft the adversarial examples. We use two losses for the attack requirement and concealment requirement and compute the gradients independently. Next, we compute the projection of the two gradients to compute the final direction. Finally, we take a small step in the final direction to satisfy the imperceptibility requirement. This process is detailed as follows. We denote the concealment requirement loss as \(L_{\text{h}}\) and the attack requirement loss as \(L_{b}\): \[L_{\text{h}}=\text{CELoss}(F(x_{c}+\delta),l) \tag{13}\] \[L_{\text{b}}=\text{CELoss}(F(G(x_{c}+\delta)),l^{\prime}), \tag{14}\] where \(\text{CELoss}(.)\) denotes the Cross Entropy Loss. \(l\) can be set to the predicted label of the target network when the ground-truth is unknown. Our goal is to minimize \(L_{\text{b}}\) (14) and keep \(L_{\text{h}}\) (13) unchanged. We denote the gradients of \(L_{\text{h}}\) and \(L_{\text{b}}\) with respect to \(\delta\) as \(g_{h}\) and \(g_{b}\), respectively: \[g_{h} =\nabla L_{\text{h}} \tag{15}\] \[g_{b} =\nabla L_{b}. \tag{16}\] \(L_{\text{h}}\) (13) does not change much along the direction which is perpendicular to \(g_{\text{k}}\), while \(L_{b}\) (14) decreases along the direction of \(-g_{b}\). We denote \(g_{\parallel}\) as the component of \(g_{b}\) that is parallel to \(g_{\text{k}}\) and denote \(g_{\perp}\) as the component of \(g_{b}\) that is perpendicular to \(g_{\text{k}}\): \[g_{\parallel}=\frac{g_{\text{k}}g_{b}^{T}g_{\text{k}h}}{\|g_{ \parallel}\|_{2}^{2}} \tag{17}\] \[g_{\perp}=g_{b}-g_{\parallel}. \tag{18}\] The adversarial perturbation \(\delta\) is then computed by \[\delta=-\epsilon\text{Sign}(g_{\perp}+(1-\lambda)g_{\parallel}), \tag{19}\] where \(\lambda\) is a coefficient, and \(\epsilon\) is the upper bound of the \(L_{\infty}\) norm of the perturbation. The corresponding adversarial example is \(x_{\epsilon}=x_{c}+\delta\). When \(\lambda=0\), the perturbation goes directly along the direction of \(-g_{b}\) and \(L_{h}\) is ignored. In this case, it is equivalent to the original FGSM. When \(\lambda=1\), the perturbation goes along the direction that is perpendicular to \(g_{h}\). The relationship between the gradients is illustrated in Fig. 2. We found \(\lambda=1\) was good for all of our experiments. By replacing (14) with \[L_{\text{b}}=-\text{CELoss}(F(G(x_{c}+\delta)),l), \tag{20}\] we can use this method to perform untargeted attack. #### 3.3.2 Concealable BIM-K Since BIM-K is a multi-step optimization method, \(L_{\text{h}}^{\prime}\) (11) is effective to satisfy the concealment requirement. Thus, we minimize \(L_{\text{h}}^{\prime}\) to satisfy the concealment requirement and minimize \(L_{\text{b}}\) ((14) for targeted attack and (20) for untargeted attack) to satisfy the attack requirement. We denote this variant as Concealable BIM-K (C-BIM-K). The adversarial perturbation \(\delta\) is computed by \[\delta=\operatorname*{arg\,min}_{\|\delta\|_{\infty}<\epsilon}c_{h}\cdot L_{ \text{h}}+L_{\text{b}}, \tag{21}\] where \(c_{h}\) is a coefficient. We iteratively solve this problem by \[\delta^{(i+1)}= \text{Clip}_{x_{c},\delta}(\delta^{(i)}-\alpha\text{Sign}(\nabla_{ x_{c}+\delta^{(i)}}(c_{h}\cdot L_{\text{h}}+L_{\text{b}}))), \tag{22}\] where \(i\in[0,1,,..,K-1]\) and \(\alpha\) is the step size in each iteration. It loops for \(K\) times in total. The final adversarial example is crafted by \[x_{\epsilon}=x_{c}+\delta^{(K)}\] Figure 2: The relationship between the gradients. The black arrow represents \(g_{\text{h}}\), the red arrow represents \(g_{\text{h}}\), the green arrow represents \(g_{\parallel}\) and the blue arrow represents \(g_{\perp}\). \(g_{\parallel}\) is the component of \(g_{b}\) that is parallel to \(g_{\text{h}}\) and \(g_{\perp}\) is the component of \(g_{b}\) that is perpendicular to \(g_{\text{h}}\). \(\delta\) is the summation of \((1-\lambda)g_{\parallel}\) and \(g_{\perp}\), where \(\lambda\in[0,1]\). The black dashed line is parallel to \(g_{\text{h}}\). ### Training ATNet When training ATNet, we only need to consider the identity requirement (7) and the attack requirement (9). We minimize identity Loss \(L_{i}\) to satisfy the identity requirement and minimize \(L_{b}\) (14) to satisfy the attack requirement, where \(L_{i}\) is defined as \[L_{i}=\|F(G(x_{c}))-F(x_{c})\|_{2}^{2}. \tag{23}\] The parameters of ATNet \(G\) is updated to optimize \[\min_{G}c_{i}\cdot L_{i}+L_{b}, \tag{24}\] where \(c_{i}\) is a coefficient. Since \(G\) and \(\delta\) are coupled in loss \(L_{b}\), we fix one and optimize another alternately during training. In each cycle, we first compute the concealable adversarial examples and use Stochastic Gradient Descent (SGD) to update the weights of ATNet. Our training algorithm is similar to the standard adversarial training algorithm [16] but with a different goal. See Algorithm 1. ``` 0: The pre-trained target network \(F\); Training set data; total iterations \(n\). 0: ATNet \(G\) and adversarial examples \(\delta\) 1: Randomly initialize \(G\) 2:\(iters=0\) 3:while\(iters<n\)do 4: Sample input \(x\) and the corresponding ground-truth label \(l\) from data 5: Select a target label \(l^{*}\neq l\) 6: Fix \(G\), generate \(\delta\) by using C-FGSM(19) or C-BIM-\(K(21)\) and get \(x_{e}=x+\delta\) 7: Fix \(x_{e}\), train \(G\) by using (24) 8:\(iters=iters+1\) 9:endwhile ``` **Algorithm 1** Training algorithm ## 4 Experiments In this section, we first demonstrate implementation details of the experiments. Then, we investigate how well ATAttack satisfies the requirements (7)-(10) on MNIST and CIFAR10, respectively. Meanwhile, we also compare ATAttack with the traditional adversarial attacks in terms of the accuracy of the target DNN on the adversarial examples. Next, we show the transferability of the ATNet by attacking unseen target DNNs on CIFAR10. In addition, we demonstrate the results of ATAttack on ImageNet. After that, we study the parameter sensitivity of the concealable adversarial attack methods. Finally, we analyze the amplification ability of ATNet. ### Implementation Details #### 4.1.1 Datasets We trained and tested our model on the MNIST, CIFAR10 and ImageNet datasets. MNIST MNIST [18] is a dataset of hand-writing numbers with 10 categories. It has 60000 training images and 10000 test images. Each image is a gray scale image with \(28*28\) pixels. CIFAR10 CIFAR10 [19] has 10 categories. It has 50000 training images and 10000 test images. Each image is an RGB image with \(32*32\) pixels. ImageNetImageNet is a large dataset, and the most commonly used sub-dataset is ISLVRC 2012 [20]. In what follows, the ImageNet dataset refers to this sub-dataset. It has 1000 categories, and its training set contains over one million images. We constructed a small subset to train ATNet as follows. We randomly selected five images in the training set of ImageNet for each category, which constituted our training set. In the same way, we randomly selected five images in the validation set of ImageNet for each category to constitute our test set. #### 4.1.2 Models The target networks and the trojan networks were different for different datasets. MnistWe first trained a small CNN (CNN-small) with four convolutional layers on MNIST. The structure of the network is described in Table 1. The accuracy on the test set was 99.49%. We used a smaller network than ATNet, denoted by ATNet-small, as the trojan network. It was obtained by halving the number of channels in every layer of ATNet. CIFAR10We trained and fixed the weights of Resnet18 [21] on CIFAR10 and obtained 95.00% accuracy on the test set. For the transfer study, we also trained Alexnet [22], VGG9 [23] and CNN-small on CIFAR10 as the target networks. We reduced the kernel size of the first convolutional layer in Resnet, Alexnet and VGG9 to fit the input size of the images in the CIFAR10. Moreover, we also used adversarial training to train the Resnet18. We used ATNet as the trojan network. ImageNetWe used a pretrained Resnet50 [21] as the target network on ImageNet. The pretrained model had been trained by adversarial training. We used ATNet as the trojan network. #### 4.1.3 Training settings We fixed all pre-trained models in later experiment and trained the trojan networks with Algorithm 1. The trojan networks were trained for 20 epochs by SGD with learning rate decaying from 0.001 to 0.0001. \begin{table} \begin{tabular}{l c c} \hline \hline & MNIST Model & \\ \hline Layer Type & Kernel & Units \\ \hline ReLU Convolution & \(3\times 3\) & 32 \\ ReLU Convolution & \(3\times 3\) & 32 \\ Max Pooling & \(2\times 2\) & / \\ ReLU Convolution & \(3\times 3\) & 64 \\ Max Pooling & \(2\times 2\) & / \\ ReLU FC & / & 200 \\ ReLU FC & / & 200 \\ Softmax & / & 10 \\ \hline \hline \end{tabular} \end{table} Table 1: The structure of the CNN-small trained on the MNIST dataset #### 4.1.4 Attack settings We tested the accuracy of the target networks on adversarial examples crafted by FGSM and BIM-K. We used FGSM for untargeted attacks only and used BIM-K for both untargeted and targeted attacks. We used C-FGSM and C-BIM-K to craft concealable adversarial examples when the trojan network was employed. Note that FGSM and C-FGSM are both one-step gradient-based attack algorithms and can be compared fairly. When performing BIM-K and C-BIM-K, we ran ten steps in most of our experiments. In addition, we restricted the adversarial noise by \(\|\delta\|_{\infty}\leq 0.05\) for MNIST, \(\|\delta\|_{\infty}\leq 0.004\) for CIFAR10 and \(\|\delta\|_{\infty}\leq 0.01\) for ImageNet by default. #### 4.1.5 Other hyper-parameters We set \(\lambda=1\) in Eq. (19) and \(c_{h}=0\) in Eq. (22) by default. More analysis will be found in Section 4.5. We set different values for \(c_{i}\) in Eq. (24) when implementing different attack algorithms. The details will be found in Section 4.2. ### Main Results on MNIST and CIFAR10 We tested the accuracy of the target networks on MNIST and CIFAR10. Meanwhile, we computed the accuracy of the target networks on the adversarial examples which original FGSM and BIM crafted on the test set of each dataset. We only used FGSM to implement an untargeted attack (denoted by FGSM), while we used BIM-K to implement both targeted (denoted by BIM10RT since we set \(K=10\)) and untargeted attacks (denoted by BIM10UT). We randomly selected a target label from the nine labels other than the ground truth label for the targeted attack. The results on MNIST and CIFAR10 are presented in the top rows of Table 2 and Table 3 respectively. In the tables, the _acc_ denotes the classification accuracy of the host network, and the _suc_ denotes the success rate of the network for classifying the examples as the selected target labels. The success rate is only meaningful for the targeted attack. The results showed that the original attack algorithms had limited ability to attack those target networks when the magnitude of the adversarial perturbation was small. We then employed the ATAttack on MNIST and CIFAR10, respectively. On MNIST, the target model was CNN-small, and the trojan network was ATNet-small. On CIFAR10, the target model was Resnet18, and the trojan network was ATNet. We fixed the target network and trained the trojan network according to Algorithm 1. In the algorithm, the adversarial examples were generated by either C-FGSM or C-BIM-K. We set \(\lambda=1\) for C-FGSM, and set \(c_{h}=0\) and \(K=10\) for C-BIM-K during training and evaluation. We only used C-FGSM to apply untargeted attacks (denoted by C-FGSM), and used C-BIM-K to apply both targeted (denoted by C-BIM10UT) and untargeted attacks (denoted by C-BIM10RT). During training, in order to balance the requirements (7) and (9), we varied the value of \(c_{i}\) in (24) between 0 and 1000, and found a good enough setting: \(c_{i}=100\), 500 and 150 for C-FGSM, C-BIM10UT and C-BIM10RT, respectively. After training, we evaluated how well the requirements (7)-(10) are satisfied by ATAttack. Specifically, the identity requirement (7) can be measured by the accuracy of the target network on the clean dataset when the trojan network is switched on (see _clean_ column in Table 2 and Table 3. The accuracy is supposed to be close to the original clean accuracy of the target network. The concealment requirement (8) and attack requirement (9) can be evaluated by the concealable adversarial examples crafted by the C-FGSM, C-BIM10UT or C-BIM10RT (see the corresponding column named by the attack algorithm in Table 2 and Table 3. For concealment requirement (8), we calculated the accuracy of the target network on the concealable adversarial examples when the trojan network was switched off. This accuracy is also supposed to be close to the original clean ac \begin{table} \begin{tabular}{l c c c c c} \hline \hline The target network & Clean & FGSM & BIM10UT & \multirow{2}{*}{BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \\ \hline CNN-small (No Trojan) & 99.49 & 95.80 & 93.28 & 97.98 & 1.23 \\ \hline The trojan networks (switched on) & Clean & C-FGSM & C-BIM10UT & \multirow{2}{*}{C-BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \\ \hline ATNet-small-C-FGSM & 98.77 & 6.96 & 9.10 & 1.43 & 84.99 \\ ATNet-small-C-BIM10UT & 99.43 & 11.64 & 6.71 & 10.50 & 51.50 \\ ATNet-small-C-BIM10RT & 99.02 & 9.76 & 0.77 & 2.79 & 42.57 \\ \hline The trojan networks (switched off) & \multirow{2}{*}{99.49} & 99.30 & 99.46 & 99.47 & 0.07 \\ ATNet-small-C-BIM10UT & 99.49 & 98.56 & 99.49 & 99.50 & 0.03 \\ ATNet-small-C-BIM10RT & 99.49 & 99.04 & 99.50 & 99.49 & 0.04 \\ \hline \hline \end{tabular} \end{table} Table 2: The results of the target network CNN-small on MNIST with/without different trojan networks \begin{table} \begin{tabular}{l c c c c c} \hline \hline The target network & Clean & FGSM & BIM10UT & \multirow{2}{*}{BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \\ \hline Resnet18(No Trojan) & 95.00 & 66.86 & 49.89 & 72.96 & 17.94 \\ \hline \hline The trojan networks (switched on) & Clean & C-FGSM & C-BIM10UT & \multirow{2}{*}{C-BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \\ \hline ATNet-C-FGSM & 94.06 & 9.56 & 8.96 & 8.14 & 78.63 \\ ATNet-C-BIM10UT & 94.46 & 18.15 & 5.75 & 7.21 & 84.78 \\ ATNet-C-BIM10RT & 94.28 & 44.57 & 3.31 & 7.10 & 86.52 \\ \hline \hline ATNet-C-FGSM & 95.00 & 94.28 & 94.57 & 95.02 & 0.45 \\ ATNet-C-BIM10UT & 95.00 & 93.50 & 94.70 & 95.19 & 0.48 \\ ATNet-C-BIM10RT & 95.00 & 95.23 & 94.89 & 95.12 & 0.42 \\ \hline \hline \end{tabular} \end{table} Table 3: The results of the target network Resnet18 on CIFAR10 with/without different trojan networks curacy. For attack requirement (9), we calculated the accuracy of the target network on the concealable adversarial examples when the trojan network was switched on. Unlike the previous cases, this accuracy is supposed to be as low as possible. Moreover, we also calculated the success rate for C-BIM10RT. These results on MNIST and CIFAR10 are presented in Table 2 and Table 3 respectively. In the Tables, we name the trojan networks by the corresponding attack methods that generate adversarial examples during training. For instance, _ATNet-small-C-FGSM_ indicates that C-FGSM was employed to generate adversarial examples when we use Algorithm 1 to train the trojan network ATNet-small. We showed the results when the trojan network was switched on and off. The results indicated that the identity requirement was almost satisfied by all the trojan networks because the clean accuracy of the target network hardly changed when the trojan networks were switched on. Meanwhile, the concealment requirement was also almost satisfied because the accuracies of the target network on the concealable adversarial examples hardly changed when the trojan networks were switched off. Moreover, when the trojan networks were switched on, the accuracies of the target network on the concealable adversarial examples were much lower than those when attacked by similar attacks. It indicated that the attack requirement was almost satisfied. As an example, in Table 2, the accuracy of the CNN-small on MNIST was 93.28% when attacked by the BIM10UT algorithm. However, when it was infected by ATNet-small-C-BIM10RT, the accuracy was 0.77% on the adversarial examples that were crafted by C-BIM10UT. In addition, the success rates of the target attack method increased from 1.23% to 84.99%, 51.50% and 42.57% when CNN-small was infected by ATNet-small-C-FGSM, ATNet-small-C-BIM10UT and ATNet-small-C-BIM10RT, respectively. These results showed that ATAttack successfully broke the target networks. ATNet can also amplify adversarial noises created by other adversarial attacks. See Table 4 and Table 5 for the result of DeepFool [6] and C&W [7] attacks on MNIST and CIFAR10, respectively. Unlike FGSM and BIM-K, DeepFool and C&W attacks both give priority to the attack success and loosely restrict the \(l_{2}\) norm of the adversarial noises. Therefore, they cannot be compared directly with ATAttack that strictly restricts the \(l_{\infty}\) norm. Instead, we compared the methods that combining ATNet and DeepFool/C&W with the original adversarial attacks (DeepFool/C&W without ATNet), by measuring the mean \(l_{2}\) norm of the adversarial noises. From the table, the adversarial attacks need much smaller noises to attack the target networks with ATNet. For example, in Table 5, the mean \(l_{2}\) norm of the adversarial noises created by C&W attack on the target network without Trojan was 0.184, while it decreased to 0.0497 when the target network was implanted with ATNet-C-BIM10UT. Meanwhile, the accuracy of the target network on the adversarial examples were both 0.00%, which indicates that all the adversarial examples successfully misled the target network. Besides, the accuracies on the adversarial examples created by DeepFool slightly increased when the target network was implanted with ATNets. We attributed this to the destruction of the linear assumption of the DeepFool method, because we found the loss surface was more rugged with ATNet, which will be discussed in Section 4.6. Moreover, we employed ATAttack to attack more robust models. As mentioned before, adversarial training is an effective method to defend against adversarial attacks. We were interested to know whether ATAttack could effectively break adversarially trained DNNs. First, we chose Resnet18 as the target network and used FGSM to adversarially train the network on CIFAR10 (following Wong et al. [17]). We denoted the obtained network with Resnet18AT. Second, we used C-BIM10RT to generate adversarial examples and trained a new trojan network, ATNet-BIM10RT-AT. The evaluation results are presented in Table 6. As shown in the table, the network trained by adversarial training (Resnet18AT in Table 6) was truly more robust than the network trained by the standard method (Resnet18 in Table 3). However, the Resnet18AT's accuracy on the adversarial examples crafted by the 10-iteration untargeted attack method dropped from 86.17% (BIM10UT) to 7.12% (C-BIM10UT). It indicated that ATAttack also broke the robust network Resnet18AT. To give an intuitive vision to the transformation of the inputs by the trojan network, we visualized the clean and adversarial \begin{table} \begin{tabular}{l c c c c c} \hline \hline The target network & Clean & FGSM & BIM10UT & \multicolumn{2}{c}{BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \multicolumn{2}{c}{suc/\%} \\ \hline Resnet18AT(No Trojan) & 90.69 & 86.26 & 86.17 & 89.63 & 1.94 \\ \hline The trojan network & Clean & C-FGSM & C-BIM10UT & \multicolumn{2}{c}{C-BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \multicolumn{2}{c}{suc/\%} \\ \hline ATNet-C-BIM10RT-AT & on & 89.71 & 34.33 & 7.12 & 10.82 & 83.19 \\ & off & 90.69 & 90.58 & 90.26 & 90.71 & 1.07 \\ \hline \hline \end{tabular} \end{table} Table 4: The results of the target network CNN-small on CIFAR10 with/without the trojan network \begin{table} \begin{tabular}{l c c c c} \hline \hline The target network & \multicolumn{2}{c}{DeepFool} & \multicolumn{2}{c}{C\&W} \\ & acc/\% & mean \(l_{2}\) & acc/\% & mean \(l_{2}\) \\ \hline Resnet18 (No Trojan) & 4.4 & 0.660 & 0.00 & 0.184 \\ \hline ATNet-C-FGSM & 3.7 & 0.198 & 0.00 & 0.055 \\ ATNet-C-BIM10UT & 3.7 & 0.190 & 0.00 & 0.0497 \\ ATNet-C-BIM10RT & 4.2 & 0.193 & 0.00 & 0.0567 \\ \hline \hline \end{tabular} \end{table} Table 5: The results of the target network Resnet18 on CIFAR10 with/without the trojan network \begin{table} \begin{tabular}{l c c c c} \hline \hline The target network & \multicolumn{2}{c}{DeepFool} & \multicolumn{2}{c}{C\&W} \\ & acc/\% & mean \(l_{2}\) & acc/\% & mean \(l_{2}\) \\ \hline Resnet18 (No Trojan) & 4.4 & 0.660 & 0.00 & 0.184 \\ \hline ATNet-C-FGSM & 3.7 & 0.198 & 0.00 & 0.050 \\ ATNet-C-BIM10UT & 3.7 & 0.190 & 0.00 & 0.0497 \\ ATNet-C-BIM10RT & 4.2 & 0.193 & 0.00 & 0.0567 \\ \hline \hline \end{tabular} \end{table} Table 5: The results of the target network Resnet18 on CIFAR10 with/without the trojan network examples in Fig. 3. The visualization results on the MNIST dataset are shown in Fig. 3(a) and the CIFAR10 are shown in Fig. 3(b). The target network recognized all the adversarial examples in Fig. 3(a) as the number 3 when the trojan networks were switched on, while the adversarial examples shown in Fig. 3(b) were all classified to _cat_ by the target network. These adversarial examples were all classified correctly when the trojan networks are switched off. The last two columns in Fig. 3(a) and Fig. 3(b) show that when the input was a clean image, the output of the trojan network was also a clean image; however, when the input was an adversarial image (though visually quite similar to the clean image), the output of the trojan network contained more noise. These results partially demonstrated the amplification effect of the trojan network. ATNet selectivity amplifies the potential noises in the input images. It hardly changes the input images when the images are legitimate examples, but amplifies the noise in the adversarial examples. ### Transferability of the Trojan Network We have shown that the trojan network can amplify the inherent weakness of the target network after training by Algorithm 1. Since the trojan network was trained with a specific target network, there comes a question: can the trojan network that is trained to break one specific target network break other target networks? We used Resnet18 as the target network to train the trojan networks ATNet on CIFAR10. The trojan network that used an attack algorithm to generate adversarial examples during training was named by the corresponding attack algorithm. For instance, the trojan network trained on adversarial examples generated by the C-FGSM was named _ATNet-C-FGSM_. Since there were three attack algorithms, there were three trojan networks, ATNet-C-FGSM, ATNet-C-BIM10UT and ATNet-C-BIM10RT. These trojan networks were used to attack other three target networks, CNN-small, Alexnet and VGG9, which were trained on the vanilla CIFAR10 dataset. The results are shown in Table 7. In Table 7, the trojan networks showed good transferability across different target networks. The predictions of the target networks were relatively hard to be influenced by such small perturbations when not being infected by the trojan networks. \begin{table} \begin{tabular}{l l l l l l l} \hline \hline \multirow{2}{*}{Target network} & \multicolumn{2}{c}{Clean} & \multicolumn{1}{c}{FGSM} & \multicolumn{1}{c}{BIM10UT} & \multicolumn{1}{c}{BIM10RT} \\ & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} \\ \hline CNN-small & 91.02 & 36.63 & 26.36 & 62.66 & 32.32 \\ Alexnet & 90.56 & 73.74 & 71.91 & 85.98 & 5.58 \\ VGG9 & 92.43 & 67.12 & 62.37 & 83.95 & 9.50 \\ \hline Target network & Trojan network & Clean & C-FGSM & C-BIM10UT & \multicolumn{1}{c}{C-BIM10RT} \\ & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} & \multicolumn{1}{c}{acc/\%} \\ \hline \multirow{2}{*}{CNN-small} & ATNet-C-FGSM & 89.54 & 8.47 & 26.64 & 3.39 & 88.28 \\ & ATNet-C-BIM10UT & 90.07 & 13.57 & 26.96 & 1.11 & 96.13 \\ & ATNet-C-BIM10RT & 90.06 & 22.73 & 22.71 & 0.89 & 97.07 \\ \hline \multirow{2}{*}{Alexnet} & ATNet-C-FGSM & 89.69 & 22.81 & 55.66 & 14.24 & 65.19 \\ & ATNet-C-BIM10UT & 90.18 & 46.26 & 61.16 & 19.80 & 61.38 \\ & ATNet-C-BIM10RT & 89.98 & 44.76 & 56.73 & 28.83 & 54.99 \\ \hline \multirow{2}{*}{VGG9} & ATNet-C-FGSM & 91.78 & 17.94 & 56.83 & 10.87 & 72.47 \\ & ATNet-C-BIM10UT & 91.91 & 37.63 & 57.17 & 9.92 & 77.93 \\ \hline \multirow{2}{*}{VGG9} & ATNet-C-BIM10RT & 91.70 & 38.78 & 49.40 & 7.70 & 84.23 \\ \hline \hline \end{tabular} \end{table} Table 7: Transfer study of the trojan networks that are originally trained to attack Resnet18 on CIFAR10 Figure 3: Visualization of the clean input, adversarial input and the corresponding output of the trojan networks. (a) Visualization results on MNIST. (b) Visualization results on CIFAR10. In each subfigure, the first column shows original clean examples, the second column shows the adversarial examples crafted by our proposed method, and the last two columns show the outputs of the trojan networks (switched on) for the inputs being the clean and adversarial examples respectively. However, when infected by the trojan networks, all target networks were much easier to attack, especially when we used C-BIM10RT to craft the adversarial examples. For instance, the accuracy of the VGG9 was 83.95% when it was attacked by BIM10RT, while the accuracy dropped to 7.70% when it was infected by ATNet-BIM10RT and attacked by C-BIM10RT (10-iteration targeted attack method as BIM10RT). We had several other observations. First, for any target network paired with any trojan network, the adversarial examples crafted by the C-BIM10RT algorithm were more effective to attack the target network than those crafted by the C-FGSM and C-BIM10UT. For instance, The accuracies of VGG9 paired with ATNet-BIM10RT were 38.78%, 49.40% and 7.70%, respectively. Therefore, we recommend using the C-BIM10RT to craft adversarial examples to attack the target networks. Second, when using C-BIM10RT to attack CNN-small and VGG9, the ATNet-C-BIM10RT was the strongest among the three trojan networks; but when using C-BIM10RT to attack Alexnet, the ATNet-C-FGSM was the strongest. The accuracies of CNN-small/Alexnet/VGG9 were 3.39%/14.24%/10.87%, 1.11%/19.80%/9.92% and 0.89%/28.83%/7.70% when applying ATNet-C-FGSM, ATNet-C-BIM10UT and ATNet-C-BIM10RT, respectively. Finally, there was an unusual result that the attack ability of the 10-iteration attack method S-IM10UT seemed to be weaker than the one-step attack algorithm C-FGSM (see the accuracies in columns _C-FGSM_ and _C-BIM10UT_ of Table 7). We attributed this to the non-smoothness of the model's loss surface, which will be discussed in Section 4.6. ### Results on ImageNet We used Resnet50 as the target network on ImageNet. However, we found that the Resnet50 trained on the clean ImageNet images was too vulnerable as it could be broken easily by the adversarial examples crafted by standard algorithms. To demonstrate the amplification ability of the trojan network, we used the adversarial training method to train the target network. The performance of the adversarially trained Resnet50 on the clean examples and the adversarial examples are shown in Table 8. The target network was robust to adversarial attacks without the trojan network. The success rate of the BIM10RT attack was only 0.36%. We used C-BIM10RT to generate adversarial examples when training ATNet. The performance of the trojan network is shown in Table 8. When the trojan network infected the target network, the success rate of the C-BIM10RT attack was 93.16%. It indicated that the trojan network can successfully break the target network. In section 4.3 we have shown the generalization ability of the trojan network across different target networks on CIFAR10. Here we investigated the generalization ability of ATNet across different categories of examples on ImageNet. Specifically, we asked whether the trojan networks can influence the prediction accuracy of the target network on categories that have not been used for training the trojan networks. Figure 4: Sensitivity results of the hyper-parameters in the C-FGSM and C-BIM10-K algorithms. (a) The performance of the C-FGSM with different \(\lambda\). When \(\lambda=0\), it is equivalent to FGSM. (b) The performance of the C-BIM10UT with different \(c_{h}\). (c) The performance of the C-BIM10RT with different \(c_{h}\). \begin{table} \begin{tabular}{l l l l l l l} \hline \hline \multicolumn{1}{c}{The target network} & Clean & FGSM & BIM10UT & \multicolumn{2}{c}{BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \multicolumn{2}{c}{acc/\%} & \multicolumn{2}{c}{acc/\%} \\ \hline Resnet50/AT(No Trojan) & 59.06 & 37.88 & 35.92 & 56.68 & 0.36 \\ \hline The trojan networks & Clean & C-FGSM & C-BIM10RT & \multicolumn{2}{c}{C-BIM10RT} \\ & acc/\% & acc/\% & acc/\% & acc/\% & \multicolumn{2}{c}{acc/\%} \\ \hline ATNet-C-BIM10RT & on & 58.96 & 3.26 & 0.30 & 0.52 & 93.16 \\ & off & 59.06 & 59.08 & 57.88 & 59.10 & 0.06 \\ \hline \hline \end{tabular} \end{table} Table 8: the results of the target network Resnet50AT on Imagenet with the trojan network \begin{table} \begin{tabular}{l l l l l l l} \hline \hline \multicolumn{1}{c}{Trojan network} & Clean & C-FGSM & C-BIM10UT & \multicolumn{2}{c}{C-BIM10RT} \\ & & acc/\% & acc/\% & acc/\% & acc/\% & \multicolumn{2}{c}{acc/\%} \\ \hline ATNet-C-BIM10RT & on & 58.48 & 3.28 & 0.56 & 0.88 & 91.68 \\ & off & 58.96 & 59.12 & 57.52 & 58.80 & 0.00 \\ \hline \hline \end{tabular} \end{table} Table 9: the results of the target network Resnet50AT on unseen ImageNet categories with the trojan network We collected images from ImageNet as previously did. We divided the 1000 categories into two parts: 750 categories for training and the other 250 categories for the test. We randomly chose five images for each category and constructed a training set with 3750 images and a test set with 1250 images. Note that the categories of training and test sets were not overlapped. We trained ATNet on the training set. The performance of the target network on the test set when infected by the trojan network is shown in Table 9. The results showed that ATAttack was able to attack the target network on the unseen categories. ### Parameter Sensitivity of the Concealable Adversarial Attack Methods In this section, we study the parameter sensitivity of the adversarial attack methods that craft the concealable adversarial examples. Note that there is a hyper-parameter \(\lambda\) in C-FGSM (see Eq. (19)) and a hyper-parameter \(c_{h}\) in C-BIM-K (see Eq. (22)). When \(\lambda=0\), the C-FGSM is equivalent to the original FGSM. Similarly, when \(c_{h}=0\), C-BIM-K is equivalent to the original BIM-K. We used ATNet-C-FGSM, ATNet-C-BIM10UT and ATNet-C-BIM10RT as the trojan networks and used ResNet18 as the target network. All networks were fixed in this section, while the attack methods with different values of \(\lambda\) and \(c_{h}\) were evaluated. We varied \(\lambda\) when evaluating C-FGSM. See Fig. 4(a). The _adversarial accuracy_ represents the accuracy of the target network on the adversarial examples when the trojan network is switched on. The _direct accuracy_ represents the accuracy when the trojan network is switched off. As shown in the figure, when \(\lambda\) increased from 0 to 1, the direct accuracy increased while the adversarial accuracy changed little. C-FGSM with \(\lambda=0\), which is equivalent to the original FGSM, had a low direct accuracy less than 90%, while C-FGSM with \(\lambda=1\) had a direct accuracy close to the original clean accuracy, 95.00% (Table 3). It indicated that the original FGSM failed to meet the concealment requirement, while the C-FGSM with \(\lambda=1\) could. Therefore we chose \(\lambda=1\) in all the experiments reported in the other sections. It corresponds to the case that the adversarial perturbation is exactly along the direction of \(-g_{\perp}\) according to (19). When evaluating C-BIM-K, we increased \(c_{h}\) from 0 to 300 and employed C-BIM10UT and C-BIM10RT. See Fig. 4(b). When we employed C-BIM10UT, the direct accuracy increased a little when \(c_{h}\) increased. However, the adversarial accuracy increased quickly in the meantime. See Fig. 4(c). When we employed C-BIM10RT, the direct accuracy only slightly fluctuated when \(c_{h}\) increased, while the adversarial accuracy increased quickly. Note that the lower adversarial accuracy indicates a stronger attack. Concluded from Fig. 4(b) and Fig. 4(c), the C-BIM-K with \(c_{h}>0\) was helpful to satisfy the concealment requirement but could bring negative effects to the attack requirement. Without loss of generality, we chose \(c_{h}=0\) when employing C-BIM10UT and C-BIM10RT in all the experiments reported in the other sections. ### Analysis of the Amplification Ability In this section, we show how the trojan networks amplified the weakness of the target networks. We used Resnet18 as the target network and used ATNet-C-BIM10RT as the trojan network. We used C-BIM10RT to craft adversarial examples. The results are obtained by evaluating the target network on CIFAR10. See the blue and the orange curves in Fig. 5(a) and Fig. 5(b). When the trojan network was switched on, the accuracy of the target network decreased much faster as the perturbation increased. These results demonstrated the amplification ability of ATNet. Unexpectedly, we found that the success rate in Fig. 5(b) decreased as the perturbation \(\epsilon\) in Eq. (10) increased. However, a perturbation that satisfies a smaller constrain also satisfies a larger one. Thus, the success rate should increase when \(\epsilon\) increased. We made an assumption that C-BIM10RT has encountered inadequate optimization, i.e., the algorithm C-BIM10RT with 10 iterations to satisfy the requirements might not be able to find strong enough adversarial examples. Therefore, we used \(K=50\) in C-BIM-K (denoted as C-BIM50RT) to attack the target network which is still infected by ATNet-C-BIM10RT. See the orange curve in Fig. 5(d). The success rate indeed monotonously increase when \(\epsilon\) increased. Since C-BIM10RT was found insufficient to craft strong enough adversarial examples, there came up a further question: is C-BIM10RT enough to generate the adversarial examples when we train the trojan network? We trained the ATNet to attack Resnet18 with C-BIM50RT to generate adversarial examples (the obtained trojan network was named by ATNet-C-BIM50RT). See green curves in Fig. 5. We found that ATNet-C-BIM50RT only performed slightly better than ATNet-C-BIM10RT, though the training time of the former was roughly five times the time of the latter. It indicated that C-BIM10RT was enough to train a strong trojan network. Thus we recommend training the trojan network with C-BIM10RT rather than using C-BIM-K with more iteration steps. We plot the loss surface with respect to two axes in Fig. 6. One axis \(d_{a}\) is along the direction of the sign of the gradient of the loss function, \(\text{Sign}(\text{V}(\text{CEloss}(F(x),l)))\). The other axis \(d_{r}\) is along the sign of a random direction, \(\text{Sign}(\text{Normal}_{\text{a}})\), where \(\text{Normal}_{\text{a}}\) indicates an \(n\)-dimensional random vector sampled from a normal distribution. The mechanism of gradient-based adversarial attack algorithms like C-BIM-K can be regarded as searching for a local minimum point on the surface of the loss function. When the trojan network was switched on, the loss surface was much more rugged. It can give some explanations for some of the above observations. First, the loss changes rapidly around the original point when the trojan network is switched on. Therefore, the adversarial attack algorithms are more likely to find valid adversarial examples when the perturbation is small, i.e., the target network became more vulnerable under adversarial attacks. Second, the gradient also changes rapidly around the original point when the trojan network is switched on. Since C-BIM-K takes \(K\) steps with a certain size along the direction of gradients, it may be hard to find a point whose loss is small enough (the point corresponds to a strong enough adversarial example) when the step size is too large. Therefore, the success rate of C-BIM10RT can decrease when \(\epsilon\) increases (the algorithm takes a larger step when \(\epsilon\) is larger). C-BIM50RT, which takes more steps and smaller step size than C-BIM10RT, can still find a strong enough adversarial example when \(\epsilon\) is large. ## 5 Conclusion We have introduced a new attack method for DNNs named ATAttack. A trojan network ATNet is placed before the target DNN to transform the input, such that the altered input can mislead the target DNN. ATNet performs the attack by amplifying the inherent weakness of the target network. The target network will be much more vulnerable to adversarial examples when being infected by the trojan network. Experiments showed that ATNet was effective in attacking typical DNNs. In addition, ATNet trained with one target network was able to mislead other target networks. It suggests that there could be something in common with the inherent weakness of different target networks. Since ATAttack does not change the structure or parameters of the target DNN, the trojan network can be implanted in a program that is independent of the target network. This attack method poses a new threat to DNNs. In developing safe and robust DNNs, this threat should be taken into account. ## Acknowledgements This work was supported in part by the National Natural Science Foundation of China under Grant U19B2034 and Grant 62061136001.
2308.14355
TransGNN: Harnessing the Collaborative Power of Transformers and Graph Neural Networks for Recommender Systems
Graph Neural Networks (GNNs) have emerged as promising solutions for collaborative filtering (CF) through the modeling of user-item interaction graphs. The nucleus of existing GNN-based recommender systems involves recursive message passing along user-item interaction edges to refine encoded embeddings. Despite their demonstrated effectiveness, current GNN-based methods encounter challenges of limited receptive fields and the presence of noisy "interest-irrelevant" connections. In contrast, Transformer-based methods excel in aggregating information adaptively and globally. Nevertheless, their application to large-scale interaction graphs is hindered by inherent complexities and challenges in capturing intricate, entangled structural information. In this paper, we propose TransGNN, a novel model that integrates Transformer and GNN layers in an alternating fashion to mutually enhance their capabilities. Specifically, TransGNN leverages Transformer layers to broaden the receptive field and disentangle information aggregation from edges, which aggregates information from more relevant nodes, thereby enhancing the message passing of GNNs. Additionally, to capture graph structure information effectively, positional encoding is meticulously designed and integrated into GNN layers to encode such structural knowledge into node attributes, thus enhancing the Transformer's performance on graphs. Efficiency considerations are also alleviated by proposing the sampling of the most relevant nodes for the Transformer, along with two efficient sample update strategies to reduce complexity. Furthermore, theoretical analysis demonstrates that TransGNN offers increased expressiveness compared to GNNs, with only a marginal increase in linear complexity. Extensive experiments on five public datasets validate the effectiveness and efficiency of TransGNN.
Peiyan Zhang, Yuchen Yan, Xi Zhang, Chaozhuo Li, Senzhang Wang, Feiran Huang, Sunghun Kim
2023-08-28T07:03:08Z
http://arxiv.org/abs/2308.14355v3
# Can Transformer and GNN Help Each Other? ###### Abstract. Although Transformer has achieved great success in natural language process and computer vision, it has difficulty generalizing to medium and large scale graph data for two important reasons: (i) High complexity. (ii) Failing to capture the complex and entangled structure information. In graph representation learning, Graph Neural Networks(GNNs) can fuse the graph structure and node attributes but have limited receptive fields. Therefore, we question that can we combine Transformer and GNNs to help each other? In this paper, we propose a new model named **TransGNN** where the Transformer layer and GNN layer are used alternately to improve each other. Specifically, to expand the receptive field and disentangle the information aggregation from edges, we propose using Transformer to aggregate more relevant nodes' information to improve the message passing of GNNs. Besides, to capture the graph structure information, we utilize positional encoding and make use of the GNN layer to fuse the structure into node attributes, which improves the Transformer in graph data. We also propose to sample the most relevant nodes for Transformer and two efficient samples update strategies to lower the complexity. At last, we theoretically prove that TransGNN is more expressive than GNNs only with extra linear complexity. The experiments on eight datasets corroborate the effectiveness of TransGNN on node and graph classification tasks. Graph data, Graph Neural Networks, Transformer + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: thanks: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research. + Footnote †: Both authors contributed equally to this research.
2308.12056
Unraveling the Neural Network: Identifying Temporal Labeling of Visual Events through EEG-Based Functional Connectivity Analysis of Brain Regions
Understanding the complex interplay between the brain and a dynamic environment necessitates the continuous generation and updating of expectations for forthcoming events and their corresponding sensory and motor responses. This study investigates the interconnectivity patterns associated with time perception in predictable and unpredictable conditions. EEG signals were obtained from an existing database, encompassing an experiment conducted on healthy participants subjected to two conditions: predictable and unpredictable, across various time delays. Functional connectivity between brain regions was estimated using the phase lag index method, allowing for the identification of differences in time perception between conditions. Comparative analysis revealed significant variations, particularly in the gamma, beta, and theta frequency bands, with more pronounced differences observed in the predictable condition. Subsequent exploration of the dissimilarities within each delay demonstrated significant differences across all delays. Notably, the unpredictable condition exhibited increased connectivity within the alpha band during the 400-ms delay, specifically between occipital and temporal regions, with higher mean connectivity compared to the predictable condition. In the delta band, distinct connectivity patterns emerged, involving connections between central and frontal regions across different delays. Notably, heightened connectivity between central and prefrontal regions was observed during the 83-ms delay. The right hemisphere of the prefrontal cortex played a pivotal role in time perception. Furthermore, a decline in connectivity across the delta, theta, and beta bands was observed during the longest delay (800 ms) in both conditions, relative to other delays.
Sina Khoonbani, Hasan Ramezanian
2023-08-23T10:55:19Z
http://arxiv.org/abs/2308.12056v1
Unraveling the Neural Network: Identifying Temporal Labeling of Visual Events through EEG-Based Functional Connectivity Analysis of Brain Regions ###### Abstract Understanding the complex interplay between the brain and a dynamic environment necessitates the continuous generation and updating of expectations for forthcoming events and their corresponding sensory and motor responses. This study investigates the interconnectivity patterns associated with time perception in predictable and unpredictable conditions. EEG signals were obtained from an existing database, encompassing an experiment conducted on healthy participants subjected to two conditions: predictable and unpredictable, across various time delays. Functional connectivity between brain regions was estimated using the phase lag index method, allowing for the identification of differences in time perception between conditions. Comparative analysis revealed significant variations, particularly in the gamma, beta, and theta frequency bands, with more pronounced differences observed in the predictable condition. Subsequent exploration of the dissimilarities within each delay demonstrated significant differences across all delays. Notably, the unpredictable condition exhibited increased connectivity within the alpha band during the 400-ms delay, specifically between occipital and temporal regions, with higher mean connectivity compared to the predictable condition. In the delta band, distinct connectivity patterns emerged, involving connections between central and frontal regions across different delays. Notably, heightened connectivity between central and prefrontal regions was observed during the 83-ms delay. The right hemisphere of the prefrontal cortex played a pivotal role in time perception. Furthermore, a decline in connectivity across the delta, theta, and beta bands was observed during the longest delay (800 ms) in both conditions, relative to other delays. These findings enhance our understanding of the neural mechanisms underlying time perception and underscore the impact of predictability on connectivity dynamics. temporal perception, predictable events, unpredictable events, EEG signals, functional connectivity analysis, Phase Lag Index (PLI), gamma band, beta band, theta band, alpha band, delta band, frontal lobe ## I Introduction The human brain can be regarded as a complex structure composed of numerous interconnected networks. As the brain functions as an integrated system, the performance of specific tasks within the brain is not solely derived from the isolated activities of its regions, but rather relies on the interaction and communication among its constituent parts. Therefore, examining the connections and interactions among the brain regions is crucial for a comprehensive understanding of brain activity. Investigations of brain interactions are conducted at various levels. Considering that the brain operates at a high speed, although the physical connections between regions may remain stable for several seconds, the functional communication (functional connectivity) between activities of different regions can vary on a small time scale, even within milliseconds. In this study, electroencephalography (EEG) signals are utilized to record the electrical activity of the brain [1]. EEG signals provide an approximate measurement of postsynaptic activity of neuronal cells with a temporal resolution on the order of milliseconds, enabling the description of brain activity dynamics [2]. Hence, the use of EEG can be valuable in investigating functional connections between regions due to its high temporal resolution. Various estimators, such as correlation estimators, partial coherence, mutual information, phase locking value, phase lag index, phase slope index, weighted phase lag index, etc., have been employed in studies to explore functional connections [3, 4, 5]. The concept of time is defined as a quantitative measure of various sequential events to compare their duration or the interval between them [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]. The traditional view, influenced by St. Augustine of Hippo philosophy, has been of interest to cognitive neuroscientists, suggesting that time is a composite of simultaneous and disjointed mental concepts. For instance, the past is constructed through memories, the present is shaped by attention, and the future is anticipated through prediction [25]. To interact with the changing environment we live in, the brain constantly requires generating and updating predictions about future events [26]. In fact, the ability to predict the timing of events in the environment enables humans to allocate the necessary processes for comprehension and appropriate action [27]. Additionally, in order to communicate with the surrounding environment, the brain needs to perceive the timing of events and utilize estimates of time to regulate sensory and motor responses. However, it is still unclear how the brain processes time. Furthermore, it has been well-established that the temporal concept is correlated with perceptual processing [28, 29, 30, 31, 32, 33, 34]. Recognizing regular timing is not the only temporal pattern that the brain is capable of perceiving. Recent studies on humans and primates have focused on investigating the brain's capacity to identify more complex temporal distributions apart from regular intervals [35, 36]. To understand how the brain operates during different time periods and utilizes them for external interactions, it is necessary to identify the regions and mechanisms involved in the temporal processing. It is evident that the brain should not rely solely on one mechanism or a specific region for all different temporal ranges. While an internal clock, which perceives time in the form of 24-hour intervals, has been identified as a known system [37], neural mechanisms operating at sub-millisecond to second timescales, representing temporal intervals, are still not fully comprehended [38]. Cellular activity changes related to temporal processing have been observed in the cerebellum [39], thalamus [40], posterior parietal cortex [41], prefrontal cortex [42, 43, 44, 45] and motor cortex [46] in monkey behavior. Furthermore, neurological disorders ultimately alter the functioning of the cerebral cortex, which may contribute to other timing impairments in Parkinson's Disease and early stages of diseases such as Huntington. Specifically, damage to the right frontal cortex and subcortical structures disrupts temporal perception [47]. Findings suggest that the prefrontal cortical regions may control attention and memory, which interact with timing processes [48]. In study [49], the aim was to investigate whether the prediction of stimulus timing modulates sensory labeling accuracy and whether the timing between the cue and stimulus has an impact on this modulation. EEG signals were recorded in predictable block conditions with stimuli presented after a fixed delay relative to the cue, and in unpredictable block conditions with stimuli presented after variable delay sequences (83, 150,400, and 800 milliseconds) relative to the visual cue. The predictability effect on behavior was observed at posterior parietal sites in the alpha power, specifically during the longest delay period (800 milliseconds). In fact, a significant difference and improvement in performance were observed between the predictable and unpredictable conditions at the 800-millisecond delay, indicating the influence of predictability on sensory processing. To better understand temporal processing in the brain, functional connectivity analyses were conducted using EEG signals and the Phase Lag Index (PLI) as a measure of connectivity in different brain regions. ## II Materials and Methods ### _Data Introduction_ In this study, data recorded from the article [49] were utilized. The experiment involved EEG data recorded at a sampling frequency of 1000 Hz with 64 AGCL/AG electrodes referenced to the mastoid bone. The impedance of the channels was maintained below 6 kilohms. The experiment was conducted on 29 healthy male individuals with normal vision, right-handed, and with an average age of 24 years. The experimental protocol was approved by the ethical committee of sirjan University of Medical and Sciences. A 24-inch display screen with a resolution of 1920\(\times\)1024 pixels was used in the experiment. The general experimental protocol is illustrated in Fig. 1. Initially, to ensure the participant's fixation and concentration, a fixation cross appeared. Then, stimuli were presented for 200 milliseconds, followed by a delay period. Subsequently, a visual stimulus in the form of clockwise or counterclockwise rotation appeared, and the participant was required to press the right or left key, respectively, depending on the rotation direction. Following that, to introduce a non-rhythmic aspect to the experiment (since rhythmic experiments involve the presentation of stimuli at brain frequencies), a delay was introduced. The delay was randomly sampled from a Gaussian [50, 51, 52, 53, 54, 55, 56, 57, 58] distribution with a mean of 900 milliseconds and a variance of 600 milliseconds. As mentioned, prior to stimulus presentation, a delay was introduced to transform the experiment into two conditions: predictable and unpredictable. Each block was predictable. In the predictable or unpredictable, it included 48 trials, where only one of the delays (83, 150,400, or 800 milliseconds) was considered as the target delay between the cue and the stimulus for all trials in each experiment. In the unpredictable condition, for each trial, the delay was randomly selected from the four delays (83, 150,400, or 800 milliseconds) to ensure that no delay coefficient was a multiple of another, thus avoiding the creation of harmonics in a specific rhythm. Additionally, the timing of each frame of the monitor (60 Hz frequency) was taken into account when selecting these delays to ensure proper alignment. The recorded signal aimed to investigate time perception in humans and the role of brain oscillations in timing information processing. In their study, they concluded that the temporal prediction effect on alpha power exists during the longest delay period (800 milliseconds). They observed that after the cue presentation, alpha power decreased in the predictable condition (from 172 to 373 milliseconds after the cue), compared to the unpredictable condition. However, before the stimulus presentation, alpha power increased in the predictable condition (305 milliseconds before the stimulus), compared to the unpredictable condition. The significant difference and improvement in performance were only observed during the longest delay period (800 milliseconds) between the two Fig. 1: General experimental protocol [49] conditions [49]. ### _Preprocessing_ The preprocessing steps were performed using MATLAB software and the EEGLAB toolbox. Initially, the recorded signals were imported into the software, and their DC offset was removed using a line base removal technique. To eliminate drifts and artifacts caused by very low-frequency components with significantly higher magnitude and power compared to EEG signals, a high-pass filter with a cutoff frequency of 0.5 Hz was applied. After filtering, visual inspection was performed on the signal, and the channels that were corrupted were replaced with neighboring channels using healthy channel signals. Subsequently, relative and visual data interpolation were applied to clean the data. The purpose of this process was to eliminate common noise present in all channels. For further cleaning, Independent Component Analysis (ICA) algorithm was applied to the signals, and then artifacts related to blinking, eye and neck movement, and so on, were removed. From the remaining 62 electrodes, a subset of 19 standard 10-20 electrodes fig.2 was selected for further analysis. These electrodes were chosen based on clinical relevance and their ability to cover the entire brain. After the electrode selection, segmentation was performed based on the specified timing as described in reference [49]. In this segmentation, a time interval of 500 milliseconds prior to the onset of the stimulus to 500 milliseconds after the stimulation was chosen. ### _estimate of correlation_ In the present study, the PLI (Phase Lag Index) was utilized to investigate the phase synchronization relationships in brain oscillations during a state where the phases of two oscillators were coupled. Phase synchronization refers to the simultaneous occurrence of phases despite their non-coherence in amplitude [59, 60, 61]. The foundations and theory of this method have been further examined in the following sections. #### Ii-C1 Phase lag index The Phase Lag Index (PLI) is a functional connectivity estimator defined by the equation1, which, theoretically, is resistant to volume conduction artifacts [62]. \[\text{PLI}=|\langle\text{sign}(\Delta\phi(\text{t},\text{k}))\rangle| \tag{1}\] In this equation, "sign" denotes the sign function,\(\Phi_{x}\) and \(\Phi_{Y}\) represent the phase of the momentary samples of two time series N and k = 1...N at discrete time steps tk, \(\Delta\Phi=\Phi_{x}-\Phi_{y}\), and N refers to the number of samples. Additionally, PLI values range from 0 to 1, where PLI is a statistical measure of dependence between time series that reflects the strength of their coupling. This method has been employed due to its lower sensitivity to volume conduction and common sources [63]. In this research, functional connectivity related to each of the 29 participants was estimated in the following frequency bands: delta (1-4 Hz), theta (4-8 Hz), alpha (8-13 Hz), beta (13-30 Hz), and gamma (30-49 Hz). The obtained results form 40 symmetric 19x19 matrixs, where the rows and columns correspond to the channels used in this study. Each element of the matrix represents the connectivity between two recorded channels. The elements of the matrix are symmetric with respect to the main diagonal because directionality is not relevant in functional connectivity. Therefore, in each matrix, the number of different states is equal to the following value: \[\frac{N\times(N-1)}{2}=\frac{18\times 19}{2}=171 \tag{2}\] The functional relationships were estimated by calculating the average values of PLI. Similarly, the correlation matrix was obtained for both predictable and unpredictable states, encompassing all possible delays. #### Ii-C2 statistical analysis of data After applying the necessary preprocessing steps to the data and estimating all the connections between brain channels, statistical analyses were performed. In this study, SPSS24 was used for performing the statistical analyses. Initially, the normality of the data was ensured using the Kolmogorov-Smirnov test with \(P\)-Value \(\geq 0.05\). The first step involved comparing the clockwise and counterclockwise stimulations at each of the four delays to determine if there was a significant difference. For this purpose, paired t-tests were conducted with eight paired samples (individuals in two different conditions). Subsequently, to examine whether there were significant differences among different delays within each condition, an one-way analysis of variance (ANOVA) was performed. To ensure significant differences and the results were confirmed using the False Discovery Rate (FDR) test [64]. To identify within-group differences, the Hoc-Post test was used. Finally, to determine if there were significant differences between predictable and unpredictable conditions for each delay, paired t-tests were conducted. ## III Findings and Discussion The analysis utilized data from 29 individuals, and all the data were examined in both predictable and unpredictable conditions. This comprehensive analysis allowed for a more thorough and accurate exploration of the delays associated with brain connectivity. Fig. 2: 19 selected electrodes ### _Comparison of stimulation with clockwise and counterclockwise shapes_ In this section, paired t-tests were conducted to compare the stimulation with clockwise and counterclockwise patterns. For each delay, a separate test was performed for the stimulation with clockwise and counterclockwise patterns across all frequency bands. The results of these tests did not reveal any significant differences. Based on the collected data and examination of the responses, it was observed that approximately 83% of the given responses were accurate in identifying the clockwise and counterclockwise stimulation. ### _Comparison of delays in two predictability and unpredictability conditions_ In this section, the focus was on examining significant differences between different delays in each separate predictable and unpredictable condition. The statistical test used for this purpose was ANOVA, which revealed significant differences in delays between the two conditions. tableI and tableII display the number of connections with significant differences. The largest differences were observed in the beta, theta, and gamma frequency bands, particularly in the beta and theta bands where the differences were quite noticeable, ranging from 83 milliseconds to 800 milliseconds. These differences were minimal in the delta band and very slight in the alpha band. These differences were observed in both the predictable and unpredictable conditions, although there were more differences in the predictable condition compared to the unpredictable condition. Further details regarding the differences between each delay in the 5 frequency bands are provided below. According to tableI and tableII, in the delta band of the predictable condition, the differences between delays of 83 ms with 800 ms, 150 ms with 800 ms, and 400 ms with 800 ms have increased. In this condition, the differences between the delays of 400 ms with 800 ms were particularly significant, with the majority of connections observed in the frontal region. In the unpredictable condition, the largest difference was observed between the delays of 150 ms and 800 ms, with more connections formed in the posterior region. The significant difference in this condition is relatively smaller compared to the predictable condition. In the theta band, the highest significant differences between delays of 83 ms with 800 ms, 150 ms with 800 ms, and 83 ms with 400 ms were observed in both the predictable and unpredictable conditions. In the predictable condition, the majority of connections were initially observed between the delays of 83 ms with 800 ms across the entire scalp. Subsequently, the differences between the delays of 150 ms with 800 ms were more prominent, with most connections observed in the frontal region and then in the posterior region. In the unpredictable condition, the largest differences were observed between the delays of 83 ms with800 ms, with most connections seen in the frontal region and then in the posterior region. In the alpha band, there was a very small but significant difference between the delays in the predictable condition. Two significant differences were observed between 83 and 150 milliseconds, indicating a correlation between the frontal and parietal regions. In the unpredictable condition as well, a significant difference was observed between 83 and 150 milliseconds, indicating a correlation between the parietal and frontal regions. In the beta band, the greatest significant differences in delays were observed between 83 and 800 milliseconds, and 150 and 800 milliseconds, in both the predictable and unpredictable conditions. In the predictable condition, initially the greatest delay was observed between 83 and 800 milliseconds, which was consistently observed throughout the experiment. Subsequently, the differences between 150 and 800 milliseconds were greater, indicating stronger correlations in the parietal region initially, and then in the frontal region. In the gamma band, in the predictable condition, the greatest differences were observed initially between 83 and 400 milliseconds, followed by differences between 83 and 800 milliseconds, with the strongest correlations initially observed in the parietal region and then in the posterior region. In the unpredictable condition, significant differences were observed between 150 and 400 milliseconds, with stronger correlations in the parietal region. ### _Comparison of Predictable and Unpredictable Scenarios for Each Delay_ In this section, we examined whether there are significant differences between the predictable and unpredictable scenarios for each delay. The analysis was conducted across a frequency range of 1 to 40 Hz, and the network of connections was presented in the following figures. Subsequently, separate calculations were performed for each frequency \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline Delays & delta & theta & alpha & Beta & Gamma \\ \hline 83-150 & 0 & 0 & 1 & 1 & 0 \\ \hline 83-400 & 0 & 7 & 0 & 1 & 26 \\ \hline 83-800 & 3 & 41 & 0 & 23 & 17 \\ \hline 150-400 & 0 & 1 & 0 & 1 & 34 \\ \hline 150-800 & 5 & 15 & 0 & 11 & 32 \\ \hline 400-800 & 1 & 6 & 0 & 1 & 0 \\ \hline \end{tabular} \end{table} TABLE II: -The number of significant correlations \(P\)-Value \(\geq 0.05\) among the delays in the unpredictable condition \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline Delays & delta & theta & alpha & Beta & Gamma \\ \hline 83-150 & 0 & 5 & 2 & 1 & 0 \\ \hline 83-400 & 0 & 30 & 0 & 14 & 104 \\ \hline 83-800 & 10 & 137 & 0 & 77 & 67 \\ \hline 150-400 & 0 & 5 & 0 & 5 & 53 \\ \hline 150-800 & 16 & 71 & 0 & 41 & 22 \\ \hline 400-800 & 17 & 6 & 0 & 5 & 0 \\ \hline \end{tabular} \end{table} TABLE I: -The number of significant correlations \(P\)-Value \(\geq 0.05\) 05 among the delays in the predictable condition band. The network of connections in the alpha band was compared to the results presented in reference [49]. The results for other frequency bands were also provided along with their analysis. To display the results, threshold values were determined based on the average \(\pm\) standard deviation. If the difference exceeded this threshold, it was considered significant and displayed; otherwise, it was not shown. The thickness of the lines in the figures represents the strength of the connection. In the subsequent analysis, the differences between the predictable and unpredictable scenarios were examined for each delay in all frequency bands, and the results are presented below. with increasing delays. In the delay of 150 milliseconds, strong connections are observed in the parietal and posterior regions compared to other connections at this delay. To assess the significant difference between the predictable and unpredictable scenarios, a paired t-test with a significance level of \(\alpha\)=0.05 has been conducted. The results indicate a significant difference in all delays, and particularly, larger significant differences are observed in the delays of 150 and 400 milliseconds compared to the other delays. in Figs. 7-10, the network of communication in the alpha band is observed, indicating information flow between the posterior and anterior regions. Furthermore, in both scenarios, there is communication between the two hemispheres for all delay groups. It is expected that in the predictable scenario, different regions of the brain are engaged in training at different times. Additionally, the study's findings reveal learning in the alpha band in the parietal regions, even before the stimulation, when the brain is in a training state, aligning with the results of reference [65]. Moreover, a study on neural imaging of time perception, described in reference [66], demonstrated that cortical areas such as the parietal cortex are involved in regulating temporal durations.In the unpredictable scenario, in the 400 ms delay while in the 800 ms delay, there is increased connectivity between the posterior regions and the anterior regions. The findings of this study exhibit differences in brain maps for different delays. To investigate whether there is a significant difference between the two scenarios, a paired t-test with \(\alpha\)=0.05 has been conducted, and significant correlations have been observed in all delays. In the 400 ms delay, the average connectivity in the unpredictable scenario is higher than in the predictable scenario. In the 800 ms delay, the average differences in connectivity between the unpredictable and predictable scenarios are greater in the anterior regions compared to the posterior regions. Similar significant differences have been observed in the other frequency bands, which are reported in detail below. In the delta band, for the 150 ms, 400 ms, and 800 ms delays in the predictable scenario, there was connectivity between the central and frontal regions. Additionally, in the 83 ms delay, there was strong connectivity from the central region to the anterior region. Moreover, in the 800 ms delay, there was a very strong connection from the central region to the frontal region. In the unpredictable scenario, for all delays, the number of connections was higher compared to the predictable scenario. In this scenario, although there were strong connections in the 800 ms delay, the number of connections decreased compared to other delays. In the 83 ms and 150 ms delays, there was also a very strong connection between the parietal and frontal regions. In the theta band, in both scenarios, there were connections observed in the frontal, prefrontal, and parietal regions for all delays. However, in the 800 ms delay, the number of connections decreased compared to other delays. Additionally, in the study mentioned in reference [67], it has been shown that exposure to timing estimation tasks affects the severity of intententive symptoms, ADHD, and theta band activity in the lateral posterior frontal cortex. In the beta band, in the 800 ms delay, there was a decrease in connections compared to other delays in both scenarios. Additionally, the prefrontal region had connections to other areas in all delays, and in the unpredictable scenario, there were more connections compared to the predictable scenario. In the gamma band, in the unpredictable scenario, there were connections throughout the brain for all delays, and in the predictable scenario, there were connections for the delays of 83 and 150 milliseconds. Additionally, there were connections between the posterior and anterior regions in both scenarios. Furthermore, in the article referenced as [68], it is shown that intervals of less than a second and processing time are associated with increased cognitive functions in areas including the prefrontal cortex. The results reported in paper [49] indicate that predictability has an effect on behavior at a delay of 800 milliseconds. The authors concluded that there is a predictive timing effect on alpha power during the longest delay period (800 milliseconds). In their experiments, it was found that after the presentation of a cue, alpha power decreased in the predictable condition (between 172-373 milliseconds after the cue) compared to the unpredictable condition, while before the stimulus presentation, alpha power increased in the predictable condition (305 milliseconds before the stimulus) compared to the unpredictable condition. Their study only observed a significant difference between the predictable and unpredictable conditions at the longest delay (800 milliseconds), whereas, Fig. 10: illustrates the average correlations in two conditions, predictable (A) and unpredictable (B), along with their significant differences (C), for the alpha band at a delay of 800 milliseconds estimated using the PLI method. (The green line indicates a higher average correlation in the unpredictable condition compared to the predictable condition, while the orange line indicates the opposite trend.) Fig. 9: The average correlations in two conditions, predictable (A) and unpredictable (B), along with their significant differences (C), for the alpha band at a delay of 400 milliseconds estimated using the PLI method. (The green line represents a higher average correlation in the unpredictable condition compared to the predictable condition, while the orange line indicates the opposite trend.) in the current study, a significant difference between the two conditions was observed at all delays. ## IV conclusion The results indicate that there was no significant difference observed between the clockwise and counterclockwise stimuli. Comparing the delays in both the predictable and unpredictable conditions, the findings suggest that the greatest differences in delays were observed in the gamma, beta, and theta bands, with the largest differences between the 83 and 800 milliseconds delays in the beta and theta bands. In the study by Rajkumar et al. [69], it was shown that participants who perceived time as shorter than the physical time exhibited higher beta power and higher coherence in central regions. Additionally, in the study by [70], a correlation matrix of connectivity was demonstrated between the frontal-central and posterior regions across all frequencies. In the current study, it was observed that, in comparison of delays, both in the predictable and unpredictable conditions, there were connectivity patterns between the frontal-central regions in all frequency bands except for alpha. In this section, a significant difference was observed between the delays, with a greater difference observed in the predictable condition compared to the unpredictable condition. By examining these significant differences, it is possible to extract the regions that were more involved in the process. The article referenced in [71] states that the brain does not exhibit significantly different neuronal spike activity in time intervals less than 500 milliseconds. Therefore, it is suggested to design an experiment with delays ranging from 2 to 3 intervals above 500 milliseconds in order to analyze temporal events with greater clarity and accuracy. Additionally, to reduce participant fatigue without compromising the integrity of the experiment, it is recommended to use fewer trials per delay group.
2301.01521
Artificial neural network as an effective tool to calculate parameters of positron annihilation lifetime spectra
The paper presents the application of the multi-layer perceptron regressor model for predicting the parameters of positron annihilation lifetime spectra using the example of alkanes in the solid phase. A good agreement of calculation results was found when comparing with the commonly used methods. The presented method can be used as an alternative quick and accurate tool for decomposition of PALS spectra in general. The advantages and disadvantages of the new method are discussed.
M. Pietrow, A. Miaskowski
2023-01-04T10:18:58Z
http://arxiv.org/abs/2301.01521v1
Artificial neural network as an effective tool to calculate parameters of positron annihilation lifetime spectra ###### Abstract The paper presents the application of the multi-layer perceptron regressor model for predicting the parameters of positron annihilation lifetime spectra using the example of alkanes in the solid phase. A good agreement of calculation results was found when comparing with the commonly used methods. The presented method can be used as an alternative quick and accurate tool for decomposition of PALS spectra in general. The advantages and disadvantages of the new method are discussed. ## 1 Introduction Positron Annihilation Lifetime Spectroscopy (PALS) is one of the useful experimental methods using positrons for studying structural details in a wide spectrum of materials, in particular in the solid state [1]. This method is based on the annihilation of positrons where their lifetime and annihilation intensity in the sample is dependent on some properties of the material in the nano scale, including local electron density, bound electron energy, and the density and size of free volumes in the sample. Depending on the material, besides the process of direct annihilation, a positron can form a meta-stable atomic state with an electron, called a positronium (Ps), which can exist in two spin states referred to as _para-_ and _ortho_-Ps differing in properties (especially, their lifetimes differ in vacuum by three orders of magnitude) [2]. A number of conditions must be met for the Ps to be formed in matter. One of them is that free volumes of a sufficiently large size must be present. For these materials, a Ps is extremely useful in material science since its lifetime can be related to the size of free volumes [3]. Depending on the structure of the sample, there is possibly a variety of Ps components which annihilate with characteristic lifetimes. All these populations give their own account to the positron annihilation spectrum measured experimentally. PALS spectra require decomposition in the post-measuring procedure of decomposition resulting in both the calculation of lifetimes for particular species of positrons and the relative amplitudes for these processes (so-called spectrum inversion problem) [4]. Many algorithms used for data processing require assuming an exponential character of positron decay. They also require fixing the number of components used during the decomposition. For example, the method used by one of the adequate software, the LT programme [5] or PALSfit [6], consists in fitting the PALS experimental spectrum to a sum of a given number of exponential functions usually convoluted with the (multi) gaussian apparatus resolution curve. The PALS spectra used here were measured for normal alkanes (n-alkanes), i.e. the simplest organic molecules where carbon atoms form a straight chain of the molecule and are saturated by hydrogen atoms. The n-alkanes with a different number \(n\) of carbon atoms in the molecule form a homologous series described by the general chemical formula \(\mathrm{C}_{n}\mathrm{H}_{2n+2}\) (\(\mathrm{C}n\) is used as an abbreviation). Alkanes in the solid phase form molecular crystals where the trains of elongated molecules are separated by gaps called the inter-lamellar gaps. Ps can be formed in the free volumes made by both the gaps and the spaces generated by changes in the conformation with temperature [3]. Using the PALS technique, the size of these free volumes can be determined from the lifetime and the relation between both being given by the Tao-Eldrup formula or its modification [7]. According to our previous analysis of alkanes carried out with the use of the PALS technique, the best results of the spectrum decomposition are achieved assuming only one population of _ortho_- and _para_-Ps, whereas the ratio of the _ortho_ to _para_ intensity is fixed at 3/1. Tools of machine learning like genetic algorithms or artificial neural networks have been used to perform numerical calculations in a variety of aspects in positron science [8, 9, 8, 10, 11, 12]. They have also been used for unfolding the lifetimes and intensities from PALS spectra [13, 14, 15, 16]. Possibly due to the low computing power of the hardware and the low time resolution of PALS spectrometers at the time when the neural network algorithms for decomposition of PALS spectra were proposed, most of the spectra used in these calculations are simulated by the software but not measured directly. For the same reason, the neural network architecture used there does not allow changing parameters as much as is allowed by algorithms developed today. Furthermore, no procedure allowing application for the same calculations of spectra registered for different time constants per channel has been presented since then. Thus, the preferred software used for spectrum decomposition is still based on non-linear fitting algorithms which do not include a possibility of establishing the result based on a multi-spectra set at the same time. Here, we present an approach to analysis of PALS spectra based on the multi-layer perceptron (MLP) model, which is one of the tools of machine learning [17]. The model assumes a network of inter-connected neurons grouped in the input layer (\(\texttt{In}_{i}\)), the hidden neurons layers (\(\texttt{h}_{i}^{k}\)) and the output neurons layer (\(\texttt{Out}_{i}\)), where \(i\) goes over the neurons in a given layer and \(k\) numbers the hidden layers. A graphical diagram of the network used is shown in fig. 1. The numbers of In and Out neurons are determined by the amount of the independent input data introduced to the network and the data defined to be the results of calculation in a given problem, respectively. The number of hidden layers and the number of neurons within these layers are set experimentally to optimise the network to give required results. To each layer (excluding the output layer), one bias neuron is attached for technical reasons [18]. The tool assumes the learning process first, where the In neurons are fed with the data for which the result of the Out neurons is known in advance. During this process, the weight coefficients for pairs of inter-connected neurons are adjusted by an algorithm, so that the output of the MLP can give results most similar to the expected ones. The MLP becomes to be trained after a number of iterations of training. Once the MLP results of learning are satisfied, the MLP can be used to calculate the output for the input data never used in the training process. Figure 1: Schematic view of the MLP applied. The PALS data from consecutive channels of the MCA are transferred as the amplitudes of the consecutive input neurons \(\texttt{In}_{i}\). \(\texttt{h}_{i}\) denote neurons in the \(i\)-th hidden layer whereas \(\texttt{Out}_{i}\) denote output neurons returning chosen PALS decomposition parameters. The MLP type of network can be applied to solve the problem of both classification and regression. For the first group of problems, it is required from the MLP to ascribe the values of the output parameters in the form of well separated categories. These so-called _labels_ can always be parametrised by a discrete set of numbers. The problem described in this paper is classified as rather a regression problem (MLPR) where the values of the output at each Out neuron are characterised by a continuous set of values. Consequently, the output may contain values approaching these appearing during the learning process but may not necessarily be exactly of the same value. The internal algorithms of the MLPR allows regarding the learning process as a way of finding the quasi-continuous output function of input parameters. In our case, based on the data from the PALS spectra applied as the input values of the perceptron, the MLPR is used for solving the regression problem of finding the values of key PALS parameters on the output. ## 2 Method The _scikit-learn_ library was used to estimate the PALS parameters for alkanes [19]. In our case, the MLP regressor class (called _MLPRegressor_), which belongs to one of the supervised neural network models, was implemented. In this class, the output is a set of continuous values. It uses the square error as the loss function. This model optimises the squared error using the Broyden-Fletcher-Goldfarb-Shanno algorithm (LBFGS) [20], which belongs to quasi-Newton methods. Some MLPRegressor parameters playing a key role are mentioned below. Their values require to be tuned, especially the alpha hyper-parameter, which helps in avoiding overfitting by penalising weights with large magnitudes. A full list of parameters of MLPRegressor is defined in [21]. In the learning process here, we used spectra collected for years from an analog spectrometer for several alkanes (in the range of C\({}_{6}\) - C\({}_{40}\)) measured at several temperatures (-142\({}^{\circ}\)C - 100\({}^{\circ}\)C). Irrespective of both the goal of the particular experiment and the length of the alkane chain used as a sample, the initial assumptions made for starting the analysis of the spectra made by the LT programme [5] were the same. Each measurement resulting in the spectra used was performed with a sample prepared in a similar way, i.e. the sample was degassed, and the rate of cooling or heating was the same. In each case, the measurement at constant temperature took place for at least one hour which gave some hundreds of thousands of annihilations (the strength of the radioactive source was similar in each case). During some experiments the temperature was changed stepwise but each spectrum was collected at constant temperature. The most important issue here is that the post-experimental analysis of the spectra was conducted under the same general assumptions every time. Especially, for the decomposition of these spectra, we used LT supposing that the time resolution curve can be approximated by one-gaussian curve. Every time it was assumed that the annihilation process in the Kapton envelope accounted for 10% (so-called _source correction_). Additionally, only one component was always assumed for _para_- and _ortho_-Ps, whereas their intensity ratio was fixed at the value 3/1 (see [22] for details of the experimental procedure). Taking into account these assumptions, each spectrum was decomposed into three exponential curves for which the intensities (\(I\)) and lifetimes (\(\tau\)) were calculated for the following sub-populations of positrons: the free positron annihilation (\(I_{2}\), \(\tau_{2}\)), _para_ (\(I_{1}\), \(\tau_{1}\)), and _ortho_-Ps (\(I_{3}\), \(\tau_{3}\))1. The database collected in this way contained 7973 PALS spectra, wherein about 75% were used in the neural network training process and the rest were used as a testing set for checking the accuracy of the results given by the learned network. Footnote 1: Numbering of the indices is related to the length of \(\tau\). The increasing values of the indices correspond to the rising length of lifetime. The number of input neurons is determined by the number of channels of the Multi-channel Analyser (MCA) module of the PALS spectrometer recording PALS spectra. Furthermore, the number of the output neurons is related in this model to the number of PALS parameters, which are supposed to be predicted for further studies of physical processes in the sample. The decomposition of the PALS spectrum made by commonly used programs, like LT, allows determining (\(I\),\(\tau\)) pairs for all assumed components of a given spectrum. However, often, not all these parameters are needed for further analysis. Furthermore, some of these parameters are inter-dependent. For example, in the case of PALS spectra for the alkanes discussed here, one assumes that the spectrum is built up by events from the three populations of positrons mentioned above (\(\tau_{1}\) - \(\tau_{3}\), \(I_{1}\) - \(I_{3}\) parameters). However, from the practical view point, only \(\tau_{2}\), \(I_{2}\), \(\tau_{3}\), and \(I_{3}\) are then used for studying physical processes and the structure of the sample. Furthermore, in this case, \(I_{i}\) are inter-dependent and fulfil the following relations \(I_{1}\)+\(I_{2}\)+\(I_{3}\)=100%2 and \(I_{3}\)/\(I_{1}\)=3. Thus, effectively, the parameters considered as the Out parameters of MLPR are only \(I_{2}\), \(\tau_{2}\), and \(\tau_{3}\). According to this, we declared in our modelling only three output neurons for receiving values for these three parameters. ## 3 Preparation of input and output data During the PALS measurements, the time constant per channel (\(\Delta\)) varied, depending on the internal properties and settings of the spectrometer. Most of the data used here were collected with \(\Delta\)=11.9 ps; however, some spectra were measured with \(\Delta\)=11.2 ps, 13.2 ps, 11.6 ps, and 19.5 ps (fig. 2). Therefore, it is important for the In neurons to code the PALS amplitude samples not in the relation to the channel numbers but in the scale of time. Hence, in addition to the spectrum amplitudes, the regressor has to learn the times associated with these amplitudes. Thus, one half of the In neurons is fed with time values for consecutive channels of a spectrum, whereas the second half is fed with the values of their amplitude. The advantage of the regression approach applied here is the ability to test spectra measured even for a time sequence that has never appeared in an extreme case in the training process. This method requires setting correctly a common zero-time for each spectrum. To achieve this, the original data from the left slope of the spectrum peak (and only a few points to its right) were used to interpolate the resolution curve, which is assumed to be in the gaussian form. The position of this peak defines a zero-time for a spectrum. One-gaussian interpolation is compatible with previous LT analysis assumptions. Based on the common starting position for all spectra established in this way, the values of time for each channel on the right to the peak were re-calibrated for each spectrum depending on \(\Delta\) for which the spectrum was measured. Finally, for further analysis, we took the same \(N\) number of consecutive channels for each spectrum on the right to its peak (points \(p_{i}\) in fig. 3). The \(\delta\) parameter shown in fig. 3 denotes the distance (in time units) between the first point on the right to the peak and the calculated time position of the peak. The number \(N\) taken for further analysis was established experimentally. Finally, the spectrum data for the MLPR input are the \(N\) points \(p_{i}\) with their two values: the re-calibrated number of counts in a given channel (see below) and their re-calibrated times of annihilation. Then, to minimise errors, the original input data were transformed before application. Each original spectrum was stored in 8192 channels of MCA. Firstly, starting from the first channel on the right to the spectrum maximum (\(p_{1}\) in fig. 3), 2k channels were taken from the original spectrum. This means that the spectra were truncated at about 25 ns of the registration time (varying to some extent, depending on the \(\Delta\) for a given spectrum). Secondly, to smooth random fluctuations, the data were smoothed in most cases. One of the examples of smoothing is averaging over five consecutive channels. In this case, the number of samples in each spectrum shrank from the original 2k channels to the amount of 400. Since the In neurons transfer information about the pair of values - times (\(t\)-part) and amplitudes (\(A\)-part), 800 input neurons that fed the MLPR with the data in this case were declared. Thirdly, to standardise the range of the input data values, the set of the PALS amplitudes was normalised to the maximum value of the amplitude and then logarithmised. According to these transformations, the \(A\)-part data covered the numerical range [-9,0] - fig. 4. Furthermore, to adjust the range of the values in the \(t\)-sector, the values of time were divided by -2.5. As a result, all data transferred Figure 2: Number of spectra (horizontal axis) with a given value of the time constant per channel \(\Delta\) (vertical axis) used as a data set in the presented calculations. to the In neurons were in the range of [-10,0]. Additionally, we applied some transformation of the original values for the Out neurons in order to have their values at each neuron scaled to the same range. Initially, the first output neuron is related to \(I_{2}\), whereas its original value range is typically tenths (in % units). The second neuron transfers the information related to \(\tau_{2}\) whose original values are of the order of 0.1 (of ns), whereas the order of \(\tau_{3}\) related to the third neuron is originally 1 (of ns). In order to have the uniform order of numerical values on all Out neurons, the data that finally feed with them are [\(I_{2}\)/10, \(\tau_{2}\)\(\cdot\)10, \(\tau_{3}\)]. The criterion of acceptance of training the network was the best value of the score validation function defined for this regressor as \[\mathcal{S}=1-\frac{\sum_{N}(\mathcal{O}_{\text{true}}-\mathcal{O}_{\text{ pred}})^{2}}{\sum_{N}\mathcal{O}_{\text{true}}^{2}}, \tag{1}\] where \(\mathcal{O}_{\text{true}}\), \(\mathcal{O}_{\text{pred}}\) - expected (known) and calculated (predicted) values of the result, respectively [19, 21]. \(\mathcal{S}\) is calculated for both the learning and testing sets separately. \(N\) here denotes the number of spectra in the trained or tested set. The optimum value of \(\mathcal{S}\) is \(\approx\)1. Figure 4: Input data directed to In neurons can be divided into two sub-sets: \(t\)-part which is a set of time values for points \(p_{1}\), \(p_{2}\),... (see fig. 3) and \(A\)-part coding the log function of their normalised amplitudes. In special cases, these data are smoothed or compressed before use in MLPR. Figure 3: Schematic view of a peak region of the PALS spectrum. The bullets indicate \((t,log(A))\) pairs saved in the MCA channels, whereas the star indicates a position of a peak calculated assuming a gaussian shape of an apparatus distribution function. Only the points to the right of the star (\(p_{1}\), \(p_{2}\),...) are taken as data introduced to MLPR. The \(\delta\) parameter denotes a time distance between the calculated peak and the first point, whereas \(\Delta\) is the time distance between two points. ## 4 Results The MLPRegressor used in these calculations requires establishing some key parameters [21] influencing the ability to learn and a speed of the learning process. We performed some tests trying to optimise these parameters. The best results we obtained by the settings shown in tab. 1. Both the names and the meaning of the technical parameters shown in the table are identical to these defined in the routine description [21]. Once the key parameters of the MLPR were established (especially the solver), we performed tests of credibility of the network changing the number of hidden layers, the number of neurons within (hidden_layer_sizes parameter), and the alpha parameter. The results in tab. 2 show examples of the results. For these networks, we specified the mean validation score parameter for both the training \(\langle\mathcal{S}_{tr}\rangle\) and testing \(\langle\mathcal{S}_{te}\rangle\) sets separately with their variation \(\delta\mathcal{S}\). Averaging was made over the results of ten runs of the training process for identical networks differing by initially random weights. We did not notice any rule giving a ratio of the numbers of neurons that should be declared in the consecutive hidden layers (especially as the number of neurons should decrease proportionally in the consecutive layers). A few initial examples shown here suggest that the accuracy of results increases when both the number of hidden layers and the number of neurons inside increase. However, the last two rows of the table show that a further increase in these parameters does not give better results. Finally, the network that gave a nearly best result was chosen (marked in bold \(\langle\mathcal{S}_{tr}\rangle\) in the table). It was checked for this network that an increase in the iterations of training (max_iter parameter) beyond about \(5\cdot 10^{9}\) did not improve \(\langle\mathcal{S}\rangle\). For several finally tested networks, the spectrum of the magnitude of inter-neurons weights was checked. It is expected that weights that differ significantly from the average range of values may affect the stability of the results. In this case, the range of weight values seems to be quite narrow. As shown in fig. 5, the weight magnitude order (exponent of weights) for the chosen network ranges from \(10^{-5}\) to \(10^{0}\), while the relative number of cases in these subsets changes exponentially. The lack of values outside the narrow set of values \begin{table} \begin{tabular}{|c|c|} \hline Parameter & value \\ \hline \hline hidden\_layer\_sizes = & 7\(\times 150\) \\ activation = & _relu_ \\ solver = & _lbfgs_ \\ alpha = & 0.01 \\ learning\_rate = & _invscaling_ \\ power\_t = & 0.5 \\ max\_iter = & 5e+9 \\ random\_state = & None \\ tol = & 0.0001 \\ warm\_start = & True \\ max\_fun = & 15000 \\ \hline \end{tabular} \end{table} Table 1: Values of the MLPRegressor parameters applied for producing the final MPLR results. \begin{table} \begin{tabular}{|c|c|c|c|c||c|c|} \hline hidden\_layer\_sizes & max\_iter & alpha & \(\langle\mathcal{S}_{tr}\rangle\) & \(\delta\mathcal{S}_{tr}\) & \(\langle\mathcal{S}_{te}\rangle\) & \(\delta\mathcal{S}_{te}\) \\ \hline \hline \(30\times 25\times 15\) & \(10^{6}\) & 0.7 & 0.950 & 0.003 & 0.942 & 0.004 \\ \hline \(3\times 100\) & \(10^{8}\) & 0.7 & 0.969 & 0.005 & 0.965 & 0.008 \\ \hline \(3\times 100\) & \(10^{8}\) & 0.1 & 0.974 & 0.005 & 0.968 & 0.008 \\ \hline \(3\times 100\) & \(5\cdot 10^{8}\) & 0.1 & 0.975 & 0.003 & 0.976 & 0.003 \\ \hline \(4\times 100\) & \(10^{8}\) & 0.1 & 0.978 & 0.004 & 0.975 & 0.006 \\ \hline \(500\times 400\times 300\times 200\) & \(5\cdot 10^{9}\) & 0.01 & 0.977 & 0.003 & 0.974 & 0.007 \\ \hline \(7\times 150\) & \(5\cdot 10^{8}\) & 0.01 & **0.985** & 0.002 & 0.975 & 0.013 \\ \hline \(500\times 500\times 400\times 400\times\times\times\times 300\times 200\times 200\) & \(5\cdot 10^{9}\) & 0.01 & 0.978 & 0.005 & 0.977 & 0.008 \\ \hline \(8\times 500\) & \(5\cdot 10^{9}\) & 0.01 & 0.982 & 0.004 & 0.980 & 0.005 \\ \hline \end{tabular} \end{table} Table 2: Evaluation score for chosen values of some MLPR parameters. \(\mathcal{S}\) values are averages over 10 runs with random initial neuron weights. A nearly optimum case of parameters is placed in a row with \(\mathcal{S}\) marked in bold. suggests that self-cleaning of the resultant weights is performed by the MLPRegressor algorithm itself. The number of all PALS spectra used as a database for the network was 7973, and 6500 were used to learn the output values (training set) by the network, while the rest were used for checking the results of learning (testing set). Tab. 3 shows a few examples of randomly taken results given by one of the networks finally used. The results given by the trained network were compared to the expected values known from the LT analysis. Although \(\mathcal{S}\) for both the trained and tested sets in this case is not the highest one obtained in our tests, the result of the use of this network is satisfactory in a practical sense because the deviation of the predicted and expected result is in the range of deviation given by LT itself. The problem of pre-preparation of spectra for calculations by MLPR is worth mentioning. The main problems are where the spectrum should be cut and to what extent it is acceptable to smooth the spectra by averaging their consecutive values. As for the first problem, it was determined by series of runs for which the spectra were cut at other that mentioned limit of 2k channels that this number of channels was almost the best choice. \(\langle\mathcal{S}\rangle\) was found to worsen in the case of a shorter cut (say, 1.5k channels), and did not improve significantly in the case of the longer ones (e.g. 3k channels) (but it took longer to compute the result because of an increase in the number of In neurons). \begin{table} \begin{tabular}{|c|c|c|c|c|c|c|} \hline \multirow{2}{*}{Example} & \multicolumn{2}{c|}{\(I_{2}\) [\%]} & \multicolumn{2}{c|}{\(\tau_{2}\) [ns]} & \multicolumn{2}{c|}{\(\tau_{3}\) [ns]} \\ & expected & predicted & expected & predicted & expected & predicted \\ \hline 1 & 68.0 & 68.8 & 0.27 & 0.28 & 1.21 & 1.20 \\ \hline 2 & 47.2 & 47.6 & 0.38 & 0.39 & 3.23 & 3.18 \\ \hline 3 & 65.4 & 65.5 & 0.30 & 0.29 & 1.35 & 1.38 \\ \hline 4 & 78.3 & 78.3 & 0.23 & 0.24 & 1.11 & 1.12 \\ \hline 5 & 52.4 & 52.4 & 0.35 & 0.34 & 2.93 & 2.93 \\ \hline 6 & 60.5 & 60.4 & 0.31 & 0.30 & 1.25 & 1.20 \\ \hline 7 & 59.3 & 58.8 & 0.29 & 0.29 & 1.19 & 1.22 \\ \hline 8 & 61.0 & 62.3 & 0.30 & 0.31 & 1.91 & 1.91 \\ \hline 9 & 70.2 & 69.5 & 0.21 & 0.21 & 1.06 & 1.10 \\ \hline 10 & 39.9 & 38.8 & 0.23 & 0.22 & 1.15 & 1.13 \\ \hline \end{tabular} \end{table} Table 3: Examples of a few randomly taken results of calculations (prediction) of the \(I_{2}\), \(\tau_{2}\), and \(\tau_{3}\) parameters compared to the expected values calculated by LT. Here, hidden_layer_size=7\(\times\)150, \(\mathcal{S}\)=0.985 for both training and testing sets. Figure 5: Number of cases (log scale) of exponents of weights for a network with 7\(\times\)100 hidden layers. For this network, the key parameters are: solver=_blfgs_, max_iter=5\(\cdot\)10\({}^{11}\), alpha=0.005, learning_rate=_invscaling_, and activation=_relu_. The accuracy of the prediction increases when the learning and testing processes are limited to one only \(\Delta\) with all parameters of the network kept constant. In this case, the set of values in the \(t\)-part for every spectrum varies in a much narrower range (only \(\delta\) changes). In this case, the training process is more effective even if the size of the training set is reduced. To show this, we separated the set of spectra measured for only one \(\Delta\)=11.9 ps. Consequently, the whole set of samples under consideration shrank to 4116 members, and 3000 of them were used for training after the transformations described above. The score \(\mathcal{S}\) obtained in this case was much greater than \(\mathcal{S}\) for an identical network applied to spectra with all possible \(\Delta\). The comparison of these two cases is shown in tab. 4 (the last row of the table). Here, to have the result reliable for networks with different (random) initial weights, the score was averaged over 30 runs. The validation score \(\mathcal{S}\) is sensitive to smoothing the spectrum which reduces to some extent the information given by the PALS spectrum. In tab. 4, two cases are compared where each 3- and 5-tuples of points of the spectrum (forming non-overlapping windows) were taken to calculate their average amplitude. For example, \(N\)=3500 points of the initial spectrum are reduced to 700 points when averaging over \(k\)=5 points; when the remainder of the division of \(N\) by \(k\) is not zero, an integer quotient is taken. \(\langle\mathcal{S}\rangle\) calculated for these two cases shows that both of them give the same results statistically. However, further shrinking the spectrum by setting \(k\)=6 or more produces worse \(\mathcal{S}\). Tab. 4 also shows the \(\mathcal{S}\) parameter when the moving average is applied during preparation of spectra. The sampling window applied here is 10. The comparison of this result to the result of calculation with unsmoothed data shows that the application of the moving average does improve predictions for the testing data set. ## 5 Conclusions We have shown in this paper that the easy-to-reach machine learning MLPRegressor tool enhanced with some programming in _Python_ making some preparation of data, can be used as an alternative method of solving the problem of inversion of PALS spectra. The main disadvantage of the presented method is the need of decomposition of training spectra by other software to have Out values for training. Once the training set is collected and the network is trained, the algorithm works very quickly, giving the result for the tested spectrum. The training process used here is based on results given by LT, i.e. a method producing results with some uncertainty itself. The uncertainty produced by the LT is caused by the use of numerical methods to compute the fit in particular cases. On the other hand, since the MLPR prediction bases on information from a large set of spectra, this approach seems to be less sensitive to the specific shape of a given spectrum and may be more accurate in predicting parameters. Furthermore, the presented method seems to be faster than the referenced ones, since calculations made by a trained network are reduced to simple transformations of matrices and vectors, which is not demanding computationally and less sensitive to numerical problems. Although the model presented here is similar to that described in [14] (and repeated in [15]), there are significant differences indicated in tab. 5. Our experimental data are collected by spectrometers differing in functional properties, especially differing in time resolution. Even for one spectrometer, this parameter should be re-calibrated periodically due to changes in experimental conditions, especially temperature. In the algorithm \begin{table} \begin{tabular}{|l|l|c|c|} \hline \multicolumn{2}{|c|}{MLPR and spectra parameters} & \multicolumn{1}{c|}{\(\langle\mathcal{S}_{tr}\rangle\)} & \multicolumn{1}{c|}{\(\langle\mathcal{S}_{te}\rangle\)} \\ \hline solver=_lbfgs_ & Several \(\Delta\)s & unsmoothed data & 0.984\(\pm\)0.005 & 0.963\(\pm\)0.006 \\ activation=_relu_ & \(N_{tr}\)=6500 (\(\sim\) 80\%) & moving average & 0.984\(\pm\)0.005 & 0.977\(\pm\)0.007 \\ \cline{2-3} learning\_rate=_invscaling_ & \(N_{te}\)=1473 & k=3 & 0.981\(\pm\)0.005 & 0.976\(\pm\)0.007 \\ \cline{2-3} alpha=0.01, In=800 & k=5 & 0.981\(\pm\)0.006 & 0.974\(\pm\)0.010 \\ \cline{2-3} hidden\_layer\_sizes=7\(\times\)150 & Fixed \(\Delta\)=11.9 ps & & \\ max\_iter=5\(\times\)10\({}^{9}\) & \(N_{tr}\)=3000 (\(\sim\)73\%) & k=5 & 0.993\(\pm\)0.002 & 0.989\(\pm\)0.003 \\ \cline{2-3} averaged over 30 trials & \(N_{te}\)=1116 & & \\ \hline \end{tabular} \end{table} Table 4: Comparison of MLPR validation score \(\mathcal{S}\) for different formats of the input data. Comparison of the results for ’raw’ data (log of normalised and adjusted data according to the procedure described in section 3) and data on which the moving average and compressing average (by each 3 and 5 separate spectrum points) are applied. The result for the network fed with the data collected for one chosen \(\Delta\) is added in the last row of the table. presented in [14], the same resolution curve for all spectra is assumed. In our data preparation procedure, the parameters of the resolution curve are interpolated for each case. Based on this, the \(\delta\) parameter is calculated and the value of the shift in time is established for consecutive channels. Although one-gaussian resolution curve was assumed here, it is possible to extend this algorithm for much more complicated cases where the distribution curve consisted in a sum of gaussians, for example. As already mentioned in [14], in that case, a possibility of recognising a distribution function would give compatibility to MELT [23]. Such an extension requires extending the calculations by applying another neural network, working in advance, which returns the parameters of the resolution curve in a given case. This problem has been solved by application of a Hopfield neural network [16]. Taking into account our collection of spectra, it was checked with the use of LT and (occasionally) with MELT that the apparatus resolution curve is one-gaussian for our spectra. Hence, they do not allow testing such an extended model. Furthermore, the MCA module of spectrometers may differ in the time constant per channel \(\Delta\). Thus, spectra used as a training data set may be collected for different channel widths. Taking into account the method presented in [14] for fixed \(\Delta\), the training result is of little use for spectra collected with another \(\Delta\). Oppositely, we have shown the possibility of application of an improved algorithm to data collected for different \(\Delta\)s. The data collected from many spectrometers may contribute to a large training data set, which allows solving the inversion problem for any PALS spectrum and, thus, may be a universal tool that can be used in different laboratories. Although the set of \(\Delta\) used here is small, the accuracy of the results is quite good. To use this tool to determine the real-world spectrum parameters, the training process should be extended by adding the spectra measured for a wider range of \(\Delta\). For greater generalisation, it is possible in principle to attach spectra collected for other compounds to the training data set. For consistency, it suffices for a training database to keep the same number of components (three here) in spectrum decomposition. However, in practice, some incompatibilities of the spectra for different compounds may arise because decomposition into a few exponential processes is probably always a simplification of a real case where some distribution of the size and shape of free volumes should be taken into account as well as other Ps formation details. Although the approach presented here is reduced to the analysis of alkanes solely, the algorithm can be applied in calculation of PALS parameters of other types of samples as well.
2310.04318
Model Order Reduction for the 1D Boltzmann-BGK Equation: Identifying Intrinsic Variables Using Neural Networks
Kinetic equations are crucial for modeling non-equilibrium phenomena, but their computational complexity is a challenge. This paper presents a data-driven approach using reduced order models (ROM) to efficiently model non-equilibrium flows in kinetic equations by comparing two ROM approaches: Proper Orthogonal Decomposition (POD) and autoencoder neural networks (AE). While AE initially demonstrate higher accuracy, POD's precision improves as more modes are considered. Notably, our work recognizes that the classical POD-MOR approach, although capable of accurately representing the non-linear solution manifold of the kinetic equation, may not provide a parsimonious model of the data due to the inherently non-linear nature of the data manifold. We demonstrate how AEs are used in finding the intrinsic dimension of a system and to allow correlating the intrinsic quantities with macroscopic quantities that have a physical interpretation.
Julian Koellermeier, Philipp Krah, Julius Reiss, Zachary Schellin
2023-10-06T15:28:52Z
http://arxiv.org/abs/2310.04318v1
Model Order Reduction for the 1D Boltzmann-BGK Equation: Identifying Intrinsic Variables Using Neural Networks ###### Abstract Kinetic equations are crucial for modeling non-equilibrium phenomena, but their computational complexity is a challenge. This paper presents a data-driven approach using reduced order models (ROM) to efficiently model non-equilibrium flows in kinetic equations by comparing two ROM approaches: Proper Orthogonal Decomposition (POD) and autoencoder neural networks (AE). While AE initially demonstrate higher accuracy, POD's precision improves as more modes are considered. Notably, our work recognizes that the classical POD-MOR approach, although capable of accurately representing the non-linear solution manifold of the kinetic equation, may not provide a parsimonious model of the data due to the inherently non-linear nature of the data manifold. We demonstrate how AEs are used in finding the intrinsic dimension of a system and to allow correlating the intrinsic quantities with macroscopic quantities that have a physical interpretation. **Keywords**: Model order reduction, data-driven methods, kinetic equations, neural autoencoder networks, proper orthogonal decomposition, Sod shock tube, Boltzmann-BGK ## 1 Introduction Kinetic equations are widely used in science and engineering [20, 25, 26, 33]. They allow the modeling of deviations from an equilibrium model which is given by an underlying macroscopic equation like the Euler equations, providing detailed insight into fundamental physical processes [35]. However, kinetic equations are often characterized by a large dimensional phase space, making them computationally expensive to solve and sometimes even unfeasible for realistic applications [35]. Investing in solving kinetic equations is only beneficial if large deviations from equilibrium are present [35]. Striking a balance between a fast but inaccurate equilibrium solver and a slow but accurate non-equilibrium solver remains an open challenge. Our work aims to address this challenge by providing a proof-of-concept for a data-driven solution to efficient modeling of flows in different non-equilibrium regimes. In the field of non-equilibrium gas flows, several standard methods to discretize the high dimensional phase space exist. Particle-based Monte Carlo methods are only tractable in the free flight regime and out of scope in the transition regime of moderate non-equilibrium unless special techniques are used [5]. The straightforward Discrete Velocity Method (DVM) uses a pointwise discretization of the velocity space, potentially leading to a large number of equations [30]. Specially tailored moment models are based on the expansion of the particle distribution function and lead to a set of extended fluid dynamical equations [35]. However, it is by no means clear a-priori how many equations are sufficient and which variables are optimal [19, 34]. To tackle the computational complexity of kinetic equations, recently, reduced order models (ROM) have been introduced, enabling reductions in computational complexity by orders of magnitudes [1, 7, 8, 9]. Two different approaches have been followed in the literature. The classical offline-online decomposition as used by [1] involves a two-stage procedure. In the offline stage, the full order model (FOM) is assessed to create a database, which is then utilized to generate a data-dependent basis through proper orthogonal decomposition (POD). This basis allows an efficient description of the FOM on a low-dimensional linear subspace during the online phase. On the other hand, the online adaptive basis method called dynamic low-rank approximation [13] constructs the low dimensional linear basis during the online phase itself, eliminating the need to evaluate the expensive FOM. It has been successfully applied to kinetic equations in the works by Einkemmer et al. [7, 8, 9]. However, the additional complexity of updating the basis during the evolution makes it less online efficient than the classical offline-online approach shown in [15] for a shallow water moment model. In this work, we adopt the same offline strategies as in [1]. Specifically, we sample data for a classical test case called Sod shock tube using a discrete velocity model as our FOM and compare the compression of the linear reduced subspace created by POD with a non-linear description provided by neural autoencoder networks. Neural networks, based on the universal approximation theorem [29], allow for the approximation of a wide range of function classes and appear promising in identifying the intrinsic dimension of a system. However, the non-linear relation between macroscopic model equations and the discrete velocity model hinders the determination of these dimensions using linear reduction methods like the POD. This paper aims to utilize these data-driven model reduction techniques to reduce the number of describing variables and equations and determine how many and which variables are useful in specific test cases. For the non-vanishing Knudsen number, we expect to need more non-equilibrium variables with corresponding balance laws, while in the limit of vanishing Knudsen number, we expect to recover the Euler equations, given by conservation laws for mass, momentum, and energy. To the knowledge of the authors, this is the first paper aiming to bridge the gap between equilibrium and non-equilibrium flows using neural networks in this way. The long-term objective of this line of work is to enable dynamically adapting the model by varying the number of variables during the online phase, paving the way for more efficient and accurate model adaptive simulations of kinetic equations. The organization of the paper is as follows: In Section 2, we introduce the 1D model problem and the reference data used for model reduction. Section 3 describes the two model reduction techniques used in this study: Proper Orthogonal Decomposition (POD) and Autoencoder Networks. The results are presented in Section 4, and the paper concludes with a summary in Section 5. ## 2 The Boltzmann-BGK Model and Data This paper considers a proof-of-concept of using reduced models for the solution approximation of the 1D Boltzmann-BGK equation [2] for monoatomic, ideal gases \[\partial_{t}f+c\partial_{x}f=\frac{1}{\tau}(f_{M}-f), \tag{1}\] which is a potentially high-dimensional equation for the unknown probability density function \(f(t,x,c)\), where \(t\in\mathbb{R}^{+}\) is the time, \(x\in\mathbb{R}\) is the spatial variable, and \(c\in\mathbb{R}\) the microscopic particle velocity. For simplicity we consider the one-dimensional case in this paper, but the results can be extended to the multi-dimensional case. Computing solutions and generating data of the Boltzmann-BGK model is essential for industrial and scientific applications, but often so computationally prohibitive that a large number of test cases is not feasible. To reduce time and cost during the data generating process, experiments or numerical simulations can be replaced by reduced-order models (ROMs). For standard continuum flows the widely-used Euler equations can be applied, but more rarefied regimes require different extended fluid dynamical models. Rarefaction levels are distinguished with the help of the Knudsen number \(\mathrm{Kn}\) defined by the ratio of the mean free path length of the particles \(\lambda\) over a reference length \(l\) as \[\mathrm{Kn}=\frac{\lambda}{l}. \tag{2}\] The right-hand side of the BGK collision operator (1) models the relaxation with relaxation time \(\tau\in\mathbb{R}^{+}\) towards the equilibrium Maxwellian distribution \(f_{M}(t,x,c)\) given by \[f_{M}(t,x,c)=\frac{\rho(t,x)}{(2\pi RT(t,x))^{\frac{3}{2}}}\exp\left(-\frac{(c -u(t,x))^{2}}{2RT(t,x)}\right), \tag{3}\] where \(\rho(t,x)\), \(v(t,x)\) and \(T(t,x)\) are density, bulk velocity, and temperature of the flow, respectively. \(R\) is the universal gas constant. In this work, we consider the relaxation time \(\tau\) a parameter and set it equal to the Knudsen number, \(\tau=\mathrm{Kn}\), however, the relaxation time can also be changed, e.g., to depend on the gas density and temperature in addition. For practical computations, we consider macroscopic moments of the distribution function, which are given by multiplying the distribution function with the co-called collision invariants \((1,c,\frac{1}{2}c^{2})\) and integrating in velocity space \[\rho(t,x) = \int f(t,x,c)\,\mathrm{d}c, \tag{4}\] \[\rho(t,x)u(t,x) = \int cf(t,x,c)\,\mathrm{d}c,\] (5) \[E(t,x) = \int\frac{1}{2}c^{2}f(t,x,c)\,\mathrm{d}c, \tag{6}\] where \(E\) denotes the total energy. The temperature \(T(t,x)\) and the pressure \(p(t,x)\) can be obtained by \[T(t,x)=\frac{2E(t,x)}{3\rho(t,x)}-\frac{u(t,x)^{2}}{3}\quad\text{and}\quad p(t,x)=\rho(t,x)T(t,x). \tag{7}\] Figure 1 illustrates the relation between the macroscopic moments and the distribution function \(f(t,x,c)\) at a certain position in time and space. The density \(\rho(t,x)\) is the integral of the distribution function, which is centered around the macroscopic velocity \(u(t,x)\), and the mean deviation is related to the temperature \(T(t,x)\). The Boltzmann-BGK equation (1) is in equilibrium when \(f=f_{M}\). Multiplying the equilibrium solution with the collision invariants and integrating in velocity space, one finds the Euler equations of classical gas dynamics \[\partial_{t}\rho+\partial_{x}(\rho u)=0, \tag{8}\] \[\partial_{t}(\rho u)+\partial_{x}(\rho u^{2}+p)=0,\] (9) \[\partial_{t}E+\partial_{x}(u(E+p))=0, \tag{10}\] Figure 1: Illustration of the macroscopic moments corresponding to an example distribution function. which are conservation laws for mass, momentum, and energy, respectively. For distribution functions further away from equilibrium, for example due to a larger relaxation time \(\tau\) and a significantly large Knudsen number Kn, the Euler equations do not give accurate results. In this case, additional equations can be used, which are derived by the so-called method of moments [14, 35]. This effectively leads to an extended set of equations, called moment model. It is possible to preserve important properties like hyperbolicity with moment models [11, 17]. The additional equations (for example for the heat flux and higher-order moments) add complexity, but allow for more accurate solutions [18, 34]. However, it is often unclear a-priori, how many equations are needed for an efficiently accurate and computationally feasible solution. In this work, we aim to give a proof-of-concept for a data-based identification of the necessary number of variables, called the intrinsic physical dimension. ### Sod shock tube test case and reference data Sod's shock tube is a well-established test case in the field of rarefied gases [19]. It uses discontinuous initial conditions based on equilibrium values \[\begin{cases}(\rho_{L},u_{L},p_{L})=(1,0,1)&\text{if }x<0.5,\\ (\rho_{R},u_{R},p_{R})=(0.125,0,0.1)&\text{if }x>0.5,\end{cases} \tag{11}\] corresponding to a jump in density and pressure at \(x=0.5\) due to a diaphragm at that position, which is removed at time \(t=0\). The problem setup at \(t=0\) is shown in fig. 2, which is split into two regions left and right of the diaphragm. For the generation of reference data we employ a discrete velocity method (DVM) [27], which uses a pointwise microscopic velocity space discretization \[\partial_{t}f_{k}(t,x)=-(c_{k})\partial_{x}f_{k}(t,x)+\frac{1}{\tau}\left(M_{ fk}(t,x)-f_{k}(t,x)\right), \tag{12}\] where a uniform grid in velocity space is considered with \(c_{k}=k\Delta c\) to discretize the distribution function \(f_{k}(t,x)=f(t,x,c_{k})\), for some \(k\in\mathbb{Z}\). After a subsequent discretization in space, the DVM eq. (12) leads to a coupled ODE system in time than can be solved with standard methods. For the numerical reference data, we use \(N_{x}=200\) spatial points \(x_{k}\in[0,1]\), \(N_{c}=40\) discrete velocities \(c_{j}\in[-10,10]\) and \(N_{t}=25\) time steps \(t^{n}\in[0,0.12]\) summarized in table 1. It is possible to choose another range for the discrete velocity points, but in typical applications the range of the bulk velocity is not known, such that one has to include a safety margin. We therefore chose the domain \([-10,10]\). The goal of the model order reduction is now to reduce the complexity of the computation using lower dimensional models. For that matter, it is not relevant what the actual error of the numerical reference data is or if is fully converged. It is fair to say that a full reference solution might easily take into account more spatial points, time steps, and discrete velocities, which makes it even more necessary to reduce the complexity. Figure 2: Problem setup for the 1D Sod shock tube. A diaphragm at the center is initially separating the domain in two regions, where initial conditions for density \(\rho\), macroscopic velocity \(u\), and pressure \(p\) are indicated. For the model order reduction later, we consider two different Knudsen numbers for Sod's shock-tube test case: \(\mathrm{Kn}=0.00001\) for a small Knudsen number in the hydrodynamic regime and \(\mathrm{Kn}=0.01\) for a relatively large Knudsen number in the rarefied regime. To understand the behavior of the reference solutions for non-vanishing Knudsen numbers, we first describe the solution for vanishing Knudsen number in equilibrium, i.e., \(\mathrm{Kn}=0\), which can be obtained using the method of characteristics and the Rankine Hugoniot jump conditions connecting the states before and after the shocks [24]. Starting from the initial condition in fig. 3a, the solution evolves for \(t>0\) and five regions are formed that are depicted in fig. 3b [32]. A rarefaction wave is moving to the left between \(x_{1}\) and \(x_{2}\). The contact discontinuity is located at \(x_{3}\), where the macroscopic velocity \(u\) and the pressure \(p\) are continuous in contrast to the density \(\rho\) and the energy \(E\). \(x_{4}\) is the position of the shock wave. In non-equilibrium, i.e., for solutions evolving with Knudsen numbers \(\mathrm{Kn}>0\), the solution does not have discontinuities due to the finite relaxation time \(\tau\). Figure 3c shows the reference solutions \(f(t,x,c)\) at \(t_{0}=0\), \(t_{1}=0.06\) and \(t_{3}=0.12\) for the two levels of rarefaction considered in this paper: \(\mathrm{Kn}=0.00001\) and \(\mathrm{Kn}=0.01\). Increasing the Knudsen number leads to a smoother transition from region 1 to region 5 with a less pronounced shock front. ## 3 Methods In this section we present two common methods used for reducing the dimensionality of high dimensional data: (1) the proper orthogonal decomposition (POD) and (2) neural autoencoder networks (AE). The methods will be used to parameterise the high dimensional data stemming from the DVM simulation, using a linear mapping in case of the POD and a non-linear mapping in case of AE. Although the classical POD-MOR approach shows that linear mappings are sufficient to describe the non-linear solution manifold of the BGK equation to a good accuracy [1], it is in general not sufficient to determine a parsimonious model of the full model data, since the data manifold can be non-linear. Here, neural autoencoder networks can be used as they are capable to find the intrinsic dimension of a system. ### Proper orthogonal decomposition The _proper orthogonal decomposition_[31] (POD) approximates the data with help of dyadic pairs: \[f(x,t,c_{i})\approx\sum_{k=1}^{r}\hat{f}_{k}(x,t)\psi_{k}(c_{i})\qquad\text{ for }r\ll N_{c}\,. \tag{13}\] The pairs \(\{(\hat{f}_{k}(x,t),\psi_{k}(c_{i}))\}_{k=1,\ldots,r}\) are the structures in the data that contain the most energy and they are chosen to minimize the gap between the data and the reconstruction eq. (13). In the following, \(\psi_{k}(c_{i})\) are termed POD-modes and \(\hat{f}_{k}(x,t)\) the corresponding reduced variables. For notation, we define \(f^{(i)}(x,t)=f(x,t,c_{i})\) and the vectors \(f(x,t)=(f^{(1)}(x,t),\ldots,f^{(N_{c})}(x,t))\) and \(\psi_{k}=(\psi_{k}(c_{1}),\ldots,\psi_{k}(c_{N_{c}}))\). The proper orthogonal decomposition computes the solution of the minimization problem: \[\min_{\psi_{k}}\|f(x,t)-\sum_{k=1}^{r}\langle f(x,t),\psi_{k}\rangle\psi_{k}\| _{2}^{2}\quad\text{such that}\quad\langle\psi_{k},\psi_{l}\rangle=\delta_{kl}. \tag{14}\] \begin{table} \begin{tabular}{c c c c} \hline Variable & Number of nodes \(i\) & Domain extension & Step size (uniform) \\ \hline \(x\) & 200 & [0, 1] & 0.005 \\ \(c\) & 40 & [-10,10] & \(\approx\) 0.51282051 \\ \(t\) & 25 & [0,0.12] & 0.005 \\ \hline \end{tabular} \end{table} Table 1: Problem setup for the Boltzmann-BGK model in Sod’s shock tube. Figure 3: Sod shock tube and reference data. Initial conditions (a); equilibrium solution (b); Reference solutions in rarefied and hydrodynamic regime (c); Macroscopic quantities at \(t=0.12s\) (d). Technically one can solve this optimization problem using a singular value decomposition (SVD) of the so-called snapshot matrix [22]: \[\mathbf{F}=\begin{bmatrix}f^{(1)}(x_{1},t_{1})&\cdots&f^{(N_{c})}(x_{1},t_{1})\\ \vdots&\ddots&\vdots\\ f^{(1)}(x_{N_{a}},t_{1})&\cdots&f^{(N_{c})}(x_{N_{x}},t_{1})\\ f^{(1)}(x_{1},t_{2})&\cdots&f^{(N_{c})}(x_{1},t_{2})\\ \vdots&\ddots&\vdots\\ f^{(1)}(x_{N_{x}},t_{N_{t}})&\cdots&f^{(N_{c})}(x_{m},t_{N_{t}})\end{bmatrix} \in\mathbb{R}^{(N_{x}N_{t})\times N_{c}}\,. \tag{15}\] The snapshot matrix collects the time and space discrete distribution function in its columns. Each column holds the time-spatial values for a different discrete velocity. Performing an SVD factorizes \(\mathbf{F}\) as \[\mathbf{F}=\mathbf{\Phi}\mathbf{\Sigma}\mathbf{\Psi}^{\mathbf{T}}, \tag{16}\] with diagonal matrix \(\mathbf{\Sigma}=\text{diag}(\sigma_{1},\ldots,\sigma_{m})\), \(m=\text{min}(N_{x}N_{t},N_{c})\), containing the singular values \(\sigma_{1}\geq\sigma_{2}\geq\cdots\geq\sigma_{m}\geq 0\) and \(\mathbf{\Phi}\in\mathbb{R}^{N_{x}N_{t}\times m},\mathbf{\Psi}\in\mathbb{R}^{N _{c}\times m}\) are orthogonal matrices containing the left and right singular vectors, respectively. The first \(r\) columns of the truncated \(\mathbf{\Psi}_{r}=[\psi_{1},\ldots,\psi_{r}]\in\mathbb{R}^{N_{c}\times r}\) contain the POD modes in eq. (13). Together with \(\mathbf{\Sigma}_{r}=\text{diag}(\sigma_{1},\ldots,\sigma_{r})\) and the \(r\) leading left singular vectors \(\mathbf{\Phi}_{r}\in\mathbb{R}^{(N_{x}N_{t})\times r}\) they yield the rank \(r\)-term approximation \(\mathbf{F}_{r}\) of the snapshot matrix given by \[\mathbf{F}_{r}:=\mathbf{\Phi}_{r}\mathbf{\Sigma}_{r}\mathbf{\Psi}_{r}^{T}. \tag{17}\] According to the Eckart-Young-Mirsky theorem [6, 28]\(\mathbf{F}_{r}\) is the best rank \(r\) approximation and the resulting error in the Frobenius norm is rigorously computed from the trailing singular values \[\|\mathbf{F}-\mathbf{F}_{r}\|_{\mathrm{F}}^{2}=\sum_{k=r+1}^{m}\sigma_{k}^{2}. \tag{18}\] A common choice for \(r\) is to truncate after a certain energy percentage is reached in the reduced system compared to the full system: \[E_{\text{cum}}=\frac{\|\mathbf{F}_{r}\|_{\mathrm{F}}}{\|\mathbf{F}\|_{ \mathrm{F}}}=\frac{\sum_{k=1}^{r}\sigma_{k}^{2}}{\sum_{k=1}^{m}\sigma_{k}^{2}}. \tag{19}\] In this paper, POD is used to compare with the autoencoder from the next section. ### Autoencoders Neural networks, particularly autoencoder networks, have become widely used tools for dimension reduction [36]. A comprehensive introduction to autoencoder networks can be found in [12]. Here we only summarize briefly the common idea of autoencoder networks and give the specific details of our implementation. An autoencoder aims to reproduce the input data while compressing it through an information bottleneck. It consists of two main components: * The encoder, denoted as \(g_{\text{enc}}\), maps the input data \(f\) to points \(\hat{f}\) in a lower-dimensional latent space: \(g_{\text{enc}}\colon\mathbb{R}^{M}\to\mathbb{R}^{r},f\mapsto\hat{f}=g_{\text{ enc}}(f)\), \(r\ll M\). * The decoder, denoted as \(g_{\text{dec}}\), reconstructs the input space from the latent representation: \(g_{\text{dec}}\colon\mathbb{R}^{r}\to\mathbb{R}^{M},\hat{f}\mapsto g_{\text{ dec}}(\hat{f})=\tilde{f}\), \(r\ll M\). Note that the dimension of the latent space is denoted by \(r\), to match the rank of the POD approximation. The autoencoder is defined as the composition of both parts: \(\tilde{f}=g_{\text{dec}}\left(g_{\text{enc}}\left(f\right)\right)\). For our purpose, we identify the discrete velocity space as the input dimension \(M=N_{c}\). Thus, the autoencoder maps each time-spatial value of the distribution function \(f(x,t)\in\mathbb{R}^{N_{c}}\) onto a smaller latent space \(\hat{f}(x,t)\in\mathbb{R}^{r}\), which parameterizes the necessary physical information of the system. The goal of the optimization procedure is to determine \(g_{\text{dec}}\) and \(g_{\text{enc}}\) such that the reconstruction error over a set of training/testing data contained in \(\mathbf{F}\) is minimized. The reconstruction error is defined as: \[\mathcal{L}=\frac{1}{N_{c}}\|f(x,t)-g_{\text{dec}}\circ g_{\text{enc}}\circ f(x,t)\|_{2}^{2}\,. \tag{20}\] The reconstruction error is the sum of the two-norm of the discrete velocities vector of the difference between the input data \(f\) and the reconstructed data \(\tilde{f}\) that has been squeezed through the informational bottleneck. The assumption is, that if the original data can be represented well while the information went through a smaller latent space, there exists a physical law in the latent space that describes the system sufficiently. The intrinsic latent dimension \(r=p^{*}\) which is sufficient to describe the data is then called the _intrinsic physical dimension_ similar to the intrinsic dimension defined in [23]. Such a reduced model is then termed parsimonious because it explains the data with a minimum number of variables. In the training procedure, the functions \(g_{\text{enc}}\) and \(g_{\text{dec}}\) are determined by trainable parameters of the network, referred to as weights and biases. The networks are constructed using a composition of layers \(g_{\text{enc}}=L_{1}\circ L_{2}\circ\cdots\circ L_{N}\). Typically, each layer \(L_{n}\colon\mathbb{R}^{i}\to\mathbb{R}^{o}\) in the network consists of an affine linear mapping \(\mathbf{x}\mapsto h_{n}(\mathbf{W}_{n}x+b_{n})\), where \(\mathbf{W}_{n}\in\mathbb{R}^{o,i}\) represent the weights, \(\mathbf{b}_{n}\in\mathbb{R}^{o}\) denote the biases, and \(h_{n}\) are predefined non-linear functions. The configuration of the input and output dimensions \(i\) and \(o\) for each layer, the choice of activation function, and the number of layers collectively determine the architecture of the network. The choice of these so-called hyper-parameters is often difficult and a matter of trial and error. ArchitectureIn our studies we have exploited _fully connected neural autoencoder networks_ (FCNN) and convolutional autoencoder networks (CNN). However, in this manuscript we restrict ourselves to the results of the fully connected network, since it gave structurally the best results. We have studied a variety of different activation functions, hidden layers, batch sizes and depths of the network. The best results concerning the validation error and acceptable training time where obtained by the network defined in table 2. A comprehensive study of the parameter optimization is attached to the manuscript in section 5. TrainingBefore the training we initialize the weights of the network using the standard initialization implemented in pytorch. Thus the weights are randomly uniform distributed between \(m^{-1/2}\) and \(m^{1/2}\) with \(m\) being the number of input nodes in the layer. Our network is trained by splitting the data consisting of \(N_{x}\times N_{t}\) samples in a testing and training set with a 80/20 split over 3000 epochs using a batch size of 4. In each epoch the network is updated using the Adam optimizer with a learning rate of \(10^{-5}\). More information about hyperparameters and training of the network can be found in the appendix section 5. \begin{table} \begin{tabular}{l c c} \hline \hline **Parameter** & hydrodynamic & rarefied \\ \hline Layer Sizes & [\(N_{c}\), 30, \(r\), 30, \(N_{c}\)] & [\(N_{c}\), 40, \(r\), 40, \(N_{c}\)] \\ Activation function & ELU & ReLU \\ Loss function & MSE eq. (20) & MSE eq. (20) \\ Optimizer & Adam & Adam \\ Learning rate & \(10^{-5}\) & \(10^{-5}\) \\ Epochs & 3000 & 3000 \\ Batch size & 4 & 4 \\ \hline \hline \end{tabular} \end{table} Table 2: Hyper-parameters of Fully Connected Autoencoder Network (FCNN) for the hydrodynamic and rarefied regime. Results We reconstruct the full order model (FOM) solution with the help of POD and an autoencoder, the FCNN, for which the selection of hyperparameters and the training are described in the previous section. Note that we apply both model reduction techniques to reconstruct both the rarefied reference data and the hydrodynamic reference data. The goal is to later determine the intrinsic dimension of the data for both cases. We therefore compare the two dimension reduction techniques by means of different measures. The intrinsic variables obtained from POD and the FCNN will be referred to as \(\mathbf{h}\) and \(\mathbf{r}\), where the former describes the intrinsic variables when reducing the hydrodynamic data and the latter when reducing the rarefied data. For the purpose of comparing the results we define the \(L_{2}\)-error \[\mathcal{E}_{\text{rel}}=\frac{\|\mathbf{F}-\tilde{\mathbf{F}}\|_{2}}{\| \mathbf{F}\|_{2}}\,, \tag{21}\] where \(\mathbf{F}\) the reference data is given in eq. (15) and the reconstructed data \(\tilde{\mathbf{F}}\) is either \(\mathbf{F}_{r}\) in case of the POD or the FCNN predictions with \(r\) latent variables for every \((x,t,c)\) in the data set. ### Singular value decay of reference data As a first step, we perform a POD with the hydrodynamic data and with the rarefied data. The obtained singular values \(\sigma\), as well as the cumulative energy (cusum-e) defined in eq. (19), are shown in fig. 4. As expected, more modes are necessary in the rarefied regime compared to the hydrodynamic regime. With a total of \(p^{\text{POD}}=4\) intrinsic variables, a cumulative energy of over 99% can be achieved for the hydrodynamic regime. The cumulative energy of the singular values of the rarefied regime only reaches above 99% with \(p^{\text{POD}}=6\) singular values. For the POD we define the _intrinsic dimension_\(p^{\text{POD}}\) as the smallest truncation rank \(r\) of the reduced system, at which the cumulative energy \(E_{\text{cum}}\) defined in eq. (19) reaches 99%. Although this choice is arbitrary it is a common practice in classical MOR to truncate eq. (13), whenever 99% of the cumulative energy is reached. In fig. 4, we further see that the rate at which the singular values drop is approximately exponential in both regimes, which has been also observed by [1]. Consequently, a rapid decay of the Kolmogorov N-width is indicated. Note that the singular value decay is similar for both domains but not exactly the same, thus leading to an expected increase in the number of intrinsic variables in the rarefied regime necessary to achieve similar \(L_{2}\)-errors. It is important to note that the parameter \(p^{\text{POD}}\) is not expected to precisely match the actual intrinsic dimension \(p^{*}\) of the solution manifold. The intrinsic dimension represents Figure 4: Singular value decay \(\sigma\) and cumulative energy increase for the number of singular variables \(k\) in the hydrodynamic regime (a) and in the rarefied regime (b). A black cross marker corresponds to over 99% cumulative energy. the minimum number of variables required to accurately describe the system's exact solution manifold. This discrepancy arises because the solution manifold is fundamentally nonlinear, making it challenging to adequately capture with a parsimonious linear approximation. For the FCNN, the intrinsic dimension is defined as the smallest number of intrinsic variables that minimizes the error. In well-trained models, the FCNN's intrinsic dimension should ideally align with \(p^{*}\). From a fluid mechanics perspective, the hydrodynamic regime theoretically requires only \(p^{*}=3\) intrinsic variables. This is because near-equilibrium flows in this regime can be effectively characterized by three macroscopic quantities: density \(\rho\), macroscopic velocity \(u\), and total energy \(E\), as outlined in eq. (8)-eq. (10), see also [1, 19]. Conversely, the rarefied regime demands a larger intrinsic dimension, denoted as \(p^{*}\). This is due to the need for more than only the equilibrium Maxwellian distribution function to describe the microscopic velocities adequately. Therefore, we initially set \(p^{*}=3\) intrinsic variables (\(\mathbf{h}\)) for the FCNN in the hydrodynamic case and choose \(p^{*}=5\) intrinsic variables (\(\mathbf{r}\)) for the rarefied regime. This choice aligns with extended fluid dynamic models as described in [19, 35]. We note that each FCNN with different latent space dimension \(r\) needs to be trained separately. This is different from the POD, where the decomposition is only performed once. Thereafter the approximation quality is given by the truncation rank \(r\). ### Variation of the number of intrinsic variables The variation of the number of intrinsic variables \(r\) in fig. 5 sheds light on the performance of the autoencoder with different bottleneck layer sizes. In the case of the POD \(r\) is the truncation rank of the decomposition eq. (13) and the latent space dimension in case of the FCNN. To this end, \(r\) is varied for both the POD and the FCNN over \(r\in\{1,2,3,4,8,16,32\}\) for the hydrodynamic case and over \(r\in\{1,2,4,5,8,16,32\}\) for the rarefied case. We note that the loss of information when applying POD goes exponentially to zero with increasing \(r\), which is not surprising when consulting the _Eckard-Young Theorem_[6]. Note that the FCNN is retrained for each different \(r\). By changing \(r\), i.e. widening the bottleneck layer, a gain or loss of capacity occurs that can be connected to stability during training. Both for the hydrodynamic and the rarefied regime, POD initially yields a larger error than the FCNN for small number of intrinsic variables \(r\). Not surprisingly, the POD accuracy increases with the number of singular values taken into account until the error reaches machine precision. The FCNN error decreases as well and then reaches a plateau, with a Figure 5: The \(L_{2}\)-Error over the variation of the latent space dimension/truncation rank \(r\) using FCNN/POD for the hydrodynamic regime (left) and the rarefied regime (right). typical remaining error due to the network architecture and training. For the previously identified values \(p^{*}=3\) in the hydrodynamic case and \(p^{*}=5\) in the rarefied case, the FCNN results in a more accurate approximation than the POD. We note that when testing the FCNN against POD and fixing \(r\) the FCNN is limited by the estimation error of the training and performs under its abilities. However, POD uses five to six times more parameters than the FCNN while the deterministic character enables POD to achieve any possible accuracy, which was not observed with the neural network. In the following, we consider the intrinsic variables with constant values \(p^{*}=3\) in the hydrodynamic case and \(p^{*}=5\) in the rarefied case. This leads to the number of trainable parameters of the POD and the FCNN shown in table 3. We can see that the FCNN achieves a relatively small error with a small number of parameters in comparison with the POD for this choice of the number of intrinsic variables. Next, a qualitative analysis with the actual reconstructions is presented. From computations of the \(L_{2}\)-error over time \(t\), which are not shown due to conciseness, it became clear that the time step that contributes most to the error is the last time step in case of POD, while the FCNN distributes the error more evenly over all time steps. ### Reconstruction quality The reconstructed solutions compared to the full order model (FOM) at the final time step \(t=0.12s\) are given in fig. 6. Because of the small overall errors indicated in table 3 both the POD and the FCNN reproduce the FOM solution without any visible differences at first sight. \begin{table} \begin{tabular}{c c c c c c} \hline \hline Algorithm & \multicolumn{2}{c}{Parameters \(\theta\)} & \multicolumn{2}{c}{Int. variables \(p\)} & \multicolumn{2}{c}{\(L_{2}\)-error} \\ & **H** & **R** & **H** & **R** & **H** & **R** \\ \hline POD & 15129 & 25225 & 3 & 5 & 0.0205 & 0.0087 \\ FCNN & 2683 & 3725 & 3 & 5 & 0.0008 & 0.0009 \\ \hline \hline \end{tabular} \end{table} Table 3: Amount of parameters used to reconstruct \(f\), the number of intrinsic variables \(p\) and the corresponding \(L_{2}\)-Error for POD and FCNN, both for hydrodynamic (**H**) and rarefied (**R**) regimes. Figure 6: Comparison of the FOM solutions \(f\) (left column) with reconstructions \(\hat{f}\) obtained from POD (middle column) and FCNN (right column) at end time \(t=0.12s\) for \(x\in[0.375,0.75]\) in the hydrodynamic regime (top row) and in the rarefied regime (bottom row). As shown in fig. 7, the more subtle information loss from the model reduction can unfold in actual differences in the macroscopic quantities \(\rho\), \(\rho u\) and \(E\). Overall, fig. 7 shows that the errors are larger for the hydrodynamic regime (top row), most notably for the momentum and energy of the POD model close to the contact discontinuity. However, the position of the shock is well approximated. In contrast, the FCNN model yields a very good agreement in the hydrodynamic case. For the rarefied regime, both models approximate the FOM solution very well. The lack of sharp shock structures in the full model and the increased intrinsic dimension \(p^{*}=5\) combined seem to notably influence the accuracy. ### Conservation properties The physical consistency of the reduced \(\tilde{f}\), in terms of conservation of mass, momentum, and energy, is a critical criterion for its validity. Hence, conservation properties are analyzed in the following. We note that conservation of mass, momentum, and energy is not directly built-in by means of a specifically tailored loss function. Even though we can expect to recover some conservation properties as they are implicitly built into the numerical reference data. The investigation of different loss functions to improve upon this is left for future work. We investigate the conservation properties by means of the derivative of the cell-averaged conserved quantities mass, momentum, and total energy, defined exemplary as \[\frac{\mathrm{d}}{\mathrm{d}t}\int\rho(x,t)\,\mathrm{d}x\Delta t=\overline{ \rho}, \tag{22}\] for the mass. Note that a derivative \(\overline{\rho}=0\) denotes conservation of mass, for example. We expect the conservation of mass and total energy, while the momentum increases with a constant rate, due to the boundary conditions of the test case, featuring a larger pressure on the left-hand side of the domain. Figure 8 shows the evolution of the derivatives of mass, momentum, and total energy as a function of time for the hydrodynamic regime (top row) and the rarefied regime (bottom Figure 7: Comparison of FOM macroscopic quantities \(\rho\), \(\rho u\) and \(E\) with POD and the FCNN for the hydrodynamic regime (top row) and the rarefied regime (bottom row) at time \(t=0.12s\). row). Indeed, fig. 8 indicates that conservation of mass and energy are achieved with reasonable accuracy for the FCNN, while the error is larger for the POD reconstruction for both regimes. Also the increase in momentum of the full order model (FOM) is accurately described by the FCNN with a larger error for the POD method for both regimes. Overall, the errors are slightly smaller for the rarefied case compared to the hydrodynamic case, which might be due to the higher capacity of the neural network and more modes for the POD using five intrinsic variables in the rarefied regime. ### Physical interpretability An important question in the context of model reduction with neural networks is the interpretability of the results, because of the usual black-box nature of neural networks [10]. Especially when benchmarking neural networks for model order reduction with POD, evaluating the interpretability of the intrinsic variables is important, since POD by construction achieves a so-called physically interpretable decomposition of the input data [3] as outlined previously. Following the assumption that the hydrodynamic case can be fully described in terms of three macroscopic quantities and that the rarefied case is reasonably describable in a similar way with an extended set of five variables, we test the intrinsic variables \(\mathbf{h}\) and \(\mathbf{r}\) for similarities and investigate if they match any macroscopic quantity. Two related macroscopic quantities, namely the temperature \(T\) and macroscopic velocity \(u\), are added to the three macroscopic variables \(\rho\), \(\rho u\), and \(E\). In fig. 9 and fig. 12, these are plotted first over the whole domain of \(x\) and \(t\) and for the end time \(t=0.12s\) for both regimes. Similarly, we plot both the FCNN's and the POD's first 3 intrinsic variables \(\mathbf{h}\) of the hydrodynamic Figure 8: Comparison of the conservative properties of reconstructions obtained from POD and the FCNNs with the conservative properties of the FOM solution using the mass, momentum, and energy derivative. A value of 0 indicates conservation. FCNN approximately conserves mass and energy, while the momentum increases with the correct rate of the test case. case and 5 intrinsic variables \(\mathsf{r}\) of the rarefied test case \[\mathsf{h} =[h_{0}(x,t),h_{1}(x,t),h_{2}(x,t)],\] \[\mathsf{r} =[r_{0}(x,t),r_{1}(x,t),r_{2}(x,t),r_{3}(x,t),r_{4}(x,t)],\] depicted in fig. 10 and fig. 13 respectively. Strikingly, most intrinsic variables of the FCNN in fig. 10 and fig. 13 and the POD in fig. 11 and fig. 14 appear to be a combination of the five intrinsic variables shown in fig. 9 and fig. 12, respectively. In particular consider FCNN in the hydrodynamic case by comparing fig. 9 and fig. 10. The rarefaction wave, shock wave, and contact discontinuity, which can be identified in \(h_{0}\) reflect a combination of those found in the density \(\rho\) and the total energy \(E\). Furthermore, \(h_{1}\) seems to model the negative momentum \(\rho u\), with different boundary values. The temperature \(T\) appears linked to \(h_{2}\), where the same fluctuation appears. Similar results hold true for the POD variables in fig. 11, where especially the first two Figure 11: First three intrinsic variables \(h_{0}(x,t)\), \(h_{1}(x,t)\) and \(h_{2}(x,t)\) of hydrodynamic case obtained by the POD. Top row depicts the whole \((x,t)\) domain, bottom row is for \(t=0.12\). Figure 10: Intrinsic variables \(h_{0}(x,t)\), \(h_{1}(x,t)\) and \(h_{2}(x,t)\) of hydrodynamic case obtained by the FCNN. Top row depicts the whole \((x,t)\) domain, bottom row is for \(t=0.12\). Figure 9: Macroscopic quantities of the hydrodynamic case obtained by the FOM. Density \(\rho\), momentum \(\rho u\), total energy \(E\), temperature \(T\), and velocity \(u\) over time \(t\) and space \(x\) in the top row and at \(t=0.12\) in the bottom row. Figure 14: First five intrinsic variables \(r_{0}(x,t)\), \(r_{1}(x,t)\), \(r_{2}(x,t)\), \(r_{3}(x,t)\) and \(r_{4}(x,t)\) of rarefied case obtained by the POD. Top row depicts the whole \((x,t)\) domain, bottom row is for \(t=0.12\). Figure 12: Macroscopic quantities of the rarefied case obtained by the FOM. Density \(\rho\), momentum \(\rho u\), total energy \(E\), temperature \(T\), and velocity \(u\) over time \(t\) and space \(x\) in the top row and at \(t=0.12\) in bottom row. Figure 13: Intrinsic variables \(r_{0}(x,t)\), \(r_{1}(x,t)\), \(r_{2}(x,t)\), \(r_{3}(x,t)\) and \(r_{4}(x,t)\) of rarefied case obtained by the FCNN. Top row depicts the whole \((x,t)\) domain, bottom row is for \(t=0.12\). variables closely resemble the density \(\rho\) and the momentum \(\rho u\). Interestingly, this does not relate to very good conservation properties of the POD in comparison with FCNN as shown in the previous section and fig. 8. Considering the FCNN in the rarefied case, we compare fig. 12 and fig. 13. Here \(r_{3}\) clearly reflects the shape of the density \(\rho\). Moreover, the peak of the velocity \(u\) can be observed in \(r_{0}\). For the other intrinsic variables of \(r_{1}\), \(r_{2}\) and \(r_{4}\) a clear discernability of macroscopic quantities is difficult to observe and might require linear or nonlinear combinations. Additionally, it is possible that those intrinsic variables resemble non-equilibrium variables not present among the macroscopic variables. Considering the POD results in fig. 14, we again see a very good agreement of the first intrinsic variables with density and momentum. For more physical insight into the relation between macroscopic variables and intrinsic variables, the Pearson correlation between all variable combinations is computed in [12] for the FCNN. Note that we expect similar results for the POD based on the previous results, but do not present them here for conciseness. The Pearson correlation coefficient \(r_{X,Y}=r_{Y,X}\) is a measure of linear correlation between two sets of data, here represented by a macroscopic variable \(X\in\{\rho,\rho u,E,T,u\}\) and an intrinsic variable \(Y\in\{r_{0},r_{1},r_{2},\}\) for the hydrodynamic case and \(Y\in\{r_{0},r_{1},r_{2},r_{3},r_{4}\}\) for the rarefied case. It is commonly defined as \[r_{X,Y}=\frac{\sum\left(x_{i}-\bar{x}\right)\left(y_{i}-\bar{y}\right)}{\sum \sqrt{(x_{i}-\bar{x})}\sqrt{\sum\left(y_{i}-\bar{y}\right)}}. \tag{23}\] Note that \(r_{X,Y}\in[-1,1]\), with \(r_{X,Y}=0\) meaning that there is no correlation between both data sets, \(r_{X,Y}=1\) indicating a perfect correlation, and \(r_{X,Y}=-1\) indicating a perfect anti-correlation. The Pearson correlation coefficients for the hydrodynamic test case are presented in fig. 15. As predicted by the previous analysis, there appears to be an almost perfect correlation of the first intrinsic variable \(r_{0}\) with the density \(\rho\). This means that the FCNN succeeds at identifying the density \(\rho\) precisely as an internal variable. Note that \(r_{0}\) also correlates almost perfectly with the energy \(E\), as the energy depends linearly on \(\rho\). Additionally, there is a relatively strong linear correlation between \(r_{2}\) and both the momentum \(\rho u\) as well as the temperature \(T\). The intrinsic variable \(r_{2}\) on the other hand seems to be correlated with all variables. The Pearson correlation coefficients for the rarefied test case are presented in fig. 16. In agreement with the previous results, there is no clear correlation of most of the intrinsic variables. An exception is \(r_{0}\), which is anti-correlated with \(u\) and \(r_{3}\), which correlates almost perfectly with the energy \(E\). Note that only linear correlations are tested here. For further analysis on the disentanglement of the intrinsic variables, it might be more suitable to consider nonlinear correlations beyond the Pearson correlation coefficients. One option that could be explored in future work would be to train the functional relation between the intrinsic variables and macroscopic variables, for example by means of symbolic regression [4]. ## 5 Conclusion This paper marks the first comparison of velocity space model reduction techniques for rarefied flows using proper orthogonal decomposition (POD) and a fully connected neural network (FCNN). As physically expected, the rarefied regime needs more modes than the hydrodynamic regime. Choosing three and five intrinsic variables for the hydrodynamic and rarefied case, respectively, leads to less than one percent error. The FCNN is initially more accurate but has a remaining error even for larger number of intrinsic variables, while POD achieves subsequently higher accuracy with increasing the number of parameters. The resulting errors of the macroscopic variables are small, especially in the smoother rarefied case. Even though not strictly enforced, the FCNN approximately exhibits the correct conservation of mass, momentum, and energy, while POD has a slightly larger error. Figure 16: Pearson correlation between macroscopic quantities and intrinsic variables for the rarefied case. Figure 15: Pearson correlation between macroscopic quantities and intrinsic variables for the hydrodynamic case. The correlation of intrinsic variables and macroscopic variables is investigated by means of the evolution of the reconstructed values and the pairwise correlation for the FCNN. The density is directly included in the latent space while the relation with other macroscopic variables seems to be more complex. In addition to optimizing the neural network's performance, our research endeavors to enhance its predictive capabilities by incorporating fundamental physical properties such as conservation and interpretability. This objective includes the exploration of different loss functions and the regularization techniques. Furthermore, future work can utilize the model reduction approach in real-world scenarios, including simulations and parameter predictions. Lastly, the presented concepts could be applied in related fields, such as shallow flows [16] or fusion plasmas [21]. ## Author Contribution Statement (CRediT) All authors contributed to this publication. The authors contributions differ in the following points: **Julian Koellermeier:**: initial idea, methodology, setup of test cases, reference data, writing **Philipp Krah:**: initial idea, methodology, implementation, visualization, writing **Julius Reiss:**: initial idea, supervision **Zachary Schellin:**: implementation, training, visualization ## Conflict of Interest The authors declare that they have no conflict of interest. ## Code and Data Availability All data and scripts to reproduce the results can be obtained from the authors on reasonable request. ## Acknowledgement The authors would like to acknowledge the financial support of the CogniGron research center and the Ubbo Emmius Funds (University of Groningen). Centre de Calcul Intensif d'Aix-Marseille is acknowledged for granting access to its high performance computing resources. P. Krah acknowledges partial funding from the Agence Nationale de la Recherche (ANR), project CM2E, grant ANR-20-CE46-0010-01.
2306.04171
Nuclear mass predictions based on deep neural network and finite-range droplet model (2012)
A neural network with two hidden layers is developed for nuclear mass prediction, based on the finite-range droplet model (FRDM12). Different hyperparameters, including the number of hidden units, the choice of activation functions, the initializers, and the learning rates, are adjusted explicitly and systematically. The resulting mass predictions are achieved by averaging the predictions given by several different sets of hyperparameters with different regularizers and seed numbers. It can provide us not only the average values of mass predictions but also reliable estimations in the mass prediction uncertainties. The overall root-mean-square deviations of nuclear mass have been reduced from $0.603$ MeV for the FRDM12 model to $0.200$ MeV and $0.232$ MeV for the training set and validation set, respectively.
To Chung Yiu, Haozhao Liang, Jenny Lee
2023-06-07T05:48:39Z
http://arxiv.org/abs/2306.04171v1
# Nuclear mass predictions based on deep neural network and finite-range droplet model (2012) ###### Abstract A neural network with two hidden layers is developed for nuclear mass prediction, based on the finite-range droplet model (FRDM12). Different hyperparameters, including the number of hidden units, the choice of activation functions, the initializers, and the learning rates, are adjusted explicitly and systematically. The resulting mass predictions are achieved by averaging the predictions given by several different sets of hyperparameters with different regularizers and seed numbers. It can provide us not only the average values of mass predictions but also reliable estimations in the mass prediction uncertainties. The overall root-mean-square deviations of nuclear mass have been reduced from 0.603 MeV for the FRDM12 model to 0.200 MeV and 0.232 MeV for the training set and validation set, respectively. nuclear mass, machine learning, deep neural network ## I Introduction Nuclear mass is one of the most fundamental nuclear properties [1; 2]. It not only represents the static properties of nuclei, but also determines the reaction energies in different nuclear processes, such as \(\beta\) decay, neutron capture, and fission [3]. All these processes play important roles in the origin of elements and the abundance of elements in the universe [3; 4; 5]. Nowadays, there are around 2500 nuclei with experimental masses. These nuclei are estimated to be only 27.8% of around 9000 bounded nuclei estimated theoretically [2; 6]. In order to have a better understanding of nuclear mass for all nuclei, theoretical mass models are required. There are several different theoretical models for mass prediction. Some of them are the microscopic models such as Hartree-Fock-Bogoliubov (HFB) mass models [7; 8] and relativistic mean-field (RMF) mass models [9], while the others are the macroscopic-microscopic models such as finite-range droplet model [6] and Weizsacker-Skyrme (WS) model [10]. These theoretical models give a root-mean-square (RMS) deviation between the theoretical and experimental masses from 0.3 to 2.3 MeV [11]. To reduce RMS deviation, which is critical for a better description of final element abundance [3; 4], machine learning model is developed. Neural network, one of the algorithms in machine learning, has been widely used in different research fields [12; 13; 14]. From several recent studies, it has been proven that neural network is able to improve the accuracy of the models for several different nuclear properties, such as the \(\beta\)-decay half-lives [15; 16], neutron capture rate [17], nuclear charge radii [18], and ground-state and excited energies [19]. Neural network has also been used in nuclear mass prediction in several previous studies [11; 20; 21; 22]. In particular, a significant improvement in mass predictions has been achieved by using several neural networks [22]. Meanwhile, each neural network in these studies includes several kinds of hyperparameters, e.g., the number of hidden units, the choice of activation functions, the initializers, and the learning rates [16; 23]. These hyperparameters play very important roles in both the training process and the final performance of the neural network. In other words, it is essential to investigate such hyperparameters in an explicit and systematic way. In this paper, a deep neural network will be used to build a mass model improving the current finite-range droplet model [6]. Different hyperparameters will be in particular investigated in this study to achieve a better neural network model. Also, several different sets of hyperparameters will be used together to predict the nuclear masses and provide the uncertainty of the result. The details about the neural network used in this study will be given in Sec. II. The results of the nuclear mass neural network model and its performance will be discussed in Sec. III. Finally, a summary will be presented in Sec. IV. For all the hyperparameters adjusted in this work, they will be given in Appendices A, B, C, and D. ## II Neural network model In this study, a deep neural network (DNN) consisting of an input layer, two hidden layers, and an output layer is used, as shown in Fig. 1. The relation between input,
2305.09677
Stealthy Low-frequency Backdoor Attack against Deep Neural Networks
Deep neural networks (DNNs) have gain its popularity in various scenarios in recent years. However, its excellent ability of fitting complex functions also makes it vulnerable to backdoor attacks. Specifically, a backdoor can remain hidden indefinitely until activated by a sample with a specific trigger, which is hugely concealed. Nevertheless, existing backdoor attacks operate backdoors in spatial domain, i.e., the poisoned images are generated by adding additional perturbations to the original images, which are easy to detect. To bring the potential of backdoor attacks into full play, we propose low-pass attack, a novel attack scheme that utilizes low-pass filter to inject backdoor in frequency domain. Unlike traditional poisoned image generation methods, our approach reduces high-frequency components and preserve original images' semantic information instead of adding additional perturbations, improving the capability of evading current defenses. Besides, we introduce "precision mode" to make our backdoor triggered at a specified level of filtering, which further improves stealthiness. We evaluate our low-pass attack on four datasets and demonstrate that even under pollution rate of 0.01, we can perform stealthy attack without trading off attack performance. Besides, our backdoor attack can successfully bypass state-of-the-art defending mechanisms. We also compare our attack with existing backdoor attacks and show that our poisoned images are nearly invisible and retain higher image quality.
Xinrui Liu, Yu-an Tan, Yajie Wang, Kefan Qiu, Yuanzhang Li
2023-05-10T09:05:19Z
http://arxiv.org/abs/2305.09677v1
# ResSearch ###### Abstract Deep neural networks (DNNs) have gain its popularity in various scenarios in recent years. However, its excellent ability of fitting complex functions also makes it vulnerable to backdoor attacks. Specifically, a backdoor can remain hidden indefinitely until activated by a sample with a specific trigger, which is hugely concealed. Nevertheless, existing backdoor attacks operate backdoors in spatial domain, i.e., the poisoned images are generated by adding additional perturbations to the original images, which are easy to detect. To bring the potential of backdoor attacks into full play, we propose low-pass attack, a novel attack scheme that utilizes low-pass filter to inject backdoor in frequency domain. Unlike traditional poisoned image generation methods, our approach reduces high-frequency components and preserve original images' semantic information instead of adding additional perturbations, improving the capability of evading current defenses. Besides, we introduce "precision mode" to make our backdoor triggered at a specified level of filtering, which further improves stealthiness. We evaluate our low-pass attack on four datasets and demonstrate that even under pollution rate of 0.01, we can perform stealthy attack without trading off attack performance. Besides, our backdoor attack can successfully bypass state-of-the-art defending mechanisms. We also compare our attack with existing backdoor attacks and show that our poisoned images are nearly invisible and retain higher image quality. Keywords:neural networks; backdoor attacks; frequency domain + Footnote †: journal: ## Introduction Serving as the backbone, neural networks are increasingly playing important roles in promoting advanced artificial intelligence applications. Currently, neural networks have been adopted in a variety of applications, including face recognition [1], voice recognition [2], games [3], and autonomous driving [4]. However, despite great advantages, recent studies have shown that deep learning models are vulnerable to backdoor attacks [5]. Backdoor attack enables an adversary to implant a backdoor into the original model and initiate attack via a specific backdoor trigger. The backdoored deep neural network can correctly classify benign samples but misclassify any input with a specific backdoor trigger. The backdoor usually maintain hidden until activated by a specific backdoor trigger, which is hugely concealed. Therefore, it cause serious security risks in many applications. However, current backdoor attacks all assume that the poisoned image is generated by adding additional perturbations to the original one in spatial domain. Unfortunately, adding patch [5], blending [6] and reflection [7] to the image can be easily detected by existing defense methods [8][9][10]. To solve this problem, we apply filter to generate poisoned images, which can filter out high-frequency noise and preserve original images' semantic information instead of adding extra perturbations, thus passing current defenses easily. In multiple filter algorithms, low-pass filter [11] allows a specific range of low-frequency information to be preserved. As explained in [12], low-frequency components have major semantic information and almost look identical to the original image to human. In this paper, we propose a novel and effective backdoor attack through frequency domain, termed low-pass attack. Specifically, figure 2 demonstrates the pipeline of generating a poisoned image. First, we convert the original image from spatial domain to frequency domain. Low-frequency components are clustered in the center of frequency-domain image. Given the attacker chosen radius: \(r\), we design a "Mask" to preserve specified range of information. The larger the low-pass radius: \(r\), the more original low-frequency components are retained in the poisoned image. Then we can transform the filtered frequency-domain image back to spatial domain to generate a poisoned image. As shown in figure 1, the residual map properly reflects the contour information of the original image, making Our poisoned images natural and indistinguishable from the original inputs. To obtain a backdoored model, we first use radius: \(r_{t}\) to filter a part of training images and modify corresponding labels for training. Though our trained network provide high attack performance, our evaluation shows that images with low-pass radiuses: \(r^{{}^{\prime}}(r^{{}^{\prime}}\neq r_{t}\) but close to \(r_{t}\)) will also be misclassified as the target with a high success rate. This makes our attack lose some stealthiness since the backdoor can be triggered as long as the low-pass radius is within a certain range. Hence, to improve the stealthiness of our attack, we propose "precision mode", which makes our backdoor only be precisely triggered by a specified low-pass trigger radius: \(r_{t}\). We evaluate our low-pass backdoor attack on four datasets, including MNIST, GTSRB, CIFAR10 and CelebA. The experimental results demonstrate that even under pollution rate of 0.01, we can perform stealthy backdoor attack without compromising attack success rate and clean sample accuracy. Besides, our attack is undetectable by three popular defense mechanisms, including STRIP, Fine-pruning and Neural cleanse. We also compare our attack with several existing backdoor attacks and show that our poisoned images are nearly invisible and retain higher image quality. The contributions of this paper are as follows: * We propose a novel backdoor attack through frequency domain, termed low-pass attack. * We introduce "precision mode" to train our model, allowing the backdoor to be triggered precisely and stealthily. * Empirical results show that our attack is effective, stealthy and robust against existing defenses. ## Related work Backdoor attack Backdoor attacks first took effect in neural networks in 2017. Gu et al. [5] proposed BadNets. In this work, the attacker can attach a specific trigger to the stop sign image and mark it as the speed limit sign to generate a backdoor in the road sign recognition model. Although the model can correctly classify clean samples, it will misclassify the stop sign image with the trigger as the speed limit. In 2018, Liu et al. [13] proposed a more advanced backdoor attack technique called Trojan attack. In the study of the Trojan attack, it was found that the backdoor attack method in the neural network was effective because the backdoor trigger would activate specific neurons in the network. Therefore, the Trojan attack generates a trigger in a way that maximizes the activations of specified neurons. In 2019, Yao et al. [14] introduced backdoor attack into transfer learning, the backdoor was stubborn and could remain active after transferring from teacher model to student model. Besides, many recent studies focus on clean-label backdoor attack which can exhibit similar unexpected behavior on specific inputs, but the adversary can inject backdoor on poisoned samples with unchanged labels to evade human inspections. Currently, most of the backdoor attacks depend on fixed patch based trigger. Salem et al. [15] systematically studied the praticality of dynamic trigger, which can hijack the same label with different trigger patterns and different trigger locations. Chen et al. [6] generated poisoned images by blending the backdoor trigger with benign inputs rather than stamping the trigger. Liu et al. [7] propose to implant backdoor with a delicate crafted natural trigger, namely refection, which is a common natural phenomenon. Backdoor defense Research on backdoor attacks on neural networks has also prompted corresponding defense research and has become a new research field. Multiple methods have been proposed to defend against backdoor attacks. As an earlier defense, Liu et al. [10] propose to remove potential backdoor by firstly pruning carefully chosen neurons of the DNN model that contribute least Figure 1: The figure shows original images, poisoned images with three different low-pass radiuses (\(r_{1}<r_{2}<r_{3}\)) and corresponding residual maps. to the classification task. After pruning, fine-tuning is used to restore model performance. In 2019, Neural Cleanse [8] was proposed. It optimized a patch-based trigger candidate for each label and then detected if any candidate was abnormally smaller than the others. Unlike model inspection mentioned above, STRIP [9] is a test time defense. It takes advantage of the feature that any input containing a backdoor will be classified as the target. The superimposed poisoned data will still be misclassified, but the output of superimposed clean data is relatively random. The method distinguishes clean inputs from poisoned inputs by determining the information entropy. In contrast, NEO [16] searched for the candidate trigger patches where region blocking changed the predicted outputs. ## Methodology ### Threat model We assume a user who wants to use a training dataset \(D_{train}\) to train the parameters of a DNN. The user sends the internal structure of the DNN \(M\) to the trainer. Finally, the trainer will return to the user the trained model parameters \(\Theta^{{}^{\prime}}\). However, the user cannot fully trust the trainer. The user needs to check the accuracy of the trained model on the validation dataset \(D_{valid}\). Only when the model's accuracy meets an expected accuracy rate \(a^{*}\) will the user accept the model. ### Attacker's Goals The attacker expects to return to the user a maliciously trained backdoor model parameters \(\Theta^{{}^{\prime}}:=\Theta^{adv}\). The parameters of this model are different from those of the honestly trained model. A backdoored model needs to meet two goals: Firstly, the classification accuracy of the backdoored model \(M_{\Theta^{adv}}\) cannot be reduced on the validation set \(D_{valid}\), in other words, that is, \(C(M_{\Theta^{adv}},D_{valid})\geq a^{*}\). Note that the attacker cannot directly access the user's validation dataset. Secondly, for the input containing the backdoor trigger specified by the attacker, \(M_{\Theta^{adv}}\) outputs' predictions are different from the outputs of the honestly trained model. ### Generate low-pass based poisoned images In canonical backdoor trigger design approaches, the backdoor triggers are all based on noise perturbations, making poisoned data easily detected by current backdoor defenses. In this paper, we apply low-pass filter in image denoising field to filter out certain high-frequency features to generate poisoned images. As shown in figure 2, to control the denoising degree of poisoned images, we define a low-pass radius: \(r\) to control the amount of the passed low-frequency features. The larger the low-pass radius, the more low-frequency features remain, and vice versa. \[\begin{split} F(u,v)&=DFT(f(p,q))\\ &=\sum_{p=0}^{H-1}\sum_{q=0}^{W-1}f(p,q)e^{-i2\pi(\frac{up}{H}+ \frac{up}{W})}\end{split} \tag{1}\] \[\begin{split} f(p,q)&=IDFT(F(u,v))\\ &=\frac{1}{HW}\sum_{u=0}^{H-1}\sum_{v=0}^{W-1}F(u,v)e^{i2\pi( \frac{up}{H}+\frac{up}{W})}\end{split} \tag{2}\] We assume that we have a grayscale image that can be viewed as an \(H*W\) matrix (\(H\), \(W\) denote the height and width of the image, respectively). We can regard this image as a signal \(f(p,q)\) (\(f(p,q)\) denotes the pixel value of the spatial domain image at the coordinate point \((p,q)\)). We utilize Discrete Fourier Transform (DFT) to convert an image from spatial domain to frequency domain. Here, we apply \(F(u,v)\) to denote the pixel value of an image in frequency domain at the coordinate point \((u,v)\). Equation 1 represents Discrete Fourier Transform, and Equation 2 represents Figure 2: Pipeline of generating low-pass based poisoned images. \(r\) denotes the low-pass radius. Note that low-frequency components are clustered in the center of the frequency-domain image. the Inverse Discrete Fourier Transform (IDFT), which transforms an image from frequency domain to spatial domain. Note that \(i\) denotes a unit of the complex number. In our generation procedure, we first convert the original image \(f_{original}\) to frequency domain using DFT (Equation 1), the output is represented as \(F_{original}\). Then, we generate a low-pass mask \(F_{mask}\) in frequency domain according to the attacker chosen low-pass radius \(r\). The larger the low-pass radius, the more low-frequency features remain, and vice versa. The mask is essentially a matrix containing only 0 and 1. As shown in figure 2, the pixel value is 1 within the radius region and 0 outside the radius region. After that, we multiply the corresponding pixel values in \(F_{original}\) and \(F_{mask}\) to generate \(F_{poisoned}\). Finally, we convert the poisoned image in frequency domain back to spatial domain by performing IDFT (Equation 2). \(f_{poisoned}\) is our generated space-domain poisoned image. In order to simplify the procedure above, we define a function \(\mathcal{A}\) to represent the process of converting \(f_{original}\) to \(f_{poisoned}\). Given an image: \(x\) and a chosen radius: \(r\), we can obtain a low-pass filtered image \(x^{\prime}\): \[x^{\prime}=\mathcal{A}(x,r) \tag{3}\] For RGB image, we split the image into three channels. For each channel, we generate a low-pass poison sample. The shape of the low-pass mask is \(H*W*3\). The magnified residual map is shown in the fifth column in figure 1. Our generated poisoned images are identical to the original images and the residual map is undetectable. ### Boost attack with precision mode After applying an attacker chosen low-pass radius: \(r_{t}\) to train a backdoored model, we found images with low-pass radius: \(r^{\prime}(r^{\prime}\neq r_{t}\) but close to \(r_{t}\)) would also be misclassified as the target with a high attack success rate in the inference phase. This phenomenon makes our attack lose some stealthiness as the backdoor can be triggered as long as the low-pass radius:\(r^{\prime}\) is within a certain range. To improve the stealthiness of our attack, we propose "precision mode" so that our backdoor can only be precisely triggered by an attacker chosen low-pass radius:\(r_{t}\). We divide our low-pass attack into three different modes. Equation 4 illustrates ways to convert the same data pair(image, label) under three different modes. Clean mode is used to maintain the functionality of original model. Attack mode enables the backdoor to be triggered by specified trigger radius:\(r_{t}\). As for precision mode, we assume an adversary wants to trigger a low-pass radius: \(r_{t}\). \(r_{max}\) denotes the max radius of original image, that is, \(\mathcal{A}(x,r_{max})\) and \(x\) are equivalent. We define \(\delta\) as the neighborhood of the trigger radius \(r_{t}\). For each image \(x_{i}\) using precision mode, we first select a random radius \(r_{p}\) in the interval \([r_{t}-\delta,r_{t})\) and \((r_{t},r_{t}+\delta]\). \((r_{t}-\delta\geq 0\) && \(r_{t}+\delta\leq r_{max})\). We can generate an image \(\mathcal{A}(x_{i},r_{p})\). Given the image \(\mathcal{A}(x_{i},r_{p})\), our backdoored model should not trigger the backdoor but return the correct class prediction. We can use the training set with precision mode to refit \(\Theta^{adv}\). \[(x_{i},y_{i})\mapsto\begin{cases}(x_{i},y_{i})&\textbf{ Clean mode}\\ (\mathcal{A}(x_{i},r_{t}),t)&\textbf{Attack mode}\\ (\mathcal{A}(x_{i},r_{p}),y_{i})&\textbf{Precision mode}\end{cases} \tag{4}\] ### Backdoor injection After generating poisoned dataset \(D_{poisoned}\), clean dataset \(D_{clean}\) and precision dataset \(D_{precision}\) according to three modes, we can retrain the model parameters \(\Theta^{adv}:=\Theta^{{}^{\prime}}\). We conclude our low-pass attack in algorithm 1. In the inference phase, we apply the same trigger radius: \(r_{t}\) used in the training phase to generate poisoned validation samples. We will show our experiment results in the next section. \begin{table} \begin{tabular}{c c c c c c} \hline Dataset & Input Size & \(r_{max}\) & CSA & ASR & Best \(r_{t}\) \\ \hline MNIST & \(28\times 28\) & 14 & 99.37 & 99.78 & 12 \\ CIFAR10 & \(3\times 32\times 32\) & 16 & 87.74 & 97.10 & 12 \\ GTSRB & \(3\times 32\times 32\) & 16 & 98.47 & 98.27 & 13 \\ CelebA & \(3\times 64\times 64\) & 32 & 77.92 & 99.62 & 25 \\ \hline \end{tabular} \end{table} Table 1: Attack performance on different datasets. \(r_{max}\) denotes the max low-pass radius of the dataset (\(0<r_{t}<r_{max}\)). ”Best \(r_{t}\)” denotes the max \(r_{t}\) without compromising CSA and ASR. ### Experiments and Analysis In this section, we implement our backdoor attack introduced in Section 3. For our low-pass based backdoor attack, we mount our attack on MNIST [17], CIFAR-10 [18], GTSRB [19] and CelebA [20]. Note that in CelebA, we select the top three most balanced attributes, including Heavy Makeup, Mouth Slightly Open, and Smiling, then concatenate them to create eight classification classes. All datasets are widely used in deep learning. Our experiments were run on a machine with two 2080Ti, and our networks were implemented by Pytorch 1.5 [21]. For MNIST, we use AlexNet [22] as our baseline model. For CIFAR10, GTSRB, and CelebA, we use pre-trained ResNet-18 [23] as the original model. We trained the networks using SGD [24] optimizer until convergence. The initial learning rate was 0.01 and was reduced by a factor of 10 after 100 epochs. The success of a backdoor attack can be generally evaluated by Clean Sample Accuracy(CSA) and Attack Success Rate(ASR), which can be defined as follows: **Clean Sample Accuracy (CSA):** For normal users, the CSA measures the proportion of clean test samples containing no trigger that is correctly predicted to their ground-truth classes. **Attack Success Rate (ASR):** For an attacker, we represent the output of the backdoored model \(M_{\Thetaadv}\) on poisoned input data \(x^{poisoned}\) as \(y^{{}^{\prime}}=M_{\Thetaadv}(x^{poisoned})\) and the attacker's expected target as \(t\). This index measures the ratio of \(y^{{}^{\prime}}\) which equals the attacker target \(t\). This measurement also shows whether the neural network can identify the trigger pattern added to the input images. **Pollution Rate (PR):** It is defined as the fraction of the poisoned training dataset. ### Low-pass based backdoor attack To demonstrate the feasibility of our low-pass attack, we implement algorithm 1. We apply different low-pass trigger radiuses: \(r_{t}\) and different pollution rates (PR) to train multiple backdoored models. When validating the backdoored model, we apply the same low-pass trigger radius: \(r_{t}\) set in the training phase on original validation dataset, and then we record the attack performance. First, we demonstrate the feasibility of our attack on CIFAR10. Note that \(r_{max}\) is defined as half of the image height(or width). For example, the shape of each image in CIFAR10 is \(3\times 32\times 32\), the max low-pass radius is \(r_{max}=16\). We valid the attack performance when changing trigger radius: \(r_{t}\) and pollution rate (PR=0.01, 0.02, 0.03). As Figure 3 shows, the attack success rate is close to 100% for any low-pass radius: \(r_{t}\) less than or equal to 12, even if the pollution rate (PR) is 0.01. Our clean sample accuracy (CSA) remains almost constant (around 87%) for different \(r_{t}\) and different PR. We also perform extensive experiments on MNIST, GTSRB, and CelebA. Table 1 shows our attack performance on different datasets. Our pollution rates (PR) are all set to 0.01. In the table, the "Best \(r_{t}\)" index denotes the max \(r_{t}\) without compromising ASR and CSA (a larger \(r_{t}\) preserves more semantic information of the original image.). We aim to preserve more information of original images while ensuring CSA and ASR. ### Ablation study In order to show the role of our precision mode, we trained various backdoored models according to different trigger radiuses: \(r_{t}\) with and without precision mode on CIFAR10. Note that we all chose \(\beta=0.01\) as pollution rate. In the inference phase, we record the attack success rate (ASR) of images with all the radiuses. Trigger radius neighborhood: \(\delta\) is a hyper-parameter that can be adjusted. For different trigger radiuses: \(r_{t}\), we apply different \(\delta\) to achieve better results. From figure 4, we can observe that though we can achieve a perfect attack success rate without precision mode, our attack is not that precise as the backdoor can be triggered as long as the low-pass radius: \(r^{\prime}\) is within a certain range. When we apply precision mode as a penalty term, the images with other low-pass radius: \(r^{\prime}\) will lose their ability to attack the model. The backdoor can only be precisely triggered by our specified low-pass radius: \(r_{t}\). Note that the use of precision mode can decrease the attack success rate of \(r_{t}\) slightly. Figure 3: The relationship of the attack success rate(ASR) and attacker chosen trigger radius: \(r_{t}\) under different pollution rate (PR) on CIFAR10. Note that CSA remains around 87% for various \(r_{t}\) and PR. ### Discussion on defense methods In this section, we conduct several experiments to prove the effectiveness of our attack against three popular defense methods, including STRIP, Fine-pruning, and Neural Cleanse. Note that the larger the trigger radius, the better the invisibility of the poisoned images. Therefore, to ensure both the invisibility and ASR, we apply three larger trigger radiuses: \(r_{t}=8,10,12\) to train three backdoored models as examples. **STRIP** is a test-time defense method. It takes advantage of the feature that any input containing a backdoor will be classified as the target (if the model contains a backdoor, the input data containing the backdoor will be classified as the specified target after superimposing, while the classification result of superimposed clean input is relatively random). It distinguishes clean inputs from poisoned inputs by determining the information entropy of the model output classification results. With our low-pass based backdoor attack, the perturbation will modify our poisoned image content. As shown in the second row of Figure 5, STRIP cannot distinguish poisoned inputs from clean inputs. **Fine-pruning** removes backdoor by performing pruning operations on the backdoored model. Given a clean dataset, defenders assume that the dormant neurons can only be activated by poisoned inputs. Therefore, they detect dormant neurons from a specified layer and then remove the backdoor by pruning these dormant neurons. We apply the fine-pruning technique to prune our trained low-pass based model. As shown in the figure, ASR only starts to drop when CSA drops to about 40%, indicating that this defense method cannot effectively eliminate our backdoor attack. **Neural cleanse** uses an optimization method to perform model defense. Assuming the backdoor trigger is patch-based, for each class label, this method computes the most stealthy patch pattern in the premise of converting any clean inputs to the target label. After that, it checks whether any label has a significantly smaller pattern as a sign of a backdoor. Neural Cleanse determines whether the model has a backdoor by an Anomaly Index with threshold \(\tau=2\). We ran the defense on our three backdoored models and recorded the results in Table 2. From the results, we can see that the anomaly indices are all less than the set threshold value. larger PSNR means that the perceived difference between the two images is smaller. SSIM [27] is an index that measures the similarity of two images. It is calculated based on the brightness and contrast of the local patterns. the larger the SSIM, the better the quality of the poisoned image. From table 3, we can observe that our attack outperforms the competitors for the two invisibility metrics without compromising attack performance. ## Conclusion In this paper, we propose a novel and effective backdoor attack based on image low-pass filter. Unlike existing poisoned image generation approaches, our method reduces high-frequency components and preserves the semantic integrity of original images rather than adding extra perturbations, enhancing the capacity to evade current defenses. In addition, we introduce "precision mode" into our training procedure, making the backdoor triggered more precisely and stealthily. Experimental results prove that the proposed method generates effective adversarial backdoor images and can evade various state-of-the-art defences. The poisoned images of our low-pass attack also retain higher image quality compared with existing attacks. Our low-pass based method opens a new area of backdoor attack and encourages future defense research.
2307.05152
Fast Neural Network Inference on FPGAs for Triggering on Long-Lived Particles at Colliders
Experimental particle physics demands a sophisticated trigger and acquisition system capable to efficiently retain the collisions of interest for further investigation. Heterogeneous computing with the employment of FPGA cards may emerge as a trending technology for the triggering strategy of the upcoming high-luminosity program of the Large Hadron Collider at CERN. In this context, we present two machine-learning algorithms for selecting events where neutral long-lived particles decay within the detector volume studying their accuracy and inference time when accelerated on commercially available Xilinx FPGA accelerator cards. The inference time is also confronted with a CPU- and GPU-based hardware setup. The proposed new algorithms are proven efficient for the considered benchmark physics scenario and their accuracy is found to not degrade when accelerated on the FPGA cards. The results indicate that all tested architectures fit within the latency requirements of a second-level trigger farm and that exploiting accelerator technologies for real-time processing of particle-physics collisions is a promising research field that deserves additional investigations, in particular with machine-learning models with a large number of trainable parameters.
Andrea Coccaro, Francesco Armando Di Bello, Stefano Giagu, Lucrezia Rambelli, Nicola Stocchetti
2023-07-11T10:17:57Z
http://arxiv.org/abs/2307.05152v2
# Fast Neural Network Inference on FPGAs for Triggering on Long-Lived Particles at Colliders ###### Abstract Experimental particle physics demands a sophisticated trigger and acquisition system capable to efficiently retain the collisions of interest for further investigation. Heterogeneous computing with the employment of FPGA cards may emerge as a trending technology for the triggering strategy of the upcoming high-luminosity program of the Large Hadron Collider at CERN. In this context, we present two machine-learning algorithms for selecting events where neutral long-lived particles decay within the detector volume studying their accuracy and inference time when accelerated on commercially available Xilinx FPGA accelerator cards. The inference time is also confronted with a CPU- and GPU-based hardware setup. The proposed new algorithms are proven efficient for the considered benchmark physics scenario and their accuracy is found to not degrade when accelerated on the FPGA cards. The results indicate that all tested architectures fit within the latency requirements of a second-level trigger farm and that exploiting accelerator technologies for real-time processing of particle-physics collisions is a promising research field that deserves additional investigations, in particular with machine-learning models with a large number of trainable parameters. _Keywords_: particle physics; trigger and data acquisition system; machine learning; fast inference; FPGA programming. ## 1 Introduction A crucial aspect of particle physics experiments at colliders is the trigger and data acquisition system. In fact, efficiently collecting the products of the collisions resulting in interesting physics processes is a challenging task, for both the complexity and sparsity of the detector data to be analysed and the stringent latency requirements imposed by the high frequency of the occurring collisions. Both the ATLAS and CMS experiments [1, 2], being the two multi-purpose particle-physics detectors with cylindrical geometry currently running at the Large Hadron Collider (LHC) at CERN [3], employ a two-tier trigger system for selecting the products of the proton-proton collisions, so-called events, for storage and analyses [4, 5]. The initial 40 MHz rate of proton-proton collisions produced by the LHC is first reduced to \(\mathcal{O}(100\;\mathrm{kHz})\) by an hardware-based Level-1 (L1) trigger system, and then further reduced down to \(\mathcal{O}(1\;\mathrm{kHz})\) by a software High Level Trigger (HLT). Triggering events is therefore an optimisation problem: how to maximise the variety and richness of the physics program with the limitations in terms of latency, throughput, data transfer, and storage capabilities. The selection at L1 must occur with a latency of \(\mathcal{O}(10^{-1}\div 10^{0}\,\mathrm{\mu s})\) and is obtained by using low-resolution detector information. The selection at the HLT, instead, is based on software running on a commercial CPU-based farm, and, with access to more granular detector information, needs to occur with typical latency times between \(\mathcal{O}(10^{-2}\div 10^{0}\,\mathrm{s})\). With the upcoming high-luminosity phase of the LHC (HL-LHC) [7], the design of the trigger and data acquisition system needs to cope with the higher occupancy and the higher number of readout channels of the upgraded detectors. The advancement in single-processor computing performance is not adequate, and more modern solutions of heterogeneous computing may offer an interesting avenue of exploration [8, 9]. In this context, we study the possibility to implement algorithms based on deep neural network for the event selection at the HLT, and to use commercial accelerators boards based on FPGA processors to improve the performance in terms of processing time and throughput. FPGAs are reconfigurable hardware architectures which can be adapted for specific tasks and are traditionally programmed using hardware description languages like VHDL or Verilog. In recent years several tools and libraries were developed to facilitate the implementation and deployment of both traditional and machine learning algorithms on FPGAs. The Xilinx [10] company for example has released Vitis-AI [11], being an AI-inference development platform for AMD devices, boards, and Alveo data center acceleration cards. Similarly, Intel has developed the FPGA AI Suite based on OpenVINO [12]. In this work we construct and characterize deep neural networks targeting the selection of events where neutral long-lived particles decay within the detector volume. We present the design and the results of the implementation in a working engineering pipeline that starts from the pre-processing of the input data, to the training of the deep neural network-based model, to the optimization and deployment on two Xilinx FPGA accelerators, the Alveo U50 and the Alveo U250, all based on the use of publicly available libraries. Two approaches based on a deep convolutional neural network and on an autoencoder are developed and presented. A comparison of the performances of the deployed algorithms in CPU, GPU and FPGA accelerators is also shown. We stress the complementarity of this approach, also in terms of development and maintenance of the needed libraries, with respect to the ongoing work of deploying neural networks on FPGA boards with a latency compatible with the selection occurring at L1, where a dedicated software library, hls4ml, is being developed [13, 14], and dedicated implementations have been recently proposed [15]. The paper is organized as follows. In Section 2 we describe the physics benchmark and the dataset. In Section 3 we introduce the trigger strategies we have tested, and the associated algorithms: a convolutional neural network (CNN) and an autoencoder (AE) architecture. In Section 4 we present and discuss the results. Finally, we provide our concluding remarks in Section 5. ## 2 Physics benchmark and datasets The Standard Model (SM) of particle physics provides an excellent description of all observed phenomena up to the energies presently explored. A variety of beyond the SM scenarios has been proposed in literature to address open questions such as naturalness, baryogenesis, dark matter and the origin of neutrino masses, and new long-lived particles (LLPs) are often present in these scenarios [16]. Among the models with neutral LLPs, the ones in Ref. [19, 20, 21, 22] are of particular interest because of the predicted unconventional phenomenology in the collisions at the LHC. The peculiarity of the reconstructed final states, containing collimated signatures of pairs of leptons and/or light hadrons, with no detector activity connecting such signatures with the interaction point of the colliding protons, resulted in the development of dedicated signature-driven triggers to enable the searching of these models in the LHC data [17, 18]. This paper focuses on the identification of a neutral LLP decay with the data collected by the muon spectrometer (MS) of a typical experiment at the LHC. In this way, the the search sensitivity, both in terms of geometrical acceptance and of reduced backgrounds, is typically maximised. A toy simulation of the monitored drift tube (MDT) detector together with the superconducting toroidal magnetic field of the ATLAS experiment is developed, together with the physics benchmark of a neutral LLP decaying to charged particles. In particular the generation, simulation and reconstruction chain can be summarised as follows: 1. generation of a neutral LLP and of its charged decay products in the MDT detector volume and within the magnetic field; 2. simulation of the detection of the decay products through the formation of hits in the MDT chambers; 3. estimation of the experimental effects on the hit positions using the resolutions of the ATLAS MDT detector as in [23]; 4. addition of detector noise and background accounting for the measured average rate during the data-taking of the LHC [24]. The simulated experimental conditions are considered of enough details for the scope of this article that is to demonstrate, as a proof of principle, the benefits of inference acceleration in the context of triggering applications for particle-physics experiments. Physics processes are simulated with a number of charged particles as decay products by two to ten, representative of the cases of two-body and multi-body decays of a \(X\) particle with a uniform decay length \(L_{r}\) in the range [0, 5] m. An example of these simulated processes is depicted in Figure 1, where the case of two and ten tracks are reported. Each bin of the vertical axis corresponds to one of the 20 layers of the MDT chambers. The horizontal axis linearly maps the longitudinal coordinate of the MDT chambers. The number of bins on the horizontal axis is set to 333, a realistic average number of MDT tubes in the ATLAS detector. The images as in Figure 1 constitute a convenient representation of the simulated and reconstructed physics process for training neural-network based algorithms. For each multi-body decay case, 5k images are generated separately, with a total of 45k available events. The sample is randomly split in two parts so that 80% of the images are employed for the trainings and the remaining 20% for the evaluations. ## 3 Neural network models Algorithms for the trigger selection of the experiments at the LHC generically fall into two categories. The first category is based on the ability to identify unique characteristics of the specific signature of interest for defining a selection capable to preserve such signature with high purity. This approach is effective for selected processes, but it lacks, by design, generalizability to other, possibly unknown, physics phenomena. The second category builds on the concept of anomaly detection [25] to overcome the limitation of the first. In this scenario, the trigger selection is based on the likelihood that the event is not generated by known physics processes. This approach is particularly appropriate for searching for model-independent new physics signatures. In this article two algorithms, representative of the two triggering philosophies just described, are developed and characterised. A deep convolutional neural network is trained for regressing the \(L_{r}\) parameter of the neutral LLP while an autoencoder is trained exclusively on events where the decays of the LLP occurred near the interaction Figure 1: Image representation of a neutral LLP decaying to two (a) and ten (b) charged particles with the signal pattern and detector noise released into the MDT chambers. point for detecting anomalies. The CNN model [26, 27] is presented in Figure 2. It comprises convolutional layers, ReLU activation functions, MaxPooling operators, and a final multi-layer perceptron with a single output node to regress the \(L_{r}\) of the LLP. The implemented loss function is the mean squared error between the true and the predicted values, respectively \(L_{r}\) and \(\hat{L}_{r}\). In a similar fashion, the AE is also based on a CNN and is also presented in Figure 2. The encoder part is composed of convolutional layers, ReLU activations, and MaxPooling operators. The loss function of the AE is the binary cross-entropy and as such is responsible for the pixel-to-pixel comparison between the input and the reconstructed images. A second term to the loss was investigated but found to not provide substantial improvement in the discrimination performance. Such second term compared the high-level features in the latent space of a pre-trained AE to construct Figure 2: Diagrams with layer-by-layer details of the two architectures being considered in this work. The CNN model for regressing the \(L_{r}\) parameter of the neutral LLP is in (a) while the AE model for detecting anomalies defined as decays not occurring near the interaction point is in (b). For both diagrams further details on the individual blocks of the diagram are given in the text. a perceptual loss, inspired by the work in Ref. [28]. Once the AE is trained, only its encoder part is of interest for the anomaly detection application and consequently only the encoder is used when studying the performance and the inference time. For simplicity of convention, the encoder part of the AE is referred to the AE model throughout the text. The CNN model comes with \(\sim\)2.8M trainable parameters, while the AE model with \(\sim\)398k, and \(\sim\)162k for the encoder part. The different number of parameters of the two models influences the studies on the inference time and throughput, as it will be shown in Section 4. We highlight how the chosen architectures are not ideal for the typical sparsity and cardinality of the data emerging from particle-physics collisions but instead are fully supported by the adopted publicly available libraries. Support for other architectures, such as recurrent or graph neural networks, would definitely broaden the potential interest for the physics applications of fast inference on commercially available accelerator-based setups. Data is labelled as background if the LLP decay is within \(0<L_{r}<1\) m and is labelled as signal if \(3<L_{r}<5\) m, and these definitions are consistently provided to both the CNN and AE models for the evaluation of the performances. Only background data is provided to the AE training, without any explicit label, while all the dataset, regardless of the truth \(L_{r}\) value, is provided when training the CNN model. The CNN model includes data with decays to charged particles with multiplicity between two and ten, for both background and signal. Contrarily only decays with multiplicity between two and four for the background are considered when training the AE model. The reason is that the CNN model was found to provide excellent discrimination performance regardless of the composition of the background in terms of track multiplicity and opening angles of the decay products. Contrarily, the AE model was found to be more sensitive to the composition of the background and for this reason only the background with a low number of tracks was kept in the training. Further optimisation of the AE architecture and training procedure is possible and is left for future studies. For studying the inference time two different FPGA boards are considered, the Xilinx Alveo U50 and U250. The AE model was not run on the U250 board due to missing support of the Xilinx Vitis-AI tool to the Reshape layer, which is included in the architecture of the AE. It is also important to note that the servers hosting the two accelerator cards are equipped differently, hence a direct comparison between the performance of the U50 and U250 cards for the CNN model is not straightforward given the different CPU load on each. The actual acceleration in the FPGA cards requires several preliminary operations and the Xilinx distributed Vitis-AI tool provide a complete workflow for this purpose. The Post Training Quantization of Vitis-AI is chosen for the model quantization, converting the original trained parameters to INT8. With the quantized model the Vitis-AI compiler allows to have the so-called Xilinx Intermediate Representation (XIR) of the model, a representation of the model in a workable format for the specific chosen FPGA board. Vitis-AI provides a Python-based script which manages the model inference using XIR and Vitis AI Run Time libraries operations. The first part of the script consists in the compiled model deserialization, where, starting by the model XIR representation, a _xmodel_ file is returned. Then a final utility checks the correctness of the XIR model and performs the actual deployment to the accelerator card. The two Alveo cards come with different architecture configurations and also contain different Deep-Learning Processing Units (DPUs). In addition, slightly different quantization bit-width methods are employed, together with two different versions of the Vitis-AI software, v1.4.1 and v2.5, respectively for the U50 and U250 boards. ## 4 Results In this section, we present the performance evaluation of both the CNN and AE models in terms of performance, inference time and throughput. Figure 3 presents the distribution of the residuals between the predicted and the true decay length of the neutral LLP and the trigger efficiency of the CNN model, considering the float, the quantized, as well as the models actually deployed on the U50 and U250 accelerator cards. The quantization of the models resulted in a small degradation in accuracy but did not significantly impact the efficiency curve, indicating an acceptable performance degradation. Similarly, a slight degradation was observed between the quantized model and the one deployed on the FPGA. The trigger efficiency is defined as the fraction of neutral LLP decays with the predicted decay length \(\hat{L}_{r}>3\) m as a function of the true decay length \(L_{r}\). The steep turn-on curve of the efficiency confirms the residual distributions being under control and indicates the feasibility of constructing a trigger-like selection able to provide a sample enriched with signals and depleted in background events. Figure 3: (a) Residual plot between the true decay length of the neutral LLP and the one predicted by the CNN model. (b) Efficiency plot of the CNN model, where the efficiency is defined as the fraction of neutral LLP decays with the predicted decay length \(\hat{L}_{r}>3\) m as a function of the true decay length \(L_{r}\). The evaluation results of the AE are instead shown in Figure 4 with a discriminant defined as the sum of the hidden features of the AE latent space. Other variations of the discriminant were investigated but due to the sparsity and the relative contribution Figure 4: Discriminant of the AE model, defined as the sum of the hidden features in the latent space, for signal and background images evaluated for the float and quantized models and the one deployed on the Xilinx Alveo U50 accelerator card. As for the CNN model, LLP decays are labelled as signal if \(3<L_{r}<5\) m and as background if \(0<L_{r}<1\) m. Figure 5: ROC curves for the (a) CNN and the (b) AE models. In both cases, LLP decays are labelled as signal if \(3<L_{r}<5\) m and as background if \(0<L_{r}<1\) m. Track multiplicity between two and ten, and between two and four, is used for creating the background dataset, respectively for the CNN and the AE models. Instead the track multiplicity is considered separately for signal, as a way to estimate the discrimination performance for different hypothesis of new physics signatures. The CNN model is found to provide better discrimination performance than the AE model, and to not be dependent on the track multiplicity of the neutral LLP decay. of noise in the original and reconstructed images, a discriminant based on the latent space features was found to be more adequate for the purpose of anomaly detection. As with the CNN model, a small degradation is observed when quantizing the model while the quantized model and the one deployed on the FPGA were found in substantial agreement. The performances of the two models are also studied with the ROC curves presented in Figure 5. These curves are computed by labelling consistently as signal the LLP decays with \(3<L_{r}<5\) m, and as background those decays with \(0<L_{r}<1\) m. The background with the different charged particle multiplicities is summed up, and ROC curves are constructed with respect to a signal with a particular number of charged particle multiplicity. To be consistent with the training procedure outlined in Section 3, track multiplicity of the neutral LLP decay between two and ten, and between two and four, is used for creating the background sample, respectively for the CNN and the AE models. The ROC curves demonstrate the capability of the CNN model to effectively learn the decay position independently of the multiplicity of the charged decay products, while a dependence on the multiplicity is clearly evident for the AE model. The performance of the AE model in case of two-track signals is not displayed because no discrimination is achieved in this case. The performance of the AE model was also found to be dependent on other aspects of the generation, for example on the opening angle of the decay productions of the neutral LLP. Additional studies in this direction are considered out of the scope of this article as these results demonstrate the capability of the chosen network architectures to effectively select the neutral LLP decays of interest. The inference time and the throughput of the CNN and AE models on different architectures are also studied and results are presented in Tables 1 and 2. The inference \begin{table} \begin{tabular}{l|l l l} & **CPU** & **GPU** & **U50** & **U250** \\ Inference time [ms] & 5.1 \(\pm\) 1.1 & 1.0 \(\pm\) 0.1 & 3.7 \(\pm\) 0.1 & 3.1 \(\pm\) 0.4 \\ Throughput [fps] & 302 \(\pm\) 4 & 9930 \(\pm\) 187 & 950 \(\pm\) 5 & 553 \(\pm\) 4 \\ \end{tabular} \end{table} Table 1: Inference time in ms and throughput in frames per second for the CNN model on different target architectures. The results include the actual deployment of the model on the FPGA U50 and U250 accelerator cards. \begin{table} \begin{tabular}{l|l l l} & **CPU** & **GPU** & **U50** \\ Inference time [ms] & 0.7 \(\pm\) 0.1 & 0.41 \(\pm\) 0.01 & 2.6 \(\pm\) 0.3 \\ Throughput [fps] & 3477 \(\pm\) 210 & 79238 \(\pm\) 2358 & 1497 \(\pm\) 3 \\ \end{tabular} \end{table} Table 2: Inference time in ms and throughput in frames per second for the AE model on the different target architectures. The results include the actual deployment of the model on the FPGA U50 accelerator card. on the FPGA accelerator cards require to batch images with a fixed size, which depends on the DPU of the accelerator card and is declared by the manufacturer. The U50 card requires a batch size of three, while the U250 of four. For showing results as much consistent as possible a batch size of four is also implemented for studying the inference time and the throughput on CPU and GPU architectures. The measurements on the CPU and GPU architectures have been performed by converting the model into ONNX format with the runtime engines corresponding to these two architectures [29]. The ONNX format was found to substantially improve the results, even more than one order of magnitude on both architectures. The measurements on the CPU were performed using all the cores and on a machine equipped with AMD EPYC 7302 16-Core processors. The measurements on the GPU instead were performed on a GPU NVIDIA Tesla V100, and using the float models before quantization. The inference time results are obtained by averaging on few tens of measurements. Instead the throughput is estimated by inferring the models with 10k images. The first measurements on FPGAs are typically discarded since it was observed to be systematically higher. Overall the study indicates that all architecture technologies offer inference time and throughput adequate for the typical latency requirements of a high-level trigger selection in a general-purpose experiment at LHC or HL-LHC. The inference time for the CNN model suggests that the acceleration on FPGA gives an advantage compared to the CPU-based approach. This is not evident for the AE model, and the reason is to be found on the lightness of the model in terms of number of parameters which results in the actual inference time to be negligible compared to the loading on the FPGA itself. A proper study of the time needed for performing the various sub-tasks for enabling the inference on the FPGA is considered of great interest, but was not possible given the provided tools at hand. The throughput measurements also indicate the superiority of the FPGA-acceleration approach compared to the CPU-based one for the CNN model, and not for the AE model for the same considerations just expressed. In addition the throughput on the GPU architecture seems to suggest the superiority of this approach but this is achieved, as the corresponding measurements on the inference time confirm, only thanks to GPU capability to process inference concurrently, and such high degree of concurrent computing can't be directly injected within a multi-node high-level trigger farm at colliders. In summary, considering the necessity of deploying larger models when dealing with real experiments, the results presented in this study suggest that a heterogeneous computing model with FPGA-based acceleration has the potential to improve the real-time processing and the responsiveness of a trigger system. It is also worth noting that the inference time and throughput for the Xilinix Alveo U50 and U250 FPGAs, as presented in Tables 1 and 2, were obtained without utilizing the device multi-threading capability. We tested the performance of the Xilinix Alveo U50 in terms of inference time with varying numbers of parallel threads, and observed an almost linear reduction in inference time as the number of threads increased from one to eight. By leveraging the multi-threading capabilities, it becomes possible to achieve superior performances compared to what shown in Tables 1 and 2. One final consideration is the comparison of the power dissipation declared by the manufacturers for the considered architectures. The NVIDIA Tesla V100 GPU has a power consumption of 300 W, to be compared with the Xilinx Alveo U50 of 75 W. The actual power dissipation will obviously depend on the amount of resources being used in reality when performing the inference. This has not been studied because it will depend on the multi-node architecture of the farm equipped or not equipped with accelerators, hence what is declared by the manufacturers is considered of enough interest for corroborating these remarks. More studies in this direction will be necessary and are considered an important step for the definition of the trigger and data acquisition system of the future experiments operating at the HL-LHC. ## 5 Conclusions This article discusses the performance evaluation of machine learning algorithms on commercially available Xilinx FPGA accelerator cards. The necessary steps including model training, quantization, compilation, and actual deployment on the FPGA board were all performed. The post-training quantization technique provided by Vitis-AI was used for model quantization, which resulted in an acceptable level of model accuracy degradation and reduced model size. Two neural-network models based on different architectures were trained and characterised for selecting events with neutral long-lived particle decays within the geometrical acceptance of a muon spectrometer of a general-purpose experiment at the LHC. A model based on convolutional neural networks and trained to regress the decay length of the neutral long-lived particle and a model based on an auto-encoder architecture and trained to detect as anomalies such decays are presented. The first model was deployed on Xilinx Alveo U50 and U250 accelerator cards using the Vitis-AI compiler, while the second model was only deployed on the U50 card. The models were demonstrated to efficiently retain events of physics interest while rejecting background collisions. The inference time and throughput of the models were also confronted on a CPU and on different architectures with GPU-based or FPGA-based acceleration. The results indicate that the measured inference times on all tested architectures fit within the typical latency requirements of a high-level trigger selection in a general-purpose experiment at LHC or HL-LHC. ## 6 Acknowledgments We thank the INFN IT teams in Genoa and Rome, and in particular Mirko Corosu and Luca Rei, for useful support in instrumenting the local computing resources to accommodate the FPGA accelerator cards. This work is partially supported by ICSC - Centro Nazionale di Ricerca in High Performance Computing, Big Data and Quantum Computing, funded by European Union - NextGenerationEU.
2305.06222
Learning of viscosity functions in rarefied gas flows with physics-informed neural networks
The prediction non-equilibrium transport phenomena in disordered media is a difficult problem for conventional numerical methods. An example of a challenging problem is the prediction of gas flow fields through porous media in the rarefied regime, where resolving the six-dimensional Boltzmann equation or its numerical approximations is computationally too demanding. Physics-informed neural networks (PINNs) have been recently proposed as an alternative to conventional numerical methods, but remain very close to the Boltzmann equation in terms of mathematical formulation. Furthermore, there has been no systematic study of neural network designs on the performance of PINNs. In this work, PINNs are employed to predict the velocity field of a rarefied gas flow in a slit at increasing Knudsen numbers according to a generalized Stokes phenomenological model using an effective viscosity function. We found that activation functions with limited smoothness result in orders of magnitude larger errors than infinitely differentiable functions and that the AdamW is by far the best optimizer for this inverse problem. The design was found to be robust from Knudsen numbers ranging from 0.1 to 10. Our findings stand as a first step towards the use of PINNs to investigate the dynamics of non-equilibrium flows in complex geometries.
Jean-Michel Tucny, Mihir Durve, Andrea Montessori, Sauro Succi
2023-05-10T14:55:17Z
http://arxiv.org/abs/2305.06222v2
# Learning of viscosity functions in rarefied gas flows with physics-informed neural networks ###### Abstract The prediction non-equilibrium transport phenomena in disordered media is a difficult problem for conventional numerical methods. An example of a challenging problem is the prediction of gas flow fields through porous media in the rarefied regime, where resolving the six-dimensional Boltzmann equation or its numerical approximations is computationally too demanding. Physics-informed neural networks (PINNs) have been recently proposed as an alternative to conventional numerical methods, but remain very close to the Boltzmann equation in terms of mathematical formulation. Furthermore, there has been no systematic study of neural network designs on the performance of PINNs. In this work, PINNs are employed to predict the velocity field of a rarefied gas flow in a slit at increasing Knudsen numbers according to a generalized Stokes phenomenological model using an effective viscosity function. We found that activation functions with limited smoothness result in orders of magnitude larger errors than infinitely differentiable functions and that the AdamW is by far the best optimizer for this inverse problem. The design was found to be robust from Knudsen numbers ranging from 0.1 to 10. Our findings stand as a first step towards the use of PINNs to investigate the dynamics of non-equilibrium flows in complex geometries. R Rarefied gas flow, physics-informed neural networks, inverse problem, effective viscosity, phenomenological constitutive relationship, ## 1 Introduction Recently, deep learning methods have been proposed to recover the solution of non-linear partial differential equations (PDEs) [1, 2]. Deep learning methods show great promise for solving inverse problems on general transport problems in disordered media, where boundary conditions (BCs) or transport properties are unknown but constitutive relationships and experimental or numerical data about phenomena in the domain is available. Rather than attempting to discretize PDEs directly to solve systems of discretized equations, physics-informed neural networks (PINNs) use automatic differentiation to define all derivatives of physical variables on a meshless grid [3]. The PDE itself is used in the PINN as a residual to a loss function, which is an objective to be minimized. Additional information on constitutive equations or on the BCs of the problem can be added seamlessly, which requires much less testing and programming than with conventional CFD codes. When BCs can be written explicitly, mathematical problems are usually called forward problems, while PINNs learning relying mainly on data in the domain interior are usually called inverse problems. A notoriously difficult physical problem to solve with conventional CFD methods is the study of porous media with gas flows in the rarefied regime, where the mean free path of gas molecules \(\lambda\) is comparable to the characteristic length \(L_{C}\) of the flow. In such rarefied gas flows, there is no clear separation of scales between the gradient of physical variables and momentum transfer at the molecular level. The Boltzmann equation (BE), describing the propagation and collision of population from a statistical mechanics point of view, is well known to be valid for all Knudsen numbers (\(Kn=\lambda/L_{C}\)) [4, 5]. Mesoscopic discretizations of the BE such as high-order Lattice-Boltzmann methods (LBM) [6][7-13], discrete unified gas-kinetic schemes (DQKS) [14-16] and discrete velocity methods (DVM) [17] have been shown to recover the Boltzmann equation for sufficiently large velocity sets. However, as the BE is six-dimensional, this process leads quickly to prohibitive computational and memory requirements. Furthermore, it is generally difficult to know _a priori_ the required size of the velocity set as the Knudsen number increases. On one hand, microscopic representations such as the direct simulation Monte-Carlo (DSMC) method with its Lagrangian sampling of populations, is well suited for rarefied flows, but requires huge number of samples in the continuum limit to recover the gas flow in the continuum limit (\(Kn\to 0\)) [18, 19]. On the other hand, Eulerian macroscopic methods such as the Chapman-Enskog and Grad's moment methods study departure from equilibriums in the BE and attempt to recover closed forms for local macroscopic variables (density, velocity, temperature, etc.), and perform poorly as the Knudsen number increases [4, 20-23]. Inspired by such methods, PINNs have been used increasingly to solve rarefied gas flows. PINNs have been used to solve the Boltzmann-BGK equation in forward and inverse problems in the rarefied regime using a discrete-velocity method [24]. In the aforementioned paper, the researchers used a 3x3 velocity set for small Knudsen flows (D2Q9 lattice), while much larger velocity sets such as 28x28 velocity set is used for larger Knudsen flows both in forward and inverse problems. PINNs have also been developed using moment methods as a loss function in both forward and inverse problem formulations [25, 26]. However, the difficulty of knowing _a priori_ the size of the velocity set required for the approximation of the BE remains in such formulations. PINNs have also been trained as inverse problem formulations on DSMC results to approximate the velocity field and their derivatives [27]. However, this approach might be prone to overfitting caused by a too large number of variables, especially with geometries of dimension larger than one. An alternative to the use of BE approximations is a phenomenological description of rarefied gas flow phenomena with scaling laws for transport coefficients [28]. This approach shows great interest for finding solutions in industrial/engineering contexts, where we are not interested _per se_ on the collisional and propagational behavior of populations, but rather on local macroscopic variables or integral variables such as flow rates, heat flows and work, etc. Two phenomena specific to rarefied gas flows which must be described as the Knudsen increases: 1) the apparent slip at the solid-gas boundary, and 2) departure from the linear shear-stress relationship. When \(Kn>0.001\), at the solid-gas boundary, gas molecules incoming from a region where the gas has a non-zero value creates an apparent slip flow. When \(Kn>0.1\), the Knudsen layer, a region of a thickness with \(O\!\sim\!(\lambda)\), the Newtonian relationship between shear stress and shear strain is no longer valid as a result of insufficient gas-gas molecular collisions, takes a significant portion of the domain. Those physical phenomena are mathematically formulated in conventional CFD codes respectively as slip BCs on velocity and with an effective viscosity function in the Navier-Stokes solver. However, the coupling of those two phenomena may be difficult to obtain for disordered tridimensional geometries. To the authors' knowledge, PINNs were never used to recover the BCs and the effective viscosity for such an inverse problem. Moreover, the success of PINNs rely on the choice of activation functions, optimizers, neural structures, loss weights and other hyperparameters, for which research is very limited as stated in this recent review paper [29]. Such choices are generally written in research papers with little explanation and appear to be highly dependant both on the problem's physics and mathematical formulation. Studying PINN designs for this phenomenological approach is interesting for its applicability to other physical problems such as the Darcy flows [30], non-Newtonian flows for liquid polymers [31], and electrical conductivity in graphene [32]. In this paper, various implementations of a deep neural network informed by the generalized Stokes equation will be tested to recover the velocity field of a rarefied gas flow. The remainder of the article is divided as follows. In Section 2, the mathematical formulation of the generalized Stokes equation and data generation for the inverse problem will be presented. Various designs for the structure of the PINNs will be presented and tested respectively in Section 3 and 4. A robust, efficient and accurate PINN will be tested on different Knudsen numbers in Section 5. Concluding remarks will be related in Section 6. ## 2 The generalized Stokes model In this section, we present the generalized Stokes model that will be leveraged inside the PINN to recover the velocity field of a rarefied gas flow. In Subsection 2.1.1, the relationship between shear stress and shear strain, which breaks down in the Knudsen layer of a rarefied gas flow, will be defined. In subsection 2.1.2, a velocity field through a slit benchmark will be derived to train the PINN later on. ### Definition of the effective viscosity In this work, we consider a steady-state and incompressible gas flow moved by a uniform force field. In addition, we assume the flow to be laminar: i.e., the diffusive character of the flow is dominant. The Cauchy momentum equation can thus be written as follows [33]: \[0=-\frac{1}{\rho}\nabla\cdot\mathbf{\sigma}+\mathbf{f} \tag{1}\] where \(\rho\) is the density, \(\sigma\) is the viscous stress tensor and \(\mathbf{f}\) is a volumic force field (assumed in this work to be uniform). According to the kinetic theory of gases, the viscosity \(\mu\) of a gas unbounded by solid walls can be derived from the thermodynamical properties of the gas as follows [4]: \[\mu=\frac{\lambda P}{\sqrt{\frac{\pi\mathcal{R}T}{2}}} \tag{2}\] where \(P\) is the gas pressure, \(T\) is the temperature of the gas and \(\mathcal{R}\) is the specific perfect gas constant. In the Knudsen layer however, a region of a thickness of the order of the mean free path, insufficient collisions happen between gas molecules, which reduce the transfer of momentum. Therefore, viscosity, as the proportionality constant between the viscous stress tensor and the shear rate, can no longer be considered uniform. In the generalized Stokes equation, we assume the viscous stress tensor can be modeled with a space-dependant effective viscosity scalar field \(\mu_{e}(\mathbf{x})<\mu\) as follows [34]: \[\mathbf{\sigma}=-\mu_{e}(\mathbf{x})\nabla\mathbf{v} \tag{3}\] where \(\mathbf{v}\) is the velocity field. In the general case, the effective viscosity is unknown a priori and should depend on the mean free path and the solid-fluid boundary. It is convenient to define the viscosity function \(\Psi(\mathbf{x})\) as the ratio between the effective viscosity as follows: \[\Psi(\mathbf{x})=\frac{\mu_{e}(\mathbf{x})}{\mu} \tag{4}\] For a rarefied gas flow in the laminar regime with negligible heat transfer, the following property is verified by construction: \(0<\Psi(\mathbf{x})<1\). ### Current benchmark: rarefied gas flow through a slit While the aforementioned formulation is a quantitatively accurate phenomenological description for planar flows, deriving and computing the viscosity function _a priori_ is difficult and with questionable validity depending on the geometry, especially if the gas domain is non-convex [35; 36]. However, finding the solution to the Boltzmann equation is a problem of its own, and numerical methodologies require extensive verification and validation work. In this paper, we limit ourselves to the benchmark of a one-dimensional rarefied gas flow through a slit of size \(D\), as shown in Fig. 1. It is proposed to generate the data with the phenomenological model proposed by Guo et al., where the unidimensional flow field generated through this model had been compared with DSMC numerical solutions [37] linearized Boltzmann equation solutions [38] and validated with experimental values. The viscosity function is defined as [34]: \[\Psi(x)=\frac{1}{2}\Bigg{(}F\left(\frac{D}{2}-x\right)+F\left(\frac{D}{2}+x \right)\Bigg{)} \tag{5}\] where \(F(\beta)\) is defined as: \[F(\beta)=1+(\beta-1)\exp(-\beta)-\beta^{2}E_{i}(\beta) \tag{6}\] and where the exponential integral function \(E_{i}(\beta)\) is defined as: \[E_{i}(\beta)=\int_{1}^{\infty}\!\!t^{-1}\exp(-\beta t)\,\mathrm{d}t \tag{7}\] The following slip boundary condition from Guo is imposed [39]: \[v_{w}=A_{1}\lambda\Psi(x^{*})\frac{\partial v}{\partial n}-A_{2}\lambda^{2} \Psi(x^{*})\left(\frac{\partial}{\partial n}\Big{(}\Psi(x^{*})\frac{\partial v }{\partial n}\Big{)}\right) \tag{8}\] where \(x^{*}\) is the location of a BC and is either equal to \(-\frac{D}{2}\) or \(\frac{D}{2}\) for the slit shown in Fig. 1, \(n\) is the vector normal to the solid surface, \(A_{1}=0.8183\) and \(A_{2}=0.6531\) are phenomenological Figure 1: Schematic representation of a rarefied gas flow in a slit of size \(D\) driven by a volumic force \(f\). constants derived that can be derived from theoretical models or experimental values. Similar phenomenological models were validated for one-dimensional rarefied gas flows in the following articles [39-43]. The solution to Eq. (1) using the constitutive relationships in Eqs. (3), definitions of the viscosity function in Eqs. (4) and (5) and the BC (8) yields the following closed-form solution for the velocity: \[v=-\frac{f}{\mu}\int_{-D/2}^{D/2}\frac{x}{\Psi(x)}\mathrm{d}x \tag{9}\] The velocity data was generated through a trapezoid integration method with 4096 points. While the effective viscosity field (Eq. (5)) is generated at each point for the purpose of generating the velocity data, the effective viscosity field will only be used later for verification of the accuracy of the PINN, and not to train the PINN. ## 3 Physics-informed neural network designs While the rarefied gas flow through a slit may be described using the generalized Stokes model and a second-order velocity BC, such a model may become ineffective for more complicated geometries. This warrants the training of PINNs to recover the velocity field without; 1) knowledge of a relationship between the velocity and other moments at the gas-solid interface; 2) knowledge of the viscosity function throughout the domain. In this section, we expose PINN concepts applied to this inverse problem, as well as various choices of implementations that are generally not systematically tested for the prediction of physical phenomena. The most classical PINN architecture used in the literature for the approximation of PDEs for physical phenomena is the fully-connected PINN, which is shown in Fig. 2. The fully-connected PINN is made of \(h\) hidden layers of \(n\) neurons, takes as an input the position in the gas. Each layer of the fully-connected PINN expresses its output \(\mathbf{z}^{(k)}\) as follows: \[\begin{split}\mathbf{z}^{(0)}=\mathbf{x}\\ \mathbf{z}^{(k)}=\sigma\big{(}\mathbf{W}^{(k)}\mathbf{z}^{(k-1)}+ \mathbf{b}^{(k)}\big{)}\\ \mathbf{z}^{(h)}=\sigma\big{(}\mathbf{W}^{(h)}\mathbf{z}^{(h-1)} +\mathbf{b}^{(h)}\big{)}\end{split} \tag{10}\] where \(\sigma(t)\) is a non-linear activation function, and \(\mathbf{W}^{(k)}\) and \(\mathbf{b}^{(k)}\) are the weight matrix and the bias vector of the \(k\)th layer (\(k=(1,\cdots,h-1)\)), which are the trainable model parameters. For the fully-connected PINN, the last layer \(\mathbf{z}^{(h)}\) recovers both the velocity and the viscosity function. An example of a partially-connected PINN is shown in Fig. 3, where two sub-neural networks are created to compute the velocity and the viscosity function. Table 1 gives a summary of popular activation functions and their properties. Figure 3: Depiction of a partially-connected PINN architecture to solve the extended Stokes inverse problem. Figure 2: Depiction of a fully-connected PINN architecture to solve the extended Stokes inverse problem. For both PINN architectures, it is aimed to minimize the total loss function \(\mathcal{L}_{tot}\), which corresponds to a weighted sum of several loss terms. For this inverse problem, the distance \(\mathcal{L}_{data}\) between the velocity predicted by the model and the velocity values produced with Eq. (9) is of primordial importance. The distinguishing factor between a statistical regression using deep learning and a PINN, however, is the definition of the PDE loss function \(\mathcal{L}_{PDE}\), which is the residual corresponding to a normalized Eq. (1) and (3). The first-order and second-order partial derivatives related to velocities and viscosity in \(\mathcal{L}_{PDE}\) are computed using automatic differentiation, which relies on accumulation of numerical values computed directly at code execution at machine precision [48]. All those loss functions are computed using the \(L^{2}\) norm, which penalizes large local errors. In future configurations for rarefied gas flows, it might be possible to add a periodic boundary condition on all physical variables of interests, which gives additional constraints to the problem. The weights and biases that will minimize the total loss function are computed using an optimizer. The basic principle works as follows: weights and biases are updated using automatic differentiation in successions of forward- and/or back-propagations through stochastic gradient descent methods. Famous examples include Root Mean Square Propagation (RMSProp[49]) and Adaptative Moment Estimation (Adam) [50]. Quasi-Newton methods such as the limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS-B) algorithm [51] can also be used after an initial use of stochastic gradient descent. Derivatives of activation function at each node as a function of the PINN's weights and biases are again computed using automatic differentiation. The rate at which those weights and biases are modified by the optimizer is an hyperparameter called the learning rate. To prevent overfitting of the neural network to the values and improve its robustness, \(L^{2}\) regularization and weight decay contributions can also be supplemented to the PINN. \(L^{2}\) regularization adds the \(L^{2}\) norm of the weights to the total loss function: \[L^{*}_{tot}=\mathcal{L}_{tot}+w_{reg}\sqrt{\mathbf{W^{t}W}} \tag{11}\] where \(w_{reg}\) is the regularization hyperparameter. Alternatively, a weight decay term can be added to weights in the optimizer, the contribution of which is weighted with a weight decay hyperparameter \(w_{wd}\). While the \(L^{2}\) regularization and weight decay are similar in implementation \begin{table} \begin{tabular}{|l|c|c|c|} \hline Name & \(\sigma_{t}\) & Range & Smoothness \\ \hline ELU [44] & \(\begin{pmatrix}(\exp(t)-1),&t\leq 0\\ t,&t>0\end{pmatrix}\) & \((-1,\infty)\) & \(C^{1}\) \\ \hline ReLU [45] & \(\max(0,t)\) & \((0,\infty)\) & \(C^{0}\) \\ \hline SeLU [46] & \(\Omega\begin{pmatrix}\alpha(\exp(t)-1),&t\leq 0\\ t,&t>0\end{pmatrix}\) & \((-\Omega\alpha,\infty)\) & \(C^{0}\) \\ & with parameters \(\Omega\approx 1.0507\) and \(\alpha\approx 1.6733\) & & \\ \hline Sigmoid & \(\dfrac{1}{1+\exp{(-t)}}\) & (0,1) & \(C^{\infty}\) \\ \hline SiLU [47] & \(\dfrac{t}{1+\exp{(-t)}}\) & \((-0.278,\infty)\) & \(C^{\infty}\) \\ \hline Tanh & \(\tanh(t)=\dfrac{\exp(t)-\exp{(-t)}}{\exp(t)+\exp{(-t)}}\) & (\(-1\),1) & \(C^{\infty}\) \\ \hline \end{tabular} \end{table} Table 1: Description of activation function \(\sigma\) and mathematical properties for the RMSprop optimizer, researchers have suggested it is not the case for the Adam optimizer, and have proposed a new implementation called Adamw where the weight decay is properly set on the weights of the neurons [52]. As several hyperparameters are present in these PINNs, it will be easier to understand the meaning of the hyperparameters if all physical variables used to the train the PINN are normalized. In this study, the body force term \(\mathbf{f}\) and viscosity \(\mu\) were set equal to one. This choice is valid because of the laminarity assumptions of our problem (or by inspecting Eq. (9)). ## 4 Test of PINN designs In this section, the manifold of PINN designs for the approximation of the velocity and the viscosity field will be explored. As a full factorial design would be too fastidious to simulate and interpret, results are presented from the most critical to the least critical to the stability of the PINN solution, i.e.: 1) activation function and associated initializers, 2) optimizers and learning rates, 3) weights in the loss function, 4) PINN architectures, 5) size of the mini-batches. Preliminary trials have shown that the "base" PINN design shown in Table 2 is a good compromise of robustness and low computational requirements as a starting point for this parametric study, in the sense that varying one parameter from this base case allows it to converge and thus show more interesting results. However, this combination is not necessarily the one that gives the lowest prediction error. Note also that preliminary tests have not shown any significant difference between the Hammersley and other pseudorandom sequences. \begin{table} \begin{tabular}{|p{142.3pt}|p{142.3pt}|} \hline Activation function & Tanh \\ \hline Optimizer & AdamW \\ \hline Learning rate & 1E-5 \\ \hline Weight decay & 1E-3 \\ \hline Architecture & Fully-connected \\ \hline Number of layers & 10 \\ \hline Number of neurons per layer & 80 \\ \hline Ratio of PDE to velocity residue weights & 1E-3 \\ \hline Ratio of periodic BC to velocity residue weights & 1E-3 \\ \hline Size of mini-batches & 32 points \\ \hline Iterations per epoch & 100 \\ \hline Choice of points in the mini-batch & Hammersley sequence \\ \hline \end{tabular} Unless stated otherwise, the Knudsen number is always chosen to be \(Kn=1\), which is well into the transition regime and has interlapping Knudsen layers in the whole domain, but where gas-gas molecular collisions still give a significant gradient to the velocity and viscosity profile. All computations were performed on one CPU (Intel 19 64 GB Ram) and one GPU (Nvidia RTX3090, 24 GB of Ram, 10496 CUDA cores) using the DeepXDE [53] library with PyTorch v.1.13.1 [54] and Cuda v.11.7 [55]. \end{table} Table 2: “Base” PINN design for the parametric tests Choice of the activation function As the activation function determines the relationship between the inputs and the outputs of each neuron, its properties are expected to be of prime importance in the convergence and accuracy of the neural network. The \(L^{2}\) relative error of neural network predictions compared to the solution of Eq. (9) are presented in Table 3 for each activation function and its corresponding initialization as suggested by the literature, while velocity and viscosity functions are compared respectively with Eqs. (9) and (5) in Figs. 4-9. It can be readily seen that activation functions with limited smoothness and non-compact ranges such as ELU, ReLU and SELU create orders of magnitude larger errors than the others on velocity, while being the main data furnished to the network. It can be noted that most of the spurious behavior of the velocity field in Figs. 4-6 a) appears in the middle of the slit, where the gradient of both the velocity and the viscosity functions are equal to zero. As derivatives of weights and biases are computed backwards in the automatic differentiation procedure, the learning process uses the inverse of the derivative of the loss function that is ill-conditioned when an activation function with limited smoothness is used. The neural network is unable to incorporate even a minute fraction of the physics-informed part in the loss function, especially considering the low value of the weight on the PDE residue compared to the weight on the data residue used in those tests (\(\frac{w_{PDE}}{w_{data}}=0.001\)). In particular, according to the generalized Stokes model of a rarefied gas flow, the viscosity function should never be negative. Figs. 7-9, where results for infinitely differentiable functions are shown, show much better behavior. In Fig. 7, it appears that after 2000 epochs, PINNs using the Sigmoid function is finally able to converge to Eqs. (9) and (5): however, convergence is rather slow as evidenced by its behavior at 200 epochs. While PINN outputs for the infinitely smooth SiLU function (shown in Fig. 8) behave better for the velocity profile, the PINN struggles to learn the viscosity function even after 2000 epochs. The Tanh activation function achieves the lowest relative errors and exhibit better convergence behavior, as further evidenced in Fig. 10. For this reason, the Tanh activation function will be retained for the remainder of the article. One can notice that the PINN easily learns the viscosity function in the center of the profile, with the largest error being committed at the edges of the domain. The magnitude of the error still remains lower than 2% despite: 1) the viscosity only appearing in the PDE term and 2) the lack of constraints on the viscosity function. \begin{table} \begin{tabular}{|l|l|l|l|l|l|l|} \hline Activation function & Initialization & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & Runtime \\ & & error on \(\nu\) & error on \(\Psi\) & error on \(\nu\) & error on \(\Psi\) & (5) \\ & & after 200 & after 200 & after 2000 & after 2000 & \\ & & epochs (-) & epochs (-) & epochs (-) & epochs (-) & \\ \hline ELU & He normal & 2.32E-0 & 1.06E-0 & 2.33E-1 & 2.85E-0 & 1527 \\ \hline ReLU & He normal & 2.72E-2 & 5.71E-1 & 1.82E-2 & 7.32E-1 & 1125 \\ \hline SeLU & He normal & 2.86E-0 & 9.54E-1 & 1.36E-1 & 4.60E-0 & 1524 \\ \hline Sigmoid & Xavier normal & 9.04E-2 & 2.82E-0 & 4.43E-4 & 1.92E-2 & 1386 \\ \hline SiLU & He normal & 5.89E-4 & 1.24E-1 & 3.62E-4 & 3.17E-2 & 1634 \\ \hline Tanh & Xavier normal & 6.20E-4 & 5.04E-2 & 5.03E-5 & 3.16E-3 & 1361 \\ \hline \end{tabular} \end{table} Table 3: Performance of activation functions Figure 4: PINN results using the ELU activation function and the He normal initialization for a) the velocity \(v\); b) the viscosity function \(\Psi\) Figure 5: PINN results using the ReLU activation function and the He normal initialization for a) the velocity \(v\); b) the viscosity function \(\Psi\) Figure 6: PINN results using the SeLU activation function and the He normal initialization for a) the velocity \(v\); b) the viscosity function \(\Psi\) Figure 8: PINN results using the SiLU activation function and the He normal initialization for a) the velocity \(v\) and b) the viscosity function \(\Psi\) Figure 7: PINN results using the Sigmoid activation function and the Xavier normal initialization for a) the velocity \(v\) and b) the viscosity function \(\Psi\) Figure 9: PINN results using the Tanh activation function and the Xavier normal initialization for a) the velocity \(v\) and b) the viscosity function \(\Psi\) ### Choice of optimizers and learning rates The performance of PINNs trained with common choices of optimizers (Adam+L2 regularization, AdamW and RMSProp are presented respectively in Tables 3-5. The use of the Adam optimizer + L2 regularization and the AdamW optimizer with a weight decay of zero is equivalent to the Adam optimizer: results for the Adam optimizers were thus added to Tables 3 and 4 for this reason for comparison purposes. In Table 3, for the Adam optimizer with L2 regularization, the weight decay has a negative impact on the \(L^{2}\) relative error both for the velocity field and the viscosity function. This could be expected, as the use of an additional constraint on the weight values decreases the relative impact of the velocity error on the loss function. However, in Tables 4 and 5, using a small weight decay of 1E-5 tends to slightly improve learning with the AdamW optimizer and RMSProp. Clearly, the AdamW with a weight decay of 1E-3 offers the best performance, with an order of magnitude smaller \(L^{2}\) relative error with a slight 10% higher cost compared to the RMSProp optimizer. Figs. 11-13 show PINN outputs of the Adam optimizer with L2 regularization, the AdamW and the RMSProp optimizers respectively for combinations of a 1E-5 weight decay and a 1E-6 learning rate. For neural networks converging with a low relative error in the end, this typical behavior is shown in Figs. 12-13. Although the velocity profile is qualitatively good after only 200 epochs, the viscosity function seems to have a curvature of opposite sign to the analytical solution. In Eqs. (5) and (9) one can remark both the effective viscosity and the velocity profiles are concave: i.e., the first derivatives are decreasing functions of \(x\). However, further inspection of the PDE loss term of the PINN shows that first derivatives being increasing functions of \(x\) if \(\Psi\) increases or decreases accordingly, which corresponds to a saddle point of the loss function and is not easily avoided with Quasi-Newton optimization procedures such as the L-BFGS-B method. The use of the L-BFGS-B method has not led to significant improvement of any of the stochastic descent approaches (Adam+L2, AdamW and RMSProp). Figure 10: Evaluation of the a) Loss during training, and b) relative error after 2000 epochs for the PINN using the Tanh activation function and the Xavier normal initialization \begin{table} \begin{tabular}{|l|l|l|l|l|l|l|l|} \hline Weight & Learning & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & Runtime (s) \\ decay & rate & error on \(v\) & error on \(\Psi\) & error on \(v\) & error on \(\Psi\) & \\ & & after 200 & after 200 & after 2000 & after 2000 & after 2000 & \\ & & epochs (-) & epochs (-) & epochs (-) & epochs (-) & epochs (-) & \\ \hline 1E-1 & 1E-3 & 3.91E-3 & 6.58E-2 & 7.23E-3 & 4.40E-1 & 1347 \\ \hline 1E-1 & 1E-4 & 7.67E-4 & 1.97E-2 & 1.56E-4 & 1.08E-2 & 1343 \\ \hline 1E-1 & 1E-5 & 5.60E-4 & 3.94E-2 & 9.98E-5 & 8.10E-3 & 1339 \\ \hline 1E-1 & 1E-6 & 8.02E-3 & 2.38E-1 & 7.82E-5 & 4.90E-3 & 1356 \\ \hline 1E-3 & 1E-3 & 4.66E-3 & 2.13E-2 & 1.59E-3 & 7.27E-2 & 1344 \\ \hline 1E-3 & 1E-4 & 5.82E-4 & 2.15E-2 & 5.34E-4 & 2.07E-2 & 1341 \\ \hline 1E-3 & 1E-5 & 5.91E-4 & 4.50E-2 & 5.80E-5 & 4.36E-3 & 1340 \\ \hline 1E-3 & 1E-6 & 9.36E-3 & 2.80E-1 & 7.80E-5 & 4.48E-3 & 1345 \\ \hline 1E-5 & 1E-3 & 1.04E-3 & 2.89E-2 & 1.47E-4 & 1.65E-2 & 1344 \\ \hline 1E-5 & 1E-4 & 2.46E-4 & 1.04E-2 & 4.95E-4 & 8.49E-3 & 1341 \\ \hline 1E-5 & 1E-5 & 5.84E-4 & 4.26E-2 & 4.12E-5 & 2.44E-3 & 1350 \\ \hline 1E-5 & 1E-6 & 6.79E-3 & 2.24E-1 & 5.12E-5 & 3.32E-3 & 1350 \\ \hline 0 & 1E-3 & 1.75E-3 & 6.12E-2 & 4.11E-4 & 1.91E-2 & 1336 \\ \hline 0 & 1E-4 & 6.68E-4 & 2.07E-2 & 7.51E-4 & 2.43E-2 & 1342 \\ \hline 0 & 1E-5 & 1.04E-3 & 4.87E-2 & 1.01E-4 & 3.68E-3 & 1345 \\ \hline 0 & 1E-6 & 1.11E-2 & 2.26E-1 & 2.05E-4 & 7.36E-3 & 1348 \\ \hline \end{tabular} \end{table} Table 4: Performance of the AdamW optimizer \begin{table} \begin{tabular}{|l|l|l|l|l|l|l|} \hline Weight & Learning & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & Runtime (s) \\ decay & rate & error on \(v\) & error on \(\Psi\) & error on \(v\) & error on \(\Psi\) & \\ & & after 200 & after 200 & after 2000 & after 2000 & \\ & & epochs (-) & epochs (-) & epochs (-) & epochs (-) & \\ \hline 1E-1 & 1E-3 & 1.01E-1 & 2.60E+4 & 1.01E-1 & 6.64E+3 & 1346 \\ \hline 1E-1 & 1E-4 & 9.19E-2 & 2.05E+6 & 9.19E-2 & 1.56E+5 & 1348 \\ \hline 1E-1 & 1E-5 & 9.01E-2 & 4.35E+0 & 9.00E-2 & 2.19E+6 & 1359 \\ \hline 1E-1 & 1E-6 & 8.45E-2 & 2.48E+0 & 9.01E-2 & 6.42E+0 & 1358 \\ \hline 1E-3 & 1E-3 & 6.65E-3 & 8.83E-2 & 6.19E-3 & 9.15E-2 & 1349 \\ \hline 1E-3 & 1E-4 & 6.18E-3 & 8.99E-2 & 6.23E-3 & 1.00E-1 & 1356 \\ \hline 1E-3 & 1E-5 & 4.96E-3 & 1.02E-1 & 4.41E-3 & 1.30E-1 & 1352 \\ \hline 1E-3 & 1E-6 & 1.15E-2 & 3.50E-1 & 4.59E-3 & 5.78E-2 & 1352 \\ \hline 1E-5 & 1E-3 & 2.35E-3 & 3.40E-2 & 7.05E-4 & 2.27E-2 & 1349 \\ \hline 1E-5 & 1E-4 & 1.04E-3 & 3.27E-2 & 9.26E-4 & 2.70E-2 & 1361 \\ \hline 1E-5 & 1E-5 & 8.37E-4 & 4.10E-2 & 5.49E-4 & 2.15E-2 & 1352 \\ \hline 1E-5 & 1E-6 & 9.67E-3 & 2.28E-1 & 4.58E-4 & 2.15E-2 & 1358 \\ \hline 0 & 1E-3 & 1.75E-3 & 6.12E-2 & 4.11E-4 & 1.91E-2 & 1336 \\ \hline 0 & 1E-4 & 6.68E-4 & 2.07E-2 & 7.51E-4 & 2.43E-2 & 1342 \\ \hline 0 & 1E-5 & 1.04E-3 & 4.87E-2 & 1.01E-4 & 3.68E-3 & 1345 \\ \hline 0 & 1E-6 & 1.11E-2 & 2.26E-1 & 2.05E-4 & 7.36E-3 & 1348 \\ \hline \end{tabular} \end{table} Table 3: Performance of the Adam optimizer + L2 regularization \begin{table} \begin{tabular}{|l|l|l|l|l|l|l|l|} \hline Weight & Learning & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & Runtime (s) \\ decay & rate & error on \(v\) & error on \(\Psi\) & error on \(v\) & error on \(\Psi\) & \\ & & after 200 & after 200 & after 2000 & after 2000 & \\ & & epochs (-) & epochs (-) & epochs (-) & epochs (-) & \\ \hline 1E-1 & 1E-3 & 9.34E-2 & 2.05E+2 & 9.34E-2 & 2.06E+2 & 1200 \\ \hline 1E-1 & 1E-4 & 9.26E-2 & 1.98E+3 & 9.37E-2 & 1.99E+3 & 1197 \\ \hline 1E-1 & 1E-5 & 9.00E-2 & 3.76E+1 & 9.00E-2 & 6.40E+3 & 1200 \\ \hline 1E-1 & 1E-6 & 8.46E-2 & 2.98E+0 & 9.11E-2 & 4.09E+0 & 1204 \\ \hline 1E-3 & 1E-3 & 1.38E-2 & 1.51E+0 & 3.53E-3 & 3.98E-1 & 1203 \\ \hline 1E-3 & 1E-4 & 1.12E-2 & 1.57E-1 & 9.34E-3 & 1.09E-1 & 1210 \\ \hline 1E-3 & 1E-5 & 7.90E-3 & 1.27E-1 & 6.21E-3 & 9.12E-2 & 1204 \\ \hline 1E-3 & 1E-6 & 1.14E-2 & 3.01E-1 & 6.10E-3 & 7.03E-2 & 1204 \\ \hline 1E-5 & 1E-3 & 9.15E-2 & 2.18E+0 & 3.44E-3 & 3.65E-2 & 1215 \\ \hline 1E-5 & 1E-4 & 5.13E-3 & 9.37E-2 & 3.63E-3 & 4.38E-2 & 1215 \\ \hline 1E-5 & 1E-5 & 2.08E-3 & 5.92E-2 & 1.15E-3 & 2.58E-2 & 1214 \\ \hline 1E-5 & 1E-6 & 6.29E-3 & 2.38E-1 & 6.14E-4 & 3.28E-2 & 1209 \\ \hline 0 & 1E-3 & 1.83E-2 & 3.79E+0 & 1.95E-2 & 5.90E+0 & 1193 \\ \hline 0 & 1E-4 & 7.62E-3 & 1.04E-1 & 1.50E-3 & 4.99E-2 & 1200 \\ \hline 0 & 1E-5 & 3.16E-3 & 1.44E-1 & 2.34E-3 & 1.62E-2 & 1194 \\ \hline 0 & 1E-6 & 2.43E-3 & 3.34E-1 & 2.70E-4 & 1.33E-2 & 1192 \\ \hline \end{tabular} \end{table} Table 5: Performance of the RMSProp optimizer Figure 11: PINN results using the Adam optimizer + L2 regularization and a 1E-5 weight decay and a 1E-6 learning rate for a) the velocity \(v\) and b) the viscosity function \(\Psi\) ### Weights of the loss function The ratio of the PDE loss weight to the data loss weight \(\frac{w_{PDE}}{w_{data}}\) determines the importance of the "physics-informed" contribution compared to the data velocity contribution to the loss function. Table 6 shows the impact of \(\frac{w_{PDE}}{w_{data}}\) on the PINN performance when no boundary conditions are imposed at the edges of the domain. The larger the contribution of the PDE loss weight, the lower the \(L^{2}\) relative error. However, preliminary tests had shown that using a larger \(\frac{w_{PDE}}{w_{data}}\) makes the PINN diverge more easily when using a larger learning rate or an alternative optimizer to AdamW. Figure 12: PINN results using the AdamW optimizer and a 1E-5 weight decay and a 1E-6 learning rate for a) the velocity \(v\) and b) the viscosity function \(\Psi\) Figure 13: PINN results using the RMSProp optimizer and a 1E-5 weight decay and a 1E-6 learning rate for a) the velocity \(v\) and b) the viscosity function \(\Psi\) Table 6 - Influence of the \(\frac{W_{PDE}}{w_{data}}\) on the performance of a PINN without boundary condition \begin{tabular}{|l|l|l|l|l|l|l|} \hline Ratio of the PDE loss & Learning & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & Runtime \\ weight to the data & rate & error on \(v\) & error on \(\Psi\) & error on \(v\) & error on \(\Psi\) & (s) \\ loss weight \(\frac{W_{PDE}}{w_{data}}\) & & after 200 & after 200 & after 2000 & after 2000 & \\ & & epochs (-) & epochs (-) & epochs (-) & epochs (-) & epochs (-) & \\ \hline 1E-1 & 1E-3 & 5.42E-4 & 2.12E-2 & 3.50E-3 & 5.38E-2 & 1351 \\ \hline 1E-1 & 1E-4 & 1.47E-3 & 3.37E-2 & 3.25E-3 & 1.01E-2 & 1346 \\ \hline 1E-1 & 1E-5 & 1.05E-3 & 3.06E-2 & 5.16E-4 & 1.10E-2 & 1354 \\ \hline 1E-1 & 1E-6 & 6.00E-3 & 1.66E-1 & 1.06E-4 & 4.91E-3 & 1354 \\ \hline 1E-3 & 1E-3 & 1.36E-3 & 3.54E-2 & 7.14E-2 & 1.35E+0 & 1355 \\ \hline 1E-3 & 1E-4 & 1.29E-3 & 3.77E-2 & 5.27E-4 & 1.45E-2 & 1348 \\ \hline 1E-3 & 1E-5 & 2.40E-3 & 5.57E-2 & 1.28E-3 & 2.85E-2 & 1350 \\ \hline 1E-3 & 1E-6 & 9.38E-3 & 2.18E-1 & 1.21E-4 & 4.87E-3 & 1357 \\ \hline 1E-5 & 1E-3 & 2.64E-3 & 1.27E-1 & 9.02E-2 & 7.73E-1 & 1351 \\ \hline 1E-5 & 1E-4 & 1.31E-3 & 4.37E-2 & 2.21E-3 & 7.23E-2 & 1357 \\ \hline 1E-5 & 1E-5 & 8.24E-4 & 3.97E-2 & 3.65E-4 & 1.46E-2 & 1351 \\ \hline 1E-5 & 1E-6 & 1.16E-2 & 8.51E-2 & 4.33E-4 & 1.21E-2 & 1353 \\ \hline \end{tabular} It is difficult to have a general closed-form equation for a velocity boundary condition in rarefied gas flows. However, in the future, some structures might have a periodical geometry and this knowledge can be incorporate in the training of a PINN. As the solution in Eq. (9) is periodical in nature, the behavior of the PINN with a periodic BC can thus be tested. Fixing \(w_{BC_{\Psi}}=w_{BC_{\Psi}}=w_{PDE}\), PINNs were trained using this periodical boundary condition, for which performance results are shown in Table 7. For the slit benchmark, the imposition of periodic BCs does not appear to have much influence on \(L^{2}\) relative error. However, this conclusion may have to be revisited for higher-dimensional problems in the future. Table 7 - Influence of the \(\frac{W_{PDE}}{w_{data}}\) on the performance of a PINN with \(w_{BC_{\Psi}}=w_{BC_{\Psi}}=w_{PDE}\) \begin{tabular}{|l|l|l|l|l|l|l|} \hline Ratio of the PDE & Learning & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & Runtime \\ loss weight to & rate & error on \(v\) & error on \(\Psi\) & error on \(v\) & error on \(\Psi\) & (s) \\ the data loss & & after 200 & after 200 & after 2000 & after 2000 & after 2000 \\ weight \(\frac{W_{PDE}}{w_{data}}\) & & & epochs (-) & epochs (-) & epochs (-) & epochs (-) & \\ \hline 1E-1 & 1E-3 & 1.55E-3 & 4.74E-2 & 6.01E-3 & 2.47E-2 & 1355 \\ \hline 1E-1 & 1E-4 & 6.74E-4 & 2.95E-2 & 1.92E-4 & 8.03E-3 & 1350 \\ \hline 1E-1 & 1E-5 & 9.34E-4 & 3.30E-2 & 3.09E-4 & 9.17E-3 & 1353 \\ \hline 1E-1 & 1E-6 & 7.05E-3 & 2.07E-1 & 1.20E-4 & 6.11E-3 & 1354 \\ \hline 1E-3 & 1E-3 & 3.48E-3 & 4.06E-2 & 3.16E-3 & 4.42E-2 & 1347 \\ \hline 1E-3 & 1E-4 & 8.62E-4 & 4.47E-2 & 2.22E-4 & 9.72E-3 & 1355 \\ \hline 1E-3 & 1E-5 & 9.62E-4 & 5.27E-2 & 1.78E-4 & 8.00E-3 & 1345 \\ \hline 1E-3 & 1E-6 & 8.80E-3 & 1.98E-1 & 2.68E-4 & 8.78E-3 & 1350 \\ \hline 1E-5 & 1E-3 & 5.78E-3 & 4.33E-1 & 9.01E-2 & 2.12E+1 & 1347 \\ \hline 1E-5 & 1E-4 & 5.34E-4 & 9.13E-2 & 2.63E-4 & 2.77E-2 & 1347 \\ \hline 1E-5 & 1E-5 & 1.01E-3 & 8.29E-2 & 1.86E-4 & 2.06E-2 & 1353 \\ \hline 1E-5 & 1E-6 & 6.85E-3 & 2.07E+0 & 2.05E-4 & 2.67E-2 & 1345 \\ \hline \end{tabular} It is difficult to have a general closed-form equation for a velocity boundary condition in rarefied gas flows. However, in the future, some structures might have a periodical geometry and this knowledge can be incorporate in the training of a PINN. As the solution in Eq. (9) is periodical in nature, the behavior of the PINN with a periodic BC can thus be tested. Fixing \(w_{BC_{\Psi}}=w_{BC_{\Psi}}=w_{PDE}\), PINNs were trained using this periodical boundary condition, for which performance results are shown in Table 7. For the slit benchmark, the imposition of periodic BCs does not appear to have much influence on \(L^{2}\) relative error. However, this conclusion may have to be revisited for higher-dimensional problems in the future. Table 8 - Influence of the \(\frac{W_{PDE}}{w_{data}}\) on the performance of a PINN with \(w_{BC_{\Psi}}=w_{BC_{\Psi}}=w_{PDE}\) \begin{tabular}{|l|l|l|l|l|l|l|l|} \hline Ratio of the PDE & Learning & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & \(L^{2}\) relative & Runtime \\ loss weight to & rate & error on \(v\) & error on \(\Psi\) & error on \(v\) & error on \(\Psi\) & (s) \\ the data loss & & after 200 & after 200 & after 2000 & after 2000 & after 2000 \\ weight \(\frac{W_{PDE}}{w_{data}}\) & & & epochs (-) & epochs (-) & epochs (-) & epochs (-) & \\ \hline 1E-1 & 1E-3 & 1.55E-3 & 4.74E-2 & 6.01E-3 & 2.47E-2 & 1355 \\ \hline 1E-1 & 1E-4 & 6.74E-4 & 2.95E-2 & 1.92E-4 & 8.03E-3 & 1350 \\ \hline 1E-1 & 1E-5 & 9.34E-4 & 3.30E-2 & 3.09E-4 & 9.17E-3 & 1353 \\ \hline 1E-1 & 1E-6 & 7.05E-3 & 2.07E-1 & 1.20E-4 & 6.11E-3 & 1354 \\ \hline 1E-3 & 1E-3 & 3.48E-3 & 4.06E-2 & 3.16E-3 & 4.42E-2 & 1347 \\ \hline 1E-3 & 1E-4 & 8.62E-4 & 4.47E-2 & 2.22E-4 & 9.72E-3 & 1355 \\ \hline 1E-3 & 1E-5 & 9.62E-4 & 5.27E-2 & 1.78E-4 & 8.00E-3 & 1345 \\ \hline 1E-3 & 1E-6 & 8.80E-3 & 1.98E-1 & 2.68E-4 & 8.78E-3 & 1350 \\ \hline 1E-5 & 1E-3 & 5.78E-3 & 4.33E-1 & 9.01E-2 & 2.12E+1 & 1347 \\ \hline 1E-5 & 1E-4 & 5.34E-4 & 9.13E-2 & 2.63E-4 & 2.77E-2 & 1347 \\ \hline 1E-5 & 1E-5 & 1.01E-3 & 8.29E-2 & 1.86E-4 & 2.06E-2 PINN architectures In this subsection, the impact of the PINN architecture (a fully connected vs. a partially connected neural network as shown respectively in Figs. 2-3) is evaluated for various total numbers of neurons and numbers of neurons per layer. Tables 8 and 9 show respectively the performance of a fully connected PINN and of a partially connected PINN. For the fully connected PINN, the total number of neurons does not seem to have a substantial impact on the \(L^{2}\) relative error and only contributes to larger runtimes. However, for a given total number of neurons, increasing the number of layers from 2 to 10 (i.e. making the neural network "deeper") substantially lowers the relative error found after 200 epochs both on the velocity and the viscosity function. However, the improvement of the PINNs with the number of layers is less systematic when the PINNs are left to converge for 2000 epochs. Similar conclusions are found for the partially connected PINN. Comparing the two architectures, it seems the partially connected PINN gives slightly smaller \(L^{2}\) relative errors compared to the fully connected PINN. This is expected, noting however that preliminary tests have shown that partially connected PINNs diverge more easily if using a larger learning rate or an alternative optimizer to AdamW. It also seems the runtime is about 50% longer on the partially connected PINN than on the fully connected PINN. This result is somewhat surprising considering the lower number of gradients to be evaluated in the partially connected PINN. One explanation could be that designs with relatively low number of neurons do not fully take advantage of the acceleration potential of the GPU. ### Size of the mini-batch The use of mini-batches for the PINN training allows the use of small subsets of the velocity data for the evaluation of the loss function. This feature would be especially useful for the training of PINNs on multidimensional flow problems. Table 10 shows the impact of the mini-batch size on PINN performance. As expected, the larger the mini-batch size, the larger the runtime and the smaller the \(L^{2}\) relative error for all learning rates, especially for large learning rates. However, it seems that the \(L^{2}\) relative errors tend to plateau for 64 data points or more. \begin{table} \begin{tabular}{|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|} \hline Total number of neurons & Number of neurons per layer (\(h\)) & \(L^{2}\) relative error on \(v\) epochs (-) & \(L^{2}\) relative error on \(v\) epochs (-) & \(L^{2}\) relative error on \(v\) epochs (-) & Runtime (s) \\ \hline 200 & 2 & 1.01E-2 & 2.73E-1 & 9.96E-5 & 6.27E-3 & 588 \\ 200 & 4 & 7.90E-3 & 2.50E-1 & 7.97E-5 & 3.54E-3 & 890 \\ \hline 200 & 5 & 3.45E-3 & 2.33E-1 & 1.07E-4 & 7.14E-3 & 1076 \\ \hline 200 & 10 & 2.54E-3 & 1.19E-1 & 2.08E-4 & 8.18E-3 & 1960 \\ 400 & 2 & 9.24E-3 & 2.78E-1 & 1.33E-4 & 8.36E-3 & 593 \\ 400 & 4 & 1.44E-3 & 6.37E-2 & 8.88E-5 & 5.54E-3 & 1008 \\ 400 & 5 & 1.32E-3 & 6.19E-2 & 1.52E-4 & 7.26E-3 & 1135 \\ 400 & 10 & 1.79E-3 & 7.40E-2 & 4.18E-4 & 1.31E-2 & 2067 \\ 800 & 2 & 9.60E-3 & 2.86E-1 & 1.87E-4 & 1.51E-2 & 660 \\ 800 & 4 & 1.05E-3 & 4.21E-2 & 7.97E-5 & 3.36E-3 & 1145 \\ 800 & 5 & 1.12E-3 & 4.61E-2 & 1.30E-4 & 9.06E-3 & 1375 \\ 800 & 10 & 2.17E-3 & 6.25E-2 & 5.53E-4 & 1.55E-2 & 2170 \\ 1600 & 2 & 8.85E-3 & 2.50E-1 & 2.88E-4 & 1.31E-2 & 1053 \\ 1600 & 4 & 7.12E-3 & 2.01E-1 & 1.52E-4 & 7.25E-3 & 1482 \\ 1600 & 5 & 2.00E-3 & 7.35E-2 & 6.85E-4 & 2.00E-2 & 1628 \\ 1600 & 10 & 8.21E-4 & 3.84E-2 & 1.98E-4 & 7.90E-3 & 2535 \\ \hline \end{tabular} \end{table} Table 9: Performance of the partially-connected PINN with two subnetworks for the velocity and the viscosity function ## 5 Influence of the Knudsen number on PINN performance In this section, a PINN design based on the conclusions of Section 4 (summed up in Table 11) is tested for a gas flow through a slit on a wide range of Knudsen numbers. Figs. 14-17 show PINN results the velocity and viscosity function profiles while Table 12 shows the \(L^{2}\) relative error for \(Kn=0.1,0.5,2\) and \(10\) respectively. Despite widely different scales for the velocity and shapes for the effective viscosity profiles, the PINN was able to converge to results from the \begin{table} \begin{tabular}{|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|p{56.9pt}|} \hline Number of data points in the mini-batch & Learning rate & \(L^{2}\) relative error on \(\nu\) after 200 epochs (-) & \(L^{2}\) relative error on \(\nu\) epochs (-) & \(L^{2}\) relative error on \(\nu\) epochs (-) & \(L^{2}\) relative error on \(\nu\) epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) relative error on \(\nu\) epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) relative error on \(\nu\) epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) relative error on \(\nu\) epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) relative error on \(\nu\) error & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) relative error on \(\nu\) error & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & Runtime (s) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\nu\) error on \(\nu\) after 200 epochs (-) & \(L^{2}\) error on \(\ validated phenomenological model with a very low relative error after 2000 epochs. This shows the potential of PINNs to converge for rarefied gas flows using only the velocity field as training data and representation of the shear stress-shear strain relationship using an effective viscosity as a scalar field. Figure 16: PINN results for the slit benchmark with a \(Kn=2\) with the profiles for: a) the velocity \(v\) and b) the viscosity function \(\Psi\) Figure 17: PINN results for the slit benchmark with a \(Kn=10\) with the profiles for: a) the velocity \(v\) and b) the viscosity function \(\Psi\) Figure 15: PINN results for the slit benchmark with a \(Kn=0.5\) with the profiles for: a) the velocity \(v\) and b) the viscosity function \(\Psi\) Conclusion Characterization of non-equilibrium physical phenomena using a constitutive relationship is a well-known approach to model complex systems. In this paper, PINNs have been proposed to learn the effective viscosity of a rarefied gas flow through a slit. The only information that was given to the PINN in the loss function was the velocity data obtained from a validated phenomenological model and the local linearity of the effective viscosity function. More importantly, no explicit information was given on the velocity of the boundary condition or on the shape of the effective viscosity function, which makes it a challenging inverse problem for a PINN to be trained on. As the manifold of PINN designs was not well documented in the literature, a large parametric study was made to find a PINN design that is both robust and accurate. It was found that a combination of the Tanh activation function and the AdamW optimizer is key to the convergence of the PINN for this problem. A relatively low 1E-3 ratio between the PDE loss weight and the velocity data loss weight should be used for robustness and accuracy. Periodic boundary conditions have not significantly improved the accuracy of the PINN. Counter-intuitively, a partially-connected PINN design with two sub-networks for the velocity and viscosity function slightly improved the result, while slightly increasing its runtime on the tested benchmark. The use of a mini-batch containing as low as 32 data points does not significantly impact the accuracy of the PINN while significantly improving the runtime. The accuracy of the PINNs was demonstrated on a wide range of Knudsen numbers \(0.1<Kn<10\) exhibiting quite different shapes for the velocity and the effective viscosity functions. The findings of this paper have potential to be applicable to any characterization of physical phenomena through a PINN using a constitutive relationship. However, all the PINN training was limited on a relatively simple one-dimensional slit geometry. Future work will include the test of our PINN on physical phenomena with higher-dimensional geometries. ## Acknowledgements J.-M. T. thanks the FRQNT "Fonds de recherche du Quebec - Nature et technologies (FRQNT)" for financial support (Research Scholarship No. 314328). The authors acknowledge funding from the European Research Council Grant Agreement No. 739964 (COPMAT) and ERC-PoC2 grant No. 101081171 (DropTrack).
2310.10806
Convolutional Neural Network Model for Diabetic Retinopathy Feature Extraction and Classification
The application of Artificial Intelligence in the medical market brings up increasing concerns but aids in more timely diagnosis of silent progressing diseases like Diabetic Retinopathy. In order to diagnose Diabetic Retinopathy (DR), ophthalmologists use color fundus images, or pictures of the back of the retina, to identify small distinct features through a difficult and time-consuming process. Our work creates a novel CNN model and identifies the severity of DR through fundus image input. We classified 4 known DR features, including micro-aneurysms, cotton wools, exudates, and hemorrhages, through convolutional layers and were able to provide an accurate diagnostic without additional user input. The proposed model is more interpretable and robust to overfitting. We present initial results with a sensitivity of 97% and an accuracy of 71%. Our contribution is an interpretable model with similar accuracy to more complex models. With that, our model advances the field of DR detection and proves to be a key step towards AI-focused medical diagnosis.
Sharan Subramanian, Leilani H. Gilpin
2023-10-16T20:09:49Z
http://arxiv.org/abs/2310.10806v1
# Convolutional Neural Network Model for Diabetic Retinopathy Feature Extraction and Classification ###### Abstract The application of Artificial Intelligence in the medical market brings up increasing concerns but aids in more timely diagnosis of silent progressing diseases like Diabetic Retinopathy. In order to diagnose Diabetic Retinopathy (DR), ophthalmologists use color fundus images, or pictures of the back of the retina, to identify small distinct features through a difficult and time-consuming process. Our work creates a novel CNN model and identifies the severity of DR through fundus image input. We classified 4 known DR features, including micro-aneurysms, cotton woods, exudates, and hemorrhages, through convolutional layers and were able to provide an accurate diagnostic without additional user input. The proposed model is more interpretable and robust to overfitting. We present initial results with a sensitivity of 97% and an accuracy of 71%. Our contribution is an interpretable model with similar accuracy to more complex models. With that, our model advances the field of DR detection and proves to be a key step towards AI-focused medical diagnosis. ## 1 Introduction Medical diagnosis serves as the foundational step in patient care, determining the pathway for treatment and intervention. According to Dr. Edmund Arthur of the University of Alabama at Birmingham School of Optometry, the accuracy and timeliness of diagnoses are essential, as they directly influence the patient's prognosis and quality of life. A delay in identifying a condition can cause health issues, increase costs, and lower chances of full recovery. Recognizing a disease in its nascent stages often provides a broader array of treatment options and increases the likelihood of a favorable outcome. Diabetic Retinopathy (DR) exemplifies conditions where early detection can make a profound difference. DR, a complication resulting from diabetes, threatens the retina's blood vessels, jeopardizing the crucial light-sensitive layer at the back of the eye. Despite the potential to prevent up to 98% of vision loss with timely intervention, its silent progression often eludes timely detection, resulting in irreversible vision impairments. Artificial Intelligence (AI) has emerged as a solution for more effective diagnostic tools. Within AI, there is a subset of complex models called Convolutional Neural Networks (CNNs). However, CNNs applications for DR therapy have been of high complexity, requiring a high amount of computational resources. The most widely used approach for DR diagnosis consists of a dilated eye exam administered by an ophthalmologist or optometri. However, deep learning models perform with the same accuracy as medical professionals at processing and analyzing fundus images1, which depict the retina in detail. CNNs may also be able to diagnose other conditions, including cataracts, glaucoma, and even illnesses outside the retina. In Figure 1, there are four main features from a fundus image showing positive signs of DR. By processing these images, CNNs can identify early indicators of DR, illuminating proactive medical interventions aided by AI. In this paper, we present the different models currently available for DR detection and their limitations and challenges. We review the technical methods used, including an in-depth explanation of the CNN architecture, our new methodology and model, and an open-source GitHub repository for public access2. The training process and post-training techniques used to improve accuracy are thoroughly examined in the Explanation of CNN Layers and Methods sections, respectively. In addition to the methodology, we compare pre-trained models with the proposed ADL-CNN model and examine the benefits and disadvantages of each. Furthermore, we explore the potential implications of CNN advancements in healthcare, suggest areas for further research, and discuss the impact these innovations can have on disease detection and management. ## 2 Literature Review We provide a brief history of DR detection and how its diagnosis evolved. In addition to going over the various pre-existing studies on CNN models for DR detection, we also highlight each model's and method's limitations. Then, we will highlight what our model brings that is different from other studies and the advantages our model entails. ### Historical overview of DR detection In the early stages of DR diagnosis, its approach was based on a patient's symptomatic presentation and rudimentary examination techniques [1]. Eduard Jaeger and Albert von Graefe, in the 1850s described diabetic macular changes: a historical review suggests the evolution of our understanding [1]. It took more than a century for a consensus to emerge regarding the link between cystoid macular edema, which is caused by the accumulation of fluids in the macula, and diabetes mellitus (DM), where the body's immune system attacks and destroys insulin-producing cells in the pancreas. Recognizing the connection between cystoid macular edema and diabetes mellitus today influences diagnostic methods for patients with visual symptoms. The first line of diagnosis typically involved direct ophthalmoscopy, a method discussed in the historical evolution of DR diagnosis [2]. Digital fundus photography reshaped DR screening in the late 20th and early 21st century. Comparisons between singly, two-field, and three-field 45-degree Color Fundus Photographs (CFP) showed varying sensitivities and specificities. These advancements have modernized DR diagnosis, with varying sensitivities and specificities observed across different Color Fundus Photograph methods. With more advances in integrated AI and DR screening, the FDA approved an autonomous AI device that used 45-degree digital CFP for DR detection called the EyeArt AI system. On a side note, confocal scanning ophthalmoscopy emerged as a technique that provided ultra-widefield imaging. With these advancements, other challenges lie ahead on this path of innovation and integration. The intricacies of integrating various technologies seamlessly, ensuring universal accessibility to these advanced diagnostic tools, and refining AI algorithms for increased accuracy are among the ongoing challenges. While previous models may have offered solutions to specific challenges, a collaborative effort across medical, technological, and regulatory domains is essential for realizing the full potential of these novel diagnostic approaches. ### Specific Studies on DR Detection using CNNs In a study by Yasashvini R. et al., researchers attempted to classify DR using both CNN and hybrid deep CNNs [3]. Their methodology combined the strengths of CNN architectures with a hybrid deep CNN via a mixture of different Figure 1: Different features of a CFP show the presence of DR. This Fundus Image was pulled from the Messidor-2 dataset and had a classified severity of 6 (PDR). These are the 4 features that were extracted and processed by our machine-learning model. classifiers. They hypothesized that by combining the power of both these mixed classifiers, the accuracy of DR would increase, better accounting for the variety of features and abnormalities present in DR-affected CFPs. Their results were successful in achieving accuracy rates close to 100%. Following the onset of high precision in DR-prediction models, Pratt et al. introduced the task of predicting severity in DR diagnosis [4]. Their multi-dimensional data supports severity prediction in CFPs, from retinal features such as micro-aneurysms, exudates, and hemorrhages. Pratt and his team developed a CNN architecture that underwent data augmentation to achieve this dual objective. In Figure 2, we can see the architecture that Pratt et al. used. Their CNN model classified the fundus images between the seven different severities with a sensitivity of 95% and an accuracy of 75% on the validation images. In our work, we augment their architecture's weights and layers. Albahli & Yar's research emphasized the customizability of CNNs in the medical domain [5]. Albahli & Yar designed three deep-learning models to detect the severity of diabetic retinopathy from retina images and determine its potential progression to macular edema. Their main challenge was the limited dataset they used: the Indian Diabetic Retinopathy Image Dataset (IDRiD). To counteract this, they designed features such as Brightness, Color, and Contrast enhancement, Color Jitters, and Contrast Limited Adaptive Histogram Equalization to generate a broader range of images. Their study used pre-trained models like ResNet50, VGG16, and VGG19 and customized them to DR detection. Their results, after validation, showcased the potential of custom CNNs, with each model yielding reasonable outputs. On the other hand, the study by Shu-I Pao et al. used entropy images to increase DR detection performance [6]. In this context, the entropy image is an abstract representation computed using the green component of the CFP. By pre-processing these entropy images using unsharp masking, the researchers were able to enhance the clarity and definition of the features. The outcome was a bi-channel CNN, which effectively utilized the features from the gray level and the green component's entropy images. This approach, while complex, provided a comprehensive manner for improving the detection performance of severe DR cases. In summary, these studies show the immense potential and versatility of CNNs in DR detection. Whether it is the combined powers of CNNs and hybrid networks, the emphasis on severity classification, the adaptability of custom models, or the complex manipulation of entropy images, the domain of DR detection is witnessing fast progress and growth. ### Limitations of Current Models One explicit limitation emerges from the study by Yasashvini et al. While integrating standard CNNs with hybrid deep convolutional networks might enhance precision, it inadvertently adds to the model's complexity. Such sophisticated models often require vast computational resources, both in terms of training and inference. Furthermore, the more complex a model is, the higher the likelihood of overfitting, especially when the available dataset is not large enough. Our proposed model is less complex and has repeatedly been tested on overfitting curves. Overfit models might perform exceedingly well on training data but falter when faced with unseen data, making them unreliable for real-world applications. Testing the model with multiple data sets to ensure uniform reliability in the real world is important. In the research led by Pratt et al., the results were primarily based on one specific dataset: the Kaggle dataset. The variability and uniqueness of retinal images suggest that a model trained on one dataset might not generalize well to images from different sources, patients of varied demographics, or images captured using different equipment. This bias-related limitation ties into the data scarcity in DR and fundus imaging. Albahli's research, which introduced custom CNN models, highlighted another significant limitation related to data scarcity. The requirement to employ image generation techniques like BCC enhancing, CJ, and CLAHE to expand their dataset indicates the prevalent challenge of limited datasets in the field. Having a limited dataset not only hampers the depth of training but also raises concerns about the model's ability to generalize to a broader range of images. In our model, we have trained and tested it with a more comprehensive dataset and have seen repeatable and reliable results Fig. 2: CNN architecture for a DR detection model. This model finds the severity of DR through 7 different classifications of DR (No DR, Mild DR, Moderate DR, Severe DR, Very Severe DR, PDR, and Advanced PDR). with additional data sets. Moreover, artificially augmenting data can sometimes introduce new artifacts or fail to replicate the subtle nuances of natural images, potentially leading to models that might misinterpret or overlook certain features. Another question arises by introducing many data augmentation techniques: whether pre-processing techniques mask significant data features. Shu-I Pao and his team's research brings forth the intricacies of preprocessing. While the emphasis on entropy images derived from the green component of fundus photographs and preprocessing techniques like unsharp masking is innovative, it also adds layers of processing that might not be feasible in real-world, time-sensitive scenarios. Such intricate preprocessing might also introduce biases or inadvertently filter out certain relevant features, limiting the model's diagnostic capabilities. Our model sticks to basic preprocessing to resize the image and extract key features without modifying or filtering the actual image itself. Lastly, a collective limitation observed from all these studies is the gap between theoretical performance and real-world implementation. While these models showcase impressive metrics in controlled environments, challenges such as computational constraints, integration with existing healthcare systems, interpretability of results, and ensuring consistent performance across diverse patient populations remain. Addressing these practical limitations is paramount for the successful and widespread adoption of CNNs in DR diagnostics. ### AI Trust in Healthcare Environment The area of healthcare, particularly in recent years, has observed a large fusion of artificial intelligence (AI) applications, covering a broad spectrum ranging from diagnostics and clinical decision-making to digital public health. AI's potential to enhance clinical outcomes and efficiency is acknowledged, but the acceptance of this technology remains contingent on multiple factors. During the COVID-19 pandemic, Chalutz Ben-Gal's study investigated the acceptance of AI in primary care [7]. It was found that while many patients showcase a resistance towards AI, several factors can potentially tilt the balance in favor of AI. Explicit mentions of AI's superior accuracy, positive nudges from primary care physicians, and assurances of personalized patient listening experiences could enhance AI acceptance. Notably, Robertson et al. found that specific demographics, including Black respondents and older individuals, were less inclined to choose AI, highlighting the consideration of demographic-specific concerns in AI adoption [8]. Diving deeper into the diagnostic field, the potential of AI to augment diagnostic precision is immense. However, as noted by Robertson et al., patients' trust in AI may water based on disease severity and their perceived personalization of the AI system. Lastly, considering the viewpoint of healthcare professionals, Lambert et al. presented an integrative review highlighting the barriers to AI acceptance in the hospital setting [9]. The fear of losing professional autonomy in integrating AI into existing clinical workflows was a recurring concern. Conversely, training geared towards AI utilization emerged as a positive catalyst and gained acceptance among countless professionals. The study further emphasized the significance of involving end-users during the early stages of AI development, suggesting a collaborative approach to ensure that the technology meets real-world needs and challenges. In conclusion, while the potential benefits of AI in healthcare are vast, its acceptance remains an issue, necessitating a comprehensive understanding of both patients' and practitioners' perspectives coupled with tailored approaches to address their specific concerns. ## 3 Understanding Convolutional Neural Networks Convolutional Neural Networks (CNNs) are pivotal in machine learning and artificial intelligence, especially for image processing and classification tasks. Inspired by biological neural networks, CNNs emulate human perception by recognizing patterns from image pixels, enabling classification, identification, and visual data reconstruction [10]. In the realm of healthcare, particularly radiology, they exhibit considerable potential in enhancing conventional diagnostic methodologies, resulting in improved speed, reliability, and occasionally superior accuracy [11]. Fundamentally, neural networks comprise interconnected nodes or "neurons" that execute elementary mathematical operations. These networks are constructed to model intricate data relationships. As depicted in Figure 3, CNNs encompass input layers for data reception, hidden layers for data processing, and output layers for prediction/decision-making. Unlike conventional neural networks employing full interconnections between layers, CNNs employ sparse connections to focus on local features, rendering them highly efficient in capturing spatial hierarchies. Consequently, CNNs are exceptionally well-suited for tasks such as image recognition, where the extraction of local features such as edges, corners, and textures offers valuable information. CNNs belong to a category of neural networks known as Deep Learning models [12]. As the name suggests, these models are characterized by their depth or the number of layers data must pass hierarchically. Deep Learning, a subfield of machine learning, offers significant advantages over traditional machine learning methods. The depth of the network allows for more complex features to be learned, thereby increasing the model's ability to understand intricate patterns in the data, especially in medical imaging tasks [13]. ### Breaking Down the Architecture: Layers, Filters, Feature Extraction, etc. The convolutional layer is the core aspect of a CNN. This layer performs the convolution operation on the input, passing the result to the next layer. These operations focus on local regions of the input, preserving the relationship between pixels by learning image features [14]. For instance, in DR detection, this localized focus enables CNNs to discern pixel-level details, capturing critical retinal features and enhancing the model's feature-learning capability. After convolution, the layers often employ an activation function, the most common being the Rectified Linear Unit (ReLU). ReLU, in the kernels section of Figure 3, introduces non-linearity into the system, which allows the model to learn from the error and make adjustments, improving its performance during the training process. Following the convolutional and activation layers, CNNs usually contain pooling layers to reduce dimensionality. The pooling operation condenses the feature map obtained from the previous layer, usually by taking the maximum (as in Equation 1) or average value (as in Equation 2) from a group of values in the feature map3. This pooling process also results in reduced size and computational complexity of the resultant feature map. Footnote 3: Nanos, G., & Nanos, G. (2023). Neural Networks: Pooling layers, Baeldung on Computer Science. Baeldung on Computer Science. [https://www.baeldung.com/cs/neural-networks-pooling-layers](https://www.baeldung.com/cs/neural-networks-pooling-layers) \[MaxPooling(X)_{i,j,k}=\max_{m,n}X_{i\cdot s_{x}+m,j\cdot y+n,k} \tag{1}\] \[AvgPooling(X)_{i,j,k}=\frac{1}{f_{x}\cdot f_{y}}\sum_{m,n}X_{i\cdot s_{x}+m,j \cdot y+n,k} \tag{2}\] One of the significant operations in CNNs involves filter or kernel feature extraction, as illustrated in Figure 3. Filters, which are small and adjustable parameters, traverse the input image, generating feature maps. For example, one filter may focus on edge detection, while another specializes in identifying specific colors. The concept of "stride" defines how filters move across the input image, determining their step size. These adjustable parameters collectively provide spatial control over the convolution operation, enabling precise adjustments and customization. Towards the end of the network, fully connected layers, also known as dense layers, utilize the high-level features acquired from preceding layers to classify the image into distinct categories. These layers share a structural resemblance to a standard multi-layer perceptron neural network. ### Explanation of CNN Layers, with a Specific Focus on Image Classification Tasks Forward propagation in CNNs entails the sequential transmission of the input image through multiple layers. As the image traverses from one layer to the next, it gives rise to feature maps characterized by reduced dimensionality, which are subsequently employed in the final layers for classification purposes [15]. Similar to other neural networks, CNNs use backpropagation for training. This algorithm evaluates the disparity between the output produced by forward propagation and the expected outcome, subsequently modifying the filter weights, as illustrated in Figure 3. This weight adjustment process is often facilitated by Stochastic Gradient Descent (SGD) optimizers. 1. Initialization: Initialize the weights (\(w_{1}\), \(w_{2}\)) and biases (\(b_{1}\),\(b_{2}\)) with random values. 2. Forward Pass: Pass a training example (\(x_{\textit{train}}\)) through the network to compute the predicted output (\(y\)) Fig. 3: This flowchart highlights the CNN architecture that is used in our proposed model. It has different kernels and depth layers that take input images and output the classification. The input layer is where the color fundus image is fed into the neural network. Then the convolutional layers apply a set of filters to the input image, detecting specific features like edges, textures, and shapes that are tied into the DR signs, as highlighted in Figure 1. Then, the ReLU activation function is applied element-wise, introducing nonlinearity. The weights represent the parameters that the network learns during training, and the final output is the severity classification of DR based on features extracted from the input image by preceding layers. 3. Compute Loss: Calculate the loss, as in equation 3, using predicted output and the true target \[L=\frac{1}{2}(y-y_{true})^{2}\] (3) 4. Backpropagation: Compute the gradients of the loss with respect to the weights and biases using the chain rule (calculus) 5. Update Weight: Adjust the weights using the gradients and small learning rate according to SGD update rule4, as in Equation 4 and 5 \[w_{i}=w_{i}-\alpha(\frac{\partial L}{\partial w_{i}})\] (4) \[b_{i}=b_{i}-\alpha(\frac{\partial L}{\partial b_{i}})\] (5) 6. Repeat: Repeat steps 2-5 for specified number of epochs until convergence Pre-trained models are applied in various scenarios, particularly when working with limited training datasets. This approach applies pre-trained CNNs, with subsequent fine-tuning of their final layers for adaptation to new tasks. This reduces computational resource demands instead of using significant compute to train a CNN from scratch. CNNs utilize batch processing techniques, which enhance training efficiency by enabling faster and more parallel computation. Furthermore, cross-entropy loss functions are used to quantify the disparity between predicted outputs and actual labels, with the primary training objective being the minimization of this loss function. Without the cross-entropy loss function, CNNs risk overfitting, introducing biases, and failing to generalize effectively on unseen data. Similarly, a CNN's performance can be influenced by hyperparameters like learning rate, filter size, filter count, and layer count. Consequently, hyperparameter optimization is frequently conducted to refine these settings. Beyond image classification, CNNs find applications in complex tasks such as video analysis, natural language processing, and autonomous driving. In the healthcare domain, their image recognition capabilities are invaluable for the detection of anomalies in X-rays, MRIs, CT scans, and CFPs, as elaborated in this paper. As CNNs and their associated technologies continue to evolve, they hold immense promise for healthcare applications, ranging from early disease classification for conditions like cataracts and cancers to real-time patient monitoring. ## 4 Methodology ### Data Sets Used We incorporated multiple data sets to develop, train, and validate our model, with a primary focus on the Messidor-2 dataset. Table 1 gives a snapshot of the datasets we utilized. The primary dataset which our model was built from is the Messidor-2 dataset. Between October 2009 and September 2010, diabetic patients were imaged using a Topcon TRC NW6 non-mydriatic fundus camera with a 45\({}^{\circ}\) field of view, resulting in 345 total DR examinations. Only maculencentered images were considered for this dataset. This was then combined with the Messidor-original database, which has a total of 529 DR examinations, to create the Messidor-2 Data set. Initially, we used a 70-30 train-test split with the Messidor-2 dataset taking inspiration from other studies in the field [16]. However, we adjusted this split to 80-20 to minimize training and validation losses. Our secondary data sets include the Kaggle dataset, APTOS, DDR, and DeepDRid. 1. Kaggle: This dataset was involved in one of the Kaggle Challenges relating to medical imaging and CNNs. This dataset covers a diverse range of sources and conditions, with over 88,000 images. 2. APTOS (Asia Pacific Tele-Opthalmology Society): This society concentrates on eye-related conditions, including DR. This dataset includes patients of Asian descent and is very comprehensive, with over 13k images. 3. DDR: This dataset is sourced from 147 hospitals spread across 243 provinces in China. These images are classified based on the severity of diabetic retinopathy into 5 categories. 4. DeepDRid: This dataset originated from the 2nd Diabetic Retinopathy: Segmentation and Grading Challenge in collaboration with ISBI in 2018. This dataset focuses on three pivotal tasks: dual-view disease grading, image quality estimation, and transfer learning. All these datasets were classified based on the severity of DR present in the images. The five severities were none, mild, moderate, severe, and proliferative DR. The images of poor data quality were excluded from the datasets, and a manual review took place before putting these images into our \begin{table} \begin{tabular}{l|l|l|l} \hline Dataset & Year Released & Image Count & Field of Vision (FOW) \\ \hline Kaggle & 2015 & 88k & 50\({}^{\circ}\) \\ APTOS & 2019 & 13k & Not specified \\ DDR & 2019 & 13.6k & 45\({}^{\circ}\) \\ Messidor-2 & 2010 & 1748 & 45\({}^{\circ}\) \\ DeepDRid & 2019 & 2256 & Not specified \\ \hline \end{tabular} \end{table} Table 1: The different publicly available CFP datasets for classifying DR. model. In Figure 4, we can see examples of CFPs that passed this review and made it onto the dataset. There are significant differences between these CFPs and their features, including the hard exudate, cotton wool, and hemorrhage, as annotated in Figure 1. ### Methods Our approach is split into two primary stages: the training/validation phase and the testing phase. First, Data was aggregated from various sources like hospitals and specialized data repositories during the initial phase. We used the Messidor-2 dataset as our baseline data. We removed any 25 low-quality images from the consolidated dataset through an ancillary intelligent model and organized them using a 70-30 split5. We split each subcategory, or severity, using Skilearn's train-test split function. Footnote 5: Our updated dataset is attached to the github link in Footnote 2. During the pre-processing stage, we used two operations to reduce noise and remove gaps in the background and foreground of the CFP. The first procedure is known as Erosion. Erosion is used to eliminate or spike the edge of the area and is represented by Equation 6[17]. \[A\ominus B=p|B_{p}\subseteqq A \tag{6}\] Then we also applied dilation, which is used to broaden the rim of the background or foreground image configuration. This procedure helps us fill the gap created through erosion and is defined by equation 7[17]: \[A\oplus B=x|B_{x}\cap X\neq 0 \tag{7}\] Where \[\odot\] denote the oision; \(A\) = Structuring element and \(B\) = the erosion of the dilation of that set. These equations are from the _Tyler Coye Algorithm_. In the CNN model, we used convolutional operations to extract features. We could convert the images into feature activation maps using diverse filter sizes. Then, using the Rectified Linear Unit (ReLU) activation function, we further enhanced this model with non-linearity. Following this, we employed a pooling layer, an instrumental part in compressing the activation map's dimensions without significant information loss. We then vectored the activation maps, processed through several fully connected layers, resulting in a severity rating based on the DR-positive or DR-negative classification. In the model's second stage, we tested the data using our test-split of the Messidor-2 data set and other secondary data sets, as highlighted in section 2. To prevent our model from overfitting, we implemented the early stopping mechanism, which was used to reduce training time from 8 hours 36 mins to 4 hours and 55 mins. This technique monitors our model's performance on the validation set and halts training once the performance starts deteriorating. This ensures that the model does not overfit. We also implemented a drop-out mechanism, which allowed randomly selected neurons to be ignored at each iteration. This ensured that our neural network remained accurate and generalized well to new-unseen data. We also used the Keras auto-hyperparameter tuning module to tune crucial parameters of our models. This algorithm uses a mathematical approach to parameter tuning; this tweaks the learning rate, batch size, epochs, and dropout rate to ensure the lowest validation losses and highest accuracy. We were able to increase our validation accuracy from 55% to 70% using this hyperparameter tuner. ## 5 Results In our initial study, the DR model was trained, validated, and tested on the Messidor data set. With 1748 images split into five severity categories, we had about 300 for each severity. These 500 images were then split in an 80-20 ratio for the test-train split. As seen in Figure 4(a), our model's performance throughout the training process is consistent. Averaging at approximately 97% over 100 epochs, this model can recognize and predict patterns within the training dataset. The validation accuracy remained at 70% throughout the 100 epochs. Though slightly lower than the training data, this validation accuracy aligns with the understanding that generalizing our model to unseen data will reasonably lower the accuracy. The training loss, as seen in Figure 4(b), remained under 0.3 across all epochs. On the other hand, the validation loss was higher at about 1.5-1.8. As shown in Table 6, the training Figure 4: This figure has three images of CFPs that contain DR (in the top row) and three images of CFPs that do not contain DR (in the bottom row). The annotated features are as follows: a. Hemorrhage; b. MA; c. Drusen; d. Exudates; e. Optic disc; f. Fovea; g. Blood vessel; h. Background doi: [https://doi.org/10.1371/journal.pone.0066730.g001](https://doi.org/10.1371/journal.pone.0066730.g001) and validation accuracy also stabilized around the seventh epoch, hinting that our accuracies were not just a fluke. Additionally, this model was reset and repeatedly tested, bringing stable and similar accuracy values every time. ## 6 Discussion Our model demonstrates the effectiveness of CNNs in DR detection, with a streamlined architecture. In comparison to Yasashvini R. et al.'s hybrid deep CNNs, our model strikes a balance between complexity and efficacy. Unlike Albahl et al.'s research, which relied on multiple image enhancement techniques due to data scarcity, our model was trained on a more comprehensive dataset and validated on additional datasets. In contrast to techniques like entropy-based image processing highlighted by Shu-I Pao et al., our model aims for direct, effective, and reproducible DR classification, maintaining competitive validation accuracy. A 20% delta between training and validation metrics indicates room for improvement. Future work includes implementing regularization techniques like L1 or L2 regularization to address this disparity. Additionally, inspired by Su-I Pao et al.'s use of entropy images, we may explore further feature engineering techniques to extract informative features from retinal images. In the evolving field of DR detection, our model offers promise and scalability. Future iterations, along with advancements such as regularization techniques, have the potential to improve accuracy. Our approach's simplicity enables integration with diverse datasets and applicability across demographics and equipment sources. ## 7 Conclusion In our study on DR detection using CNNs, we achieved enhanced efficiency and accuracy in categorizing DR severity levels from retinal images. Our approach, which incorporated preprocessing techniques like erosion and dilation alongside convolutional operations, consistently yielded a 97% training accuracy over 100 epochs. Impressively, our validation accuracy reached 71%, marking significant progress towards automated medical diagnosis in DR. Comparative analysis with other studies underscores the effectiveness of our approach, striking a balance between model understanding and detection efficacy. The model is adaptable across diverse datasets, requiring minimal image enhancement due to the comprehensive Messidor-2 dataset used. However, the gap between training and validation metrics indicates potential for model enhancement, including advanced regularization techniques and feature engineering to improve accuracy and mitigate overfitting. Future improvements may explore more advanced preprocessing techniques and incorporate regularization methods to bridge the gap between training and validation loss metrics. Collaborating with healthcare institutions to obtain \begin{table} \begin{tabular}{l|l|l l|l} \hline **Epochs** & **Training Loss** & **Training Accuracy** & **Validation Loss** & **Validation Accuracy** \\ \hline 0 & 0.075937 & 0.971781 & 1.577781 & 0.70000 \\ 1 & 0.076237 & 0.964727 & 1.689509 & 0.694737 \\ 2 & 0.083331 & 0.970018 & 1.463975 & 0.710526 \\ 3 & 0.076263 & 0.973545 & 1.697605 & 0.700000 \\ 4 & 0.96008 & 0.962963 & 1.778189 & 0.663158 \\ 5 & 0.073751 & 0.966490 & 1.582166 & 0.693684 \\ 6 & 0.072941 & 0.96727 & 1.623718 & 0.784211 \\ 7 & 0.076225 & 0.966490 & 1.609345 & 0.700000 \\ \hline \end{tabular} \end{table} Table 2: Training and Validation Results for Proposed CNN model diverse datasets could further enhance the model's adaptability across various clinical scenarios. Our consistent results and the interpretability of our approach underscore the reliability of CNNs in DR detection. Our work raises questions about how healthcare professionals will adapt to AI technologies in the medical field and the potential for more optimal Neural Networks in medical classification tasks. As the medical community embraces the intersection of healthcare and AI, the advancements presented in this and other studies contribute to a safer and more clinically advanced society.
2305.10468
Connected Hidden Neurons (CHNNet): An Artificial Neural Network for Rapid Convergence
Despite artificial neural networks being inspired by the functionalities of biological neural networks, unlike biological neural networks, conventional artificial neural networks are often structured hierarchically, which can impede the flow of information between neurons as the neurons in the same layer have no connections between them. Hence, we propose a more robust model of artificial neural networks where the hidden neurons, residing in the same hidden layer, are interconnected that leads to rapid convergence. With the experimental study of our proposed model in deep networks, we demonstrate that the model results in a noticeable increase in convergence rate compared to the conventional feed-forward neural network.
Rafiad Sadat Shahir, Zayed Humayun, Mashrufa Akter Tamim, Shouri Saha, Md. Golam Rabiul Alam
2023-05-17T14:00:38Z
http://arxiv.org/abs/2305.10468v2
# Connected Hidden Neurons (CHNNet): An Artificial Neural Network for Rapid Convergence ###### Abstract The core purpose of developing artificial neural networks was to mimic the functionalities of biological neural networks. However, unlike biological neural networks, traditional artificial neural networks are often structured hierarchically, which can impede the flow of information between neurons as the neurons in the same layer have no connections between them. Hence, we propose a more robust model of artificial neural networks where the hidden neurons, residing in the same hidden layer, are interconnected, enabling the neurons to learn complex patterns and speeding up the convergence rate. With the experimental study of our proposed model as fully connected layers in shallow and deep networks, we demonstrate that the model results in a significant increase in convergence rate. ## 1 Introduction The brain, which is the main inspiration behind developing artificial neural networks, processes large amounts of data passed by senses from different parts of the body. The neurons in the brain form complex and dense connections among themselves, which is important for efficient and flexible information processing[25]. A brain can have approximately 100 billion neurons and 100 trillion neuronal connections, which implies that each neuron can have connections with 1 thousand other neurons[2]. Artificial neural networks (ANNs), on the contrary, often follow hierarchical structures with simple neural connections, which can impede the flow of information between neurons as the neurons in the same layer have no connections between them. In some scenarios, to improve the generalization power of new and unseen data, it is important to have more connections among the neurons, as a network with more connections can learn more robust and meaningful features[29]. Moreover, having more connections among the neurons can potentially speed up the convergence rate, as it helps to learn complex patterns and relations in the data[5]. We hypothesize that designing a neural network model with an increased number of neural connections would result in a performance gain. In traditional ANNs, specifically in multilayer perceptrons (MLP), to increase the number of connections while keeping the number of layers fixed, the number of neurons per hidden layer has to be increased[5]. However, increasing the number of neurons can lead to overfitting and a slow convergence problem in the model[6]. To prevent overfitting and improve the generalization performance of MLPs, regularization techniques such as dropout[26] and weight decay[24] are used. On the other hand, to solve the problem of slow convergence, activation functions such as the rectified linear unit (ReLU)[4], techniques such as batch normalization[14] and adaptive gradient methods such as the Adam optimizer[16] are used. However, using regularization[29], activation functions[3], batch normalization[13] and adaptive gradient methods[27] have some undesirable limitations as well. Hence, we propose to connect the hidden neurons of the networks in order to increase the number of neural connections in the network. However, connecting all the hidden neurons in a network will be very compute-intensive, and thus we design an ANN model where the hidden neurons, residing in the same hidden layer only, are interconnected. The primary contributions of the paper are summarized as follows: * We introduced a neural network model, namely CHNNet (Connected Hidden Neurons), in which we created connections among the hidden neurons residing in the same hidden layer, enabling robust information sharing among the neurons. * We formulated mathematical equations to calculate the activations of the hidden layers in forward propagation and revised the backpropagation algorithm to calculate the gradients based on the formulated forward propagation equations, preserving the parallel computability of the model. * We trained the proposed model on benchmark datasets and demonstrated its performance using a variable number of hidden layers, hidden neurons, and epochs against the traditional MLP model. The model depicted a significant increase in convergence rate without showing overfitting behavior. * As our model generates a larger number of trainable parameters, we tested the model against that of a traditional MLP model. The MLP model's trainable parameters were increased to be around the same as CHNNet. Our results showed that CHNNet outperformed the MLP model, particularly in deep networks. ## 2 Literature review In the infancy of neural networks, Minsky and Papert [21] specified significant drawbacks of perceptrons and suggested the raw idea of MLP. The MLP architecture they proposed is hierarchical in structure and has no connections among hidden neurons in the same layer. Further, a few MLP architectures were analyzed in the literature by Rumelhart et al. [23], none of which featured connections among the hidden neurons. Thus far, a number of ANNs have been introduced using different approaches to establish connections among neurons. A Recurrent Neural Network (RNN) has self-connections among hidden neurons through time; that is, the self-connections work as information carriers from one time step to another, which is best suited for processing sequential data [23]. The Kohonen Neural Network, proposed by Kohonen [17], has neurons arranged in a two-dimensional lattice structure and strongly connected to neighboring neurons, which enables the network to perform better on data clustering problems. The Hopfield Neural Network, a single-layered neural network introduced by Hopfield [11], has neurons symmetrically connected to all other neurons through bidirectional connections and is primarily used for associative memory problems. Similar to the Hopfield Network, the Boltzmann Machine has its neurons connected symmetrically with all other neurons, with the exception that the neurons are divided into visible units and hidden units [10]. Neural networks like the Echo State Network (ESN) [15] and Liquid State Machine (LSM) [20] have featured a pool of neurons, namely a reservoir, which consists of numerous randomly connected neurons, providing them with non-linear modeling ability. However, as the reservoir is randomized, it requires numerous trials and sometimes even luck [22]. It should be emphasized that the referred ANNs have specific use cases that are irrelevant to the concentration of our work. In the contemporary period, designing new paths for information flow in neural networks has attained noticeable success. Convolutional Neural Network (CNN) architectures like DenseNet [12], ResNet [9] and UNet++[30], which use skip connections to directly pass information from a layer to a deeper layer, have reached state-of-the-art (SOTA) performance. Moreover, Liu et al. [19] introduced the Group Neural Network, which, to overcome the blockade at information passing, features a group of neurons that can connect freely with each other. However, due to its irregular architecture, the training of the network cannot be accelerated through parallel computing. It is significant to mention that our approach to connecting the hidden neurons is distinct from that of the referred ANNs. ## 3 Methodology The proposed architecture features additional self-connections and interconnections among the hidden neurons, as shown in figure 1. We formulated mathematical equations for forward propagation and revised the backpropagation algorithm for hidden layers only, as no new connections are introduced in input and output layers. ### Forward propagation Rumelhart et al. [23] note that the process of calculating the activations of each layer in the forward direction is straightforward and can be done quickly using matrix operations. Therefore, the forward propagation can be computed for an entire batch of inputs using matrix operations, which is much faster than computing it for each input individually. Mathematically, forward propagation can be expressed as follows: Let \(Y\) be the output, and \(f\) be the activation function. For the \(l\)th hidden layer, the input is \(a^{[l-1]}\) and the output \(a^{[l]}\) is computed as: \[z^{[l]}=w^{[l]}a^{[l-1]}+b^{[l]}\] \[a^{[l]}=f(z^{[l]})\] where \(w^{[l]}\) is the weight matrix connecting \((l-1)\)th layer to \(l\)th layer, \(b^{[l]}\) is the bias vector \(l\)th layer and \(z^{[l]}\) and \(a^{[l]}\) are the pre-activation and post-activation outputs of \(l\)th layer respectively. The output of the network is computed as: \[Y=f(z^{[L]})\] where \(z^{[L]}\) is the pre-activation output of the output layer and \(L\) is the number of layers in the network. Unlike traditional MLP architectures, in CHNNet, information from one hidden neuron is being incorporated into the other hidden neurons residing in the same hidden layer. Therefore, for the forward propagation, we have two sets of weight matrices, one set is the weight matrix connecting \((l-1)\)th layer to \(l\)th layer and the other set is the weight matrix connecting hidden neurons of \(l\)th Figure 1: Proposed architecture of CHNNet with (a) one hidden layer and (b) two hidden layers. layer to other hidden neurons of the layer. Then for layer \(l\), the input is \(a^{[l-1]}\) and the pre-activation output \(z^{[l]}\) is computed as: \[z^{[l]}=w_{1}^{[l]}\cdot a^{[l-1]}+w_{2}^{[l]}\cdot h^{[l]}+b^{[l]} \tag{1}\] where \(w_{1}^{[l]}\) is the weight matrix connecting \((l-1)\)th layer to \(l\)th layer, \(w_{2}^{[l]}\) is the weight matrix connecting hidden neurons of \(l\)th layer to other hidden neurons of the layer, \(b^{[l]}\) is the bias vector \(l\)th layer, \(h^{[l]}\) is the post-activation output of the hidden neurons and \(z^{[l]}\) and \(a^{[l]}\) are the pre-activation and post-activation outputs of \(l\)th layer respectively. The post-activation output of the hidden neurons \(h^{[l]}\) in equation 1 is the variable that is introduced in CHNNet. For \(l\)th layer, the input is \(a^{[l-1]}\) and output \(h^{[l]}\) is computed as: \[t^{[l]}=w_{1}^{[l]}\cdot a^{[l-1]}+b^{[l]} \tag{2}\] \[h^{[l]}=f(t^{[l]}) \tag{3}\] where \(t^{[l]}\) is the pre-activation output of \(l\)th layer. Finally, the post-activation output \(a^{[l]}\) of \(l\)th layer is computed as: \[a^{[l]}=f(z^{[l]})\] ### Backpropagation As described by Rumelhart et al. [23], the backpropagation can be mathematically expressed as follows: Let \(Y\) be the output, \(f\) be the activation function and \(E\) be the loss function. The upstream gradient for the output layer \(\delta_{u}^{(L)}\), where \(L\) is the number of layers in the network, can be computed as: \[\delta_{u}^{(L)}=\frac{\partial E}{\partial Y}\] Now for \(l\)th layer, the upstream gradient \(\delta_{u}^{[l]}\) can be computed as: \[\delta_{u}^{[l]}=w^{[l+1]^{\mathsf{T}}}\cdot\delta^{[l+1]}\] where \(w^{[l+1]}\) is the weight matrix connecting \((l)\)th layer to \((l+1)\)th layer and \(\delta^{[l+1]}=\frac{\partial E}{\partial z^{[l+1]}}\), where \(z^{[l]}\) be the pre-activation output of \(l\)th layer. Then for \(l\)th layer \(\delta^{[l]}\) can be computed as: \[\delta^{[l]}=\delta_{u}^{[l]}\odot f^{\prime}(z^{[l]})\] In the end, the gradients can be calculated as: \[\frac{\partial E}{\partial w^{[l]}}=\delta^{[l]}\cdot a^{[l-1]^{\mathsf{T}}}\] \[\frac{\partial E}{\partial b^{[l]}}=\delta^{[l]}\] Finally the weight matrix \(w^{[l]}\) and bias vector \(b^{[l]}\) can be updated using the following equations: \[w^{[l]}\to w^{[l]}-\eta\cdot\frac{\partial E}{\partial w^{[l]}} \tag{4}\] \[b^{[l]}\to b^{[l]}-\eta\cdot\frac{\partial E}{\partial b^{[l]}} \tag{5}\] In contrast to traditional MLP architectures, CHNNet has two sets of weight matrices. The weight matrix \(w_{1}^{[l]}\) can be updated using equation 4. For weight matrix \(w_{2}^{[l]}\), the gradient can be computed as: \[\frac{\partial E}{\partial w_{2}^{[l]}}=\delta^{[l]}\cdot{h^{[l]}}^{\mathsf{T}} \tag{6}\] Finally, weight matrix \(w_{2}^{[l]}\) can be updated using as follows: \[w_{2}^{[l]}\to w_{2}^{[l]}-\eta\cdot\frac{\partial E}{\partial w_{2}^{[l]}} \tag{7}\] The process of backpropagation for a hidden layer is summarized in Algorithm 1. ``` Computing Delta: \[\delta^{[l]}=\delta^{[l]}_{u}\odot f^{\prime}(z^{[l]})\] Computing Gradients: \[\frac{\partial E}{\partial w^{[l]}}=\delta^{[l]}\cdot a^{[l-1]^{\mathsf{T}}}\] \[\frac{\partial E}{\partial w^{[l]}_{2}}=\delta^{[l]}\cdot h^{[l]^{ \mathsf{T}}}\] \[\frac{\partial E}{\partial b^{[l]}}=\delta^{[l]}\] Updating Weights: \[w^{[l]}_{1}\to w^{[l]}_{1}-\eta\cdot\frac{\partial E}{\partial w^{[l]}_{1}}\] \[w^{[l]}_{2}\to w^{[l]}_{2}-\eta\cdot\frac{\partial E}{\partial w^{[l]}_{2}}\] \[b^{[l]}\to b^{[l]}-\eta\cdot\frac{\partial E}{\partial b^{[l]}}\] Computing Downstream Gradient: \[\delta^{[l-1]}_{u}=w^{[l]^{\mathsf{T}}}_{1}\cdot\delta^{[l]}\] ``` **Algorithm 1** Backpropagation for a single hidden layer in CHNNet ## 4 Performance evaluation To evaluate the performance of our proposed model, we used the software library TensorFlow 2 by Google. Using the TensorFlow library, we constructed a layer, namely the CHN Layer, implementing the forward and backpropagation described in Section 3. Using the CHN layer, along with other layers provided by the TensorFlow library, we performed all our experiments. Our goal was not to get SOTA performance on the benchmark datasets. Rather, it was to achieve a better convergence rate without overfitting behavior. We compared the performance of the CHN layer, as fully connected hidden layers in shallow networks and deep networks, with that of the Dense layer provided by the TensorFlow library, which implements traditional MLP forward propagation and backpropagation mechanisms. ### Datasets We evaluated the performance of the CHN layer on six benchmark datasets of different sizes and diverse features. All the chosen datasets are well-structured, with clear patterns and few outliers. For our experiments in shallow networks, we used three benchmark datasets, namely Abalone, Iris and the MNIST dataset. The Abalone dataset, used for linear regression experiments, contains 4177 instances and 8 attributes[1]. The Iris dataset contains 150 instances of 3 classes of iris plants, each having 4 numerical attributes[1]. We split both the Abalone and Iris datasets in a ratio of 80:20 randomly for training and testing sets, respectively. The MNIST dataset, consisting of 28x28 images of handwritten digits divided into 10 classes, holds 60,000 training samples and 10,000 testing samples[18]. Both the Iris and MNIST datasets are used for classification experiments. We used another three benchmark datasets to conduct our experiments in deep networks, namely the Boston Housing, Breast Cancer and Fashion MNIST datasets. The Boston Housing dataset, used for linear regression experiments, contains 506 instances and 13 attributes[7]. The Breast Cancer (Diagnostics) dataset contains 569 instances and 30 numerical attributes of 2 classes of breast cancer [31]. We split both the Boston Housing and Breast Cancer datasets in a ratio of 80:20 randomly as well. The Fashion MNIST dataset has the exact same features as the MNIST dataset mentioned earlier, with the only exception that instead of digits, the dataset has 10 classes of fashion accessories[28]. Both the Breast Cancer and Fashion MNIST datasets are used for classification experiments. ### Hyperparameters We chose the number of hidden neurons in the hidden layers to be a power of 2 due to hardware reasoning. The loss functions for the experiments were chosen depending on the type of dataset and the desired output format. We used mean square error in linear regression problems [8], categorical cross entropy in multi-class classification problems [5] and binary cross entropy in binary classification problems [5]. The optimizers are selected based on the improvement they could bring to the performance of the models. ### CHN layer in shallow networks #### 4.3.1 Training parameters We trained the models on the Abalone dataset using a network with 8-1 neurons, mean square error as a loss function and batches of size 256. For the Iris dataset, we used a network as 128-3, categorical cross entropy as a loss function and one batch of size 120. As optimizer, for both the Abalone and Iris data sets, we used the Adam optimizer with a learning rate of 0.001. While training on the MNIST dataset, we used a 128-10 network, an RMSprop optimizer with a learning rate of 0.001, sparse categorical cross entropy as a loss function and batches of size 512. #### 4.3.2 Test results As shown in figure 2, the CHN layer had a better convergence rate, specifically on the Iris and MNIST datasets, compared to the Dense layer. Moreover, when trained using a smaller number of epochs on the Iris and MNIST datasets, CHNNet was able to achieve more accuracy than the Dense layer, as demonstrated in table 1. On the abalone dataset, the CHN layer had comparable performance to the Dense layer, as there was no significant performance difference between the models. However, the CHN layer generated more trainable parameters than the Dense layer in all experiments, as new connections among the hidden neurons were introduced in the designed layer. ### CHN layer in deep networks #### 4.4.1 Training parameters We used a network with 64-64-1 neurons, an RMSprop optimizer with a learning rate of 0.001 and the mean square error as the loss function for training the models on the Boston Housing dataset. For Figure 2: Loss graph of CHN layer and Dense layer on (a) Abalone, (b)Iris and (c)MNIST dataset and accuracy graph of the layers on (d)Iris and (e)MNIST dataset. the Breast Cancer dataset, we used a network of 64-64-3, an Adam optimizer with a learning rate of 0.001 and binary cross entropy as a loss function. For experiments on both the Boston Housing and Breast Cancer datasets, we used batches of size 128. While training on the Fashion MNIST dataset, we used a 256-256-256-10 network, an SGD optimizer with a learning rate of 0.001, sparse categorical cross entropy as a loss function and batches of size 32. #### 4.4.2 Test results Compared to shallow networks, the CHN layer showed significantly better performance in deep networks, with faster convergence as depicted in figure 3 and better loss and accuracy measurements than the Dense layer when tested with a smaller number of epochs, as illustrated in table 1. Specifically, on the Fashion MNIST dataset, the CHN layer noticeably outperformed the Dense layer with more accuracy and less loss for any number of epochs. However, in deep networks as well, the CHN layer generated more trainable parameters than the Dense layer. ### Equating CHN layer and Dense layer In the experiments conducted previously, the CHN layer generated more trainable parameters than the Dense layer. Thereby, we conducted some more experiments with an increased number of hidden \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline & & \multicolumn{3}{c}{Dense Layer} & \multicolumn{3}{c}{CHN Layer} \\ \hline Datasets & epoch & Trainable & Average & Average & Trainable & Average & Average \\ & & Params & Loss & Accuracy & Params & Loss & Accuracy \\ \hline Abalone & 50 & 97 & 0.007 & - & 161 & 0.007 & - \\ & 20 & 97 & 0.012 & - & 161 & 0.009 & - \\ \hline Iris & 500 & 1,027 & 0.16 & 93.33 & 17,411 & 0.21 & 93.33 \\ & 50 & 1,027 & 0.54 & 84.34 & 17,411 & 0.27 & **92.15** \\ \hline MNIST & 30 & 101,770 & 0.08 & 97.68 & 118,154 & 0.09 & 97.67 \\ & 5 & 101,770 & 0.12 & 96.21 & 118,154 & 0.093 & **97.15** \\ \hline \hline \end{tabular} \end{table} Table 1: Performance measurement of CHN layer in shallow network. Figure 3: Loss graph of CHN layer and Dense layer on (a) Boston Housing, (b)Breast Cancer and (c)Fashion MNIST dataset and accuracy graph of the layers on (d)Breast Cancer and (e)Fashion MNIST dataset. neurons in the dense layer to raise the number of trainable parameters in the Dense layer around that of the CHN layer. #### 4.5.1 Training parameters All the training parameters were exactly the same as in previous experiments, except that we increased the number of hidden neurons in the Dense layer. Hence, we had Dense layers with an architecture of 16-1 for the abalone dataset, 2048-3 for the iris dataset, 150-10 for the MNIST dataset, 110-110-1 for the Boston Housing dataset, 105-105-1 for the Breast Cancer dataset and 360-360-360-10 for the fashion MNIST dataset. #### 4.5.2 Test results Even after increasing the number of hidden neurons in Dense layers, the CHN layer showed a significantly faster convergence rate without acquiring overfitting behavior on the Boston Housing, Breast Cancer and Fashion MNIST datasets. As shown in table 3, the CHN layer outperformed the Dense layer in those datasets as well. It should be emphasized that the proposed layer exhibits better performance in deep networks compared to shallow networks. In shallow networks as well, the CHN layer exhibits comparable performance to the Dense layer. \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline & & \multicolumn{3}{c}{Dense Layer} & \multicolumn{3}{c}{CHN Layer} \\ \hline Datasets & epoch & Trainable & Average & Average & Trainable & Average & Average \\ & & Params & Loss & Accuracy & Params & Loss & Accuracy \\ \hline Boston & 100 & 5,121 & 26.77 & 31.84 & 13,313 & 25.21 & - \\ & 50 & 5,121 & 50.71 & - & 13,313 & **25.45** & - \\ \hline Cancer & 100 & 6,209 & 0.1 & 96.76 & 14,401 & 0.05 & 97.35 \\ & 30 & 6,209 & 0.13 & 95.65 & 14,401 & 0.06 & **97.1** \\ \hline F\_MNIST & 10 & 335,114 & 0.365 & 86.47 & 531,722 & 0.332 & **87.81** \\ \hline \hline \end{tabular} \end{table} Table 2: Performance measurement of CHN layer in deep network. Figure 4: Loss graph of CHN layer and Dense layer on (a) Abalone, (b)Iris, (c)MNIST, (d)Boston Housing, (e)Breast Cancer and (f)Fashion MNIST dataset. ### Discussion From the experiments conducted, it is evident that CHNNet has the potential to outperform the Dense layer. Specifically, in deep networks, CHNNet depicts promising outcomes. Though CHNNet generates a larger number of trainable parameters than traditional MLP models, with nearly equal numbers of trainable parameters, the proposed model exhibits comparable performance in shallow networks and outperforms the traditional MLP model in deep networks. ## 5 Future Work CHNNet, thus far, has been tested on a relatively small set of benchmark datasets, which leaves the scope for more comprehensive experiments with the model. As the model generates numerous parameters, some algorithms can also be proposed to reduce the number of connections systematically. Moreover, the model has not been tested as a fully connected layer in CNN architectures, which also has the potential to generate compelling outcomes. It would be interesting to see if more efficient CNN architectures could be developed utilizing the features of CHNNet. Further, there is the opportunity for research on implementing RNN models based on architecture of CHNNet. ## 6 Conclusion We designed a rapidly converging ANN, namely CHNNet, which is different from the existing multi-layered networks in that it creates connections among the hidden neurons of the same layer. In addition, we described the forward propagation and backpropagation mechanisms of the proposed model. CHNNet depicted a significant increase in convergence rate, resulting in fewer epochs for training compared to traditional MLP-based models, especially in deep networks. On the contrary, the model generated numerous trainable parameters, which increased the training time per epoch compared to the traditional models. However, even with a nearly equal number of trainable parameters in both CHNNet and traditional models, CHNNet depicted a comparable performance in shallow networks and outperformed the traditional models in deep networks without adapting overfitting behavior.
2309.03919
A hybrid quantum-classical fusion neural network to improve protein-ligand binding affinity predictions for drug discovery
The field of drug discovery hinges on the accurate prediction of binding affinity between prospective drug molecules and target proteins, especially when such proteins directly influence disease progression. However, estimating binding affinity demands significant financial and computational resources. While state-of-the-art methodologies employ classical machine learning (ML) techniques, emerging hybrid quantum machine learning (QML) models have shown promise for enhanced performance, owing to their inherent parallelism and capacity to manage exponential increases in data dimensionality. Despite these advances, existing models encounter issues related to convergence stability and prediction accuracy. This paper introduces a novel hybrid quantum-classical deep learning model tailored for binding affinity prediction in drug discovery. Specifically, the proposed model synergistically integrates 3D and spatial graph convolutional neural networks within an optimized quantum architecture. Simulation results demonstrate a 6% improvement in prediction accuracy relative to existing classical models, as well as a significantly more stable convergence performance compared to previous classical approaches.
L. Domingo, M. Chehimi, S. Banerjee, S. He Yuxun, S. Konakanchi, L. Ogunfowora, S. Roy, S. Selvaras, M. Djukic, C. Johnson
2023-09-06T11:56:33Z
http://arxiv.org/abs/2309.03919v3
A Hybrid Quantum-Classical Fusion Neural Network to Improve Protein-Ligand Binding Affinity Predictions for Drug Discovery ###### Abstract The field of drug discovery hinges on the accurate prediction of binding affinity between prospective drug molecules and target proteins, especially when such proteins directly influence disease progression. However, estimating binding affinity demands significant financial and computational resources. While state-of-the-art methodologies employ classical machine learning (ML) techniques, emerging hybrid quantum machine learning (QML) models have shown promise for enhanced performance, owing to their inherent parallelism and capacity to manage exponential increases in data dimensionality. Despite these advances, existing models encounter issues related to convergence stability and prediction accuracy. This paper introduces a novel hybrid quantum-classical deep learning model tailored for binding affinity prediction in drug discovery. Specifically, the proposed model synergistically integrates 3D and spatial graph convolutional neural networks within an optimized quantum architecture. Simulation results demonstrate a 6% improvement in prediction accuracy relative to existing classical models, as well as a significantly more stable convergence performance compared to previous classical approaches. S. Banerjee\({}^{1}\), S. He Yuxun\({}^{1}\), S. Konakanchi\({}^{1}\), L. Ogunfowora\({}^{1}\), S. Roy\({}^{1}\), S. Selvaras\({}^{1}\), L. Domingo\({}^{2*}\), M. Chehimi\({}^{2}\), M. Djukic\({}^{2}\) and C. Johnson\({}^{2*}\)+\({}^{1}\) Purdue University, The Data Mine, USA, \({}^{2}\) Ingenii Inc., New York, USA, \({}^{*}\)Corresponding Authors' Emails: {laia,christine}@ingenii.dev Quantum machine learning (QML), drug discovery, binding affinity, quantum fusion model. ## 1 Introduction The healthcare landscape has undergone a transformative shift, notably marked by advancements in drug discovery through the integration of emerging technologies. Through complex molecular interactions and precise computational modeling of compound interactions, novel drugs are rigorously designed and identified. Central to this design process is the understanding of proteins and their role in disease mechanisms [1]. In the field of drug discovery, it is imperative to identify proteins that are instrumental in the cascade of molecular interactions leading to a specific disease [2]. Upon the identification of such a target protein, a list of prospective drug candidates is generated. These candidates, often described as small molecules or compounds termed _ligands_, have the potential to modulate the target protein's activity through binding interactions [3]. Ideal ligands are chosen based on their high binding affinity to the target protein, coupled with minimal off-target interactions with other proteins. However, quantifying such binding affinities is a resource-intensive endeavor [4], both in terms of time and financial investment. This is particularly true considering that the initial screening process often encompasses thousands of compounds [4, 5]. The transition from conventional laboratory methods to computer-aided design (CAD) has markedly improved the efficiency and accuracy of drug discovery and binding affinity prediction. This advancement has been further bolstered by the incorporation of artificial intelligence (AI) and machine learning (ML) algorithms, which facilitate exhaustive analyses of large-scale datasets, uncovering previously undetected patterns related to the atomic features of protein-ligand molecular complexes [6]. Furthermore, recent strides in quantum computing have added another layer of sophistication to drug discovery efforts, offering unprecedented parallelized computational capabilities [7]. Quantum machine learning (QML) models, in particular, are well-suited to manage the challenges of exponentially increasing data dimensionality, often outperforming traditional ML models under specific conditions. Taken together, these technological advancements make QML and hybrid quantum-classical models highly promising for navigating the complex, high-dimensional challenges intrinsic to drug discovery [8]. Related Works.Several prior works [9, 10, 11, 12, 13] addressed the problem of binding affinity prediction in drug discovery using tools from both classical ML and QML. For instance, the work in [9] leveraged 3D-convolutional neural networks (3D-CNNs) to perform protein-ligand binding affinity predictions in a faster and more efficient manner relative to other ML models. Moreover, the work in [10] enhanced the model proposed in [9] by predicting binding affinities using an ensemble of several independently-trained 3D-CNN network layers. Furthermore, the work in [11] introduces a classical fusion model combining a 3D-CNN and a spatial graph CNN (SG-CNN). The model in [11] enhances binding affinity prediction by concurrently processing grid-based, context-based, and graph-based protein features. However, the models proposed in [9, 10, 11] suffer from issues with convergence stability, and their predictive accuracy stands to gain from further optimization. Additionally, the work in [12] uses quantum support vector machines for virtual drug screening. Although the hybrid QML model in [12] outperforms classical counterparts, its focus on a limited subset of protein-ligand features restricts model accuracy and scalability to larger datasets. Finally, the work in [13] proposes a hybrid QML architecture, modifying a classical CNN by replacing a classical convolutional layer with an optimized quantum circuit. While the work in [13] successfully tackles the computational complexity inherent in classical neural networks, it does not yield an improvement in binding affinity predictive accuracy, thus achieving a comparable performance to classical models. To the best of our knowledge, no existing research has effectively tackled the issue of binding affinity prediction in drug discovery by capitalizing on the benefits of QML while simultaneously achieving high accuracy and ensuring smooth, stable convergence. Contributions.The main contribution of this paper is the development of a novel hybrid quantum fusion model aimed at enhancing the binding affinity predictions in drug discovery. The proposed model strategically integrates 3D-CNNs and SG-CNNs to leverage their respective strengths in processing diverse facets of the training data. The proposed quantum architecture is meticulously designed for optimal accuracy. Simulation results demonstrate the superior performance of the proposed hybrid quantum fusion model relative to state-of-the-art classical models. Particularly, the proposed model achieves a 6% improvement in the binding affinity prediction accuracy, and exhibits faster, smoother, and more stable convergence, thereby boosting its generalization capacity. ## 2 System Model This section describes the proposed hybrid quantum fusion model, its components, the data used in training the model, and the necessary pre-processing steps. ### Proposed Hybrid QML Architecture The proposed hybrid quantum fusion architecture builds upon the classical fusion model introduced in [11] while integrating quantum neural networks (QNNs) into the model design. In particular, the protein-ligand complex data (see Section 2.2) is initially fed into a 3D-CNN and an SG-CNN, simultaneously. Then, late-late fusion is performed by feeding the outputs from the second-to-last layer of each of the two respective CNNs into a quantum fusion model, which incorporates a QNN. Let us now briefly introduce the individual components of the proposed architecture, which is shown in Fig. 1. #### 2.1.1 3d-Cnn CNNs are deep learning models specifically designed for processing and analyzing high-dimensional arrays such as images, volumes, or series data. Because of their ability to automatically learn and extract features from input data, they are a cornerstone of modern computer vision applications. The adopted 3D-CNN model in this work is based on the ResNet architecture with two residual blocks [14]. After each layer, the output is passed through a batch normalization followed by a nonlinear ReLU activation function. The output from the convolutional layers is then pooled, flattened, and fed through a sequence of fully connected layers, producing the final output of the model. The exact architecture of the adopted 3D-CNN is shown in Fig. 1(a). #### 2.1.2 Sg-Cnn An SG-CNN capitalizes on the benefits of convolutional layers while leveraging the structural relationships within protein-ligand complexes. They effectively capture and preserve spatial information using a 2D graph representation, where each edge corresponds to a bond between atoms across all molecules. For each molecule within the complex, spatial Figure 1: a) 3D-CNN architecture. b) SG-CNN architecture c) Proposed hybrid quantum fusion model. In the hybrid fusion model, outputs from the second-to-last layer of each of the 2 classical neural networks trained with the PDBbind dataset are encoded onto quantum states before being fed into a feed-forward quantum neural network (QNN). information and associated features are initially processed through a graph gated recurrent unit (GGRU), incorporating information from its nearest neighbors. The resulting output vector subsequently enters another GGRU, accumulating information from the next nearest neighbors. This pivotal stage, known as the _graph gather step_, is followed by the data passing through a sequence of fully connected layers, ultimately yielding the final output of the SG-CNN. The exact architecture of the adopted SG-CNN is shown in Fig. 1(b). #### 2.1.3 Quantum Fusion Model The quantum fusion model takes the outputs from the second-to-last layer of the two aforementioned CNN models. In particular, this input is a vector of size 16, as it entails the output of 10 nodes from the 3D-CNN and 6 nodes for the SG-CNN (see Fig. 1 c)). By optimally fusing these two pre-final layers, this strategy effectively aggregates the acquired knowledge during the training of the CNNs, thereby achieving superior performance. Unlike the classical fusion model in [11], which is simply a one-layer feed-forward neural network, the quantum fusion model incorporates a QNN that consists of a quantum circuit divided into two blocks. The first block is the _quantum encoding_ part, which maps the input data into a quantum circuit, and the second block is a _parameterized quantum circuit (PQC)_, where quantum operations are applied to retrieve information from the encoded data. In the quantum fusion model, the considered outputs of the 3D-CNN and SG-CNN models are first encoded into quantum states through quantum embedding circuits, then run through the trainable QNN. Quantum Encoding Techniques.A variety of quantum data encoding techniques have been recently developed in the literature [15]. In this work, we focus on two of the most effective encoding techniques, analyzing and comparing their performance in the context of binding affinity prediction. The two considered methods are: 1. **Amplitude encoding.** where the features are encoded in the amplitudes of the quantum state in the computational basis [16]. This scheme requires only \(\lceil\log_{2}(n)\rceil\) qubits to encode a data sample into a quantum state, where \(n\) represents the input dimension of the QNN. The depth of the embedding circuit grows as \(O(poly(n))\) while the number of parameters subject to optimization scales as \(O(log_{2}(n))\). 2. **Hybrid Angle Encoding (HAE)**, where amplitude encoding is implemented using parallel blocks of independent qubits [15]. The features are divided into \(b\) blocks of size \(2^{m}-1\), where \(m\) represents is the number of qubits. Accordingly, \(b\times m\) qubits are required to encode the whole data sample into a quantum state. PQC ArchitectureAfter encoding the data into quantum states (or qubits), they pass through a PQC. The architecture of the PQC is designed to generate a substantial level of entanglement and expressibility, by creating cross connections between the qubits. The PQC consists of several quantum gates which are controlled by classically-optimized parameters. Several potential PQC architectures were analyzed, and the resulting optimal architecture is composed of 3D generalized rotation gates with all-to-all CNOT connections, catalogued as _strongly entangling layers_. ### Dataset The PDBbind dataset [17] (2020 version) is adopted as the input to train the proposed quantum fusion model. PDBbind represents an extensive compilation of experimentally determined binding affinity data between proteins and ligands. This dataset meticulously associates protein-ligand complexes with their respective affinity measurements, a curation process executed via manual extraction from peer-reviewed scientific publications. The current latest PDBbind version, released in early 2020, contains a total of 19,443 protein-ligand complexes. Additionally, a meticulously curated subset of 5,316 samples has been compiled, specifically comprising high-quality complexes. Finally, an even higher-quality core set of 285 samples is derived, primarily for validating binding affinity prediction methods. We utilize the refined set in the training and validation phases of our analysis, with 25% of the data reserved for validation. Then, the core set is used for the testing phase. ### Data Pre-processing Before passing the PDBbind data into the two CNN architectures, it is essential to pre-process the raw data and extract pertinent input features from the 3D structures of proteins and ligands. In this regard, our approach closely aligns with established featurization techniques as outlined in [18, 11, 13], thereby facilitating the comparability of our results with existing state-of-the-art models. Moreover, the PDB files are converted to Mol2 files using the UCSF Chimera software [19]. The input data for 3D-CNN consists of spatial representation of 3D structures of atoms of protein-ligand pairs. The atoms are voxelized into a grid of size \(N\times N\times N\) with a voxel size of \(1\) A, and the number of voxels set to \(N=48\) to strike a balance between covering the entire pocket regions and lowering the input data size for the CNN model. \(C=19\) features are extracted for each voxelized atom using OpenBabel [20], bringing the input data for 3D-CNN to a \(C\times N\times N\times N\) matrix. Such features include the atom type, hybridization, number of heavy atom bonds, number of bonds with heteroatoms, structural properties, partial charge, and molecule type (protein vs ligand). On the other hand, the input data for SG-CNN consists of a spatial graph representation of the protein-ligand complexes, with the atoms forming the nodes, and the bonds between atoms forming the edges, of the graph. As in Ref. [11], covalent bonds are represented by an \(N\times N\) adjacency matrix and non-covalent bonds by an \(N\times M\) matrix, where the element \(A_{ij}\) of each matrix represents the Euclidean distance between the atoms \(i\) and \(j\). ## 3 Experiments and Results In this section, the conducted experiments and simulations are presented, and the obtained results are analyzed. To validate the performance of our proposed hybrid quantum fusion model, we benchmark against the classical fusion counterpart model. The binding affinity prediction performance of both fusion models is evaluated using five different metrics: root mean square error (RMSE), mean absolute error (MAE), \(R^{2}\), Pearson coefficient, and Spearman coefficient. Recall that the RMSE and MAE should be minimized to obtain optimal performance, while \(R^{2}\), Pearson and Spearman coefficients should be maximized. ### Experimental Setup Following a comparative evaluation of various optimizers and hyperparameters, the training of both fusion models was conducted using the ADAM optimizer with a learning rate of \(\eta=0.002\), a batch size of 50 samples, and a mean squared error loss function. Moreover, in the QNN, \(\sigma_{z}\) Pauli operator projection measurements were performed on all qubits to extract the classical measurement outcomes. The final prediction is made with a classical linear layer with a ReLu activation function. Finally, the PQC has a depth of 10 layers. ### Binding affinity prediction performance First, we compare the performance of the proposed quantum fusion model and its classical counterpart for the five considered metrics, which is summarized in Table 1. From Table 1, we notice that the quantum fusion model provides better performance for all five metrics, which represents an up to 6% improvement over the classical model. ### Convergence of the fusion model Next, in Fig. 2, we compare the convergence of the loss function in the validation set for the quantum and classical fusion models. We notice from Fig. 2 that the convergence of the loss function for the quantum model is much smoother and stable than that of the classical model. Therefore, the quantum fusion model provides much more reliable predictions, which are less likely to produce overfitting in the training set. ### Impact of quantum encoding Finally, we compare the performance of the proposed quantum fusion model with amplitude encoding and HAE techniques, as shown in Fig. 3. For HAE, we used \(b=2\) and \(m=4\), corresponding to encoding 30 data points. The 16 features of the QNN input vector were padded with zeros to create a 30-dimensional vector. From Fig. 3, it is clear that the amplitude encoding outperforms the HAE technique. ## 4 Conclusion In this paper, we have proposed a novel hybrid QML model, offering accurate and reliable binding affinity predictions, which is a critical factor in drug discovery. The proposed model is a quantum fusion model that integrates 3D-CNN and SG-CNN classical models with QNNs. Simulation results validate the superiority of the quantum model relative to the classical fusion counterpart model, demonstrating a 6% accuracy enhancement while achieving faster and smoother convergence, thus mitigating the risk of overfitting. ## 5 Acknowledgment This research was supported by Ingenii Inc, USA. Authors would also like to thank the Data Mine project at Purdue University, specifically Dr. Mark Daniel Ward. \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline Method & \(R^{2}\) & MAE & Pearson & Spearman & RMSE \\ \hline \hline Class. Fsn & 0.60 & 1.05 & 0.777 & 0.766 & 1.37 \\ \hline Q’tum Fsn & 0.63 & 1.04 & 0.809 & 0.815 & 1.29 \\ \hline \end{tabular} \end{table} Table 1: Comparison of classical and quantum fusion model for the five error metrics. Figure 3: Comparison of test statistics resulting from two data encoding schemes (amplitude vs. hybrid angle) and strongly entangling layers in the quantum circuits. Figure 2: Comparison of the convergence of the loss function for the classical and quantum fusion models.
2304.12630
Spatiotemporal Graph Convolutional Recurrent Neural Network Model for Citywide Air Pollution Forecasting
Citywide Air Pollution Forecasting tries to precisely predict the air quality multiple hours ahead for the entire city. This topic is challenged since air pollution varies in a spatiotemporal manner and depends on many complicated factors. Our previous research has solved the problem by considering the whole city as an image and leveraged a Convolutional Long Short-Term Memory (ConvLSTM) model to learn the spatiotemporal features. However, an image-based representation may not be ideal as air pollution and other impact factors have natural graph structures. In this research, we argue that a Graph Convolutional Network (GCN) can efficiently represent the spatial features of air quality readings in the whole city. Specially, we extend the ConvLSTM model to a Spatiotemporal Graph Convolutional Recurrent Neural Network (Spatiotemporal GCRNN) model by tightly integrating a GCN architecture into an RNN structure for efficient learning spatiotemporal characteristics of air quality values and their influential factors. Our extensive experiments prove the proposed model has a better performance compare to the state-of-the-art ConvLSTM model for air pollution predicting while the number of parameters is much smaller. Moreover, our approach is also superior to a hybrid GCN-based method in a real-world air pollution dataset.
Van-Duc Le
2023-04-25T07:57:07Z
http://arxiv.org/abs/2304.12630v1
# Spatiotemporal Graph Convolutional Recurrent Neural Network Model ###### Abstract Citywide Air Pollution Forecasting tries to precisely predict the air quality multiple hours ahead for the entire city. This topic is challenged since air pollution varies in a spatiotemporal manner and depends on many complicated factors. Our previous research [1] has solved the problem by considering the whole city as an image and leveraged a Convolutional Long Short-Term Memory (ConvLSTM) model to learn the spatiotemporal features. However, an image-based representation may not be ideal as air pollution and other impact factors have natural graph structures. In this research, we argue that a Graph Convolutional Network (GCN) can efficiently represent the spatial features of air quality readings in the whole city. Specially, we extend the ConvLSTM model to a Spatiotemporal Graph Convolutional Recurrent Neural Network (Spatiotemporal GCRNN) model by tightly integrating a GCN architecture into an RNN structure for efficient learning spatiotemporal characteristics of air quality values and their influential factors. Our extensive experiments prove the proposed model has a better performance compare to the state-of-the-art ConvLSTM model for air pollution predicting while the number of parameters is much smaller. Moreover, our approach is also superior to a hybrid GCN-based method in a real-world air pollution dataset. ## 1 Introduction Air Pollution is a severe problem for many big cities in the world. Accurately predicting air quality multiple hours ahead is a challenging task in recent years. One of the most concerning problems is that air pollution varies by both spatial and temporal forms. As pointed in recent research papers [1], [2], [3], [4], [5], the air cleanness in a city changes from one location to other locations and time by time. Therefore, we need a _spatiotemporal architecture_ to model air pollution features efficiently and effectively. Our previous paper in [1] illustrated that many _spatiotemporal factors_ can affect a city's air quality. These factors include meteorological factors such as rain, humidity, wind speed, wind direction; transportation factors like the traffic volume or vehicle driving speed; and external factors such as air pollution from nearby cities or areas. These mentioned spatiotemporal influences make the air pollution forecasting problem harder; thus, an air quality prediction model should effectively represent the air pollution values and their spatiotemporal impact factors. Our past research introduced a large-scale _real-world air pollution dataset_ collected from Seoul city in South Korea to tackle the spatiotemporal air pollution forecasting task. Using the collected Seoul data, we proposed to use a combination of Convolutional Neural Network (CNN) and Long Short-Term Memory (LSTM) in a _ConvLSTM model_ to interpolate and predict air pollution for the entire city by leveraging an image-based approach. The ConvLSTM model outperformed other Deep Learning models in forecasting air pollution of Seoul city in 12 hours ahead. However, the image-based representation may not capture well the natural graph structures of air pollution observation stations in a city and other impact factors such as meteorology or traffic. This research tries to solve and overcome the mentioned problem by leveraging a graph-based method. In Fig. 1, we show a graph structure constructed for the air pollution forecasting problem in Seoul city, South Korea. Each node denotes an air pollution monitoring station, and edges are the connections between two stations weighted by their distance. Inspired from recent success in using Figure 1: A Graph structure constructed for the air pollution forecasting problem in Seoul city, South Korea. Each node denotes an air pollution monitoring station. The labels of edges are the real-world distances between stations (some are omitted). Graph Convolutional Networks (GCNs) for spatiotemporal problems and derived from the spatiotemporal basis of air pollution data and its influential factors, we propose a **Spatiotemporal Graph Convolutional Recurrent Neural Network (Spatiotemporal GCRNN)** model. Our model uses a GCN structure to encode the spatial feature and an RNN architecture to model the time-series features of the air pollution data. The most crucial point is that we tightly integrate the GCN architecture into the RNN structure to have a unified unit that efficiently learns the spatiotemporal features at the same time. Our experiments prove that the proposed method yields better performance than previous approaches to Seoul data while the parameters are much smaller. In the ConvLSTM paper for air pollution interpolating and forecasting [1], a large scale dataset of air pollution and spatiotemporal related factors was constructed. This dataset includes air pollution values in monitoring stations collected in Seoul city for three years, from 2015 to 2017, and many air quality impact factors that contribute to building an accurate air pollution prediction model. However, we believe that an even larger dataset will accelerate this field of research with better prediction models. Therefore, in this study, we collect more data from Seoul city in two recent years of 2018 and 2019 with all aforementioned spatiotemporal factors. The new dataset has more extended period of data (from 2015 to 2019), more data points (a 75\(\%\) bigger) which brings a more significant training data for both air pollution and spatiotemporal research. In summary, our contributions in this paper are three folds: * **Firstly**, we introduce **Spatiotemporal Graph Convolutional Recurrent Neural Network model**, a unified integration of GCN and RNN architectures, which works efficiently and effectively for spatiotemporal air pollution forecasting problems. * **Secondly**, we conduct extensive experiments to prove the proposed method produces **better performance than the state-of-the-art ConvLSTM model** and **outperforms a recent GCN based approach**. We implemented the two most common graph convolutional operators, such as spectral graph and diffusion graph convolution, in our model. * **Lastly**, we **enlarge the previous large-scale dataset of Seoul data to a new massive dataset** to bring researchers a large-scale data source for both air pollution and spatiotemporal related problems. The rest of the paper is structured as follows: First, we review relating literature in the related work section. The following are detailed descriptions of our proposed method and architecture. The empirical experiments are then presented and evaluated. Finally, we conclude and discuss our future research directions. ## 2 Related work ### _Spatiotemporal Deep Learning for Air Pollution Forecasting_ Many Deep Learning based models have been adopted for spatiotemporal air pollution prediction. In [2], the authors proposed a method that used a _spatial predictor_ as a neural network to model the spatial correlations at different locations. Their approach defined spatial neighbors of a station within three circles from farthest (e.g., 300km) to nearest (e.g., 30km), and then aggregated the air pollutant values and related factors such as meteorological data in these circles. Their spatial learning algorithm is complicated and uses hand-crafted features (e.g., the circles' diameters). In contrast, our approach uses graph convolution to automatically learn the graph structures of air pollution stations and related factors in any locations in a city. Similarly, in [3], the authors introduced a _real-time air pollution prediction model_ based on big data; and in [4], an _LSTM-based encoder-decoder method_ was employed to forecast air pollution in South Korea. A more recent research [5] models air pollution influential factors using a _multi-modal approach_ for air pollution forecasting in Seoul city. Nevertheless, none of those aforementioned solutions leverages the graph structure for air pollution data as in our current research. Air pollution forecasting is also a time series prediction problem. There are some well-known machine learning algorithms for time series forecasting such as Auto-regressive Integrated Moving Average (ARIMA), Support Vector Regression (SVR), and Recurrent Neural Networks (RNNs). In [5], the authors did experiments to show that the ARIMA, SVR, and pure RNN models were inefficient in middle-to-long-term air pollution prediction since they could not exploit spatiotemporal information from many impact factors. On the other hand, some RNN variants such as Long Short-Term Memory (LSTM) [15] and Gated Recurrent Units (GRUs) [16] enable us to handle longer training sequence and create more accurate prediction for long-term foreseeing. Many recent papers have leveraged and proved the advantages of LSTM and GRUs structures in air pollution forecasting [1, 4, 5]. In this paper, we follow previous papers and propose to use GRUs as an RNN architecture to learn temporal features of air pollution data. ### _Spatiotemporal Graph Convolutional Networks_ In recent years, Convolutional Neural Networks (CNNs) have been generalized to arbitrary graphs based on the _spectral graph theory_. Graph Convolutional Networks (GCNs) were first introduced in [6], which connects the spectral graph theory and deep neural networks. Paper [7] proposes _ChebNet_ model to improve GCN with fast localized spectral convolutional filters. Paper [8]_simplifies ChebNet_ by parameterizing each spectral filter by the first order Chebyshev polynomials and achieves state-of-the-art performance in semi-supervised classification tasks. GCNs are now trending for spatiotemporal problems like traffic forecasting. In [9], the authors represented the pair-wise spatial correlations between traffic sensors using a directed graph in which nodes are sensors, and edge weights are closeness between the sensor pairs denoted by the roads network distance. The proposed model was a _graph diffusion convolution model_ to capture the spatial dependency of traffic sensors. Many following papers also suggest using GCN in traffic forecasting and produce reasonable results [10], [11]. Similarly, GCNs have been started using in air pollution forecasting problems. A paper in [12] proposed a _geo-context based diffusion convolutional recurrent neural network (GC-DCRNN)_ model for forecasting short-term PM\({}_{2.5}\) concentrations. In the paper [13], the researchers introduced to use a _sequential combination of graph convolutional neural network and long short-term memory model_ for spatiotemporal PM\({}_{2.5}\) forecasting in 72 hours ahead. A newer paper [14] defined a _knowledge enhanced graph neural network model_ for PM\({}_{2.5}\) forecasting. These papers both leveraged the GCN model as the spatial representation for air pollution features but still have shortcomings compared to our approach. The geo-context based method in [12] tried to use geographic features around monitoring stations such as roads, buildings, green lands, or water areas to model the spatial relationships between stations. It also exploited a graph convolutional recurrent neural network as in our system. The biggest problem is that they used static data such as geographic features collected from OpenStreetMap data. In contrast, we use dynamic and real-time data like traffic volume and average vehicle speeds on roads. Moreover, in crowded cities like Seoul, the geo-context around each monitoring station may be similar because of the high density of buildings and roads. Therefore, the geo-context is reduced to the real-world distances between stations as in our method. The approach in [13] firstly extracted the spatial features of input data by graph convolution operations, and then fed the extracted features into an LSTM model to learn the temporal features. The final layer was a fully connected layer to regress the PM\({}_{2.5}\) values. This paper's input data was air pollution values and weather data in Jing-Jin-Ji (Beijing, Tianjin, and Hebei) area in North China. The distinct steps of GCN and LSTM layers in this method may not accurately capture the complex correlations of many spatiotemporal factors in the air pollution forecasting problem as in our Spatiotemporal GCRNN model can capture both spatial and temporal features at the same time. The more recent paper [14] attempted to enhance the nodes and edges of a graph by the knowledge from the air pollution domain such as the air pollution transportation between cities, the meteorological information, and the geographical knowledge (e.g., mountains). We argue that their knowledge enhance approach does not generalize well for other spatiotemporal forecasting problems and they only consider the city-level prediction, whereas we try to forecast air pollution at the station-level for a city. ## 3 Methodology In this section, we formalize the air pollution forecasting as a GCN problem and describe how the _Spatiotemporal Graph Convolutional Recurrent Neural Network_ model can capture well the spatiotemporal features. ### _Graph and Graph Convolutional Network Representations_ The most important concepts in the graph theory are (Weighted) Adjacency Matrix (\(W\)), Degree Matrix (\(D\)), and Laplacian Matrix (\(L\)). For a graph \(G=(V,E)\), in which \(V=\{v_{i}\}\), \(i=1,..,N\), \(E=\{(v_{i},v_{j})\}\), the following equations define \(W\), \(D\), \(L\) of a graph, and some common types of Laplacian Matrices such as symmetric normalized Laplacian (L\({}^{sym}\)) or random walk normalized Laplacian (L\({}^{rw}\)): \[\begin{split}& W=\{w_{ij}\},w_{ij}=\begin{cases}\text{weighted value, if }(v_{i},v_{j})\in E\\ 0,\text{ otherwise}\end{cases}\\ & D=\{d_{ij}\},d_{ij}=\begin{cases}deg(v_{i})\text{, if i = j, }\sum deg(v_{i})=2|E|\\ 0,\text{ otherwise}\end{cases}\\ & L=D-W\\ & L^{sym}=D^{-1/2}(D-W)D^{-1/2}\\ & L^{rw}=D^{-1}(D-W)\end{cases}\end{split} \tag{1}\] The following equation denotes the kernel of a GCN in the ChebNet model [7]: \[g_{\theta}(\Lambda)=\sum_{k=0}^{K-1}\theta_{k}T_{k}(\tilde{\Lambda}) \tag{2}\] where \(g_{\theta}\) is a kernel (\(\theta\) represents the vector of Chebyshev coefficients) applied to \(\Lambda\), the diagonal matrix of Laplacian eigenvalues (\(\tilde{\Lambda}\) represents the diagonal matrix of scaled Laplacian eigenvalues, \(\tilde{\Lambda}=2\Lambda/\lambda_{max}-I_{n}\), \(\lambda_{max}\) is the largest eigenvalue of \(L\)). \(k\) is the smallest order neighborhood, and \(K\) indicates the largest order localization. Finally, \(T\) stands for the Chebyshev polynomials of the \(k\)th order. ### _Problem Formalization_ The goal of an air pollution forecasting task is to predict the future air quality values given previously observed air pollution from \(N\) correlated air pollution monitoring stations. We can represent the monitoring stations network as a weighted graph \(G=(V,E,W)\), where \(V\) is a set of nodes or stations, \(|V|=N\), \(E\) is a set of station relationships (edges), and \(W\in R^{N\times N}\) is a weighted adjacency matrix denoting the stations correlations. The distance of two observation stations indicates the relation between two stations in the graph. Let \(F\) is the number of features in each node (e.g., the air pollution values and other impact factors values at that node), then the input graph signal of \(G\) is \(X\in R^{N\times F}\). \(X^{(t)}\) denotes the input graph signal observed at time \(t\), and \(\tilde{X}^{(t^{\prime})}\) is the output graph signal at time \(t^{\prime}\), \(\tilde{X}\in R^{N\times 1}\) (because we only output one estimated air pollution value for one station at a time). The air pollution forecasting problem tries to learn a function \(h(.)\) that maps \(T\) historical graph signals to future \(T^{\prime}\) graph signals, given a graph \(G\): \[[X^{(t-T+1)},...,X^{(t)};G]\xrightarrow{h(.)}[\tilde{X}^{(t+1)},...,\tilde{X}^ {(t+T^{\prime})}] \tag{3}\] Fig. 2 shows how an air pollution forecasting task is constructed as a graph based problem with the graph signals representing the air pollution monitoring stations. Both input and output graph signals have the same graph structure. ### _Modeling Spatial Features_ In this paper, we learn the _spatial dependency_ between air pollution monitoring stations by representing the station network into a graph structure as in the Problem Formalization section. After that, we employ the graph convolution operators to model the spatial features of input graph signals. The extracted spatial features are used in combination with temporal features to predict future air pollution outputs. We try with two well-known graph convolution definitions, spectral graph convolution and diffusion graph convolution, for modeling spatial dependency. The formulas of two graph convolutional definition are presented below. The _spectral graph convolution_[6, 7, 8] employs the concepts of symmetric normalized graph Laplacian matrix \(L=D^{-1/2}(D-W)D^{-1/2}=\Phi\Lambda\Phi^{T}\). The convolution operation over a graph signal \(X\in R^{N\times F}\) and a kernel \(g_{\theta}\) is defined as below: \[X_{:,f}\star_{G}g_{\theta}=\Phi(\sum_{k=0}^{K-1}\theta_{k} \Lambda^{k})\Phi^{T}X_{:,f}\] \[=\sum_{k=0}^{K-1}\theta_{k}L^{k}X_{:,f}=\sum_{k=0}^{K-1}\tilde{ \theta_{k}}T_{k}(\tilde{L})X_{:,f} \tag{4}\] with the kernel \(g_{\theta}\) as in equation 2, \(\theta\) are the learnable parameters, \(f\in\{1,...,F\}\). \(\star_{G}\) denotes the convolution over a graph G. \(T_{0}(x)=1,T_{1}(x)=x,T_{k}(x)=xT_{k-1}(x)-T_{k-2}(x)\) are the basis of the Chebyshev polynomials. \(\tilde{L}=2L/\lambda_{max}-I\) represents a rescaling of the graph Laplacian that maps the eigenvalues from \([0,\lambda_{max}]\) to \([-1,1]\) since Chebyshev polynomial forms an orthogonal basis in \([-1,1]\). We can approximate the kernel \(g_{\theta}\) by a truncated expansion in terms of Chebyshev polynomials \(T_{k}(x)\) up to \(K\)th order. The graph convolution definition is now have the form: \[X_{:,f}\star_{G}g_{\theta^{\prime}}\approx\sum_{k=0}^{K}\theta_{k}^{\prime}T_ {k}(\tilde{L})X_{:,f} \tag{5}\] This expression is \(K\)-localized since it is a \(K\)th-order polynomial in the Laplacian, i.e. it depends only on nodes that are at maximum \(K\) steps away from the central node (\(K\)th-order neighborhoods). Equation 5 is our spectral graph convolution definition used in this paper. A _graph diffusion convolution_ was defined in the paper [9]. The diffusion process is characterized by a random walk on graph \(G\) with restart probability \(\alpha\in[0,1]\), and a state matrix \(D^{-1}W\), where \(D\) is the degree diagonal matrix (see equation 1). The resulted diffusion convolution from the mentioned diffusion process is specified as: \[X_{:,f}\star_{G}g_{\theta}=\sum_{k=0}^{K-1}(\theta_{k}(D^{-1}W)^{k})X_{:,f} \text{ for }f\in\{1,...,F\} \tag{6}\] where \(\theta\) are the parameters for the filter \(g_{\theta}\) and \(D^{-1}W\) represents the transition matrix of the diffusion process. The parameter \(K\) is the number of diffusion steps from a node to its neighborhood, which corresponds to the \(K\)th-order in the spectral graph convolution. Since spectral graph convolution and graph diffusion convolution are two common graph convolution operators, in this paper, we implement each operator for the GCN layer and do experiments to compare their influences to the prediction results. ### _Modeling Temporal Features_ The previous paper [1] proved the power of a combination of CNN and RNN models in spatiotemporal forecasting problems by using convolutional operators to replace the fully connections in input-to-state and state-to-state transitions of an LSTM cell. In this paper, we also leverage that idea by replacing the matrix multiplications in a GRU cell with the graph convolution to _learn spatial and temporal features of the input data simultaneously_. A GRU or Gated Recurrent Unit [16] model is a variant of RNN model that can learn long-term sequence of data similar to an LSTM model but with the smaller number of parameters. A GRU cell with the graph convolution operators establishes a spatiotemporal layer that we call a **Graph Convolutional Recurrent Neural Network layer**, or **GCRNN layer**. In detail, following are four transformation equations for reset gate, update gate, candidate values and hidden states Figure 2: An air pollution forecasting task is constructed as a graph-based problem. \(T\) is the number of historical graph signals, \(T^{\prime}\) is the number of future prediction graph signals. \(X\in R^{N\times F}\) is an input graph signal, \(\tilde{X}\in R^{N\times 1}\) is an output signal, \(h(.)\) is the learned function given the graph \(G\). in a GRU cell of one GCRNN layer. \[\begin{split}& r^{(t)}=\sigma(\Theta_{r}\star_{G}[X^{(t)},H^{(t-1 )}]+b_{r})\\ & u^{(t)}=\sigma(\Theta_{u}\star_{G}[X^{(t)},H^{(t-1)}]+b_{u})\\ & C^{(t)}=tanh(\Theta_{C}\star_{G}[X^{(t)},(r^{(t)}\odot H^{(t-1 )})]+b_{C})\\ & H^{(t)}=u^{(t)}\odot H^{(t-1)}+(1-u^{(t)})\odot C^{(t)}\end{split} \tag{7}\] where \(X^{(t)}\), \(H^{(t)}\) denote the input and output at time \(t\), \(r^{(t)},u^{(t)}\) are reset gate and update gate at time \(t\), \(C^{(t)}\) are candidate values at time \(t\), respectively. \(\star_{G}\) means the graph convolutional operator defined by spectral graph convolution (equation 5) or diffusion convolution (equation 6). \(\Theta_{r},\Theta_{u},\Theta_{C}\) are parameters for the corresponding filters. \(\odot\) denotes the Hadarmad product or element-wise matrix-matrix multiplication. \(\sigma\) and \(tanh\) are the activation functions. For multiple steps forecasting, a sequence to sequence architecture (seq2seq) is applied [17]. Both the encoder and decoder of the seq2seq consist of one or many GCRNN layers. The final states of the encoder are used to initialize the initial state of the decoder. The combination of GCRNN layers and a seq2seq scheme builds up our **Spatiotemporal Graph Convolutional Recurrent Neural Network (Spatiotemporal GCRNN)** model. Fig. 3 shows the system architecture of our Spatiotemporal GCRNN model designed for spatiotemporal air pollution forecasting. The input is the historical time-series of air pollution represented as graph signals, and the output is the future multiple hours of air pollution prediction. ### Modeling Spatiotemporal Impact Factors As presented in previous paper [1], air pollution in a city is influenced by many spatiotemporal factors. Regarding this paper's graph based approach, each spatiotemporal impact factor will be represented as a graph signal with the same graph structure as air pollution graph. We propose a strategy to learn these impact factors and air pollution graph features efficiently. We fuse air pollution values and all spatiotemporal influential factors as one input graph signal with multiple features at the corresponding node. Denotes \(X_{a}\in R^{N\times F_{a}}\) is the air pollution graph signal, \(X_{m}\in R^{N\times F_{m}}\) is the meteorological graph signal, \(X_{t}\in R^{N\times F_{t}}\) is the traffic volume graph signal, \(X_{s}\in R^{N\times F_{s}}\) is the average driving speed graph signal, and \(X_{o}\in R^{N\times F_{o}}\) is the outside air pollution graph signal. \(N\) is the number of graph nodes, \(F_{a}\), \(F_{m}\), \(F_{t}\), \(F_{s}\), and \(F_{o}\) are air pollution, meteorological, traffic volume, average speed, and outside air pollution number of features, respectively. Then the input graph signal \(X\) of the model is a **concatenation** of all graph signals: \[X=X_{a}\oplus X_{m}\oplus X_{t}\oplus X_{s}\oplus X_{o} \tag{8}\] \(\oplus\) is a vector concatenation operator. Therefore, the total number of features for the input graph signals is \(\mathcal{F}=F_{a}+F_{m}+F_{t}+F_{s}+F_{o}\). All graph convolution operations (equation 5 and equation 6) and GRU equations (equation 7) are not changed except the input graph signals turn to \(X^{(t)}\in R^{N\times\mathcal{F}}\). Fig. 4 shows the strategy of modeling spatiotemporal impact factors as the combination of input graph signals. The architecture of the Spatiotemporal GCRNN model does not change. Figure 4: Modeling spatiotemporal impact factors by fusing all input data into a combined graph signal. Figure 3: The overall architecture of our **Spatiotemporal Graph Convolutional Recurrent Neural Network** model. Input Graph Signals are historical air pollution data represented in graph structures. Prediction Outputs are predicted air pollution values in some hours ahead. A GCRNN Layer includes a GRU cell with graph convolution operators. An Encoder and Decoder architecture is applied to predict multiple future time-steps. ## 4 Experiments In this section, we describe our extensive experiments to prove the strength of the proposed Spatiotemporal GCRNN model in spatiotemporal air pollution forecasting tasks. After introducing the experiments' setup, we conduct experiments to directly compare the performance of the Spatiotemporal GCRNN to ConvLSTM, a state-of-the-art air pollution prediction method from the previous paper [1], following are comparisons with a recent GCN-based air pollution forecasting model. Lastly, we ablation study the effects of many GCN configurations such as \(K\)th-order, weighted adjacency matrix construction, and different types of graph convolutional operators. ### _Experiments Setup_ We use the Seoul dataset as in the state-of-the-art paper [1]. The Seoul dataset is a large-scale dataset that consists of 3-year spatiotemporal data in Seoul city, Korea, from 2015 to 2017. This dataset includes air pollutants, such as \(PM_{10}\), \(PM_{2.5}\),...; meteorological data, like temperature, wind speed, wind direction, rainfall,...; traffic volume of main roads; average driving speed on roads; and the air pollution from 3 areas in China (Beijing, Shanghai, and Shandong) that affects Seoul's air quality. As mentioned in the Introduction section, in this paper, we broaden the Seoul dataset with a more extended period of air pollution and related impact factors data. Table I shows statistics about our new Seoul dataset compared to the existing one. Our new dataset is _83%_ more in the number of air pollution samples and _75%_ larger in the total number of all data points. Nevertheless, to keep a fair comparison with previous methods, we still do experiments with the existing Seoul dataset and reserve the new dataset for further research. We follow the same data pre-processing of ConvLSTM model from [1] for this paper's experiments, including the grid construction. Firstly, Seoul city is divided into a grid of shape \(32\times 32\), and each grid-cell is assigned with the corresponding observation stations or traffic survey points. This step makes our experiments in this paper comparable with the previous method. After the pre-processing, we construct a graph for the grid-level air pollution forecasting problem with each node is assigned by the corresponding cell. We use the Tensorflow framework [18] to build the model and Nvidia GPU for training and testing. All experiments in this paper use the base learning rate of 0.001 and decay every ten epochs with the decay ratio 0.1 until reaching the minimal value of 2.0e-06. The batch size is 64, the number of GRU hidden units is 64, and the number of GCRNN layers is 2. We train with a maximum of 100 epochs but apply early stopping when the validation error does not decrease after 50 epochs. The Adam optimizer is utilized by its convergence speed and popular in deep learning optimizing problems. We also employ the _Root Mean Squared Error (RMSE) loss_ to compare the differences between the real observed and the estimated values. The training set is two years, 2015 and 2016, and the test set is the year 2017. This split strategy ensures the training and test set have the same distribution but still makes our model a good generalization. Regarding test set errors, we apply the following metrics to have numerous viewpoints on the testing performance. The first metric is a common regression metric such as _Root Mean Squared Error (RMSE)_. Also, we utilized a correlation coefficient _R squared_ (\(R^{2}\)) score, which was used in [13], to show how good is our prediction values' distribution fit to the real observed values. Moreover, the citywide spatiotemporal air pollution interpolation and prediction paper [1] presented a novel spatiotemporal metric called _spRMSE_ (or spatiotemporal RMSE). This metric evaluates how other spatiotemporal factors impact the efficiency of prediction outputs. To calculate this measurement, we use the following process: alternately remove one of the existing air pollution values in a node of the input graph signal in test set but still keep the features of other nodes and then compute RMSE of predicted air pollution value with the ground-truth one. The final error is the mean of RMSEs after this procedure with all nodes in the testing data. We will compare the _spRMSE_ metric values of our proposed Spatiotemporal GCRNN model to the ConvLSTM model. ### _Performance comparisons with the ConvLSTM model for short-term air pollution forecasting_ In this section, we conduct experiments of the Spatiotemporal GCRNN model for air pollution forecasting. We use PM\({}_{2.5}\) air pollutants as in the experiments of the ConvLSTM model [1]. The number of nodes of the input graph signals is 25 nodes (corresponding to 25 PM\({}_{2.5}\) monitoring stations). To prove the graph based model is better for spatial data, we also perform experiments with PM\({}_{10}\) air pollutants, which are observed by larger monitoring stations, 37 stations corresponding to 37 nodes of the input graph signals. The forecasting time-steps are similar to the paper [1], from 1 hour to 12 hours in the future. Fig. 5 shows RMSE metric values on testing data of the ConvLSTM model and Spatiotemporal GCRNN model with \begin{table} \begin{tabular}{|l|l|l|} \hline Statistic & _New dataset_ & Existing \\ \hline Time Period & _01/01/2015_ & 01/01/2015 \\ & \(\sim\) & \(\sim\) \\ & _12/31/2019_ & 09/30/2017 \\ \hline **Total Hours** & _43,824_ & 24,048 \\ \hline **Total Number of Data Samples** & _193,217,386_ & 110,468,780 \\ \hline **Air Pollution Data Samples** & _1,716,952_ & 937,872 \\ \hline Meteorology Data Samples & _753,326_ & 735,734 \\ \hline Traffic Volume Data Samples & _10,716,240_ & 5,955,072 \\ \hline Average Driving Speed Data Samples & _179,951,956_ & 102,761,187 \\ \hline China Air Pollution Data Samples & _78,912_ & 78,912 \\ \hline \end{tabular} \end{table} TABLE I: New Seoul dataset statistics and compared to the existing one PM\({}_{2.5}\) and PM\({}_{10}\) air pollution forecasting from 1 hour to 12 hours (smaller is better). The Spatiotemporal GCRNN model produces **slightly better performance in RMSE values** compare to the ConvLSTM model with PM\({}_{2.5}\) air pollution prediction but achieves **significant better results for PM\({}_{10}\) prediction**. These results claim that a graph-based method can capture more information from a larger and more complex structure than a image-based approach in the ConvLSTM paper [1]. Moreover, one advantage of the graph-based model is the smaller model size. The ConvLSTM model with 12 hours forecasting has the number of trainable parameters more than 20.5M parameters while the Spatiotemporal GCRNN model has only 371K parameters, a **55x smaller**. Hence, we can conclude that _the Spatiotemporal GCRNN model with a much smaller size than a ConvLSTM model can produce better performance for spatiotemporal air pollution forecasting_. Regarding comparing the performance of modeling the _spatiotemporal impact factors_ by ConvLSTM and Spatiotemporal GCRNN models, we use both _RMSE_ and _spRMSE_ metrics. We perform the experiments with the two types of input graph signals, air pollution only and air pollution with spatiotemporal impact factors, respectively. The performance results of Spatiotemporal GCRNN and ConvLSTM models are presented in Table 2. In the table, _ConvLSTM_ and _ConvLSTM_ + _All_ are ConvLSTM models without and with spatiotemporal impact factors data, _ST-GCRNN_ and _ST-GCRNN_ + _All_ are Spatiotemporal GCRNN models including only air pollution input data and including all spatiotemporal impact factors, respectively. All experiments are executed with PM\({}_{2.5}\) air pollution 1-hour ahead prediction (similar to experiments in [1]). The results reveal that a _Spatiotemporal GCRNN_ model obtains better performance in terms of RMSE and spRMSE metrics than a ConvLSTM model in both input data are air pollution only and air pollution with all spatiotemporal impact factors. Even compare to the best RMSE in [1] with ConvLSTM + Meteorology data, the ST-GCRNN model still achieves smaller RMSE value (5.5947 vs. 6.5809). In addition, the _Spatiotemporal GCRNN_ + _All_ has a _smaller spRMSE_ value than Spatiotemporal GCRNN without spatiotemporal impact factors. Therefore, we still recognize the efficacy of a GCN-based model in learning spatiotemporal factors for air pollution forecasting problems. ### _Performance comparisons with a GCN-based air pollution prediction model for long-term forecasting_ In this experiment section, we choose the model in [13] as our baseline for GCN-based air pollution forecasting comparisons. As pointed out in the related work section, the GCN-based model in [13] is a Hybrid model that includes a GCN model and an LSTM layer as our system but it separates them to two consequential steps while we combine two architectures into a unified system. We implement the _Hybrid model of GCN and LSTM_ from the paper [13] in Seoul data. This model includes three sequential layers, the first layer is a GCN model to extract spatial features of the input data, the second one is an LSTM model with input is the extracted spatial features and output is the learned temporal features, and the last layer is a fully connected (FC) layer to regress the predictions. We implement GCN and LSTM layers of the Hybrid model with the same hyper-parameters as in our Spatiotemporal GCRNN model. We also apply the same training and testing configurations as in section 4.1. The input graph signals of the Hybrid model are identical to our model. For performance comparisons of this Hybrid model with our proposal model, we conduct experiments for medium to long-term prediction time steps: forecasting 12, 24, and up to 72 hours in the future with both PM\({}_{2.5}\) and PM\({}_{10}\) air pollutants. Table 3 demonstrates the results on the same test set of _the Hybrid model_ and _Spatiotemporal GCRNN_ with PM\({}_{2.5}\) and PM\({}_{10}\) air pollution forecasting in 12, 24 and 72 hours ahead. Overall, our Spatiotemporal GCRNN model achieves better performance in PM\({}_{2.5}\) and PM\({}_{10}\) forecasting over the Hybrid model. In detail, our ST-GCRNN model obtains a larger gap of the performance in PM\({}_{2.5}\) forecasting than PM\({}_{10}\). The reason could be that the distributions of PM\({}_{2.5}\) air pollution values are more complicated than the PM\({}_{10}\) readings and our unified combination of GCN and GRU models can exploit the complex correlations of PM\({}_{2.5}\) air pollution better than sequential steps as in the Hybrid model. \begin{table} \begin{tabular}{|l|l|l|l|} \hline & \multicolumn{2}{c|}{Air pollution only} & \multicolumn{2}{c|}{With ST impact factors} \\ \hline Metric & ConvLSTM & ST- & ConvLSTM & ST-GCRNN \\ & & GCRNN & + All & + All \\ \hline spRMSE & 15.4872 & **14.9522** & 11.0254 & **10.9960** \\ \hline RMSE & 8.3147 & **5.5947** & 7.1703 & **5.5963** \\ \hline \end{tabular} \end{table} TABLE 2: Performance comparisons with spatiotemporal (ST) impact factors by ConvLSTM and Spatiotemporal GCRNN (ST-GCRNN) models on PM\({}_{2.5}\) with 2 metrics, spRMSE and RMSE (smaller is better). Fig. 5: Compare testing performance of ConvLSTM model (**ConvLSTM**) and Spatiotemporal GCRNN model (**ST-GCRNN**) for PM\({}_{10}\) and PM\({}_{2.5}\) air pollution forecasting from 1 to 12 hours in Seoul data (smaller is better). We prove the above assessment by doing statistical analysis for PM\({}_{2.5}\) and PM\({}_{10}\) air pollutants in Table IV. We compute the mean and standard deviation values for the following statistical measurements of the data: data points changing by time (which means the distribution of air pollution readings at each station over the time), and data points changing by locality (equals to the distribution of air pollution values over all stations in a city at a time). The statistic values are computed based on the [0-1] normalized data of PM\({}_{2.5}\) and PM\({}_{10}\) readings. From the table, the PM\({}_{2.5}\) air pollutant data has a higher standard deviation than the PM\({}_{10}\) regarding changing by time or by locality. It means the distribution of PM\({}_{2.5}\) values spreads around the mean value more than PM\({}_{10}\) data; thus, they need a more efficient architecture to learn their correlations. Regarding the less spreading PM\({}_{10}\) values, our model is still better the Hybrid model in 12, 24 and 72 hours forecasting. From these experiments' results, we can conclude that the tight integration of GCN and RNN models in Spatiotemporal GCRNN architecture learns the spatiotemporal air pollution data better than separated layers in a GCN-based hybrid approach. Furthermore, the number of trainable parameters of the Hybrid model is 518K parameters, a **1.5x** larger our model. ### Ablation study the effects of different GCN configurations To evaluate the effects of different GCN configurations toward the forecasting results, we experiment with the following parameters: \(K\)**-order** to explore the impact of the graph convolutional filter's receptive fields; weighted adjacency matrix \(W\)**threshold**\(\epsilon\) to vary the sparsity of \(W\); and the **graph convolution definitions** (spectral or diffusion graph convolution). The \(K\)**-order** determines the number of nearest neighbors of a node that will be considered as the filter's receptive fields in graph convolutional operation. When \(K\) increases, the size of receptive fields larger, and the graph can capture wider spatial dependency at the cost of increasing learning complexity and the training time. Fig. 6 shows the results with different \(K\) on the validate set. We observe that with the increase of K, the validation loss first quickly falls (\(K\) from 1 to 2), and then decreases slightly (\(K\geq 3\)), while the training time per epoch rises a lot. In this paper, we use \(K\) **= 2** as the default \(K\)-order value to balance between the validation loss and the training time. Regarding computing the weighted adjacency matrix \(W\), we use a **threshold**\(\epsilon\) to control the sparsity of \(W\). All weights less than \(\epsilon\) will be set to zero. A weighted edge equals to zero also means there is no relationship between two nodes of that edge. In graph based problems, \(W\) can be built using a thresholded Gaussian kernel [19]. \(W_{ij}=exp(-\frac{dist(v_{i},v_{j})^{2}}{\sigma^{2}})\) if \(dist(v_{i},v_{j})\leq\epsilon\), otherwise \(0\). \(dist(v_{i},v_{j})\) denotes the distance between 2 stations in station-level or 2 grid-cells in grid-level. \(\sigma\) is the standard deviation of distances and \(\epsilon\) is the threshold. In this paper, we experiment with three decreasing values of \(\epsilon\): 0.1, 0.01, and 0.0 (no threshold). From the experiments' results in Fig. 7, we can observe that when \(\epsilon\) decreases from 0.1 to 0.0, the validation loss decreases, but the training time for one epoch also goes up. Hence, we use \(\epsilon\) = \(\mathbf{0.01}\) as the default threshold in building the adjacency matrix for the graph since it has the trade-off between the validation errors and the training time. For the last ablation study, we explore the effects of **different graph convolution operators** such as _spectral convolution_ and _diffusion convolution_. The spectral convolution operation is implemented as in equation 5 while the diffusion convolution is performed following equation 6. From [9], the diffusion convolution implementation includes \begin{table} \begin{tabular}{|l|c c|c c|} \hline & \multicolumn{2}{c|}{PM\({}_{2.5}\)} & \multicolumn{2}{c|}{PM\({}_{10}\)} \\ \hline Statistical & Mean & Std. deviation & Mean & Std. deviation \\ \cline{2-5} measurement & &viation & & \\ \hline By time & 0.136927 & 0.091587 & 0.040974 & 0.031563 \\ \hline By locality & 0.136927 & 0.038279 & 0.040974 & 0.010903 \\ \hline \end{tabular} \end{table} TABLE IV: Statistical analysis of PM\({}_{2.5}\) and PM\({}_{10}\) air pollutants experimental data: Mean and Std. deviation (data is [0-1] normalized) \begin{table} \begin{tabular}{|l|l|l|l|} \hline & T & Hybrid model & _ST-GCRNN_ \\ \hline \multirow{3}{*}{PM\({}_{2.5}\)} & 12 hours & 9.1880 & **8.5074** \\ \cline{2-4} & 24 hours & 12.9689 & **10.1350** \\ \cline{2-4} & 72 hours & 14.1043 & **12.5671** \\ \hline \multirow{3}{*}{PM\({}_{10}\)} & 12 hours & 16.8503 & **16.8093** \\ \cline{2-4} & 24 hours & 19.7901 & **19.1588** \\ \cline{2-4} & 72 hours & 24.4862 & **24.4360** \\ \hline \end{tabular} \end{table} TABLE III: Performance comparisons between the Hybrid model, and Spatiotemporal GCRNN (ST-GCRNN) in PM\({}_{2.5}\) and PM\({}_{10}\) for 12, 24, and 72 hours air pollution forecasting. The metric is RMSE (smaller is better). Fig. 6: Effects of \(K\)-order values in Spatiotemporal GCRNN model. When K increases from 1 to 4, the Validation Loss decreases but the Training Time rises. two cases, the first is a _random walk diffusion_, and the second is a _dual random walk diffusion_ with the diagonal matrix \(D\) in equation 6 is split into 2 matrices: an out-degree diagonal matrix and an in-degree diagonal matrix. Fig. 8 shows RMSE values for these studying graph convolution operations with three time steps 1, 6, and 12 hours in PM\({}_{2.5}\) forecasting. As a results, the **dual random walk diffusion convolution** achieves a slightly better performance than other convolutional implementations. ## 5 Conclusion In this paper, we introduce a spatiotemporal GCN-based model for the citywide air pollution forecasting. The new proposal model named **Spatiotemporal Graph Convolutional Recurrent Neural Network** is a deep integration of a GCN model for spatial features extraction and an RNN model for temporal features learning. The Spatiotemporal GCRNN model has the size **55x smaller** than the state-of-the-art ConvLSTM model for air pollution forecasting but produces better results. Through a series of empirical experiments, we prove that our Spatiotemporal GCRNN model has better performance than the ConvLSTM model in short-term air pollution prediction, and also achieves superior results in medium to long-term air pollution forecasting compare to a GCN-based hybrid model that separates GCN and LSTM in discrete layers. Moreover, in this research, we expand the previous Seoul data from 3 years time period to a 5-year dataset (**75\(\%\) bigger**). We hope that this large-scale dataset will become a valuable data source for researchers in air pollution as well as spatiotemporal based research. We will public the new dataset along with this paper. In the future, we will enhance our research in the following directions: first, exploiting advanced graph convolution network models such as spatial-based graph convolution or graph attention networks to achieve better performance; second, due to the small size of the graph-based model, we can deploy the trained model to build real-time spatiotemporal forecasting for urban intelligent systems. ## Acknowledgments This work was supported by the New Industry Promotion Program (1415166913, Development of Front/Side CameraSensor for Autonomous Vehicle) funded by the Ministry of Trade, Industry Energy (MOTIE, Korea).
2302.10430
Interval Type-2 Fuzzy Neural Networks for Multi-Label Classification
Prediction of multi-dimensional labels plays an important role in machine learning problems. We found that the classical binary labels could not reflect the contents and their relationships in an instance. Hence, we propose a multi-label classification model based on interval type-2 fuzzy logic. In the proposed model, we use a deep neural network to predict the type-1 fuzzy membership of an instance and another one to predict the fuzzifiers of the membership to generate interval type-2 fuzzy memberships. We also propose a loss function to measure the similarities between binary labels in datasets and interval type-2 fuzzy memberships generated by our model. The experiments validate that our approach outperforms baselines on multi-label classification benchmarks.
Dayong Tian, Feifei Li, Yiwen Wei
2023-02-21T04:00:44Z
http://arxiv.org/abs/2302.10430v1
# Interval Type-2 Fuzzy Neural Networks for Multi-Label Classification ###### Abstract Prediction of multi-dimensional labels plays an important role in machine learning problems. We found that the classical binary labels could not reflect the contents and their relationships in an instance. Hence, we propose a multi-label classification model based on interval type-2 fuzzy logic. In the proposed model, we use a deep neural network to predict the type-1 fuzzy membership of an instance and another one to predict the fuzzifiers of the membership to generate interval type-2 fuzzy memberships. We also propose a loss function to measure the similarities between binary labels in datasets and interval type-2 fuzzy memberships generated by our model. The experiments validate that our approach outperforms baselines on multi-label classification benchmarks. Interval type-2 fuzzy logic, structured prediction, multi-dimensional labels, multi-label classification. ## I Introduction Multi-label classification (MLC) aims at predicting multiple labels by exploring the dependencies among labels. It has been widely used in natural language processing [10] and computer vision [40]. Classical MLC models make binary predictions. That is, they use 0 and 1 to indicate the categorizations. However, intuitively, human has fuzzy discrimination on an instance(Fig. 1). When categorizing these four images in Fig. 1, human observers may consider the semantic relationships between flowers or women in the images and hence they may give fuzzy estimations of their categories. For image (a), it apparently belongs to flower. For (b), someone may consider the woman is the main content while others may consider woman and flower are of the same importance. For (c), we human can make sure that the image belongs to the woman category and the flower is just a decoration. However, the flower occupies a considerably large area in the image. A MLC model may also consider that it belongs to flower category in certain degree. For (d), human observers' opinions may be contradictory again because someone may consider the woman holds the flower in front of her face so she probably want to show a special species of flower, while someone may consider that the flower is just an ordinary one and the main content of the image is still the woman. Almost in all datasets, instances are directly labeled by 0 or 1, which cannot effectively represent humans' fuzzy judgment. Interval type-2 fuzzy logic is capable of representing different human opinions on categorization. It is the motivation that we explore how to build a fuzzy-logic-based model for MLC. In uni-label classification, probability and type-1 fuzzy logic are a little bit confusing. Softmax is widely used in neural networks for uni-label classification. The output of softmax can be explained as the probability of an instance belonging to a category. Someone can "illegally" explain the probabilities as type-1 fuzzy memberships. If we are working on uni-label classification, there is few numerical difference between these two explanations. For example, we can explain Fig. 1 as this. The probability of the image (a) belonging to flower category is maximum, so the image is belonging to flower category. The membership of the image (b) belonging to woman category is maximum. If we must make a decision on which category it belongs to, we have to categorize the image into woman category. However, if we are interested in multi-label classifications, there is a key difference between probabilities and fuzzy logic. We should examine the joint probability (Fig. 2). Instead, we can explain the outputs of a neural network as type-1 fuzzy memberships. Although we give a reasonable explanation to the outputs, type-1 fuzzy logic is not fuzzy [36]. Hence, interval type-2 fuzzy logic is used here. We believe that the more categories an instance belongs to, the fuzzier its memberships are. Therefore, we use the number of its categories to control the fuzziness of its memberships (Fig. 2). By introducing interval type-2 fuzzy logic, we need design Fig. 1: Illustration of different types of labels. The labels in dataset are binary. Type-1 fuzzy labels may be generated from the judgment of a human expert. Type-2 fuzzy labels may be generated from the several human experts’ judgment. To visualize the feature extraction of a learning model, say convolutional neural network, we assume the extracted features are two-dimensional. The images’ features are plotted in the feature space. the loss function of the classifier to measure the dissimilarities between interval type-2 fuzzy labels and binary labels. The overall scheme of our model is illustrated in Fig. 3. The following of this paper is organized as follows. In Section II, related works are briefly reviewed. The preliminaries are given in Section III. The formulation of our models is shown in Section IV. In Section V, we report the experimental results of our method. The conclusive remarks are given in Section VI. ## II Related Works An intuitive way for MLC is using classifier chains [30] which decomposes a multi-label classification into a series of binary classifications. The subsequent binary classifiers are built on the prediction of preceding ones. Recurrent neural networks (RNN) and convolutional neural networks (CNN) are used in classifier chains [40]. The MLC can be also transformed to a label ranking problem. Label ranking based methods use \(L(L-1)/2\) binary classifiers for pairwise comparisons between each label pair [17]. Wang _et al._[43] proposed an efficient learning algorithm for solving multi-label ranking problem which is used to model facial action unit recognition task. Random \(k\)-Labelsets [37][42] methods build multi-class sub-models on random subsets of labels, and then learn single-label classifier for the prediction of each element in the powerset of this subset. Lo _et al._[26] proposed a basis expansions model for MLC. The basis function is a label powerset classifier trained on a random \(k\)-labelset. The authors derive an analytic solution to learn the expansion coefficients which minimize the error between the prediction and the groundtruth. Mutual information is incorporated to evaluate the redundancy level and imbalance level of each \(k\)-labelset [41]. K-nearest neighbor (KNN), another classical machine learning method, is combined with maximum a posteriori (MAP) principle to determine the label set of an unseen instance [49]. Dimension reduction methods can be also used for MLC [6][11][21]. Xu _et al._[45] proposed a probabilistic class saliency estimation approach for calculating the projection matrix in linear discriminant analysis for dimension reduction. Decision tree can be built recursively based on a multi-label-entropy based information gain criterion [14]. A set of support vector machines can be optimized to minimize an empirical ranking loss for MLC [16]. The correlation labels can be encoded as constrains for MLC [19]. Aligning embeddings of data features and labels in a latent space is a popular trend in MLC. Yeh _et al._[46] use canonical correlation analysis to combine two autoencoders for features and labels to build a label-correlation sensitive loss function. However, the learned latent space is not smooth so small perturbations can lead to totally different decoding results. Similar decoded targets cannot be guaranteed even though the embeddings of features and labels are close in the latent space [2]. Bai _et al._[2] substitute the autoencoders with variational autoencoders so the deterministic latent spaces become probabilistic latent spaces. KL-divergence is used to align the Gaussian latent spaces and the sampling process enforces smoothness. Sundar _et al._[33] adopt the \(\beta\)-VAE for similar purposes. These methods assume a uni-modal Gaussian latent space, which may cause over-regularization and posterior collapse [15][44]. Li _et al._[25] proposed a deep label-specific feature learning model to bind the label and local visual region in images and they use two variant graph convolutional networks to capture the relationships among labels. Tan _et al._[34] link the manifolds of instance and label spaces, which facilitates using topological relationship of the manifolds in the instance space to guide the manifold construction of the label space. Modeling label correlation is another popular research area in MLC. Structured prediction energy networks (SPENs) [3][4] optimize the sum of local unary potentials Fig. 2: The differences among probabilities, type-1 fuzzy logic and interval type-2 fuzzy logic. Suppose we have \(L\) categories. In the multi-label classification case, we examine the joint probabilities of all elements in the _label powerset_ which is defined as a set of all possible label combinations. Hence, there are \(2^{L}\) label combinations. If we directly explain the output of the classifier as type-1 or type-2 fuzzy predictions, we only need to examine \(L\) fuzzy memberships. and a global potential are trained with a SVM loss. However, the alternating optimization approach suffers from instabilities during training. Tu _et al._[38] proposed several strategies to stabilize the joint training of structured prediction of SPENs. The deep value network (DVN) [20] trains a similar energy network by fitting the task cost function. Zhang _et al._[48] proposed cross-coupling aggregation strategy to simultaneously exploit the label correlation and handle class-imbalance issue. Ma _et al._[27] assume the instances can be clustered into different groups so that the label correlations can be modeled within each sub-group. Input convex neural networks (ICCNs) [1] design potentials which are convex with respect to the labels so that inference optimization will be able to reach global optimum. Bi _et al._[7] use a probabilistic model exploiting the multi-label correlations. Lanchantin _et al._[24] propose label message passing (LaMP) neural networks for MLC. LaMP treats labels as nodes on a label-interaction graph and computes the hidden representation of each label node conditioned on the input using attention-based neural message passing. Chen _et al._[12] adopt graph convolutional network (GCN). Each node on the graph is represented by word embeddings of a label. The GCN is learned to map this label graph into a set of inter-dependent object classifiers. These classifiers are applied to the image descriptors extracted by another sub-net, enabling the whole network to be end-to-end trainable. Zhang _et al._[50] predict labels using a deep neural network in a way that respects the set structure of the problem. Patel _et al._[29] exploit the taxonomic relationships among labels using box embeddings [39]. Brukhim _et al._[9] use cardinality [35] of labels as constraints for training the classifier. ## III Preliminaries We consider the setting of assigning \(L\) labels \(\mathbf{y}=(y_{1},\ldots,y_{L})\) to an input \(\mathbf{x}\in\mathbb{R}^{d}\), where \(d\) is the dimension of instance features. The true label (which is binary) of \(\mathbf{x}\) is denoted as \(\mathbf{y}^{*}\). The fuzziness of \(\mathbf{y}\) is controlled by fuzzifier \(\underline{m}\) and \(\overline{m}\). That is, \(\mathbf{x}\) is belonged to the \(i\)-th category in a degree of \([y_{i}^{\underline{m}},y_{i}^{\overline{m}}]\). Almost all datasets provide binary labels. To compute the metrics for comparison, we will generate binary predicted labels \(\hat{\mathbf{y}}\) based on \(\mathbf{y}\). \(\hat{\mathbf{y}}\)'s are the final predictions of our model. The notations are listed in Table I. ## IV Formulation In this section, we will explain our models in details. There are three main components in our model. First, there is a deep neural network used as a fuzziness initializer to generate Fig. 3: The scheme of our method. The input data are used to train two neural networks, a fuzziness initializer and a fuzzifier estimator. The fuzziness initializer is used to generate type-1 fuzzy labels. The output of the bottleneck of the autoencoder is used as an input of a fuzzifier estimator. The estimated fuzzifiers are incorporated into type-1 fuzzy labels to generate interval type-2 fuzzy labels. Then, we design a loss function to measure the dissimilarities between binary labels in original dataset and generated interval type-2 fuzzy labels. The loss function is used to train the parameters of the fuzziness initializer. Finally, the interval type-2 fuzzy labels are defuzzified to binary predictions. All metrics in our experiments are computed based the binary predictions and groundtruth binary labels. initial labels. Second, we use another network to predict the fuzzifier \(\underline{m}\) and \(\overline{m}\). Third, we design an algorithm to compare the interval type-2 labels and binary labels. ### _Fuzziness initializer_ Indeed, we can use any classical classification neural networks as our fuzziness initializer. The key difference is the activation functions of output layers. To generate the initial guess of fuzzy membership value, we should use an activation function whose value ranges from 0 to 1. Rather than using Sigmoid function which may cause gradient vanishing and slow convergence, we use the following activation function: \[\begin{cases}g(\mathbf{x})=0.5+\alpha\left(\mathbf{w}^{\top}\mathbf{x}- \frac{1}{L}\left(\mathbf{1}^{\top}\mathbf{x}+\mathbf{1}^{\top}\mathbf{w} \right)\right)\\ f(\mathbf{x})=\max\left(0,\min\left(1,g(\mathbf{x})\right)\right),\end{cases} \tag{1}\] where \(L\) is the dimension of vector \(\mathbf{x}\) or \(\mathbf{w}\), and \(\alpha\) is a learned parameter which is initially set as \(1\). \(\frac{1}{L}(\mathbf{x}+\mathbf{w})\) can be treated as bias term of the neuron. Eq. (1) is similar to the idea of Batch Normalization (BN) [23]. BN learns two parameters \(\beta\) and \(\gamma\) in \[\tilde{\mathbf{Z}}=\beta\mathbf{Z}+\gamma, \tag{2}\] to standardize mini-batches, where \(\mathbf{Z}\) is the output of one layer and \(\tilde{\mathbf{Z}}\) is the output of BN. \(\gamma\) in Eq. (2) is expected to be a constant vector. However, when the neural network is trained by mini-batch, it is impossible for \(\gamma\) to hold constant. Hence, for each neuron, we minus the means of \(\mathbf{x}\) and \(\mathbf{w}\). The bias term of each neuron can vary according to mini-batched data. What Eq. (1) really learns is a proper weight \(\mathbf{w}\) that makes \(\mathbf{w}^{\top}\mathbf{x}\) can be centered by \(\frac{1}{L}\left(\mathbf{x}+\mathbf{w}\right)\). \(0.5\) in Eq. (1) is used to shift the zero-centered outputs to 0.5-centered so that we can use \(f(\mathbf{x})\) to generate values in interval \([0,1]\). \(\alpha\) in Eq. (1) is similar to \(\beta\) in Eq. (2). It is used to change the standard deviation of outputs to approximately 1. Therefore, Eq. (1) can avoid gradient vanishing as BN. ### _Fuzzifier Estimator_ Fuzziness estimator is used to estimate the fuzzifier of predicted labels, i.e. \(\overline{m}\) and \(\underline{m}\). As we discussed above, the fuzziness is related to the number of categories an instance belongs to, i.e. \(|y^{*}|\). Hence, we use another neural network to predict \(|y^{*}|\). We denote the prediction of \(|y^{*}|\) as \(\hat{m}\) hereafter. To estimate \(\hat{m}\), firstly, we train an autoencoder. Then, we train a constrained linear regression model on the outputs of the bottleneck of the autoencoder to estimate \(\hat{m}\) (Fig. 3). We add a softmax layer on the bottleneck of the autoencoder and we add a cross-entropy to the object function of the autoencoder: \[\begin{split}\operatorname*{arg\,min}_{\Theta_{e},\Theta_{d}}& \left\|x-h\left(h\left(\mathbf{x};\Theta_{e}\right);\Theta_{d} \right)\right\|_{F}^{2}\\ &+\eta CE\left(S\left(h\left(\mathbf{x};\Theta_{e}\right),l \right)\right),\end{split} \tag{3}\] where \(h(\mathbf{x},\Theta_{e})\) is the function of encoder, \(h(\mathbf{x},\Theta_{d})\) is the function of decoder, \(CE\) is cross entropy function, \(S\) is the Softmax layer and \(\eta\) is a tuned parameter. \(l\) is an one-hot vector which indicates the number of categories an instance belongs to. If the \(i\)-th element of \(l\) is non-zero, it indicates that the instance belongs to \(i\) categories. For example, if the original label of an instance is \([0,1,0]\), its \(l\) is \([1,0,0]\) which indicates the instance only belongs to one category. If the original label of an instance is \([1,0,1]\), its \(l\) is \([0,1,0]\) which indicates the instance belongs to two categories. The reason why we do not directly train a classification neural network to predict \(l\) is that we want to de-correlate the neural networks we used for predicting \(y\) and \(l\). This idea comes from Random Forest which randomly chooses subsets of variables to construct trees so that these trees are less correlated. The Random Forest increases the bias of the model while decreases the variance of the model. In our model, although \(y\) and \(l\) are different supervision information, they are correlated to each other. Furthermore, the neural networks have the ability of predicting \(y\) or \(l\) using a few layers close to the output, even when the inputs are the same. That is, if we use the same random seed and structure for two deep neural networks that predict \(y\) and \(l\) respectively, they may only significantly differ in 1 or 2 layers close to the output. Using autoencoder, the data themselves are another "supervision" information for training so that those two neural networks are possible to be more de-correlated. After the autoencoder is trained, we use the bottleneck's outputs to train a simple linear regression model. The label is the number of categories an instance belongs to, i.e. \(|y^{*}|\). We use the output of the linear regression model as \(\hat{m}\). We set \(\underline{m}=\hat{m}/|y^{*}|\) and \(\overline{m}=\hat{m}/L\). Note that \(|y^{*}|\leq L\) and \(0\leq y\leq 1\). Therefore, \(\underline{m}\geq\overline{m}\) and \(y^{\underline{m}}\leq y^{\overline{m}}\). For a special case when \(\overline{m}=\underline{m}\), the fuzzifier estimator believes the instance only belongs to one category. There is no fuzziness at all in this case. ### _Loss Function_ Traditional loss functions for structured learning can be cross entropy, \(F_{1}\) measure, etc. Our model generates interval type-2 fuzzy labels for data. However, the real labels for the data are generally binary. Hence, we should make a judgment on the differences between the predicted labels \(\mathbf{y}\) and real labels \(\mathbf{y}^{*}\). An intuitive way is using the middle point of each interval \([y_{\overline{m}}^{\overline{m}},y_{\overline{i}}^{\overline{m}}]\). Then, the traditional loss functions can be applied. The problem is that two different intervals may have the same middle point. For example, \([0.3,0.6]\) and \([0.4,0.5]\) have the same middle point \(0.45\). This way cannot sufficiently utilize the fuzziness information. We design our loss function based on the continuous extension of \(F_{1}\) measure [20]: \[E\left(\mathbf{y},\mathbf{y}^{*},\underline{m},\overline{m}\right)=-\frac{2 \mathbf{y}^{\underline{m}^{\top}}\mathbf{y}^{*}}{\mathbf{1}^{\top}\left( \mathbf{y}^{\underline{m}}+\mathbf{y}^{*}\right)}-\frac{2\mathbf{y}^{ \overline{m}^{\top}}\mathbf{y}^{*}}{\mathbf{1}^{\top}\left(\mathbf{y}^{ \overline{m}}+\mathbf{y}^{*}\right)} \tag{4}\] ### _Defuzzification_ To compute the metrics for comparing different methods. We eventually have to generate binary prediction of labels. That is, we have to determine an instance belongs to which categories based on their fuzzy memberships. Suppose we use the middle point of an interval for defuzzification. Then, we just need to sort the middle points, and set top \([\hat{m}]\)\(y_{i}\)'s as 1 and the remaining \(y_{i}\)'s as 0, where \([\cdot]\) rounds \(\cdot\) to the closest integer. The problem is, as we discussed above, the middle point cannot fully utilize the information of interval type-2 fuzzy logic. Here, we use a linear combination between middle point and interval size for defuzzification, i.e. \[\bar{y}=\frac{y^{\overline{m}}+y^{\underline{m}}}{2}-\frac{\lambda}{2}\left(y^ {\overline{m}}-y^{\underline{m}}\right), \tag{5}\] where \(\lambda\) is positive constant which is set as 0.1 in our experiments. Finally, we sort the elements in \(\bar{y}\), and set the top \([\hat{m}]\) elements as 1 and the remaining elements as 0 to generate final prediction \(\hat{y}\). ### _Implementation Details_ Fuzziness initializers can be any classification neural networks as long as their output layers can be written as an activation imposing on a linear combination of weights and inputs. We use \(\mathcal{B}=\{b_{i}\},i=1,\ldots\) to represent the set that contains all such neural networks. \(b_{i}\) is a single candidate neural network that can be used as our fuzziness initializer. We can directly substitute the activation function of the output layer of \(b_{i}\) with Eq. (1). Otherwise, if we want to directly use the pre-trained weights, we can add an additional layer with activation function Eq. (1) on the top of the output layer of \(b_{i}\). For computational efficiency, we do not have to train the autoencoder separately. We can use several layers of the fuzziness initializer \(b_{i}\) as the encoder, build a symmetric neural network as decoder and freeze all other parameters. Let us take VGG16 [32] as an example. VGG16 is a convolutional neural network for image classification. We can freeze all the parameters of convolutional layers. Then we use the full-connected layers as encoder and build a symmetric full-connected layers as decoder. Thus, the input data \(\mathbf{x}\) of autoencoder in Eq. (3) is actually the outputs of convolutional part or the inputs of full-connected part of VGG16. The rationale of this is illustrated in Fig. 4. Note that in the view of signal processing, convolution in time domain is multiplication in frequency domain. One can use Fourier Transform to compute the spectrum of a time-domain signal. In Fig 4, both of the fuzziness initializer and the fuzzifier estimator can use the same vector for their own predictions. For convolutional neural networks, such as VGG16, we treat the convolutional part as feature extraction. Fuzziness initializer and fuzzifier estimator share the features. Thus, after we trained the fuzziness initializer, we can freeze the feature extraction part. On the other hand, we can directly use pretrained deep neural networks to extract feature vectors from raw data. In this way, deep full-connected neural networks of several layers can be used both for the fuzziness initializer and the fuzzifier estimator. ## V Experimental Results ### _Benchmarks_ We evaluate our method on three widely-used multi-label datasets, _scene_[8], _mirflickr_[22] and _nus-wide_[13]. These datasets are publicly available1. The statistics of these three datasets are given in Table II. We randomly separate _nus-wide_ dataset into training (80%), validation (10%) and testing (10%) splits and use the original splits of _scene_ and _mirflickr_ datasets. To eliminate the effects of feature extraction neural networks, we directly use extracted features rather than raw images. For _scene_ and _mirflickr_ datasets, there is only one option on features in the download links. For _nus-wide_ dataset, we select the 128D-cVALD features. Footnote 1: _scene_ and _nus-wide_ datasets with 128D-cVALD features are available at [http://mula.sourceforge.net/datasets-mlc.html](http://mula.sourceforge.net/datasets-mlc.html). _mirflickr_ dataset is available at [https://github.com/JunwenBaik-gmvae](https://github.com/JunwenBaik-gmvae). ### _Baselines_ We compare our methods to ASL [31], RBCC [18], MPVAE [2], LaMP [24], C2AE [46], SLEEC [6], HARAM [5], MLKNN [49] and BR [47]. ASL uses an asymmetric loss for positive and negative samples so that easy negative samples can be dynamically down-weighted. RBCC learns a Bayesian network to condition the prediction of child nodes only on their parents in order to circumvent the unprinciped ordering in classical recurrent classifier chains [28]. MPVAE learns and aligns probabilistic embedding for labels and features. LaMP uses attention-based neural message passing to compute the hidden representation of label nodes of a label-interaction graph to learn the interactions among labels. C2AE adopts autoencoders to embedding data and labels in a latent space. SLEEC assumes the label Fig. 4: Illustration of training fuzzifier estimator. When Chord C is played, the three pressed keys have a spectrum like the second row. If 7 band-pass filters are used to detect which of the 7 white keys in an octave are pressed, the filters’ spectrum will look like the third row. Finally, we examine the output of these 7 filters. The filters that have significant outputs are denoted as 1 and others are denoted as 0. We will get the a binary vector at the fourth row. The fuzziness initializer identifies which chord is played, while the fuzzifier estimator only counts how many keys are pressed, which is equivalent to compute the \(l_{0}\)-norm of filters’ outputs. matrix is low-rank so embedding the label in low-dimensional space can improve the prediction accuracy. HARAM adds an extra ART layer to fuzzy adaptive resonance associative map neural network to increase the classification speed. MLKNN first finds the k-nearest neighbors of an instance and then uses maximum a posteriori principle to determine the label set. BR decomposes the multi-label classification into independent binary classifications. ### _Evaluation_ We evaluate our method using four metrics, i.e. Example F1, Micro-F1, Macro-F1 and Hamming Accuracy (HA). We denote true positives, false positives and false negatives by \(TP_{j}\), \(FP_{j}\) and \(FN_{j}\), respectively for the \(j\)-th of \(L\) label categories. HA is defined as \[\frac{1}{L}\sum_{j=1}^{L}\mathbb{1}\left[\hat{y}_{j}=y_{j}^{*}\right], \tag{6}\] where \(\mathbb{1}[\cdot]\) is an indicator function which equals to 1 if the condition is true otherwise equals to 0. Example-F1 is defined as \[\frac{2\sum_{j=1}^{L}\hat{y}_{j}y_{j}^{*}}{\sum_{j=1}^{L}y_{j}+y^{*}j}. \tag{7}\] Micro-F1 is defined as \[\frac{\sum_{j=1}^{L}tp_{j}}{\sum_{j=1}^{L}2tp_{j}+fp_{j}+fn_{j}}. \tag{8}\] Macro-F1 is defined as \[\frac{1}{L}\sum_{j=1}^{L}\frac{2tp_{j}}{2tp_{j}+fp_{j}+fn_{j}}. \tag{9}\] ### _Results and discussion_ The results are given in Table III and Table IV. Our method outperforms the existing state-of-the-art methods on all datasets. The best numbers are marked in bold. All the numbers of our method are averaged over 5 random seeds. For example-F1, the best results of compared methods are among MPVAE, ASL and RBCC. Our method improves over the best compared method by 1.6%, 4.3% and 3.2% on _scene_, _mirflickr_ and _nus-wide_, respectively. For micro-F1 and macro-F1, the best results of compared methods are between MPVAE and ASL. For micro-F1, our method improves over the best compared one by 2.4%, 5.4% and 5.3% on _scene_, _mirflickr_ and _nus-wide_, respectively. For macro-F1, our method improves over the best compared one by 0.9%, 5.5% and 9.5% on _scene_, _mirflickr_ and _nus-wide_, respectively. For HA, the best results of compared methods are among LaMP, MPVAE and ASL, our method improves over the best one by 0.5%, 1.1% and 0.6% on _scene_, _mirflickr_ and _nus-wide_, respectively. ### _Ablation studies_ To demonstrate the effectiveness of interval type-2 fuzzy logic used in our method, we modify our method by type-1 fuzzy logic. Eq. (4) is modified as \[E(y,y^{*})=-\frac{2y^{\top}y^{*}}{\mathbb{1}^{\top}(y+y^{*})}. \tag{10}\] For defuzzification, we directly use \(\mathbb{1}[y_{j}\geq 1/\tilde{L}]\). The results on three datasets are given in Table V. In Table V, example-F1, micro-F1 and macro-F1 are abbreviated as ex-F1, mi-F1 and ma-F1, respectively. The interval Type-2 fuzzy logic substantially improves the performance over type-1 fuzzy logic. \(\eta\) in Eq. (3) and \(\lambda\) in Eq. (5) are two important hyperparameters in our model. \(\eta\) controls the weight of cross entropy. In Eq. (3), both of mean squared error and cross entropy can be independently used as an objective function for training a neural network. We set \(\eta\) as 1 in all our experiments. Our model is robust to \(\eta\). However, with large \(\eta\), one should be careful with the choice of learning rate. Our model is relatively sensitive to \(\lambda\). In Fig. 5, we show the performance of our model in different \(\lambda\) settings. In Fig. 5, \[\Delta M=M_{best}-M_{current}. \tag{11}\] \(M\) stands for a metric, i.e. exmaple-F1, micro-F1, macro-F1 or HA. \(M_{best}\) stands for the best metric among all experiments of different \(\lambda\) settings. \(M_{current}\) stands for metric corresponding to current \(\lambda\) setting. Hence, all the values of \(\Delta M\) are no greater than 0. From Fig. 5, we found the best \(M\)'s are generally achieved at \(\lambda=0.1\sim 0.2\) and occasionally at \(\lambda=0\). When \(\lambda=0\), Eq. (5) degrades to classical defuzzification, i.e. the middle point of the interval. When \(\lambda\) gets larger, say exceeding \(0.3\), the performance drops dramatically. This phenomenon is reasonable. The size of the interval should not dominate the prediction. For example, given two intervals \([0.4,0.5]\) and \([0.5,0.9]\), although the latter interval has a larger size, it still implies the classifier is more confident on the prediction, because all the numbers in the latter interval is no less than those in the former one. ## VI Conclusion In this paper, we proposed a multi-label classification method using interval type-2 fuzzy logic. Two neural networks are used for fuzziness intializer and fuzzifier estimation. The fuzzifier estimation neural network is supervised by the number of categories an instance belongs to and its prediction is used to generate interval type-2 fuzzy labels. A loss function measuring the dissimilarities between interval type-2 fuzzy labels and binary labels were proposed for training the fuzziness intializer. Finally, a defuzzification method is proposed to generate binary labels from interval type-2 fuzzy labels for metric computations. Experiments on widely-used datasets validate the better performance of our methods to the compared state-of-the-art methods. Future works include modeling hierarchical relations among labels using interval type-2 fuzzy logic and extending the proposed method to multi-modal multi-label classification task.
2310.08708
Polynomial Time Cryptanalytic Extraction of Neural Network Models
Billions of dollars and countless GPU hours are currently spent on training Deep Neural Networks (DNNs) for a variety of tasks. Thus, it is essential to determine the difficulty of extracting all the parameters of such neural networks when given access to their black-box implementations. Many versions of this problem have been studied over the last 30 years, and the best current attack on ReLU-based deep neural networks was presented at Crypto 2020 by Carlini, Jagielski, and Mironov. It resembles a differential chosen plaintext attack on a cryptosystem, which has a secret key embedded in its black-box implementation and requires a polynomial number of queries but an exponential amount of time (as a function of the number of neurons). In this paper, we improve this attack by developing several new techniques that enable us to extract with arbitrarily high precision all the real-valued parameters of a ReLU-based DNN using a polynomial number of queries and a polynomial amount of time. We demonstrate its practical efficiency by applying it to a full-sized neural network for classifying the CIFAR10 dataset, which has 3072 inputs, 8 hidden layers with 256 neurons each, and over million neuronal parameters. An attack following the approach by Carlini et al. requires an exhaustive search over 2 to the power 256 possibilities. Our attack replaces this with our new techniques, which require only 30 minutes on a 256-core computer.
Adi Shamir, Isaac Canales-Martinez, Anna Hambitzer, Jorge Chavez-Saab, Francisco Rodrigez-Henriquez, Nitin Satpute
2023-10-12T20:44:41Z
http://arxiv.org/abs/2310.08708v1
# Polynomial Time Cryptanalytic Extraction of Neural Network Models ###### Abstract Billions of dollars and countless GPU hours are currently spent on training Deep Neural Networks (DNNs) for a variety of tasks. Thus, it is essential to determine the difficulty of extracting all the parameters of such neural networks when given access to their black-box implementations. Many versions of this problem have been studied over the last 30 years, and the best current attack on ReLU-based deep neural networks was presented at Crypto'20 by Carlini, Jagielski, and Mironov. It resembles a differential chosen plaintext attack on a cryptosystem, which has a secret key embedded in its black-box implementation and requires a polynomial number of queries but an exponential amount of time (as a function of the number of neurons). In this paper, we improve this attack by developing several new techniques that enable us to extract with arbitrarily high precision all the real-valued parameters of a ReLU-based DNN using a polynomial number of queries _and_ a polynomial amount of time. We demonstrate its practical efficiency by applying it to a full-sized neural network for classifying the CIFAR10 dataset, which has 3072 inputs, 8 hidden layers with 256 neurons each, and about 1.2 million neuronal parameters. An attack following the approach by Carlini et al. requires an exhaustive search over \(2^{256}\) possibilities. Our attack replaces this with our new techniques, which require only 30 minutes on a 256-core computer. Keywords:ReLU-Based Deep Neural Networks Neural Network Extraction Polynomial Query and Polynomial Time Differential Attack. ## 1 Introduction In this paper, we consider the problem of extracting all the weights and biases of a Deep Neural Network (DNN), which is queried as a black box to obtain the outputs corresponding to carefully chosen inputs. This is a long-standing open problem that was first addressed by cryptographers and mathematicians in the early nineties of the last century [1, 2], and then was followed up one decade later by an adversarial reverse-engineering attack presented by Lowd and Meck in [1]. More recently, since around 2016, this problem has enjoyed a steady stream of new ideas by research groups from both industry and academia [OMR23,JCB\({}^{+}\)20, RK20,BBJP19,TZJ\({}^{+}\)16], culminating with an algorithm that Carlini, Jagielski and Mironov presented at Crypto 2020 [CJM20], which in the general case, requires a polynomial number of queries but an exponential amount of time. Due to this time complexity, their algorithm was practically demonstrated only on some toy examples in which the layers of the showcased networks (beyond the first hidden layer, which is usually easy to extract) contain at most a few tens of neurons. The main obstacle that made the Carlini et al. algorithm exponential in time was their inability to determine one bit of information (namely, a \(\pm\) sign) about each neuron in the DNN. This hindrance forced them to use exhaustive search over all the possible sign combinations in each layer, which is prohibitively expensive for any realistic network whose width is more than a few tens of neurons. Our main contribution in this paper is to show how to efficiently find these signs by a new chosen input attack, which we call _neuron wiggling_, as well as two other methods that target the first two hidden layers and the last one. Our techniques resemble a combination of first-order and second-order differential cryptanalysis, in which we use a chosen input attack to slightly change the inputs to the DNN in a small number of carefully chosen directions and observe both the slope and the curvature produced in the output of the network as a result of these input changes. However, it differs from standard differential attacks on digital cryptosystems by using real-valued inputs and outputs rather than bit strings. We demonstrate the practical applicability of our algorithm by performing a sign-recovery attack on a DNN trained to recognize the standard CIFAR10 classes. This DNN has 3072 inputs, 8 hidden layers, 256 neurons per hidden layer, and about 1.2 million weights. Our techniques replaced the exhaustive search over \(2^{256}\) possible combinations of neuronal signs carried out by Carlini et al. in each layer by a new algorithm which requires only 32 minutes on a 256-core computer to find all the \(8\times 256\) neuronal signs in the 8 layers of the network. Our model of deep neural networks is essentially the same as the one used by Carlini et al.. We assume that the network is fully connected (with no skip connections), with \(r\) hidden layers of varying width in which each neuron consists of an affine mapping followed by Rectified Linear Units (ReLU) activation functions. For the sake of simplicity in the analysis of our algorithm, we assume that all the network weights are real numbers, that arithmetic operations over real numbers (both by the network and by the attacker) are carried out with infinite precision in unit time, and that the attacker can perform arbitrarily small changes in the inputs of the network and observe their corresponding outputs with arbitrarily high precision. In practice, it was sufficient to use standard 64-bit floating point arithmetic to extract the full-sized CIFAR10 network, but higher precision may be required to attack considerably deeper networks due to the possible accumulation of rounding errors throughout our computations. However, since our algorithm uses only polynomially many arithmetic opera tions, we expect the asymptotic number of bits of precision to also grow only polynomially with the size of the network. In our attack (as well as the one by Carlini et al.), it is essential to assume that the activation function is ReLU-like since we concentrate on the behavior of the network in the vicinity of _critical points_, which are defined as inputs in whose tiny vicinity exactly one ReLU input in one of the layers changes sign. Regardless of the complexity of the network, we expect the network's output to abruptly change its behavior as a result of this ReLU transition, which makes this event noticeable when we observe the network's outputs. Such abrupt changes are also visible when we apply a smooth softmax function to the logits, and thus, our attack can use outputs which are either the logits produced by the last linear layer or their softmax values (which translate the logits into a probability distribution over the possible classes). We can generalize the attack to any other type of activation function that looks like a piecewise linear function (with possibly more than one sharp bend), such as a leaky ReLU, but not to smooth activation functions such as a sigmoid which have no critical points. Our attack can be applied without modifications to convolutional networks since they can be described as a special form of a fully connected network. While our analysis and experiments support our claim of efficiency in the extraction of the weights of large networks, there are several important caveats. First of all, fully connected networks have certain symmetries which make it impossible to extract the exact form of the original network, but only a functionally equivalent form. For example, we can reorder the neurons of any layer and adjust the weights accordingly, we can merge two neurons that have exactly the same weights and biases, we can eliminate any neuron whose output is multiplied by a weight of zero by all the next layer neurons, or we can multiply all the weights (including the bias) of a particular neuron by some positive constant \(c\) while multiplying all the weights which multiply the output of that neuron in the next layer neurons by \(c^{-1}\); all these changes do not change the input/output behavior of the network, and thus they are invisible to any black-box attack. In addition, there could be some unlucky events, which we do not expect to encounter but which will cause our attack to fail. For example, there could be neurons whose values before the ReLU almost never change sign, and thus our bounded number of queries will fail to detect any critical point for them.3 Finally, during the attack, we may fail to solve some systems of linear equations if their determinant is exactly zero, but even the slightest change in the real-valued entries in such a matrix should eliminate the problem. We thus have to qualify our assertion that our attack always succeeds, in the same way that most cryptanalytic attacks on cryptosystems are in fact heuristics that are not guaranteed to succeed in some particularly unlucky situations. It is important to note that when the attacker is only given an (adversarially chosen) collection of known inputs along with their corresponding outputs, then a famous result of Blum and Rivest back in 1993 [1] shows that just to decide whether there exists a 2 layer 3 neuron DNN on \(n\) inputs which is consistent with the provided pairs is NP-complete. However, in our case, the attacker can apply a chosen input attack, and thus he is not likely to suffer from this particular complexity barrier. ### Our Contributions Building on the work of [10], we present a black-box attack that permits the recovery of a functionally equivalent model of a deep neural network that uses ReLU activation functions. In contrast with the approach presented in [10], our attack has polynomial time complexity in terms of the number of neurons in the DNN, and can thus be applied (in principle) to arbitrarily deep and wide neural networks. In addition, we can easily deal with many types of expanding neural networks, where [10] struggles. To make this possible, we develop three new sign recovery techniques. The first one, called _SOE_, is based on solving a system of linear equations derived from observed first derivative values. The _Neuron Wiggle_ method applies differences in the input to maximally change the value of the neuron of interest. These changes propagate to the output and a statistical analysis of the output variations allows recovery of the sign. Finally, the _Last Hidden Layer_ technique is applicable only to the last layer in the network and employs second-order derivatives to construct a different system of linear equations whose solution simultaneously yields the signs of all the neurons in this layer. We showcase our findings with a practical sign-recovery attack against a 3072-input network with 8 hidden layers and \(d=256\) neurons per hidden layer for classifying the CIFAR10 dataset. ### Overview of our Attack Our attack follows the same strategy as the one presented in [10] by Carlini et al. Namely, we recover the parameters (i.e., weights and bias of each neuron) for the first hidden layer and "peel off" that layer. Thus, the attack now reduces to extracting the parameters of a DNN with one less hidden layer. We then recover the parameters for the second layer, peel it off, and continue in this fashion until the last hidden layer. Finally, the parameters for the output layer1 are obtained. After peeling off the first hidden layer, however, we no longer have full control of the input to the second layer since the first layer is not an invertible mapping (e.g., no negative numbers can be output by its ReLUs). This lack of control over the input to the layer is also true for all subsequent hidden layers. Recovering the parameters of each hidden layer is done in two steps. First, for each neuron, we recover some multiple of its weights and bias. The sign of this unknown multiplicative factor is called the _sign for the neuron_. In the second step, we find the signs for all the neurons in the current layer; we need them to find the actual mapping represented by this layer in order to peel it off and proceed to the next layer. Recovering signs is essential because multiplication by a positive constant is a symmetry of the network, but multiplication by a negative constant is not a symmetry due to the nonlinear behavior of the ReLU. To find the multiple of the parameters, we use the same techniques as in [14, Sections 4.2 and 4.3.2]. To recover the sign for the neurons in the general case, Carlini et al. had to use exhaustive search over all the sign combinations in all the neurons in the current layer, which required an exponential amount of time. In this work, we introduce three new polynomial-time techniques. **System of equations (_SOE_)**. As pointed out in [14], in networks that are contractive enough, we essentially have full control over the inputs to any of the layers, and the signs can be easily recovered one by one through a method they propose, which we refer to as _Freeze_. Here, we present an alternative method called _SOE_, which recovers the signs for all neurons simultaneously by solving a system of equations. Not only is it more efficient in terms of oracle queries, but also in time complexity since it solves a single system of equations whereas _Freeze_ would need to solve one system of equations per neuron. Both _Freeze_ and _SOE_ are significantly simpler and more efficient than the methods we describe next but are heavily limited by the contraction requirement and typically are only applicable to the first few layers. _Neuron Wiggle_. Practically, most neural networks do not have contractive-enough hidden layers. The attack in [14] uses, in this case, a more general technique that determines the signs by exhaustive search while requiring a polynomial number of oracle queries. As our main result, we present the _Neuron Wiggle_ technique, which is polynomial in both, time and queries to the oracle. This is the method of choice for most of the layers in both, contractive or expansive networks. In this method, we choose a _wiggle_ (i.e., a small change in a carefully chosen direction) in the input to the network that makes the input to the ReLU for some targeted neurons experience a large change, while all the other neurons in the network are expected to experience much smaller changes. This makes it possible to recover the sign for the targeted neuron, since if the input to that neuron's ReLU is negative, the effect of the large change will be blocked, while if the input to the ReLU is positive, this change will propagate through this ReLU and the subsequent layers, and eventually cause a change at the output. By choosing a critical point and wiggling in two opposite directions, we can detect the direction where the larger output change is present, thereby recovering the sign. However, some critical points may lead to a wrong decision on the sign, and thus, we have to repeat it at multiple unrelated inputs to gather reliable statistical evidence for which wiggles are blocked and which ones go through the ReLU. It is important to note that even without knowing the neuron's sign, the attacker can easily aggregate all the experiments that are on the same active/inactive side of the ReLU, and then he can use the statistical difference between these two clusters to determine which cluster is on the active and which cluster is on the inactive side of the ReLU. In our practical attacks, accumulating statistical evidence from 200 input points was sufficient to recover the correct sign for each neuron, except possibly in the last hidden layer. The main problem in the last hidden layer is that there is no randomization present in the function computing the output. That means if the weight that connects a particular neuron to the output is considerably smaller than the others, almost no amount of wiggling of the corresponding neuron will get through to the output. We thus used the neuron wiggle technique to successfully attack all but the first and last hidden layers of a CIFAR10 network with 256 neurons per layer. _Last Hidden Layer_. Here, we develop a specialized technique to reliably deal with the last layer, which exploits exactly the same property that made the neuron wiggling technique less reliable for this layer (namely, the fact that there is a fixed linear mapping that maps the outputs of these neurons to the final output). This allows us to construct arbitrarily many linear equations in the coefficients of this fixed output function by exploring multiple unrelated inputs to the DNN, and their unique solution simultaneously yields the unknown signs for all the last layer neurons. This method has lower time and query complexity than Neuron Wiggle, but its applicability is limited to the last layer. #### Organization The remainder of this paper is organized as follows. In section 2, we present a brief summary of the state of the art on DNN parameter extraction in the black-box model. In section 3, we present several basic definitions, and assumptions, and state the problem to solve. We complete that section by giving an overview of the approach by Carlini et al. before presenting our own sign-recovery techniques in section 4. All the practical attacks carried out in this work are presented in section 5. The concluding remarks are drawn in section 6. ## 2 Related Work Model extraction in the context of DNNs aims to obtain its architecture, the weights, and biases associated with each neuron in the network and, occasionally, the network's training hyperparameters. Although early work can be traced back to Fefferman [10] (who proved in 1994 that perfect knowledge of the output of a sigmoid-based network uniquely specifies its architecture and neurons' weights, and also proved that two neural networks with the same input-output map are isomorphic up to trivial equivalences), followed by Lowd and Meek in 2005 [13], the most important body of literature on this topic has been published since 2016, when Tramer et al. studied the problem of functional equivalence for the case of multi-class logistic regression and the multi-layer perceptron. Since then, many attacks have been presented considering different attack scenarios and security models [14, 15, 16, 17, 18] (see also [14] for a comprehensive survey). As discussed in section 1, in this paper, we are primarily interested in a security model where the only interaction the attacker has with the DNN is submitting queries to it and observing the corresponding outputs (e.g., accessing it as a web service). Therefore, the attacker does not have access to the software or the hardware where the network has been deployed, which rules out side-channel and/or fault injection attacks as the ones reported in [11, 12]. Furthermore, the main goal of our attack is to recover a functionally equivalent model of the network. Such precision is normally out of reach for the hardware attacks described in [11]. The state-of-the-art black-box model extraction has been traditionally centered around DNNs with ReLU activation functions. In the beginning, it was thought that the most effective way of extracting the model of the networks was through oracle calls that revealed information about the gradients. In [13], this approach was theoretically analyzed and implemented to attack networks with one hidden layer. An improvement of this work followed quickly afterward in [12], offering significant improvements to the functional equivalence of the extracted model but still constrained to attacks dealing with relatively modest one-layer DNNs and relying on the unrealistic help of an oracle that leaked the gradients. Almost simultaneously, Rolnick and Kording presented in [15] an approach that, by only observing the output of the network, was theoretically capable of extracting the parameters of deeper networks. However, in practice, the algorithm in [15] only worked for two-layer networks. Meanwhile, a similar strategy was theoretically analyzed in [14]. A follow-up work by Carlini et al. was presented in [16]. In this paper, the authors presented important technical improvements and devised novel techniques that allowed them to obtain a much higher precision in the neuron's parameters extraction while using remarkably fewer oracle calls than the previous methods reported in [15, 12] (cf. [16, Table 1]). However impressive the high precision results obtained by the authors, they only managed to deal with neural networks of no more than three hidden layers and with a relatively modest number of a few tens of neurons beyond the first layer. The main reason the approach presented in [16] could not scale up well for larger and deeper networks was that the weights of the neurons could only be obtained up to a constant of unknown sign. Indeed, finding the sign for the neurons had a prohibitively exponential cost in time and has remained until now as one of the two main obstacles towards extracting deeper and larger neural networks. The second obstacle, also acknowledged by the authors of [16], is that of dealing with so-called expansive neural networks, i.e., networks where the number of neurons in a given inner layer is larger than the number of inputs to that layer. ## 3 Preliminaries ### Basic Definitions and Notation Informally, a neural network is a collection of connected nodes called _neurons_. Neurons are arranged in _layers_ and are connected to those in the previous and the next layer. Every neuron has a _weight_ associated with each incoming connection and a _bias_. We present next several important formal definitions by closely following the definitions and notation given in [1]. Definition 1: An _r_-deep neural network _is a function \(f:\mathcal{X}\rightarrow\mathcal{Y}\) composed of alternating linear _layers_\(f_{i}\) and a non-linear _activation function_\(\sigma\) acting component-wise: \[f=f_{r+1}\circ\sigma\circ\cdots\circ\sigma\circ f_{2}\circ\sigma\circ f_{1}.\] We focus our study on Deep Neural Networks (DNN) over the real numbers. Then, \(\mathcal{X}=\mathbb{R}^{d_{0}}\) and \(\mathcal{Y}=\mathbb{R}^{d_{r+1}}\), where \(d_{0}\) and \(d_{r+1}\) are positive integers. As in [1], we only consider neural networks using the ReLU activation function \(\sigma:x\mapsto\max(x,0)\). Definition 2: The _\(i\)-th_ fully connected layer _of a neural network is a function \(f_{i}:\mathbb{R}^{d_{i-1}}\rightarrow\mathbb{R}^{d_{i}}\) given by the affine transformation_ \[f_{i}(x)=A^{(i)}x+b^{(i)},\] _where \(A^{(i)}\in\mathbb{R}^{d_{i}\times d_{i-1}}\) is the _weight matrix_, \(b^{(i)}\in\mathbb{R}^{d_{i}}\) is the _bias vector_ of the \(i\)-th _layer_ and \(d_{i-1},d_{i}\) are positive integers. Layers in neural networks often have more structure than just a matrix-vector multiplication as above (e.g., convolutional layers). However, they may admit a description as a special form of a fully connected layer. We call a network _fully connected_ if all its layers are fully connected. The first \(r\) layers are the _hidden layers_, and layer \(r+1\) is the _output layer_. Definition 3: A _neuron_ is a function determined by the corresponding weight matrix and activation function. Particularly, the \(j\)-th neuron of layer \(i\) is the function \(\eta\) given by \[\eta(x)=\sigma(A^{(i)}_{j}x+b^{(i)}_{j}),\] where \(A^{(i)}_{j}\) and \(b^{(i)}_{j}\) denote, respectively, the \(j\)-th row of \(A^{(i)}\) and \(j\)-th coordinate of \(b^{(i)}\). Definition 4: Let \(\ell=d_{i-1}\) and \(A^{(i)}_{j}\) be described as \((a_{1},a_{2},\ldots,a_{\ell})\). The _signature_ of the \(j\)-th neuron in layer \(i\) is the tuple \[\left(\frac{a_{1}}{a_{1}}=1,\frac{a_{2}}{a_{1}},\ldots,\frac{a_{\ell}}{a_{1}} \right). \tag{1}\] Definition 5: Let \(\mathcal{V}(\eta;x)\) denote the value that neuron \(\eta\) takes with \(x\in\mathcal{X}\) before applying \(\sigma\). If \(\mathcal{V}(\eta;x)>0\) then \(\eta\) is _active_. When \(\mathcal{V}(\eta;x)=0\), \(\eta\) is _critical_, and we call \(x\) a _critical point_ for \(\eta\)5. Otherwise, it is _inactive_. The state of \(\eta\) on input \(x\) (i.e., active, inactive, or critical) is denoted by \(\mathcal{S}(\eta;x)\). Footnote 5: Carlini et al.’s “critical point” is “being critical” in our definition. Carlini et al.’s “witness for a neuron being at a critical point” is “a critical point” in our definition. Definition 6: Let \(x\in\mathcal{X}\). The _linear neighbourhood_ of \(x\) is the set \[\{u\in\mathcal{X}\mid\mathcal{S}(\eta;x)=\mathcal{S}(\eta;u)\text{ for all neurons }\eta\text{ in the network}\}.\] Definition 7: The _architecture_ of a fully connected neural network is described by specifying its number of layers along with the dimension \(d_{i}\) (i.e., number of neurons) of each layer \(i=1,\cdots,r+1\). We say that \(d_{0}\) is the dimension of the inputs to the neural network, whereas \(d_{r+1}\) gives the number of outputs of the network. A neural network has \(N=\sum_{i=1}^{r}d_{i}\) neurons. As in [3], we specify the architecture of a neural network by enumerating the dimensions of its layers. For example, the eight-hidden-layer network for classifying the CIFAR10 dataset showcased in this paper has the architecture \[3072-256^{(8)}-10.\] Let \(F_{i}\) denote the function that computes the first \(i\) layers of the DNN after the ReLUs, i.e., \(F_{i}=\sigma\circ f_{i}\circ\cdots\circ\sigma\circ f_{1}\). By definition, all neurons remain in the same state when evaluating the DNN with an input in the linear neighborhood of \(x\in\mathcal{X}\). Following the explanation in [3], for any such point \(x^{\prime}\), we have that \[F_{i}(x^{\prime}) =I^{(i)}(A^{(i)}\cdots(I^{(2)}(A^{(2)}(I^{(1)}(A^{(1)}x^{\prime}+b ^{(1)}))+b^{(2)})\cdots+b^{(i)})\] \[=I^{(i)}A^{(i)}\cdots I^{(2)}A^{(2)}I^{(1)}A^{(1)}x^{\prime}+\beta\] \[=\Gamma x^{\prime}+\beta,\] where \(I^{(j)}\) are \(0-1\) diagonal matrices with a \(0\) on the diagonal's \(k\)-th entry when neuron \(k\) at layer \(j\) is inactive and \(1\) on the diagonal's \(k\)-th entry when that neuron is active. That is, in the linear neighborhood of an input \(x\), we can "collapse" the action of various contiguous layers into an affine transformation. If we make a change \(\Delta\) to the input, we can observe the corresponding change in the value of the neurons: \[F_{i}(x+\Delta)-F_{i}(x)=\Gamma(x+\Delta)+\beta-(\Gamma(x)+\beta)=\Gamma\Delta.\] This \(\Delta\) must be such that \(x+\Delta\) is in the linear neighborhood of \(x\). Assume that we fully know the first \(i-1\) layers, and we are currently recovering layer \(i\). Let \(F_{i-1}\) and \(G_{i+1}\) represent, respectively, the fully recovered and non-recovered part of the DNN, i.e., \[f=\underbrace{f_{r+1}\circ\sigma\circ\cdots\circ\sigma\circ f_{i+1}}_{G_{i+1} }\circ\sigma\circ f_{i}\circ\underbrace{\sigma\circ f_{i-1}\circ\cdots\circ \sigma\circ f_{1}}_{F_{i-1}}.\] Then, the neural network can be depicted as in Figure 1. Furthermore, if we restrict inputs \(x^{\prime}\) to be in the linear neighbourhood of \(x\), we can collapse \(F_{i-1}\) and \(G_{i+1}\) as \[F_{i-1}(x^{\prime})=F_{x}^{(i-1)}x^{\prime}+b_{x}^{(i-1)}\quad\text{and}\quad G _{i+1}(x^{\prime})=G_{x}^{(i+1)}x^{\prime}+b_{x}^{(i+1)},\] respectively. We use the subscript in the collapsed matrices and bias vectors to indicate that they are defined in the linear neighborhood of \(x\). Definition 8: We call the \(j\)-th row of \(G_{x}^{(i+1)}\) the _output coefficients_ for the \(j\)-th output of the DNN. ### Problem Statement and Assumptions The parameters \(\theta\) of a DNN \(f_{\theta}\) are the concrete assignments to the weights and biases. Following the setting in [10], in a _model parameter extraction attack_, an attacker generates queries \(x\) to an oracle \(\mathcal{O}\) which returns \(f_{\theta}(x)\). The goal of the attacker is to obtain a set of parameters \(\hat{\theta}\) such that \(f_{\hat{\theta}}(x)\) is as similar as possible to \(f_{\theta}(x)\). We focus on the attack presented in [10]. As mentioned in subsection 1.2, Carlini et al.'s attack recovers the parameters layer by layer in two steps. The first one finds multiples of the parameters, particularly the signatures of the neurons as defined in Equation 1. Since the signature consists of ratios of pairs of weights, negating all these weights simultaneously will preserve the signature but nonlinearly change the outputs of this neuron's ReLU. Consequently, before we can peel off a layer of neurons, we have to determine for each one of its neurons separately whether the weights and biases are one possible vector of values or its negated vector. That is, we must get a sign of that neuron's weight. The second step recovers these signs for all neurons in the current layer. In this paper, we specifically focus our attention on the latter half, which was the exponential-time bottleneck in [10], under the assumption that the signatures are already known. The following are the assumptions we have regarding the oracle and the capabilities of the attacker: Figure 1: Representation of the DNN according to the recovered part \(F_{i-1}\), current target layer \(i\) and unknown part \(G_{i+1}\). * **Full-domain inputs**. We can feed arbitrary inputs from \(\mathcal{X}=\mathbb{R}^{d_{0}}\). * **Complete outputs**. We receive outputs directly from \(f\) without further processing. * **Fully connected network and ReLU activations**. The network is fully connected, and all activation functions are the ReLU function. * **Fully precise computations**. All computations are done with infinite-precision arithmetic. * **Signature availability and uniqueness**. We have access to the signature of each neuron. Also, we assume that no two signatures are the same. All but the last one are also assumptions in [10]. Regarding full precision, we remark that computations by both the oracle and the attacker enjoy this characteristic. Carlini et al. assume single-output DNNs. However, we allow for multiple outputs, which enhances the performance of our techniques and is incidentally also more realistic. Finally, if a full attack following [10] using our sign recovery methods is to be performed, we must also assume _knowledge of the architecture_. This assumption is required to apply the methods in [10]. ### Carlini et al.'s Differential Attack We now present a high-level description of the techniques by Carlini et al. [10]. #### 3.3.1 Finding critical points To discover critical points, Carlini et al. analyze the function induced by a DNN when an input \(x_{1}\) is linearly transformed into another input \(x_{2}\). For the sake of simplicity and without loss of generality, we will assume in the following that the network has a single output. Let \(x_{1},x_{2}\in\mathbb{R}^{d_{0}}\) and \(\mu:[0,1]\rightarrow\mathbb{R}^{d_{0}}\) defined as \[\mu:\lambda\mapsto x_{1}+\lambda(x_{2}-x_{1})\] be the linear transformation of \(x_{1}\) into \(x_{2}\). This induces an output function on the DNN, \[f^{*}(\lambda):=f(\mu(\lambda)),\] which is a piecewise linear function with first-order discontinuities precisely when one of the neurons is toggling between active/inactive states. As shown in Figure 2, we can identify the first-order discontinuities and revert the mapping \(\mu\) to recover the point at which the line from \(x_{1}\) to \(x_{2}\) intersects a boundary between linear neighborhoods, which is a critical point for some neuron. In practice, it suffices to measure the slope of the graph in Figure 2 at different points and extrapolate to find the critical point, all while checking that there are no other abrupt changes in behavior in-between. We refer to section B for the fully-detailed algorithm. At this point, we do not yet know to which layer each critical point belongs, but by sampling enough pairs \(x_{1},x_{2}\) we expect to eventually find multiple critical points for every neuron in the network. #### 3.1.2 Finding signatures The input to the DNN is also the input to the first hidden layer, and we have full control over it. Let \(\eta\) be a neuron with weights \((a_{1},\ldots,a_{\ell})\). Given \(x^{*}\in\mathbb{R}^{d_{0}}\) a critical point for \(\eta\), we can query \(\alpha_{i,-}=\frac{\partial f}{\partial e_{i}}(x^{*}-\varepsilon e_{i})\) and \(\alpha_{i,+}=\frac{\partial f}{\partial e_{i}}(x^{*}+\varepsilon e_{i})\), where \(\{e_{i}\}_{i=1}^{d_{0}}\) is the canonical basis of \(\mathbb{R}^{d_{0}}\) and \(\varepsilon\) is a small real number. Since \(x^{*}\) is a critical point, only either \(\alpha_{i,-}\) or \(\alpha_{i,+}\) will have \(\eta\) in its active state assuming that \(\varepsilon\) is sufficiently small so that no other neuron toggles. The difference \(\alpha_{i,+}-\alpha_{i,-}\) contains the gradient information moving from the input coordinate \(i\) through neuron \(\eta\) and to the output; the gradient information through all other neurons cancel out. In other words, this difference is a multiple of \(a_{i}\) given by the other layers of the DNN. Dividing out by another coordinate eliminates the multiplicative factor, i.e., \((\alpha_{i,+}-\alpha_{i,-})/(\alpha_{k,+}-\alpha_{k,-})=a_{i}/a_{k}\). If we fix \(k=1\), the signature (1) is recovered. We denote by \(\hat{A}_{j}^{(i)}\) the signature of the \(j\)-th neuron in layer \(i\) and \(\hat{A}^{(i)}\) the matrix whose \(j\)-th row is \(\hat{A}_{j}^{(i)}\). Critical points for the same neuron in the target layer 1 will yield the same signature, while critical points for neurons in other layers will generate different signatures. This allows us to decide which signatures correspond to a layer-1 neuron (i.e., those signatures appearing with repetitions). See [3] for details on this. After peeling off layers, we can also determine if a signature corresponds to a neuron in the current target layer by observing repetitions. However, starting from layer 2 we no longer have full control of the layer's input, and applying the method above is not possible (we cannot change one coordinate at a time). To overcome this, in layer \(i>1\), we sample \(d_{i}+1\) directions \(\delta_{k}\sim\mathcal{N}(0,\varepsilon I_{d_{0}})\in\mathbb{R}^{d_{0}}\), and let \(\{y_{k}\}=\{\partial^{2}f(x^{*})/\partial\delta_{1}\partial\delta_{k}\}_{k=1} ^{d_{i}}\) and \(h_{k}=F_{i-1}(x^{*}+\delta_{k})\). The signature is then given by the vector \(a\) such that \(\langle h_{k},a\rangle=y_{k}\). This, however, yields partial signatures (since the ReLUs in the previous layer set negative values to zero). Different critical points for the same neuron yield different partial signatures. Figure 2: The input space can be partitioned into linear neighborhoods, and the output function displays abrupt changes in behavior when moving across their borders. Each partial signature will yield a different set of coordinates and with enough partial signatures, we can reconstruct the full one. #### 3.3.2 Finding signs using the freezing method We now consider the problem of finding the signs of a given layer. If the network is not expanding, this problem is easy for the first hidden layer. Indeed, for target neuron \(k\) in layer \(i\), we can find a wiggle \(\Delta_{k}\) in the input space that produces a wiggle \(\pm e_{k}\) in the first hidden layer, where \(e_{k}\in\mathbb{R}^{d_{i}}\) is a basis vector in the \(k\)-th direction, by solving a system of \(d_{1}\) equations in \(d_{0}\) variables given by the first layer's weight matrix. For any \(x\) in the input space, the outputs of the neural network at \(x\) and \(x+\Delta_{k}\) will be equal if the \(k\)-th neuron is inactive in the linear neighborhood of \(x\) (since the \(k\)-th neuron is suppressed by the ReLU whereas all other neurons remain unchanged by construction), and will be different otherwise. We refer to this simple sign-recovery technique as _Freeze_. There are some scenarios where the same method can be applied to deeper layers. Note that in the linear neighborhood of any input \(x\), the mapping from the \(d_{0}\)-dimensional input space to the space of values entering layer \(i\) is an affine mapping since there are no ReLUs that flip from active to inactive or vice versa. The rank of this mapping determines in how many linearly independent directions we can slightly perturb the inputs to layer \(i\) when we consider arbitrary perturbations of the input \(x\). If the rank is high enough, we can still expect to find preimages for each of the basis vectors and can apply the _Freeze_ method. In general, however, our ability to change the inputs to a deep hidden layer is severely limited, since about half of the neurons in each layer are expected to be suppressed, and thus, the rank of the affine mapping decreases as we move deeper into the network. This issue is pointed out in [10], where it is claimed that the _Freeze_ method can only be applied in networks that are "_sufficiently contracting_" (that is, layer size should decrease by roughly a factor of 2 in each layer in order to compensate for the rank loss). In networks that are not sufficiently contractive, Carlini et al. use instead the much more expensive technique of exhaustive search over all the possible sign combinations (as described in [10, Section 4.4]) that is exponential in time, which makes their attack feasible only for toy examples of non-contracting networks. ## 4 Our New Sign-Recovery Techniques As just mentioned, the diminishing control over the inputs to a layer is a significant problem that makes sign recovery in deeper layers harder. To better understand our proposed solutions, we first describe this problem in greater detail. Let \(x\in\mathbb{R}^{d_{0}}\) be an input to the DNN. Recall that \(F_{x}^{(i-1)}\) and \(G_{x}^{(i+1)}\) are the collapsed matrices for \(x\) corresponding to the already recovered and unknown part of the DNN, respectively. Definition 9: The space of control for layer \(i\) around input \(x\), denoted by \(V_{x}^{(i-1)}\), is the range of the linear transformation \(F_{x}^{(i-1)}\). The dimension of this space is called the number of degrees of freedom for layer \(i\) with input \(x\) and is denoted by \(d_{x}^{(i-1)}\). The space of control is the vector space containing all possible small changes at the input to layer \(i\) and, by the definition, \(d_{x}^{(i-1)}=\text{rank}(F_{x}^{(i-1)})\). Due to the ReLUs in layers \(1\) to \(i-1\) making neurons inactive, for a fixed \(x\), the number of degrees of freedom remains equal or decreases with increasing \(i\). To see this, consider an input \(x\) making half of the \(d\) neurons in layer \(1\) be active. The matrix \(F_{x}^{(1)}\) would then have rank \(d/2\), and particularly, the rows corresponding to inactive neurons are the zero vector. If layer two has \(d^{\prime}<d/2\) active neurons (with the same input \(x\)), the matrix \(F_{x}^{(2)}\) has rank \(d^{\prime}\), and therefore the number of degrees of freedom is also \(d^{\prime}\). Now, if \(d^{\prime}\geq d/2\), \(F_{x}^{(2)}\) has rank \(d/2\) (since the rank of \(F_{x}^{(1)}\) cannot be increased when multiplied by another matrix). We have the same situation for the subsequent layers: the rank can never be increased once it has decreased. In fact, the number of degrees of freedom at layer \(i\) is typically determined by the minimum number of active neurons per layer among all layers \(1\) to \(i-1\), but in some cases, it can be strictly smaller. Consider a DNN with input dimension \(d\) and the same width \(d\) in all its hidden layers. Assume further that each neuron has probability \(1/2\) of being Figure 3: Intuition for the space of control (Definition 9). Consider a network with \(2\)-dimensional input and two hidden layers with two neurons in each. (a) For the first hidden layer, the space of control is the full \(2\)-dimensional space. We can move around the input \(x_{0}\) in any direction. (b) After the first hidden layer, if one ReLU is positive and the other negative, we lose one dimension of control. (c) The linear transformation in the second layer will rotate, translate, and scale the space of control. (d) Therefore, after the ReLU’s in the second layer (if again one is positive and one negative), we are still left with a one-dimensional space of control. Note that with no rotation, the space of control collapses into a point after these two hidden layers. active. Initially, the number of degrees of freedom is equal to the dimension \(d\) of the input to the DNN. Then, the first hidden layer will have, on average, half of its neurons active, which drops the number of degrees of freedom at the input of layer 2 to \(d/2\). We can think of the ReLU's projecting the space of control onto a space determined by the active neurons. One may think that half of those \(d/2\) degrees of freedom will again be lost in the second layer due to the fact that half of its ReLU's will be inactive, ending with \(d/4\) degrees of freedom. However, before going to the ReLUs on that layer, the space of control for layer 2 is typically rotated by \(A^{(2)}\). This rotation may make many coordinates survive the projection of the ReLUs in the second layer. We may still lose some degrees of freedom, but not as many as half of them in each successive layer. Due to this effect of the linear transformation, the number of degrees of freedom will typically stabilize after the first few layers. Figure 3 depicts this phenomenon in a two-dimensional space, and Table 2 shows the average number of active neurons and the average number of degrees of freedom in the 8 successive hidden layers of the actual CIFAR10 network we attack. We now describe our methods for sign recovery with the loss of degrees of freedom in mind. Recall that in the context of the attack, when recovering the signs for layer \(i\), we fully know \(F_{i-1}\), we know \(f_{i}\) up to a sign per neuron, and \(G_{i+1}\) is completely unknown. To simplify our notation, we may drop the subscript \(x\) from the collapsed matrices, space of control, and number of degrees of freedom if \(x\) is clear by the context. ### SOE Sign-Recovery We first describe a method for sign recovery in cases where the number of degrees of freedom is sufficiently large. We refer to the method as SOE since it relies on solving a System Of Equations. This method is superficially similar to _Freeze_, but uses different equations and a different set of variables (in the case of [3], the variables referred to the direction we have to follow in input space to freeze all the neurons except the targeted one, while in our SOE technique the variables refer to the coefficients of the output function \(G_{i+1}\) at some randomly selected point \(x\)). Our technique is more efficient in both its query and time complexities since Carlini et al. had to solve a different system of equations for each targeted neuron, while in our SOE technique, one system of linear equations can simultaneously provide the signs of all the neurons in the current layer. We assume without loss of generality that the network has a single output (additional outputs can be simply ignored). As before, let \(I_{x}^{(i)}\) be the matrix representing the ReLU at layer \(i\) on input \(x\). The equation for the change in output under an arbitrary sequence of changes in input \(\Delta_{k}\), can then be written as \[f(x+\Delta_{k})-f(x)=G_{x}^{(i+1)}I_{x}^{(i)}A^{(i)}F_{x}^{(i-1)}\Delta_{k}.\] Let \(y_{k}=A^{(i)}F_{x}^{(i-1)}\Delta_{k}\) and \(c=G_{x}^{(i+1)}I_{x}^{(i)}\). If the left-hand side is observed to take values \(z_{k}\) through direct queries, the equation can be rewritten as \[c\cdot y_{k}=z_{k},\] which can be regarded as a system of equations where \(c\) is a vector of variables. Because of the ReLU, if neuron \(j\) is inactive on input \(x\) we will necessarily have \(c_{j}=0\), so after obtaining \(d_{i}\) equations, we can solve the system and determine which neurons are inactive around \(x\) and hence the appropriate choice of signs for the current layer. Remark 1: In the context of the attack, we can only recover \(y_{k}\) up to a global scaling of each entry (including possibly a sign flip), but this results in a system of equations where the solution has the same set of variables vanishing. #### 4.1.2 Oracle Calls/Time This method is optimal in terms of queries since it only requires \(d_{i}+1\) queries to solve a layer of size \(d_{i}\) (namely, it must query \(f(x)\) and \(f(x+\Delta_{k})\) for \(d_{i}\) values of \(k\)). Once the queries have been performed, the time complexity of the attack comes from solving a system of equations, which can be done in \(\mathcal{O}(d_{i}^{3})\) with standard methods. #### 4.1.3 Limitations Each choice of \(\Delta_{k}\) produces a new equation, so we attempt to gather more equations until the system is uniquely solvable. However, the equations that are obtained may not all be linearly independent. In fact, since the \(y_{k}\) all lay in \(A^{(i)}(V_{x}^{(i-1)})\), we will only obtain enough linearly independent equations if \(d_{x}^{(i-1)}\geq d_{i}\). This is likely to be the case if the layer size is steadily contracting by a factor of 2, but there is an important exception for the first two hidden layers. Indeed, as long as the network is not expanding, the linear map corresponding to the first hidden layer can usually be inverted. This makes it easy to find an \(x\) at which all first-layer neurons are active and hence \(d_{x}^{(1)}=d_{1}\geq d_{2}\). Therefore, the method applies straightforwardly for the first two hidden layers on the sole condition of non-expansiveness and is likely to succeed in subsequent layers only if they each contract by a factor close to 2. ### Neuron Wiggle Sign-Recovery The method presented here does not have the strict constraints on the network's architecture as the one above, since its performance gradually degrades as the number of degrees of freedom diminishes, whereas in SOE the system of equations abruptly changes from solvable to unsolvable. Definition 10: A _wiggle at layer \(i\)_is a vector \(\delta\in\mathbb{R}^{d_{i-1}}\) of differences in the value of the neurons in that layer. Recall that the recovered weight matrix for layer \(i\) is \(\hat{A}^{(i)}\in\mathbb{R}^{d_{i}\times d_{i-1}}\) and let its \(k\)-th row be \(\hat{A}^{(i)}_{k}\). For a wiggle \(\delta\) at layer \(i\), neuron \(k\in\{1,\ldots,d_{i}\}\) in that layer changes its value by \(e_{k}=\langle\hat{A}^{(i)}_{k},\delta\rangle\). Consider one output of the DNN and let \((c_{1},\ldots,c_{d_{i}})\) be its corresponding vector of output coefficients (i.e., its corresponding row vector in \(G^{(i+1)}\)). If we "push" the differences \(e_{k}\) through the remaining layers, the difference in the output is \[\sum_{k\in I}c_{k}e_{k}, \tag{2}\] where \(I\) contains the indices of all active neurons at layer \(i\). We want to recover the sign of neuron \(j\). If this neuron is active, the output difference contains the contribution of \(e_{j}\). If the neuron is inactive, the ReLU "blocks" \(e_{j}\) and it does not contribute. When \(c_{j}e_{j}\) is sufficiently large, we can detect whether it is present in (2) and use this information to recover the sign of the neuron. This is best achieved when \(\delta\) is a wiggle that maximizes the change in value for that neuron, i.e., \(\|\hat{A}^{(i)}\delta\|_{\infty}=|e_{j}|\). The crucial property we use here is that maximizing the _size_ of the wiggle produced by a linear expression does not require knowledge of its sign - if we negate the expression we get a wiggle of the same size but in the opposite direction. We now show how to compute such a maximal wiggle and how to recover the target neuron's sign. #### 3.2.2 Compute Target Neuron Wiggle Let \(\delta\in\mathbb{R}^{d_{i-1}}\) be parallel to \(\hat{A}^{(i)}_{j}\) (i.e., all coordinates of \(\delta\) have either the same or opposite sign to the corresponding coordinate of \(\hat{A}^{(i)}_{j}\)). Then, all summands in the dot product \(\langle\hat{A}^{(i)}_{j},\delta\rangle\) have the same sign. If no other row of \(\hat{A}^{(i)}\) is a multiple of \(\hat{A}^{(i)}_{j}\), with very high probability \(|\langle\hat{A}^{(i)}_{j},\delta\rangle|>|\langle\hat{A}^{(i)}_{k},\delta\rangle|\), for all \(k\neq j\). That means \(\|\hat{A}^{(i)}\delta\|_{\infty}=|\langle\hat{A}^{(i)}_{j},\delta\rangle|\). Hence, the change of value for neuron \(j\) can be maximized if the wiggle is parallel to \(\hat{A}^{(i)}_{j}\). Recall that \(V^{(i-1)}\) is the space of control for layer \(i\) given an input \(x\). We project \(\hat{A}^{(i)}_{j}\) onto \(V^{(i-1)}\) and get \(\delta\) by scaling this projection to have a sufficiently small norm \(\varepsilon^{(i-1)}\); see Figure 4. Finally, we get the input difference \(\Delta\in\mathbb{R}^{d_{0}}\) that generates \(\delta\) by finding a pre-image of \(\delta\) under \(F^{(i-1)}\). #### 3.2.3 Recover Target Neuron Sign We want to recover the sign for \(\eta_{j}\), the \(j\)-th neuron in layer \(i\). Let \(x^{*}\) be a critical point for \(\eta_{j}\) and let \(\Delta\in\mathbb{R}^{d_{0}}\) generate the wiggle \(\delta\) (at layer \(i\)) that maximizes the change in value for that neuron. Assume the sign of \(\eta_{j}\) to be positive. Then, the signs of the recovered weights \(\hat{A}^{(i)}_{j}\) are the same as those of the real weights \(A^{(i)}_{j}\). This implies that also the coordinates of \(\delta\) have the same sign as those of \(A^{(i)}_{j}\) and \(e_{k}=\langle A^{(i)}_{k},\delta\rangle\) has a positive value. Assume the DNN has a single output. Since \(x^{*}\) is a critical point for \(\eta_{j}\), evaluating the DNN at \(x^{*}+\Delta\) makes \(\eta_{j}\) active, thus \[f(x^{*}+\Delta)-f(x^{*})=c_{j}e_{j}+\sum_{k\in I\setminus\{j\}}c_{k}e_{k},\] where \(I\) contains the indices of all active neurons at layer \(i\). It is necessary that \(\Delta\) changes the state of neuron \(\eta_{j}\) only. Evaluating at \(x^{*}-\Delta\) makes the wiggle \(\delta\) have opposite signs to those in \(A_{j}^{(i)}\). Then, all differences \(e_{k}\) also have opposite signs (compared to evaluating at \(x^{*}+\Delta\)). In this case, \(\eta_{j}\) becomes inactive and we have that \[f(x^{*}-\Delta)-f(x^{*})=-\sum_{k\in I\setminus\{j\}}c_{k}e_{k}.\] Now assume that \(\eta_{j}\) has a negative sign. Then, the wiggle \(\delta\) will have opposite signs to those in \(A_{j}^{(i)}\) and following a similar analysis as above, we get that \[f(x^{*}+\Delta)-f(x^{*})=-\sum_{k\in I\setminus\{j\}}c_{k}e_{k}\] and \[f(x^{*}-\Delta)-f(x^{*})=c_{j}e_{j}+\sum_{k\in I\setminus\{j\}}c_{k}e_{k}.\] So, in order to find the sign we need to distinguish whether \(c_{j}e_{j}\) contributes to the output difference with \(x^{*}+\Delta\) or \(x^{*}-\Delta\). Let \(L=f(x^{*}-\Delta)-f(x^{*})\) and \(R=f(x^{*}+\Delta)-f(x^{*})\) denote, respectively, the output difference to the left and right of \(x^{*}\). We decide \(c_{j}e_{j}\) appears on the left, i.e., the sign of the neuron is \(-1\), if \(|L|>|R|\). Otherwise, we decide the sign to be \(+1\). Since \(c_{j}e_{j}\neq 0\), it is not possible that \(|L|=|R|\). If \(c_{j}e_{j}\) and \(\sum_{k}c_{k}e_{k}\) have the same sign, then \(|c_{j}e_{j}+\sum_{k}c_{k}e_{k}|>|-\sum_{k}c_{k}e_{k}|\) always holds and the decision on the sign is also always correct. If \(c_{j}e_{j}\) and \(\sum_{k}c_{k}e_{k}\) have opposite signs, however, an incorrect decision may occur. This wrong decision happens when \(|-\sum_{k}c_{k}e_{k}|>|c_{j}e_{j}+\sum_{k}c_{k}e_{k}|\). Then, it is necessary that \(|c_{j}e_{j}|>2|\sum_{k}c_{k}e_{k}|\) to make a correct decision. Recall that a given input to the DNN defines a particular matrix \(G^{(i+1)}\). That is, different inputs define different coefficients for the output of the DNN. We refer to this fact as _output randomization_ and exploit it to overcome the problem of making a wrong sign decision. We find \(s\) different critical points for neuron \(\eta_{j}\); each point defines different output coefficients. We expect that the majority of these points define coefficients such that \(c_{j}e_{j}\) and \(\sum_{k}c_{k}e_{k}\) fulfill the conditions for making a correct decision. For each critical point, we compute the Figure 4: Computing a wiggle that maximizes the change in the target neuron. wiggle \(\delta\), its corresponding input difference \(\Delta\), and make the choice for the sign. Let \(s_{-}\) and \(s_{+}\) denote, respectively, the number of critical points for which the sign is chosen to be \(-1\) and \(+1\). Also, let the _confidence level_\(\alpha\) for \(-1\) be \(s_{-}/s\) and \(s_{+}/s\) for \(+1\). Then, decide the sign to be \(-1\) if \(s_{-}>s_{+}\) and its confidence level is greater than a threshold \(\alpha_{0}\). If \(s_{+}>s_{-}\) and its confidence level is greater than \(\alpha_{0}\), decide \(+1\). Otherwise, no decision on the sign is made. When the latter happens, we may try to recover the sign with additional critical points. In our experiments in section 5, very few wrong signs were initially produced by testing 200 critical points for each neuron in the CIFAR10 network; all of them were known to be problematic due to their low confidence level, and they are all fixable by testing more critical points. Note that as the number of neurons in the network increases, we expect the neuron wiggling technique to get even better since in higher dimensions vectors tend to be more orthogonal to each other, and thus the ratio between the sizes of the wiggles in the targeted neuron and in other neurons should increase. So far, we assumed a single output for the DNN. When it has multiple outputs, we can use the Euclidean norm over the vector of outputs to compare \(L\) and \(R\), which is beneficial for this method. This is because each critical point randomizes the coefficients of multiple outputs, and the probability of multiple outputs having simultaneously "bad" coefficients (which may lead to wrong decisions) is lower. #### 5.2.2 Oracle Calls/Time Recall that layer \(i\) has \(d_{i}\) neurons. To recover the sign of a single neuron, for \(s\) critical points, we compute \(\Delta\) and compare \(L\) with \(R\). Computing \(\Delta\) requires no oracle queries: it only requires linear algebra operations to find a critical point \(x^{*}\), project \(\hat{A}_{j}^{(i)}\) onto \(V^{(i-1)}\) and find \(\Delta\). Particularly, matrix multiplications and matrix inversions. The size of the matrices involved is given by the number of inputs \(d_{0}\) and the number of neurons \(d_{i}\). So, the time complexity is \(\mathcal{O}(d^{3})\) operations, where \(d=\max(d_{0},d_{i})\). Comparing \(L\) with \(R\) requires querying the oracle on \(x^{*}\), \(x^{*}-\Delta\) and \(x^{*}+\Delta\). Computing \(L=\|f(x^{*}-\Delta)-f(x^{*})\|\) and \(R=\|f(x^{*}+\Delta)-f(x^{*})\|\) requires \(\mathcal{O}(d_{r+1})\) operations, where \(d_{r+1}\) is the number of outputs of the DNN. Thus, we require \(3s\) queries and \(\mathcal{O}(sd^{3})\) operations for a single neuron. In total, we require \(3sd_{i}\) queries and \(\mathcal{O}(sd_{i}d^{3})\) operations to recover the sign of all neurons in layer \(i\). Appendix 0.A contains a back-of-the-envelope estimation of the signal-to-noise ratio for each critical point we test, showing that even in expansive networks we only require a relatively small number of experiments \(s\) to make a good guess. #### 5.2.3 Limitations We can think of \(c_{j}e_{j}\) as a signal and \(\sum_{k}c_{k}e_{k}\) as noise. We have seen that when the signs of the signal and the noise are different, we may wrongly decide the sign of a neuron. This happens when the signal is not big enough compared to the noise. Particularly, if the number of neurons in layer \(i\) is too large compared to the degrees of freedom (for a particular input \(x\)), the signal may be really weak with respect to the noise. That means this technique may not work with DNNs which have at least one hidden layer with a large expansion factor compared to the smallest hidden layer or the number of inputs. However, we had no trouble recovering the signs when several successive hidden layers had twice the number of neurons compared to the dimension of the input space. Also, this method may not be suitable for DNNs with a small number of neurons in the target layer. The probability of two random vectors being perpendicular decreases in low-dimensional spaces. Therefore, the wiggle for the target neuron may produce a sensibly large change for other neurons as well (those with weight vectors somewhat parallel to that of the target neuron). In this situation, the contribution of the other neurons may counteract that of the target neuron. Finally, this method leverages _output randomization_. There is no output randomization when recovering the last hidden layer. If there are neurons in that layer with bad (constant) output coefficients, their corresponding sign will always be incorrectly recovered. The method in the next section exploits this lack of output randomization to recover the signs in the last hidden layer. ### Last Hidden Layer Sign-Recovery The method presented here recovers the sign of neurons in the last hidden layer. The output of the DNN is produced by the affine transformation \(f_{r+1}\)_without_ subsequent ReLUs. Therefore, in layer \(r\) (the last hidden layer), the matrix \(G^{(r+1)}\) is the same for any input \(x\). This means all inputs define the same output coefficients; equivalently, there is no output randomization for that layer. We use this fact to recover the signs of the neurons. The output coefficients are recovered via second derivatives, thus, this method resembles a second-order differential cryptanalysis. Assume that the DNN has a single output and let \(c_{1},\ldots,c_{d_{r}}\) be its output coefficients. Also, let \(x\) be an input to the DNN and \(y^{(i)}\) be the output of layer \(i\) after the ReLUs, i.e., \(y^{(i)}=F_{i}(x)\). The output of the DNN is given by \[f(x)=c_{1}y_{1}^{(r)}+\cdots+c_{d_{r}}y_{d_{r}}^{(r)}+b^{(r+1)}, \tag{3}\] where \(y_{k}^{(r)}\) is the \(k\)-th coordinate of \(y^{(r)}\) and \(b^{(r+1)}\) is the bias of the output layer. With the recovered matrix \(\hat{A}^{(r)}\), we can compute the value that neuron \(k\) in layer \(r\) takes before the ReLU, i.e., \(e_{k}=\langle\hat{A}^{(r)}_{k},y^{(r-1)}\rangle\), but we do not know its sign \(s_{k}\). Let us consider both options. Exactly one of \(e_{k}\) or \(-e_{k}\) will be positive, and the other will be negative; the latter would be blocked by the ReLU. So, \(\sigma(e_{k},-e_{k})\) is either \((e_{k},0)\) or \((0,-e_{k})\), depending on whether \(e_{k}>0\) or \(e_{k}<0\), respectively. We know the value \(e_{k}\), so we can compute \(\sigma(e_{k},-e_{k})\). Let us write \((\hat{y}_{k+}^{(r)},\hat{y}_{k-}^{(r)})=\sigma(e_{k},-e_{k})\). Now, finding \(s_{k}\) is equivalent to deciding whether the real value \(y_{k}^{(r)}\) of the neuron after the ReLU is \(\hat{y}_{k+}^{(r)}\) or \(\hat{y}_{k-}^{(r)}\). The contribution to \(f(x)\) in Equation 3 is \(c_{k}\hat{y}_{k+}^{(r)}\) when \(s_{k}=+1\), otherwise, it is \(c_{k}\hat{y}_{k-}^{(r)}\). Then, that equation can be rewritten as \[f(x)=\sum_{k=1}^{d_{r}}c_{k}\left(s_{k}\hat{y}_{k+}^{(r)}+(1-s_{1})\hat{y}_{k -}^{(r)}\right)+b^{(r+1)}.\] So, we take random inputs \(x\), construct a system of linear equations, and solve for the unknowns \(s_{k}\) and \(b^{(r+1)}\). We must choose at least \(d_{r}+1\) random inputs for the system to have a unique solution. The output coefficients \(c_{k}\) can be obtained through a second derivative; the latter represents the change in the slope of the function. Figure 5 depicts that the second derivative of the ReLU function \(\sigma\) is the same at a critical point regardless of the sign of its input. Let \(x^{*}\) be a critical point for neuron \(k\) in layer \(i\) and \(\Delta\) be a small-norm vector in the linear neighborhood of \(x^{*}\). Then, \[f(x^{*}+\Delta)-2f(x^{*})+f(x^{*}-\Delta)=\pm\langle F_{k}^{(i)},\Delta \rangle c_{k},\] where \(F_{k}^{(i)}\) is the \(k\)-th row of the matrix \(F^{(i)}\) defined by \(x^{*}\) when collpasing layers \(1\) to \(i\). The sign above is \(+\) when \(x+\Delta\) activates the neuron, and it is \(-\) otherwise. If \(\Delta\) is parallel to \(F_{k}^{(i)}\), \(\langle F_{k}^{(i)},\Delta\rangle>0\) and the neuron is active with \(x+\Delta\). Then, dividing the quantity above by \(\langle F_{k}^{(i)},\Delta\rangle\) yields the coefficient. When recovering the sign, we do not have access to the real \(F^{(i)}\), but we know \(\hat{F}^{(i)}=\hat{A}^{(i)}F^{(i-1)}\). To get the coefficient of neuron \(k\), we choose \(\Delta\) as \(\hat{F}_{k}^{(i)}\) scaled to have a sufficiently small norm. Getting the output coefficient of a neuron can be done for any hidden layer. It is only in the last one that the coefficients remain constant for different points \(x^{*}\). #### 4.2.2 Oracle Calls/Time First, for each neuron, we find a critical point and compute the output coefficient. This requires 3 oracle queries and linear algebra operations with time complexity \(\mathcal{O}(d^{3})\), where \(d=\max(d_{0},d_{r})\). That is \(3d_{r}\) queries and time complexity \(\mathcal{O}(d_{r}d^{3})\) for all \(d_{r}\) neurons. Then, constructing the system of equations requires also \(\mathcal{O}(d^{3})\) operations (to compute the values \(\hat{y}_{k-}^{(r)}\) and \(\hat{y}_{k+}^{(r)}\) for \(d_{r}+1\) points) and \(d_{r}+1\) queries. Finally, solving the system of equations requires \(\mathcal{O}(d_{r}^{3})\) operations and no queries. In total, we require \(4d_{r}+1\) queries, and the time complexity is \(\mathcal{O}(d_{r}d^{3})\) operations. #### 4.2.3 Limitations This technique requires the output coefficients to be constant. This only happens in the last hidden layer. Therefore, this method is applicable to that layer only. ## 5 Practical Sign Recovery Attacks This section presents the experimental results of our proposed sign recovery techniques from section4. We first do a set of preliminary experiments on "well-behaved" unitary balanced neural networks of varying sizes (subsection5.2), before we recover the real-world CIFAR10 network (subsection5.3). Our software implementation is available in6 Footnote 6: Anonymized for submission. [https://anonymous.4open.science/r/deti-C405](https://anonymous.4open.science/r/deti-C405) We have executed the majority of our experiments on a DGX A100 server on a 40 GiB GPU. However, our experiments are not GPU intensive and will run with similar runtimes on most personal computers. ### Implementation Caveats #### 5.1.1 Infinite Numerical Precision The assumption of infinite numerical precision cannot be upheld practically, as conventional deep learning packages such as TensorFlow [1] only offer a maximal backend floating point precision of 64 bits. This practical limitation will influence all of our techniques: At infinite numerical precision, we could create an infinitesimal wiggle to be sure that we stay within the linear region of the neural network, but the limited floating point precision forces us to create a wiggle of sufficient magnitude, and this larger-magnitude wiggle, in turn, can accidentally toggle one of the other neurons. This requires us to perform a linearity check, which leads to additional oracle queries (see AppendixB). The limited floating point precision also means that the small uncertainties in our recovered weights will propagate to larger errors in our prediction of neuron values at deeper layers. For both _SOE_ and the _Last Hidden Layer_ method, this means that the system of equations we recover can have slightly imprecise coefficients, and variables that should be exactly zero may instead resolve to a relatively small value. For all of the networks we studied, we found it sufficient to declare a small threshold for what should be considered a zero, but this line will get increasingly blurry with deeper networks. #### 5.1.2 Neuron Wiggle: Confidence-level \(\alpha\) The neuron wiggle is a statistical method, and in all following experiments we use \(s=200\) samples per neuron sign recovery. The sign recovery result for each neuron has a certain confidence level \(\alpha\in(0.5,1.0]\). A confidence level of \(\alpha=1.0\) (\(\alpha\approx 0.5\)) means absolute certainty (low certainty) in the recovered sign. The vast majority of signs is recovered (\(\diagup\)), even if \(\alpha\approx 0.5\). However, a very small number of signs is recovered **incorrectly** (\(\diagup\)). We consider decisions with a confidence level below a cut-off value \(\alpha_{0}\) to be **borderline** and re-analyze the neurons with \(\alpha\leq\alpha_{0}\) after updating the signs for all neurons with high confidence level \(\alpha>\alpha_{0}\). The cut-off value \(\alpha_{0}\) is chosen adaptively so that the neurons with the least-confident 10% of all sign-recoveries are reanalyzed (Figure6(a)). ### Unitary Balanced Neural Networks We start with experiments on a set of "well-behaved" toy networks of varying sizes before tackling a "real-world" CIFAR10 network in the following section. #### 5.2.1 Methodology Training small networks is sometimes done on artificial datasets, such as random data in [3]. Instead of training on random data, we purposefully create "well-behaved" networks with the following characteristics: The weights of each neuron are given by a unit vector chosen uniformly at random. The bias of each neuron is chosen such that it has a 50% probability of being active. Using our unitary balanced networks, we avoid anomalies originating from the non-deterministic neural network training on random data. #### 5.2.2 Results on 784-128-1 The largest network presented in [3] is the 784-128-1 network with around 100k parameters. Using _Freeze_ the time complexity for the sign recovery can be estimated as \(\mathcal{O}(d_{i}d^{3})=128\times 784^{3}=2^{35}\). If _Exhaustive Search_ would have to be used, the time complexity for the sign recovery can be estimated as \(\mathcal{O}(2^{d_{i}})=2^{128}\). While [3] can still recover the 784-128-1 network in "under an hour", deeper networks with multiple hidden layers are untractable due to the sign recovery with exhaustive search. We can recover the signs of all neurons in the 128 neuron-wide hidden layer with either _SOE_ in about \((6.77\pm 0.04)\,\mathrm{s}\), or alternatively, the _Last Hidden Layer_ technique in about \((18.6\pm 0.05)\,\mathrm{s}\). In our implementations of _SOE_ and _Last Hidden Layer_, parallelization and further speed-up are trivially achievable. Note that although the complexities of the two methods are similar, the execution time of _Last Hidden Layer_ is mainly determined by the time it takes the algorithm to find the output coefficients, which is in turn dominated by the cost of finding critical points. Figure 6: (a) illustrates that we reanalyze borderline neurons with low confidence level \(\alpha<\alpha_{0}\) as explained in _Neuron Wiggle_: Confidence-level \(\alpha\). (b) shows the approximately cubic runtime scaling with the neural network input dimension investigated in Results on \(d_{0}\)-256\({}^{(8)}\)-10. Since these searches are independent, they can be done in parallel with a linear speedup factor. On the other hand, _SOE_ does not require critical points, which explains the slight gap in performance. #### 5.2.2 Results on 100-200(\({}^{3}\))-10 This network is a larger version of the 10-20-20-1 network presented in [3]. As this network is expansive, the _Freeze_ technique and _SOE_ cannot be used, and before our work _Exhaustive Search_ with an estimated cost of \(2^{200}\) would have had to be employed for sign recovery. We use the _Neuron Wiggle_ technique in hidden layers 1 and 2, and the _Last Hidden Layer_ technique in hidden layer 3. In hidden layer 1 and 2 the _Neuron Wiggle_ recovers all neuron signs correctly, even the ones with a low confidence level \(\alpha\approx 0.5\). The (per-layer parallelizable) execution time per neuron is \((16.3\pm 0.4)\,\mathrm{s}\), respectively \((18.8\pm 0.5)\,\mathrm{s}\). The _Last Hidden Layer_ technique recovers hidden layer 3 in a total execution time of \((35.8\pm 0.2)\,\mathrm{s}\). #### 5.2.3 Results on \(d_{0}\)-256(\({}^{8}\))-10 Before moving on to our "actual" CIFAR10 network (3072-256\({}^{(8)}\)-10), we investigate the runtime scaling on unitary balanced networks with varying input dimensions \(d_{0}=\{256,512,1024,2048,3072\}\). According to our time order complexity estimation, we expect a cubic scaling of the runtime \(\sim\mathcal{O}(sd_{i}d^{3})\) with the input dimension \(d=\max(d_{0},d_{i})\). For each network \(d_{0}\)-256\({}^{(8)}\)-10, we recover a subset of neurons in hidden layer three. Figure 6(b) shows an approximately cubic scaling with the shortest sign recovery time of \(37\,\mathrm{s}\) for \(d_{0}=256\), and the longest sign recovery time of \(114\,\mathrm{s}\) for \(d_{0}=3072\). ### CIFAR10 Neural Network #### 5.3.1 The CIFAR10 Dataset CIFAR10 is one of the typical benchmarking datasets in visual deep learning. It contains a balanced ten-class subset of the 80 Million Tiny Images [10]. Each of the ten classes (e.g., airplane, cat, and frog) contains \(32\times 32\) pixel RGB images, totaling 50,000 training and 10,000 test images. #### 5.3.2 Our CIFAR10 Model Table 1 gives a detailed description of our CIFAR10 model. On the CIFAR10 dataset, we perform a standard rescaling of the pixel values from \(0\dots 255\) to \(0\dots 1\). For our model training, we choose typical settings (the optimizer is stochastic gradient descent with a momentum of 0.9; the loss is sparse categorical crossentropy; batch size 64), similar to [10]. Our eight-hidden-layer model shows CIFAR10 test accuracies within the expected range: Typical test accuracies for densely connected neural networks with pure ReLU activation functions are around \(\approx 0.53\)[10]. We note that better test accuracies are achieved using more advanced neural network architectures-beyond densely connected layers with pure ReLU activation functions. The current state of the art, Google Research's so-called vision transformer (ViT-H/14), achieves \(0.995\) test accuracy on CIFAR10 [4, Table 2]. As mentioned previously, the _space of control_ is essential for the sign recovery, and here we provide the experimental analysis for our \(3072-256^{(8)}-10\) CIFAR10 model. Table 2 shows that after a sharp initial drop, the space of control stabilizes in the deeper layers. This supports our intuition from Figure 3 that a dramatic fall in the space of control is prevented by the affine transformations. We analyzed our CIFAR10 network using our _SOE_ (hidden layers 1 and 2), _Last Hidden Layer_ (last hidden layer), and _Neuron Wiggle_ (hidden layer three to penultimate) sign recovery techniques. #### 4.1.1 Results with SOE and Last Layer Technique Table 3 shows the results of the sign recovery with the _SOE_ and _Last Hidden Layer_ techniques on our CIFAR10 model. Since these methods are algebraic, all neuron signs can be recovered successfully. We collect a system of equations as described in subsection 4.1 (_SOE_) and subsection 4.3 (_Last Hidden Layer_). For _SOE_, we collect one \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline model & acc. & CIFAR10 & \#(hidden layers) & \#(hidden neurons) & parameters \\ \hline \(3072-256^{(8)}-10\) & 0.5249 & 8 & 2048 & 1,249,802 \\ \hline \end{tabular} Note: Column ‘model’ shows the model configuration with the number of neurons in the (input layer, hidden layers\({}^{\#(\text{hidden layers})}\), output layer); ‘acc. CIFAR10’ shows the evaluation accuracy of the model on the 10,000 CIFAR10 test images; ‘#(hidden layers)’ shows the number of hidden layers; ‘#(hidden neurons)’ shows the total number of hidden layer neurons; ‘parameters’ shows the total number of model weights and biases. \end{table} Table 1: Description of our CIFAR10 model. Each image of the CIFAR10 dataset has \(32\times 32=1024\) pixels per RGB channel. Accordingly, our model has \(3\times 1024=3072\) input neurons. Further, it has 10 output neurons, one for each class in CIFAR10. We arbitrarily chose 256 neurons in each hidden layer. Our 8-hidden-layer CIFAR10 model with around 1.25M parameters is the largest model we analyze in this manuscript. \begin{table} \begin{tabular}{l|l l l l l l l l} \hline \hline \(i\): Layer ID & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ \#(ON ReLUs) & 127\(\pm\)8 & 80\(\pm\)8 & 72\(\pm\)8 & 74\(\pm\)6 & 82\(\pm\)6 & 95\(\pm\)6 & 99\(\pm\)7 & 100\(\pm\)10 \\ \(\text{rank}(F^{(i)})\) & 127\(\pm\)8 & 80\(\pm\)8 & 71\(\pm\)7 & 68\(\pm\)6 & 68\(\pm\)6 & 68\(\pm\)6 & 68\(\pm\)6 & 68\(\pm\)6 \\ \hline \end{tabular} \end{table} Table 2: The average number of ReLUs on their positive side in each hidden layer of our \(3072-256^{(8)}-10\) CIFAR10 model for 10k random inputs, as well as the rank of a linearized representation \(\mathcal{M}\) of the network up to the respective layer. equation per hidden layer neuron (in total \(256\)). Each equation \(k=1,\ldots,256\) contains the model output difference \(f(x+\Delta_{k})-f(x)\), and therefore, a total of \(256+1\) oracle calls are necessary. Even in our non-optimized implementation, the runtimes are well below thirty seconds for the CIFAR10 model. For the _Last Hidden Layer_ technique, we collect one equation per hidden layer neuron (in total \(256\)) and one equation per output neuron bias (in total \(10\)). #### 4.2.2 Results with the Neuron Wiggle Technique Table 4 shows the results of the sign recovery with the _Neuron Wiggle_ technique on our CIFAR10 model. Each neuron sign was recovered using \(200\) critical points. We find criticals point for each target neuron by starting from a randomly chosen input image from the CIFAR10 dataset. As detailed in section 5.1, the neuron Wiggle technique is statistical. We reanalyze borderline neurons with a low confidence level \(\alpha\leq\alpha_{0}\). Detailed neuron-by-neuron results for hidden layer \(7\) (of \(8\)) are shown in section 5. The mean sign recovery time per neuron in the relevant layers with layer IDs \(2,\ldots,8\) is \(\tilde{t}_{\text{total}}=(234\pm 44)\,\text{seconds}\). Note that the sign recovery of the \(256\) neurons within the same hidden layer can be parallelized. Therefore, a parallelized implementation of our sign recovery algorithm on a suitable \(256\)-core computer would take around \(4\) minutes per layer and a total of about \(32\) minutes for the \(8\)-hidden layer DNN. Compared to our preliminary experiments on the unitary balanced networks, the sign recovery time for the comparable-size CIFAR10 model is almost twice as long. The detailed analysis in section 5 shows that the increased execution time is due to finding critical points: in the actual CIFAR10 network, it takes around \(110\,\text{s}\), while it only took \(10\,\text{s}\) in the unitary balanced network. Notable differences to the unitary balanced network are a smaller _space of control_ and the existence of _always-off_ or _almost-always-off_ neurons, which makes finding critical points more challenging. \begin{table} \begin{tabular}{l|l l l|l l l} \hline \hline \multicolumn{6}{c}{_SOE_} & \multicolumn{6}{c}{_Last Hidden Layer_} \\ \hline layer ID & & queries & runtime & layer ID & & queries & runtime \\ \hline 1,2 & 256 & 256+1 & \((16\pm 1)\,\text{s}\) & \(8\) & \(256\) & \(256\)+\(10\) & \((189\pm 40)\,\text{s}\) \\ \hline \end{tabular} Column ‘queries’ contains the number of oracle queries. The runtime is the total execution time for recovering all neuron signs in seconds. For both, _SOE_ and _Last Hidden Layer_, these execution times can be significantly reduced further by parallelizing the implementation. \end{table} Table 3: Results of the sign recovery with the _SOE_ and _Last Hidden Layer_ techniques on our \(3072-256^{(8)}-10\) CIFAR10 model. Each hidden layer contains \(256\) neurons. All neuron signs can be recovered successfully (). ## 6 Conclusions In this paper, we presented the first polynomial-time algorithm for extracting the parameters of ReLU-based DNNs from their black-box implementation. We also demonstrated the practical efficiency of our sign recovery by applying it to a deep network for classifying CIFAR10 images. We used SOE (\(i=1,2\), \((16\pm 1)\) s per layer), Neuron Wiggling (\(i=3\ldots 7\), \((234\pm 44)\) s per layer) and Last Hidden Layer (\(i=8\), \((189\pm 40)\) s). The total required time is about 30 minutes. We also demonstrated its applicability to several layer deep, expanding networks whose width was much larger than the number of inputs (where all the previous techniques based on solving systems of linear equations failed). Among the many problems left open are: 1. Developing countermeasures and countercountermeasures for our attack. 2. Dealing with the case in which only the class decisions are provided rather than the exact logits. 3. Dealing with more modern machine learning architectures such as transformers. 4. Dealing with discrete domains such as texts in LLMs where derivatives are not well defined. \begin{table} \begin{tabular}{c|c c c c c} \hline \hline \multirow{2}{*}{layerID} & \(\alpha_{0}\) & **correct** & **fixable** & **incorrect** & \\ & (adaptive) & \((\alpha>0.5)\) and \(\swarrow\) & \((\alpha\leq\alpha_{0})\) and \(\times\) & (\(\alpha>\alpha_{0})\) and \(\times\) & runtime \\ \hline 1 & 0.79 & 255/256 & 1/256 & 0/256 & 1121 s \\ 2 & 0.67 & 254/256 & 2/256 & 0/256 & 185 s \\ 3 & 0.74 & 256/256 & 0/256 & 0/256 & 219 s \\ 4 & 0.74 & 256/256 & 0/256 & 0/256 & 295 s \\ 5 & 0.74 & 256/256 & 0/256 & 0/256 & 201 s \\ 6 & 0.75 & 256/256 & 0/256 & 0/256 & 269 s \\ 7 & 0.70 & 253/256 & 3/256 & 0/256 & 234 s \\ 8 & 0.77 & 252/256 & 4/256 & 0/256 & 384 s \\ \hline \hline \end{tabular} Note that our other two sign recovery techniques are faster for hidden layers 1, 2, and 8, and we only show the neuron wiggle timing for these layers for the sake of completeness. The column ’runtime’ refers to the mean runtime per neuron in the target layer, where the signs of all the neurons in the same layer can be extracted in parallel on a multicore computer. \end{table} Table 4: Results of the sign recovery with the _Neuron Wiggle_ method on hidden layers \(1,\ldots,8\) of our CIFAR10 model 3072-256\({}^{(8)}\)-10. Each hidden layer contains 256 neurons. The vast majority is evaluated **correctly** (\(\swarrow\)), even at a low confidence level (\(\alpha\approx 0.5\)). 256 highlights the cases where all neurons are analyzed correctly, even those with low confidence level \(\alpha\). Borderline neurons with a low confidence level (\(\alpha\leq\alpha_{0}\)) are re-evaluated. The column **fixable** contains the borderline neurons with wrongly recovered signs (\(\lhd\)) and low confidence level. Zero **incorrect** decisions (\(\lhd\)) were made with a high confidence level (\(\alpha>\alpha_{0}\)).
2307.02198
ChiENN: Embracing Molecular Chirality with Graph Neural Networks
Graph Neural Networks (GNNs) play a fundamental role in many deep learning problems, in particular in cheminformatics. However, typical GNNs cannot capture the concept of chirality, which means they do not distinguish between the 3D graph of a chemical compound and its mirror image (enantiomer). The ability to distinguish between enantiomers is important especially in drug discovery because enantiomers can have very distinct biochemical properties. In this paper, we propose a theoretically justified message-passing scheme, which makes GNNs sensitive to the order of node neighbors. We apply that general concept in the context of molecular chirality to construct Chiral Edge Neural Network (ChiENN) layer which can be appended to any GNN model to enable chirality-awareness. Our experiments show that adding ChiENN layers to a GNN outperforms current state-of-the-art methods in chiral-sensitive molecular property prediction tasks.
Piotr Gaiński, Michał Koziarski, Jacek Tabor, Marek Śmieja
2023-07-05T10:50:40Z
http://arxiv.org/abs/2307.02198v2
# ChiENN: Embracing Molecular Chirality with Graph Neural Networks ###### Abstract Graph Neural Networks (GNNs) play a fundamental role in many deep learning problems, in particular in cheminformatics. However, typical GNNs cannot capture the concept of chirality, which means they do not distinguish between the 3D graph of a chemical compound and its mirror image (enantiomer). The ability to distinguish between enantiomers is important especially in drug discovery because enantiomers can have very distinct biochemical properties. In this paper, we propose a theoretically justified message-passing scheme, which makes GNNs sensitive to the order of node neighbors. We apply that general concept in the context of molecular chirality to construct Chiral Edge Neural Network (ChiENN) layer which can be appended to any GNN model to enable chirality-awareness. Our experiments show that adding ChiENN layers to a GNN outperforms current state-of-the-art methods in chiral-sensitive molecular property prediction tasks. Keywords:Graph Neural Networks GNN Message-passing Chirality Molecular Property Prediction ## 1 Introduction Recent advances in Graph Neural Networks (GNNs) have revolutionized cheminformatics and enabled learning the molecular representation directly from chemical structures [9, 30]. GNNs are widely used in molecular property prediction [34, 20, 36, 31], synthesis prediction [17, 3], molecule generation [21, 2, 22], or conformer generation [19, 11, 33, 6]. Surprisingly, typical GNNs cannot capture the concept of chirality, roughly meaning they do not distinguish between a molecule and its mirror image, called enantiomer (see Fig. 1). Although enantiomers share many physical, chemical, and biological properties, they may behave remarkably differently when interacting with other chiral molecules, e.g. chiral proteins. For this reason, capturing chirality is critical in the context of drug design [23, 12, 10, 25, 16] and should not be ignored by the design of GNN architecture. A chiral molecule is a molecule with at least one chiral center which is usually a carbon atom with four non-equivalent constituents. The mirror image of a chiral molecule, called an enantiomer, cannot be superposed back to the original molecule by any combination of rotations, translations, and conformational changes (see Fig. 1). Therefore, enantiomers are molecules with different bond arrangements and the same graph connectivity. There are many examples of chiral drugs used in pharmacy whose enantiomers cause substantially different effects [23]. For instance (S)-penicillamine is an antiarthritic drug while its enantiomer (R)-penicillamine is extremely toxic [15]. Actually, chirality can be a characteristic of any class of graphs embedded in euclidean space (where we have an intuitive notion of reflection). For instance, Fig. 2 shows two 2D road maps that are mirror images of each other and possess different properties. For this reason, modeling chirality in GNNs is not restricted to the chemical domain. In this paper, we propose and theoretically justify a novel order-sensitive message-passing scheme, which makes GNNs sensitive to chirality. In contrast to existing methods of embracing chirality, our framework is not domain specific and does not rely on arbitrary chiral tagging or torsion angles (see Section 2). The only inductive bias our method introduces to a GNN is the dependency on the orientation of the neighbors around a node, which lies at the core of chirality. The key component of the proposed framework is the message aggregation function. In a typical GNN, the messages incoming to a node from its neighbors are treated as a set and aggregated with a permutation-invariant function (sum, max, etc.). It makes the model unable to distinguish between chiral graphs with the same connectivity, but with Figure 1: An example of a chiral molecule (left) and its mirror image (right). Figure 2: An illustration of a road map (left) and its mirror image (right). We see that the maps share the same connectivity between cities, however, to get from city \(A\) to city \(B\) one has to take the second exit on a roundabout \(D\) for the left map, and the first exit for the right map. different spatial arrangements. We re-invent this approach and introduce a message aggregation function that is sensitive to the spatial arrangement (order) of the neighbors. Our approach can be used in any chiral-sensitive graph domain where chirality can be expressed by an order of the neighboring nodes. We apply that general order-sensitive message-passing framework in the context of molecular chirality to construct Chiral Edge Neural Network (ChiENN) layer. The ChiENN layer can be appended to most molecular GNN models to enable chirality sensitiveness. Our experiments show that ChiENN can be successfully used within existing GNN models and as a standalone model consisting of stacked ChiENN layers. In both cases, ChiENN outperforms current state-of-the-art methods in chiral-sensitive molecular property prediction tasks by a large margin. We make our code publicly available1. Footnote 1: [https://github.com/gmum/ChiENN](https://github.com/gmum/ChiENN) Our contributions are as follows: 1. We propose and theoretically justify a general order-sensitive message-passing scheme. Our method can be adapted to any chiral-sensitive graph domain where chirality can be expressed by an order of the neighboring nodes (Section 3). 2. We use the proposed framework to construct a novel ChiENN layer that enables chirality awareness in any GNN model in the domain of molecular graphs (Section 4). The proposed ChiENN can be applied to any 3D graph task with the notion of chirality. 3. We evaluate and analyze the ChiENN layer and show that it outperforms current state-of-the-art methods in chiral-sensitive molecular property prediction tasks (Section 5). ## 2 Related Work **Explicit Tagging of Chiral Center.** The most common approach for incorporating chirality into GNN is to use local or global chiral tags [27, 18, 13]. Both local and global tagging can be seen in the following way. Every carbon atom with four non-equivalent constituents, called a chiral center, is given a tag (CCW or CW) describing the orientation of its constituents. The orientation is defined using the enumeration of constituents computed by an arbitrary algorithm. The constituent with the highest number (4) is positioned so that it points away from the observer. The curve passing through the constituents with numbers 1, 2, and 3 respectively determines a clockwise (CW) or counterclockwise (CCW) orientation of the chiral center. Although enumeration algorithms for global and local tagging differ (the latter is not explicitly used in practice), the expressivity of both methods is limited, as we show in Section 5. #### 2.0.1 3D GNNs with torsion angles. Some recent GNN models enrich graphs with 3D information, like distances between atoms [4, 20], angles between bonds [28, 8], and torsion angles between two bonds joined by another bond [5, 7]. As distances and angles are invariant to chirality, the torsion angles (that are negated upon reflection) are required for 3D GNN to express the chirality. However, even access to a complete set of torsion angles does not guarantee expressivity in chiral-sensitive tasks as shown in [1]. Torsion angles are sensitive to bond rotations and can also be negated by the reflection of a non-chiral molecule. In [1], the authors proposed the ChIRo model that instead of embedding single torsion angles, embeds sets of torsion angles with a common bond. ChIRo is the current state-of-the-art method for chiral-sensitive tasks. In contrast to ChIRo, our proposed method does not incorporate distances, angles, or torsion angles. It only relies on the orientation of neighbors around a node, making it more general and easily adaptable to other chiral graph domains. Moreover, our experiments show that the ChiENN layer outperforms ChIRo by a large margin on chiral-sensitive molecular tasks (see Section 5). #### 2.0.2 Changing Aggregation Scheme. The method most related to our approach is the Tetra-DMPNN model from [24] which replaces a classic message-passing scheme with a chiral-sensitive one. The proposed aggregation scheme is guided by local chiral tags, meaning that it relies on some arbitrary rules for enumerating neighbors and cannot be applied to nodes other than chiral centers. Moreover, the Tetra-DMPNN method is computationally expensive and does not scale with the number of possible neighbors of a chiral center, making the model useful only in the context of chemistry. Our approach provides a general, efficient, and scalable chiral-sensitive message passing and outperforms the Tetra-DMPNN on chiral-sensitive molecular tasks by a large margin (see Section 5). ## 3 Order-Sensitive Message-Passing Scheme **Setting.** Let us consider a directed graph \(G=(X,E)\) in which every node \(x_{i}\in X\) is represented by a \(N\)-dimensional encoding (\(x_{i}\in\mathbb{R}^{N}\)). Edge \(e_{ij}\) connects nodes \(x_{i}\) and \(x_{j}\) and is represented by \(M\)-dimensional encoding (\(e_{ij}\in\mathbb{R}^{M}\)). In addition, we assume that for every node \(x\in X\), we are given an order \(o\) of all its neighbors \(o=(x_{0},x_{1},\ldots,x_{d-1})\). The order of neighbors forms a sequence, which stands in contrast to typical graphs, where neighbors are treated as an unordered set. Given a permutation \(\pi\) on \(\{0,1,\ldots,d-1\}\), we assume that two orders \(o_{1}=(x_{0},\ldots,x_{d-1})\) and \(o_{2}=(x_{\pi(0)},\ldots,x_{\pi(d-1)})\) are equivalent if and only if \(\pi\) is a shift i.e. \(\pi(i)=(i+k)\) mod \(d\), for a fixed \(k\in\mathbb{Z}\). In other words, the neighbors form the sequence on a ring. One of the most common mechanisms in GNN is message-passing, which updates the representation of a node \(x\) by the information coming from its neighbors (\(x_{0},\ldots,x_{d-1}\)), which can be written as: \[x^{\prime}=f(x;x_{0},\ldots,x_{d-1}).\] In this paper, we are going to describe the general message-passing scheme, which is aware of the neighbors' order. Before that, we discuss possible choices of the aggregation function \(f\). #### 2.0.1 Vanilla message-passing as a permutation-invariant transformation. Let us first discuss a basic case, where \(f\) is a permutation-invariant function, i.e. \[f(x;x_{0},\ldots,x_{d-1})=f(x;x_{\pi(0)},\ldots,x_{\pi(d-1)}),\] for every permutation \(\pi\) of \(\{0,1,\ldots,d-1\}\). This aggregation ignores the order of neighbors and lies in a heart of typical GNNs. Let us recall that \(f\) is permutation-invariant with respect to \(\{x_{0},x_{1},\ldots,x_{d-1}\}\) if and only if it can be decomposed in the form [35]: \[f(x_{0},x_{1},\ldots,x_{d-1})=\rho(\sum_{i=0}^{d-1}\phi(x_{i})),\] for suitable transformations \(\phi\) and \(\rho\). In the context of graphs, a general form of a permutation-invariant aggregation of neighbors \(\{x_{0},x_{1},\ldots,x_{d-1}\}\) of \(x\) is: \[x^{\prime}=f(x;x_{0},\ldots,x_{d-1})=\rho(x;\sum_{i=0}^{d-1}\phi(x;x_{i})), \tag{1}\] for suitable transformations \(\phi\) and \(\rho\). By specifying \(\rho,\phi\) as neural networks, we get the basic formula of vanilla message-passing. #### 2.0.2 Shift-invariant aggregation. Vanilla message-passing relies on permutation-invariant aggregation and it does not take into account the neighbor's order. Thus we are going to discuss the weaker case of aggregation function \(f\) and assume that \(f\) is shift-invariant, i.e. \[f(x;x_{0},\ldots,x_{d-1})=f(x;x_{0+p},\ldots,x_{d-1+p}),\] for any shift by a number \(p\in{0,\ldots,d-1}\), where the additions on indices are performed modulo \(d\). This assumption is consistent with our initial requirement that shifted orders are equivalent. The following theorem gives a general formula for shift-invariant mappings. Theorem 2.1: _The function \(f\) is shift-invariant if and only if \(f\) can be written as:_ \[f(x_{0},\ldots,x_{d-1})=\sum_{p=0}^{d-1}g(x_{0+p},\ldots,x_{d-1+p})\] _for an arbitrary function \(g\)._ Proof: If \(f\) is shift invariant, then \(f(x_{0},\ldots,x_{d-1})=f(x_{0+p},\ldots,x_{d-1+p})\) for every \(p\), and consequently \[f(x_{0},\ldots,x_{d-1})=\sum_{p=0}^{d-1}\frac{1}{d}f(x_{0+p},\ldots,x_{d-1+p}).\] On the other hand, if the function \(f\) can be written as \(\sum_{p=0}^{d-1}g(x_{0+p},\ldots,x_{d-1+p})\), then it is shift-invariant for arbitrary function \(g\). Following the above theorem, we get a general formula for shift-invariant aggregation applicable to graphs: \[x^{\prime}=\rho(x;\sum_{p=0}^{d-1}\psi(x;x_{0+p},\ldots,x_{d-1+p})), \tag{2}\] for suitable \(\rho\) and \(\psi\), where all additions are performed modulo \(d\). Now, we want to ensure that our function \(f\) is not only shift-invariant but also order-sensitive #### 2.0.1 Order-sensitive message-passing. Let us assume that we are in the class of shift-invariant transformations. We are going to specify the formula (2) to obtain ab aggregation, which is sensitive to any permutation other than shift. More precisely, we say that \(f\) is order-sensitive if and only if for every permutation \(\pi\), we have: \[f(x;x_{0},\ldots,x_{d-1})=f(x;x_{\pi(0)},\ldots,x_{\pi(d-1)})\iff\pi(i)=(i+k) \text{ mod }d.\] Let us investigate typical functions \(\psi\) in formula (2), which can be implemented using neural networks. We start with the simplest case, where \(\psi\) is linear. Then \[\sum_{p=0}^{d-1}\psi(x_{0+p},\ldots,x_{d-1+p})=\sum_{p=0}^{d-1}\sum_{i=0}^{d-1 }w_{i}x_{i+p}=\sum_{i=0}^{d-1}w_{i}\sum_{p=0}^{d-1}x_{i+p}=\sum_{i=0}^{d-1}w_{i }\sum_{j=0}^{d-1}x_{j},\] does not depend on the order of the neighbors \((x_{0},...,x_{d-1})\). To construct more complex functions, we use an arbitrary Multi-Layer Perceptron (MLP) as \(\psi\). Since MLPs are universal approximators (for a sufficiently large number of hidden units), we can find such parameters \(\theta\) that \(\sum_{p=0}^{d-1}\psi_{\theta}(x_{\pi(0)+p},\ldots,x_{\pi(d-1)+p})\) returns a different value for every permutation \(\pi\) that is not a shift. Therefore our aggregation scheme with \(\psi\) given by MLP can learn order-sensitive mapping. Following the above observations, we implement our order-sensitive message-passing using MLP as \(\psi\). To match our construction to various numbers of neighbors in a graph, we restrict \(\psi\) to be \(k\)-ary (denoted as \(\psi^{k}\)) for some fixed \(k>1\) and overload it so that: \[\psi^{k}(x_{0},\ldots,x_{d-1})=\psi^{k}(x_{0},\ldots,x_{d-1},\underbrace{0, \ldots,0}_{k-d})\text{ for }d<k.\] Given that, we implement the Eq. (2) with the following neural network layer: \[\begin{split} x^{\prime}=Wx+\sum_{p=0}^{d-1}\psi^{k}(x_{0+p},...,x _{k-1+p}),\\ \psi^{k}(x_{0+p},...,x_{k-1+p})=W_{1}\sigma(W_{2}(x_{0+p}|...|x_{k- 1+p})).\end{split} \tag{3}\] Our \(k\)-ary message function \(\psi^{k}\) is composed of concatenation operator \(|\) and two-layer MLP with ELU as \(\sigma\). Intuitively, the output of \(\psi^{k}(x_{0+p},...,x_{k-1+p})\) can be seen as a message obtained jointly from \(k\) consecutive neighbors starting from a neighbor \(p\) in order \((x_{0},...,x_{d-1})\) which is illustrated in Fig. 3. ## 4 ChiENN: Chiral-Aware Neural Network In this section, we apply the order-sensitive message-passing framework to molecular graphs. We show that order-sensitive aggregation is a key factor for embracing molecular chirality. Roughly speaking, in contrast to vanilla message-passing, the proposed ChiENN (Chiral-aware Edge Neural Network) is able to distinguish enantiomers, where one molecule is a mirror image of the second. Although we evaluate the ChiENN model in the context of molecular property prediction, the proposed model can be applied to any 3D graph task with the notion of chirality. To construct ChiENN based on our order-sensitive message-passing scheme from Eq. (3), we need to define a notion of neighbors' order in molecular graphs that grasps the concept of chirality (see Fig. 4). We introduce this notion of order for edge (dual) molecular graphs and provide a simple transformation from standard molecular graphs to edge molecular graphs. Therefore the rest of the section is organized into three subsections: 1. **Edge Graph** describing the transformation from a molecular graph to its edge (dual) form used in our ChiENN model, 2. **Neighbors Order** defining the order of the neighbors in an edge graph, Figure 3: An illustration of our update rule for node \(x\) with 3 ordered neighbors \((x_{0},x_{1},x_{2})\) and for \(k=2\). We see that \(\psi^{k}\) is used to embed pairs of consecutive nodes. 3. **Chiral-Aware Update** constructing order-sensitive update rule using our order-sensitive framework from the Section 3. ### Edge Graph Let us suppose, we have a directed graph \(G=(X,C,E)\) that represents a concrete conformation (3D embedding) of a molecule. The node encoding \(x_{i}\in X\) corresponds to an \(i\)-th atom from a molecule, \(c_{i}\in C\subseteq\mathbb{R}^{3}\) are its coordinates in 3D space, and the edge encoding \(e_{ij}\in E\) represents a bond between \(i\)-th and \(j\)-th atoms. To make the definition of neighbor order straightforward, our ChiENN model operates on an edge (dual) graph \(G^{\prime}=(X^{\prime},C^{\prime},E^{\prime})\) which swaps nodes with edges from the original graph \(G\). It means that the node \(x_{ij}\in X^{\prime}\) represents the edge \(e_{ij}\in E\), while the edge \(e_{ij,jk}\in E^{\prime}\) represents the node \(x_{j}\) that connects edge \(e_{ij}\in E\) with \(e_{jk}\in E\). Similarly, \(c^{\prime}_{ij}\in\mathbb{R}^{3}\times\mathbb{R}^{3}\) is now a 3D coordinate vector that links positions \(c_{i}\) and \(c_{j}\). Formally, we have: \[X^{\prime} =\{x_{ij}=e_{ij}:e_{ij}\in E\},\] \[C^{\prime} =\{c_{ij}=c_{i}|c_{j}:c_{i},c_{j}\in C,e_{ij}\in E\},\] \[E^{\prime} =\{e_{ij,jk}=e_{ij}|x_{j}|e_{jk}:e_{ij},e_{jk}\in E,x_{j}\in X\},\] where \(|\) stands for a concatenation operator. Clearly, the constructed edge graph \(G^{\prime}=(X^{\prime},C^{\prime},E^{\prime})\) can be fed to any GNN that can take as an input the original graph \(G=(X,C,E)\). ### Neighbors Order In an edge molecular graph \(G=(X,C,E)\), a node \(x_{jk}\in E\) represents a directed bond from atom \(j\) to atom \(k\) in the original molecule. It is assigned with a 3D Figure 4: An intuitive illustration of the neighbor ordering in a molecule. First, we pick a directed bond from atom C to H and then order the rest of the neighbors around that bond. We observe that for a chiral molecule (left) and its mirror image (right), we obtain different orders of the \(COOH\), \(CH_{3}\), and \(OH\) constituents. vector \(c_{jk}\in C\subseteq\mathbb{R}^{3}\times\mathbb{R}^{3}\) spanned from atom \(j\) to atom \(k\). Therefore, we will sometimes refer to nodes as if they were 3D vectors. Let us consider the node \(x_{jk}\) and the set of its incoming neighbors: \(N(x_{jk})=\{x_{i_{1}j},x_{i_{2}j},...,x_{i_{d}j}\}\). By construction of \(G\), every node \(x_{jk}\) has a corresponding parallel node \(x_{kj}\). For simplicity, we will treat this parallel node separately and exclude it from the set of neighbors, i.e. \(x_{kj}\notin N(x_{jk})\). The construction of the neighbors \(N(x_{jk})\) order is illustrated in Fig. 5 and consists of two steps: 1. Transformation: first, we perform a sequence of 3D transformations on \(x_{jk}\) and \(N(x_{jk})\) to make \(x_{jk}\) anchored to coordinate origin, perpendicular to \(yz\) plane and pointed away from the observer (see Fig. 5 b)). 2. Sorting: second, we project the transformed neighbors \(N(x_{jk})\) to the \(yz\) plane and sort the projections by the angle to the \(y\) axis. Details of the above construction are presented in the supplementary materials. Two observations can be made regarding the above construction: **Observation 1**: _The above construction returns non-equivalent orders for a chiral center and its mirror image._ **Observation 2**: _Any \(SE(3)\) transformation of a molecule coordinates \(C\) and any internal rotation of its bonds (conformation) can only change the shift of the order \(o\), resulting in equivalent order \(o^{\prime}\)._ Figure 5: An illustration of ordering the neighbors \(\{x_{0},x_{1},x_{2}\}\) of \(x_{jk}\) for a chiral molecule (top) and its mirror image (bottom) around the chiral center \(j\). First, we perform a sequence of 3D transformations on \(x_{jk}\) and its neighbors to make \(x_{jk}\) anchored to coordinate origin, perpendicular to \(yz\) plane and pointed away from the observer. Next, we project the transformed neighbors to the \(yz\) plane and sort the projections by the angle to the \(y\) axis. We see that for the chiral molecule (top) and its mirror image (bottom), we obtained non-equivalent orders \((x_{1},x_{0},x_{2})\) and \((x_{0},x_{1},x_{2})\). Therefore, the above construction grasps the notion of chirality in a molecule and is additionally \(SE(3)\)- and conformation-invariant. We artificially excluded \(x_{kj}\) from a set of \(x_{jk}\) neighbors, because its parallel to \(x_{jk}\) and therefore its angle to \(y\) axis after the sequence of transformations is undefined. In theory, another neighbor \(x_{ij}\) can also be parallel to \(x_{jk}\) and should also be excluded from the neighbor set, but we have not observed such a case in our experiments and decided not to take it into account. ### Chiral-Aware Update Once we transformed a molecular graph to edge (dual) molecular graph \(G=(X,E,C)\) using transformation from Section 4.1 and assigned every node \(x_{jk}\) with an order of its neighbors \((x_{1},...,x_{d})\) using construction from Section 4.2, we can define the order-sensitive update rule of our ChiENN model: \[\begin{split}& x_{jk}^{\prime}=W_{1}x_{jk}+W_{2}x_{kj}+\sum_{p=0}^{ d-1}\psi^{k}(x_{0+p},...,x_{k-1+p}),\\ &\psi^{k}(x_{0+p},...,x_{k-1+p})=W_{3}\sigma(W_{4}(x_{0+p}|...|x_ {k-1+p})),\end{split} \tag{4}\] where \(\psi^{k}\) is \(k\)-ary message function and \(\sigma\) is ELU non-linear activation. The update rule is almost the same as that from Eq. (3), but here we add a term that explicitly embeds \(x_{kj}\) node, which was artificially excluded from the order of the \(x_{jk}\) neighbors. ## 5 Experiments We compare ChiENN with several state-of-the-art models on a variety of chiral-sensitive tasks. Details of experiments are described in Section 5.1, while the results can be found in Section 5.2. Furthermore, to validate design choices behind ChiENN we also conducted an ablation study, presented in Section 5.3. ### Set-up **Datasets.** We conduct our experiments on five different datasets affected by molecule chirality. First, two datasets proposed in [1] which are designed specifically to evaluate the capability of a model to express chirality: classification of tetrahedral chiral centers as R/S (which should be a necessary, but not sufficient, condition to learn meaningful representations of chiral molecules); and enantiomer ranking, in which pairs of enantiomers with enantioselective docking scores were selected, and the task was to predict which molecule of the pair had a lower binding affinity in a chiral protein pocket. Second, the binding affinity dataset, which is an extension of the previously described enantiomer ranking, with the same underlying molecules, but the task being regression of the binding affinity. Additionally, we take two datasets from the MoleculeNet benchmark [32] that do not explicitly require prediction of molecule chirality, but contain some percentage of molecules with chiral centers, and the underlying biological task in principle might be chirality-dependant: BACE, a binary classification dataset for prediction of binding results for a set of inhibitors of human \(\beta\)-secretase 1 (BACE-1) [29]; and Tox21, a multilabel classification dataset containing qualitative toxicity measurements on 12 different targets, including nuclear receptors and stress response pathways. #### 4.2.2 Reference methods. As reference models we consider several state-of-the-art neural network architectures for processing graphs, both chirality-aware and general: GPS [26], SAN [14], DMPNN [34], ChIRo [1], and Tetra-DMPNN [24]. For models not designed to process chirality, that is DMPNN, GPS, and SAN, we additionally considered their variants with chiral atom tags included in the node features, similar to [1]. For the proposed approach we consider both a pure model obtained by stacking several ChiENN layers, as well as combining ChiENN layers with other architectures (ChiENN+GPS and ChiENN+SAN). #### 4.2.3 Training details. All models were trained using Adam optimizer for up to 100 epochs, with a cosine learning rate scheduler with 10 warm-up epochs and gradient norm clipping, following the set-up of [26]. Cross-entropy and L1 loss functions were used for classification and regression, respectively. Note that in \begin{table} \begin{tabular}{l c c c} \hline \hline \multirow{2}{*}{Model} & \multirow{2}{*}{R/S} & Enantiomer & Binding \\ & & ranking & affinity \\ \cline{2-4} & Accuracy \(\uparrow\) & R. Accuracy \(\uparrow\) & MAE \(\downarrow\) \\ \hline DMPNN & 0.500\(\pm\)0.000 & 0.000\(\pm\)0.000 & 0.310\(\pm\)0.001 \\ DMPNN+tags & - & **0.701\(\pm\)0.003** & **0.285\(\pm\)0.001** \\ \hline GPS & 0.500\(\pm\)0.000 & 0.000\(\pm\)0.000 & 0.330\(\pm\)0.003 \\ GPS+tags & - & 0.669\(\pm\)0.037 & 0.318\(\pm\)0.004 \\ GPS+ChiENN & **0.989\(\pm\)0.000** & **0.753\(\pm\)0.004** & **0.258\(\pm\)0.001** \\ \hline SAN & 0.500\(\pm\)0.000 & 0.000\(\pm\)0.000 & 0.317\(\pm\)0.004 \\ SAN+tags & - & 0.722\(\pm\)0.004 & 0.278\(\pm\)0.003 \\ SAN+ChiENN & **0.987\(\pm\)0.001** & **0.764\(\pm\)0.005** & **0.257\(\pm\)0.002** \\ \hline ChIRo & 0.968\(\pm\)0.019 & 0.691\(\pm\)0.006 & 0.359\(\pm\)0.009 \\ Tetra-DMPNN & 0.935 \(\pm\)0.001 & 0.690\(\pm\)0.006 & 0.324\(\pm\)0.026 \\ ChiENN & **0.989\(\pm\)0.000** & **0.760\(\pm\)0.002** & **0.275\(\pm\)0.003** \\ \hline \hline \end{tabular} \end{table} Table 1: Comparison of ChiENN-based approaches with the reference methods on chiral-sensitive tasks. Methods are split into groups by the underlying base model, except for the bottom group which includes models specifically designed to be chiral-sensitive. We **bold** the best results in every group and _underline_ the best results across all groups. All variations of our method (ChiENN, SAN+ChiENN, and GPS+ChiENN) significantly outperform current state-of-the-art chiral-sensitive models. Note that for the R/S task, we omitted the results for models with chiral tags encoded in node features, for which the task is trivial. contrast to [1], to keep the set-up consistent across models we did not use triplet margin loss for ChIRo, and observed worse results than reported in [1]. We also performed a grid search with the identical budget (see Appendix B.1). For all datasets and models, we reported results averaged from three runs. For enantiomer ranking, binding affinity, and R/S, we used data splits provided by [1] and for BACE and Tox21, we used random splits with a train-valid-test ratio of 7:1:2. For each model and dataset, we report mean results from 3 independent runs with the best parameters picked by grid search. #### 5.1.3 Evaluation. Note that for the binding rank task we used accuracy modified with respect to [1]. We required the difference between the predicted affinity of two enantiomers to be higher than the threshold of 0.001. This led to ranking accuracy being equal to 0 for models unable to distinguish chiral molecules. ### Comparison with Reference Methods In this section, we compare ChiENN-based networks with state-of-the-art reference architectures using the experimental setting described in Section 5.1. #### 5.2.1 Chiral-sensitive tasks. The results on chiral-sensitive tasks are presented in Table 1. For both the enantiomer ranking and binding affinity, ChiENN-based approaches achieved the best results, producing a significant improvement in performance over the state-of-the-art chiral-aware architectures, that is ChIRo and Tetra-DMPNN. For both GPS and SAN, there was a significant improvement in performance due to the addition of ChiENN layers when compared to chiral tag inclusion. It demonstrates that ChiENN model can enable chiral-awareness demonstrating the general usefulness of the proposed layer, and the fact that it can be combined with a model preferred in a given task. Finally, as expected, all of the chirality-aware methods can properly distinguish chiral centers in the R/S task, while the baselines that do not capture the concept of chirality (DMPNN, GPS and SAN) cannot. Note that for this task, we omitted the results for models with chiral tags encoded in node features, for which the task is trivial. #### 5.2.2 Remaining tasks. The results on BACE and Tox21 tasks are in Table 2. We see that the ChiENN model achieves results comparable to state-of-the-art models, however the influence of chirality-sensitiveness on these tasks is not clear. For SAN we actually observed a slight drop in performance when using ChiENN layers, and for GPS the results remained roughly the same. The possible explanations for that might be either 1) lack of importance of chirality on predicted tasks, or 2) small dataset size, leading to overfitting in presence of chiral information. Our conclusion is that ChiENN layers significantly improve the performance in chiral-sensitive tasks, and produce comparable results in the other tasks, where the influence of chirality is not clear. We believe that further investigation on the influence of chirality on the tasks commonly used in the molecular property prediction domain would be beneficial and we leave it for future work. ### Ablation Studies #### 5.3.1 Comparison of \(k\)-ariness of the message function. We began with an analysis of the impact of \(k\)-ariness (Equation 3) of the message function used by ChiENN. Specifically, in this experiment, we used the pure variant of ChiENN, which is a graph neural network using ChiENN layers as message-passing layers. We varied \(k\in\{1,2,3\}\), where \(k=1\) disables the ability of the network to distinguish enantiomers as it collapses our order-sensitive message passing scheme from Eq. (3) to vanilla message-passing from Eq. (1). We considered values of \(k\) up to 3 since it corresponds to the airiness of standard chiral centers observed in the edge graphs (see Section 4.1) of molecules. The results are presented in Table 3. As expected, choosing \(k=1\) leads to a failure in distinguishing enantiomers (makes message passing permutation invariant), as demonstrated by minimum performance in R/S and enantiomer ranking tasks. Interestingly, for most datasets choosing \(k=2\) was sufficient, leading to a comparable performance to \(k=3\). The only exception to that was BACE dataset, for which a noticeable drop in performance was observed when using \(k=2\). We used \(k=3\) in the remainder of this paper. #### 5.3.2 Using ChiENN layer with existing models. Secondly, we conducted an ablation of different design choices that can be made to enable enantiomer recognition within the existing architectures. Specifically, we focused on the GPS model and considered using three different strategies: \begin{table} \begin{tabular}{l c c} \hline \hline \multirow{2}{*}{Model} & BACE & Tox21 \\ \cline{2-3} & AUC \(\uparrow\) & AUC \(\uparrow\) \\ \hline DMPNN & **0.847\(\pm\)0.015** & 0.813\(\pm\)0.008 \\ DMPNN+tags & 0.840\(\pm\)0.004 & **0.824\(\pm\)0.006** \\ \hline GPS & **0.841\(\pm\)0.004** & 0.821\(\pm\)0.000 \\ GPS+tags & 0.812\(\pm\)0.017 & **0.825\(\pm\)0.002** \\ GPS+ChiENN & 0.839\(\pm\)0.008 & 0.821\(\pm\)0.007 \\ \hline SAN & **0.846\(\pm\)0.012** & **0.842\(\pm\)0.007** \\ SAN+tags & 0.829\(\pm\)0.009 & 0.841\(\pm\)0.004 \\ SAN+ChiENN & 0.826\(\pm\)0.014 & 0.834\(\pm\)0.005 \\ \hline ChIRo & 0.815\(\pm\)0.010 & **0.847\(\pm\)0.005** \\ Tetra-DMPNN & 0.824\(\pm\)0.017 & 0.807\(\pm\)0.003 \\ ChiENN & **0.838\(\pm\)0.003** & 0.838\(\pm\)0.003 \\ \hline \hline \end{tabular} \end{table} Table 2: Comparison of ChiENN-based approaches with the reference methods on tasks **not** explicitly requiring chirality. We see that the ChiENN model achieves results comparable to state-of-the-art models. proposed in this paper, the inclusion of chiral tags in the node features of the graph, and finally, replacement of message passing layers with ChiENN layers. The results are presented in Table 4. Several observations can be made: first of all, in the case of R/S task, we can see that both using chiral tags and the ChiENN layers allows us to properly recognize chiral centers (and as stated before, due to the simplicity of the task, good performance here is a necessary, but not sufficient, requirement for learning meaningful chiral representations). Secondly, using ChiENN layers significantly improves the performance in the enantiomer ranking (explicitly requiring chirality) and binding affinity (implicitly requiring it) tasks, more than simply including chiral tags. Interestingly, combining chiral tags with edge graph transformation improves the performance compared to using the tags alone (though not as much as using ChiENN layers), suggesting that it might be a feasible general strategy. Finally, the results on two remaining tasks, that is BACE and Tox21, for which the impact of chirality is unclear, are less straightforward: in the case of BACE, GPS with edge graph transformation achieves the best performance, and in the case of Tox21, using both the edge graph transformation and including the chiral tags. However, we can conclude that using ChiENN layers outperforms simply including chiral tags in tasks requiring chirality, and have comparable performance to the baseline GPS in other tasks. ## 6 Conclusions In this paper, we proposed and theoretically justify a general order-sensitive message-passing scheme that can be applied to any chiral-sensitive graph do main where chirality can be expressed by an order of the neighboring nodes. We used the proposed framework to construct a novel ChiENN layer that enables chirality awareness in any GNN model in the domain of molecular graphs, where chirality plays an important role as it can strongly alter the biochemical properties of molecules. Our experiments showed that the ChiENN layer allows to outperform the current state-of-the-art methods in chiral-sensitive molecular property prediction tasks. ## Acknowledgements The research of J. Tabor was supported by the Foundation for Polish Science co-financed by the European Union under the European Regional Development Fund in the POIR.04.04.00-00-14DE/18-00 project carried out within the Team-Net program. The research of P. Gainski and M. Smieja was supported by the National Science Centre (Poland), grant no. 2022/45/B/ST6/01117. For the purpose of Open Access, the author has applied a CC-BY public copyright license to any Author Accepted Manuscript (AAM) version arising from this submission. ## Ethical Statement As we consider our work to be fundamental research, there are no direct ethical risks or societal consequences; these have to be analyzed per concrete application.
2305.06587
How Expressive are Spectral-Temporal Graph Neural Networks for Time Series Forecasting?
Spectral-temporal graph neural network is a promising abstraction underlying most time series forecasting models that are based on graph neural networks (GNNs). However, more is needed to know about the underpinnings of this branch of methods. In this paper, we establish a theoretical framework that unravels the expressive power of spectral-temporal GNNs. Our results show that linear spectral-temporal GNNs are universal under mild assumptions, and their expressive power is bounded by our extended first-order Weisfeiler-Leman algorithm on discrete-time dynamic graphs. To make our findings useful in practice on valid instantiations, we discuss related constraints in detail and outline a theoretical blueprint for designing spatial and temporal modules in spectral domains. Building on these insights and to demonstrate how powerful spectral-temporal GNNs are based on our framework, we propose a simple instantiation named Temporal Graph GegenConv (TGC), which significantly outperforms most existing models with only linear components and shows better model efficiency.
Ming Jin, Guangsi Shi, Yuan-Fang Li, Qingsong Wen, Bo Xiong, Tian Zhou, Shirui Pan
2023-05-11T05:56:38Z
http://arxiv.org/abs/2305.06587v2
# How Expressive are Spectral-Temporal Graph Neural Networks for Time Series Forecasting? ###### Abstract Spectral-temporal graph neural network is a promising abstraction underlying most time series forecasting models that are based on graph neural networks (GNNs). However, more is needed to know about the underpinnings of this branch of methods. In this paper, we establish a theoretical framework that unravels the expressive power of spectral-temporal GNNs. Our results show that linear spectral-temporal GNNs are universal under mild assumptions, and their expressive power is bounded by our extended first-order Weisfeiler-Leman algorithm on discrete-time dynamic graphs. To make our findings useful in practice on valid instantiations, we discuss related constraints in detail and outline a theoretical blueprint for designing spatial and temporal modules in spectral domains. Building on these insights and to demonstrate how powerful spectral-temporal GNNs are based on our framework, we propose a simple instantiation named _Temporal Graph GegenConv_ (TGC), which significantly outperforms most existing models with only linear components and shows better model efficiency. ## 1 Introduction Graph neural networks (GNNs) have achieved considerable success in static graph representation learning for many tasks [1]. Many existing studies, such as STGCN [2] and Graph WaveNet [3], have successfully extended GNNs to time series forecasting. Among these methods, either first-order approximation of ChebyConv [4] or graph diffusion [5] is typically used to model time series relations, where a strong assumption of local homophiles is made [6]. Thus, they are only capable of modeling _positive correlations_ between time series that exhibit strong similarities, and we denote this branch of methods as message-passing-based spatial-temporal GNNs (MP-STGNNs). Nevertheless, how to model real-world multivariate time series with complex spatial dependencies that evolve remains an open question. This complexity is depicted in Fig. 1, in which _differently signed relations_ between time series are evident. Recently, Cao et al. [7] introduced the concept of spectral-temporal GNNs (SPGTNNs), which sheds light on modeling differently signed time series correlations by approximating graph convolutions with a broad range of graph spectral filters beyond low-pass filtering [8; 9]. Though StemGNN [7] has achieved remarkable improvements in time series forecasting, the theoretical foundations of Figure 1: Differently signed spatial relations between time series in PeMS07 dataset. **Left**: Visualization of four randomly selected traffic sensor readings. **Right**: Spatial relations between time series may be different in two windows (e.g., A and D are positively and negatively correlated in windows 1 and 2, respectively). SPTGNNs remain under-researched. There are several unresolved fundamental questions: **Q1.** What is the general form of SPTGNNs? **Q2.** How expressive are SPTGNNs? **Q3.** When will they fail to generalize well? **Q4.** How to design provably expressive SPTGNNs? We establish a series of theoretical results (summarized in Fig. 2) to answer these questions. We begin by formulating a general framework of SPTGNNs (**Q1**; Sec. 3.1), and then prove its universality of linear models (i.e., linear SPTGNNs are powerful enough to represent arbitrary time series) under mild assumptions through the lens of discrete-time dynamic graphs (DTDGs) [10] and spectral GNNs [13]. We further discuss related constraints from various aspects (**Q3**; Sec. 3.2) to make our theorem useful in practice on _any_ valid instantiations. After this, we extend the color-refinement algorithm on DTDGs and prove that the expressive power of SPTGNNs is theoretically bounded by the proposed temporal 1-WL test (**Q2**; Sec. 3.2). To answer the last question (**Q4**; Sec. 3.3), we prove that under mild assumptions, linear SPTGNNs are sufficient to produce expressive time series representations with orthogonal function bases and individual spectral filters in their graph and temporal frequency-domain models. Our results, for the first time, unravel the learning capabilities of SPTGNNs and outline a blueprint for designing powerful GNN-based forecasting models. Drawing from and to validate these theoretical insights, we present a simple SPTGNN instantiation, named TGC (short for _Temporal Graph GegenConv_), that well generalizes related work in time series forecasting. Though our primary goal is not to achieve state-of-the-art performance, our method, remarkably, is very efficient and significantly outperforms numerous existing models on several time series benchmarks and forecasting settings _with minimal designs_. Comprehensive experiments on synthetic and real-world datasets demonstrate that: (1) Our approach excels at learning time series relations of different types compared to MP-STGNNs; (2) Our design principles, e.g., orthogonal bases and individual filtering, are crucial for SPTGNNs to perform well; (3) Our instantiation (TGC) can be readily augmented with nonlinearities and other common model choices. Finally, and more importantly, our findings pave the way for devising a broader array of provably expressive SPTGNNs. ## 2 Preliminaries In time series forecasting, given a series of historical observations \(\mathbf{X}\in\mathbb{R}^{N\times T\times D}\) encompassing \(N\) different \(D\)-dimensional variables across \(T\) time steps, we aim to learn a function \(f(\cdot):\mathbf{X}\mapsto\hat{\mathbf{Y}}\), where the errors between the forecasting results \(\hat{\mathbf{Y}}\in\mathbb{R}^{N\times H\times D}\) and ground-truth \(\mathbf{Y}\) are minimized with the following mean squared loss: \(\frac{1}{H}\sum_{t=1}^{H}||\hat{\mathbf{Y}}_{t}-\mathbf{Y}_{t}||_{F}^{2}\). \(H\) denotes the forecasting horizon. In this work, we learn an adjacency matrix \(\mathbf{A}\in\mathbb{R}^{N\times N}\) from the input window \(\mathbf{X}\) to describe the connection strength between \(N\) variables, as in [7]. Specifically, we use \(\mathbf{X}_{t}:=\mathbf{X}_{:,t,\cdot}\in\mathbb{R}^{N\times D}\) to denote the observations at a specific time \(t\), and \(\mathbf{X}_{n}:=\mathbf{X}_{n,:,:}\in\mathbb{R}^{T\times D}\) as a time series of a specific variable \(n\) with \(T\) time steps and \(D\) feature dimensions. Detailed preliminaries are in Appendix A. Graph Spectral Filtering.For simplicity and modeling the multivariate time series from the graph perspective, we let \(\mathcal{G}_{t}=(\mathbf{A},\mathbf{X}_{t})\) denote an _undirected_ graph snapshot at a specific time \(t\) with the node features \(\mathbf{X}_{t}\). In a graph snapshot, \(\mathbf{A}\) and its degree matrix \(\mathbf{D}\in\mathbb{R}^{N\times N}\) s.t. \(\mathbf{D}_{i,i}=\sum_{j=1}^{N}\mathbf{A}_{i,j}\) Figure 2: Venn diagram of our method and overview of our contributions. thus, its normalized graph Laplacian matrix \(\hat{\mathbf{L}}=\mathbf{D}^{-\frac{1}{2}}(\mathbf{D}-\mathbf{A})\mathbf{D}^{- \frac{1}{2}}\) is symmetric and can be proven to be positive semi-definite. We let the eigendecomposition of \(\mathcal{G}_{t}\) to be \(\hat{\mathbf{L}}=\mathbf{U}\mathbf{\Lambda}\mathbf{U}^{\top}\). Below, we define graph convolution to filter input signal in the spectral domain w.r.t. node connectivity. **Definition 1** (Graph Convolution).: _Assume there is a filter function of eigenvalues \(g(\cdot):[0,2]\mapsto\mathbb{R}\), we define the graph convolution on \(\mathcal{G}_{t}\) as filtering the input signal \(\mathbf{X}_{t}\) with the spectral filter:_ \[g(\mathbf{\Lambda})\star\mathbf{X}_{t}:=\mathbf{U}g(\mathbf{\Lambda})\mathbf{ U}^{\top}\mathbf{X}_{t}. \tag{1}\] Directly computing Eq. 1 is costly. We approximate the _learnable_ filter function \(g_{\theta}(\mathbf{\Lambda})\) with a truncated \(K\)-degree polynomial expansion: \(g_{\theta}(\lambda):=\sum_{k=0}^{K}\mathbf{\Theta}_{k,:}P_{k}(\lambda)\); thus, the graph spectral filtering takes the form of \(\mathbf{U}g_{\theta}(\mathbf{\Lambda})\mathbf{U}^{\top}\mathbf{X}_{t}\!:=\! \sum_{k=0}^{K}\mathbf{\Theta}_{k,:}\mathbf{U}P_{k}(\mathbf{\Lambda})\mathbf{ U}^{\top}\mathbf{X}_{t}\!=\!\sum_{k=0}^{K}\mathbf{\Theta}_{k,:}P_{k}(\hat{ \mathbf{L}})\mathbf{X}_{t}\). If \(g_{\theta}(\hat{\mathbf{L}})=\sum_{k=0}^{K}\mathbf{\Theta}_{k,:}P_{k}(\hat{ \mathbf{L}})\), we have the graph convolution redefined as: \(g(\mathbf{\Lambda})\star\mathbf{X}_{t}:=g_{\theta}(\hat{\mathbf{L}})\mathbf{ X}_{t}\). Orthogonal Time Series Representations.Time series can be analyzed in both time and spectral domains. In this work, we focus on modeling time series using sparse orthogonal representations. Specifically, for an input signal of the \(n^{\text{th}}\) variable, we represent \(\mathbf{X}_{n}\) by a set of orthogonal components \(\hat{\mathbf{X}}_{n}\). We provide further details in Appendix A, discussing _discrete Fourier transformation_ (DFT) and other applicable space projections with orthogonal bases. ## 3 Spectral-Temporal Graph Neural Networks We address _all_ research questions in this section. We first introduce the general form of SPTGNNs and then unravel the expressive power of this family of methods. On this basis, we further shed light on the design of powerful SPTGNNs with theoretical proofs. ### Formulation Overall Architecture.We illustrate the general framework of SPTGNNs in Fig. 3, where we stack \(M\) building blocks to capture spatial and temporal dependencies in spectral domains. Without loss of generality, we formulate this framework with the minimum redundancy and a straightforward optimization objective, where common add-ons in prior arts, e.g., spectral attention [14], can be easily incorporated. To achieve time series connectivity without prior knowledge, we directly use the latent correlation layer from [7], as this is not our primary focus. Building Block.From the graph perspective and given the adjacency matrix \(\mathbf{A}\), we can view the input signal \(\mathbf{X}\) as a particular DTDG with a sequence of regularly-sampled static graph snapshots \(\{\mathcal{G}_{t}\}_{t=0}^{T-1}\), where node features evolve but with fixed graph topology. In a SPTGNN block, we filter \(\mathbf{X}\) from the spatial and temporal perspectives in spectral domains with _graph spectral filters_ (GSFs) and _temporal spectral filters_ (TSFs). Formally, considering a single dimensional input \(\mathbf{X}_{d}:=\mathbf{X}_{:,:,d}\in\mathbb{R}^{N\times T}\), we define a SPTGNN block as follows without the residual connection: \[\mathbf{Z}_{d}=\mathcal{T}_{\phi_{d}}\Big{(}g_{\theta_{d}}(\hat{\mathbf{L}}) \mathbf{X}_{d}\Big{)}=\mathcal{T}_{\phi_{d}}\Big{(}\sum_{k=0}^{K}\mathbf{ \Theta}_{k,d}P_{k}(\hat{\mathbf{L}})\mathbf{X}_{d}\Big{)}. \tag{2}\] This formulation is straightforward. \(\mathcal{T}_{\phi}(\cdot)\) represents TSFs, which work in conjunction with space projectors (detailed in Sec. 3.3) to model temporal dependencies between node embeddings across snapshots. The internal expansion corresponds to GSFs' operation, which embeds node features in each snapshot \(\mathcal{G}_{t}\) by learning variable relations. The above process can be understood in different ways. The polynomial bases and coefficients generate distinct GSFs, allowing the internal \(K\)-degree expansion in Eq. 2 to be seen as a combination of different _dynamic graph profiles_ at varying hops in the graph domain. Each profile filters out a specific frequency signal. Temporal dependencies are then modeled for each profile before aggregation: \(\mathbf{Z}_{d}=\sum_{k=0}^{K}\mathcal{T}_{\phi_{d}}\Big{(}\mathbf{\Theta}_{k,d }P_{k}(\hat{\mathbf{L}})\mathbf{X}_{d}\Big{)}\), which is equivalent to our formulation. Alternatively, dynamic graph profiles can be formed directly in the spectral domain, resulting in the formulation in StemGNN [7] with increased model complexity. Figure 3: The general formulation of SPTGNNs with \(M\) building blocks to predict future values \(\hat{\mathbf{Y}}\) based on historical observations \(\mathbf{X}\). \(g_{\theta}(\cdot)\) and \(\mathcal{T}_{\phi}(\cdot)\) are graph and temporal spectral filters. \(\mathcal{F}(\cdot)\) and \(\mathcal{F}^{-1}(\cdot)\) are forward and inverse space projectors. ### Expressive Power of Spectral-Temporal GNNs In this section, we develop a theoretical framework bridging spectral and dynamic GNNs, elucidating the expressive power of SPTGNNs for modeling time series data. All proofs are in Appendix C. Linear GNNs.For a linear GNN on \(\mathbf{X}\in\mathbb{R}^{N\times D}\), we define it using a trainable weight matrix \(\mathbf{W}\) and parameterized spectral filters \(g_{\theta}(\hat{\mathbf{L}})\) as \(\tilde{\mathbf{Z}}=g_{\theta}(\hat{\mathbf{L}})\mathbf{X}\mathbf{W}\). This simple linear GNN can express any polynomial filter functions, denoted as _Polynomial-Filter-Most-Expressive_ (PFME), under mild assumptions [13]. Its expressiveness establishes a lower bound for spectral GNNs. To examine the expressive power of SPTGNNs, we generalize spectral GNNs to model dynamic graphs. For simplicity, we initially consider linear GNNs with a single linear mapping \(f_{\phi}(\cdot)\). To align with our formulation, \(\mathcal{T}_{\phi}(\cdot)\) should also be linear functions; thus, Eq. 2 can be interpreted as a linear GNN extension, where \(f_{\phi}(\cdot)\) depends on historical observations instead of a graph snapshot. Accordingly, linear SPTGNNs establish a lower bound for the expressive power of SPTGNNs. **Proposition 1**.: _A SPTGNN can differentiate any pair of nodes at an arbitrary valid time that linear SPTGNNs can if \(\mathcal{T}_{\phi}(\cdot)\) can express any linear time-variant functions._ Despite their simplicity, linear SPTGNNs maintain the fundamental spectral filtering forms of SPTGNNs. We begin by defining the _universal approximation theorem_ for linear SPTGNNs. **Theorem 1**.: _A linear SPTGNN can produce arbitrary dimensional time series representations at any valid time iff: (1) \(\hat{\mathbf{L}}\) has no repeated eigenvalues; (2) \(\mathbf{X}\) encompasses all frequency components with respect to the graph spectrum; (3) \(\mathcal{T}_{\phi}(\cdot)\) can express any single-dimensional univariate time series._ Next, we separately explore these conditions and relate them to practical spectral-temporal GNNs. Multidimensional and Multivariate Prediction.In a graph snapshot, each dimension may exhibit different properties, necessitating distinct filters for processing [13]. An example with two-dimensional predictions is provided in Fig. 4. A simple solution involves using multidimensional polynomial coefficients, as explicitly shown in Eq. 2. A concrete example is presented in [8], where given a series of Bernstein bases, different polynomial coefficients result in various Bernstein approximations, corresponding to distinct GSFs. Similarly, when modeling temporal clues between graph snapshots, either dimension in any variable constitutes a unique time series requiring a specific filtering. An example reconstructing a two-variate time series of one dimension is in Fig. 4. In practice, we use multidimensional masking and weight matrices for each variable, forming a set of different TSFs. This is discussed in Sec. 3.3. Missing Frequency Components and Repeated Eigenvalues.GSFs can only scale existing frequency components of specific eigenvalues. For each graph snapshot, linear SPTGNNs cannot generate new frequency components if certain frequencies are missing from the original graph spectrum. For instance, in Fig. 4, a frequency component corresponding to \(\lambda=1\) cannot be generated with a spectral filter. Although this issue is challenging to address, it is rare in real-world attributed graphs [13]. In a graph with repeated eigenvalues given its topology, multiple frequency components will be scaled by the same \(P_{k}(\lambda)\), thus affecting spectral filtering. Universal Temporal Spectral Filtering.For a finite-length one-dimensional univariate time series, it can be provably modeled using a _frequency-domain model_ (FDM), consisting of sparse orthogonal space projectors and spectral filters. Fig. 4 exemplifies modeling two time series with distinct TSFs. Further details are discussed in Sec. 3.3. Figure 4: Multidimensional and multivariate predictions. **Left:** Multidimensional predictions within a snapshot require individual filtration for each output dimension to preserve different information. **Right:** Individual filter is needed to model each single-dimensional time series. Nonlinearity.Nonlinear activation can be applied in both GSFs and TSFs. In the first case, we examine the role of nonlinearity over the spatial signal, i.e., \(\sigma(\mathbf{X}_{t})\), enabling frequency components to be mixed w.r.t. the graph spectrum [13]. In the second case, we investigate the role of nonlinearity over the temporal signal by studying its equivalent effect \(\sigma^{\prime}(\cdot)\), as \(\sigma(\tilde{\mathbf{X}}_{n})=\mathcal{F}^{-1}\big{(}\sigma^{\prime}(\mathcal{ F}(\mathbf{X}_{n}))\big{)}\). Here, we have \(\sigma^{\prime}(\tilde{\mathbf{X}}_{n})=\mathcal{F}\big{(}\sigma(\mathcal{F}^ {-1}(\tilde{\mathbf{X}}_{n}))\big{)}\), where different components in \(\tilde{\mathbf{X}}_{n}\) are first mixed (e.g., via Eq. S6) and then element-wise transformed by a nonlinear function \(\sigma(\cdot)\) before being redistributed (e.g., via Eq. S5). Consequently, a similar mixup exists, allowing different components to transform into each other in an orthogonal space. Connection to Dynamic Graph Isomorphism.Analyzing the expressive power of GNNs is often laid on graph isomorphism. In this context, we first define the _temporal Weisfeiler-Lehman (WL) test_ and subsequently establish a connection to linear SPTGNNs in Theorem 2. **Definition 2** (Temporal 1-WL test).: _Temporal 1-WL test on discrete-time dynamic graphs \(\mathcal{G}:=\{\mathcal{G}_{t}\}_{t=0}^{T-1}\) with a fixed node set \(\mathbb{V}\) is defined below with iterative graph coloring procedures:_ _Initialization: All node colors are initialized using node features. In a snapshot at time \(t\), we have_ \(\forall v\in\mathbb{V},c^{(0)}(v,t)=\mathbf{X}_{t}[v]\)_. In the absence of node features, all nodes get the same color._ _Iteration: At step \(l\), node colors are updated with an injective (hash) function: \(\forall v\in\mathbb{V},t\in[1,T),c^{(l+1)}(v,t)=\textsc{Hash}(c^{(l)}(v,t),c^ {(l)}(v,t-1),\{\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\! \!\! ### Design of Spectral Filters In this section, we outline a blueprint for designing powerful SPTGNNs, with all proofs available in Appendix C. We initially explore the optimal acquisition of spatial node embeddings within individual snapshots, focusing on the selection of the polynomial basis, \(P_{k}(\cdot)\), for linear SPTGNNs. **Theorem 3**.: _For a linear SPTGNN optimized with mean squared loss, any complete polynomial bases result in the same expressive power, but an orthonormal basis guarantees the maximum convergence rate if its weight function matches the graph signal density._ This theorem guides the design of GSFs for learning node embeddings in each snapshot w.r.t. the optimization of coefficients. Following this, we discuss the optimal modeling of temporal clues between snapshots in spectral domains. We begin by analyzing the function bases in space projectors. **Lemma 1**.: _A time series with data points \(x_{j}(t)\) can be expressed by \(Q\) uncorrelated components \(z_{i}(t)\) with an orthogonal (possibly complex) projector [16], i.e., \(x_{j}(t)=\sum_{i=1}^{Q}e_{ij}z_{i}(t)\). The eigenvectors \(e_{i}\) are orthogonal and determine the relationship between the data points \(x_{j}(t)\)._ Operating on all spectral components is normally unnecessary [17; 14]. Consider a multivariate time series \(\mathbf{X}_{1}(t),\cdots,\mathbf{X}_{N}(t)\), where each \(T\)-length univariate time series \(\mathbf{X}_{i}(t)\) is transformed into a vector \(\mathbf{a}_{i}=(a_{i,1},\cdots,a_{i,T})^{\top}\in\mathbb{R}^{T\times 1}\) through a space projection. We form matrix \(\mathbf{A}=(\mathbf{a}_{1},\mathbf{a}_{2},\cdots,\mathbf{a}_{N})^{\top}\in \mathbb{R}^{N\times T}\) and apply a linear spectral filter as \(\mathbf{AW}\). Note that \(\mathbf{A}\) does _not_ denote the adjacency matrix here. We then randomly select \(S<T\) columns in \(\mathbf{A}\) using the masking matrix \(\mathbf{S}\in\{0,1\}^{S\times T}\), obtaining compact representation \(\mathbf{A}^{\prime}=\mathbf{AS}^{\top}\) and linear spectral filtration as \(\mathbf{A}^{\prime}\mathbf{W}\). We demonstrate that, under mild conditions, \(\mathbf{A}^{\prime}\mathbf{W}\) preserves most information from \(\mathbf{AW}\). By projecting each column vector of \(\mathbf{A}\) into the subspace spanned by column vectors in \(\mathbf{A}^{\prime}\), we obtain \(P_{\mathbf{A}^{\prime}}(\mathbf{A})=\mathbf{A}^{\prime}(\mathbf{A}^{\prime})^ {\dagger}\mathbf{A}\). Let \(\mathbf{A}_{k}\) represent \(\mathbf{A}\)'s approximation by its \(k\) largest singular value decomposition. The lemma below shows \(||\mathbf{AW}-P_{\mathbf{A}^{\prime}}(\mathbf{A})\mathbf{W}||_{F}\) is close to \(||\mathbf{W}||_{F}||\mathbf{A}-\mathbf{A}_{k}||_{F}\) if the number of randomly sampled columns \(S\) is on the order of \(k^{2}\). **Lemma 2**.: _Suppose the projection of \(\mathbf{A}\) by \(\mathbf{A}^{\prime}\) is \(P_{\mathbf{A}^{\prime}}(\mathbf{A})\), and the coherence measure of \(\mathbf{A}\) is \(\mu(\mathbf{A})=\Omega(k/N)\), then with a high probability, the error between \(\mathbf{AW}\) and \(P_{\mathbf{A}^{\prime}}(\mathbf{A})\mathbf{W}\) is bounded by \(||\mathbf{AW}-P_{\mathbf{A}^{\prime}}(\mathbf{A})\mathbf{W}||_{F}\leq(1+ \epsilon)||\mathbf{W}||_{F}||\mathbf{A}-\mathbf{A}_{k}||_{F}\) if \(S=O(k^{2}/\epsilon^{2})\)._ The lemmas above demonstrate that in most cases we can express a 1-dimensional time series with (1) orthogonal space projectors and (2) a reduced-order linear spectral filter. For practical application on \(D\)-dimensional multivariate time series data, we simply extend dimensions in \(\mathbf{S}\) and \(\mathbf{W}\). **Theorem 4**.: _Assuming accurate node embeddings in each snapshot, a linear SPTGNN can, with high probability, produce expressive time series representations at valid times if its temporal FDMs consist of: (1) Linear orthogonal space projectors; (2) Individual reduced-order linear spectral filters._ ### Connection to Related Work Here, we briefly discuss the connection between our theoretical framework and other GNN-based methods. See Appendix B for detailed related work. In comparison to MP-STGNNs, our approach offers two main advantages: (1) It can model differently signed time series relations by learning a wide range of GSFs (e.g., low-pass and high-pass); (2) On this basis, it can represent arbitrary multivariate time series under mild assumptions with provably expressive temporal FDMs. As such, our results effectively generalize these methods (Fig. 2). While a few studies on SPTGNNs exist, e.g., StemGNN [7], our work is the first to establish a theoretical framework for generalizing this family of methods, which is strictly more powerful. See Appendix B for detailed comparisons. ## 4 Instantiation In this section, we present a straightforward yet effective instantiation based on the discussion in Sec. 3. We first outline the basic formulation of the proposed Temporal Graph \(\underline{\mbox{{Ge}gen}}\underline{\mbox{{Conv}}}\) (TGC) and then connect it to other common practices. For the sake of clarity, we primarily present the canonical TGC, which contains _only_ linear components in its building blocks and strictly inherits the basic formulation presented in Fig. 3. Refer to Appendix D for model details. Again, our primary aim here is not to achieve state-of-the-art performance, but rather to validate our theoretical insights through the examination of TGC (and one of its variants, TGC\({}^{\dagger}\)). Graph Convolution.We implement \(P_{k}(\cdot)\) in GSFs using the Gegenbauer basis due to its (1) generality and simplicity among orthogonal polynomials, (2) universality regarding its weight function, and (3) reduced model tuning expense. The Gegenbauer basis has the form \(P_{k}^{\alpha}(x)=\frac{1}{k}[2x(k+\alpha-1)P_{k-1}^{\alpha}(x)-(k+2\alpha-2)P_{ k-2}^{\alpha}(x)]\), with \(P_{0}^{\alpha}(x)=1\) and \(P_{1}^{\alpha}(x)=2\alpha x\) for \(k<2\). Specifically, \(P_{k}^{\alpha}(x),k=0,1,...\) are orthogonal on the interval \([-1,1]\) w.r.t. the weight function \((1-x^{2})^{\alpha-1/2}\). Based on this, we rewrite \(P_{k}(\hat{\mathbf{L}})\) in Eq. 2 as \(P_{k}^{\alpha}(\mathbf{I}-\hat{\mathbf{L}})=P_{k}^{\alpha}(\hat{\mathbf{A}})\), and the corresponding graph frequency-domain model (convolution) is defined as \(\sum_{k=0}^{K}\theta_{k}P_{k}^{\alpha}(\hat{\mathbf{A}})\mathbf{X}\). Temporal Frequency-Domain Models.When designing temporal FDMs, linear orthogonal projections should be approximately sparse to support dimension reduction, e.g., DFT. For spectral filters, we randomly select \(S\) frequency components before filtration. Specifically, for components \(\mathbf{f}\in\mathbb{C}^{T}\) in \(\mathbf{F}\in\mathbb{C}^{N\times T\times D}\) along \(N\) and \(D\) dimensions, we denote sampled components as \(\mathbf{f}^{\prime}:=\mathbf{f}_{1}\in\mathbb{C}^{S}\), where \(\mathbf{I}=\{i_{0},\cdots,i_{S-1}\}\) is a set of selection indices s.t. \(\forall s\in\{0,\ldots,S-1\}\) and \(i_{s-1}<i_{s}\). This is equivalent to \(\mathbf{f}^{\prime}=\mathbf{f}\hat{\mathbf{S}}^{\top}\) with \(\hat{\mathbf{S}}\in\{0,1\}^{S\times T}\), where \(\hat{\mathbf{S}}_{i,s}=1\) if \(i=i_{s}\). Thus, a standard reduced-order TSF is defined as \(\mathbf{f}^{\prime}=\mathbf{f}\hat{\mathbf{S}}^{\top}\mathbf{W}\) with a trainable weight matrix \(\mathbf{W}\in\mathbb{C}^{S\times S}\). TGC Building Block.Suppose \(\tilde{\mathbf{Z}}=\sum_{k=0}^{K}\theta_{k}P_{k}^{\alpha}(\hat{\mathbf{A}}) \mathbf{X}\), we discuss two linear toy temporal FDMs. We first consider a basic coarse-grained filtering with the masking and weight matrices \(\mathbf{S}_{1}\) and \(\mathbf{\Phi}_{1}\): \[\mathbf{F}=\mathcal{F}(\tilde{\mathbf{Z}}),\quad\mathbf{F}^{\prime}=\textsc{ Pad}(\mathbf{FS}_{1}^{\top}\mathbf{\Phi}_{1}),\quad\mathbf{Z}^{\prime}= \mathcal{F}^{-1}(\mathbf{F}^{\prime}). \tag{3}\] Next, we consider an _optional_ fine-grained filtering based on time series decomposition, where \(\mathbf{S}_{2}\) and \(\mathbf{\Phi}_{2}\) are optimized to further capture the information in detailed signals (e.g., seasonalities) while maintaining global time series profiles (i.e., trends): \[\mathbf{Z}^{\prime}_{t},\mathbf{Z}^{\prime}_{s}=\textsc{Decomp}(\mathbf{Z}^{ \prime}),\quad\mathbf{F}_{s}=\mathcal{F}(\mathbf{Z}^{\prime}_{s}),\quad \mathbf{F}^{\prime}_{s}=\textsc{Pad}(\mathbf{F}_{s}\mathbf{S}_{2}^{\top} \mathbf{\Phi}_{2}),\quad\mathbf{Z}=\mathbf{Z}^{\prime}_{t}+\mathcal{F}^{-1}( \mathbf{F}^{\prime}_{s}). \tag{4}\] After stacking multiple blocks, we forecast by transforming time series representations \(\mathbf{Z}\). For time series decomposition and component padding, i.e., \(\textsc{Decomp}(\cdot)\) and \(\textsc{Pad}(\cdot)\), refer to Appendix D. In the same appendix, we also show that this implementation can be further boosted with the inclusion of nonlinearities and other common model choices (TGC\({}^{\dagger}\)), leading to more competitive performance. Connection to Other Polynomial Bases.We compare our design in TGC with other common practices in approximating graph convolutions: Monomial, Chebyshev, Bernstein, and Jacobi bases. More details are in Appendix E. For non-orthogonal polynomials, such as Monomial and Bernstein, our method with the Gegenbauer basis guarantees faster model convergences (Theorem 3) and better empirical performances in most cases. Compared with other orthogonal polynomials, we know that: (1) Our basis is a generalization of the second-kind Chebyshev basis; (2) Though our choice is a particular form of the Jacobi basis, the orthogonality of the Gegenbauer basis is well-posed in most real-world scenarios concerning its weight function; thus, our design is a simpler and nearly optimal solution for our purpose with only minor performance degradation. ## 5 Experiment In this section, we evaluate the effectiveness and efficiency of our method on seven real-world benchmarks by comparing TGC and TGC\({}^{\dagger}\) with twenty different baselines. To empirically validate our theoretical claims, we further perform extensive ablation studies and present a variety of visualizations using both synthetic and real-world examples. Main Results.Our method is evaluated against related work in terms of model effectiveness (Tab. 1 and Tab. 2, averaged over 5 runs) and efficiency (Tab. 3, averaged over 5 runs), showcasing the potential of SPTGNNs for time series forecasting. Our additional result statistics are in Appendix H. We compare our vanilla instantiation (TGC) with the most pertinent and representative works in Tab. 1 (_left_) on four traffic benchmarks, employing the forecasting protocol from [7]. Next, we assess our method (TGC\({}^{\dagger}\), the nonlinear version of TGC) against state-of-the-art STGNNs in Tab. 1 (_right_), utilizing a standard testbed from [18]. Additionally, we report long-term forecasting results in Tab. 2, comparing our approach with state-of-the-art models and adhering to the setting in [29]. Detailed experimental setups are available in Appendix G. Our method consistently outperforms most baselines by significant margins in Tab. 1 and Tab. 2. In short-term forecasting, TGC and TGC\({}^{\dagger}\) achieve average performance gains of 7.3% and 1.7% w.r.t. the second-best results. Notably, we observe a significant improvement (\(\sim\)8%) over StemGNN [7], a special case of our method with nonlinearities. Considerable enhancements are also evident when compared to ASTGCN [23] (\(\sim\)9%) and LSGCN [25] (\(\sim\)7%), which primarily differ from StemGNN in temporal dependency modeling and design nuances. In long-term forecasting, our method further exhibits impressive performance, outperforming the second-best results by about 3.3%. These results indicate that even simple, yet appropriately configured SPTGNNs (discussed in Sec. 3.3) are potent time series predictors. In Tab. 3, we examine our method's efficiency by comparing TGC to representative baselines. We find that TGC forms the simplest and most efficient SPTGNN to date compared with StemGNN. In comparison to other STGNNs, such as STGCN [2] and DCRNN [22], our method also exhibits superior model efficiency across various aspects. Though deep time series models like LSTNet [19] are faster in model training, they do not have spatial modules and thus less effective. Evaluation of Modeling Time Series Dependencies.Our method, in contrast to most GNN-based approaches, excels at learning different signed spatial relations between time series. Predetermined or learned graph topologies typically reflect the strength of underlying connectivity, yet strongly correlated time series might exhibit distinct properties (e.g., trends), which MP-STGNNs often struggle to model effectively. To substantiate our claims, we first visualize and compare the learned TGC and STGCN\((1^{st})\)[2] representations on two synthetic time series groups with positive and negative correlations. Fig. 5(a) reveals that STGCN\((1^{st})\) fails to differentiate between the two correlation groups. This is because methods like STGCN\((1^{st})\) aggregate neighborhood information with a single perspective (i.e., low-pass filtration). We further examine the learned embeddings of two groups of randomly sampled time series between TGC and STGCN\((1^{st})\) on a real-world traffic dataset (Fig. 5(b)), where similar phenomena can be observed. Our experimental settings are detailed in Appendix G. Ablation Studies.We perform ablation studies from three perspectives. First, we evaluate the GSFs in TGC with different polynomial bases (A.1 to A.5) in the first block. Next, we examine other core designs in the second block: B.1 and B.2 apply identical polynomial coefficients in GSFs and \begin{table} \begin{tabular}{c c c c c c c c c c} \hline \hline \multirow{2}{*}{Method} & MAE & RMSE & MAE & RMSE & MAE & RMSE & MAE & RMSE & RMSE \\ \hline \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} \\ \hline LSTNet [19] & 10.70 & 29.67 & 26.40 & 37.38 & 2.34 & 4.26 & 20.36 & 31.69 & 20.16 \\ DeepGLO [12] & 10.55 & **29.10** & 26.50 & 33.00 & 3.35 & 6.49 & 19.34 & 27.18 & 19.42 & 21.78 \\ DCRNN [22] & 17.25 & 23.25 & 25.54 & 35.90 & 3.01 & 5.25 & 15.12 & 25.22 & 25.22 \\ DCRNN [22] & 18.18 & 30.31 & 24.70 & 38.12 & 2.25 & 4.04 & 17.86 & 27.83 & 26.75 \\ STGCN [2] & 17.49 & **30.12** & 22.70 & 35.50 & 2.25 & 4.04 & 18.02 & 27.43 & 18.02 \\ GWN [7] & 19.85 & **32.54** & 29.88 & 37.90 & **1.91** & 28.16 & 27.95 & 18.94 & 20.25 \\ STGNN(7) & 14.32 & 21.64 & 20.24 & 21.25 & 21.44 & 4.01 & 15.83 & 24.02 & 16.51 & 25.97 \\ TGC **(Onsns)** & **13.52** & 21.74 & **18.77** & **29.92** & **1.92** & **3.35** & **14.58** & **22.73** \\ \hline \hline \end{tabular} \end{table} Table 1: Short-term forecasting results on four traffic benchmarks. We use the **bold** and underline fonts to indicate the best and second-best results. We follow [7] and [18] for the experimental setting and baseline results in left and right tables, respectively. \begin{table} \begin{tabular}{c|c c c c c c c c c c c c c} \hline \hline Method & \multicolumn{2}{c}{TGC\({}^{\dagger}\)} & \multicolumn{2}{c}{PLM [29]} & \multicolumn{2}{c}{PLGNN\({}^{\dagger}\)} & \multicolumn{2}{c}{Autrophance [20]} & \multicolumn{2}{c}{Inceptance [31]} & \multicolumn{2}{c}{LootTanks [22]} & \multicolumn{2}{c}{Retrome [33]} \\ \hline Metrics & MAE & RMSE & MAE & RMSE & MAE & RMSE & MAE & RMSE & MAE & RMSE & MAE & RMSE \\ \hline 5 & 0.90 & 0.20 & 0.42 & **0.30** & **0.49** & 0.297 & 0.427 & 0.317 & 0.488 & 0.382 & 0.357 & 0.507 & 0.402 & 0.558 \\ 192 & 0.20 & 0.42 & **0.29** & **0.44** & 0.308 & 0.442 & 0.334 & 0.471 & 0.386 & 0.544 & 0.368 & 0.513 & 0.433 & 0.500 \\ 336 & 0.313 & 0.470 & **0.25** & **0.43** & 0.313 & 0.460 & 0.338 & 0.480 & 0.394 & 0.548 & 0.380 & 0.529 & 0.433 & 0.591 \\ \hline 3 & 90.6 & **0.25** & **0.46** & 0.254 & 0.446 & 0.296 & 0.465 & 0.336 & 0.515 & 0.384 & 0.547 & 0.400 & 0.677 & 0.996 & 0.800 \\ 192 & **0.26** & **0.46** & **0.28** & 0.288 & 0.475 & 0.365 & 0.352 & 0.387 & 0.554 & 0.544 & 0.773 & 0.559 & 0.811 & 0.638 & 0.867 \\ 336 & **0.317** & **0.515** & 0.233 & 0.516 & 0.380 & 0.552 & 0.395 & 0.599 & 0.523 & 0.760 & 0.652 & 0.892 & 0.596 & 0.799 \\ \hline 96 & **0.324** & **0.443** & 0.311 & 0.557 & 0.363 & 0.448 & 0.532 & 0.267 & 0.254 & 0.469 & 0.255 & 0.451 \\ 192 & **0.29** & **0.479** & 0.356 & 0.595 & 0.354 & 0.483 & 0.674 & 0.586 & 0.280 & 0.487 & 0.254 & 0.489 & 0.274 & 0.472 \\ 336 & **0.271** & **0.478** & 0.370 & 0.628 & 0.372 & 0.518 & 0.957 & 1.131 & 0.285 & 0.496 & 0.295 & 0.512 & 0.228 \\ \hline \hline \end{tabular} \end{table} Table 2: Long-term forecasting results on three time series. We follow [29] for the experimental setting and baseline results. We use same notations as in Tab. 1. \begin{table} \begin{tabular}{c c c c c c c c} \hline \hline Method & \multicolumn{2}{c}{_PMS03_} & \multicolumn{2}{c}{_PMS04_} & \multicolumn{2}{c}{_PMS057_} & \multicolumn{2}{c}{_PMS08_} \\ \hline LSTNet & 0.4/2.2/3.8 & 0.3/1.3/2.3 & 0.2/0.9/1.5 & 0.2/1.0/1.7 \\ DeepGLO & 0.6/14.8/3.8 & 0.6/8.5/6.0 & 0.3/26.6/2.6 & 0.3/5.9/4.2 \\ DCRNN & 0.00 & 0.4/0.0/0.0 & 0.4/0.0/0.0 & 0.4/0.0 & 0.4/0.0 \\ STGCN & 0.3/25/13 & 0.3/14.6/9.0 & 0.2/8.6/4.1 & 0.2/8.0/5.0 \\ StemGNN & 1.4/17/24 & 1.3/9.0/13 & 1.2/6.0/8.0 & 1.1/6.0/9.0 \\ TGC & 0.4/12/21 & 0.3/6.2/11 & 0.2/3.9/7.2 & 0.1/4.2/8.4 \\ \hline \hline \end{tabular} \end{table} Table 3: Efficiency comparison of representative models: Trainable parameters (M trainable weights in temporal FDMs along \(D\) dimensions, respectively. B.3 utilizes the same set of TSFs across \(N\) variables. B.4 replaces orthogonal space projections with random transformations. B.5 and B.6 separately remove the coarse-grained and fine-grained temporal FDMs. Lastly, we evaluate add-ons that make TGC\({}^{\dagger}\). C.1 eliminates nonlinearities, and C.2 disables the spectral attention. In the first block of results, we validate the discussion in Sec. 4: (1) Orthogonal polynomials (A.3 to A.5) yield significantly better performance than non-orthogonal alternatives (A.1 and A.2); (2) Although the performance gaps between A.3 to A.5 are minor, polynomial bases with orthogonality that hold on more general weight functions tend to result in better performances. The results of B.1 to B.3 support the analysis of multidimensional and multivariate predictions in Sec. 3.2, with various degradations observed. In B.4, we see an average 4% MAE and 7% RMSE reduction, confirming the related analysis in Sec. 3.3. The results of B.5 and B.6 indicate that both implementations (Eq. 3 and Eq. 4) are effective, with fine-grained temporal FDMs being able to see a maximum 3.1% and 0.8% improvement over TGC by introducing nonlinearities (C.2) and spectral attention (C.1). Simply combining both leads to even better performance (i.e., TGC\({}^{\dagger}\)). Model Convergence.We compare model convergence between STGCN(\(1^{st}\)) [2], StemGNN [7], and TGC across two scenarios with different learning rates. Our instantiation with Gegenbauer bases has the fastest convergence rate in both cases, further confirming Theorem 3 with ablation studies. Also, as anticipated, STGCN(\(1^{st}\)) is more tractable than StemGNN w.r.t. the model training due to certain relaxations but at the cost of model effectiveness. Additional Experiments.Refer to Appendix H for details. (1) We evaluate TGC against additional baselines on other time series benchmarks; (2) We conduct parameter studies examining the impact of the Gegenbauer parameter \(\alpha\), polynomial degree \(K\), number of selected modes \(S\), and number of building blocks \(M\); (3) Additional visualizations; (4) Statistics of our results in Tab. 1 and Tab. 2. ## 6 Conclusion We formally define spectral-temporal GNNs and establish a theoretical framework for this family of methods, with the following important takeaways: (1) Spectral-temporal GNNs can be universal with mild assumptions; (2) Orthogonal bases and individual spectral filters are key to designing powerful GNN-based time series models. To validate our theorem, we propose a simple instantiation (TGC) and its nonlinear variant (TGC\({}^{\dagger}\)), outperforming most baselines on various real-world benchmarks. Having established a firm theoretical groundwork for GNN-based time series forecasting, we are yet to explore specific scenarios such as time-evolving graph structures. Additionally, investigating the applicability of our theories to other tasks, such as time series classification and anomaly detection, would also be valuable. We leave these explorations for future work. \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline \multicolumn{1}{c}{\multirow{2}{*}{Variant}} & MAGE & RMSE & MAE & RMSE & MAE & RMSE & MAE & RMSE \\ & & TGC\({}^{\dagger}\) & & RMSE & RMSE & RMSE & RMSE & RMSE \\ \hline **A.1** Monomial & 27.64 & 43.52 & 59.94 & 120.18 & 5.68 & 7.3 & 29.6 & 43.37 \\ **A.2** Bronstein & 27.38 & 43.17 & 55.17 & 10.53 & 5.57 & 8.64 & 27.57 & 40.28 \\ **A.3** Cheylayer & 13.56 & 23.84 & 13.78 & 20.29 & 1.94 & 3.73 & 14.62 & 29.93 \\ **A.3** Cheylayer & 13.52 & 21.24 & 12.89 & 2.92 & 1.22 & 3.58 & 14.23 & 27.22 \\ **A.3** Lewis & **13.34** & **21.51** & **18.84** & **20.44** & **1.91** & **3.43** & **14.29** & **23.15** \\ \hline **T.0** **(Ours)** & **13.52** & 21.74 & 18.70 & 28.92 & **1.82** & **3.35** & **14.25** & **22.73** \\ **B.1** who MLP, \(k\) & 14.07 & 21.28 & 19.07 & 30.93 & 2.05 & 3.45 & 15.14 & 23.94 \\ **B.2** who MLP, \(k\) & 21.25 & 21.73 & 19.52 & 30.11 & 1.96 & 3.40 & 15.06 & 23.25 \\ **B.3** who MLP, \(k\) & 15.80 & 21.77 & 19.22 & 30.50 & 1.97 & 3.44 & 15.12 & 25.28 \\ **B.4** who MLP, \(k\) & 13.72 & 21.75 & 19.10 & 30.42 & 2.03 & 1.53 & 15.28 \\ **B.5** who MLP, \(k\) & 13.82 & **14.19** & 13.52 & 20.1 & 1.37 & 15.18 & 23.71 \\ **B.6** who MLP, \(k\) & 13.71 & 21.59 & 18.31 & 20.96 & 1.91 & 3.39 & 14.38 & 23.10 \\ \hline **T.0** **(Ours)** & **13.39** & **23.34** & **20.39** & **1.84** & **2.38** & **1.40** & **22.40** \\ **C.1** who MLP, \(k\) & 13.75 & 21.43 & 18.63 & 20.70 & 1.92 & 3.36 & 14.94 & 24.93 \\ **C.2** who MLP, \(k\) & 13.42 & 21.38 & 18.50 & 20.51 & 1.86 & 1.70 & 14.63 & 27.45 \\ \hline \hline \end{tabular} \end{table} Table 4: Ablation study results. We use the **bold** and underline fonts to denote the best results in each ablation block, respectively. Figure 6: Evaluation of learning differently signed time series relations. Figure 7: Model convergence comparison on PeMS07 dataset. **Left**: \(lr=0.01\). **Right**: \(lr=0.001\). ## References * [1] William L Hamilton. Graph representation learning. _Synthesis Lectures on Artificial Intelligence and Machine Learning_, 14(3):1-159, 2020. * [2] Bing Yu, Haoteng Yin, and Zhanxing Zhu. Spatio-temporal graph convolutional networks: A deep learning framework for traffic forecasting. In _International Joint Conferences on Artificial Intelligence_, pages 3634-3640, 2018. * [3] Zonghan Wu, Shirui Pan, Guodong Long, Jing Jiang, and Chengqi Zhang. Graph wavenet for deep spatial-temporal graph modeling. In _International Joint Conference on Artificial Intelligence_, pages 1907-1913, 2019. * [4] Michael Defferrard, Xavier Bresson, and Pierre Vandergheynst. Convolutional neural networks on graphs with fast localized spectral filtering. In _Advances in Neural Information Processing Systems_, pages 3837-3845, 2016. * [5] Johannes Klicpera, Stefan Weissenberger, and Stephan Gunnemann. Diffusion improves graph learning. In _Advances in Neural Information Processing Systems_, pages 13366-13378, 2019. * [6] Shouheng Li, Dongwoo Kim, and Qing Wang. Beyond low-pass filters: Adaptive feature propagation on graphs. In _Joint European Conference on Machine Learning and Knowledge Discovery in Databases_, pages 450-465. Springer, 2021. * [7] Defu Cao, Yujing Wang, Juanyong Duan, Ce Zhang, Xia Zhu, Congrui Huang, Yunhai Tong, Bixiong Xu, Jing Bai, Jie Tong, et al. Spectral temporal graph neural network for multivariate time-series forecasting. In _Advances in neural information processing systems_, volume 33, pages 17766-17778, 2020. * [8] Mingguo He, Zhewei Wei, Hongteng Xu, et al. Bernnet: Learning arbitrary graph spectral filters via bernstein approximation. In _Advances in Neural Information Processing Systems_, volume 34, pages 14239-14251, 2021. * [9] Tyler Derr, Yao Ma, and Jiliang Tang. Signed graph convolutional networks. In _IEEE International Conference on Data Mining_, pages 929-934. IEEE, 2018. * [10] Ming Jin, Yu Zheng, Yuan-Fang Li, Siheng Chen, Bin Yang, and Shirui Pan. Multivariate time series forecasting with dynamic graph neural odes. _IEEE Transactions on Knowledge and Data Engineering_, 2022. * [11] Linhao Luo, Gholamreza Haffari, and Shirui Pan. Graph sequential neural ode process for link prediction on dynamic and sparse graphs. In _Proceedings of the Sixteenth ACM International Conference on Web Search and Data Mining_, pages 778-786, 2023. * [12] Ming Jin, Yuan-Fang Li, and Shirui Pan. Neural temporal walks: Motif-aware representation learning on continuous-time dynamic graphs. In _Advances in Neural Information Processing Systems_, 2022. * [13] Xiyuan Wang and Muhan Zhang. How powerful are spectral graph neural networks. In _International Conference on Machine Learning_, 2022. * [14] Tian Zhou, Ziqing Ma, Qingsong Wen, Xue Wang, Liang Sun, and Rong Jin. Fedformer: Frequency enhanced decomposed transformer for long-term series forecasting. In _International Conference on Machine Learning_, volume 162, pages 27268-27286. PMLR, 2022. * [15] Amauri H Souza, Diego Mesquita, Samuel Kaski, and Vikas K Garg. Provably expressive temporal graph networks. In _Advances in Neural Information Processing Systems_, 2022. * [16] John M Wallace and Robert E Dickinson. Empirical orthogonal representation of time series in the frequency domain. part i: Theoretical considerations. _Journal of Applied Meteorology and Climatology_, 11 (6):887-892, 1972. * [17] Michael Poli, Stefano Massaroli, Federico Berto, Jinkyoo Park, Tri Dao, Christopher Re, and Stefano Ermon. Transform once: Efficient operator learning in frequency domain. In _Advances in Neural Information Processing Systems_, 2022. * [18] Jeongwhan Choi, Hwangyong Choi, Jeehyun Hwang, and Noseong Park. Graph neural controlled differential equations for traffic forecasting. In _Proceedings of the AAAI Conference on Artificial Intelligence_, pages 6367-6374, 2022. * [19] Guokun Lai, Wei-Cheng Chang, Yiming Yang, and Hanxiao Liu. Modeling long- and short-term temporal patterns with deep neural networks. In _Proceedings of 41st International ACM SIGIR Conference on Information Retrieval_, pages 95-104. ACM, 2018. * [20] Syama Sundar Rangapuram, Matthias W. Seeger, Jan Gasthaus, Lorenzo Stella, Yuyang Wang, and Tim Januschowski. Deep state space models for time series forecasting. In _Advances in Neural Information Processing Systems_, pages 7796-7805, 2018. * [21] Rajat Sen, Hsiang-Fu Yu, and Inderjit S Dhillon. Think globally, act locally: A deep neural network approach to high-dimensional time series forecasting. In _Advances in neural information processing systems_, volume 32, 2019. * [22] Yaguang Li, Rose Yu, Cyrus Shahabi, and Yan Liu. Diffusion convolutional recurrent neural network: Data-driven traffic forecasting. In _International Conference on Learning Representations_, 2018. * [23] Shengan Guo, Youfang Lin, Ning Feng, Chao Song, and Huaiyu Wan. Attention based spatial-temporal graph convolutional networks for traffic flow forecasting. In _Proceedings of the AAAI Conference on Artificial Intelligence_, volume 33, pages 922-929, 2019. * [24] Lei Bai, Lina Yao, Salil S Kanhere, Xianzhi Wang, and Quan Z Sheng. Stg2seq: spatial-temporal graph to sequence model for multi-step passenger demand forecasting. In _International Joint Conferences on Artificial Intelligence_, pages 1981-1987, 2019. * [25] Rongzhou Huang, Chuyin Huang, Yubao Liu, Genan Dai, and Weiyang Kong. Lsqcn: Long short-term traffic prediction with graph convolutional networks. In _International Joint Conferences on Artificial Intelligence_, volume 7, pages 2355-2361, 2020. * [26] Theodoros Sofianos, Alessio Sampieri, Luca Franco, and Fabio Galasso. Space-time-separable graph convolutional network for pose forecasting. In _Proceedings of the IEEE/CVF International Conference on Computer Vision_, pages 11209-11218, 2021. * [27] Mengzhang Li and Zhanxing Zhu. Spatial-temporal fusion graph neural networks for traffic flow forecasting. In _Proceedings of the AAAI conference on artificial intelligence_, pages 4189-4196, 2021. * [28] Zheng Fang, Qingqing Long, Guojie Song, and Kunqing Xie. Spatial-temporal graph ode networks for traffic flow forecasting. In _Proceedings of the 27th ACM SIGKDD conference on knowledge discovery & data mining_, pages 364-373, 2021. * [29] Tian Zhou, Ziqing Ma, xue wang, Qingsong Wen, Liang Sun, Tao Yao, Wotao Yin, and Rong Jin. Film: Frequency improved legendre memory model for long-term time series forecasting. In _Advances in Neural Information Processing Systems_, 2022. * [30] Haixu Wu, Jiehui Xu, Jianmin Wang, and Mingsheng Long. Autoformer: Decomposition transformers with auto-correlation for long-term series forecasting. In _Advances in Neural Information Processing Systems_, volume 34, pages 22419-22430, 2021. * [31] Haoyi Zhou, Shanghang Zhang, Jieqi Peng, Shuai Zhang, Jianxin Li, Hui Xiong, and Wancai Zhang. Informer: Beyond efficient transformer for long sequence time-series forecasting. In _Proceedings of the AAAI Conference on Artificial Intelligence_, pages 11106-11115, 2021. * [32] Shiyang Li, Xiaoyong Jin, Yao Xuan, Xiyou Zhou, Wenhu Chen, Yu-Xiang Wang, and Xifeng Yan. Enhancing the locality and breaking the memory bottleneck of transformer on time series forecasting. In _Advances in neural information processing systems_, volume 32, 2019. * [33] Nikita Kitaev, Lukasz Kaiser, and Anselm Levskaya. Reformer: The efficient transformer. In _International Conference on Learning Representations_, 2020. ## How Expressive are Spectral-Temporal Graph Neural Networks for Time Series Forecasting? (Supplementary Material) ## Appendix A Preliminaries For a matrix \(\mathbf{M}\in\mathbb{R}^{a\times b}\), we denote \(\mathbf{M}_{i,:}\) and \(\mathbf{M}_{:,j}\) as the \(i^{\text{th}}\) row and \(j^{\text{th}}\) column of this matrix. Specifically, we use \(\mathbf{M}_{\text{A}\text{B}}\) to denote a submatrix of \(\mathbf{M}\) with row and column index sets \(\mathbb{A}\) and \(\mathbb{B}\). Suppose \(\mathbf{M}\) can be factorized into a canonical form and represented by its eigenvalues \(\mathbf{\Lambda}\) and eigenvectors \(\mathbf{U}\), we denote its _condition number_ as \(\kappa(\mathbf{M})=\frac{|\lambda_{max}|}{|\lambda_{min}|}\), where \(\lambda_{min}\) and \(\lambda_{max}\) are the smallest and largest eigenvalues, respectively. \(\kappa(\mathbf{M})=\infty\) if \(\mathbf{M}\) is singular. ### Graph Spectral Filtering In this work, we model a multivariate time series with the length \(T\) as a set of _undirected_ graph snapshots \(\{\mathcal{G}_{t}\}_{t=0}^{T-1}\) s.t. \(\mathcal{G}_{t}=(\mathbf{A},\mathbf{X}_{t})\). Given a graph topology \(\mathbf{A}\), we have its degree matrix defined as \(\mathbf{D}\in\mathbb{R}^{N\times N}\) s.t. \(\mathbf{D}_{i,i}=\sum_{j=1}^{N}\mathbf{A}_{i,j}\), which is symmetric. On this basis, we define the normalized graph Laplacian matrix as \(\hat{\mathbf{L}}=\mathbf{D}^{-\frac{1}{2}}\mathbf{L}\mathbf{D}^{-\frac{1}{2}}\), where \(\mathbf{L}=\mathbf{D}-\mathbf{A}\), and we know \(\hat{\mathbf{L}}\) is symmetric and positive semi-definite. We let its eigendecomposition of \(\hat{\mathbf{L}}\) to be \(\hat{\mathbf{L}}=\mathbf{U}\mathbf{\Lambda}\mathbf{U}^{\top}\), where \(\mathbf{\Lambda}\) and \(\mathbf{U}\) are matrices of eigenvalues and eigenvectors. We first define _graph Fourier transformation_ (GFT) below. **Definition A1**.: _Graph Fourier transform of the signal \(\mathbf{X}_{t}\) is defined as \(\tilde{\mathbf{X}}_{t}=\mathbf{U}^{\top}\mathbf{X}_{t}\), where \(\tilde{\mathbf{X}}_{t}^{(\lambda)}=\mathbf{U}_{:,\lambda}^{\top}\mathbf{X}_{t}\) denote the frequency component of input signal at the frequency \(\lambda\). Correspondingly, the inverse graph Fourier transform of \(\tilde{\mathbf{X}}_{t}\) is defined as \(\mathbf{X}_{t}=\mathbf{U}\tilde{\mathbf{X}}_{t}\)._ The above definition describes how to transform input signals between original and orthonormal spaces, and we say \(\mathbf{X}_{t}\) contains \(\lambda\) frequency component if \(\tilde{\mathbf{X}}_{t}^{(\lambda)}\neq\vec{0}\). To filter input signals in the frequency domain w.r.t. node connectivity, we have graph convolution defined below. **Definition A2**.: _Assume there is a filter function of eigenvalues \(g(\cdot):[0,2]\mapsto\mathbb{R}\), we define the spectral convolution on \(\mathcal{G}_{t}\) as filtering the input signal \(\mathbf{X}_{t}\) with the spectral filter:_ \[g(\mathbf{\Lambda})\star\mathbf{X}_{t}:=\mathbf{U}g(\mathbf{\Lambda})\mathbf{ U}^{\top}\mathbf{X}_{t}.\] (S1) The filter function can be parameterized, i.e., \(g_{\theta}(\mathbf{\Lambda})\), but directly calculating the above equation requires eigendecomposition with the time complexity of \(\mathcal{O}(N^{3})\). To alleviate this issue, we can first approximate \(g_{\theta}(\mathbf{\Lambda})\) with a truncated expansion of a polynomial with \(K\) degrees: \[g_{\theta}(\lambda):=\sum_{k=0}^{K}\mathbf{\Theta}_{k,:}P_{k}(\lambda).\] (S2) Thus, graph spectral filtering takes the following form: \[\mathbf{U}g_{\theta}(\mathbf{\Lambda})\mathbf{U}^{\top}\mathbf{X}_{t}:=\sum_ {k=0}^{K}\mathbf{\Theta}_{k,:}\mathbf{U}P_{k}(\mathbf{\Lambda})\mathbf{U}^{ \top}\mathbf{X}_{t}=\sum_{k=0}^{K}\mathbf{\Theta}_{k,:}P_{k}(\hat{\mathbf{L}}) \mathbf{X}_{t}.\] (S3) If we let \(g_{\theta}(\hat{\mathbf{L}})=\sum_{k=0}^{K}\mathbf{\Theta}_{k,:}P_{k}(\hat{ \mathbf{L}})\), we derive the following practical spectral graph convolution operation that goes beyond the low-pass filtering: \[g(\mathbf{\Lambda})\star\mathbf{X}_{t}:=g_{\theta}(\hat{\mathbf{L}})\mathbf{X}_ {t}.\] (S4) ### Orthogonal Time Series Representations In real-world time series data, complex behaviors such as periodic patterns are prevalent. Spectral analysis facilitates the disentanglement and identification of these patterns. This study aims to represent time series using sparse orthogonal components. Given an input signal, \(\mathbf{X}_{n}\), its values at time \(t\) are denoted as \(\mathbf{X}_{n}(t)\). As per Lemma 1, numerous orthogonal projections, such as discrete Fourier or cosine transformations, can serve as space projections for our objectives. **Definition A3**.: _Discrete Fourier transformation (DFT) on time series takes measurements at discrete intervals, and transforms observations into frequency-dependent amplitudes:_ \[\tilde{\mathbf{X}}_{n}(k)=\sum_{t=0}^{T-1}\mathbf{X}_{n}(t)e^{-2\pi ikt/T},\;k =\{0,1,\cdots,T-1\}.\] (S5) _Inverse transformation (IDFT) maps a signal from the frequency domain back to the time domain:_ \[\mathbf{X}_{n}(t)=\frac{1}{T}\sum_{k=0}^{T-1}\tilde{\mathbf{X}}_{n}(k)e^{2\pi ikt /T},\;t=\{0,1,\cdots,T-1\}.\] (S6) **Definition A4**.: _Discrete cosine transformation (DCT) is similar but uses real numbers, which express a sequence of observations with a set of cosine waves oscillating at different frequencies:_ \[\tilde{\mathbf{X}}_{n}(k)=\sqrt{\frac{2}{T}\sum_{t=0}^{T-1}\mathbf{X}_{n}(t) cos[\frac{\pi}{T}(t+\frac{1}{2})(k+\frac{1}{2})]},\;k=\{0,1,\cdots,T-1\}.\] (S7) _Inverse transformation (IDCT) distributes the data back to the time domain by multiplying \(2/T\)._ In this study, we employ DFT and IDFT by default in temporal frequency-domain models. ## Appendix B Related Work ### Deep Time Series Forecasting Time series forecasting has been extensively researched over time. Traditional approaches primarily focus on statistical models, such as vector autoregressive (VAR) [34] and autoregressive integrated moving average (ARIIMA) [35]. In contrast, deep learning-based methods have recently achieved significant success. Deep learning-based approaches, on the other hand, have achieved great success in recent years. For example, recurrent neural network (RNN) and its variants, e.g., FC-LSTM [36], are capable to well model univariate time series. TCN [37] improves these methods by modeling multivariate time series as a unified entity and considering the dependencies between different variables. Follow-up research, such as LSTNet [19] and DeepState [20], proposes more complex models to handle interlaced temporal and spatial clues by marrying sequential models with convolution networks or state space models. Recently, Transformer [38]-based approaches have made great leaps, especially in long-term forecasting [39]. For these methods, an encoder-decoder architecture is normally applied with improved self- and cross-attention, e.g., logsparse attention [32], locality-sensitive hashing [33], and probability sparse attention [31]. As time series can be viewed as a signal of mixed seasonalities, Zhou _et al._ further propose FEDformer [14] and a follow-up work FILM [29] to rethink how spectral analysis benefits time series forecasting. Nevertheless, these methods do not explicitly model inter-time series relationships (i.e., spatial dependencies), and we elaborate on the connections between them and our research later in this section. ### Spatial-Temporal Graph Neural Networks A line of research explores capturing time series relations using GNNs. For instance, DCRNN [22] combines recurrent units with graph diffusion [5] to simultaneously capture temporal and spatial dependencies, while Graph WaveNet [3] interleaves TCN [37] and graph diffusion layers. Subsequent studies, such as STSGCN [26], STFGNN [27], and STGODE [28], adopt similar principles but other ingenious designs to better characterize underlying spatial-temporal clues. However, these methods struggle to model differently signed time series relations since their graph convolutions operate under the umbrella of message passing, which serves as low-pass filtering assuming local homophiles. Some STGNNs, such as ASTGCN [23] and LSGCN [25], directly employ ChebConv [4] for capturing time series dependencies. However, their graph convolutions using the Chebyshev basis, along with the intuitive temporal models they utilize, result in sub-optimal solutions. Consequently, the expressiveness of most STGNNs remains limited. Spectral-temporal graph neural networks (SPGTNNs), on the other hand, first make it possible to fill the gap by (properly) approximating both graph and temporal convolutions with a broad range of filters in spectral domains, allowing for better pattern extraction and modeling. A representative work in this category is StemGNN [7]. However, it faces two fundamental limitations: (1) Its direct application of ChebConv is sub-optimal, and (2) although its temporal FDMs employ orthogonal space projections, they fail to make proper multidimensional and multivariate predictions as discussed. We elaborate on the connection between our research and GNN-based time series forecasting methods later in this section. ### Spectral Graph Neural Networks Spectral graph neural networks are grounded in spectral graph signal filtering, where graph convolutions are approximated by truncated polynomials with finite degrees. These graph spectral filters can be either trainable or not. Examples with predefined spectral filters include APPNP [40] and GraphHeat [41], as illustrated in [8]. Another branch of work employs different polynomials with trainable coefficients (i.e., filter weights) to approximate effective graph convolutions. For instance, ChebConv [4] utilizes Chebyshev polynomials, inspiring the development of many popular spatial GNNs with simplifications [42]. BernNet [8] employs Bernstein polynomials but can only express positive filter functions due to regularization constraints. Recently, JacobiConv [13] demonstrated that graph spectral filtering with Jacobi polynomial approximation is highly effective on a wide range of graphs under mild constraints. Although spectral graph neural networks pave the way for SPTGNNs, they primarily focus on modeling static graph-structured data without the knowledge telling how to effectively convolute on dynamic graphs for modeling time series data. ### Connection to Related Work We discuss the connection between our theoretical framework of SPTGNNs and most related works, including deep time series models, spatial-temporal GNNs, and spectral GNNs. Most of the deep time series models approximate expressive temporal filters with deep neural networks and learn important patterns directly in the time domain, e.g., TCN [37], where some complex properties (e.g., periodicity) may not be well modeled. Our work generalizes these methods in two ways: (1) When learning on univariate time series data, our temporal frequency-domain models guarantee that the most significant properties are well modeled with high probability (Lemma 1 and Lemma 2); (2) When learning on multivariate time series data, our framework models diverse inter-relations between time series (Fig. 1) and intra-relations within time series with theoretical evidence. For most spatial-temporal GNNs, they either use the first-order approximation of ChebyConv [4] (e.g., STGCN\((1^{st})\)[2]) or graph diffusion (e.g., DCRNN [22]) to model time series dependencies. These methods can be generalized as message-passing-based spatial-temporal GNNs (MP-STGNNs). In comparison, our framework has two major advantages: (1) It can model differently signed time series relations by learning a wide range of graph spectral filters (e.g., low-pass and high-pass), while MP-STGNNs only capture positive correlations between time series exhibiting strong similarities; (2) On this basis, it can express any multivariate time series under mild assumptions with provably expressive temporal frequency-domain models, while MP-STGNNs approximate effective temporal filtering in time domains with deep neural networks. Even compared to STGNNs employing ChebyConv, our proposal generalizes them well: (1) We provide a blueprint for designing effective graph spectral filters and point out that using Chebyshev basis is sub-optimal; (2) Instead of approximating expressive temporal models with deep neural networks, we detail how to simply construct them in frequency domains. Therefore, our results generalize most STGNNs effectively. Although there are few studies on SPTGNNs, such as StemGNN [7], we are not only the first to define the general formulation and provide a theoretical framework to generalize this branch of methods but also free from the limitations of StemGNN mentioned above. Compared with spectral GNNs, such as BernNet [8] and JacobiConv [13], our work extends graph convolution to model dynamic graphs comprising a sequence of regularly-sampled graph snapshots. A detailed comparison between the polynomial basis in our instantiation and that in common spectral GNNs is in Appendix E. ## Appendix C Proofs ### Proof of Theorem 1 **Theorem 1**.: _A linear SPTGNN can produce arbitrary dimensional time series representations at any valid time iff: (1) \(\hat{\mathbf{L}}\) has no repeated eigenvalues; (2) \(\mathbf{X}\) encompasses all frequency components with respect to the graph spectrum; (3) \(\mathcal{T}_{\phi}(\cdot)\) can express any single-dimensional univariate time series._ Proof.: Let us assume that \(t=1\) (i.e., there is only one snapshot \(\mathcal{G}_{t}\) of the graph \(\{\mathcal{G}_{t}\}_{t=0}^{T-1}\)), \(\mathcal{T}_{\phi}(\cdot)\) reduces to linear functions of a graph snapshot and the linear spectral-temporal GNN reduces to a linear spectral GNN, which can be equivalently written as: \[\mathbf{Z}_{t}=g_{\theta}(\hat{\mathbf{L}})\mathbf{X}_{t}\mathbf{\Phi}\in\mathbb{ R}^{N\times D}.\] (S8) We first prove the universality theorem of linear spectral GNNs in a graph snapshot on the basis of Theorem 4.1 in [13]. In other words, assuming \(\tilde{\mathbf{X}}_{t}=\mathbf{U}^{\top}\mathbf{X}_{t}\) has non-zero row vectors and \(\hat{\mathbf{L}}\) has unique eigenvalues, we first aim to prove that for any \(\mathbf{Z}_{t,d}\in\mathbb{R}^{N\times 1}\), there is a linear spectral GNN to produce it. We assume there exists \(\mathbf{\phi}^{*}\in\mathbb{R}^{D}\) s.t. all elements in \(\tilde{\mathbf{X}}_{t}\mathbf{\phi}^{*}\) are non-zero. Considering a case where \((\tilde{\mathbf{X}}_{t}\mathbf{\phi})_{i}=0\) and letting the solution space to be \(\mathbb{S}_{i}\), we know that \(\mathbb{S}_{i}\) is a proper subspace of \(\mathbb{R}^{D}\) as the \(i\)-th row of \(\tilde{\mathbf{X}}_{t}\) is non-zero. Therefore, \(\mathbb{R}^{D}\setminus\cup_{i=1}^{N}\mathbb{S}_{i}\neq\emptyset\), and we know that all vectors \(\mathbf{\phi}\) in \(\mathbb{R}^{D}\setminus\cup_{i=1}^{N}\mathbb{S}_{i}\) are valid to form \(\mathbf{\phi}^{*}\). We then filter \(\tilde{\mathbf{X}}_{t}\mathbf{\phi}^{*}\) to get \(\mathbf{Z}_{t,d}\). Firstly, we let \(\tilde{\mathbf{Z}}_{t,d}=\mathbf{U}^{\top}\mathbf{Z}_{t,d}\) and assume there is a polynomial with \(N-1\) order: \[p_{i} :=g_{\theta}(\lambda_{i}),\] (S9) \[=\sum_{k=0}^{N-1}\theta_{k}\lambda_{i}^{k}\ \ \ \text{s.t.}\ \ p_{i}=\tilde{\mathbf{Z}}_{t,d}[i]/(\tilde{\mathbf{X}}_{t}\mathbf{\phi}^{*})_{ i}\ \ \ \text{and}\ \ \ \forall i\in\{1,\cdots,N\}.\] On this basis, the polynomial coefficients \(\mathbf{\theta}\) is the solution of a linear system \(\mathbf{B}\mathbf{\theta}=\mathbf{p}\) where \(\mathbf{B}_{i,j}=\lambda_{i}^{j-1}\). Since \(\lambda_{i}\) are different from each other, \(\mathbf{B}^{\top}\) turns to a nonsingular Vandermonde matrix, where a solution \(\mathbf{\theta}\) always exists. Therefore, a linear spectral GNN can produce any one-dimensional prediction under certain assumptions. The above proof states that linear spectral GNNs can produce any one-dimensional prediction if \(\hat{\mathbf{L}}\) has no repeated eigenvalues (i.e., condition 1) and the node features \(\mathbf{X}\) contain all frequency components w.r.t. graph spectrum (i.e., condition 2). When \(t\geq 2\), \(\mathcal{T}_{\phi}(\cdot)\) turns to linear functions over all historical observations of graph snapshots. In order to distinguish between different historical graph snapshots, \(\mathcal{T}_{\phi}(\cdot)\) must be universal approximations of all historical graph snapshots, implying that \(\mathcal{T}_{\phi}(\cdot)\) is able to express any one-dimensional univariate time series (i.e., condition 3). ### Proof of Theorem 2 **Theorem 2**.: _For a linear SPTGNN with valid temporal FDMs and a \(K\)-degree polynomial basis in its GSFs, \(\forall u,v\in\mathbb{V},\mathbf{Z}_{t}[u]=\mathbf{Z}_{t}[v]\) if \(\mathbf{C}^{(K+1)}(u,t)=\mathbf{C}^{(K+1)}(v,t)\). \(\mathbf{Z}_{t}[i]\) and \(\mathbf{C}^{(K)}(i,t)\) represent node \(i\)'s embedding at time \(t\) in such a GNN and the \(K\)-step temporal 1-WL test, respectively._ Proof.: Given valid temporal frequency-domain models (i.e., space projectors and TSFs) and a \(K\)-degree polynomial filter function, the prediction of a linear SPTGNN can be formulated as follows. \[\mathbf{Z}=\mathcal{T}_{\phi}\left(\sum_{k=0}^{K}\mathbf{\Theta}_{k}P_{k}(\hat{ \mathbf{L}})\mathbf{X}\right).\] (S10) For ease of reading, we redefine \(\mathcal{T}_{\phi}(\cdot)\) as the combination of space projections and TSFs in the following proof. Let us assume \(t=1\) (i.e., there is only one snapshot \(\mathcal{G}_{t}\) of the graph \(\{\mathcal{G}_{t}\}_{t=0}^{T-1}\)), \(\mathcal{T}_{\phi}(\cdot)\) reduces to linear functions of a single graph snapshot and a linear SPTGNN reduces to a linear spectral GNN. Using the framework in [41], Eq. S10 can be viewed as a \(k+1\)-layer GNN. The output of the last layer in GNN produces the output of linear spectral GNNs [13]. According to the proof of Lemma 2 in [41], if WL node labels \(\mathbf{C}^{(K+1)}(u)=\mathbf{C}^{(K+1)}(v)\), the corresponding GNN's node features should be the same at any iteration. Therefore, for all nodes \(\forall u,v\in\mathbb{V},\mathbf{Z}[u]=\mathbf{Z}[v]\) if \(\mathbf{C}^{(K+1)}(u)=\mathbf{C}^{(K+1)}(v)\). When \(t\geq 2\), we have a DTDG defined as a sequence of graph snapshots \((\mathcal{G}_{1},\mathcal{G}_{2},\ldots)\) that are sampled at regular intervals, and each snapshot is a static graph. Note that any DTDGs can be equivalently converted to continuous-time temporal graphs (CTDGs). The CTDG can be equivalently viewed as time-stamped multi-graphs with timestamped edges, i.e., \(\mathcal{G}(t)=\{(u_{k},v_{k},t_{k})\mid t_{k}<t\}\). According to Proposition 6 in [15], the expressive power of dynamic GNN with injective message passing is bounded by the temporal WL test on \(\mathcal{G}(t)\). Since \(\mathcal{T}_{\phi}(\cdot)\) is a set of linear functions over all historical observations of graph snapshots, i.e., \(\mathcal{T}_{\phi}(\cdot)\) represents linear transformations of \(\mathcal{G}(t)\). The defined SPTGNN, i.e., \(\mathbf{Z}=\mathcal{T}_{\phi}(\sum_{k=0}^{K}\mathbf{\Theta}_{k}P_{k}(\hat{ \mathbf{L}})\mathbf{X})\), should be as expressive as dynamic GNN with injective message passing. Hence, if temporal WL node labels \(\mathbf{C}^{(K+1)}(u,t)=\mathbf{C}^{(K+1)}(v,t)\), the corresponding GNN's node features should be the same at any timestamp \(t\) and at any iteration. Therefore, for all nodes \(\forall u,v\in\mathbb{V},\mathbf{Z}_{t}[u]=\mathbf{Z}_{t}[v]\) if \(\mathbf{C}^{(K+1)}(u,t)=\mathbf{C}^{(K+1)}(v,t)\). ### Proof of Proposition 2 **Proposition 2**.: _If a discrete-time dynamic graph with a fixed graph topology at time \(t\) has no repeated eigenvalues in its normalized graph Laplacian and has no missing frequency components in each snapshot, then the temporal 1-WL is able to differentiate all non-isomorphic nodes at time \(t\)._ Proof.: Assume there are no repeated eigenvalues and missing frequency components w.r.t. graph spectrum in a DTDG with fixed topology and time-evolving features, i.e., \(\{\mathcal{G}_{t}\}_{t=0}^{T-1}\). According to Corollary 4.4 in [13], we know that if a graph has no repeated eigenvalues and missing frequency components, then 1-WL test can differentiate any pair of non-isomorphic nodes. We denote the colors of two nodes \(u\) and \(v\) in \(\mathcal{G}_{t}\) after \(L\) 1-WL interactions as \(\mathbf{C}^{(L)}(u,t)\) and \(\mathbf{C}^{(L)}(v,t)\) s.t. \(\mathbf{C}^{(L)}(u,t)\neq\mathbf{C}^{(L)}(v,t)\) if \(u\) and \(v\) are non-isomorphic. On this basis, we consider two scenarios in \(\mathcal{G}_{t+1}\): (1) Two or more non-isomorphic nodes have identical initial colors; (2) None of the non-isomorphic nodes have identical colors. Under the assumptions in this proposition, the 1-WL test can differentiate \(u\) and \(v\) in \(\mathcal{G}_{t+1}\) on both cases with different \[\mathbf{C}^{(L)}(u,t+1) :=\textsc{Hash}(c^{(L-1)}(u,t+1),\{\!\!\{c^{(L-1)}(m,t+1):e_{u,m,t +1}\in\mathbb{E}(\mathcal{G}_{t+1})\}\!\})\] and \[\mathbf{C}^{(L)}(v,t+1) :=\textsc{Hash}(c^{(L-1)}(v,t+1),\{\!\!\{c^{(L-1)}(m,t+1):e_{v,m,t +1}\in\mathbb{E}(\mathcal{G}_{t+1})\}\!\}).\] Therefore, no matter whether \(\mathbf{C}^{(L)}(u,t)\) and \(\mathbf{C}^{(L)}(v,t)\) are identical or not (they are different in fact as mentioned), we have nonidentical \[\mathbf{C}^{(L)}(u,t+1) :=\textsc{Hash}(c^{(L-1)}(u,t+1),c^{(L-1)}(u,t),\{\!\!\{c^{(L-1)} (m,t+1):e_{u,m,t+1}\in\mathbb{E}(\mathcal{G}_{t+1})\}\!\})\] and \[\mathbf{C}^{(L)}(v,t+1) :=\textsc{Hash}(c^{(L-1)}(v,t+1),c^{(L-1)}(v,t),\{\!\!\{c^{(L-1)} (m,t+1):e_{v,m,t+1}\in\mathbb{E}(\mathcal{G}_{t+1})\}\!\})\] in the temporal 1-WL test, where \(\mathbf{C}^{(L)}(u,t):=c^{(L-1)}(u,t)\) and \(\mathbf{C}^{(L)}(v,t):=c^{(L-1)}(v,t)\). ### Proof of Proposition 3 **Proposition 3**.: _If a discrete-time dynamic graph with a fixed graph topology has no multiple eigenvalues in its normalized graph Laplacian and has no missing frequency components in each snapshot, then no automorphism exists._ Proof.: Given a DTDG \(\{\mathcal{G}_{t}\}_{t=0}^{T-1}\) consists of \(T\) static graph snapshots with fixed graph topology and time-evolving node features, we first prove that all pairs of nodes are non-isomorphic. In a snapshot \(\mathcal{G}_{t}\), assume there is a permutation matrix \(\mathbf{P}\), we have \[\hat{\mathbf{L}}:=\mathbf{P}^{\top}\hat{\mathbf{L}}\mathbf{P}=\mathbf{P} \mathbf{U}\mathbf{A}\mathbf{U}^{\top}\mathbf{P}^{\top},\] (S11) and we know \[\mathbf{\Lambda}:=\mathbf{U}^{\top}\mathbf{P}\mathbf{U}\mathbf{\Lambda} \mathbf{U}^{\top}\mathbf{P}^{\top}\mathbf{U}=\mathbf{V}\mathbf{\Lambda} \mathbf{V}^{\top},\] (S12) where \(\mathbf{V}\) is an orthogonal matrix. Since all diagonal elements in \(\mathbf{\Lambda}\) are different because we assume no repeated eigenvalues, then the eigenspace of each eigenvalue has only one dimension [13]; thus, we have \(\mathbf{U}^{\top}\mathbf{P}\mathbf{U}=\mathbf{D}\), where \(\mathbf{D}\) is a diagonal matrix s.t. \(\mathbf{V}:=\mathbf{D}\) with \(\pm 1\) elements. Now considering the node features \(\mathbf{X}_{t}:=\mathbf{P}\mathbf{X}_{t}\), we have \(\hat{\mathbf{X}}_{t}=\mathbf{V}\hat{\mathbf{X}}_{t}\); thus \((\mathbf{I}-\mathbf{D})\hat{\mathbf{X}}_{t}=0\) based on the above discussion. If there are no missing frequency components in \(\hat{\mathbf{X}}_{t}\), i.e., no zero row vectors, we have \(\mathbf{D}=\mathbf{I}\) and know that \[\mathbf{P}=\mathbf{U}\mathbf{D}\mathbf{U}^{\top}=\mathbf{I}.\] (S13) Hence, we prove that all nodes in a graph snapshot \(\mathcal{G}_{t}\) are non-isomorphic. In \(\{\mathcal{G}_{t}\}_{t=0}^{T-1}\), we have \(\mathbf{V}:=\mathbf{D}\) always holds across all snapshots if its normalized graph Laplacian has no repeated eigenvalues. On this basis, if there are no missing frequency components by giving \(\mathbf{X}_{t},\forall t\in\{0,1,\dots,T-1\}\), all pairs of nodes are non-isomorphic in an attributed DTDG with fixed graph topology. ### Proof of Theorem 3 **Theorem 3**.: _For a linear SPTGNN optimized with mean squared loss, any complete polynomial bases result in the same expressive power, but an orthonormal basis guarantees the maximum convergence rate if its weight function matches the graph signal density._ Proof.: Directly analyzing Eq. 2 is complex and unnecessary to study the effectiveness of different polynomial bases when learning time series relations at each time step. Since optimizing the spectral-temporal GNNs formulated in Eq. 2 can be understood as a two-step (i.e., graph-then-temporal) optimization problem, we directly analyze the optimization of \(\mathbf{\Theta}\) w.r.t. the formulation below based on the squared loss \(\mathcal{L}=\frac{1}{2}||\mathbf{Z}_{t}-\mathbf{Y}_{t}||_{F}^{2}\) on a graph snapshot \(\mathcal{G}_{t}\) with the target \(\mathbf{Y}_{t}\). \[\mathbf{Z}_{t}=\sum_{k=0}^{K}\mathbf{\Theta}_{k}P_{k}(\hat{\mathbf{L}}) \mathbf{X}_{t}.\] (S14) This is a convex optimization problem, thus the convergence rate of gradient descent relates to the condition number of the Hessian matrix [44]. In other words, the convergence rate reaches the maximum if \(\kappa(\mathbf{H})\) reaches the minimum. We have \(\mathbf{H}_{k_{1},k_{2}}\) defined as follows that is similar in [13]. \[\begin{split}\frac{\partial\mathcal{L}}{\partial\mathbf{\Theta}_{k _{1}}\partial\mathbf{\Theta}_{k_{2}}}&=\mathbf{X}_{t}^{\top}P_{ k_{2}}(\hat{\mathbf{L}})P_{k_{1}}(\hat{\mathbf{L}})\mathbf{X}_{t},\\ &=\sum_{i=1}^{n}P_{k_{2}}(\lambda_{i})P_{k_{1}}(\lambda_{i})\tilde {\mathbf{X}}_{t}[\lambda_{i}].\end{split}\] (S15) This equation can be written as a Riemann sum as follows. \[\frac{\partial\mathcal{L}}{\partial\mathbf{\Theta}_{k_{1}}\partial\mathbf{ \Theta}_{k_{2}}}=\sum_{i=1}^{n}P_{k_{2}}(\lambda_{i})P_{k_{1}}(\lambda_{i}) \frac{F(\lambda_{i})-F(\lambda_{i-1})}{\lambda_{i}-\lambda_{i-1}}(\lambda_{i}- \lambda_{i-1}).\] (S16) In the above formula, \(F(\lambda_{i}):=\sum_{\lambda_{j}\leq\lambda_{i}}(\tilde{\mathbf{X}}_{t}[ \lambda_{j}])^{2}\) and \(\frac{F(\lambda_{i})-F(\lambda_{i-1})}{\lambda_{i}-\lambda_{i-1}}\) denotes the graph signal density at the frequency \(\lambda_{i}\). When \(n\rightarrow\infty\), we have the \((k_{1},k_{2})\) element in \(\mathbf{H}\) rewrite as follows. \[\mathbf{H}_{k_{1},k_{2}}=\int_{\lambda=0}^{2}P_{k_{2}}(\lambda)P_{k_{1}}(\lambda) \frac{\Delta F(\lambda)}{\Delta\lambda}\,d\lambda.\] (S17) We know that \(\kappa(\mathbf{H})\) reaches the minimum if \(\mathbf{H}\) is a diagonal matrix, which tells that the polynomial bases, e.g., \(P_{k_{1}}(\lambda)\) and \(P_{k_{2}}(\lambda)\), should be orthogonal w.r.t. the weight function \(\frac{\Delta F(\lambda)}{\Delta\lambda}\). ### Proof of Lemma 2 **Lemma 2**.: _Suppose the projection of \(\mathbf{A}\) by \(\mathbf{A}^{\prime}\) is \(P_{\mathbf{A}^{\prime}}(\mathbf{A})\), and the coherence measure of \(\mathbf{A}\) is \(\mu(\mathbf{A})=\Omega(k/N)\), then with a high probability, the error between \(\mathbf{AW}\) and \(P_{\mathbf{A}^{\prime}}(\mathbf{A})\mathbf{W}\) is bounded by \(||\mathbf{AW}-P_{\mathbf{A}^{\prime}}(\mathbf{A})\mathbf{W}||_{F}\leq(1+ \epsilon)||\mathbf{W}||_{F}||\mathbf{A}-\mathbf{A}_{k}||_{F}\) if \(S=O(k^{2}/\epsilon^{2})\)._ Proof.: Similar to the analysis in Theorem 3 from [45] and Theorem 1 from [14], we have \[||\mathbf{AW}-P_{\mathbf{A}^{\prime}}(\mathbf{A})\mathbf{W}||_{F} \leq||\mathbf{W}||_{F}||\mathbf{A}-P_{\mathbf{A}^{\prime}}( \mathbf{A})||_{F}\] (S18) \[=||\mathbf{W}||_{F}||\mathbf{A}-\mathbf{A}^{\prime}(\mathbf{A}^{ \prime})^{\dagger}\mathbf{A}||_{F}\] \[\leq||\mathbf{W}||_{F}||\mathbf{A}-(\mathbf{A}\mathbf{S}^{\top} )(\mathbf{A}_{k}\mathbf{S}^{\top})^{\dagger}\mathbf{A}_{k}||_{F}.\] Then, following Theorem 5 from [45], if \(S=O(k^{2}/\epsilon^{2}\times\mu(\mathbf{A})N/k)\), we can obtain the following result with a probability at least \(0.7\) \[||\mathbf{A}-(\mathbf{A}\mathbf{S}^{\top})(\mathbf{A}_{k}\mathbf{S}^{\top})^{ \dagger}\mathbf{A}_{k}||_{F}\leq(1+\epsilon)||\mathbf{A}-\mathbf{A}_{k}||_{F}.\] (S19) Since \(\mu(\mathbf{A})=\Omega(k/N)\), when \(S=O(k^{2}/\epsilon^{2})\) together with Eq. S18 and Eq. S19, we can obtain the final bound as \[||\mathbf{AW}-P_{\mathbf{A}^{\prime}}(\mathbf{A})\mathbf{W}||_{F}\leq(1+ \epsilon)||\mathbf{W}||_{F}||\mathbf{A}-\mathbf{A}_{k}||_{F}.\] (S20) ## Appendix D Additional Model Details ### TGC Model Architecture Figure S2: Tensor flow in fine-grained temporal frequency-domain models. ### Time Series Decomposition Given a time series \(\mathbf{x}\in\mathbb{R}^{T}\), we extract its trend information by conducting moving average with a window size \(w\) on the input signal, i.e., \(\tilde{\mathbf{x}}(t)=\big{(}\mathbf{x}(t-w+1)+\cdots+\mathbf{x}(t)\big{)}/w\), where we simply pad the first \(w-1\) data points with zeros in \(\tilde{\mathbf{x}}\). After this, we obtain detailed time series information (e.g., seasonality) by subtracting the trend from the input signal. ### Component Padding We employ discrete Fourier transformations as space projections by default in TGC and TGC\({}^{\dagger}\). We pad the filtered signal tensors in both the coarse-grained and fine-grained temporal FDMs with \(0+0j\), thereby reshaping them from \(\mathbb{C}^{N\times S\times D}\) to \(\mathbb{C}^{N\times T\times D}\). An illustration of this can be seen in Fig. S2. ### Nonlinearities Nonlinearities can be either applied in graph and/or temporal frequency-domain models. We apply both in TGC\({}^{\dagger}\). In the first case, we add the ReLU activation \(\sigma(\cdot)\) as follows. \[g(\mathbf{\Lambda})\star\mathbf{X}_{t}:=g_{\theta}(\hat{\mathbf{L}})\sigma( \mathbf{X}_{t}).\] (S21) In the second case, we have Eq. 3 and Eq. 4 modified as follows. \[\mathbf{F}=\mathcal{F}(\tilde{\mathbf{Z}}),\hskip 14.226378pt\mathbf{F}^{ \prime}=\textsc{Pad}(\sigma(\mathbf{F}\mathbf{S}_{1}^{\top}\mathbf{\Phi}_{1})),\hskip 14.226378pt\mathbf{Z}^{\prime}=\mathcal{F}^{-1}(\mathbf{F}^{\prime}).\] (S22) \[\mathbf{Z}^{\prime}_{t},\mathbf{Z}^{\prime}_{s}=\textsc{Decomp}(\mathbf{Z}^{ \prime}),\hskip 8.535827pt\mathbf{F}_{s}=\mathcal{F}(\mathbf{Z}^{\prime}_{s}), \hskip 8.535827pt\mathbf{F}^{\prime}_{s}=\textsc{Pad}(\sigma(\mathbf{F}_{s} \mathbf{S}_{2}^{\top}\mathbf{\Phi}_{2})),\hskip 8.535827pt\mathbf{Z}= \mathbf{Z}^{\prime}_{t}+\mathcal{F}^{-1}(\mathbf{F}^{\prime}_{s}).\] (S23) ### Spectral Attention Attention in spectral domains [14] can be easily incorporated in temporal frequency-domain models. In TGC\({}^{\dagger}\), we implement the spectral filters in fine-grained temporal FDMs with spectral attention instead of Eq. S23. Specifically, we first decompose the input signal via \(\mathbf{Z}^{\prime}_{t},\mathbf{Z}^{\prime}_{s}=\textsc{Decomp}(\mathbf{Z}^{ \prime})\). After this, we generate the queries \(\mathbf{Q}=\sigma(\mathbf{\Phi}_{2,1}\mathbf{Z}^{\prime}_{t})\in\mathbb{R}^{N \times T\times D}\), keys \(\mathbf{K}=\sigma(\mathbf{\Phi}_{2,2}\mathbf{Z}^{\prime}_{s})\in\mathbb{R}^{ N\times T\times D}\), and values \(\mathbf{V}=\sigma(\mathbf{\Phi}_{2,3}\mathbf{Z}^{\prime}_{s})\in\mathbb{R}^{N \times T\times D}\). \(\sigma(\cdot)\) denotes the ReLU activation. Then, we project all three matrices into the frequency domain via the discrete Fourier transformation, i.e., \(\tilde{\mathbf{Q}}=\mathcal{F}(\mathbf{Q})\mathbf{S}_{2,1}^{\top}\in\mathbb{C} ^{N\times S\times D}\), \(\tilde{\mathbf{K}}=\mathcal{F}(\mathbf{K})\mathbf{S}_{2,2}^{\top}\in\mathbb{C} ^{N\times S\times D}\), and \(\tilde{\mathbf{V}}=\mathcal{F}(\mathbf{V})\mathbf{S}_{2,3}^{\top}\in\mathbb{ C}^{N\times S\times D}\). Finally, we select informative components with \[\mathbf{F}^{\prime}_{s}=\textsc{Softmax}(\frac{\tilde{\mathbf{Q}}\tilde{ \mathbf{K}}^{\top}}{\sqrt{n_{q}d_{q}}})\tilde{\mathbf{V}}.\] (S24) Now we obtain the learned embeddings via \(\mathbf{Z}=\mathbf{Z}^{\prime}_{t}+\mathcal{F}^{-1}\big{(}\textsc{Pad}( \mathbf{F}^{\prime}_{s})\big{)}\). We illustrate the tensor flow of this process in Fig. S3. ## Appendix E Connection to Other Polynomial Bases We compare our instantiation with common practices in approximating graph convolutions: Monomial, Chebyshev, Bernstein, and Jacobi bases. We visualize these polynomial bases with limited degrees in Fig. S4. For the Monomial basis \((1-\lambda)^{k}\), it is non-orthogonal for arbitrary choices of weight functions [13]. Although the Bernstein basis \(\binom{K}{k}(1-\frac{\lambda}{2})^{K-k}(\frac{\lambda}{2})^{k}\) is also non-orthogonal, existing studies show that a small conditional number of the Hessian matrix \(\kappa(\mathbf{H})\) may still be achieved to enable fast convergence, where \(\kappa(\mathbf{H})\) can also be lower than using Monomial basis [46]. While the Bernstein basis is better than the Monomial basis in approximating graph convolutions, our instantiation with the Gegenbauer basis guarantees the minimum \(\kappa(\mathbf{H})\) to be achieved in most cases; thus, it is more desired. We provide examples in Fig. S5 showing that the weight functions of Gegenbauer polynomials fit graph signal densities well in most cases. Our main results also confirm this in Tab. 4. For orthogonal polynomials, the second-kind Chebyshev basis is a particular case of the Gegenbauer basis with \(\alpha=1\) and only orthogonal w.r.t. a particular weight \(\sqrt{1-\lambda^{2}}\). Though the Gegenbauer basis forms a particular case of the Jacobi basis with both of its parameters set to \(\alpha-\frac{1}{2}\), we show that the orthogonality of the Gegenbauer basis is well-posed on common real-world graphs w.r.t. its weight function \((1-\lambda^{2})^{\alpha-\frac{1}{2}}\) as shown in Fig. S5. Thus, in this work, we use the Gegenbauer basis as a simpler solution for our purpose with only minor performance degradation (Tab. 4). ## Appendix F Datasets * **PeMS03, 04, 07, and 082**: These datasets are collected by the Caltrans Performance Measurement System (PeMS) 3 from traffic sensors installed in highway systems spanned across metropolitan areas in California. The sampling rate of these datasets is 5 minutes, where PeMS03, 07, and 08 record traffic flow, and PeMS04 is about traffic speed. * **Electricity4**: This dataset consists of electricity consumption records of 321 customers with 1-hour sampling rate. Footnote 4: [https://github.com/laiguokun/multivariate-time-series-data](https://github.com/laiguokun/multivariate-time-series-data) * **Solar-Energy5**: This dataset consists of photovoltaic production records of 137 sites in Alabama State in 2006. The sampling rate in this dataset is 10 minutes. Footnote 5: [https://github.com/zhouhaoyi/Informer2020](https://github.com/zhouhaoyi/Informer2020) * **Weather6**: This dataset consists of the one-year records of 21 meteorological stations installed in Germany. The sampling rate in this dataset is 10 minutes. Footnote 6: [https://github.com/microsoft/StemGNN/blob/master/dataset/ECG_data.csv](https://github.com/microsoft/StemGNN/blob/master/dataset/ECG_data.csv) * **ECG7**: This dataset consists of the 5000 records of 140 electrocardiograms in the URC time series archive8. Footnote 7: [https://www.cs.ucr.edu/~eamonn/time_series_data/](https://www.cs.ucr.edu/~eamonn/time_series_data/) ## Appendix G Experimental Setting All experiments are conducted on a Linux server with \(4\times\) GeForce RTX 2080 Ti 11GB, \(1\times\) Intel Core i9-9900X, and 128GB system memory. ### Short-Term Forecasting Here, we detail the experimental setting of short-term time series forecasting. Our main results are in Tab. 1 and Tab. S4. The dataset statistics are in Tab. S1. We briefly introduce all baselines as follows. * **FC-LSTM**[47] forecasts a time series with fully-connected long short-term memory units. * **TCN**[37] forecasts time series data with stacked dilated convolutions. * **LSTNet**[19] uses convolutions to mine local time series dependencies and recurrent neural networks to model temporal clues. * **DeepState**[20] takes advantage of state space models, where time-related parameters are calculated via recurrent neural networks by digesting the input series. * **DeepGLO**[21] leverages TCN regularized matrix factorization to capture global features, along with another set of temporal networks to capture local patterns of each time series. * **SFM**[48] enhances long short-term memory units by breaking down cell states of a time series into a set of frequency components. * **DCRNN**[22] integrates graph diffusion into recurrent neural networks to capture spatial and temporal relations in multivariate time series data. * **STGCN**[2] combines ChebyConv [4] and temporal convolutions together into a decoupled neural architecture to capture spatial and temporal multivariate time series relations simultaneously. Note that \(\text{STGCN}(1^{st})\) adopts the first-order approximation of ChebyConv. * **Graph WaveNet**[3] integrates TCN and graph diffusion [5], along with a graph structure refinement mechanism, to learn spatial and temporal multivariate time series relations. * **ASTGCN**[23] improves existing works with separate spatial and temporal attention. Note that MSTGCN is a variant of ASTGCN with all attention mechanisms disabled. * **STG2Seq**[24] proposes to capture both spatial and temporal correlations simultaneously with hierarchical graph convolutions adapted from GCN [42]. * **LSGCN**[25] introduces the spatial gated block with a novel attention-enhanced graph convolution network to better capture spatial dependencies in STGNNs. * **STSGCN**[26] proposes a space-time-separable graph convolution network to models entire graph dynamics with only graph convolution networks adapted from GCN [42]. * **STFGNN**[27] incorporates various time series correlation mining strategies to learn spatial-temporal fusion graphs that facilitate the learning of latent spatial and temporal dependencies. * **STGODE**[28] introduces spatial-temporal graph ordinary differential equation networks to better capture both short- and long-range spatial correlations compared with other STGNNs. * **StemGNN**[7] marries ChebyConv and temporal frequency-domain models to model time series spatial and temporal dependencies in spectral domains. General experimental setting.We adopt the Mean Absolute Forecasting Errors (MAE) and Root Mean Squared Forecasting Errors (RMSE) as evaluation metrics. On three traffic datasets (i.e., PeMS03, 04, and 08), we use the data split of 60%-20%-20%. On the rest of the time series datasets, i.e., PeMS07, Electricity, Solar-Energy, and ECG, we follow [7] and use the split ratio of 70%-20%-10%. For data preprocessing, we use min-max normalization and Z-Score normalization on ECG and the rest of the datasets, respectively. On four traffic datasets (i.e., PeMS03, 04, 07, and 08), we use the past 1-hour observations to predict the next 15-minute traffic volume or speed. _We also use this setting in ablation studies and model efficiency comparisons._ On the Electricity dataset, we forecast the next 1-hour consumption with the past 24-hour readings. On the Solar-Energy dataset, we use the past 4-hour data to predict the productions in the next half hour. On the ECG dataset, we set the window size and forecasting horizon to 12 and 3. For the baseline configurations, we follow [7]. For the primary hyperparameter settings of TGC on different datasets, see Tab. S2. Experimental setting in Tab. 1 (right).We adopt the same evaluation metrics and follow the experimental setting in [18]. For the four traffic datasets, we use a data split of 60%-20%-20%. In terms of data preprocessing, min-max normalization is employed. Here, we use the past 1-hour observations to predict the next 1-hour traffic volume or speed. ### Long-Term Forecasting In this subsection, we detail the experimental setting of long-term time series forecasting. Our results are in Tab. 2. The dataset statistics are in Tab. S1. For all baselines, we detail them as follows. * **FILM**[29] first applies Legendre polynomial to approximate time series and then denoises approximations with a frequency-domain model based on Fourier projections. * **FEDformer**[14] proposes a frequency-enhanced Transformer framework for effective long-term time series forecasting. * **Autoformer**[30] designs a decomposition Transformer with the auto-correlation mechanism for long-term time series forecasting. * **Informer**[31] is an efficient Transformer with ProbSparse self-attention for long-term time series forecasting. * **LogTrans**[32] uses LogSparse attention to implement an efficient Transformer for time series forecasting. * **Reformer**[33] marries local-sensitive hashing with Transformer to significantly reduce the model complexity. Similar to short-term forecasting, we adopt the MAE and RMSE as evaluation matrices. For dataset split and baseline settings, we follow [29]. Specifically, we use the split of 70%-10%-20% for all three datasets. On the Electricity dataset, we use the past 4 days' observations to predict the consumption of the next 4, 8, and 14 days. On the Solar-Energy and Weather datasets, we predict the next 16, 32, and 56 hours' readings by using the past 16-hour data. It is worth noting that we use Jacobi polynomial basis for long-term forecasting by default, which has two tunable parameters \(\alpha\) and \(\beta\) (See Appendix E). The hyperparameter setting of our method for long-term forecasting is in Tab. S3. ### Evaluation of Modeling Differently Signed Time Series Relations We now describe the generation of the synthetic dataset used in our experiments in Fig. 5(a). To assess our method's ability to model differently signed time series relations, we create two groups of time series, each with a length of 2000. For the first group, we generate a sinusoidal signal and develop 100 distinct instances with varying amplitudes and injected random noise. Similarly, we generate another group of data based on cosinusoidal oscillation. Consequently, we know that: (1) Time series within each group are positively correlated; (2) Time series across different groups are negatively correlated. We denote these two groups as types A and B in our experiments. Referring to our discussion and the results in Fig. 5(a), we make two clear observations: (1) Both our method (i.e., TGC) and MP-STGNNs can learn positive relations between time series (i.e., same colored shapes should be close to each other); (2) However, only our method can model differently signed (e.g., purely negatively correlated) time series (i.e., differently colored shapes should be far away from each other). ## Appendix H Additional Results ### Additional Forecasting Results We provide our supplementary short-term forecasting results in Tab. S4, from which the following observations can be made: (1) TGC, in most cases, outperforms all baseline methods by substantial margins, with an average improvement of 35% compared to the best deep time series baselines; (2) It generally outperforms StemGNN, although the performance gaps are not very significant under this experimental setting. ### Parameter Studies In Fig. S6, we study four important hyperparameters in TGC. Our experimental results lead to the following observations: (1) Adjusting the \(\alpha\) in Gegenbauer polynomials impacts model performance variably across datasets. For instance, a smaller \(\alpha\) is generally favored in three PeMS datasets, as depicted in Fig. S6a; (2) The polynomial degree should not be too small to avoid information loss, as demonstrated by the poor performance when \(K=1\) in Fig. S6b. In practice, we set \(K\) between 3 and 5, as higher degrees do not bring additional performance gains; (3) Similarly, setting \(S\) too small or too large is not desirable, as shown in Fig. S6c. This is to prevent information loss and mitigate the impact of noise; (4) Stacking more building blocks seems to result in better performance, as illustrated in Fig. S6d. However, this comes at the cost of model efficiency. ### Additional Evaluation of Modeling Time Series Dependencies Additional evaluation can be found in Fig. S7 and Fig. S8, where we compare the learned time series embeddings from two SPTGNNs (i.e., Ours and StemGNN [7]) and MP-STGNNs (i.e., STGCN\((1^{st})\)[2] and Graph WaveNet [3]). It is evident that SPTGNNs excel in learning different signed spatial relations between time series, yielding significantly distinct representations with much higher clustering purities in both cases, further substantiating our claims in the main text. ### Additional Main Result Statistics Tab. S5 presents both the average performances and 95% confidence intervals for our results reported in Tab. 1 and Tab. 2 with five individual runs on seven real-world time series datasets, covering both short-term and long-term forecasting tasks. ## Appendix I Visualization
2305.18961
Quantum Convolutional Neural Networks for Multi-Channel Supervised Learning
As the rapidly evolving field of machine learning continues to produce incredibly useful tools and models, the potential for quantum computing to provide speed up for machine learning algorithms is becoming increasingly desirable. In particular, quantum circuits in place of classical convolutional filters for image detection-based tasks are being investigated for the ability to exploit quantum advantage. However, these attempts, referred to as quantum convolutional neural networks (QCNNs), lack the ability to efficiently process data with multiple channels and therefore are limited to relatively simple inputs. In this work, we present a variety of hardware-adaptable quantum circuit ansatzes for use as convolutional kernels, and demonstrate that the quantum neural networks we report outperform existing QCNNs on classification tasks involving multi-channel data. We envision that the ability of these implementations to effectively learn inter-channel information will allow quantum machine learning methods to operate with more complex data. This work is available as open source at https://github.com/anthonysmaldone/QCNN-Multi-Channel-Supervised-Learning.
Anthony M. Smaldone, Gregory W. Kyro, Victor S. Batista
2023-05-30T11:48:12Z
http://arxiv.org/abs/2305.18961v2
# Quantum Convolutional Neural Networks for Multi-Channel Supervised Learning ###### Abstract As the rapidly evolving field of machine learning continues to produce incredibly useful tools and models, the potential for quantum computing to provide speed up for machine learning algorithms is becoming increasingly desirable. In particular, quantum circuits in place of classical convolutional filters for image detection-based tasks are being investigated for the ability to exploit quantum advantage. However, these attempts, referred to as quantum convolutional neural networks (QCNNs), lack the ability to efficiently process data with multiple channels and therefore are limited to relatively simple inputs. In this work, we present a variety of hardware-adaptable quantum circuit ansatzes for use as convolutional kernels, and demonstrate that the quantum neural networks we report outperform existing QCNNs on classification tasks involving multi-channel data. We envision that the ability of these implementations to effectively learn inter-channel information will allow quantum machine learning methods to operate with more complex data. **Keywords:** Quantum Machine Learning, Convolutional Neural Networks, Multi-Channel Data, Image Classification, Supervised Learning ## 1 Introduction Quantum computers are devices that utilize quantum mechanical phenomena such as superposition and entanglement to solve problems that are infeasible with timescales provided by classical computers. From the time quantum computers were first pro posed in 1982 [1], researchers have been working to develop algorithms that provide quantum advantage over classical algorithms [2, 3, 4, 5, 6, 7, 8]. The main application challenges are related to noise, high gate errors and short decoherence times [9], necessitating the development of more efficient quantum circuit ansatzes. In recent years, devices have demonstrated quantum supremacy such as those introduced by Google AI Quantum (2019) [10], the University of Science and Technology of China (2020) [11], and IBM (2021) [12]. Machine learning (ML) has been gaining significant attention in recent years for strongly influencing many important fields of study and sectors of society. Image recognition [13, 14, 15], natural language processing [16, 17, 18], self-driving vehicles [19, 20, 21, 22, 23], robotics [24, 25, 26, 27, 28], and molecular biochemistry [29, 30, 31, 32] are just some of the fields that are being revolutionized by ML. The most prominent example would be ChatGPT, a chatbot built on top of OpenAI's generative pre-trained transformer (GPT)-3.5 and GPT-4 large language models that has been fine-tuned for conversation using both supervised and reinforcement learning from human feedback techniques [33, 34]. In the natural sciences, Deepmind's Alphafold is able to accurately predict 3D models of protein structures, and is accelerating research in nearly every field of molecular biology and biochemistry [35]. The advances in both quantum computing and ML inspire the development of quantum ML (QML) methods to exploit the speed of quantum computations and the predictive capabilities of ML. There has been recent work demonstrating the feasibility and advantages of substituting components of classical ML architectures with quantum analogues [36, 37, 38, 39], such as quantum circuits in place of classical convolutional kernels in convolutional neural networks (CNNs) [40, 41, 42, 43, 44, 45, 46, 47, 48]. Classical CNNs are state-of-the-art for image, video, and sound recognition tasks [49, 50] and also have applications in the natural sciences [51, 52, 53, 54, 55, 56]. CNNs that incorporate quantum circuits to function as kernels, referred to as Quantum CNNs (QCNNs), have performed well on classification tasks involving simple data such as the MNIST dataset of handwritten digits [42, 48], as well as multi-channel data such as the CIFAR-10 dataset [45, 57]. The QCNN was introduced in 2019 by Cong _et al._[40], and was applied to quantum phase recognition and quantum error correction optimization. Since then, QCNNs have been applied in areas ranging from high energy physics [43] to biochemistry [44]. However, current methods either do not effectively capture inter-channel information, or require more qubits than are currently permissible, and therefore lack the ability to efficiently process more complex data with multiple channels. With current QCNNs, the number of required qubits scales linearly with the length of the channel dimension of the input data. This is a feasible approach for simple data that can be modeled with small filters. For instance, Jing _et al._ demonstrated the ability to use a 12- and 18-qubit circuit to function as a 2 \(\times\) 2 and 3 \(\times\) 3 convolutional filter, respectively, on low resolution red-green-blue (RGB) images (three channels, one for each color) [45]. However, extension of this approach to tasks involving data with more channels is prohibited by current hardware limitations. As an attempt to overcome this challenge, there has been much recent work that performs a measurement on each channel individually, collapsing the wavefunction after measuring a given channel of the data and storing the measurement classically [42, 43, 44, 46]. Although the hardware requirements have no dependence on the number of channels when using this method, much of the inter-channel information is lost, which is valuable for accurately modeling the data. In this work, we propose several methods for operating with multi-channel data that preserve inter-channel information and require a number of qubits that is independent of the length of the channel dimension of the input data. ## 2 Quantum Circuits and Related Mathematical Formalisms ### Brief Theory of Quantum Computing Qubits are two-level systems used in computations to exploit the quantum mechanical phenomena of superposition and entanglement. The state of a single qubit can be represented by: \[\left|\psi\right\rangle=\alpha\left|0\right\rangle+\beta\left|1\right\rangle \text{ such that }\left|\alpha\right|^{2}+\left|\beta\right|^{2}=1\text{ and }\alpha,\beta\in\mathbb{C}. \tag{1}\] The state of a multi-qubit system is represented by the tensor product of all \(N\) single qubit states: \[\left|\Psi\right\rangle=\bigotimes_{i=1}^{N}\left|\psi_{i}\right\rangle=\left| \psi_{1}\right\rangle\otimes\left|\psi_{2}\right\rangle\otimes\cdots\otimes \left|\psi_{N}\right\rangle \tag{2}\] These qubit states are transformed via unitary operations. For any single qubit unitary, \[U=\begin{bmatrix}u_{00}&u_{01}\\ u_{10}&u_{11}\end{bmatrix}, \tag{3}\] the matrix of a two-qubit controlled operation may be expressed as \[CU=\begin{bmatrix}1&0&0&0\\ 0&1&0&0\\ 0&0&u_{00}&u_{01}\\ 0&0&u_{10}&u_{11}\end{bmatrix}. \tag{4}\] In a two-qubit controlled gate, if the control qubit is in the \(\left|1\right\rangle\) state, the unitary operation is applied to the target qubit. If the control qubit is in the \(\left|0\right\rangle\) state, the target qubit is unaffected. Measurements on a quantum state are performed by taking the expectation value of a Pauli operator, \(\sigma\) as shown in Equation 5. Quantum circuits model the sequential manipulation and measurement of qubits. \[\mathcal{M}=\left\langle\psi\right|\sigma_{x,y,z}\left|\psi\right\rangle \tag{5}\] ### The Deposit and Reverse Method The proposed Deposit and Reverse (DR) method takes advantage of phase kickback (i.e., phase accumulation on the ancilla qubit) and the guaranteed invertibility of quantum gates. In our case, a single channel of classical data is encoded into a quantum state and passed through a learnable set of unitary operations. Quantum information from the working qubits is deposited onto the ancilla qubit via a phase kickback, and the working qubits are uncomputed to return them to the uninitialized \(\ket{0}\) state, preparing them for angle encoding. This process is repeated for each channel, and the relative quantum phase is accumulated on the ancilla qubit. After processing all channels of the data, the ancilla qubit is measured, and the expectation value is used as the output of that quantum convolution. #### 2.2.1 State Preparation The DR-QCNN method removes the dependency of the number of necessary qubits on the length of the channel dimension of the data, and requires only \(F^{2}+1\) qubits, where \(F\) is the length of a single dimension of the square filter. The working qubits perform a convolution over one channel of an input signal, and the output is stored on the ancilla qubit. The uninitialized quantum state and classical input can be represented as: \[\ket{\Psi_{0}}=\ket{0}\otimes\ket{\psi_{0}}=\ket{0}\otimes\ket{0}^{\otimes N-1 },\mathbf{x}_{l,w,c}\in\mathbb{R}^{N-1} \tag{6}\] where \(l,w,c\) are the initial indices of an input 3D-tensor of total length \(L\), width \(W\), and channels \(C\), respectively, \(\ket{\Psi_{0}}\) is the state of the total quantum system, and \(\ket{\psi_{0}}\) is the state of the working qubits. \(\mathbf{x}_{l,w,c}\) is a vector of the flattened normalized input data covered by the filter for a single channel, described by the expression: \[\mathbf{x}_{l,w,c}=\{x_{l,w,c},x_{l,w+1,c},\cdots,x_{l,w^{\prime},c},x_{l+1,w,c},x_{l+1,w+1,c},\cdots,x_{l+1,w^{\prime},c},\cdots,x_{l^{\prime},w^{\prime},c}\} \tag{7}\] where \(l^{\prime}\) and \(w^{\prime}\) represent the final index covered by the filter of the length and width dimensions. \[l^{\prime}=l+F-1,w^{\prime}=w+F-1 \tag{8}\] In this work, the input data is encoded into a quantum state with angle encoding, as this method requires only a single gate per qubit and permits a low circuit depth compared to basis encoding and amplitude encoding. We encode all normalized data \(\mathbf{x}\) with a rotation about the Pauli-X axis by \(\pi x_{i}\) radians. Additionally, we prepare the ancilla qubit by placing it into a state of maximal superposition with a Hadamard transformation. The matrix representation of the gates for a rotation about the Pauli-X axis and a Hadamard transformation are described in Equations 10 and 9, respectively. \[\mathbf{R_{x}}\left(\theta\right)=\begin{bmatrix}\cos\left(\frac{ \theta}{2}\right)&-\sin\left(\frac{\theta}{2}\right)\\ -\sin\left(\frac{\theta}{2}\right)&\cos\left(\frac{\theta}{2}\right)\end{bmatrix} \tag{9}\] \[\mathbf{H}=\frac{1}{\sqrt{2}}\begin{bmatrix}1&1\\ 1&-1\end{bmatrix} \tag{10}\] The prepared quantum state is represented as: \[\ket{\Psi_{1}}=\ket{+}\otimes\ket{\psi_{1}}=\mathbf{H}\ket{0}\otimes\bigotimes \bigotimes_{i=1}^{F^{2}}\mathbf{R_{x}}\left(x_{i}\cdot\pi\right)\ket{\psi_{0}} \tag{11}\] #### 2.2.2 Circuit Construction Let \(\mathbf{U}\) be the set of \(\gamma\) chosen unitaries to perform the quantum convolution. \[\mathbf{U}=\prod_{i=1}^{\gamma}U_{i} \tag{12}\] After the classical data has been encoded and the deposition qubit has been placed into a state of maximal superposition, \(\mathbf{U}\) is applied to the working qubits, transforming the total state according to: \[\left|\Psi_{2}\right\rangle=\left|+\right\rangle\otimes\mathbf{U}\left|\psi_{ 1}\right\rangle=\left|+\right\rangle\otimes\left|\psi_{2}\right\rangle. \tag{13}\] Following this convolutional unitary, we parametrically deposit phasic information from the entangled working register onto the prepared ancilla qubit. This is achieved via a phase gate, controlled by the deposition qubit: \[\left|\Psi_{3}\right\rangle=CP\left(\theta\right)\left(\left|+\right\rangle \otimes\left|\psi_{2}\right\rangle\right)=\left|\psi_{a}\right\rangle\otimes \left|\psi_{2}\right\rangle, \tag{14}\] where the matrix representation of the single qubit phase gate is: \[P\left(\theta\right)=\begin{bmatrix}1&0\\ 0&e^{i\theta}\end{bmatrix} \tag{15}\] The application of a learnable controlled phase gate provides a quantum phase kick back. The phasic information that is learned within the entangled block is deposited onto the ancilla qubit without disrupting the state of the working register, assuming the ancilla qubit is in any arbitrary superposition state and the remaining \(F^{2}\) qubits are entangled in an arbitrary state \(\left|\psi_{c}\right\rangle\) (Appendix). It should be noted that these phase depositions on the ancilla qubit may be applied to each qubit in the working register to retain as much information as possible. For simplicity, we restrict the phase depositions to a single operation. The inverse convolutional unitary \(\mathbf{U^{-1}}\) may be applied to \(\left|\psi_{2}\right\rangle\) to uncompute the working register without changing \(\left|\psi_{a}\right\rangle\): \[\left|\Psi_{4}\right\rangle=\left|\psi_{a}\right\rangle\otimes\mathbf{U^{-1} }\left|\psi_{2}\right\rangle=\left|\psi_{a}\right\rangle\otimes\mathbf{U^{-1} }\mathbf{U}\left|\psi_{1}\right\rangle=\left|\psi_{a}\right\rangle\otimes \left|\psi_{1}\right\rangle. \tag{16}\] After uncomputing the working register, the angle-encoded classical data is uncomputed to return the convolutional register to the uninitialized state \(\left|0\right\rangle^{\otimes N-1}\), prepared for an additional convolution: \[\left|\Psi_{5}\right\rangle=\left|\psi_{a}\right\rangle\otimes\overset{F^{2}} {\underset{i=1}{\overset{F^{2}}{\otimes}}}\mathbf{R_{x}}\left(-x_{i}\cdot\pi \right)\left|\psi_{1}\right\rangle=\left|\psi_{a}\right\rangle\otimes\left| \psi_{0}\right\rangle \tag{17}\] It should be noted that performing a hard reset of the qubits in the working register will result in a mathematically identical state to \(\left|\Psi_{5}\right\rangle\). Measurements are typically the most error-prone operations to conduct, so the choice to reset or uncompute the working register should be dictated by the specifications of the available quantum hardware. This procedure is repeated for each channel of the input data, a Hadamard gate is applied to the ancilla qubit in state \(\ket{\psi_{a}^{\prime}}\), and then a measurement is taken on the final state of the ancilla: \[\mathcal{M}=\bra{\mathbf{H}\psi_{a}^{\prime}}\sigma_{z}\ket{\mathbf{H}\psi_{a}^{ \prime}}. \tag{18}\] A sample circuit is shown in Figure 1. The total number of gates and total circuit depth is calculated by Equation 19 and Equation 20, respectively: \[\mathrm{Gates}=\left(C-1\right)\left(2F^{2}+2\mathbf{U}_{G}+1\right)+F^{2}+ \mathbf{U}_{G}+3 \tag{19}\] \[\mathrm{Depth}=\left(C-1\right)\left(2\mathbf{U}_{D}+3\right)+\mathbf{U}_{D}+2 \tag{20}\] where \(\mathbf{U}_{G}\) is the number of gates and \(\mathbf{U}_{D}\) is the depth of the chosen set of convolutional unitaries \(\mathbf{U}\). ### Deposit and Reverse with Parallel Channels Method The Deposit and Reverse with Parallel Channels-QCNN (DRPC-QCNN) method decreases the circuit depth compared to that which is used in the DR-QCNN method. The DRPC-QCNN operates simultaneously on \(R\) parallelized channels, where \(R\) is the number of specified registers, and then deposits and reverses as in the DR-QCNN method. This method therefore requires \(RF^{2}+1\) qubits. #### 2.3.1 State Preparation The states of the working qubits in the DRPC-QCNN method are prepared similarly to the DR-QCNN method, with the caveat of each register being encoded with a different channel of the data The overall quantum state is initialized as done in Equation 6. The data covered by the filter of \(R\) channels is angle encoded as done in Equation 11, and the ancilla qubit is placed in a uniform superposition. #### 2.3.2 Circuit Construction The method of deposition and reversal is extended to \(R\) working qubit registers in the DRPC-QCNN. All working qubits are entangled according to Equation 22. This hierarchical method of first entangling intra-channel data and then inter-channel data is similar to the method used in the HQConv circuit [45]. Relative phasic information is deposited onto the ancilla qubit from the first qubit of each working register in Equation 23, and a measurement is taken as previously done in Equation 18. Figure 1: Deposit and Reverse (DR) circuit using a 2 \(\times\) 2 filter applied to three channels. \[|\Psi_{2}\rangle=|+\rangle\otimes\bigotimes_{i=1}^{R}|\mathbf{U}\psi_{1,i}\rangle= |+\rangle\otimes\bigotimes_{i=1}^{R}|\psi_{2,i}\rangle \tag{21}\] \[|\Psi_{3}\rangle=|+\rangle\otimes\mathbf{U}_{c}\bigotimes_{i=1}^{R}|\psi_{2,i} \rangle=|+\rangle\otimes|\psi_{3}\rangle \tag{22}\] \[|\Psi_{4}\rangle=CP^{R}\left(\theta\right)(|+\rangle\otimes|\psi_{3}\rangle)=| \psi_{a}\rangle\otimes|\psi_{4}\rangle \tag{23}\] This circuit is visualized in Figure 2. Although more qubits are being used than in the DR-QCNN, the number of gates and circuit depth have been reduced. The number of gates and depth of the DRPC-QCNN is calculated according to Equations 24 and 25, where \(\mathbf{U}_{c_{G}}\) and \(\mathbf{U}_{c_{D}}\) are the number of gates and depth, respectively, in the inter-channel unitary block. \[\text{Gates}=\left(\frac{C}{R}-1\right)\left(1+2RF^{2}+2R\mathbf{U}_{G}+2 \mathbf{U}_{c_{G}}+R\right)+R\mathbf{U}_{G}+\mathbf{U}_{c_{G}}+R+1 \tag{24}\] **Fig. 2**: Deposit and Reverse with Parallel Channels (DRPC) circuit with three registers using a 2 \(\times\) 2 filter applied to six channels. Parallelizing the channels allows for the opportunity to entangle them before the deposition step. \[\text{Depth}=\left(\frac{C}{R}-1\right)\left(2+2\mathbf{U}_{D}+2\mathbf{U}_{c_{D}} +R\right)+\mathbf{U}_{D}+\mathbf{U}_{c_{D}}+R+1 \tag{25}\] ### Deposit and Reverse with Parallel Channels - Topologically Considerate Method The circuit construction put forth in Section 2.3.2 is generalizable to \(C\) channels, but it becomes difficult to control each register from the same ancilla qubit as \(C\) becomes large. To account for this difficulty, we present an additional method that mitigates the challenges related to the topology of the hardware being used by introducing additional ancilla qubits. In this method, the maximum number of controlled depositions can be conducted before beginning to deposit phase onto the next ancilla qubit. With this Deposit and Reverse with Parallel Channels - Topologically Considerate (DRPC-T-QCNN) method, the ancilla qubits are entangled at the conclusion of all depositions, generating the final state: \[\left|\Psi\right\rangle=\left(\mathbf{U}_{a}\bigotimes_{i}^{A}\left|\psi_{a, i}\right\rangle\right)\otimes\left|\psi\right\rangle, \tag{26}\] where \(A\) is the total number of ancilla qubits, \(\mathbf{U}_{a}\) is set of unitaries entangling the ancilla register, \(\left|\psi_{a,i}\right\rangle\) is the state of the \(i\)th ancilla qubit, and \(\left|\psi\right\rangle\) is the final state of the working registers. The total number of qubits in this method is \(RF^{2}+A\). Figure 3: Deposit and Reverse with Parallel Channels - Topologically Considerate (DRPC-T) circuit with three registers using a 2 \(\times\) 2 filter applied to six channels. ### Weighted Expectation Value Method The Weighted Expectation Value (WEV)- QCNN method adds a hybrid component to classically learn inter-channel features. The quantum convolutions are performed in the traditional sense of passing the filter over each channel individually. After the expectation values are acquired, we apply a classical weight and bias before summing each value to generate the corresponding output: \[\tilde{x}_{i^{\prime},j^{\prime}}=\sum_{c=1}^{C}\bra{\Psi_{i,j,c}}\sigma_{z} \ket{\Psi_{i,j,c}}\cdot w_{i,j,c}+b_{i,j,c} \tag{27}\] \(\tilde{x}_{i^{\prime},j^{\prime}}\) is a single classical output data point given by the quantum convolution. \(\Psi_{i,j}\) is the wavefunction after the convolution. This method is ideal for few qubits, few gates, and shallow circuit depth. The total number of qubits is \(F^{2}\), and the number of gates and circuit depth are shown in Equations 28 and 29, respectively. \[\text{Gates}=F^{2}+\mathbf{U}_{G} \tag{28}\] \[\text{Depth}=1+\mathbf{U}_{D} \tag{29}\] ### Convolutional Unitary Blocks The unitary blocks used to perform the convolutions are designed to demonstrate the functionality of the proposed methods. Unitary blocks \(\mathbf{U}_{1}\) and \(\mathbf{U}_{2}\) are shown in Figure 4, and are based on [58] and [42], respectively. The gate \(X^{\theta}\) represents a power of an \(X\) gate, and is described by Equation 30. The entangling unitary blocks \(\mathbf{U}_{c}\) and \(\mathbf{U}_{a}\) used in the DRPC and DRPC-T circuits are detailed in the Appendix. \[X^{\theta}=\begin{bmatrix}e^{\frac{i\pi\theta}{2}}\cos\left(\frac{\pi\theta}{2 }\right)&-ie^{\frac{i\pi\theta}{2}}\sin\left(\frac{\pi\theta}{2}\right)\\ -ie^{\frac{i\pi\theta}{2}}\sin\left(\frac{\pi\theta}{2}\right)&e^{\frac{i\pi \theta}{2}}\cos\left(\frac{\pi\theta}{2}\right)\end{bmatrix} \tag{30}\] ## 3 Results and Discussion ### Architecture We evaluate the proposed quantum circuits as components of a hybrid quantum-classical machine learning architecture for image classification. A quantum circuit is used to perform the convolution over the embedded input pixels of the image and build the output feature map, and a two-layer feed-forward network is used to obtain the probabilities for each possible class. This architecture is portrayed in Figure 5. ### Datasets We utilize the CIFAR-10 dataset, as well as three sets of synthetic data designed to isolate the ability of our circuits to learn inter-channel information. All models are trained for 20 epochs and the hyperparameters used for each dataset are not changed between models. #### 3.2.1 Cifar-10 The Canadian Institute for Advanced Research, 10 classes (CIFAR-10) [59] is a dataset of images that has become a prominent benchmark for image recognition models. This dataset consists of 50,000 training and 10,000 testing RGB images of ten different classes: airplane, automobile, bird, cat, dog, deer, frog, horse, ship, and truck. Each image is 32 \(\times\) 32 pixels (in this work, we rescale them to 10 \(\times\) 10 pixels). Unless otherwise specified, we train on 500 randomly selected images from each class, and test on 100 randomly selected images from each class that do not appear in the training set. #### 3.2.2 Synthetic Noisy Colors 10 \(\times\) 10 pixel images of nine colors are created (blue, green, red, cyan, magenta, yellow, light cyan, pink, and light yellow), and 20% of these pixels are randomly selected and corrupted by setting all channel values of the corrupted pixel to 0. Three representative images are shown in Figure 7. In total, there are 400 images for each color (3,600 total images), where 80% of these images were used for training and 20% are used for testing. #### 3.2.3 Synthetic Noisy Patterned Colors To demonstrate that this method also captures intra-channel features, four different design shapes are drawn on the synthetic colors in white before corruption. In this dataset six base colors (blue, green, red, cyan, magenta, and yellow) are used, for a Figure 5: Hybrid quantum-classical machine learning architecture used to evaluate each of the proposed circuits. Figure 6: Three representative full-resolution (32 \(\times\) 32 pixel) images from the CIFAR-10 dataset. total of 24 classes, four of which are shown in Figure 8. We create 400 10 \(\times\) 10 training images of each class, and use 80% for training and 20% for testing. #### Synthetic High-Channel Data We create a 12-channel dataset consisting of tensors of shape 10 \(\times\) 10 \(\times\) 12 that are each populated with a uniform random distribution of numbers \(\in[0,1)\). Each of the 10 classes is defined by the addition of 0.5 to three distinct channels of the data, and is shown in Figure 9. ### CIFAR-10 Dataset Results All four proposed methods DR-QCNN, DRPC-QCNN, DRPC-T-QCNN, and WEV-QCNN are tested against a control QCNN. This control QCNN operates by passing the quantum filter over each channel individually, acquiring an expectation value, and summing the expectation values to produce the final output. To comprehensively evaluate the proposed QCNNs on the CIFAR-10 dataset, each model is evaluated on an _n_-member classification task, where \(n\) (two - ten) classes are contained in the training and test sets. We begin with ten classes and iteratively remove the remaining class that the DR-QCNN classifies with the least accuracy, Figure 8: Each design shape of patterned noisy color from the dataset. The designs are created using white (255, 255, 255), and then subsequently subjected to the random corruption. Figure 7: Three representative noisy color data points from the data set. Each color in the figure has a different number of populated channels: red (255, 0, 0), cyan (0, 255, 255), and light yellow (255, 255, 128). performing a classification at each iteration. The DRPC-QCNN using \(\mathbf{U}_{1}\) achieves the highest binary accuracy of 93.5%, compared to 85.0% with the control QCNN. When trained on all ten classes, the DR-QCNN was able to achieve 37.0% while the control QCNN produced 28.2% accuracy. The performance of each method on variable numbers of classes is shown in Figure 10. A comparison between each circuit is displayed for each type of classification in Figure 11. For all classifications, the DR-QCNN, DRPC-QCNN, and WEV-QCNN outperformed the control QCNN. The DR-QCNN achieves state-of-the-art performance on the CIFAR-10 dataset compared to current quantum neural networks (Table 1). ### Synthetic Dataset Results In an attempt to demonstrate that the increased accuracy of the DR-QCNN, DRPC-QCNN, and WEV-QCNN models can be attributed to their ability to extract features across the channel dimension, all proposed methods and the control QCNN are evaluated with synthetic datasets that emphasize inter-channel relationships. These synthetic datasets place all patterns to be learned in the channel dimension only, rather than both the spatial and channel dimension of the data. In an RGB image, the color is explicitly defined by the value of each channel. In the synthetic 12-channel dataset, the classes are determined by which channels contains higher values than the others. By relegating all important learnable patterns to the channel dimension, the proposed models' abilities to extract inter-channel features are demonstrated. All proposed methods are able to achieve 95% accuracy, with DRPC-QCNN achieving 100% accuracy on the _synthetic 12-channel dataset_. When predicting the color of noisy RGB images, the proposed models demonstrate the ability to learn, with the DR-QCNN and DRPC-QCNN achieving 100% accuracy. The control QCNN is shown to perform much worse. The results for the _noisy colors with shapes dataset_ are similar to those of the _noisy color dataset_. Figure 9: Synthetic high-channel data. Each element in the blue colored channels are random numbers between 0 and 1. Each element in the red colored channels are random numbers between 0.5 and 1.5. **Fig. 10**: Test set accuracy as a function of training epochs for the CIFAR dataset. Deposit and Reverse (DR) quantum convolutional neural network (QCNN), DR with parallel channels (DRPC)-QCNN, DRPC topologically considerate (DRPC-T)-QCNN, weighted expectation value (WEV)-QCNN, and a control QCNN are evaluated for two to ten classes on the CIFAR dataset. The control QCNN passes a filter individually over each channel and sums the expectation values. Quantum convolutions are performed with \(\mathbf{U}_{1}\). \begin{table} \begin{tabular}{c c} \hline Quantum Model & Test Accuracy \\ \hline \hline Quanvolutional Neural Network1[47; 57] & 34.9\% \\ Neural Network with Quantum Entanglement1[57] & 36.0\% \\ Flat Quantum Convolutional Ansatz2[45] & 41.8\% \\ Our work (DR-QCNN) & 45.1\% \\ \hline Classical Model & Test Accuracy \\ \hline CNN3 & 64.6\% \\ CNN-P3 & 51.2\% \\ \hline \hline \end{tabular} 1Models make no attempt to learn inter-channel information, and instead converts the images to grayscale. 2Model is tested with images from the training data. This accuracy is a reproduction trained and tested on the full CIFAR-10 data using their exact architecture and circuit. 3Both architectures are shown in Figures 1 and 2 in the Appendix. CNN-P is a CNN with the same number of parameters as our work. \end{table} Table 1: Full 60,000 CIFAR-10 Image Recognition Figure 11: Test set accuracy as a function of training epochs for the Deposit and Reverse (DR) quantum convolutional neural network (QCNN), DR with parallel channels (DRPC)-QCNN, DRPC topologically considerate (DRPC-T)-QCNN, weighted expectation value (WEV)-QCNN, and a control QCNN for binary and ten-member classification. Quantum convolutions are performed with \(\mathbf{U}_{1}\). Figure 12: Test set accuracy and test set loss as a function of training epochs for the Deposit and Reverse (DR) quantum convolutional neural network (QCNN), DR with parallel channels (DRPC)-QCNN, DRPC topologically considerate (DRPC-T)-QCNN, weighted expectation value (WEV)-QCNN, and control QCNN for classification of the _synthetic 12-channel dataset_ using \(\mathbf{U}_{2}\). Figure 13: Test set accuracy and test set loss as a function of training epochs for the deposit and reverse (DR) quantum convolutional neural network (QCNN), DR with parallel channels (DRPC)-QCNN, DRPC topologically considerate (DRPC-T)-QCNN, weighted expectation value (WEV)-QCNN, and control QCNN for classification of the _noisy colors dataset_ using \(\mathbf{U}_{2}\). **Fig. 14**: Test set accuracy and test set loss as a function of training epochs for the Deposit and Reverse (DR) quantum convolutional neural network (QCNN), DR with parallel channels (DRPC)-QCNN, DRPC topologically considerate (DRPC-T)-QCNN, weighted expectation value (WEV)-QCNN, and control QCNN for classification of the _noisy colors with shapes dataset_ using \(\mathbf{U}_{2}\). ## 4 Summary The proposed quantum circuits allow our QCNNs to effectively learn inter-channel information, as shown through evaluation of the models on synthetic data that holds important patterns in the channel dimension. Moreover, the DR-QCNN method achieves state-of-the-art performance on the CIFAR-10 dataset compared to current quantum neural networks. The poorer performance of the proposed DRPC-T-QCNN suggests better efforts must be made to effectively correlate the multiple ancilla qubits. It is our hope that soon this method will lose relevance, as fully connected systems are beginning to emerge, most recently Honeywell's 32-qubit trapped-ion quantum processor [60]. As these models possess a heightened ability to learn inter-channel patterns, we wish to apply these to deeper layers in quantum-hybrid neural networks. For the DR-QCNN, DRPC-QCNN, and DRPC-T-QCNN, the first qubit of each working register is used as the target to provide a phase kickback to the ancilla qubit(s). It is theorized higher accuracy may be achieved by performing controlled phase gates targeting all qubits in the working register, however as this work aims to create hardware considerate circuits, this is left to future projects. Since all expectation values are weighted in the WEV-QCNN method, it is proposed that as this method is parallelized across a Quantum Processing Unit the classical weights will learn which qubits are better performing than others and weight them less in the final output. This could serve as a quantum error corrective technique inherent to the WEV-QCNN method, and running it on real quantum hardware would test this theory. Beyond image recognition, we envision that these methods can be applied to problems in the natural and physical sciences. ## 5 Methods ### Hardware All scripting was done in Python 3.9.13. The quantum simulation package Cirq [61] version 0.13.1 was used, as well as Tensorflow 2.7.0 [62] and Tensorflow Quantum 0.7.2 [63]. An Intel i7-13700KF CPU, 12GB Nvidia GeForce RTX 3080Ti GPU, and 64GB of 3600MHz CL18 RAM were used for all computations. ### Datasets The CIFAR-10 dataset (Section 3.2.1) was loaded with Tensorflow Keras, and the pixel values were normalized between 0 and 1. The training and testing data were segregated by class, and the first 500 data points in each class of the training data were used as the training set. The first 100 data points in each class of the test data were used as the test set. Both sets were then shuffled using scikit-learn [64]. After building the training and test sets, all images were downsized from 32 \(\times\) 32 \(\times\) 3 to 10 \(\times\) 10 \(\times\) 3 using bilinear interpolation. The _noisy color dataset_ (Section 3.2.2) was created by making a colored 10 \(\times\) 10 - pixel square in Microsoft Paint using the RGB values specified in Table 3 and then images were saved as PNG files. For each color, 400 replicas of the images were loaded with Tensorflow, and 20% of the pixels were randomly corrupted in each by setting the pixel value to 0, 0, 0. The _noisy colors with shapes dataset_ (Section 3.2.3) was prepared analogously, where the shapes were drawn by setting the pixel values to white (255, 255, 255). Each channel in both of these RGB synthetic datasets was normalized to \(\frac{c}{C}\), where \(c\) is the index of the channel and \(C\) is the total number of channels. This allows the model to better distinguish between channels in the Bloch sphere. The _synthetic 12-channel dataset_ (Section 3.2.4) was created by initializing a 10 \(\times\) 10 \(\times\) 12 tensor, where all elements were populated with uniformly distributed random values between 0 and 1. 0.5 was added to every element in the three specified channels that comprised a class, where \(i\) class is defined by adding 0.5 to channels \(i\) to \(i+2\). 100 replicas of each class were generated to serve as training data, and 20 replicas of each class were generated to serve as test data. ### Machine Learning The learnable parameters in the quantum circuits were initialized using the Xavier method [65]. For the CIFAR-10 and synthetic RGB datasets (all but the _synthetic 12-channel dataset_), the classical weights and biases associated with the expectation values in the WEV-QCNN were initialized with a random normal distribution centered at 1.0 and 0.0, respectively, with both distributions having a standard deviation of 0.1. Xavier initialization was also used for the classical weights and biases when training on the _synthetic 12-channel dataset_. Categorical cross-entropy was used as the loss function, and Adam optimizer [66] was used to update the weights. A constant learning rate was used, which was a constant rate of 0.001 and was used for all datasets, except for the _synthetic 12-channel dataset_ which used a learning rate of 0.01. The exponential decay rate for the first and second moment estimations were set to 0.9 and 0.999, respectively for all training. Epsilon was set to \(1.0\times 10^{-7}\). The output of each hidden layer in the model architecture was activated with ReLU, and Softmax was applied to the final output layer to obtain probabilities. The classical architecture was the same for all models. Accuracy was calculated as the ratio of images the model classified correctly to the number of total images the model attempted to classify. ## 6 Data Availability All of our software including that to generate the synthetic datasets and reproduce the results from this work are available as open source at [https://github.com/anthonysmaldone/QCNN-Multi-Channel-Supervised-Learning](https://github.com/anthonysmaldone/QCNN-Multi-Channel-Supervised-Learning). ## 7 Statements and Declarations The authors declare no competing financial interest. \begin{table} \begin{tabular}{c c} \hline \hline Number of Classes & Class That is Added \\ \hline 2 & frog, ship \\ 3 & 2 + automobile \\ 4 & 3 + truck \\ 5 & 4 + airplane \\ 6 & 5 + bird \\ 7 & 6 + cat \\ 8 & 7 + horse \\ 9 & 8 + dog \\ 10 & 9 + deer \\ \hline \hline \end{tabular} \end{table} Table 2: Classes used in CIFAR-10 Experiments \begin{table} \begin{tabular}{c c} \hline \hline Color & RGB Value \\ \hline Blue & 0, 0, 255 \\ Green & 0, 255, 0 \\ Red & 255, 0, 0 \\ Cyan & 0, 255,255 \\ Magenta & 255, 0, 255 \\ Yellow & 255, 255, 0 \\ Light Cyan & 128, 255, 255 \\ Pink & 255, 128, 255 \\ Light Yellow & 255, 255, 128 \\ \hline \hline \end{tabular} \end{table} Table 3: Colors used in the Noisy Colors Dataset ## 8 Acknowledgements We acknowledge the support provided by the NSF CCI grant (Award Number 2124511). ## Appendix Let the deposition qubit be in an arbitrary superposition state \[\left|\psi_{a}\right\rangle=\alpha\left|0\right\rangle+\beta\left|1\right\rangle. \tag{1}\] When the \(CP\left(\theta\right)\) gate is applied to a qubit, if the control qubit is \(\left|0\right\rangle\), the state of the qubits remain unaltered. If the control qubit is in the \(\left|1\right\rangle\) state, phase is attached to the state of the control qubit as shown \[CP\left(\theta\right)\left(\left|0\right\rangle\otimes\left|\Psi_{c}\right\rangle \right)=\left|0\right\rangle\otimes\left|\Psi_{c}\right\rangle, \tag{2}\] \[CP\left(\theta\right)\left(\left|1\right\rangle\otimes\left|\Psi_{c}\right\rangle \right)=e^{i\theta}\left|1\right\rangle\otimes\left|\Psi_{c}\right\rangle. \tag{3}\] The parameterized phase gate being controlled by the deposition qubit and targeting the entangled state will show that only the state of the controlled qubit is affected. \[CP\left(\theta\right)\left(\left|\psi_{a}\right\rangle\otimes\left|\Psi_{c} \right\rangle\right)=CP\left(\theta\right)\left(\left(\alpha\left|0\right\rangle +\beta\left|1\right\rangle\right)\otimes\left|\Psi_{c}\right\rangle\right)=\] \[CP\left(\theta\right)\left(\alpha\left|0\right\rangle\otimes\left|\Psi_{c} \right\rangle+\beta\left|1\right\rangle\otimes\left|\Psi_{c}\right\rangle \right)=\] \[CP\left(\theta\right)\left(\alpha\left|0\right\rangle\otimes\left|\Psi_{c} \right\rangle\right)+CP\left(\theta\right)\left(\beta\left|1\right\rangle \otimes\left|\Psi_{c}\right\rangle\right)=\] \[\alpha\left|0\right\rangle\otimes\left|\Psi_{c}\right\rangle+\beta e^{i\theta }\left|1\right\rangle\otimes\left|\Psi_{c}\right\rangle=\left(\alpha\left|0 \right\rangle+\beta e^{i\theta}\left|1\right\rangle\right)\otimes\left|\Psi_{ c}\right\rangle=\] \[\left|\psi_{a}\right\rangle\otimes\left|\Psi_{c}\right\rangle \tag{4}\] Thus, Equation 14 holds, and the ancilla qubit is not entangled with the qubits in the working register. Figure 1: CNN Architecture Figure 2: CNN-P Architecture
2308.08230
Exploring Winograd Convolution for Cost-effective Neural Network Fault Tolerance
Winograd is generally utilized to optimize convolution performance and computational efficiency because of the reduced multiplication operations, but the reliability issues brought by winograd are usually overlooked. In this work, we observe the great potential of winograd convolution in improving neural network (NN) fault tolerance. Based on the observation, we evaluate winograd convolution fault tolerance comprehensively from different granularities ranging from models, layers, and operation types for the first time. Then, we explore the use of inherent fault tolerance of winograd convolution for cost-effective NN protection against soft errors. Specifically, we mainly investigate how winograd convolution can be effectively incorporated with classical fault-tolerant design approaches including triple modular redundancy (TMR), fault-aware retraining, and constrained activation functions. According to our experiments, winograd convolution can reduce the fault-tolerant design overhead by 55.77\% on average without any accuracy loss compared to standard convolution, and further reduce the computing overhead by 17.24\% when the inherent fault tolerance of winograd convolution is considered. When it is applied on fault-tolerant neural networks enhanced with fault-aware retraining and constrained activation functions, the resulting model accuracy generally shows significant improvement in presence of various faults.
Xinghua Xue, Cheng Liu, Bo Liu, Haitong Huang, Ying Wang, Tao Luo, Lei Zhang, Huawei Li, Xiaowei Li
2023-08-16T09:03:13Z
http://arxiv.org/abs/2308.08230v1
# Exploring Winograd Convolution for Cost-effective Neural Network Fault Tolerance ###### Abstract Winograd is generally utilized to optimize convolution performance and computational efficiency because of the reduced multiplication operations, but the reliability issues brought by winograd are usually overlooked. In this work, we observe the great potential of winograd convolution in improving neural network (NN) fault tolerance. Based on the observation, we evaluate winograd convolution fault tolerance comprehensively from different granularities ranging from models, layers, and operation types for the first time. Then, we explore the use of inherent fault tolerance of winograd convolution for cost-effective NN protection against soft errors. Specifically, we mainly investigate how winograd convolution can be effectively incorporated with classical fault-tolerant design approaches including triple modular redundancy (TMR), fault-aware retraining, and constrained activation functions. According to our experiments, winograd convolution can reduce the fault-tolerant design overhead by 55.77% on average without any accuracy loss compared to standard convolution, and further reduce the computing overhead by 17.24% when the inherent fault tolerance of winograd convolution is considered. When it is applied on fault-tolerant neural networks enhanced with fault-aware retraining and constrained activation functions, the resulting model accuracy generally shows significant improvement in presence of various faults. Winograd convolution, Vulnerability Analysis, Fault-Tolerance, Soft Errors. ## I Introduction Inspired by the great success of deep neural networks (DNNs) in computer vision and natural language processing in the past decade [1], people seek to explore the use of DNNs in more and more domains of applications. Many of the applications such as autonomous driving and medical robotics can be closely coupled with human safety and demand resilient processing of DNNs. Otherwise, unexpected inference failure may even lead to catastrophic consequences [2][3]. While the underlying computing engines that sustain DNN processing are typically fabricated with nanoscale technologies recently, and can inevitably suffer growing soft errors induced by alpha particles, neutrons, and heavy ions [4, 5, 6, 7, 8], fault-tolerant design approaches against soft errors become critical to the adoption of DNNs on these safety-critical applications. In addition, many prior works [9, 10, 11, 12] demonstrate that the fault tolerance of DNNs can also be utilized to relax the requirements of 100% correctness of the execution, and leveraged for higher performance and energy efficiency through techniques such as voltage scaling [13][14], overclocking [15][16] and model pruning [17]. In order to improve the fault tolerance of DNNs, various approaches have been proposed from different perspectives. Classical triple modular redundancy (TMR) [18] is a straightforward way to enhance the fault tolerance of DNNs yet will induce more than 200% computing overhead. Selective TMR or hardening [19][20] is generally preferred, as it significantly reduces the redundancy overhead by protecting only a fraction of the most vulnerable part of the DNN processing. Prior work in [21, 22, 23] applied typical algorithm-based fault tolerance (ABFT) algorithm to actively perform a light-weight error detection approach via a matrix-matrix multiplication based checksum mechanism. On top of the error detection, error correction which is usually much more expensive will only be invoked when errors are detected. In this case, the error correction overhead can be greatly amortized across the entire neural network processing. The above approaches improve the DNN fault tolerance significantly, but they generally require additional error detection overhead at runtime and usually affect the DNN data flow and performance accordingly. Unlike the redundancy and recomputing based fault-tolerant design approaches, another categories of approaches attempt to investigate the inherent fault tolerance of DNNs. Fault-aware retraining approach [24][25] essentially learns fault information to adapt to the specific failure scenarios. However, retraining is required for different failure scenarios and can induce considerable training cost. Instead of tuning the model parameters, the authors in [26][27] utilize network architecture search (NAS) to search for fault-tolerant, high-precision, and high-performance networks. Compared to clean neural networks, the searched fault-tolerant models typically will be more complex due to the fault-tolerant design constraints, resulting in additional computing overhead or lower accuracy. Different from prior research works, we aim to improve the inherent fault tolerance of DNNs without compromising the model accuracy nor affecting the execution performance. We observe that bit-flip errors in multiplication and addition operations usually induce distinct influence on output results. Basically, compared to addition, bit-flip errors on multiplication will generally cause larger computing bias, which makes multiplication more sensitive to soft errors accordingly. At the same time, we notice that winograd convolution can [28] greatly reduces the number of multiplication operations in standard convolution through equivalent linear transformation [29, 30, 31, 32], which poses great potential in improving the fault tolerance of DNNs. With the above observations, we investigate the fault tolerance of winograd-based DNNs comprehensively, and explore how we can leverage the inherent fault tolerance for more cost-effective protection against soft errors. Fault injection is widely utilized for fault tolerance analysis and existing fault injection tools usually inject random bit-flip errors with the granularity of neurons [9][33][34]. While winograd convolution can be viewed as an equivalent computing approach of standard convolution with the proposed kernel partition [35], the output neurons of winograd convolution will be the same with that calculated with standard convolution. In this case, we cannot differentiate the fault tolerance of winograd convolution and standard convolution given the widely utilized neuron-level fault injection tools, which hinders the fault tolerance analysis of winograd convolution consequently. To address the problem, we seek to conduct more fine-grained fault injection and propose an operation-level fault injection approach, which can be aware of the different convolution calculation approaches without compromising the generality of the fault injection. With the operation-level fault injection, we investigate the fault tolerance of winograd-based DNNs from different granularities such as models, layers, and operation types. The investigation confirms the much higher resilience of winograd convolution over standard convolution. Then, we leverage winograd convolution for more cost-effective fault tolerance of DNNs. Specifically, we explore the combination of winograd convolution with classical fault-tolerant neural network computing approaches including TMR, fault-aware retraining, and constrained activation functions. Our experiments demonstrate that winograd convolution can be utilized to reduce the fault-tolerant design overhead significantly and improve the model accuracy in presence of various soft errors. The contributions of this work can be summarized as follows. The second and the third contributions are mainly extended on top of the conference paper [36]. * We discover and investigate the fault tolerance of winograd DNNs comprehensively for the first time from different granularities such as models, layers, and operation types. * With the observation that the widely used neuron-level fault injection frameworks fail to differentiate the influence of soft errors on standard convolution and winograd convolution, we propose an operation-level fault injection framework for more fine-grained reliability analysis of neural network processing and have it open sourced on github1. Footnote 1: [https://github.com/xuczinghua/Operation-level-FLgit](https://github.com/xuczinghua/Operation-level-FLgit) * We leverage the inherent fault tolerance of winograd convolution to optimize the classical fault-tolerant approaches including TMR, fault-aware retraining, and constrained activation functions. Our experiments further confirm the advantages brought by winograd convolution in terms of both fault-tolerant design overhead and model accuracy improvement under various fault configurations. ## II Background and Related Work ### _Winograd Convolution_ Winograd convolution converts the matrix multiplication in standard convolution into element-wise multiplication, which is achieved by linearly transforming the input feature map and convolution kernels to a different domain of data representation. The element-wise multiplication results can be restored to the standard feature map domain with the corresponding inverse linear transformation. With the transform-calculation-inverse transformation process, the number of multiplication operations can be reduced considerably and the multiplication operations are replaced with more cost-effective addition operations, which significantly enhances the computing efficiency accordingly. \[Y_{k,b}=A^{T}\left(\sum_{c\,=\,1}^{C}\left(Gg_{k,c}G^{T}\right)\odot\left(B^ {T}d_{c,b}B\right)\right)A \tag{1}\] A typical tiled winograd convolution is presented in Equation 1, where \(\odot\) denotes the element-wise multiplication, \(Y\) denotes the output feature, \(g\) denotes the filter, \(d\) denotes the input feature. The subscript \(c\) and \(k\) denote the \(c\)-th input channel and \(k\)-th output channel respectively, and \(b\) denotes the \(b\)-th tile. \(A\), \(G\), and \(B\) denote the transformation matrices of output, filter, and input respectively. For a \(3\times 3\) winograd convolution \(F(2\times 2,3\times 3)\) operating on a \(4\times 4\) input tile generate a \(2\times 2\) output, the number of multiplication is reduced \(2.25\times 6\) from \(2\times 2\times 3\times 3=36\) to \((m+r-1)^{2}=(2+3-1)^{2}=16\). In general, the number of multiplication is reduced by \((m\times r)^{2}/(m+r-1)^{2}\). The data transform requires \(32\) additions, and the inverse transform requires \(24\) additions. When winograd convolution is conducted on \(3\times 3\) filter with unit stride, there will be no accuracy penalty. Even when the convolution filter and stride are larger, they can also be split to small ones according to the decomposable winograd method proposed in [35] and ensures lossless conversion. Winograd convolution has been explored from various angles such as quantization [37][38], tiling [39], hardware acceleration [40] for efficient DNN computing. As far as we know, there is still a lack of investigation of winograd convolution from the perspective of fault tolerance. In this work, we aim to investigate the fault tolerance of winograd-based convolution neural networks and take advantage of the improved neural network fault tolerance for soft error mitigation. ### _Reliability Analysis of Neural Networks_ Soft errors that are almost inevitable in existing large-scale VLSI designs typically manifest as bit flips and can propagate along with the neural network data flow. They may cause incorrect computing results and induce considerable accuracy loss. Quantifying the influence of soft errors and understanding the reliability of neural networks is an essential step to protect against the soft errors, especially for safety-critical applications like autonomous driving and robotics. There have been many prior works that evaluated the reliability of DNNs subjected to soft errors from different angles. For example, [41] studied the resilience of CNNs with different data types, values, data reuses, and types of layers to guide the fault-tolerant design. [9] explored the relationship between fault rate and model accuracy under various setups such as quantization, layer types, and network structures. [42] analyzed the impact of faults on SNNs with different parameters including splitters, routers, and neurons. Some of the reliability evaluations explored the reliability difference among components of neural networks such that they can be utilized to perform selective protection with less protection overhead [43, 44, 45]. More neural network reliability evaluation works can be found in recent surveys [46][47]. Fault injection platforms or fault simulation are usually required for the reliability study of neural network processing. Neuron-level fault injection platforms such as TensorFI [34], PyTorchFI [33], Ares [9] typically have bit errors injected to neurons or activations to model the influence of soft errors on neural network processing. They are widely utilized for the generality and much more convenient deployment. In contrast, some recent fault injection platforms have specific hardware architectures like GPUs [48][49] and neural network accelerators [50][51] considered for more accurate simulation. Compared to the neuron-level fault injection, they have higher fault simulation accuracy, but they are closely coupled with specific hardware architectures, which limits the generality of the analysis and slows down the simulation substantially. ### _Fault Tolerance of Neural Networks_ To protect neural network processing against errors in silicon, many fault-tolerant approaches have been extensively studied. Although conventional fault-tolerant design approaches such as triple modular redundancy, dual modular redundancy (DMR), ECC, and algorithm-based fault tolerance (ABFT) [52, 53, 54, 55] can potentially alleviate the influence of soft errors, they usually require considerable computing overhead. For instance, the authors in [56] have an self-checking scheme integrated in each modular of a typical DMR approach such that each modular can detect errors by itself. In this case, the revised DMR can also recover when only one of the modular is faulty. Although the redundancy overhead is reduced substantially compared to a standard TMR, it still takes more than 100% computing overhead and remains prohibitively expensive. In contrast, it is more flexible and cost-effective to take advantage of the inherent fault tolerance of the neural networks and alleviate the fault-tolerant design overhead. The authors in [57, 58, 59, 60] explored the fault tolerance of neural networks with retraining. Basically, it has the underlying hardware fault information learned and has the retrained model to adapt to the fault information. However, retraining is required for different fault scenarios and will induce considerable training cost. Several regularization techniques [61][62] have been proposed to constrain the range of weights and computing results in presence of hardware faults eventually. Unlike the works that retain the model architectures, the authors in [26][27] proposed to take fault tolerance into consideration in neural architecture search framework such that the searched network architecture fulfills both the fault tolerance metric and accuracy metric. More fault-tolerant approaches can also be found in recent surveys [46][47][63][64]. Existing works either require additional computing overhead or compromise the generality of the model. In this paper, we discover and evaluate the inherent fault tolerance of winograd convolution. With the fault tolerance of winograd convolution, we can achieve more cost-effective protection of neural network processing against soft errors without additional computing overhead nor accuracy penalty. ## III Fault Injection Platform To address the reliability analysis problem of winograd convolution, we propose an operation-level fault injection platform for more fine-grained reliability analysis without compromising the generality of the fault injection nor slowing down the fault simulation speed too much. Specifically, it has random bit-flip errors injected to fine-grained primitive operations such as addition and multiplication rather than coarse-grained operations of entire neurons. At the same time, it retains the advantage of prior neuron-level fault injection and also targets general neural network processing rather than a specific computing engine. We implemented it on top of PyTorch and open sourced on github. To illustrate the accuracy of the proposed operation-level fault injection, we take VGG19 on CIFAR-100 and GoogleNet on CIFAR-10 quantized with 16bit fixed point as an example, and compare the resulting model accuracy over that based on neuron-level fault injection. Specifically, we utilize bit error rate (BER) as the error metric. Although BER is originated from hardware error metric which refers to the bit flip error probability of a single memory bit, it is adapted to fit the soft error metric of neural network processing. Essentially, Fig. 1: Model accuracy drop curves under different bit error rate (BER) using both the neuron-level fault injection (FI) and the operation-level FI. The accuracy drop curves obtained from different FI platforms are generally consistent while the shift between the curves are mainly caused by the different BER definitions. from a statistical perspective, BER represents the ratio of the total number of bit errors over the total number of neuron bits or operation bits in an neural network. For the neuron-level fault injection, BER is calculated based on neurons, following previous work [9][33], we inject random soft errors into the output neurons of each convolution layer to simulate the bit-flip error. For the operation-level fault injection, BER is calculated based on operations. The model accuracy of standard convolution and winograd convolution under different BER setups obtained using different fault injection platforms are presented in Figure 1. We present the results with error band for more comprehensive comparison in which the confidence interval is set to be 95%. It can be seen that the trend of the model accuracy drop under different BER setups are generally similar. The difference of the two accuracy curves are mainly caused by the different BER setups. For example, for VGG19 and GoogleNet based on winograd convolution, the BER based on neuron-level fault injection are roughly \(1.4\times 10^{3}\) and \(1.6\times 10^{3}\) higher than the operation-level fault injection respectively. The number of primitive operations of VGG19 and GoogleNet are roughly \(1.2\times 10^{3}\) and \(1.3\times 10^{3}\) more than the number of neurons, respectively. It can be seen that the BER difference is roughly consistent with the difference of operation number and neuron number in both VGG19 and GoogleNet, which confirms the inherent consistence of the two fault injection methods. To enable more clear comparison, we have BER in neuron-level fault injection scaled to that defined in operation-level fault injection. In this case, we evaluate the accuracy of standard convolution and winograd convolution under different BER setups. The experiment result is shown in Figure 2. It can be seen that there is no accuracy difference between standard convolution and winograd convolution under different bit error rate when using the neuron-level fault injection platform. It shows that the influence of soft error on standard convolution and winograd convolution cannot be distinguished as expected, because neuron-level fault injection is performed on neurons rather the neuron computing procedures. Nevertheless, the difference is clearly observed when the fine-grained operation-level fault injection is adopted. At the same time, we can observe that despite the difference in fault simulation accuracy, the general trend of the model accuracy under different bit error rate obtained from the two different fault injection platforms remains consistent. On top of the model-wise comparison, we also compare the computing difference of a single neural network layer using operation-level fault injection and neuron-level fault injection respectively in presence of different bit flip errors. Specifically, we utilize root mean square error (RMSE) as the output variation metric and we take the 11th layer of VGG19 on CIFAR-100 as an example. The comparison is presented in Figure 3. It reveals that the RMSE obtained with operation-level fault injection and neuron-level fault injection of a standard convolution under different error rate is quite close to each other in general. In contrast, the RMSE differs considerably for winograd convolution and the RMSE obtained with operation-level fault injection is much lower. The main reason is that neuron-level fault injection fails to take advantage of the fault tolerance brought by winograd convolution. In addition, we also have the proposed fault injection platform compared to fault injection platforms with hardware architecture details. While existing fault injection platforms with architecture details [48][51] focus on the analysis of different consequences of errors and they are usually difficult to be applied for model accuracy evaluation directly, we revised a state-of-the-art fault injection platform based on scale-sim simulator [51] for the model accuracy analysis. We reuse the same floating point model VGG16 evaluated in [51] for the accuracy evaluation on ImageNet dataset. As errors in control logic are not considered in operation-level fault injection, we simply avoid the errors that will crash the control logic for a fair comparison. The model accuracy comparison under different BER setups is presented in Figure 4. The accuracy measured in Figure 4(a) refers to the percentage of correct inference over the total number of inference using the same input, while the accuracy used in Figure 4(b) refers to the percentage of correct inference over the total number of inference using different inputs. It can be observed that the proposed operation-level fault injection shows quite similar accuracy drop with that evaluated with the fault injection in [51] in both cases, which confirms the fault simulation accuracy of operation-level fault injection. injection and the neuron-level fault injection framework. In addition, we have a set of different ResNet models on ImageNet including ResNet18, ResNet50, ResNet101 utilized as the benchmark. The experiment result is presented in Figure 5. It can be observed that the operation-level fault injection is 1.07\(\times\) and 1.03\(\times\) slower than the baseline and neuron-level fault injection respectively. Particularly, this slowdown remains consistent across different model sizes, validating the scalability of the proposed fault injection platform over varying models. ## IV Fault Tolerance of Winograd DNNs Based on the proposed operation-level fault injection platform, we evaluate the fault tolerance of winograd-based DNNs from different granularities. First of all, we compare the fault tolerance of standard convolution and winograd convolution under different bit error rate. Then, we study standard convolution and winograd convolution in terms of layer granularity. Finally, we investigate the impact of soft errors on different types of operations in both standard convolution and winograd convolution. ### _Evaluation Setup_ The major experiment setups include datasets and models benchmark, fault models, fault injection framework, and hardware platforms. **Datasets And Models.** In this evaluation, we use DenseNet169 on ImageNet, ResNet50 on ImageNet, VGG19 on CIFAR-100, and GoogleNet on CIFAR-10 as the benchmark neural networks. Each neural network is quantized to a 8bit fixed point version and a 16bit fixed point version respectively. **Fault Models.** We utilize bit flip to characterize typical soft errors. Particularly, following prior reliability analysis work [9][41], we also use bit error rate (BER), which represents the ratio of bit flip errors over the total number of bits of operations in the model as the soft error intensity metric. **Error Injection.** We adopt the operation-level fault injection platform proposed in Section III for the reliability evaluation. It only covers the convolution layer in the model. **Hardware Platforms.** All the evaluation experiments are performed on a server equipped with two [email protected] Intel Xeon processors, 512GB memory, and four PH402 SKU 200 GPU cards. ### _Network-wise Fault Tolerance Evaluation_ In this sub section, we evaluated the accuracy of the benchmark neural networks implemented with standard convolution and winograd convolution under different bit error rate setups ranging from 0 to 1E-7, and utilize the accuracy degradation curves to characterize the resilience of the models subjected to bit flip errors. The experiment result is shown in Figure 6. It can be observed that the general trend of the accuracy curves of different models are similar. Basically, when the bit error rate is low, most of the computing errors can be tolerated and the model accuracy generally remains steady or drops slightly. When the bit error rate further increases, the model accuracy drops sharply as the distributed errors reach certain threshold and corrupt the models. In addition, we notice that different model architectures generally exhibit different accuracy degradation curves. We also observe that under each model architecture, neural network implemented with winograd convolution generally shows significant higher accuracy compared to that implemented with standard convolution. As shown in the dotted line in the figure, winograd convolution can improve the accuracy by up to 40% compared with standard convolution. The main reason is that winograd convolution [28] can reduce the arithmetic complexity by 2.25\(\times\) compared to standard convolution, and the total number of bit flip errors of winograd convolution within an inference will be much less than that of standard convolution due to the shorter runtime. Hence, the error induced computing variation will be less significant. While the performance advantage of winograd convolution over standard convolution depends on the neural network sizes, the total number of errors injected also varies for different neural network models and leads to different accuracy loss accordingly. In addition, we find that models quantized with int16 are more vulnerable than that with int8, because bit flip for int16 can cause larger data variation on average. Fig. 4: Comparison between operation-level fault injection and Saca-FI that has architecture details considered in fault injection [51]. Fig. 5: Fault simulation time of various neural network models in presence of different fault injection. ### _Layer-wise Fault Tolerance Evaluation_ To gain insight of the fault tolerance of winograd DNNs, we conduct layer-wise fault analysis of the neural networks with both winograd convolution and standard convolution, which is also an important basis for selective model protection. To characterize a layer fault tolerance of neural networks, as shown in Figure 7, we take VGG19 on CIFAR-100 as an example to implement layer-wise fault tolerance evaluation. we choose fault injection with a baseline accuracy loss 15% for winograd convolution. We use the model accuracy of standard convolution and winograd convolution at certain bit error rate as the baseline, denoted as ST-Conv-Base and WG-Conv-Base, respectively. We inject random bit errors into the operation of the entire neural network except the under evaluated layer to simulate model accuracy after protecting the under evaluated layer to obtain layer-wise model accuracy of the entire neural network using standard convolution and winograd convolution, denoted as ST-Conv and WG-Conv. The model accuracy difference of that obtained model accuracy after protecting the layer under evaluation relative to the baseline represents the fault sensitivity of the layer under evaluation. In general, larger accuracy difference indicates that higher model accuracy can be recovered from the baseline. Hence, the corresponding layer is more critical to the fault tolerance of the entire neural network. In addition, the variables # of Mul in ST-Conv and # of Mul in WG-Conv denote the number of multiplication operations involved in each layer of the standard convolution and winograd convolution models, respectively. These variables are employed to demonstrate the correlation between the fault sensitivity of the evaluated layer and the number of multiplication operations under operation-level fault injection. The experiment result is shown in Figure 7. It reveals the sensitivity of the different layers of the neural network. As can be seen from the figure, there is a large difference in sensitivity between the layers of the standard convolution and winograd convolution neural networks. Among them, the centering layers of both standard convolution and winograd convolution neural network are more sensitive to the bit errors, while the layers in the beginning and the end of the network are less sensitive. The accuracy difference between layers of winograd convolution is up to 12.34%, and the accuracy difference between layers of standard convolution is up to 27.21%. It is probably because of the difference in operation number involved in each layer, as the layer-wise model accuracy is roughly consistent with the number of multiplication operations involved in each layer according to Figure 7. Basically, the layers with more operations are likely to induce higher accuracy improvement. In addition, the layer-wise accuracy of the neural network implemented with winograd convolution is generally much higher than that implemented with standard convolution. The trend of the layer-wise accuracy is roughly consistent for neural networks implemented with both standard convolution and winograd convolution. ### _Operation Type Fault Tolerance Evaluation_ As winograd greatly changes the number of multiplication and addition in neural networks, we also investigate the fault tolerance from the perspective of operation types. Evaluation metrics are similar to layer-wise fault tolerance evaluation metrics. Assume that the entire model is exposed to random bit errors, then the model accuracy at which the multiplication operations are kept fault-free can be used to measure the Fig. 6: Accuracy of benchmark neural networks calculated with standard convolution and winograd convolution. sensitivity of the multiplication operations to bit errors. Higher accuracy indicates that these operations are more vulnerable and need to be protected with higher priority. Similarly, the sensitivity of operations in different neural networks under different bit error rate can be obtained. The experiment result is shown in Figure 8. Note that ST-Conv-Add and ST-Conv-Mul represent the accuracy of fault-free addition and fault-free multiplication in standard convolution respectively, while WG-Conv-Add and WG-Conv-Mul represent the accuracy of fault-free addition and fault-free multiplication in winograd convolution respectively. The experiment result shows that multiplication operations are more vulnerable than addition operations in standard convolution and winograd convolution of different neural networks under various bit error rate. In addition, we notice that the accuracy of WG-Conv-Add with more addition included is generally higher than that of ST-Conv-Add, but addition remains much less important to the accuracy of the entire neural network. In contrast, WG-Conv-Mul achieves comparable accuracy to ST-Conv-Mul at most bit error rates, but since winograd convolution have much fewer multiplication operations than standard convolution. This shows that compared to standard convolution, winograd convolution only needs to protect fewer multiplication operations to achieve the same accuracy, which makes winograd convolution more cost-effective for protection than standard convolution. ## V Exploring Winograd for Cost-effective Fault Tolerance We already demonstrate the significant fault tolerance advantage of winograd convolution in Section IV. However, winograd convolution can still suffer dramatic accuracy loss when soft errors exceed the fault-tolerance capability. In this case, we still need more intensive protection, and we mainly investigate how winograd convolution can be explored for more cost-effective fault tolerance using existing fault-tolerant design approaches in this section. Specifically, we take TMR and fault-tolerant DNNs based on fault-aware retraining and constrained activation functions as typical examples, and explore the use of winograd convolution for less fault-tolerant design overhead. ### _Winograd Convolution and TMR_ TMR is a classical approach to mitigate soft errors in silicon. Prior layer-wise TMR [52] for DNNs protects only a fraction of layers based on the vulnerability of the layers. Although more fine-grained protection is also possible, it remains difficult to separate the different operation types because the different operation types are closely coupled especially for DNN accelerators. We notice that winograd convolution splits the multiplication and addition operations considerably, which enables TMR protection across different operation types and layers without altering the computing patterns. On top of winograd convolution, we propose a fine-grained TMR protection approach as shown in Algorithm 1, which priorities the protection of a set of continuous operations across both the layers and operation types. First of all, we divide the operations into continuous segments with the same number of operations. Suppose the protection granularity of the basic processing segment is \(m\), and the total number of operations of the model is \(M\), we get \(\lceil M/m\rceil\) basic segments to be protected (line 2). Then, we select the segments for protection iteratively. Specifically, we utilize the vulnerability factor of the basic computing segments \(S_{i}\) as the protection priority metric. The vulnerability factor \(V_{i}\) is defined as the model accuracy improvement between models with the target computing segment protected and models without any protection (lines 3-8). Computing segments with higher vulnerability factor are preferred for the protection because they promise higher model accuracy improvement. As different computing segments may be correlated, we gradually add the segments for protection and investigate the accuracy at the end of each iteration. The procedure will stop when the model accuracy reaches the design goal of accuracy (i.e., \(ACC\)) such that the TMR protection overhead can be constrained(line 10-14). To simplify the protection granularity characterization, we utilize the ratio \(P=nm/M\) instead. Larger \(P\) indicates more coarse-grained protection granularity and \(P\) can be used to compromise between the TMR overhead and model accuracy. We have the proposed TMR protection approach applied to three different neural network implementations including standard convolution (ST-Conv), winograd convolution without being aware of the fault tolerance (WG-Conv-W/O-AFT), and winograd convolution with being aware of the fault tolerance (WG-Conv-W/AFT). Note that WG-Conv-W/O-AFT utilizes the same TMR protection option with ST-Conv because it is not aware of the fault tolerance of winograd convolution. The major difference between WG-Conv-W/O-AFT and ST-Conv is that WG-Conv-W/O-AFT conducts the neural network processing and protection on top of winograd convolution, while ST-Conv conducts on standard convolution. In contrast, WG-Conv-W/AFT conducts TMR protection on top of winograd convolution using fault-tolerant analysis results of winograd convolution. The experiments use VGG19 quantized with int16 on CIFAR-100 as the benchmark example and its original model accuracy is 72.6%. The bit error rate is set to 30% accuracy loss. We evaluate the TMR overhead of the three different convolution processing approaches including ST-Conv, WG Fig. 7: Accuracy of VGG19 on CIFAR-100 with one fault-free layer while the rest of layers are injected using operation-level fault injection. We have the neural network implemented with standard convolution and winograd convolution respectively. The base accuracy refers to the occasion when all the neural network layers are injected with the same bit error rate. Conv-W/O-AFT, and WG-Conv-W/AFT at different protection ratio i.e. \(P\) setups. \(P\) ranges from 5% to 0.1% and the target model accuracy is set to be 70%. All the TMR overhead is normalized to that of ST-Conv. We utilize the number of primitive operations such as addition and multiplication to measure the computing overhead. According to the comparison in [65], multiplication is generally more expensive than addition, so we have the operations weighted for a fair computing overhead comparison. The overhead of an multiplication (int8) is set to be 6.67\(\times\) higher over that of an add operation (int8). When the proposed fine-grained TMR protection is applied, the TMR overhead based on different convolution processing approaches is shown in Figure 9. It can be observed that the TMR overhead generally gets lower given more fine-grained TMR protection granularity as expected. Compared to conventional layer-wise TMR protection, the proposed fine-grained TMR reduces the TMR overhead by 3.84% to 15.3% depending on the protection granularity. The benefits of fine-grained TMR protection gets saturated when \(P\) is closer to 1%. The is probably attributed to the limited resolution of the vulnerability factor calculation based on fault injection. When comparing the different convolution processing approaches, we notice that WG-Conv-W/AFT requires the least TMR overhead under all the different protection granularity setups. Specifically, WG-Conv-W/O-AFT shows 55.77% less TMR overhead than ST-Conv on average, which is mainly attributed to the reduced computing overhead of fine-grained winograd convolution. When the fault tolerance capability of winograd convolution is considered, TMR computing overhead can be further reduced by 17.24% without compromising the model accuracy. We also evaluate the TMR overhead under different design goals ranging from 45% to 70%. The protection granularity ratio \(P\) is set to be 1%. The TMR overhead is normalized to that of ST-Conv based on the number of primitive operations. The experiment result is presented in Figure 10. It can be observed that TMR overhead can be reduced dramatically when lower model accuracy is required and less DNN processing needs to be protected. Although the computing benefit is mainly attributed to the reduced multiplication operations in winograd convolution, the fault tolerance of winograd convolution also contributes substantially especially when the target model accuracy is less stringent. For instance, when the target model accuracy is 45%, WG-Conv-W/AFT that fully explores the winograd convolution fault tolerance reduces the TMR overhead by 20% compared to WG-Conv-W/O-AFT. Fig. 8: Accuracy of standard and winograd neural networks with fault-free addition or fault-free multiplication under different bit error rate. ### _Winograd convolution and fault-tolerant DNNs_ Different from classical TMR, there are also fault-tolerant design approaches including fault-aware retraining and constrained activation functions that investigate the inherent fault tolerance of DNNs. In this section, we mainly explore whether the fault-tolerant DNNs can benefit from the fault tolerance of winograd convolution. Specifically, fault-tolerant retraining generally takes soft errors induced computing variation into loss calculation such that the retrained model have both data and computing errors involved in the model. As for constrained activation functions, it mainly revises the activation function such as Relu with additional range constraints to filter out neurons with very large or small values which are probably caused by soft errors. The range is obtained through profiling of the maximum and minimum data of neurons in the DNNs. Essentially, it suppresses the influence of soft errors on DNN processing. In this section, we apply winograd convolution to the fault-tolerant DNNs based on fault-aware training and constrained activation functions, and compare them with the fault-tolerant DNNs without using winograd conversion under various bit error rate setups. The comparison is shown in Figure 11 and Figure 12. In general, winograd convolution can further enhance the model accuracy on top of existing fault-tolerant DNNs despite the bit error rate setups, DNN models, and quantization data width. Particularly, as shown in Figure 11, we notice that winograd based DNN processing generally shows comparable model accuracy improvement when the fault-aware training is applied under various setups, which roughly demonstrates orthogonal fault tolerance capability between winograd convolution and fault-aware training. As for the constrained activation functions in Figure 12, we observe that winograd convolution also clearly improves the fault tolerance of DNNs under all the different setups. Nevertheless, the improvement is generally higher for the baseline models while the improvement is limited for the DNNs with constrained activation functions. The main reason is probably because the constrained activation functions already enhance the model significantly and leaves limited space for winograd convolution, but winograd processing is still great beneficial and requires less computing at the same time. In summary, we can conclude that winograd based DNN processing provides a unique angle of fault-tolerant design and can be integrated with the major fault-tolerant design approaches for DNNs. ## VI Conclusion This paper discovers and studies the fault tolerance of winograd-based DNNs comprehensively, and evaluates its fault tolerance from different granularities such as models, layers and operation types for the first time. With the evaluation, we further explore the use of winograd fault tolerance for cost-effective fault-tolerant designs. We propose a fine-grained TMR-based redundancy approach for DNNs that can span not only different layers but also different operation types. According to our experiments, the TMR computing overhead of winograd convolution is significantly reduced without compromising the accuracy. Additionally, we incorporate winograd convolution with classical fault-tolerant neural network approaches including fault-aware retraining and constrained activation functions, and verify its orthogonality with other classical fault-tolerant approaches.
2302.04451
Generalization in Graph Neural Networks: Improved PAC-Bayesian Bounds on Graph Diffusion
Graph neural networks are widely used tools for graph prediction tasks. Motivated by their empirical performance, prior works have developed generalization bounds for graph neural networks, which scale with graph structures in terms of the maximum degree. In this paper, we present generalization bounds that instead scale with the largest singular value of the graph neural network's feature diffusion matrix. These bounds are numerically much smaller than prior bounds for real-world graphs. We also construct a lower bound of the generalization gap that matches our upper bound asymptotically. To achieve these results, we analyze a unified model that includes prior works' settings (i.e., convolutional and message-passing networks) and new settings (i.e., graph isomorphism networks). Our key idea is to measure the stability of graph neural networks against noise perturbations using Hessians. Empirically, we find that Hessian-based measurements correlate with the observed generalization gaps of graph neural networks accurately. Optimizing noise stability properties for fine-tuning pretrained graph neural networks also improves test performance on several graph-level classification tasks.
Haotian Ju, Dongyue Li, Aneesh Sharma, Hongyang R. Zhang
2023-02-09T05:54:17Z
http://arxiv.org/abs/2302.04451v3
# Generalization in Graph Neural Networks: Improved ###### Abstract Graph neural networks are widely used tools for graph prediction tasks. Motivated by their empirical performance, prior works have developed generalization bounds for graph neural networks, which scale with graph structures in terms of the maximum degree. In this paper, we present generalization bounds that instead scale with the largest singular value of the graph neural network's feature diffusion matrix. These bounds are numerically much smaller than prior bounds for real-world graphs. We also construct a lower bound of the generalization gap that matches our upper bound asymptotically. To achieve these results, we analyze a unified model that includes prior works' settings (i.e., convolutional and message-passing networks) and new settings (i.e., graph isomorphism networks). Our key idea is to measure the stability of graph neural networks against noise perturbations using Hessians. Empirically, we find that Hessian-based measurements correlate with the observed generalization gaps of graph neural networks accurately; Optimizing noise stability properties for fine-tuning pretrained graph neural networks also improves test performance on several graph-level classification tasks. ## 1 Introduction A central measure of success for a machine learning model is the ability to generalize well from training data to test data. For linear and shallow models, the generalization gap between their training performance and test performance can be quantified via complexity notions such as the Vapnik-Chervonenkis dimension and Rademacher complexity. However, formally explaining the empirical generalization performance of deep models remains a challenging problem and an active research area (see, e.g., Hardt and Recht [25]). There are by now many studies for fully-connected and convolutional neural networks that provide an explanation for their superior empirical performance [4, 43]. Our work seeks to formally understand generalization in graph neural networks (GNN) [45], which are commonly used for learning on graphs [23]. As a concrete example for motivating the study of generalization performance, we consider the fine-tuning of pretrained graph neural networks [27]. Given a pretrained GNN learned on a diverse range of graphs, fine-tuning the pretrained GNN on a specific prediction task is a common approach for transfer learning on graphs. An empirical problem with fine-tuning is that, on one hand, pretrained GNNs use lots of parameters to ensure representational power. On the other hand, fine-tuning a large GNN would overfit the training data and suffer poor test performance without proper algorithmic intervention. Thus, a better understanding of generalization in graph neural networks can help us identify the cause of overfitting and, consequently, inspire designing robust fine-tuning methods for graph neural networks. A naive application of the generalization bounds from fully-connected feedforward networks [4; 42] to GNNs would imply an extra term in the generalization bound that scales with \(n^{l-1}\), where \(n\) is the number of nodes in the graph, hence rendering the error bounds vacuous. Besides, Scarselli et al. [46] shows that the VC dimension of GNN scales with \(n\). Thus, although the VC dimension is a classical notion for deriving learning bounds, it is oblivious to the graph structure. Recent works have taken a step towards addressing this issue with better error analysis. Verma and Zhang (2019) find that one-layer graph neural networks satisfy uniform stability properties [49], following the work of Hardt et al. [26]. The generalization bound of Verma and Zhang [49] scales with the largest singular value of the graph diffusion matrix of the model. However, their analysis only applies to a single layer and node prediction. Garg et al. (2020) analyze an \(l\) layer message-passing neural network \(-\) with \(l-1\) graph diffusion layers and \(1\) pooling layer \(-\) for graph prediction tasks [16]. Their result scales with \(d^{l-1}\), where \(d\) is the maximum degree of the graph. Subsequently, Liao et al. (2021) develop a tighter bound but still scales with \(d^{l-1}\)[37]. For both results, the graph's maximum degree is used to quantify the complexity of node aggregation in each diffusion step. In this paper, our major contribution is to show generalization bounds for graph neural networks by reducing the max degree to the spectral norm of the graph diffusion matrix. We analyze the stability of a graph neural network against noise injections. Denote an \(l\)-layer GNN by \(f\). Based on PAC-Bayesian analysis [39], the generalization gap of \(f\) will be small if \(f\) remains stable against noise injections; otherwise, the generalization gap of \(f\) will be large. By quantifying the noise stability of \(f\) via Lipschitz-continuity properties of its activation functions, one can get PAC-Bayes bounds for feedforward networks that correlate with their observed generalization gaps [12; 2; 31; 34]. We use a refined stability analysis of graph neural networks through Hessians and show tight generalization bounds on the graph diffusion matrix. **Our Contributions.** The goal of this work is to improve the theoretical understanding of generalization in graph neural networks, and in that vein, we highlight two results below: * First, we prove sharp generalization bounds for message-passing neural networks [9; 17; 33], graph convolutional networks [35], and graph isomorphism networks [54]. Our bounds scale with the spectral norm of \(P_{{}_{G}}^{l-1}\) for an \(l\)-layer network, where \(P_{{}_{G}}\) denotes a diffusion matrix on a graph \(G\) and varies between different models (see Theorem 3.1 for the full statement). We then show a matching lower bound instance where the generalization gap scales with the spectral norm of \(P_{{}_{G}}^{l-1}\) (see Theorem 3.2). Figure 1: **Left: Our spectral norm bounds for graph diffusion matrices are orders of magnitude smaller than maximum degree bounds on real-world graphs; In Figure 0(a), we measure the spectral norm and the max degree for five graph datasets. Right: In Figure 0(b), our Hessian-based generalization measure (plotted in green, scaled according to the _left axis_) matches the empirically observed generalization gaps of graph neural networks (plotted in yellow, scaled according to the _left axis_). The blue line shows a uniform-convergence bound (scaled according to the _right axis_) that is orders of magnitude larger than the observed gaps.** * Second, our stability analysis of graph neural networks provides a practical tool for measuring generalization. Namely, we show that the noise stability of GNN can be measured by the trace of the loss Hessian matrix. The formal statement is given in Lemma 4.3, and our techniques, which include a uniform convergence of the Hessian matrix, may be of independent interest. We note that the proof applies to twice-differentiable and Lipschitz-continuous activation functions (e.g., tanh and sigmoid). Taken together, these two results provide a sharp understanding of generalization in terms of the graph diffusion matrix for graph neural networks. We note that the numerical value of our bounds in their dependence on the graph is much smaller than prior results [16, 37], as is clear from Figure 0(a). Moreover, the same trend holds even after taking weight norms into account (see Figure 2, Section 3.3). Further, the Hessian-based bounds (see Lemma 4.3, Section 4) are non-vacuous, matching the scale of empirically observed generalization gaps in Figure 0(b). Finally, motivated by the above analysis, we also present an algorithm that performs gradient updates on perturbed weight matrices of a graph neural network. The key insight is that minimizing the average loss of multiple perturbed models with independent noise injections is equivalent to regularizing \(f\)'s Hessian in expectation. We conduct experiments on several graph classification tasks with Molecular graphs that show the benefit of this algorithm in the fine-tuning setting. ## 2 Related Work **Generalization Bounds:** An article by Zhang et al. (2017) finds that deep nets have enough parameters to memorize real images with random labels, yet they still generalize well if trained with true labels. This article highlights the overparametrized nature of modern deep nets (see also a recent article by Arora [1]), motivating the need for complexity measures beyond classical notions. In the case of two-layer ReLU networks, Neyshabur et al. (2019) show that (path) norm bounds better capture the "effective number of parameters" than VC dimension\(-\)which is the number of parameters for piecewise linear activations [5]. For multilayer networks, subsequent works have developed norm, and margin bounds, either via Rademacher complexities [4, 20, 38], or PAC-Bayesian bounds [2, 42, 36, 34]. All of these bounds apply to the fine-tuning setting following the distance from the initialization perspective. Our analysis approach builds on the work of Arora et al. (2018) and Ju et al. (2022). The latter work connects perturbed losses and Hessians for feedforward neural networks, with one limitation Hessians do not show any explicit dependence on the data. This is a critical issue for GNN as we need to incorporate the graph structure in the generalization bound. Our result instead shows an explicit dependence on the graph and applies to message-passing layers that involve additional nonlinear mappings. We will compare our analysis approach and prior analysis in more detail when we present the proofs in Section 4 (see Remark 4.4). **Graph Representation Learning:** Most contemporary studies of learning on graphs consider either node-level or graph-level prediction tasks. Our result applies to graph prediction while permitting an extension to node prediction: see Remark 4.2 in Section 4. Most graph neural networks follow an information diffusion mechanism on graphs [45]. Early work takes inspiration from ConvNets and designs local convolution on graphs, e.g., spectral networks [6], GCN [35], and GraphSAGE [24] (among others). Subsequent works have designed new architectures with graphs attention [48] and isomorphism testing [54]. Gilmer et al. (2017) synthesize several models into a framework called message-passing neural networks. Besides, one could also leverage graph structure in the pooling layer (e.g., differentiable pooling and hierarchical pooling [59, 62]). It is conceivable that one can incorporate the model complexity of these approaches into our analysis. Recent work applies pretraining to large-scale graph datasets for learning graph representations [27]. Despite being an effective transfer learning approach, few works have examined the generalization of graph neural nets in the fine-tuning step. Besides learning on graphs, GNNs are also used for combinatorial optimization [47] and causal reasoning [55]. There is another approach for graph prediction using kernels [50, 11]. There are also alternative graph diffusion processes besides GNN [18, 19, 61]. For references, see review articles [23, 7, 13, 53]. **Generalization in GNN:** Recent work explores generalization by formalizing the role of the algorithm, and the alignment between networks and tasks [56]. Esser et al. [14] finds that transductive Rademacher complexity-based bound provides insights into the behavior of GNNs (e.g., under stochastic block models). Besides, there are works about size generalization, which refer to performance degradation when models extrapolate to graphs of different sizes from the input [47, 58]. It is conceivable that the new tools we have developed may be useful for studying extrapolation. **Expressivity of GNN:** The expressivity of GNN for graph classification can be related to graph isomorphism tests and has connections to one-dimensional Weisfeiler-Lehman testing of graph isomorphism [41, 54]. This implies limitations of GNN for expressing tasks such as counting cycles [44, 8, 3]. The expressiveness view seems orthogonal to generalization, which instead concerns the sample efficiency of learning. For further discussions and references, see a recent survey by Jegelka [30]. ## 3 Sharp Generalization Bounds for Graph Neural Networks We first introduce the problem setup for analyzing graph neural networks. Then, we state our generalization bounds for graph neural networks and compare them with the prior art. Lastly, we construct an example to argue that our bounds are tight. ### Problem setup Consider a graph-level prediction task. Suppose we have \(N\) examples in the training set; each example is an independent sample from a distribution denoted as \(\mathcal{D}\), which is jointly supported on the feature space \(\mathcal{X}\) times the label space \(\mathcal{Y}\). In each example, we have an undirected graph denoted as \(G=(V,E)\), which describes the connection between \(n\) entities, represented by nodes in \(V\). For example, a node could represent a molecule, and an edge between two nodes is a bond between two molecules. Each node also has a list of \(d\) features. Denote all node features as an \(n\) by \(d\) matrix \(X\). For graph-level prediction tasks, the goal is to predict a graph label \(y\) for every example. We will describe a few examples of such tasks later in Section 5.2. **Message-passing neural networks (MPNN).** We study a model based on several prior works for graph-level prediction tasks [9, 17, 16, 37]. Let \(l\) be the number of layers: the first \(l-1\) layers are diffusion layers, and the last layer is a pooling layer. Let \(d_{t}\) denote the width of each layer for \(t\) from \(1\) up to \(l\). There are several nonlinear mappings in layer \(t\), denoted as \(\phi_{t},\rho_{t}\), and \(\psi_{t}\); further, they are all centered at zero. There is a weight matrix \(W^{(t)}\) of dimension \(d_{t-1}\) by \(d_{t}\) for transforming neighboring features, and another weight matrix \(U^{(t)}\) of dimension \(d\) by \(d_{t}\) for transforming the anchor node feature. For the first \(l-1\) layers, we recursively compute the node embedding from the input features \(H^{(0)}=X\): \[H^{(t)}=\phi_{t}\Big{(}XU^{(t)}+\rho_{t}\big{(}P_{{}_{G}}\psi_{t}(H^{(t-1)}) \big{)}W^{(t)}\Big{)}. \tag{1}\] For the last layer \(l\), we aggregate the embedding of all nodes: let \(\mathbf{1}_{n}\) be a vector with \(n\) values of one: \[H^{(l)}=\frac{1}{n}\mathbf{1}_{n}^{\top}H^{(l-1)}W^{(l)}. \tag{2}\] Note that this setting subsumes many existing GNNs. Several common designs for the graph diffusion matrix \(P_{{}_{G}}\) would be the adjacency matrix of the graph (denoted as \(A\)). \(P_{{}_{G}}\) can also be the normalized adjacency matrix, \(D^{-1}A\), with \(D\) being the degree-diagonal matrix. Adding an identity matrix in \(A\) is equivalent to adding self-loops in \(G\). In GCN, we can set \(U^{(t)}\) as zero, \(\rho_{t}\) and \(\psi_{t}\) as identity mappings. **Notations.** For any matrix \(X\), let \(\left\|X\right\|\) denote the largest singular value (or spectral norm) of \(X\). Let \(\left\|X\right\|_{F}\) denote the Frobenius norm of \(X\). We use the notation \(f(N)\lesssim g(N)\) to indicate that there exists a fixed constant \(c\) that does not grow with \(N\) such that \(f(N)\leq c\cdot g(N)\) for large enough values of \(N\). Let \(W\) and \(U\) denote the union of the \(W\) and \(U\) matrices in a model \(f\), respectively. ### Main results Given a message-passing neural network denoted as \(f\), what can we say about its generalization performance? Let \(f(X,G)\) denote the output of \(f\), given input with graph \(G\), node feature matrix \(X\), and label \(y\). The loss of \(f\) for this input example is denoted as \(\ell(f(X,G),y)\). Let \(\hat{L}(f)\) denote the empirical loss of \(f\) over the training set. Let \(L(f)\) denote the expected loss of \(f\) over a random example of distribution \(\mathcal{D}\). We are interested in the generalization gap of \(f\), i.e., \(L(f)-\hat{L}(f)\). How would the graph diffusion matrix \(P_{{}_{G}}\) affect the generalization gap of graph neural networks? To motivate our result, we examine the effect of incorporating graph diffusion in a one-layer linear neural network. That is, we consider \(f(X,G)\) to be \(\frac{1}{n}\mathbf{1}_{n}^{\top}P_{{}_{G}}XW^{(1)}\), which does not involve any nonlinear mapping for simplicity of our discussion. In this case, by standard spectral norm inequalities for matrices, the Euclidean norm of \(f\) (which is a vector) satisfies: \[\left\|f(X,G)\right\| =\left\|\frac{1}{n}\mathbf{1}_{n}^{\top}P_{{}_{G}}XW^{(1)}\right\|\] \[\leq\left\|\frac{1}{n}\mathbf{1}_{n}^{\top}\right\|\cdot\left\|P_ {{}_{G}}\right\|\cdot\left\|X\right\|\cdot\left\|W^{(1)}\right\| \tag{3}\] Thus, provided that the loss function \(\ell(\cdot,y)\) is Lipschitz-continuous, standard arguments imply that the generalization gap of \(f\) scales with the spectral norm of \(P_{{}_{G}}\) (divided by \(\sqrt{N}\)) [40]. Let us compare this statement with a fully-connected neural net that averages the node features, i.e., the graph diffusion matrix \(P_{{}_{G}}\) is the identity matrix. The spectral norm of \(P_{{}_{G}}\) becomes one. Together, we conclude that the graph structure affects the generalization bound of a single layer GNN by adding the spectral norm of \(P_{{}_{G}}\). Our main result is that incorporating the spectral norm of the _graph diffusion matrix_\(P_{{}_{G}}^{l-1}\) is sufficient for any \(l\) layer MPNN. We note that the dependence is a power of \(l-1\) because there are \(l-1\) graph diffusion layers: see equation (1). Let \(f\) be an \(l\)-layer network whose weights \(\mathbf{W},\mathbf{U}\) are defined within a hypothesis set \(\mathcal{H}\): For every layer \(i\) from \(1\) up to \(l\), we have that \[\left\|W^{(i)}\right\|\leq s_{i}, \left\|W^{(i)}\right\|_{F}\leq s_{i}r_{i},\] \[\left\|U^{(i)}\right\|\leq s_{i}, \left\|U^{(i)}\right\|_{F}\leq s_{i}r_{i}, \tag{4}\] where \(s_{1},s_{2},\ldots,s_{l}\) and \(r_{1},r_{2},\ldots,r_{l}\) are bounds on the spectral norm and stable rank and are all greater than or equal to one, without loss of generality. We now present the full statement. **Theorem 3.1**.: _Suppose all of the nonlinear activations in \(\left\{\phi_{t},\rho_{t},\psi_{t}:\forall\,t\right\}\) and the loss function \(\ell(\cdot,y)\) (for any fixed label \(y\in\mathcal{Y}\)) are twice-differentiable, Lipschitz-continuous, and their first-order and second-order derivatives are both Lipschitz-continuous._ _With probability at least \(1-\delta\) over the randomness of \(N\) independent samples from \(\mathcal{D}\), for any \(\delta>0\), and any \(\epsilon>0\) close to zero, any model \(f\) with weight matrices in the set \(\mathcal{H}\) satisfies:_ \[L(f)\leq(1+\epsilon)\hat{L}(f)+\mathrm{O}\left(\frac{\log(\delta^{-1})}{N^{3/4 }}\right)+\sum_{i=1}^{l}\sqrt{\frac{CBM_{i}\left(\max_{(X,G,y)\sim\mathcal{D}} \left\|X\right\|^{2}\left\|P_{G}\right\|^{2(l-1)}\right)\left(r_{i}^{2}\prod \limits_{j=1}^{l}s_{j}^{2}\right)}{N}}, \tag{5}\] _where \(B\) is an upper bound on the value of the loss function \(\ell(x,y)\) for any \((x,y)\sim\mathcal{D}\), and \(C\) is a fixed Lipchitz constant depending on the activation's and the loss function's Lipschitz-continuity (see equation (43), Appendix A.2.4)._ As a remark, prior works by Garg et al. [16] and Liao et al. [37] consider an MPNN with \(W^{(t)}\) and \(U^{(t)}\) being the same for \(t\) from \(1\) up to \(l\), motivated by practical designs [17, 33]. Thus, their analysis needs to be conducted separately for GCN and MPNN with weight tying. By contrast, our result allows \(W^{(t)}\) and \(U^{(t)}\) to be arbitrarily different across different layers. This unifies GCN and MPNN without weight tying in the same framework so that we can unify their analysis. We defer the proof sketch of our result along with a discussion to Section 4. ### Comparison with prior art In Table 1, we compare our result with prior results. We first illustrate the effects of graph properties on the generalization bounds. Then we will also show a numerical comparison to incorporate the other components of the bounds. * Suppose \(P_{{}_{G}}\) is the adjacency matrix of \(G\). Then, one can show that for any undirected graph \(G\), the spectral norm of \(P_{{}_{G}}\) is less than the maximum degree \(d\) (cf. Fact A.1, Appendix A for a proof). This explains why our result is strictly less than prior results for MPNN in Table 1. * Suppose \(P_{{}_{G}}\) is the normalized and symmetric adjacency matrix of \(G\): \(P_{{}_{G}}=\tilde{D}^{-1/2}\tilde{A}\tilde{D}^{-1/2}\), where \(\tilde{A}\) is \(A+\text{Id}\) and \(\tilde{D}\) is the degree-diagonal matrix of \(\tilde{A}\). Then, the spectral norm of \(P_{{}_{G}}\) is at most one (cf. Fact A.1, Appendix A for a proof). This fact explains why the graph dependence of our result for GCN is \(1\) in Table 1. Thus, we can see that this provides an exponential improvement compared to the prior results. Thus, for the above diffusion matrices, we conclude that the spectral norm of \(P_{{}_{G}}\) is strictly smaller than the maximum degree of graph \(G\) (across all graphs in the distribution \(\mathcal{D}\)). Numerical Comparison.Next, we conduct an empirical analysis to compare our results and prior results numerically. Following the setting of prior works, we use two types of models that share their weight matrices across different layers, including GCN [35] and the MPNN specified in Liao et al. [37]. For both models, we evaluate the generalization bounds by varying the network depth \(l\) between \(2,4,\) and \(6\). We consider graph prediction tasks on three collaboration networks, including IMDB-B, IMDB-M, and COLLAB [57]. IMDB-B includes a collection of movie collaboration graphs. In each graph, a node represents an actor or an actress, and an edge denotes a collaboration in the same movie. The task is to classify each graph into the movie genre as Action or Romance. The IMDB-M is a multi-class extension with the movie graph label Comedy, Romance, or Sci-Fi. COLLAB includes a list of ego-networks of scientific researchers. Each graph includes a researcher and her collaborators as nodes. An edge in the graph indicates \begin{table} \begin{tabular}{|c|c|c|c|c|} \hline \hline Graph Dependence & **GCN** & **MPNN** & **GIN** & **GraphSAGE-Mean** \\ \hline Garg et al. (2020) & \(d^{l-1}\) & \(d^{l-1}\) & - & - \\ Liao et al. (2021) & \(d^{\frac{l-1}{2}}\) & \(d^{l-1}\) & - & - \\ **Ours (Theorems \(3.1\) and \(4.5\))** & \(1\) & \(\left\|A\right\|^{l-1}\) & \(\sum_{i=1}^{l-1}\frac{\left\|A\right\|^{l}}{l-1}\) & \(\left\|D^{-1}A\right\|^{l-1}\) \\ \hline \hline \end{tabular} \end{table} Table 1: How does the generalization gap of graph neural networks scale with graph properties? In this work, we show spectrally-normalized bounds on \(P_{{}_{G}}\) and compare our results with prior results in the following table. We let \(A\) denote the adjacency matrix, \(D\) be the degree-diagonal matrix of \(A\), and \(l\) be the depth of the GNN. Previous generalization bounds scale with the graph’s maximum degree denoted as \(d\). Our result instead scales with the spectral norm of \(P_{{}_{G}}\) and applies to new settings, including graph isomorphism networks (GIN) [54] and GraphSAGE with mean aggregation [24]. a collaboration between two researchers. The task is to classify each ego-network into the field of the researcher, including High Energy, Condensed Matter, and Astro Physics. We report the numerical comparison in Figure 2. We report the averaged result over three random seeds. Our results are consistently smaller than previous results. As explained in Table 1, the improvement comes from the spectral norm bounds on graphs compared with the max degree bounds. ### A matching lower bound Next, we show an instance with the same dependence on the graph diffusion matrix as our upper bound. In our example: * The graph \(G\) is the complete graph with self-loops inserted in each node. Thus, the adjacency matrix of \(G\) is precisely a square matrix with all ones. We will set \(P_{{}_{G}}\) as the adjacency matrix of \(G\). * In the first \(l-1\) graph diffusion layers, the activation functions \(\phi,\rho,\psi\) are all linear functions. Further, we fix all the parameters of \(\mathbf{U}\) as zero. * The loss function \(\ell\) is the logistic loss. Then, we demonstrate a data distribution such that there always exists some weight matrices within \(\mathcal{H}\) whose generalization gap must increase in proportion to the spectral norm of \(P_{{}_{G}}^{l-1}\) and the product of the spectral norm of every layer \(s_{1},s_{2},\ldots,s_{l}\). **Theorem 3.2**.: _Let \(N_{0}\) be a sufficiently large value. For any norms \(s_{1},s_{2},\ldots,s_{n}\), there exists a data distribution \(\mathcal{D}\) on which with probability at least \(0.1\) over the randomness of \(N\) independent samples from \(\mathcal{D}\), for any \(N\geq N_{0}\), the generalization gap of \(f\) is greater than the following:_ \[\left|L(f)-\hat{L}(f)\right|\gtrsim\sqrt{\frac{\left(\max_{(\chi,G,\psi)\sim \mathcal{D}}\left\|P_{{}_{G}}\right\|^{2(l-1)}\right)\left(\prod\limits_{i=1}^{ l}s_{i}^{2}\right)}{N}}. \tag{6}\] Figure 2: Comparing our result and prior results [16, 37] on three graph classification tasks. **Upper**: The experiments are conducted on GCNs. **Lower**: The experiments are conducted on MPNNs following the setup of Liao et al. [37]. Notice that the lower bound in (6) exhibits the same scaling in terms of \(G-\left\lVert P_{{}_{G}}\right\rVert^{l-1}\)--as our upper bound from equation (5). Therefore, we conclude that our spectral norm bound is tight for multilayer MPNN. The proof of the lower bound can be found in Appendix A.3. **Remark 3.3**.: Our results from Theorem 3.1 and 3.2 together suggest the generalization error bound scales linearly in \(l\). To verify whether this is the case, we conducted an empirical study on three architectures (GCN, GIN-Mean, and GIN-Sum) that measured the growth of generalization errors as the network depth \(l\) varies. We find that the generalization error grows sublinearly with \(l\) to \(\left\lVert P_{{}_{G}}\right\rVert\). We also note that this sublinear growth trend has been captured by our Hessian-based generalization bound (cf. Figure 0(a)). It would be interesting to understand better why the sublinear trend happens and further provide insight into the behavior of GNN. **Remark 3.4**.: Theorem 3.2 suggests that in the worst case, the generalization bound would have to scale with the spectral norms of the graph and the weight matrices. Although this is vacuous for large \(l\), later in Lemma 4.1, we show a data-dependent generalization bound using the trace of the Hessians, which is non-vacuous. As shown in Figure 0(a), Hessian-based measurements match the scale of actual generalization errors: the green line, calculated based on the trace of the loss Hessian matrix (cf. equation (7)), matches the scale of the actual generalization error plotted in the yellow line. ## 4 Proof Techniques and Extensions Our analysis for dealing with the graph structure seems fundamentally different from the existing analysis. In the margin analysis of Liao et al. [37], the authors also incorporate the graph structure in the perturbation error. For bounding the perturbation error, the authors use a triangle inequality that results in a \((1,\infty)\) norm of the matrix \(P_{{}_{G}}\) (see Lemma 3.1 of Liao et al. [37] for GCN). We note that this norm can be larger than the spectral norm by a factor of \(\sqrt{n}\), where \(n\) is the number of nodes in \(G\): in the case of a star graph, this norm for the graph diffusion matrix of GCN is \(\sqrt{n}\). By comparison, the spectral norm of the same matrix is less than one (see Fact A.1, Appendix A). How can we tighten the perturbation error analysis and the dependence on \(P_{{}_{G}}\) in the generalization bounds, then? Our proof involves two parts: * **Part I:** By expanding the perturbed loss of a GNN, we prove a bound on the generalization gap using the trace of the Hessian matrix associated with the loss. * **Part II:** Then, we explicitly bound the trace of the Hessian matrix with the spectral norm of the graph using the Lipschitzness of the activation functions. **Part I:**_Measuring noise stability using the Hessian._ We first state an implicit generalization bound that measures the trace of the Hessian matrix. Let \(\mathbf{H}^{(i)}\) denote the Hessian matrix of the loss \(\ell(f(X,G),y)\) with respect to layer \(i\)'s parameters, for each \(i\) from \(1\) up to \(l\). Particularly, \(\mathbf{H}^{(i)}\) is a square matrix whose dimension depends on the number of variables within layer \(i\). Let \(\mathbf{H}\) denote the Hessian matrix of the loss \(\ell(f(X,G),y)\) over all parameters of \(f\). **Lemma 4.1**.: _In the setting of Theorem 3.1, with probability at least \(1-\delta\) over the randomness of the \(N\) training examples, for any \(\delta>0\) and \(\epsilon\) close to \(0\), we get:_ \[L(f)\leq(1+\epsilon)\hat{L}(f)+(1+\epsilon)\sum_{i=1}^{l}\sqrt{\frac{B\cdot \left(\max_{(X,G,y)\sim\mathcal{D}}\operatorname{Tr}\left[\mathbf{H}^{(i)} \left[\ell(f(X,G),y)\right]\right]\right)s_{i}^{2}r_{i}^{2}}{N}}+\mathrm{O} \left(\frac{\log(\delta^{-1})}{N^{3/4}}\right). \tag{7}\] Proof Sketch.At a high level, the above result follows from Taylor's expansion of the perturbed loss. Suppose each parameter of \(f\) is perturbed by an independent noise drawn from a Gaussian distribution with mean zero and variance \(\sigma^{2}\). Let \(\tilde{\ell}(f(X,G),y)\) be the perturbed loss value of an input example \(X,G\) with label \(y\). Let \(\mathcal{E}\) denote the noise injections organized in a vector. Using Taylor's expansion of the perturbed loss \(\tilde{\ell}\), we get: \[\tilde{\ell}(f(X,G),y)-\ell(f(X,G),y)=\mathcal{E}^{\top}\nabla\ell(f(X,G),y)+ \frac{1}{2}\mathcal{E}^{\top}\mathbf{H}\big{[}\ell(f(X,G),y)\big{]}\mathcal{E} +\mathrm{O}(\sigma^{3}). \tag{8}\] Notice that the expectation of the first-order expansion term above is equal to zero. The expectation of the second-order expansion term becomes \(\sigma^{2}\) times the trace of the loss Hessian. To derive equation (7), we use a PAC-Bayes bound of McAllester (39, Theorem 2). There are two parts to this PAC-Bayes bound: * The expectation of the noise perturbation in equation (8), taken over the injected noise \(\mathcal{E}\); * The KL divergence between the prior and the posterior, which is at most \(s_{i}^{2}r_{i}^{2}\) for layer \(i\), for \(i\) from \(1\) up to \(l\), within the hypothesis set \(\mathcal{H}\). Thus, one can balance the two parts by adjusting the noise variance at each layer--this leads to the layerwise Hessian decomposition in equation (7). A critical step is showing the uniform convergence of the Hessian matrix. We achieve this based on the Lipschitz-continuity of the first and twice derivatives of the nonlinear activation mappings. With these conditions, we prove the uniform convergence with a standard \(\epsilon\)-cover argument. The complete proof can be found in Appendix A.2.1. **Remark 4.2**.: Our argument in Lemma 4.1 applies to graph-level prediction tasks, which assume an unknown distribution of graphs. A natural question is whether the analysis applies to node-level prediction tasks, which are often treated as semi-supervised learning problems. The issue with directly applying our analysis to semi-supervised learning is that the size of a graph is only finite. Instead, a natural extension would be to think about our graph as a random sample from some population and then argue about generalization in expectation of the random sample. It is conceivable that one can prove a similar spectral norm bound for node prediction in this extension. This would be an interesting question for future work. **Part II:**_Spectral norm bounds of the trace of the Hessian._ Next, we explicitly analyze the trace of the Hessian at each layer. We bound the trace of the Hessian using the spectral norm of the weight matrices and the graph based on the Lipschitz-continuity conditions from Theorem 3.1. Notice that the last layer is a linear pooling layer, which can be deduced from layer \(l-1\). Hence, we consider the first \(l-1\) layers below. **Lemma 4.3**.: _In the setting of Theorem 3.1, the trace of the loss Hessian matrix \(\mathbf{H}^{(i)}\) taken over \(W^{(i)}\) and \(U^{(i)}\) satisfies the following, for any \(i=1,2,\cdots,l-1\),_ \[\left|\mathrm{Tr}\left[\mathbf{H}^{(i)}\left[\ell(f(X,G),y)\right] \right]\right| \lesssim\ s_{l}^{2}\left(\sum_{p=1}^{d_{i-1}}\frac{d_{i}}{q=1} \left\|\frac{\partial^{2}H^{(l-1)}}{\partial\big{(}W^{(i)}_{p,q}\big{)}^{2}} \right\|_{F}+\sum_{p=1}^{d_{i}}\sum_{q=l}^{d_{i}}\left\|\frac{\partial^{2}H^{( l-1)}}{\partial\big{(}U^{(i)}_{p,q}\big{)}^{2}}\right\|_{F}+\left\|\frac{ \partial H^{(l-1)}}{\partial W^{(i)}}\right\|_{F}^{2}+\left\|\frac{\partial H ^{(l-1)}}{\partial U^{(i)}}\right\|_{F}^{2}\right) \tag{9}\] \[\lesssim\ \left\|X\right\|^{2}\left\|P_{c}\right\|^{2(l-1)}\prod_{j =1:\ j\neq i}^{l}s_{j}^{2}. \tag{10}\] Proof Sketch.Equation (9) uses the chain rule to expand out the trace of the Hessian and then applies the Lipschitzness of the loss function. Based on this result, equation (10) then bounds the first and second derivatives of \(H^{(l-1)}\). This step is achieved via an induction of \(\partial H^{(j)}\) and \(\partial^{2}H^{(j)}\) over \(W^{(i)}\) and \(U^{(i)}\), for \(j=1,\ldots,l-1\) and \(i=1,\ldots,j\). The induction relies on the feedforward architecture and the Lipschitzness of the first and second derivatives. We leave out a few details, such as the constants in equations (9) and (10) that can be found in Appendix A.2.2 and A.2.3. Combining both parts together, we get equation (1). **Remark 4.4**.: We compare our analysis with the approach of Liao et al. [37]. Both our analysis and Liao et al. [37] follow the PAC-Bayesian framework. But additionally, we explore Lipschitz-continuity properties of the first and second derivatives of the activation functions (e.g., examples of such activations include tanh and sigmoid). This allows us to measure the perturbation loss with Hessians, which captures data-dependent properties much more accurately than the margin analysis of Liao et al. [37]. It would be interesting to understand if one could still achieve spectral norm bounds on graphs under weaker smoothness conditions (see, e.g., Wei and Ma [51]). This is left for future work. ### Extensions **Graph isomorphism networks.** This architecture concatenates every layer's embedding together for more expressiveness [54]. A classification layer is used after the layers. Let \(V^{(t)}\) denote a \(d_{i}\) by \(k\) matrix (recall \(k\) is the output dimension). Denote the set of these matrices by \(\mathcal{V}\). We average the loss of all of the classification layers. Let \(\hat{L}_{\text{\tiny{GIN}}}(f)\) denote the average loss of \(f\) over \(N\) independent samples of \(\mathcal{D}\). Let \(L_{\text{\tiny{GIN}}}(f)\) denote the expected loss of \(f\) over a random sample of \(\mathcal{D}\). See also equation (44) in Appendix A.4 for their precise definitions. Next, we state a generalization bound for graph isomorphism networks. Let \(f\) be any \(l\)-layer MPNN with weights defined in a hypothesis space \(\mathcal{H}\): the parameters of \(f\) reside within the constraints from equation (4); further, for every \(i\) from \(1\) up to \(l\), the spectral norm of \(V^{(i)}\) is less than \(s_{l}\). Building on Lemma 4.3, we show a bound that scales with the spectral norm generalization of the averaged graph diffusion matrices. Let \(P_{\text{\tiny{GIN}}}\) denote the average of \(l-1\) matrices: \(P_{\text{\tiny{G}}},P_{\text{\tiny{G}}}^{2},\ldots,P_{\text{\tiny{G}}}^{l-1}\). We state the result below. **Corollary 4.5**.: _Suppose the nonlinear activation mappings and the loss function satisfy the conditions stated in Theorem 3.1. With probability at least \(1-\delta\) for any \(\delta\geq 0\), and any \(\epsilon\) close to zero, any \(f\) in \(\mathcal{H}\) satisfies:_ \[L_{\text{\tiny{GIN}}}(f)\leq(1+\epsilon)\hat{L}_{\text{\tiny{GIN}}}(f)+\sum_{i =1}^{l}\sqrt{\frac{BCd_{i}\cdot\left(\max_{(X,G,y)\sim\mathcal{D}}\|X\|^{2} \left\|P_{\text{\tiny{GIN}}}\right\|^{2}\right)\left(r_{i}^{2}\prod_{j=1}^{l} s_{j}^{2}\right)}{N}}+\text{O}\left(\frac{\log(\delta^{-1})}{N^{3/4}}\right), \tag{11}\] _where \(B\) is an upper bound on the value of the loss function \(\ell\) across the data distribution \(\mathcal{D}\), and \(C\) is a fixed constant that only depends on the Lipschitz-continuity of the activation mappings and the loss._ The proof can be found in Appendix A.4. In particular, we apply the trace norm bound over the model output of every layer. The classification layer, which only uses a linear transformation, can also be incorporated. Fine-tuned Graph Neural Networks.We note that all of our bounds can be applied to the fine-tuning setting, where a graph neural network is initialized with pretrained weights and then fine-tuned on the target task. The results can be extended to this setting by setting the norm bounds within equation (4) as the distance between the pretrained and fine-tuned model. ## 5 Noise Stability Optimization for Fine-tuning GNNs A common practice to apply graph and deep learning is to adopt a pretrained GNN and fine-tune it for a target problem. Typically, only a small amount of data is available for fine-tuning. Thus, the fine-tuned model may overfit the training data, incurring a large generalization gap. A central insight from our analysis is that maintaining a small perturbed loss ensures lower generalization gaps. Motivated by this observation, we present an optimization algorithm to minimize the perturbed loss of a model. Let \(f\) denote a model and \(\tilde{\ell}(f)\) be the perturbed loss of \(f\), with noise injected inside \(f\)'s weight matrices. Recall from step (8) that \(\tilde{\ell}(f)\) is equal to \(\ell(f)\) plus several expansion terms. In particular, minimizing the expectation of \(\tilde{\ell}(f)\) is equivalent to minimizing \(\hat{L}(f)\) plus the trace of the Hessian matrix. To estimate this expectation, we sample several noise perturbations independently. Because Taylor's expansion of \(\tilde{\ell}(f)\) also involves the gradient, we cancel this out by computing the perturbed loss with the negated perturbation. Algorithm 1 describes the complete procedure. ``` 0: A training dataset \(\{(X_{i},G_{i},y_{i})\}_{i=1}^{N}\) with node feature \(X_{i}\), graph \(G_{i}\), and graph-level label \(y_{i}\), for \(i=1,\dots,N\). 0: Number of perturbations \(m\), noise variance \(\sigma^{2}\), learning rate \(\eta\), and number of epochs \(T\). 0: A trained model \(f^{(T)}\). 1: At \(t=0\), initialize the parameters of \(f^{(0)}\) with pretrained GNN weight matrices. 2:for\(1\leq t\leq T\)do 3:for\(1\leq i\leq m\)do 4: Add perturbation \(\mathcal{E}_{i}\) drawn from a normal distribution with mean zero and variance \(\sigma^{2}\). 5: Let \(\tilde{L}_{i}(f^{(t-1)})\) be the training loss of the model \(f^{(t-1)}\) with weight matrix perturbed by \(\mathcal{E}_{i}\). 6: Let \(\tilde{L}_{i}^{{}^{\prime}}(f^{(t-1)})\) be the training loss of the model \(f^{(t-1)}\) with weight matrix perturbed by \(-\mathcal{E}_{i}\). 7:endfor 8: Use stochastic gradient descent to update \(f^{(t)}\) as \(f^{(t-1)}-\frac{\eta}{2m}\sum_{i=1}^{m}\big{(}\nabla\tilde{L}_{i}\big{(}f^{(t -1)}\big{)}+\nabla\tilde{L}_{i}^{{}^{\prime}}\big{(}f^{(t-1)}\big{)}\big{)}\). 9:endfor ``` **Algorithm 1** Noise stability optimization for fine-tuning graph neural networks We evaluate the above algorithm for fine-tuning pretrained GNNs. Empirical results reveal that this algorithm achieves better test performance compared with existing regularization methods for five graph classification tasks. ### Experimental setup We focus on graph classification tasks, including five datasets from the MoleculeNet benchmark [52]. In each dataset, the goal is to predict whether a molecule has a certain chemical property given its graph representation. We use pretrained GINs from Hu et al. [27] and fine-tune the model on each downstream task. Following their experimental setup, we use the scaffold split for the dataset, and the model architecture is fixed for all five datasets. Each model has 5 layers; each layer has 300 hidden units and uses average pooling in the readout layer. We set the parameters, such as the learning rate and the number of epochs following their setup. We compare our algorithm with previous regularization methods that serve as benchmark approaches for improving generalization. This includes early stopping, weight decay, dropout, weight averaging [29], and distance-based regularization [21]. For implementing our algorithm, we set the number of perturbations as 10 and choose the noise standard deviation \(\sigma\) with a grid search in \(\{0.01,0.02,0.05,0.1,0.2,0.5\}\). ### Experimental results Table 2 reports the test ROC-AUC performance averaged over multiple binary prediction tasks in each dataset. Comparing the average ranks of methods across datasets, our algorithm outperforms baselines on all five molecular property prediction datasets. The results support our theoretical analysis that the noise stability property of GNN is a strong measure of empirical generalization performance. Next, we provide details insights from applying our algorithm. First, we hypothesize that our algorithm is particularly effective when the empirical generalization gap is large. To test the hypothesis, we vary the size of the training set in the BACE dataset; we compare the performance of our algorithm with early stopping until epoch 100. We plot the generalization gap between the training and test losses during training, shown in Figure 2(a)-2(b). As the trend shows, our algorithm consistently reduces the generalization gap, particularly when the training set size \(N\) is 600. Second, we hypothesize that our algorithm helps reduce the trace of the Hessian matrix (associated with the loss). We validate this by plotting the trace of the Hessian as the number of epochs progresses during training, again using the BACE dataset as an example. Specifically, we average the trace over the training dataset. Figure 2(c) shows the averaged trace values during the fine-tuning process. The results confirm that noise stability optimization reduces the trace of the Hessian matrix (more significantly than early stopping). We note that noise stability optimization also reduces the largest eigenvalue of the Hessian matrix, along with reducing the trace. This can be seen in Figure 2(d). Lastly, we study the number of perturbations used in our algorithm. While more perturbations would lead to a better estimation of the noisy stability, we observe that using 10 perturbations is sufficient for getting the most gain. We also validate that using negated perturbations consistently performs better than not using them across five datasets. This is because the negated perturbation cancels out the first-order term in Taylor's expansion. In our ablation study, we find that adding the negated perturbation performs better than not using it by 1% on average over the five datasets. **Remark.** We note that noise stability optimization is closely related to sharpness-aware minimization (SAM) [15]. Noise stability optimization differs in two aspects compared with SAM. First, SAM requires solving constrained minimax optimization, which may not even be differentiable [10]. Our objective remains the same after perturbation. Second, SAM reduces the largest eigenvalue of the Hessian matrix, which can be seen from Taylor's expansion of \(\tilde{\ell}(f)\). We reduce the trace of the Hessian matrix, which includes reducing the largest eigenvalue as part of the trace. There is another related work that regularizes noise stability in NLP [28]. Their approach adds noise perturbation in the input and regularizes the loss change in the output. Our approach directly adds the perturbation in the weight matrices. \begin{table} \begin{tabular}{l c c c c c c} \hline \hline Dataset & SIDER & ClinTox & BACE & BBBP & Tox21 & \\ \# Molecule Graphs & 1,427 & 1,478 & 1,513 & 2,039 & 7,831 & Avg. Rank \\ \# Binary Prediction Tasks & 27 & 2 & 1 & 1 & 12 & \\ \hline Early Stopping & 61.06\(\pm\)1.48 & 68.25\(\pm\)2.63 & 82.86\(\pm\)0.95 & 67.80\(\pm\)1.05 & 77.52\(\pm\)0.23 & 5.8 \\ Weight Decay & 61.30\(\pm\)0.21 & 67.43\(\pm\)2.88 & 83.72\(\pm\)0.99 & 67.98\(\pm\)2.41 & 78.23\(\pm\)0.35 & 5.0 \\ Dropout & 63.90\(\pm\)0.90 & 73.70\(\pm\)2.80 & 84.50\(\pm\)0.70 & 68.07\(\pm\)1.30 & 78.30\(\pm\)0.30 & 3.6 \\ Weight Averaging & 63.67\(\pm\)0.34 & 78.78\(\pm\)1.49 & 83.93\(\pm\)0.36 & 70.26\(\pm\)0.24 & 77.59\(\pm\)0.11 & 3.4 \\ Distance-based Reg. & 64.36\(\pm\)0.48 & 76.68\(\pm\)1.19 & 84.65\(\pm\)0.48 & 70.37\(\pm\)0.44 & 78.62\(\pm\)0.24 & 2.2 \\ \hline **Ours (Alg. 1)** & **65.13\(\pm\)0.18** & **80.18\(\pm\)0.82** & **85.07\(\pm\)0.43** & **71.22\(\pm\)0.36** & **79.31\(\pm\)0.24** & **1.0** \\ \hline \hline \end{tabular} \end{table} Table 2: Test ROC-AUC (%) score for five molecular property prediction datasets with different regularization methods. The reported results are averaged over five random seeds. Figure 3: In Figures 2(a) and 2(b), we show that our algorithm is particularly effective at reducing the generalization gap for small training dataset sizes \(N\). In Figures 2(c) and 2(d), we find that both the trace and the largest eigenvalue of the loss Hessian matrix decreased during training. Conclusion This work develops generalization bounds for graph neural networks with a sharp dependence on the graph diffusion matrix. The results are achieved within a unified setting that significantly extends prior works. In particular, we answer an open question mentioned in Liao et al. [37]: a refined PAC-Bayesian analysis can improve the generalization bounds for message-passing neural networks. These bounds are obtained by analyzing the trace of the Hessian matrix with the Lipschitz-continuity of the activation functions. Empirical findings suggest that the Hessian-based bound matches observed gaps on real-world graphs. Thus, our work also develops a practical tool to measure the generalization performance of graph neural networks. The algorithmic results with noise stability optimization further demonstrate the practical implication of our findings. Our work opens up many interesting questions for future work. Could the new tools we have developed be used to study generalization in graph attention networks [48]? Could Hessians be used for measuring out-of-distribution generalization gaps of graph neural networks? ## Acknowledgement Thanks to Renjie Liao, Haoyu He, and the anonymous referees for providing constructive feedback on our work. Thanks to Yang Yuan for the helpful discussions. HJ and DL acknowledge financial support from the startup fund of Khoury College of Computer Sciences, Northeastern University.
2309.02352
Neural Network Solutions of Bosonic Quantum Systems in One Dimension
Neural networks have been proposed as efficient numerical wavefunction ansatze which can be used to variationally search a wide range of functional forms for ground state solutions. These neural network methods are also advantageous in that more variational parameters and system degrees of freedom can be easily added. We benchmark the methodology by using neural networks to study several different integrable bosonic quantum systems in one dimension and compare our results to the exact solutions. While testing the scalability of the procedure to systems with many particles, we also introduce using symmetric function inputs to the neural network to enforce exchange symmetries of indistinguishable particles.
Paulo F. Bedaque, Hersh Kumar, Andy Sheng
2023-09-05T16:08:48Z
http://arxiv.org/abs/2309.02352v1
# Neural Network Solutions of Bosonic Quantum Systems in One Dimension ###### Abstract Neural networks have been proposed as efficient numerical wavefunction ansatze which can be used to variationally search a wide range of functional forms for ground state solutions. These neural network methods are also advantageous in that more variational parameters and system degrees of freedom can be easily added. We benchmark the methodology by using neural networks to study several different integrable bosonic quantum systems in one dimension and compare our results to the exact solutions. While testing the scalability of the procedure to systems with many particles, we also introduce using symmetric function inputs to the neural network to enforce exchange symmetries of indistinguishable particles. ## I Introduction Solving many-body quantum mechanical systems involves obtaining solutions to a high-dimensional partial differential equation or diagonalizing exponentially large Hamiltonians, both of which pose significant challenges. Thus, analytically solved models are few and far between. [1; 2; 3; 4; 5; 6; 7]. Various methods have been developed to obtain approximate solutions to complex quantum systems. For one such method called Variational Monte Carlo, a variational ansatz for the ground state wavefunction is assumed and an estimate for the ground state energy is obtained by minimizing the energy of the system over the parameters of the chosen approximate wavefunction form. The use of trial wavefunctions has been used to study a broad range of many-body systems, from Fermi and Bose gases to quantum chemistry [8; 9; 10; 11; 12; 13; 14; 15; 16; 17]. In particular, the Slater-Jastrow [18] wavefunction ansatz has been employed widely [19; 20; 21] because, by construction, it captures correlations between interacting particles and incorporates the correct intuitive functional form of the physical system. Tensor networks and density matrix renormalization group methods [22] were shown to efficiently encode low-lying eigenstates of local, gapped Hamiltonian spin systems using only a polynomial number of parameters. This eliminates the need to search through an exponentially-large Hilbert space. More recently, established machine learning techniques such as neural networks have found their way into quantum physics [23; 24]. In the context of studying ground states of quantum systems, neural networks conveniently provide a numerical wavefunction ansatz for which one can vary to minimize the system energy cost function. The minimization can be done efficiently using established machine learning methods of backpropagation and gradient descent. Another appeal of using neural networks is that they were shown to be universal function approximators [25; 26] and thus can be used to describe any general wavefunction. As a consequence, the number of variational parameters is not intrinsically tied to the function form (i.e. Jastrow) of the ansatz and can be increased easily. Carleo and Troyer [27] showed that a type of neural network called restricted Boltzmann machines were sufficient to describe ground state wavefunctions of spin systems with a reasonable number of parameters. Later, restricted Boltzmann machines was found to map directly to matrix product state approximations of spin states [28; 29]. For particles interacting via continuous-space potentials, several systems of indistinguishable particles have also been studied using neural networks including the Calogero-Sutherland model [30], nuclear models [31; 32; 33], and chemical systems [34; 35]. Quantum systems involving indistinguishable particles must have ground state wavefunctions which satisfy position exchange (anti)symmetries. This poses a challenge in which the constructed neural network trial wavefunction should satisfy these constraints. In one spatial dimension, Bose symmetry can be satisfied by feeding in ordered coordinates of the bosons into the neural network [30]; however, this method is not easily generalizable to systems of higher dimensions. Pfau et. al. [35] developed the FermiNet neural network structure to impose fermionic antisymmetry to study electron-electron and electron-ion interactions in atoms. The FermiNet structure constructs the most general fermionic wavefunction space for which one can search for the ground state through by taking Slater determinants of permutation-equivariant functions. The permutation-equivariance of such functions are enforced through permutation-equivariant neural network layers. In this paper, we instead propose the use of carefully selected symmetric inputs to enforce the Bose symmetry of the neural network ansatz. By using symmetric functions as inputs to the neural network, we are able to construct the most general Bose symmetric function as we increase the number of nodes and layers; this gives us full flexibility in changing the architecture of the network. We benchmark the use of symmetric functions by computing ground state energies and wavefunctions of several one-dimensional, exactly-solvable quantum systems and comparing both quantitative and qualitative results. Our methodology is not restricted to studying exactly-solvable systems and we also explore systems in which no analytical solution is known. We further demonstrate the scalability and versatility of our neural network ansatz by calculating ground states of systems with dozens of particles. In Sec. II, we outline the various models for which we study and compare numerical results to. In Sec. III, we explicitly construct the Bose symmetric neural network functions and outline our procedure for computing ground states. Sec. IV discusses our results; we find that our neural network ansatz is able to accurately compute ground state energies and features of the many-body systems considered over their various phases. Then we conclude with Sec. V by exploring prospects of using symmetric function constructions to write general bosonic and fermionic trial wavefunctions in a higher number of spatial dimensions. ## II Models To show the validity of our symmetric input neural network solutions, we apply our neural-network-based methodologies to solve for the ground state wavefunctions and energies for several different one-dimensional quantum systems. We consider both a system of cold bosons in a harmonic trap and a system of trapped bosons with short and long-range interactions. Both quantum systems are inspired by the Lieb-Liniger model Lieb and Liniger (1963); Lieb and Liniger (1963) -- a homogeneous gas of indistinguishable bosons interacting via a contact delta-function potential which was shown to be exactly solvable in one dimension through the use of Bethe ansatz Lieb and Liniger (1964); Lieb and Liniger (1965); Lieb and Liniger (1966). These Lieb-Liniger-inspired models have rich phase structure and have been studied through the lenses of both finding exact solutions and performing numerical analyses Lieb and Liniger (1964); Lieb and Liniger (1964); Lieb and Liniger (1965); Lieb and Liniger (1965); Lieb (1966); Lieb (1966). Thus, they provide good testbeds for which to compare both quantitative and qualitative ground state results to. ### Cold Bosons in a Harmonic Trap The first Hamiltonian which we consider describes spinless bosons in a harmonic trap. The interactions of the condensate are approximated by a contact potential. Using units where \(\hbar=1\), the Hamiltonian is \[\hat{H}=\sum_{i=1}^{N}\left(-\frac{1}{2m}\frac{\partial^{2}}{\partial x_{i}^{ 2}}+\frac{1}{2}m\omega^{2}x_{i}^{2}\right)+\sum_{i<j}^{N}g\delta(x_{i}-x_{j}) \tag{1}\] In general, we take \(m=\omega=1\). The interaction is repulsive when \(g>0\) and attractive when \(g<0\). When \(g>0\), the interaction strength \(g\) is proportional to the two-boson s-wave scattering length Lieb and Liniger (1964). Although the addition of the harmonic trap causes the system to no longer be analytically solvable Lieb and Liniger (1964) for the general case of many particles, the two-boson case has been solved exactly Lieb and Liniger (1964); Lieb and Liniger (1965). ### Trapped Bosons with Short and Long-Range Interactions Recently, another quantum system has been shown to be exactly solvable for a general case of \(N\) bosons Lieb and Liniger (1964). The model consists again of particles in harmonic confinement interacting with a delta-function potential of strength \(g\). Additionally, a long-range linear interaction potential of strength \(\sigma\) is added, which, in one dimension, corresponds to either Coulomb repulsion (\(\sigma<0\)) or gravitational attraction (\(\sigma>0\)). \[\begin{split}\hat{H}&=\sum_{i=1}^{N}\left(-\frac{1 }{2m}\frac{\partial^{2}}{\partial x_{i}^{2}}+\frac{1}{2}m\omega^{2}x_{i}^{2} \right)\\ &+\sum_{i<j}^{N}\left(g\delta(x_{i}-x_{j})+\sigma|x_{i}-x_{j}| \right)\end{split} \tag{2}\] Again, we take \(m=\omega=1\). The model was found to be integrable when \(\sigma=-m\omega g/2\)1. In that case, \(g>0\) corresponds to both interaction terms being repulsive and \(g<0\) corresponds to both terms being attractive. The coupling strength is again related to the one-dimensional s-wave scattering length \(a_{s}=-2/(mg)\). The exact expression for the ground state energy of the Hamiltonian (2) was found to be \[E_{0}=\frac{N\omega}{2}-mg^{2}\frac{N(N^{2}-1)}{24} \tag{3}\] with a corresponding (non-normalized) ground state wave function \[\psi_{0}(x_{1},...x_{N})=\prod_{i<j}e^{-|x_{i}-x_{j}|/a_{s}}\prod_{i}e^{-x_{i}^ {2}/(2a_{\rm ho}^{2})} \tag{4}\] where \(a_{\rm ho}=\sqrt{1/(m\omega)}\) denotes the harmonic oscillator length. When \(g>0\), the ground state wavefunction is maximized at \(|x_{i}-x_{j}|=Na_{\rm ho}^{2}/a_{s}\) and the bosons tend to spread out with equal spacing about the center of the harmonic trap. When a weak repulsion is turned on, the system forms an incompressible liquid of flat density [44; 45]. In the limit of strong repulsion \(g\gg 1\) the probability of overlap between any two particles drops to zero and the system forms a Wigner crystal [46]. In the other regime, when \(g<0\), the bosons collapse into the center of the trap. In the limit of \(g\rightarrow-\infty\), the ground state wavefunction of (2) becomes \[\psi_{0}(x_{1},...,x_{N})=\prod_{i<j}e^{-|x_{i}-x_{j}|/a_{s}} \tag{5}\] resembling a McGuire bound-state solution [39] describing a bright soliton [47]. It is surprising that despite the fact that different signs of the interaction strength \(g\) yield such different behaviors, the expression (3) for the ground state energy of the system implies that the ground state energy does not depend on the sign of \(g\). ## III Methods Given a Hamiltonian describing a quantum system of \(N\) indistinguishable bosons, we would like to solve the time independent Schrodinger equation for the ground state energy and wavefunction. To do this, we employ the variational principle; any arbitrary wavefunction \(\psi\) must have an expectation value of the energy at least as large as the ground state energy. \[\langle E\rangle_{0}\leq\langle E(\theta)\rangle=\frac{\int dX\:\psi^{\dagger }(X,\theta)\hat{H}\psi(X,\theta)}{\int dX\:\psi^{\dagger}(X,\theta)\psi(X, \theta)} \tag{6}\] Here \(X\) stands for the positions of the \(N\) bosons. Typically, one begins with an ansatz for the wavefunction \(\psi(X,\theta)\), where the \(\theta\) are its variational parameters and then minimize \(\langle E(\theta)\rangle\) with respect to \(\theta\) to obtain an estimate for the ground state of the quantum system. ### Neural Network Wavefunction Antsatze The quality of the estimate for the ground state energy and wavefunction depends both on the number of variational parameters one uses as well as the particular functional form of \(\psi\). Although one could successfully make well-posed guesses as to the correct functional form of the ground state wavefunction based on expectations on the underlying physics of the system, we would like to more systematically search the space of potential ground state wavefunctions. In this context, the application of neural networks is powerful. #### iii.1.1 Neural Networks We define a neural network with \(L\) layers as a function which takes \(n_{1}=N\) inputs and produces \(n_{L}=M\) outputs -- defined in the following way: \[\begin{split}& I_{i+1}=O_{i}=f(\mathbf{W}_{i}\vec{I}_{i}+\vec{b}_{ i}),\ 1\leq i\leq L-1\\ & O_{L}=\mathbf{W}_{L}\vec{I}_{L}+\vec{b}_{L}\end{split} \tag{7}\] The inputs \(I_{i}\) at layer \(i\) are multiplied by an \(n_{i+1}\times n_{i}\) matrix of weights \(\mathbf{W}_{i}\)2. A bias vector \(\vec{b}_{i}\) of length \(n_{i+1}\) is added before applying an activation function \(f\) to each resulting vector element. The output \(O_{i}\) of the \(i\)-th layer then becomes the input for the \((i+1)\)-th layer, where the same procedure is repeated with a different set of weights and biases. While in general, a different activation function can be used at each layer, we choose to keep the same function throughout. To ensure that the neural network produces an output whose range is over all reals, an activation function is _not_ used in the final output layer. Footnote 2: For clarity, \(n_{1}=N\) and \(n_{L}=M\); \(n_{i}\) is the number of nodes at layer \(i\). Neural networks are useful in the context of writing down a variational ansatz for the wavefunction because multilayer neural networks have been shown to be universal function approximators [25; 26]. The advantage is that, without needing to change the architecture of the neural network function, we can explore a general space of functions to find the ground state wavefunction by varying the parameters \(\theta=\{\mathbf{W}_{i},\vec{b}_{i}\}\). The efficiency of the functional expressivity for many-body wavefunctions, however, is not clear and is a property we seek to explore. We denote our ansatz neural network function as \(\mathcal{A}(I_{1},...,I_{N})\); it takes in \(N\) inputs and returns a single output (\(M=1\)). #### ii.1.2 Enforcing Ground State Symmetries A neural network ansatz for the ground state wavefunction of a system of \(N\) indistinguishable bosons should satisfy the following two constraints. Firstly, the wavefunction must obey Bose exchange symmetry. \[\psi(...,x_{i},...,x_{j},...)=\psi(...,x_{j},...,x_{i},...) \tag{8}\] where the \(x_{n}\) are the positions of the bosons. Thus we must construct our neural network such that it is fully symmetric under exchange of particle positions. To do this, we look for a bijection between the set of particle positions \(\{x_{i}\}\) and a set of functions of \(\{x_{i}\}\) which are symmetric under \(x_{i}\leftrightarrow x_{j}\). The simplest such bijection generates the set of elementary symmetric polynomials \[e_{i}=\sum_{1\leq j_{1}<j_{2}<...<j_{i}\leq N}x_{j_{1}}x_{j_{2}}...x_{j_{i}} \tag{9}\] For instance, for \(N=3\): \[\begin{split} e_{1}&=x_{1}+x_{2}+x_{3},\\ e_{2}&=x_{1}x_{2}+x_{1}x_{3}+x_{2}x_{3},\\ e_{3}&=x_{1}x_{2}x_{3}.\end{split} \tag{10}\] We can see this by noting that the \(e_{i}\) are the coefficients of a degree-\(N\) polynomial over an auxiliary variable \(t\) whose \(N\) roots are the positions \(x_{i}\) -- namely \[f(t)=(t-x_{1})(t-x_{2})...(t-x_{N}) \tag{11}\] For ease of implementation however, we note that the Newton-Girard identities define a further bijection between the set of \(\{e_{i}\}\) to the set of power-sums \[\xi_{i}=\sum_{k=1}^{N}\,x_{k}^{i} \tag{12}\] Since the set of \(\{\xi_{i}\}\) are also fully symmetric under exchange of \(x_{i}\), we can construct a Bose symmetric neural network function by feeding in the \(\{\xi_{i}\}\) as inputs (\(I_{i}=\xi_{i}\)). In practice, for large \(N\), \(|\xi_{i}|\) can easily become extremely large; thus, we normalize the initial particle positions by an approximate width \(w\) of the position-space ground state wavefunction 3 Footnote 3: For example, if the system were a harmonic oscillator with \(m=\omega=1\), we choose \(w\approx 2\) such that the majority of the nonzero region of the Gaussian ground state is contained within the selected width. \[\tilde{\xi}_{i}=\sum_{k=1}^{N}\left(\frac{x_{k}}{w}\right)^{i} \tag{13}\] such that the \(\tilde{\xi}_{i}\) are at most \(\mathcal{O}(1)\) throughout the search for the ground state wavefunction. \[\psi(x_{1},...,x_{N})\sim\mathcal{A}(\tilde{\xi}_{1},...,\tilde{\xi}_{N}) \tag{14}\] The \(\{\tilde{\xi}_{i}\}\) retains information about the original particle coordinates but loses information about their ordering, as desired. Secondly, the ground state wavefunction of a system of indistinguishable bosons can be taken to be real and positive. Thus, we constrain our neural network weights and biases to be real-valued. We can also, without loss of generality, write the wavefunction ansatz as \[\psi(x_{1},...,x_{N})=e^{-\mathcal{A}(\tilde{\xi}_{1},...,\tilde{\xi}_{N})} \cdot e^{-\Omega\sum_{i=1}^{N}\,x_{i}^{2}} \tag{15}\] Since we are looking for bound ground state solutions of the Hamiltonians models we consider, we want to search the space of wavefunctions which vanish at infinity. We multiply our neural network function by the Gaussian factor to ensure that this property is satisfied even when the neural network function itself may be relatively flat over its inputs for a given set of weights and biases. Because the bosons in the quantum systems we study are confined in a harmonic trap with \(m=\omega=1\), we choose \(\Omega=0.5\). The neural network function \(\mathcal{A}\), then, is purely responsible for capturing the complexities of particle interactions. At zero inter-particle interaction strength, \(\mathcal{A}\) should minimize trivially to zero everywhere in the ground state. ### Neural Network Architecture To search for the ground state energy and wavefunction of a quantum system, we first construct a neural network wavefunction ansatz of the form in (15). For the neural network, we choose to use the continuously-differentiable CELU as our activation function \(f\). \[\text{CELU}(x)=\begin{cases}x&x>0\\ e^{x}-1&x\leq 0\end{cases} \tag{16}\] Furthermore, we initialize the real-valued weights and biases of the neural network to be \(\mathcal{O}(1)\) and nonzero -- drawn randomly from a normal distribution centered around zero with standard deviation \(\sigma=1\). Using \(\langle E\rangle\) as a cost function, we perform gradient descent using the Adam optimizer [48] to approach the ground state. We use Adam step sizes of between \(10^{-3}\) and \(10^{-6}\), decreasing the step size as the minimization approaches closer to convergence. Using relatively large step sizes in certain regions of parameter space close to convergence can lead to being stuck in orbit cycles and exhibit oscillatory behavior in the cost function [49]. The other hyperparameters of the Adam optimizer describing the decay rates of the moments and ensuring numerical stability are kept at their default values: \(\beta_{1}=0.9,\beta_{2}=0.999,\epsilon=10^{-8}\). Because the integrals involved in obtaining \(\langle E\rangle\) and \(\langle\partial E/\partial\theta\rangle\) are difficult to compute exactly for a complicated neural network function and for many particles \(N\), we estimate the energy and the gradient using Metropolis importance sampling, drawing from the distribution \(\pi(X)\sim\psi(X,\theta)^{2}/\int dX\;\psi(X,\theta)^{2}\). However, the Hamiltonians which we study contain potential terms which involve delta functions in position. This creates a zero-overlap problem in the Monte Carlo evaluation of this integral in which none of the sampled position configurations induce a contribution to the energy or gradient from those delta function terms. We introduce a remedy in Appendix A. Although computing the gradient using Monte Carlo methods is not as precise as an analytic calculation, the stochasticity tends to aid in avoiding being stuck in local minima during the minimization [50; 51; 52]. In general, there has not been a systematic solution to choosing an optimal number of layers and nodes of a neural network for any given problem [53]. Here, we arbitrarily choose to construct our neural network function with between four to ten layers. Although a more careful analysis in choosing the number of layers has yet to be done, we decide to use more layers when solving quantum systems of more particles since we expect that more layers are needed to capture the ground state of a more complicated system. Keeping the same number of layers in solving a particular system, we systematically increase the number of nodes at each layer until we find that our prediction for the ground state energy ceases to decrease within error bars given by the finite Monte Carlo sampling. Fig. 1 shows convergence in \(\langle E(\beta)\rangle\) as we increase the total number of variational parameters (weights and biases) in the neural network. We find that an increasing number of parameters for systems of more particles is needed; however, this dependence appears to be slower than exponential in number of particles. Finally, to perform the neural network computations and gradient descent minimizations, we utilize Google's JAX [54] package in Python. JAX has built-in automatic differentiation, just-in-time compilation speed-up, and vectorization features which make it an appealing and convenient choice to run neural network computations with. ## IV Results To check that our variational neural network wavefunction ansatz (15) is universal enough to capture the ground state behaviors of many different quantum systems, we use our ansatz to compute the ground states in various phases of the Hamiltonian models described in Sec. II. We compare our results to the analytic solutions of the exactly solvable models. We then also explore an unsolved regime of one of these models. Figure 1: Shows the relative error of the ground state energies for the quantum system of \(N\) bosons described by the Hamiltonian in (2) as the number of neural network parameters \(\beta\) is increased. Eight layers were used in the neural network throughout. The statistical error bars from the Monte Carlo calculations on some points are too small to be seen. \(\langle E\rangle_{0}\) here is taken to be the value of the ground state energy computed with the largest \(\beta\). ### Cold Bosons in a Harmonic Trap Preliminarily, we first study a one-dimensional system of two indistinguishable bosons (\(N=2\)) in a harmonic trap, interacting via a contact potential (II.1). An exact expression for the ground state energy of the system was given by Busch et. al. [40]. Using our neural network ansatz, we compute the ground state energies of the system at various interaction strengths \(g\). Fig. 2 shows a comparison of the two results. As we increase the number of parameters \(\beta\) in the neural network ansatz, we find that, over the wide range of \(g\), the neural network ground state energies converge towards agreement with those of the analytic solution to within error bars. The mean values are also consistent with the exact expression to approximately one to two percent precision. Throughout the final calculations for this model, we fixed our neural network to have four layers and roughly \(5\cdot 10^{4}\) variational parameters. Although this likely uses more parameters than needed to describe the simpler two-boson system, the results give confidence that our Bose symmetric neural network ansatz, as desired, is able to capture the ground state physics of the different systems without needing to specify a particular functional form for the ansatz or adjusting the architecture of the neural network. ### Trapped Bosons with Short and Long-Range Interactions Next, we examine the model in which the bosons interact with a long-range linear potential along with the delta-function potential whose properties are summarized in Sec. II.2. We are able to use the neural network ansatz to study both the Figure 3: Shows ground state behaviors of two bosons interacting with short and long-range interactions described in II.2 in the exactly-solvable regime \(\sigma=-g/2\). We plot the position-space probability density; brighter colors indicate a larger value of \(\psi(x,y)^{2}\) and the bosons have a higher probability of being there. The blue lines which run through \(y=-x\) are shown to guide the eye. The top shows the system with a repulsive potential (\(g=1.5\)) while the bottom shows the system with an attractive potential (\(g=-1.0\)). Figure 2: Shows the ground state energies of the quantum system described in II.1. We plot the results computed from our neural network ansatz (red) against the exact results (black) given by Busch et. al. [40]. The statistical error bars from the Monte Carlo integration of the energy in most cases are too small to be seen. Convergence towards the exact result is seen as the number of parameters \(\beta\) in the neural network ansatz is increased. exactly-solvable regime of \(\sigma=-g/2\) solved by Beau et. al [7] as well as the regime \(\sigma=-g\) in which no analytic solution is known. #### iii.1.1 Exactly-solvable Regime (\(\sigma=-g/2\)) We again begin with a simpler system of just two particles. Using our neural network ansatz, we compute the ground state energies and wavefunctions for various values of the coupling in the exactly-solvable regime \(g=-\sigma/2\) and compare the results to the analytic solution. Fig. 3 displays the ground state wavefunction of the system while Fig. 4 shows a comparison of the ground state energies. We find that the ground states given by the neural network ansatz give the same behavior as described by the exact ground state wavefunction (4). When \(g>0\) and the interactions are both repulsive, the two bosons separate an equal distance apart from the center of the harmonic trap. Alternatively, when \(g<0\) and the interactions are both attractive, the bosons collapse towards the center of the trap and form a bright soliton. Quantitatively, the ground state energies computed using the variational method also agree with the analytic expression (3) to within two-percent statistical errors. The unintuitive quadratic dependence of the ground state energy on \(g\) is also confirmed. Having shown the ability of our neural network ansatz to accurately compute ground state wavefunctions and energies of smaller, simpler systems, we further demonstrate the versatility and generalizability of the neural network methodology by computing ground state properties of the quantum system in (2) with fifty indistinguishable bosons 4. We study both a repulsive system (\(g=0.05\)) and an attractive system (\(g=-0.03\)). Using a neural network ansatz with \(\beta\approx 2\cdot 10^{5}\), we find that the computed ground state energies fall within one percent of those predicted by Figure 5: Shows the ground state density functions for the system of fifty bosons with \(\sigma=-g/2\). The top panel displays the normalized local density while the bottom displays the normalized pair correlation. The points are heights of the position/distance binning and are linearly interpolated to guide the eye. The dark/light red show the density functions from the analytic/neural network wavefunction respectively in the attractive case while the dark/light blue show the density function sfrom the analytic/neural network wavefunction in the repulsive case. Figure 4: Shows a comparison of the ground state energies of the system (2) with two bosons at potential strengths \(\sigma=-g/2\). The black line shows the analytic expression for the ground state energy \(E_{0}\) from Beau et. al. (3) and the red points are ground state energies computed from the neural network ansatz. the exact \(E_{0}\) (3); the calculations yielded for \(g=0.05\), \(E_{0}^{\rm NN}=12.083(72)\) as compared with \(E_{0}=11.984375\) and for \(g=-0.03\), \(E_{0}^{\rm NN}=20.367(76)\) as compared with \(E_{0}=20.314375\). To comprehensively check of the ground state features of the system, we also calculate the local density profile \[n(x)=\int dx_{2}...dx_{N}\psi_{0}(x=x_{1},x_{2},...,x_{N})^{2} \tag{17}\] and the density-density correlation function \[g_{2}(y)=\int dx_{1}...dx_{N}\:\delta(y-|x_{1}-x_{2}|)\psi_{0}(x_{1},...,x_{N}) ^{2} \tag{18}\] for both the analytic \(\psi_{0}\) (4) and the ground state wavefunction given by the neural network ansatz \(\psi_{0}^{\rm NN}\)5. The density functions \(n(x)\) and \(g_{2}(y)\) are computed by generating histograms of positions \(x_{1}\) and distances \(x_{1}-x_{2}\) respectively -- both taken from Monte Carlo samples drawn from the distribution \(\pi(X)\sim\psi_{0}(X)^{2}/\int dX\psi_{0}(X)^{2}\). Fig. 5 shows the density functions from both \(\psi_{0}\) and \(\psi_{0}^{\rm NN}\) plotted on top of one another. We find close agreement between the two in both phases of the model (\(g>0\) and \(g<0\)). This gives evidence that the neural network ansatz is not only able to provide an accurate estimate for the ground state energy but can also faithfully encode information about the ground state wavefunction. Footnote 5: The choices \(x=x_{1}\) and \(\delta(y-|x_{1}-x_{2}|)\) in \(n(x)\) and \(g_{2}(y)\) respectively are arbitrary because \(\psi_{0}\) is Bose symmetric. #### iii.2.2 Non-integrable Regime (\(\sigma=-g\)) The variational approach using neural network ansatze is not restricted to computing integrable systems. We also apply the methodology to explore the system of bosons interacting with short and long-range interactions (2) with symmetric coupling strengths \(\sigma=-g\) for which no exact ground state has been found. We then compare our computed ground state properties to those of the exactly solvable system \(\sigma=-g/2\) (see [7]). The results show that although the ground state energies behave quantitatively very differently, the general phase structures of the two regimes are similar in nature. We begin by looking at a system of four bosons with a strong repulsive coupling \(g=-\sigma=2.5\) and another with an attractive coupling \(g=-\sigma=-1.0\). Fig. 6 shows the local density and the pair-correlation function for both four-boson systems. Just as with the exactly-solvable model, a crystal structure is clearly seen in the case of strong repulsion. The local density shows four distinct equally spaced peaks. The pair-correlation function shows that the probability of two particles being in the same position is close to zero. Instead, the correlation function is maximal at distinct separations corresponding to \(y=\pm|x_{1}-x_{2}|=nd,n\in\mathds{Z}\) where \(d\) is the inter-particle spacing between two nearest neighbors in the crystal. In the case of attraction on the other hand, both the density profile and the pair density peak strongly at \(y=0\); again, all of the particles clump towards the center of the harmonic trap and form a bright soliton [47]. We further use our neural network ansatz to search for the ground states of systems of ten and Figure 6: Shows the ground state density functions for the system of four bosons. The top panel displays the normalized local density while the bottom displays the normalized pair correlation. Each panel contains results for the attractive (blue) and the repulsive (red) systems. fifty particles at various coupling strengths \(g=-\sigma\). Fig. 7 shows the computed ground state energies as a function of \(g\) while Fig. 8 shows the single-particle and pair density profiles. We find that here, the energies exhibit the same asymptotic behavior of \(E_{0}\rightarrow-\infty\) as \(|g|\rightarrow\infty\) as in the exactly-solvable model. However, the ground state energy is no longer independent of the sign of \(g\) and changes asymmetrically as the interactions in the system flip from repulsion to attraction. When \(g>0\), the energy drops more rapidly than in the exactly-solvable case while when \(g<0\), the energy of the resulting soliton initially rises before dropping again at higher attractive coupling. The qualitative features, however, again match the behaviors of the system at \(\sigma=-g/2\). From the local density profile, we see that as we turn on a repulsive potential (\(g>0\)), the bosons begin to spread symmetrically about the center of the harmonic trap. As the repulsion becomes stronger, the particle density shows a mesa-like feature of finite width \(w\). This resembles, for example, the behavior of nuclei at saturation density. The addition of particles to the system does not change the density but instead increases the droplet size. The two-body correlation for many particles at weak repulsion increases monotonically from the maximal separation \(y=\pm w\) inwards towards \(y=0\) since more pairs of particles have smaller rather than larger separations. In the vicinity of zero separation, the probability of finding two particles in the same location is decreased and we expect a slight dip in the pair-correlation function. This is clearly seen in the system with ten particles where the repulsion was stronger; the dip is not seen in the fifty particle system because the weaker re Figure 8: Shows the ground state density functions for systems of ten and fifty bosons. In each panel, the (light) blue shows the (repulsive) attractive system for \(N=10\) and the (light) red shows the (repulsive) attractive system for \(N=50\). Figure 7: Shows a comparison of the ground state energies of the Hamiltonian (2) with N = 10 and 50 bosons. The red points are energies computed from the neural network ansatz at the non-integrable regime \(\sigma=-g\). The statistical error are too small to be seen. The black line shows the analytic expression for \(E_{0}\) when \(\sigma=-g/2\) for comparison. pulsion allows the bosons to retain a tendency of remaining close to one another. On the other hand, we again find that if we instead turn on an attractive interaction between the particles, the local density as well as the pair-correlation peak sharply at the center of the harmonic trap and zero separation respectively. This structure is again characteristic to that of a bright soliton. ## V Conclusions Neural networks and machine learning techniques provide powerful tools for the Variational Monte Carlo approach to solving many-body quantum systems. We used a neural network to parametrize a variational wavefunction ansatz for the ground state of systems of indistinguishable bosons in one dimension. Then using the ansatz, we were able to successfully numerically compute the ground state energies and wavefunctions of several quantum systems of various qualitative phases, ranging from two to fifty particles. The advantages of using a neural network ansatz include being able to search the most general space of possible ground state wavefunctions without needing to limit to specific functional forms. Neural networks also have convenient scalability; it is straightforward both to increase the number of variational parameters in the ansatz as well as increase the number of particles in the system. The application of such ansatze also does not need to be restricted to solvable systems and can be used to explore properties of non-integrable systems. Many important many-body systems, including condensates, atoms, and nuclei involve indistinguishable particles. Wavefunctions of such systems must satisfy Fermi or Bose exchange symmetry. We advocated and demonstrated that using symmetric functions of the original particle coordinates as inputs to the neural network aptly enforces Bose exchange symmetry in one dimension. The symmetric inputs are chosen to be bijective to the original set of coordinates and so we do not limit the generality of the wavefunction space spanned by the neural network. In addition, we propose a method to deal with delta-function interactions without the need to regularize them. The use of symmetric inputs to enforce exchange symmetries of the system can be generalized to use to study systems in a higher number of spatial dimensions in a straightforward way. To enforce Bose symmetry in three dimensions, one needs to find a bijection between the set of vector coordinates \(\{\vec{r}_{i}\},i=1,...,N\) and symmetric functions \(\{s_{j}(r_{1}^{x},r_{1}^{y},r_{1}^{z},...,r_{N}^{x},r_{N}^{y},r_{N}^{z})\},j= 1,...,M\) where \(M\) may be greater than \(3N\). The \(\{s_{j}\}\) must be symmetric in exchanges \(\vec{r}_{n}\leftrightarrow\vec{r}_{m}\) but not in exchanges of individual coordinate directions (i.e \(r_{n}^{x}\leftrightarrow r_{m}^{x}\)). Given the set of \(\{s_{j}\}\), one should be able to reconstruct the set of \(\{r_{i}^{x},r_{i}^{y},r_{i}^{z}\}\) including the fact that particular sets of three coordinates specify the position of individual particles. To write a Fermi anti-symmetric function in three dimensions, one theoretically simply needs to take a single Slater determinant of functions \(\phi_{i}(\vec{r}_{j};\{\vec{r}_{j}/\})\), where \(\phi_{i}\) is _Bose_ symmetric under exchange of any \(\vec{r}_{n}\rightarrow\vec{r}_{m},m,n\neq j\)[35]. Thus if one finds a bijection to a set of symmetric functions necessary for enforcing Bose symmetry in three dimensions, one can use the same bijection to enforce Fermi symmetry. Work to find such a mapping is being pursued. ###### Acknowledgements. We thank Andrei Alexandru and Scott Lawrence for helpful discussions and comments. This work was supported in part by the U.S. Department of Energy, Office of Nuclear Physics under Award Numbers DE-SC0021143, DE-FG02-93ER40762. ## Appendix A Importance Sampling for Delta-function Observables Consider the Lieb-Liniger Hamiltonian [1; 2] for a system of \(N\) indistinguishable bosons \[\hat{H}=\sum_{i=1}^{N}-\frac{1}{2}\frac{\partial^{2}}{\partial x_{i}^{2}}+ \sum_{i<j}^{N}\,g\delta(x_{i}-x_{j}) \tag{10}\] and a positive and real wavefunction \[\psi(X)=e^{-A(x_{1},...,x_{N})} \tag{11}\] We would like to compute the energy associated with the wavefunction. \[\langle E\rangle=\frac{\int dx_{1}..dx_{N}\,\psi\hat{H}\psi}{\int dx_{1}...dx _{N}\,\psi^{2}}=K+V \tag{12}\] where \[K=\frac{\int dx_{1}...dx_{N}\,e^{-2A(X)}\sum_{i}\,\frac{1}{2}\left(\frac{ \partial^{2}A}{\partial x_{i}^{2}}-\left(\frac{\partial A}{\partial x_{i}} \right)^{2}\right)}{\int dx_{1}...dx_{N}\,e^{-2A(X)}}\] \[V=\frac{\int dx_{1}...dx_{N}\,e^{-2A(X)}\sum_{i<j}g\delta(x_{i}-x_{j})}{\int dx _{1}...dx_{N}\,e^{-2A(X)}} \tag{13}\] The kinetic term \(K\) can be computed easily using importance sampling \[K=\left\langle\,\sum_{i=1}^{N}\,\frac{1}{2}\left(\frac{\partial^{2}A}{\partial x _{i}^{2}}-\left(\frac{\partial A}{\partial x_{i}}\right)^{2}\right)\,\right\rangle _{\psi^{2}} \tag{10}\] where \(\langle...\rangle_{\psi^{2}}\) denotes an average over samples drawn from the distribution \[\Pi_{\psi^{2}}(x_{1},...x_{N})=\frac{e^{-2A(X)}}{\int dx_{1}...dx_{N}\,e^{-2A( X)}} \tag{11}\] Using the same importance sampling technique to compute the potential term \(V\) leads to a zero-overlap problem as described in Sec. III.2. Instead we restructure the integral involved in \(V\) to become amenable to importance sampling using the following manipulations. We first explicitly integrate out the \(x_{2}\) coordinate using the delta functions. The choice of \(x_{2}\) is arbitrary due to the Bose exchange symmetry of the wavefunction. \[\begin{split} V&=g\frac{N(N-1)}{2}I\\ I&=\frac{\int dx_{1}dx_{3}...dx_{N}\,e^{-2A(\tilde{ X})}}{\int dx_{1}dx_{2}...dx_{N}\,e^{-2A(X)}}\end{split} \tag{12}\] where \(\tilde{X}\) denotes the set of positions where \(x_{2}\) is replaced by \(x_{1}\) (i.e \(\{x_{1},x_{1},x_{3},...,x_{N}\}\)). We use the Bose symmetry of the wavefunction to eliminate the sum over pairs of particles. Next, we rewrite the integral \(I\) as \[I=\frac{\int dx_{1}...dx_{N}\,\frac{\exp(-2A(\tilde{X}))}{\exp(-2A(X))} \mathcal{D}(x_{2})\exp(-2A(X))}{\int dx_{1}...dx_{N}\,\exp(-2A(X))} \tag{13}\] where \(\mathcal{D}(x_{2})\) is any function such that \[\int_{-\infty}^{\infty}dx_{2}\,\mathcal{D}(x_{2})=1 \tag{14}\] In practice, we choose a Gaussian form \[\mathcal{D}(x_{2})=\frac{1}{\alpha\sqrt{\pi}}e^{-x_{2}^{2}/\alpha^{2}} \tag{15}\] The parameter \(\alpha\), which is different for each different \(\psi\), is chosen arbitrarily such that \(\mathcal{D}(y_{*})\approx 10^{-5}\) where \(y_{*}\) is the maximum value of \(|x_{2}|\) over many position samples taken from \(\Pi_{\psi^{2}}(X)\). In this way, \(\mathcal{D}(x_{2})\) is neither too wide such that we emphasize unimportant regions of \(\psi^{2}\) not sampled by the Monte Carlo method nor too narrow such that we don't capture all of the important regions of \(\psi^{2}\). Now, we can also compute \(V\) by drawing samples from \(\Pi_{\psi^{2}}(X)\), just as we did for \(K\). \[V=g\frac{N(N-1)}{2}\Big{\langle}\,\frac{e^{-2A(x_{1},x_{1},x_{3},...,x_{N})}}{ e^{-2A(x_{1},x_{2},...,x_{N})}}\mathcal{D}(x_{2})\Big{\rangle}_{\psi^{2}} \tag{16}\] We note that this method of avoiding the zero-overlap problem occasionally produces large error estimates and fails to converge when \(e^{-2A(X)}\) is small for many different sampled \(X\). However, the method is still reliable because this is precisely the region of \(e^{-2A(X)}\) that is sampled the least by the Metropolis algorithm.
2308.08218
Expressivity of Spiking Neural Networks
The synergy between spiking neural networks and neuromorphic hardware holds promise for the development of energy-efficient AI applications. Inspired by this potential, we revisit the foundational aspects to study the capabilities of spiking neural networks where information is encoded in the firing time of neurons. Under the Spike Response Model as a mathematical model of a spiking neuron with a linear response function, we compare the expressive power of artificial and spiking neural networks, where we initially show that they realize piecewise linear mappings. In contrast to ReLU networks, we prove that spiking neural networks can realize both continuous and discontinuous functions. Moreover, we provide complexity bounds on the size of spiking neural networks to emulate multi-layer (ReLU) neural networks. Restricting to the continuous setting, we also establish complexity bounds in the reverse direction for one-layer spiking neural networks.
Manjot Singh, Adalbert Fono, Gitta Kutyniok
2023-08-16T08:45:53Z
http://arxiv.org/abs/2308.08218v2
# Expressivity of Spiking Neural Networks ###### Abstract This article studies the expressive power of spiking neural networks where information is encoded in the firing time of neurons. The implementation of spiking neural networks on neuromorphic hardware presents a promising choice for future energy-efficient AI applications. However, there exist very few results that compare the computational power of spiking neurons to arbitrary threshold circuits and sigmoidal neurons. Additionally, it has also been shown that a network of spiking neurons is capable of approximating any continuous function. By using the Spike Response Model as a mathematical model of a spiking neuron and assuming a linear response function, we prove that the mapping generated by a network of spiking neurons is continuous piecewise linear. We also show that a spiking neural network can emulate the output of any multi-layer (ReLU) neural network. Furthermore, we show that the maximum number of linear regions generated by a spiking neuron scales exponentially with respect to the input dimension, a characteristic that distinguishes it significantly from an artificial (ReLU) neuron. Our results further extend the understanding of the approximation properties of spiking neural networks and open up new avenues where spiking neural networks can be deployed instead of artificial neural networks without any performance loss. ## 1 Introduction The development and the implementation of learning algorithms [10] coupled with the advancement in computational power -- GPUs and highly parallelized hardware -- have contributed to the recent empirical success of (deep) artificial neural networks [1]. Deep neural networks, nowadays, are used in a wide range of numerous real-world applications such as image recognition [14], natural language processing [21], [3], [15], [16], drug discovery [17], and game intelligence [18]. The downside of training and inferring on large deep neural networks implemented on classical digital hardware is the consumption of an enormous amount of time and energy [15]. At the same time, rapid advancement in the field of neuromorphic computing allows for both analog and digital computation, energy efficient and highly parallelized computational operations, and faster inference [20], [22]. Neuromorphic computers are electronic devices consisting of (artificial) neurons and synapses that aim to mimic the structure and certain functionalities of the human brain [19]. Unlike traditional von Neumann computers, which consist of separate processing and memory units, neuromorphic computers utilize neurons and synapses for both processing and memory tasks. In practice, a neuromorphic computer is typically programmed by deploying a network of spiking neurons [20], i.e., programs are defined by the structure and parameters of the neural network rather than explicit instructions. The computational model of a spiking neuron models the neural activity in the brain much more realistically as compared to other computational models of a neuron, thus making them well-suited for creating brain-like behaviour in these computers. In this work, we adopt the shorthand notation "SNNs" for spiking neural networks and "ANNs" for other types of traditional artificial neural networks. In ANNs, both inputs and outputs are analog-valued. However, in SNNs, neurons transmit information to other neurons in the form of an _action-potential_ or a _spike_[10]. These spikes can be considered as point-like events in time, where incoming spikes received via a neuron's synapses trigger new spikes in the outgoing synapses. This asynchronous information transmission in SNNs stands in contrast to ANNs, where information is propagated synchronously through the network. Hence, a key difference between ANNs and SNNs lies in the significance of timing in the operation of SNNs. Moreover, the (typically analog) input information needs to be encoded in the form of spikes, necessitating a spike-based encoding scheme. Different variations of encoding schemes exist, but broadly speaking, the information processing mechanisms can be classified into rate coding and temporal coding [14]. Rate coding refers to the number of spikes in a given time period ("firing frequency") whereas, in temporal coding, one is interested in the precise timing of a spike [15]. The notion of firing rate adheres to earlier neurobiological experiments where it was observed that some neurons fire frequently in response to some external stimuli ([16], [10]). The latest experimental results from neurobiology indicate that the firing time of a neuron is essential in order for the system to respond faster to more complex sensory stimuli ([17], [18], [19]). The firing rate results in higher latency and is computationally expensive due to extra overhead related to temporal averaging. With the firing time, each spike carries a significant amount of information, thus the resulting signal can be quite sparse. While there is no accepted standard on the correct description of neural coding, in this work, we assume that the information is encoded in the firing time of a neuron. The event-driven nature and the sparse information propagation through relatively few spikes, provided for instance by the time-to-first-spike encoding [10], facilitate system efficiency in terms of reduced computational power and improved energy efficiency. Due to the sporadic nature of spikes, a significant portion of the network remains idle while only a small fraction actively engages in performing computations. This efficient resource utilization allows SNNs to process information effectively while minimizing energy consumption. It is intuitively clear that the described differences in the processing of the information between ANNs and SNNs should also lead to differences in the computations performed by these models. For ANNs, several groups have analyzed the expressive power of (deep) neural networks ([13], [15], [16], [17]), and in particular provided explanations for the superior performance of deep networks over shallow ones ([18], [13]). In the case of ANNs with ReLU activation function, the number of linear regions into which the input space is partitioned into by the ANN is another property that highlights the advantages of deep networks over shallow ones. Unlike shallow networks, deep networks divide the input space into exponentially more number of linear regions if there are no restrictions placed on the depth of the network ([12], [15]). This capability enables deep networks to express more complex functions. There exists further approaches to characterize the expressiveness of ANNs, e.g., the concept of VC-dimension in the context of classification problems ([1], [10], [11]). However, in this work, we consider the problem of expressiveness from the perspective of the approximating theory and by quantifying the number of the linear regions. At the same time, very few attempts have been made that aim to understand the computational power of SNNs. By employing suitable encoding mechanisms to encode information through spikes, it has been shown that spiking neurons can emulate Turing machines, arbitrary threshold circuits, and sigmoidal neurons ([15], [16]). Similarly, [15] shows that continuous functions can be approximated to arbitrary precision using SNNs. In [15], biologically relevant functions are depicted that can be computed by a single spiking neuron but require ANNs with a significantly larger number of neurons to achieve the same task. A common theme is that the model of the spiking neurons and the description of their dynamics varies, in particular, it is often chosen and adjusted with respect to a specific goal or task. For instance, in [14], the authors delve into the theoretical exploration of self-connection spike neural networks, analyzing their approximation capabilities and computational efficiency. [17] aims at generating highly performant SNNs for image classification. The method applied, known as FS-conversion, involves a modified version of the standard spiking neuron model and entails configuring spiking neurons to emit only a limited number of spikes, while considering the precise spike timing. Hence, the results may not generalize to SNNs established via a different, more general neuronal model. The primary challenge in advancing the domain of spiking networks has revolved around devising effective training methodologies. Optimizing spiking neural networks using gradient descent algorithm is hindered by discrete and non-differentiable nature of spike generation function. One way is to use approximate gradients to enable gradient descent optimization within such networks ([12], [13]). By using more elaborate schemes, ([3], [14]) are able to train networks using exact gradients. Due to the difficulty of effectively training SNNs from scratch, another line of research focuses on converting a trained ANN to an SNN performing the same task ([15], [16], [17], [18], [19], [18]). These works have primarily concentrated on the conversion of ANNs with ReLU activation function and effectively studied the algorithmic construction of SNNs approximating or even emulating given ANNs. In an attempt to follow up along the lines of previous works, in particular, the expressivity of SNNs [10], the linear region property of ANNs [13] as well as first strides in that direction in SNNs [12], and the conversion of ReLU-ANNs into SNNs with time-to-first-spike encoding [14], we aim to extend the theoretical understanding that characterizes the differences and similarities in the expressive power between a network of spiking and artificial neurons employing a piecewise-linear activation function, which is a popular choice in practical applications [1]. Specifically, we aim to determine if SNNs possess the same level of expressiveness as ANNs in their ability to approximate various function spaces and in terms of the number of linear regions they can generate. This study does not focus on the learning algorithms for SNNs; however, we wish to emphasize that through a comprehensive examination of the computational power of SNNs, we can assess the potential advantages and disadvantages of their implementation in practical applications, primarily from a theoretical perspective. By exploring their capabilities, we gain valuable insights into how SNNs can be effectively utilized in various real-world scenarios. ContributionsIn this paper, to analyze SNNs, we employ the noise-free version of the Spike Response Model (SRM) [1]. It describes the state of a neuron as a weighted sum of response and threshold functions. We assume a linear response function, where additionally each neuron spikes at most once to encode information through precise spike timing. This in turn simplifies the model and also makes the mathematical analysis more feasible for larger networks as compared to other neuronal models where the spike dynamics are described in the form of differential equations. In the future, we aim to expand our investigation to encompass multi-spike responses and refractoriness effects, thus, the selection of this model is appropriate and comprehensive. The main results are centered around the comparison of expressive power between SNNs and ANNs: * **Equivalence of Approximation:** We prove that a network of spiking neurons with a linear response function outputs a continuous piecewise linear mapping. Moreover, we construct a two-layer spiking neural network that emulates the ReLU non-linearity. As a result, we extend the construction to multi-layer neural networks and show that an SNN has the capacity to effectively reproduce the output of any deep (ReLU) neural network. Furthermore, we present explicit complexity bounds that are essential for constructing an SNN capable of realizing the output of an equivalent ANN. We also provide insights on the influence of the encoding scheme and the impact of different parameters on the above approximation results. * **Linear Regions:** We demonstrate that the maximum number of linear regions that a one-layer SNN generates scales exponentially with the input dimension. Thus, SNNs exhibit a completely different behaviour compared to ReLU-ANNs. ImpactDue to the theoretical nature of this work, the results provided in this paper deepen our understanding of the differences and similarities between the expressive power of ANNs and SNNs. In theory, our findings indicate that the low-power neuromorphic implementation of spiking neural networks is an energy-efficient alternative to the computation performed by (ReLU-)ANNs without loss of expressive power. It serves as a meaningful starting point for exploring potential advantages that SNNs might have over ANNs. It also enhances our understanding of performing computations where time plays a critical role. Having said that, SNNs can represent and process information with precise timing, making them well-suited for tasks involving time-dependent patterns and events. We anticipate that the advances in event-driven neuromorphic computing will have a tremendous impact, especially for edge-computing applications such as robotics, autonomous driving, and many more. This is accomplished while prioritizing energy efficiency -- a crucial factor in modern computing landscapes. Furthermore, one can also envision the possibility of interweaving ANNs and SNNs for obtaining maximum output in specific applications [14]. OutlineIn Section 2, we introduce necessary definitions, including the Spike Response Model and spiking neural networks. We present our main results in Section 3. In Section 4, we discuss related work and conclude in Section 5 by summarizing the limitations and implications of our results. The proofs of all the results are provided in the Appendix A. ## 2 Spiking neural networks In [13], Maass described the computation carried out by a spiking neuron in terms of firing time. We use a similar model of computation for our purposes. First, we list the basic components and assumptions needed for constructing spiking neural networks followed by a description of the computational model, which then yields a mathematically sound definition. In neuroscience literature, several mathematical models exist that describe the generation and propagation of action-potentials. Action-potentials or spikes are short electrical pulses that are the result of electrical and biochemical properties of a biological neuron [1]. The Hodgkin-Huxley model describes the neuronal dynamics in terms of four coupled differential equations and is the most realistic and accurate model in describing the neuronal dynamics ([12], [13]). This bio-chemical behaviour is modelled using electric circuits comprising of capacitors and resistors. Interested readers can refer to [13] for a comprehensive and detailed introduction to the dynamics of spiking neurons. To study the expressivity of SNNs, the main principles of a spiking neuron are condensed into a (simplified) mathematical model, where certain details about biophysics of a biological neuron are neglected. In this work, we consider the Spike Response Model (SRM) [1] as a formal model for a spiking neuron. It effectively captures the dynamics of the Hodgkin-Huxley model and is a generalized version of the leaky integrate and fire model [1]. The SRM leads to the following definition of an SNN [13]. **Definition 1**.: _A spiking neural network \(\Phi\) is a (simple) finite directed graph \((V,E)\) and consists of a finite set \(V\) of spiking neurons, a subset \(V_{\text{in}}\subset V\) of input neurons, a subset \(V_{\text{out}}\subset V\) of output neurons, and a set \(E\subset V\times V\) of synapses. Each synapse \((u,v)\in E\) is associated with_ * _a synaptic weight_ \(w_{uv}\geq 0\)_,_ * _a synaptic delay_ \(d_{uv}\geq 0\)_,_ * _and a response function_ \(\varepsilon_{uv}:\mathbb{R}^{+}\rightarrow\mathbb{R}\)_._ _Each neuron \(v\in V\setminus V_{\text{in}}\) is associated with_ * _a firing threshold_ \(\theta_{v}>0\)_,_ * _and a membrane potential_ \(P_{v}:\mathbb{R}\rightarrow\mathbb{R}\)_,_ _which is given by_ \[P_{v}(t)=\sum_{(u,v)\in E}\sum_{t_{u}^{f}\in F_{u}}w_{uv}\varepsilon_{uv}(t-t_{ u}^{f}), \tag{1}\] _where \(F_{u}=\{t_{u}^{f}:1\leq f\leq n\text{ for some }n\in\mathbb{N}\}\) denotes the set of firing times of a neuron \(u\), i.e., times \(t\) whenever \(P_{u}(t)\) reaches \(\theta_{u}\) from below._ In general, the membrane potential includes an additional term \(\Theta_{v}:\mathbb{R}^{+}\rightarrow\mathbb{R}^{+}\), (aka _threshold function_), that models the refractoriness effect. That is, if a neuron \(v\) emits a spike at time \(t_{v}^{f}\), \(v\) cannot fire again for some time immediately after \(t_{v}^{f}\), regardless of how large its potential might be. However, we additionally assume that the information is encoded in single spikes, i.e., each neuron fires just once. Thus, the refractoriness effect can be ignored and we can effectively model the contribution of \(\Theta_{v}\) by the constant \(\theta_{v}\) introduced in the definition. Moreover, the single spike condition simplifies (1) to \[P_{v}(t)=\sum_{(u,v)\in E}w_{uv}\varepsilon_{uv}(t-t_{u}),\quad\text{ where }t_{u}=\inf_{t\geq\min\limits_{(z,u)\in E}\{t_{u}+d_{zu}\}}P_{u}(t)\geq\theta_{u}. \tag{2}\] The _response function_\(\varepsilon_{uv}(t)\) models the membrane potential of a postsynaptic neuron \(v\) as a result of a spike from a presynaptic neuron \(u\)[1]. A biologically realistic approximation to the response function \(\varepsilon_{uv}\) is a delayed \(\alpha\) function [1], which in particular is non-linear and leads to intractable problems when analyzing the propagation of spikes through an SNN. Hence, following [13], we only require \(\varepsilon_{uv}\) to satisfy the following condition: \[\varepsilon_{uv}(t)=\begin{cases}0,&\text{if }t\notin[d_{uv},d_{uv}+\delta],\\ s\cdot(t-d_{uv}),&\text{if }t\in[d_{uv},d_{uv}+\delta],\end{cases} \tag{3}\] where \(s\in\{+1,-1\}\) and \(\delta>0\) is some constant assumed to be the length of a linear segment of the response function. The _synaptic delay_\(d_{uv}\) is the time required for a spike to travel from \(u\) to \(v\). The variable \(s\) refers to the fact that biological synapses are either _excitatory_ or _inhibitory_. An excitatory postsynaptic potential increases, whereas an inhibitory postsynaptic potential decreases the membrane potential of a postsynaptic neuron \(v\). Thus, inserting the condition (3) in (2) gives \[P_{v}(t)=\sum_{(u,v)\in E}\mathbf{1}_{0<t-t_{u}-d_{uv}\leq\delta}\cdot w_{uv} \cdot s\cdot(t-t_{u}-d_{uv}),\quad\text{where }t_{u}=\inf_{t\geq\min\limits_{(s,u)\in E}\{t_{s}+d_{uv} \}}P_{u}(t)\geq\theta_{u}. \tag{4}\] In the remainder, we set \(w_{uv}:=s\cdot w_{uv}\) and allow \(w_{uv}\) to take arbitrary values in \(\mathbb{R}\). ### Computation in terms of firing time Using (4) enables us to iteratively compute the firing time \(t_{v}\) of each neuron \(v\in V\setminus V_{\text{in}}\) if we know the firing time \(t_{u}\) of each neuron \(u\in V\) with \((u,v)\in E\) by solving for \(t\) in \[\inf_{t\geq\min\limits_{(u,v)\in E}\{t_{u}+d_{uv}\}}P_{v}(t)=\inf_{t\geq\min \limits_{(u,v)\in E}\{t_{u}+d_{uv}\}}\sum_{(u,v)\in E}\mathbf{1}_{0<t-t_{u}-d _{uv}\leq\delta}\cdot w_{uv}(t-t_{u}-d_{uv})=\theta_{v}. \tag{5}\] In particular, \(t_{v}\) satisfies \[\theta_{v}=\sum_{(u,v)\in E}\mathbf{1}_{0<t-t_{u}-d_{uv}\leq\delta}\cdot w_{uv }(t_{v}-t_{u}-d_{uv})=\sum_{(u,v)\in E(\mathbf{t}_{U})}w_{uv}(t_{v}-t_{u}-d_{uv }), \tag{6}\] where \(E(\mathbf{t}_{U}):=\{(u,v)\in E:d_{uv}+t_{u}<t_{v}\leq d_{uv}+t_{u}+\delta\}\) and \(\mathbf{t}_{U}:=(t_{u})_{(u,v)\in E}\) is a vector containing the given firing times of the presynaptic neurons. In other words, \(E(\mathbf{t}_{U})\) identifies the presynaptic neurons that actually have an effect on \(t_{v}\) based on \(\mathbf{t}_{U}\). For instance, if \(t_{w}>t_{v}\) for some synapse \((w,v)\in E\), then \(w\) certainly did not contribute to the firing of \(v\) since the spike from \(w\) arrived after \(v\) already fired so that \((w,v)\notin E(\mathbf{t}_{U})\). Finally, the firing time of \(t_{v}\) is then explicitly given by \[t_{v}=\frac{\theta_{v}}{\sum_{(u,v)\in E(\mathbf{t}_{U})}w_{uv}}+\frac{\sum_{( u,v)\in E(\mathbf{t}_{U})}w_{uv}(t_{u}+d_{uv})}{\sum_{(u,v)\in E(\mathbf{t}_{U})}w_{uv }}. \tag{7}\] The dynamic of a simple network in this model is depicted in Figure 1. **Remark 1**.: _Equation (7) shows that \(t_{v}\) is a weighted sum (up to a positive constant) of the firing times of neurons \(u\) with \((u,v)\in E(\mathbf{t}_{U})\). Flexibility in this model is provided through \(E(\mathbf{t}_{U})\). Depending on the firing time of the presynaptic neurons \(\mathbf{t}_{U}\) and the associated parameters (weights, delays, threshold), \(E(\mathbf{t}_{U})\) contains a set of different synapses so that the expression in (7) varies accordingly. We will further study this property in Section 3.4._ **Remark 2**.: _Subsequently, we will employ (7) to analyze and construct SNNs. In particular, we simply assume that the length \(\delta\) of the linear segment of the response function introduced in (3) is large enough so that (7) holds. Informally, a small linear segment requires incoming spikes to have a correspondingly small time delay to jointly affect the potential of a neuron. Otherwise, the impact of the earlier spikes on the potential may already have vanished before the subsequent spikes arrive. Consequently, incorporating \(\delta\) as an additional parameter in the SNN model leads to additional complexity since the same firing patterns may result in different outcomes. However, an in-depth analysis of this effect is left as future work._ The final model provides a highly simplified version of the dynamics observed in biological neural systems. Nevertheless, we attain a theoretical model that, in principle, can be directly implemented on neuromorphic hardware and moreover, enables us to analyze the computations that can be carried out by a network of spiking neurons. When the parameter \(\delta\) is arbitrarily large, then the simplified Spike Response Model, stemming from the linear response function and the constraint of single-spike dynamics, exhibits similarities to the integrate and fire model. Conversely, if \(\delta\) is arbitrarily small, it resembles leaky integrate and fire model. ### Input and output encoding By restricting our framework of SNNs to acyclic graphs, we can arrange the underlying graph in layers and equivalently represent SNNs by a sequence of their parameters. This is analogous to the common representation of feedforward ANNs via a sequence of matrix-vector tuples ([1], [2]). **Definition 2**.: _Let \(d,L\in\mathbb{N}\). A spiking neural network \(\Phi\) with input dimension \(d\) and \(L\) layers associated to the acyclic graph \((V,E)\) is a sequence of matrix-matrix-vector tuples_ \[\Phi=((W^{1},D^{1},\Theta^{1}),(W^{2},D^{2},\Theta^{2}),\dots,(W^{L},D^{L}, \Theta^{L}))\] _where \(N_{0}=d\) and \(N_{1},N_{2},\dots,N_{L}\in\mathbb{N}\), and where each \(W^{l}\) and each \(D^{l}\) is an \(N_{l-1}\times N_{l}\) matrix, and \(\Theta^{l}\in\mathbb{R}_{+}^{N_{l}}\). \(N_{0}\) is the input dimension and \(N_{L}\) is the output dimension of the network. The matrix entry in \(W^{l}_{uv}\) and \(D^{l}_{uv}\) represents the weight and delay value associated with the synapse \((u,v)\in E\), and the entry \(\Theta^{l}_{v}\) is the firing threshold associated with node \(v\). We call \(N(\Phi):=d+\sum_{j=1}^{L}N_{j}\) the number of neurons of the network \(\Phi\), and \(L(\Phi):=L\) denotes the number of layers of \(\Phi\)._ **Remark 3**.: _In an ANN, each layer performs some non-linear transformation on their inputs and then the information is propagated through the layers in a synchronized manner. However, in an SNN, information is transmitted through the network in the form of spikes. Spikes from neurons in layer \(l-1\) influence the membrane potential of neurons in layer \(l\) and ultimately trigger them to spike (according to the framework described in the previous paragraph). Hence, spikes are propagated through the network asynchronously since the firing times of the individual neurons vary._ The (typically analog) input information needs to be translated into the input firing times of the employed SNN, and similarly, the output firing times of the SNN need to be translated back to an Figure 1: (a) A single layer spiking network with one output neuron \(v\). Neuron \(v\) receives inputs from five input neurons \(u_{1},\dots,u_{5}\) that fire at times \(t_{u_{1}},\dots,t_{u_{5}}\) respectively. (b) The trajectory in black shows the evolution of the membrane potential \(P_{v}(t)\) of neuron \(v\) as a result of spikes from input neurons that arrive at times \(t_{u_{i}v}+d_{u_{i}v}\) (vertical arrows). Neurons \(u_{1}\) and \(u_{2}\) generate excitatory postsynaptic potentials with distinct strengths represented by \(w_{u_{i}v}\), while neurons \(u_{3}\) and \(u_{5}\) produce inhibitory postsynaptic potentials with varying strengths (dashed lines). Neuron \(v\) fires at time \(t_{v}\) once \(P_{v}(t_{v})=\theta\). The spike from neuron \(u_{4}\) does not influence the firing time of \(v\) since \(t_{v}<t_{u_{4}}+d_{u_{4}v}\). appropriate target domain. We will refer to this process as input encoding and output decoding. In general, the applied encoding scheme certainly depends on the specific task at hand. For tasks that involve modelling complex time patterns or a sequence of events with multiple spikes, sophisticated encoding schemes may be required. However, we can formulate some guiding principles for establishing the encoding scheme. The firing times of input and output neurons should encode analog information in a consistent way so that different networks can be concatenated in a well-defined manner. This enables us to construct suitable subnetworks and combine them appropriately to solve more complex tasks. Second, our focus in this work lies on exploring the intrinsic capabilities of SNNs, rather than the specifics of the encoding scheme. In the extreme case, the encoding scheme might directly contain the solution to a problem, underscoring the need for a sufficiently simple and broadly applicable encoding scheme to avoid this. The potential power and suitability of different encoding schemes is a topic that warrants separate investigation on its own. **Remark 4**.: _Based on these considerations and our setting, we fix an appropriate encoding scheme. However, we will point out occasionally the effect of adjusting the scheme in certain ways. Analog input information is encoded in the firing times of the input neurons of an SNN \(\Phi\) in the following manner: For any \(x\in[a,b]^{d}\), \(d\in\mathbb{N}\), \(a,b\in\mathbb{R}\), we set the firing times of the input neurons \(u_{1},\ldots,u_{d}\) of \(\Phi\) to \((t_{u_{1}},\ldots,t_{u_{d}})^{T}=T_{in}+x\), where \(T_{in}\in\mathbb{R}^{d}\) is some constant reference time, e.g., \(T_{in}=(a,\ldots,a)^{T}\). The bounded input domain ensures that an appropriate reference time can be fixed. The firing times of the non-input neurons of \(\Phi\) are then determined based on (7). Finally, the firing times of the output neurons \(v_{1},\ldots,v_{n}\) encode the target \(y\in\mathbb{R}^{n}\) via \((t_{v_{1}},\ldots,t_{v_{d}})^{T}=T_{out}+y\), where \(T_{out}\in\mathbb{R}^{n}\) is some constant reference time. For simplicity and with a slight abuse of notation, we will sometimes refer to \(T_{in},T_{out}\) as one-dimensional objects, i.e., \(T_{in},T_{out}\in\mathbb{R}\) which is justified as the corresponding vectors contain the same element in each dimension (see Figure 2). Additionally, note that the introduced encoding scheme translates analog information into input firing times in a continuous manner._ For the discussion ahead, we point out the difference between a network and the target function it realizes. A network is a structured set of weights, delays and thresholds as defined in Definition 2, and the target function it realizes is the result of the asynchronous propagation of spikes through the network. **Definition 3**.: _On \([a,b]^{d}\) with \(a,b\in\mathbb{R}\), the realization of an SNN \(\Phi\) with input reference time \(T_{in}\in\mathbb{R}\) and \(N_{L}\in\mathbb{N}\) output neurons \(v_{1},\ldots,v_{N_{L}}\) is defined as the map \(\mathcal{R}_{\Phi}:\mathbb{R}^{d}\rightarrow\mathbb{R}^{N_{L}}\) such that_ \[\mathcal{R}_{\Phi}(x)=(-T_{out}+t_{v_{1}},\ldots,-T_{out}+t_{v_{N_{L}}})^{T},\] _where the firing times of the output neuron provide the realization \(\mathcal{R}_{\Phi}(x)\) of \(\Phi\) in temporal coding, i.e., \(v_{1},\ldots,v_{N_{L}}\) fire at time \((T_{out},\ldots,T_{out})^{T}+\mathcal{R}_{\Phi}(x)\) for some fixed output reference time \(T_{out}>T_{in}\)._ Next, we give a corresponding definition of an ANN and its realization. Figure 2: Computation graph associated with a spiking neural network \(\Phi\) with input-output dimension \(d\), width \(d\) and \(L-1\) hidden layers. The synapses in between the layers are labelled with synaptic weight matrices \(W\) and delay matrices \(D\). Each node in the network \(\Phi\) is associated with a threshold parameter \(\theta\). Analog input and output values are encoded in the firing time \(t_{u_{i}}=T_{\text{in}}+x_{i}\) (respectively \(t_{v_{i}}=T_{\text{out}}+y_{i}\)) of a neuron. **Definition 4**.: _Let \(d,L\in\mathbb{N}\). An artificial neural network \(\Psi\) consisting of \(d\) input neurons and \(L\) layers is a sequence of matrix-vector tuples_ \[\Psi=((W^{1},B^{1}),(W^{2},B^{2}),\ldots,(W^{L},B^{L}))\] _where \(N_{0}=d\) and \(N_{1},\ldots,N_{L}\in\mathbb{N}\), and where each \(W^{l}\) is an \(N_{l-1}\times N_{l}\) matrix, and \(B^{l}\in\mathbb{R}^{N_{l}}\). \(N_{0}\) is the input dimension and \(N_{L}\) is the output dimension of the network. We call \(N(\Psi):=\sum_{j=0}^{L}N_{j}\) the number of neurons of the network \(\Psi\), \(L(\Psi):=L\) the number of layers of \(\Psi\) and \(N_{l}\) the width of \(\Psi\) in layer \(l\). The realization of \(\Psi\) is defined as the map \(\mathcal{R}_{\Psi}:\mathbb{R}^{N_{0}}\rightarrow\mathbb{R}^{N_{L}}\),_ \[\mathcal{R}_{\Psi}(x)=y_{L},\] _where \(y_{L}\) results from_ \[y_{0} =x,\] \[y_{l} =\sigma(W^{l}y_{l-1}+B^{l}),\text{ for }l=1,\ldots,L-1,\] \[y_{L} =W^{L}y_{L-1}+B^{L}, \tag{8}\] _where \(\sigma:\mathbb{R}\rightarrow\mathbb{R}\) is acting component-wise and is called the activation function._ **Remark 5**.: _From now on, we will always employ ReLU, i.e., \(\sigma(x)=\max(0,x)\) as the activation function of an ANN. Finally, we assume that the realization is defined on some bounded domain \([a,b]^{d}\subset\mathbb{R}^{d}\)._ One can perform basic actions on neural networks such as concatenation and parallelization to construct larger networks from existing ones. Adapting a general approach for ANNs as defined in ([11], [2]), we formally introduce the concatenation and parallelization of networks of spiking neurons in the Appendix A.1. ## 3 Main results In the first part, we prove that SNNs generate **C**ontinuous **P**iecewise **L**inear (CPWL) mappings, followed by realizing a ReLU activation function using a two-layer SNN. Subsequently, we provide a general result that shows that SNNs can emulate the realization of any multi-layer ANN employing ReLU as an activation function. Lastly, we analyze the number of linear regions generated by SNNs and compare the arising pattern to the well-studied case of ReLU-ANNs. If not stated otherwise, the encoding scheme introduced in Remark 4 is applied and the results need to be understood with respect to this specific encoding. ### Spiking neural networks realize continuous piecewise linear mapping A broad class of ANNs based on a wide range of activation functions such as ReLU generate CPWL mappings [10], [12]. In other words, these ANNs partition the input domain into regions, the so-called linear regions, on which an affine function represents the neural network's realization. We show that SNNs also express CPWL mappings under very general conditions. The proof of the statement can be found in the Appendix A.2. **Theorem 1**.: _Any SNN \(\Phi\) realizes a CPWL function provided that the sum of synaptic weights of each neuron is positive and the encoding scheme is a CPWL function._ **Remark 6**.: _Note that the encoding scheme introduced in Remark 4 is a CPWL mapping (in input as well as output encoding)._ **Remark 7**.: _The positivity of the sum of weights ensures that each neuron in the network emits a spike. In general, if this condition is not met by a neuron, then it does not fire for certain inputs. Therefore, the case may arise where an output neuron does not fire and the realization of the network is not well-defined. Via the given condition we prevent this behaviour. For a given SNN with an arbitrary but fixed input domain it is a sufficient but not necessary condition to guarantee that spikes are emitted by the the output neurons. Instead, one could also adapt the definition of the realization of an SNN, however, the CPWL property described in the theorem may be lost._ Despite the fact that ReLU is a very basic CPWL function, it is not straightforward to realize ReLU via SNNs; see Appendix A.3 for the proof. **Theorem 2**.: _Let \(a<0<b\). There does not exist a one-layer SNN that realizes \(\sigma(x)=\max(0,x)\) on \([a,b]\). However, \(\sigma\) can be realized by a two-layer SNN on \([a,b]\)._ **Remark 8**.: _We note that the encoding scheme that converts the analog values into the time domain plays a crucial role. In the proof of the Theorem 2, an SNN is constructed that realizes \(\sigma\) via the encoding scheme \(T_{\text{in}}+\cdot\) and \(T_{\text{out}}+\cdot\). At the same time, the encoding scheme \(T_{\text{in}}-\cdot\) and \(T_{\text{out}}-\cdot\) fails in the two-layer case. Moreover, utilizing an inconsistent input and output encoding enables us to construct a one-layer SNN that realizes \(\sigma\). This shows that not only the network but also the applied encoding scheme is highly relevant. For details, we refer to Appendix A.3._ **Remark 9**.: _Note that in a hypothetical real-world implementation, which certainly includes some noise, the constructed SNN that realizes ReLU is not necessarily robust with respect to input perturbation. Analyzing the behaviour and providing error estimations is an important future task._ ### Expressing ReLU-network realizations by spiking neural networks In this subsection, we extend the realization of a ReLU neuron to the entire network, i.e., realize the output of any ReLU network using SNNs. The proof of the following statement can be found in the Appendix A.4. **Theorem 3**.: _Let \(L,d\in\mathbb{N}\), \([a,b]^{d}\subset\mathbb{R}^{d}\) and let \(\Psi\) be an arbitrary ANN of depth \(L\) and fixed width \(d\) employing a ReLU non-linearity, and having one-dimensional output. Then, there exists an SNN \(\Phi\) with \(N(\Phi)=N(\Psi)+L(2d+3)-(2d+2)\) and \(L(\Phi)=3L-2\) that realizes \(\mathcal{R}_{\Psi}\) on \([a,b]^{d}\)._ Sketch of proof.: Any multi-layer ANN with ReLU activation is simply an alternating composition of affine-linear functions and a non-linear function represented by ReLU. To realize the mapping generated by some arbitrary ANN, it suffices to realize the composition of affine-linear functions and the ReLU non-linearity and then extend the construction to the whole network using concatenation and parallelization operations. **Remark 10**.: _The aforementioned result can be generalized to ANNs with varying widths that employ any type of piecewise linear activation function._ **Remark 11**.: _In this work, the complexity of neural networks is assessed in terms of the number of computational units and layers. However, the complexity of an SNN can be captured in different ways as well. For instance, the total number of spikes emitted in an SNN is related to its energy consumption (since emitting spikes consumes energy). Hence, the minimum number of spikes to realize a given function class may be a reasonable complexity measure for an SNN (with regard to energy efficiency). Further research in this direction is necessary to evaluate the complexity of SNNs via different measures with their benefits and drawbacks._ ### Equivalence of approximation It is well known that ReLU-ANNs not only realize CPWL mappings but that every CPWL function in \(\mathbb{R}^{d}\) can be represented by ReLU-ANNs if there are no restrictions placed on the number of parameters or the depth of the network [1], [3]. Therefore, ReLU-ANNs can represent any SNN with a CPWL encoding scheme. On the other hand, our results also imply that SNNs can represent every ReLU-ANN and thereby every CPWL function in \(\mathbb{R}^{d}\). The key difference in the realization of arbitrary CPWL mappings is the necessary size and complexity of the respective ANN and SNN. Recall that realizing the ReLU activation via SNNs required more computational units than the corresponding ANN (see Theorem 3). Conversely, we demonstrate using a toy example that SNNs can realize certain CPWL functions with fewer number of computational units and layers compared to ReLU-based ANNs. **Example 1**.: _For \(\theta>0\), \([a,b]\subset\mathbb{R}\), consider the CPWL function \(f:[a,b]\rightarrow\mathbb{R}\) given by_ \[f(x)=\begin{cases}x,&x\leq-\theta\\ \frac{x-\theta}{2},&-\theta<x<\theta\\ 0,&x\geq\theta\end{cases}=-\frac{1}{2}\sigma(-x-\theta)-\frac{1}{2}\sigma(-x+ \theta), \tag{9}\] _where \(\sigma\) is the ReLU activation. A one-layer SNN with one output unit and two input units can realize \(f\). However, to realize \(f\), any ReLU-ANN requires at least two layers and four computational units; see Appendix A.5 for the proof._ These observations illustrate that the computational structure of SNNs differs significantly from that of ReLU-ANNs. While neither model is clearly beneficial in terms of network complexity to express all CPWL functions, each model has distinct advantages and disadvantages. To gain a better understanding of this divergent behaviour, in the next section, we study the number of linear regions that SNNs generate. ### Number of linear regions The number of linear regions can be seen as a measure for the flexibility and expressivity of the corresponding CPWL function. Similarly, we can measure the expressivity of an ANN by the number of linear regions of its realization. The connection of the depth, width, and activation function of a neural network to the maximum number of its linear regions is well-established, e.g., with increasing depth the number of linear regions can grow exponentially in the number of parameters of an ANN ([14], [1], [1]). This property offers one possible explanation for why deep networks tend to outperform shallow networks in expressing complex functions. Can we observe a similar behaviour for SNNs? To that end, we first analyze the properties of a spiking neuron. For the proof, we refer to Appendix A.2. **Theorem 4**.: _Let \(\Phi\) be a one-layer SNN with a single output neuron \(v\) and \(d\) input neurons \(u_{1},\ldots,u_{d}\) such that \(\sum_{i=1}^{d}w_{u_{i}v}>0\). Then \(\Phi\) partitions the input domain into at most \(2^{d}-1\) linear regions. In particular, for a sufficiently large input domain, the maximal number of linear regions is attained if and only if all synaptic weights are positive._ **Remark 12**.: _By examining the parameters of \(\Phi\), one can assess the number of linear regions into which the input domain is divided by \(\Phi\). For instance, if a single input neuron \(u_{j}\) causes the firing of \(v\), then the corresponding synaptic weight \(w_{u_{j}v}\) is necessarily positive. Thus, if \(w_{u_{j}v}\leq 0\), then \(u_{j}\) could not have caused the firing of \(v\) and \(\Phi\) can under no circumstances achieve the maximal number of linear regions. Similarly, one can derive via (7) that any subset of input neurons {\(u_{j_{1}},\ldots,u_{j_{k}}\)} with \(\sum_{i}w_{u_{j_{i}}v}\leq 0\) did not cause a firing of \(v\). The condition \(\sum_{i=1}^{d}w_{u_{i}v}>0\) simply ensures that the notion of linear region is applicable. Otherwise, the input domain is still partitioned into polytopes by the SNN but there exists a region where the realization of the network is not well-defined (see Remark 7). Finally, to ensure that the linear region corresponding to a subset of input neurons with a positive sum of weights is actually realized, the input domain simply needs to be chosen suitably large._ **Remark 13**.: _One-layer ReLU-ANNs and one-layer SNNs with one output neuron both partition the input domain into linear regions. Nevertheless, the differences are noteworthy. A one-layer ReLU-ANN will partition the input domain into at most two linear regions, independent of the dimension of the input. In contrast, for a one-layer SNN the maximum number of linear regions scales exponentially in the input dimension. One may argue that the distinct behaviour arises due to the fact that the 'non-linearity' in the SNN is directly applied on the input, whereas the non-linearity in the ANN is applied on the single output neuron. By shifting the non-linearity and applying it instead on the input, the ANN would exhibit the same exponential scaling of the linear regions as the SNN. However, this change would not reflect the intrinsic capabilities of the ANN since it has rather detrimental effect on the expressivity and, in particular, the partitioning of the input domain is fixed and independent of the parameters of the ANN. In contrast, for SNNs one can also explicitly compute the boundaries of the linear regions. This is exemplarily demonstrated for a two-dimensional input space in Appendix A.2. It turns out that only specific hyperplanes are eligible as boundaries of the linear region in this simple scenario. Hence, the flexibility of the SNN model to generate arbitrary linear regions is to a certain extent limited, albeit not entirely restricted as in the adjusted ANN._ Although we established interesting differences in the structure of computations between SNNs and ANNs, many questions remain open. In particular, the effect of depth in SNNs needs further consideration. The full power of ANN comes into play with large numbers of layers. Our result in Theorem 4 suggests that a shallow SNN can be as expressive as a deep ReLU network in terms of the number of linear regions required to express certain types of CPWL functions. In ([15]; Lemma 3), the authors showed that a deep neural network employing any piecewise linear activation function cannot span all CPWL functions with the number of linear regions scaling exponentially in the number of parameters of the network. Studying these types of functions and identifying (or excluding) similar behaviour for SNNs requires a deeper analysis of the capabilities of SNNs, providing valuable insights into their computational power. This aspect is left for future investigation. Related work The inherently complex dynamics of spiking neurons complicate the analysis of computations carried out by an SNN. In this section, we mention the most relevant results that investigate their computational or expressive power. One of the central results in this direction is the Universal Approximation Theorem for SNNs [14]. The author showed the existence of SNNs that approximates arbitrary feedforward ANNs employing sigmoidal activation function and thus, approximating any continuous function. The result is based on temporal coding by single spikes and under the presence of some additional assumptions on the response and threshold functions. In contrast, we show that an SNN can realize the output of an arbitrary ANN with CPWL activation and further specify the size of the network to achieve the associated realization, which has not been previously demonstrated. Moreover, we also study the expressivity of SNNs in terms of the number of linear regions and provide new insights on realizations generated by SNNs. [13] shows that continuous functions can be approximated to arbitrary precision using SNNs in temporal coding. In another direction, the author in [14] constructed SNNs that simulate arbitrary threshold circuits, Turing machines and a certain type of random access machines with real-valued inputs. In [15], the authors delve into the theoretical exploration of self-connection spike neural networks (scSNNs), analyzing their approximation capabilities and computational efficiency. The theoretical findings demonstrate that scSNNs, when equipped with self-connections, can effectively approximate discrete dynamical systems with a polynomial number of parameters and within polynomial time complexities. Our approach centers on precise spike timing, while theirs hinges on firing rates and includes a distinct model featuring self-connections, further setting their approach apart from ours. The study by [10] presents convergence theory that rigorously establishes the convergence of firing rates to solutions corresponding to LASSO problems in the Locally Competitive Algorithms framework. Another line of research focuses on converting (trained) ANNs, in particular with ReLU activation, into equivalent SNNs and, thereby avoiding or facilitating the training process of SNNs. This has been studied for various encoding schemes, spike patterns and spiking neuron models ([17], [18], [19], [20], [15], [21], [22], [23]). By introducing a general algorithmic conversion from ANNs to SNNs, one also establishes approximation and/or emulation capabilities of SNNs in the considered setting. Most related to our analysis of the expressivity of SNNs are the results in [12]. The authors define a one-to-one neuron mapping that converts a trained ReLU neural network to a corresponding SNN consisting of integrate and fire neurons by a non-linear transformation of parameters. This is done under the assumption of having access to a trained ReLU network, weights and biases of the trained model and the input data on which the model was trained. We point out that the underlying idea of representing information in terms of spike time and apply choosing the parameters of an SNN model such that the output is encoded in the firing time is similar to ours. However, significant distinctions exist between our approach and theirs, particularly in terms of the chosen model, objectives, and methodology. Our choice of the model is driven by our intention to better understand expressivity outcomes. In terms of methodology, we introduce an auxiliary neuron to ensure the firing of neurons even when a corresponding ReLU neuron exhibits zero activity. This diverges from their approach, which employs external current and a special parameter to achieve similar outcomes. Moreover, our work involves a fixed threshold for neuron firing, whereas their model incorporates a threshold that varies with time. Lastly, we study the differences in expressivity and structure of computations between ANNs and SNNs, whereas in [12], only the general conversion of ANNs to SNNs is examined and not vice versa. Finally, we would like to mention that a connection between SNNs and piecewise linear functions was already noted in [16]. The author shows that a spiking network consisting of non-leaky integrate and fire neurons, employing exponentially decaying synaptic current kernels and temporal coding, exhibits a piecewise linear input-output relation after a transformation of the time variable. This piecewise relation is continuous unless small perturbations influences the spiking behaviour, specifically concerning whether the neuron fires or remains inactive. ## 5 Discussion The central aim of this paper is to study and compare the expressive power of SNNs and ANNs employing any piecewise linear activation function. In an ANN, information is propagated across the network in a synchronized manner. In contrast, in SNNs, spikes are only emitted once a subset of neurons in the previous layer triggers a spike in a neuron in the subsequent layer. Hence, the imperative role of time in biological neural systems accounts for differences in computation between SNNs and ANNs. We show that a one-layer SNN with one output neuron can partition the input domain into an exponential number of linear regions with respect to the input dimension. The exact number of linear regions depends on the parameters of the network. Our expressivity result in Theorem 3 implies that SNNs can essentially approximate any function with the same accuracy and (asymptotic) complexity bounds as (deep) ANNs employing a piecewise linear activation function, given the response function satisfies some basic assumptions. Rather than approximating some function space by emulating a known construction for ReLU networks, one could also achieve optimal approximations by leveraging the intrinsic capabilities of SNNs instead. The findings in Theorem 4 indicate that the latter approach may indeed be beneficial in terms of the complexity of the architecture in certain circumstances. However, we point out that finding optimal architectures for approximating different classes of functions is not the focal point of our work. The significance of our results lies in investigating theoretically the approximation and expressivity capabilities of SNNs, highlighting their potential as an alternative computational model for complex tasks. The insights obtained from this work can further aid in designing architectures that can be implemented on neuromorphic hardware for energy-efficient applications. Extending the model of a spiking neuron by incorporating, e.g., multiple spikes of a neuron, may yield improvements on our results. However, by increasing the complexity of the model the analysis also tends to be more elaborate. In the aforementioned case of multiple spikes the threshold function becomes important so that additional complexity when approximating some target function is introduced since one would have to consider the coupled effect of response and threshold functions. Similarly, the choice of the response function and the frequency of neuron firings will surely influence the approximation results and we leave this for future work. LimitationsIn theory, we prove that SNNs are as expressive as ReLU-ANNs. However, achieving similar results in practice heavily relies on the effectiveness of the training algorithms employed. The implementation of efficient learning algorithms with weights, delays and thresholds as programmable parameters is left for future work. However, there already exists training algorithms such as the SpikeProp algorithm [1], [22], which consider the same programmable parameters as our model and may be a reasonable starting point for future implementations. In this work, our choice of model resides on theoretical considerations and not on practical considerations regarding implementation. However, there might be other models of spiking neurons that are more apt for implementation purposes -- see e.g. [23] and [24]. Furthermore, in reality, due to the ubiquitous sources of noise in the spiking neurons, the firing activity of a neuron is not deterministic. For mathematical simplicity, we perform our analysis in a noise-free case. Generalizing to the case of noisy spiking neurons is important (for instance with respect to the aforementioned implementation in noisy environments) and may lead to further insights in the model. M. Singh is supported by the DAAD programme Konrad Zuse Schools of Excellence in Artificial Intelligence, sponsored by the Federal Ministry of Education and Research. M. Singh also acknowledges support from the Munich Center for Machine Learning (MCML). G. Kutyniok acknowledges support from LMUexcellent, funded by the Federal Ministry of Education and Research (BMBF) and the Free State of Bavaria under the Excellence Strategy of the Federal Government and the Lander as well as by the Hightech Agenda Bavaria. Further, G. Kutyniok was supported in part by the DAAD programme Konrad Zuse Schools of Excellence in Artificial Intelligence, sponsored by the Federal Ministry of Education and Research. G. Kutyniok also acknowledges support from the Munich Center for Machine Learning (MCML) as well as the German Research Foundation under Grants DFG-SPP-2298, KU 1446/31-1 and KU 1446/32-1 and under Grant DFG-SFB/TR 109, Project C09 and the German Federal Ministry of Education and Research (BMBF) under Grant MaGriDo.
2310.11265
Image Compression using only Attention based Neural Networks
In recent research, Learned Image Compression has gained prominence for its capacity to outperform traditional handcrafted pipelines, especially at low bit-rates. While existing methods incorporate convolutional priors with occasional attention blocks to address long-range dependencies, recent advances in computer vision advocate for a transformative shift towards fully transformer-based architectures grounded in the attention mechanism. This paper investigates the feasibility of image compression exclusively using attention layers within our novel model, QPressFormer. We introduce the concept of learned image queries to aggregate patch information via cross-attention, followed by quantization and coding techniques. Through extensive evaluations, our work demonstrates competitive performance achieved by convolution-free architectures across the popular Kodak, DIV2K, and CLIC datasets.
Natacha Luka, Romain Negrel, David Picard
2023-10-17T13:38:38Z
http://arxiv.org/abs/2310.11265v1
# Image Compression using only Attention based Neural Networks ###### Abstract In recent research, Learned Image Compression has gained prominence for its capacity to outperform traditional handcrafted pipelines, especially at low bit-rates. While existing methods incorporate convolutional priors with occasional attention blocks to address long-range dependencies, recent advances in computer vision advocate for a transformative shift towards fully transformer-based architectures grounded in the attention mechanism. This paper investigates the feasibility of image compression exclusively using attention layers within our novel model, _QPressFormer_. We introduce the concept of learned _image queries_ to aggregate patch information via cross-attention, followed by quantization and coding techniques. Through extensive evaluations, our work demonstrates competitive performance achieved by convolution-free architectures across the popular Kodak, DIV2K, and CLIC datasets. _Keywords --_ Learned Image Compression, Vision Transformers, Visual Attention ## 1 Introduction Image compression stands as a pivotal research domain, driven by the ubiquity of images in today's digital landscape. The persistent pursuit of higher image quality, while simultaneously optimizing bit size for storage and transmission, underscores its paramount importance. For many years, image compression codecs were meticulously handcrafted, yielding iconic solutions like the widely-used JPEG algorithm. In the post-JPEG era, a lineage of handcrafted codecs emerged, including JPEG2000 [2], BPG format [3] (leveraging the HEVC video compression standard [4]), and Google's WebP [5]. Nevertheless, recent years have witnessed a transformative shift towards learned image compression, propelled by deep learning approaches. In the contemporary landscape, these learned codecs have not only achieved parity with their handcrafted counterparts but have also demonstrated the potential to surpass them. In both hand-designed and learned image compression paradigms, common components are shared within the encoding and decoding processes. During encoding, an analysis transform maps the image from its pixel space representation to a more compression-friendly domain, followed by quantization, a pivotal step in lossy codecs. Subsequently, a lossless coding scheme translates the image data into a compact bitstream. In the decoding phase, inverse operations unfold: the received bits are decoded, followed by synthesis through a suitable transform, ultimately restoring the image to its pixel space. A distinctive advantage inherent in learned compression methods arises from their holistic optimization approach. In this paradigm, all constituent blocks are collectively learned and end-to-end optimized. This optimization strategy diligently works to minimize distortion while concurrently minimizing bit-rate consumption. Conversely, traditional hand-designed methods require the separate optimization of individual blocks, which may not inherently synergize when used together. Furthermore, hand-designed approaches involve human-centric decisions in selecting the transform, introducing inherent bias. In stark contrast, learned methods offer greater flexibility, as the network autonomously adapts both the analysis and synthesis transforms, determining the optimal compromise between rate and quality within specified constraints. In learned image compression, numerous approaches have emerged for the analysis stage. Remarkably, transformer-based architectures, introduced by Vaswani et al. [6], have remained relatively unexplored, despite their pervasive adoption in Computer Vision where they have demonstrated their supremacy over CNNs in many computer vision tasks [7]. It is interesting to note that while attention or transformer blocks find occasional integration, they are almost invariably utilized _in conjunction with_ other usual convolution blocks, in both the analysis and synthesis processes [8, 9]. Furthermore, a critical prerequisite for effective image compression is the reduction of spatial redundancy, and the transformer's attention mechanism, which aggregates related elements within a sequence, appears especially well-suited for this purpose. With this context in mind, we propose in this paper a comprehensive investigation of the potential benefits of relying _exclusively_ on the transformer's attention mechanism for image compression, thereby eliminating convolutional priors from the equation. The remaining of this paper is structured as follows: First, we present recent achievements in learned image compression, as well as basics on attention mechanisms. Then, we present and explain our transformer-based analysis/synthesis model based on our _image queries_ concept. These _image queries_ are learned prototypes which aggregate information from image step by step thanks to transformer cross-attention blocks. Finally, we show and analyze results of the proposed architecture on several datatsets to give some insights about the inner working of our proposed model _QPressFormer_, before we conclude. ## 2 Related Work ### Learned Image Compression In the realm of image compression, conventional lossless and lossy codecs, typified by ubiquitous standards like JPEG and its successors such as JPEG2000 [2], WebP [5], and BPG [3], have long prevailed as the industry norm. These well-established codecs continue to be indispensable in contemporary applications, exemplified by the ongoing development of the VVC codec [10] for video, with adaptions tailored for image compression. Nonetheless, the recent years have witnessed a burgeoning interest in deep learning-driven approaches for both lossless and near-lossless image compression [11], marking a noteworthy departure from conventional methodologies. Todericci et al. introduced an innovative approach using recurrent neural networks (RNNs) [12, 13] for variable-rate image compression. Their method involves multiple passes of the original image through the network, generating an \(m\)-bit representation at each step to control the final bit-rate. While they explored various scenarios, they did not incorporate attention mechanisms. Another strategy entails training multiple networks for distinct bit-rates. Balle et al. introduced an innovative approach [14, 1] centered on learning the probability distribution of images within a latent space, with a concurrent focus on minimizing both the distortion and the entropy of this learned distribution. As per Shannon's theory, entropy serves as a lower bound for code length, rendering it synonymous with bit-rate minimization. The delicate equilibrium between these two objectives delineates the distortion/bit-rate trade-off. Their methodology incorporates convolutional transforms, paired with normalization functions [15] for image compression. To enhance the estimation of the latent probability distribution, Balle and colleagues introduced side information through latent variable models, where the variables obtained from the analysis transform are Figure 1: Image reconstruction from DIV2K. Zoom comparisons with original, convolutional equivalent model from [1] and BPG are shown on the sides. Even at lower PSNR, our method significantly improves on the details of the penguin’s fur, as captured by the lpips metrics. Examples on Kodak and CLIC in appendix A. treated as observed variables. A prior, referred to as the hyper-prior, is learned on these variables, effectively serving as a 'prior of the prior' to better account for spatial dependencies within the latent space. The ensuing hyper-latent variables are subsequently learned, contributing to the distribution in the hyper-latent space whose entropy is minimized to minimize bit-rate of this side-information. These hyper-variables allowing the variances inference of the original latent variables modeled as zero-mean Gaussian variables. In recent works [16], significant advancements were made in optimizing the image compression pipeline, with two notable steps. Causal consideration of context began to be incorporated to enhance the inference of parameters within the distribution of subsequent latent variables. Building upon this foundation, attention mechanisms were integrated to encompass contextual information, wherein latent variables were modeled as Gaussian mixture models (GMMs), with parameter inferences facilitated by hyper latent variables [17]. Concurrently, several works embraced attention mechanisms to more effectively account for contextual nuances, particularly concerning bit allocation. These mechanisms dynamically allocate more bits to regions of higher attention, signifying their increased complexity and importance [18, 19]. Notably, while transformers have occasionally served as attention modules within these architectures [9, 8], they have been employed alongside convolutional components, distinguishing our approach. Finally, generative models have also been investigated [20, 21, 22]. This results in better perception quality image especially in low bit-rate setup even if it is sometimes not reflected by distortion metrics like PSNR or MS-SSIM due to the Perception-Distortion trade-off [23]. Similarly to other approaches, even when attention is used it is in addition to convolutions. ### Transformers Transformers, initially introduced by Vaswani et al. in the domain of Natural Language Processing (NLP) for translation tasks [6], have since permeated diverse NLP applications, from BERT [24] to LlaMA [25] models. Within Computer Vision (CV), Dosovitskiy et al. inaugurated the integration of transformers [26], which are now prevalent in various vision tasks encompassing object detection [27], image synthesis [28], or cross-modal endeavors such as Text-Image Retrieval and Visual Question Answering [29]. Notably, transformers have supplanted traditional CNNs [7]. The transformer architecture relies on an attention mechanism, facilitating interactions between two distinct sequences of tokens. Its fundamental objective is to iteratively aggregate tokens from a sequence denoted as _values_, organized in a matrix \(V\), into another sequence known as _queries_, stored in a matrix \(Q\). This aggregation is guided by the similarity between elements in \(Q\) and \(V\). To achieve this, the _values_ are subject to \(h\) projections, distributed across different sub-units termed _heads_, yielding \(h\) sets of _keys_, amalgamated within a matrix \(K\). For each set of _keys_, a similarity score \(s_{i,j}\) is computed using the dot product between \(q_{i}\) and \(k_{j}\), where \(k_{j}\) corresponds to specific features of \(v_{j}\). These similarity scores are gathered within a matrix, normalized through the softmax function, and designated as the attention matrix \(A\). Thus, at each iteration \(n\), \(h\) attention matrices are computed using the following equation: \[A^{n}=\sigma\left(Q^{n}\left(K^{n}\right)^{T}\right) \tag{1}\] Once the attention matrices are obtained, they are employed to compute a weighted sum of the _values_, subsequently added to the _queries_. Consequently, the _queries_ accumulate the most akin _values_ corresponding to \(h\) specific features, as determined through the projection of _values_ into \(h\) sets of _keys_. This process is concisely captured in the following equation, where \([\dots]_{h}\) denotes the aggregation of the \(h\) sub-units: \[Q^{n+1}=Q^{n}+\left[A^{n}V^{n}\right]_{h}=Q^{n}+\left[\left(\sum_{k}a_{ik}^{n }v_{kj}^{n}\right)_{i,j}\right]_{h} \tag{2}\] The equation 2 correspond to the main module of transformer called Multi-Head-Attention denoted MHA in the following. In order to preserve the dimension \(d\) of the whole transformer, all elements in the \(h\) sub-units are projected in a space of dimension \(d_{h}=\frac{d}{h}\), which implies \(d\equiv 0\left(mod\ h\right)\). There are 2 different MHA modules. The Self-Attention module, \(\text{SA}\left[Q\right]\), correspond to the case where each _query_ aggregates itself with its most similar _queries_ according to particular features. In this case _queries_ and _values_ are identical. The other case correspond to the Cross-Attention, \(\text{CA}\left[Q,V\right]\). Here, the set of _queries_ and _values_ are different. The sequence of _queries_ aggregates information from another sequence. More details are available in [6]. ## 3 Method In this section, we introduce our convolution-free architecture, denoted QPressFormer, which exclusively relies on attention blocks. For the compression component, we adopt a factorized prior model similar to [1]. To ensure comparability, our aim is to develop a model with similar target bitrate, while replacing convolutional analysis and synthesis transforms with attention-based counterparts. The whole pipeline of our QPressFormer model is illustrated in Figure 2. An image \(I\) is first divided into patches, which are unrolled and augmented with positional encodings corresponding to their patch index using the transformation denoted as \(\varphi\). The resulting set of vectors serves as the _values_/_keys_ (\(V_{E}/K_{E}\)) for the encoder \(E\), which employs attention blocks exclusively. Additionally, a set of \(N\) learned vectors, referred to as 'Image queries' (\(Q_{E}^{in}\)), serves as _queries_. The set \(Q_{E}\) aggregates information from the image at each step \(n\) through the attention process outlined in Section 2.2. In-depth, the blocks of \(E\) consist of transformer decoder blocks [6], governed by the following equations for each layer \(n\): \[\begin{split} Q^{n+1/2}=\operatorname{CA}\left[\operatorname{ SA}\left[Q^{n}\right],\varphi(I)\right]\\ Q^{n+1}=Q^{n+1/2}+\operatorname{FFW}^{n}(Q^{n+1/2})\end{split} \tag{3}\] At the final stage, the output _queries_ (\(Q_{E}^{out}\)) containing the compressed image. In this study, we work with 256x256 RGB images divided into 16x16 patches. This results in 256 patches, flattened as 768-dimensional vectors, which sets the embedded dimension of our architecture. We opt for \(N=64\)_Image Queries_. \(Q_{E}^{out}\) corresponds to the latent variables so the probability distribution of \(Q_{E}^{out}\) is estimated using a network and its entropy minimized to reduce the bit-rate, as discussed in Section 2.1. Importantly, our reconstruction perception metric is not the Mean-Square-Error (MSE) but lips [30], a perceptual metric that aligns better with human perception. The decoding process mirrors the encoding procedure. The vectors \(\{Q_{E}^{out}\}\), containing the compressed image, serve as _values_ (\(V_{D}\))/_keys_ (\(K_{D}\)) for the image decoder \(D\). The _queries_ in \(D\) are learned vectors corresponding to patch prototypes. They aggregate the compressed image progressively, and in the final stage, are reshaped and reassembled to yield the decompressed image \(\hat{I}\). Figure 2: QPressFormer : Our Proposed Architecture. The architecture is trained on the ImageNet using Adam with a learning rate of 1e-4. Beyond 100,000 steps, optimizing lpips becomes more challenging. We observed that upscaling images to 512x512 before using lpips enhances results without requiring other changes. Both \(E\) and \(D\) have 12 heads and a depth of 12. ## 4 Results ### Quantitative Results In Table 1, we present a comparative analysis between our model, BPG and equivalent convolutional factorized prior models from [1] with pretrained weights obtained from CompressAI [31] on three datasets (Kodak [32], CLIC [33] and DIV2K [34]). For the MSE and MS-SSIM optimized models, we select weights corresponding to the closest bit per pixel (bpp) to our model. Our evaluation employs a range of metrics, including PSNR, MS-SSIM [35], lpips [30], and FID [36], which assesses the realism of generated images. Given that our architecture was trained on 256x256 images, we decompose all images into 256x256 segments and input each 256x256 part to the network before reassembling them. In cases where the image dimensions are not divisible by 256x256, we employ center cropping to obtain the largest segment divisible by 256x256. To ensure a fair comparison with convolutional counterparts or hand-designed BPG format, we apply the same image decomposition for reconstruction. As shown in Table 1, the convolutional model optimized on MSE (respectively on MS-SSIM) performs better in terms of PSNR (respectively on MS-SSIM). In the same manner, our model performs significantly better on lpips. Moreover, our model performs better on FID even if it was not trained specifically for it. Besides, even if the PSNR and MS-SSIM of our model is lower than convolutionnal counterpart, it captures better perceptual details - as expected with the lpips optimization - as shown in figure 1. Convolution bias is thus not a prerequisite for Image compression and a transformer architecture seems at least equivalent or better - in terms of perceptual metrics FID and lpips - than convolutional networks and BPG. ### Visual analysis To understand how the attention blocks process the image during encoding, we perform several visualizations. During the attention process, the attention weights are computed for a given pair of _query_ and _key_. As each _key_ corresponds to a patch, we can see which part of the image one _query_ pays attention to by plotting its attention matrix. By combining the attention matrices of all queries, layers and heads (with **maximum**), we obtain a heatmap showing which parts of the image have been processed (Figure 3). As expected for good reconstruction, the whole image is attended, almost uniformly. In other words, at least one query pays attention only once in each image area. To better understand what information is captured by a _query_, we visualize the layers and heads **mean** attention map for each _query_ individually. An example is given in Figure 3(c). It is worth noting the **maximum** of attention maps and the **mean** of attention maps able us to make two distinct observations. The mean \begin{table} \begin{tabular}{l|c||c|c|c|c} Method & bpp & PSNR\(\uparrow\) & MS-SSIM\(\uparrow\) & lpips\(\downarrow\) & FID\(\downarrow\) \\ \hline & & \multicolumn{4}{c}{Kodak} \\ QpressFormer & 0.296 & 27.19 & 0.9203 & **0.2126** & **68.60** \\ Conv+mse [1] & 0.258 & 31.59 & 0.9608 & 0.3386 & 154.06 \\ Conv+mssim [1] & 0.320 & 30.66 & **0.9745** & 0.2913 & 117.94 \\ BPG [3] & 0.301 & **32.78** & 0.9626 & 0.2872 & 110.90 \\ & & \multicolumn{4}{c}{DIV2K (val-set)} \\ QpressFormer & 0.300 & 25.50 & 0.9159 & **0.2267** & **19.19** \\ Conv+mse [1] & 0.290 & 30.10 & 0.9642 & 0.3429 & 63.12 \\ Conv+mssim [1] & 0.322 & 28.94 & **0.9716** & 0.3237 & 49.78 \\ BPG [3] & 0.307 & **30.84** & 0.9604 & 0.3155 & 54.73 \\ & & \multicolumn{4}{c}{CLIC (test-set)} \\ QpressFormer & 0.286 & 27.96 & 0.9339 & **0.2244** & **9.63** \\ Conv+mse [1] & 0.230 & 32.33 & 0.9657 & 0.3820 & 51.85 \\ Conv+mssim [1] & 0.277 & 31.32 & **0.9758** & 0.3536 & 36.83 \\ BPG [3] & 0.297 & **34.31** & 0.9712 & 0.3216 & 40.78 \\ \end{tabular} \end{table} Table 1: Quantitative results on Kodak, CLIC and DIV2K datasets. correspond to the area which is the most watched by the _query_ whereas the **maximum** allows us to ensure that all areas are watched by _queries_ at least one time. An original 256x256 crop from Kodak and the decoded patch are given in Figure 3(a) and 3(b). The figure 3(c) shows the **mean** attention map - across heads and layers - for _query_ 11. The attention is more focused on a part of the roof. To verify that this specific query encodes this particular region, we reconstruct the image without it. We can then see on the figure 3(d) that the area where the removed _query_ paid attention to is not reconstructed properly. Interestingly, the area is inferred and in-painted with the roof texture, indicating that information from others patches able the encoder to infer information in that area. In Figure 3(e), the reconstruction error without this particular query and averaged over the Kodak dataset shows that the spatial information encode by the _query_ is the same for all images. In fact, after looking at the 64 averaged reconstruction error, nearly all _queries_ encode spatial information. It is worth noting that this spatial encoding property in the queries is an emergent behavior of the model, as it was not designed in the architecture or in the optimization. However, spatial information is not the whole information encoded by _queries_\(Q_{E}^{out}\). First, a look at **maximum** attention maps of queries allow us to discover that the same _query_ pays attention to areas in different locations for different 256x256 crops of the same kodak image. Figure 9 in appendix C gives more details. Second, if each _query_ was specialized spacially, in-painting wouldn't be possible. To better visualize the elements encoded by _queries_, we perform a PCA on the whole queries for a Kodak image to reduce the dimensions of _queries_ from 768 to 3. In the following we refers to these reduce dimensional _queries_ as _meta-queries_. We can then visualize a RGB image corresponding to the main, or at least the most important, information decoded at each layer of the decoder. Remember that the output _queries_ of the encoder \(Q_{E}^{out}\) serve as _keys/values_ for the decoder wherein the _queries_ are learned patchs prototypes. After reducing the dimensionality of \(Q_{E}^{out}\), we can project on it the mean across heads of cross-attention matrices (instead of the decoder _values_ obtained from the full encoder _queries_) for a given layer of the decoder with the following Figure 4: 256x256 Kodak Image Crop Reconstruction with all \(Q_{E}\) or with \(\left\{Q_{E}\right\}_{11}\) removed (denoted \({}^{\dagger}\)). Figure 3: Attention map (max attn scores for all queries/layers/heads) for a Kodak image. equation: \[I_{visu}^{n}=\frac{1}{nb_{heads}}\sum_{h\in heads}\left(A_{h}^{n}\right)Q_{E;[:3]}^{ out} \tag{4}\] In equation 4 \(Q_{E;[:3]}^{out}\) denotes the _meta-queries_ - _i.e._ output encoder _queries_ obtained after PCA for reducing dimension to 3. The figure 5 shows clearly that _queries_ contain spatial information extracted at some specific layers: figure 4(b) shows the same colors across different positions for different 256x256 blocks of an kodak image in addition to smooth transitioning between colors. In contrast figure 4(d) show a nearly segmentation of the original kodak image demonstrating some semantic information is extracted at others layers in the decoder, and so present in the queries. Thus, to perform a full reconstruction, _queries_ encodes at the same time semantic and spatial information. More visualizations are given in appendix B ## 5 Conclusion In this study, we explore learned image compression exclusively through attention blocks, eliminating convolutional biases. Our model, _QPressFormer_, introduces "image queries" for cross-attention-based information aggregation. Our results show competitive results with convolutional counterparts with improved perceptual metrics. Future research should further investigate attention-based image compression. While we focused on analysis and synthesis components with a basic prior model, incorporating enhancements on prior model from convolutional models into attention-based architectures can assess transformer-based compression against state-of-the-art convolutional counterparts. Figure 5: Visualization of information encoded by output encoder _queries_ and extracted at layer 1 and 11 of the decoder. 4(b) shows the layer 1 extract more spatial information from the _queries_ whereas 4(d) shows more semantics extraction with a nearly segmentation of image.
2305.09850
MINT: Multiplier-less INTeger Quantization for Energy Efficient Spiking Neural Networks
We propose Multiplier-less INTeger (MINT) quantization, a uniform quantization scheme that efficiently compresses weights and membrane potentials in spiking neural networks (SNNs). Unlike previous SNN quantization methods, MINT quantizes memory-intensive membrane potentials to an extremely low precision (2-bit), significantly reducing the memory footprint. MINT also shares the quantization scaling factor between weights and membrane potentials, eliminating the need for multipliers required in conventional uniform quantization. Experimental results show that our method matches the accuracy of full-precision models and other state-of-the-art SNN quantization techniques while surpassing them in memory footprint reduction and hardware cost efficiency at deployment. For example, 2-bit MINT VGG-16 achieves 90.6% accuracy on CIFAR-10, with roughly 93.8% reduction in memory footprint from the full-precision model and 90% reduction in computation energy compared to vanilla uniform quantization at deployment. The code is available at https://github.com/Intelligent-Computing-Lab-Yale/MINT-Quantization.
Ruokai Yin, Yuhang Li, Abhishek Moitra, Priyadarshini Panda
2023-05-16T23:38:35Z
http://arxiv.org/abs/2305.09850v4
# MINT: Multiplier-less INTeger Quantization for Spiking Neural Networks ###### Abstract We propose Multiplier-less INTeger (MINT) quantization, an efficient uniform quantization scheme for the weights and membrane potentials in spiking neural networks (SNNs). Unlike prior SNN quantization works, MINT quantizes the memory-hungry membrane potentials to extremely low bit-width (2-bit) to significantly reduce the total memory footprint. Additionally, MINT quantization shares the quantization scale between the weights and membrane potentials, eliminating the need for multipliers and floating arithmetic units, which are required by the standard uniform quantization. Experimental results demonstrate that our proposed method achieves accuracy that matches other state-of-the-art SNN quantization works while outperforming them on total memory footprint and hardware cost at deployment time. For instance, 2-bit MINT VGG-16 achieves 48.6% accuracy on TinyImageNet (+0.28% from the full-precision baseline) with approximately 93.8% reduction in total memory footprint from the full-precision model; meanwhile, our model reduces area by 93% and dynamic power by 98% compared to other SNN quantization counterparts. Neuromorphic computing, Spiking neural networks, Neural network compression, Computer architecture ## I Introduction Spiking Neural Networks (SNNs) [1, 2, 3] have emerged as a promising alternative to Artificial Neural Networks (ANNs) due to their energy efficiency in processing highly sparse unary spike trains. This feature makes them attractive candidates for low-power edge devices, as they can run with much-simplified arithmetic units. As SNNs continue to gain popularity, numerous prior studies have aimed to enhance their performance for edge deployment. As shown in Fig. 1, one group of previous works [2, 4, 5, 6, 7] has a discernible trend of improving accuracy and diminishing timesteps of SNNs on the CIFAR10 image classification task. These efforts help SNNs achieve higher task accuracy with lower computation energy. Another group of research efforts has focused on the limited on-chip memory for edge deployment of SNNs. These prior works have sought to compress the SNN model size by either pruning [8] or quantizing the weights of SNNs [9, 10, 11]. While prior optimizations have improved the performance of SNNs towards more efficient edge deployment, one significant issue has been largely overlooked in previous research - the memory footprint of the membrane potential. As shown in Fig. 1, the memory footprint of the membrane potential, often remains several times larger than the memory size of weights. The membrane potential is used to store temporal information and is related to the generation of output spikes inside the Leaky-Integrate-and-Fire (LIF) neuron. A dedicated memory is required for each hidden neuron to store its unique membrane potential for each timestep and input image, in order to ensure the proper functionality of SNNs. Thus, the memory footprint of the membrane potential grows significantly as the size of SNNs, the number of timesteps, or the number of mini-batches scales up. While weight quantization has been extensively explored by the prior works [9, 10, 11, 12] and brings significant SNN model size reduction, the storage size of membrane potential becomes dominant when the size of weights decreases. For instance, as shown in Fig. 2 (a), on the VGG9 network, as the bit-precision of weights decreases from 32-bit to 4-bit, the proportion of the membrane potential in the total memory footprint grows from less than 20% to more than 60%. Moreover, as batch size increases from 1 to 32, the membrane potential takes up over 98% of the total memory footprint. Unfortunately, the compression of membrane potential has been consistently overlooked by existing SNN research efforts. To address the problem of the expanding size of membrane potential, this work studies the quantization of membrane potential together with weight quantization. We explore the membrane potential quantization based on standard uniform quantization (UQ), an integer-based technique extensively used in prior quantization works [10, 13, 14]. However, as shown on the left side of Fig. 2 (b), naively applying UQ to SNNs brings two hardware-related problems. Fig. 1: Visualization of the selected prior works including, STQ [9], BNIT [4], Direct SNN [2], TSSL [5], Event-BP [6], TDBN [7], and LTH [8], on improving the performance of SNNs on the CIFAR10 dataset. **Firstly**, in the standard UQ, after the convolution between the quantized weights (int) and the inputs (unary spikes), the convolution result (int) is multiplied by a full-precision floating-point (float) scaling factor to ensure high inference accuracy. Consequently, full-precision floating-point multipliers are physically required, leading to high hardware costs in the system that deploys the SNNs. **Secondly**, the LIF operations right after the scaling become floating-point-based due to the floating-point multiplications. The float LIFs require extra floating-point hardware units, increasing hardware overheads in SNN deployment. To address the issues mentioned above, we propose Multiplier-less Integer-based (MINT) quantization for both the weights and membrane potentials of SNNs, which is illustrated on the right-hand side of Fig. 2 (b). MINT effectively reduces the size of weights and membrane potentials, while also addressing the two hardware issues associated with Uniform Quantization (UQ) by avoiding multipliers and floating-point arithmetic units of LIF. We summarize our key contributions as follows: 1. We introduce the MINT quantization scheme for the weights and membrane potentials of SNNs. MINT is a uniform quantization scheme that uses fully integer-based operations, eliminating the need for multipliers to perform quantization scaling during inference time. 2. We evaluate MINT with two representative deep SNN architectures (VGG-9 [15] and VGG-16 [15]) on two benchmark datasets (CIFAR10 [16] and TinyImageNet [17]). The experimental results show that our quantized models achieve similar accuracy to the full-precision baselines while significantly reducing memory cost. For example, our 2-bit quantized VGG-16 leads to approximately 93.8% memory footprint reduction with a negligible accuracy degradation (-0.6%) on CIFAR-10. 3. We further deploy the SNN models quantized by MINT and other state-of-the-art SNN quantization schemes on three existing specialized SNN hardware accelerators (SpinalFlow [18], PTB [19], and SATA [20]). While achieving competitive accuracy results with other methods, MINT saves significant hardware resources at deployment. For instance, MINT saves 93% area and 96% dynamic power at the PE-array level on SpinalFlow compared to ADMM-Quant [10]- a state-of-the-art SNN quantization scheme that reports the best accuracy on CIFAR-10 among all other SNN quantization works. 4. We report the speedup of the int8 model quantized by MINT from the fp32 baseline on RTX-2080 Ti and NVIDIA A100. Additionally, we carry out sparsity-related ablation studies on MINT. ## II Related Work Spiking neural networks (SNNs) have recently been extensively explored as a new generation of low-power deep neural networks for efficient edge device deployment [1, 3]. There are two main types of SNNs: conversion-based SNNs and BPTT-based SNNs. Conversion-based SNNs are converted from pre-trained artificial neural network (ANN) models, as seen in [21, 22, 23]. Although conversion-based SNNs offer good accuracy, they require a large number of timesteps (50-2000 timesteps), leading to prohibitive energy costs [20], unsuitable for edge devices. BPTT-based SNNs use surrogate gradients to circumvent the non-differentiability problem of LIF and backpropagate the gradients through both spatial and temporal dimensions to train SNNs from scratch [2, 4, 5, 6, 7]. Specifically, we call this training method as backpropagation-through-time (BPTT) [24]. These BPTT-based SNNs can achieve iso-accuracy performance compared to the conversion-based SNNs while running at a much lower number of timesteps (\(<30\)). Our work focuses on the quantization of BPTT-based SNNs. Many prior works focus on improving the accuracy of BPTT-based SNNs, such as [2, 4, 5, 6, 7]. Some works also aim to reduce the number of timesteps required in SNNs. For example, in [4], the early exit algorithm is explored to reduce the number of timesteps to below 20. In [2], a more efficient input encoding is utilized, further reducing the number of timesteps below 10 while improving accuracy. Other works, such as [8] and [25], explore the lottery-ticket-hypothesis-based pruning method for SNNs, which retains high accuracy while removing more than \(98\%\) of the weight connections. Weight quantization in SNNs has also been explored in [9, 10, 11]. In [9] and [10], weight quantization together with pruning has been studied. In [10], the ADMM method optimizes a pre-trained full-precision network to quantize the weights into low precision. K-means clustering quantization is used in [9] to achieve reasonable accuracy with 5-bit weight SNNs. However, all of these prior works used full-precision floating-point representation to store the membrane potential. As a result, the total memory footprint of SNNs remains large. Additionally, they require either multipliers for quantization scaling or specialized arithmetic circuits to convert the weights into the format of K-means clustering. In our work, we explore the simultaneous quantization of weights and membrane potentials using fully-integer operations without the need for multipliers to scale convolution results or any extra hardware circuits to support the quantization-aware inference. One very recent work [11] explored fully integer-based SNNs with both weights and membrane potentials quantized in Fig. 2: (a) The proportion of membrane potential (denoted as \(U\)) in the overall memory footprint of SNNs when reducing weight precision and increasing mini-batches. (b) An overview of the comparison between our MINT quantization and the standard uniform quantization (UQ). The color blue denotes integer operations while green represents floating-point operations. the fixed-point format without quantization scaling. However, due to the limited representation range of the fixed-point format, they did not achieve reasonable inference accuracy at low precision. For example, they only achieved 33.5% accuracy on CIFAR10 with 2-bit weights and 8-bit membrane potentials, whereas our quantization scheme achieved 88.39% with both weights and membrane potentials quantized to 2 bits. We summarize the methodology differences between our MINT quantization scheme and other prior SNN quantization methods in Table. I. Detailed quantitative comparisons with prior works are presented in the experimental section. It is important to note that while several other prior works have explored integer quantization of SNNs [26, 27], they have primarily focused on very shallow networks with a local learning rule that is not suitable for large-scale image classification tasks. Furthermore, they did not consider the quantization of the membrane potential, making their work orthogonal to ours. ## III Preliminaries ### _Spiking Neural Networks_ SNNs process unary spike trains over multiple discrete timesteps through Leaky-Integrate-and-Fire (LIF) neurons which introduce non-linearity and capture temporal information in the network. We describe the behavior of LIF neurons in formal mathematical equations. At timestep \(t\), the LIF neurons in layer \(l\) first convolve the input spikes with the weights, and the resulting values are stored in a dedicated memory called the membrane potential. Since the input spikes are unary, the convolution operation in the LIF neurons simplifies to a simple accumulation instead of a multiply-and-accumulate (MAC) operation, which can be implemented without multipliers. The accumulated potential at the current timestep is added to the residual memory potential from the previous timestep \(t-1\). We refer to this step as the "membrane potential update" stage, which we define as follows: \[\mathbf{H}_{l}^{(t)}=\ \mathbf{W}_{l}\mathbf{S}_{l-1}^{(t)}+\mathbf{U}_{l}^{(t-1)}. \tag{1}\] The \(\mathbf{W}_{l}\) denotes the weight matrix at layer \(l\) and \(\mathbf{S}_{l-1}^{(t)}\) denotes the input spike matrix from layer \(l-1\) at timestep \(t\). The residual membrane potential matrix from the previous timestep \(t-1\) at layer \(l\) is denoted as \(\mathbf{U}_{l}^{(t-1)}\) and the matrix of membrane potential before reset is defined as \(\mathbf{H}_{l}^{(t)}\). The membrane potentials before reset are then compared to a pre-set threshold \(v_{th}\). If the potential exceeds the threshold, the neuron will generate an output spike, otherwise, no output spike will be produced. The output spike matrix for layer \(l\) at timestep \(t\) is denoted as \(\mathbf{S}_{l}^{(t)}\). We refer to this step as the "firing" stage and formulate it as follows: \[\mathbf{S}_{l}^{(t)}=\ \Theta(\mathbf{H}_{l}^{(t)},v_{th}), \tag{2}\] where \[\Theta(x,y)=\left\{\begin{array}{ll}1&\quad x>y\\ 0&\quad\text{else.}\end{array}\right.\] Finally, we calculate the residual membrane potential matrix \(\mathbf{U}_{l}^{(t)}\) at layer \(l\) and timestep \(t\). First, we reset the membrane potential matrix \(\mathbf{H}_{l}^{(t)}\) according to the output spikes generated at this timestep and the selected reset mode. In the hard reset mode, the membrane potential is reset to \(0\) upon output spike generation. In contrast, the soft reset mode reduces the membrane potential by \(v_{th}\). We then multiply the membrane potential after reset by a leakage factor \(\tau\) and store it back in memory to be used in the next timestep. We refer to this stage as the "reset" stage: \[\mathbf{U}_{l}^{(t)}=\left\{\begin{array}{ll}\tau\mathbf{H}_{l}^{(t)}\left(1-\mathbf{S}_ {l}^{(t)}\right)&\quad\text{hard reset}\\ &\\ \tau\left(\mathbf{H}_{l}^{(t)}-\mathbf{S}_{l}^{(t)}v_{th}\right)&\quad\text{soft reset} \end{array}\right. \tag{3}\] We further illustrate the spatial and temporal dynamics of one LIF neuron in Fig. 3. ### _Uniform Quantization_ Uniform fixed-point quantization methods have been extensively studied by prior works [13, 14, 28]. The uniform fixed-point quantization works as an affine mapping between the fixed-point number vector \(\mathbf{q}\) and the floating-point number vector \(\mathbf{r}\) of the form: \[\mathbf{r}=\alpha\left(\mathbf{q}-Z\right), \tag{4}\] where both the \(\alpha\) (scaling factor) and \(Z\) (zero-point) are the quantization parameters. For \(b\)-bit quantization, \(\mathbf{q}\) consists of integers representing one of the \(2^{\text{b}}\) quantized levels in the range of \([0,2^{b}]\). The scaling factor \(\alpha\) is an arbitrary 32-bit floating number that Fig. 3: Illustration of the temporal and spatial dynamics of the LIF neuron, where the temporal dynamics refer to the LIF operations across different timesteps, and the spatial dynamics refer to the convolution operation between input spikes and weights. scales the quantized levels to best fit the distribution of the original values in \(\mathbf{r}\). The zero-point \(Z\) is an integer that ensures \(\mathbf{r}=0\) can be exactly represented by one of the quantized levels. We empirically find that zero-point is not necessary for quantization in SNNs, thus we do not include the zero-point \(Z\) in the rest of this work. For instance, assume that we have a full precision weight matrix \(W^{l}\) for layer \(l\), then the \(b\)-bit uniform quantization of the weight is defined as: \[\mathbf{W}_{l}=\alpha\mathbf{\hat{W}}_{l}, \tag{5}\] where the \(\mathbf{\hat{W}}_{l}\) is the quantized weight matrix with each of its elements represented by a \(b\)-bit integer. The value of scaling factor \(\alpha\) is calculated from \[\alpha=\frac{\max\left(|\tanh(\mathbf{W}_{l})|\right)}{2^{b-1}-1}, \tag{6}\] and the quantized weight matrix \(\mathbf{\hat{W}}_{l}\) is then represented as \[\mathbf{\hat{W}}_{l}=\left|\left(\frac{\mathbf{W}_{l}}{\alpha}\right)\right| \tag{7}\] The \(\lfloor\cdot\rceil\) denotes the rounding function that rounds the input into the nearest integer. ## IV Analysis of Quantization in SNNs ### _Naive Uniform Quantization of SNNs_ We begin our analysis by applying a naive approach of uniform quantization to the \(l\)-th layer of SNNs. We assume a scaling factor of \(\alpha_{1}\) for the weight matrix \(\mathbf{W}_{l}\), \(\alpha_{2}\) for the residual membrane potential matrix at the previous timestep \(\mathbf{U}_{l}^{(t-1)}\), and \(\alpha_{3}\) for the membrane potential matrix at the current timestep \(\mathbf{U}_{l}^{(t)}\). It is important to note that we do not consider the use of a zero-point and assume the reset type to be hard. The LIF update equations for the naive uniform quantized SNNs are given below: \[\mathbf{H}_{l}^{(t)}= \ \alpha_{1}\mathbf{\hat{W}}_{l}\mathbf{S}_{l-1}^{(t)}+\alpha_{2}\mathbf{\hat {U}}_{l}^{(t-1)}, \tag{8}\] \[\mathbf{S}_{l}^{(t)}= \ \Theta(\mathbf{H}_{l}^{(t)},v_{th}),\] (9) \[\alpha_{3}\mathbf{\hat{U}}_{l}^{(t)}= \ \tau\mathbf{H}_{l}^{(t)}(1-\mathbf{S}_{l}^{(t)}). \tag{10}\] We further illustrate the dataflow of the naive quantized LIF neuron in Fig. 4. In the naive uniform quantized LIF, we observe that although the convolution operations between the weights and input spikes are in the integer domain (colored in blue), all other computations are in the floating-point domain (colored in green). Moreover, there are three 32-bit floating-point multiplications due to the scaling factors, \(\alpha\), along the datapath, which undermines the benefits of the simplified arithmetic units of SNNs. We do not consider the operation of leakage as a multiplication since \(0.5\) is a very common leakage factor used by prior literature [4, 8] that can be efficiently implemented with a shift operation. We observe that quantizing the membrane potentials \(\mathbf{U}_{l}^{(t)}\) and \(\mathbf{U}_{l}^{(t-1)}\) into integers does not help accelerate any operations along the datapath. As a result, it is better to keep them at floating-point precision, thereby eliminating the need for floating-point multiplications for \(\alpha_{2},\alpha_{3}\). Still, there will be one 32-bit floating-point multiplication for \(\alpha_{1}\) and other floating-point operations remaining on the datapath. These operations will incur additional energy and area overhead for the SNN hardware. We present a comparison of the relative energy and area costs between integers and floats for several arithmetic units in Table II. ### _Role of Scaling in Quantized SNNs_ In this section, we reflect on the role of scaling in SNNs and check whether it is possible to remove it, thus eliminating the multiplication involved with scaling. We start the examination by substituting Eq. 8 into Eq. 10. Assume there is no output spike generated at timestep \(t\). Then we will have the full equation for calculating the residual membrane potential \[\alpha_{3}\mathbf{\hat{U}}_{l}^{(t)}= \ \tau\left(\alpha_{1}\mathbf{\hat{W}}_{l}\mathbf{S}_{l-1}^{(t)}+\alpha_{2} \mathbf{\hat{U}}_{l}^{(t-1)}\right), \tag{11}\] which can be rewritten as \[\mathbf{\hat{U}}_{l}^{(t)}= \ \tau\left(\frac{\alpha_{1}}{\alpha_{3}}\mathbf{\hat{W}}_{l}\mathbf{S}_{l -1}^{(t)}+\frac{\alpha_{2}}{\alpha_{3}}\mathbf{\hat{U}}_{l}^{(t-1)}\right) \tag{12}\] In Eq. 12, the only two non-integers left are \(\frac{\alpha_{1}}{\alpha_{3}}\) and \(\frac{\alpha_{2}}{\alpha_{3}}\). Assume \(\tau=0.5\). In order to remove those two full-precision floating-point multiplications, one straightforward method is to have \(\alpha_{1}=\alpha_{2}=\alpha_{3}\). By having all the scaling factors equal to each other, we manage to transform Eq. 12 into: \[\mathbf{\hat{U}}_{l}^{(t)}= \ \tau\left(\mathbf{\hat{W}}_{l}\mathbf{S}_{l-1}^{(t)}+\mathbf{\hat{U}}_{l}^{( t-1)}\right). \tag{13}\] The Eq. 13 now only consists of integer values and integer operations. Moreover, there is no multiplication required for scaling. Fig. 4: Illustration of naive uniform quantization applied to the LIF neuron. The blue color indicates integer values and operations, while the green color represents floating-point operations and values. ### _Review the Firing in Quantized SNNs_ In Eq. 13, we manage to eliminate the multiplication involved in the datapath for calculating the residual membrane potential. We then examine the other datapath that generates the output spike. We again substitute Eq. 8 into Eq. 9 and find that the firing function will only generate an output spike if the following condition is valid: \[\alpha_{1}\hat{\mathbf{W}}_{l}\mathbf{S}_{l-1}^{(t)}+\alpha_{2}\hat{\mathbf{U}}_{l}^{(t-1) }>v_{th}. \tag{14}\] We can apply the previous idea of maintaining the same scaling value \(\alpha=\alpha_{1}=\alpha_{2}\). Then we divide \(\alpha\) into both sides of the inequality. The firing condition in Eq. 15 is thus of the form: \[\hat{\mathbf{W}}_{l}\mathbf{S}_{l-1}^{(t)}+\hat{\mathbf{U}}_{l}^{(t-1)}>\frac{v_{th}}{ \alpha}. \tag{15}\] We have empirically observed that \(\alpha\) is always greater than zero, which means the direction of the inequality in Eq. 15 is always preserved. Therefore, we can compute \(\frac{v_{th}}{\alpha}\) offline, which eliminates the need for any multiplication operations along the datapath. Additionally, since the left-hand side of Eq. 15 is always an integer, we can transform the equation into the following form and still achieve the same firing results: \[\hat{\mathbf{W}}_{l}\mathbf{S}_{l-1}^{(t)}+\hat{\mathbf{U}}_{l}^{(t-1)}\geq\left\lceil \frac{v_{th}}{\alpha}\right\rceil, \tag{16}\] where \(\lceil\cdot\rceil\) is the ceil operation. We define this new integer firing threshold as \(\theta\). ## V Multiplier-less Integer SNN Quantization ### _Inference Datapath_ As discussed in Sec. IV-B and IV-C, by sharing the quantization scaling factor between weights and membrane potentials across timesteps for each layer, we can implement our quantization scheme using integer-only arithmetic that requires no multiplications during inference. The inference algorithm is described in Alg. 1. We first perform a convolution operation between the input spikes and weights. As the input spikes are unary and the weights are quantized to integers, the convolution operation is simplified to an integer-based accumulation. Subsequently, the membrane potential before reset \(\mathbf{H}_{l}^{(t)}\) is computed by adding the integer convolution result \(\mathbf{X}_{l}^{(l)}\) and the quantized integer residual membrane potential \(\mathbf{U}_{l}^{(t-1)}\). Next, the integer membrane potential before reset \(\mathbf{H}_{l}^{(t)}\) is compared with the precomputed integer firing threshold \(\theta\) discussed in Sec. IV-C. Based on the comparison results, the unary output spikes are generated. If no output spike is generated, the integer \(\mathbf{H}_{l}^{(t)}\) is left shifted by 1, which is the same as multiplying by a leak factor with the value of 0.5. The result is then cast down to the target bitwidth and stored as the residual membrane potential \(\mathbf{U}_{l}^{(t)}\). Alternatively, if an output spike is generated, a zero is stored as the residual membrane potential. This inference path is repeated for all other layers and timesteps in SNNs, utilizing integer arithmetic and eliminating the need for multiplications. Fig. 5 illustrates the dataflow for MINT quantized LIF neurons. ### _Training with Simulated Quantization_ During the forward path of training, we apply the following simulated quantization function \(Q\) to weights and membrane potentials: \[Q(r,n)=\frac{\left\lfloor\mathrm{clamp}\left(\frac{r}{\mathrm{s}(r)},-1,1 \right)\mathrm{s}(n)\right\rceil\mathrm{a}(r)}{\mathrm{s}(n)}, \tag{17}\] where \[\mathrm{s}(n) =2^{n-1}-1,\] \[\mathrm{a}(r) =\max(|\tanh(r)|),\] \[\mathrm{clamp}(r,a,b) =\min(\max(r,a),b).\] Here, \(r\) represents a full-precision floating-point number to be quantized, and \(n\) represents the number of bits assigned to the quantized integer. As we focus on uniform quantization in this work, we fix \(n_{w}\) for all layers' weights and \(n_{u}\) for the membrane potentials across all layers and timesteps in our experiments. We illustrate the position where the fake quantization is inserted in the forward path of training in Fig. 6. During backward propagation, we use full-precision floating-point gradients for all quantities. We employ the straight-through estimator [13] to approximate the derivative Fig. 5: Illustration of our MINT quantization of the LIF neuron. The blue color indicates the integer values or operations. for the non-differentiable rounding function \(\lfloor\cdot\rceil\). Hence, we can simulate the quantization errors during inference for our models at training time. ### _Shareable Quantization Scale_ As discussed in Sec. IV-B and IV-C, our method requires sharing one quantization scaling factor or scale between weights and membrane potentials. This means that we will have a single quantization scale \(\alpha\) for each layer that can be shared between these two quantities. During inference, we replace the firing threshold \(v_{th}\) with the integer value \(\left\lceil\frac{v_{th}}{\alpha}\right\rceil\). During training, we apply the fake quantization \(Q\) to weights and membrane potentials along the forward path, and the \(\text{a}(r)\) term in Eq. 17 is replaced with \(\alpha\). Further, instead of directly sharing the quantization scales between weights and membrane potentials, we make the shared scale \(\alpha\) a learnable parameter [29]. We update \(\alpha\) with full-precision gradients during backward propagation in the training process. ## VI Evaluation under Existing SNN Systems To better understand the potential benefits of multiplier-less integer quantization on hardware, we evaluated MINT on several existing ASIC SNN hardware systems. Specifically, we focused our evaluation on systolic-array-based ASIC accelerators for SNNs [18, 19, 20]. These accelerators utilize a dataflow architecture with high data reuse between processing elements (PEs), which is commonly found in ANN accelerators. ### _Exisiting SNN Accelerators_ **SpinalFlow**[18] is a systolic-array-based SNN inference accelerator that utilizes the extremely sparse temporal encoded SNNs through unique tick-batch dataflow. Inside each PE, several small scratchpad memories hold the membrane potential and weights. Additionally, an adder and a comparator support the LIF operation inside every PE. Each PE generates the output for only one neuron across the entire timestep. **PTB**[19] is another state-of-the-art systolic-array-based SNN inference accelerator that supports highly parallel processing of rate-coded SNNs. Inside each PE of the PTB, there are small scratchpads for holding the weights, input spikes, and membrane potentials. Each PE equips LIF arithmetic units and an accumulator for carrying out the convolution. Although several PEs divide the workload across timesteps, each PE still needs to complete a full convolution and LIF cycle (Eq. 1 - 3) for at least one timestep. **SATA**[20] is a systolic-array-based training accelerator for BPTT-based SNNs. To minimize the data movement of multi-bit operands across timesteps, SATA combines the weight stationary dataflow with the tick-batch dataflow of SpinalFlow. SATA has a much larger size of both the input scratch pad and the weight scratch pad. We will use SATA's energy estimation tool to get an estimation of the energy reduction from our MINT-quantized models. Although these prior SNN accelerator designs vary in their architectural details, they share a common feature: to minimize the data movements of multi-bit partial sums and membrane potentials, they adopt an output-stationary-like dataflow. In these designs, one LIF neuron is mapped to one dedicated PE for the entire input interval, as shown in Figure 7. This design feature implies that the hardware units inside each PE must support the entire LIF operation as shown in Eq. 1-Eq. 3, which means that all prior works [18, 19, 20] have embedded LIF units inside each PE. ### _Impact of Quantization on SNN Accelerator Design_ As discussed in Sec. IV-A, supporting naive uniform quantization on SNNs requires at least one 32-bit floating-point multiplier and several floating-point arithmetic units along the LIF computation datapath. This means that to support uniform quantization on output-stationary-oriented SNN accelerators, we need to add quantization support to all PEs, resulting in each PE having its own full-precision multipliers and other floating-point arithmetic units. This would cause significant overheads at the PE level, especially since the array size in prior designs is at least 128. Although larger PE array size increases throughput, it brings additional hardware cost for uniform quantization of SNNs. Fig. 8 illustrates the difference in area breakdown of the 4-bit version of SpinalFlow [18] before and after adding uniform quantization support to the PEs. Fortunately, our MINT quantization scheme eliminates the need for multipliers and all floating-point arithmetic units Fig. 6: (a) The inference path that shows the use of MINT arithmetic to compute the membrane potential and generate output spikes. (b) The training path illustrates the fake quantization inserted for both weights and membrane potentials to simulate the quantization error that will occur during the inference time. The blue color indicates the integer values or operations and the green indicates the float values or operations. Fig. 7: Illustration of the output-stationary dataflow that is commonly adopted by the prior SNN accelerators inside PEs, saving significant hardware resources for the entire system. ## VII Experiments ### _Experimental Settings_ #### Vii-A1 Software Configuration **Models and datasets.** We choose two representative deep network architectures: VGG-9 [15] and VGG-16 [15]. We evaluate our quantization schemes on two public image-classification datasets: CIFAR-10 [16] and TinyImageNet, which contains 200 classes from the ImageNet dataset [17]. **Baselines.** We use the model trained with 32-bit floating-point (fp32) weights and membrane potentials as our baseline. To validate our quantization scheme, we compare our MINT quantized model of varying precisions to the baseline. Additionally, we compare our quantization scheme with three prior SNN quantization works: ST-Quant [9], ADMM-Quant [10], and STBP-Quant [11]. **Training.** We use the state-of-the-art direct encoding technique [2] to train our SNNs. This method has demonstrated remarkable effectiveness in training BPTT-based SNNs, enabling them to achieve high accuracy with only a few timesteps. Unless otherwise specified, all experiments in the following sections use timesteps \(T\) = 4. We include all the training configurations in Table. III. Additionally, we initialize our shareable quantization scaling \(\alpha\) and scale its gradients with the hyperparameters in [29]. **Implementation.** We implement the SNN training framework for our MINT quantization in PyTorch. We also implement VGG-16 using the CUDA source code to test memory cost and speedup. 2D convolutions and the max-pooling operations are implemented using CuDNN for achieving accurate GPU statistics. To compare the 8-bit quantized model with the full precision baseline, we implement the network with \(\text{CUDNN\_DATA\_INT8}\) and \(\text{CUDNN\_DATA\_FLOAT}\). #### Vii-A2 Hardware Configuration We synthesize all the arithmetic units using Synopsys Design Compiler at 400MHz using 32nm CMOS technology to obtain area, dynamic power, and static power. We use CACTI [30] to simulate on-chip SRAM and off-chip DRAM to obtain memory statistics. We also build a PyTorch-based simulator to estimate latency and energy based on standard modeling strategies [19, 20, 31]. To evaluate our quantization scheme and other quantization methods on existing SNN hardware systems, we synthesize [18, 19] from scratch, all architecture configurations identical to the original work. The only changes we make are adjusting the operand sizes of the arithmetic units according to the bit-width of the weights and membrane potentials. Additionally, we synthesize another version with the PE arrays supporting the naive uniform quantization (adding 32-bit multipliers and using floating-point LIF units). We perform energy estimation using SATA tool [20]. ### _Experimental Results_ #### Vii-B1 Accuracy and Convergence Table. IV summarizes the accuracy of MINT quantization scheme for various combinations of weight and membrane potential precision for different SNN models and datasets. For instance, w8u8 represents a network with both weights and membrane potentials quantized to 8 bits using MINT quantization. The fp32 represents the full-precision baseline. Although the fp32 baseline achieves the highest accuracy for most of the datasets and networks, MINT achieves a similar level of accuracy while significantly reducing the memory footprint of the models. On the CIFAR10 dataset, the accuracy of the relatively shallow VGG-9 network does not drop significantly even when both weights and membrane potentials are compressed to 2-bit precision. This result suggests that very low bit-width integer operations can achieve similar accuracy as the full-precision floating-point baseline on small SNN networks. On the other hand, the accuracy of the VGG-16 network drops Fig. 8: Area breakup of (a) 4-bit Spinalflow without naive uniform quantization supports and (b) with naive uniform quantization supports monotonically with the decreasing precision of weights and membrane potentials. However, even at w2u2 precision, the accuracy of the quantized network remains very close to the fp32 baseline, with less than 0.6% top-1 accuracy drop. On the more challenging TinyImageNet dataset, we observe an accuracy drop at the precision of w2u2 for the VGG-9 network. However, the accuracy drop remains within an acceptable range (less than 1.5% compared to fp32 baseline). Remarkably, MINT achieves higher accuracy than the full-precision baseline on the VGG-16 network, suggesting that our method may serve the purpose of regularization. #### Iv-B2 Memory Saving and Speedup Memory Saving.In this section, we first present the memory footprint reduction of our quantization scheme with different precision combinations of weights and membrane potentials, as shown in Fig. 9, using a batch size of one. We observe a reduction in memory usage proportional to the reduction in weight precision compared to the fp32 baseline. For instance, our w2u2 VGG-16 model compresses approximately 93.8% of the memory footprint from the fp32 baseline. Therefore, with a batch size of one, the model size reduction primarily comes from weight quantization. However, to improve inference speed, prior works [2, 4, 5, 6, 7] commonly use mini-batch sizes larger than 1. In such cases, membrane potential quantization becomes important. We illustrate the importance of membrane potential quantization in Fig. 10. When a single batch size is used, we observe that solely quantizing the weight to 4 bits and leaving the membrane potential at full precision can still achieve approximately 70% memory reduction from the fp32 VGG-16 baseline on TinyImageNet. However, with a batch size of 4, the 4-bit weight quantization without the membrane potential quantization can only reduce around 40% of the total memory footprint of the baseline. Moreover, with a batch size of 16, the 4-bit weight quantization can only compress the total memory footprint by 15%, while quantizing the membrane potential to 4 bits can further reduce 72.4% of the total memory footprint. Please note that, for visualization purposes, we only illustrate the importance of membrane potential using a relatively small batch size (16). However, a batch size that is larger than 50 is very commonly used in prior SNN works [2, 4, 5, 6, 7] while keeping the membrane potentials at full precision. Thus, we emphasize the importance of membrane potential quantization in this work. Speedup.In Fig. 11, we present the layerwise inference latency of our quantization scheme at w8u8 precision compared to the fp32 baseline for VGG-16 on CIFAR-10 and TinyImageNet, tested on two different CUDA devices: RTX-2080Ti and NVIDIA A100. Overall, we observe a trend of faster inference with the 8-bit quantized model across all devices. Specifically, we find that the int8 model consistently runs faster than the fp32 baseline on the first two layers, while also demonstrating a significant acceleration on the last three layers in most cases. MINT achieves an overall acceleration of 4.5%(9.1%) for CIFAR-10(TinyImageNet) on RTX-2080Ti and 6.2%(17.4%) on A100. Overall, we observe that the larger the input image, the more significant the acceleration, and that A100 provides better support for int8 inference, leading to greater benefits from int8 operations. (\(T=8\) for all methods) when making the comparison. We used the same number of mini-batches as the prior works when comparing the total memory footprint (50 for STBP-Quant and ADMM-Quant, and 32 for ST-Quant). The prior works used a high precision of membrane potential, which incurs more memory cost when mini-batches are used. We quantized the membrane potential to the same precision as the weights to adopt our multiplier-less integer quantization scheme and save more memory. We show the comparison results in Table. V. In general, our quantization scheme is the first to consider compressing both the weights and membrane potentials to a very low precision (less than 8 bits) while preserving very similar accuracy with the state-of-the-art baseline. At 8-bit, 4-bit, and 2-bit weight quantization, we consistently outperformed STBP-Quant, another prior SNN quantization work that considered membrane potential quantization. STBP-Quant achieved low accuracy of 33.5% at w2u8 precision, while our work retained accuracy at 88.4% with both membrane potential and weight quantized to 2 bits. When compared with the full-precision membrane potential baseline, our quantization scheme encounters an acceptable level of accuracy degradation (-0.84% to -1.28%) across 8-bit, 5-bit, 4-bit, and 2-bit weight quantization. This is because the full-precision membrane potential can to some extent help alleviate the information loss brought by weight quantization. However, we achieved significant memory footprint reduction by quantizing the weights and membrane potential simultaneously. On average, our quantized SNN models only require 2.8% of the total memory footprint of ADMM-Quant and 8% of ST-Quant. Furthermore, for the baseline with the highest accuracy, ADMM-Quant, quantization scaling (Eq. 5) has been used to compensate for the quantization error. As we discussed in Sec. IV-A, quantization scaling would require high precision multipliers and floating-point arithmetic units, which incur high hardware costs on SNN systems (Sec. VI-B). Our method, on the other hand, does not require any multipliers or floating-point units for scaling and thus will receive more hardware benefits at deployment time. We will discuss more hardware benefits of our method in the next section. ### _Evaluation on Existing Hardware Systems_ In this section, we demonstrate the hardware benefits of our MINT quantization scheme. We evaluate our method on SpinalFlow [18] and PTB [19], with a focus on the PE-array level analysis. The PE-array level evaluation measures the PE-array area, dynamic power, and static power. We divide this evaluation process into two categories: **scale vs. non-scale** and **high-precision vs. low-precision**. In the **scale vs. non-scale** evaluation, we compare the PE-array level evaluation results at the same operand bit-width, between our method (high accuracy without multipliers and fully integer) and ADMM-Quant [10] (highest accuracy but requires multipliers for quantization scaling and not fully integer). For the **high-precision vs. low-precision**, we compare the PE-array level evaluation results at different operand sizes between our method (fully integer and multiplier-less that achieves high accuracy with small operand size) and STBP-Quant [11] (fully integer and does not require multipliers, but achieves reasonable accuracy only with large operand size). Additionally, we evaluate our quantization scheme on SATA [20] to estimate the total forward energy consumption from the system level. Fig. 11: Layer-wise speedup results for VGG-16 using int8 weight and membrane potential precision compared to fp32 precisions on CIFAR10 and TinyImageNet. Results are shown for RTX 2080Ti (a) and A100 (b) GPUs. #### Vii-C1 Evaluation on SpinalFlow and PTB **Scale vs. non-scale:** Although our quantization scheme has slightly lower accuracy performance than ADMM-Quant (on average \(-1.1\%\)), our hardware deployment cost is much lower compared to ADMM-Quant on both SpinalFlow and PTB. In Fig. 12, we show the PE-array level comparison results between ADMM-Quant and our quantization scheme on both SpinalFlow and PTB. We first evaluate the area, dynamic power, and static power of the PE array between our methods and ADMM-Quant with full precision membrane potential (admm-Ufp). We find that the PE array implemented with our quantization scheme saves 76% (93%), 86% (95%), and 93% (96%) total PE-array area with weights of 8 bits, 4 bits, and 2 bits on SpinalFlow (PTB), respectively. Furthermore, our method reduces the dynamic power cost of ADMM-Quant by 84%, 96%, and 98% on SpinalFlow and 94%, 94%, and 95% on PTB across different weight precisions. The static power cost reduction follows a similar trend as the dynamic power on both hardware systems. We further assume that ADMM-Quant will work with membrane potential quantized to the same precision as the weights (admm-Uq) and re-compare it with our quantization scheme. It turns out that the trend of reduction still holds. This observation suggests that inserting full-precision multipliers and floating-point arithmetic units into each PE will hurt the overall PE-array level performance significantly. **High-Precision vs. Low-Precision** We further compare our quantization scheme with STBP-Quant, which produces a fully integer quantized network without the use of scaling in the quantizer. We evaluate the CIFAR-10 accuracy trends of both methods as we reduce the operand size of the processing element (PE) array from w8 to w5, w4, and w2. In Fig. 13, we present the accuracy vs. PE-array area results obtained with both methods on SpinalFlow. Our method achieves high accuracy while scaling down the total PE-array area by approximately 80%. On the other hand, STBP-Quant exhibits accuracy degradation of more than 50% during the PE-array scaling down. We observe similar trends on PTB. #### Vii-C2 Evaluation on SATA We use SATA [20] to study the total inference energy difference across different precisions of weights and membrane potentials. The result is presented in Fig. 14. As our MINT quantization does not introduce any hardware overheads to the processing element (PE), the computation energy and memory movement energy scale down linearly with the operands' precisions. We observe that our w2u2 VGG-9 network achieves an approximately 87.3% total inference energy reduction on a single image of CIFAR-10 when compared to the one with 16-bit weights and membrane potentials. ## VIII Ablation Studies #### Vi-1 Study on Spike Sparsity We investigate the spike activity of our MINT-quantized model by measuring the average spike Fig. 14: Normalized computation and memory energy cost for our MINT-quantized VGG-9 SNN models with different weight and membrane potential precision on CIFAR-10. Fig. 12: Comparisons of area, dynamic power, and static power between our method and two baseline methods: ADMM-Quant with full precision membrane potential (admm-Ufp), and ADMM-Quant with quantized membrane potential (admm-Uq). Fig. 13: CIFAR-10 accuracy vs. PE-array area on SpinalFlow and PTB for STBP-Quant and our MINT quantization. sparsity for the network. This is done by computing the average spike sparsity across all inputs and all timesteps. For example, for a 4-timestep SNN, a 92% sparsity indicates that each LIF neuron is expected to spike only \((1-0.92)*4=0.32\) times throughout the inference. We compare the average spike sparsity of our MINT-quantized VGG-9 models on CIFAR-10 with other state-of-the-art full-precision SNN works. The results show that our MINT quantization does not incur any sparsity reduction. By maintaining the same level of high spike sparsity as other SNN works, our quantized models can enjoy the same amount of computation energy reduction [4, 20, 32, 33]. #### V-C2 Study on Reset Mode We further investigate the effects of different LIF reset modes on our MINT quantization scheme by comparing the hard reset mode, which is used in MINT, with the soft reset mode, a popular reset mode used in many prior SNN works [9, 35]. In Fig. 16, we observe that the w2u2 VGG-16 model trained with the hard reset mode has better training accuracy and convergence speed than the one trained with the soft reset mode on CIFAR-10. Although our MINT quantization scheme currently uses the hard reset mode, we note that it also supports the soft reset mode. To implement the soft reset LIF in MINT, we simply replace the \(0\) in line 5 of Alg. 1 with \((H_{l}^{t}-v_{th})\). ## IX Conclusion In this paper, we have introduced multiplier-less integer-based (MINT) quantization for both the weights and the membrane potentials of SNNs. By sharing the quantization scale between the weights and membrane potentials and transforming the LIF update equations, we are able to significantly compress the memory footprint of SNNs while dodging all the hardware overheads brought by the original uniform quantization. Our method achieves comparable accuracy to full-precision baselines and other state-of-the-art SNN quantization methods. At the same time, our method achieves a smaller memory footprint by quantizing the membrane potential, which is a memory-hungry quantity that has been mostly neglected in prior works. Our MINT method also achieves huge hardware resource reduction at deployment time on several existing SNN hardware platforms due to the elimination of multipliers and floating-point units. In conclusion, our proposed MINT quantization method offers a practical and effective solution for reducing the memory footprint and hardware resource requirements of SNNs without sacrificing accuracy. Our method has the potential to enable the deployment of large-scale SNNs on resource-constrained devices, opening up new possibilities for SNN-based edge computing. ## X Acknowledgements We thank our reviewers for their valuable feedback. This work was supported in part by CoCoSys, a JUMP2.0 center sponsored by DARPA and SRC, Google Research Scholar Award, the National Science Foundation CAREER Award, TII (Abu Dhabi), the DARPA AI Exploration (AIE) program, and the DoE MMICC center SEA-CROGS (Award #DE-SC0023198).
2310.11271
Error analysis for hybrid finite element/neural network discretizations
We describe and analyze a hybrid finite element/neural network method for predicting solutions of partial differential equations. The methodology is designed for obtaining fine scale fluctuations from neural networks in a local manner. The network is capable of locally correcting a coarse finite element solution towards a fine solution taking the source term and the coarse approximation as input. Key observation is the dependency between quality of predictions and the size of training set which consists of different source terms and corresponding fine & coarse solutions. We provide the a priori error analysis of the method together with the stability analysis of the neural network. The numerical experiments confirm the capability of the network predicting fine finite element solutions. We also illustrate the generalization of the method to problems where test and training domains differ from each other.
Uladzislau Kapustsin, Utku Kaya, Thomas Richter
2023-10-17T13:45:01Z
http://arxiv.org/abs/2310.11271v1
# Error analysis for hybrid finite element/neural network discretizations ###### Abstract We describe and analyze a hybrid finite element/neural network method for predicting solutions of partial differential equations. The methodology is designed for obtaining fine scale fluctuations from neural networks in a local manner. The network is capable of locally correcting a coarse finite element solution towards a fine solution taking the source term and the coarse approximation as input. Key observation is the dependency between quality of predictions and the size of training set which consists of different source terms and corresponding fine & coarse solutions. We provide the a priori error analysis of the method together with the stability analysis of the neural network. The numerical experiments confirm the capability of the network predicting fine finite element solutions. We also illustrate the generalization of the method to problems where test and training domains differ from each other. Keywords:Neural networks PDE approximation Finite element method Msc: 65Y10 65N12 65N30 ## 1 Introduction and motivation The use of neural networks to approximate solutions to partial differential equations has made considerable progress in recent years. In particular the class of Physics Inspired Neural Networks (PINN) [27], like the Deep Ritz method, has been investigated intensely [8]. Especially for high dimensional problems [18; 4; 9] or parameter dependent partial differential equations [1] these approaches offer a new point of view and promise a substantial increase in efficiency. There are further methods in the literature which exploit the weak formulations of the PDEs [14] or incorporate finite element (FE) spaces in the loss function [2; 22; 24]. See [28] for a review. However, when standard problems such as three dimensional fluid mechanics are considered, neural network based approaches have to compete with highly sophisticated and refined classical discretization methods. Finally, the training of the network often remains the crucial problem. Even though the theoretical approximation properties of neural networks may be superior, the efficient solution of the associated optimization problems is still an open problem. On the other hand, there are highly efficient Newton-Krylov space methods, possibly with optimal multigrid methods for preconditioning. The main drawback of simple PINN's is the need to re-train when the problem parameters change. DeepONet [17] is one approach to this issue. Here, instead of training one net to represent a specific problem, two nets are used to represent possible solutions as well as the solution operator. But even this approach could not yet prove the efficiency and accuracy of established methods. An alternative approach we follow is to combine established methods for coarse representation of a solution with a neural network to resolve fine scales whose representation is often not possible. This approach has many potential applications, for example in fluid mechanics, where finite element or finite volume methods can reproduce the coarse structure with great accuracy while respecting conservation principles, but simultaneous resolution of fine-scale turbulent processes is often not possible or would simply be too expensive. A super-resolution methodology in this direction was introduced in [11]. With the _Deep Neural Network Multigrid Solver_ (DNN-MG) [21; 19; 20] we have introduced a concept which embeds a neural network fluently into a multigrid hierarchy, solves the coarse grid levels directly, e.g. with a finite element multigrid method, and predicts the corrections on fine grid levels locally by a neural network. An application to stationary linear problems including a simplified error analysis of this hybrid approach has been studied in our preliminary work [12]. Here, the neural network intervenes only locally: the grid is decomposed into patches, e.g., in 2d a range of \(p\times p\) (\(p\in\mathbb{N}\) is small here, usually less than four) elements, and on each of these patches the correction to a finer solution is pulled from the network. This approach was shown to increase efficiency for standard flow problems compared to established methods. Furthermore, the local design, i.e. the application of a mesh to all patches, allows a very good generalizability. The DNN-MG solver can be regarded as a numerical solution method in the sense of a domain decomposition method rather than an approximation method. The network never sees the whole solution but always only small sections. The mathematical analysis of PINNs is already well advanced. In particular, the aspect of approximation with neural networks is very well established, starting with the universal approximation theorem in the late 80s [3; 6]. Especially for the application to partial differential equations relevant results are available [10; 18; 25] and optimal estimates in \(W^{n,p}\)-spaces are known, see [7] for a review neural network's approximation properties. Of the PINNs, the Deep Ritz method [8] in particular is well studied. It is based on the direct approximation of the energy functional (in the case of symmetric differential operators, e.g., Laplace or Stokes) with neural networks and Monte Carlo integration. Here, quite comprehensive a priori [25] as well as a posteriori error estimation are available [23]. The goal of this work is to investigate hybrid approaches that enrich a finite element solution on coarse grids with fine scale fluctuations from a neural network in terms of the DNN-MG method. We restrict ourselves to the simple linear Poisson equation and give the complete a priori error analysis of the hybrid method. In the next section we will briefly describe the finite element discretization and introduce some notation. Section 3 then introduces the hybrid approximation method and describes the training of the neural networks. We start the analysis of the method with the version where global network updates are used and then refine the a priori analysis for the local neural network updates. Numerical demonstrations follow in Section 4. ## 2 Preliminaries We start with describing the model problem and then introduce the notation and finite element discretization. Let \(\Omega\subset\mathbb{R}^{d},\ d\in\{2,3\}\) be a domain with polygonal boundary. For \(f\in H^{-1}(\Omega)\) let \(u\in H^{1}_{0}(\Omega)\) be the weak solution to the Poisson equation \[-\Delta u=f,\quad u|_{\partial\Omega}=0. \tag{1}\] ### Finite element discretization By \(\Omega_{h}\) we denote a finite element mesh of the domain \(\Omega\), where \(h\) stands for the diameter of the largest cell. For simplicity we assume that \(\Omega_{h}\) is a simplical mesh that satisfies the common assumptions of structural regularity and shape regularity [5]. We assume that there is a hierarchy of finite element meshes \[\Omega_{H}:=\Omega_{0}\preccurlyeq\Omega_{1}\prec\cdots\preccurlyeq\Omega_{L}=: \Omega_{h}, \tag{2}\] where we denote by \(\Omega_{l-1}\preccurlyeq\Omega_{l}\), that each element of the fine mesh \(T\in\Omega_{l}\) originates from the uniform refinement of a coarse element \(T^{\prime}\in\Omega_{l-1}\), for instance, uniform splitting of a quadrilateral or triangular element into four and of a hexahedral or tetrahedral element into eight smaller ones, respectively. On \(\Omega_{h}\) let \(V_{h}\) be the space of piecewise polynomials of degree \(r\geq 1\) satisfying the homogeneous Dirichlet condition on the boundary \(\partial\Omega\) \[V_{h}:=\left\{\phi\in C(\bar{\Omega}),\ \phi|_{T}\in P^{(r)}(T)\ \forall T\in \Omega_{h},\ \phi|_{\partial\Omega}=0\right\}\] where \(P^{(r)}(T)\) is the space of polynomials of degree \(r\) on a cell \(T\in\Omega_{h}\). On the hierarchy of meshes (2) we hence define the hierarchy of spaces \(V_{h}^{(l)}\) on \(\Omega_{l}\) for \(l=0,\ldots,L\). These spaces are nested \[V_{h}^{(l-1)}\subset V_{h}^{(l)},\quad l=1,\ldots,L.\] If not necessary for understanding of the specific context, we will skip the index \(l\) referring to the mesh level. Then, \(u_{h}\in V_{h}\) is the finite element solution to \[(\nabla u_{h},\nabla\phi_{h})=(f,\phi_{h})\quad\forall\phi_{h}\in V_{h}, \tag{3}\] with the \(L^{2}\) inner product \((\cdot,\cdot)\). For two right hand sides \(f,g\in H^{-1}(\Omega)\) and the corresponding finite element solutions \(u_{h}^{f},u_{h}^{g}\in V_{h}\) it holds \[\|\nabla(u_{h}^{f}-u_{h}^{g})\|_{L^{2}(\Omega)}=\|f-g\|_{H^{-1}(\Omega)} \tag{4}\] Given sufficient regularity of the right hand side, namely \(f\in H^{r-1}(\Omega)\) (using for simplicity the notation \(H^{0}(\Omega):=L^{2}(\Omega)\)) and of the domain, either having a \(C^{r+1}\)-boundary or, in the case \(r=1\) being convex, the standard a priori error estimate \[\|u-u_{h}\|_{L^{2}(\Omega)}+h\|\nabla(u-u_{h})\|_{L^{2}(\Omega)}\leq ch^{r+1}\|f \|_{H^{r-1}(\Omega)} \tag{5}\] holds. ### Notation Over subdomains \(\omega\subseteq\Omega\) the \(L^{2}-\) and \(H^{s}-\) norms are denoted by \(\|\cdot\|_{\omega}\) and \(\|\cdot\|_{s,\omega}\), respectively. We omit the index \(\omega\), if the norm is considered on the whole domain \(\Omega\). With \(\|\cdot\|_{2}\) we denote the Euclidean norm for vectors and the spectral norm for matrices. With \(X_{\omega}^{h}\) and \(X_{\omega}^{H}\) we denote the nodes of the meshes \(\Omega_{h}\) and \(\Omega_{H}\) that lie in the subdomain \(\omega\), respectively. Moreover, for \(v\in C(\overline{\omega})\) we define \[\|v\|_{L^{2}(\omega)}:=\Big{(}\sum_{x\in X_{\omega}^{h}}v(x)^{2}\Big{)}^{\frac {1}{2}}. \tag{6}\] Definition 1 (Patch): A patch \(\mathcal{P}\in\Omega_{h}\) is defined to be a subdomain that is geometrically identical to one certain cell \(M\) of the coarse mesh \(\Omega_{H}\). We exploit that a patch is not only identified with the degrees of freedoms of the element \(M\) but also by the cells assembling it, \(\mathcal{P}=\{T\in\Omega_{h}\ :T\subset M\}\). By \(V_{\mathcal{P}}\) we denote the local finite element subspace \[V_{\mathcal{P}}:=\text{span}\left\{\phi_{h}|_{\mathcal{P}},\ \phi_{h}\in V_{h} \right\}.\] By \(R_{\mathcal{P}}:V_{h}\to V_{\mathcal{P}}\) we denote the restriction to the local patch space, defined via \[R_{\mathcal{P}}(u_{h})(x)=u_{h}(x)\quad\forall x\in X_{\mathcal{P}}^{h}.\] By \(P_{\mathcal{P}}:V_{\mathcal{P}}\to V_{h}\) we denote the prolongation defined by \[P_{\mathcal{P}}(u_{\mathcal{P}})(x)=\begin{cases}\frac{1}{n(x)}u_{\mathcal{P} }(x)&x\in X^{h},\\ 0&\text{otherwise},\end{cases}\] where \(n(x)\in\mathbb{N}\) is the number of patches that contain the degree of freedom \(x\). ## 3 Hybrid finite element neural network discretization Consider two finite dimensional spaces \(V_{H}\) and \(V_{h}\) that are built on coarse and fine meshes \(\Omega_{h}\) and \(\Omega_{H}\), respectively. The idea of the paper is to determine an approximate solution on the coarse mesh \(\Omega_{H}\) with the finite element method and then to obtain the fine mesh fluctuations in forms of neural network updates. In other words, we seek hybrid solutions \(u_{\mathcal{N}}\) which are found by augmenting \(u_{H}\in V_{H}\) with a neural network update \(w_{\mathcal{N}}\in V_{h}\), i.e. \[u_{\mathcal{N}}:=u_{H}+w_{\mathcal{N}}\in V_{h}.\] The neural network predicts the finite element coefficients on the fine mesh \(\Omega_{h}\) and as input it receives all data that is available: the coarse solution \(u_{H}\in V_{H}\), the problem data, i.e. the source term \(f\). The output \(\mathcal{N}(u_{H},f)\) is a vector, which determines the coefficients of \(w_{\mathcal{N}}\in V_{h}\). Moreover, these updates are to be obtained locally in such a way that the network is not acting on the aforementioned data on the whole domain \(\Omega\). Instead the network acts on the patches \(\mathcal{P}\) separately in order to obtain the values of an update \(w_{\mathcal{N}}|_{\mathcal{P}}\) by providing the coefficient vector \(\mathcal{N}(u_{H}|_{\mathcal{P}},f|_{\mathcal{P}})\) of \(V_{\mathcal{P}}\). An illustration of the local updates is given in Fig. 1. Definition 2 (Hybrid solution): Given a subdivision of the domain \(\Omega\) into a set of patches, a neural network function \(\mathcal{N}(\cdot)\) acting on each patch and the coarse mesh solution \(u_{H}\in V_{H}\), we define the hybrid solution \(u_{\mathcal{N}}\in V_{h}\) as \[u_{\mathcal{N}}:=u_{H}+\sum_{\mathcal{P}}P_{\mathcal{P}}w_{N}^{\mathcal{P}},\] where \(w_{N}^{\mathcal{P}}=\sum_{i=1}^{N_{dof}}\mathcal{N}(R_{\mathcal{P}}u_{H},R_{ \mathcal{P}}f)_{i}\phi_{i}^{\mathcal{P}}\). Here, \(\mathcal{N}(R_{\mathcal{P}}u_{H},R_{\mathcal{P}}f)_{i}\) is the \(i\)-th output of the network and \(\phi_{i}^{\mathcal{P}},\;i\in\{1,\cdots,N_{dof}\}\) are the basis functions of \(V_{\mathcal{P}}\). As networks we will only consider fully connected multilayer perceptrons: Definition 3 (Multilayer perceptron): The function \(\mathcal{N}:\mathbb{R}^{N_{0}}\rightarrow\mathbb{R}^{N_{L}}\) defined via \[\mathcal{N}=l_{L}\circ\sigma\circ l_{L-1}\circ\cdots\circ\sigma\circ l_{1} \tag{7}\] is called a _multilayer perceptron (MLP)_ of _depth_\(L\in\mathbb{N}\) with an _activation function_\(\sigma:\mathbb{R}\rightarrow\mathbb{R}\). The \(l_{i}(x):\mathbb{R}^{N_{i-1}}\rightarrow\mathbb{R}^{N_{i}}\) are called _layers_ and defined as \[l_{i}(x)=W_{i}x+b_{i},\;i=1,\ldots,L \tag{8}\] Figure 1: Illustration of the hybrid solver. The finite element solution \(u_{H}\) is approximated on the coarse mesh (left). On each patch (one or multiple elements) this solution is locally extracted and interpolated into a refined mesh. Together with the fine mesh right hand side information \(f_{h}\) it is the input of a neural network. The output \(w_{\mathcal{N}}\) is the local correction towards an improved solution and is prolongated back onto the fine global mesh. where \(W_{i}\in\mathbb{R}^{N_{i-1}\times N_{i}}\) are _weights_ and \(b_{i}\in\mathbb{R}^{N_{i}}\) are _biases_. The input to the neural network (on each patch) is a vector \(x_{\mathcal{P}}\in\mathbb{R}^{N_{0}}\) and we decompose it into \(x_{\mathcal{P}}=(x_{\mathcal{P}}^{u_{H}},x_{\mathcal{P}}^{f})\), where \[x_{\mathcal{P}}^{u_{H}}=\big{(}R_{\mathcal{P}}u_{H}(x)\big{)}_{x\in X_{ \mathcal{P}}^{H}}\;,\quad x_{\mathcal{P}}^{f}=\big{(}R_{\mathcal{P}}f(x)\big{)} _{x\in X_{\mathcal{P}}^{h}}\;. \tag{9}\] ### Training of the neural network Now, let's explain how we pre-train a neural network \(\mathcal{N}\). First of all, it is necessary to select a set of training problems. We generate the training data by selecting a set \(\mathcal{F}\subset H^{-1}(\Omega)\) of right hand side functions \(f\). Then, we solve the Poisson equation for each \(f\in\mathcal{F}\) for both coarse and fine meshes \(\Omega_{H}\) and \(\Omega_{h}\), respectively. The input data is evaluated as described in (9). The output data \(z_{\mathcal{P}}\in\mathbb{R}^{N_{L}}\) is given as \[z_{\mathcal{P}}=\big{(}u_{h}(x)-u_{H}(x)\big{)}_{x\in X_{\mathcal{P}}^{h}}^{T}\] which is simply a difference between fine and coarse solution on each fine mesh node \(x\) belonging to the patch \(\mathcal{P}\). We would like to underline that the network update of the solution \(w_{\mathcal{N}}\) is given by the value of the network applied not globally to the whole domain \(\Omega\), but locally to each patch \(\mathcal{P}\) (see Definition 1). Once the training data is available, we need to solve the following optimization problem \[\min_{\begin{subarray}{c}W_{i}\in\mathbb{R}^{N_{i-1},N_{i}},b_{i}\in\mathbb{R }^{N_{i}},\\ i\in\{0,\ldots,L\}\end{subarray}}\quad\frac{1}{N_{T}N_{\mathcal{P}}}\sum_{ \mathcal{P}}\lVert z_{\mathcal{P}}-\mathcal{N}(y_{\mathcal{P}})\rVert_{2}^{2} \tag{10}\] where \(N_{T}\) is the number of source terms in the training set \(\mathcal{F}\) and \(N_{\mathcal{P}}\) is the number of patches. In order to solve this problem we use one of the stochastic gradient descent based methods. After the network has been trained, we can finally apply it to other problems that were not in the training data. For this, firstly we again construct input data in the same way as described above and compute network Figure 2: Multilayer perceptron predictions. Then, we construct a complete network solution \(u_{\mathcal{N}}\) by summing up (and averaging) these predictions as described in Definition 2. Considering everything we have developed so far from the finite element perspective we note that each coarse solution \(u_{H}\in V_{H}\) also belongs to \(V_{h}\) and there it takes the form \[u_{H}=\sum_{i=1}^{N_{\mathit{dof}}}U_{h}^{i}\phi_{h}^{i}\] where \(\{\phi_{h}^{i}\}_{i=1}^{N_{\mathit{dof}}}\) is the basis of the fine finite element space \(V_{h}\) and where \(U_{h}^{i}\in\mathbb{R}\) are corresponding coefficients. As a consequence of the fact that, we update the coarse solution \(u_{H}\) only on fine mesh nodes, we can consider this whole procedure as a simple update of fine mesh coefficients \(U_{h}^{i}\), i.e. \[u_{\mathcal{N}}=\sum_{i=1}^{N_{\mathit{dof}}}(U_{h}^{i}+W_{\mathcal{N}}^{i}) \phi_{h}^{i}\in V_{h}.\] ### Error estimate using a global network update We will start with a simplified setting, where there is only one patch that covers the complete domain, \(\mathcal{P}=\Omega_{h}\), compare Definition 1. Here, the hybrid finite element solution is directly given by \[u_{\mathcal{N}}=u_{H}+\mathcal{N}(R_{\Omega_{h}}u_{H},R_{\Omega_{h}}f).\] For brevity of notation we simply write \(u_{\mathcal{N}}=u_{H}+\mathcal{N}(f)\), implicitly assuming that the network also receives values of the coarse mesh solution \(u_{H}\in V_{H}\) corresponding to \(f\) as an input. Theorem 3.1 (A priori finite element error for the single-patch solution): _Let \(\mathcal{N}\) be the network trained on the training set \(\mathcal{F}=\{f_{1},\ldots,f_{N_{T}}\}\) such that the loss function (10) is reduced to the error order of \(\epsilon^{2}\). For \(f\in H^{r-1}(\Omega)\), let \(u\in H^{r+1}(\Omega)\cap H_{0}^{1}(\Omega)\) be the solution to the Poisson problem, \(u_{H}\in V_{H}\) be the coarse finite element approximation of polynomial degree \(r\geq 1\) and \(u_{\mathcal{N}}=u_{H}+\mathcal{N}(f)\in V_{h}\) be the hybrid solution. It holds_ \[\|\nabla(u-u_{\mathcal{N}})\|\leq C\left(h^{r}\|f\|_{r-1}+\min_{f_{i}\in \mathcal{F}}\left\{\|f-f_{i}\|_{-1}+\|\nabla(\mathcal{N}(f)-\mathcal{N}(f_{i} ))\|\right\}+\epsilon\right),\] _where \(h<H\) is the mesh size of the fine space \(V_{h}\) and \(\epsilon\) is the network approximation and training error for the training data set._ Proof: For arbitrary \(f_{i}\in\mathcal{F}\) we split the error \[\|\nabla(u-u_{\mathcal{N}})\|\leq\underbrace{\|\nabla(u-u_{h})\|}_{=(I)}+ \underbrace{\|\nabla(u_{h}-u_{h}^{f_{i}})\|}_{=(II)}+\underbrace{\|\nabla(u_{ h}^{f_{i}}-u_{\mathcal{N}}^{f_{i}})\|}_{=(III)}+\underbrace{\|\nabla(u_{\mathcal{N}}^{f_{i}}-u_{ \mathcal{N}})\|}_{=(IV)}\] into the fine mesh finite element error \[(I)=\|\nabla(u-u_{h})\|\leq Ch^{r}\|f\|_{r-1},\] where \(u_{h}\in V_{h}\) is the finite element solution in the resolved space to the right hand side \(f\). Next, into the data approximation error \[(II)=\|\nabla(u_{h}-u_{h}^{f_{i}})\|\leq\|f-f_{i}\|_{-1},\] where \(u_{h}^{f_{i}}\in V_{h}\) is the fine finite element solution to an arbitrary \(f_{i}\in\mathcal{F}\) from the training data set and into the network approximation and optimization error \[(III)=\|\nabla(u_{h}^{f_{i}}-u_{\mathcal{N}}^{f_{i}})\|\leq C\epsilon.\] Finally, using the composition \(u_{\mathcal{N}}=u_{H}+\mathcal{N}(f)\), the generalization error of the network and a further error term depending on the richness of the data set remains \[(IV)=\|\nabla(u_{\mathcal{N}}^{f_{i}}-u_{\mathcal{N}})\| \leq\|\nabla(u_{H}^{f_{i}}-u_{H})\|+\|\nabla(\mathcal{N}(f_{i})- \mathcal{N}(f))\|\] \[\leq\|f-f_{i}\|_{-1}+\|\nabla(\mathcal{N}(f_{i})-\mathcal{N}(f))\|.\] Combining the above gives the result. This lemma shows that the hybrid approach is able to reduce the error up to the accuracy of the fine finite element space \(V_{h}\), the tolerance of the neural network training, the richness of the training data set \(\mathcal{F}\) and the stability of the neural network that governs it ability to generalize beyond the training data set. This last term \[\|\nabla(\mathcal{N}(f_{i})-\mathcal{N}(f))\|\] will depend on the design of the neural network and it will be investigated in Section 3.4. ### Error estimates for local neural network updates We now tend to the discussion of a local application of the neural network. The global analysis in Section 3.2 is still valid, if the domain \(\Omega^{tr}\), where the training data is generated and the domain \(\Omega\), where the actual simulation is run are the same and if the same meshes are used. The localized approach will however allow us for more flexibility when it comes to choosing an approximation of the right hand side to one of the training data \(f\approx f_{i}\), as this can be done individually on each patch. Furthermore, if we allow for a generalization of the domains, i.e. \(\Omega\neq\Omega^{tr}\) the analysis also must be refined. To keep the notation simple, we will make the following assumptions on the meshes, see also Fig. 3. Assumption (Uniform compatability of meshes and patches)Let \(\Omega\) be the domain of application with meshes \(\Omega_{h}\) and \(\Omega_{H}\). By \(\Omega^{tr}\) we denote the domain where the training data is generated and by \(\Omega_{h}^{tr}\) and \(\Omega_{H}^{tr}\) the corresponding meshes. We assume that the patches \(\{\mathcal{P}_{1},\ldots,\mathcal{P}_{N_{\mathcal{P}}}\}\) of \(\Omega_{h}\) and \(\Omega_{H}\) and the patches \(\{\mathcal{P}_{1}^{tr},\ldots,\mathcal{P}_{N_{\mathcal{P}}^{tr}}^{tr}\}\) are compatible in the following sense: For each \(\mathcal{P}\in\Omega_{h}\), there exists a training patch \(\mathcal{P}^{tr}\in\Omega_{h}^{tr}\) which is a translation and/or rotation of \(\mathcal{P}\). This assumption is restrictive and only allows fully uniform meshes. We refer to Remark 1 for some hints on how the approach can be extended to more general settings. Moreover, for each patch \(\mathcal{P}\in\Omega_{h}\) we define an enlarged domain \(\tilde{\mathcal{P}}\) with \(\mathcal{P}\subset\subset\tilde{\mathcal{P}}\) that could be the union of all patches \(\mathcal{P}^{\prime}\in\Omega_{h}\) that overlap with \(\mathcal{P}\), i.e. \[\tilde{\mathcal{P}}:=\bigcup_{\begin{subarray}{c}\mathcal{P}^{\prime}\in \Omega_{h}\\ \tilde{\mathcal{P}}^{\prime}\cap\tilde{\mathcal{P}}\neq\emptyset\end{subarray}} \mathcal{P}^{\prime} \tag{11}\] For the distance between \(\mathcal{P}\) and \(\partial\tilde{\mathcal{P}}\setminus\partial\Omega\) it holds \(d(\mathcal{P},\tilde{\mathcal{P}})=\mathrm{dist}(\mathcal{P},\partial\tilde{ \mathcal{P}}\setminus\partial\Omega)=\mathcal{O}(h_{\mathcal{P}})\) where \(h_{\mathcal{P}}\) is the diameter of a patch. This distance is relevant for local error estimates such as (13). Now we present the main result of this paper which we will prove later on. Theorem 2.2 (A priori finite element error for the hybrid solution based on local patches): _For \(f\in H^{r-1}(\Omega)\), let \(u\in H^{r+1}(\Omega)\cap H^{1}_{0}(\Omega)\) be the solution to the Poisson problem, \(u_{H}\in V_{H}\) be the coarse finite element approximation of degree \(r\geq 1\) and \(u^{i}_{H}\in V_{H}\) be the coarse finite element approximation solution that corresponds to \(f_{i}\in L^{2}(\Omega)\), \(i=1,\ldots,N_{T}\). Let Assumption 3.3 be satisfied and \(\mathcal{N}\) be the network trained on the training set_ \[\mathcal{F}_{\mathcal{P}}=\{(f_{1},u^{1}_{H},u^{1}_{h})|_{\mathcal{P}},\ldots, (f_{N_{T}},u^{N_{T}}_{H},u^{N_{T}}_{h})|_{\mathcal{P}}:\mathcal{P}\in\Omega_{ h}\}\] _such that the loss (10) is reduced below the error order of \(\epsilon^{2}\)._ _For the hybrid solution \(u_{\mathcal{N}}=u_{H}+\sum_{\mathcal{P}}P_{\mathcal{P}}\mathcal{N}(f)\in V_{h}\) it holds_ \[\|\nabla(u_{h}-u_{\mathcal{N}})\|\leq c\Big{[}\big{(}h^{r}+H^{2r} \big{)}\|f\|_{r-1}+H^{2r}\max_{1\leq i\leq N_{T}}\|f_{i}\|_{r-1,\Omega^{tr}}\] \[+\Big{(}\sum_{\mathcal{P}\in\Omega_{h}}\min_{1\leq i\leq N_{T}} \Big{\{}\|f\!-\!f_{i}\|^{2}_{-1,\tilde{\mathcal{P}}}\!+\!\|\nabla(u_{H}\!-\!u^ {i}_{H})\|_{\tilde{\mathcal{P}}}^{2}\!+\!\|\nabla(\mathcal{N}(f_{i})\!-\! \mathcal{N}(f))\|_{\mathcal{P}}^{2}\Big{\}}\Big{)}^{\frac{1}{2}}\Big{]}+\epsilon. \tag{12}\] Figure 3: Training and application domains \(\Omega^{tr}\) and \(\Omega\) as well as the corresponding meshes \(\Omega^{tr}_{h}\) and \(\Omega_{h}\) can differ. Both however must be split into the same kind of patches. A patch \(\mathcal{P}\) and the extended patch \(\tilde{\mathcal{P}}\) is marked in both domains in orange and blue, respectively. #### 3.3.1 Local finite element error estimates To prepare the proof to Theorem 2.2 we state several auxiliary estimates. We start by citing an a priori error estimate for the local finite element error. Applied to each patch it holds \[\|\nabla(u-u_{h})\|_{\mathcal{P}}\leq c\Big{(}h^{r}\|u\|_{r+1,\tilde{\mathcal{P} }}+d(\mathcal{P},\tilde{\mathcal{P}})^{-1}\|u-u_{h}\|_{\tilde{\mathcal{P}}} \Big{)}. \tag{13}\] See (26, Theorem 5.1) for details and the proof. The second term in (13) is a local \(L^{2}\) error term which can be further analyzed as follows. For the Poisson problem we consider the adjoint solution \(z\in H^{1}_{0}(\Omega)\) \[-\Delta z=\frac{u-u_{h}}{\|u-u_{h}\|}\chi_{\tilde{\mathcal{P}}}\text{ in }\Omega,\;z=0\text{ on }\partial\Omega,\] where \(\chi_{\tilde{\mathcal{P}}}\) is the characteristic function of \(\tilde{\mathcal{P}}\). Hereby we get \[\|u-u_{h}\|_{\tilde{\mathcal{P}}}\leq ch^{r}\|u\|_{r+1}\cdot h\|\chi_{\tilde{ \mathcal{P}}}\|\leq ch^{r+1}h_{\tilde{\mathcal{P}}}^{\frac{d}{2}}\|u\|_{r+1},\] as \(|\tilde{\mathcal{P}}|^{\frac{1}{2}}=\mathcal{O}(h_{\tilde{\mathcal{P}}}^{ \frac{d}{2}})\). Combination with (13) and noting that \(d(\mathcal{P},\tilde{\mathcal{P}})=\mathcal{O}(h_{\tilde{\mathcal{P}}})\) gives \[\|\nabla(u-u_{h})\|_{\mathcal{P}}\leq ch^{r}\big{(}\|u\|_{r+1,\tilde{\mathcal{ P}}}+h\cdot h_{\mathcal{P}}^{\frac{d}{2}-1}\|u\|_{r+1}\big{)}. \tag{14}\] In addition, we will require local finite element error estimates in Sobolev norms with negative index. Lemma 1 (Local finite element estimates in negative norms): _It holds_ \[\|u-u_{h}\|_{1-r,\mathcal{P}}\leq ch^{2r}\Big{(}\|u\|_{r+1,\tilde{\mathcal{P}} }+h\cdot h_{\mathcal{P}}^{\frac{d}{2}-1}\|u\|_{r+1}\Big{)}. \tag{15}\] Proof: Let \(\psi\in H^{r-1}(\mathcal{P})\) and \(E\psi\in H^{r-1}(\tilde{\mathcal{P}})\) be its natural extension to a smooth domain \(\hat{\mathcal{P}}\) satisfying \(\mathcal{P}\subset\subset\hat{\mathcal{P}}\subset\subset\tilde{\mathcal{P}}\). Further, let \(z\in H^{r+1}(\tilde{\mathcal{P}})\cap H^{1}_{0}(\tilde{\mathcal{P}})\) be the solution to the adjoint problem \[(\phi,E\psi)=(\nabla\phi,\nabla z)_{\tilde{\mathcal{P}}}\quad\forall\phi\in H ^{1}_{0}(\tilde{\mathcal{P}})\] and therefore it satisfies \(\|z\|_{r+1}\leq c\|E\psi\|_{r-1,\tilde{\mathcal{P}}}\leq c\|\psi\|_{r-1, \mathcal{P}}\). Then, we have \[(u-u_{h},\psi)_{\mathcal{P}}\leq\|\nabla(u-u_{h})\|_{\mathcal{P}}ch^{r}\|\psi \|_{r-1,\mathcal{P}},\] which, together with (14) gives (15). #### 3.3.2 Localized finite element solutions The comparison of the solution on the application mesh \(\Omega_{h}\) with training data obtained on \(\Omega_{h}^{tr}\) will be by means of local problems that are defined only on the surrounding of a single patch. Definition 4 (Local problems): Let \(\mathcal{P}\subset\subset\tilde{\mathcal{P}}\) be a patch and a slightly enlarged domain matching the mesh \(\Omega_{h}\). By \(V_{h}(\tilde{\mathcal{P}})\), \(V_{H}(\tilde{\mathcal{P}})\) and \(V_{h,0}(\tilde{\mathcal{P}})\) we denote local finite element spaces, \(V_{h,0}\) having zero boundary data on \(\partial\tilde{\mathcal{P}}\). For \(u_{H}\in V_{H}(\tilde{\mathcal{P}})\) we define \(v_{h}\in V_{h,0}(\tilde{\mathcal{P}})\) via \[(\nabla(u_{H}+v_{h}),\nabla\phi_{h})_{\tilde{\mathcal{P}}}=(f,\phi_{h})\quad \forall\phi_{h}\in V_{h,0}(\tilde{\mathcal{P}}). \tag{16}\] Lemma 2 (Local problems): _Let \(u_{h}\in V_{h}\) and \(u_{H}\in V_{H}\) be solutions to_ \[(\nabla u_{h},\phi_{h})=(f,\phi_{h})\quad\forall\phi_{h}\in V_{h},\quad(\nabla u _{H},\phi_{H})=(f,\phi_{H})\quad\forall\phi_{h}\in V_{H}. \tag{17}\] _For the solution to the local problem \(v_{h}\in V_{h,0}(\tilde{\mathcal{P}})\) with finite elements of degree \(r\in\mathbb{N}\) it holds_ \[\|\nabla v_{h}\|_{\tilde{\mathcal{P}}} \leq\|\nabla(u_{h}-u_{H})\|_{\tilde{\mathcal{P}}} \tag{18}\] \[\|v_{h}\|_{1-r,\tilde{\mathcal{P}}} \leq c\big{(}h^{r}+H^{r})\|\nabla(u_{h}-u_{H})\|_{\tilde{\mathcal{P }}}. \tag{19}\] Proof: Testing (16) with \(\phi_{h}=v_{h}\) and inserting \(\pm(\nabla u_{h},\nabla v_{h})_{\tilde{\mathcal{P}}}\) gives \[\|\nabla v_{h}\|_{\tilde{\mathcal{P}}}^{2}=(f,v_{h})_{\tilde{\mathcal{P}}}-( \nabla u_{h},\nabla v_{h})_{\tilde{\mathcal{P}}}+(\nabla(u_{H}-u_{h}),\nabla v _{h})_{\tilde{\mathcal{P}}}.\] The first term is zero using (17), as \(v_{h}\) can be extended to \(\hat{v}_{h}\in V_{h}\) by zero outside of \(\tilde{\mathcal{P}}\). Estimating with Cauchy-Schwarz and dividing by \(\|\nabla v_{h}\|_{\tilde{\mathcal{P}}}\) gives the energy norm estimate (18). Next, for \(\psi\in H^{r-1}(\tilde{\mathcal{P}})\) we define the adjoint solution \(z\in H^{1}_{0}(\tilde{\mathcal{P}})\) \[(\phi,\psi)=(\nabla\phi,\nabla z)\quad\forall\phi\in H^{1}_{0}(\tilde{ \mathcal{P}}) \tag{20}\] For \(\phi:=v_{h}\in V_{h,0}(\tilde{\mathcal{P}})\subset H^{1}_{0}(\tilde{\mathcal{P}})\) it holds by means of (16) for all \(z_{h}\in V_{h,0}(\tilde{\mathcal{P}})\) \[(v_{h},\psi) =(\nabla v_{h},\nabla z)_{\tilde{\mathcal{P}}}-\Big{(}(\nabla v_ {h},\nabla z_{h})_{\tilde{\mathcal{P}}}+(\nabla u_{H},\nabla z_{h})_{\tilde{ \mathcal{P}}}-(f,z_{h})_{\tilde{\mathcal{P}}}\Big{)}\] \[=\big{(}\nabla v_{h},\nabla(z-z_{h})\big{)}_{\tilde{\mathcal{P}}} -\Big{(}(f,z_{h})_{\tilde{\mathcal{P}}}-(\nabla u_{H},\nabla z_{h})_{\tilde{ \mathcal{P}}}\Big{)}\] \[=\big{(}\nabla v_{h},\nabla(z-z_{h})\big{)}_{\tilde{\mathcal{P}}} -\Big{(}(\nabla u_{h},\nabla z_{h})_{\tilde{\mathcal{P}}}-(\nabla u_{H},\nabla z _{h})_{\tilde{\mathcal{P}}}\Big{)}\] \[=\big{(}\nabla v_{h},\nabla(z-z_{h})\big{)}_{\tilde{\mathcal{P}}} -(\nabla(u_{h}-u_{H}),\nabla(z_{h}-z_{H}))_{\tilde{\mathcal{P}}},\] where we used that \(u_{h}\) is solution to (17) and also Galerkin orthogonality with respect to \(V_{H}\) and \(V_{h}\). Hence, taking \(z_{h}=I_{h}z\in V_{h,0}(\tilde{\mathcal{P}})\) and \(z_{H}=I_{H}z\in V_{H,0}(\tilde{\mathcal{P}})\) as the interpolations \[\big{|}(v_{h},\psi)_{\tilde{\mathcal{P}}}\big{|}\leq\|\nabla v_{h}\|_{\tilde{ \mathcal{P}}}ch^{r}\|\psi\|_{r-1,\tilde{\mathcal{P}}}+\|\nabla(u_{h}-u_{H})\|_{ \tilde{\mathcal{P}}}c_{i}\big{(}h^{r}+H^{r}\big{)}\|\psi\|_{r-1,\tilde{\mathcal{ P}}}.\] Using the energy norm estimate (18) and taking the supremum over \(\psi\in H^{r-1}(\tilde{\mathcal{P}})\) gives the estimate. After these preparations we conclude with the proof to the main theorem. Proof (Proof of Theorem 2.2): As in the single-patch case we first introduce the fine mesh solution \(u_{h}\in V_{h}\) to the right hand side \(f\in L^{2}(\Omega)\) \[\|\nabla(u-u_{\mathcal{N}})\|\leq Ch^{r}\|f\|_{r-1}+\|\nabla(u_{h}-u_{\mathcal{N }})\|. \tag{21}\] As \(u_{\mathcal{N}}=u_{H}+\sum P_{\mathcal{P}}\mathcal{N}(f)\) is composed of local updates we, from here on, consider the local contributions \(\|\nabla(u_{h}-u_{\mathcal{N}})\|_{\mathcal{P}}\). On each patch \(\mathcal{P}\) we introduce the following local solutions to local problems given by Definition 4 \[\begin{split}& v_{h}\in V_{h,0}(\tilde{\mathcal{P}})\qquad(\nabla(u_{ H}+v_{h}),\nabla\phi_{h})_{\tilde{\mathcal{P}}}=(f,\phi_{h})_{\tilde{ \mathcal{P}}}\qquad\forall\phi_{h}\in V_{h,0}(\tilde{\mathcal{P}})\\ & v_{h}^{i}\in V_{h,0}(\tilde{\mathcal{P}})\qquad(\nabla(u_{H}^{i }+v_{h}^{i}),\nabla\phi_{h})_{\tilde{\mathcal{P}}}=(f_{i},\phi_{h})_{\tilde{ \mathcal{P}}}\qquad\forall\phi_{h}\in V_{h,0}(\tilde{\mathcal{P}})\end{split} \tag{22}\] The index \(i\) will refer to an element of the training data. The first local problem in (22) is to estimate the local error between \(u_{h}\) and \(u_{H}^{h}:=u_{H}+v_{h}\) on the application domain \(\Omega\), whereas the second local problem estimates the local error between the training data \(u_{h}^{i}\) and \(u_{H}^{h,i}:=u_{H}^{i}+v_{h}^{i}\) on the training mesh. We split the error as \[\|\nabla(u_{h}-u_{\mathcal{N}})\|_{\mathcal{P}}\leq\|\nabla(u_{h} -u_{H}^{h})\|_{\mathcal{P}}+\|\nabla(u_{H}^{h}-u_{H}^{h,i})\|_{\mathcal{P}}\\ +\|\nabla(u_{h}^{i}-u_{H}^{h,i})\|_{\mathcal{P}}+\|\nabla(u_{h}^{i }-u_{\mathcal{N}})\|_{\mathcal{P}} \tag{23}\] First and third term can be estimated by (29, Theorem 5.2), where local finite element algorithms are analyzed that decompose the solution \(u_{h}\) into a global coarse solution \(u_{H}\in V_{H}\subset V_{h}\) and into a local fine mesh solution. However, we refine their proof and basically only use (29, Lemma 1), introduce \(\pm u_{H}\) and use Lemma 2 above to get \[\begin{split}\|\nabla(u_{h}-u_{H}^{h})\|_{\mathcal{P}}& \leq c\|u_{h}-u_{H}^{h}\|_{1-r,\tilde{\mathcal{P}}}\\ &\leq c\Big{(}\|u_{h}-u_{H}\|_{1-r,\tilde{\mathcal{P}}}+H^{r}\| \nabla(u_{h}-u_{H})\|_{\tilde{\mathcal{P}}}\Big{)}.\end{split} \tag{24}\] We insert \(\pm u\) and using the local error estimates (14) (on each \(\mathcal{P}\) making up \(\tilde{\mathcal{P}}\)) and the local negative norm estimate (15) to bound \[\|\nabla(u_{h}-u_{H}^{h})\|_{\mathcal{P}}\leq cH^{2r}\big{(}\|u\|_{r+1,\tilde{ \mathcal{P}}}+H\cdot h_{\mathcal{P}}^{\frac{d}{2}-1}\|u\|_{r+1}\big{)}. \tag{25}\] Likewise, for \(u_{h}^{i}-u_{H}^{h,i}\) in (23) we get \[\|\nabla(u_{h}^{i}-u_{H}^{h,i})\|_{\mathcal{P}}\leq cH^{2r}\big{(}\|u^{i}\|_{r+ 1,\tilde{\mathcal{P}}}+H\cdot h_{\mathcal{P}}^{\frac{d}{2}-1}\|u^{i}\|_{r+1, \Omega^{tr}}\big{)}. \tag{26}\] Next, considering the definition of (22), the second term in (23) can be estimated as an error that measures the richness of the training data \[\|\nabla(u_{H}^{h}-u_{H}^{h,i})\|_{\mathcal{P}}\leq\|\nabla(u_{H}-u_{H}^{i}) \|_{\tilde{\mathcal{P}}}+\|f-f_{i}\|_{-1,\tilde{\mathcal{P}}} \tag{27}\] The last term in (23) is split into \[\|\nabla(u_{h}^{i}-u_{\mathcal{N}})\|_{\mathcal{P}}\leq\|\nabla(u_{h}^{i}-u_ {\mathcal{N}}^{i})\|_{\mathcal{P}}+\|\nabla(u_{\mathcal{N}}^{i}-u_{\mathcal{N }})\|_{\mathcal{P}}, \tag{28}\] where \(u_{\mathcal{N}}^{i}:=u_{H}^{i}+\sum_{\mathcal{P}}P_{\mathcal{P}}\mathcal{N}(f_{ i})\) is the local network approximation for the training data element \(u_{H}^{i}\). The first term \[\epsilon_{net}^{i}:=\|\nabla(u_{h}^{i}-u_{\mathcal{N}}^{i})\|_{\mathcal{P}} \tag{29}\] depends on the expressitivity of the neural network and the optimization error. The second term of (28) is estimated as \[\|\nabla(u_{\mathcal{N}}^{i}-u_{\mathcal{N}})\|_{\mathcal{P}}\leq\|\nabla(u_{H}^{ i}-u_{H})\|_{\mathcal{P}}+c\|\nabla(\mathcal{N}(f_{i})-\mathcal{N}(f))\|_{ \mathcal{P}} \tag{30}\] and again consists of the data error \(\|\nabla(u_{H}-u_{H}^{i})\|_{\mathcal{P}}\) and, finally, the local network generalization error. We combine (23)-(30) and sum over all patches to get \[\|\nabla(u_{h}-u_{\mathcal{N}})\|^{2}\leq c\Big{[}\big{(}h^{2r}+H^ {4r}\big{)}\|f\|_{r-1}^{2}\\ +\sum_{\mathcal{P}\in\Omega_{h}}\min_{i}\Big{\{}\|f-f_{i}\|_{-1, \mathcal{\bar{P}}}^{2}+\|\nabla(u_{H}-u_{H}^{i})\|_{\mathcal{\bar{P}}}^{2}+( \epsilon_{net}^{i})^{2}+H^{4r}\|u^{i}\|_{r+1,\mathcal{\bar{P}}}^{2}\\ +H^{4r+2}\cdot h_{\mathcal{P}}^{d-2}\big{(}\|u\|_{r+1,\Omega}^{2 }+\|u^{i}\|_{r+1,\Omega^{tr}}^{2}\big{)}+\|\nabla(\mathcal{N}(f_{i})-\mathcal{ N}(f))\|_{\mathcal{P}}^{2}\Big{\}}\Big{]}\] Taking the square root and pulling the \(\|u^{i}\|_{H^{r+1}(\mathcal{\bar{P}})}\leq\|f^{i}\|_{r-1,\Omega^{tr}}\) term out of the minimum we get \[\|\nabla(u_{h}-u_{\mathcal{N}})\|\] \[+\max_{i}\Big{\{}\big{(}1+H\cdot h_{\mathcal{P}}^{\frac{d}{2}-1} \sqrt{N_{\mathcal{P}}}\big{)}H^{2r}\|f_{i}\|_{r-1,\Omega^{tr}}\Big{\}}\] \[+\!\left(\sum_{\mathcal{P}\in\Omega_{h}}\min_{i}\Big{\{}\|f-f_{i} \|_{\mathcal{P}}^{2}+\|\nabla(u_{H}-u_{H}^{i})\|_{\mathcal{P}}^{2}+\|\nabla( \mathcal{N}(f_{i})-\mathcal{N}(f))\|_{\mathcal{P}}^{2}\Big{\}}\right)^{\frac{ 1}{2}}\Big{]}\!+\!\epsilon_{net},\] where \(N_{\mathcal{P}}\) is the number of patches. Even if each coarse mesh element is chosen as single patch, it holds \(N_{\mathcal{P}}=\mathcal{O}(H^{-d})\) and \(h_{\mathcal{P}}=H\) such that \(H^{\frac{d}{2}}\sqrt{N_{\mathcal{P}}}=\mathcal{O}(1)\) and the a priori estimate follows. Remark 1 (Extension to more general settings): Assumption 3.3 gives little freedom in the generalization of the domain \(\Omega^{tr}\). Basically, all domains have to be put together by blocks of patches that are found in the training data. The path for a further generalization would be by means of introducing a parametric setup: data is still kept local on the patches \(\mathcal{P}\), but the training of the network and the application of the network is always by means of transformation to a reference patch \(\mathcal{P}_{r}\). In setting up the neural network approach, the training data then must include a sufficient variety of different patch geometries and sizes that are also found in the application domain \(\Omega\). This approach would also be a first step towards an application to locally refined finite element methods. ### Stability of the neural network We continue with a stability result which will be used to further analyze the error estimates from Theorems 1 and 2. Lemma 3 (Network stability): _Let the activation function \(\sigma:\mathbb{R}\rightarrow\mathbb{R}\) of the MLP (see Def. 3) satisfy_ \[|\sigma(y)-\sigma(y_{i})|\leq c_{0}|y-y_{i}|\] _with \(c_{0}>0\). Then, for each patch \(\mathcal{P}\), for the inputs \(y\) and \(y^{f_{i}}\) and the corresponding finite element functions \(w_{\mathcal{N}}\) and \(w_{\mathcal{N}}^{f_{i}}\), obtained from the network updates the following inequality holds_ \[\|\nabla(w_{\mathcal{N}}-w_{\mathcal{N}}^{f_{i}})\|_{\mathcal{P}}\leq c\cdot c_ {W}\cdot c_{0}^{L}\cdot h^{\frac{d}{2}-1}\|y-y^{f_{i}}\|_{2} \tag{31}\] _where_ \[c_{W}:=\prod_{j=1}^{L}\|W^{j}\|_{2}. \tag{32}\] Proof: There exist constants \(c_{1},c_{2}>0\) independent of \(h_{\mathcal{P}}\) and \(n_{\mathcal{P}}\), which is the number of coefficients in each patch, such that \[c_{1}\|v\|_{\mathcal{P}}^{2}\leq\frac{h_{\mathcal{P}}^{d}}{n_{\mathcal{P}}}\|v \|_{l^{2}(\mathcal{P})}^{2}\leq c_{2}\|v\|_{\mathcal{P}}^{2}\quad\forall v\in V _{\mathcal{P}}.\] The number of fine mesh coefficients in each patch \(n_{\mathcal{P}}\) scales like \(n_{\mathcal{P}}=\mathcal{O}(h^{-d}\cdot h_{\mathcal{P}}^{d})\), hence \[c_{1}\|v\|_{\mathcal{P}}^{2}\leq h^{d}\|v\|_{l^{2}(\mathcal{P})}^{2}\leq c_{2 }\|v\|_{\mathcal{P}}^{2}\quad\forall v\in V_{\mathcal{P}}. \tag{33}\] Together with the inverse inequality and (33), for each \(v\in V_{h}\) it holds \[\|\nabla v\|_{\mathcal{P}}^{2}\leq c_{inv}^{2}h^{-2}\|v\|_{\mathcal{P}}^{2} \leq ch^{d-2}\|v\|_{\ell^{2}(\mathcal{P})}^{2}.\] Using the definition of the network gives \[\|w_{\mathcal{N}}-w_{\mathcal{N}}^{f_{i}}\|_{\ell^{2}(\mathcal{P})}=\|z_{L}(y )-z_{L}(y^{f_{i}})\|_{2} \tag{34}\] where \(z_{i}(y)=(l_{i}\circ\sigma\circ l_{i-1}\circ\cdots\circ\sigma\circ l_{1})(y)\) and \(l_{i}\) are as defined in (8). By using the definition of \(z_{j}\) and from the assumption we obtain for an arbitrary layer \(j\) \[\|z_{j}(y)-z_{j}(y^{f_{i}})\|_{2} =\|W^{j}((\sigma\circ z_{j-1})(y)-(\sigma\circ z_{j-1})(y^{f_{i}} ))\|_{2} \tag{35}\] \[\leq\|W^{j}\|_{2}\|(\sigma\circ z_{j-1})(y)-(\sigma\circ z_{j-1}) (y^{f_{i}})\|_{2}\] \[\leq c_{0}\|W^{j}\|_{2}\cdot\|z_{j-1}(y)-z_{j-1}(y^{f_{i}})\|_{2}.\] Then, by applying (35) recursively to the last layer we obtain \[\|z_{L}(y)-z_{L}(y^{f_{i}})\|_{2}\leq c_{0}^{L}\prod_{i=1}^{L}\|W_{j}\|_{2} \cdot\|y-y^{f_{i}}\|_{2}.\] Hence, by applying it to (34) we arrive to \[\|\nabla(w_{\mathcal{N}}-w_{\mathcal{N}}^{f_{i}})\|_{\mathcal{P}}\leq c_{0}^{ L}h^{\frac{d}{2}-1}\prod_{j=1}^{L}\|W^{j}\|_{2}\cdot\|y-y^{f_{i}}\|_{2}.\] Note that more superior bounds can be obtained by using methods based on a relaxation to a polynomial optimization problem [16]. As next we show how the difference between inputs are related to the differences of corresponding source terms and the coarse finite element solutions. Lemma 4: _Given input vectors \(y\) and \(y^{f_{i}}\) in form of (9) together with \(f,f_{i}\in C(\Omega)\) and \(u_{H},u_{H}^{f_{i}}\in V_{H}\). It holds_ \[\left\|y-y^{f_{i}}\right\|_{2}\leq c(h^{-\frac{d}{2}}\|u_{H}-u_{H}^{f_{i}}\|_{ \mathcal{P}}+\|f-f_{i}\|_{\ell^{2}(\mathcal{P})})\] Proof: Per definition of \(y\) and \(y^{f_{i}}\) we have \[\left\|y-y^{f_{i}}\right\|_{2}^{2}=\left\|u_{H}-u_{H}^{f_{i}}\right\|_{\ell^{2 }(\mathcal{P})}^{2}+\|f-f_{i}\|_{\ell^{2}(\mathcal{P})}^{2}.\] The claim follows by applying inequality (33) to the first term above. By combining Lemmas 3 and 4 we obtain the following Corollary. Corollary 1: _Under the same assumptions of Lemma 3 it holds_ \[\|\nabla(w_{\mathcal{N}}-w_{\mathcal{N}}^{f_{i}})\|_{\mathcal{P}}\leq c_{ \mathcal{N}}(h^{-1}\|u_{H}-u_{H}^{f_{i}}\|_{\mathcal{P}}+h^{\frac{d}{2}-1}\|f- f_{i}\|_{\ell^{2}(\mathcal{P})})\] _where \(c_{\mathcal{N}}=\mathcal{O}(c_{W}\cdot c_{0}^{L})\)._ As next, an immediate consequence of previous results is presented. Corollary 2 (A priori error estimate for the hybrid solution (single-patch case)): _Under the assumptions of Theorem 1 and Corollary 1 it holds_ \[\|\nabla(u-u_{\mathcal{N}})\| \leq c\bigg{[}h^{r}\|f\|_{r-1}+\epsilon\] \[+\min_{f_{i}\in\mathcal{F}}\Bigl{\{}(1+c_{\mathcal{N}}c_{P}h^{-1} )\|f-f_{i}\|_{-1}+c_{\mathcal{N}}h^{\frac{d}{2}-1}\|f-f_{i}\|_{\ell^{2}(\Omega )}\Bigr{\}}\bigg{]}\] _where \(c_{\mathcal{N}}=\mathcal{O}(c_{W}\cdot c_{0}^{L})\) and \(c_{P}\) is the Poincare constant._ Proof: The claim follows from Theorem 1 and Corollary 1, where we have used the Poincare inequality and stability of the weak Poisson problem \[h^{-1}\|u_{H}-u_{H}^{f_{i}}\|\leq c_{P}h^{-1}\|\nabla(u_{H}-u_{H}^{f_{i}})\| \leq c_{P}h^{-1}\|f-f_{i}\|_{-1}\] Likewise, for the multi-patch case the following result is obtained, which we state without proof. Corollary 3 (A priori error estimate for the hybrid solution (multi-patch case)): _Under the assumptions of Theorem 2 and Corollary 1 it holds_ \[\|\nabla(u_{h}-u_{\mathcal{N}})\| \leq c\Big{[}(h^{r}+H^{2r})\|f\|_{r-1}+H^{2r}\max_{i}\|f_{i}\|_{r- 1,\Omega^{tr}}\] \[\qquad+\Big{(}\sum_{\mathcal{P}\in\Omega_{h}}\min_{i}\left\{\|f- f_{i}\|_{-1,\tilde{\mathcal{P}}}^{2}+c_{\mathcal{N}}^{2}h^{d-2}\|f-f_{i}\|_{\ell^{2} (\mathcal{P})}^{2}\right.\] \[\qquad+\left\|\nabla(u_{H}-u_{H}^{i})\right\|_{\tilde{\mathcal{P }}}^{2}+c_{\mathcal{N}}^{2}h^{-2}\|u_{H}-u_{H}^{i}\|_{\mathcal{P}}^{2}\Big{\}} \Big{]}+\epsilon\] _where \(c_{\mathcal{N}}=\mathcal{O}(c_{W}\cdot c_{0}^{L})\)._ The error estimates from Theorems 1 and 2, as well as the two corollaries, show a balanced error. In particular, they prove the practical usefulness of the method: the total error is given as a balance of richness of the training data, i.e., number and distribution of the training elements, and quality of the training data, i.e., the resolution of the training data. Both can be controlled. In addition, there is the network and optimization error, which in principle can be influenced by the architecture, depth and width of the network. The practical efficiency of the method will always depend on the specific example and especially on how much the effort of offline phase and online phases differ. For typical problems in fluid mechanics, the 3d flow around obstacles, we observed substantial increases in efficiency for relevant generalizations of the training data [20]. Numerically we could not yet identify the role of the coarse mesh contribution \(O(H^{2r})\) that suggests the relation \(h=H^{2}\) between the two grid levels. ## 4 Numerical experiments In the following paragraphs we will document different numerical simulations to explore the performance of the hybrid finite element neural network approach. We will start by an in-depth analysis of the algorithm and the sensitivity of the approximation properties on the various aspects like network size, variety of training data or optimization and regularization procedure. Then, we add a second test case to explore the generalization capacity of the approach. ### Configuration of the test case We start by describing our experimental setup. Let \(\Omega=(0,1)^{2}\) be the unit square. We consider the two-dimensional Poisson equation with homogeneous Dirichlet boundary conditions \[-\Delta u=f\ \text{in}\ \Omega,\quad u=0\ \text{on}\ \partial\Omega. \tag{36}\] We consider right hand sides from the following set of functions \[\mathcal{F}\ :=\ \Big{\{}f(x_{1},x_{2})\ =\ \sin(2\pi\,\cdot\,C_{1}(x_{1}\,+ \,C_{2}))\,\cdot\,\sin(2\pi\,\cdot\,C_{3}(x_{2}\,+\,C_{4}))\Big{\}} \tag{37}\] and training data is declared by picking random and uniformly distributed samples from this set. For each such \(f\in\mathcal{F}\) we will then compute finite element solutions \(u_{h}\) and \(u_{H}\) as training data. ### Neural network setup and optimization The neural network is a multilayer perceptron as described previously in Section 3, see Definition 3. We consider networks with \(L-1=4\) hidden layers, each having a width of \(512\), if not stated otherwise. The total number of trainable parameters depends on the size of the input and output vectors, see Table 1. In order to perform \(k\) refinements, the network receives 4 nodal values of the coarse solution and \((2^{k}+1)^{2}\) nodal values of the source term. The output vector contains \((2^{k}+1)^{2}\) nodal values which predicts the difference between fine and coarse finite element solutions. #### 4.2.1 Generation of training data For creating training and test data sets we randomly generate finite sets of functions taken from \(\mathcal{F}\) as given in (37). To generate such a function it suffices to generate four real numbers, namely \(C_{1},C_{2},C_{3}\) and \(C_{4}\). Since \(C_{2}\) and \(C_{4}\) are the phase shifts of respective terms in \(f\) divided by \(2\pi\) we sample them uniformly at random from [0.0,1.0]. \(C_{1}\) and \(C_{3}\) are frequencies of respective terms, so restrict them to be only from [1.0,1.5]. The computations are performed for a coarse step size \(H\) and for the fine mesh sizes \(h=H/2\), \(h=H/4\) and \(h=H/8\). Hereby, we generate sets of training and test triples \((f_{i},u_{H}^{i},u_{h}^{i})\in\mathcal{F}\times V_{H}\times V_{h}\) for \(i=1,\ldots,N_{T}\). In our experiments, we set \(H=2^{-3}\) which corresponds to 64 cells. Due to the local neural network setup, each triple \((f_{i},u_{H}^{i},u_{h}^{i})\) generates a larger number of training patches \(N_{\mathcal{P}}\), one for each patch of the triangulation. The number of patches are always the same as the number of elements in the coarse mesh. Hence, \(H=h_{\mathcal{P}}\) and we have \(N_{\mathcal{P}}=64\). A second test data set of the same size is additionally chosen from \(\mathcal{F}\). #### 4.2.2 Optimization For the training of the network we use the Adam optimizer [15]. The loss function is the mean square error divided by the number of patches and the number of training data as defined in (10). As Lemma 3 shows, stability of the network is tightly related with the multiplications of spectral norms of the weights. Therefore, we also perform experiments with a modified loss function by including a regularization term which we report in Section 4.4. ### Accuracy of the hybrid finite element neural network solver In this first test case, we analyze the accuracy of the hybrid solver. For this purpose, we consider the mean error over all test data. Starting from the coarse solution with grid size \(H=2^{-3}\), the hybrid method is enriched with neural networks. In doing so, we predict 1, 2 or 3 grid levels, thus trying to achieve accuracies \(h=H/2\), \(h=H/4\) and \(h=H/8\). \begin{table} \begin{tabular}{c|c|c|c|c} \hline H/h & \(N_{0}\) & \(N_{1,\ldots,4}\) & \(N_{5}\) & \# parameters \\ \hline \(2^{2}\) & 4 + 25 & 512 & 25 & 816 153 \\ \(2^{3}\) & 4 + 81 & 512 & 81 & 873 553 \\ \(2^{4}\) & 4 + 289 & 512 & 289 & 1 086 753 \\ \hline \end{tabular} \end{table} Table 1: The number of neurons \(N_{l}\) at each layer \(l\in\{0,\ldots,5\}\) and the total number of trainable parameters (weights and biases) \(\sum_{l=1}^{L=5}N_{l-1}\cdot N_{l}+N_{l}\). In this first test, we only want to investigate the approximation ability of the neural network and we use an excessive number of training data to keep the error term \(\min_{i}\left\{\|f-f_{i}\|+\|\nabla(u_{H}-u_{H}^{i})\|\right\}\) small. Thus, from (12), considering linear finite elements \(r=1\), it remains \[\|\nabla(u-u_{\mathcal{N}})\|=\mathcal{O}\big{(}h+H^{2}\big{)}\] Since we do not know the analytical solution we use a reference solution instead, which is calculated on a mesh with element size \(h/4\). The numerical results shown in Table 2 confirm the estimate and the hybrid neural network solution recovers the accuracy of the fine mesh solution. #### 4.3.1 Dependency on the training data set In Fig. 4 we show the approximation error of the hybrid simulation for the three prediction levels \(h=H/2\), \(h=H/4\) and \(h=H/8\) depending on the size of the training data set \(N_{T}\). The results indicate that the corresponding fine mesh \begin{table} \begin{tabular}{c c c} \hline \hline \(h\) & \(\|u-u_{h}\|\) & \(\|u-u_{\mathcal{N}}\|\) \\ \hline \(H/2\) & 1.25e-04 & 1.25e-04 \\ \(H/4\) & 3.21e-05 & 3.29e-05 \\ \(H/8\) & 8.13e-06 & 1.11e-05 \\ \hline \hline \end{tabular} \begin{tabular}{c c} \hline \hline - \(\blacktriangle\)- & Reference \(\|u-u_{h}\|\) & Hybrid \(\|u-u_{\mathcal{N}}\|\) \\ \hline \hline \end{tabular} \end{table} Table 2: Performance of the hybrid solution for three different refinement levels. We show the average error on the test data. The training data set \(\mathcal{F}\) is sufficiently big such that the data error is negligible. Figure 4: Dependency of the prediction quality \(\|u-u_{\mathcal{N}}\|\) (for the test data) on the size of the training data set. accuracy is reached in all three cases, however, only for an increase amount of training data. This is in accordance to the error estimate (12), which shows that the error term \(H^{2r}+h^{r}\) must be balanced with the data error \(\min_{i}\|f-f_{i}\|\) and \(\min_{i}\|\nabla(u_{H}-u_{H}^{i})\|\). Furthermore, Fig. 4 suggests the scaling \(\min_{i}\|f-f_{i}\|=\mathcal{O}(N_{T}^{-\frac{1}{2}})\). Figure 5 indicates the constant \(c_{W}\) (32), see Lemma 3, and its dependency on the target step size \(h\) as well as on the amount of training data \(N_{T}\). Growth of this constant is slower for finer target step sizes. All in all, a linear dependency of \(c_{W}\) on \(N_{T}\) appears eminent. This result is not desirable as \(c_{W}\) enters the error estimate of Theorem 3.1 in the same way as the data error \(\min\|f-f_{i}\|\). This data error must decrease faster than the growth of the constant. #### 4.3.2 Error depending on the network complexity Next we study the dependency of the error on the complexity of the network. Again we consider the cases \(h=H/2,H/4\) and \(H/8\). We used \(N_{T}=2^{12}\) training problems for this experiment. First we choose the number of hidden layers of the perceptron between 1, 2, 4 or 8 with 512 neurons in each layer. The results can be seen in Figure 6. We observe that most of the time using four layers seems to be optimal for cases \(h=H/2\) and \(H/4\). For the case \(h=H/8\) we observe that after three layers the network is more prone to overfitting, and while the train error keeps reducing, the test error is not getting any better. Just like above, let's also consider how the constant \(c_{W}\) (32) from the bound changes as we vary the number of layers. This can be seen in Figure 7. Here we observe that the value of \(c_{W}\) increases with number of layers. Next, we fix the number of layers to be 4 and vary the number of neurons per layer from 8 to 512. The results can be seen in Figure 8. Here we observe that error behaves similarly to the experiment where we varied the amount of training data - the error decreases as the number of neurons increases. So, we confirm that 512 is most likely indeed the optimal choice in the current setting. Results for the the bound can be seen in Figure 9. Same as above we observe that the value of \(c_{W}\) increases with number of neurons. Figure 5: Bound vs number of training problems ### Impact of the regularization Since experiments in the previous sections showed that the bound \(c_{W}\) from (32) grows fast with respect to the training data set size (see Fig. 5) and the network complexity (see Figs. 7 and 9), we aim to penalize it. To this end, we modify our loss function such that the optimization problem (10) is replaced with \[\min_{\begin{subarray}{c}W_{i},b_{i},\\ i\in\{0,\dots,L\}\end{subarray}}\quad\frac{1}{N_{T}N_{\mathcal{P}}}\sum_{ \mathcal{P}}\lVert z_{\mathcal{P}}-\mathcal{N}(y_{\mathcal{P}})\rVert_{2}^{2} \;+\;\frac{\alpha}{N_{T}N^{param}}\prod_{i=1}^{N_{L}}\lVert W_{i}\rVert_{F} \tag{38}\] where \(W_{i}\in\mathbb{R}^{N_{i-1}}\times\mathbb{R}^{N_{i}}\) stands for the weights and \(N^{param}\) for the number of parameters. We use the Frobenius norm \(\lVert\cdot\rVert_{F}\) since minimizing the singular norm would be extremely computationally expensive and the Frobenius norm bounds the singular norm. Figure 6: Dependency of the prediction quality \(\lVert u-u_{\mathcal{N}}\rVert\) (for the test data) on the number of network layers. The size of the training data is chosen as \(N_{T}=2^{12}\) for all cases. Figure 7: Corresponding to Fig. 6 we show the estimates for the bound for \(c_{W}\) depending on the number of layers. In Fig. 10 we compare the resulting constant for fixed \(h=H/2\) and varying \(\alpha\). For the sake of comparison we also consider \(\alpha=0\), which means using the loss function without regularization (10). In Fig. 11 we show the effect on the quality of the hybrid approximation. As the choice \(\alpha=10^{-4}\) leads to a smaller error and a smaller bound \(c_{W}\) among other choices, we present further results on the dependency to the training data set size, but now with \(\alpha=10^{-4}\) in the modified loss function (38). These results can be seen in Figure 12 and Figure 13 respectively. ### Role of data preprocessing Finally, we justify our specific choice of data preprocessing, so-called standardization, which we employed in every experiment presented in this paper. The data Figure 8: Dependency of the prediction quality \(\|u-u_{\mathcal{N}}\|\) (for the test data) on the number of neurons in hidden layers. The size of the training data is chosen as \(N_{T}=2^{12}\) for all cases. Figure 9: Corresponding to Fig. 8 we show the estimates for the bound for \(c_{W}\) depending on the number of layers. preprocessing has a large effect on the optimization of the network and its approximation quality. In order to illustrate this, we consider fixed \(h=H/2\) and we vary the amount of training data from \(2^{12}\) to \(2^{16}\). As for preprocessing methods, we considered no preprocessing, min-max scaling to \([0,1]\) and standardization. These methods were applied to each input and output feature separately. Min-max scaling works by uniformly rescaling a given feature to the interval \([0,1]\). In other words for a given set of samples \(X=(X_{1},X_{2},\ldots,X_{n})\in\mathbb{R}^{n}\) with minimum values \(X_{\min}\) and maximum value \(X_{\max}\), the min-max normalization of it can be defined as following: \[\tilde{X}_{min-max}:=\frac{X-X_{\min}}{X_{\max}-X_{\min}}. \tag{39}\] Figure 11: Approximation errors \(\|u-u_{\mathcal{N}}\|\) of the solutions obtained with regularization factors \(\alpha\in\{0,10^{-4},10^{-2},1\}\). Figure 10: The bound \(c_{W}\) corresponding to different regularization factors \(\alpha\in\{0,10^{-4},10^{-2},1\}\) Standardization is similar but instead of rescaling the data to \([0,1]\), it transforms the data to have mean value of \(0\) and variance of \(1\), i.e. \[\tilde{X}_{std}=\frac{X-\text{Mean}(X)}{\text{Var}(X)}. \tag{40}\] Figure 14 shows the results where \(y\)-axis corresponds to the average values of the validation metric. As it was mentioned above, validation metric is defined as the \(\ell_{2}\)-norm (6) of difference between given and a reference solution. \(x\)-axis here corresponds to the number of training data. While the topmost line depicts the validation metric of coarse (input) solutions on the test data set, the bottommost line depicts the validation metric for the fine (target) solutions on both the test data sets. The rest of the lines depicts the validation metric for solutions obtained by using the proposed method with aforementioned preprocessing methods on train and test data sets. Figure 12: Regularization with \(\alpha=10^{-4}:\) Dependency of the prediction quality \(\|u-u_{\mathcal{N}}\|\) (for the test data) on the size of the training data set. Figure 13: Estimate for the bound for \(c_{W}\) obtained with regulariza- tion factor \(\alpha=10^{-4}\). We observe that no preprocessing gives the worst results compared to other methods and the error of the resulting solution is even getting bigger with more training data. The second best preprocessing method turned out to be min-max scaling. It performs pretty well even with small amount of the training data and the error improves with more data. The best preprocessing method is standardization. In this case, the error of the proposed method reaches the error of the target one slightly faster and can give the comparable error to min-max scaling while using less data for the training. Since standardization performed the best, we have used it in all our experiments. Due to the fact that standardization consists of just a few arithmetic operations performed on both input and output features, the computational overhead of it is negligible. ### Generalizations to different domains In this section we discuss the application of the network to a domain different from the one, that was used for generation of the training data. In the previous sections we have used \(\Omega_{\rm train}=(0,1)^{2}\) for both training and testing. Now, we leave the experimental settings mostly untouched and after the training was performed on \(\Omega_{\rm train}\) we apply the network to the solutions of Equation 1 on \(\Omega_{\rm test}=(0,2)\times(0,1)\). In this section we consider a problems of the aforementioned form for our further tests. The equation we approximate solutions of is again the Poisson problem \[-\Delta u=\sin(2\pi\cdot C_{1}(x_{1}+C_{2}))\cdot\sin(2\pi\cdot C_{3}(x_{2}+C_ {4}))\ \mbox{in}\ \Omega,\quad u=0\ \mbox{on}\ \partial\Omega. \tag{41}\] where \(C_{1}=1.2,C_{2}=0.2,C_{3}=1.4,C_{4}=0.4\). Table 3 shows the results for this test-case. We observe optimal convergence for predicting one \(H/2\) or two mesh levels \(H/4\), but the accuracy is slightly non-optimal if three mesh levels are to be predicted, i.e. in the case \(h=H/8\). Figure 15 shows the solution and the error \(u-u_{\mathcal{N}}\) for the extended domain problem. Figure 14: Importance of preprocessing: dependency of the prediction quality \(\|u-u_{\mathcal{N}}\|\) (for the test data) on the size of the training data set. \begin{table} \begin{tabular}{c c c c} \hline \hline \(h\) & \(\|u-u_{H}\|\) & \(\|u-u_{h}\|\) & \(\|u-u_{\mathcal{N}}\|\) \\ \hline \(H/2\) & 3.83e-04 & 1.00e-04 & 1.00e-04 \\ \(H/4\) & 3.82e-04 & 2.53e-05 & 2.68e-05 \\ \(H/8\) & 3.82e-04 & 6.37e-06 & 1.19e-05 \\ \hline \hline \end{tabular} \begin{tabular}{c c} \hline \hline \(\cdot\ ## 5 Conclusion In this paper we have introduce introduced and analyzed a local hybrid finite element neural network method and its application to the Poisson problem. We have employed neural networks to reduce the complexity of solving Poisson equation for a family of source terms. The network operates locally, which enables it to be domain agnostic, meaning that it can be applied to problems on different domains which are not included in the training data. The most important component of this paper is the theoretical investigation of the proposed method. In particular we performed an a priori error analysis of the local hybrid finite element neural network method including the stability analysis of the network being used. Theoretical findings are accompanied with numerical results, which have shown that the error of the hybrid solution can be controlled by the amount of the training data and by tuning the hyperparameters of the network. We have shown first generalization results to a slightly modified domain and found good performance. However, generalization of the method will fail if the character of the solution changes. For instance, generalization from the very regular square-domain setting to an L-shaped domain with reentrant corners will not give satisfactory results, as the singular behavior close to the corner is never seen during training of the network. Since neural networks essentially perform an interpolation of the data and processes available in the training, an appropriate enrichment of the training data will be necessary in this case. Further steps will focus on the extension of the analysis to the time-dependent case, where the hybrid DNN-MG solver has shown very high accuracy in relevant problems [21; 19; 20]. The time-dependent case is appealing as it could enable one to achieve the accuracy of the fine temporal discretizations by calculation solutions from coarse discretizations only and receiving the temporal fluctuations from the network. This will be the focus of an upcoming work. ## Data availability The Python scripts for reproducing the numerical test cases are published on Zenodo [13]. ## Acknowledgements The authors acknowledge the support of the GRK 2297 MathCoRe, funded by the Deutsche Forschungsgemeinschaft, Grant Number 314838170. ## Conflict of interest The authors declare that they have no conflict of interest.
2304.09358
Investigating the Nature of 3D Generalization in Deep Neural Networks
Visual object recognition systems need to generalize from a set of 2D training views to novel views. The question of how the human visual system can generalize to novel views has been studied and modeled in psychology, computer vision, and neuroscience. Modern deep learning architectures for object recognition generalize well to novel views, but the mechanisms are not well understood. In this paper, we characterize the ability of common deep learning architectures to generalize to novel views. We formulate this as a supervised classification task where labels correspond to unique 3D objects and examples correspond to 2D views of the objects at different 3D orientations. We consider three common models of generalization to novel views: (i) full 3D generalization, (ii) pure 2D matching, and (iii) matching based on a linear combination of views. We find that deep models generalize well to novel views, but they do so in a way that differs from all these existing models. Extrapolation to views beyond the range covered by views in the training set is limited, and extrapolation to novel rotation axes is even more limited, implying that the networks do not infer full 3D structure, nor use linear interpolation. Yet, generalization is far superior to pure 2D matching. These findings help with designing datasets with 2D views required to achieve 3D generalization. Code to reproduce our experiments is publicly available: https://github.com/shoaibahmed/investigating_3d_generalization.git
Shoaib Ahmed Siddiqui, David Krueger, Thomas Breuel
2023-04-19T00:54:00Z
http://arxiv.org/abs/2304.09358v1
# Investigating the Nature of 3D Generalization in Deep Neural Networks ###### Abstract Visual object recognition systems need to generalize from a set of 2D training views to novel views. The question of how the human visual system can generalize to novel views has been studied and modeled in psychology, computer vision, and neuroscience. Modern deep learning architectures for object recognition generalize well to novel views, but the mechanisms are not well understood. In this paper, we characterize the ability of common deep learning architectures to generalize to novel views. We formulate this as a supervised classification task where labels correspond to unique 3D objects and examples correspond to 2D views of the objects at different 3D orientations. We consider three common models of generalization to novel views: (i) full 3D generalization, (ii) pure 2D matching, and (iii) matching based on a linear combination of views. We find that deep models generalize well to novel views, but they do so in a way that differs from all these existing models. Extrapolation to views beyond the range covered by views in the training set is limited, and extrapolation to novel rotation axes is even more limited, implying that the networks do not infer full 3D structure, nor use linear interpolation. Yet, generalization is far superior to pure 2D matching. These findings help with designing datasets with 2D views required to achieve 3D generalization. Code to reproduce our experiments is publicly available: [https://github.com/shoaibahmed/investigating_3d_generalization.git](https://github.com/shoaibahmed/investigating_3d_generalization.git) ## 1 Introduction Visual object recognition systems need to be able to generalize to novel views of objects using a small set of training views. This ability has been studied extensively in neuroscience, psychology, and computer vision [20, 17, 21, 8, 4]. In order to explain these remarkable generalization capabilities of the human visual system in terms of object recognition, a range of different hypotheses have been proposed. One common theory is that humans perform pure view-based recognition [20, 17, 21]. However, the generalization capabilities exhibited by humans in visual recognition are hard to explain using a purely view-based recognition system. An alternative view is that humans build a partial 3D representation of the object rather than leveraging purely view-based recognition [8, 4, 5]. Deep learning models have also demonstrated the capability to recognize objects from novel viewpoints. However, since these mechanisms are not explicitly built into the architecture, the reasons responsible for this capability are unclear. This knowledge is important to understanding and improving visual recognition systems. Based on prior work in neuroscience and computer vi Figure 1: **Examples from the generated Paperclip Dataset.** We plot a single paperclip object at different orientations along the z-axis on the horizontal axis and along the y-axis on the vertical axis. See Fig. 13 for rotation along other axes. sion, we identify three distinct classes of behaviors for visual recognition that can explain the generalization capabilities of deep learning models: * Full 3D recognition, where the system recovers a full 3D model of the object given a limited number of views. Once this 3D object is constructed, recognition is performed by selecting the model which best explains the given view. Such a model should generalize to all views given a small number of training views. * Pure 2D matching, where recognition is performed directly by identifying the nearest training view for the given test view. Such a model should generalize only to similar views, independent of the axis of rotation. * Matching based on a linear combination of views (2.5D matching), where the system interpolates between a limited number of views in order to construct a better representation of the underlying 3D object. Such a model should generalize well to rotation axes represented in the training data. In this paper, we aim to understand the mechanisms responsible for generalization in deep networks by evaluating how far a model can generalize by learning on a limited number of training views for a given 3D object. 2D views of objects are generated via rotations around different axes. The appearance of 3D objects varies across viewpoints for two reasons: self-occlusion, and the geometry of 3D projection. Self-occlusion results simply in the presence, or absence of features in the image, similar to other forms of occlusions. The geometric dependence of the two-dimensional view on the pose parameters has received extensive study in the literature [19, 9, 11]. Synthetic wire-like objects i.e., Paperclips are a particularly good model to study the latter phenomenon as they have limited self-occlusion. For this reason, Paperclips have been used to study generalization in humans, monkeys, and pigeons in the past [20, 17, 21, 23]. We use a limited number of views to train and evaluate the generalization capabilities of the model on all possible axis-aligned rotations. We also perform evaluations on 3D models of real-world objects - models of chairs from ShapeNet [6]. We formulate this as a supervised classification task, where the 3D model refers to the class, while specific 2D views based on different 3D rotations of the underlying 3D object refer to the training/evaluation examples. This formulation is consistent with experiments on monkeys/humans where they were tasked to distinguish views of the same object from views of another object [20, 17, 21, 23]. Our results show that deep models exhibit behavior that is neither full 3D recognition nor pure 2D matching. This behavior is also distinct from the linear combination of views on paperclips in subtle ways. In particular, the contributions of this paper are: * We present new datasets of synthetic paperclips and chairs for testing the 3D generalization of models. * By analyzing the generalization capabilities of deep learning models on rotations of 3D objects around different axes, we show that deep learning models are capable of substantial generalization across views, but behave differently from all existing mathematical models of generalization across views. * We show that generalization improves with the number of classes, showing that 3D generalization is based in part on learning model-independent features. * We show that these results are consistent across different input representations, architectures (ResNets, VGG, and ViTs) as well as real-world 3D objects (3D models of chairs [6]), highlighting that these results are not an artifact of the chosen representation, 3D object or architecture. ## 2 Background & Related Work We analyze the 3D generalization capabilities of deep learning models, as well as the class of behavior leveraged Figure 2: **Examples from the generated 3D Chairs Dataset.** We use the same generation protocol as for the paperclips dataset but use the 3D models of chairs from ShapeNet [6] instead of synthetic Paperclips. We plot a single chair object at different orientations along the z-axis on the horizontal axis and along the y-axis on the vertical axis. by these models for recognition by training on different 2D views of the underlying 3D object. For this purpose, we first describe the geometry of vision, followed by different classes of behavior for visual recognition that we consider in this work to evaluate deep networks. We then describe visual recognition in humans, highlighting the behavioral class that they are hypothesized to follow. Finally, we discuss prior work analyzing failure modes of deep networks in 3D generalization as well as the evaluation of generalization on OOD poses which is closest to our work. ### Geometry of Vision Visual systems are commonly modeled as performing a central projection of 3D objects onto the image plane. This projection is determined by 6 pose parameters covering 3D translation and rotation, where pitch, yaw, and roll correspond to rotation along the x-axis, y-axis, and z-axis respectively. For objects sufficiently distant from the camera, this projection is usually approximated via an orthographic projection along with the scale. Based on these 6 pose parameters, the set of views forms a 6-dimensional manifold in image space. An ideal recognition system should be invariant to variations in all 6 parameters. We can achieve approximate invariance to 4 of the 6 parameters by modeling recognition to be invariant under 2D translation, rotation, and scale. This is commonly achieved in deep learning systems via data augmentation. This leaves 2 pose parameters, namely rotation along the x-axis and y-axis (pitch and yaw). ### Classes of Behavior for Visual Recognition We consider three dominant classes of behavior for visual recognition from classical computer vision as well as neuroscience literature i.e. (i) full 3D recognition, (ii) pure 2D recognition, and (iii) 2.5D matching based on a linear combination of views. Full 3D RecognitionHuttenlocher and Ullman (1987) [13] proposed a pure 3D recognition algorithm i.e. recognition by alignment where the 3D model is aligned with the given 2D view for recognition. This assumes access to an underlying 3D model of the object. For full 3D recognition, the manifold of views can be reconstructed from a limited number of samples using structure from motion theorems [14]. Systems performing full 3D recognition should generalize to all views given just a couple of training views. Pure 2D MatchingPoggio et al. [20] presented pure 2D matching systems, where distances to views are defined via radial basis functions (RBF) from existing views, and recognition is performed based on the nearest training view for the given test view. For pure 2D matching, 4 of the 6 view parameters can be eliminated via augmentation, followed by simple nearest neighbor lookup or sampling for the remaining two parameters. Systems performing pure 2D matching should generalize to very similar views, independent of the axis of rotation. Linear Combination of ViewsLinear combination of views (or 2.5D) matching was popularized by Ullman and Basri (1989) [24], where intermediate views are constructed by a linear combination of training views. This is akin to interpolating the given views to achieve a larger effective number of views for recognition. For the linear combination of views, the 6D view manifold can be approximated with a linear manifold containing the view manifold. Systems performing a linear combination of views should generalize well to rotations along the axes represented in the training data. ### Visual Recognition in Humans There has been a long line of research arguing for view-centric or pure 2D matching-based recognition in humans [20, 17, 21], where the visual system responds to view-specific features of the object, which are not invariant to different transformations of the original object. The generalization-based approach is another dominant hypothesis where the visual system learns view-invariant features which can be useful for recognition even when considering novel views of the object [8, 4, 5]. One hypothesis for how this can be to be achieved is by relying on Geon Structural Descriptions (GSD) of the object, which remains invariant to these identity-preserving transformations [5]. Karimi et al. (2017) [15] compared recognition between humans and deep learning systems, and argued that humans focus on view-invariant features of the input, while deep learning models employ a view-specific recognition approach, which impedes their ability to be invariant to a certain set of transformations. ### 3D Generalization Failures of Deep Networks Recent work has also attempted to analyze the 3D generalization failures of deep networks. Alcorn et al. (2019) [3] showed that novel 3D poses of familiar objects produced incorrect predictions from the model. Abbas et al. (2022) [2] extended this evaluation to state-of-the-art models and showed that current models still struggle to recognize objects in novel poses. Madan et al. (2021) [18] similarly showed that such misclassification can be induced by even minor variations in lighting conditions or poses which can still be considered in-distribution. Experiments in psychology have also demonstrated that reaction times, as well as error rates, also increase for humans when looking at objects from novel viewpoints [23]. The investigation of adversarial examples has also been extended beyond \(L_{p}\) norm-based attacks using a differentiable renderer to identify adversarial poses [16, 26]. All these investigations are targeted toward trying to find vulnerabilities in the model recognition behavior. On the other hand, we attempt to understand the model's generalization when provided with a small number of training views. ### Generalization to OOD poses Cooper et al. (2021) [7] attempted to systematically understand the generalization of the model to novel poses by evaluating on out-of-distribution poses of the underlying 3D object. Although their work shares some conceptual similarities with ours, there are noteworthy differences in the evaluation settings: * The study by Cooper et al. (2021) [7] focused on OOD performance. In contrast, our research primarily addresses the issue of generalization from multiple training views (multi-view generalization). * Our work is the first to demonstrate the dependence on the number of views, specifically the interaction between views. The observed synergistic effects of training on multiple views of the same object are quite intriguing. * The conclusion drawn from [7] regarding the model's ability to achieve only planar generalization is related to our case of linear interpolation of views. However, our work extends this concept to multiple views. * The experimental setup in [7] differs from ours, as they appear to perform per-category classification, rendering the classification problem to be considerably simpler. In our study, we formulate a per-object classification problem (similar to the prior studies in psychology and neuroscience [20, 17, 21, 23]) and reveal the synergistic effects of the number of views as well as the number of classes on generalization across the training axis. ## 3 Methods We first discuss the dataset generation technique employed in this paper for generating our datasets, followed by the training protocol used to train our models. ### Datasets The paperclip dataset is comprised of 10,000 synthetically generated 3D paperclip models. Vertices of the different 3D models are initialized randomly within a sphere around the previous point and connected together to form a paperclip. We restrict the number of vertices to 8 and reject 3D models with extremely sharp edges or overlaps between wires of the paperclip. Each paperclip is rescaled and translated to the center of the camera once the full paperclip has been generated. We then rotate the object for a full 360 degrees sequentially through all three axes. For multi-axis rotations, we consider a stride of 10 degrees, resulting in a total of \(36\times 36\) frames per combination. Since there are three such combinations in total (xy, xz, and yz), the total number of frames in the dataset turns out to be: \((360\times 3+36\times 36\times 3)\times 10000\sim 50M\). Examples from the dataset are visualized in Fig. 1. Training is performed by sub-sampling these classes, as well as the number of views used during training. We have also generated a similar dataset to compute 3D generalization on real-world 3D objects, specifically 3D models of chairs from ShapeNet [6]. We render these objects without texture in order to ensure that the model is forced to use shape rather than texture for recognition. The chairs are randomly rotated to avoid them having in their canonical pose. This helps in breaking object symmetries, making them comparable to our paperclip setup. Examples from the chair dataset are visualized in Fig. 2. We use Unity3D for our 3D renderings [1]. We place the camera at a small distance, looking directly at the object located in the center of the frame. See Fig. 12 for an illustration of the camera setup. ### Training All training hyperparameters are specified in Appendix A and summarized in Table 1. We perform random horizontal flips and random cropping (with a scale of 0.5 to 1.0) during training following regular deep-learning training recipes. It is important to note that we only aim to capture the impact of 3D rotations. The model is expected to acquire translation and scale invariance via the random crops used during training (see Fig. 1). This also avoids the learning of trivial solutions by the model. We default to using ResNet-18 for our experiments unless mentioned otherwise. We always train on rotations along the y-axis and evaluate on rotations along all three axes, including simultaneous rotations along two axes. ## 4 Results We divide the results into two distinct settings based on the range from which the views are sampled: (i) uniformly sampled views, and (ii) range-limited sampled views. ### Uniformly sampled views In this setting, we train the model on a limited number of uniformly sampled views from the view-sphere when only rotating along the y-axis. As the number of views increases, the model should get a holistic understanding of the full 3D object. ## 4 Conclusion Figure 3: **Change in recognition behavior with an increasing number of views.** We plot the performance of the model with an increasing number of views on our paperclip dataset when training with rotations only along the y-axis using 10000 classes, starting from a view with no rotation (\(0^{\circ}\)). The red line indicates the observed performance, the gray line indicates the expected performance from a purely view-based model (replicated from # views=1 condition), and the orange region indicates the performance difference between a purely view-based recognition system and deep learning models. The second last row visualizes the performance of the most powerful setting (12 equidistant views w/ 10000 classes) when rotating along two different axes simultaneously with blue dots indicating training views. The final row summarizes these results with a different number of views as well as a different number of classes. The figure highlights how recognition behavior changes with an increasing number of views, where the model is strictly view-based when considering a single or two views (a-b) but exhibits surprising generalization to intermediate views (c-f) located in between when the number of views increases (\(\geq 3\)). The results also show that deep learning models do not generalize well to rotations around novel axes. Fig. 3 presents our results in this setting, where we fix the number of classes to be 10,000. We highlight the difference in the performance of a purely view-based recognition system and our trained model with orange color. The model seems to be performing pure 2D matching with a small number of views (Fig. 2(a)-b). However, as the number of views increases, there is a drastic shift in recognition behavior where the model exhibits significantly better generalization than that of pure 2D matching (Fig. 2(c)-f). _Is the model successfully recovering the full underlying 3D object?_ In order to answer this, we evaluate the model's performance when rotating the object along a different axis. Full 3D recognition based on reconstructing a 3D representation of the object should generalize to novel rotations. However, we see in Fig. 2(g)-l that once we rotate the object along a different axis, the model fails to generalize. These results disprove both full 3D recognition and pure 2D matching as possible classes of behavior employed by deep models, leaving only the linear combination of views as the most likely class of behavior exhibited by deep models. Generalization on intermediate views between training viewsFig. 4 shows the performance of the model, helping Figure 4: **Model achieves higher generalization on views embedded within training views.** We plot the performance of the model on two different settings i.e., with [-15, 15] as training views and [-30, 30] as training views. We see that despite 0-degree rotation and 30-degree rotation being equally spaced from training views in the case of [-15, 15], the model generalizes better to the views between training views i.e., 0-degree rotation. Figure 5: **Our results generalize to other representations.** We plot the performance of the model using different input representations with 1000 classes. The first row represents the coordinate image representation, while the second row represents the coordinate array representation (see Fig. 14 for a visual depiction of the representations used). The figure indicates that our findings generalize to other input representations. us to understand generalization differences between views that are embedded within training views vs. views that are outside the set of training views. We see that despite the two views being equally distant from the training views, views that are embedded within the training views achieve higher generalization. #### 4.1.1 Generalization to other representations Since we use 3D renderings of synthetic paperclip objects, this may make the process of recognition more difficult. A Figure 6: **Same conclusions hold for real-world 3D objects.** We plot the performance of the model on 3D chairs dataset (see Fig. 3 for description). We observe similar conclusions hold for 3D models where the model generalizes along the axis of rotation, but fails to generalize to rotations along novel axes. paperclip is fully specified by the position of its vertices. Therefore, we also evaluate two different simplified input representations i.e., (i) coordinate image representation and (ii) coordinate array representation. In the case of coordinate image representation, we represent the coordinates directly as a set of points on an image plane and train a regular CNN on top of these images. In the case of coordinate array representation, we project the coordinates onto two different arrays, one representing the x-coordinates and one representing the y-coordinates. As multiple points can be projected down to the same location, each vertex projection carries a weight of 1/8 for a total of 8 vertices. We concatenate the two arrays and train a multi-layer perceptron (MLP) on top of this representation. A visual depiction of these representations is provided in Fig. 14. In particular, we train ResNet-18 on the coordinate image representation and a 4-layer MLP w/ ReLU activations on the coordinate array representation. This change in representation makes a negligible impact to the results as depicted in Fig. 5, where the model generalizes to intermediate views of the training axis, but fails to generalize to novel axes of rotation. These results indicate that our findings are not a representation-specific artifact. #### 4.1.2 Generalization to real-world objects We visualize the results from our chairs dataset in Fig. 6. We observe a similar trend where the generalization of the model is higher than pure 2D matching but lower than full 3D generalization. These results advocate that the obtained results are not an artifact of the chosen object i.e. Paperclips, but rather, relate to the recognition behavior of deep learning models. #### 4.1.3 Generalization to other architectures Fig. 3 presented generalization results for ResNet-18 [12]. In Fig. 7, we additionally show results for VGG-11 (w/ BN) [22] and ViT-B/16 [10]. ViT-B/16 trained using 1000 classes failed to converge in our case, resulting in very low final accuracy. It is clear from the figure that our findings do generalize to architectures beyond ResNets. The plot also hints that the model is slightly better at generalizing towards rotation not directly in the image plane (x-axis) as compared to rotations directly along the image plane (z-axis). This highlights that in-plane rotations are particularly hard for deep-learning models to handle. Figure 7: **Our results generalize to other architectures. We plot the performance of the model with an increasing number of uniformly sampled views on the paperclips dataset for VGG and ViT (all previous results were based on ResNet-18). The figure indicates that our findings are not an architecture-specific artifact, but relate to the general behavior of deep learning models.** #### 4.1.4 Generalization w/ 2D rotation augmentations As the model particularly struggles to handle in-plane rotations, we evaluate the performance of the model by using in-plane rotations as an augmentation. In-plane rotation is equivalent to z-axis rotation as the camera is perfectly aligned with the rotation axis. The results are visualized in Fig. 8. We see that in-plane rotation improves generalization along the z-axis (which is aligned with in-plane rotations) while having no impact on generalization along the x-axis. This indicates that in-plane rotation augmentations alone are insufficient to force the model to learn a holistic Figure 8: **Random 2D rotation augmentation along the image plane improves generalization. We plot the performance of the model along all three axes (see Fig. 12 for a visual illustration of the relationship between 3D rotations and the image plane). We see that random rotations in the image plane improve generalization along the z-axis which is partially aligned with the image plane but fails to improve generalization along a different axis i.e. x-axis. We also visualize multi-axis rotations in the second row for 12 training views and 1000 classes to get a better understanding of the model’s generalization.** Figure 9: **Model benefits from a larger number of classes for generalization. We plot the performance of the model with an increasing number of classes when training on only a particular set of rotations only along the y-axis per class ([-60, 60]). Training views are marked with vertical lines. The plot shows that the model’s generalization drastically improves with an increasing number of classes, specifically for intermediate views without any supporting training examples (\(100^{\circ}-260^{\circ}\)), hinting that the model is leveraging knowledge across classes.** 3D representation. #### 4.1.5 Robustness against changes in background In order to ensure that the obtained results are not an artifact of the simple black background without any distractors, we replace the black background with a randomly chosen image from the landscapes dataset found on Kaggle1 for every example in the batch as part of our augmentation pipeline (sample training images with the random backgrounds are visualized in Fig. 15). We find qualitatively similar results with these random backgrounds even though the task is considerably harder, resulting in higher error rates. Footnote 1: [https://www.kaggle.com/datasets/arnaud58/landscape-pictures](https://www.kaggle.com/datasets/arnaud58/landscape-pictures) ### Range-limited sampled views In this setting, we explore generalization from views sampled from a limited range of rotations. We train on a small subset of views sampled uniformly from [-30, 30] degrees of rotation and evaluate the performance of the model on all possible rotations. We visualize these results in Fig. 10. It is clear from the figure that despite an increasing number of views sampled uniformly within this range, the model fails to generalize to views outside this range, indicating that the model failed to construct a view-independent representation of the input. Results in Section 4.1 already ruled out the possibility of pure 2D matching or full 3D recognition, making the linear combination of views the most likely class of behavior employed by deep models for recognition. However, for objects such as paperclips, where self-occlusion is not an issue, a linear combination of views should be able to extrapolate i.e. generalize within the axis of rotation. Since this is not the case, this indicates that the model is operating at somewhere close to the linear combination of views, but is still distinct in some aspects. #### 4.2.1 Extending the range of views The model trained on range-limited sampled views fails to extrapolate to novel views along the training axis. In order to understand the relationship between view range and expected generalization along the training axis, we evaluate the performance of the model while relaxing the range limits used to train the model in Fig. 11. We see that once the range covers a large fraction of the possible views, and there are a sufficiently large number of views used for training, the model generalizes within the axis of rotation. However, this generalization is still limited to the training axis. Furthermore, this generalization is also correlated with the number of classes. We further evaluate the relationship between the number of classes and generalization for a particular selection of training on views from [-60, 0, 60] degrees of rotation along the y-axis in Fig. 9. The plot shows that despite having the same number of views available for training the model, simply increasing the number of classes helps the model to generalize to rotations along the training axis by improv Figure 11: **Large view range is important for generalization.** We plot the performance of the model with an increasing range from which the views are sampled when training and evaluating with rotations only along the y-axis. The plot shows that the model ultimately achieves generalization to different rotations along the y-axis outside this limited range of views when increasing the range from which the views are sampled, specifically with a large number of classes. This hints that the model is leveraging knowledge across classes. Figure 10: **Large number of views from a limited range fails to achieve generalization.** We plot the performance of the model with an increasing number of views sampled in the range [-30, 30] on the paperclips dataset when training and evaluating with rotations only along the y-axis using 10000 classes. The plot shows that the model fails to generalize to different rotations along the y-axis outside this limited range of views. ing the model's performance, particularly on intermediate views between \(100^{\circ}\) to \(260^{\circ}\) rotation. This hints that the model is able to share knowledge between classes in order to construct a more general representation of the input. ## 5 Conclusion This paper has experimentally studied the behavior class employed by deep learning models for visual recognition by analyzing the generalization capabilities of the model on axis-aligned rotations of 3D objects when trained on a limited number of views. Our results show that deep learning models generalize to novel views in a way that differs from all '_classical_' computer vision models. The closest model is matching based on a linear combination of views. We summarize our findings as: * We have shown that deep models do not perform pure 2D matching since the achieved generalization is higher than a purely view-based recognition system * We have shown that deep models do not perform full 3D recognition because the model failed to achieve generalization to rotations along novel axes * We have shown that deep models behave similarly to linear interpolation of views, but are still distinct in terms of behavior as the model failed to generalize to rotations outside the limited range of views even for simple paperclip objects without self-occlusions * We have shown that 3D generalization abilities generalize across different 3D models These results are of practical importance in two ways. First, they allow us to design training sets for 3D object recognition with deep networks more efficiently by particularly focusing on views that are most beneficial for the model to learn. Our results show that covering entire axes is better than sampling more views from a limited range of rotations along the axes. Second, they imply that incorporating better 3D generalization capabilities directly into our deep networks such as object reconstruction followed by recognition may significantly improve the efficiency at which our networks use training data. This sample-efficient reconstruction can be achieved via structure from motion theorems [14].
2302.02829
Collective Robustness Certificates: Exploiting Interdependence in Graph Neural Networks
In tasks like node classification, image segmentation, and named-entity recognition we have a classifier that simultaneously outputs multiple predictions (a vector of labels) based on a single input, i.e. a single graph, image, or document respectively. Existing adversarial robustness certificates consider each prediction independently and are thus overly pessimistic for such tasks. They implicitly assume that an adversary can use different perturbed inputs to attack different predictions, ignoring the fact that we have a single shared input. We propose the first collective robustness certificate which computes the number of predictions that are simultaneously guaranteed to remain stable under perturbation, i.e. cannot be attacked. We focus on Graph Neural Networks and leverage their locality property - perturbations only affect the predictions in a close neighborhood - to fuse multiple single-node certificates into a drastically stronger collective certificate. For example, on the Citeseer dataset our collective certificate for node classification increases the average number of certifiable feature perturbations from $7$ to $351$.
Jan Schuchardt, Aleksandar Bojchevski, Johannes Gasteiger, Stephan Günnemann
2023-02-06T14:46:51Z
http://arxiv.org/abs/2302.02829v1
# Collective Robustness Certificates: ###### Abstract In tasks like node classification, image segmentation, and named-entity recognition we have a classifier that simultaneously outputs multiple predictions (a vector of labels) based on a single input, i.e. a single graph, image, or document respectively. Existing adversarial robustness certificates consider each prediction independently and are thus overly pessimistic for such tasks. They implicitly assume that an adversary can use different perturbed inputs to attack different predictions, ignoring the fact that we have a _single_ shared input. We propose the first collective robustness certificate which computes the number of predictions that are _simultaneously_ guaranteed to remain stable under perturbation, i.e. cannot be attacked. We focus on Graph Neural Networks and leverage their locality property - perturbations only affect the predictions in a close neighborhood - to fuse multiple single-node certificates into a drastically stronger collective certificate. For example, on the Citeseer dataset our collective certificate for node classification increases the average number of certifiable feature perturbations from \(7\) to \(351\). ## 1 Introduction Most classifiers are vulnerable to adversarial attacks (Akhtar & Mian, 2018; Hao-Chen et al., 2020). Slight perturbations of the data are often sufficient to manipulate their predictions. Even in scenarios where attackers are not present it is critical to ensure that models are robust since data can be noisy, incomplete, or anomalous. We study classifiers that collectively output many predictions based on a single input. This includes node classification, link prediction, molecular property prediction, image segmentation, part-of-speech tagging, named-entity recognition, and many other tasks. Various techniques have been proposed to improve the adversarial robustness of such models. One example is adversarial training (Goodfellow et al., 2015), which has been applied to part-of-speech tagging (Han et al., 2020), semantic segmentation (Xu et al., 2020) and node classification (Feng et al., 2019). Graph-related tasks in particular have spawned a rich assortment of techniques. These include Bayesian models (Feng et al., 2020), data-augmentation methods (Entezari et al., 2020) and various robust network architectures (Zhu et al., 2019; Geisler et al., 2020). There are also robust loss functions which either explicitly model an adversary trying to cause misclassifications (Zhou & Vorobeychik, 2020) or use regularization terms derived from robustness certificates (Zugner & Gunnemann, 2019). Other methods try to detect adversarially perturbed graphs (Zhang et al., 2019; Xu et al., 2020) or directly correct perturbations using generative models (Zhang & Ma, 2020). However, none of these techniques provide guarantees and they can only be evaluated based on their ability to defend against known adversarial attacks. Once a technique is established, it may subsequently be defeated using novel attacks (Carlini & Wagner, 2017). We are therefore interested in deriving adversarial robustness certificates which provably guarantee that a model is robust. In this work we focus on node classification.1 Here, the goal is to assign a label to each node in a single (attributed) graph. Node classification can be the target of either _local_ or _global_ adversarial attacks. Local attacks, such as Nettack (Zugner et al., 2018; Zugner et al., 2020), attempt to alter the prediction of a particular node in the graph. Global attacks, as proposed by Zugner and Gunnemann (2019), attempt to alter the predictions of many nodes at once. With global attacks, the attacker is constrained by the fact that all predictions are based on a _single_ shared input. To successfully attack some nodes the attacker might need to insert certain edges in the graph, while for another set of nodes the same edges must not be inserted. With such mutually exclusive adversarial perturbations, the attacker is forced to make a choice and can attack only one subset of nodes (see Fig. 1). Existing certificates (Zugner and Gunnemann, 2019; Bojchevski and Gunnemann, 2019; Bojchevski et al., 2020) are designed for local attacks, i.e. to certify the predictions of individual nodes. So far, there is no dedicated certificate for global attacks, i.e. to certify the predictions of many nodes at once2. A naive certificate for global attacks can be constructed from existing single-node certificates as follows: One simply certifies each node's prediction independently and counts how many are guaranteed to be robust. This, however, implicitly assumes that an adversary can use different perturbed inputs to attack different predictions, ignoring the fact that we have a single shared input. Footnote 2: Chiang et al. (2020) certify multi-object detection, but they still treat each detected object independently. We propose a _collective robustness certificate_ for global attacks that directly computes the number of _simultaneously_ certifiable nodes for which we can guarantee that their predictions will not change. This certificate explicitly models that the attacker is limited to a single shared input and thus accounts for the resulting mutual exclusivity of certain attacks. Specifically, we fuse multiple single-node certificates, which we refer to as base certificates, into a drastically (and provably) stronger collective one. Our approach is independent of how the base certificates are derived, and any improvements to the base certificates directly translate to improvements to the collective certificate. The key property which we exploit is _locality_. For example, in a \(k\)-layer message-passing graph neural network (Gilmer et al., 2017) the prediction for any given node depends only on the nodes in its \(k\)-hop neighborhood. Similarly, the predicted segment for any pixel depends only on the pixels in its receptive field, and the named-entity assigned to any word only depends on words in its surrounding. For classifiers that satisfy locality, perturbations to one part of the graph do not affect all nodes. Adversaries are thus faced with a budget allocation problem: It might be possible to attack different subsets of nodes via perturbations to different subgraphs, but performing all perturbations at once could exceed their adversarial budget. The naive approach discussed above ignores this, overestimating how many nodes can be attacked. We design a simple (mixed-integer) linear program (LP) that enforces a single perturbed graph. It leverages locality by only considering the amount of perturbation within each receptive field when evaluating the single-node certificates (see Fig. 1). We evaluate our approach on different datasets and with different base certificates. We show that incorporating locality alone is sufficient to obtain significantly better results. Our proposed certificate: * Is the first _collective_ certificate that explicitly models simultaneous attacks on multiple outputs. * Fuses individual certificates into a provably stronger certificate by explicitly modeling _locality_. * Is the first node classification certificate that can model not only global and local budgets, but also the number of adversary-controlled nodes, regardless of whether the base certificates support this. Figure 1: Previous certificates consider each node independently. Most nodes cannot be certified since the adversary can choose a different perturbed graph per node (left). This is impossible in practice due to mutually exclusive perturbations. Our collective certificate enforces a single perturbed graph (center). It aggregates the amount of perturbation within each receptive field and then evaluates a single-node certificate to determine whether the corresponding prediction is robust (right). ## 2 Preliminaries **Data and models.** We define our unperturbed data as an attributed graph \(\mathcal{G}=(\mathbf{X},\mathbf{A})\in\mathbb{G}\) with \(\mathbb{G}=\{0,1\}^{N\times D}\times\{0,1\}^{N\times N}\), consisting of \(N\)\(D\)-dimensional feature vectors and a directed \(N\times N\) adjacency matrix. Each vertex is assigned one out of \(C\) classes by a multi-output classifier \(f:\mathbb{G}\mapsto\{1,\dots,C\}^{N}\). In the following, \(f_{n}(\mathcal{G})=f_{n}(\mathbf{X},\mathbf{A})=f_{n}\) refers to the prediction for node \(n\). **Collective threat model.** Unlike previous certificates, we model an adversary that aims to change multiple predictions at once. Let \(\mathbb{B}_{\mathcal{G}}\subseteq\mathbb{G}\) be a set of admissible perturbed graphs. Given a clean graph \(\mathcal{G}\), the adversary tries to find a \(\mathcal{G}^{\prime}\in\mathbb{B}_{\mathcal{G}}\) that maximizes the number of misclassified nodes, i.e. \(\sum_{n\in\mathbb{T}}\mathbf{1}_{f_{n}(\mathcal{G})\neq f_{n}(\mathcal{G}^{ \prime})}\), for some set of target nodes \(\mathbb{T}\subseteq\{1,\dots,N\}\). Following prior work (Zugner and Gunnemann, 2019), we constrain the set of admissible perturbed graphs \(\mathbb{B}_{\mathcal{G}}\) through global and (optionally) local constraints on the number of changed bits. Our global constraints are parameterized by scalars \(r_{\mathbf{X}_{\text{add}}},r_{\mathbf{X}_{\text{del}}},r_{\mathbf{A}_{\text{add}}},r_{ \mathbf{A}_{\text{del}}}\in\mathbb{N}_{0}\). They are an upper limit on how many bits can be added (\(0\to 1\)) or deleted (\(1\to 0\)) when perturbing \(\mathbf{X}\) and \(\mathbf{A}\). Our local constraints are parameterized by vectors \(r_{\mathbf{X}_{\text{add,loc}}},r_{\mathbf{X}_{\text{del,loc}}},r_{\mathbf{A}_{\text{add, loc}}},r_{\mathbf{A}_{\text{del,loc}}}\in\mathbb{N}_{0}^{N}\). They are an upper limit on how many bits can be added or deleted per row of \(\mathbf{X}\) and \(\mathbf{A}\), i.e. how much the attributes of a particular node can change and how many incident edges can be perturbed. Often, it is reasonable to assume that no adversary has direct control over the entire graph. Instead, a realistic attacker should only be able to perturb a small (adaptively chosen) subset of nodes. To model this, we introduce an additional parameter \(\sigma\in\mathbb{N}\). For all \((\mathbf{X}^{\prime},\mathbf{A}^{\prime})\in\mathbb{B}_{\mathcal{G}}\), there must be a set of node indices \(\mathbb{S}\subseteq\{1,\dots,N\}\) with \(|\mathbb{S}|\leq\sigma\) such that for all \(d\in\{1,\dots,D\}\) and \(n,m\in\{1,\dots,N\}\): \[\left(X^{\prime}_{n,d}\neq X_{n,d}\implies n\in\mathbb{S}\right)\left(A^{ \prime}_{n,m}\neq A_{n,m}\implies n\in\mathbb{S}\lor m\in\mathbb{S}\right). \tag{1}\] The set \(\mathbb{S}\) is not fixed, but chosen by the adversary.3 The resulting set \(\mathbb{B}_{\mathcal{G}}\) is formally defined in Section B. If the global budget parameters are variable and the remaining parameters are clear from the context, we treat \(\mathbb{B}_{\mathcal{G}}\) as a function \(\mathbb{B}_{\mathcal{G}}:\mathbb{N}_{0}^{4}\mapsto\mathcal{P}(\mathbb{G})\) that, given global budget parameters, returns the set of all perturbed graphs fulfilling the constraints. Footnote 3: Note that the adversary only needs to control one of the nodes incident to an edge in order to perturb it. We do not associate different costs for perturbing different nodes or edges, but such an extension is straightforward. **Local predictions.** Our certificate exploits the locality of predictions, i.e. the fact that predictions are only based on a subset of the input data. We characterize the receptive field of \(f_{n}\) via an indicator vector \(\mathbf{\psi}^{(n)}\in\{0,1\}^{N}\) corresponding to rows in attribute matrix \(\mathbf{X}\) and an indicator matrix \(\mathbf{\Psi}^{(n)}\in\{0,1\}^{N\times N}\) corresponding to entries in adjacency matrix \(\mathbf{A}\). For all \((\mathbf{X}^{\prime},\mathbf{A}^{\prime}),(\mathbf{X}^{\prime\prime},\mathbf{A}^{\prime\prime}) \in\mathbb{B}_{\mathcal{G}}\): \[\sum_{m=1}^{N}\sum_{d=1}^{D}\psi_{m}^{(n)}\mathbf{1}_{X^{\prime}_{m,d}\neq X^{ \prime\prime}_{m,d}}+\sum_{i=1}^{N}\sum_{j=1}^{N}\Psi_{i,j}^{(n)}\mathbf{1}_{ A^{\prime}_{i,j}\neq A^{\prime\prime}_{i,j}}=0\implies f_{n}(\mathbf{X}^{ \prime},\mathbf{A}^{\prime})=f_{n}(\mathbf{X}^{\prime\prime},\mathbf{A}^{\prime\prime}). \tag{2}\] Eq. 2 enforces that as long as all nodes and edges for which \(\mathbf{\psi}^{(n)}=1\) or \(\mathbf{\Psi}^{(n)}=1\) remain unperturbed, the prediction \(f_{n}\) does not change. Put differently, changes to the rest of the data do not affect the prediction. Note that the adversary can alter receptive fields, e.g. add edges to enlarge them. To capture all potential alterations, \(\mathbf{\psi}^{(n)}\) and \(\mathbf{\Psi}^{(n)}\) correspond to all data points that influence \(f_{n}\) under some graph in \(\mathbb{B}_{\mathcal{G}}\), i.e. the union of all receptive fields achievable under the threat model. ## 3 Compact representation of Base certificates Before deriving our collective certificate, we define a representation that allows us to efficiently evaluate base certificates. A base certificate is any procedure that can provably guarantee that the prediction \(f_{n}\) for a specific node \(n\) cannot be changed by any perturbed graph in an admissible set, such as sparsity-aware smoothing (Bojchevski et al., 2020). As you shall see in the next section, our collective certificate requires evaluating base certificates for varying adversarial budgets within \(\mathbb{L}=[r_{\mathbf{X}_{\text{add}}}]\times[r_{\mathbf{X}_{\text{del}}}]\times[r_{ \mathbf{A}_{\text{add}}}]\times[r_{\mathbf{A}_{\text{del}}}]\) (with \([k]=\{0,\dots,k\}\)), the set of vectors that do not exceed the collective global budget. A base certificate implicitly partitions \(\mathbb{L}\) into a set of budgets \(\mathbb{K}^{(n)}\subseteq\mathbb{L}\) for which the prediction \(f_{n}\) is certifiably robust and its complement \(\overline{\mathbb{K}^{(n)}}=\mathbb{L}\setminus\mathbb{K}^{(n)}\) with \[\mathbb{K}^{(n)}\subseteq\left\{\mathbf{\rho}\in\mathbb{N}_{0}^{4}\mid\mathbf{\rho} \in\mathbb{L}\land\forall(\mathbf{X}^{\prime},\mathbf{A}^{\prime})\in\mathbb{B}_{ \mathcal{G}}(\mathbf{\rho}):f_{n}(\mathbf{X},\mathbf{A})=f_{n}(\mathbf{X}^{\prime},\mathbf{A}^{ \prime})\right\}. \tag{3}\] Note the subset relation. The set \(\mathbb{K}^{(n)}\) does not have to contain all budgets for which \(f_{n}\) is robust. Conversely, a certain budget vector \(\mathbf{\rho}\) not being part of \(\mathbb{K}^{(n)}\) does not necessarily mean that \(f_{n}\) can be attacked under threat model \(\mathbb{B}_{\mathcal{G}}(\mathbf{\rho})\) - its robustness is merely unknown. We now make the following natural assumption about base certificates: If a classifier is certifiably robust to perturbations with a large global budget, it should also be certifiably robust to perturbations with a smaller global budget. \[\forall\mathbf{\rho}\in\mathbb{K}^{(n)},\mathbf{\rho}^{\prime}\in\mathbb{L}:[\forall d \in\{1,2,3,4\}:\rho_{d}^{\prime}\leq\rho_{d}]\implies\left[\mathbf{\rho}^{\prime }\in\mathbb{K}^{(n)}\right]. \tag{4}\] From a geometric point of view, Eq. 4 means that the budgets \(\mathbb{K}\) for which the prediction \(f_{n}\) is certifiably robust form a singular enclosed volume around \((0\quad 0\quad 0\quad 0)^{T}\) within the larger volume \(\mathbb{L}\). Determining whether a classifier is robust to perturbations in \(\mathbb{B}_{\mathcal{G}}(\mathbf{\rho})\) is equivalent to determining which side of the surface enclosing the volume \(\mathbb{K}\) the budget vector \(\mathbf{\rho}\) lies on. This can be be done by evaluating linear inequalities, as shown in the following. First, let us assume that all but one of the budgets are zero, e.g. \(\mathbb{L}=[r_{\mathbf{X}_{\mathrm{add}}}]\times[0]\times[0]\times[0]\), with \(r_{\mathbf{X}_{\mathrm{add}}}>0\). Due to Eq. 4 there must be a distinct value \(p_{n}\in\mathbb{N}_{0}\) (the smallest uncertifiable budget) with \(\forall\mathbf{\rho}\in\mathbb{L}:\mathbf{\rho}\in\overline{\mathbb{K}^{(n)}} \iff\rho_{1}\geq p_{n}\). Evaluating the base certificate can thus be performed by evaluating a single inequality. This approach can be generalized to arbitrary types of perturbations. Instead of using a single scalar \(p_{n}\), we characterize the volume of budgets \(\mathbb{K}^{(n)}\) via the pareto front of points on its enclosing surface: \[\mathbb{P}^{(n)}=\left\{\mathbf{\rho}\in\overline{\mathbb{K}^{(n)}}\mid\neg \exists\mathbf{\rho}^{\prime}\in\overline{\mathbb{K}^{(n)}}:\mathbf{\rho}^{\prime} \neq\mathbf{\rho}\wedge\forall d\in\{1,2,3,4\}:\rho_{d}^{\prime}\leq\rho_{d} \right\}. \tag{5}\] These points fulfill \(\forall\mathbf{\rho}\in\mathbb{L}\left(\mathbf{\rho}\in\overline{\mathbb{K}^{(n)}} \iff\exists\mathbf{p}\in\mathbb{P}^{(n)},\forall d\in\{1,2,3,4\}:\rho_{d}\geq p_{ d}\right).\) Here, evaluating the base certificate can be performed by evaluating \(4|\mathbb{P}|\) inequalities. In the following, we assume that we are directly given this pareto front (or the smallest uncertifiable budget). Finding the pareto front can be easily implemented via a flood-fill algorithm that identifies the surface of volume \(\mathbb{K}^{(n)}\), followed by a thinning operation (for more details, see Section D). ## 4 Collective certificate To improve clarity in this section, we only discuss the global budget constraints. All remaining constraints from the threat model can be easily modelled as linear constraints. You can find the certificate for the full threat model in Section C. We first formalize the naive collective certificate described in the introduction, which implicitly allows the adversary to use different graphs to attack different predictions. We then derive the proposed collective certificate, first focusing on attribute additions before extending it to arbitrary perturbations. We relax the certificate to a linear program to enable fast computation and show the certificate's tightness when using a randomized smoothing base certificate. We conclude by discussing the certificate's time complexity and limitations. **Naive collective certificate.** Assume we are given a clean input \((\mathbf{X},\mathbf{A})\), a multi-output classifier \(f\), a set \(\mathbb{T}\) of target nodes and a set of admissible perturbed graphs \(\mathbb{B}_{\mathcal{G}}\) fulfilling collective global budget constraints given by \(r_{\mathbf{X}_{\mathrm{add}}},r_{\mathbf{X}_{\mathrm{add}}},r_{\mathbf{A}_{\mathrm{add}}},r_{\mathbf{A}_{\mathrm{add}}}\). Let \(\mathbb{L}=[r_{\mathbf{X}_{\mathrm{add}}}]\times[r_{\mathbf{X}_{\mathrm{add}}}]\times[ r_{\mathbf{A}_{\mathrm{add}}}]\times[r_{\mathbf{A}_{\mathrm{add}}}]\) be the set of all vectors that that do not exceed the collective global budget. Further assume that the base certificate guarantees that each classifier \(f_{n}\) is certifiable robust to perturbations within a set of budgets \(\mathbb{K}^{(n)}\) (see Eq. 3). As discussed, the naive certificate simply counts the predictions whose robustness to perturbations from \(\mathbb{B}_{\mathcal{G}}\) is guaranteed by the base certificate. Using the representation of base certificates introduced in Section 3, this can be expressed as \(\sum_{n\in\mathbb{T}}\mathbf{1}\left[\mathbb{K}^{(n)}=\mathbb{L}\right]\). From the definition of \(\mathbb{K}^{(n)}\) in Eq. 3, we can directly see that this is a lower bound on the optimal value of \(\sum_{n\in\mathbb{T}}\min_{(\mathbf{X}^{\prime},\mathbf{A}^{\prime})\in\mathbb{B}_{ \mathcal{G}}}\mathbf{1}\left[f_{n}(\mathbf{X},\mathbf{A})=f_{n}(\mathbf{X}^{\prime},\mathbf{A}^{ \prime})\right]\), i.e. the number of predictions guaranteed to be stable under attack. Note that each summand involves a different minimization problem, meaning the adversary may use a different graph to attack each of the nodes. **Collective certificate for attribute additions.** To improve upon the naive certificate, we want to determine the number of predictions that are simultaneously robust to attacks with a _single_ graph: \[\min_{(\mathbf{X}^{\prime},\mathbf{A}^{\prime})\in\mathbb{B}_{\mathcal{G}}}\sum_{n\in \mathbb{T}}\mathbf{1}\left[f_{n}(\mathbf{X},\mathbf{A})=f_{n}(\mathbf{X}^{\prime},\mathbf{A}^{ \prime})\right]. \tag{6}\] Solving this problem is usually not tractable. For simplicity, let us assume that the adversary is only allowed to perform attribute additions. As before, we can lower-bound the indicator functions using the base certificates: \[\min_{(\mathbf{X}^{\prime},\mathbf{A}^{\prime})\in\mathbb{B}_{\mathcal{O}}}\sum_{n\in \mathbb{T}}\mathbf{1}\left[\left(b\quad 0\quad 0\quad 0\right)^{T}\in\mathbb{K}^{(n)}\right] \tag{7}\] where \(b=\sum_{(n,d):X_{n,d}=0}X^{\prime}_{n,d}\) is the number of attribute additions for a given perturbed graph. Since this certificate only depends on the number of perturbations, it is sufficient to optimize over the number of attribute additions while enforcing the global budget constraint: \[\min_{b\in\mathbb{N}_{0}}\sum_{n\in\mathbb{T}}\mathbf{1}\left[\left(b\quad 0\quad 0 \quad 0\right)^{T}\in\mathbb{K}^{(n)}\right]\text{ s.t. }b\leq r_{\mathbf{X}_{\text{ valid}}}. \tag{8}\] There are two limitations: (1) The certificate does not account for locality, but simply considers the number of perturbations in the entire graph. In this regard, it is no different from the naive collective certificate; (2) Evaluating the indicator functions, i.e. certifying the individual nodes, might involve complex optimization problems that are difficult to optimize through. We tackle (1) by evaluating the base certificates locally. **Lemma 1**: _Assume multi-output classifier \(f\), corresponding receptive field indicators \(\mathbf{\psi}^{(n)}\in\{0,1\}^{N}\) and \(\mathbf{\Psi}^{(n)}\in\{0,1\}^{N\times N}\), and a clean graph \((\mathbf{X},\mathbf{A})\). Let \(\mathbb{K}^{(n)}\) be the set of certifiable global budgets of prediction \(f_{n}\), as defined in Eq. 3. Let \((\mathbf{X}^{\prime},\mathbf{A}^{\prime})\) be a perturbed graph. Define \(\mathbf{X}^{\prime\prime}\in\{0,1\}^{N\times D}\) and \(\mathbf{A}^{\prime\prime}\in\{0,1\}^{N\times N}\) as follows:_ \[\mathbf{X}^{\prime\prime}_{i,d} =\psi^{(n)}_{i}\mathbf{X}^{\prime}_{i,d}+(1-\psi^{(n)}_{i})\mathbf{X}_{i,d}, \tag{9}\] \[\mathbf{A}^{\prime\prime}_{i,j} =\Psi^{(n)}_{i,j}\mathbf{A}^{\prime}_{i,j}+(1-\Psi^{(n)}_{i,j})\mathbf{A} _{i,j}, \tag{10}\] _i.e. use values from the clean graph for bits that are not in \(f_{n}\)'s receptive field. If there exists a vector of budgets \(\mathbf{\rho}\in\mathbb{N}_{0}^{4}\) such that \((\mathbf{X}^{\prime\prime},\mathbf{A}^{\prime\prime})\in\mathbb{B}_{\mathcal{O}}(\bm {\rho})\) and \(\mathbf{\rho}\in\mathbb{K}^{(n)}\), then \(f_{n}(\mathbf{X},\mathbf{A})=f_{n}(\mathbf{X}^{\prime},\mathbf{A}^{\prime})\)._ See proof in Section B. Due to Lemma 1 we can ignore all perturbations outside \(f_{n}\)'s receptive field when evaluating its base certificate. We can thus replace \(\left(b\quad 0\quad 0\quad 0\right)^{T}\) in Eq. 8 with \(\left(\mathbf{b}^{T}\mathbf{\psi}^{(n)}\quad 0\quad 0\quad 0\right)^{T},\) where the vector \(\mathbf{b}\in\mathbb{N}_{0}^{N}\) indicates the number of attribute additions at each node. Optimizing over \(\mathbf{b}\) yields a collective certificate that accounts for locality: \[\min_{\mathbf{b}\in\mathbb{N}_{0}}\sum_{n\in\mathbb{T}}\mathbf{1}\left[\left(\mathbf{b}^{ T}\mathbf{\psi}^{(n)}\quad 0\quad 0\quad 0\right)^{T}\in\mathbb{K}^{(n)}\right]\text{ s.t. }||\mathbf{b}||_{1}\leq r_{\mathbf{X}_{\text{ valid}}}. \tag{11}\] We now tackle issue (2) by employing the compact representation of base certificates defined in Section 3. Since we are only allowing one type of perturbation, the base certificate of each classifier \(f_{n}\) is characterized by the smallest uncertifiable radius \(p_{n}\) (see Section 3). To evaluate the indicator function in Eq. 11 we simply have to compare the number of perturbations in \(f_{n}\)'s receptive field to \(p_{n}\), which can be implemented via the following MILP: \[\min_{\mathbf{b}\in\mathbb{N}_{0}^{N},\mathbf{t}\in\{0,1\}^{N}}|\mathbb{T }|-\sum_{n\in\mathbb{T}}t_{n} \tag{12}\] \[\text{s.t. }\mathbf{b}^{T}\mathbf{\psi}^{(n)}\geq p_{n}t_{n}\quad\forall n \in\{1,\dots,N\}\] (13) \[||\mathbf{b}||_{1}\leq r_{\mathbf{X}_{\text{ valid}}}. \tag{14}\] Eq. 14 ensures that the number of perturbations fulfills the global budget constraint. Eq. 13 ensures that the indicator \(t_{n}\) can only be set to \(1\) if the local perturbation on the l.h.s. exceeds or matches \(p_{n}\), i.e. \(f_{n}\) is _not_ robustly certified by the base certificate. The adversary tries to minimize the number of robustly certified predictions in \(\mathbb{T}\) (see Eq. 8), which is equivalent to Eq. 12. **Collective certificate for arbitrary perturbations**. Lemma 1 holds for arbitrary perturbations. We only have to consider the perturbations within a prediction's receptive field when evaluating its base certificate. However, when multiple perturbation types are allowed, the base certificate of a prediction \(f_{n}\) is not characterized by a scalar \(p_{n}\), but by its pareto front \(\mathbb{P}^{(n)}\) (see Eq. 5). Let \(\mathbf{P}^{(n)}\in\mathbb{N}_{0}^{[\mathbb{P}^{(n)}]\times 4}\) be a matrix encoding of the set \(\mathbb{P}^{(n)}\). To determine if \(f_{n}\) is robust we can check whether there is some pareto-optimal point \(\mathbf{P}_{i,:}^{(n)}\) such that the amount of perturbation in \(f_{n}\)'s receptive field matches or exceeds \(\mathbf{P}_{i,:}^{(n)}\) in all four dimensions. This can again be expressed as a MILP (see Eq. 15 to Eq. 23 below). As before, we use a vector \(\mathbf{t}\) with \(t_{n}=1\) indicating that \(f_{n}\) is not certified by the base certificate. The adversary tries to find a budget allocation (parameterized by \(\mathbf{b}_{\mathbf{X}_{\text{add}}},\mathbf{b}_{\mathbf{X}_{\text{del}}}\) and \(\mathbf{B}_{\mathbf{A}}\)) that minimizes the number of robustly certified predictions in \(\mathbb{T}\) (see Eq. 15). Eq. 20 and Eq. 21 ensure that the budget allocation is consistent with the global budget parameters characterizing \(\mathbb{B}_{\mathcal{G}}\). The value of \(t_{n}\) is determined by the following constraints: First, Eq. 17 to Eq. 19 ensure that \(Q_{\mathcal{D},d}^{(n)}\) is only set to \(1\) if the local perturbation matches or exceeds the pareto-optimal point corresponding to row \(p\) of \(\mathbf{P}^{(n)}\) in dimension \(d\). The constraints in Eq. 16 implement logic operations on \(\mathbf{Q}^{(n)}\): Indicator \(s_{p}^{(n)}\) can only be set to \(1\) if \(\forall d\in\{1,2,3,4\}:Q_{p,d}^{(n)}=1\). Indicator \(t_{n}\) can only be set to \(1\) if \(\exists p\in\{1,\ldots,|\mathbb{P}^{(n)}|\}:s_{p}^{(n)}=1\). Combined, these constraints enforce that if \(t_{n}=1\), there must be some point in \(\mathbb{P}^{(n)}\) that is exceeded or matched by the amount of perturbation in all four dimensions. \[\min_{(\mathbf{Q}^{(n)},\mathbf{s}^{(n)})_{n=1}^{N},\mathbf{b}_{\mathbf{X}_{\text{add }}},\mathbf{b}_{\mathbf{X}_{\text{del}}},\mathbf{B}_{\mathbf{A}},\mathbf{t}}|\mathbb{T}|-\sum_{n \in T}t_{n}\] (15) s.t. \[||\mathbf{s}^{(n)}||_{1}\geq t_{n},\qquad Q_{p,d}^{(n)}\geq s_{p}^{(n )}, \tag{16}\] \[(\mathbf{b}_{\mathbf{X}_{\text{add}}})^{T}\mathbf{\psi}^{(n)}\geq Q_{i,1}^{(n )}P_{p,1}^{(n)},\qquad(\mathbf{b}_{\mathbf{X}_{\text{del}}})^{T}\mathbf{\psi}^{(n)}\geq Q_ {p,2}^{(n)}P_{p,2}^{(n)},\] (17) \[\sum_{m,m^{\prime}\leq N}(1-A_{m,m^{\prime}})(\mathbf{\Psi}^{(n)} \odot\mathbf{B}_{\mathbf{A}})_{m,m^{\prime}}\geq Q_{p,3}^{(n)}P_{p,3}^{(n)},\] (18) \[\sum_{m,m^{\prime}\leq N}A_{m,m^{\prime}}(\mathbf{\Psi}^{(n)}\odot \mathbf{B}_{\mathbf{A}})_{m,m^{\prime}}\geq Q_{p,4}^{(n)}P_{p,4}^{(n)},\] (19) \[||b_{\mathbf{X}_{\text{add}}}||_{1}\leq r_{\mathbf{X}_{\text{add}}},\qquad ||b_{\mathbf{X}_{\text{add}}}||_{1}\leq r_{\mathbf{X}_{\text{del}}},\] (20) \[\sum_{(i,j):A_{i,j}=0}B_{\mathbf{A}_{i},j}\leq r_{\mathbf{A}_{\text{add}} },\qquad\sum_{(i,j):A_{i,j}=1}B_{\mathbf{A}_{i},j}\leq r_{\mathbf{A}_{\text{del}}},\] (21) \[\mathbf{s}^{(n)}\in\{0,1\}^{|\mathbb{P}^{(n)}|},\qquad\mathbf{Q}^{(n)} \in\{0,1\}^{|\mathbb{P}^{(n)}|\times 4}\qquad\mathbf{t}\in\{0,1\}^{N}\] (22) \[\mathbf{b}_{\mathbf{X}_{\text{add}}},\mathbf{b}_{\mathbf{X}_{\text{del}}}\in \mathbb{N}_{0}^{N},\qquad\mathbf{B}_{\mathbf{A}}\in\{0,1\}^{N\times N}. \tag{23}\] **LP-relaxation.** For large graphs, finding an optimum to the mixed-integer problem is prohibitively expensive. In practice, we relax integer variables to reals and binary variables to \([0,1]\). Semantically, the relaxation means that bits can be partially perturbed, nodes can be partially controlled by the attacker and classifiers can be partially uncertified (i.e. \(1>t_{n}>0\)). The relaxation yields a linear program, which can be solved much faster. **Tightness for randomized smoothing.** One recent method for robustness certification is randomized smoothing (Cohen et al., 2019). In randomized smoothing, a (potentially non-deterministic) base classifier \(h:\mathbb{X}\mapsto\mathbb{Y}\) that maps from some input space \(\mathbb{X}\) to a set of labels \(\mathbb{Y}\) is transformed into a smoothed classifier \(g(x)\) with \(g(x)=\operatorname*{argmax}_{y\in\mathbb{Y}}\Pr\left[h(\phi(x)=y\right]\), where \(\phi(x)\) is some randomization scheme parameterized by input \(x\). For the smoothed \(g(x)\) we can then derive probabilistic robustness certificates. Randomized smoothing is a black-box method that only depends on \(h\)'s expected output behavior under \(\phi(x)\) and does not require any further assumptions. Building on prior randomized smoothing work for discrete data by Lee et al. (2019), Bojchevski et al. (2020) propose a smoothing distribution and corresponding certificate for graphs. Using their method as a base certificate to our collective certificate, the resulting (non-relaxed) certificate is tight. That is, our mixed-integer collective certificate is the best certificate we can obtain for the specified threat model, if we do not use any information other than the classifier's expected predictions and their locality. Detailed explanation and proof in Section E. **Time complexity.** For our method we need to construct the pareto fronts corresponding to each prediction's base certificate. This has to be performed only once and the results can then be reused in evaluating the collective certificate with varying parameters. We discuss the details of this pre-processing in Section D. The complexity of the collective certificate is based on the number of constraints and variables of the underlying (MI)LP. In total, we have \(13\sum_{n=1}^{N}|\mathbb{P}^{(n)}|+8N+2e+5\) constraints and \(5\sum_{n=1}^{N}|\mathbb{P}^{(n)}|+4N+e\) variables, where \(e\) are the number of edges in the unperturbed graph (we disallow edge additions). For single-type perturbations we have \(\mathcal{O}(N+e)\) terms, linear in the number of nodes and edges. The relaxed LP takes at most a few seconds to certify robustness for single-type perturbations and a few minutes for multiple types of perturbations (see Section 5). **Limitations.** The proposed approach is designed to exploit locality. Without locality, it is equivalent to a naive combination of base certificates that sums over perturbations in the entire graph. A non-obvious limitation is that our notion of locality breaks down if the receptive fields are data-dependent and can be arbitrarily extended by the adversary. Recall how we specified locality in Eq. 2: The indicators \(\mathbf{\psi}^{(n)}\) and \(\mathbf{\Psi}^{(n)}\) correspond to the union of all achievable receptive fields. Take for example a two-layer message-passing neural networks and an adversary that can add new edges. Each node is classified based on its \(2\)-hop neighborhood. For any two nodes \(n,m\), the adversary can construct a graph such that \(m\) is in \(f_{n}\) receptive field. We thus have to treat the \(f_{n}\) as global, even if for any single graph they might only process some subgraph. Nonetheless, our method still yields significant improvements for edge deletions and arbitrary attribute perturbations. As discussed in prior work (Zugner & Gunnemann, 2020) edge addition is inherently harder and less relevant in practice. ## 5 Experimental evaluation **Experimental setup.** We evaluate the proposed approach by certifying node classifiers on multiple graphs and with different base certificates. We use \(20\) nodes per class to construct a train and a validation set. We certify all remaining nodes. We repeat each experiment five times with different random initializations and data splits. Unless otherwise specified, we do not impose any local budget constraints or constraints on the number of attacker-controlled nodes. We compare the proposed method with the naive collective certificate, which simply counts the number of predictions that are certified to be robust by the base certificate. All experiments are based on the relaxed linear programming version of the certificate. We assess the integrality gap to the mixed-integer version in Section A. The code is publicly available under [https://www.daml.in.tum.de/collective-robustness/](https://www.daml.in.tum.de/collective-robustness/). We also uploaded the implementation as supplementary material. **Datasets, models and base certificates.** We train and certify models on the following datasets: Cora-ML (McCallum et al. (2000); Bojchevski & Gunnemann (2018); \(N=2810\), \(7981\) edges, \(7\) classes), Citeseer (Sen et al. (2008); \(N=2110\), \(3668\) edges, \(6\) classes), PubMed (Namata et al. (2012); \(N=19717\), \(44324\) edges, \(3\) classes), Reuters-215784 (\(N=862\), 2586 edges, \(4\) classes) and WebKB (Craven et al. (1998); \(N=877\), \(2631\) edges, \(5\) classes). The graphs for the natural language corpora Reuters and WebKB are constructed using the procedure described in Zhou & Vorobeychik (2020), resulting in 3-regular graphs. We use five types of classifiers: Graph convolution networks (GCN) (Kipf & Welling, 2017), graph attention networks (GAT) (Velickovic et al., 2018), APPNP (Gasteiger et al., 2019), robust graph convolution networks (RGCN) (Zhu et al., 2019) and soft medoid aggregation networks (SMA) (Geisler et al., 2020). All classifiers are configured to have two layers, i.e. each node's classifier is dependent on its two-hop neighborhood. We use two types of base certificates: (Bojchevski et al., 2020) (randomized smoothing, arbitrary perturbations) and Zugner & Gunnemann (2019) (convex relaxations of network nonlinearities, attribute perturbations). We provide a summary of all hyperparameters in Section F. Footnote 4: Distribution 1.0, available from [http://www.daviddlewis.com/resources/testcollections/reuters21578](http://www.daviddlewis.com/resources/testcollections/reuters21578) **Evaluation metrics.** We report the _certified ratio_ on the test set, i.e. the percentage of nodes that are certifiably robust under a given threat model, averaged over all data splits. We further calculate the standard sample deviation in certified ratio (visualized as shaded areas in plots) and the average wall-clock time per collective certificate. For experiments in which only one global budget parameter is altered, we report the _average certifiable radius_, i.e. \(\bar{r}=(\sum_{r=0}^{\infty}\omega(r)*r/\sum_{r=0}^{\infty}\omega(r))\), where \(\omega(r)\) is the certified ratio for value \(r\) of the global budget parameter, averaged over all splits. **Attribute perturbations.** We first evaluate the certificate for a single perturbation type. Using randomized smoothing as the base certificate, we evaluate the certified ratio of GCN classifiers for varying global attribute deletion budgets \(r_{\mathbf{X}_{\text{del}}}\) on the citation graphs Cora, Citeseer and PubMed (for Reuters and WebKB, see Section A). The remaining global budget parameters are set to \(0\). Fig. 2 shows that for all datasets, the proposed method yields significantly larger certified ratios than the naive certificate and can certify robustness for much larger \(r_{\mathbf{X}_{\text{del}}}\). The average certifiable radius on Citeseer increases from \(7.18\) to \(351.73\). The results demonstrate the benefit of using the collective certificate, which explicitly models simultaneous attacks on all predictions. The average wall-clock time per certificate on Cora, Citeseer and PubMed is \(2.0\,\mathrm{s}\), \(0.29\,\mathrm{s}\) and \(336.41\,\mathrm{s}\). Interestingly, the base certificate yields the highest certifiable ratios on Cora, while the collective certificate yields the highest certifiable ratios on PubMed. We attribute this to differences in graph structure, which are explicitly taken into account by the proposed certification procedure. **Simultaneous attribute and graph perturbations.** To evaluate the multi-dimensional version of the certificate, we visualize the certified ratio of randomly smoothed GCN classifiers for different combinations of \(r_{\mathbf{X}_{\text{\tiny{del}}}}\) and \(r_{\mathbf{A}_{\text{\tiny{del}}}}\) on Cora-ML. For an additional experiment on simultaneous attribute additions and deletions, see Section A. Fig. 4 shows that we achieve high certified ratios even when the attacker is allowed to perturb both the attributes and the structure. Comparing the contour lines at \(50\,\mathrm{\char 37}\) the naive certificate can only certify much smaller radii, e.g. at most 6 attribute deletions compared to 39 for our approach. The average wall-clock time per certificate is \(106.90\,\mathrm{s}\). **Different classifiers.** Our method is agnostic towards classifier architectures, as long as they are compatible with the base certificate and their receptive fields can be determined. In Fig. 4 we compare the certified collective robustness of GAT, GCN, and APPNP, using the sparse smoothing certificate on Cora-ML.5 Better base certificates translate into better collective certificates. For an additional experiment on the benefits of robust classifier architectures RGCN and SMA, see Section A. Figure 4: Comparison of certified ratios for GAT, GCN and APPNP on Cora-ML under varying \(r_{\mathbf{X}_{\text{\tiny{del}}}}\) for our (solid lines) and the naïve (dotted lines) collective certificate. **Different base certificates.** Our method is also agnostic to the base certificate type. We show that it works equally well with base certificates other than randomized smoothing. Specifically, we use the method from Zugner & Gunnemann (2019). We certify a GCN model for varying \(r_{\mathbf{X}_{\text{\tiny{adcl}}}}\) on Cite-seer. Unlike randomized smoothing, this base certificate models local budget constraints. Using the default in the base certificate's reference implementation, we limit the number of attribute additions per node to \([0.01D]=21\) for both the base and the collective certificate. Fig. 6 shows that the proposed collective certificate is again significantly stronger. The average certified radius \(\hat{r}\) increases from \(17.12\) to \(971.36\). The average wall-clock time per certificate is \(0.39\,\mathrm{s}\). **Local constraints.** We evaluate the effect of additional constraints in our threat model. We can enforce local budget constraints and limit the number of attacker-controlled nodes, even if they are not explicitly modeled by the base certificate. In Fig. 6, we use a smoothed GCN on Cora-ML and vary both the global budget for edge deletions, \(r_{\mathbf{A}_{\text{\tiny{adcl}}}}\), and the local budgets \(\mathbf{r}_{\mathbf{A}_{\text{\tiny{adcl}},\text{\tiny{loc}}}}\). Even though the base certificate does not support local budget constraints, reducing the number of admissible deletions per node increases the certified ratio as expected. For example, limiting the adversary to one deletion per node more than doubles the certified ratio at \(r_{\mathbf{A}_{\text{\tiny{adcl}}}}=1000\). In Fig. 7, we fix a relatively large local budget of \(16\) edge deletions per node (only \(\sim 5\%\) of nodes on Cora-ML have a degree \(>16\)) and vary the number of attacker-controlled nodes. We see that for any given number of attacker nodes, there is some point \(r_{\mathbf{A}_{\text{\tiny{adcl}}}}\) after which the certified ratio curve becomes constant. This constant value is an an upper limit on the number of classifiers that can be attacked with a given local budget and number of attacker-controlled nodes. It is independent of the global budget. ## 6 Conclusion We propose the first collective robustness certificate. Assuming predictions based on a single shared input, we leverage the fact that an adversary must use a single adversarial example to attack all predictions. We focus on Graph Neural Networks, whose locality guarantees that perturbations to the input graph only affect predictions in a close neighborhood. The proposed method combines many weak base certificates into a provably stronger collective certificate. It is agnostic towards network architectures and base certification procedures. We evaluate it on multiple semi-supervised node classification datasets with different classifier architectures and base certificates. Our empirical results show that the proposed collective approach yields much stronger certificates than existing methods, which assume that an adversary can attack predictions independently with different graphs. ## 7 Acknowledgements This research was supported by the German Research Foundation, Emmy Noether grant GU 1409/2-1, the German Federal Ministry of Education and Research (BMBF), grant no. 01IS18036B, and the TUM International Graduate School of Science and Engineering (IGSSE), GSC 81.
2308.04595
Quantization Aware Factorization for Deep Neural Network Compression
Tensor decomposition of convolutional and fully-connected layers is an effective way to reduce parameters and FLOP in neural networks. Due to memory and power consumption limitations of mobile or embedded devices, the quantization step is usually necessary when pre-trained models are deployed. A conventional post-training quantization approach applied to networks with decomposed weights yields a drop in accuracy. This motivated us to develop an algorithm that finds tensor approximation directly with quantized factors and thus benefit from both compression techniques while keeping the prediction quality of the model. Namely, we propose to use Alternating Direction Method of Multipliers (ADMM) for Canonical Polyadic (CP) decomposition with factors whose elements lie on a specified quantization grid. We compress neural network weights with a devised algorithm and evaluate it's prediction quality and performance. We compare our approach to state-of-the-art post-training quantization methods and demonstrate competitive results and high flexibility in achiving a desirable quality-performance tradeoff.
Daria Cherniuk, Stanislav Abukhovich, Anh-Huy Phan, Ivan Oseledets, Andrzej Cichocki, Julia Gusak
2023-08-08T21:38:02Z
http://arxiv.org/abs/2308.04595v1
# Quantization Aware Factorization ###### Abstract Tensor decomposition of convolutional and fully-connected layers is an effective way to reduce parameters and FLOP in neural networks. Due to memory and power consumption limitations of mobile or embedded devices, the quantization step is usually necessary when pre-trained models are deployed. A conventional post-training quantization approach applied to networks with decomposed weights yields a drop in accuracy. This motivated us to develop an algorithm that finds tensor approximation directly with quantized factors and thus benefit from both compression techniques while keeping the prediction quality of the model. Namely, we propose to use Alternating Direction Method of Multipliers (ADMM) for Canonical Polyadic (CP) decomposition with factors whose elements lie on a specified quantization grid. We compress neural network weights with a devised algorithm and evaluate it's prediction quality and performance. We compare our approach to state-of-the-art post-training quantization methods and demonstrate competitive results and high flexibility in achiving a desirable quality-performance tradeoff. ## 1 Introduction Recent years more and more applications based on deep learning algorithms appear on the market, and many of them are developed to work on mobile and edge devices. However, neural networks which are in the core of such algorithms can not usually be used as it is, because they either do not satisfy memory and energy constraints of devices or perform the inference phase not fast enough to satisfy the user needs. Thus, many approaches to reduce and accelerate neural networks have been proposed in the literature. Conventionally, these approaches include pruning, tensor/factorization methods, quantization, knowledge distillation, and architecture search. Thoughtful combination of different techniques gain their benefits simultaneously. The availability of additional information, such as training data or loss/gradients values, yields additional opportunities to improve performance of compressed models. From this point of view, we distinguish among techniques that do not use additional data, use data but do not perform training, and those that run several training epochs to tune parameters of the compressed model. In our paper we propose a method that jointly performs factorization and quantization of neural networks. Namely, we replace a convolutional layer represented with parameters in FLOAT32 format with a decomposed layer, which is constructed as a sequence of convolutional layers with weights in lower precision format (e.g., INT8/INT6/INT4). By applying our method we benefit from reduction in number of parameters and operations due to factorization and further model size reduction and acceleration due to lower bit representation of weights. Our main contributions are the following: * We introduce an ADMM-based algorithm, which approximates a tensor with a CP-factorization, where factors are represented in lower precision format, e.g., INT8/INT6/INT4. * We propose a neural network compression method that simultaneously performs factorization and quantization of weight tensors based on introduced tensor approximation technique. As far as we are concerned, this is the first work that introduces weights approximation by CP-decomposition with lower precision factors. * We show that in terms of compression/accuracy trade-off our approach performs better than conventional tensor approximation methods followed by quantization of factors. * We demonstrate the effectiveness of our method in comparison with other quantization approaches that are applicable when only a small set of training data is available. ## 2 Related Work There are many papers related to neural network speed-up and compression. In this section we review the most relevant to our proposed technique. ### Factorization Various tensor decompositions [12, 2] are used to factorize weights [20, 13, 8] or activations [3, 7] of deep neural networks. These approaches allow to store less parameters during training and inference and to speedup the computation by reducing the number of required elementary operations. For linear layers, prior works have utilized Tensor-Train (TT) format [19]. For convolutional layers, whose weights are 4D tensors, authors in [14] used CPD. Authors in [21] also decomposed convolutional layers through CP-decomposition but proposed to flatten spatial dimension and factorize 3D tensors instead of the original 4D. Other tensor approximations techniques like Tucker [11] or block term decompositions are used by researches as well. In our paper, we focus on CP decomposition for convolutional layers with kernel spatial dimensions greater than \(1\) and matrix factorization for linear layers or 1x1 convolutional layers. We prefer to study these type of decompositions to others as they show promising accuracy/speed-up trade-off in existing research papers. ### Quantization Due to memory/power consumption limitations of edge devices, the quantization step is necessary, when pre-trained models are deployed. A comprehensive overview of papers on neural network quantization can be found in [6] and [18]. Quantization might greatly impede the quality of a neural network prediction. There are different techniques to restore the quality, some of them requiring additional data or training. Best accuracy restoration can be obtained with quantization-aware training: fine-tuning the quantized model while restricting model weights to be on the quantization grid. Another approach, taken in [26], is to learn bit-width and quantization parameters simultaneously with model weights. However, both techniques require dataset and resources to train. Because of training expenses, methods that allow for more accurate quantization but avoid training/fine-tuning have been a research interest in several papers: authors in [5] scale the weights of consecutive layers which allows them achieve smaller quality drop on a wide variety of networks; AdaRound [17] proves that rounding to the nearest node of the quantization grid is not the best strategy and propose to choose rounding by optimization process which requires only a few thousand samples of data, researches in [10] further develop the idea of AdaRound, complementing it with integer programming to determine the best bit-width for each layer. ### Admm Alternating Direction Method of Multipliers or ADMM [1] is an optimization algorithm for convex problems. The advantages of ADMM algorithm are that it can be efficiently parallelized [22, 16] and the convergence is guaranteed in convex case [1]. However, for non-convex problems the algorithm is not guaranteed to converge or might not converge to a global minimum. Authors in [4] proposed using ADMM in conjunction with local improvement methods to find sufficient heuristic solutions. In [9] authors have applied ADMM to a task of finding a CP-decomposition that satisfied particular constraints like non-negativity, sparsity, etc.. They called this approach AO-ADMM, since one of the objectives was an Alternating Optimization(in particular, Alternating Least Squares) that is used to find CP factors. Authors in [27] have embedded ADMM into training neural network to impose low TT-rank structure on its weights. After training, the weights are decomposed into a TT-format and fine-tuned. [15] aimed to apply ADMM to training neural network with weights that lie on a grid of scaled powers of two. The first objective function in their case is model prediction loss, the second - projection of weight tensors on the grid of scaled powers of two. The authors solve a discrete non-convex constraint problem by alternating between optimizing a scaling factor and projecting onto a fixed grid. The method converges, however, the projection even on the unscaled grid is a non-convex problem and is not guaranteed to converge to global minimum. ## 3 Methodology ### Convolutional Layer Factorization Similar to [14] and, later, [21], we represent convolution layer weights as a 3-way tensor by flattening spatial dimension and decompose it into 3 consecutive convolutional layers. Let \(\mathbf{K}\in\mathbb{R}^{T\times S\times D\times D}\) be a kernel tensor, corresponding to convolutional layer with \(S\) input channels, \(T\) output channels, and \(D\times D\) spatial convolution. Let \(\overline{\mathbf{K}}\in\mathbb{R}^{T\times S\times D^{2}}\) denote the \(\mathbf{K}\) tensor after reshape operation. Using rank-R CP decomposition, one element of \(\overline{\mathbf{K}}\) can be represented as: \[\overline{\mathbf{K}}(t,s,dd)\cong\sum_{r=1}^{R}\overline{K}^{dd}(dd,r)K^{s}(s,r )K^{t}(t,r) \tag{1}\] Then, in order to reshape convolutional layer back to original shape, we reshape factor-matrix \(\overline{K}^{dd}\) to a tensor \(\mathbf{K}^{dd}\) of shape \(D\times D\times R\). \[\mathbf{K}(t,s,j,i)\cong\sum_{r=1}^{R}\mathbf{K}^{dd}(j,i,r)K^{s}(s,r)K^{t}(t,r) \tag{2}\] Therefore, having an input, \(X\), to the convolutional layer, the output tensor, \(Y\), is calculated as: \[\mathbf{Y}(t,h^{\prime},w^{\prime})=\] \[\sum_{h=h^{\prime}-\delta}^{h^{\prime}+\delta}\sum_{w=w^{\prime}- \delta}^{w^{\prime}+\delta}\sum_{s=1}^{S}\mathbf{K}(t,s,h-h^{\prime}+\delta,w-w^{ \prime}+\delta)\mathbf{X}(s,h,w) \tag{3}\] Substituting kernel expression into the formula above, performing rearrangements and grouping summands, we obtain the following consecutive expressions for the approximate evaluation of the convolution \[\mathbf{Z}^{1}(r,h,w)=\sum_{s=1}^{S}K^{s}(s,r)\mathbf{X}(s,h,w),\] \[\mathbf{Z}^{2}(r,h^{\prime},w^{\prime})=\] \[\sum_{h=h^{\prime}-\delta}^{h^{\prime}+\delta}\sum_{w=w^{\prime}- \delta}^{w^{\prime}+\delta}\mathbf{K}^{dd}(h-h^{\prime}+\delta,w-w^{\prime}+\delta,r)\mathbf{Z}^{1}(r,h,w),\] \[\mathbf{Y}(t,h^{\prime},w^{\prime})=\sum_{r=1}^{R}K^{t}(t,r)\mathbf{Z}^{ 2}(r,h^{\prime},w^{\prime}),\] where \(\delta=D/2\). Therefore, we substitute original convolution with a sequence of smaller convolutions: point-wise convolution that reduces the number of input channels from \(S\) to \(R\), convolution with the same spatial dimension as the original but with \(R\) number of input and output channels, and another point-wise convolution that changes the number of channels from \(R\) to \(T\). The last convolution in sequence adds the original bias. 1x1 kernel sizeConvolutional layer with 1x1 kernel is equivalent to a Linear layer with weight matrix of shape \(S\times T\) acting on the input with flattened spatial dimension and, thus, can be decomposed into two matrix factors and replaced with a sequence of two convolutional layers both with kernel size 1x1. ### Quantization Quantizing of neural network means transforming its weights and/or activations into low-bit fixed-point representations, e.g., INT8. It saves memory occupied by model parameters, reduces the amount of data transfer, size and energy consumption of the MAC operation [18]. In our work we use both signed symmetric and asymmetric uniform per-tensor quantization [18] in which tensors are mapped to their int versions in the following way: \[x_{\text{int}}=\text{clip}\left(\lfloor\frac{x}{\text{scale}}\rceil+z;-2^{b-1},2^{b-1}-1\right), \tag{4}\] where \(\lfloor x\rceil\) denotes rounding \(x\) to the nearest integer, scale is a step of the quantization grid, \(z\) is a zero-point and \(b\) is a number of bits in quantization. In case of symmetric quantization \(z\) is assumed to be \(0\). Real-valued approximation is obtained by extracting zero-point and multiplying by scale: \(x\approx\text{scale}*(x_{\text{int}}-z)\). For per-tensor MinMax quantization [18], scale is determined from minimum and maximum values of tensor \(X\): \[\text{scale}=\frac{\max\{X\}-\min\{X\}}{2^{b}-1} \tag{5}\] MinMax quantization, however, might suffer from large outliers. A way to alleviate this issue is to use MSE approach to set range of values [18]. In case of symmetric quantization (to reduce number of optimized parameters from 2 to 1 and provided that the value distribution is symmetric, as shown in Figure 2), \(\text{scale}\) calculation takes the following form: \[\text{scale}=\frac{2q_{\text{max}}}{2^{b}-1} \tag{6}\] and \(q_{\max}\) is determined through optimizing \[\operatorname*{arg\,min}_{q_{\text{max}}}\lVert X-\hat{X}(q_{\max})\rVert_{F}^ {2} \tag{7}\] where \(\hat{X}\) is a quantized tensor \(X\). In Section 4, we perform an ablation study to determine the best quantization scheme (Figure 2). ### Quantization-aware factorization Finding a decomposition that produces less error after quantization can be formulated as a constrained tensor factorization problem. A method called AO-ADMM(a hybrid of the Alternating Optimization and the Alternating Direction Method of Multipliers) has been shown [9] to successfully solve problems that involve non-negativity, sparsity or simplex constraints. In our work we extend the field of its application by introducing a constraint function that ensures low quantization error of the derived factors and construct a corresponding algorithm. Searching for a factorization of \(n\times m\) matrix \(X\) that satisfies quantization constraint (i.e. obtained factors are equal to their quantized versions) means minimizing the following function: \[\operatorname*{minimize}_{A,B}\frac{1}{2}\lVert X-AB^{T}\rVert_{F}^{2}+I_{Q}(A) +I_{Q}(B) \tag{8}\] where \(A\) is a matrix of shape \(n\times r\), \(B\) - of shape \(r\times m\) (\(r\leq n,m\)) and \(I_{Q}\) is an indicator function such that \(I_{Q}(Y)=0\) when \(Y\in Q\) and \(I_{Q}(Y)=+\infty\) if \(Y\notin Q\). In case of symmetric per-tensor quantization [18], \(Q\) is a set of tensors whose elements belong to a discrete quantization grid \(\{(-2^{b-1})*\mathrm{scale},...,(2^{b-1}-1)*\mathrm{scale}\}\). We introduce an auxilary variable, \(\tilde{B}\), and formulate a constrained Least Squares problem, which can be solved using alternating update scheme by fixing one variable and minimizing the objective function over the other. For fixed factor, \(A\), the subproblem takes the following form: \[\begin{split}&\underset{B,\tilde{B}}{\text{minimize}}\ \frac{1}{2}\|X-A\tilde{B}\|_{F}^{2}+I_{Q}(B)\\ &\text{subject to }B=\tilde{B}^{T}\end{split} \tag{9}\] The ADMM method introduces a dual variable, \(U\), for the equality constraint, \(B=\tilde{B}^{T}\), and alternates between optimizing each part of the objective function: \[\tilde{B} =\arg\min_{\tilde{B}}\left(\frac{1}{2}\|X-A\tilde{B}\|_{F}^{2}+ \frac{\rho}{2}\|B-\tilde{B}^{T}+U\|_{F}^{2}\right) \tag{10}\] \[B =\arg\min_{B}\left(I_{Q}(B)+\frac{\rho}{2}\|B-\tilde{B}^{T}+U\|_{ F}^{2}\right)\] (11) \[U =U+B-\tilde{B}^{T} \tag{12}\] The optimal solution for the auxiliary variable \(\tilde{B}\) is given in closed form: \[\tilde{B}=(A^{T}A+\rho I)^{-1}(X^{T}A+\rho(B+U))^{T} \tag{13}\] For efficiency, (13) is solved through Cholesky decomposition of \(A^{T}A+\rho I\). Solving (10) for the factor, \(B\), gives the minimum distance between \((\tilde{B}^{T}-U)\) and set \(Q\): \[\begin{split} B&=\underset{B\in Q}{\text{argmin}}\|B -\tilde{B}^{T}+U\|_{F}^{2}\\ &=\mathrm{proj}_{Q}(\tilde{B}^{T}-U)\end{split} \tag{14}\] Overall, the ADMM procedure for the factor, \(B\), is defined in Algorithm 2. For \(X\approx A\tilde{B}^{T}\) matrix factorization \(G\) is a Gram matrix of the factor that is fixed on current iteration of Alternating Least Squares and \(K\) is an original matrix multiplied by a fixed factor (\(A^{T}A\) and \(X^{T}A\) from (13)). We adopt expressions for \(r\), \(s\) and \(\rho\) from [9]. Similarly, the task is solved for the remaining factor through minimizing \(||X-\tilde{A}^{T}B^{T}||_{F}^{2}\) over set \(Q\). The procedure continues alternating between factors until convergence. ``` Input: B, U,K, G, rank Output: B, U 1:\(\rho\leftarrow\mathrm{trace}(G)/\mathrm{rank}\) 2:\(L\leftarrow\mathrm{Cholesky}(G+\rho I)\) 3:repeat 4:\(\tilde{B}\gets L^{-T}L^{-1}(K+\rho(B+U))^{T}\) 5:\(B_{0}\gets B\) 6:\(B\leftarrow\mathrm{proj}_{Q}(\tilde{B}^{T}-U)\) 7:\(U\gets U+B-\tilde{B}^{T}\) 8:\(r\leftarrow\|B-\tilde{B}^{T}\|_{F}^{2}/\|B\|_{F}^{2}\) 9:\(s\leftarrow\|B-B_{0}\|_{F}^{2}/\|U\|_{F}^{2}\) 10:until\(r<\epsilon\) and \(s<\epsilon\) ``` **Algorithm 1** Solve 9 using ADMM For 3-way tensors, the matrix multiplication of two factors in (8) is replaced with the Canonical Polyadic decomposition (CP): \[\begin{split}\underset{A,B,C}{\text{minimize}}(\frac{1}{2}\|\mathbf{ X}-\sum_{r=1}^{R}A_{:,r}\otimes B_{:,r}\otimes C_{:,r}\|_{F}^{2}\\ +I_{Q}(A)+I_{Q}(B)+I_{Q}(C))\end{split} \tag{15}\] where \(\mathbf{X}\) is a tensor of shape \(n\times m\times k\), A is a matrix of shape \(n\times r\), B - matrix of shape \(m\times r\), C - matrix of shape \(k\times r\), \(\otimes\) denotes the outer product. The constrained ALS subproblem for factor \(B\) takes the following form: \[\begin{split}&\underset{B,\tilde{B}}{\text{minimize}}\ \frac{1}{2}\|\mathbf{X}_{(2)}-\tilde{B}^{T}(C\odot A)^{T}\|_{F}^{2}+I_{Q}(B) \\ &\text{subject to }B=\tilde{B}^{T}\end{split} \tag{16}\] where \(\mathbf{X}_{(2)}\) is a matrix unfolding of tensor \(\mathbf{X}\) by mode \(2\), \(\odot\) denotes Khatri-Rao product. The ADMM procedure is the same as in Algorithm 2, with \(G=(A^{T}A)*(C^{T}C)\) and \(K=\mathbf{X}_{(2)}(C\odot A)\)[23]. Optimization with respect to factors \(A\) and \(C\) is done in the same manner [23]. Alternating between factors proceeds until convergence. The set \(Q\) is non-convex, thus, it is not guaranteed that solution converges to global or even local minimum. Moreover, as shown in Figure 1, convergence depends on initialization. Authors in [4] proposed to use Multistart, Polishing and Neighbor search to improve solution. However, in our case, search among neighbors(even sampling search) of current iteration factor would require number of computations comparable to the number of parameters in a layer. Polishing on \(Q\) reduces to simple recomputation of \(\tilde{B}_{k+1}\) with \(B_{k+1}\) instead of \(B_{k}\) since the only convex restriction [4] that can be chosen in this case is the trivial one. Carefully choosing initialization, however, proved to be a plausible technique to obtain a better solution (Figure 1). ## 4 Experiments We use pretrained ResNet18 model from torchvision model \(\text{zoo}^{*}\) and \(\text{ImageNet}^{\dagger}\) dataset to evaluate our method. First, we conduct several ablation studies to determine quantization scheme, initialization, convergence properties e.t.c.. Then, we compare variations of our method with state-of-the-art approaches from previous papers as well as a naive approach of directly quantizing factors. In all our experiments we utilize per-tensor quantization. For fair comparison, we only consider methods that do not perform model fine-tuning and require only a small sub-sample of the training dataset. MetricsIn some ablation studies we compute a quantized reconstruction error metric: \[e_{\text{quant}}=\frac{\|\mathbf{X}_{(2)}-\hat{B}(\hat{C}\odot\hat{A})^{T}\|_{ F}}{\|\mathbf{X}_{(2)}\|_{F}} \tag{17}\] where \(\hat{A}\), \(\hat{B}\), \(\hat{C}\) are quantized factors of tensor \(\mathbf{X}\). \(\mathbf{X}_{(2)}\) is a matrix unfolding by mode \(2\). We could use any other unfolding, the purpose of this notation is merely to address the fact that Frobenius norm is formulated for matrices. Taking into consideration benefits of reducing both MAC operations (factorization) and operand's bit-width (quantization), we adopt BOP metric, introduced in [26] and use it to compare our method with other approaches. For layer \(l\), BOP count is computed as follows: \[BOPs(l)=MACs(l)b_{w}b_{a} \tag{18}\] where \(b_{w}\) is a bit-width of weights and \(b_{a}\) is a bit-width of (input) activations. While computing this metric for the whole model we take into consideration all layers including BatchNorms. Factorization ranksTo choose a rank for each layer factorization, we set up a parameter reduction rate (i.e. the ratio of the number of the factorized layer's parameters over that of the original layer) and define the rank as \(N/(n+m)/rate\) for fully-connected layers and \(N/(n+m+k)/rate\) for convolutions. \(N\) is the number of parameters in the original layer, \(n\), \(m\) and \(k\) - dimensions of reshaped convolution weights (Section 3.1 ), \(rate\) denotes parameter reduction rate. BatchNorm calibrationSince Resnet models have a lot of BatchNorm layers, and both factorization and quantization disturb the distribution of outputs, calibrating BatchNorm layers' parameters (performing inference with no gradients or activations accumulation) can boost model prediction quality. The same procedure was used, for example, in AdaQuant[10]. In all our experiments we perform calibration on \(2048\) samples from training dataset. It is the same number of samples as used in AdaRound[17] and AdaQuant. ### Ablation studies CP factors quantizationFirst, we try to perform factorization and quantization successively. We obtain factors using CPD and CPD-EPC [21] and compare results after Figure 1: Convergence of ADMM algorithm for a single layer of ResNet18 model with random and CPD-EPC initialization. We have found that using CPD-EPC as initialization instead of random sampling leads to lower quantized reconstruction error, while only a few number of CPD-EPC iterations is sufficient. This result reproduces throughout all model layers. quantizing weights while leaving activations in full precision (Table 1). Although CPD factors provide close to un-factorized model accuracy, they degrade to very poor quality of predictions upon quantization. CPD-EPC factors provide better model accuracy after quantization, while having lower accuracy before quantization. This is explained by the fact that CPD-EPC minimizes Sensitivity [25] of a decomposition that results in factors with lower value range then that of the classic CPD (Figure 2). It alleviates the problem of large outliers for uniform quantization. We have also found (Figure 1) that using a few iterations of CPD-EPC as initialization of ADMM algorithm decreases quantized reconstruction error (17) by keeping value distribution narrowly around zero (Figure 2) which ensures a better quality of model predictions after quantization, especially when using symmetric quantization schemes. We have observed that only a few iterations of cpd-epc is sufficient, after which accuracy of a quantized model ceases to improve. Quantization schemeWe conducted an ablation study to choose between MinMax and MseMinMax quantization schemes to be used in a projection step of ADMM algorithm (14). Results are presented in Table 2. Although MSEMinMax slightly increases the overall computation time, it produces consistently better results due to scale adjustment. Hence, we use MSEMinMax scheme in all subsequent experiments. Bit-allocationDetermining the best trade-off between bit-allocation and reduction rate is not a trivial task. We performed several ablation studies (Figures 3(a) and 3(b)) to choose between different configurations and came to the conclusion that our ADMM-based approach benefits most from lower bit-width, while for conventional decomposition followed by quantization, the best results were achieved with 6-bit weight quantization. ### Baselines We use top-1 test accuracy and BOP count (18) to compare our method to other post-quantization approaches: AdaRound[17], AdaQuant[10], AdaRound applied to factors obtained with CPD-EPC decomposition and naive approach of successive CPD-EPC factorization and quantization. We used AdaRound implementation from the AIMET++ framework and AdaQuant from the author's repositorySS. AdaRound uses per-tensor quantization, while AdaQuant \begin{table} \begin{tabular}{|l|c|c|} \hline \#bits W/A & CPD & CPD-EPC \\ \hline \hline 32/32 & 69.26 & 66.65 \\ 8/32 & 0.1 & 66.5 \\ 6*/32 & 0.1 & 65.47 \\ 4*/32 & 0.1 & 37.54 \\ \hline \end{tabular} \end{table} Table 1: Comparison (% top-1 test accuracy) between CPD and CPD-EPC decompositions of a ResNet18 model(with reduction rate 2) before and after per-tensor MinMax quantization of weights. *We quantize all factorized layers to a specified bit-width, but leave batchnorm, downsample, first and last layers in \(8\) bits. Figure 2: Histograms of values of factor matrix obtained with different decomposition methods from a single layer (layer1.0.conv1) of the ResNet18 model. Our ADMM-based algorithm produces factors whose values lie on a specified quantization grid. performes per-channel quantization of weights. For AdaQuant, we used the advanced pipeline [10] with bias-tuning, even though it involves quantization-aware training step. We report the best accuracy we could achieve, though it is not equal to accuracy depicted in AdaQuant paper. But considering \(71.97\%\) FP32 benchmark reported for ResNet18 model (in comparison with \(69.76\%\) used as starting point in this paper), the quality drop remains the almost the same. We have also noticed that AdaQuant does not consider quantizing inputs to residual connection summation. With ADMM, CPD-EPC and CPD-EPC+AdaRound methods we do not factorize the first, last and downsample layers of the model. These layers contain small number of parameters but are placed in crucial parts of the architecture. Thus, factorizing them will not bring sufficient reduction in mac operations but might significantly degrade accuracy of predictions. Due to the fact that we do not factorize these layers, their weights still lie in full range of FP32 values in contrast with ADMM-factorized layers whose values lie on a uniform quantization grid of a specific bit-width. We leave these layers to 8-bit quantization for ADMM and \begin{table} \begin{tabular}{|l|c|c|} \hline \#bits W/A & MinMax & MseMinMax \\ \hline \hline 8/8 & 67.99 & 68.56 \\ 6*/8 & 67.51 & 68.41 \\ 4*/8 & 62.66 & 67.75 \\ \hline \end{tabular} \end{table} Table 2: Comparison (% top-1 test accuracy) between per-tensor MinMax and MSEMinMax quantization schemes used in projection step of ADMM iteration (the algorithm was run with reduction rate \(2\)). Post-factorization quantization of weights is performed with per-tensor MSEMinMax scheme in both cases. Quantization of activations is performed by histogram observer evaluated on 500 samples. *We quantize all factorized layers to a specified bit-width, but leave batchnorm, downsample, first and last layers in \(8\) bits. Figure 3: Comparison between post-training quantization methods on ResNet18 model. wXaY denotes quantization of weights with bit-width X and activations with bit-width Y. rZ labels indicate that factorization was performed with reduction rate Z. ADMM-EPC defines our ADMM-based approach with CPD-EPC initialization. *We quantize all factorized layers to a specified bit-width, but leave batchnorm, downsample, first and last layers in \(8\) bits. **AdaQuant quantizes all layers to \(4\) bits, except for the first and last layer which are quantized to \(8\) bits. AdaQuant uses per-channel quantization. -CPD-EPC benchmarks. This distribution of bit-widths is concordant with other works on quantizing resnet-like architectures, e.g., [10], even though factorization of layers is not involved. Results are presented in Figure 3, more details can be found in the supplementary materials. It can be seen that our ADMM-based method outperforms other approaches on smaller BOP count values and shows competitive results on larger ranges. Another benefit of a joint factorization-quantization approach is that it is more adaptive in achieving a desirable trade-off between accuracy and efficiency: varying reduction rates gives more flexibility than changing bit-widths configurations. ## 5 Conclusion In this paper we proposed a technique for compressing neural networks that performs joint factorization and quantization. We introduced ADMM-based approximation algorithm to replace weights with float32 elements with their factorized representations, whose factors contain elements of lower precision (int8/int6/int4). Our method allows to benefit from both factorization and quantization techniques, resulting in decrease of model size and acceleration in model inference. Our experiments have shown that ADMM-based joint quantization and factorization shows superior or on par results in comparison to other recent approaches to post-training quantization that do not involve model training and only require a small subset of training data. Moreover, our method allows for a flexible trade-off between accuracy and acceleration not restricted solely by bit-width configurations. Nevertheless, there are a lot of opportunities to improve our method. For example, incorporating more sophisticated tensor and quantization techniques. Another possible direction would be to devise an algorithm of jointly choosing best factorization rank and bit-width similar Bayesian optimization in PARS [24] or integer programming approach in [10].
2306.04987
Convolutional Recurrent Neural Network with Attention for 3D Speech Enhancement
3D speech enhancement can effectively improve the auditory experience and plays a crucial role in augmented reality technology. However, traditional convolutional-based speech enhancement methods have limitations in extracting dynamic voice information. In this paper, we incorporate a dual-path recurrent neural network block into the U-Net to iteratively extract dynamic audio information in both the time and frequency domains. And an attention mechanism is proposed to fuse the original signal, reference signal, and generated masks. Moreover, we introduce a loss function to simultaneously optimize the network in the time-frequency and time domains. Experimental results show that our system outperforms the state-of-the-art systems on the dataset of ICASSP L3DAS23 challenge.
Han Yin, Jisheng Bai, Mou Wang, Siwei Huang, Yafei Jia, Jianfeng Chen
2023-06-08T07:19:14Z
http://arxiv.org/abs/2306.04987v4
# Convolutional Recurrent Neural Network with Attention for 3D Speech Enhancement ###### Abstract 3D speech enhancement can effectively improve the auditory experience and plays a crucial role in augmented reality technology. However, traditional convolutional-based speech enhancement methods have limitations in extracting dynamic voice information. In this paper, we incorporate a dual-path recurrent neural network block into the U-Net to iteratively extract dynamic audio information in both the time and frequency domains. And an attention mechanism is proposed to fuse the original signal, reference signal, and generated masks. Moreover, we introduce a loss function to simultaneously optimize the network in the time-frequency and time domains. Experimental results show that our system outperforms the state-of-the-art systems on the dataset of ICASSP L3DAS23 challenge. 3D Speech Enhancement, Convolutional Recurrent Neural Network, Attention Mechanism ## I Introduction 3D audio is a multi-channel audio processing technology designed to provide a more immersive listening experience by simulating a realistic three-dimensional sound field. But in real world environments, speech communication is usually disturbed by various background noise, leading to poor intelligibility and clarity. Some speech-related tasks, such as automatic speech recognition, also suffer from performance degradation when noise and reverberation are involved. Therefore, speech enhancement (SE), which aims at improving the quality of speech signals, has received widespread attention recently. Researchers often use filters with different characteristics to eliminate noise components [1, 2, 3]. Another approach named spectral subtraction uses mathematical models to estimate the noise spectrogram, which is then be subtracted from the original spectrogram [4, 5]. However, these conventional algorithms are usually based on strong assumptions and require professional knowledge to model and analyze signals. To overcome the limitations of traditional algorithms, deep learning (DL) has emerged as a powerful approach to improve the performance of SE [6, 7, 8]. It does not require extensive feature engineering or domain knowledge to capture data patterns accurately and can adapt well to unstructured data. Recently, SE is typically regarded as a supervised learning problem with neural networks falling into two categories: time-domain-based [9] and time-frequency (T-F) domain-based methods [10, 11]. Time-domain-based approaches extract information directly from the waveform to construct a regression function for the target speech. However, SE methods in the time domain usually need to deal with continuous time series data, which leads to the problem of high computational complexity. In contrast, SE systems carrying out in the T-F domain can take advantage of efficient frequency-domain algorithms such as Fast Fourier Transform, so the computational complexity is relatively lower. Firstly, speech is transformed into a time-frequency representation by the Short-time Fourier Transform (STFT). Then, DL models, such as convolutional neural networks (CNNs), are used to reconstruct the clean speech spectrogram. Finally, the inverse Short-time Fourier Transform (iSTFT) is applied to generate time domain signals. Recently, the U-Net structure has been proposed to improve SE performance [12]. It uses skip connections to connect the output of some layers in the encoder with the input of corresponding layers in the decoder. In this way, the decoder can access lower-level feature maps, which preserve more spatial information. However, this structure is not suitable for modeling long-range interactions, or interactions with variable-length dependencies, which are common to certain forms of audio such as speech [13]. Some researchers try to incorporate recurrent neural networks (RNNs) into CNNs to extract dynamic voice information. E.g., the famous music separation model, Demucs [14], adds a bidirectional long short-term memory (Bi-LSTM) block between the encoder and the decoder, achieving state-of-the-art performance. Similarly, DCCRN [15] incorporates a complex-valued LSTM block into the U-Net structure and achieves great SE performance. In addition to one-step approaches, researchers have proposed some multi-stage SE methods, hoping to iteratively eliminate the noise signal [16, 17, 18, 19]. In our previous work [20], we propose a two-stage U-Net framework to eliminate noise and reverberation in 3D speech signals, which achieves the state-of-the-art performance but lacks some form of attention mechanism for efficient fusion of signals and masks from different stages. To address the above issues, in this paper, we propose a convolutional recurrent neural network for 3D SE by using two sequentially stacked U-Nets. Firstly, we integrate a Dual-path RNN (DPRNN) block [21] into the first U-Net, which can iteratively and alternately apply time-domain and frequency-domain modeling. Secondly, we propose an attention mechanism to fuse the original signal, reference signal, and generated masks. Then, we utilize the multi-layer perceptron (MLP) to perform frequency-domain beamforming on the multi-channel data to form a monaural output. Finally, we introduce a loss function to simultaneously optimize the network in the T-F and time domains. This paper is organized as follows: Section II describes the proposed methods. Section III gives details of experiments such as datasets, evaluation metrics, baselines and settings. Section IV shows the experimental results and Section V gives our discussion and conclusions. ## II Proposed Methods ### _Overview_ Fig. 1 illustrates the architecture of the proposed convolutional recurrent neural network for 3D SE. We use the time-domain representation of the noisy speech signal \(\mathbf{S}_{n}(t)\in\mathbb{R}^{C\times(T\times S)}\) as the input of the system, where \(C\) denotes the total number of audio channels, \(T\) represents the duration of the audio, and \(S\) is the sampling rate. STFT is then applied to obtain the time-frequency domain representation \(\mathbf{X}(t,f)\in\mathbb{C}^{C\times L\times F}\), where \(L\) represents the number of frames, and \(F\) denotes the frequency bins. The convolutional recurrent neural network takes the amplitude of \(\mathbf{X}(t,f)\) as input and uses it to reconstruct the spectrogram of clean speech. \(|\mathbf{X}(t,f)|\) is passed through the first U-Net to produce an estimated real-valued mask \(\mathbf{M}_{1}(t,f)\in\mathbb{R}^{C\times L\times F}\). Then, \(\mathbf{X}(t,f)\) and \(\mathbf{M}_{1}(t,f)\) are multiplied by element-wise to produce the reference signal \(\mathbf{X}_{f}(t,f)\in\mathbb{C}^{C\times L\times F}\), formulated as: \[\mathbf{M}_{1}(t,f)=\mathrm{UN}_{1}[|\mathbf{X}(t,f)|] \tag{1}\] \[\mathbf{X}_{f}(t,f)=\mathbf{X}(t,f)\odot\mathbf{M}_{1}(t,f) \tag{2}\] Where \(\mathrm{UN}_{1}\) represents the first U-Net, and \(\odot\) means element-wise multiplication. The amplitude of the reference signal is fed into the second U-Net to generate another mask \(\mathbf{M}_{2}(t,f)\in\mathbb{R}^{C\times L\times F}\): \[\mathbf{M}_{2}(t,f)=\mathrm{UN}_{2}[|\mathbf{X}_{f}(t,f)|] \tag{3}\] Where \(\mathrm{UN}_{2}\) represents the second U-Net. After that, we use an attention block to perform weighted fusion of mask tensors \(\mathbf{M}_{1}(t,f)\) and \(\mathbf{M}_{2}(t,f)\) to get the final mask \(\mathbf{M}(t,f)\in\mathbb{R}^{C\times L\times F}\). Similarly, original signal \(\mathbf{X}(t,f)\) and the reference signal \(\mathbf{X}_{f}(t,f)\) are weighted and fused to produce the estimated signal \(\hat{\mathbf{X}}(t,f)\in\mathbb{C}^{C\times L\times F}\), formulated as: \[\left\{\begin{array}{c}\mathbf{M}(t,f)=\mathrm{Att}\left[\mathbf{M}_{1}(t,f),\mathbf{M}_{2}(t,f)\right]\\ \hat{\mathbf{X}}(t,f)=\mathrm{Att}\left[\mathbf{X}(t,f),\mathbf{X}_{f}(t,f) \right]\end{array}\right. \tag{4}\] Where \(\mathrm{Att}\) represents the attention block. The enhanced spectrogram \(\mathbf{X}_{m}(t,f)\in\mathbb{C}^{C\times L\times F}\) can be calculated by element-wise multiplication of the estimated signal \(\hat{\mathbf{X}}(t,f)\) and the final mask \(\mathbf{M}(t,f)\): \[\mathbf{X}_{m}(t,f)=\hat{\mathbf{X}}(t,f)\odot\mathbf{M}(t,f) \tag{5}\] \(\mathbf{X}_{m}(t,f)\) is passed through a neural beamforming filter in the frequency domain to get a monaural output \(\mathbf{X}_{e}(t,f)\in\mathbb{C}^{L\times F}\) and we use iSTFT to generate the enhanced time domain speech signal \(\mathbf{S}_{e}(t)\in\mathbb{R}^{T\times S}\), formulated as: \[\left\{\begin{array}{c}\mathbf{X}_{e}(t,f)=\mathrm{Beam}\left[\mathbf{X}_{ m}(t,f)\right]\\ \mathbf{S}_{e}(t)=\mathrm{iSTFT}\left[\mathbf{X}_{e}(t,f)\right]\end{array}\right. \tag{6}\] ### _U-Net structure_ As shown in Fig. 1, the proposed system is mainly composed of two U-Nets. **Encoder**: The encoder comprises \(L=10\) stacked encoder blocks, each of which is composed of a two-dimensional convolution with \(C_{in}\) input channels and \(C_{out}\) output channels, followed by a batch normalization and a LeakyReLU activation function [22]. **Decoder**: The decoder is the inverse of the encoder and comprises 10 decoder blocks, each of which contains a two-dimensional transposed convolution, followed by a batch normalization and a LeakyReLU activation function. Encoder and decoder parameters are set to the same. **Skip connection**: Similar to the multi-channel U-Net structure [12], skip connections are used between encoder blocks and corresponding decoder blocks. These skip connections allow the input to be directly transmitted to the output and preserve more feature details. Fig. 1: The architecture of the proposed convolutional recurrent neural network for 3D speech enhancement The architectures of the encoder and decoder blocks are illustrated in Fig. 2. Table I presents the detailed configurations of two-dimensional convolution layers in the encoder blocks. ### _DPRNN Block_ In order to perform dynamic feature extraction, we incorporate a DPRNN block between the encoder and decoder to iteratively apply time-domain and frequency-domain modeling. As shown in Fig. 3, the DPRNN block is composed of four stacked DPRNN modules. Suppose \(\mathbf{Z}(t,f)\in\mathbb{R}^{C\times L\times F}\) is the output of the encoder, which is used as the input to the DPRNN block. Subsequently, \(\mathbf{Z}\) is passed through two consecutive Bi-LSTMs, each of which contains 128 hidden units, for sequentially time and frequency modeling. We perform a residual connection between the input and the output of each Bi-LSTM. After that, the output of the second Bi-LSTM is fed to a convolutional layer with \(C_{in}\) of 128 and \(C_{out}\) of 256. The Norm and PReLU depicted in the figure refer to group normalization [23] and parametric rectified linear unit [24], respectively. ### _Attention Block_ Let \(\mathbf{X}_{i}\) and \(\mathbf{A}_{i}\) denote the \(i\)-th input tensor and \(i\)-th learnable weight tensor, respectively. The output of the attention block is given by: \[\mathbf{O}=\sum_{i=1}^{N}\mathbf{A}_{i}\odot\mathbf{X}_{i} \tag{7}\] By adding attention blocks to the system, the convolutional recurrent neural network can learn to assign bigger weights to more important features. Reference signals estimated at each stage can be effectively fused through the attention mechanism to further improve the performance of clean speech spectrogram reconstruction. ### _Neural Beamforming Filter_ As shown in Fig. 1, we pass the enhanced multi-channel spectrogram \(\mathbf{X}_{m}(t,f)\in\mathbb{C}^{C\times L\times F}\) through a neural beamformer at the end of the system. There are two motivations: 1) Through frequency-domain beamforming, the amplitude and phase of \(\mathbf{X}_{m}\) at different frequencies are adjusted to enhance the signal from the target direction. 2) Form a monaural output. Specifically, as shown in Fig. 4, we implement this neural beamforming filter using MLPs so that the beam weights can be learned adaptively. Fig. 4: The architecture of the beamforming filter Fig. 3: The architecture of DPRNN block and DPRNN module Fig. 2: The architecture of the encoder and decoder block ### _Loss Function_ Recently, the mean absolute error loss function, defined in the time domain, has been increasingly employed for speech enhancement tasks because of its superior performance [12], which can be formulated as: \[\text{MAE}=\frac{1}{T}\sum_{t=1}^{T}|x(t)-\hat{x}(t)| \tag{8}\] where \(x(t)\) denotes the clean speech signal and \(\hat{x}(t)\) denotes the enhanced speech signal. In this paper, we propose a loss function which combines the normalized relative error in the T-F and time domains. It can be formulated as: \[\begin{split} Loss=&\frac{\gamma}{LF}\sum_{t=1}^{L }\sum_{f=1}^{F}\frac{||\mathbf{X}(t,f)|-|\widehat{\mathbf{X}}(t,f)||}{| \mathbf{X}(t,f)|}\\ &+\frac{1-\gamma}{T}\sum_{t=1}^{T}\frac{|x(t)-\hat{x}(t)|}{|x(t)|} \end{split} \tag{9}\] where \(\mathbf{X}(t,f)\) and \(\widehat{\mathbf{X}}(t,f)\) denote the clean and the enhanced spectrogram, respectively, \(x(t)\) and \(\hat{x}(t)\) represent corresponding speech signals in the time domain and \(\gamma\) is the hyperparameter. By default, \(\gamma\) is set to 0.5. ## III Experiments ### _Dataset_ The proposed system is evaluated on the 3D audio dataset provided by the L3DAS23 challenge. The dataset is semi-synthetic, where the spatial sound scenes are generated by convolving computed room impulse responses (RIRs) with clean sound samples. The noise data is sourced from the FSD50K dataset [25], and clean speech samples are extracted from Librispeech [26]. Overall, the dataset comprises approximately 90 hours 4-channel recordings with a sampling rate of 16kHz. To capture a comprehensive range of acoustic environments, two Ambisonics microphones are positioned at 443 random locations across 68 houses to generate RIRs. The sound sources are placed in random locations of a cylindrical grid. One microphone is located in the exact position selected, while the other is positioned 20 cm apart from it. Both microphones are situated at a height of 1.6 m, which approximates the average near height of a standing person. Details about the dataset can be found at [https://www.l3das.com/icassp2023/dataset.html](https://www.l3das.com/icassp2023/dataset.html). ### _Baselines_ We conduct a comparative analysis of the proposed method against several state-of-the-art baselines, including: **FasNet**[27]: A neural beamformer that leverages both magnitude and phase information of the signal, operating in the time domain. **U-Net**[12]: A multi-channel autoencoder neural network that performs in the T-F domain. This method won the first place in the L3DAS21 challenge, showing its effectiveness in dealing with 3D speech enhancement tasks. **SE-UNet**[20]: A two-stage U-Net architecture proposed by us before, which got the second place in the L3DAS23 challenge. ### _Evaluation Metrics_ We utilize a set of objective criteria including Short-Time Objective Intelligibility (STOI) and Word Error Rate (WER). STOI is employed to estimate the intelligibility of speech, while WER is used to evaluate the performance of speech on recognition. Both STOI and WER scores are normalized to the range of \([0,1]\), facilitating a consistent and comparative analysis across different methods. Moreover, we use an additional metric defined by the L3DAS23 challenge, which provides an overall evaluation of speech enhancement performance. This metric combines the STOI and WER scores, which can be calculated as: \[\mathrm{Metric}=\left(\mathrm{STOI}+\left(1-\mathrm{WER}\right)\right)/2 \tag{10}\] ### _Training Setup and Hyper-parameters_ We employ a batch size of 12 and the Adam optimizer to train all models. The initial learning rate is set to 0.001, and we use early stopping based on validation loss to select the best model. For the proposed system, we preprocess audio data using STFT with a window size of 512 and a hop size of 128. We cut all recordings into 4.792-second segments and use them as the input of the network. Dropout rate is set to 0.1. ## IV Results and Discussion Experimental results of the proposed system and baselines are presented in Table II. Results show that the proposed method outperforms baselines in terms of both STOI and WER. Compared to our previous work, SE-UNet, STOI is improved by 0.022 and WER is reduced by 0.019. In Fig. 5, we visually demonstrate the effectiveness of the proposed method by comparing the enhanced speech spectrogram, the noisy speech spectrogram and the clean speech spectrogram. It can be seen that our system removes the noise signals while suppressing reverberation effectively. Furthermore, we explore the impact of the proposed loss function by evaluating the system using different settings. As shown in Table III, results show that SE performs better when optimized from T-F domain and time domain at the same time. Moreover, it can be found that the T-F loss has a great influence on STOI, while the time-domain loss affects WER more. We recommend to set the default value of \(\gamma\) to 0.5 for achieve a general good performance for 3D SE. ## V Conclusions In this paper, we propose a convolutional recurrent neural network for 3D speech enhancement using two stacked U-Nets. Firstly, we incorporate a DPRNN block into the first U-Net for alternately extracting dynamic voice information in the time and frequency domains. Then, we introduce an attention mechanism to effectively fuse the original signal, reference signal, and generated masks. Finally, an loss function for SE tasks is proposed to simultaneously optimize the network on the T-F and time domains. Experimental results show that the proposed system can achieve the state-of-the-art 3D speech enhancement performance and surpasses the baselines on the dataset of L3DAS23 challenge.
2305.18632
Graph Rewriting for Graph Neural Networks
Given graphs as input, Graph Neural Networks (GNNs) support the inference of nodes, edges, attributes, or graph properties. Graph Rewriting investigates the rule-based manipulation of graphs to model complex graph transformations. We propose that, therefore, (i) graph rewriting subsumes GNNs and could serve as formal model to study and compare them, and (ii) the representation of GNNs as graph rewrite systems can help to design and analyse GNNs, their architectures and algorithms. Hence we propose Graph Rewriting Neural Networks (GReNN) as both novel semantic foundation and engineering discipline for GNNs. We develop a case study reminiscent of a Message Passing Neural Network realised as a Groove graph rewriting model and explore its incremental operation in response to dynamic updates.
Adam Machowczyk, Reiko Heckel
2023-05-29T21:48:19Z
http://arxiv.org/abs/2305.18632v1
# Graph Rewriting for Graph Neural Networks ###### Abstract Given graphs as input, Graph Neural Networks (GNNs) support the inference of nodes, edges, attributes, or graph properties. Graph Rewriting investigates the rule-based manipulation of graphs to model complex graph transformations. We propose that, therefore, (i) graph rewriting subsumes GNNs and could serve as formal model to study and compare them, and (ii) the representation of GNNs as graph rewrite systems can help to design and analyse GNNs, their architectures and algorithms. Hence we propose Graph Rewriting Neural Networks (GReNN) as both novel semantic foundation and engineering discipline for GNNs. We develop a case study reminiscent of a Message Passing Neural Network realised as a Groove graph rewriting model and explore its incremental operation in response to dynamic updates. ## 1 Introduction Neural Networks (NNs) are among the most successful techniques for machine learning. Starting out from application data, e.g. in a relational database, NNs require an encoding of the data into discrete vectors. Graph Neural Networks (GNNs) operate on graphs instead of tabular data. According to [19] a GNN is "an optimizable transformation on all attributes of the graph (nodes, edges, global context) that preserves graph symmetries (permutation invariances)". GNNs are applied to [19] images, text, molecules, social networks, programming code [1] and even mathematical equations [14], in areas such as antibacterial discovery [22], physics simulation [18], fake news detection [17], traffic prediction [15] and recommendation systems [7]. They support supervised, semi-supervised or unsupervised learning (where data labelling is expensive or impossible) and allow links between input vectors, resembling more closely the structure of the application data. In a recommender system where engagements with social media posts are nodes, they may predict such nodes based on the history of engagement, with attributes representing the strength of engagement. Graph rewriting is the rule-based transformation of graphs [12]. Since GNNs are essentially graph transformations, we ask if they can be modelled by graph rewriting, and what the benefits of such a representation might be. Drawing from its rich theory and tool support, we would like to explore the use of graph rewriting as a computational model for GNNs, to specify and compare GNN variants, study their expressiveness and complexity, and as a design and prototyping language for GNNs, evaluating specific GNN architectures and analysing interactions between GNNs and the software and real-world systems with which they interact. In modern data-driven applications, data is diverse, large-scale, evolving, and distributed, demanding incremental and distributed solutions. This has led to a variety of GNNs [25] and a need for a unifying theory to describe their expressiveness and cost [4], evolution and incremental updates [8]. In this short paper, we suggest that typed attributed graph rewriting with control can address these demands. We will illustrate this claim by means of a case study of a recommender system for posts in a social network modelled as a _Graph Rewriting Neural Network (GReNN)_, a controlled graph rewriting system based on a cycle of training and inference transformations with the possibility of dynamic data updates. Training involves the tuning of parameters such as weights and thresholds to support the inference of graph features or properties. The example does not follow a particular GNN architecture, but can be seen as an elaboration of message-passing GNNs over directed heterogeneous graphs with dynamic changes and incremental updates, a combination we have not encountered in any existing formalism. In particular, typed attributed graphs allow for heterogeneity, where nodes of different types have different attributes and are connected by differently-typed edges, while the rule-based approach supports both local inference operations of message-passing GNNs and updates to the graph structure representing changes in the real-world data. ## 2 A Recommender System GRENN We consider a social network with users, posts, and engagements, e.g., reads, likes or retweets, modelled as a Groove graph rewriting system [9]. In the type graph users have an _upd_ attribute that determines if training is required on engagements with posts by this user. Posts have _weights_s that model how representative they are of their author, i.e., how well engagements with these posts predict engagements with other posts by that user. Engagements have a _strength_ attribute to the model quality of the interaction of a user with a post, e.g. a read may be weaker than a like or retweet. Engagements also have _error, obs_ and _count_ attributes. The error represents the difference between the actual strength of engagement and the strength inferred from engagements with similar posts. This is used for training the posts' weights by the gradient descent rule. The Boolean _upd_ and _obs_ attributes signal, respectively, if an update is required to the training after a change of data affecting this node and if the strength of the node is observed from real-world engagement as opposed to being inferred. The _count_ attribute, which is always 1, is used to calculate the cardinality of Engagement nodes in a multi-pattern match in Groove. To control training we add an Error node with _error_ and _delta_ attributes. All attributes except _strength_ are part of the general mechanism while _weight_ also has application-specific meaning. The rules come in two flavours: dynamic update rules to create users, posts and engagements, and rules for training and inference. Update rules are shown in Fig. 1 in Groove notation. As usual, elements in thin solid black outline represent read access, dashed blue elements are deleted, and thick green elements are created, while nodes and edges in dotted red represent negative conditions. The dotted red line labelled "=" means that the linked nodes are not equal. Rules to create engagements exist in three versions to create engagements of strengths \(0.2,0.4\) and \(0.8\) (but only the rule for \(0.4\) is shown). When creating a new engagement, the user who authored the post has their _upd_ attribute set to _true_ to trigger retraining. The training and inference rules are shown in Fig. 2. Nodes labelled \(\forall\) or \(\forall^{>}\) represent nested multi rules, @-labelled edges associating nodes to their nesting levels and _in_ edges showing quantifier nesting. The _infer_ rule at the bottom calculates the expected strengths of new engagements as weighted sums of the strengths of all observed engagements of the same user with posts by a second user whose _upd_ attribute is _true_ (and then changes to _false_). The red-green dotted outline says that an Engagement node is only created if there is not already one, combining node creation with a negative condition. The assignment shown in green inside that Engagement node realises the following formula. \[strength=\frac{\sum_{m\in M}(p(m).weight*e(m).strength)}{\text{card }M} \tag{1}\] \(M\) is the set of matches of the multi pattern represented by the non-empty quantification node \(\forall^{>}\), with \(e(m)\) and \(p(m)\) referencing the Engagement and Post nodes of match \(m\in M\). This is nested in another \(\forall\) node to apply the inference to all eligible Engagement nodes at once. Recall that the weights of Post nodes show how well a post represents the average post by that user. The _error_ rule in the top computes the inference error as the difference between the observed value of strength and the inferred value. This is typical of semi-supervised learning in GNNs where some of the nodes represent Figure 1: Rules for dynamic updates: _newUser_, _newPost_, and _newEngagement04_. Figure 2: Top to bottom: Rules _error, delta_ and _infer_. training samples while others are inferred. Structure and inference formula are similar to the _infer_ rule. We use an Error node with a global _error_ attribute to control the training cycle. This is calculated as the sum of absolute _error_ values of all observed engagements, and training stops when the _delta_, the difference of global errors between this and the previous cycle is below 0.0001. The _delta_ rule in the middle of Fig. 2 implements gradient descent backward propagation, updating the weights of the posts by the product of the average error and strengths of the user's engagements' with this post. We use a control program to iterate training and inference, and to simulate the insertion of newly observed data during the runtime of the model. The program starts with a training cycle through _error_ and _delta_ for as long as possible, i.e., until the delta value falls below the threshold. Inference consists of one application of the _infer_ rule: ``` functiontraining(){ alap{error; delta;} } functioninference(){ infer; } functionupdate(){ nodeu; newUser(out u); nodep; newPost(u, out p); newEngagement02(p); newEngagement04(p); } training; inference; update; training; inference; ``` All rules use nested universal quantification over engagements, so a single application per rule covers the entire graph. The sample dynamic update rules called by the _update_ function create a new user and post and two engagements. Rule parameters ensure that new posts, engagements and users are linked. Then we run the training and inference again, demonstrating the possibility of incremental updates and repeated training to reflect the interleaving of real-world changes and consequent data updates with the operation of the GRENN model. The start graph at the top of the Fig. 3 has three users, three posts and six engagements, all representing "observed" data that can be used to train post weights. An intermediate graph, after the first training cycle, is shown Figure 3: Top to bottom: start, intermediate and final graphs. in the middle, with final global error and delta values, and updated post weights. The final graph extends this by, among other things, the structure at the bottom, where the user on the right of the fragment is the same as the one in the top left of the intermediate graph. In the final graph, it has two newly observed and one newly inferred engagement with a new post by the new user on the left. ## 3 Discussion: GRENN vs GNN The purpose of this exercise was not to demonstrate how existing GNN approaches can be realised as graph rewrite systems, but to adopt principles of GNNs, such as the use of graphs to represent data for training and inference, to enable semi-supervised learning by labelling parts of the graph with real-world observations, and to employ the graph structure to direct training and inference. However, our model goes beyond mainstream GNNs in two important aspects. First, the graphs employed are heterogeneous (typed) directed graphs rather than homogeneous (untyped) undirected ones. This allows us to operate directly on an application-oriented data model such as a knowledge graph [13] of a social media network, rather than an encoding. Knowledge graphs are used for data integration, graph-based analytics and machine learning [20]. "Message-passing type GNNs, also called Message Passing Neural Networks (MPNN), propagate node features by exchanging information between adjacent nodes. A typical MPNN architecture has several propagation layers, where each node is updated based on the aggregation of its neighbours' features" [4]. MPNNs realise a supervised machine learning algorithm on graph-structured data by utilising the message-passing algorithm [10]. Notable variants of GNNs include Convolutional NNs [6], Gated GNNs [16] and Deep Tensor NNs [21]. We relate our model to the concepts and terminology from [10], which describes the operation of MPNNs on undirected graphs \(G\) by message passing, update and readout steps. Given node features \(x_{v}\) and edge features \(e_{vu}\), message passing updates hidden states \(h^{t}_{v}\) at each node \(v\) for \(T\) steps according to message functions \(M_{t}\) and vertex update functions \(U_{t}\) using messages \[m^{t+1}_{v}=\sum_{u\in N(v)}M_{t}(h^{t}_{v},h^{t}_{u},e_{vu})\] where \(N(v)\) is the set of neighbours of \(v\) and updates \[h_{v}^{t+1}=U_{t}(h_{v}^{t},m_{v}^{t+1}).\] After step \(T\), readout \(R\) computes an output vector for the graph. Hence messages aggregated from nodes' neighbourhoods are used in updates to compute new states. \(M_{t}\) and \(U_{t}\) can be learned by neural networks. Often this means that \(M_{t}\) computes a weighted sum of node and edge features, with weights trained by backpropagation, while \(U_{t}\) implements activation thresholds or controls the rate of change by weighing residual states against massages. Our Eq. (1) can be seen as a combination of \(M_{t}\) and \(U_{t}\). The update function is the identity since no activation or balancing between residual and new features is required, and the message is a weighted average of engagement strengths with posts by the same user. However, the analogy is incomplete because our graphs are directed and not homogeneous, and the strength of engagement is a feature of an "engaged with post by" relation between users rather than a user node. Indeed "one could also learn edge features in an MPNN by introducing hidden states for all edges in the graph...and updating them analogously" [10]. The relational nature of engagement is the reason why we only use a single step of forward propagation: All "engagements with posts" between the same two users are accessible locally in one step. A complex pattern realises the relation, so we need a sum over the multi pattern to compute the average. Hence graph patterns allow querying heterogeneous graphs where their homogeneous encodings are processed by navigating along edges. Apart from supporting a direct representation of the data, graph patterns increase the expressive power of GNNs also on homogeneous graphs [3]. Like weights and features, the graph structure is usually represented by matrices, such as adjacency or incidence and degree matrices. If the graph is undirected, its adjacency matrix is symmetrical. If the graph is weighted, it contains real-valued edge weights. A GRENN model supports directed edges, class heterogeneity and incremental updates to process dynamic application data in its original form without encoding. As of now, most GNN approaches only support undirected and homogenous graphs, but there is a trend towards more general models: In [11], the authors present an example of a directed MPNN and use it in conjunction with a graph attention network. In [10] the authors state that "It is trivial to extend the formalism to directed multigraphs". Multi-class approaches are utilised in IoT applications such as [2]. Emerging support for heterogeneous graph data includes [24; 23] which present a new algorithm called Explicit Message-Passing Heterogeneous Graph Neural Network (EMP). While GReNNs support both directed and heterogeneous data at the model level, such approaches may provide a platform to implement our models efficiently. Incremental forward and back propagation in GNNs can substantially save time and resources [8] by reducing computations to nodes affected by updates. This is especially useful for big-data applications, where batch processing is not affordable and efficient. NNs and GNNs do not easily support data updates. Hence, the second generalisation in our approach is to model the dynamic updates of the graph and control specifically where retraining is required. This includes adding new nodes, an operation that would break most matrix-based representations by changing the dimensions of the matrices involved. GReNNs reimagine GNNs free of considerations of efficient representation of and computations on graphs. This is appropriate from a modelling perspective, but unlikely to scale to large graphs. To support an engineering approach to GNN development based on graph rewriting, a study of the possible implementations of such models in mainstream GNNs is required. First experiments show that it is possible in principle to map a model such as ours to an undirected homogeneous graph by interpreting the edges of that simpler graph as paths or patterns in our model. This is a reduction that GNN developers have to perform when they present their application data as input to a GNN, but we believe that by studying this systematically we can find standard mappings from a typed attributed graph model into graphs supported by suitable GNN technology. The suggestion that graph rewriting can serve as a semantic foundation for GNNs requires mappings in the opposite direction, taking the various GNN approaches and modelling them as GReNNs. Then, such embeddings could be used to compare the different graph types, inference or training rules. The theory of graph grammars with its language hierarchies and corresponding rule formats may well play a role here. GNNs can be based on attributed directed or undirected, simple or multi, homogeneous or typed, binary, hyper or hierarchical graphs, with little support for reuse of algorithms or implementations [19]. The categorical theory and potentially generic implementation of graph rewriting [5] can be a model to unify such diverse approaches.
2304.14447
Analyzing Vietnamese Legal Questions Using Deep Neural Networks with Biaffine Classifiers
In this paper, we propose using deep neural networks to extract important information from Vietnamese legal questions, a fundamental task towards building a question answering system in the legal domain. Given a legal question in natural language, the goal is to extract all the segments that contain the needed information to answer the question. We introduce a deep model that solves the task in three stages. First, our model leverages recent advanced autoencoding language models to produce contextual word embeddings, which are then combined with character-level and POS-tag information to form word representations. Next, bidirectional long short-term memory networks are employed to capture the relations among words and generate sentence-level representations. At the third stage, borrowing ideas from graph-based dependency parsing methods which provide a global view on the input sentence, we use biaffine classifiers to estimate the probability of each pair of start-end words to be an important segment. Experimental results on a public Vietnamese legal dataset show that our model outperforms the previous work by a large margin, achieving 94.79% in the F1 score. The results also prove the effectiveness of using contextual features extracted from pre-trained language models combined with other types of features such as character-level and POS-tag features when training on a limited dataset.
Nguyen Anh Tu, Hoang Thi Thu Uyen, Tu Minh Phuong, Ngo Xuan Bach
2023-04-27T18:19:24Z
http://arxiv.org/abs/2304.14447v1
# Analyzing Vietnamese Legal Questions using Deep Neural Networks with Biaffine Classifiers ###### Abstract In this paper, we propose using deep neural networks to extract important information from Vietnamese legal questions, a fundamental task towards building a question answering system in the legal domain. Given a legal question in natural language, the goal is to extract all the segments that contain the needed information to answer the question. We introduce a deep model that solves the task in three stages. First, our model leverages recent advanced autoencoding language models to produce contextual word embeddings, which are then combined with character-level and POS-tag information to form word representations. Next, bidirectional long short-term memory networks are employed to capture the relations among words and generate sentence-level representations. At the third stage, borrowing ideas from graph-based dependency parsing methods which provide a global view on the input sentence, we use biaffine classifiers to estimate the probability of each pair of start-end words to be an important segment. Experimental results on a public Vietnamese legal dataset show that our model outperforms the previous work by a large margin, achieving 94.79% in the F1 score. The results also prove the effectiveness of using contextual features extracted from pre-trained language models combined with other types of features such as character-level and POS-tag features when training on a limited dataset. Keywords:Question Answering Legal Domain Deep Neural Network Biaffine Classifier BERT BiLSTM. ## 1 Introduction Question answering (QA) [7, 12, 22, 28, 29, 30], a sub-field of natural language processing (NLP) and information retrieval (IR), aims to build computer systems that can automatically answer questions in natural languages. There are two main approaches for building QA systems: IR-based and knowledge-based. The former approach finds and extracts answers from a collection of unstructured text, while the latter utilizes structured text or knowledge bases. Although two approaches exploit different types of resources, they share the first step, question analysis, which extracts the needed information to answer the input question. Such information is then used to form a query in various ways which serves as the input for the next step. Question analysis is therefore a crucial task for both IR-based and knowledge-based question answering. In this paper, we target at the question analysis task in the legal domain, which is undoubtedly important but has received less attention. Legal and regulatory documents are ubiquitous and have a great impact on our life. Figure 1 shows two examples of Vietnamese legal questions annotated with key information. The goal is to correctly extract two types of information in the first question (Traffic Light-TL and Question Type-QT), and four types of information in the second question (Type of Vehicle-TV, Alcohol Concentration-AC, Value-V, and Question Type-QT). We call the segments that contain important information important segments. Traditional methods often frame the task as a sequence labeling problem and exploit probabilistic graphical models like conditional random fields (CRFs) [14] to solve it. The main advantage of those methods is that they can build an accurate model using a relatively small annotated corpus with a handcrafted feature set. Recently, however, deep neural networks have made tremendous breakthroughs in various NLP tasks and applications, including sentence classification [13, 26], sequence labeling [2, 9, 33], syntactic and dependency parsing [21, 34], natural language inference [5, 10], machine translation [27, 35], as well as question answering [10, 12]. Furthermore, the well-known limitation of deep models, i.e. data hungry, could be mitigated by using advanced pre-trained models and fine-tuning [5, 10]. All of these make deep neural networks the preferred choice for NLP tasks in general and QA in particular. Here, we propose to use deep neural networks for Vietnamese question analysis in the legal domain. Our method combines several recent advanced techniques in the NLP and deep learning research communities: pre-trained language models [5] for contextual word embeddings, convolutional neural networks (CNNs) [16] for extracting character-level features, and bidirectional long-short term memory networks (BiLSTM) [8] for sentence-level representations. Furthermore, instead of formulating it as a sequence labeling problem, we employ biaffine classifiers Figure 1: Examples of two legal questions and their important information. to estimate directly the possibility that a pair of words becomes an important segment. The main advantage of biaffine classifiers is that they provide a global view on the input sentence, which has been shown to be effective in dependency paring [6, 17], and named entity and relation extraction [23, 36]. Experimental results on a Vietnamese corpus consisting of 1678 legal questions show that our model outperforms a SOTA method by a large margin, showing the F\({}_{1}\) score of 94.79%. The effectiveness of these components of the model is also validated by an ablation study. The remainder is organized as follows. Section 2 reviews related work. Section 3 presents our model for extracting important information from Vietnamese legal questions. The model architecture is presented first, and its key components are then described in more detail. Experimental results and error analysis are introduced in Section 4. Finally, Section 5 concludes the paper and shows some future work. ## 2 Related Work Several studies have been performed on Vietnamese QA in various domains, including travel, education, as well as legal. Tran et al. [28] introduce a Vietnamese QA system, which can answer simple questions in the travel domain by mining information from the Web. Bach et al. [3] focus on the task of analyzing Vietnamese question in education. Using deep neural networks (BiLSTM-CRFs) with a rich set of features, their model can accurately extract 14 types of vital information from education utterances. In the legal domain, Duong and Ho [7] develop a QA system to answer Vietnamese questions about provisions, procedures, processes, etc. in enterprise laws. Kien et al. [12] introduce a retrieval-based method for answering Vietnamese legal questions by learning text representation. Their model leverages CNNs and attention mechanisms to extract and align important information between a question and a legal article. Other works on Vietnamese question answering include Nguyen et al. [22], Tran et al. [29], and Le-Hong and Bui [15]. Perhaps the most closely work to ours is the one of Bach et al. [1], which also focuses on analyzing Vietnamese legal questions. Our method, however, is distinguished from theirs in two aspects. First, we formulate the task as a multi-class classification problem instead of sequence labeling. Second, we utilize deep neural networks instead of using traditional models like CRFs. ## 3 Method ### Model Overview Our goal is to extract all important segments from an input legal question, where each segment is a triple of start/end positions and a label for the information type. Figure 2 illustrates our proposed architecture. First, we create word representations by concatenating different types of features: contextual word embeddings, character-level features, and part-of-speech (POS) tag embeddings. The outputs of the word representation layer are then fed into two stacked BiLSTMs to obtain the sentence-level representations. After that, we use two feed forward neural networks (FFN) to generate different representations for the start/end of segments. Finally, we employ a biaffine classifier to create a \(n\times n\times c\) scoring tensor \(R\), where \(n\) denotes the length of the input question, and \(c\) is the number of labels (including Null for non important information). Tensor \(R\) provides scores for all possible segments that could contain key information. In the up-coming sections, we show the model components in detail. For notation, we denote vectors, matrices, and scalars with bold lower-case (e.g., \(\mathbf{x}_{t}\), \(\mathbf{h}_{t}\), \(\mathbf{b}\)), bold upper-case (e.g., \(\mathbf{H}\), \(\mathbf{W}_{i}\), \(\mathbf{V}_{i}\)), and italic lower-case (e.g., \(n\), \(c\)), respectively. Figure 2: Model architecture. ### Word Representations Because words are basic elements to form written languages, a good word representation method is the first and crucial step to build successful NLP systems. In this work, we create rich information word representations by integrating multiple information sources, including contextual word embeddings, character-level features, and POS-tag embeddings. **Contextual word embeddings**. Traditional NLP approaches usually represent words by one-hot vectors with one value 1 and the rest 0. These high-dimensional sparse vectors are memory consuming and cannot capture the word semantics. Distributed word representation methods, which use low-dimensional continuous vectors, have been introduced to handle these issues. Word2vec [20], Fasttext [4], and Glove [25] are successful examples of such methods that represent similar words with similar vectors. Although these methods have made many breakthroughs in NLP research, they represent words by fix vectors which are context independent. Static word embedding methods like word2vec are therefore limited in representing polysemous words. Recently, contextual word embedding methods have been shown to be the key component of many SOTA NLP systems [5, 18]. The main advantage of these methods it that they can learn different representations for polysemous words by considering the sequence of all words in sentences/documents. Perhaps BERT proposed by Devlin et al. [5] is the most famous and popular contextual word embedding method. The key technical innovation of BERT is applying the bidirectional training of Transformer [31] to language modeling with two strategies: masked-language modeling and next sentence prediction. In this work, we use PhoBERT [24], a monolingual variant of RoBERTa [18] pre-trained on a 20GB word-level Vietnamese dataset. Like BERT and RoBERTa, PhoBERT segments the input sentence into sub-words, which brings the balance between character- and word-level hybrid representations and enables the encoding of rare words with appropriate sub-words. We represent each sub-word by concatenating embeddings of the last four encoding layers (9 to 12) of PhoBERT-base, and the contextual embedding of a word is the embedding of its first sub-word. **Character-level features**. Beside contextual word embeddings, we also utilize morphological information from characters. Additional character embeddings are derived from character-level convolutional (charCNN) networks. As shown in Figure 3, charCNN consists of 1D operations: convolution and max pooling. Feature maps are then concatenated to produce a character-level representation for the word. **POS-tag embeddings**. We suppose POS tags are another useful source of information. Therefore, we also use POS tag embeddings to represent words. These embedding vectors are initialized randomly in range \((-\sqrt{3/dim},\sqrt{3/dim})\), where \(dim\) denotes their dimension. We use \(\text{VnCoreNLP}\)[32] for word segmentation and POS tagging for input questions. Finally, all feature vectors are concatenated into a single embedding for representing a word. Word vectors are then fed into BiLSTM networks to create sentence-level representations. ### BiLSTM Long short-term memory (LSTM) networks [11] are designed for sequence data modeling problem. Let \(\mathbf{X}=(\mathbf{x}_{1},\mathbf{x}_{2},\ldots,\mathbf{x}_{n})\) denote the input question where \(\mathbf{x}_{i}\) is the embedding of the \(i^{th}\) word. At each position \(t\), the LSTM computes an intermediate representation using a hidden state \(\mathbf{h}\): \[\mathbf{h}_{t}=f(\mathbf{h}_{t-1},\mathbf{x}_{t})\] where \(f\) includes an input gate, a forget gate, an output gate, and a memory cell (denoted by \(\mathbf{i}_{t}\), \(\mathbf{f}_{t}\), \(\mathbf{o}_{t}\), \(\mathbf{c}_{t}\), respectively) to update \(\mathbf{h}_{t}\): \[\mathbf{i}_{t}=\sigma(\mathbf{W}_{i}\mathbf{x}_{t}+\mathbf{V}_{i} \mathbf{h}_{t-1}+\mathbf{b}_{i}),\] \[\mathbf{f}_{t}=\sigma(\mathbf{W}_{f}\mathbf{x}_{t}+\mathbf{V}_{f }\mathbf{h}_{t-1}+\mathbf{b}_{f}),\] \[\mathbf{o}_{t}=\sigma(\mathbf{W}_{o}\mathbf{x}_{t}+\mathbf{V}_{o }\mathbf{h}_{t-1}+\mathbf{b}_{o}),\] \[\mathbf{c}_{t}=\mathbf{f}_{t}\odot\mathbf{c}_{t-1}+\mathbf{i}_{t }\odot\tanh(\mathbf{W}_{c}\mathbf{x}_{t}+\mathbf{V}_{c}\mathbf{h}_{t-1}+ \mathbf{b}_{c}),\] \[\mathbf{h}_{t}=\mathbf{o}_{t}\odot\tanh(\mathbf{c}_{t}),\] and the output \(\mathbf{y}_{t}\) can be produced based on \(\mathbf{h}_{t}\): \[\mathbf{y}_{t}=\sigma(\mathbf{W}_{y}\mathbf{h}_{t}+\mathbf{b}_{y}),\] where \(\odot\) indicates the multiplication operator function, \(\sigma\) is the element-wise softmax, and \(\mathbf{W}_{*}\), \(\mathbf{V}_{*}\), and \(\mathbf{b}_{*}\) (\(*\) denotes \(i\),\(f\),\(o\),\(c\),\(y\)) are weight matrices and vectors to be learned during the training process. Bidirectional long short-term memory (BiLSTM) [8] combine two LSTMs: one network moves from the left to the right and the other network moves from the right to the left of the sequence. Two BiLSTMs are exploited to learn a higher level of semantics within the sentence. Figure 3: CNN-based character-level features. ### Biaffine Layer We employ two feed forward neural networks (FFNs) to create different representations for start/end positions. The outputs of two FFNs at position \(t\) are denoted by \(\mathbf{g}_{t}^{start}\) and \(\mathbf{g}_{t}^{end}\): \[\mathbf{g}_{t}^{start}=\text{FFN}^{start}(\mathbf{y}_{t})\] \[\mathbf{g}_{t}^{end}=\text{FFN}^{end}(\mathbf{y}_{t})\] For each start-end candidate pair \((i,j)\), \(1\leq i\leq j\leq n\), we apply the biaffine classifier: \[\mathbf{r}_{i,j}=\text{Biaffine}(\mathbf{g}_{i}^{start},\mathbf{g}_{j}^{end})= (\mathbf{g}_{i}^{start})^{\top}\mathbf{U}\mathbf{g}_{j}^{end}+\mathbf{W}( \mathbf{g}_{i}^{start}\oplus\mathbf{g}_{j}^{end})+\mathbf{b},\] where \(\mathbf{U}\), \(\mathbf{W}\), \(\mathbf{b}\) are a \(d\times c\times d\) tensor, a \(c\times 2d\) matrix, and a bias vector, respectively, and \(d\) is the size of the output layers of both \(\text{FFN}^{start}\) and \(\text{FFN}^{end}\). Vector \(\mathbf{r}_{i,j}\) is then fed into a softmax layer to produce probability scores \(\mathbf{s}_{i,j}\): \[\mathbf{s}_{i,j}(k)=\frac{exp(\mathbf{r}_{i,j}(k))}{\sum_{k^{\prime}=1}^{c} exp(\mathbf{r}_{i,j}(k^{\prime}))}\] The label of segment \((i,j)\) can be determined as: \(\widehat{l}=\arg\max_{k}\mathbf{s}_{i,j}(k)\). The question analysis task now becomes a multi-class classification problem and model parameters are learned to minimize the cross-entropy loss function. ## 4 Experiments ### Data and Evaluation Method In our experiments we used the Vietnamese dataset of legal questions introduced by Bach et al. [1]. This dataset consists of 1678 legal questions about the traffic law in Vietnam. Questions were annotated with 16 labels reflecting different aspects of the domain listed in Table 1. We performed cross-validation tests with the same training/test data splits of Bach et al. [1]. For each fold, we used 10% of the training set as a validation set. The performance of extraction models was measured using popular metrics such as precision, recall and the F\({}_{1}\) score. \begin{table} \begin{tabular}{c|l|c|l|l|l} \hline \hline **Label** & **Meaning** & **\#** & **Label** & **Meaning** & **\#** \\ \hline \hline A & Action of vehicle & 1087 & L & Location & 426 \\ \hline AC & Alcohol concentration & 44 & QT & Question type & 1678 \\ \hline ANO & Annotation & 75 & SP & Speed & 115 \\ \hline DL & Driving license & 119 & TI & Traffic instructor & 93 \\ \hline IF1 & Add. info. about vehicle & 196 & TL & Traffic light & 31 \\ \hline IF2 & Add. info. about traffic light & 12 & TP & Traffic participant & 20 \\ \hline IF3 & Add. info. about traffic participant & 287 & TV & Type of vehicle & 1245 \\ \hline IF4 & Add. info. & 227 & V & Value & 231 \\ \hline \hline \end{tabular} \end{table} Table 1: Types of important information and their occurrence numbers ### Network Training Our models were implemented in PyTorch3 using Huggingface's Transformers4. In all experiments, we set the batch size to 64. The max character length was set to 15, and the max sequence length was tuned in \([50,60,80,100]\) for all models, and the best value was 60. We set the dimensions of character-level features and POS-tag embeddings to 256 and 100, respectively. We used dimension of 300 for FFNs, and kernel sizes of 3 and 4 for charCNN. To mitigate overfitting, we used a dropout rate of 0.3 for each hidden layer. Our models were trained using the AdamW optimizer [19]. We set the epsilon and weight decay to default values in PyTorch, i.e. \(1e\)-8. The learning rate was tuned in [3\(e\)-5, 4\(e\)-5, 5\(e\)-5] and the best learning rate value was \(5e\)-5. For each model, we trained for 30 epochs and selected the version that obtained the highest F\({}_{1}\) score on the validation set to apply to the test set. Footnote 3: [https://pytorch.org/](https://pytorch.org/) Footnote 4: [https://huggingface.co/transformers/](https://huggingface.co/transformers/) ### Experimental Results #### 4.3.1 Our Model vs. Baseline We first conducted experiments to compare our model with the previous work of Bach et al. [1] (our baseline). Table 2 shows experimental results on each type of information and the overall scores of two models. Our model outperformed the baseline for 15 out of 16 types of information. Types with the biggest improvements in the F\({}_{1}\) score include TL (Traffic light: 19.79%), ANO (Annotation: 9.61%), TP (Traffic participant: 7.48%), A (Action: 4.47%), and SP (Speed: 4.33%). Overall, our model achieved a micro F\({}_{1}\) score of 94.79%, which improved 1.85% (26.20% error rate reduction) in comparison with the baseline. Experimental results demonstrated the effectiveness of deep neural networks compared to traditional methods like CRFs. #### 4.3.2 Ablation Study Next we evaluated the contribution of individual components of our model by performing an ablation study as follows: * **Biaffine classifier**: We replaced the biaffine classifier with a CRF/softmax layer and reformulated the task as a sequence labeling problem * **Character-level features**, **POS-tag embeddings**, **BiLSTMs**: We removed each component in turn. * **PhoBERT Embeddings**: We replaced contextual word embeddings with static word embeddings. In our experiments, we used Fasttext [4], a variant of Word2Vec [20] which deals with unknown words and sparsity in languages by using sub-word models. Experimental results in Table 3 proved that all the components contributed to the success of our model. Our first observation is that the performance of the system degraded when we modified or removed a component. While the full model got 94.79%, the F\({}_{1}\) score reduced to 94.62% and 93.59% when we replaced the biaffine classifier with CRF/softmax function and reformulated the task as a sequence labeling problem. The score was only 94.46%, 94.33%, and 93.77%, when we removed POS-tag features, character-level features, and the BiLSTM layers, respectively. The results showed that the BiLSTM layers have a high impact on the performance of our model. The second observation is that replacing contextual word embeddings by static word embeddings leads to the biggest decrease of 1.98%. This indicated that contextual word embeddings from pre-trained language models like PhoBERT played a critical role in our model. ### Error Analysis This section discusses the cases in which our model failed to extract important information. By analyzing the model's predictions on the test sets, we found that most errors belong to one of two following types: * **Type I: Incorrect segments**. Our model identified segments that are shorter or longer than the gold segments. * **Type II: Incorrect information types**. Our model recognized segments (start and end positions) correctly but assigned wrong information types (labels) to the segments. Figure 4 shows four examples of error cases. Among them, the first two examples belong to Type I and the others belong to Type II. While our model \begin{table} \begin{tabular}{c|c|c|c|c|c|c} \hline \hline & \multicolumn{2}{c|}{**Baseline** (Bach et al. [1])} & \multicolumn{4}{c}{**Our Model**} \\ \hline \hline **Type** & **Prec.(\%)** & **Rec.(\%)** & **F.(\%)** & **Prec.(\%)** & **Rec.(\%)** & **F\({}_{1}\)(\%)** \\ \hline \hline A & 88.20 & 89.14 & 88.66 & 92.91 & 93.35 & 93.13 (**4.47\(\uparrow\)**) \\ \hline AC & 95.78 & 95.78 & 95.78 & 96.12 & 97.28 & 96.70 (**0.92\(\uparrow\)**) \\ \hline ANO & 85.58 & 60.57 & 68.82 & 73.17 & 84.51 & 78.43 (**9.61\(\uparrow\)**) \\ \hline DL & 97.97 & 99.20 & 98.54 & 100.00 & 98.26 & 99.12 (**0.58\(\uparrow\)**) \\ \hline IF1 & 94.64 & 87.35 & 90.67 & 90.34 & 91.48 & 90.91 (**0.24\(\uparrow\)**) \\ \hline IF2 & 100.00 & 73.33 & 82.67 & 86.72 & 70.44 & 77.74 (4.93\(\downarrow\)) \\ \hline IF3 & 88.08 & 75.06 & 80.91 & 85.77 & 83.45 & 84.59 (**3.68\(\uparrow\)**) \\ \hline IF4 & 85.77 & 74.34 & 79.51 & 80.14 & 82.97 & 81.53 (**2.02\(\uparrow\)**) \\ \hline L & 92.23 & 92.71 & 92.44 & 93.18 & 96.31 & 94.72 (**2.28\(\uparrow\)**) \\ \hline QT & 96.03 & 94.84 & 95.42 & 95.89 & 96.07 & 95.98 (**0.56\(\uparrow\)**) \\ \hline SP & 95.61 & 91.44 & 93.23 & 100.00 & 95.24 & 97.56 (**4.33\(\uparrow\)**) \\ \hline TI & 99.05 & 95.53 & 97.24 & 100.00 & 100.00 & 100.00 (**2.76\(\uparrow\)**) \\ \hline TL & 86.95 & 60.35 & 68.59 & 87.33 & 89.46 & 88.38 (**19.79\(\uparrow\)**) \\ \hline TP & 80.00 & 60.67 & 67.21 & 76.35 & 73.11 & 74.69 (**7.48\(\uparrow\)**) \\ \hline TV & 97.32 & 98.78 & 98.04 & 99.57 & 97.99 & 98.77 (**0.73\(\uparrow\)**) \\ \hline V & 98.18 & 99.26 & 98.71 & 100.00 & 98.23 & 99.11 (**0.40\(\uparrow\)**) \\ \hline \hline Overall & 93.84 & 92.05 & 92.94 & 94.30 & 95.28 & 94.79 (**1.85\(\uparrow\)**) \\ \hline \hline \end{tabular} \end{table} Table 2: Experimental results of our model compared with the baseline (the improvements are indicated in bold) identified a longer segment in the first case, it detected a shorter segment in the second case. In the third and fourth examples, our model made a mistake on labels (TP instead of ANO, and IF4 instead of A). ## 5 Conclusion We have introduced a deep neural network model for analyzing Vietnamese legal questions, a key step towards building an automatically question answering system in the legal domain. By utilizing recent advanced techniques in the NLP and deep learning research communities, our model can correctly extract 16 types of important information. For future work, we plan to develop a question answering system for Vietnamese legal questions. Studying deep neural network models for other NLP tasks in Vietnamese language is another direction for future work. ## Acknowledgements We would like to thank FPT Technology Research Institute, FPT University for financial support which made this work possible.
2301.12603
Do We Really Need Graph Neural Networks for Traffic Forecasting?
Spatio-temporal graph neural networks (STGNN) have become the most popular solution to traffic forecasting. While successful, they rely on the message passing scheme of GNNs to establish spatial dependencies between nodes, and thus inevitably inherit GNNs' notorious inefficiency. Given these facts, in this paper, we propose an embarrassingly simple yet remarkably effective spatio-temporal learning approach, entitled SimST. Specifically, SimST approximates the efficacies of GNNs by two spatial learning techniques, which respectively model local and global spatial correlations. Moreover, SimST can be used alongside various temporal models and involves a tailored training strategy. We conduct experiments on five traffic benchmarks to assess the capability of SimST in terms of efficiency and effectiveness. Empirical results show that SimST improves the prediction throughput by up to 39 times compared to more sophisticated STGNNs while attaining comparable performance, which indicates that GNNs are not the only option for spatial modeling in traffic forecasting.
Xu Liu, Yuxuan Liang, Chao Huang, Hengchang Hu, Yushi Cao, Bryan Hooi, Roger Zimmermann
2023-01-30T01:30:04Z
http://arxiv.org/abs/2301.12603v1
# Do We Really Need Graph Neural Networks for Traffic Forecasting? ###### Abstract Spatio-temporal graph neural networks (STGNN) have become the most popular solution to traffic forecasting. While successful, they rely on the message passing scheme of GNNs to establish spatial dependencies between nodes, and thus inevitably inherit GNNs' notorious inefficiency. Given these facts, in this paper, we propose an embarrassingly simple yet remarkably effective spatio-temporal learning approach, entitled SimST. Specifically, SimST approximates the efficacies of GNNs by two spatial learning techniques, which respectively model local and global spatial correlations. Moreover, SimST can be used alongside various temporal models and involves a tailored training strategy. We conduct experiments on five traffic benchmarks to assess the capability of SimST in terms of efficiency and effectiveness. Empirical results show that SimST improves the prediction throughput by up to 39 times compared to more sophisticated STGNNs while attaining comparable performance, which indicates that _GNNs are not the only option for spatial modeling in traffic forecasting_. Machine Learning, ICML ## 1 Introduction In recent years, urban traffic forecasting has emerged as one of the most important components of Intelligent Transportation Systems. Given historical traffic observations (e.g., traffic speed, flow) collected from sensors on road networks, the task focuses on predicting future traffic trends for each sensor, which provides insights for improving urban planning and traffic management (Zheng et al., 2014). Spatio-Temporal Graph Neural Networks (STGNNs) have become the de facto most popular tool for traffic forecasting, in which sequential models such as Temporal Convolution Networks (TCNs) or Recurrent Neural Networks (RNNs) are applied for modeling temporal dependencies (Yu et al., 2018; Pan et al., 2019; Wu et al., 2020; Lan et al., 2022), and Graph Neural Networks (GNNs) (Kipf and Welling, 2017; Defferrard et al., 2016) are utilized to capture spatial correlations among different locations. After revisiting the STGNNs proposed in recent years, we find that they mostly focus on enhancing the spatial learning modules (i.e., GNNs) with either complex aggregation rules or sophisticated layers to improve predictive performance. While successful, we note that they rely heavily on GNNs for performing the message passing step and thus inevitably inherit GNNs' notorious inefficiencies, especially when the graphs are large or with dense connections (Chen et al., 2021; Zhang et al., 2022). As a concrete example, the commonly used adaptive adjacency matrix is built by matrix multiplication of two node embedding tables, producing a fully-connected graph (Wu et al., 2019; Bai et al., 2020; Han et al., 2021). During feature aggregation, such a fully-connected structure leads to _quadratic_ computational complexity w.r.t. the number of sensors. Consequently, the scalability challenges of GNNs hinder the deployment of STGNNs in large-scale and real-time traffic forecasting systems that are latency-bound and require fast inference. Although there are plenty of efforts in the graph domain to improve the efficiency of GNNs, such as via graph simplification (Hamilton et al., 2017; Chen et al., 2018; Chiang et al., 2019; Zeng et al., 2020; Zheng et al., 2020), the related studies in STGNNs are still scarce to the best of our knowledge, as such simplification usually leads to information loss and performance degradation (Wu et al., 2020). Given these facts and inspired by recent progress in eliminating GNNs for node classification (Zhang et al., 2022; Tian et al., 2022), we may ask: _can we remove GNNs to trim down the explosive complexity while still remaining competitive in traffic forecasting accuracy?_ Present WorkTo answer this question, we first demonstrate the functionalities of GNNs as follows. The superior performance of GNNs stems from its structure-aware exploitation of graphs: (1) for each node in the graph, a single GNN layer is used to first aggregate features from nodes' neighbors and then transform the aggregated representations via a feed-forward network, and (2) by stacking multiple layers, the hidden representations of nodes receive messages from long-distance neighbors. In this work, we propose two spatial learning modules to _approximate_ the above efficacies of GNNs without requiring message passing, reducing the time complexity to _linear_. (1) _Local Proximity Modeling_. We take a local view and fragment the traffic network to build an _ego-graph_ for each node, which is constructed by incorporating historical observations of the node's neighbors. Then an MLP is applied to transform the observations to the hidden states at each time step. (2) _Global Correlation Learning_. Inspired by recommender systems that learn user embeddings to reflect user behavioral similarities (He et al., 2017; Zhang et al., 2019), we propose to use sensor embeddings to represent sensors' inherent properties and collaboratively capture spatial relationships between _arbitrary sensor pairs_ in a data-driven manner. Compared with stacking a number of GNN layers to enlarge the receptive field and build long-range spatial dependencies, our module sets up direct connections between nodes and thereby learns the global correlations. In practice, GNNs can be used alongside various temporal models, such as GRU (Chung et al., 2014), WaveNet (Oord et al., 2016), and Transformer (Vaswani et al., 2017), for spatio-temporal learning. Analogously, we empirically find that our proposed spatial modules are agnostic to the temporal encoders and work in a plug-and-play manner. Moreover, we devise a new training strategy for SimST to further boost performance, which increases sample diversity during batch formation and enhances generalization. Integrating the above components, we propose a Simple yet effective Spatio-Temporal learning approach termed **SimST**, which _trims the quadratic cost and performs on par with STGNNs in empirical studies_. Our contributions are summarized as follows. * We for the first time demonstrate that GNNs are not the only choice for spatial modeling in traffic forecasting, by presenting a simple yet admirable method called SimST. * Despite its simplicity, SimST achieves remarkable empirical results in terms of throughput and accuracy against sophisticated state-of-the-art STGNNs: SimST is significantly more efficient than baselines, with up to \(\mathbf{39}\times\) higher inference throughput, while performing on par with them. * We conduct ablation and case studies to promote a better understanding of our method and motivate future research to rethink the importance of GNNs in traffic forecasting. ## 2 Related Work Traffic forecasting is a crucial application in smart city efforts. In recent years, STGNNs have become the most widely used tools for predicting traffic (Cao et al., 2020; Liu et al., 2022; Chen et al., 2021, 2022). Generally, they integrate GNNs with either RNNs or TCNs to capture the spatial and temporal dependencies in traffic data. For example, DCRNN (Li et al., 2018) considered traffic flow as a diffusion process and combined a novel diffusion convolution with GRU. Other efforts (Pan et al., 2019; Fang et al., 2021; Liu et al., 2022) were also based on RNNs. To improve training speed and enjoy parallel computation, plenty of works (Wu et al., 2019, 2020; Li & Zhu, 2021) replaced RNNs with dilated causal convolution. A fundamental problem for using GNNs in traffic modeling is how to establish a graph structure. The mainstream approach to define such structures is using either a predefined and sparse matrix constructed from the road network distances between sensors (Yu et al., 2018; Li et al., 2018; Song et al., 2020), or an adaptive and dense matrix that records the pairwise relationships between nodes (Wu et al., 2019; Bai et al., 2020; Han et al., 2021; Choi et al., 2022). However, researchers have noted that the predefined matrix is heuristic and does not reflect the genuine dependencies between nodes, which degrades model performance (Wu et al., 2019; Bai et al., 2020). Models applying the adaptive matrix generally achieve superior performance. Though successful, the adaptive matrix discards the sparsity of the graph and incurs a quadratic computational cost, making it hard to deploy for latency-constrained or large-scale traffic applications. Other methods that use attention mechanisms for spatial learning (Zheng et al., 2020) also suffer from quadratic time complexity. In this study, we propose SimST to alleviate the inefficiency issue by eliminating the inefficient GNN component in the model. ## 3 Preliminary Traffic ForecastingLet \(G=(\mathcal{V},\mathcal{E})\) represent a directed sensor graph with \(|\mathcal{V}|\) nodes and \(|\mathcal{E}|\) edges, and \(\mathbf{X}^{T}\in\mathbb{R}^{|\mathcal{V}|\times\mathcal{V}}\) denote the features of all nodes from time step 1 to \(T\), where \(F\) is the feature dimension. The features usually consist of a target attribute (e.g., traffic speed) and other auxiliary information, such as time of day (Wu et al., 2019). Following common settings (Li et al., 2018; Wu et al., 2019), a weighted adjacency matrix \(\mathbf{A}\in\mathbb{R}^{|\mathcal{V}|\times|\mathcal{V}|}\) is applied to describe the graph topology, where \(\mathbf{A}_{ij}=\exp(-\frac{\mathrm{dist}(v_{i},v_{j})^{2}}{s^{2}})\) if \(\mathrm{dist}(v_{i},v_{j})\leqslant r\) else \(\mathbf{A}_{ij}=0\), \(\mathrm{dist}(v_{i},v_{j})\) denotes the road network distance between sensors \(v_{i}\) and \(v_{j}\), \(s\) is the standard deviation of distances, and \(r\) is a threshold for sparsity (Shuman et al., 2013). The non-zero entries in \(\mathbf{A}\) form the set of edges in \(\mathcal{E}\). In traffic forecasting, we aim to learn a neural network \(\mathbf{\Theta}\) to predict the target attribute in future \(T_{f}\) steps based on \(T_{h}\) historical observations over the sensor graph: \[G,\mathbf{X}^{T_{h}}\xrightarrow{\mathbf{\Theta}}\hat{\mathbf{Y}}^{T_{f}} \tag{1}\] where \(\mathbf{X}^{T_{h}}\in\mathbb{R}^{|\mathcal{V}|\times T_{h}\times F}\) indicates the observations and \(\hat{\mathbf{Y}}^{T_{f}}\in\mathbb{R}^{|\mathcal{V}|\times T_{f}\times 1}\) is the predictions. A prediction loss, e.g., mean absolute error, is utilized to train the neural network: \[\mathcal{L}(\mathbf{\Theta})=\frac{1}{|\mathcal{V}|}\sum_{v_{i}\in\mathcal{V}}|\hat{ \mathbf{Y}}_{v_{i}}^{T_{f}}-\mathbf{Y}_{v_{i}}^{T_{f}}| \tag{2}\] Graph Neural NetworksAlthough various forms of GNNs exist, our work refers to the conventional message passing scheme (Kipf and Welling, 2017) that is widely adopted in traffic forecasting. Specifically, message passing functions in two ways: aggregating one-hop neighbors to model local correlations, and stacking layers to build long-range relationships. Formally, the node representations \(\mathbf{H}^{l}\) at the \(l\)-th layer of GNNs are learned by first aggregating messages from node neighbors \(\mathcal{N}(v)\), and then transforming the representations via feed-forward propagation: \[\mathbf{H}^{l}=\sigma(\tilde{\mathbf{A}}\mathbf{H}^{l-1}\mathbf{W}^{l}) \tag{3}\] where \(\tilde{\mathbf{A}}\) denotes the normalized adjacency matrix, \(\mathbf{W}^{l}\) denotes the learnable weights at the \(l\)-th layer, and \(\sigma\) is the activation function (e.g., ReLU). ## 4 Methodology As a typical spatio-temporal data mining task, traffic forecasting requires modeling both spatial and temporal aspects. In this section, we start by describing how spatial correlations are set up by the proposed spatial learning modules in Section 4.1. We then introduce three temporal encoders to capture the temporal dependencies and a predictor for generating the future in Section 4.2. Finally, we present a node-based batch sampling method for training SimST in Section 4.3. Figure 1 depicts the architecture of SimST. ### Spatial Learning Modules The inefficiency of GNNs has been extensively discussed within the graph domain (Chiang et al., 2019; Chen et al., 2021; Zhang et al., 2022). Relying on GNNs to set up spatial correlations via message passing, STGNNs also suffer from flagrant inefficiencies. In this work, we propose two simple yet effective alternatives to approximate the functionalities of GNNs and thus allow each node to exploit spatial information without message passing. Local Proximity ModelingA single GNN layer is capable of aggregating neighborhood features in a non-Euclidean structure. To consider such a locality characteristic without using a GNN layer, we propose to first perform graph fragmentation to generate an _ego-graph_ for each node. The features of each ego-graph are the \(T_{h}\) steps historical time series of the center node and its one-hop neighbors. Multi-hop neighbors can also be incorporated if needed, but we found that incorporating more neighbors may suffer from overfitting in experiments (see Section 5.4.3). We then transform the raw features at each time step to their hidden representations via a multi-layer perceptron (MLP). Specifically, for each node \(v\), we consider its top-\(k\) one-hop neighbors based on the weights in the normalized matrix \(\tilde{\mathbf{A}}\), where \(\tilde{\mathbf{A}}=\tilde{\mathbf{D}}^{-\frac{1}{2}}(\mathbf{A}+\mathbf{I})\tilde{\mathbf{D}}^{- \frac{1}{2}}\) and \(\tilde{\mathbf{D}}\) is the degree matrix of \(\mathbf{A}+\mathbf{I}\). We also consider the neighbors in the reversed direction, i.e., the entries in \(\mathbf{A}^{T}\), so that the model can perceive the impact from forward and backward neighbors. Let \(\mathcal{N}_{f}^{1}(v)\) and \(\mathcal{N}_{b}^{1}(v)\) denote the selected one-hop neighbors in two directions. We construct the feature matrix \(\mathbf{X}_{G_{v}}^{T_{h}}\in\mathbb{R}^{T_{h}\times(2k+3)}\) of an ego-graph \(G_{v}\) during period \(T_{h}\): \[\mathbf{X}_{G_{v}}^{T_{h}}=\text{COMBINE}(\mathbf{X}_{v}^{T_{h}},\{\mathbf{X} _{v_{f}}^{T_{h}}:v_{f}\in\mathcal{N}_{f}^{1}(v)\},\\ \{\mathbf{X}_{v_{b}}^{T_{h}}:v_{b}\in\mathcal{N}_{b}^{1}(v)\},\mathbf{X}_{ avgf}^{T_{h}},\mathbf{X}_{avgg}^{T_{h}}) \tag{4}\] where the last two terms are the average histories of all one-hop neighbors in two directions, allowing the center node to learn more about its local context. Note that the execution of building ego-graphs can be completed in data preprocessing, so it has no influence on model training and inference. Then, we apply an MLP to transform the raw features in \(\mathbf{X}_{G_{v}}^{T_{h}}\) and generate the representations \(\mathbf{H}_{G_{v}}^{T_{h}}\in\mathbb{R}^{T_{h}\times D_{m}}\), where \(D_{m}\) is the model hidden dimension. Compared with a GNN layer, our module replaces message aggregation (i.e., weighted sum) operation with ego-graph construction that can be finished in the data preprocessing stage. Figure 1: An overview of SimST from the perspective of a node \(v\) with \(T_{h}\)-step history. Our approach is essentially a single-node architecture (each node is handled individually by the model), which differs from existing STGNNs that require the entire graph as input. Global Correlation LearningRepresenting users with unique embeddings and learning with these embeddings to capture similarities in behavior among users, is a fundamental technique in recommender systems (He et al., 2017; Zhang et al., 2019). Along a similar line, we argue that the traffic situation of a sensor is largely influenced by its specific position on a road, e.g., on the mainline or on a ramp. This is an intrinsic, time-invariant property of the sensor: hence, we propose to represent it using static sensor location embeddings. During end-to-end training, the embedding table collaboratively learns spatial relationships between _arbitrary node pairs_ in a data-driven manner. Apart from capturing global correlations, this module can serve as a complement to the local proximity modeling function, which is particularly useful when the connections in \(\mathbf{A}\) are noisy (Wu et al., 2019; Bai et al., 2020). A detailed case study is conducted in Section 5.5, where we show that the learned sensor embeddings contain significant information for sensor relevance reasoning. Compared with stacking multiple GNN layers to enlarge the receptive field and establish long-range correlations, our proposed module uses embedding similarity to reflect the relationships between arbitrary sensor pairs, and thus further considers global knowledge. Moreover, the connections between sensors are built in a direct way, which keeps our module from over-squashing (Alon and Yahav, 2021). As for implementation, we randomly initialize a low-dimensional embedding for each sensor, leading to an embedding table \(\mathbf{E}\in\mathbb{R}^{|\mathcal{V}|\times D_{n}}\), where \(D_{n}\) is the node embedding size. To fuse the embeddings with model hidden representations, we apply an MLP to map \(\mathbf{E}\) to \(\mathbf{H}\in\mathbb{R}^{|\mathcal{V}|\times D_{m}}\). Complexity ComparisonWe provide a complexity comparison between the spatial learning modules here. As GCN (Kipf and Welling, 2017) is the widely adopted form of GNNs in spatio-temporal models, we take it as a baseline. Suppose a \(L\)-layer GCN with fixed hidden features \(D_{m}\) is applied. For STGNNs applying the predefined adjacency matrix, the time complexity is \(O(L|\mathcal{E}|D_{m}+L|\mathcal{V}|D_{m}^{2})\). When applying the adaptive adjacency matrix that boosts performance, the complexity becomes \(O(L|\mathcal{V}|^{2}D_{m}+L|\mathcal{V}|D_{m}^{2})\). In SimST, the complexity of proximity modeling is \(O(|\mathcal{V}|R)\), where \(R\) is the average degree of nodes. The complexity of correlation learning is \(O(|\mathcal{V}|D_{n}D_{m})\). It is obvious that SimST has lower complexity and is capable of supporting forecasting applications on large-scale sensor networks. ### Temporal Encoder & Predictor There are several viable options for building the temporal dependencies of a node's history. To demonstrate that SimST can be generalized to various temporal models, we incorporate three basic and popular backbones in this study: GRU (Chung et al., 2014) (RNN-based), WaveNet (Oord et al., 2016) (TCN-based), and Transformer (Vaswani et al., 2017). The representations \(\mathbf{H}_{G_{v}}^{T_{h}}\in\mathbb{R}^{T_{h}\times D_{m}}\) are the input of the temporal encoder. For GRU and WaveNet, they compress the temporal dimension to 1, generating the output \(\mathbf{h}_{G_{v}}\in\mathbb{R}^{D_{m}}\), while for Transformer, the resulting representation still has the same shape as \(\mathbf{H}_{G_{v}}^{T_{h}}\). We only take the last time step as the final output. Moreover, since the standard Transformer is aware of all input time steps during self-attention and the traffic status at the current step is in fact not conditioned on its future, we follow WaveNet to introduce causality into the attention mechanism, leading to the design of the Causal Transformer. This ensures that the model cannot violate the temporal order of inputs and such causality can be easily implemented by masking the specific entries in the attention map. Finally, we concatenate the spatio-temporal summary \(\mathbf{h}_{G_{v}}\in\mathbb{R}^{D_{m}}\) of node \(v\) with its location embedding \(\mathbf{H}_{v}\in\mathbb{R}^{D_{m}}\), which is then fed into the predictor (implemented as an MLP) for generating the forecasting results of node \(v\): \(\mathbf{\dot{Y}}_{v}^{T_{f}}=\text{MLP}(\mathbf{h}_{G_{v}}||\mathbf{H}_{v})\). ### Node-based Batch Sampling for Training SimST When training an STGNN, the input data are usually a four-dimensional tensor \(\mathbf{X}^{T_{h}}\in\mathbb{R}^{B\times|\mathcal{V}|\times T_{h}\times F}\), where \(B\) denotes the set batch size. That said, nodes are strictly bound together and the batch sampling unit is the entire graph. However, directly applying this graph-based sampling to SimST leads to two issues. First, since SimST is a single-node architecture, the actual batch size \(B^{*}\) for SimST is \(B\times|\mathcal{V}|\). For example, there are 883 nodes in the PeMSD7 dataset (Song et al., 2020) and usually \(B\) is set to 64, then \(B^{*}=~{}\)56,512. Such a large number reduces the noise in the gradient estimation and leads to a degenerated generalization (Keskar et al., 2017). Also, when \(|\mathcal{V}|\) is large, it can easily cause GPU out-of-memory problems. Second, we argue that the graph-based sampling method significantly diminishes sample diversity when forming mini-batches. For example, the traffic flow of all nodes from 8 to 9 a.m. on January 26 will always appear in the same batch. To tackle these issues, we propose to remove the restriction on nodes and change the batch sampling unit from a graph to a single node. Note that the same node at different time periods is viewed as different instances. Consequently, the input to SimST becomes \(\mathbf{X}^{T_{h}}\in\mathbb{R}^{B^{*}\times T_{h}\times F}\), where \(B^{*}\ll B\times|\mathcal{V}|\). The benefits are two-fold. First, our solution provides flexibility to choose \(B^{*}\), which can be disproportionate to \(|\mathcal{V}|\) and thus allows for smaller values like 256. This property enhances generalization (Keskar et al., 2017), and allows SimST to have low GPU memory costs and to easily scale to large graphs. Second, our approach provides more sample diversity when forming mini-batches, which yields a generalization improvement (Ash et al., 2020). ## 5 Experiments ### Experimental Setup DatasetsWe conduct experiments on commonly used traffic benchmarks. The details are presented in Table 2. All traffic readings are aggregated into 5-minute windows, resulting in 288 data points per day. Note that the values in traffic flow datasets are generally much larger than those in speed-related datasets. Following (Li et al., 2018; Song et al., 2020; Choi et al., 2022), we use the 12-step historical data to predict the next 12 steps. Z-score normalization is applied to the input data for fast training. We build the adjacency matrix of each dataset by using road network distances with a thresholded Gaussian kernel (Shuman et al., 2013). The threshold \(r\) is set to 0 for PeMSD4, PeMSD7, PeMSD8, and 0.1 for LA and BAY. More information is provided in Appendix A. BaselinesWe compare SimST with the following baselines. Historical Average (HA) (Pan et al., 2012) and Vector Autoregression (VAR) (Toda, 1991) are traditional methods. DCRNN (Li et al., 2018), STGCN (Yu et al., 2018), ASTGCN (Guo et al., 2019), GWNET (Wu et al., 2019), STSGCN (Song et al., 2020), and AGCRN (Bai et al., 2020) are well-known STGNNs. We also incorporate methods that are published recently: STGODE (Fang et al., 2021), STGCNDE (Choi et al., 2022), GMSDR (Liu et al., 2022). Implementation DetailsSimST is implemented with PyTorch 1.12. There are three variants of SimST based on the applied temporal encoders. We describe the specific configurations for different variants in Appendix B. The following settings are the same for all variants. We train our method via the Adam optimizer with an initial learning rate of 0.001 and a weight decay of 0.0001. We set the maximum epochs to 150 and use an early stop strategy with a patience of 20. The batch size is 1,024. The embedding size \(D_{n}\) is 20. The top-\(k\) nearest neighbors are set to 3 for LA and BAY, and 0 for PeMSD4, PeMSD7, and PeMSD8 (due to limited available edges). For baselines, we run their codes based on the recommended configurations if their accuracy is not known for a dataset. If known, we use their officially reported accuracy. Experiments are repeated five times with different seeds on an NVIDIA RTX A6000 GPU. Evaluation MetricsWe adopt three common metrics in forecasting tasks to evaluate the model performance, including mean absolute error (MAE), root mean squared error (RMSE), and mean absolute percentage error (MAPE). For efficiency measurement, the commonly used floating point operations per second (FLOPS) cannot reflect the "real" running speed of methods because it ignores the effects of parallelization. Hence, we apply the metric of throughput per second (TPS) in this study, which indicates the average number of samples the network can process in one second. We provide a wall-clock time comparison in Appendix D. ### Performance Comparison In this section, we conduct a model comparison between SimST variants and state-of-the-art STGNNs on five real-world traffic benchmarks. The three variants of SimST are SimST-GRU, SimST-WaveNet (WN), and SimST-Causal Transformer (CT). According to the empirical results in \begin{table} \begin{tabular}{l|c c c|c c c|c c c|c c c|c c c} \hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{PeMSD4} & \multicolumn{3}{c|}{PeMSD7} & \multicolumn{3}{c|}{PeMSD8} & \multicolumn{3}{c|}{LA} & \multicolumn{3}{c}{BAY} \\ \cline{2-13} & MAE & RMSE & MAPE & MAE & RMSE & MAPE & MAE & RMSE & MAPE & MAE & RMSE & MAPE & MAE & RMSE & MAPE \\ \hline \hline HA & 38.03 & 59.24 & 27.88\% & 45.12 & 65.64 & 24.51\% & 34.86 & 59.24 & 27.88\% & 4.16 & 7.80 & 13.00\% & 2.88 & 5.59 & 6.80\% \\ VAR & 24.54 & 38.61 & 17.24\% & 50.22 & 75.63 & 32.22\% & 19.19 & 29.81 & 13.10\% & 5.28 & 9.06 & 12.50\% & 2.24 & 3.96 & 4.83\% \\ \hline DCRNN & 22.39 & 34.93 & 15.19\% & 23.41 & 36.66 & 9.98\% & 16.62 & 25.95 & 10.60\% & 3.14 & 6.28 & 8.65\% & 1.63 & 3.65 & 3.70\% \\ STGCN & 21.59 & 33.83 & 15.49\% & 26.12 & 41.43 & 11.92\% & 17.41 & 26.72 & 11.78\% & 3.39 & 6.79 & 9.34\% & 1.88 & 4.30 & 4.28\% \\ ASTGCN & 21.58 & 33.76 & 14.71\% & 25.77 & 39.41 & 11.67\% & 17.91 & 27.34 & 11.36\% & 3.57 & 7.19 & 10.32\% & 1.86 & 4.07 & 4.27\% \\ GWNET & 19.33 & **30.73** & 13.18\% & 20.65 & 33.47 & 8.84\% & **14.98** & **23.75** & 9.75 & **30.6** & **6.10** & **8.38\%** & 1.58 & 3.54 & 3.59\% \\ STSGCN & 21.19 & 33.65 & 15.90\% & 24.26 & 39.03 & 10.21\% & 17.13 & 26.80 & 10.96\% & 3.32 & 6.66 & 9.06\% & 1.79 & 3.91 & 4.06\% \\ AGCRN & 19.83 & 32.26 & 12.97\% & 20.69 & 34.19 & 8.86\% & 15.95 & 25.22 & 10.09\% & 3.19 & 6.41 & 8.84\% & 1.62 & 3.61 & 3.66\% \\ STGODE & 20.84 & 32.82 & 13.77\% & 22.99 & 37.54 & 10.14\% & 16.81 & 25.97 & 10.62\% & 4.73 & 7.60 & 11.71\% & 1.77 & **3.33** & 4.02\% \\ STGCNDE & 19.21 & 31.09 & **12.76\%** & 20.53 & 33.84 & 8.80\% & 15.45 & 24.81 & 9.92\% & 3.58 & 6.84 & 9.91\% & 1.68 & 3.66 & 3.80\% \\ GMSDR & 20.49 & 32.13 & 14.15\% & 22.27 & 34.94 & 9.86\% & 16.36 & 25.58 & 10.28\% & 3.21 & 6.41 & 8.76\% & 1.69 & 3.80 & 3.74\% \\ \hline SimST-WN & 19.56 & 31.24 & 13.38\% & 20.81 & 33.94 & 8.87\% & 15.55 & 24.70 & 10.17\% & 3.19 & 6.35 & 8.97\% & 1.60 & 3.55 & 3.66\% \\ SimST-CT & 19.32 & 30.98 & 13.35\% & 20.63 & 33.71 & 8.70\% & 15.13 & 24.18 & 2.73\% & 3.11 & 6.19 & 8.73\% & 1.59 & 3.50 & 3.61\% \\ SimST-GRU & **19.19** & 30.92 & 13.13\% & **20.14\({}^{*}\)** & **33.34** & **8.46\%** & 14.99 & 24.26 & **9.66\%** & 3.16 & 6.29 & 8.82\% & **1.57** & 3.47 & **3.58\%** \\ \hline \end{tabular} \end{table} Table 1: Test MAE, RMSE, and MAPE results averaged over all predicted time steps on five datasets. We bold the best results and underline the second best results. \({}^{*}\) denotes the improvement of SimST over the best baseline is statistically significant at level 0.05. \begin{table} \begin{tabular}{l|c c c c} \hline Dataset & \#Node & \#Edge & \#Instance & Attribute \\ \hline \hline PeMSD4 (Song et al., 2020) & 307 & 338 & 16,992 & Flow \\ PeMSD7 (Song et al., 2020) & 883 & 865 & 28,224 & Flow \\ PeMSD8 (Song et al., 2020) & 170 & 276 & 17,856 & Flow \\ LA (Li et al., 2018) & 207 & 1,515 & 34,272 & Speed \\ BAY (Li et al., 2018) & 325 & 2,369 & 52,116 & Speed \\ \hline \hline \end{tabular} \end{table} Table 2: Dataset statistics. Table 1, all variants of SimST achieve competitive performance on the three evaluation metrics of all datasets, which validates the effectiveness of SimST and indicates SimST can generalize to various architectures of temporal models. For comparison among SimST variants: note that for fairness we ensure that the variants have a similar number of parameters (around 150k). SimST-GRU generally achieves comparable performance to state-of-the-art baselines, i.e., GWNET and STGNCDE. SimST-CT also attains competitive accuracy, with little difference from SimST-GRU and GWNET. We notice that while Transformers are generally considered a more powerful model, our results show that a simple GRU works well for traffic prediction. In summary, our results provide strong support for our claim that GNNs are not the only option for spatial modeling in traffic forecasting. Moreover, considering the very different design of SimST compared to other state-of-the-art methods, we hope that this will inspire follow-on studies in graph-less designs. Additionally, we find that: (1) STGNNs approaches surpass HA and VAR by a large margin due to their greater learning capacity. (2) The capability of methods that apply the adaptive matrix, such as GWNET and AGCRN, has been overlooked. They have achieved similar performance to the recently proposed approaches. ### Efficiency Comparison In this part, we select the top-performing approaches and compare their efficiency with SimST variants. It can be seen from Table 3 that all SimST variants are significantly more efficient than baselines, thanks to their simple model architecture and linear time complexity w.r.t. \(|\mathcal{V}|\). Specifically, comparing TCN-based models, SimST-WN has around 45% fewer parameters than GWNET but achieves \(3.3\times-5.6\times\) higher TPS. For RNN-based methods, SimST-GRU is \(3.7\times\) - \(6.1\times\) and \(19\times-26\times\) faster than AGCRN and GMSDR, respectively. STGODE and STGNCDE are the recently published methods that are based on neural ordinary differential equations. Though achieving competitive performance, they suffer from significant inefficiency problems. For example, SimST-WN has comparable performance to them but is \(11\times\) - \(17\times\) and \(30\times\) - \(39\times\) faster. Among the variants, SimST-WN achieves the highest TPS due to WaveNet's superior parallelism capability. SimST-GRU also achieves good TPS results, which we attribute to an optimized implementation in the PyTorch library. See Appendix D for more results on efficiency comparison. ### Ablation Study We have demonstrated the effectiveness and efficiency of SimST. Next, we select SimST-GRU and SimST-CT as the representatives (due to their preferable performance) and conduct a series of ablation and case studies on one flow-based dataset PeMSD4, and one speed-related dataset LA. #### 5.4.1 Effects of spatial learning modules To study the effects of two spatial modules, we consider the following three settings for comparisons: (1) **w/o Correlation Learning (CL)**: we turn off the spatial correlation learning module. (2) **w/o Proximity Modeling (PM)**: for each node, we only input the histories of itself. (3) **CT/GRU**: we do not perform spatial learning. The results \begin{table} \begin{tabular}{l|c c|c c|c c|c c c|c c|c c|c c} \hline \hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{PeMSD4} & \multicolumn{3}{c|}{PeMSD7} & \multicolumn{3}{c|}{PeMSD8} & \multicolumn{3}{c|}{LA} & \multicolumn{3}{c}{BAY} \\ \cline{2-13} & Param & TPS & \(\Delta\) & Param & TPS & \(\Delta\) & Param & TPS & \(\Delta\) & Param & TPS & \(\Delta\) & Param & TPS & \(\Delta\) \\ \hline \hline GWNET & 303 & 1,876 & \(4.15\times\) & 314 & 522 & \(5.65\times\) & 300 & 3,258 & \(3.75\times\) & 301 & 2,825 & \(3.30\times\) & 303 & 1,738 & \(3.52\times\) \\ AGCRN & 749 & 1,559 & \(4.99\times\) & 755 & 445 & \(6.62\times\) & 747 & 1,733 & \(7.06\times\) & 748 & 1,604 & \(5.82\times\) & 749 & 1,466 & \(4.17\times\) \\ STGODE & 715 & 552 & \(14.09\times\) & 733 & 226 & \(13.04\times\) & 710 & 721 & \(16.97\times\) & 709 & 682 & \(13.69\times\) & 713 & 532 & \(11.49\times\) \\ STGNCDE & 377 & 217 & \(35.85\times\) & 388 & 76 & \(38.79\times\) & 374 & 362 & \(33.79\times\) & 375 & 251 & \(37.19\times\) & 377 & 204 & \(29.97\times\) \\ GMSDR & 880 & 267 & \(29.14\times\) & 2253 & 119 & \(27.77\times\) & 423 & 465 & \(26.31\times\) & 641 & 300 & \(31.12\times\) & 923 & 238 & \(25.68\times\) \\ \hline SimST-CT & 147 & 4,597 & \(1.69\times\) & 159 & 1,656 & 1.78\(\times\) & 144 & 7,887 & \(1.55\times\) & 145 & 5,969 & \(1.56\times\) & 148 & 4,041 & \(1.51\times\) \\ SimST-GRU & 130 & 6,167 & \(1.26\times\) & 142 & 2,268 & \(1.30\times\) & 127 & 10,494 & \(1.17\times\) & 128 & 7,766 & \(1.20\times\) & 131 & 5,440 & \(1.12\times\) \\ SimST-WN & 167 & **7,780** & - & 179 & **2,948** & - & 164 & **12,232** & - & 165 & **9,335** & - & 168 & **6,113** & - \\ \hline \hline \end{tabular} \end{table} Table 3: A efficiency comparison between five best-performing baselines and SimST variants. Param denotes the number of learnable parameters and the magnitude of parameters is Kilo (\(10^{3}\)). TPS is measured on the validation set during inference. We bold the highest TPS. The \(\Delta\) column means the TPS improvements of SimST-WN over all the other methods. Figure 2: Effects of two spatial learning modules: correlation learning (CL) and proximity modeling (PM). are shown in Figure 2. First, we find that removing CL leads to significant degradation of MAE for both SimST-GRU and SimST-CT on both datasets, revealing the great importance of building global correlations under the SimST framework. Second, the benefit of PM is marginal on PeMSD4. This is because the average degree of nodes in PeMSD4 is only 1.1, so the available neighbor information is very limited. In contrast, the average degree of nodes in the LA dataset is 7.3, where PM affects performance more. Third, we notice that removing the CL module has a greater impact on the PeMSD4 dataset than on the LA dataset. The reason is that when neighbor information is scarce, the CL module takes a greater responsibility to supplement neighbor knowledge. Conversely, when there are more neighbors, the influence of CL on performance is less significant. #### 5.4.2 Effects of Node-based Batch Sampling We examine the effects of the node-based sampling method from two aspects. First, we show the influence of the batch size number in the first row of Figure 3. Generally, both SimST-GRU and SimST-CT reach their best performance when setting \(B^{*}\) to 1,024 on the two datasets, revealing the necessity of applying a small \(B^{*}\). The negative influence of using a large batch size such as 19,648, is more significant on the PeMSD4 dataset. Besides, we find that SimST-CT only occupies around 2GB of memory on our GPU across all datasets. In contrast, the memory cost of STGNNs usually grows as \(|\mathcal{V}|\) increases. For example, on the dataset with the lowest \(|\mathcal{V}|=170\) and the highest \(|\mathcal{V}|=883\), GWNET requires around 3GB and 11GB of memory, respectively. Second, we present the effects of different batch-forming approaches, i.e., graph-based sampling and node-based sampling by drawing the convergence curves in the second and third rows of Figure 3. Note that we ensure fair comparisons by setting the same \(B^{*}\) in experiments. In Figure 3, it can be seen that node-based batch sampling surpasses the counterpart. Concretely, node-based sampling is only slightly better than the graph-based method when a large \(B^{*}\) is applied (e.g., 19,648/13,248). This is because the sample diversity of graph-based sampling is rich enough at this time. As \(B^{*}\) decreases to small values (e.g., 1,228/828), which is necessary to improve performance, the impact of sample diversity becomes significant, i.e., generalization performance is greatly improved, especially on PeMSD4. Also, we find that the curves of node-based sampling are generally more stable than the graph-based method. #### 5.4.3 Hyperparameter Study In Figure 4, first row, we show the effects of the number of top-\(k\) one-hop neighbors. We replace PeMSD4 with the BAY dataset because the average degree of nodes is only 1.1 in PeMSD4. From the figure, we observe that the performance gradually improves when \(k\) increases from 0 to 3. But the performance worsens when we set \(k\) to 4, indicating a potential overfitting issue. Next, we assess the effects of the sensor embedding dimension size in the second row of Figure 4. We find that both SimST-GRU and SimST Figure 4: Effects of the top-\(k\) neighbors on BAY and LA datasets, and sensor embedding dimension on PeMSD4 and LA datasets. Figure 3: Effects of the node-based batch sampling strategy on PeMSD4 (left column) and LA (right column) datasets. For simplicity, here we denote SimST-GRU as GRU and SimST-CT as CT. In the first row, the largest values in the x-axis are computed by \(|\mathcal{V}|\times 64\) (the common batch size used in STGNNs (Wu et al., 2019; Bai et al., 2020; Choi et al., 2022)). In the second and third rows, the number in the legend denotes \(B^{*}\). CT are not sensitive to the changes in the dimension on both datasets. The results also suggest that a small dimension such as 16, is sufficient to learn correlations between nodes. ### Case Study In this section, we explore further to understand _what exactly the sensor embeddings have learned_ through a case study that makes connections between embedding similarities and real-world sensor locations. We apply SimST-CT on LA and BAY since only these two datasets provide sensors' coordinates. Concretely, we first compute pairwise cosine similarities between sensor embeddings, i.e., for \(v_{i},v_{j}\in\mathcal{V},\text{similarity}=\frac{E_{v_{i}}\cdot E_{v_{j}}}{ \left\|E_{v_{i}}\right\|_{2}\left\|E_{v_{j}}\right\|_{2}}\), and pairwise geodesic distances between sensors based on their coordinates. Then we calculate the average cosine similarities within the ranges of 0-1, 1-5, 5-10, 10-20, and 20-35 kilometers of all sensors, leading to a statistical overview shown in Figure 5 (left part). It can be seen that cosine similarity becomes smaller when the geodesic distance gets larger. This result obeys Tobler's First Law of Geography, i.e., near things are more related than distant things. Next, we look at an example by selecting sensor 62 in LA as the anchor node, which is located at the intersection of two highways. We also visualize its top similar neighbors based on cosine similarity in Figure 5 (upper right). We find that (1) sensors 13 and 58 are the nearby neighbors, which are also included in the adjacency matrix. (2) sensors 201 and 178 are distant nodes. They are considered similar sensors because they are also located at intersections, and thus share similar traffic patterns to the anchor. The situation in the BAY dataset is similar to LA (shown in the lower right of Figure 5), so we do not elaborate further. ### Discussion & Future Work We find that SimST-GRU and SimST-CT perform worse than the state-of-the-art STGNNs (i.e., STGNCDE and GWNET) when we turn off the node-based batch sampling strategy. This result indicates that the proposed two spatial learning modules can only approximate the efficacies of GNNs, and the training strategy of SimST is an indispensable component to obtain comparable performance to the state-of-the-art. In addition, we note that when the neighbor information is relatively rich, such as with LA, SimST-CT is slightly below the state-of-the-art. Therefore, we plan to address this performance gap by utilizing pretrained models and knowledge distillation (Zhang et al., 2022). Lastly, our findings in this work are currently limited to traffic forecasting, while we would like to expand SimST to other spatio-temporal applications such as air quality prediction. ## 6 Conclusion In this paper, we propose SimST, a simple, effective, and efficient spatio-temporal learning method for traffic forecasting. It approximates GNNs with two proposed spatial learning modules, involves a node-based batch sampling strategy, and is temporal-model-agnostic. Our study suggests that message passing is not the only effective way of modeling spatial relations in traffic forecasting; hence, we hope to spur the development of new model designs with both high efficiency and effectiveness in the community. Figure 5: A case study of learned sensor embeddings. The Count axis on the left part means the number of sensor pairs within the corresponding ranges, and the trend is indicated by red dotted line. The sum of the counts is \(|\mathcal{V}|^{2}\). On the right part, the star icons represent the anchor sensor, the circle icons denote the selected similar sensors, and the roads colored in red are the highways in California, USA.
2303.05506
TANGOS: Regularizing Tabular Neural Networks through Gradient Orthogonalization and Specialization
Despite their success with unstructured data, deep neural networks are not yet a panacea for structured tabular data. In the tabular domain, their efficiency crucially relies on various forms of regularization to prevent overfitting and provide strong generalization performance. Existing regularization techniques include broad modelling decisions such as choice of architecture, loss functions, and optimization methods. In this work, we introduce Tabular Neural Gradient Orthogonalization and Specialization (TANGOS), a novel framework for regularization in the tabular setting built on latent unit attributions. The gradient attribution of an activation with respect to a given input feature suggests how the neuron attends to that feature, and is often employed to interpret the predictions of deep networks. In TANGOS, we take a different approach and incorporate neuron attributions directly into training to encourage orthogonalization and specialization of latent attributions in a fully-connected network. Our regularizer encourages neurons to focus on sparse, non-overlapping input features and results in a set of diverse and specialized latent units. In the tabular domain, we demonstrate that our approach can lead to improved out-of-sample generalization performance, outperforming other popular regularization methods. We provide insight into why our regularizer is effective and demonstrate that TANGOS can be applied jointly with existing methods to achieve even greater generalization performance.
Alan Jeffares, Tennison Liu, Jonathan Crabbé, Fergus Imrie, Mihaela van der Schaar
2023-03-09T18:57:13Z
http://arxiv.org/abs/2303.05506v1
# Tangos: Regularizing Tabular Neural Networks through Gradient Orthogonalization and Specialization ###### Abstract Despite their success with unstructured data, deep neural networks are not yet a panacea for structured tabular data. In the tabular domain, their efficiency crucially relies on various forms of regularization to prevent overfitting and provide strong generalization performance. Existing regularization techniques include broad modelling decisions such as choice of architecture, loss functions, and optimization methods. In this work, we introduce Tabular Neural Gradient Orthogonalization and Specialization (TANGOS), a novel framework for regularization in the tabular setting built on latent unit attributions. The gradient attribution of an activation with respect to a given input feature suggests how the neuron _attends_ to that feature, and is often employed to interpret the predictions of deep networks. In TANGOS, we take a different approach and incorporate neuron attributions directly into training to encourage orthogonalization and specialization of _latent attributions_ in a fully-connected network. Our regularizer encourages neurons to focus on sparse, non-overlapping input features and results in a set of diverse and specialized latent units. In the tabular domain, we demonstrate that our approach can lead to improved out-of-sample generalization performance, outperforming other popular regularization methods. We provide insight into _why_ our regularizer is effective and demonstrate that TANGOS can be applied jointly with existing methods to achieve even greater generalization performance. ## 1 Introduction Despite its relative under-representation in deep learning research, tabular data is ubiquitous in many salient application areas including medicine, finance, climate science, and economics. Beyond raw performance gains, deep learning provides a number of promising advantages over non-neural methods including multi-modal learning, meta-learning, and certain interpretability methods, which we expand upon in depth in Appendix C. Additionally, it is a domain in which general-purpose regularizers are of particular importance. Unlike areas such as computer vision or natural language processing, architectures for tabular data generally do not exploit the inherent structure in the input features (i.e. locality in images and sequential text, respectively) and lack the resulting inductive biases in their design. Consequentially, improvement over non-neural ensemble methods has been less pervasive. Regularization methods that implicitly or explicitly encode inductive biases thus play a more significant role. Furthermore, adapting successful strategies from the ensemble literature to neural networks may provide a path to success in the tabular domain (e.g. Wen et al., 2020). Recent work in Kadra et al. (2021) has demonstrated that suitable regularization is essential to outperforming such methods and, furthermore, a balanced _cocktail_ of regularizers results in neural network superiority. Regularization methods employed in practice can be categorized into those that prevent overfitting through data augmentation (Krizhevsky et al., 2012; Zhang et al., 2018), network architecture choices (Hinton et al., 2012; Ioffe and Szegedy, 2015), and penalty terms that explicitly influence parameter learning (Hoerl and Kennard, 1970; Tibshirani, 1996; Jin et al., 2020), to name just a few. While all such methods are unified in attempting to improve out-of-sample generalization, this is often achieved in vastly different ways. For example, \(L1\) and \(L2\) penalties favor sparsity and shrinkage, respectively, on model weights, thus choosing more parsimonious solutions. Data perturbation techniques, on the other hand, encourage smoothness in the system assuming that small perturbations in the input should not result in large changes in the output. Which method works best for a given task is generally not known _a priori_ and considering different classes of regularizer is recommended in practice. Furthermore, combining multiple forms of regularization simultaneously is often effective, especially in lower data regimes (see e.g. Brigato and Iocchi, 2021 and Hu et al., 2017). Neuroscience research has suggested that neurons are both _selective_(Johnston and Dark, 1986) and have _limited capacity_(Cowan et al., 2005) in reacting to specific physiological stimuli. Specifically, neurons selectively choose to focus on a few chunks of information in the input stimulus. In deep learning, a similar concept, commonly described as a _receptive field_, is employed in convolutional layers (Luo et al., 2016). Here, each convolutional unit has multiple filters, and each filter is only sensitive to specialized features in a local region. The output of the filter will activate more strongly if the feature is present. This stands in contrast to fully-connected networks, where the all-to-all relationships between neurons mean each unit depends on the entire input to the network. We leverage this insight to propose a regularization method that can encourage artificial neurons to be more specialized and orthogonal to each other. **Contributions. (1) Novel regularization method for deep tabular models.** In this work, we propose TANGOS, a novel method based on regularizing neuron attributions. A visual depiction is given in Figure 1. Specifically, each neuron is more _specialized_, attending to sparse input features while its attributions are more _orthogonal_ to those of other neurons. In effect, different neurons pay attention to non-overlapping subsets of input features resulting in better generalization performance. We demonstrate that this novel regularization method results in excellent generalization performance on tabular data when compared to other popular regularizers. **(2) Distinct regularization objective.** We explore how TANGOS results in distinct emergent characteristics in the model weights. We further show that its improved performance is linked to increased diversity among weak learners in an ensemble of latent units, which is generally in contrast to existing regularizers. **(3) Combination with other regularizers.** Based upon these insights, we demonstrate that deploying TANGOS _in tandem_ with other regularizers can further improve generalization of neural networks in the tabular setting beyond that of any individual regularizer. Figure 1: **TANGOS encourages specialization and orthogonalization. TANGOS penalizes neuron attributions during training. Here, indicates strong positive attribution and indicates strong negative attribution, while interpolating colors reflect weaker attributions. Neurons are regularized to be _specialized_ (attend to sparser features) and _orthogonal_ (attend to non-overlapping features).** ## 2 Related Work **Gradient Attribution Regularization.** A number of methods exist which incorporate a regularisation term to penalize the network gradients in some way. Penalizing gradient attributions is a natural approach for achieving various desirable properties in a neural network. Such methods have been in use at least since Drucker & Le Cun (1992), where the authors improve robustness by encouraging invariance to small perturbations in the input space. More recently, gradient attribution regularization has been successfully applied across a broad range of application areas. Some notable examples include encouraging the learning of robust features in auto-encoders (Rifai et al., 2011), improving stability in the training of generative adversarial networks (Gulrajani et al., 2017), and providing robustness to adversarial perturbations (Moosavi-Dezfooli et al., 2019). While many works have applied a shrinkage penalty (L2) to input gradients, Ross et al. (2017) explore the effects of encouraging sparsity by considering an L1 penalty term. Gradient penalties may also be leveraged to compel a network to _attemd_ to particular human-annotated input features (Ross et al., 2017). A related line of work considers the use of gradient aggregation methods such as Integrated Gradients (Sundararajan et al., 2017) and, typically, penalizes their deviation from a given target value (see e.g. Liu & Avici (2019) and Chen et al. (2019)). In contrast to these works, we do not require manually annotated regions upon which we constrain the network to attend. Similarly, Erion et al. (2021) provide methods for encoding domain knowledge such as smoothness between adjacent pixels in an image. We note that while these works have investigated penalizing a predictive model's output attributions, we are the first to regularize attributions on latent neuron activations. We provide an extended discussion of related works on neural network regularization more generally in Appendix A. ## 3 Tangos ### Problem Formulation We operate in the standard supervised learning setting, with \(d_{X}\)-dimensional input variables \(X\in\mathcal{X}\subseteq\mathbb{R}^{d_{X}}\) and target output variable \(Y\in\mathcal{Y}\subseteq\mathbb{R}\). Let \(P_{XY}\) denote the joint distribution between input and target variables. The goal of the supervised learning algorithm is to find a predictive model, \(f_{\theta}:\mathcal{X}\rightarrow\mathcal{Y}\) with learnable parameters \(\theta\in\Theta\). The predictive model belongs to a hypothesis space \(f_{\theta}\in\mathcal{H}\) that can map from the input space to the output space. The predictive function is usually learned by optimizing a loss function \(\mathcal{L}:\Theta\rightarrow\mathbb{R}\) using _empirical risk minimization_ (ERM). The empirical risk cannot be directly minimized since the data distribution \(P_{XY}\) is not known. Instead, we use a finite number of iid samples \((x,y)\sim P_{XY}\), which we refer to as the training data \(\mathcal{D}=\{(x_{i},y_{i})\}_{i=1}^{N}\). Once the predictive model is trained on \(\mathcal{D}\), it should ideally predict well on out-of-sample data generated from the same distribution. However, overfitting can occur if the hypothesis space \(\mathcal{H}\) is to complex and the sampling of training data does not fully represent the underlying distribution \(P_{XY}\). Regularization is an approach that reduces the complexity of the hypothesis space so that more generalized functions are learned to explain the data. This leads to the following ERM: \[\theta^{*}=\operatorname*{arg\,min}_{\theta\in\Theta}\frac{1}{|\mathcal{D}|} \sum_{(x,y)\in\mathcal{D}}\mathcal{L}(f_{\theta}(x),y)+\mathcal{R}(\theta,x,y), \tag{1}\] that includes an additional regularization term \(\mathcal{R}\) which, generally, is a function of input \(x\), the label \(y\), the model parameters \(\theta\), and reflects prior assumptions about the model. For example, \(L1\) regularization reflects the belief that sparse solutions in parameter space are more desirable. ### Neuron Attributions Formally, attribution methods aim to uncover the importance of each input feature of a given sample to the prediction of the neural network. Recent works have demonstrated that feature attribution methods can be incorporated into the training process (Lundberg & Lee, 2017; Erion et al., 2021). These _attribution priors_ optimize attributions to have desirable characteristics, including interpretability as well as smoothness and sparsity in predictions. However, these methods have exclusively investigated _output_ attributions, i.e., contributions of input features to the output of a model. To the best of our knowledge, we are the first work to investigate regularization of _latent attributions_. We rewrite our predictive function \(f\) using function composition \(f=l\circ g\). Here \(g:\mathcal{X}\to\mathcal{H}\) maps the input to a representation \(h=g(x)\in\mathcal{H}\), where \(\mathcal{H}\subseteq\mathbb{R}^{d_{H}}\) is a \(d_{H}\)-dimensional latent space. Additionally, \(l:\mathcal{H}\to\mathcal{Y}\) maps the latent representation to a label space \(y=l(h)\in\mathcal{Y}\). We let \(h_{i}=g_{i}(x)\), for, \(i\in[d_{H}]\) denote the \(i^{th}\) neuron in the hidden layer of interest. Additionally, we use \(a^{i}_{j}(x)\in\mathbb{R}\) to denote the attribution of the \(i^{th}\) neuron w.r.t. the feature \(x_{j}\). With this notation, upper indices correspond to latent units and lower indices to features. In some cases, it will be convenient to stack all the feature attributions together in the attribution vector \(a^{i}(x)=[a^{i}_{j}(x)]_{j=1}^{d_{X}}\in\mathbb{R}^{d_{X}}\). Attribution methods work by using gradient signals to evaluate the contributions of the input features. In the most simplistic setting: \[a^{i}_{j}(x)\equiv\frac{\partial h_{i}(x)}{\partial x_{j}}. \tag{2}\] This admits a simple interpretation through a first-order Taylor expansion: if the input feature \(x_{j}\) were to increase by some small number \(\epsilon\in\mathbb{R}^{+}\), the neuron activation would change by \(\epsilon\cdot a^{i}_{j}(x)+\mathcal{O}(\epsilon^{2})\). The larger the absolute value of the gradient, the stronger the effect of a change in the input feature. We emphasize that our method is _agnostic_ to the gradient attribution method, as different methods may be more appropriate for different tasks. For a comprehensive review of different methods, assumptions, and trade-offs, see Ancona et al. (2017). For completeness, we also note another category of attribution methods is built around _perturbations_: this class of methods evaluates contributions of individual features through repeated perturbations. Generally speaking, they are more computationally inefficient due to the multiple forward passes through the neural network and are difficult to include directly in the training objective. ### Rewarding Orthogonalization and Specialization The main contribution of this work is proposing regularization on neuron attributions. In the most general sense, any function of any neuron attribution method could be used as a regularization term, thus encoding prior knowledge about the properties a model should have. Specifically, the regularization term is a function of the network parameters \(\theta\) and \(x\), i.e., \(\mathcal{R}(\theta,x)\), and encourages prior assumptions on desired behavior of the learned function. Biological sensory neurons are highly specialized. For example, certain visual neurons respond to a specific set of visual features including edges and orientations within a single receptive field. They are thus highly _selective_ with _limited capacity_ to react to specific physiological stimuli (Johnston & Dark, 1986; Cowan et al., 2005). Similarly, we hypothesize that neurons that are more specialized and pay attention to sparser signals should exhibit better generalization performance. We propose the following desiderata and corresponding regularization terms: * **Specialization.** The contribution of input features to the activation of a particular neuron should be sparse, i.e., \(||a^{i}(x)||\) is small for all \(i\in[d_{H}]\) and \(x\in\mathcal{X}\). Intuitively, in higher-dimensional settings, a few features should account for a large percentage of total attributions while others are near zero, resulting in more _specialized_ neurons. We write this as a regularization term for mini-batch training: \[\mathcal{L}_{\mathrm{spec}}(x)=\frac{1}{B}\sum_{b=1}^{B}\frac{1}{d_{H}}\sum_{i =1}^{d_{H}}\lVert a^{i}(x_{b})\rVert_{1},\] where \(b\in[B]\) is the batch index of \(x_{b}\in\mathcal{X}\) and \(\lVert\cdot\rVert_{1}\) denotes the \(l_{1}\) norm. * **Orthogonalization.** Different neurons should attend to non-overlapping subsets of input features given a particular input sample. To encourage this, we penalize the correlation between neuron attributions \(\rho[a^{i}(x),a^{j}(x)]\) for all \(i\neq j\) and \(x\in\mathcal{X}\). In other words, for each particular input, we Figure 2: **Method illustration.** TANGOS regularizes the gradients with respect to each of the latent units. want to discipline the latent units to attend to different aspects of the input. Then, expressing this as a regularization term for mini-batch training, we obtain: \[\mathcal{L}_{\mathrm{orth}}(x)=\frac{1}{B}\sum_{b=1}^{B}\frac{1}{C}\sum_{i=2}^{d _{H}}\sum_{j=1}^{i-1}\rho\left[a^{i}(x_{b}),a^{j}(x_{b})\right].\] Here, \(C\) is the number of pairwise correlations, \(C=\frac{d_{H}\cdot(d_{H}-1)}{2}\), and \(\rho[a^{i}(x_{b}),a^{j}(x_{b})]\in[0,1]\) is calculated using the cosine similarity \(\frac{|a^{i}(x_{b})\ a^{j}(x_{b})|}{||a^{i}(x_{b})||||a^{j}(x_{b})||_{2}}\) where \(\|\cdot\|_{2}\) denotes the \(l_{2}\) norm. These terms can be combined into a single regularization term and incorporated into the training objective. The resulting TANGOS regularizer can be expressed as: \[\mathcal{R}_{\texttt{TANGOS}}(x)=\lambda_{1}\mathcal{L}_{\mathrm{spec}}(x)+ \lambda_{2}\mathcal{L}_{\mathrm{orth}}(x),\] where \(\lambda_{1}\), \(\lambda_{2}\in\mathbb{R}\) act as weighting terms. As this expression is computed using gradient signals, it can be efficiently implemented and minimized in any auto-grad framework. ## 4 _How_ and _Why_ Does TANGOS Work? To the best of our knowledge, TANGOS is the only work to explicitly regularize latent neuron attributions. A natural question to ask is (1) _How is_ TANGOS _different from other regularization?_ While intuitively it makes sense to enforce _specialization_ of each unit and _orthogonalization_ between units, we empirically investigate if other regularizers can achieve similar effects, revealing that our method regularizes a unique objective. Having established that the TANGOS objective is unique, the next question is (2) _Why does it work?_ To investigate this question, we frame the set of neurons as an ensemble, and demonstrate that our regularization improves diversity among _weak learners_, resulting in improved out-of-sample generalization. ### TANGOS Regularizes a Unique Objective TANGOS encourages generalization by explicitly decorrelating and sparsifying the attributions of latent units. A reasonable question to ask is if this is unique, or if other regularizers might achieve the same objective implicitly. Two alternative regularizers that one might consider are \(L2\) weight regularization and \(Dropout\). Like TANGOS, weight regularization methods implicitly and partially penalize the gradients by shrinking the weights in the neural network. Additionally, \(Dropout\) trains an ensemble of learners by forcing each neuron to be more independent. In Figure 3, we provide these results on the UCI temperature forecast dataset (Cho et al., 2020), in which data from 25 weather stations in South Korea is used to predict next-day peak temperature. We train a fully connected neural network for each regularization method. Specifically, we plot \(\mathcal{L}_{spec}\) and \(\mathcal{L}_{orth}\) for neurons in the penultimate layers and the corresponding generalization performance. We supply an extended selection of these results on additional datasets and regularizers in Appendix J. First, we observe that TANGOS significantly decreases correlation between different neuron attributions while other regularization terms, in fact, increase them. For \(L2\) weight regularization, this suggests that as the neural network weights are made smaller, the neurons increasingly attend to the same input features. A similar effect is observed for \(Dropout\) - which has a logical explanation. Indeed, \(Dropout\) creates redundancy by forcing each latent unit to be independent of others. Naturally, this encourages individual neurons to attend to overlapping features. In contrast, TANGOS aims to achieve specialization, such that neurons pay attention to sparse, non-overlapping features. Additionally, we note that no alternative regularizers achieve greater attribution sparsity. This does not come as a surprise for \(Dropout\), where the aim to induce redundancy in each neuron will naturally encourage individual neurons to attend to more features. While \(L2\) does achieve a similar level of sparsity, this is paired with a high \(\mathcal{L}_{orth}\) term indicating that, although the latent units do attend to sparse features, they appear to collapse to a solution in which they all attend to the same weighted subset of the input features. This, as we will discover in SS4.2, is unlikely to be optimal for out-of-sample generalization. Therefore, we conclude that the pairing of the specialization and orthogonality objectives in TANGOS regularizes a unique objective. ### TANGOS Generalizes by Increasing Diversity Among Latent Units Having established how TANGOS differs from existing regularization objectives, we now turn to answer _why_ it works. In this section, we provide an alternative perspective on the effect of TANGOS regularization in the context of ensemble learning. A predictive model \(f(x)\) may be considered as an ensemble model if it can be written in the form \(f(x)=\sum_{T_{k}\in\mathcal{T}}\alpha_{k}T_{k}(x)\), where \(\mathcal{T}\) represents a set of basis functions sometimes referred to as _weak learners_ and the \(\alpha_{k}\)'s represent their respective scalar weights. It is therefore clear that each output of a typical neural network may be considered an ensemble predictor with every latent unit in its penultimate layer acting as a weak learner in their contribution to the model's output. More formally, in this setting \(T_{k}(x)\) is the activation of latent unit \(k\) with respect to an input \(x\) and \(\alpha_{k}\) is the subsequent connection to the output activation. With this in mind, we present the following definition. **Definition 4.1**.: _Consider an ensemble regressor \(f(x)=\sum_{T_{k}\in\mathcal{T}}\alpha_{k}T_{k}(x)\) trained on \(\mathcal{D}=\{(x_{i},y_{i})\}_{i=1}^{N}\) where each \((x,y)\) is drawn randomly from \(P_{XY}\). Additionally, the weights are constrained such that \(\sum_{k}\alpha_{k}=1\). Then, for a given input-label pair \((x,y)\), we define:_ 1. _The overall ensemble error as:_ \(\mathrm{Err}=(f(x)-y)^{2}\)_._ 2. _The weighted errors of the weak learners as:_ \(\overline{\mathrm{Err}}=\sum_{k}\alpha_{k}(T_{k}(x)-y)^{2}\)_._ 3. _The ensemble diversity as:_ \(\mathrm{Div}=\sum_{k}\alpha_{k}(T_{k}(x)-f(x))^{2}\)_._ Intuitively, \(\overline{\mathrm{Err}}\) provides a measure of the strength of the ensemble members while \(\mathrm{Div}\) measures the diversity of their outputs. To understand the relationship between these two terms and the overall ensemble performance, we consider Proposition 1. **Proposition 1** (Krogh & Vedelsby 1994).: _The overall ensemble error for an input-label pair \((x,y)\) can be decomposed into the weighted errors of the weak learners and the ensemble diversity such that:_ \[\mathrm{Err}=\overline{\mathrm{Err}}-\mathrm{Div}. \tag{3}\] This decomposition provides a fundamental insight into the success of ensemble methods: an ensemble's overall error is reduced by decreasing the average error of the individual weak learners and increasing the diversity of their outputs. Successful ensemble methods explicitly increase ensemble diversity when training weak learners by, for example, sub-sampling input features (random forest, Breiman, 2001), sub-sampling from the training data (bagging, Breiman, 1996) or error-weighted input importance (boosting, Buhlmann, 2012). Returning to the specific case of neural networks, it is clear that TANGOS provides a similar mechanism of increasing diversity among the latent units that act as weak learners in the penultimate Figure 3: **Comparison of regularization objectives. (Top) Generalization performance of key regularization techniques, (Bottom) corresponding neuron attributions evaluated on the test set. \(L2\) and \(DO\) can reduce overfitting, but neuron attributions are in fact becoming more correlated. TANGOS achieves the best generalization performance by penalizing a different objective.** layer. By forcing the latent units to attend to sparse, uncorrelated selections of features, the learned ensemble is encouraged to produce diverse learners whilst maintaining coverage of the entire input space in aggregate. In Figure 4, we demonstrate this phenomenon in practice by returning to the UCI temperature forecast regression task. We provide extended results in Appendix J. We train a fully connected neural network with two hidden layers with the output layer weights constrained such that they sum to 1. We observe that regularizing with TANGOS increases diversity of the latent activations resulting in improved out-of-sample generalization. This is in contrast to other typical regularization approaches which also improve model performance, but exclusively by attempting to reduce the error of the individual ensemble members. This provides additional motivation for applying TANGOS in the tabular domain, an area where traditional ensemble methods have performed particularly well. ## 5 Experiments In this section, we empirically evaluate TANGOS as a regularization method for improving generalization performance. We present our benchmark methods and training architecture, followed by extensive results on real-world datasets. There are a few main aspects that deserve empirical \begin{table} \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline Dataset & Baseline & L1 & L2 & DO & BN & IN & MU & TANGOS \\ \hline \multicolumn{10}{|c|}{Regression (Mean Squared Error)} \\ \hline FB & 0.037 & 0.081 & **0.029** & 0.060 & 0.699 & 0.043 & 0.147 & 0.032 \\ BH & 0.192 & 0.197 & 0.183 & 0.209 & 0.190 & 0.215 & 0.286 & **0.166** \\ WE & 0.118 & 0.096 & 0.099 & 0.097 & **0.090** & 0.101 & 0.146 & 0.093 \\ BC & 0.323 & 0.263 & 0.277 & 0.282 & 0.294 & 0.308 & 0.323 & **0.244** \\ WQ & 0.673 & 0.641 & 0.644 & 0.658 & 0.639 & 0.669 & 0.713 & **0.637** \\ SC & 0.422 & 0.408 & 0.411 & 0.423 & 0.410 & 0.434 & 0.547 & **0.387** \\ FF & 1.274 & 1.280 & 1.274 & 1.266 & 1.330 & **1.201** & 1.289 & 1.276 \\ PR & 0.624 & 0.611 & 0.580 & 0.592 & 0.647 & 0.591 & 0.745 & **0.573** \\ ST & 0.419 & 0.416 & 0.418 & 0.387 & 0.461 & 0.539 & **0.380** & 0.382 \\ AB & 0.345 & 0.319 & 0.332 & **0.312** & 0.348 & 0.355 & 0.366 & 0.325 \\ \hline \hline \multicolumn{10}{|c|}{Avg Rank} & 5.4 & 3.8 & 3.4 & 4.0 & 5.0 & 5.5 & 7.1 & **1.9** \\ \hline \multicolumn{10}{|c|}{Classification (Mean Negative Log-Likelihood)} \\ \hline \hline HE & 0.490 & 0.472 & 0.431 & 0.428 & 0.459 & 0.435 & **0.416** & 0.426 \\ BR & 0.074 & 0.070 & 0.070 & 0.078 & 0.080 & 0.071 & 0.095 & **0.069** \\ CE & 0.519 & **0.395** & 0.407 & 0.436 & 0.604 & 0.457 & 0.472 & 0.408 \\ CR & 0.464 & 0.405 & 0.402 & 0.456 & 0.460 & 0.481 & 0.448 & **0.369** \\ HC & 0.320 & 0.222 & 0.226 & 0.237 & 0.257 & 0.312 & 0.248 & **0.215** \\ AU & 0.448 & 0.442 & 0.385 & 0.405 & 0.549 & 0.479 & 0.478 & **0.379** \\ TU & 1.649 & 1.633 & 1.613 & 1.621 & **1.484** & 1.646 & 1.657 & 1.495 \\ EN & 1.040 & 1.040 & 1.042 & 1.058 & 1.098 & 1.072 & 1.065 & **0.974** \\ TH & 0.700 & 0.506 & **0.500** & 0.714 & 0.785 & 0.638 & 0.618 & 0.513 \\ SO & 0.606 & **0.238** & 0.382 & 0.567 & 0.484 & 0.540 & 0.412 & 0.371 \\ \hline \hline Avg Rank & 6.4 & 3.0 & 2.7 & 4.8 & 6.3 & 6.0 & 5.2 & **1.7** \\ \hline \end{tabular} \end{table} Table 1: **Stand-Alone Regularization. Comparison of regularizers on regression and classification in terms of test MSE and NLL. All models are trained on real-world datasets using 5-fold cross-validation and final evaluation reported on a held-out test set. **Bold** indicates the best performance. The average rank of each method across both regression and classification is included in the final row of the respective tables.** Figure 4: **Neuron Diversity. Overall ensemble error and decomposition in terms of diversity and average error of the weak learners. Note while all methods achieve low overall error, TANGOS is the only method that does so by increasing the diversity among the latent units.** investigation, which we investigate in turn: \(\blacktriangleright\)**Stand-alone performance.** SS5.1 Comparing the performance of TANGOS, where the focus is on applying it as a stand-alone regularizer, to a variety of benchmarks on a suite of real-world datasets. \(\blacktriangleright\)**In tandem performance.** SS5.2 Motivated by our unique regularization objective and our analysis in SS4, we demonstrate that applying TANGOS_in conjunction_ with other regularizers can lead to even greater gains in generalization performance. \(\blacktriangleright\)**Modern architectures.** SS5.3 We evaluate performance on a state-of-the-art tabular architecture and compare to boosting. All experiments were run on NVIDIA RTX A4000 GPUs. Code is provided on Github12. Footnote 1: [https://github.com/alanjeffares/TANGOS](https://github.com/alanjeffares/TANGOS) **TANGOS.** We train TANGOS regularized models as described in Algorithm 1 in Appendix F. For the specialization parameter we search for \(\lambda_{1}\in\{1,10,100\}\) and for the orthogonalization parameter we search for \(\lambda_{2}\in\{0.1,1\}\). For computational efficiency, we apply a sub-sampling scheme where 50 neuron pairs are randomly sampled for each input (for further details see Appendix F). **Benchmarks.** We evaluate TANGOS against a selection of popular regularizer benchmarks. First, we consider weight decay methods **L1** and **L2** regularization, which sparsify and shrink the learnable parameters. For the regularizers coefficients, we search for \(\lambda\in\{0.1,0.01,0.001\}\) where regularization is applied to all layers. Next, we consider Dropout **(DO)**, with drop rate \(p\in\{10\%,25\%,50\%\}\), and apply DO after every dense layer during training. We also consider implicit regularization in batch normalization (**BN**). Lastly, we evaluate data augmentation techniques Input Noise (**IN**), where we use additive Gaussian noise with mean 0 and standard deviation \(\sigma\in\{0.1,0.05,0.01\}\) and MixUp (**MU**). Furthermore, each training run applies early stopping with patience of 30 epochs. In all experiments, we use 5-fold cross-validation to train and validate each benchmark. We select the model which achieves the lowest validation error and provide a final evaluation on a held-out test set. ### Generalization: Stand-Alone Regularization For the first set of experiments, we are interested in investigating the individual regularization effect of TANGOS. To ensure a fair comparison, we evaluate the generalization performance on held-out test sets across a variety of datasets. **Datasets.** We employ \(20\) real-world tabular datasets from the UCI machine learning repository. Each dataset is split into \(80\%\) for cross-validation and the remaining \(20\%\) for testing. The splits are standardized on just the training data, such that features have mean \(0\) and standard deviation \(1\) and categorical variables are one-hot encoded. See Appendix L for further details on the \(20\) datasets used. **Training and Evaluation.** To ensure a fair comparison, all regularizers are applied to an MLP with two ReLU-activated hidden layers, where each hidden layer has \(d_{H}+1\) neurons. The models are trained using Adam optimizer with a dataset-dependent learning rate from \(\{0.01,0.001,0.0001\}\) and are trained for up to a maximum of \(200\) epochs. For regression tasks, we report the average Mean Square Error (MSE) and, on classification tasks, we report the average negative log-likelihood (NLL). **Results.** Table 1 provides the benchmarking results for individual regularizers. We observe that TANGOS achieves the best performance on \(10/20\) of the datasets. We also observe that on 6 of the remaining datasets, TANGOS ranks second. This is also illustrated by the ranking plot in Appendix H. There we also provide a table displaying standard errors. As several results have overlapping error intervals, we also assess the magnitude of improvement by performing a non-parametric Wilcoxon signed-rank sum test (Wilcoxon, 1992) paired at the dataset level. We compare TANGOS to the best-performing baseline method (L2) as a one-tailed test for both the regression and classification results obtaining p-values of 0.006 and 0.026 respectively. This can be interpreted as strong evidence to suggest the difference is statistically significant in both cases. Note that a single regularizer is seldom used by itself. In addition to a stand-alone method, it remains to be shown that TANGOS brings value when used with other regularization methods. This is explored in the next section. ### Generalisation: In Tandem Regularization Motivated by the insights described in SS4, a natural next question is whether TANGOS can be applied in conjunction with existing regularization to unlock even greater generalization performance. In this set of experiments, we investigate this question. **Setup.** The setting for this experiment is identical to SS5.1 except now we consider the six baseline regularizers _in tandem_ with TANGOS. We examine if pairing our proposed regularizer with existing methods results in even greater generalization performance. We again run 5-fold cross-validation, searching over the same hyperparameters, with the final models evaluated on a held-out test set. **Results.** We summarize the aggregated results over the datasets for each of the six baseline regularizers in combination with TANGOS in Figure 5. Consistently across all regularizers in both the regression and the classification settings, we observe that adding TANGOS regularization improves test performance. We provide the full table of results in the supplementary material. We also note an apparent interaction effect between certain regularizers (i.e. input noise for regression and dropout for classification), where methods that seemed to not be particularly effective as stand-alone regularizers become the best-performing method when evaluated in tandem. The relationship between such regularizers provides an interesting direction for future work. ### Closing the Gap on Boosting In this experiment, we apply TANGOS regularization to a state-of-the-art deep learning architecture for tabular data (Gorishniy et al., 2021) and evaluate its contribution towards producing competitive performance against leading boosting methods. We provide an extended description of this experiment in Appendix B and results in Table 2. We find that TANGOS provides moderate gains in this setting, improving performance relative to state-of-the-art boosting methods. Although boosting approaches still match or outperform deep learning in this setting, in Appendix C we argue that deep learning may also be worth pursuing in the tabular modality for its other distinct advantages. ## 6 Discussion In this work, we have introduced TANGOS, a novel regularization method that promotes specialization and orthogonalization among the gradient attributions of the latent units of a neural network. We showed _how_ this regularization objective is distinct from other popular methods and motivated _why_ it provides out-of-sample generalization. We empirically demonstrated TANGOS utility with extensive experiments. This work raises several exciting avenues for **future work** including (1) developing TANGOS beyond the tabular setting (e.g. images), (2) investigating alternative efficient methods for achieving specialization and orthogonalization, (3) proposing other latent gradient attribution regularizers, (4) augmenting TANGOS for specific applications such as multi-modal learning or increased interpretability (see Appendix C). \begin{table} \begin{tabular}{|c|c|c c|c c|} \hline \multirow{2}{*}{Setting} & \multirow{2}{*}{Dataset} & \multicolumn{2}{c|}{FT-Transformer} & \multicolumn{2}{c|}{Boosting} \\ \cline{3-6} & & Baseline & \(\mathbf{+}\)TANGOS & XGBoost & CatBoost \\ \hline \multirow{2}{*}{Default} & Jannis & \(0.714\pm 0.002\) & \(\mathbf{0.720}\pm 0.000\) & \(0.711\pm 0.000\) & \(\mathbf{0.724}\pm 0.001\) \\ & Higgs & \(0.721\pm 0.002\) & \(\mathbf{0.723}\pm 0.000\) & \(0.717\pm 0.000\) & \(\mathbf{0.728}\pm 0.001\) \\ \hline \multirow{2}{*}{Tuned} & Jannis & \(0.720\pm 0.001\) & \(\mathbf{0.727}\pm 0.001\) & \(0.724\pm 0.000\) & \(\mathbf{0.727}\pm 0.001\) \\ & Higgs & \(0.727\pm 0.002\) & \(\mathbf{0.729}\pm 0.002\) & \(0.728\pm 0.001\) & \(\mathbf{0.729}\pm 0.002\) \\ \hline \end{tabular} \end{table} Table 2: **FT-Transformer Architecture and Boosting. Adding TANGOS regularization can contribute to closing the gap between state-of-the-art tabular architectures and leading boosting methods. We report mean accuracy \(\pm\) standard deviation.** Figure 5: **In Tandem Regularization. Aggregated errors across the 10 regression datasets (left) and the 10 classification datasets (right). In all cases, the addition of TANGOS provides superior performance over the standalone regularizer.** ## Acknowledgments We thank the anonymous ICLR reviewers as well as members of the van der Schaar lab for many insightful comments and suggestions. Alan Jeffares is funded by the Cystc Fibrosis Trust. Tennison Liu would like to thank AstraZeneca for their sponsorship and support. Fergus Imrie and Mihaela van der Schaar are supported by the National Science Foundation (NSF, grant number 1722516). Mihaela van der Schaar is additionally supported by the Office of Naval Research (ONR). ## Reproducibility Statement We have attempted to make our experimental results easily reproducible by both a detailed description of our experimental procedure and providing the code used to produce our results ([https://github.com/alanjeffares/TANGOS](https://github.com/alanjeffares/TANGOS)). Experiments are described in Section 5 with further details in Appendices F and L. All datasets used in this work can be freely downloaded from the UCI repository (Dua et al., 2017) with specific details provided in Appendix L.
2308.05106
Balancing Accuracy and Training Time in Federated Learning for Violence Detection in Surveillance Videos: A Study of Neural Network Architectures
This paper presents an investigation into machine learning techniques for violence detection in videos and their adaptation to a federated learning context. The study includes experiments with spatio-temporal features extracted from benchmark video datasets, comparison of different methods, and proposal of a modified version of the "Flow-Gated" architecture called "Diff-Gated." Additionally, various machine learning techniques, including super-convergence and transfer learning, are explored, and a method for adapting centralized datasets to a federated learning context is developed. The research achieves better accuracy results compared to state-of-the-art models by training the best violence detection model in a federated learning context.
Pajon Quentin, Serre Swan, Wissocq Hugo, Rabaud Léo, Haidar Siba, Yaacoub Antoun
2023-06-29T19:44:02Z
http://arxiv.org/abs/2308.05106v1
Balancing Accuracy and Training Time in Federated Learning for Violence Detection in Surveillance Videos: A Study of Neural Network Architectures ###### Abstract This paper presents an investigation into machine learning techniques for violence detection in videos and their adaptation to a federated learning context. The study includes experiments with spatio-temporal features extracted from benchmark video datasets, comparison of different methods, and proposal of a modified version of the "Flow-Gated" architecture called "Diff-Gated." Additionally, various machine learning techniques, including super-convergence and transfer learning, are explored, and a method for adapting centralized datasets to a federated learning context is developed. The research achieves better accuracy results compared to state-of-the-art models by training the best violence detection model in a federated learning context. ## 1 Introduction Violence detection can be used in many contexts: soccer stadiums, surveillance cameras, video sharing services, etc. Moreover, humans aren't able to detect violence on this scale because of the huge quantity of data involved. In the context of a CCTV center such AI can be used to inform the authorities and permit to intervene faster Youssef _et al._ (2021). Federated learning can play a crucial role in ensuring data privacy and security for violence detection in surveillance videos, especially in compliance with GDPR regulations EU (2016). By keeping the training data and machine learning model on the devices where it was collected, the risk of sensitive information being intercepted on the network can be avoided Gosselin _et al._ (2022). Moreover, federated learning can leverage techniques like differential privacy Hu _et al._ (2020) to protect individual privacy and reduce the risk of model reverse-engineering Cheng _et al._ (2020). This approach can be particularly useful in contexts such as CCTV centers, where timely detection of violence can inform authorities and help to intervene faster. The ethical implications tied to the use of machine learning for violence detection in surveillance contexts are significant. Potential issues range from infingingements of privacy rights Crawford and Schultz (2013) to biases in the algorithm, potentially leading to discriminatory outcomes Zou and Schiebinger (2018), Buolamwini and Gebru (2018). These systems, while technologically innovative, need to be used judiciously to avoid misuse and ensure fairness and transparency Mittelstadt _et al._ (2016); Greene _et al._ (2019). They should not replace human judgement, but act as supportive tools for security personnel. Thus, it becomes critical to foster responsible AI practices, placing paramount importance on individual privacy and fairness. In this paper, we propose a deep learning architecture for violence detection that can be effectively trained using federated learning, with memory efficiency and reduced training time as key considerations. By exploring the use of spatio-temporal features and machine learning techniques such as super-convergence and transfer learning, we achieve better accuracy results compared to state-of-the-art models. Our approach can pave the way for privacy-preserving and efficient violence detection in a range of real-world scenarios. ## 2 Related work In this section, we explore two important topics in the field of data science: violence detection and federated learning. ### Violence Detection Violence detection is a sub-field of action recognition that consists of detecting specific actions in videos. The detection of violence or fight scenes has been an active research field for a long time. Classical methods for violence detection used hand-crafted features, such as ViF Violent FlowHassner _et al._ (2012), which detects changes in optical flow, and OViF Oriented Violent FlowGao _et al._ (2016), an improvement of ViF that makes better use of the orientation information of optical flows. Optical flow is the apparent changes in the pixels of two consecutive images of a video. More recently, deep learning methods have been developed, achieving better results and requiring less processing than classical methods, allowing the model to learn the violence patterns. To do this, several architectures have been experimented with over time. One method is to use 3D CNNs Ding _et al._ (2014), which applies convolutions to videos. This method has improved over time, such as in Li _et al._ (2019), which applies the concepts of DenseNet Huang _et al._ (2017) to improve the model's performance and reduce the number of parameters. Another deep learning method is to use Conv-LSTM cells [21] and a traditional CNN. LSTM aggregates the features extracted by the CNN on the frames of the video to obtain temporal information. This is what is done by [20]. [1] proposed using two input channels instead of one corresponding to the video frames. The additional channel is the optical flow, which helps the model focus on the areas where there is movement and possibly violence. ### Federated Learning Data governance has become an important consideration in violence detection research, particularly with regards to the ethical and legal implications of video data privacy following the implementation of the GDPR [1]. In response, federated learning has emerged as a promising approach for training data science models without centralized data storage, with several algorithms such as FederatedAveraging [17], FedProx [11], MIME [14], and FEDOPT [1] proposed for this purpose. In this paper, we adopt FederatedAveraging [17], a technique that allows each client to train a local model with their own data. The resulting models are then averaged to train a global model that is sent back to the clients after each round. FederatedAveraging has been demonstrated to be well-suited to Non-IID (independent and identically distributed) data distributions in [17]. Relatedly, [21] work in 2022 also leveraged federated learning for violence detection in videos, using various pre-trained convolutional neural networks on the AIRTLab Dataset and finding the best performance with MobileNet architecture, showcasing a high accuracy of 99.4% with only a marginal loss when compared to non-federated learning settings. ## 3 Methodology In this subsection, we present the architectures of the models used for violence detection and how we adapted these models for the federated learning context. Our objective is to achieve state-of-the-art or higher accuracy while being resource and time-efficient since these models are intended to be deployed and trained in CCTV centers, which typically have less powerful computers than research environments. We also describe the methodology we used to develop and optimize our violence detection model, which involved addressing the limitations of classical classifiers using transfer learning, early stopping, and One-Cycle training. Additionally, we explore multi-channel input models using both optical flow and frame differences, and detail the specific model architectures we used to achieve better performance while reducing computation time. Overall, this section provides a comprehensive overview of our approach to developing a robust and efficient violence detection model. ### Limitation of Classical Classifiers [14] utilized a pre-trained model on the Sports-1M dataset [15] for feature extraction (see Figure 1) and employed an SVM classifier to classify videos as violent or non-violent. We explored different classification methods for violence detection and evaluated their performance. In particular, we tested decision tree and random forest classifiers using a pre-trained model to extract video features. We optimized the hyperparameters of both classifiers using grid search and trained them on the extracted features. Despite being marginally faster than the SVM classifier, the decision tree and random forest classifiers did not meet our needs in terms of speed and accuracy on our dataset. For instance, it took around 5 minutes to extract features from 300 videos of 5 seconds in 30 fps and low resolution, followed by 10 seconds for the classifier training, which is not efficient for our use case. This experimentation revealed that classical classification methods on extracted features for violence detection are not well-suited for real-time applications. ### Transfer Learning and Early Stopping To improve training efficiency, it was essential to explore various transfer learning architectures. [14] utilized a transfer learning architecture consisting of six pre-trained layers, with two fully connected layers of 4096 and 512 neurons respectively, and a final output layer (see Figure 2). We tried many different architectures, from starting the transfer learning one layer earlier, to adding multiple training layers, each layer containing from 256 to 4096 neurons. The goal being to get a better training time or ROC curve than the model used in the previous paper, therefore, the time to beat was 12min30s and the AUC was 0,987. Through trial and error, we obtained results ranging from 8 minutes of training time and an AUC of 0.941 to 17 minutes and and AUC of 0.991. We noticed that the more neurons we used on the before last layer, the faster the network converged, but at the same time, the worse the accuracy became. However, these results are not what we need since they are slower and less accurate than what a random forest classifier is able to produce (Table 1). The aim being to get the most efficient training possible due to material constraints in a federated context, we want to reduce training time as much as possible, which leads us to the next section. ### Transfer Learning and One-Cycle Training To reduce training time without sacrificing results, we aimed to accelerate the convergence of our networks. We used a technique called cyclical learning rates, introduced by [13], which involves gradually increasing the learning rate from a very low value to a high value and then decreasing it back to the starting value. This technique can help speed up convergence. The super-convergence [13] uses a single cycle of cyclical learning with optimal learning rates to train a model for a few epochs. This method is called One-Cycle training. In order to find these lower and higher bounds of learning rates, we trained the model for one single epoch with a learning rate gradually rising from \(1e^{-15}\) to 1 and plotted the loss on a graph as the Y-axis with the learning rate as the X-axis. The minimum and maximum learning rates were respectively located after a sharp drop and before a sharp rise in loss. We used this method to reduce training time while maintaining high accuracy and ROC curves with an Area Under Curve of over 0.96. We, then, experimented with various architectures by varying the number of layers, number of neurons, and starting layer for transfer learning. We found that training time evened out completely, and that lighter architectures starting from the seventh layer tended to produce better results. Therefore, we chose an architecture with 1024 neurons on the seventh layer and a final fully connected layer (see Figure 2). This approach allows for faster training times than feature extraction methods while maintaining similar accuracy. ### Multi-Channel Input Models using Optical Flow We experimented with multi-input models, including the Flow-Gated architecture proposed by [1], which has a lightweight design (272,690 parameters) and uses both RGB frames and optical flow inputs to identify areas of movement and potential violence (see Figure 3). The model consists of four blocks, including the RGB and Optical Flow Channels, a Merging Block, and a Fully Connected Layer, with all 3D CNN blocks using depth-wise separable convolutions from MobileNet [10] and Pseudo-3D Residual Networks [14] to reduce parameters without sacrificing performance. However, the time required to compute optical flow is a significant drawback, with an average computation time of 9 seconds for a 5-second, 30fps video, making it unsuitable for near real-time violence detection and minimizing learning time. ### Multi-Channel Input Models using Frame Differences To reduce computation time required for calculating optical flow, we opted to use frame differences instead, as demonstrated in [11]. This method requires significantly less computation time (0.065 seconds compared to 9 seconds for optical flow) and also reduces the number of input channels required. Unlike optical flow, which also provides direction of movement, frame differences only detect changes in the image. We retained the original Flow-Gated model architecture and modified the optical flow channel to use frame differences. We also added more dropout to the fully connected layer to prevent overfitting. This modified architecture, which we named "Diff-Gated", is lightweight (272,546 parameters) and achieves better results than the original Flow-Gated network, as shown in Table 6. These changes have reduced pre-processing and training time while improving accuracy. ## 4 Experiment In this section, we describe the experiments we conducted to develop and optimize our violence detection model. We begin by explaining our choice of dataset and the setup we used for our experiments. We then discuss how we adapted the dataset to the federated learning context and the challenges we faced. In the next section, we present our results for training previously tested models in a federated setting. ### Dataset Selection Various datasets exist for violence detection, such as the Movies dataset [1] consisting of fight scenes from movies or the Hockey Fight dataset [1] composed of fights from hockey games. However, these datasets have specific video contexts and may not represent real-life situations. To choose the most relevant dataset, we looked for CCTV footage of real-life physical violence situations with a significant number of videos and that have been used in other studies. Figure 1: Structure of the feature extraction architecture [13] Figure 2: Structure of the transfer learning architecture [13] We selected the RWF-2000 dataset [1], consisting of 2000 videos from various sources of CCTV cameras, with 1000 violent videos and 1000 non-violent videos. All videos are 5 seconds long and filmed at 30 fps. To ensure the reliability of our models in multiple situations, we also used three other datasets: the crowd violence dataset [1], the AIRTLab dataset [1], and the hockey fights dataset [1]. However, training the RWF-2000 dataset required a significant amount of RAM, even with high-memory resources like Google Colab (83.5GB RAM). To avoid memory issues, we limited ourselves to using 300 to 400 videos for training. ### Experimental Setup: Hardware and Software All our experiments were conducted using Google Colab. For the non-federated models, we used a high-RAM setup and a standard GPU (Tesla T4). For the federated model experiments, we used a high-RAM setup with a premium GPU (Nvidia V100 or A100), as the power and RAM associated with a premium GPU were necessary for federated learning. We needed to simulate multiple clients and a server on a single machine to create a federated learning environment. Given the novelty of our engagement with Google Colab and video classification, coupled with the challenging timeline, our primary focus was directed towards other pivotal aspects of the project. Consequently, the optimization of memory usage presents an area for further exploration and improvement. ### Data Preparation for Federated Learning: Adapting Traditional Datasets The datasets we have chosen for violence detection consist of videos labelled either "violent" or "non-violent". However, in a federated learning context, multiple "clients" are needed, each simulating a different data source. This presents a challenge, as traditional datasets are not designed for federated learning. To address this challenge, we propose and develop a method to simulate a federated-learning ready dataset from a traditional one. Our method involves a stratified split, which means that each video is associated with one and only one client, and each client has approximately the same number of violent and non-violent videos. This ensures that the data distribution is balanced across the different clients and reduces the risk of Non-IID data, making it easier to train a model. Our proposed method offers several advantages. Firstly, it enables us to use traditional datasets for federated learning. Secondly, it helps to prevent the failure of models due to Non-IID data distribution. Lastly, it provides a more realistic representation of the data distribution in real-world scenarios, where different data sources may have varying proportions of violent and non-violent videos. ### Federated Learning with Previously Tested Models We focused on training only one of our models in a federated context. Our choice was the model presented in 3.3 because it had the best accuracy/training time ratio while reducing the number of parameters. We experimented with two frameworks: TensorFlow Federated [1] and Flower [1]. While achieving an accuracy of over 80% with TensorFlow Federated is extremely time-consuming, we found it easier to do so with Flower. As a result, we decided to focus our efforts on Flower. Although we were satisfied with our metrics using Flower, we encountered issues because no memory was freed between training rounds. Despite this, we were able to successfully train the model presented in 3.3 using the FederatedAveraging algorithm [10]. We observed the following: * When training on a random sample of data sources each round, our metrics were slightly lower than those obtained outside of a federated context. We consider this result expected because the model was trained on fewer data per round. * When training on every data source each round, the accuracy was higher than that obtained outside of a federated context. We believe this is due to the multiple rounds of training, corresponding to multiple complete training cycles, instead of two epochs used for training using the One-Cycle method. In conclusion, we were able to successfully adapt our non-federated models to a federated learning context using the Figure 3: Structure of the flow gated architecture [1] Flower framework. We were able to train the model presented in Section 3.3 using the FederatedAveraging algorithm. Although we faced some challenges due to memory size issues in a federated context, we were still able to achieve good metrics for our federated model. Our results show that training on a random sample of data sources each round resulted in slightly lower accuracy, while training on every data source each round resulted in higher accuracy compared to training outside of a federated context. These findings suggest that federated learning has the potential to improve violence detection models while preserving privacy, and could be further explored in future work. ## 5 Results In this section, we present the results of our experiments on violence detection in videos using deep learning techniques. We first compare the accuracies of different classifiers following feature extraction on three hundred videos of the RWF-2000 database. We also report the preprocessing times of different datasets, which are influenced by video framerate, resolution, and length. Next, we provide the results of our proposed model trained on four different datasets, with different numbers of epochs and maximum learning rates. We also compare the accuracy and computation time of our Diff-Gated model with the original Flow-Gated architecture on the RWF-2000 dataset. Finally, we show the validation accuracy of our federated learning model on the RWF-2000 dataset for each round of training. ### Classifiers Comparison Table 1 presents the accuracy and training times of various classifiers using the C3D model and different feature extraction methods on 300 videos of the RWF-2000 dataset [3]. The feature extraction process takes approximately five minutes, which needs to be added to the training time to determine the overall time required for generating a classifier. ### Establishing Baseline Model Performance for Subsequent Comparisons Although using decision trees instead of a SVM can save some time in training, the amount of time needed to extract features makes it not worthwhile to pursue this avenue in our context [11]. The preprocessing times shown in table 2 are influenced by several factors, such as the frame rate, resolution, and length of the videos used in the datasets. For instance, the Hockey Fights dataset takes less time to process because each video lasts only one second, is filmed at around 30fps, and has a resolution of 360p. On the other hand, the AIRTlab dataset has longer videos, with a duration of five seconds, filmed at 30fps and a resolution of 1080p. The results presented in Table 3 can be used as a baseline for comparison with the subsequent models. It is important to note that the model used is the one presented in section 3.2, with 512 neurons on its penultimate dense layer. ### Model Performance across Datasets and Configurations The tables 4 and 5 display the results of training our model on four different databases, with the penultimate layer utilizing 1024 neurons. The table 6 shows us the accuracy of the multi-channel models we have experimented with during this research on the complete RWF-2000 dataset [3]. Our proposed model, referred to as **Diff-Gated**, achieves higher accuracy while reducing computation in comparison to the original Flow-Gated architecture [3]. Table 7 presents the validation accuracy of our federated model for each round of training on 400 videos from the RWF-2000 dataset. Round 0 accuracy corresponds to the val \begin{table} \begin{tabular}{l r r} \hline Classifier & Accuracy & Training time \\ \hline C3D + SVM(fc7) & 99.8\% & 23s \\ C3D + Decision Trees(fc7) & 83.9\% & 10s \\ C3D + Random Forest (fc7) & 99.5\% & 10s \\ C3D + Decision Trees(fc6) & 85.9\% & 10s \\ C3D + Random Forest(fc6) & 99.5\% & 10s \\ \hline \end{tabular} \end{table} Table 1: Accuracy and training times of the extraction feature methods on 300 videos of the RWF-2000 dataset. \begin{table} \begin{tabular}{l r r} \hline \hline C3DFC w/ Early Stopping & Accuracy & ROC AUC \\ \hline AIRTLab & 95.6\% & 0.9894 \\ Crowd Violence & 99.0\% & 0.9994 \\ Hockey Fights & 96.6\% & 0.9931 \\ RWF-2000 (400 videos) & 94.7\% & 0.9922 \\ \hline \hline \end{tabular} \end{table} Table 3: Results of the model proposed by [11] on different datasets. \begin{table} \begin{tabular}{l r r} \hline \hline Dataset & \# videos & \(\approx\) preprocessing time \\ \hline AIRTLab & 350 & 3m30s \\ Crowd Violence & 246 & 36s \\ Hockey Fights & 1000 & 1m08s \\ RWF-2000 (400 videos) & 400 & 2m36s \\ \hline \hline \end{tabular} \end{table} Table 2: Number of videos per dataset and their approximate preprocessing time. \begin{table} \begin{tabular}{l r r} \hline \hline C3DFC w/ Early Stopping & Accuracy & ROC AUC \\ \hline AIRTLab & 95.6\% & 0.9894 \\ Crowd Violence & 99.0\% & 0.9994 \\ Hockey Fights & 96.6\% & 0.9931 \\ RWF-2000 (400 videos) & 94.7\% & 0.9922 \\ \hline \hline \end{tabular} \end{table} Table 3: Results of the model proposed by [11] on different datasets. idation accuracy of the model before the first round of training. ## 6 Conclusion In this paper, we present an innovative examination of machine learning models for violence detection in videos, with a particular emphasis on Federated Learning and our proposed Diff-Gated architecture. We not only maintain or improve upon the accuracy of conventional methods but also reduce training times, enhancing model usability in practical applications. Our work incorporated super-convergence for transfer learning and explored diverse classifiers for extracting spatio-temporal features from videos. Through modifications to the Flow-gated architecture proposed by [1], we were able to boost accuracy and cut down training and preprocessing time. Moreover, we introduced a method for adapting centralized datasets to a federated learning context, using it to train our violence detection model. Despite demonstrating that deep learning models can be effectively trained using federated learning, we note the resource-intensive nature of federated learning, particularly with video data. While our research has made significant strides, the challenges inherent in federated learning, such as dealing with Non-IID and unevenly distributed data, cannot be overlooked [11]. Our future efforts will aim at exploring different federated learning strategies and studying the impact of unbalanced client data. Despite these challenges, our work provides valuable insights for researchers and practitioners alike, underlining the potential of Federated Learning and other novel techniques in violence detection and other real-world applications.
2307.16099
On Neural Network approximation of ideal adversarial attack and convergence of adversarial training
Adversarial attacks are usually expressed in terms of a gradient-based operation on the input data and model, this results in heavy computations every time an attack is generated. In this work, we solidify the idea of representing adversarial attacks as a trainable function, without further gradient computation. We first motivate that the theoretical best attacks, under proper conditions, can be represented as smooth piece-wise functions (piece-wise H\"older functions). Then we obtain an approximation result of such functions by a neural network. Subsequently, we emulate the ideal attack process by a neural network and reduce the adversarial training to a mathematical game between an attack network and a training model (a defense network). We also obtain convergence rates of adversarial loss in terms of the sample size $n$ for adversarial training in such a setting.
Rajdeep Haldar, Qifan Song
2023-07-30T01:04:36Z
http://arxiv.org/abs/2307.16099v1
# On Neural Network approximation of ideal adversarial attack and convergence of adversarial training ###### Abstract Adversarial attacks are usually expressed in terms of a gradient-based operation on the input data and model, this results in heavy computations every time an attack is generated. In this work, we solidify the idea of representing adversarial attacks as a trainable function, without further gradient computation. We first motivate that the theoretical best attacks, under proper conditions, can be represented as smooth piece-wise functions (piece-wise Holder functions). Then we obtain an approximation result of such functions by a neural network. Subsequently, we emulate the ideal attack process by a neural network and reduce the adversarial training to a mathematical game between an attack network and a training model (a defense network). We also obtain convergence rates of adversarial loss in terms of the sample size \(n\) for adversarial training in such a setting. ## 1 Introduction Neural networks are universal approximators [22, 8, 28, 34] and have enjoyed immense popularity in the realm of machine learning problems and artificial intelligence applications over the past two decades. Their ability to approximate arbitrary functions with high accuracy has facilitated state-of-the-art performance in nonparametric regression and classification problems. Although, neural networks showcase high accuracy and fairly well generalization on the training data and testing data; their testing performance is vulnerable to minor perturbations to the original data [37]. [16] introduced a gradient-based method to generate bounded perturbations of input data (adversarial examples/attack) which significantly hampers the predictive performance of a given neural network. The adversarial robustness of neural networks has been a topic of importance since then. One popular way to make neural networks robust to such attacks is via training over generated adversarial examples (adversarial training). The robustness of the network will directly correspond to the quality or strength of the attack. Over the years a slew of work has been done in generating strong adversarial attacks [2], thereby increasing the robustness of the network models when adversarially trained. Traditionally, the attack generation process has been some sort of gradient-based operation such as the Fast-gradient [16, 9], Iterative gradient [27], Projected gradient descent (PGD) [29], Carlini Wagner Attack [7] etc, requiring direct access to the analytic form of the model. Attacks that are generated having direct access to the underlying model are known as _white-box attacks_. Alternatively, one can view these attacks as a function of the input data which results in a perturbation in the original space. If we think of attacks as a function, one can approximate it using a neural network. So, the underlying classification/regression model is a neural network that must learn how to defend itself (robustness) against the attacks generated by an adversary neural network; adversarial training in this context then becomes a game (in a game-theoretic sense) between two neural networks. This perspective of using neural networks to generate attacks is fairly recent and has been explored in [4, 40, 39, 23]. A benefit of using neural networks to generate attacks is that we learn an attack function after training. Once we obtain this attack function spanning over the input space, we can just use it to generate new adversarial examples without having access to the underlying predictive model. Using neural networks to generate attacks we can exhibit so-called _semi-white box_ or _black-box attacks_, which have limited access or no access to the underlying model respectively. Another consideration is the computation costs to generate these attacks; The empirical successful white box attacks like PGD or similar iterated gradient methods usually require recurrent gradient computations for each new sample of data. Even though a lot of progress has been made on the algorithmic front from both attack [23, 14, 39, 9] and defense [13, 12, 35, 36] perspectives; there is a lack of theoretical results to justify such methods. In this paper, we would like to unify these ideas in a common mathematical framework and motivate adversarial training in the context of an adversarial game (attack-defense) between two neural networks. In this work, we will prove results for RELU-based neural networks defined as: **Definition 1.1** (Deep Neural Networks).: Define the class of deep Relu networks \(f\in\mathcal{F}_{\sigma}(L,W,w,\kappa,B)\) as parametrized functions of the form: \[f(x)=A^{(L)}\cdot\sigma\left(A^{(L-1)}\cdots\sigma\left(A^{(1)}x+b^{(1)} \right)\cdots+b^{(L-1)}\right)+b^{(L)},\] where the \(A^{(l)}\)'s are the weight matrices and \(b^{(l)}\)'s are the bias vectors with real-valued elements, and the activation function \(\sigma:\mathbb{R}\mapsto\mathbb{R}\) is applied element-wise. \(\sigma(x)=\mathrm{ReLU}(x)=\max\{0,x\}\) (rectified linear unit). The network is \(L\)-layer deep and its width is bounded by \(\sup_{l}\dim(b^{(l)})\leq w\). Further, we assume that \[\max_{i,j,l}\left|A^{(l)}_{ij}\right|\leq\kappa,\max_{i,l}|b^{(l)}_{i}|\leq \kappa,\sum_{l=1}^{L}\left\|A^{(l)}\right\|_{0}+\left\|b^{(l)}\right\|_{0}\leq W,\text{ for }i=1,\ldots,L,\] i.e. all elements in the \(A^{(l)}\)'s and \(b^{(l)}\)'s are bounded in absolute value by \(\kappa\), and there are at most \(W\) non-zero parameters in total. Finally, we assume \(\|f\|_{\infty}\leq B<\infty\) for all \(f\). If the particular value \(B\) is an arbitrarily large constant, we may suppress the notation and write \(\mathcal{F}_{\sigma}(L,W,w,\kappa,B)=\mathcal{F}_{\sigma}(L,W,w,\kappa)\). ### Contribution We first formalize the notion of an ideal or best possible attack characterized by the underlying loss for the classification/regression problem. Then we justify how gradient-based PGD and FGSM attacks are related to the ideal attack. Furthermore, we show indeed the ideal attack can be approximated by neural networks up to arbitrary accuracy; justifying the use of neural networks to generate attacks. Subsequently, we derive convergence bounds for adversarial training in the context of an adversarial game between two neural networks as the sample-size \(n\) increases. Finally, we showcase some numerical experiments to verify the capabilities of neural networks to learn the ideal attack function. Also, the robustness and attack strength of adversarial trained networks in the context of an adversarial game has been compared to the PGD robustly trained networks and PGD attacks respectively. ### Problem definition / Notation Let \((x,y)=\mathcal{Z}\in\mathcal{X}\times\mathcal{Y}=\tilde{\mathcal{Y}}\) represent an observation pair where \(x\in\mathcal{X}\) is the predictor and \(y\in\mathcal{Y}\) is the response, where \(\mathcal{Y}=\mathbb{R}^{k}\) or \(\mathcal{Y}=\{1,\ldots,k\}\) for regression and classification problems respectively. Without loss of generality, we assign \(\mathcal{X}=[0,1]^{D}\) after normalization. Let \(f:\mathcal{X}\rightarrow\mathbb{R}^{k}\in\mathcal{C}\) be our model, where \(\mathcal{C}\) is some function class. \(\mathcal{L}:\mathbb{R}^{k}\times\mathcal{Y}\rightarrow\mathbb{R}\,\) denotes a loss function which we wish to minimize, this could be the negative log-likelihood or any reasonable discrepancy measure between \(f(x)\) and \(y\). An ideal model minimizes the expected loss, i.e., \(f^{*}=\arg\inf\limits_{f\in\mathcal{C}}\mathbb{E}\mathcal{L}(f(x),y)\), where \(\mathbb{E}=\mathbb{E}_{(x,y)\sim\mathcal{P}}\) denotes the expectation over the true distribution \(\mathcal{P}\) of the data. **Definition 1.2** (\((p,\delta)\) Perturbation function class).: \(\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})\) is a \((p,\delta)\) perturbation function class restricted on function class \(\tilde{\mathcal{C}}\) \[\mathcal{F}^{p}_{\delta}=\{g:\tilde{\mathcal{Y}}\rightarrow\mathcal{X}\in \tilde{\mathcal{C}}:\forall(x,y)\in\tilde{\mathcal{Y}},\,\left\|g(x,y)\right\| _{p}\leq\delta\}, \tag{1}\] where \(\tilde{\mathcal{C}}\) is some base function class, for instance, the class of continuous functions, spline functions, Holder functions, etc; **Definition 1.3** (\(\ell_{p}(\delta)\) function attack).: \(\lambda^{f}\) is the best \(\ell_{p}(\delta)\) function attack (within the family \(\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})\)) on \(f\) iff \[\lambda^{f}(x,y)=\arg\max_{\lambda\in\mathcal{F}^{p}_{\delta}(\mathcal{C})} \mathbb{E}\mathcal{L}(f(x+\lambda(x,y)),y). \tag{2}\] Our definition for \(\ell_{p}(\delta)\) function attack serves as a surrogate of the _point wise_\(\ell_{p}\) attacks of strength \(\delta\) in the literature, defined as \[\lambda^{p.w}(x,y)=\arg\max_{\|\lambda\|_{p}\leq\delta}\mathcal{L}(f(x+ \lambda),y). \tag{3}\] Note that if \(\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})\) has a nice parameterized form, then the evaluation of \(\lambda^{f}\), e.g., designing an attack for new observations, would be more computationally efficient than \(\lambda^{p.w}(x,y)\), which generally needs to be evaluated point-wisely. Our framework is similar to the one defined in [4]. #### Adversarial Training The adversarial training aims to make the model robust against adversarial attacks via minimizing the objective loss under the best possible attack function on the model, i.e., **Definition 1.4** (Robust \((p,\delta)\) model).: \(f^{*}\) is a robust \((p,\delta)\) model if it minimises the following objective: \[f^{*}=\arg\min_{f\in\mathcal{C}}\max_{\lambda\in\mathcal{F}^{p}_{\delta}( \tilde{\mathcal{C}})}\mathbb{E}\mathcal{L}(f(x+\lambda(x,y)),y) \tag{4}\] where \(\mathbb{E}\,\mathcal{L}(f(x+\lambda(x,y)),y)\) is the adversarial loss. When shifting from the point-wise paradigm to a functional form of an attack, the natural question is which perturbation function class \(\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})\) (or more specifically the choice of \(\tilde{\mathcal{C}}\)) is appropriate to induce adversarial perturbations, that can approximate the strongest point-wise attack \(\lambda^{p.w}\), of any given input \((x,y)\) and model \(f\in\mathcal{C}\)? The theoretical goal of this work is to determine a function class that includes the optimal pointwise attack (i.e., \(\lambda^{p.w}\in\tilde{\mathcal{C}}\)), then we can try to approximate this function class up to arbitrary accuracy using a parametric family, i.e., neural networks. Subsequently, we can then view our adversarial training framework (4) as a mathematical game between two networks, and establish the statistical properties for this game. ## 2 Best adversarial attack In this section, we will first develop some heuristics and then rigorously show that for smooth \(f\)'s, the point-wise attacks (3) can be represented by functions of a certain form. We will first develop some intuition by analyzing the simple case of \(\ell_{\infty}(\delta)\) attacks on linear and logistic regression models. For the sake of brevity, from now onwards we will denote: \[\mathcal{L}(f(x+\lambda(x,y)),y)\coloneqq\mathcal{L}(f,\lambda,\mathcal{Z}) \text{ and }\mathcal{L}(f(x),y)\coloneqq\mathcal{L}(f,\mathcal{Z}) \tag{5}\] ### Attacks on linear models and FGSM #### Linear regression Let \(y|x\sim N(\beta\cdot x,\sigma^{2})\) be the true relationship, and \(f(x)=\hat{\beta}\cdot x\) be the estimated model. The loss, in this case, is the negative log-likelihood up to a constant: \(\mathcal{L}(f(x),y)=(y-\hat{\beta}\cdot x)^{2}\). For a given \(\hat{\beta}\), the ideal function attack \(\lambda^{f}\) should satisfy the objective: \(\lambda^{f}=\arg\max_{\lambda\in\mathcal{F}^{p}_{\delta}(\mathcal{C})} \mathbb{E}\mathcal{L}(f(x+\lambda),y)\). With some straightforward one can see that the _point wise_ attack (3) is as follows: \[\lambda^{p.w}(x,y)=\delta\cdot\text{sign}[(\hat{\beta}\cdot x-y)/\hat{\beta}].\] Note that one easily derives that this attack is equivalent to \(\lambda^{p.w}(x,y)=\delta\cdot\text{sign}(\nabla_{x}\mathcal{L}(f,\mathcal{Z}))\) as \(\text{sign}(\frac{1}{\hat{\beta}})=\text{sign}(\hat{\beta})\). For the multivariate case \(Y|X\sim N(\beta^{T}X,\Sigma)\) where \(\beta\) is a vector now, one can get analogous results. The essential point is that for the linear regression case, the best point-wise adversarial attacks are essentially _piece-wise constant functions_ which are related to the gradient of the underlying loss \(\mathcal{L}\) w.r.t. \(x\). On the other hand, if our perturbation function class \(\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})\) is flexible enough and can well approximate any piece-wise constant functions, then trivially, \(\lambda^{f}(x,y)\approx\lambda^{p.w}(x,y)\). #### Logistic regression For binary classification, \(\mathcal{Z}=(y,x)\in\{0,1\}\times[0,1]\) follows the conditional distribution: \(\mathbb{P}(y=1|x)=p(\beta,x)=\frac{1}{1+e^{-\beta x}}\), i.e., \(y|x\sim\mathrm{Bernoulli}(p(\beta,x))\). Let the model \(f\) be the logistic regression fit with parameter estimator \(\hat{\beta}\). The loss is the negative log-likelihood up to a constant: \(\mathcal{L}(f(x),y)=-y\ln\!\left(p(\hat{\beta},x)\right)-(1-y)\ln\!\left(1-p( \hat{\beta},x)\right)\). As in linear regression case, one can calculate \(\lambda^{p.w}\); by simple algebra, one can see the critical condition is \(\hat{\beta}(p(\hat{\beta},x+\lambda)-y)=0\) and \(p(\hat{\beta},x+\lambda)\) is monotonic in \(\lambda\), which results in \[\lambda^{p.w}(x,y)=\delta\cdot\text{sign}(0.5-y)\text{sign}(\hat{\beta}). \tag{6}\] We can replicate the exact same arguments for the multivariate case, and get the analogous result (with \(\hat{\beta},x\) now being vectors). As in linear regression case, one can express \(\lambda^{p.w}\) (under the \(\ell_{\infty}(\delta)\) function attack) in terms of the gradient of \(\mathcal{L}(f,\mathcal{Z})\), and we get the exact same form: \[\lambda^{p.w}(x,y)=\delta\cdot\text{sign}(\nabla_{x}\mathcal{L}(f,\mathcal{Z})). \tag{7}\] Consequently, if the function class \(\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})\) can well approximate any piece-wise constant functions, then \(\lambda^{f}(x,y)\approx\lambda^{p.w}(x,y)\). _Remark_ (FGSM as \(\ell_{\infty}(\delta)\) function attack).: The attack of form \(\delta\cdot\text{sign}(\nabla_{x}\mathcal{L}(f,\mathcal{Z}))\) is known as the fast-gradient signed max (FGSM) attack in the literature. [16] argues that FGSM is the exact attack for logistic regression. We can reaffirm this even from a function attack perspective, if the function class \(\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})\) is sufficiently broad. In general, we can extend this idea and think of FGSM as a piece-wise constant function which is the best \(\ell_{\infty}(\delta)\) function attack for linear models. The idea of a piece-wise smooth function for arbitrary loss is a much more general concept and we will see how FGSM fits as a special case in our framework. ### Gradient flow-based attack #### Basic concepts In this section, we will construct a functional form for the best point-wise \(\ell_{p}(\delta)\) attack using the concept of gradient flows and continuous dynamic systems (CDS). For the sake of completeness, preliminary knowledge of CDS can be found in the appendix. Readers of interest in the detailed background and theories of CDS may refer to Katok's book on the Modern Theory of dynamical systems or Brin's book which provides a more condensed version of the theory [6, 25]. Definition A.1 formally defines a CDS \(T\), as a function of time in an arbitrary metric space \(\mathcal{X}\). \(T\) can be thought of as a law that dictates the movement of a particle in \(\mathcal{X}\) as a function of its initial position, i.e., \(T(t)x_{0}\) is the location of a particle at time \(t\) initializing from \(x_{0}\). Given a CDS \(T\), an object of interest is the set of points in space \(\mathcal{X}\) where the particle is headed given any initial position. These special points can be said to _attract_ the particle towards them (i.e. Definition A.2). We would also want the trajectory of the particle given a particular initial point to be tractable, and the set of initial points \(\mathcal{A}(T)\) for which the trajectory is well defined is called the _attractor_ (Definition A.5). A point \(x_{0}\in\mathcal{X}\) is a stationary point for a dynamical system \(T\) if \(T(t)x_{0}=x_{0}\) for all \(t\in\mathbb{R}^{+}\) (i.e., a stationary point is a singleton invariant set A.4). Corresponding to a given CDS \(T\), one can define \(T^{-1}\) which represents the inverse dynamics, i.e. for any \(s\geq t\) and \(s,t\in\mathbb{R}^{-}\) we have \(T(s-t)T^{-1}(t)=T^{-1}(s)\). If \(T^{-1}\) is unique for a \(T\), we say \(T\) is one-one. \(T^{-1}\) controls the flow of particles going back in time, one can think of it as an inverse mapping. If \(T\) is one-one, we can have an abuse of notation and extend \(T\) to the negative time domain as \(T(s)\coloneqq T^{-1}(s)\) if \(s<0\). We can also define the concept of stable (\(W_{s}(x_{0})\)) and unstable set (\(W_{u}(x_{0})\)) of a stationary point \(x_{0}\) (Definition A.6) of an one-to-one CDS. The stable set is essentially the set of points that eventually reach \(x_{0}\) under the dynamic system \(T\); Similarly, the unstable set is the set of points that eventually reach \(x_{0}\) under the inverse dynamics \(T^{-1}\). #### 2.2.1 Gradient Flow We will consider a CDS \(T^{gf}\), which follows a gradient dynamic, i.e., \(T^{gf}\) is the solution to the ordinary differential equation \(\dot{x}=\nabla_{x}F(x)\) where \(F(x)=\mathcal{L}(f(x),y)\). Note that for the simplicity of the technical analysis, we assume that \(F(x)\) is continuously differentiable and all of its local optimums locate in the interior of \(\mathcal{X}\). Assume that \(\mathcal{X}\) is a compact space, if the gradient is bounded everywhere in \(\mathcal{X}\), then \(\mathcal{A}(T^{gf})=\mathcal{X}\). Also, the stationary points of \(T^{gf}\) (\(\{x:T^{gf}(t)x=x;\;\forall t\in\mathbb{R}^{+}\}\)) are essentially the equilibria/critical points (\(E=\{x:\nabla F(x)=0\}\)) of \(F\). A classic result in the literature is that for \(T^{gf}\) the set of equilibria _attracts_\(\mathcal{A}(T^{gf})\) (Section 6, Theorem 6.12 [20]). This essentially means that if the particle follows the gradient dynamic system, it is guaranteed to reach a critical point. The gradient flow satisfies a lot of nice properties including point-dissipative (Definition A.3) set of equilibria, being one-one CDS, \((T^{gf})^{-1}\) being just the negative gradient flow, i.e., solution of the ODE \(\dot{x}=-\nabla F(x)\), etc. Also, for a maximization framework, the path followed by gradient flow is a natural choice to study as it is locally maximal; following the gradient flow path, the function value is non-decreasing as \(\dot{F}(x)=\|\nabla F(x)\|_{2}^{2}\geq 0\). #### 2.2.2 Decomposition of \(\mathcal{X}\) into manifolds For \(T^{gf}\), the critical points (w.r.t. gradient) are essentially the stationary points (w.r.t. dynamic system)and the stable set \(W_{s}(x_{0})\) for any \(x_{0}\in E\) are essentially the set of initial positions which lead to the local maxima/saddle \(x_{0}\) when following the gradient path. Intuitively any point in our metric space \(\mathcal{X}=\mathcal{A}(T^{gf})\) should lead to one of these critical points under \(T^{gf}\). Remark 6.11 of [20] formalizes this notion and we get \(\mathcal{X}=\bigsqcup_{x_{0}\in E}W_{s}(x_{0})\). Essentially we are able to partition the metric space based on the local maxima/saddle points of the gradient flow dynamic system. This decomposition will be useful when we argue the piece-wise nature of our function attack. Additionally, if \(T^{gf}(t)x\) is \(C^{k}\) w.r.t. \(t\) for any \(x\in W_{s}(x_{0})\) then \(W_{s}(x_{0})\) is a \(C^{k}\) manifold, and \(\mathcal{X}\) is just union of manifolds (see; Section 4 of [20]). #### 2.2.3 Projected gradient flow Let's denote \(x_{adv}=\lambda^{p.w}(x_{s},y)+x_{s}\). By the definition of a point-wise \(\ell_{p}\) attack of strength \(\delta\) (3), \(x_{adv}\) must satisfy the following constraint optimisation problem \(\forall x_{s}\in\mathcal{X}\): \[\arg\max_{x\in\mathcal{X}}F(x),\] \[\text{subject to }g_{i}(x)\leq 0,\quad\forall i\in\{1,\dots,Q\} \tag{8}\] for some \(g_{i}\)'s, where \(g_{i}(x)\) represents the inequality constraints and \(Q\) is the number of constraints. The \(i^{th}\) constraint is said to be active if and only if \(g_{i}(x)=0\). To be more specific, for \(1\leq p<\infty\), we have \(Q=1\) and \(g_{1}(x)=\|x-x_{s}\|_{p}^{p}-\delta^{p}\); for \(p=\infty\), we have \(Q=D\) and \(g_{i}(x)=|(x-x_{s})_{i}|-\delta\) for all \(i\in\{1,\dots,D\}\). The constraints are active in this case when \(x\in\partial B_{\ell_{p}(x,\delta)}\) (boundary of the \(\ell_{p}\) ball of radius \(\delta\) around \(x_{s}\)). Let \(\mathbf{J}(x)=(\dots,\mathbb{1}_{\{g_{i}(x)=0\}},\dots)^{T}\) be a \(Q\times 1\) vector whose \(i^{th}\) component represents whether the \(i^{th}\) inequality constraint is active or not (1 or 0). \(\mathbf{J}(x)\) induces an indexing set \(I(x)\subset\{1,\dots,Q\}\) for the active constraints. Define \(\mathbf{C}(x)=[(g_{i}(x))_{i\in I(x)}]\) to be the active constraint matrix and \(D\mathbf{C}(x)=[(\nabla g_{i}(x))_{i\in I(x)}]\) be its corresponding derivative/sub-derivative matrix. A projection operator which takes any vector to the surface defined by the active constraints (i.e., \(\{x:g_{i}(x)=0,\;\forall i\in I(x)\}\)) can be canonically defined as \[\mathbf{P}(x)=\mathbf{I}-D\mathbf{C}(x)^{T}(D\mathbf{C}(x)D\mathbf{C}(x)^{T})^{-1}D\mathbf{C}(x).\] Note when all constraints are inactive, \(\mathbf{C}(x)\) is a null vector and the projection reduces to the identity \(\mathbf{P}(x)=\mathbf{I}\). Consider a CDS \(T^{pgf}_{x_{s}}\) on \(\mathcal{X}=B_{p}(x_{s},\delta)\) parameterized by \(x_{s}\) as a solution to the ODE: \[\dot{x}=\mathbf{P}(x)\nabla_{x}F(x). \tag{9}\] This can be viewed as a special case of the constraint optimization problems discussed by [11]. Note that for \(1\leq p<\infty\) as we have a single norm constraint \(g_{1}(x)=\|x-x_{s}\|_{p}^{p}-\delta^{p}\), \(\mathbf{J}(x)=\mathbb{1}_{g_{1}(x)=0}\) and \[\mathbf{P}(x)=\mathbf{I}-\mathbf{J}(x)(\|\nabla g_{1}(x)\|_{2}^{2})^{-1}\nabla g_{1}(x) \nabla g_{1}(x)^{T}. \tag{10}\] When the particle is at the boundary of the \(\ell_{p}\) ball \(B_{p}(x_{s},\delta)\), i.e., \(\mathbf{J}(x)=1\), the projection matrix is just orthogonal to the normal vector to the surface of the \(\ell_{p}\) ball. thus, when the particle is at the boundary it doesn't go beyond and explores the boundary surface based on the gradient direction over the surface. The dynamic stops once the gradient becomes parallel to the normal vector of the surface, in other words, there is no direction left to explore which increases the function \(F\) further (on the surface). When the particle is inside the \(\ell_{p}\) ball it just follows the standard gradient direction. For \(p=\infty\), the \(\ell_{p}\) ball is just a hyper-cube and \(\mathbf{J}(x)\neq\mathbf{0}\) indicates which sides/diagonal of the cube the particle resides in. The ODE in this case is just: \[\dot{x}=\nabla_{x}F(x)\odot(\mathbf{1}-\mathbf{J}(x)), \tag{11}\] where \(\odot\) is the element-wise product. The ODE for \(p=\infty\) just says that once we reach the boundary of the cube, we move only along the sides by ignoring gradient components where the particle has attained side length \(\delta\). The path traversed by \(T_{x}^{pgf}\) is also non-decreasing as \(\dot{F}(x)=\nabla F^{T}(x)\mathbf{P}\nabla F(x)\geq 0\), as \(\mathbf{P}\) is positive semi-definite being a projection. #### 2.2.4 Deflecting saddle points One issue with \(T_{x_{s}}^{pgf}\) is that it can't distinguish between saddle points (where \(\nabla_{x}^{2}F(x)\) hessian is indefinite) and local maxima; the continuous dynamic stops as long as (i) \(\nabla F(x)=0\) or (ii) \(x\) on the surface of the \(\ell_{p}\) ball and \(\nabla F(x)\) is parallel to the normal vector of the \(\ell_{p}\) ball. We can modify (9) to traverse a dynamics which doesn't get stuck at the saddle points. Let \(S=\{\eta:\nabla_{x}^{2}F(x)|_{x=\eta}\text{ is indefinite}\}\subseteq E=\{x:\nabla F (x)=0\}\) be the set of saddle points. We can add a deterministic perturbation towards the unit eigenvector \(\nu_{max}^{\eta}\) corresponding to the maximum eigenvalue of \(\nabla_{x}^{2}F(x)|_{x=\eta}\) to exclude the saddle points from being a stationary point. Therefore, we define a CDS \(\bar{T}_{x_{s}}^{pgf}\) on \(B(x_{s},\delta)\) parameterized by \(x_{s}\) as a solution to the ODE: \[\dot{x}=\mathbf{P}(x)[\nabla F(x)+\sum_{\eta\in S}\psi_{\epsilon}^{\eta}(x)\nu_{ max}^{\eta}], \tag{12}\] where \(\epsilon>0\) and \(\psi_{\epsilon}^{\eta}(x)=\exp\Bigl{\{}-\frac{1}{\epsilon^{2}-\|x-\eta\|_{s} ^{2}}\Bigr{\}}\) if \(x\in B_{2}(\eta,\epsilon)\) and \(\psi_{\epsilon}^{\eta}(x)=0\) elsewhere. Essentially we are adding a smooth perturbation to the originally defined projected gradient flow dynamics as it gets closer (within \(\epsilon\) radius) to any saddle point (deflection). _Remark_.: Our goal is that \(\bar{T}_{x_{s}}^{pgf}\) can retain all the local smoothness, local optimum, and non-decreasing properties of \(T_{x_{s}}^{pgf}\) with a proper choice of \(\epsilon\). Under certain regularity of \(F\) (see; Theorem 2.1), there should exist some sufficiently small \(\epsilon\), such that \(\psi_{\epsilon}^{\eta}(x)\) is a small-bump function, which is smooth and non-negative everywhere. Near any saddle point \(\eta\in S\), we have \(\langle\nu_{max}^{\eta},\nabla F(x)\rangle\geq 0\), which preserves the non-decreasing trajectory of the original ODE. At a local maximum, all the eigenvalues of \(\nabla_{x}^{2}F(x)\) are \(<0\), resulting in the ODE around local maxima having no deflection term. Equilibrium is attained as long as \(\nabla F(x)=0\), preserving the local maximas from the original ODE. We can now define an attack function as: \[\lambda^{pgf}(x,y)=\lim_{t\to\infty}\bar{T}_{x}^{pgf}(t)x-x. \tag{13}\] Our next theorem demonstrates that (13) is the _best point-wise attack_. More importantly, by the nature of CDS, \(\lambda^{pgf}(x,y)\) has certain regularity (e.g., local smoothness) properties, i.e., it belongs to some _perturbation function class_\(\mathcal{F}_{\delta}^{p}\) consisting of regulated functions, therefore, \(\lambda^{pgf}(x,y)\) is also the _best function attack_ over this particular \(\mathcal{F}_{\delta}^{p}\). Details of this \(\mathcal{F}_{\delta}^{p}\) will be addressed in section 2.4. **Theorem 2.1**.: _Given \(F(x)=\mathcal{L}(f(x),y)\) be locally \(C^{2}\) almost surely, and the set of critical points \(E=\{x:\nabla F(x)=0\}\) be finite, non-degenerate with any \(a,b\in E\) satisfying \(dist(a,b)\geq\delta\); choosing any \(0<\epsilon<\delta\) in (12), then \(\lambda^{pgf}(x,y)\) in (13) is the best point-wise attack of strength \(\delta\)._ The proof relies on showing that \(x_{adv}=\lambda^{pgf}(x,y)+x\) satisfies the KKT (Karush-Kuhn-Tucker) conditions and the SOSC (second order sufficient condition) for the constraint optimization (8). ### Discretization of the best attack Equation (13) is a construction of an ideal/best \(\ell_{p}(\delta)\) point-wise attack function for a given loss \(F(x)=\mathcal{L}(f(x),y)\). The underlying CDS \(\bar{T}_{x}^{pgf}\) used in construction for this attack utilizes the information related to the saddle points of \(F(x)\) (12). In practice, we usually have no access to the saddle points or the eigenvalues associated with them; that itself is a challenging optimization problem especially when \(f(x)\) is characterized by deep neural networks. Note that the terms \(\mathbf{P}(x)\sum_{\eta\in S}[\psi_{\epsilon}^{\eta}(x)\nu_{max}^{\eta}]\) were added to the original projected gradient flow dynamics \(T_{x}^{pgf}\) (9) to account for deflection around saddle points, so that the dynamic doesn't get stuck in one of such points. For our purpose, we were interested in showing the existence of an ideal attack using such artificial construction. The key point was that such a dynamic can locally solve the unconstrained optimization problem (8). In real life, one can achieve an equivalent effect with very _high probability_ by introducing stochastic noise to the original projected gradient flow dynamics (9). This leads to an ODE of the underlying dynamics being a stochastic differential equation: \(dx(t)=\mathbf{P}(x(t))[\nabla F(x(t))+2dB(t)]\) (where \(B(t)\) is a Brownian motion). It is well known that introducing stochasticity in the original dynamics, helps us solve the issue of getting stuck in saddle points _almost surely_. This fact has been illustrated in [10, 32, 42, 24]. So the core component dictating the dynamic system is the term \(\dot{x}=\mathbf{P}(x)\nabla F(x)\) accompanied by a deflection term or noise term to avoid saddle points. If we consider the discrete time step version of the ODE based on the core component we get: \[x^{t+1}=\Pi(x^{t}+\gamma\nabla F(x^{t})), \tag{14}\] where \(\gamma\) is the step-size and the operator \(\Pi\) is (discrete) analogous to \(\mathbf{P}(x)\) which is a (continuous) projection to the \(\ell_{p}\) ball of radius \(\delta\) around \(x^{0}\) (initial point). This is a projected gradient-ascent algorithm derived from the underlying ODE (9). Note that to eliminate the possibility that the process (14) is stuck at a saddle point, one can always inject noise into it by replacing \(\nabla F\) with its stochastic version (e.g., stochastic gradient descent). In general, the discretization can be characterized by any projected- steepest ascent algorithm the form: \[x^{t+1}=\Pi(x^{t}+\gamma\vec{d}), \tag{15}\] where \(\vec{d}\) is the steepest ascent direction. The steepest ascent direction \(\vec{d}\) can be attributed as a unit vector with respect to \(\left|\left|\right|\right|_{p}\) norm which is maximal along the gradient direction. [3] explores and gives justification for these various steepest ascent directions. Steepest ascent w.r.t. \(\left|\cdot\right|\right|_{2}\) norm gives \(\vec{d}\propto\nabla F\) which reduces to (14). Steepest ascent w.r.t. \(\left|\cdot\right|_{1}\) gives us \(\vec{d}\propto\nabla F_{i_{max}}\cdot\mathbf{e}^{i_{max}}\) which is essentially a coordinate ascent update step (\(i_{max}=\arg\max_{i}(\nabla F)_{i}\), \(\mathbf{e}^{i}\) is the \(i^{th}\) standard basis vector in \(\mathbb{R}^{D}\)). Steepest ascent w.r.t. \(\left|\left|\right|\right|_{\infty}\) implies \(\vec{d}\propto\text{sign}(\nabla F)\) which is a signed gradient update step. In \(\mathbb{R}^{D}\), all the norms are equivalent and all of these steepest ascent algorithms will generally enjoy the same convergence rate [3]. _Remark_ (PGD and FGSM attack as discretization of the best attack). If we consider the steepest ascent direction w.r.t. \(\left|\cdot\right|\right|_{\infty}\), \(\vec{d}\propto\text{sign}(\nabla F)\), then the discrete time step updates for our ODE (9) becomes: \[x^{t+1}=\Pi(x^{t}+\gamma\,\text{sign}\nabla F(x^{t})). \tag{16}\] This is essentially the projected gradient descent attack proposed in the eminent paper [29]. As \(\gamma\to 0\) the discrete dynamics converge to the continuous dynamics. In real life, as the PGD updates are done on batches of data, the discrete dynamics inherently include a noise term due to random batch selection of data, which helps us deflect the saddle points. Also, when the step size \(\gamma=\delta\), then there is essentially only one update step \(t=0\) and we get \(x=x^{0}+\delta\,\text{sign}\nabla F(x^{0})\). This is equivalent to the FGSM attack proposed in [16]. We can now understand why the FGSM turns out to be the best \(\ell_{p}(\delta)\) function attack for linear models 2.1; for linear models, the FGSM is exact and equivalent to (2) as the gradient direction is constant. ### Motivation for piece-wise Holder spaces Theorem 2.1 guarantees the existence of a \(\ell_{p}(\delta)\) function attack, now the natural next step is to define a perturbation function class to which such a function attack belongs. Once we define such a function class, we aim to show it can be approximated by neural networks with arbitrary accuracy and as a consequence, we can emulate the best function attack (13) using neural networks. In section 2.2.2, it was discussed that \(T^{gf}\) induces a partition of the underlying metric space into stable sets \(\mathcal{X}=\bigsqcup_{x_{0}\in E}W_{s}(x_{0})\). If \(T^{gf}\) is \(C^{k}\) smooth in \(W_{s}(x_{0})\) w.r.t. \(x\), then this will induce smoothness in \(\bar{T}_{x}^{pgf}\) (12) and \(\lambda^{f}(x,y)\) defined in (2) up to certain singularities. \(\lambda^{pgf}(x,y)\) can be seen as local projection of \(T^{gf}\) characterised by \(\mathbf{P}(x)\), which inherits smoothness properties of \(T^{gf}\) almost everywhere. **Lemma 2.2**.: _Let \(\nabla F\) be \(C^{k}\) smooth w.r.t. \(x\in\bigsqcup_{x_{0}\in E}W_{s}^{o}(x_{0})\) then, \(\lambda^{pgf}(x,y)\) is \(C^{k}\) smooth w.r.t. \(x\in\bigsqcup_{x_{0}\in E}W_{s}^{o}(x_{0})\) for all \(p\), where \(W^{o}\) denotes the interior of the set \(W\)._ As we are dealing with compact spaces (\(x\in[0,1]^{D}\)), \(C^{k}\) smoothness will imply belonging to a Holder space (Definition A.7) w.r.t. \(x\). We can consider the space of piece-wise Holder function space to describe \(\lambda^{f}(x,y)\) where the pieces are characterized by the singularities (Boundaries \(\partial W_{s}(x_{0});x_{0}\in E\)). ## 3 Piece-wise Holder function and its approximation **Definition 3.1**.: Let \(\mathbf{A}=\{A_{i}\}\) be any disjoint partition of the domain space \(\mathcal{X}\). i.e, \(\mathcal{X}=\bigsqcup_{i}A_{i}\). Then a function \(h:\mathbb{R}^{D}\to\mathbb{R}\) belongs to \(\bar{\mathcal{H}}(\omega,\mathcal{X})\), a piece-wise Holder function class iff for some \(\mathbf{A}\), the restriction of the function \(h\) to any piece \(A_{i}\in\mathbf{A}\), denoted by \(h_{A_{i}}\), belongs to \(\mathcal{H}(\omega,A_{i})\) (Definition A.7). Based on Section 2.4, we would like to consider the perturbation function class (Definition 1.2) as \(\lambda^{f}(x,y)\in\mathcal{F}^{p}_{\delta}(\tilde{\mathcal{C}})=\mathcal{F}^ {p}_{\delta}(\bigotimes_{i=1}^{D}\bar{\mathcal{H}}(\omega_{i},\mathcal{X}))\) (where \(\bigotimes\) denotes the product space). For the sake of notational convenience we will denote \(\bar{\mathcal{H}}(\omega^{*},D,\mathcal{X})\coloneqq\bigotimes_{i=1}^{D}\bar{ \mathcal{H}}(\omega_{i},\mathcal{X})\) where \(\omega^{*}=\min\{\omega_{i}\}\). There has been a convincing argument to use \(\tilde{\mathcal{C}}=\bar{\mathcal{H}}(\omega^{*},D,\mathcal{X})\), but the way we defined \(\lambda^{f}(x,y)\)(13) won't have a closed-form expression. Hence, we would like to use some closed-form parametric family of functions to emulate the perturbation function class where the _best attack function_ resides. We can use a family of Relu neural networks (Definition 1.1) to approximate our perturbation function class with arbitrary accuracy up to a small measurable set \(\nu\). Theorem 3.1 shows that using a sufficiently wide network one can achieve arbitrarily small approximation error. **Definition 3.2** (Asymptotic notation).: For any two real functions a,b: * \(a\prec b\) or \(a=\mathcal{O}(b)\) denotes there exists a positive constant \(0<C<\infty\) such that \(|a|\leq C|b|\). * \(a\succ b\) or \(a=\Omega(b)\) denotes there exists a positive constant \(0<C<\infty\) such that \(|a|\geq C|b|\) * \(a\asymp b\) or \(a=\Theta(b)\) iff \(a\prec b\prec a\). * Consider two real sequences \(a_{n},b_{n}\) then \(a_{n}=o_{\mathbb{P}}(b_{n})\) denotes that \(\frac{a_{n}}{b_{n}}\) converges to 0 in probability. **Theorem 3.1**.: _Let \(\mu\) be a probability measure on the space \(\mathcal{X}\). For any \(h\in\bar{\mathcal{H}}(\omega^{*},D,\mathcal{X})\) and \(\mathcal{X}_{s}=Supp(\mu)\subset\mathcal{X}\) with \(\dim_{M}(\mathcal{X}_{s})=d\) (see; Definition A.9). Then given \(W\geq c_{1}\epsilon^{-\frac{\nu}{\nu}},w\geq c_{2}\epsilon^{-\frac{\nu}{\nu}}, \kappa\geq c_{3}\epsilon^{-c_{4}},L=c_{5}\) and a measurable set \(\nu\) with \(\mu(\nu)=\mathcal{O}(\epsilon^{\frac{1}{\nu}})\), there exists a neural network \(\hat{h}\) such that:_ \[\inf_{\hat{h}\in\mathcal{F}_{\sigma}(L,W,w,\kappa)}\sup_{x\in\mathcal{X}_{s} \setminus\nu}||\hat{h}(x)-h(x)||_{\infty}\leq\epsilon, \tag{17}\] _where \(c_{1},c_{2},c_{3},c_{4},c_{5}>0\) are some large enough constants independent of \(\epsilon\)._ **Corollary 3.2**.: _For any \(h\in\bar{\mathcal{H}}(\omega^{*},D,\mathcal{X})\) with \(\mathcal{X}_{s}=Supp(\mu)\subset\mathcal{X}\,,\dim_{M}(\mathcal{X}_{s})=d\), there exists \(\hat{h}\in\mathcal{F}_{\sigma}(L,W,w,\kappa)\) with sufficiently large \(\kappa\) and depth \(L\) such that:_ \[\sup_{x\in\mathcal{X}\setminus\nu}\left\|\hat{h}(x)-h(x)\right\|_{\infty}= \mathcal{O}\left(\min(W,w)^{-\omega^{*}/d}\right), \tag{18}\] _where \(\mu(\nu)=\mathcal{O}\left(\min(W,w)^{-1/d}\right)\). Furthermore, if \(h\in\bigotimes_{i}\mathcal{H}(\omega_{i},\mathcal{X})\), then \(\mu(\nu)=0\)._ Proof.: Representing \(\epsilon\) in terms of the width \(w\) and number of non-zero parameters \(W\) we get the above result. Also, when \(h\in\prod_{i}\mathcal{H}(\omega_{i},\mathcal{X})\) is just product space of Holder functions without any pieces, we don't require the measurable set \(\nu\) to bound the error. As in the proof of Theorem 3.1, \(\nu\) arises as a consequence of covering the boundary of pieces in a piece-wise Holder function. Theorem 3.1 and corollary 3.2 justifies the existence of a Relu neural net which can approximate the best \(\ell_{p}(\delta)\) function attack \(\lambda^{f}(x,y)\) as defined in (13). The approximation error \(\epsilon\) decays based on the number of non-zero parametres, the width \(W\), \(w\) of the network. The decay rate is controlled by \(\omega^{*}/d\) which makes sense as the smoothness \(\omega^{*}\) increases the function is easier to approximate; inversely it is harder to approximate as the intrinsic dimension \(d\) of the input space increases. Similar observations can be made about the measure of \(\nu\); whose decay rate only depends on the dimension \(d\), not the smoothness. ## 4 Convergence of Adversarial Training Let \(f^{*}\) be the robust (\(p\),\(\delta\)) model (4), this is the true robust model in some arbitrary function space \(\mathcal{C}\). We would like to study how the empirical estimate of \(\widehat{f}_{n}\in\mathcal{C}_{n}\) w.r.t sample size \(n\) converges to \(f^{*}\). Corresponding to any \(f\in\mathcal{C}\) we also have the best \(\ell_{p}(\delta)\) function attack \(\lambda^{f}(x,y)\in\mathcal{F}_{\delta}^{p}(\tilde{\mathcal{C}})\) which maximises the adversarial loss (2). For notation convenience now on wards denote \(\lambda^{f}\coloneqq\lambda^{f}(x,y)\) for any model \(f\); also \(\Lambda=\mathcal{F}_{\delta}^{p}(\tilde{\mathcal{C}})\) original function space of attacks. Adversarial training to find the robust \((p,\delta)\) model \(f^{*}\) is the sequential mini-max problem: \[\lambda^{f} =\arg\max_{\lambda\in\Lambda}\mathbb{E}\mathcal{L}(f,\lambda, \mathcal{Z}),\quad\forall f\in\mathcal{C},\] \[f^{*} =\arg\min_{f\in\mathcal{C}}\mathbb{E}\mathcal{L}(f,\lambda^{f}, \mathcal{Z}).\] In order to find the empirical estimator \(\widehat{f}_{n}\) of the above sequential mini-max we can restrict the function spaces to \(\mathcal{C}_{n},\Lambda_{n}\) and optimize the empirical adversarial loss such that: \[\widehat{\lambda}_{n}^{f}\in\Lambda_{n}:\mathbb{E}_{n}\mathcal{L}(f,\widehat{ \lambda}_{n}^{f},\mathcal{Z})\geq\sup_{\lambda\in\Lambda_{n}}\mathbb{E}_{n} \mathcal{L}(f,\lambda,\mathcal{Z})-\eta_{n},\quad\forall f\in\mathcal{C} \tag{19}\] \[\widehat{f}_{n}\in\mathcal{C}_{n}:\mathbb{E}_{n}\mathcal{L}(\widehat{f}_{n}, \widehat{\lambda}_{n}^{f},\mathcal{Z})\leq\inf_{f\in\mathcal{C}_{n}}\mathbb{ E}_{n}\mathcal{L}(f,\widehat{\lambda}_{n}^{f},\mathcal{Z})+\bar{\eta}_{n}. \tag{20}\] \(\mathbb{E}_{n}\) is just the empirical expectation over the observed \(n\)-sample data \(\{(x_{i},y_{i})\}_{i=1}^{n},\widehat{\lambda}_{n}^{f},\widehat{f}_{n}\) are empirical epimators of \(\lambda^{f},f^{*}\) respectively. Notice that \(\widehat{\lambda}_{n}^{f},\widehat{f}_{n}\) might not reach the supremum and infimum respectively w.r.t. the adversarial loss exactly but are very close to it, up to some small error values \(\eta_{n},\bar{\eta}_{n}\). This is done, as \(\mathcal{C}_{n},\Lambda_{n}\) (Sieve-spaces [19]) might not be closed in general. #### Zero-Sum game and Nash condition In the real-life implementation, the above mini-max optimization faces practical bottlenecks due to equation (19) as we need to find \(\widehat{\lambda}_{n}^{f}\) for all possible \(f\in\mathcal{C}\) then proceed to minimization problem (20). Fortunately, the adversarial training framework is a special form of mini-max optimization. Let \(V=\mathbb{E}\mathcal{L}(f,\lambda,\mathcal{Z})\), then a robust model is trying to minimize \(V\) and a \(\ell_{p}(\delta)\) attack is trying to minimize \(-V\). This sort of mini-max optimization is known as a _Zero-Sum_ game [1]. A classical result in game theory is that Nash equilibrium is attained at the solution of a zero-sum mini-max optimization. Hence, an equivalent optimization scheme to (19),(20) based on empirical Nash condition will be as follows: \[\widehat{\lambda}_{n}\in\Lambda_{n}:\mathbb{E}_{n}\mathcal{L}( \widehat{f}_{n},\widehat{\lambda}_{n},\mathcal{Z}) \geq\sup_{\lambda\in\Lambda_{n}}\mathbb{E}_{n}\mathcal{L}(\widehat{ f}_{n},\lambda,\mathcal{Z})-\eta_{n} \tag{21}\] \[\widehat{f}_{n}\in\mathcal{C}_{n}:\mathbb{E}_{n}\mathcal{L}( \widehat{f}_{n},\widehat{\lambda}_{n},\mathcal{Z}) \leq\inf_{f\in\mathcal{C}_{n}}\mathbb{E}_{n}\mathcal{L}(f,\widehat{ \lambda}_{n},\mathcal{Z})+\widetilde{\eta}_{n} \tag{22}\] The above scheme is like a solution to a two-player game where the best robust model is minimization of the loss w.r.t. the best attack and the best attack itself is maximization of the loss w.r.t. the best robust model. The Nash equilibrium formulation is useful when we do adversarial training in practice; instead of exploring the whole parameter/function space we just iteratively find the best attack given a model and then robustly train the model given the best attack and continue the process until we reach equilibrium. #### Convergence rate We will state convergence results on the expected difference in loss based on the empirical estimate \(\widehat{f}_{n}\) and \(f^{*}\); also \(\widehat{\lambda}^{f}\) and \(\widehat{\lambda}^{f}_{n}\) for any \(f\) with respect to the sample size \(n\). Also, we assume that the original parameter space for the model is a product of Holder space i.e. \(f\in\mathcal{C}=\prod_{i}^{K}\mathcal{H}(\bar{\omega}_{i},\mathcal{X})\) with smoothness \(\bar{\omega}^{*}=\min\{\bar{\omega}_{i}\}_{i=1}^{n}\). **Theorem 4.1** (Adversarial training rates).: _Let \(\mathcal{C}=\prod_{i}^{K}\mathcal{H}(\bar{\omega}_{i},\mathcal{X})\) and \(\Lambda=\mathcal{F}_{\delta}^{p}(\tilde{\mathcal{H}}(\omega^{*},D,\mathcal{X}))\), and we assume that \(\Lambda,\mathcal{C}\) are compact under \(\|\cdot\|_{\infty}\). For all \(\lambda,\lambda^{\prime}\in\Lambda,\ f,f^{\prime}\in\mathcal{C}\), assume the following conditions hold:_ * _A0: Assume that_ \(f^{*}\in\mathcal{C}\) _with support_ \(\bar{\mathcal{X}}_{s}\subset[0,1]^{D}\) _with_ \(\dim_{M}\bar{\mathcal{X}}_{s}=\bar{d}^{*}\leq D\) _(see Def._ A.9 _and_ A.7_), and that_ \(\{\lambda^{f}_{n}:f\in\mathcal{C}\}\subset\Lambda\) _on support_ \(\mathcal{X}_{s}\subset[0,1]^{D}\) _with_ \(\dim_{M}\mathcal{X}_{s}=d^{*}\leq D\) * _A1: The loss is Lipschitz continuous in_ \(f\) _and_ \(\lambda\)_,_ \[\mathcal{L}(f,\lambda,\mathcal{Z})-\mathcal{L}(f^{*},\lambda^{\prime},\mathcal{ Z})\prec\|f-f^{\prime}\|_{\widetilde{\mathcal{X}}}+\|\lambda-\lambda^{\prime}\|_{ \mathcal{X}},\] _where_ \(\|\|_{\mathcal{X}}\)_,_ \(\|\|_{\widetilde{\mathcal{X}}}\) _are the supremum norms over the supports_ \(\mathcal{X},\widetilde{\mathcal{X}}\)_._ * _A2: The variance of the loss difference is bounded by its expectation, specifically in terms of_ \(f\) _as follows:_ \[\mathbb{V}[\mathcal{L}(f,\lambda^{f},\mathcal{Z})-\mathcal{L}(f^{*},\lambda^{ f^{*}},\mathcal{Z})]\prec\mathbb{E}[\mathcal{L}(f,\lambda^{f},\mathcal{Z})- \mathcal{L}(f^{*},\lambda^{f^{*}},\mathcal{Z})]\prec\|f-f^{*}\|_{\widetilde{ \mathcal{X}}}^{2}\] _for any_ \(\widetilde{\mathcal{X}}\subset\mathcal{X}_{s}\)_._ * _A3: The variance of the loss difference is bounded by its expectation, specifically in terms of_ \(\lambda\) _as follows:_ \[\mathbb{V}[\mathcal{L}(f,\lambda^{f},\mathcal{Z})-\mathcal{L}(f,\lambda, \mathcal{Z})]\prec\mathbb{E}[\mathcal{L}(f,\lambda^{f},\mathcal{Z})-\mathcal{ L}(f,\lambda,\mathcal{Z})]\prec\|\lambda^{f}-\lambda\|_{\widetilde{\mathcal{X}}}^{2}+ \mathbb{P}^{2\omega^{*}}(x\not\in\widetilde{\mathcal{X}})\] _for any_ \(\widetilde{\mathcal{X}}\subset\mathcal{X}_{s}\)_._ _Pick any two values \(\bar{r}>\underline{r}\geq\left(\frac{d^{*}}{\omega^{*}}\vee\frac{\bar{r}^{*}} {\bar{\omega}^{*}}\right)\). Consider estimators \(\widehat{f}_{n},\widehat{\lambda}_{n}^{f}\) in equations (19),(20) with \(\eta_{n},\bar{\eta}_{n}=o_{\mathbb{P}}(n^{-2/(2+\bar{r})})\) where \(\Lambda_{n}=\mathcal{F}_{\sigma}(L,W_{n},w_{n},\bar{w}_{n})\) and \(\mathcal{C}_{n}=\mathcal{F}_{\sigma}(\underline{L},\bar{W}_{n},\bar{w}_{n}, \bar{\kappa}_{n})\) implement neural networks (cf. Definition 1.1) satisfying \(W_{n},\bar{W}_{n},w_{n},\bar{w}_{n}\asymp n^{\underline{r}/(\underline{r}+2)}\) and \(\kappa_{n},\bar{\kappa}_{n}\asymp n^{c}\) for any large enough choices of \(L,\bar{L},c>0\). Then:_ \[\mathbb{E}[\mathcal{L}(\widehat{f}_{n},\lambda^{\widehat{f}_{n} },\mathcal{Z})-\mathcal{L}(f^{*},\lambda^{f^{*}},\tilde{\mathcal{Y}})]=o_{ \mathbb{P}}(n^{-2/(2+\bar{r})}),\] \[\sup_{f\in\mathcal{C}_{n}}\mathbb{E}[\mathcal{L}(f,\lambda^{f}, \mathcal{Z})-\mathcal{L}(f,\widehat{\lambda}_{n}^{f},\mathcal{Z})]=o_{ \mathbb{P}}(n^{-2/(2+\bar{r})}).\] _Hence, \(d(\widehat{f}_{n},f^{*})=o_{\mathbb{P}}(1)\) for any (pseudo-norm \(d(\cdot,\cdot)\) under which \(\mathbb{E}[l(f,\lambda^{f},\tilde{\mathcal{Y}})]\) is compact and continuous. Further, if \(d(f,f^{*})^{1/q}\prec\mathbb{E}[\mathcal{L}(f,\mathcal{Z})-\mathcal{L}(f^{*},\mathcal{Z})]\) for \(q>0\), we get:_ \[d(\widehat{f}_{n},f^{*})=o_{\mathbb{P}}(n^{-2q/(2+\bar{r})}).\] We have the following remarks regarding the assumptions in the above theorem. _Remark_.: \(A_{0}\) is a trivial assumption ensuring that our robust model \(f^{*}\) belongs to a product space of Holder continuous functions. This is a reasonable assumption for regression/classification problems in the deep learning realm. Also, the best attack \(\lambda^{f}\) for any \(f\in\mathcal{C}\) belongs to the product space of piece-wise Holder functions; this is supported by our discussions in section 2.4. \(A1\) enforces Lipschitz continuity for our adversarial loss \(\mathcal{L}(f,\lambda,\mathcal{Z})\) w.r.t. \(\lambda\) and \(f\). \(A2,A3\) suggests that the variance and mean of difference in adversarial loss can be controlled by the difference of the underlying parameters. In \(A3\), we have the extra term \(\mathbb{P}^{2\omega^{*}}(x\not\in\widetilde{\mathcal{X}})\). This will be used to account for the small measure set where our neural network can't approximate the attack well (Refer Theorem 3.1). That is, we will let \(\widetilde{\mathcal{X}}\) be the measurable set where approximation fails and \(\omega^{*}\) is the smoothness factor for piece-wise Holder function space. ## 5 Numerical Experiments As discussed earlier the sequential mini-max optimization of our adversarial loss (19)(20) is a zero-sum game and must reach the Nash-equilibrium at the optimum (21)(22). Empirically we can reach such an equilibrium by emulating the adversarial _Zero-sum_ game between the estimators of the robust model \(f\) (4) and corresponding best attack \(\lambda^{f}\) (2). Motivated by this, given a sample of \(N\) data points we train two neural networks \(f,\lambda^{f}\) with parameters \(\theta_{f},\theta_{\lambda}\); competing against each other until convergence or Nash-equilibrium is reached (Algorithm: 1). \(T\) is the number of training epochs; \(P\) represents the number of iterations the model \(f\) is trained in each epoch; correspondingly \(H\) is the number of iterations \(\lambda^{f}\) is trained in one epoch; \(\tilde{\gamma},\bar{\gamma}\) are the learning rates for \(f,\lambda^{f}\). At each training epoch, \(f\) is optimized in order to minimize the adversarial loss given the current state of \(\lambda^{f}\); and \(\lambda^{f}\) maximizes the adversarial loss (minimizes negative adversarial loss) given the current state of \(f\). This is in a similar flavor to the training of general adversarial networks (GANs) [15], where the discriminator plays an analogous role to our robust model \(f\) and the generator is analogous to the attack model \(\lambda^{f}\) in our scenario. We apply the adversarial framework in both classification and regression settings. For the classification setting, we use the two-dimensional geometric datasets (see; Appendix D and Figure 6); we visually evaluate the consistency of the learned attack network with respect to the theoretical best attack (13) based on projected gradient flow. We also use the number of misclassifications and adversarial loss to evaluate the robustness, and attack strength of \(f,\lambda^{f}\) respectively. For the regression setting, we use the (Boston) [21], (Diabetes) [5] datasets; we evaluate adversarial loss on the test dataset as a performance metric. ``` Initialize: \(t\gets 0,h\gets 0,p\gets 0\). Each entry of \(\theta_{f},\theta_{\lambda}\sim^{iid}\mathcal{U}(-\sqrt{\frac{1}{\texttt{in\_ features}}},\sqrt{\frac{1}{\texttt{in\_features}}})\), where in_features means the width of the previous layer in the network. while\(t\leq T\)do while\(p\leq P\)do \(\theta_{f}\leftarrow\theta_{f}-\tilde{\gamma}\nabla_{\theta_{f}}\sum_{i=1}^{n} \mathcal{L}(f,\lambda^{f},(x_{i},y_{i}))\)\(\triangleright\) Can be any gradient-based optimizer, e.g., SGD, ADAM, etc \(p\gets p+1\) endwhile while\(h\leq H\)do \(\theta_{\lambda}\leftarrow\theta_{\lambda}+\tilde{\gamma}\nabla_{\theta_{\lambda}} \sum_{i=1}^{n}\mathcal{L}(f,\lambda^{f},(x_{i},y_{i}))\) \(h\gets h+1\) endwhile \(p\gets 0,h\gets 0,t\gets t+1\) endwhile ``` **Algorithm 1** Adversarial Training ## Classification We implement algorithm 1 with \(T=100,H=1,P=1\) and \(\tilde{\gamma}=10^{-3},\bar{\gamma}=2\times 10^{-4}\) for all the classification datasets. We use \(\delta=0.2\) (attack strength) and \(\ell_{p}:p=2,\infty\) for our experiment. When \(\delta\) is big, the so-called _robust overfitting_ might occurs, and optimization results may not be satisfactory, and more discussion about it can be found in Section 6. For all feasible values of \(\delta\), the analysis remains the same. Furthermore, the \(\ell_{p}\) constraint on the attack network \(\lambda^{f}\) is implemented in the forward pass through learned scaling (between 0 and 1) and normalization. Architecture and implementation details can be found in Appendix D. We use the multinomial negative loglikelihood or the cross-entropy loss as our loss function \(\mathcal{L}(f(x),y)=\sum_{j=0}^{C-1}\mathbb{1}_{y=j}\log\mathrm{Softmax}(f(x))_{j}\); the corresponding adversarial loss is then \(\mathcal{L}(f,\lambda^{f},(x,y))=\mathcal{L}(f(x+\lambda^{f}(x,y)),y)=\sum_{j =0}^{C-1}\mathbb{1}_{y=j}\log\mathrm{Softmax}(f(x+\lambda^{f}(x,y)))_{j}\). Here, \(C\) is the number of classes. ### Gradient flow and Neural Network attack direction Figure 0(a), shows the loss surface and gradient direction \(\nabla_{x}\mathcal{L}(f_{clean}(x),y))/||\nabla_{x}\mathcal{L}(f_{clean}(x),y))||\) corresponding to \(x\)'s on a grid, where the response label \(y\) is imputed by model \(f_{clean}\), which achieves almost 100% accuracy and is viewed as an oracle. Here \(f_{clean}\) is the clean model trained to minimize the standard loss (\(f_{clean}=\arg\min_{f\in\mathcal{C}_{n}}\mathbb{E}_{n}\mathcal{L}(f(x),y)\)) without any adversarial perturbation. The higher loss regions correspond to the _estimated decision boundary_ (EDB) of the dataset; this is consistent as the loss is locally maximized when any pair of classes have approximately equal probability. Figure 0(b) shows the loss surface, gradient direction, and learned attack direction of \(\lambda^{f}\) for the adversarially trained \(\ell_{2}(0.2)\) robust model \(f\) based on Algorithm 1. As discussed in Section 2.2.3, (13) is the best theoretical attack. Ignoring the deflection term for saddle points, the underlying ODE is dictated by a projected gradient flow (9, 10). For \(p=2\), the projected gradient flow projects the original gradient flow onto local spheres. Due to the smoothness of spheres in every direction, we expect a flow visually similar to the original gradient flow. This is what we see in figure 0(b), where \(\nabla_{x}\mathcal{L}(f(x),y)\) (left) and \(\lambda^{f}\) (right) are essentially the same. This also corroborates the approximation capability of neural network for piece-wise Holder function space (Theorem 3.1) where the theoretical best attack resides. Figure 0(c) is the \(\ell_{\infty}(0.2)\) case of the prior discussion. Unlike the \(\ell_{2}\) case, for \(\ell_{\infty}\), the projected gradient flow projects the gradient trajectory onto local cubes, which are not smooth in all directions. The gradient flow dynamic continues after reaching the boundary and gets projected onto the sides/diagonals of a cube (11). This is consistent with Figure 0(c) where \(\nabla_{x}\mathcal{L}(f(x),y)\) (left) is more smooth, but \(\lambda^{f}\) (right) is restricted only to diagonal directions. Subsequently, comparing the adversarially trained EDB with clean trained EDB we see that the EDB is wider after adversarial training which essentially induces the _robustness_ in the model. Also, due to the prior projection arguments \(\ell_{2}\) adversarial training preserves the geometry of the EDB while \(\ell_{\infty}\) projects the original EDB onto local cubes, making it more blocky; this phenomenon is most prominent for the circles dataset where EDB transforms from a circle (\(\ell_{2}\)) to a square (\(\ell_{\infty}\)) as expected. Figure 3: Percentage of mis-classified test labels vs training epochs for adversarial training based on Algorithm 1. The notation and legend in the plots follow Figure 2. Figure 2: **(Classification setting)** Test Loss vs training epochs for adversarial training based on Algorithm 1. Where \(f\) is our adversarially trained classifier and \(f_{PGD}\) PGD trained robust classifier. For the attacks: \(\lambda^{f}\) represents adversarially trained neural network attack based on \(f\) (_semi-white box)_; \(\lambda_{PGD}\) represents (_white-box_) PGD attack; \(\lambda_{FGSM}\) represents _(white-box_)_ FGSM attack. In the legends the combination \((f,\lambda_{PGD})\) represents the empirical loss \(\sum_{i=1}^{n_{test}}\mathcal{L}(f,\lambda_{PGD},(x_{i},y_{i}))\) when the PGD attack \(\lambda_{PGD}\) is performed on the adversarially trained defense \(f\), similarly \((f_{PGD},\lambda_{PGD})\) represents the empirical loss \(\sum_{i=1}^{n_{test}}(f_{PGD},\lambda_{PGD},(x_{i},y_{i}))\) when \(\lambda_{PGD}\) attack is performed on \(f_{PGD}\); and so on. ### Comparison with PGD attacks and PGD trained robust classifer In section 2.3 we discussed how PGD attack (16) [29] is just a discretization of the theoretical best possible attack (13). With small enough step-size \(\gamma\) we can treat PGD attack as a baseline (i.e., discrete approximation of best attack), for notational convenience we will denote \(\lambda_{PGD}\) as the PGD attack. Similarly, \(\lambda_{FGSM}\) denotes the FGSM attack mentioned in [16] which is just PGD attack with \(\gamma=\delta\) and a single iteration step. We train \(f_{PGD}\) which aims to minimize the PGD-based adversarial loss \(\mathbb{E}_{n}\mathcal{L}(f(x+\lambda_{PGD}),y)\), this is the traditional way of adversarial training mentioned in [29]. In our framework, the attack generation itself is approximated by a neural network \(\lambda_{f}\) rather than a gradient-based method, and the adversarial training becomes a mathematical game between \(f\) and \(\lambda_{f}\). The significance of \(f_{PGD}\) is that with small step-size \(\gamma\) for PGD attack generation, it will act as a baseline for our version of adversarial training. Figures 2 and 3 show the evaluated adversarial loss and misclassification rate for all attack-defense combinations on the _test data_ as we progress through adversarial training. For all the datasets we see that the adversarial loss for our robust network \(f\) with attacks \(\lambda^{f},\lambda_{PGD},\lambda_{FGSM}\) converge to their respective \(f_{PGD}\) counter-parts. The loss that our framework deals with is corresponding to the \((f,\lambda^{f})\) pair (solid red line) and the baseline would be \((f_{PGD},\lambda_{PGD})\) (dashed green line). For the streaks dataset there seems to be a gap between PGD defense \(f_{PGD}\) against FGSM attack \(\lambda_{FGSM}\) and PGD attack \(\lambda_{PGD}\); we see that our adversarially trained attack \(\lambda^{f}\) tries to match \(\lambda_{FGSM}\) attack on \(f_{PGD}\). On the other hand our defense \(f\) tries to match the loss levels of \(f_{PGD}\) defense against its own \(\lambda_{PGD}\) attack. Comparing the solid curves (defense model \(f\)) with non-solid curves (defense model \(f_{PGD}\)), our defense model has a lower loss under the same attack, indicating its higher adversarial robustness. For the misclassification rate, we see that, for circles, streaks datasets, \(f\) shows stronger defense for all types of attacks compared to \(f_{PGD}\) but the attack strength of \(\lambda^{f}\) is weaker compared to \(\lambda_{PGD}\). For moon the opposite happens where the \(\lambda^{f}\) shows misclassifications comparable to \(\lambda_{PGD}\) but the defense \(f\) is a bit weaker than \(f_{PGD}\) but still competitive. For polynomials, our defense \(f\) performs better against \(\lambda_{FGSM}\) compared to \(f_{PGD}\), but \(f_{PGD}\) is a bit better to defend against \(\lambda_{PGD}\). This is not that shocking as \(f_{PGD}\) should perform well against \(\lambda_{PGD}\) as it is adversarially trained over it. To comment on the differences between PGD and our method, we note that our attack/defense model is trained solely based on loss values, while the implemented PGD algorithm in our simulation combines the loss value and misclassification. 1 Furthermore, the PGD attack is a white box attack, while our \(\lambda_{f}\) is a _semi-white box_ attack. Footnote 1: PGD, for classification, follows the standard PGD iterations on each sample until it is misclassified. If a sample is misclassified, we do not implement further PGD iterations. Early stopping until misclassification maximizes the misclassification rate. [https://github.com/fhladrpartos/Adversarial-MF-simification/Yiob/main/vtili.py](https://github.com/fhladrpartos/Adversarial-MF-simification/Yiob/main/vtili.py) ### White box vs Semi-white box attacks: Note that technically the neural network-based attack \(\lambda^{f}\) is at a disadvantage compared to the gradient-based attacks \(\lambda_{PGD},\lambda_{FGSM}\). \(\lambda^{f}\) learns the functional form of the attack and doesn't have access to the original model while generating new attacks on the test dataset, this is known as a _semi-white_ box setting, i.e., once the model has been trained no extra gradient computations are done. In contrast, \(\lambda_{PGD},\lambda_{FGSM}\) need to be computed from scratch for each new sample in the test dataset and also need to have access to the original classifier models \(f,f_{PGD}\). These attacks hence fall into the _white-box_ setting. The competitive performance based on test loss and misclassification rate against various defense/attack combinations compared to the gradient-based method is consistent with the theory. In real life, one saves computation costs while using our framework, as \(\lambda^{f}\) approximates (13) using neural networks. Also, the defense \(f\) learned as a consequence provides competitive performance or sometimes better robustness based on these experiments. ## Regression For the Boston,Diabetes datasets, we implement Algorithm 1 with \(T=400,H=1,P=1,\tilde{\gamma}=10^{-3},\tilde{\gamma}=2\times 10^{-4}\). We use \(\ell_{2}\) attacks to compare the adversarial loss between \(f_{PGD}\) and \(f\) under \(\lambda_{FGSM},\lambda_{PGD},\lambda^{f}\) attacks on the test data. As \(\ell_{2}\) attacks preserve geometry, that perturbation strength in any direction is the same; we deemed it to be an appropriate choice for the regression setting. For the loss, we use the Gaussian negative log-likelihood or the mean-square error loss, \(\mathcal{L}(f(x),y)=\left\|f(x)-y\right\|_{2}^{2}\). The corresponding adversarial loss being \(\mathcal{L}(f,\lambda^{f},(x,y))=\mathcal{L}(f(x+\lambda^{f}(x,y)),y)=\left\| f(x+\lambda^{f}(x))-y\right\|_{2}^{2}\) Figure 4 shows the convergence of the adversarial loss for our robust defense \(f\) based on algorithm 1, comparing against the baseline \(f_{PGD}\). In Appendix D, it can be seen that for higher \(\delta\), \(\lambda^{f}\) is stronger than \(\lambda_{PGD}\). ## 6 Discussion and Conclusion ### Robust Overfitting When \(\delta\) is comparatively large, adversarial trained robust model minimizing the objective (4) tends to prioritize minimizing the loss towards generated adversarial examples and forget the original geometry of data. This could lead to distortion of the loss surface compared to the clean model and poor generalization performance of the robust model. This issue is known as _Robust Overfitting_ in the literature. [41] provides theoretical rates for reduction of generalisation error w.r.t. \(\delta\) attack strength. [43] suggests a loss-constraining method to prevent data overfitting. From our experiments, we see that robust overfitting arises as a distortion of the loss surface. Figure 5 (left) shows the loss surface of adversarially trained robust \(\ell_{\infty}(0.2)\) robust model. The robust classifier tends to defend against the perturbed data samples and as a result, forgets about the original geometry of the data points which results in distortion of the EDB. There is a trade-off between robustness and standard accuracy [38]. As \(\delta\) increases the distortion will get worse, as the perturbed data is farther from the original data. We can resolve this issue by retaining some original data information while conducting adversarial training; one can modify the standard adversarial loss as follows: \[\mathcal{L}(f,\lambda^{f},\mathcal{Z})=\mathbb{E}\mathcal{L}(f(x+\lambda^{f} (x,y)),y)\rightarrow\mathbb{E}(1-\alpha)\mathcal{L}(f(x+\lambda^{f}(x,y)),y) +\alpha\mathcal{L}(f(x),y) \tag{23}\] The above equation doesn't change any of our theory, all the convergence results and arguments still hold as they are true for a general \(\mathcal{L}(f,\lambda^{f},\mathcal{Z})\). Also, the non-adversarial counterpart of the loss function is still our original vanilla loss used for clean training. This is a canonical modification that assigns \(\alpha\) weightage to the original data. For the modified loss, the performance plots analogous to Figures 3 and 2 are almost identical, and we omit them for brevity. The advantage of this approach is that we eliminate the possible distortions in the loss surface (Figure 5 Right). This gets rid of the robust overfitting issue and even for high \(\delta\) the robust model can't stray away completely from the original data (Figure 7). [17] proposes a similar weighted loss but instead of using original data, they use a generative model to produce synthetic data which are perturbed. The idea being that synthetic data are purer in some sense and retain important features even after perturbation. Figure 4: **(Regression setting) Test Loss vs training epochs for adversarial training based on Algorithm 1. Where \(f\) is our adversarially trained classifier and \(f_{PGD}\) PGD trained robust classifier. For the attacks: \(\lambda^{f}\) represents adversarially trained neural network attack based on \(f\) _(semi-white box)_; \(\lambda_{PGD}\) represents _(white-box)_ PGD attack; \(\lambda_{FGSM}\) represents _(white-box)_ FGSM attack. In the legends the combination \((f,\lambda_{PGD})\) represents the empirical loss \(\sum_{i=1}^{n_{test}}\mathcal{L}(f,\lambda_{PGD},(x_{i},y_{i}))\) when the PGD attack \(\lambda_{PGD}\) is performed on the adversarially trained defense \(f\), similarly \((f_{PGD},\lambda_{PGD})\) represents the empirical loss \(\sum_{i=1}^{n_{test}}(f_{PGD},\lambda_{PGD},(x_{i},y_{i}))\) when \(\lambda_{PGD}\) is performed on \(f_{PGD}\); and so on.** Another popular method to deal with robust overfitting is _trade adversarial robustness off against accuracy_ (TRADES) proposed by [44]. TRADES splits the adversarial loss in a similar fashion as (23); but uses the original classifier scores instead of the true labels for the adversarial part. In our framework this will correspond to the following adversarial loss: \[\mathcal{L}(f,\lambda^{f},\mathcal{Z})=\mathbb{E}(1-\alpha)\mathcal{L}(f(x+ \lambda^{f}(x,y)),f(x))+\alpha\mathcal{L}(f(x),y). \tag{24}\] One can extend these methods to our framework by changing the adversarial loss \(\mathcal{L}(f,\lambda^{f},\mathcal{Z})\) suitably. #### AdvGAN AdvGAN proposed by [40] uses general adversarial networks (GANs) to generate adversarial examples. AdvGAN is the best performing black-box attack generation method according to the Madry MNIST challenge. The theoretical justifications for AdvGAN can be addressed by our framework. For generating an attack, a GAN is trained with a generator \(G\) and a discriminator \(D\) optimizing the objective \(\min_{G}\max_{D}\mathbb{E}\mathcal{L}_{adv}+c_{1}\mathcal{L}_{GAN}+c_{2} \mathcal{L}_{hinge}\) for some chosen constants \(c_{1},c_{2}\) determining weightage of the losses. \(\mathcal{L}_{GAN}=\log(1-D(G(x)))+\log(D(x))\) is the standard GAN loss (Bernoulli likelihood) for distinguishing between real and adversarially perturbed data; \(\mathcal{L}_{adv}=-L(f(x+G(x)),y)\) is the adversarial loss maximizing the model/classifier \(f\)'s original loss for some \(L\), e.g., MSE, cross-entropy, CW loss, etc; \(\mathcal{L}_{hinge}=\max(0,\left\|G(x)\right\|_{2}-\delta)\) is the hinge loss which softly bounds the \(\ell_{2}\) norm of the generated attacks by \(\delta\). As \(D\) appears only in \(\mathcal{L}_{GAN}\), we can train \(G\) via solving the objective \(\max_{G}\mathbb{E}-\mathcal{L}_{adv}-c_{1}\mathcal{L}_{GAN}(D^{*})-c_{2} \mathcal{L}_{hinge}\), where \(D^{*}_{G}=\arg\max_{D}\mathbb{E}\mathcal{L}_{GAN}\). To fit the advGAN approach into our framework, the generator \(G\) corresponds to the attack function \(\lambda^{f}\) and we choose the loss function as \(\mathcal{L}(f(x),y)=L(f(x),y)-c_{1}\mathcal{L}_{GAN}(D^{*}_{G})\), then the corresponding adversarial loss would be: \[\mathcal{L}(f,\lambda^{f},\mathcal{Z})=\mathcal{L}(f(x+\lambda^{f}(x,y)),y)=L (f(x+\lambda^{f}),y)-c_{1}\mathcal{L}_{GAN}(D^{*}_{G}).\] Consider the \(\ell_{2}(\delta)\) best function attack (2) for the above loss: \[\lambda^{f}=\arg\max_{\left\|\lambda\right\|_{2}\leq\delta}\mathcal{L}(f(x+ \lambda(x,y)),y)\] If we consider the Lagrangian of the above objective with Lagrangian multiplier \(c^{\prime}_{2}\), we get: \[\lambda^{f}=\arg\max_{\lambda}\mathcal{L}(f(x+\lambda(x,y)),y)+c^{\prime}_{2} (\left\|\lambda\right\|_{2}-\delta).\] When \(\left\|\lambda_{2}\right\|\leq\delta\), the optimal solution can be achieved for \(c^{\prime}_{2}=0\); when \(\left\|\lambda_{2}\right\|>\delta\), \(c^{\prime}_{2}\) has to be \(-\infty\). So, in practice, the constrained optimization can be emulated for \(\lambda^{f}\) by solving: \[\lambda^{f}=\arg\max_{\lambda}\mathcal{L}(f(x+\lambda(x,y)),y)-c_{2}\max(0, \left\|\lambda\right\|_{2}-\delta)=-\mathcal{L}_{adv}-c_{1}\mathcal{L}_{GAN} (D^{*}_{\lambda})-c_{2}\mathcal{L}_{hinge},\] where \(c_{2}>0\) is a large coefficient. This is the same loss that the generator in AdvGAN maximizes. Hence, AdvGAN can be thought of as a special case of our framework which aims to generate the best \(\ell_{2}(\delta)\) attack. Consequently, the dynamic distillation method proposed in [40] is equivalent to the mathematical game between \(G\equiv\lambda^{f}\) and \(f\). We can link the success of AdvGAN to the theoretical justifications provided in this work. Figure 5: \(\ell_{\infty}(0.2)\), Loss contour plot with learnt attack direction \(\lambda^{f}\) compared for \(\alpha=0\) (no-original data) vs \(\alpha=0.3\) (\(30\%\) weightage to original data). Dataset: circles ## Conclusion Through this work, we were able to define a generalized framework for adversarial training, in the sense that the _best_ adversarial attacks/examples (2) can take a functional form. We showed that this functional form is essentially captured by a continuous dynamic system closely related to the gradient flow of the adversarial loss (13). The traditional gradient-based attacks in the literature can be thought of as a discrete approximation of the same. Subsequently, the ideal attack resides in a piece-wise Holder space and we can render neural networks to approximate this function up to arbitrary accuracy (Theorem 3.1). This is also empirically verified through our experiments (Figure 1). Furthermore, using neural networks to generate attacks and approximating the model with another neural network results in the adversarial training process being a mathematical game between two neural networks. We provided a convergence rate for such an adversarial game/training based w.r.t. the sample size of the data (Theorem 4.1). We also compare the performance between PGD and a function-based attack generator based on neural networks; which further bolsters the argument of approximation capability of neural nets for the ideal attack. As a consequence of training a functional form, we are also able to generate attacks in a semi-white box setting, whose performance is comparable to the PGD attack. Our work provides a theoretical justification for a recent trend to use neural networks to generate attacks; additionally, we can justify the use of such networks in the context of adversarial training of a robust model.
2302.14078
Analyzing Populations of Neural Networks via Dynamical Model Embedding
A core challenge in the interpretation of deep neural networks is identifying commonalities between the underlying algorithms implemented by distinct networks trained for the same task. Motivated by this problem, we introduce DYNAMO, an algorithm that constructs low-dimensional manifolds where each point corresponds to a neural network model, and two points are nearby if the corresponding neural networks enact similar high-level computational processes. DYNAMO takes as input a collection of pre-trained neural networks and outputs a meta-model that emulates the dynamics of the hidden states as well as the outputs of any model in the collection. The specific model to be emulated is determined by a model embedding vector that the meta-model takes as input; these model embedding vectors constitute a manifold corresponding to the given population of models. We apply DYNAMO to both RNNs and CNNs, and find that the resulting model embedding spaces enable novel applications: clustering of neural networks on the basis of their high-level computational processes in a manner that is less sensitive to reparameterization; model averaging of several neural networks trained on the same task to arrive at a new, operable neural network with similar task performance; and semi-supervised learning via optimization on the model embedding space. Using a fixed-point analysis of meta-models trained on populations of RNNs, we gain new insights into how similarities of the topology of RNN dynamics correspond to similarities of their high-level computational processes.
Jordan Cotler, Kai Sheng Tai, Felipe Hernández, Blake Elias, David Sussillo
2023-02-27T19:00:05Z
http://arxiv.org/abs/2302.14078v1
# Analyzing Populations of Neural Networks via Dynamical Model Embedding ###### Abstract A core challenge in the interpretation of deep neural networks is identifying commonalities between the underlying algorithms implemented by distinct networks trained for the same task. Motivated by this problem, we introduce Dynamo, an algorithm that constructs low-dimensional manifolds where each point corresponds to a neural network model, and two points are nearby if the corresponding neural networks enact similar high-level computational processes. Dynamo takes as input a collection of pre-trained neural networks and outputs a _meta-model_ that emulates the dynamics of the hidden states as well as the outputs of any model in the collection. The specific model to be emulated is determined by a _model embedding vector_ that the meta-model takes as input; these model embedding vectors constitute a manifold corresponding to the given population of models. We apply Dynamo to both RNNs and CNNs, and find that the resulting model embedding spaces enable novel applications: clustering of neural networks on the basis of their high-level computational processes in a manner that is less sensitive to reparameterization; model averaging of several neural networks trained on the same task to arrive at a new, operable neural network with similar task performance; and semi-supervised learning via optimization on the model embedding space. Using a fixed-point analysis of meta-models trained on populations of RNNs, we gain new insights into how similarities of the topology of RNN dynamics correspond to similarities of their high-level computational processes. ## 1 Introduction A crucial feature of neural networks with a fixed network architecture is that they form a manifold by virtue of their continuously tunable weights, which underlies their ability to be trained by gradient descent. However, this conception of the space of neural networks is inadequate for understanding the computational processes the networks perform. For example, two neural networks trained to perform the same task may have vastly different weights, and yet implement the same high-level algorithms and computational processes (Maheswaranathan et al., 2019). In this paper, we construct an algorithm which provides alternative parametrizations of the space of RNNs and CNNs with the goal of endowing a geometric structure that is more compatible with the high-level computational processes performed by neural networks. In particular, given a set of neural networks with the same or possibly different architectures (and possibly trained on different tasks), we find a parametrization of a low-dimensional submanifold of neural networks which approximately interpolates between these chosen "base models", as well as extrapolates beyond them. We can use such _model embedding spaces_ to cluster neural networks and even compute _model averages_ of neural networks. A key feature is that two points in model embedding space are nearby if they correspond to neural networks which implement similar high-level computational processes, in a manner to be described later. In this way, two neural networks may correspond to nearby points in model embedding space even if those neural networks have distinct weights or even architectures. The model embedding space is parametrized by a low-dimensional parameter \(\theta\in\mathbb{R}^{d}\), and each base model is assigned a value of \(\theta\) in the space. This allows us to apply traditional ideas from clustering and interpolation to the space of neural networks. Moreover, each model embedding space has an associated _meta-model_ which, upon being given a \(\theta\), is rendered into an operable neural network. If a base model is mapped to some \(\theta\), then the meta-model, upon being given that \(\theta\), will emulate the corresponding base model. See Figure 1 for a diagrammatic depiction. Figure 1: A conceptual diagram of the Dynamo algorithm and _model embedding space_. A set of neural networks labelled \(1,...,N\) called the _base models_ are mapped to corresponding points \(\theta_{1},...,\theta_{N}\) in the model embedding space. Two points in the model embedding space are nearby if they correspond to neural networks with similar dynamics for their hidden and output states. There is an associated neural network called the _meta-model_ which, when given a \(\theta_{i}\), becomes a neural network that emulates the hidden and output dynamics of the corresponding base model \(i\). The meta-model produces a viable neural network for any given any value of \(\theta\), including points in the model embedding space that do not correspond to any base model. An interesting application is that given two base models assigned to parameters \(\theta_{1}\) and \(\theta_{2}\), we can consider the averaged model corresponding to the value \((\theta_{1}+\theta_{2})/2\). We find that this averaged model performs similarly on the task for which the two base models were trained. We also use the model embedding space to extrapolate outside the space of base models, and find cases in which the model embedding manifold specifies models that perform better on a task than any trained base model. Later on we will explain how this can be regarded as a form of semi-supervised learning. The rest of the paper is organized as follows. We first provide the mathematical setup for our algorithmic construction of model embedding spaces. After reviewing related work, we then present results of numerical experiments which implement the algorithm and explore clustering, model averaging, and semi-supervised learning on the model embedding space. We further examine how topological features of the dynamics of RNNs in model embedding spaces are reflective of classes of high-level computational processes. Finally, we conclude with a discussion. ## 2 Dynamical Model Embedding ### Mathematical Setup In this Section, we provide the mathematical setup for construction of model embedding spaces. We treat this in the RNN setting, and relegate the CNN setting to Appendix A. Notation.Let an RNN be denoted by \(F(x,h)\) where \(x\) is the input and \(h\) is the hidden state. We further denote the hidden-to-output map by \(G(h)\). We consider a collection of \(N\) RNNs \(\{(F_{n},G_{n})\}_{n=1}^{N}\) we call the _base models_ which may each have distinct dimensions for their hidden states, but all have the same dimension for their inputs as well as the same dimension for their outputs. A sequence of inputs is notated as \(\{x_{t}\}_{t=0}^{T}\) which induces a sequence of hidden states by \(h_{t+1}=F(x_{t},h_{t})\) where the initial hidden state \(h_{0}\) is given. A collection of sequences of inputs, possibly each with different maximum lengths \(T\), is denoted by \(\mathcal{D}\) which we call an _input data set_. We suppose that each base model RNN has an associated input data set. ### Meta-Models for RNNs Given a collection base model RNNs, we would like to construct a _meta-model_ which emulates the behavior of each of the base models. In this case, the meta-model is itself an RNN with one additional input \(\theta\in\mathbb{R}^{d}\) and a corresponding map \(\widetilde{F}(\theta,x,h)\) whose output is the next hidden state. Given a sequence of input states \(\{x_{t}\}_{t=0}^{T}\), we have a corresponding sequence of output states \(h_{\theta,t+1}=\widetilde{F}(\theta,x_{t},h_{\theta,t})\) starting from an initial hidden state \(h_{0}\) (which we suppose does not depend on \(\theta\)). The meta-model also includes a hidden-to-output map \(\widetilde{G}(h)\) that is independent of \(\theta\). For the meta-model \((\widetilde{F},\widetilde{G})\) to emulate a particular base model \((F_{n},G_{n})\) with respect to its corresponding data set \(\mathcal{D}_{n}\), we consider the following criteria: there is some \(\theta_{n}\) for which 1. \(\widetilde{G}(h_{\theta_{n},t})\approx G_{n}(h_{t})\) for all \(t>0\) and all input sequences in the data set; and 2. \(V_{n}(h_{\theta,t})\approx h_{t}\) for all \(t>0\) and all input sequences in the data set, where \(V_{n}\) is a transformation of a meta-model's hidden activity. We emphasize that \(\theta_{n}\) and \(V_{n}\) depend on the particular base model under consideration. The first criterion means that at some particular \(\theta_{n}\), the outputs of the meta-model RNN dynamics are close to the outputs of the base model RNN dynamics. The second criterion means that at the same \(\theta_{n}\), there is a time-independent transformation \(V_{n}\) (i.e., \(V_{n}\) does not depend on \(t\)) such the transformed hidden state dynamics of the meta-model are close to the hidden state dynamics of the base model. See Figure 2 for a visualization. As depicted in the Figure, it is convenient to regard the meta-model RNN as having inputs \((\theta_{n},x)\). As such, a sequence of inputs \(\{x_{t}\}_{t=1}^{T}\) is appended by \(\theta_{n}\) to become \(\{(\theta_{n},x_{t})\}_{t=1}^{T}\). The desired properties of the meta-model are enforced by the loss function. Defining the functions \[\mathcal{L}_{\text{output}}[\widetilde{F},\widetilde{G},\theta_ {n}] :=\frac{1}{T}\sum_{t=1}^{T}d(\widetilde{G}(h_{\theta_{n},t}),G_{n}(h_ {t})) \tag{1}\] \[\mathcal{L}_{\text{hidden}}[\widetilde{F},\theta_{n},V_{n}] :=\frac{1}{T}\sum_{t=1}^{T}\left\|V_{n}(h_{\theta_{n},t})-h_{t} \right\|_{2}^{2} \tag{2}\] where \(d\) is some suitable distance or divergence, we can construct the loss function \[\mathbb{E}_{\{x_{t}\}\sim\mathcal{D}_{n}}\Big{[}\mathcal{L}_{\text{hidden}}[ \widetilde{F},\theta_{n},V_{n}]+\lambda\,\mathcal{L}_{\text{output}}[ \widetilde{F},\widetilde{G},\theta_{n}]\Big{]} \tag{3}\] where we average over the choice of sequence \(\{x_{t}\}\) coming from the input data set \(\mathcal{D}_{n}\). Above, \(\lambda\) is a hyperparameter. Our aim is to minimize 3 over a suitable class of \(\widetilde{F},\widetilde{G},V_{n}\), as well as \(\theta_{n}\); this can be implemented computationally via the Dynamo algorithm (see Algorithm 1). As a side remark, it naively appears that a suitable alternative choice to the \(\mathcal{L}_{\text{hidden}}\) in equation 2 would be \(\frac{1}{T}\sum_{t=1}^{T}\left\|h_{\theta_{n},t}-W_{n}(h_{t})\right\|_{2}^{2}\) where here \(W_{n}\) is a map from the hidden states of the base model to the hidden states of the meta-model. However, this would be problematic since minimization may pressure \(W_{n}\) to be the the zero map (or otherwise have outputs which are small in norm) and accordingly pressure the dynamics of the meta-model to be trivial (or have small norm). As such, we opt to formulate \(\mathcal{L}_{\text{hidden}}\) as it is written in equation 2. Suppose we want the meta-model to be able to emulate an entire collection of base models \(\{(F_{n},G_{n})\}_{n=1}^{N}\). In particular, the meta-model will attempt to assign to the \(n\)th base model a Figure 2: **Left:** The hidden states \(h_{t}\) of \(F_{n}\) are close to the hidden states \(h_{\theta_{n},t}\) of \(\widetilde{F}\) after the transformation map \(V\) is applied. **Right:** The visible states \(G(h_{t})\) of \(F_{n}\) are close to the visible states \(\widetilde{G}(h_{\theta_{n},t})\). and a \(V_{n}\) so that the two criteria listed above on page 3 are satisfied for that base model. These desiderata can be implemented by minimizing the loss function \[\mathcal{L}[\widetilde{F},\widetilde{G},\{\theta_{n}\}_{n=1}^{N},\{V_{n}\}_{n=1} ^{N}]:=\frac{1}{N}\sum_{n=1}^{N}\mathbb{E}_{\{x_{t}\}\sim\mathcal{D}_{n}}\Big{[} \mathcal{L}_{n,\text{hidden}}[\widetilde{F},\theta_{n},V_{n}]+\lambda\, \mathcal{L}_{n,\text{output}}[\widetilde{F},\widetilde{G},\theta_{n}]\Big{]}\,. \tag{4}\] In some circumstances, we may want to consider base models with distinct dimensions for their output states. For instance, suppose half of the base models perform a task with outputs in \(\mathbb{R}^{d_{1}}\) and the other half perform a task without outputs in \(\mathbb{R}^{d_{2}}\). To accommodate for this, we can have two hidden-to-output maps \(\widetilde{G}_{1},\widetilde{G}_{2}\) for the meta-model, where the maps have outputs in \(\mathbb{R}^{d_{1}}\) and \(\mathbb{R}^{d_{2}}\) respectively. The loss function is slightly modified so that we use \(\widetilde{G}_{1}\) when we compare the meta-model to the first kind of base model, and \(\widetilde{G}_{2}\) when we compare the meta-model to the second kind of base model. This construction generalizes to the setting where the base models can be divided up into \(k\) groups with distinct output dimensions; this would necessitate \(k\) hidden-to-output functions \(\widetilde{G}_{1},...,\widetilde{G}_{k}\) for the meta-model. ## 3 Related Work There is a substantial body of work on interpreting the computational processes implemented by neural networks by studying their intermediate representations. Such analyses have been performed on individual models (Simonyan et al., 2013; Zeiler and Fergus, 2014; Lenc and Vedaldi, 2015) and on collections of models (Li et al., 2016; Raghu et al., 2017; Morcos et al., 2018; Kornblith et al., 2019). Prior work in this latter category has focused on pairwise comparisons between models. For example, SVCCA (Raghu et al., 2017) uses canonical correlation analysis to measure the representational similarity between pairs of models. While these methods can also be used to derive model representations by embedding the pairwise distance matrix, our approach does not require the \(\Theta(N^{2})\) computational cost of comparing all pairs of base models. Moreover, Dynamo yields an executable meta-model that can be run with model embedding vectors other than those corresponding to the base models. There is a related body of work in the field of computational neuroscience. CCA-based techniques and representational geometry are standard for comparing neural networks to the neural activations of animals performing vision tasks (Yamins and DiCarlo, 2016) as well as motor tasks. In an example of the latter, the authors of (Sussillo et al., 2015) used CCA techniques to compare brain recordings to those of neural networks trained to reproduce the reaching behaviors of animals, while the authors of (Maheswaranathan et al., 2019) used fixed point analyses of RNNs to consider network similarity from a topological point of view. Dynamo can be viewed as a form of knowledge distillation (Hinton et al., 2015), since the outputs of the base models serve as targets in the optimization of the meta-model. However, unlike typical instances of knowledge distillation involving an ensemble of teacher networks (Hinton et al., 2015; Fukuda et al., 2017) where individual model predictions are averaged to provide more accurate target labels for the student, our approach instead aims to preserve the dynamics and outputs of each individual base model. FitNets (Romero et al., 2015) employ a form a knowledge distillation using maps between hidden representations to guide learning; this is similar to our use of hidden state maps in training the meta-model. Our treatment of the model embedding vectors \(\{\theta_{n}\}\) as learnable parameters is similar to the approach used in Generative Latent Optimization (Bojanowski et al., 2018), which jointly optimizes the image generator network and the latent vectors corresponding to each image in the training set. Bojanowski et al. (2018) find that the principal components of the image representation space found by GLO are semantically meaningful. We likewise find that the principal components of the model embeddings found by Dynamo are discriminative between subsets of models. Unlike methods such as hypernetworks (Ha et al., 2017) and LEO (Rusu et al., 2019) that use a model to generate parameters for a separate network, our approach does not attempt to reproduce the parameters of the base models in the collection. Instead, the meta-model aims to reproduce only the hidden states and outputs of a base model when conditioned on the corresponding embedding vector. The core focus of our work also differs from that of the meta-learning literature (Santoro et al., 2016; Ravi and Larochelle, 2017; Finn et al., 2017; Munkhdalai and Yu, 2017), which is primarily concerned with the problem of few-shot adaptation when one is presented with data from a new task. Our empirical study centers on the post-hoc analysis of a given collection of models, which may or may not have been trained on different tasks. However, we remark that our exploration of optimization in low-dimensional model embedding space is related to LEO (Rusu et al., 2019), where a compressed model representation is leveraged for efficient meta-learning. ## 4 Empirical Results In this Section, we describe the results of our empirical study of meta-models trained using Dynamo on collections of RNNs trained on NLP tasks, and collections of CNNs trained for image classification. For RNN base models, we parameterize the meta-model as a GRU where the model embedding vector \(\theta\) is presented as an additional input at each time step. For CNN base models, we use a ResNet meta-model where \(\theta\) is an additional input for each ResNet block. In all our experiments, we hold out half the available training data for use as unlabeled data for training the meta-model; the base models were trained on the remaining training data (or a fraction thereof).1 By default, we set the output loss hyperparameter \(\lambda\) to \(1\). We defer further details on model architectures and training to the Appendices A and B. Footnote 1: For example, our IMDB sentiment base models trained on \(100\%\) of the available training data were trained on 12,500 examples, with the remaining 12,500 examples used as unlabeled data for training the meta-model. ### Visualizing Model Similarity in Embedding Space The base model embeddings \(\{\theta_{n}\}_{n=1}^{N}\) can be used for cluster analysis to evaluate the similarity structure of a collection of models. We illustrate this use case of Dynamo via a series of example applications including NLP and vision tasks. Figure 3 shows model embeddings learned by Dynamo on collections of RNNs. In these plots, we observe a clear separation of these networks according to the size of the available training data, the RNN model architecture, and the specific NLP task used for training. By computing the eigenvalues of the covariance matrix corresponding to the \(N\) model embeddings, we obtain a measure of the intrinsic dimensionality of the corresponding collections of models. In Figure 3, we find that 2 to 6 components are sufficient to explain \(95\%\) of the variance in the model embeddings. By tuning the output loss hyperparameter \(\lambda\) in equation 4, we can adjust the degree of emphasis placed on reproducing the hidden dynamics of the base networks versus their outputs. We demonstrate this effect in Figure 4: with \(\lambda=1\), we observe clear separation of ResNet-34 models trained on CIFAR-100 with different data augmentation policies ("weak", with shifts and horizontal flips Figure 3: **PCA plots of Dynamo model embeddings on collections of RNNs. From left to right: (1) The model embedding space for GRUs trained on IMDB sentiment classification dataset (Maas et al., 2011) with varying training set sizes (\(100\%\), \(50\%\), and \(25\%\) of the training data); (2) training trajectories of sentiment classification GRUs over 20 epochs, with each point corresponding to an epoch of training (low-opacity points indicate networks early in training); (3) two RNN architectures trained for IMDB sentiment classification (GRUs and vanilla RNNs); (4) GRUs trained on two NLP tasks: IMDB sentiment classification and AG News classification (Zhang et al., 2015). The second row shows the spectrum for each set of embeddings, with a dotted line indicating the number of components needed to explain \(95\%\) of the variance.** vs. "strong", with RandAugment (Cubuk et al., 2020)), and with different training set sizes. In contrast, with \(\lambda=0\) we find a weak clustering effect corresponding to differing data augmentation, and we do not find a detectable separation corresponding to differing training set sizes. We infer that the change in data augmentation policy results in a larger difference in the learned feature representations than the change in training set size. In Appendix B we illustrate the effect of setting \(\lambda=0\) for RNN models. We additionally compare the embeddings obtained using Dynamo to those derived from SVCCA (Raghu et al., 2017), a pairwise comparison technique that aligns the representations produced by a pair of networks using canonical correlation analysis (CCA). In Figure 5, we plot the 2D embeddings obtained using multidimensional scaling (MDS) on the pairwise distance matrix computed using SVCCA (modified to output \(L^{2}\) distances instead of correlations). Unlike the principal components of the Dynamo model embeddings plotted in Figure 3, the MDS coordinates are not semantically interpretable. Additionally, the cluster structure of the collection of GRUs trained with varying training set sizes is less apparent in this representation. Figure 4: **PCA plots of Dynamo model embeddings on collections of ResNet-34s trained on CIFAR-100. Left two panels: Model embeddings cluster according to the size of the training dataset and the data augmentation policy used for training. Right two panels: When trained only by comparing hidden representations (i.e., with output loss weight \(\lambda=0\)), Dynamo does not identify a clustering effect when varying the training dataset size. In the case of differing data augmentation policies, there is a weak clustering effect that suggests a consistent difference in feature representation.** Figure 5: 2D multidimensional scaling (MDS) embeddings of the SVCCA pairwise representational distances between RNN models trained on the IMDB sentiment dataset. Lastly, we note that Dynamo allows for flexibility in defining the metric used to compare the hidden states and outputs of the base models with those of the meta-model. In Appendix B.3, we demonstrate the benefit of using the \(L^{1}\) distance for clustering CNN representations. ### Extrapolation Beyond Base Model Embeddings We study the model embedding space corresponding to a trained meta-model by conditioning it on model embedding vectors \(\theta\) other than those assigned to the set of base models. Figure 6 visualizes the landscape of test accuracies for two meta-models: (i) a meta-model for 10 GRUs trained with \(50\%\) of the IMDB training data and 10 GRUs trained with \(25\%\) of the data; and (ii) a meta-model for 10 IMDB sentiment GRUs and 10 AG News classification GRUs. We note two particularly salient properties of these plots. First, the test accuracy varies smoothly when interpolating \(\theta\) between pairs of base model embeddings--we would in general _not_ observe this property when interpolating the parameters of the base GRUs directly, since they were trained with different random initializations and orderings of the training examples. Second, we observe that the embedding vector that realizes the highest test accuracy lies _outside_ the convex hull of the base model embeddings. This is perhaps surprising since typical training and inference protocols involve the use of convex combinations of various objects: for instance, averaging of predictions in model ensembles and averaging of model parameters during training (e.g., using exponential moving averages or Stochastic Weight Averaging (Izmailov et al., 2018)). This extrapolatory phenomenon suggests that Dynamo is able to derive a low-dimensional manifold of models that generalizes beyond the behavior of the base models used for training the meta-model. Figure 6: **Meta-model test accuracies over model embedding space.** We plot the relative test accuracies (normalized by the maximal test accuracy of the base models) realized by meta-models for GRUs trained on IMDB sentiment classification with varying training set size **(left)**, and for GRUs trained on IMDB and on AG News classification **(right)**. In these examples, the embedding vectors that maximize test accuracy (marked by ) do not correspond to any single base model, suggesting that meta-models are capable of generalizing beyond the base models used for training. ### Semi-Supervised Learning in Model Embedding Space The existence of model embeddings that improve on the accuracy of the base models suggests a natural semi-supervised learning (SSL) procedure involving a trained meta-model. In particular, we minimize the loss incurred by the meta-model on a small set of additional labeled examples by optimizing the value of \(\theta\). This is done by backpropagating gradients through the meta-model, with the meta-model parameters held fixed. Figure 7 shows the result of this procedure on an IMDB sentiment meta-model (previously depicted in Figure 6) with a set of additional labeled examples (disjoint from the test set) of size equal to \(1\%\) of the full training set. This procedure successfully finds a \(\theta\) that improves on the test accuracy of the best base model by \(6\%\) (\(86.4\%\) vs. \(80.3\%\)). We observe that this SSL procedure achieves lower accuracy when we train the meta-model using fewer base models. In particular, a meta-model coming from only the 10 GRUs trained with \(50\%\) of the training data yields a test accuracy of \(85.4\%\), and a meta-model coming from only a single GRU out of the 10 yields \(81.6\%\). This result suggests that a diversity of base models helps improve the accuracy achievable by the meta-model. ## 5 Dynamics of Meta-Models for RNNs In this Section we perform an analysis of the dynamical features generated by the meta-models trained on base models that perform the sentiment classification task. Sentiment classification tasks have a well-understood dynamical structure (Sussillo and Barak, 2013; Maheswaranathan et al., 2019, 2019; Aitken et al., 2020) that we can use as a basis for understanding the behavior of a corresponding meta-model. To a first approximation, the sentiment analysis task can be solved by a simple integrator that accumulates sentiment corresponding to each word (positive words such as 'good' or 'fantastic' adding positive sentiment, and negative words such as 'bad' or 'terrible' adding negative sentiment). It has been shown that simple sentiment analysis models approximate this integrator by constructing a line attractor in the space of hidden states. For instance, for the zero input \(x^{*}=\vec{0}\), it has been observed that the dynamical system generated by the map \(F_{x^{*}}(h)=F(x^{*},h)\) has a tubular region with very little movement, in the sense that \(\|F_{x^{*}}(h)-h\|_{2}\) is very small for hidden states \(h\) in this region. To investigate the dynamical behavior of the meta-model space, we trained a meta-model on a set of 20 base models which were themselves trained on the IMDB sentiment analysis task. Of these 20 base models, 10 were trained with \(50\%\) of the available training data and the remaining 10 were trained with \(100\%\) of the training data. The \(\theta\) points corresponding to these base models Figure 7: **Semi-supervised learning with low-dimensional model embeddings.** The red line shows the trajectory of 100 SGD iterates in model embedding space, starting from \(\theta_{\mathrm{init}}=0\) and terminating at \(\theta_{\mathrm{final}}\). White and orange points indicate the base model embeddings. cluster in the model embedding space according to the amount of training data. In Figure 8 we perform a fixed-point analysis of several models corresponding to points of interest in the model embedding space. The fixed-point analysis was run according to the procedure described in (Golub and Sussillo, 2018). First we selected a set of candidate hidden states \(h_{j}\) by running the model on a typical batch of inputs. For each hidden state \(h_{j}\) obtained in this way, we used gradient descent on the loss \(\|F(x^{*},h)-h\|_{2}^{2}\) to find the nearest approximate fixed point. An interesting finding is that the meta-model found line attractor structures that were very geometrically similar for models within a cluster. An interpretation of this result pertaining to _topological conjugacy_ in dynamical systems theory is discussed in Appendix C. Moreover, we find that the meta-model finds a continuous interpolation between line attractors that are relatively short and fat (corresponding to models trained on \(50\%\) of the data), and models that are tall and thin (corresponding to models trained on \(100\%\) of the data). ## 6 Discussion We have introduced the algorithm Dynamo, which maps a set of neural network base models to a low dimensional feature space. Our results show that the model embeddings provided by Dynamo capture relevant computational features of the base models. Moreover, the model embedding spaces produced by Dynamo are sufficiently smooth that model averaging can be performed, Figure 8: **Model embedding space as a space of line attractors.** We plot the model embeddings of 20 base models trained on the IMDB sentiment classification task **(left)**, along with the centroids of each cluster (marked by \(\mathsf{X}\) and \(\mathsf{X}\)). The green cluster corresponds to models trained on \(100\%\) of the data and the blue cluster corresponds to models trained on a fixed \(50\%\) fraction of the training data. A model having better test accuracy than any trained base model is also plotted (marked by \(\mathsf{X}\)). For several of the points of interest, we **(right)** find the structure of a line attractor in the hidden state space by computing approximate fixed points of the map \(h\mapsto F(x^{*},h)\). The line attractors are shown for the point marked by an \(\mathsf{X}\), the two centroids marked by \(\mathsf{X}\) and \(\mathsf{X}\), and two interpolated values in the model embedding space marked by \(\mathsf{X}\)’s. We also chose one point from each cluster to compare with the centroid of each cluster; those chosen points are the top left green point and the bottom right blue point. and model extrapolation can be used to reach new models with better performance than any base model. In our experiments where the base models were trained on the sentiment analysis task, the model embedding space describes a space of line attractors which vary smoothly in the parameter \(\theta\). We have demonstrated that Dynamo can be broadly applied to neural networks that have a dynamical structure; for example, we used the demarcation of layers of convolutional neural networks as a proxy for a dynamical time variable. This also suggests possible scientific applications of Dynamo to dynamical systems arising in nature. A present limitation of Dynamo is the need for all base models to have the same input structure. For example, one cannot presently utilize Dynamo to compare language models trained with different encodings (character-based vs. word-based, for example). #### Acknowledgments We would like to thank Will Allen, Semon Rezchikov, and Krishna Shenoy for valuable discussions. JC is supported by a Junior Fellowship from the Harvard Society of Fellows, as well as in part by the Department of Energy under grant DE-SC0007870. FH is supported by the Fannie and John Hertz Foundation. ## Appendix A Meta-models for CNNs Our setup in Section 2.2 above can be readily adapted to CNNs, or feedforward neural networks more broadly. For instance, in the case of ResNets, there is a single input \(x_{0}\) followed by a sequence of blocks which operate on different numbers of channels. We let the meta-model likewise be a ResNet with the same block structure. Moreover, we consider the output \(b_{t}\) of the \(t\)th block in place of the \(G_{n}(h_{t})\)'s in equation 1, and take the hidden states between the \(t\) and \(t+1\) blocks to be the \(h_{t}\)'s in equation 2. Since each block of a ResNet is distinct, we consider a family of maps \(V_{n,t}\) which depend on the base model \(n\) and the block layer \(t\). Letting \(B\) denote the total number of blocks, we can more explicitly write \[\mathcal{L}^{\text{CNN}}_{\text{output}}[\widetilde{F},\theta] :=\frac{1}{B}\sum_{t=1}^{B}d(b_{\theta_{n},t},b_{t}) \tag{5}\] \[\mathcal{L}^{\text{CNN}}_{\text{hidden}}[\widetilde{F},\theta_ {n},\{V_{n,t}\}_{t=1}^{B}] :=\frac{1}{B}\sum_{t=1}^{B}\left\|V_{n,t}(h_{\theta_{n},t})-h_{t} \right\|_{2}^{2}\,. \tag{6}\] Then the total loss function accounting for all \(N\) of the ResNet base models is \[\mathcal{L}^{\text{CNN}}[\widetilde{F},\{\theta_{n}\}_{n=1}^{N},\{\{V_{n,t}\}_{t=1}^{B}\}_{n=1}^{N}]\] \[:=\frac{1}{N}\sum_{n=1}^{N}\mathbb{E}_{x_{0}\sim\mathcal{D}_{n}} \Big{[}\mathcal{L}^{\text{CNN}}_{n,\text{hidden}}[\widetilde{F},\theta_{n}, \{V_{n,t}\}_{t=1}^{B}]+\lambda\,\mathcal{L}^{\text{CNN}}_{n,\text{output}}[ \widetilde{F},\theta_{n}]\Big{]} \tag{7}\] where we note that in the expectation value we are only sampling over \(x_{0}\)'s in \(\mathcal{D}_{n}\) since \(x_{0}\)'s are the only form of input data. ``` Input: features \(x\), model embedding vector \(\theta\) \(z=\text{BatchNormNorm}(\text{Conv}(x))\) \(z=\text{ReLU}(z+W\theta)\) \(z=\text{BatchNormNorm}(\text{Conv}(x))\) \(z=\text{ReLU}(x+z)\) return\(z\) ``` **Algorithm 2** Meta-Model Residual Block ## Appendix B Additional Experimental Details In this Appendix, we provide further details on our experiments as well as additional empirical results. ### Meta-Model Architectures RNN architecture.We parameterize the meta-model for RNNs as a GRU that takes the model embedding vector as an additional input at each time step. Specifically, the meta-model GRU takes as input the vector \([\theta\,;\,x_{t}]\) at each time step, where \(x_{t}\) is an input token embedding and \([\,\cdot\,;\,\cdot\,]\) denotes concatenation. The model embedding vector \(\theta\) therefore serves as a time-independent bias for the meta-model. CNN architecture.We parameterize the meta-model for CNNs with a modified ResNet architecture. In each residual block, we use a linear transformation \(W\) to map the model embedding vector \(\theta\) to the corresponding channel dimension of convolutional layer. We then add the vector \(W\theta\) to the channels at each spatial location of the feature map. This design emulates the approach used in our parametrization of the RNN meta-model, with the model embedding \(\theta\) serving as a bias term in each residual block. We reuse the weight matrix \(W\) for all residual blocks with the same channel dimension. See Algorithm 2 which outlines our treatment of a residual block. The standard ResNet architecture consists of a sequence of four layers, with each layer consisting of a sequence of residual blocks. To compute the hidden state loss \(\mathcal{L}_{\text{hidden}}\) in Dynamo, we compute distances between the output representations of each of these four layers, averaging over the number of channels and spatial locations in each set of features. ### Training Details Table 1 lists the hyperparameters used for training our RNN base models and meta-models, and Table 2 lists the hyperparameters used for our CNN base models and meta-models. By default, we use a model embedding dimension of \(16\). In the case of visualizing the training trajectories of IMDB sentiment GRUs (Figure 3, second column), we use a model embedding dimension of \(32\) due to the relatively larger number of base models. ### Supplementary Empirical Results Effect of output loss weight.Figure 9 shows the effect of setting the output loss weight \(\lambda=0\) for meta-models on RNNs. These plots illustrate that model clustering can be performed on the basis of comparing hidden state dynamics alone. We note that the change in the \(\lambda\) hyperparameter results in qualitative changes in the resulting clustering. In particular, the model embeddings for GRUs trained on AG News classification (rightmost column of Figure 9) are much more tightly coupled relative to the GRUs trained on the IMDB dataset when \(\lambda=0\). This indicates that the dynamics implemented by the AG News GRUs are much more similar than those implemented by the IMDB sentiment GRUs. Clustering with other loss functions.As noted in Section 4.1, the loss functions used to compare hidden states and outputs can be easily changed to better match the characteristics of the base models under consideration. We demonstrate the benefit of this additional flexibility by replacing the \(L^{2}\) distance in \(\mathcal{L}_{\mathrm{hidden}}\) (equation 6) with the \(L^{1}\) distance for purposes of better comparing the intermediate representations of ResNets. This choice is motivated by the observation that the use \begin{table} \begin{tabular}{l c c} \hline \hline **Hyperparameter** & **Base Model** & **Meta-Model** \\ \hline optimizer & AdamW (Loshchilov and Hutter, 2018) & AdamW \\ - learning rate & \(10^{-3}\) (\(10^{-4}\) for vanilla RNN) & \(10^{-3}\) \\ - learning rate annealing & cosine with freq. \(7/32\) & cosine with freq. \(7/32\) \\ - \(\beta\) & \((0.9,0.999)\) & \((0.9,0.999)\) \\ - \(\epsilon\) & \(10^{-8}\) & \(10^{-8}\) \\ - weight decay & \(5\times 10^{-4}\) & \(1\times 10^{-4}\) \\ number of training epochs & \(20\) (\(50\) for vanilla RNN) & \(100\) \\ batch size & \(128\) & \(128\) \\ input token embedding dimension & \(256\) & \(256\) \\ hidden dimension & \(256\) & \(512\) \\ \hline \hline \end{tabular} \end{table} Table 1: Hyperparameters used for RNN base models and meta-models. \begin{table} \begin{tabular}{l c c} \hline \hline **Hyperparameter** & **Base Model** & **Meta-Model** \\ \hline optimizer & SGD with Nesterov momentum & SGD with Nesterov momentum \\ - learning rate & \(0.03\) & \(0.03\) \\ - learning rate annealing & cosine with freq. \(7/32\) & cosine with freq. \(7/32\) \\ - momentum & \(0.9\) & \(0.9\) \\ - weight decay & \(5\times 10^{-4}\) & \(5\times 10^{-4}\) \\ number of training batches & \(2^{16}\) & \(2^{16}\) \\ batch size & \(512\) & \(512\) \\ \hline \hline \end{tabular} \end{table} Table 2: Hyperparameters used for CNN base models and meta-models. Figure 10: CIFAR-100 ResNet-34 model embeddings using \(L^{1}\) distance to compare intermediate representations **(left)** vs. \(L^{2}\) distance **(right)**. The use of the \(L^{1}\) distance results in a clearer separation between the two sets of models. Figure 9: **PCA plots of Dynamo model embeddings on collections of RNNs with output loss weight \(\lambda=0\). For ease of comparison, we have also included the plots from Figure 3 with \(\lambda=1\).** of the ReLU nonlinearity results in sparse representations, which suggests the use of the \(L^{1}\) metric. Figure 10 shows a comparison between these two distance functions in the case of ResNet-34 models trained on CIFAR-100 with "weak" data augmentation (random shifts and horizontal flips) and with "strong" data augmentation (RandAugment). Here, we parameterized the meta-model with a ResNet-50 architecture. The use of the \(L^{1}\) distance results in a clearer separation between the two sets of models. This is reflected qualitatively in the distribution of the base model embeddings in model embedding space, and quantitatively in the relative scale of the variance captured by the first principal component. ### Further investigation of the dynamics of sentiment analysis Recall from Section 5 that our trained RNN's implemented sentiment analysis via line attractor dynamics, in which inputted words kick the hidden state in a 'positive' or 'negative' direction along the line attractor according to the valence of the word (i.e. how positive or negative the word is). Figure 11 investigates how valences assigned to words change as we scan across model embedding space. We first find a fixed point \(h^{*}\) with neutral readout \(\widetilde{G}(h^{*})\approx 0\). Then given a \(\theta\) (which renders an RNN), we compute \(\widetilde{G}(\widetilde{F}(\theta,x,h^{*}))\) for a variety of word inputs \(x\). To produce a "score" for the model, we compute \[\text{Score}(\theta)=\sum_{x\in W_{\text{positive}}}\widetilde{G}(\widetilde{F }(\theta,x,h^{*}))-\sum_{x\in W_{\text{negative}}}\widetilde{G}(\widetilde{F}( \theta,x,h^{*}))-\sum_{x\in W_{\text{neutral}}}\left|\widetilde{G}(\widetilde{ F}(\theta,x,h^{*}))\right|, \tag{8}\] where the set of positive words \(W_{\text{positive}}\), negative words \(W_{\text{negative}}\), and neutral words \(W_{\text{neutral}}\) are listed in Table 3. The Figure shows that the score noticeably increases as \(\theta\) tends in the direction of the model embedding which performs best on the sentiment analysis task. Note that here we are not analyzing context effects, for instance how the string 'not terrible' would be rendered into a net-positive valence. Figure 11: A map of the word scores (described in equation 8) as a function of the parameter \(\theta=(\theta_{1},\theta_{2})\) in model embedding space. Higher scores indicate models that should have better interpretations of words. There is a noisy but discernible trend that the score increases as \(\theta_{2}\) decreases (and is highest near the value of the optimal model embedding). ## Appendix C Meta-models and topological conjugacy In this Appendix we describe the notion of topological conjugacy, its relationship to the loss function \(\mathcal{L}_{\text{hidden}}\), and provide speculation as to the interpretation of the results from Section 5. A topological conjugacy (Katok and Hasselblatt, 1997) between two dynamical systems defined by maps \(F:X\to X\) and \(E:Y\to Y\) is a homeomorphism \(\Phi:X\to Y\) satisfying \[F(x)=(\Phi^{-1}\circ E\circ\Phi)(x). \tag{9}\] Note that the dynamical systems \(F\) and \(E\) can have distinct domains. The significance of the relationship in equation 9 is that dynamics obtained from iterated applications of the map \(F\) and \(E\) are related to each other by the formula \[F^{n}(x)=(\Phi^{-1}\circ E^{n}\circ\Phi)(x)\,. \tag{10}\] Thus, if \(F\) and \(E\) are topologically conjugate, then their iterates are also topologically conjugate and this means that the dynamics are related by a change of variables. Notice that topological conjugacy is an equivalence relation; as such, the transitive property tells us that if \(F\sim E\) and \(E\sim D\) then \(F\sim D\). The notion of topological conjugacy is an important motivation for defining the loss function \(\mathcal{L}_{\text{hidden}}\), which we recall is given by \[\mathcal{L}_{\text{hidden}}[\mathcal{F},\theta,V]:=\frac{1}{T}\sum_{t=1}^{T} \left\|V(h_{\theta,t})-h_{t}\right\|_{2}^{2}, \tag{11}\] where the hidden states \(h_{t}\) are dynamics obtained from a base model \(F\), the hidden states \(h_{\theta_{t}}\) are dynamics obtained from the meta-model \(\widetilde{F}\) with parameter \(\theta\), and \(V\) is the map from the meta-model hidden states to the base model hidden states. One way of obtaining zero loss is to find a topological conjugacy with map \(V\) between the meta-model \(\widetilde{F}\) (at fixed \(\theta\)) and the base model \(F\), meaning a relationship of the form \[F(x,h)=(V\circ\widetilde{F})(\theta,x,V^{-1}h)\,. \tag{12}\] It is convenient to define the notation \(F_{x}(h):=F(x,h)\) and \(\widetilde{F}_{\theta,x}(h):=\widetilde{F}(\theta,x,h)\). Then we have \[h_{t}=(F_{x_{t}}\circ F_{x_{t-1}}\circ\cdots\circ F_{x_{1}})(h_{0})=(V\circ \widetilde{F}_{\theta,x_{t}}\circ\widetilde{F}_{\theta,x_{t-1}}\circ\cdots \circ\widetilde{F}_{\theta,x_{1}})(V^{-1}h_{0})=Vh_{\theta,t} \tag{13}\] with \(h_{\theta,0}=V^{-1}h_{0}\), so that \(\mathcal{L}_{\text{hidden}}[\mathcal{F},\theta,V]=0\) would hold. As depicted in Figure 2, to obtain zero loss it would actually suffice to find a weaker relationship of the form \[F(x,Vh)=(V\circ\widetilde{F})(\theta,x,h)\,. \tag{14}\] \begin{table} \begin{tabular}{l l} \hline \hline **Positive words** & good, awesome, terrific, exciting, fantastic, amazing, fine, superior, outstanding, superb, magnificent, marvelous, exceptional, tremendous \\ \hline **Negative words** & bad, awful, horrible, terrible, poor, inferior, unacceptable, shoddy, atrocious, crap, rubbish, garbage \\ \hline **Neutral words** & it, the, is, a, if, then, are, were, can, will, has, had, been, was, when, who, to, what \\ \hline \hline \end{tabular} \end{table} Table 3: Lists of good, negative, and neutral words selected to assess the “word valence” quality of a model. The difference here is that \(V\) need not be invertible. Using the language of topological conjugacy, we can describe a speculative but plausible interpretation of the results of Section 5. In that Section we observed that models from the same cluster had very similar dynamical features and performed similarly to the model average of the cluster. This suggests that for each model \(F_{n}\) in the same cluster, we have \[F_{n}(x,V_{n}h)\approx(V_{n}\circ F)(\overline{\theta},x,h) \tag{15}\] where \(\overline{\theta}\) is the centroid of the cluster to which \(F_{n}\) belongs. Note that here we replaced \(\theta_{n}\) with \(\overline{\theta}\), thus assuming both that \(\mathcal{L}_{\text{hidden}}\) is small and that \(\theta_{n}\) is sufficiently close to \(\overline{\theta}\). Second, making the hypothesis that there exists an inverse \(V_{n}^{-1}\) to the map \(V_{n}\), the map \(V_{n}\) may provide a topological conjugacy between the base model \(F_{n}\) and the meta-model \(\widetilde{F}_{\overline{\theta}}\) evaluated at \(\overline{\theta}\). Assuming further that our assumptions hold for all models in the cluster, using the transitivity of topological conjugacy we would conclude that base models belonging to the same cluster are topologically conjugate to one another. This would justify the intuition suggested by Figure 8 that Dynamo clusters models according to commonalities of topological structures of dynamics.
2304.04697
Brain-Inspired Spiking Neural Network for Online Unsupervised Time Series Prediction
Energy and data-efficient online time series prediction for predicting evolving dynamical systems are critical in several fields, especially edge AI applications that need to update continuously based on streaming data. However, current DNN-based supervised online learning models require a large amount of training data and cannot quickly adapt when the underlying system changes. Moreover, these models require continuous retraining with incoming data making them highly inefficient. To solve these issues, we present a novel Continuous Learning-based Unsupervised Recurrent Spiking Neural Network Model (CLURSNN), trained with spike timing dependent plasticity (STDP). CLURSNN makes online predictions by reconstructing the underlying dynamical system using Random Delay Embedding by measuring the membrane potential of neurons in the recurrent layer of the RSNN with the highest betweenness centrality. We also use topological data analysis to propose a novel methodology using the Wasserstein Distance between the persistence homologies of the predicted and observed time series as a loss function. We show that the proposed online time series prediction methodology outperforms state-of-the-art DNN models when predicting an evolving Lorenz63 dynamical system.
Biswadeep Chakraborty, Saibal Mukhopadhyay
2023-04-10T16:18:37Z
http://arxiv.org/abs/2304.04697v2
# Brain-Inspired Spiking Neural Network for Online Unsupervised Time Series Prediction ###### Abstract Energy and data-efficient online time series prediction for predicting evolving dynamical systems are critical in several fields, especially edge AI applications that need to update continuously based on streaming data. However, current Deep Neural Network (DNN)-based supervised online learning models require a large amount of training data and cannot quickly adapt when the underlying system changes. Moreover, these models require continuous retraining with incoming data making them highly inefficient. We present a novel Continuous Learning-based Unsupervised Recurrent Spiking Neural Network Model (CLURSNN), trained with spike timing dependent plasticity (STDP) to solve these issues. CLURSNN makes online predictions by reconstructing the underlying dynamical system using Random Delay Embedding by measuring the membrane potential of neurons in the recurrent layer of the recurrent spiking neural network (RSNN) with the highest betweenness centrality. We also use topological data analysis to propose a novel methodology using the Wasserstein Distance between the persistent homologies of the predicted and observed time series as a loss function. We show that the proposed online time series prediction methodology outperforms state-of-the-art DNN models when predicting an evolving Lorenz63 dynamical system. spiking neural network, recurrent, STDP, Wasserstein distance, persistent homologies, online time series prediction ## I Introduction Real-world systems are not static and keep evolving with time, thus creating the need for an evolving learning system [1]. Therefore, developing online learning methods that can make predictions by extracting the underlying dynamics from the observed time series for real-time learning and prediction of time-varying environments for machine learning (ML) models running at the edge is critical [2, 3]. However, current supervised learning models predict future timesteps based on past observations without any knowledge of the dynamics of the underlying dynamical system [4, 5, 6]. Hence, these models fail dramatically for systems continuously evolving, especially systems with sudden data distribution changes. This is because these models require a large amount of data for training and cannot adapt quickly to emergent internal dynamics. In this paper, we propose a completely unsupervised prediction of the time series, which is quick and robust in adapting to new unseen dynamics. We use recurrent spiking neural networks for extremely-energy efficient brain-inspired models that can continually learn from streaming incoming data using unsupervised plasticity rules. We focus on a recurrent spiking neural network (RSNN) model trained using unsupervised spike timing dependent plasticity rules (STDP) [7, 8] to capture the complex temporal correlations. Recent works [7, 9, 10] have shown such brain-inspired recurrent spiking neural networks trained with STDP to exhibit promising performance with very few computations. Hence the model continually learns representations of the underlying dynamical systems from which the data is generated. We predict by reconstructing the underlying dynamical systems using random delay embedding on the neuron activation time series data. This method of unsupervised forecasting of time series data contrasts with current regression-type methods used to predict time series data. It is not only data efficient but also helps in the continual modeling of evolving intelligent agents. The overall model can be described using the following four-step process: 1. We observe the projected time series from an evolving dynamical system. The time series is then fed into the encoder layer of an RSNN, where the data is converted to spike streams that are, in turn, fed into the RSNN, a recurrently connected network of Leaky Integrate and Fire (LIF) neurons, with the synapses being continually updated using STDP. 2. We sample neurons from the RSNN with the highest betweenness centrality \(\mathcal{C}_{b}\), and each of the observed spike streams is decoded to get a high-dimensional time series data 3. We then use the randomly distributed embedding [11] method to reconstruct the underlying dynamical system and predict the system's future steps from this reconstruction. The detailed process is shown in Fig. 1 and explained in greater detail in Section III-A. The key contributions of this work are as follows: * We propose a completely unsupervised online learning model using a spiking neural network using continual reconstruction of the underlying dynamical system * We sample the nodes with the highest \(\mathcal{C}_{b}\) for the reconstruction and show that such sampling is better than using all the neurons. We relate this sampling to the bottleneck layer of the autoencoder. * one where the model is reconstructed using the RMSE error as the metric and the other where the model is reconstructed using the 1-Wasserstein distance \(d_{W,1}\) between the persistent homologies between the predicted (\(\hat{p}_{H}\)) and observed time series (\(p_{H}\)) as the metric. We show that the Wasserstein-based reconstruction method always outperforms the root mean square error(RMSE)-based reconstruction method, highlighting that the persistent homologies can better capture the underlying dynamics of the system. * We showed that for a limited amount of data, the RSNN-based models outperform the DNN-based models and converge faster. However, with multiple repetitions of the same data, the DNNs outperform the RSNN models. We evaluated the models on a synthetic evolving dynamical system dataset and real-world datasets like YReal, and Dow Jones Industrial Average. The proposed CLURSNN methods outperform the supervised DNN models for online time series prediction tasks. The rest of the paper is organized as follows: Sections II and III discusses the Background and the Methods used in the paper, while in Section IV, we discuss the experiments performed and the results observed. Finally, we present the conclusions from these observations in Section V. ## II Background **Related Works:** Recent works on predictive models [4, 5, 6, 12] demonstrate the ability to discover hierarchical latent representations and complex dependencies. However, such studies focus on batch learning settings where the entire training data set should be available a priori, meaning that the relationship between inputs and outputs is always static. This assumption is restrictive for real-world applications where data arrives in streams, and the underlying dynamical system generating the data changes [13]. Cui et al. [3] described the potential of ML methods for various applications like traffic profiling, device identification, system security, Internet of Things applications, edge computing, etc. However, training an artificial intelligence model at the edge from scratch can be time-consuming and energy-inefficient. Therefore, it is desirable to train deep predictors online using only new samples to capture the changing dynamics of the environment [14, 15]. Despite the ubiquity of online learning in many real-world applications, training detailed predictors online remains a challenge. First, standard deep neural networks converge slowly on the data stream due to the unavailability of offline training advantages such as mini-batch and multi-epoch training [16, 17]. Overall, deep neural networks have powerful representation learning capabilities but lack mechanisms for successfully training data streams. Therefore, online time series forecasting using deep models is a promising but challenging problem. Several methods have been proposed to solve the online learning problem. However, current deep learning-based models require a huge amount of data for training and are also extremely energy inefficient, making it difficult to deploy in edge devices. Brain-inspired spiking neural networks have been proposed as the next generation of energy-efficient neural network models that process information in the discrete spike domain, unlike standard DNNs [18]. Most recent works on spiking neural networks are targeted for time series or spatiotemporal classification [19, 9, 20]. Some recent works also use spiking neural networks for time series forecasting [21, 10]. However, these models are trained using supervised learning methods [21] or need a supervised readout layer [22], hence cannot adapt to evolving systems. However, no work exists that uses a completely unsupervised time series prediction method that reconstructs the underlying dynamical system, which is essential for edge ML applications. **Recurrent Spiking Neural Network (RSNN)** consists of spiking neurons connected with synapses. Our simulations use the Leaky Integrate and Fire (LIF) neuron model. In the LIF neuron model, the membrane potential of the \(i\)-th neuron \(u_{i}(t)\) Fig. 1: Block Diagram showing the Different Steps for Unsupervised Prediction of Time Series using RSNN varies over time as: \[\tau_{m}\frac{dv_{i}(t)}{dt}=-\left(v_{i}(t)-v_{rest}\right)+I_{i}(t) \tag{1}\] where \(\tau_{\rm m}\) is the membrane time constant, \(v_{rest}\) is the resting potential and \(I_{\rm i}\) is the input current. When the membrane potential reaches the threshold value \(v_{\rm th}\) a spike is emitted, \(v_{i}(t)\) resets to the reset potential \(v_{\rm r}\) and then enters a refractory period where the neuron cannot spike. Spikes emitted by the \(j\)th neuron at a finite set of times \(\{t_{j}\}\) can be formalized as a spike train \(S_{i}(t)=\sum\delta\left(t-t_{i}\right)\). We use a STDP rule [7] for updating a synaptic weight (\(\Delta w\)) and is given by : \[\Delta w(\Delta t)=\{\begin{array}{ll}A_{+}(w)e^{-\frac{|\Delta t|}{\tau_{+} }}&\mbox{if }\Delta t\geq 0\\ -A_{-}(w)e^{-\frac{|\Delta t|}{\tau_{-}}}&\mbox{if }\Delta t<0\\ \end{array} \tag{2}\] \[\mbox{s.t.}A_{+}(w)=\eta_{+}(w_{\rm max}-w),A_{-}(w)=\eta_{-}(w-w_{ \rm min})\] where \(\Delta t=t_{\rm post}-t_{\rm pre}\) is the time difference between the post-synaptic spike and the presynaptic one, with synaptic time-constant \(\tau_{\pm}\).The RSNN is made of three layers: (1) an input encoding layer (\(\mathcal{I}\)), (2) a recurrent spiking layer (\(\mathcal{R}\)), and (3) an output decoding layer (\(\mathcal{O}\)). The recurrent layer consists of excitatory and inhibitory neurons, distributed in a ratio of \(N_{E}:N_{I}=4:1\). The PSPs of post-synaptic neurons produced by the excitatory neurons are positive, while those produced by the inhibitory neurons are negative. We used a LIF neuron model and trained the model using STDP rules. Fig. 2 shows an RSNN with LIF neurons and STDP synapses. **Randomly Distributed Embedding (RDE)** algorithm was proposed by Ma et al. [11] to accurately predict future states based on short-term high-dimensional data. RDE accurately predicts future dynamics based on short-term high-dimensional data. To compensate for the limited number of time points, the RDE framework creates the distribution of information from the interactions among high-dimensional variables. Thus, instead of roughly predicting a single trial of future values, RDE achieves accurate prediction using the distribution information. The RDE framework randomly generates sufficient low-dimensional non-delay embeddings from the observed data of high-dimensional variables. Each of these non-delay embeddings is then mapped to a delay embedding constructed from the data of the target variable. A target variable is a variable that we aim to predict using the RDE framework. Any of these mappings can perform as a low-dimensional weak predictor for future state prediction, and all such mappings generate a distribution of predicted future states. This distribution patches all pieces of association information from various embeddings into the complete dynamics of the target variable. After being operated by appropriate estimation strategies, it creates a stronger predictor for achieving prediction in a more reliable and robust form. Our proposed method performs the RDE-based state-space reconstruction method shown in Fig. 1 every time the batch error crosses some threshold. We use two metrics to calculate batch error: the RMSE error between the predicted and the observed time series and the Wasserstein distance between the persistent homologies of the two \(d_{W,1}(\hat{p}_{H},p_{H})\), hereafter denoted as \(d_{W}\). The details about the two loss metrics are further discussed in Section III-B. ### _Topological Data Analysis and Persistent Homology:_ Topological Data Analysis (TDA) [23] uses information from topological structures in complex data for statistical analysis and learning to identify shape-like structures in data. This paper uses a mathematical tool used in TDA called persistent homology, a part of the computational topology that converts data into simplicial complexes. A simplicial complex is a space with a triangulation. Formally, a simplicial complex \(K\) in \(\mathbb{R}^{n}\) is a collection of simplices in \(\mathbb{R}^{n}\) such that (i) every face of a simplex of \(K\) is in \(K\), and (ii) the intersection of any two simplices of \(K\) is a face of each of them. Thus, persistent homology computes the birth and death of such topologies via a persistence diagram. The procedure to compute persistent homology associated with the input point cloud data set involves the construction of filtration of simplicial complexes, ordered with respect to some resolution (scaling) parameter. A topological feature that persists for a more extensive range of scales is a significant one. An important reason why we use persistent homology is that it does not require an artificial cutoff between signal and noise since all topological features from the data are preserved, and weights are assigned according to their persistence. The output of this filtration procedure generates the persistence diagram. In the persistence diagram, the two coordinates of each point represent the birth value and the death value of a k-dimensional hole. A key property of persistent homology is that both persistence diagrams are robust under perturbations of the underlying data. The shift in the persistence diagram is directly proportional to any change in the dataset. These properties are leveraged for developing statistical methods for data analysis using persistent homologies. TDA provides a new type of analysis that complements standard statistical measures like RMSE. We use TDA to study the shape of the time series data by calculating \(d_{W}\) to detect and quantify topological patterns that appear in multidimensional time series [24]. Following the works of Gidea et al. [24], we apply TDA methods to explore the temporal behavior of topological features in the dynamical system time series data Fig. 2: Figure showing the Recurrent Spiking Neural Network with LIF neurons and STDP synapses. The inset figures show the dynamics of the LIF neurons and the STDP weight dynamics. as the state of the dynamical system evolves. Using a sliding window, we extract time-dependent point cloud data sets to which we associate a topological space. We detect transient loops in this space and measure their persistence, encoded in real-valued functions called a persistence landscape. ## III Methods ### _General Framework_ There are many components in the unsupervised online learning methodology. Figure 1 visualizes the complete data flow of the model to be implemented. First, the evolving time series is derived by projecting the Lorenz63 (L63) dynamical system [25] onto a single axis. The L63 system works in four modes: fixed point, chaos, limit cycle, and normal. Further details about the L63 dynamical system are given in Section IVa. We consider the underlying dynamical system shifting from one mode of operation to another to result in an evolving time series as depicted in Fig. 4(a). This time series is then fed as input into a layer of encoder neurons for converting the signal into spikes using a temporal encoding scheme. These spike trains are given as input to the recurrent spiking neural network (RSNN), which is trained continually using spike timing dependent plasticity rule (STDP) [9, 10]. Hence, we use the CS-HiBet method [26] to efficiently detect top-k nodes in networks with the highest \(\mathcal{C}_{b}\). CS-HiBet can perform as a distributed algorithm by using only the local information at each node, which makes it highly scalable. We record the membrane potential of these K nodes and reconstruct the underlying dynamical system from this data using random delay embedding (RDE) [11] from which we get the final predictions. **Encoder** encodes the time series data into a spike train. For this paper, we use a population Poisson encoder, i.e., each value of the continuous input time series signal is converted into a series of spike trains. The signal must be represented as spikes for the RSNN to process our time series to higher dimensional output. The spikes are only generated whenever the signal changes in value. This paper uses a temporal encoding mechanism to represent the signals efficiently. We implement the encoding mechanism based on the Step-Forward (SF) algorithm [27]. The property of temporal encodings to transfer required information faster than rate encoding can be helpful for online learning. Online adapting models that have to make quick decisions based on changes in the environment benefit most from temporal encoding. **Neuron Sampling:** The proposed algorithm is based on the hypothesis that the RSNN captures the dynamics of the underlying system from the observed input time series data. Thus, a reconstruction of the dynamical system from the neuron states can predict the future states of the dynamical system. In this work, we use a neuron sampling algorithm based on \(\mathcal{C}_{b}\) and select the neurons with the highest information flow. \(\mathcal{C}_{b}\) is used to detect the degree of influence a node has over the flow of information in a network and to find nodes that serve as a bridge between two different parts of the network. Hence, we can interpret the nodes with high \(\mathcal{C}_{b}\) similar to the bottleneck layer neurons in an autoencoder that showcase a lower-dimensional embedding of the higher-dimensional input space. \(\mathcal{C}_{b}\) measures the proportion of shortest paths in the network passing through a specific node. This is the fraction of times a node acts as a bridge in transferring valuable information between any pair of nodes along their shortest paths within the network. Hence, \(\mathcal{C}_{b}\) is correlated to the nodes' importance from an information-flow standpoint in the network. Following previous works [28], we define \(\mathcal{C}_{b}\) of node \(u\in V\) as: \(\mathcal{C}_{b}=\sum_{v,w,v\neq w}\frac{\sigma_{vw}(u)}{\sigma_{vw}}\), where \(\sigma_{vw}\) is the total number of shortest paths between every \(v,w\in V,v\neq w\), and \(\sigma_{vw}(u)\) is the number of such paths that pass through \(u\). **Decoder** We take the membrane potential outputs of the sampled nodes and feed them into the decoder to output a high-dimensional time series. To represent the RSNN state \(r(t)\), we take the sum of all the spikes \(s\) over the last \(\tau\) time steps into account. \(r_{i}^{M}(t)=\sum_{n=0}^{\tau}\gamma^{n}s_{i}(t-n)\quad\forall i\in E\). By definition, this is an exponentially decreasing rate of decoding using a sliding window. A time series that is highly volatile in a short time frame requires the decoder to react fast to the changes. The parameters \(\tau\) and \(\gamma\) are balanced to optimize the memory size of the stored data and its containment of information, including adjusting \(\tau\) to the pace at which the temporal data is presented processed. Since we model a continually evolving system, we chose the values of \(\tau\leq 50\) and \(\gamma^{\tau-1}\geq 0.1\). ### _Real-time Error Computation_ We note that the reconstruction of the dynamical system is done every time some loss metric between the predicted and observed time series exceeds some threshold. A more frequent reconstruction would make a system inefficient and prone to noise and outliers. For the experiments, we used an RSNN with 5000 LIF neurons and a synapse connectivity probability of 20%. However, though the model was the same for all the simulations, we used two different loss functions for reconstructions as follows: **RMSE-CLURSNN:** We use the RMSE loss as a metric to evaluate the loss between the predicted and the observed time series. The RMSE loss is given as \(\text{RMSE}=\sqrt{\frac{1}{n}\sum_{i=1}^{n}\left(y_{i}-\hat{y}_{i}\right)^{2}}\) where \(y\) is the observed time series and \(\hat{y}\) is the predicted time series. We calculate the RMSE loss on a rolling window of the observed and predicted time series. **Wass-CLURSNN:** Though the standard RMSE error is an efficient loss metric, it fails to capture whether the predicted time series successfully captures the _shape_ of the data. When using RMSE, we can get a high value even though the predicted time series captures the structure of the data. Since we aim to reconstruct the underlying dynamical system, we are more interested in whether we can capture the dynamics successfully, which might lead to an amplified or time-shifted prediction. Though these types of distortions do not change the fact that the model has successfully learned the underlying model, it leads to a high RMSE loss, which is undesirable. Hence, to bypass this problem, we introduce a novel loss metric in this paper. We introduce \(d_{W}\) as an alternate loss metric instead of the standard RMSE error. As described before, the persistent homologies capture the topological features of the data and not just the point values, unlike RMSE. \(d_{W}\) is calculated on a rolling time window. The detailed procedure for calculating \(d_{W}\) is shown in Fig. 3. A persistence diagram is a multiset of points in the extended plane, \(\overline{\mathbb{R}}^{2}\). Let \(X\) and \(Y\) be two persistence diagrams. To define the distance between them, we consider bijections \(\eta:X\to Y\) and take the sum of \(q\)-th powers of the \(L_{\infty}\)-distances between corresponding points, and minimize overall bijections. Measuring the distance between points \(x=(x_{1},x_{2})\) and \(y=(y_{1},y_{2})\) as \(\|x-y\|_{\infty}=\max\left\{|x_{1}-y_{1}|,|x_{2}-y_{2}|\right\}\) and taking the infimum over all bijections, we get the q-Wasserstein distance \[d_{W:q}\text{ as: }d_{W,q}(X,Y)=\left[\inf_{\eta:X\to Y}\sum_{x\in X}\|x- \eta(x)\|_{\infty}^{q}\right]^{1/q}.\] The RSNN model is kept the same for either case; hence, the learning procedure does not change. We only use the error function as a metric for efficient reconstruction of the dynamical system attractor space based on the sampled nodal observations of the RSNN. ## IV Experiments ### _Dataset_ _Synthetic: Evolving Lorenz63 (L63) System:_ We study an evolving Lorenz system using the RSNN models. The classical three-dimensional L63 attractor [25] was the first example of a low-dimensional system with chaotic solutions. The following differential equations describe the L63 system: \[\frac{\mathrm{d}x}{\mathrm{d}t}=\sigma(y-x),\frac{\mathrm{d}y}{\mathrm{d}t}= x(\rho-z)-y,\frac{\mathrm{d}z}{\mathrm{d}t}=xy-\beta z \tag{3}\] We consider four different types of behavior of the L63 system depending on the parameter values: * _Fixed Points_ (F.P) (\(\rho=60,\sigma=20,\beta=8\)) * _Chaos_ (\(\rho=36,\sigma=8.5,\beta=3.5\)) * _Limit Cycles_ (L.C.) (\(\rho=35,\sigma=21,\beta=1\)) * _Normal_ (\(\rho=28,\sigma=10,\beta=2.66\)) _Real-world Datasets:_ [29] The YReal time series is the real-world timeseries from the A1Benchmark data in Yahoo's S5 dataset. We use the time series in A4Benchmark containing synthetic outliers and change points. The time series represents the metrics of various Yahoo services with different change points and outliers. Since our model is learning from streaming data, the model's performance on outliers can help us determine the robustness of the methods. **Dow Jones Industrial Average:** We use the daily index of the Dow Jones Industrial Average (DJIA) from 1885-1962. ### _Methodology_ **Baselines DNN Model:** We compare the performance of the novel SNN-based unsupervised learning methodology with a supervised DNN-based online learning model. We choose the conventional real-time current learning (RTRL) of LSTM neural networks [30], henceforth called online DNN. It updates the network using the newly available data without considering the change points. The online DNN model uses a stochastic gradient descent (SGD) based method to learn the model from the streaming time series. With new observations, the model parameters are updated online according to the gradients of the loss of the newly available data. Online DNN explores the local features of time series to weigh the learning method's gradients with the local data's distributional properties. In particular, if a newly available observation is a potential outlier behaving differently from the regular patterns, the corresponding gradient will be down-weighted to avoid abruptly leading the online model to drift from the underlying patterns. ### _Results_ **Prediction Performance:** We compare the online prediction performances of the RSNN models with the baseline DNN models. Fig. 4(b) shows the prediction results of the Wass-CLURSNN, RMSE-CLURSNN, and the online DNN models compared to the observed time series. The Wass-CLURNN can follow the evolving system better than the other two models. The online DNN model shows the worst convergence among the three. These results are further validated by the plot of RMSE and \(d_{W}\) shown in Fig. 4(c, d), respectively. From these plots, we see that the Wass-CLURSNN performs the best and converges the fastest among the three, while the online DNN, i.e., the LSTM model, performs the worst and converges the slowest. It is to be noted here that the RMSE and \(d_{W}\) are calculated here on a rolling window of 30 timesteps. **Adaptation to Timeseries with Sinusoidal Trend:** We evaluate the rate at which the different methods used in this paper can adapt to a changing dynamical system. To make the system more complex and study this adaptation behavior further, we use a sinusoidal signal as a trend line for the time series from the L63 system sinusoidal oscillating within a sinusoidal function. We call this process the _sinusoidal trend of the time series_. The frequency of the trendline sinusoidal signal determines the time series' evolution rate, where a higher frequency (smaller Time period) implies the time series changes rapidly and the model needs to adapt more quickly to the changing system. Studying the prediction performance of the three models (Wass-CLURSNN, RMSE-CLURSNN, and online Fig. 3: Block Diagram showing the computation of Wasserstein Distance between the persistent homologies of the observed and the predicted time series DNN) on this sine-modulated L63 time series, we test how each of these models can adapt to changing dynamical systems. Fig 4(e) shows an instance of the first 300 timesteps of the sine-modulated time series. The figure shows where the L63 system in the fixed point mode is modulated using a sine wave of the time period of 300 timesteps and an amplitude of 3. Table I shows the average RMSE and average \(d_{W}\) for each of the three methods. The mean and standard deviation are taken over each of the four modes of operation. First, we report the baseline case for an unmodulated time series. We also give the results of sine-waves with periods of 100, 300, and 500 with amplitude of 3 and 5 for each case. The results are summarized in Table I. We see that Wass-CLURSNN outperforms RMSE-CLURSNN and online DNN models. **Memory Retention and Convergence:** We know that the time series constitutes four different modes of operation of the L63 dynamical system. The time series observed for these different modes of operation is shown in Fig. 4(a). Let us denote Fig. 4: (a) Fig showing the four modes of operation of the L63 dynamical system. Each mode has 300 timesteps. (b) The predicted and the observed time series data for the three models compared in the paper - RMSE-CLURSNN, Wass-CLURSNN, and online DNN. (c) The RMSE loss between the predicted and the observed time series computed in a rolling time window of 30 timesteps for the three models (d) \(d_{W}\) of the three models (e) The predicted and observed time series of the time series with a sinusoidal trend. We only show the first 300 timesteps (corresponding to the FP of the L63 System). A similar process was repeated for the other three modes of operation. these behaviors as \(a^{x}\) where \(x\) can be \(FP=\)Fixed Point, \(C\)= Chaotic, \(LC\)=Limit cycles, \(N\)= Normal. Also, let us denote the prediction time series as \(a_{n}\). We say that \(a_{n}\) has converged to a value L if \(\forall\varepsilon>0\exists N\) such that \(n\geq N\Rightarrow|a-L|<\varepsilon\). For our simulations, we fix the value of \(\varepsilon=0.1\). We use a single training epoch for the supervised models to keep the results comparable to unsupervised SNN models. Hence, to see how the convergence behavior changes when the same input is repeated, we perform the following experiment: since each iteration constitutes four modes of operation, we take 300 timesteps of each mode and calculate the number of timesteps the models require to converge for each mode. Let the number of timesteps required for iteration \(i\) for mode \(x\) by the model \(\mathcal{M}\) be denoted by \(T_{x}^{i}(\mathcal{M})\). Hence, we compare the average of the number of timesteps required to converge over all the modes of operation for each iteration, i.e., \(\sum_{x}T_{x}^{i}(\mathcal{M})\). The results are plotted in Fig. 5. The figure shows that the Wass-CLURSNN outperforms the other methods in the first few iterations and converges the fastest. We also see that the online DNN model performs the worst among the three, indicating that when training, the DNN-based model requires more training samples to converge compared to the unsupervised RSNN-based models. However, as the number of iterations increases, the online DNN takes much fewer timesteps. From this observation, we can infer that DNN-based models can converge much faster once the models are fully trained. Thus, the DNN-based models fail when the underlying dynamical system is fast evolving and there is not a lot of data available, and that is when the RSNN-based models perform the best. Thus, these two models have two separate regions of operations. **Node Sampling:** We evaluate the model's performance using all the neurons in the recurrent layer compared to the case when we are sampling neurons based on \(\mathcal{C}_{b}\). As discussed earlier, the nodes are sampled according to the ones with the highest \(\mathcal{C}_{b}\)[26]. We calculate these two types of predictions' average RMSE and average \(d_{W}\). We calculate the mean and standard deviations over the four modes of operation of the L63 system. The results are summarized in Table II. We observe that both the models perform better and converge faster, with lesser standard deviation when using the sampled neurons than all the neurons in the recurrent layer. We may interpret this result as follows: since \(\mathcal{C}_{b}\) captures a node's role in allowing information to pass from one part of the network to the other, it behaves like the bottleneck layer in an autoencoder. Hence sampling neurons with the highest \(\mathcal{C}_{b}\), we can better capture the dynamical system's latent dynamics, leading to better performance. \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline \multirow{2}{*}{**MetricModel**} & \multicolumn{2}{c|}{**RMSE-CLURSNN**} & \multicolumn{2}{c|}{**Wass-CLURSNN**} \\ \cline{2-5} & _All_ & _Sampled_ & _All_ & _Sampled_ \\ & _Neurons_ & _Neurons_ & _Neurons_ & _Neurons_ \\ \hline _RMSE_ & \(0.544\) & \(0.324\) & \(0.411\) & \(0.206\) \\ (Mean \(\pm\) Std. Deviation) & \(\pm 0.112\) & \(\pm 0.021\) & \(\pm 0.132\) & \(\pm 0.02\) \\ \hline _Wasserstein Distance_ & \(0.457\) & \(0.301\) & \(0.351\) & \(0.166\) \\ (Mean \(\pm\) Std. Deviation) & \(\pm 0.854\) & \(\pm 0.015\) & \(\pm 0.773\) & \(\pm 0.013\) \\ \hline _Timestes to Convergence_ & \(178.39\) & \(135.45\) & \(153.15\) & \(117.38\) \\ (Mean \(\pm\) Std. Deviation) & \(\pm 46.75\) & \(\pm 29.68\) & \(\pm 41.34\) & \(\pm 27.32\) \\ \hline \end{tabular} \end{table} TABLE II: Table comparing the RMSE loss, \(d_{W}\) and Timesteps required to converge for (i)RMSE-CLURSNN and (ii)Wass-CLURSNN using all the neurons in the recurrent layer vs. sampling neurons with highest \(\mathcal{C}_{b}\). The experiment was repeated for the 4 modes of operation of L63 system, and the mean and standard deviation is calculated from these observations. \begin{table} \begin{tabular}{|c|c|c|c|c|c|c|c|} \hline \multirow{2}{*}{ \begin{tabular}{c} **Trendline** \\ **Sine Amplitude** \\ **(A)** \\ \end{tabular} } & \multicolumn{2}{c|}{**RMSE-CLURSNN**} & \multicolumn{2}{c|}{**Wass-CLURSNN**} & \multicolumn{2}{c|}{**online DNN**} \\ \cline{2-9} & \multicolumn{1}{c|}{**Sine**} & \multicolumn{1}{c|}{**Average**} & \multicolumn{1}{c|}{**Average**} & \multicolumn{1}{c|}{**Average**} & \multicolumn{1}{c|}{**Average**} & \multicolumn{1}{c|}{**Average**} \\ \cline{2-9} & \multicolumn{1}{c|}{**Time Period**} & \multicolumn{1}{c|}{**RMSE**} & \multicolumn{1}{c|}{\(d_{W}\)} & \multicolumn{1}{c|}{**RMSE**} & \multicolumn{1}{c|}{\(d_{W}\)} & \multicolumn{1}{c|}{**RMSE**} & \multicolumn{1}{c|}{\(d_{W}\)} \\ \hline **0** & **-** & \(0.324\pm 0.021\) & \(0.301\pm 0.015\) & \(0.206\pm 0.02\) & \(0.166\pm 0.013\) & \(0.913\pm 0.064\) & \(0.628\pm 0.044\) \\ \hline \multirow{3}{*}{**3**} & **100** & \(0.615\pm 0.037\) & \(0.352\pm 0.019\) & \(0.441\pm 0.031\) & \(0.198\pm 0.013\) & \(1.554\pm 0.11\) & \(0.954\pm 0.067\) \\ \cline{2-9} & **300** & \(0.596\pm 0.031\) & \(0.326\pm 0.014\) & \(0.322\pm 0.024\) & \(0.183\pm 0.011\) & \(1.388\pm 0.094\) & \(0.799\pm 0.051\) \\ \cline{2-9} & **500** & \(0.357\pm 0.025\) & \(0.311\pm 0.011\) & \(0.217\pm 0.019\) & \(0.174\pm 0.01\) & \(1.068\pm 0.075\) & \(0.701\pm 0.042\) \\ \hline \multirow{3}{*}{**5**} & **100** & \(0.719\pm 0.053\) & \(0.434\pm 0.021\) & \(0.507\pm 0.048\) & \(0.276\pm 0.019\) & \(1.994\pm 0.139\) & \(0.973\pm 0.061\) \\ \cline{2-9} & **300** & \(0.655\pm 0.049\) & \(0.388\pm 0.019\) & \(0.389\pm 0.044\) & \(0.221\pm 0.016\) & \(1.635\pm 0.111\) & \(0.882\pm 0.598\) \\ \cline{1-1} \cline{2-9} & **500** & \(0.433\pm 0.032\) & \(0.335\pm 0.016\) & \(0.294\pm 0.029\) & \(0.195\pm 0.014\) & \(1.121\pm 0.079\) & \(0.866\pm 0.554\) \\ \hline \end{tabular} \end{table} TABLE I: Table comparing the performances of the three models - RMSE-CLURSNN, Wass-CLURSNN, and online DNN when using different sine-modulated time series of the evolving L63 dynamical system. The experiment is repeated for each of the four modes of operation, and the mean and standard deviation are calculated from these observations. Fig. 5: Figure compares the convergence ability of the three models over repeated iterations of the same input. The convergence is calculated using the mean number of timesteps required for the model to converge in each case. The experiment was repeated for each of the four modes of operation of the L63 system, and the mean and standard deviation from these observations are plotted. We use the log-scale value for the y-axis. **Performance on Real-world Datasets:** We compared the performances of the different models on some real-world datasets like YReal, and DJIA (as described above). The results are tabulated in Table III. The proposed methods RMSE-CLURSNN and Wass-CLURSNN outperform the other supervised DNN models. ## V Conclusions This paper proposes a novel methodology for online prediction of the time series from an evolving dynamical system using a completely unsupervised bio-plausible recurrent spiking neural network model trained with spike-timing-dependent plasticity. We leveraged recent works on topological data analysis and embedding theory to develop a new methodology for continuous reconstruction of the underlying dynamical system based on membrane potential measurements of nodes in the RSNN with the highest betweenness centrality, which behaves similarly to the bottleneck layer in an autoencoder. We proposed the RMSE-CLURSNN and the Wass-CLRSSNN model, where the prediction error is calculated using the RMSE error and the Wasserstein distance between the persistent homologies of the predicted and observed time series \(d_{W}\), respectively. We compared this new methodology's performance and convergence behavior with the online DNN model. We observed that the proposed method outperforms the standard DNN model in terms of prediction performance and convergence for an evolving dynamical system with few data points for training. However, with repeated iterations, we see that DNN-based models converge faster and show better performance. Thus, these DNN models need a large amount of data to learn. RSNN-based models, on the other hand, can adapt very quickly to changing environments. ## Acknowledgement This work is supported by the Army Research Office and was accomplished under Grant Number W911NF-19-1-0447. The views and conclusions contained in this document are those of the authors and should not be interpreted as representing the official policies, either expressed or implied, of the Army Research Office or the U.S. Government.
2306.00707
Renormalized Graph Neural Networks
Graph Neural Networks (GNNs) have become essential for studying complex data, particularly when represented as graphs. Their value is underpinned by their ability to reflect the intricacies of numerous areas, ranging from social to biological networks. GNNs can grapple with non-linear behaviors, emerging patterns, and complex connections; these are also typical characteristics of complex systems. The renormalization group (RG) theory has emerged as the language for studying complex systems. It is recognized as the preferred lens through which to study complex systems, offering a framework that can untangle their intricate dynamics. Despite the clear benefits of integrating RG theory with GNNs, no existing methods have ventured into this promising territory. This paper proposes a new approach that applies RG theory to devise a novel graph rewiring to improve GNNs' performance on graph-related tasks. We support our proposal with extensive experiments on standard benchmarks and baselines. The results demonstrate the effectiveness of our method and its potential to remedy the current limitations of GNNs. Finally, this paper marks the beginning of a new research direction. This path combines the theoretical foundations of RG, the magnifying glass of complex systems, with the structural capabilities of GNNs. By doing so, we aim to enhance the potential of GNNs in modeling and unraveling the complexities inherent in diverse systems.
Francesco Caso, Giovanni Trappolini, Andrea Bacciu, Pietro Liò, Fabrizio Silvestri
2023-06-01T14:16:43Z
http://arxiv.org/abs/2306.00707v1
# Renormalized Graph Neural Networks ###### Abstract Graph Neural Networks (GNNs) have become essential for studying complex data, particularly when represented as graphs. Their value is underpinned by their ability to reflect the intricacies of numerous areas, ranging from social to biological networks. GNNs can grapple with non-linear behaviors, emerging patterns, and complex connections; these are also typical characteristics of complex systems. The renormalization group (RG) theory has emerged as the language for studying complex systems. It is recognized as the preferred lens through which to study complex systems, offering a framework that can untangle their intricate dynamics. Despite the clear benefits of integrating RG theory with GNNs, no existing methods have ventured into this promising territory. This paper proposes a new approach that applies RG theory to devise a novel graph rewiring to improve GNNs' performance on graph-related tasks. We support our proposal with extensive experiments on standard benchmarks and baselines. The results demonstrate the effectiveness of our method and its potential to remedy the current limitations of GNNs. Finally, this paper marks the beginning of a new research direction. This path combines the theoretical foundations of RG, the magnifying glass of complex systems, with the structural capabilities of GNNs. By doing so, we aim to enhance the potential of GNNs in modeling and unraveling the complexities inherent in diverse systems. ## 1 Introduction Graph Neural Networks (GNNs) have emerged as a powerful tool for analyzing and modeling complex relational data. Unlike traditional neural networks that operate on grid-like structures such as images (Li et al., 2021) or sequences (Vaswani et al., 2017), GNNs are designed specifically for data represented as graphs. Graphs are mathematical structures composed of nodes (representing entities) and edges (representing relationships or connections between entities). Examples of graph-structured data abound in various domains, including social networks, citation networks, biological networks, and recommendation systems Zhang et al. (2019); Eraslan et al. (2019); Zhou et al. (2020). GNNs have gained significant attention in recent years due to their ability to effectively capture and exploit the inherent structural information encoded within graphs. They extend traditional neural networks by incorporating graph-based operations, allowing them to learn from both the node attributes and the underlying graph topology. This enables GNNs to model complex relationships (systems), propagate information between interconnected nodes, and make predictions or classifications based on the learned representations (Kipf and Welling, 2016; Velickovic et al., 2017). The importance of GNNs lies in their versatility and broad applicability across different domains. In social network analysis, GNNs can reveal patterns of influence, community structure, and information diffusion. In biological research, GNNs have proven valuable for protein-protein interaction prediction, drug discovery, and gene expression analysis. In recommendation systems, GNNs can leverage the graph structure to capture user-item interactions, leading to more accurate personalized recommendations. This makes GNNs particularly well-suited for tasks such as node classification, link prediction, graph generation, and graph-level classification. Despite their impressive capabilities, Graph Neural Networks (GNNs) also exhibit certain limitations that the research community has been studying. Three significant challenges faced by GNNs are over-squashing, under-reaching, and over-smoothing (Alon and Yahav, 2020; Topping et al., 2021; Di Giovanni et al., 2023; Rusch et al., 2023). Over-squashing refers to the phenomenon where the GNN is unable to propagate information between distant nodes due to the fixed size of the hidden representation. Under-reaching, on the other hand, refers to the limited ability of GNNs to effectively capture and propagate information across dependencies whose range is higher than the number of GNN layers. Finally, Oversmoothing is the tendency to get similar representations between different nodes when using a high number of GNN layers. Research on overcoming GNNs' limitations is critical, as GNNs' ability to effectively capture and analyze graph-structured data makes them a valuable tool for modeling and understanding complex systems. Complex systems, i.e., systems composed of many interacting components, exist in various domains such as social networks, biological networks, transportation networks, and communication networks (Cavagna et al., 2010; Hidalgo, 2021). Complex systems are characterized by their non-linear dynamics, emergent behavior, and intricate interdependencies, even between different scales. This has posed significant challenges to understanding and analyzing their underlying principles, and in this context, the theory of the renormalization group (RG) has naturally emerged as a powerful language to deal with such systems (Lepage, 1989; Fisher, 1974; Delamotte, 2004). RG provides a framework for systematically studying the behavior of complex systems across multiple scales, from microscopic to macroscopic. It allows researchers to identify and analyze the relevant degrees of freedom, discard irrelevant details, and uncover the universal properties that govern the system's behavior. By employing RG techniques, researchers can gain a deeper understanding of collective behavior, tackling arduous problems like critical phenomena (Toner et al., 2018; Fisher, 1974). Surprisingly enough, even though graph neural networks aim to tract complex systems and the renormalization group has emerged as a sort of magnifying glass (even though zooming-out) for studying those same complex systems, to the best of our knowledge, there are no methods that employ renormalization group theory for graph neural networks. The aim of this paper is precisely to fill this gap. Namely, borrowing from the theory of the renormalization group, we develop a method that represents the input graph at a different granularity. Instead of being obliged to consider only the smallest granularity, where each node and edge in the graph is visible, we allow the GNN to also look at larger granularities, where nodes are grouped into clusters, and it's possible to study the relations between these clusters; in order to analyze the large-scale behavior of complex networks, such as the Internet, social networks, or biological networks. Our contributions are: (a) To the best of our knowledge, we are the first to consider renormalization group theory for graph neural networks. (b) We lay out an extensive experimental section to back our claims, proving that our method improves performance significantly on standard benchmarks and baselines. (c) Finally, we hope to lay out the foundation for a new research agenda that aims to borrow theoretical properties from the renormalization group to enhance current GNNs architectures. ## 2 Renormalization of a graph ### Background We define a graph to be \(\mathcal{G}=(\mathcal{V},\mathcal{E})\) where \(\mathcal{V}\) is the set of nodes of the graph, and \(\mathcal{E}\subseteq\mathcal{V}\times\mathcal{V}\) is the set of edges. We will consider only unweighted graphs so the set of edges can also be represented through an adjacency matrix \(A\in\mathcal{R}^{|\mathcal{V}|\times|\mathcal{V}|}\), whose elements are \[A_{ij}=\begin{cases}1&(i,j)\in\mathcal{E}\\ 0&(i,j)\notin\mathcal{E}\end{cases}. \tag{1}\] We consider the Laplacian matrix defined as \[L_{ij}=[(\delta_{ij}\sum_{k}A_{ik})-A_{ij}] \tag{2}\] where \(\delta_{ij}\) is the Kronecker delta function. The theory we propose is limited to undirected graphs and we define the neighborhood of node \(u\) to be \[\mathcal{N}_{u}=\{v|(u,v)\in\mathcal{E}\}\quad. \tag{3}\] We consider for each node \(u\in\mathcal{V}\) a vector of features \(x_{u}\in\mathbb{R}^{k}\) and, as in Velickovic (2023), we represent the multiset of all the features of neighbor nodes as \[X_{\mathcal{N}_{u}}=\{\{x_{v}|v\in\mathcal{N}_{u}\}\}\quad. \tag{4}\] We will not consider edge features or graph features. We will also limit ourselves to considering graphs with a single connected component, in order to fulfill the ergodic hypothesis. Rewiring the graph means changing the set of neighborhoods \(\{\mathcal{N}_{u}\}_{u\in\mathcal{V}}\) or, equivalently, changing the adjacency matrix. For what concerns GNNs, we recognize that the main paradigm at their basis is that of message passing and, as in Bronstein et al. (2021), we write the generic update function of a GNN as \[h_{u}=\phi(x_{u},\bigoplus_{v\in\mathcal{N}_{u}}\psi(x_{u},x_{v})) \tag{5}\] where \(\phi\) and \(\psi\) are generic neural networks and \(\bigoplus\) is a permutation-invariant aggregator. In the following, we will consider two possible aggregators for \(\bigoplus\): \(\sum\) and average. While equation 5 is exactly the message passing update rule, the attentional and convolutional ones can be obtained with a suitable definition of \(\psi(x_{u},x_{v})\): \[h_{u}=\phi(x_{u},\bigoplus_{v\in\mathcal{N}_{u}}c_{vu}\psi^{\prime}(x_{v})) \quad(\text{Convolutional}), \tag{6}\] \[h_{u}=\phi(x_{u},\bigoplus_{v\in\mathcal{N}_{u}}a(x_{u},x_{v})\psi^{\prime}(x _{v}))\quad(\text{Attentional}). \tag{7}\] Simplifying, we could also write \[h_{u}=\phi^{\prime}(x_{u},X_{\mathcal{N}_{u}}) \tag{8}\] for some function \(\phi^{\prime}\), meaning that the representation of node \(u\) is a function of the features of the node itself and of the features of the neighbor nodes. ### Real space decimation. Villegas et al. (2022, 2023) showed that information diffusion in networks can unravel clusters of nodes connected by strong information communicability at each time \(\tau\). In particular, since we are assuming the graph to be connected and undirected, we can compute the normalized sum of all the diffusion trajectories connecting node \(i\) to node \(j\): \[\rho(\tau)_{ij}=\frac{(e^{-\tau L})_{ij}}{Tr(e^{-\tau L})}\quad. \tag{9}\] Two nodes are considered to reciprocally process the same information when the sum of the diffusion trajectories between them reaches a greater than or equal value to the sum of auto-diffusion trajectories of one of the two nodes. Thus, if we define \[\rho^{\prime}_{ij}=\frac{\rho_{ij}}{\min(\rho_{ii},\rho_{jj})}\quad, \tag{10}\] the meta graph is defined as \[\zeta_{ij}=\Theta(\rho^{\prime}_{ij}-1) \tag{11}\] where \(\Theta\) is the Heaviside step function. The element \(\zeta_{ij}\) is equal to \(1\) if the nodes \(i\) and \(j\) belong to the same supernode, and is equal to \(0\) otherwise. Notice that since equation 10 is a ratio, it's not necessary to compute the denominator in equation 9. The decimation procedure in real space requires substituting each cluster of nodes, as identified by the meta graph \(\zeta\), with a single supernode whose edges are all the edges of the original constituent nodes that go outside the cluster. We call the graph composed by the supernodes the decimated graph. We call \(\mathcal{W}\) the set of supernodes, similarly to how \(\mathcal{V}\) is the set of nodes in the original graph. Let \(\mathcal{Z}_{w}\) be the set of nodes of the original graph that compose the supernode \(w\in\mathcal{W}\) in the decimated graph. Finally, let \(\mathcal{M}_{w}\) for \(w\in\mathcal{W}\) be the neighborhood of \(w\) in the decimated graph. Notice that the generic update function of a GNN, equation 5, applied to the decimated graph would yield: \[h_{w}=\phi(x_{w},\bigoplus_{v\in\mathcal{M}_{w}}\psi(x_{w},x_{v}))\quad. \tag{12}\] Similarly to equation 8, we could also write \[h_{w}=\phi^{\prime}(x_{w},X_{\mathcal{M}_{w}})\quad. \tag{13}\] Nonetheless, not only Laplacian Renormalization Group (LRG) doesn't explain how to renormalize the features of each original node into the features of the supernodes, but such a renormalization of the features should be learnable, e.g. when renormalizing a molecule, if the task is "count how many hydrogens there are", you want the features of the supernode to lose all the information unrelated to hydrogens, whilst if it is "predict its structure", you may want the renormalized features to retain some of the information from all the atoms in the supernode. Moreover, saving the information of all the original nodes in the vectors associated with their supernodes could increase over-squashing. For these reasons, we propose to use LRG from a different, almost dual, point of view. We look at the decimation procedure as a rewiring one. In fact, notice that implying that the features of the supernodes are functions of the features of their constituent original nodes, we could rewrite equation 13 as \[h_{w}=\phi^{\prime\prime}(X_{\mathcal{Z}_{w}},X_{\mathcal{Z}_{v},v\in \mathcal{M}_{w}})\quad, \tag{14}\] or equivalently \[h_{w}=\phi^{\prime\prime\prime}(x_{u,u\in\mathcal{Z}_{w}},X_{\mathcal{Z}_{w} \backslash u\cup\mathcal{Z}_{v},v\in\mathcal{M}_{w}})\quad, \tag{15}\] where \(\phi,\phi^{\prime},\phi^{\prime\prime},\phi^{\prime\prime\prime}\) are not derivatives but different functions. In this way, the update on the decimated graph can be seen as an update on a rewired graph, i.e. on a graph with a different set of neighborhoods. ### Our Rewiring In order to rewire the graph, we identify the clusters that form the supernodes of the decimated graph. Then, instead of reducing the number of nodes, we increase the number of edges. Specifically, we require all the nodes belonging to the same cluster to share the same incoming and outgoing edges (Fig. 1). This is obtained by computing a new adjacency matrix \(A^{*}\) whose columns are given by \[A^{*}_{:,i}=\Theta(\sum_{j}\zeta_{i,j}A_{:,j})\quad, \tag{16}\] and whose rows are given by \[A^{*}_{i,:}=\Theta(\sum_{j}\zeta_{i,j}A_{j,:})\quad. \tag{17}\] It's easy to see that in this way, the neighborhood of \(u\) in the rewired graph is \[\mathcal{N}^{\prime}_{u}=(\mathcal{Z}_{w}\backslash u)\cup\bigcup_{v\in \mathcal{M}_{w}}\mathcal{Z}_{v}\quad. \tag{18}\] **Theorem 2.1**: _Computing the generic GNN update function, equation 5, on a node of the rewired graph, with the aggregator \(\bigoplus\) chosen as the sum or the average operator and with \(\phi(x,y)=\sigma_{\phi}(W^{(1)}x+W^{(2)}y+b_{\phi})\) where \(\sigma_{\phi}\) is an activation function and \(W^{(1)}\) has linearly independent rows, is equivalent to computing a GNN update function on a node of the decimated graph._ The proof of the theorem is given in the supplementary material, see Appendix A, but intuition is given by the fact that equation 8 becomes equation 15: this means that the representation of node \(u\) depends on the features of node \(u\) itself, the features of the other nodes that are in the same supernode and the features of the nodes that compose the neighbor supernodes. Theorem 2.1 means that the rewiring procedure effectively allows the GNN to act as if it was looking at the decimated graph obtained through LRG when computing a node representation. Moreover, the features of the original nodes are not saved in a different vector associated with the supernode, which could have increased over-squashing. Finally, the equivalence allows us not to compute the renormalized features of the supernodes. In fact, they are implicitly represented by functions of the features of the original nodes, with some of the parameters learnable, thus allowing for task-dependent renormalization. ## 3 Experimental Setup ### Datasets We run our experiments on the following datasets: We use the _Cora_ dataset (McCallum et al., 2000), which contains 2708 scientific publications. These publications are classified into one of seven classes, and the citation network contains 5429 links. Each publication in the dataset is described by a 0/1-valued word vector indicating the absence or presence of the corresponding word from the dictionary. The dictionary comprises 1433 unique words. The _PubMed_ dataset (Namata et al., 2012) is another source we test on. This set includes 19717 scientific publications from the PubMed database, all of which are related to diabetes and are classified into one of three classes. The citation network here consists of 44338 links, and each publication in the dataset is described by a Term Frequency-Inverse Document Frequency (TF-IDF) word vector from a dictionary of 500 unique words. We are also utilizing the _Citeseer_(Giles et al., 1998) dataset, which encompasses 3327 scientific publications classified into six classes. The citation network has 4732 links. Each publication in the dataset is described by a binary word vector indicating the absence or presence of the corresponding word from the dictionary, which consists of 3703 unique words. Finally, we are using the _Amazon Photo_ dataset (McAuley et al., 2015; Shchur et al., 2018). This is a subset of the Amazon co-purchase graph that contains 7650 products with 119043 edges. Each Figure 1: A visualization of the proposed rewiring procedure. The nodes of the original graph, left, are clustered in three supernodes, center. The graph is rewired in such a way that nodes in the same supernode share the same incoming and outgoing edges, right. product in the dataset is described by a bag-of-words encoding of its reviews. The graph is formed based on the "Also Bought" feature on Amazon, where an edge from item A to item B implies that item A is frequently co-purchased with item B. ### Model During our testing process, we utilize a 2-layer graph encoder, e.g, GCN (Kipf and Welling, 2016) and GAT (Velickovic et al., 2017), as the fundamental architecture. Building upon this foundation, we create multiple variations. Specifically, we develop two configurations: one referred to as "dual" and the other as "mono". In the "mono" case, we input a single graph, whether it has been rewired or not, into the network. Instead, to encode the graphs at two different scales, we propose the "dual" setting, where we feed two graphs into the network: one that has been renormalized and another that remains unchanged, or twice the latter in the vanilla setting. The information from both graphs is then combined to generate the final prediction. To train our model, we do not perform hyperparameter tuning, and we opt instead for standard values used in the literature. In fact, we use the Categorical Cross-Entropy, Adam Optimizer (Kingma and Ba, 2014), with a standard learning rate of 0.0001, over 200 epochs, using the highest accuracy achieved on the validation set as our checkpointing strategy. We perform our experiments on a workstation equipped with an Intel Core i9-10940X (14-core CPU running at 3.3GHz) and 256GB of RAM, and a single Nvidia RTX A6000 with 48GB of VRAM. ### Methods We compare our method against Graph Diffusion Convolution (GDC) (Gasteiger et al., 2019). GDC substitutes the adjacency matrix with one obtained through a generalized diffusion process on graphs. We consider two generalized diffusion processes, presented in (Gasteiger et al., 2019), for which closed-form solutions are available: Personalized PageRank (PPR) and the heat kernel diffusion. GDC proposes to substitute the adjacency matrix with a sparsified version of \(S=\sum_{k=0}^{\infty}\theta_{k}T^{k}\) where \(T\) and \(\{\theta_{k}\}\) must satisfy the constraint necessary for \(S\) to converge. The set \(\{\theta_{k}\}\) is given by the chosen diffusion process, either PPR or heat kernel in our case. Notice that GDC has been shown to act like a low-pass filter, and similarly, LRG, in the approach _a la Wilson_, disregards the highest Laplacian eigenvalues and eigenvectors. ### Task & Evaluation Metrics We train, validate, and test on the task of node classification. We report the results in terms of the Accuracy metric on the (multi) node classification task for each dataset introduced in Section 3.1. We also include standard errors for the accuracy term in our results. These errors are obtained with a bootstrap procedure and, in particular, using a bias-corrected and accelerated bootstrap. ## 4 Experimental Results In this section, we present comprehensive results in terms of accuracy on four different popular benchmarks, which serve as crucial evaluation standards in the field. These benchmarks provide a rigorous testing ground for assessing the performance of various methodologies. In our investigation, we compare six different methodologies, aiming to identify the most effective approach for the given tasks. One of the methodologies we consider is the Vanilla method, which represents the plain graph at the "default" scale. This serves as our baseline for comparison. Additionally, we examine the performance of two competitor methodologies, namely Heat and PPR, as identified in the work by Gasteiger et al. (2019) on diffusion-based algorithms. To gain further insights, we explore the effects of varying scales (\(\tau\)) within our own methodology. By considering different scales, we can evaluate how our approach performs under different conditions. The results we obtained clearly demonstrate the superiority of our method across all the datasets considered. Notably, the Cora dataset exhibits the largest nominal markup, indicating the high effectiveness of our methodology in this particular case. Another intriguing observation is the variability of the optimal scale (\(\tau\)) across different datasets, in accordance with the LRG theory which states that different networks have different characteristic scales: we find that the best performing \(\tau\) value varies depending on the dataset under consideration. Furthermore, it appears that when a larger \(\tau\) produces the best performance, the Heat and PPR methodologies struggle to achieve comparable results. In light of these findings, we plan to conduct further studies to unravel the intricate connection between the time scale (\(\tau\)) and its dependence on specific datasets and tasks. This exploration will enable us to gain a deeper understanding of the underlying dynamics and uncover valuable insights for future research. Overall, our results highlight the high quality and efficacy of the proposed methodology. We observe a significant lift in performance, reaching up to 12.1%. This improvement underscores the value of our approach and its potential impact on the broader research community and related applications. ## 5 Related works Graph Neural NetworksGraph neural networks (GNNs) are a class of deep learning models designed to operate on graph data structures, such as social networks (Bruna and Li, 2017), chemical compounds (Zitnik et al., 2018; Long et al., 2020), or traffic networks (Guo et al., 2019; Yu et al., 2017). Unlike traditional neural networks, which operate on grid-like structures, GNNs can model complex relationships and dependencies among nodes and edges in a graph. GNNs have shown promising results in various applications, including node classification, link prediction, and graph generation. One of the most popular GNN models is the Graph Convolutional Network (GCN) proposed by Kipf and Welling (2016), which uses a localized convolutional operation to aggregate information from neighboring nodes. Other notable GNN models include GraphSAGE (Hamilton et al., 2017) and GAT (Velickovic et al., 2017), which employ different aggregation strategies and attention mechanisms to capture the graph structure. Overall, GNNs have become an active area of research in machine learning and have the potential to transform various fields that involve graph data; other than a vast field of research. For a broader perspective, we refer the reader to the following surveys Zhou et al. (2020) and Wu et al. (2020). Renormalization GroupThe Renormalization group (RG) is a powerful framework describing the change in the mathematical representation of a system when looked at different scales. RG was first introduced in quantum electrodynamics (Bethe, 1947) to remove the infinities that arise from the small-scale description of the system (we refer the reader to the following surveys Lepage (1989) and Delamotte (2004)). After its first appearance in quantum electrodynamics, the RG reached full \begin{table} \begin{tabular}{l c c c c} \hline \hline & \multicolumn{4}{c}{**Datasets**} \\ **Method** & **Cliteseer** & **Cora** & **Photo** & **Pubmed** \\ \hline Vanilla & 0.683 \({}^{\star}\)\(\pm\) 0.004 & 0.739 \({}^{\dagger}\)\(\pm\) 0.005 & 0.942 \({}^{\dagger}\)\(\pm\) 0.005 & 0.738 \({}^{\dagger}\)\(\pm\) 0.002 \\ Vanilla (dual) & 0.683 \({}^{\dagger}\)\(\pm\) 0.004 & 0.728 \({}^{\dagger}\)\(\pm\) 0.005 & 0.947 \({}^{\star}\)\(\pm\) 0.005 & 0.752 \({}^{\star}\)\(\pm\) 0.002 \\ Heat & 0.725 \({}^{\star}\)\(\pm\) 0.005 & 0.790 \({}^{\star}\)\(\pm\) 0.006 & 0.939 \({}^{\star}\)\(\pm\) 0.005 & 0.738 \({}^{\star}\)\(\pm\) 0.002 \\ Heat (dual) & 0.719 \({}^{\dagger}\)\(\pm\) 0.005 & 0.790\({}^{\star}\)\(\pm\) 0.006 & **0.948 \({}^{\star}\)\(\pm\)** 0.005 & 0.762 \({}^{\star}\)\(\pm\) 0.002 \\ PPR & 0.722 \({}^{\star}\)\(\pm\) 0.005 & 0.745 \({}^{\dagger}\)\(\pm\) 0.005 & 0.941\({}^{\star}\)\(\pm\) 0.005 & 0.740 \({}^{\star}\)\(\pm\) 0.002 \\ PPR (dual) & 0.728 \({}^{\dagger}\)\(\pm\) 0.005 & 0.780 \({}^{\star}\)\(\pm\) 0.006 & 0.944\({}^{\star}\)\(\pm\) 0.005 & 0.764 \({}^{\star}\)\(\pm\) 0.002 \\ \hline **Ours** (\(\tau\)-1) & 0.681 \({}^{\dagger}\)\(\pm\) 0.004 & 0.746 \({}^{\dagger}\)\(\pm\) 0.005 & 0.811 \({}^{\dagger}\)\(\pm\) 0.004 & 0.778 \({}^{\dagger}\)\(\pm\) 0.002 \\ **Ours** (\(\tau\)-1) (dual) & 0.716 \({}^{\dagger}\)\(\pm\) 0.005 & 0.766 \({}^{\star}\)\(\pm\) 0.005 & 0.944 \({}^{\star}\)\(\pm\) 0.005 & **0.781 \({}^{\star}\)\(\pm\)** 0.002 \\ **Ours** (\(\tau\)-2) & 0.707 \({}^{\star}\)\(\pm\) 0.004 & 0.750 \({}^{\dagger}\)\(\pm\) 0.005 & 0.768 \({}^{\dagger}\)\(\pm\) 0.003 & 0.767 \({}^{\star}\)\(\pm\) 0.002 \\ **Ours** (\(\tau\)-2) (dual) & **0.731**\({}^{\dagger}\)\(\pm\) 0.005 & 0.774 \({}^{\dagger}\)\(\pm\) 0.006 & **0.948 \({}^{\star}\)\(\pm\)** 0.005 & 0.773 \({}^{\star}\)\(\pm\) 0.002 \\ **Ours** (\(\tau\)-4) & 0.709 \({}^{\star}\)\(\pm\) 0.004 & 0.693 \({}^{\dagger}\)\(\pm\) 0.004 & 0.717 \({}^{\dagger}\)\(\pm\) 0.002 & 0.752 \({}^{\star}\)\(\pm\) 0.002 \\ **Ours** (\(\tau\)-4) (dual) & 0.726 \({}^{\dagger}\)\(\pm\) 0.005 & **0.818 \({}^{\star}\)\(\pm\)** 0.006 & **0.948 \({}^{\star}\)\(\pm\)** 0.005 & 0.775 \({}^{\star}\)\(\pm\) 0.002 \\ \hline \hline \end{tabular} \end{table} Table 1: We report results on 6 different methodologies and 4 popular dataset benchmarks. Results are reported in terms of accuracy on the multi-classification task. We also provide bootstrapped confidence intervals for the results. As the experimental results indicate, our rewiring procedure is highly effective in terms of performance and a valid method to improve current graph neural network techniques. The \(\dagger\) symbol indicates that the result has been produced by a GAT, while the \(\star\) symbol indicates that a GCN was used. maturity with the work on continuous phase transitions by Wilson and Kogut (1974) (we refer the reader to the following survey (Fisher, 1974)). Wilson's approach was that of eliminating microscopic degrees of freedom. This was paralleled by Kadanoff's intuition (Kadanoff, 1966) that the strong correlation acting in the critical regime could allow for describing the system using blocks of the initial smaller components. Despite the challenges posed by their strong topological heterogeneity, decades later a renormalization group for complex networks was ultimately found in the Laplacian Renormalization Group (LRG) (Villegas et al., 2023, 2022). Such an approach was able to overcome the limitations of previous attempts (Garcia-Perez et al., 2018) like the impossibility to reconnect it to ordinary renormalization when applied to regular lattices. To our knowledge, the present paper is the first attempt to use LRG in combination with GNNs. Nonetheless, since RG is deeply connected with diffusion processes, it's important to remember that diffusion processes have been used as a pre-processing step in graph learning (Gasteiger et al., 2018, 2019). ## 6 Limitations Some of the limitations of the proposed procedure are difficult to overcome since the LRG theory that we used suffers from the same constraints: it requires working with undirected graphs with a single connected component. Similarly, the equivalence between the GNN update function on the rewired graph and on the decimated one was proved only for an aggregator of the \(\sum\) or average type, whilst it seems improbable that such an equivalence could be extended to aggregators of the min and max type, which as well are possible choices. We as well defined the procedure only for unweighted graphs, not considering, for example, edge features, even though this seems a problem that we could tackle in future works. Finally, what we believe is the main limitation of the proposed procedure is the fact that it increases the density of the edges, sometimes to such a degree that it requires reducing the dimensionality of the node features in order to train the models. When we faced this issue in some of the experiments, the results were obtained by reducing the dimensionality of the node features to the highest power of 2 that fitted into memory. Limiting the increase in edge density will most probably be the principal focus of future work in order to make the procedure easily implementable in practical situations. ## 7 Conclusion We propose a way of integrating the renormalization group (RG) with current GNN practices. We prove that our rewiring allows the GNN to look at the input graph with different granularities. The proposed implementation also frees from the necessity of defining a renormalization of the features, making it learnable, and it does so in such a way as not to provoke over-squashing. We experimentally verify that by "coarse-graining" the network, or reducing its complexity by grouping nodes, one can gain insights into its overall structure and behavior. This approach has been verified on different benchmarks and baselines and will allow researchers to understand how the properties of these networks change as we zoom in or out: for example helping to identify universal behaviors, where different systems exhibit similar behaviors at large scales. Our method has the potential to solve some of the GNNs' most severe limitations. In particular, we claim our method can alleviate the problems of under-reaching and over-squashing; both of them are in fact related to propagating information between distant nodes and, zooming out, we can vary the distance through the parameter \(\tau\). Furthermore, it could also be seen as a filter on the graph laplacian higher frequencies, significantly reducing the noise problem that naturally emerges in GNNs. We hope to lay out the foundation for a new research agenda that aims to borrow theoretical properties from the renormalization group to enhance current GNNs architecture but we as well believe that it could be used in many other problems of both geometric deep learning and general deep learning. ## 8 Acknowledgements This work was partially supported by projects FAIR (PE0000013) and SERICS (PE00000014) under the MUR National Recovery and Resilience Plan funded by the European Union - NextGenerationEU. Supported also by the ERC Advanced Grant 788893 AMDROMA, EC H2020RIA project "SoBigData++" (871042), PNRR MUR project IR0000013-SoBigData.it.
2307.01056
A 3 TOPS/W RISC-V Parallel Cluster for Inference of Fine-Grain Mixed-Precision Quantized Neural Networks
The emerging trend of deploying complex algorithms, such as Deep Neural Networks (DNNs), increasingly poses strict memory and energy efficiency requirements on Internet-of-Things (IoT) end-nodes. Mixed-precision quantization has been proposed as a technique to minimize a DNN's memory footprint and maximize its execution efficiency, with negligible end-to-end precision degradation. In this work, we present a novel hardware and software stack for energy-efficient inference of mixed-precision Quantized Neural Networks (QNNs). We introduce Flex-V, a processor based on the RISC-V Instruction Set Architecture (ISA) that features fused Mac&Load mixed-precision dot product instructions; to avoid the exponential growth of the encoding space due to mixed-precision variants, we encode formats into the Control-Status Registers (CSRs). Flex-V core is integrated into a tightly-coupled cluster of eight processors; in addition, we provide a full framework for the end-to-end deployment of DNNs including a compiler, optimized libraries, and a memory-aware deployment flow. Our results show up to 91.5 MAC/cycle and 3.26 TOPS/W on the cluster, implemented in a commercial 22nm FDX technology, with up to 8.5x speed-up, and an area overhead of only 5.6% with respect to the baseline. To demonstrate the capabilities of the architecture, we benchmark it with end-to-end real-life QNNs, improving performance by 2x - 2.5x with respect to existing solutions using fully flexible programmable processors.
Alessandro Nadalini, Georg Rutishauser, Alessio Burrello, Nazareno Bruschi, Angelo Garofalo, Luca Benini, Francesco Conti, Davide Rossi
2023-07-03T14:35:24Z
http://arxiv.org/abs/2307.01056v1
A 3 TOPS/W RISC-V Parallel Cluster for Inference of Fine-Grain Mixed-Precision Quantized Neural Networks ###### Abstract The emerging trend of deploying complex algorithms, such as Deep Neural networks (DNNs), increasingly poses strict memory and energy efficiency requirements on Internet-of-Things (IoT) end-nodes. Mixed-precision quantization has been proposed as a technique to minimize a DNN's memory footprint and maximize its execution efficiency, with negligible end-to-end precision degradation. In this work, we present a novel hardware and software stack for energy-efficient inference of mixed-precision Quantized Neural Networks (QNNs). We introduce Flex-V, a processor based on the RISC-V Instruction Set Architecture (ISA) that features fused _MacK.Load_ mixed-precision dot product instructions; to avoid the exponential growth of the encoding space due to mixed-precision variants, we encode formats into the Control-Status Registers (CSRs). Flex-V core is integrated into a tightly-coupled cluster of eight processors; in addition, we provide a full framework for the end-to-end deployment of DNNs including a compiler, optimized libraries, and a memory-aware deployment flow. Our results show up to 91.5 MAC/cycle and 3.26 TOPS/W on the cluster, implemented in a commercial 22nm FDX technology, with up to 8.5\(\times\) speed-up, and an area overhead of only 5.6% with respect to the baseline. To demonstrate the capabilities of the architecture, we benchmark it with end-to-end real-life QNNs, improving performance by 2\(\times\) - 2.5\(\times\) with respect to existing solutions using fully flexible programmable processors. Embedded Systems, PULP Platform, Quantized Neural Networks, Mixed-precision, Microcontroller ## I Introduction and Related Work Modern IoT applications require end-nodes to acquire raw data from sensors, extract "distilled" high-level features by applying near-sensors analytics including state-of-the-art ML and DL algorithms, and transmit this semantically dense information to higher-level nodes through wireless channels. However, running these models on embedded microcontroller systems poses severe challenges due to limited on-chip memory, power budget, and compute capabilities, requiring optimizations on both hardware and software. A well-established solution to shrink the full-precision DL models to fit the limited storage available on microcontrollers is the adoption of low-bitwidth (8-bit or less) integer arithmetic to represent their parameters, after post-training quantization [1] or quantization-aware training [2]. These techniques have been demonstrated on state-of-the-art DNN topologies, adopting uniform or mixed-precision quantization schemes, reducing the model footprint by 47% with a Top-1 accuracy drop in the range of 3.4%, without significant impact upon the user experience of many IoT applications. Banner et al. [3] propose a post-training 4-bit quantization method with an accuracy drop of a few percent, while authors of [1] presented further improvements reducing the memory footprint of DNNs up to 7\(\times\) at the cost of an accuracy drop of only 4%. If well supported by the hardware processing systems, reduced precision integer arithmetic offers a significant efficiency boost with respect to floating-point operations. Low-bitwidth integer formats are widely adopted in custom digital and analog accelerators such as UNPU [4], supporting fully-variable 1 to 16 bit weight bit-precision and delivering a peak energy efficiency of 50.6 TOPS/W at a throughput of 184 GOPS. Emerging Analog in-Memory Computing (AiMC) accelerators such as DIANA [5] also implicitly exploit quantization, delivering peak energy efficiency in the range of 100-1000 TOPS/W. However, the high performance and efficiency of hardwired accelerators are counterbalanced by their poor flexibility, which makes it hard to deploy real-sized end-to-end DNNs on these systems and to achieve actual efficiencies similar to the theoretical peak. Limited flexibility and high area cost per device make them hard to adopt in IoT applications. A compromise solution between dedicated accelerators and fully programmable devices is represented by FPGAs, where embedded general-purpose processors are coupled to the DSP-capable hardware to accelerate DNNs [6]. Several works explore reduced-precision arithmetic [7], but within a power envelope orders-of-magnitude larger than IoT nodes budget. Lattice proposed the SensAI stack [8], which offers machine learning ultra-low-power (1 mW to 1 W) capabilities on FPGAs. However, these solutions have a limited number of LUTs and a non-negligible unit cost, not compatible with many IoT applications. Hardware reconfigurability of these platforms offers higher flexibility than ASICs, but it is still far from the average IoT programmer demand. Additionally, their efficiency is much lower than that of ASICs. The highest flexibility for QNN inference is offered by commercial general-purpose processors coupled with optimized software libraries such as CMSIS-NN libraries [9] for ARM Cortex M4 and M7 processors. A recent approach to enhance the computing capabilities of low-power MCU systems is through domain-specific Instruction Set Architecture (ISA) extensions. To address the DNN computing at the extreme edge, ARM presented the Cortex M-55 core based on the ARMv8-1M ISA, including an M-Profile Vector Extension (MVE) called Helium [10] that also supports 8-bit MAC in structions. Unfortunately, microcontrollers implementing this ISA are not yet commercially available. Many solutions in the RISC-V ecosystem leverage this approach as well; for example, authors of [11] propose the XpulpV2 custom RISC-V ISA extensions for DSP applications, including support for 16-/8-bit SIMD operations. However, this ISA incurs performance degradation on sub-byte or mixed-precision linear kernels, since additional extra-instructions are required for data manipulation, introducing huge overhead [12, 13]. To boost sub-byte uniform linear kernels, XpulpNN [14] extends XpulpV2 with 4- and 2-bit SIMD operations. Moreover, it introduces fused _Mac&Load_ instructions that allow concurrent execution of SIMD dot-product operations with memory accesses, increasing the computation efficiency of the core up to 94%. XpulpNN outperforms the performance of commercially available Cortex-M cores by up to 20\(\times\) on quantized DNN layers. However, when operating on mixed-precision inputs, the efficiency boost of XpulpNN narrows significantly because of the massive software overhead necessary for packing and unpacking data. To eliminate the performance degradation compared to uniform precision kernels, authors of [15] propose direct hardware support for mixed-precision operations with dedicated RISC-V ISA extensions. To reduce the number of mixed-precision instructions to be encoded into the ISA, they exploit the _dynamic bit-scalable execution mode_: the ISA instruction only encodes the type of the operation, while its format is specified by a Control Status Register (CSR) of the core. In this work, we present a new hardware and software stack targeting energy-efficient inference of mixed-precision QNNs on a parallel cluster of RISC-V processors. The main contributions of this paper are the following: * We extend the RISC-V ISA with fused mixed-precision _Mac&Load_ instructions. The proposed instruction set extension allows to achieve an ASIC-like utilization of MAC units in the cores (larger than 80%), being able to operate on all the mixed-precision variants. Considering the mixed-precision capabilities and the preserved flexibility for general-purpose applications, we name our processor Flex-V. * We integrate the extended processor in an eight-cores parallel ultra-low-power (PULP) cluster implemented in a commercial 22nm FDX technology to evaluate accurately the impact of such extensions on the operating frequency, area, and power. * We integrate the proposed hardware extensions in a software framework for the end-to-end deployment of DNNs including a compiler, optimized libraries, and a memory-aware deployment flow, and we compare the proposed solution with the state-of-the-art end-to-end DNNs. We compare the extended processor with state-of-the-art architectures by running both single convolutional layers and full end-to-end QNNs, we report a summary in Table I. Our results show a performance improvement, with respect to the execution with the extensions disabled, up to 8.5\(\times\) on a single layer and up to 2.5\(\times\) on the end-to-end network with negligible degradation of accuracy and a peak energy efficiency of 3.26 TOPS/W, approaching that of accelerators, at low area cost 5.6% with respect to the baseline processor cluster and without compromising flexibility. The hardware and software described in this work are open-source, to support and boost an innovation ecosystem focusing on ultra-low-power computing for the IoT landscape. ## II Background ### _PULP cluster_ Parallel Ultra-Low Power (PULP) is an open-source computing platform exploiting near-threshold computing to reach high energy efficiency, leveraging parallelism to enhance the performance degradation at low voltage [16]. The PULP cluster adopted as a reference, shown in Fig. 1, is composed of eight RI5CY cores [11], each of them characterized by a 4-stage in-order single-issue pipeline and the RV32IMCXpulpV2 Instruction Set Architecture (ISA). XpulpV2 is a specialized extension to the RISC-V ISA [11] designed for efficient digital signal processing (DSP) computation. It features hardware loops, post-modified access load and store instructions, along with SIMD operations on 16-bit and 8-bit integer vector operands. The cores in the cluster share data on a Tightly Coupled Data memory (TCDM) of 128 kB, divided into 16 banks. The memory is accessed through a one-cycle latency logarithmic interconnect. The PULP cluster accelerator and its host, i.e. the Fabric Controller (FC), communicate through an AXI interface. Data transfers between the TCDM and the second level of memory, hosted by the Fabric Controller, are managed by a dedicated DMA. The cluster processors fetch the instructions from a two-levels (the first private to each core, the second shared) hierarchical instruction cache to enhance the hit rate. The cluster is also provided with the Hardware Synchronization Unit which manages fine-grained parallel thread dispatching Fig. 1: Parallel Ultra-Low Power (PULP) system, consisting of a Fabric Controller (FC) accelerated by a parallel cluster of 8 RISC-V based processors. and clock-gating of idle cores waiting for synchronization, enabling low-overhead and fine-grained parallelism, thus high energy efficiency. ### _QNN execution model_ The software stack we propose in this work extends the PULP-NN software library presented in [13]. It relies on the Height-Width-Channel (HWC) data layout and on an execution model optimized for resource-constrained micro-controllers. Convolution layers are implemented by combining three distinct phases: _im2col:_ for a given output pixel position, the 3D input activations (in HWC format) of the current convolution are re-arranged into a 1D vector along the filter and input channel dimensions. PULP-NN performs this operation simultaneously for 2 output pixels, producing two separate _im2col buffers_. _Matrix Multiplication:_ this step consists of a _sum-of-dot-product_ operation between the current _im2col_ buffer and the sets of filters to produce the intermediate outputs at the higher 32-bit precision. The kernel leverages the XpulpV2 ISA and exploits data locality within the Register File (RF) of RI5CY to maximize the computation throughput. As a result of design exploration in the space of registers resources available in the RI5CY RF, it is possible to implement a MatMul with a "\(4\times 2\)" unrolling factor, fetching from memory the weights from two consecutive filters and the input activations from two different _im2col_ buffers to produce two activation outputs related to four consecutive channels, in the same inner loop of the MatMul. _Quantization:_ each intermediate 32-bit accumulator from the previous stage is represented back in low-bitwidth form by applying normalization and quantization functions, composed of one MAC, one shift, and one clip operation. ## III Flex-V core Architecture We introduce Flex-V, our RISC-V ISA-extended processor that flexibly supports sub-byte and mixed-precision preserving the fully-programmable capabilities of a general-purpose processor. The three key concepts that guided the development of the core's micro-architecture are _dynamic bit-scalable_ execution, _fused Mac&Load_, and _fully-flexible mixed-precision_. In _dynamic bit-scalable_ execution, a particular op-code defines a whole family of _virtual instructions_; the choice of a particular one to execute depends on contextual bits stored in a status register of the core. Fig. 3 shows the decoding process when the Flex-V core is running in _dynamic bit-scalable_ execution mode: in case of a _Scalar_ instruction, the decoder extracts all necessary information from the encoding of the instruction and communicates it to the EX stage. Contrarily, if the received op-code corresponds to a _Virtual SIMD_ instruction, e.g. a _(ml)sdotp_, the decoder enables the proper functional unit within the EX stage, but the precision of the operation's operands depends also on status bits stored in the CSRs, such as the SIMD format, and on signals coming from dedicated controllers. The mixed-precision Dot Product (Dotp) Unit shown in Fig. 2a, exploiting the operand-precision information stored in the CSRs, implements the sub-byte and mixed-precision support. It integrates dedicated units for 4- and 2-bit operands together with a _Slicer&Router_ responsible for their extraction from a 32-bit input word. Considering the _sum-of-dot-product (sdotp)_ operation between an 8-bit operand A and a 4-bit operand B, only four elements within the 32-bit input word for B can be consumed by a single instruction: as shown in Fig. 2b, the Slicer selects either the first or the last four elements depending on the value of _MPC_CNT_ signal, then the Router directs the selected elements to the Dotp sub-unit specified by the _SIMD_FMT_ signal coming from the CSR, i.e. the DOTP-8 for this example. The overall process is governed by the Mixed-Precision Controller (MPC). The _fused Mac&Load (mlsdotp)_ instruction overlaps a SIMD _dot-product_-like operation with a Load performed during the writeback stage, typically to replace non-stationary data in a register feeding the following _Mac&Load_ instruction. Fi Fig. 3: Instruction Decoding during status-based execution. Fig. 2: _(a)_ Dotp Unit and _(b)_ execution flow of a mixed-precision _sumdotp_ instruction between 8-bit operand A and 4-bit operand B. nally, we define _fully flexible mixed-precision_ as the hardware support for automatic management of instructions involving operators with different bit precision. An additional Neural Network Register File (NN-RF), with six 32-bit registers dedicated to values of activations and weights, has been added to enable Load operations during the _Mac&Load_ write-back stage, which cannot be done in the general purpose register file (GP-RF). Finally, the core includes a _Mac&Load_ Controller (MLC) that is in charge of the automatic address generation, described in Fig. 4. Fig. 5, shows an assembly snippet of a Matrix Multiplication kernel between 8-bit activations and 4-bit weights. The kernel starts initializing the CSRs driving the inputs of the MLC (i.e. {_w,a_}_skip_, {_w,a_}_stride_, {_w,a_}_rollback_), and the MPC parameters defining encoded activations and weight precision (_simd_format_) and the weight reuse parameter (_mix_skip_). Once the CSRs needed to configure MLC and MPC are set, the inner loop of the kernel starts the execution. After the initialization of the base memory addresses, four weights and one activation are loaded explicitly to fill the NN-RF. The innermost loop executes only one explicit load per iteration, then all other updates of the NN-RF are performed in the write-back phase of the _Mac&Load_ instruction. Strides, rollbacks, and thresholds are all stored in CSRs and they depend only on static features of the MatMul, such as the number of input channels, the dimensions of the filter kernel, and the precision of the operands. During the execution of the inner loop the MLC automatically generates the memory address for both operands: it navigates a two-dimensional strided pattern by updating a register-stored pointer {_w,a_}_addr_ with three static parameters, {_w,a_}_stride_, {_w,a_}_rollback_, and {_w,a_}_skip_. The {_w,a_}_stride_ parameter corresponds to the stride in the direction of the innermost loop of the pattern, while {_w,a_}_rollback_ rolls back the pointer of all innermost loop iterations and adds the stride of a single outermost loop iteration. {_w,a_}_skip_ is the number of innermost loop iterations. Fig. 6 shows the pattern in the example of a MatMul with unrolling factor "4\(\times\)2" in PULP-NN [13]. This kind of pattern would require substantial instruction overhead (\(\sim\)30%) for pointer management; the MLC deals with this entirely in hardware. We can also note that, in case of mixed-precision inputs, there's an additional degree of unrolling with respect to uniform precision execution: thanks to the hardware support for mixed-precision, each 32-bit register dedicated to weights can be exploited from 2 to 4 times to process different activations, then they're updated at the end of each innermost loop iteration. These features, together with the automatic update of the activations and weights pointers enabled by the MLC, increase the utilization of MAC units reducing the overall number of loads from memory. Furthermore, it can be noted that, while the baseline core (i.e. RI5CY) is limited to a maximum unrolling factor of "4\(\times\)2" that saturates the registers within the GP-RF, the introduction of the dedicated NN-RF in Flex-V extends it to "4\(\times\)4" further improving data reuse, hence performance. ## IV Deployment Flow We develop an optimized software library to take advantage of the proposed ISA extensions, replacing software-based low-precision data unpacking with the hardware support for sub-byte and mixed-precision operands, and introducing the new unrolling degree for matrix multiplications between mixed-precision operands. To deploy end-to-end real-sized QNN benchmarks, we extend the open-source DORY tool [17]1 to support low-precision data formats (\(<\) 8-bit). The tool automatically produces template-based C code that wraps a target backend, managing different levels of memories (i.e., L1, L2, and the external RAM) and orchestrating the tensor movements. In particular, DORY exploits a tiling approach to separate layers into small nodes whose tensors can fit the L1 memory of the system. Then, it produces C routines which _i)_ execute these smaller nodes in L1, and _ii)_ double-buffer the movements of tensors from L2 to L1. Notice that since the DMA is not Fig. 4: Functional schematic of the _Mac&Load_ Controller. Active blocks during an activation update are highlighted in green. Fig. 5: Pseudo-assembly code of a “4\(\times\)4” _MatMul_ between 8-bit activations and 4-bit weights. Fig. 6: Example of regular addressing pattern for \(w\) in a MatMul with unrolling factor “4\(\times\)2”. blocking, the calls to the kernels are always overlapped with the asynchronous DMA calls. The existing tool only supported 8-bit integer tensors. To plug in our new library, we modify the key elements of DORY to support 2-bit and 4-bit data formats. First, we extend the tiling solver based on Constraint Programming to support different data formats: now it considers the new constraints associated with sub-byte data formats, i.e., that the convolutional loop's innermost dimensions should always be byte-aligned. Then, we create a new set of templates to support the new ISA extensions. In the new templates, before the tiling loops, we insert the CSRs setup that is common to every sub-nodes executed. Inside the tiling loops, we call the functions implementing the key kernels exploiting the new proposed ISA extensions. Finally, we adjust the DORY mapping tool to consider that layers' tensors can have different data formats, correctly sizing the data transfers between L3, L2, and L1. ## V Results and Discussion To evaluate the Flex-V core in terms of timing, power, and area overhead compared to other cores based on the RI5CY architecture, we integrate RI5CY, MPIC, XpulpNN and Flex-V cores into the PULP cluster and perform separate full implementations with the Global Foundries 22nm FDX technology node. To evaluate the proposed hardware-software stack, we benchmark the PULP cluster with the Flex-V cores on synthetic convolutional layers and on the full deployment of real-world end-to-end QNNs. ### _Physical Implementation_ We synthesize the PULP clusters with Synopsys Design Compiler-2019.12 and perform full place&route flow with Cadence Innovus-17.11.000 using the worst-case corner (SSG 0.95V, -40degC/125degC). To perform power overhead evaluations between RI5CY and Flex-V with disabled extensions, we run timing-annotated post-layout simulations of 8-bit MatMuls in typical corners at 250 MHz. The total area of the Flex-V core is 0.018 mm\({}^{2}\), with an overhead of 30% compared to RI5CY due to the additional logic to extend the Dotp Unit and implement the MLC and the MPC. We note that the impact is only 6% when we compare the area at the cluster level. The additional logic of Flex-V compared to RI5CY does not significantly impact the maximum operating frequency of the cluster (-2%), which peaks up to 463 MHz. Note that, despite the additional logic introduced to implement the new ISA extensions, the power consumption overhead with respect to RI5CY related to the execution of an 8-bit MatMul with only XpulpV2 extensions is limited to 2.47% for the single processor and 2.04% for what concerns the whole cluster thanks to clock-gated CSRs. Complete area and power results are reported in Table II. ### _DNN Layers Benchmarking_ To demonstrate the benefits of the proposed core, we benchmark the PULP cluster with Flex-V cores on a set of synthetic convolution kernels, in terms of performance and energy efficiency, and we compare it with RI5CY [11], MPIC [15] and XpulpNN [14]. The layers operate on representative tiles used in such types of devices to deploy QNN inference, applying 64\(\times\)3\(\times\)32 filters on a 16\(\times\)16\(\times\)32 input tensor and featuring different bit-precision for activations and weights (including mixed-precision). The results are then compared against the cluster execution of the same kernels on similar RISC-V cores and reported in Fig. 7. Although MPIC [15] supports mixed-precision operations in its ISA, our solution speeds-up convolution kernels by 1.4\(\times\) thanks to the Mac-Load mechanism available in the Flex-V core and the supported "\(4\times 4\)" MatMul format. Moreover, the performance boost of Flex-V grows up to 4.5\(\times\) and 8.5\(\times\) with respect to XpulpNN and XpulpV2, respectively, which show heavy performance degradation on mixed-precision and sub-byte QNN kernels due to lack of support in the ISA for these operations that require adding extra-instructions in the assembly for data manipulation. Table III shows that the proposed architecture reaches a peak of energy efficiency of 3.26 TOPS/W on the uniform 2-bit MatMul kernel and 870 GOPS/W on the 8-bit configuration, which is comparable to dedicated hardware acceleration units without giving away software flexibility. Flex-V outperforms all the other solutions for all the configurations. ### _End-to-end Networks_ To further demonstrate the capabilities of the proposed architecture, we benchmarked it with end-to-end real-life QNNs exploiting the deployment flow described in Section IV. We considered three use cases: an 8-bit MobileNetV1, a fully mixed-precision 8b4b MobileNetV1 and an aggressively quantized 4b2b ResNet-20. The two MobileNetV1 networks have been trained on ImageNet while the 4b2b ResNet-20 targets CIFAR10. It is worth noticing that the memory footprint of the 8b4b MobileNetV1 is reduced by 47% with respect to the 8-bit quantized model while its accuracy reaches 66.0%, with a degradation of only 3.3%. Performance and accuracy of all the tested networks are reported in Tab. IV: the experiments performed on the ResNet-20 featuring 4-bit activations and 2-bit weights show that the proposed architecture achieves 2.3\(\times\) and 2.5\(\times\) of speedup with respect to XpulpV2 and XpulpNN. We also report the results of the execution of an end-to-end network on the STM32H7 presented by Capotondi et al. [12]: the speedup of the proposed architecture with respect to this commercial product reaches 19\(\times\) thanks to the combination of the extended ISA and the optimized software executed on the eight-core cluster. ## VI Conclusion We presented a novel hardware and software stack that meets the challenge of energy-efficient mixed-precision QNN inference on MCU processors core. We extended the RISC-V ISA with sub-byte and mixed-precision fused _Mac&Load_ instructions aiming to remove the overhead caused by loading and unpacking data before actual computation. We integrated the Flex-V core, which implements the extended ISA, into a tightly-coupled PULP cluster of eight cores. Its implementation with GF22FDX technology shows an area overhead of only 5.6% with respect to the baseline cluster with RI5CY cores. Furthermore, we developed a software library leveraging the new ISA extensions to improve the performance of convolutional kernels, key kernels to boost the execution of end-to-end QNNs. The results on single convolutional layers show up to 38.2 MAC/cycle boosting by 8.5\(\times\) and 4.5\(\times\) the execution on RI5CY and XuplpNN cores, respectively. We also benchmarked the proposed architecture with three end-to-end real-life QNNs, obtaining a performance gain of 2\(\times\) - 2.5\(\times\) with respect to state-of-the-art solutions. From the physical implementation of the cluster in 22nm FDX technology, we observed a peak energy efficiency of 3.26 TOPS/W. ## Acknowledgement This work was supported in part by NeuroSoC HORIZON EU Project (g.a. 101070634) and in part by TRISTAN HORIZON EU Project (g.a. 101095947).
2304.02755
Hybrid Zonotopes Exactly Represent ReLU Neural Networks
We show that hybrid zonotopes offer an equivalent representation of feed-forward fully connected neural networks with ReLU activation functions. Our approach demonstrates that the complexity of binary variables is equal to the total number of neurons in the network and hence grows linearly in the size of the network. We demonstrate the utility of the hybrid zonotope formulation through three case studies including nonlinear function approximation, MPC closed-loop reachability and verification, and robustness of classification on the MNIST dataset.
Joshua Ortiz, Alyssa Vellucci, Justin Koeln, Justin Ruths
2023-04-05T21:39:00Z
http://arxiv.org/abs/2304.02755v1
# Hybrid Zonotopes Exactly Represent ReLU Neural Networks ###### Abstract We show that hybrid zonotopes offer an equivalent representation of feed-forward fully connected neural networks with ReLU activation functions. Our approach demonstrates that the complexity of binary variables is equal to the total number of neurons in the network and hence grows linearly in the size of the network. We demonstrate the utility of the hybrid zonotope formulation through three case studies including nonlinear function approximation, MPC closed-loop reachability and verification, and robustness of classification on the MNIST dataset. ## I Introduction We leverage the recently introduced concept of a hybrid zonotope to develop an equivalent representation of feed-forward fully connected neural networks whose activation functions are rectified linear activation functions (ReLU) [1]. We show that this exact and analytic expression of the input-output mapping of the neural network enables verification and robustness quantification for general neural networks and, when neural networks are embedded in closed-loop control applications, facilitates closed-loop reachability analysis and safety guarantees. This work was developed separately from, and in parallel to, a recently posted article [2]. The overall goal of our paper and use of hybrid zonotopes is similar, however, we show our approach leads to linear growth in complexity, whereas the complexity in [2] grows exponentially. To verify neural networks, a wide range of methods have been proposed to upper and lower bound the output of neural networks. In [3], reactivation upper and lower bounds are calculated and propagated layer-by-layer to calculate an overall Lipschitz constant bound for the entire network. Due to their speed these iterative approaches continue to be used (e.g., [4]). However, it requires that bounds be recomputed if the input set changes and the iterative bounding erases any memory that exists between the layers. Semi-definite programming relaxations have been used to regain the layer-to-layer history in a computationally efficient manner [5] and mixed-integer linear programming (MILP) has been used to compute exact Lipschitz bounds [6]. In the context of control systems, closed-loop reachability has been investigated with similar methods [7, 8]. Hybrid zonotopes are a generalization of constrained zonotopes, which were introduced several years earlier [9]. Like our paper here, authors have leveraged constrained zonotopes [10, 11] or polytopes [12] to propagate sets through approximated ReLU activation functions to compute bounds on the output reachability of neural networks. [13] demonstrates how these analytic expression of relaxations of ReLU neural networks can be used to, for example, train networks to be more robust to adversarial attack. Star sets offer similar expressiveness as hybrid zonotopes and have also been used to provide approximate and exact reachability of feed-forward ReLU neural networks [14]. However, like [2], the computational complexity of the mixed-integer program (number of binary variables) grows exponentially. At the heart of our approach is the ability of hybrid zonotopes to maintain an exact analytic expression from input to output. Crucially, this expression preserves how previous layers impact the propagation of the sets without iterative calculations or overapproximation. In contrast to MILP approaches (e.g., [15]), which also provide exact input-output relationships for ReLU neural network certification, the hybrid zonotope representation, due to the memory feature of zonotopes, enables it to be used in a variety of ways, including for closed loop analysis. **Notation:** Matrices are denoted by uppercase letters, e.g., \(G\in\mathbb{R}^{n\times n_{g}}\), and sets by uppercase calligraphic letters, e.g., \(\mathcal{Z}\subset\mathbb{R}^{n}\). Vectors and scalars are denoted by lowercase letters. The \(n\)-dimensional unit hypercube is denoted by \(\mathcal{B}_{\infty}^{n}=\left\{x\in\mathbb{R}^{n}\mid\left\|x\right\|_{ \infty}\leq 1\right\}\). The set of all \(n\)-dimensional binary vectors is denoted by \(\{-1,1\}^{n}\). Matrices and vectors of all \(0\) and \(1\) elements are denoted by \(\mathbf{0}\) and \(\mathbf{1}\), respectively, of appropriate dimension. The Kronecker product of matrices \(A\in\mathbb{R}^{m\times n_{g}}\) and \(B\in\mathbb{R}^{p\times q}\) is given as \(A\otimes B\in\mathbb{R}^{pm\times qn}\). Given the sets \(\mathcal{Z},\mathcal{W}\subset\mathbb{R}^{n},\mathcal{Y}\subset\mathbb{R}^{m}\), and matrix \(R\in\mathbb{R}^{m\times n}\), the linear mapping of \(\mathcal{Z}\) by \(R\) is \(R\mathcal{Z}=\left\{Rz\mid z\in\mathcal{Z}\right\}\), the Minkowski sum of \(\mathcal{Z}\) and \(\mathcal{W}\) is \(\mathcal{Z}\oplus\mathcal{W}=\left\{z+w\mid z\in\mathcal{Z},w\in\mathcal{W}\right\}\), the generalized intersection of \(\mathcal{Z}\) and \(\mathcal{Y}\) under \(R\) is \(\mathcal{Z}\cap_{R}\mathcal{Y}=\left\{z\in\mathcal{Z}\mid Rz\in\mathcal{Y}\right\}\), and the Cartesian product of \(\mathcal{Z}\) and \(\mathcal{Y}\) is \(\mathcal{Z}\times\mathcal{Y}=\left\{(z,y)\mid z\in\mathcal{Z},\,y\in\mathcal{Y}\right\}\). ## II Hybrid Zonotopes **Definition 1**: _[_1_, Def. 3]_ _The set \(\mathcal{Z}_{h}\subset\mathbb{R}^{n}\) is a hybrid zonotope if there exists \(G^{c}\in\mathbb{R}^{n\times n_{g}}\), \(G^{b}\in\mathbb{R}^{n\times n_{b}}\), \(c\in\mathbb{R}^{n}\), \(A^{c}\in\mathbb{R}^{n_{c}n_{g}}\), \(A^{b}\in\mathbb{R}^{n_{c}n_{b}}\), and \(b\in\mathbb{R}^{n_{c}}\) such that_ \[\mathcal{Z}_{h}=\left\{\begin{bmatrix}G^{c}\,G^{b}\Big{]}\begin{bmatrix}\xi^{c} \\ \xi^{b}\end{bmatrix}+c\begin{bmatrix}\xi^{c}\\ \xi^{b}\end{bmatrix}\in\mathcal{B}_{\infty}^{n_{g}}\times\{-1,1\}^{n_{b}},\\ \begin{bmatrix}A^{c}\,A^{b}\end{bmatrix}\begin{bmatrix}\xi^{c}\\ \xi^{c}\end{bmatrix}=b\end{bmatrix}\right\}. \tag{1}\] A hybrid zonotope is the union of \(2^{\mathbb{R}}\) constrained zonotopes corresponding to the possible combinations of binary factors, \(\xi^{b}\). The hybrid zonotope is given in _Hybrid Constrained Generator-representation_ and the shorthand notation of \(\mathcal{Z}_{h}=(G^{c},G^{b},c,A^{c},A^{b},b)\in\mathbb{R}^{n}\) is used to denote the set given by (1). Continuous and binary _generators_ refer to the columns of \(G^{c}\) and \(G^{b}\), respectively. A hybrid zonotope with no binary generators is a constrained zonotope, \(\mathcal{Z}_{c}=(G,c,A,b)\subset\mathbb{R}^{n}\), and a hybrid zonotope with no binary generators and no constraints is a zonotope, \(\mathcal{Z}=(G,c)\subset\mathbb{R}^{n}\). Identities and time complexity of linear mappings, Minkowski sums, generalized intersections, and generalized half-space intersections are reported in [1, Section 3.2]. An identity and time complexity for Cartesian products is given in [16]. Preliminary methods for removing redundant generators and constraints of a hybrid zonotope were reported in [1] and further developed in [16]. _Example 1 (Zonotope Memory (see also [17])):_ If we consider a dynamic system \(x_{k+1}=Ax_{k}+Bu_{k}\), with \(x_{0}\in\mathcal{X}_{0}=(G_{x}^{c},G_{x}^{b},c_{x},A_{x}^{c},A_{x}^{b},b_{x})\) and \(u_{0}\in\mathcal{U}=(G_{u}^{c},G_{u}^{b},c_{u},A_{u}^{b},A_{u}^{b},b_{u})\), then by the linear mapping and Minkowski sum identities, \[\begin{split} x_{1}\in\mathcal{X}_{1}=\Bigg{\{}& [AG_{x}^{c}\;BG_{u}^{c}],[AG_{x}^{b}\;BG_{u}^{b}],Ac_{x}+Bc_{u},\\ &\begin{bmatrix}A_{x}^{c}\\ &A_{u}^{c}\end{bmatrix},\begin{bmatrix}A_{x}^{b}\\ &A_{u}^{b}\end{bmatrix},\begin{bmatrix}b_{x}\\ b_{u}\end{bmatrix}\Bigg{\}}.\end{split} \tag{2}\] The effect of the linear mapping is encoded in the transformation of the continuous and binary generators. The memory is, however, captured in the fact that the continuous and binary factors that define the sets \(\mathcal{X}_{0}\) and \(\mathcal{U}\) are embedded in the definition of \(\mathcal{X}_{1}\). To ignore this connection - what happens with iterative methods - is to erase this memory by treating the factors of \(\mathcal{X}_{1}\) as new unrelated factors. This feature of memory is especially visible when creating extended vectors, e.g., \[\begin{split}\begin{bmatrix}x_{0}\\ x_{1}\end{bmatrix}\in\Bigg{\{}&\begin{bmatrix}G_{x}^{c}\\ AG_{x}^{c}\;\;BG_{u}^{c}\end{bmatrix},&\begin{bmatrix}G_{x}^{b}\\ AG_{x}^{b}\;\;BG_{u}^{b}\end{bmatrix},&\begin{bmatrix}c_{x}\\ Ac_{x}+Bc_{u}\end{bmatrix},\\ &\begin{bmatrix}A_{x}^{c}\\ A_{x}^{c}\\ &A_{u}^{c}\end{bmatrix},&\begin{bmatrix}A_{x}^{b}\\ A_{x}^{b}\\ A_{u}^{b}\end{bmatrix},&\begin{bmatrix}b_{x}\\ b_{x}\\ b_{u}\end{bmatrix}\Bigg{\}}.\end{split}\] Specifically, the continuous and binary factors that specify the hybrid zonotope \(\mathcal{X}_{1}\) are \([(\xi_{x}^{c})^{\top}\;(\xi_{u}^{b})^{\top}]^{\top}\) and \([(\xi_{x}^{b})^{\top}\;(\xi_{u}^{b})^{\top}]^{\top}\), respectively, where \(\xi_{x}^{c}\) and \(\xi_{x}^{b}\) specify \(\mathcal{X}_{0}\) and \(\xi_{u}^{c}\) and \(\xi_{u}^{b}\) specify \(\mathcal{U}\). There are no new factors introduced specific to \(\mathcal{X}_{1}\) - all are inherited from \(\mathcal{X}_{0}\) or \(\mathcal{U}\). In this case the redundant constraints can be dropped. ## III Neural Network Representation as a Hybrid Zonotope Consider an \(L\)-layered feed-forward fully-connected neural network \(f:\mathbb{R}^{n}\rightarrow\mathbb{R}^{m}\) mapping inputs \(x\in\mathbb{R}^{n}\) to outputs \(y=f(x)\in\mathbb{R}^{m}\) such that \[\begin{split} x^{0}&=x,\\ x^{\ell+1}&=\phi(W^{\ell}x^{\ell}+b^{\ell}), \qquad\ell\in\{0,\cdots,L-1\},\\ y&=f(x)=W^{L}x^{L}+b^{L},\end{split} \tag{3}\] where \(W^{\ell}\in\mathbb{R}^{n_{\ell+1}\times n_{\ell}}\) and \(b^{\ell}\in\mathbb{R}^{n_{\ell+1}}\) are the weight matrix and bias vector between layers \(\ell\) and \(\ell+1\), with \(n_{0}=n\) and \(n_{L+1}=m\). For this paper, all activation functions \(\phi\) are ReLU functions that operate element-wise, i.e., for the pre-activation vector \(v^{\ell+1}=W^{\ell}x^{\ell}+b^{\ell}\in\mathbb{R}^{n_{\ell+1}}\), \[\phi(v^{\ell})=[\varphi(v_{1}^{\ell})\cdots\varphi(v_{n_{\ell}}^{\ell})]^{\top}, \tag{4}\] where the ReLU function is defined as \(\varphi(v_{i})=\max\{0,v_{i}\}\). The goal of this paper is to show that such a feed-forward neural network with only ReLU activation units can be exactly - and analytically - represented by a hybrid zonotope. Core to our approach is the idea that _sets_ (including hybrid zonotopes) can be used to describe _functions_. We can accomplish this by expressing an extended set that expresses the input-to-output relationship. Given the input set \(\mathcal{X}\subset\mathbb{R}^{n}\) and output set \(\mathcal{Y}=\{f(x):x\in\mathcal{X}\}\subset\mathbb{R}^{m}\), the function \(f\) over the input set \(\mathcal{X}\) can be expressed by the set \(\mathcal{F}\subset\mathbb{R}^{n+m}\) of extended vectors \([x^{\top}\;y^{\top}]^{\top}\in\mathbb{R}^{n+m}\) such that \(\mathcal{F}=\{[x^{\top}\;y^{\top}]^{\top}:y=f(x),x\in\mathcal{X}\}\). Zonotope-based sets especially enable function representations through the "memory" engendered by the factors. The crucial connection is that some of the factors that define the output zonotope set are factors derived from the input zonotope. To begin, we represent a single ReLU activation function \(x_{i}=\varphi(v_{i})\) as a set of points \([v_{i}\;x_{i}]^{\top}\in\mathbb{R}^{2}\) over a predetermined domain \(v_{i}\in[-a,a]\). We assume \(a>0\) is chosen large enough to capture the largest anticipated absolute value of the input \(v_{i}\) such that \(|v_{i}|\leq a\). _Lemma 1:_ The set \(\Phi\subset\mathbb{R}^{2}\) of points satisfying the ReLU activation function over the domain \(\mathcal{D}_{i}=[-a,a]\) can be exactly represented as a hybrid zonotope with \(n_{g}=4\) continuous generators, \(n_{b}=1\) binary generator, and \(n_{c}=2\) constraints. To satisfy the ReLU function for \(v_{i}\in[-a,a]\), \(\Phi=\{[v_{i}\;x_{i}]^{\top}:x_{i}=\max\{0,v_{i}\},|v_{i}|\leq a\}\). Note that \(\Phi=\Phi_{1}\cup\Phi_{2}\), where \(\Phi_{1}=\{[v_{i}\;x_{i}]^{\top}:-a\leq v_{i}\leq 0,x_{i}=0\}\) and \(\Phi_{2}=\{[v_{i}\;x_{i}]^{\top}:0\leq v_{i}\leq a,x_{i}=v_{i}\}\). To represent this set, consider the zonotopes \[\begin{split}\mathcal{Z}_{1}&=\left(\begin{bmatrix} \nicefrac{{a}}{{a}}&\nicefrac{{a}}{{2}}\\ \nicefrac{{a}}{{2}}&0\end{bmatrix},\begin{bmatrix}0\\ \nicefrac{{a}}{{2}}&0\end{bmatrix},\begin{bmatrix}-a\\ -a/2\end{bmatrix}\right),\\ \mathcal{Z}_{3}&=\left(\begin{bmatrix}\nicefrac{{a}}{{a}}&\nicefrac{{a}}{{2}}\\ \nicefrac{{a}}{{2}}&0\end{bmatrix},\begin{bmatrix}a\\ a/2\end{bmatrix}\right).\end{split} \tag{5}\] As shown in Figure 1, \(\mathcal{Z}_{1}\), \(\mathcal{Z}_{2}\), and \(\mathcal{Z}_{3}\) are the same parallelogram with shifted centers. Additionally, Figure 1 Fig. 1: The intersection of the blue zonotope, \(\mathcal{Z}_{1}\), and red hybrid zonotope, \(\mathcal{Z}_{2}\cup\mathcal{Z}_{3}\), is equivalent to the ReLU function (purple) over the interval \([-a,a]\) (here shown for \(a=10\)). shows that \(\mathcal{Z}_{1}\cap\mathcal{Z}_{2}=\Phi_{1}\) and \(\mathcal{Z}_{1}\cap\mathcal{Z}_{3}=\Phi_{2}\). Therefore, \(\Phi=\{\mathcal{Z}_{1}\cap\mathcal{Z}_{2}\}\cup(\mathcal{Z}_{1}\cap\mathcal{Z}_{ 3})=\mathcal{Z}_{1}\cap(\mathcal{Z}_{2}\cup\mathcal{Z}_{3})\). Note that \(\mathcal{Z}_{2}\cup\mathcal{Z}_{3}\) can be directly expressed as the unconstrained hybrid zonotope \[\mathcal{Z}_{2}\cup\mathcal{Z}_{3}=\left\{\begin{bmatrix}a/2&a/2&0\\ a/2&0&0\end{bmatrix},\begin{bmatrix}a\\ a/2\end{bmatrix},\begin{bmatrix}0\\ 0\end{bmatrix},[\,],[\,],[\,]\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\ Proof:: The proof is similar to that of **Corollary 1**. First, we can write (10) as \(x_{k+1}=[A\;B][x_{k}^{\top}\;u^{\top}]^{\top}\). Then we note that \([x_{k}^{\top}\;u^{\top}]^{\top}\in\mathcal{F}\cap_{[\mathbf{I}_{n}\;\mathbf{0} _{n\times m}]}\mathcal{R}_{k}\) such that \(x_{k+1}\in[A\;B](\mathcal{F}\cap_{[\mathbf{I}_{n}\;\mathbf{0}_{n\times m}]} \mathcal{R}_{k})\). The result of **Theorem 2** can be repeated recursively starting from \(\mathcal{R}_{0}=\mathcal{X}_{0}\) to compute the reachable set \(\mathcal{R}_{k}\) at any time step \(k\). We omit the simple proof to satisfy space constraints. **Corollary 2**: _Assume the initial conditions set \(\mathcal{R}_{0}\) is represented as a hybrid zonotope with \(n_{g,0}\) continuous generators, \(n_{b,0}\) binary generators, and \(n_{c,0}\) constraints and that the neural network with \(n_{N}\) ReLU activation functions is represented as a hybrid zonotope \(\mathcal{F}\) with \(4n_{N}\) continuous generators, \(n_{N}\) binary generators, and \(3n_{N}\) constraints. Then the hybrid zonotope set representation complexity of the reachable set \(\mathcal{R}_{k}\) at time step \(k\) grows linearly with \(k\), resulting in \(n_{g,k}=n_{g,0}+4kn_{N}\) continuous generators, \(n_{b,k}=n_{b,0}+kn_{N}\) binary generators, and \(n_{c,k}=n_{c,0}+k(n+3n_{N})\) constraints._ In the following result, we demonstrate how the reachable sets over time can be stacked to provide additional interpretability with regard to the history of the control policy used. This result will be used in the context of the MPC case study in Section V-B. **Corollary 3**: _Assume the initial conditions set \(\mathcal{R}_{0}\) is represented as a hybrid zonotope with \(n_{g,0}\) continuous generators, \(n_{b,0}\) binary generators, and \(n_{c,0}\) constraints and that the neural network with \(n_{N}\) ReLU activation functions is represented as a hybrid zonotope \(\mathcal{F}\) with \(4n_{N}\) continuous generators, \(n_{N}\) binary generators, and \(3n_{N}\) constraints. Then the hybrid zonotope set representation of the aggregate reachable set \([x_{0}^{\top}\;x_{1}^{\top}\;...\;x_{k}^{\top}]^{\top}\in\mathcal{R}_{0:k}= \mathcal{R}_{0}\times\mathcal{R}_{1}\times\cdots\times\mathcal{R}_{k}\) has complexity \(n_{g,k}=n_{g,0}+4kn_{N}\) continuous generators, \(n_{b,k}=n_{b,0}+kn_{N}\) binary generators, and \(n_{c,k}=n_{c,0}+(n+3n_{N})\sum_{k=0}^{k}\kappa\) constraints._ Proof:: Following from Corollary 2, the hybrid zonotope \(\mathcal{R}_{0:k}\) is the Cartesian product of sets \(\mathcal{R}_{\kappa}\) for \(\kappa=1,2,\ldots,k\) each with \(n_{g,\kappa}=n_{g,0}+4\kappa n_{N}\) continuous generators, \(n_{b,\kappa}=n_{b,0}+\kappa n_{N}\) binary generators, and \(n_{c,\kappa}=n+n_{c,0}+3\kappa n_{N}\) constraints. If these sets were unrelated, the resulting hybrid zonotope would have \(\sum_{\kappa=0}^{k}n_{g,\kappa}\) continuous generators, \(\sum_{\kappa=0}^{k}n_{b,\kappa}\) binary generators, and \(\sum_{\kappa=0}^{k}n_{c,\kappa}\). However, from the proof of Theorem 2, \(\mathcal{R}_{\kappa+1}=[A\;B](\mathcal{F}\cap_{[\mathbf{I}_{n}\;\mathbf{0}_{ n\times m}]}\mathcal{R}_{\kappa})\), hence \(\mathcal{R}_{\kappa+1}\) and \(\mathcal{R}_{\kappa}\) share common factors. Namely, all continuous and binary factors that characterize \(\mathcal{R}_{\kappa}\) also contribute to characterize \(\mathcal{R}_{\kappa+1}\). Thus the extended vector \([x_{\kappa}^{\top}\;x_{\kappa+1}^{\top}]^{\top}\) belongs to a hybrid zonotope with \(\max(n_{g,\kappa},n_{g,\kappa+1})\) continuous and \(\max(n_{b,\kappa},n_{b,\kappa+1})\) binary generators. The constraints do stack and become \(n_{c,\kappa}+n_{c,\kappa+1}\). Extending this pairwise relationship forward, \(\mathcal{R}_{0:k}\) has \(\max(n_{g,0},\ldots,n_{g,k})=n_{g,k}=n_{g,0}+4kn_{N}\) continuous generators, \(\max(n_{b,0},\ldots,n_{b,k})=n_{b,k}=n_{b,0}+4kn_{N}\) binary generators, and \(n_{c,0}+(n+3n_{N})\sum_{\kappa=0}^{k}\kappa\) constraints. ## V Applications & Demonstrations The neural networks in this paper are feed-forward fully-connected neural networks with only ReLU activation units, and specified by the number of layers and width of each layer, e.g., [4,10,7,2] is a network with inputs in \(\mathbb{R}^{4}\), outputs in \(\mathbb{R}^{2}\), and with two hidden layers of 10 and 7 ReLU units, respectively. The networks are trained in MATLAB using the stochastic gradient descent optimizer with momentum (0.95) and 100 epochs. The hybrid zonotopes have been coded in MATLAB. Optimization problems have been solved using GUROBI [18]. These examples are conducted on a laptop computer using one core of an 1.9 GHz Intel i7 processor and 16GB of RAM. ### _Nonlinear Function Approximation_ Over the input domain \([-5,5]\times[-5,5]\) we train a ReLU feed-forward neural network with layer sizes [2,20,10,10,1] to approximate the function \(\cos(x_{1})+\sin(x_{2})\) by grid sampling 400 points. There are \(20+10+10=40=n_{N}\) total ReLU functions in the network and we build a hybrid zonotope \(\mathcal{F}\) capturing the input-output mapping using the extended vector \([x^{\top}y^{\top}]^{\top}\). The hybrid zonotope has \(n+4n_{N}=2+4\times 40=162\) continuous generators, \(n_{N}=40\) binary generators, and \(3n_{N}=120\) constraints. Of the \(2^{40}\) possible combinations of binary factors, 829 satisfy the constraints, leading to 829 constrained zonotopes which appear as facets of the surface Fig. 2: (Left) Hybrid zonotope of the neural network that approximates the function \(\cos(x_{1})+\sin(x_{2})\). (Right) Top-down view of the surface reveals the intricate faceting that corresponds to binary factors (equivalent to ReLU activations) being on/off. The colormap of the original function is overlaid to show how the faceting follows the contours. plotted in Figure 2. There is a one-to-one correspondence between these 829 feasible binary factor combinations and the combinations of the 40 ReLU units being active (\(>0\)) or inactive (\(\leq 0\)). ### _Model Predictive Control Policy & Closed-Loop Reachability Analysis_ We consider a double integrator system discretized with a sampling time of 1 second, \[x_{k+1}=\begin{bmatrix}1&1\\ 0&1\end{bmatrix}x_{k}+\begin{bmatrix}0.5\\ 1\end{bmatrix}u_{k}. \tag{11}\] As in [2, 19, 8], an MPC control policy is designed to stablize the system to the origin while respecting the state and input constraints, \(x_{k}\in[-5,5]\times[-1,1]\) and \(u_{k}\in[-1,1]\). A prediction horizon of 10 steps is used, with state and input weighting matrices \(Q=I_{2}\) and \(R=I\), the terminal region \(\mathcal{O}_{\infty}^{\text{LOR}}\), and with terminal penalty matrix \(P_{\infty}\), the solution of the discrete time algebraic Riccati equation. We grid the state space over \([-0.5,3]\times[-1,1]\) to produce 10,201 state-input pairs to train a neural network with layer sizes \([2,8,4,1]\). The mapping of state-to-control provided by the neural network is visualized as a hybrid zonotope surface in three dimensions in Figure 3 (right). This hybrid zonotope, with \(n=2\) and \(n_{N}=4+8=12\), has 50 continuous factors, 12 binary factors, and 36 constraints. Each facet of the surface corresponds to a different combination of binary factors. Although there are \(2^{12}\) different factor combinations, there are only 32 facets in the surface. The remaining binary factor combinations do not satisfy the linear constraints. We now use the hybrid zonotope representation of the trained neural network to analyze the closed-loop reachability of the system, similar to the approach taken for an explicit MPC controller [20]. We consider an initial state (the gray square in Figure 3), \(x(0)\in[2.5,3]\times[-0.25,0.25]\). Following Corollary 3, we construct the hybrid zonotope for the extended vector of states across time, \([x_{0}^{\top}\cdots x_{5}^{\top}]^{\top}\). Despite the 60 binary generators in the extended state hybrid zonotope, there are only 8 binary factor combinations (8 different sequences of linear control policies) that satisfy the constraints. Part of the utility of the extended state vector is that the initial set (gray square) is originally specified as an unconstrained zonotope with a center and two continuous generators. As seen in Figure 3, the initial set is faceted by constraints at later time steps to reveal the sets of initial conditions that correspond to different sequences of linear feedback control policies. Suppose that we wish to check that the system reaches the goal set \([-0.25,0.25]\times[-0.25,0.25]\) (green square in Figure 3) for any initial condition in the gray region. Although this can be confirmed by visual inspection, it can also be rigorously ensured by evaluating set containment. The containment check of two hybrid zonotopes can be posed as a feasibility evaluation of a mixed-integer linear program. ### _Classification Robustness on MNIST_ The MNIST dataset is a canonical classification problem in which \(28\times 28\) pixel images of handwritten numbers are classified into the digits 0-9. For clarity of presentation, we consider here the classification task to classify the digits "1" and "7". We train a ReLU feedforward network with layer sizes [784,5,5,1] on a corpus of 13,007 images of the digits 1 and 7, in which the input is the vectorized image (stacking columns) and the output value \(+1\) denotes a "1" and the output value \(-1\) denotes a "7". The trained network achieves an accuracy of 99.5% on a test bank of 2,163 images of the digits 1 and 7. Figure 4 (left) shows the neural network output over the test image set, with outliers denoting images that are classified poorly and - in a handful of cases - incorrectly. Inset are example images of "the 1 that looks most like a 7" (worst 1) and "the 7 that looks most like a 1" (worst 7). These examples show that the output range over the images that are 1s spans nearly the entire interval [-1,1] (same is true for 7s) despite the overall good performance of 99.5%. The hybrid zonotope representation of the network allows us to explore this output range more rigorously as a function of the input space. We define the _1s input space_ as a zonotope Fig. 3: (Right) The hybrid zonotope representation of the neural network trained to learn an MPC policy to reach the origin while avoiding constraints, e.g., avoid \(x\leq-1\). (Left) The evolution of the system state following the inputs produced by the neural network model. The initial state set at \(k=0\) is shown in gray, and steps \(k=1,\ldots,5\) alternate color between blue and red. The inset plot shows (green arrow) the break between the \(k=4\) and \(k=5\) reachable set to show that the final state set sits within the goal set (green box). whose center is the mean value of the vectorized images of the digit 1 (both training and testing). Defining \(\sigma\in\mathbb{R}^{784}\) as the standard deviation of the same vectorized images, the (continuous) generator matrix of the 1s input set is \(G_{c}=\text{diag}(\sigma)\). It is important to note that while the input set has been defined by the images, the input set is now the interval box "containing" one standard deviation away from the mean image in 784-dimensional space. Thus this 1s input set contains the entire continuous region around the nominal image of the digit 1. We follow the same procedure to produce the _7s input space_. With these input spaces, the hybrid zonotope representing the neural network has \(784+4\times 10=824\) continuous generators, \(10\) binary generators, and \(30\) constraints. We now consider an adjustment to these input sets such that \(G_{c}=\text{diag}(\alpha\sigma)\), where \(0<\alpha\leq 1\) specifies a fractional value of the standard deviation. When \(\alpha\) approaches zero, the input set approaches a single point, located at the center (mean) value. Given the classification accuracy of the neural network, this mean point will be reliably classified correctly, hence we expect the classification output range of the 1s input set with small \(\alpha\) to be very near \(+1\) and the output range of the 7s input set with small \(\alpha\) to be very near \(-1\). As \(\alpha\) grows, we expect that the output range to grow since we observed that misclassifications occur in the test dataset. Figure 4 (right) demonstrates how the hybrid zonotope representation of the neural network allows exact characterization of the upper and lower bounds of the output hybrid zonotope subject to the 1s input set and the 7s input set. The calculation of the upper and lower bounds along each dimension of a hybrid zonotope can be cast as a mixed-integer linear optimization problem. Figure 4 (right) demonstrates that although the classification accuracy is good on the test images, relatively small perturbations (in this case perturbations on the order of \(0.3\sigma\)) are sufficient to compromise the classification of some images. The sample images from the 7s input set shows that sample images from input sets corresponding to \(\alpha=0.3\) are still human-identifiable as their correct digit. Being able to quantify the output bounds on a network over a given input domain is a powerful tool to probe the robustness of a neural network. This is especially true in the context of adversarial attacks on neural networks, in which small adjustments can lead to large changes in output value (e.g., classification outcome) [21]. ## VI Conclusions In this paper, we have shown that it is possible to exactly represent a ReLU feed-forward neural network as a hybrid zonotope. This approach provides the ability to characterize variation and robustness of the mapping given by the neural network and offers rigorous ways to certify safety and reachability in closed-loop control application. A direction for future work is to formulate the Lipschitz constant for the neural network directly from the hybrid zonotope representation. Also, although the binary factors scale linearly with the number of ReLU neurons in the network, focusing on ways to best leverage advancements in mixed-integer linear optimization solvers will unlock the ability to analyze larger and larger networks. ## VII Acknowledgments We thank Neera Jain and Trevor Bird for sharing their MATLAB code for hybrid zonotopes.
2305.14578
Connecting the Dots: What Graph-Based Text Representations Work Best for Text Classification Using Graph Neural Networks?
Given the success of Graph Neural Networks (GNNs) for structure-aware machine learning, many studies have explored their use for text classification, but mostly in specific domains with limited data characteristics. Moreover, some strategies prior to GNNs relied on graph mining and classical machine learning, making it difficult to assess their effectiveness in modern settings. This work extensively investigates graph representation methods for text classification, identifying practical implications and open challenges. We compare different graph construction schemes using a variety of GNN architectures and setups across five datasets, encompassing short and long documents as well as unbalanced scenarios in diverse domains. Two Transformer-based large language models are also included to complement the study. The results show that i) although the effectiveness of graphs depends on the textual input features and domain, simple graph constructions perform better the longer the documents are, ii) graph representations are especially beneficial for longer documents, outperforming Transformer-based models, iii) graph methods are particularly efficient at solving the task.
Margarita Bugueño, Gerard de Melo
2023-05-23T23:31:24Z
http://arxiv.org/abs/2305.14578v2
Connecting the Dots: What Graph-Based Text Representations Work Best for Text Classification using Graph Neural Networks? ###### Abstract Given the success of Graph Neural Networks (GNNs) for structure-aware machine learning, numerous studies have explored their application to text classification, as an alternative to traditional feature representation models. However, most studies considered just a specific domain and validated on data with particular characteristics. This work presents an extensive empirical investigation of graph-based text representation methods proposed for text classification, identifying practical implications and open challenges in the field. We compare several GNN architectures as well as BERT across five datasets, encompassing short and also long documents. The results show that: i) graph performance is highly related to the textual input features and domain, ii) despite its outstanding performance, BERT has difficulties converging when dealing with short texts, iii) graph methods are particularly beneficial for longer documents. ## 1 Introduction The predominant forms of text representation based on vectors make it non-trivial to recover much information about the structure of a given text. Graph-based text representation strategies instead explicitly seek to capture relationships among the different text elements (nodes) by the definition of associations between pairs of them (edges). While such ideas have a long history (Hassan and Banea, 2006, _inter alia_), in recent years we have witnessed the rise of Graph Neural Network (GNN) models. These make it particularly appealing to convert even unstructured data into graphs to enable new forms of analysis and extract significant patterns by capturing dependencies between graph nodes via message passing. For text classification, several different proposals of graph-based text representation schemes have been put forth, but the majority were introduced as a solution for a particular domain-specific task and validated on a limited range of datasets with a limited set of model architectures. Some of these were proposed before the introduction of GNNs and hence validated using graph mining techniques or classical machine learning models, making it difficult to assess their merits in modern settings. This work presents a thorough empirical investigation of previously proposed graph-based text representation methods for text classification. We analyze their performance with several GNN-based architectures across five datasets. Unlike previous work (Galke and Scherp, 2022), our study considers diverse datasets both with short and long documents (more than 512 tokens). While longer documents can be particularly challenging, our study finds that GNN methods hold particularly promise for longer documents. Furthermore, we provide a particularly extensive empirical comparison of graph-based text representation methods and shed light on what are the most successful choices of GNN architectures for learning from them. The main contributions of the study are: 1. We evaluate the merits of previously proposed graph-based text representations across a variety of GNN architectures and datasets. 2. We study the effect of four different node feature initialization schemes. 3. We identify the practical implications of the previously proposed graph-based text representations, shedding light on open challenges. ## 2 Prior Work on Graphs in NLP A notable early approach for graph-based document representation is to consider co-occurrence within a fixed-size sliding window (Mihalcea and Tarau, 2004). Words are modeled as nodes, and two nodes are connected if the corresponding terms co-occur within a window of at most \(N\) words. Mihalcea and Tarau (2004) used such co-occurrence graphs for \(N\in\{2,\ldots,10\}\) as a graph-based ranking model for keyword extraction. They found lower choices of \(N\) to be preferable, as the connection between words further apart is often weaker. Hassan and Banea (2006) used the same approach for \(N=2\) along with TextRank to replace term frequency weights, and then conducted text classification with classic machine learning models. In most of their experiments, this scheme outperformed using TF-IDF vectors. Rousseau et al. (2015) also used a fixed-size sliding window graph (calling it _graph-of-words_). They cast text classification as a graph classification problem by applying graph mining to obtain subgraph features to train a classifier. _Sequence graphs_ are another simple scheme with edges reflecting the original order of words in the text (Castillo et al., 2015). The authors used the number of times the corresponding two words appear consecutively in the text as edge weights. Other graph construction methods have been proposed. Mihalcea and Tarau (2004) highlighted that depending on the application at hand, multiple text units and characteristics can be considered as vertices, such as words, collocations, entire sentences, etc. They invoked application-specific criteria to define edges, such as lexical or semantic relations. To this end, they also proposed a similarity-weighted graph for sentence extraction. Every node represents an entire sentence, while edges are defined by measuring their content overlap as the number of shared tokens. Although this scheme can be applied in other tasks (text classification or summarization), it normally results in a fairly densely connected graph, making it difficult to extract local patterns and differentiate the content of the text. Given that traditional work in linguistics and computational linguistics often considers tree and graph-structured formalisms as the principal way of analyzing individual sentences, these may also serve as building blocks for document-level representations (Arora et al., 2009; Joshi and Rose, 2009, _inter alia_). For instance, a neural parsing model (Dozat and Manning, 2016; Yuan et al., 2021) can infer word dependencies to obtain syntactic dependency trees. However, the overall graph representation becomes rather sparse, as nodes share edges with only a limited number of other units. Text Graph Convolutional Network (TextGCN; Yao et al. 2019) is a recent high-impact approach, indeed also one of the first approaches to include a Graph Convolutional Neural Network (GCN) as a classification method. TextGCN proposes a heterogeneous graph with nodes for words and documents, and edges for associations between pairs of words and document-word associations representing the terms contained in a specific document. In addition, TextGCN defines edge weights as Point-wise Mutual Information (PMI) similarity for word pairs and TF-IDF for word-in-document edges. This approach casts document classification as a node classification problem. Liu et al. (2020) proposes a text graph tensor to learn word and document embeddings using semantic, syntactic, and sequential contextual information. However, these methods are computationally inefficient and fail to capture higher-order interactions between words. Alternatively, TextLevelGCN (Huang et al., 2019) creates one graph per input text. The proposal defines every word as a node, which can be duplicated if a word appears more than once in a text. Edges are defined for word nodes within a sliding window using PMI edge weights. Despite promising results, the experiments were limited to very short documents. GraphIE (Qian et al., 2019) proposes a different scheme based on co-reference, integrating a GCN with an RNN encoder-decoder architecture for sequence tagging and information extraction tasks. Nodes can be defined as words or entire sentences, while associations are defined as co-reference and identical mention edges, to account for non-local and non-sequential ties. Despite enhancing the accuracy in the target tasks, the strategy requires prior domain knowledge to establish the edge types. Recently, some studies have brought back the classic co-occurrence graph construction methods but this time using a different message passing function based on Gated Recurrent Units (Li et al., 2015; Cho et al., 2014) for updating the node feature vectors (Zhang et al., 2020). MPAD (Nikolentzos et al., 2020) included an extra master node connected to every other node in the graph. The network is densely connected, and the structural information is vague during message passing. Since Zhang et al. (2020) outperform TextlevelGCN despite using the same graph construction, it is clear that the graph construction method and the way patterns are extracted from it are closely related. Hence, an in-depth study analyzing multiple factors in a controlled environment is necessary. In terms of broader empirical comparisons, one previous study also conducted an empirical analysis of GNN approaches for text classification (Galke and Scherp, 2022). Nevertheless, despite the comprehensive evaluation, the authors limited their analysis to standard data collections with only short texts. In contrast, our study considers a broader range of domains and more challenging datasets, including much longer documents and unbalanced classification scenarios. ## 3 Comparing Graph-Based Text Representations To study the merits of the previously proposed graph-based text representation strategies, we conducted comprehensive experiments on five text classification datasets widely known in the area. In each of these tasks, we compare different graph construction schemes using a variety of GCN models to separate the effect of the graph construction strategy from that of the message-passing technique in the model architecture. For reference, we also evaluated the BERT model as a baseline. ### Methods #### 3.1.1 Graph-Based Text Representation Among the studied techniques, there are some graph construction methods that follow an intuitive construction process. They are based solely on simple relationships between pairs of nodes and only consider basic co-occurrence statistics if needed. Thus, they do not require a deep understanding of the semantic structure. In the following, we refer to these sorts of networks as **Intuitive Graphs**. Figure 1 illustrates how they work. **Window-based:** Following Hassan and Banea (2006), given an input text, if a term has not been previously seen, then a node is added to the graph to represent it, and an undirected edge is induced between two nodes simply if they are two consecutive terms in the text. **Window-based extended:** As for the above window-based construction, except that the window size is extended to three. Then, the tokens contained in the window define edges among each other. With this, each word in the input text will ultimately be tied to the two previous terms and the two subsequent ones. **Sequence-weighted:** This strategy (Castillo et al., 2015) defines a directed graph with nodes for words and edges that represent that the two corresponding lexical units appear together in the text sequence and follow the order in which they appear. Additional edge weights capture the number of times that two vertices appear together in the text to represent the relationship's importance in the text. **Sequence simplified:** Inspired by the above sequential graphs, a simplified version is considered that omits the edge weights. Thus, the effect of the edge importance function over the pure graph structure can be studied in isolation. A more sophisticated graph-based text representation strategy requiring a deeper understanding is also considered. Contrary to the previous intuitive schemes, it requires an elaborate process for defining the graph components. **TextLevelGCN:** Every word appearing in a text is treated as a node, and edges are defined between adjacent words in a fixed-size window. Unlike Intuitive Graphs, TextLevelGCN (Huang et al., 2019) considers each word token occurrence as a separate node, i.e., it allows multiple nodes if the corresponding term occurs more than once in the text. Therefore, even for polysemous words, the specific in-context meaning can be determined by the influence of weighted information from its neighbors, improving the expressiveness of the graph. The authors further employed PMI as an edge weighting function for the word associations as in Yao et al. (2019). #### 3.1.2 Traditional Text Representation Finally, BERT (Devlin et al., 2018) is also included as a baseline to complement our comparative study. This enables us to better understand how the results of the graph methods relate to those of mainstream pretrained large language models. **BERT:** A BERT pre-trained model is included by freezing the encoder architecture and stacking a final dense layer for conducting the corresponding text classification task. **FF BERT:** Fully fine-tuning BERT for each task was also considered without any freezing. This way, the full expressiveness of the model is involved in learning downstream patterns for solving the corresponding task. ### Datasets The literature review reveals that many graph-based text representation methods have been evaluated on different datasets. Most of the time, the proposals were each introduced for a specific task domain and validated on text with very restricted characteristics such as a limited vocabulary and an average document length not greater than 221 words [16, 17]. Hence, it is unclear how these approaches can generalize to new data and be applied to long documents in a more general scenario. We consider five publicly available datasets for text classification. These are labeled by experts and validated by the community. The datasets are summarized in Table 1. **App Reviews**[1] - A collection of 288,065 English user reviews of Android applications from 23 different app categories, with the goal of fine-grained sentiment analysis in an imbalanced setting, where 60.5% of the total samples correspond to 4-star reviews. Each example includes the name of the software application package, the comment, the date when the user posted the evaluation, and the rating provided. **DBpedia**[16] - For topic classification, the DBpedia ontology classification dataset was constructed by picking 14 non-overlapping classes from DBpedia 2014 [10]. For each category, the authors randomly chose 40,000 Wikipedia articles as training samples and 5,000 samples for testing. Every article contains the title, content, and class label. Although the original DBpedia is a multilingual knowledge base, this dataset only contains English data. **IMDB**[16] - English language movie reviews from the Internet Movie Database for binary sentiment classification, with 25,000 reviews for training and 25,000 for testing, with balanced numbers of positive and negative reviews. **BBC News**[1] - A publicly available1 dataset consisting of 2,225 English documents from the BBC News website. The articles correspond to stories from 2004-5 in the areas of business, entertainment, politics, sport, and technology. The dataset exhibits minor class imbalance, with sports being the majority class with 511 articles, while entertainment is the smallest one with 386 samples. Footnote 1: [http://derekgreene.com/bbc/](http://derekgreene.com/bbc/) **Hyperpartisan News Detection (HND)**[17] - A dataset2 for binary news classification. Although it comprises two parts, _byarticle_ and _hypublisher_, this study only uses the first one. The dataset has 645 English samples labeled through crowdsourcing, with 238 (37%) labeled as hyperpartisan and 407 (63%) as not hyperpartisan. Footnote 2: [https://zenodo.org/HNDrecord](https://zenodo.org/HNDrecord) ### Experimental Setup #### 3.3.1 Data Preparation A fixed-size data partition was taken from each dataset to conduct a fair comparative analysis among the methods. Thus, a training and test split was defined, consisting of 7,000 and 3,000 samples, respectively. For those datasets that did not have \begin{table} \begin{tabular}{l|r|r|r} \hline **Dataset** & **Avg. Length** & **NoC** & **IRate** \\ \hline App Reviews & 14 & 5 & 1:8 \\ \hline DBpedia & 51 & 14 & 1:1 \\ \hline IMDB & 283 & 2 & 1:1 \\ \hline BBC News & 438 & 5 & 4:5 \\ \hline HND & 912 & 2 & 1:2 \\ \hline \end{tabular} \end{table} Table 1: **Statistics of text classification datasets.** It includes the average length of documents, the number of classes (NoC), and the imbalance rate between the minority and majority classes (IRate). Figure 1: **Intuitive Graph methods.** Given the input text “_Start working! The sooner you start working, the sooner you will have money_”, four co-occurrence graph representations are shown. These include a window-based graph [16], an extended version by setting the window size to \(3\) (new edges are shown as dashed), a sequence-weighted graph [17], and a simplified version that omits edge weights. that many examples, i.e., BBC News and HND, 80% of the samples were used for training and the remaining 20% for testing. For all datasets, we randomly reserve \(10\%\) of the samples from the training set for building the validation set. Since each graph node would represent a word of the input text, specific standardization rules are needed. Accordingly, the text normalization procedure encompassed lowercase conversion, punctuation mark and stop word removal, as well as removing any other non-ASCII character. Note that our TextLevelGCN experiments are built on the implementation3 published by the corresponding authors, on which certain additional operations are defined for data preprocessing. These include the removal of every token whose length is less than three characters, the definition of a maximum length allowed for the documents to be processed to 350 terms, elimination of words whose frequency is less than 5, the application of a lemmatizer, as well as the definition of expansion rules for the removal of English contractions. Footnote 3: [https://github.com/mojave-pku/TextLevelGCN](https://github.com/mojave-pku/TextLevelGCN) #### 3.3.2 Model Setups Graph Neural Networks.The architectural design for Intuitive Graph experiments considered varying the number of hidden layers from 1 to 4 and varying the dimensionality of the node representation vector in \(\{16,32,64\}\). We applied Dropout after every convolutional layer with a retention probability of 0.8 and used average pooling for node-level aggregation. The final representation was fed into a softmax classifier. The experiments were conducted employing three different types of graph convolutional neural layers: (i) the traditional one (GCN; Kipf and Welling 2016), (ii) using a graph isomorphism operator (GIN; Xu et al. 2018), which has shown improved structural discriminative power compared to GCNs, and (iii) including a graph attentional operator (GAT; Velickovic et al. 2017) with 4 attention heads. We followed the implementations provided in PyTorch Geometric (see Appendix C). For TextLevelGCN, we used default parameter settings as in the original implementation, varying the window size (n-gram parameter) from 1 to 4. All GNNs used a batch size of 64 samples and were trained for a maximum of 100 epochs using Adam optimization (Kingma and Ba, 2014) with an initial learning rate of \(10^{-4}\). The training was stopped if the validation macro-averaged F1 score did not improve for ten consecutive epochs. Only for HND, the patience was set at 20. Four different node vector initialization strategies were also compared. We considered GloVe Wiki-Gigaword 300-dim. embeddings (Pennington et al., 2014), Word2Vec Google News 300-dim. embeddings (Mikolov et al., 2013), static BERT pre-trained embeddings encoding each token in isolation, and a contextualized version of BERT embeddings. The latter involves encoding the entire input text using BERT and using the corresponding embedding from the 12th layer. BERT baselines.We used BERT-base uncased as the pre-trained model. A Dropout layer right after it was included with a retention probability of 80%, and a final dense layer was stacked for conducting the text classification. During training, we froze the BERT architecture and trained the classifier using Adam optimization (Kingma and Ba, 2014) with an initial learning rate of \(10^{-4}\). As for GNNs, we set a batch size of 64 samples, 100 epochs as a maximum, early stopping based on macro-averaged F1-scores with a patience of 10. In turn, for fully fine-tuning BERT, the batch size and learning rate were decreased to 32 and \(10^{-6}\), respectively. The maximum number of epochs was 10, and the patience was 5. The objective function of each model was to minimize the cross-entropy loss. Accuracy and macro-averaged F1-score metrics were evaluated, as some datasets exhibit class imbalance. The experiments were run on an NVIDIA Quadro RTX A6000 with \(48\)GB VRAM. For reproducibility, we release our code on [https://github.com/](https://github.com/)<anonymized>/<anonymized>. ## 4 Results and Discussion The results reported below show the best-performing architectures for each dataset. For a full comparison of the results, see Appendix A. Each table reports the accuracy and the F1 score on the corresponding test partition at the macro level, as averages over 10 runs. For each intuitive graph, the best results are reported in bold. A star mark is used to indicate the best architecture across the entire dataset. The comparison with baselines is presented in Table 3. ### What Convolutional Layer Works Best? GIN obtained the best results for the App Reviews and HND datasets (Table 2), showing that structural information is highly relevant for the respective tasks. Regarding the other datasets, the attention heads made it possible to efficiently identify the most influential nodes in the corresponding graphs and thus obtain the best results. Likewise, it is observed that the GAT models are stable to variations in parameters such as the number of convolutional layers and the number of hidden units. ### Do High-Dimensional Embeddings Yield Better Results? There is no clear relationship between the initialization strategy and the architecture of the GNN model. However, a noteworthy finding is that the best results were most of the time reported by non-BERT initializations. Hence, well-known pre-trained word embeddings with a much lower \begin{table} \end{table} Table 2: **Summary of key experimental results for Intuitive Graphs.** Accuracy and F1-macro are shown. dimensionality yield better results than BERT embeddings. This is the case for the App Reviews and IMDB datasets using Word2Vec, and BBC News using GloVe. ### How Well do Graphs Adapt to Different Tasks? For App Reviews, Table 2 reveals that \(\text{Window}_{\text{ext}}\) has better results than when using \(N=2\). In turn, a simplified sequence graph outperforms its weighted counterpart and the window-based constructions with an F1 score of 0.357. As these are extremely short documents, a simple model is powerful enough to address the task. Although no significant differences are observed between the window-based graphs for DBpedia, the best accuracy is reported when \(N=2\), using only one neural layer and 16 hidden units. Thus, very few parameters are sufficient to attain competitive results. Likewise, this setting outperforms all GNNs trained on sequence graphs, demonstrating that the interaction between the left-right contexts for each graph node is beneficial for the task. Similarly, the window graph surpasses its extended version on IMDB. However, comparing the sequence graphs, we observe that the simplified construction achieves even better results. With just one neural layer, \(\text{Sequence}_{\text{simp}}\) achieves 87.9% accuracy. For BBC News, Table 2 shows that as the number of convolutional layers and the number of hidden units increase, the performance of the models consistently improves, with \(\text{Window}_{\text{ext}}\) being the best graph construction at \(98\%\) accuracy. This representation establishes associations between different text parts by defining more extended contexts than using a window size of \(2\). Since news articles tend to reiterate key facts in the news multiple times, exact co-occurrences of word pairs appear to be more frequent than in other domains. Accordingly, sequence graphs with edge weights yield better results than simplified ones. Despite this, they do not surpass the results of \(\text{Window}_{\text{ext}}\). The contrary is observed for HND. The window-based graph achieves better results than its extended version, and \(\text{Sequence}_{\text{simp}}\) significantly outperforms the weighted version, which fails to learn the task. This is because, although these are extremely long documents, many of the tokens correspond to HTML, PHP markers, and other artifacts from the source. Therefore, much of the input is insignificant for solving the task. Given that a window-based construction produces more strongly connected graphs as \(N\) grows, \(\text{Window}_{\text{ext}}\) obtains worse results. However, directed graphs are preferable, as they restrict the flow of information between neighbors in a single direction, relieving message passing between insignificant nodes. This only occurs for the simplified version, since including the number of co-occurrences of said tokens would increase the effect of noise tokens. The results suggest that the construction of text graphs, although simple in terms of methodology, is fairly sensitive to the information to be represented. Despite being considered trivial in many NLP tasks, preprocessing plays a crucial role in this field. Since GNNs usually incorporate convolutional layers to spread messages between neighbors, they require valuable nodes and edges, and a good vector initialization to solve the target task. ### General Prediction Quality The BERT results show that the textual information in the documents is sufficient to outperform random prediction on the DBpedia, IMDB, and BBC News datasets. This demonstrates the low difficulty involved in these tasks. On the contrary, the most challenging ones correspond to those having document lengths longer than 512 or showing class imbalance (App Reviews and HND datasets). Despite not outperforming FF BERT, TextLevelGCN is the best graph-based model for App Reviews. It shows that the classification task benefits from edge weights, but they should be soft values for a smoother learning curve. Otherwise, it is preferable to omit them. On all other datasets, TextLevelGCN underperforms Intuitive Graphs even when processing short documents. Moreover, despite its simplicity, \(\text{Sequence}_{\text{simp}}\) outperforms TextLevelGCN. We see that the results of graph-based models are below FF BERT for short document classification. However, for long documents such as BBC News, \(\text{Window}_{\text{ext}}\) obtains the best-reported accuracy. The same is observed for HND, where Intuitive Graphs dominate as the best way to represent longer documents. In this task, FF BERT obtains significantly better validation performance than during testing, i.e., it overfits and obtains considerably lower results than TextLevelGCN. Although the latter defines a much smaller maximum length for text documents (350 tokens), TextLevelGCN has a higher accuracy than FF BERT. Therefore, graph-based document representations provide clear advantages when processing long texts. ### Discussion The results show that graph-based document representation holds substantial promise as a way of providing structural information to deep neural networks. Graph-based learning models are powerful and allow the extraction of complex patterns from text. However, they are particularly task-sensitive and depend on the lexical features of the documents to be represented. Thus, special care must be taken to properly define the components of the structure (nodes, edges, and the similarity function as edge label). Despite this, the most simplistic graph constructions (such as \(\text{Sequence}_{\text{simp}}\)) can address text classification fairly well, proving competitive even in challenging scenarios such as with data imbalance and noisy documents (i.e., a large presence of insignificant tokens). This is possible because even when a junk token occurs numerous times in the text, it will be represented as a unique node. By omitting edge weights, the learning model is prevented from focusing on these issues and thus learns the task efficiently and effectively. This phenomenon can be seen in Figure 2, where the Intuitive Graphs methods require much less time and computing resources than competitors for training. Since FF BERT is a highly complex model with respect to the number of learnable parameters, a higher execution time than graph-based models is expected. However, it is observed that for shorter documents, as in App Reviews and DBpedia, FF BERT took even longer than for medium-length documents. This suggests that this model requires several iterations to converge on these particular tasks. Beyond this, note the abrupt decrease in the execution time of the models on the BBC and HND datasets is because these datasets have a small number of samples. Therefore, the total runtime is much shorter compared to the others. See Appendix B for more details on the runtime. ## 5 Conclusion We present an empirical analysis of graph-based text representation strategies for text classification \begin{table} \begin{tabular}{l l|c|c|c|c} \cline{3-6} & & \multicolumn{2}{c|}{Validation} & \multicolumn{2}{c}{Testing} \\ \hline **Dataset** & **Model** & **Acc** & **F1-ma** & **Acc** & **F1-ma** \\ \hline \multirow{4}{*}{App Reviews} & BERT & 0.615 \(\pm\) 0.005 & 0.180 \(\pm\) 0.014 & 0.613 \(\pm\) 0.004 & 0.184 \(\pm\) 0.012 \\ & FF BERT & 0.636 \(\pm\) 0.013 & **0.374 \(\pm\) 0.012** & 0.620 \(\pm\) 0.012 & **0.369 \(\pm\) 0.011** \\ & TextLevelGCN & 0.612 \(\pm\) 0.006 & 0.336 \(\pm\) 0.013 & **0.645 \(\pm\) 0.012** & 0.358 \(\pm\) 0.010 \\ & \(\text{Sequence}_{\text{simp}}\) & **0.640 \(\pm\) 0.010** & 0.334 \(\pm\) 0.016 & 0.637 \(\pm\) 0.007 & 0.357 \(\pm\) 0.013 \\ \hline \multirow{4}{*}{DBpedia} & BERT & 0.725 \(\pm\) 0.016 & 0.681 \(\pm\) 0.021 & 0.746 \(\pm\) 0.019 & 0.741 \(\pm\) 0.021 \\ & FF BERT & **0.984 \(\pm\) 0.003** & **0.977 \(\pm\) 0.004** & **0.983 \(\pm\) 0.001** & **0.983 \(\pm\) 0.001** \\ & TextLevelGCN & 0.964 \(\pm\) 0.003 & 0.964 \(\pm\) 0.003 & 0.961 \(\pm\) 0.001 & 0.960 \(\pm\) 0.002 \\ & Window & 0.968 \(\pm\) 0.001 & 0.967 \(\pm\) 0.001 & 0.975 \(\pm\) 0.001 & 0.974 \(\pm\) 0.001 \\ \hline \multirow{4}{*}{IMDB} & BERT & 0.682 \(\pm\) 0.025 & 0.669 \(\pm\) 0.034 & 0.686 \(\pm\) 0.029 & 0.677 \(\pm\) 0.036 \\ & FF BERT & **0.869 \(\pm\) 0.009** & **0.866 \(\pm\) 0.009** & **0.884 \(\pm\) 0.007** & **0.884 \(\pm\) 0.008** \\ & TextLevelGCN & 0.864 \(\pm\) 0.005 & 0.864 \(\pm\) 0.005 & 0.868 \(\pm\) 0.002 & 0.868 \(\pm\) 0.003 \\ & \(\text{Sequence}_{\text{simp}}\) & 0.863 \(\pm\) 0.005 & 0.861 \(\pm\) 0.005 & 0.879 \(\pm\) 0.001 & 0.879 \(\pm\) 0.001 \\ \hline \multirow{4}{*}{BBC News} & BERT & 0.594 \(\pm\) 0.054 & 0.553 \(\pm\) 0.089 & 0.525 \(\pm\) 0.056 & 0.493 \(\pm\) 0.073 \\ & FF BERT & 0.967 \(\pm\) 0.011 & 0.960 \(\pm\) 0.013 & 0.978 \(\pm\) 0.003 & 0.977 \(\pm\) 0.003 \\ & TextLevelGCN & 0.962 \(\pm\) 0.005 & 0.963 \(\pm\) 0.004 & 0.973 \(\pm\) 0.004 & 0.973 \(\pm\) 0.004 \\ & Window\({}_{\text{ext}}\) & **0.977 \(\pm\) 0.009** & **0.976 \(\pm\) 0.009** & **0.980 \(\pm\) 0.003** & **0.980 \(\pm\) 0.003** \\ \hline \multirow{4}{*}{HND} & BERT & 0.559 \(\pm\) 0.162 & 0.346 \(\pm\) 0.076 & 0.522 \(\pm\) 0.059 & 0.345 \(\pm\) 0.027 \\ & FF BERT & **0.785 \(\pm\) 0.023** & 0.674 \(\pm\) 0.034 & 0.726 \(\pm\) 0.029 & 0.706 \(\pm\) 0.045 \\ \cline{1-1} & TextLevelGCN & 0.759 \(\pm\) 0.035 & **0.721 \(\pm\) 0.030** & 0.757 \(\pm\) 0.026 & 0.734 \(\pm\) 0.035 \\ \cline{1-1} & \(\text{Sequence}_{\text{simp}}\) & 0.735 \(\pm\) 0.015 & 0.687 \(\pm\) 0.017 & **0.791 \(\pm\) 0.011** & **0.785 \(\pm\) 0.011** \\ \hline \end{tabular} \end{table} Table 3: **General effectiveness.** The results of the best Intuitive Graph, TextLevelGCN, and BERT baselines are reported for the validation and testing partition. Figure 2: **Execution time.** Average execution time and shaded standard deviation for each classifier and dataset. by comprehensively analyzing their effectiveness across several GNN architectures and setups. The experiments consider a heterogeneous set of five different datasets, encompassing both short and long documents. The results show that the strength of graph-based models is closely tied to the textual features and the source domain of documents. Thus, the choice of nodes and edges is found to be crucial. Despite this, sequence graphs are shown to be a strong option, reaching competitive results across all considered tasks, especially for longer documents, and exceeding those of BERT. Along with this, we observed that pre-trained static word embeddings, instead of BERT vectors, allow reaching outstanding results on some tasks. Although predefined graph construction methods have obtained good results lately, approaches for learning the graph structure may be desirable. This would eliminate the need for picking a design manually, being less domain-dependent. However, this would come at the price of diminished explainability. Given the capacities of current deep learning models, a graph generation strategy is prone to turning into a black-box model. In future work, we will expand this study with other graph representation methods for further NLP tasks, such as summarization and question answering, since they highly rely on context understanding for solving the task. ### Limitations While this study successfully shows the impact and potential of graphs for document representation, there are some points to keep in mind. First, despite all the judgments and conclusions presented being supported by the results of the experiments, they were based on graph neural network models trained on particular sub-partitions, as stated in Section 3.3.1, so as to allow a fairer comparison between models. However, this means that the results reported here are not directly comparable with those reported in the literature. To assess how the models are positioned with regard to the State-of-the-Art in the different tasks, it is advisable to train on the original training partitions and thus learn from all the available data. It is also important to note that our study analyzes multiple text representation strategies on text classification only. Although this is one of the most important classes of NLP tasks, we cannot ensure that such graph approaches show the same behavior in other tasks. Therefore, tackling other types of problems that require a deep level of understanding of the local and global context of the text is an important direction for future work. Furthermore, all the experiments were run on English data. As English has comparatively simple grammar and well-known rules for conjugations and plurals, it is possible that graph-based models may not be as effective in other languages. Analyzing this aspect would be particularly interesting for low-resource languages. Finally, the comparison with BERT does not seem fair, since it requires a cut-off for documents with more than 512 tokens and thus is unable to access the entirety of the text. We included BERT to analyze its effects and compare the results with TextLevelGCN, which also cuts text to an even smaller length than BERT. In future work, modifications of the BERT and TextLevelGCN models, where both access all tokens contained in the document, could be investigated. ## Ethics Statement This work studies fundamental questions that can be invoked in a multitude of different application contexts. Different applications entail different ethical considerations that need to be accounted for before deploying graph-based representations. For instance, applying a trained hyperpartisan news detection model in an automated manner bears the risk of false positives, where legitimate articles get flagged merely for a choice of words that happens to share some resemblance with words occurring in hyperpartisan posts. For sentiment classification, Mohammad (2022) provides an extensive discussion of important concerns. Hence, ethical risks need to be considered depending on the relevant target use case. ## Acknowledgments This study was possible due to the funding of the Data Science and Engineering (DSE) Research School program at Hasso Plattner Institute.
2302.10975
Improved uncertainty quantification for neural networks with Bayesian last layer
Uncertainty quantification is an important task in machine learning - a task in which standardneural networks (NNs) have traditionally not excelled. This can be a limitation for safety-critical applications, where uncertainty-aware methods like Gaussian processes or Bayesian linear regression are often preferred. Bayesian neural networks are an approach to address this limitation. They assume probability distributions for all parameters and yield distributed predictions. However, training and inference are typically intractable and approximations must be employed. A promising approximation is NNs with Bayesian last layer (BLL). They assume distributed weights only in the linear output layer and yield a normally distributed prediction. To approximate the intractable Bayesian neural network, point estimates of the distributed weights in all but the last layer should be obtained by maximizing the marginal likelihood. This has previously been challenging, as the marginal likelihood is expensive to evaluate in this setting. We present a reformulation of the log-marginal likelihood of a NN with BLL which allows for efficient training using backpropagation. Furthermore, we address the challenge of uncertainty quantification for extrapolation points. We provide a metric to quantify the degree of extrapolation and derive a method to improve the uncertainty quantification for these points. Our methods are derived for the multivariate case and demonstrated in a simulation study. In comparison to Bayesian linear regression with fixed features, and a Bayesian neural network trained with variational inference, our proposed method achieves the highest log-predictive density on test data.
Felix Fiedler, Sergio Lucia
2023-02-21T20:23:56Z
http://arxiv.org/abs/2302.10975v3
# Improved uncertainty quantification for neural networks with Bayesian last layer ###### Abstract Uncertainty quantification is an essential task in machine learning - a task in which neural networks (NNs) have traditionally not excelled. Bayesian neural networks (BNNs), in which parameters and predictions are probability distributions, can be a remedy for some applications, but often require expensive sampling for training and inference. NNs with Bayesian last layer (BLL) are simplified BNNs where only the weights in the last layer and the predictions follow a normal distribution. They are conceptually related to Bayesian linear regression (BLR) which has recently gained popularity in learning based-control under uncertainty. Both consider a non-linear feature space which is linearly mapped to the output, and hyperparameters, for example the noise variance, For NNs with BLL, these hyperparameters should include the deterministic weights of all other layers, as these impact the feature space and thus the predictive performance. Unfortunately, the marginal likelihood is expensive to evaluate in this setting and prohibits direct training through back-propagation. In this work, we present a reformulation of the BLL log-marginal likelihood, which considers weights in previous layers as hyperparameters and allows for efficient training through back-propagation. Furthermore, we derive a simple method to improve the extrapolation uncertainty of NNs with BLL. In a multivariate toy example and in the case of a dynamic system identification task, we show that NNs with BLL, trained with our proposed algorithm, outperform standard BLR with NN features. Bayesian last layer, Bayesian neural network, uncertainty quantification, system identification ## I Introduction Machine learning tries to capture real world patterns and trends through data. Both, the data and these underlying patterns are subject to uncertainty. For many applications, especially those where machine learning is applied to safety critical tasks, it is imperative to predict the pattern and its corresponding uncertainty. An important example is learning-based control under uncertainty, where probabilistic system models are identified from data and used for safe control decisions [1, 2, 3, 4, 5, 6]. Bayesian linear regression (BLR) [1, 2, 3] and Gaussian processes (GPs) [1, 4] are prominent methods for probabilistic system identification. Both assume that a nonlinear feature space can be mapped linearly to the outputs, with the main difference being that for BLR the nonlinear features are explicitly defined, while in GPs they are substituted through a kernel function [7]. This is a major advantage of GPs, as the most suitable features for BLR are often challenging to determine. On the other hand, GPs scale poorly with the number of data samples [8]. For big data problems they are typically approximated with sparse GPs [9], and can be further improved with deep kernel learning [10, 11]. Especially in recent years, neural networks (NNs) and deep learning have gained significant popularity for a vast variety of machine learning tasks [12]. NNs have also been successfully applied for control applications, often to infer the system model from data [13, 14, 15, 16]. Unfortunately, one of the main challenges with NNs is their tendency to overfit and their inability to express uncertainty [17]. Bayesian neural networks (BNNs), in which the weights and predictions are probability distributions, are a concept to tackle this shortcoming. Unfortunately, BNNs can be intractable to train and query and are often approximated in practice [17, 18]. Many of the approximate BNN techniques are sampling-based, e.g. Monte Carlo dropout [19], Markov chain Monte Carlo [20] and variational inference [21]. While sampling can approximate arbitrary predictive distributions, it can be a disadvantage in comparison to GPs and BLR which yield analytical results. A promising compromise between tractability and expressiveness are NNs with Bayesian Fig. 1: Multivariate neural network with Bayesian last layer: Predicted mean and standard deviation for two outputs with different and unknown noise level. Training with the proposed Algorithm 1, which maximizes the log-marginal likelihood in (50), and yields the optimal parameter \(\alpha^{*}\). This value can then be adapted to improve the uncertainty quantification in the extrapolation regime by maximizing (42), yielding \(\alpha^{\max}\). last layer (BLL) [22, 8, 23]. These networks can be seen as a simplified BNN, where only the weights of the output layer follow a Gaussian distribution, and the remainder of the layers contain deterministic weights. At the same time, they can be interpreted as a deep kernel learning approach with linear kernel. NNs with BLL are also stronlgy related to BLR in that they consider a nonlinear feature space which is mapped linearly onto the outputs. Similarly to GPs, BLR and other probabilistic models [7, 24], NNs with BLL are trained by maximizing the marginal likelihood with respect to the model hyperparameters. These hyperparameters include prior and noise variance and, importantly, the weights of the deterministic layers. While the log-marginal likelihood (LML) can be expressed analytically for NNs with BLL, it contains expressions such as the inverse of the precision matrix, making it unsuitable for direct gradient-based optimization. Previous works, especially for control applications, have therefore either assumed knowledge of all hyperparameters [2, 6, 16], including prior and noise variance, or have maximized the LML after training a NN with fixed features [5, 25]. In previous works that did include the deterministic weights as hyperparameters, maximizing the LML required sampling the surrogate posterior during training [23], or using an approximate precision matrix [10] to enable gradient-based optimization. As a main contribution of this work, we suggest an approach to maximize the exact LML of a NN with BLL that does not require sampling and is suitable for gradient-based optimization. Most importantly, we avoid the matrix inverse in the LML by reintroducing the weights of the last layer, which were marginalized, as optimization variables. We show that our reformulation of the LML satisfies the conditions of optimality for the same solution as the original formulation. In this way, we provide a simpler training procedure, in comparison to training with variational inference, and can consistently outperform BLR with fixed features obtained from a NN. Our second main contribution is a simple algorithm to improve the BLL uncertainty quantification for extrapolation points. To this end, we relate the computation of the BLL covariance to an intuitive metric for extrapolation, which is inspired by the definition of extrapolation in [26]. Based on this relationship, the proposed algorithm adjusts a scalar parameter to improve the log-predictive density on additional validation data. Our proposed methods are derived for the multivariate-case, estimating individual noise-variances for each output with a first impression shown in Figure 1. Especially for the application of system identification, the multivariate case, using GPs and BLR, has previously been tackled by fitting an individual model to each output [1, 4, 5] or to assume i.i.d. noise for all outputs [2]. All of the presented algorithms and our results are available on online1. Footnote 1: [https://github.com/4flixt/2022_Paper_BLL_JML](https://github.com/4flixt/2022_Paper_BLL_JML). This work is structured as follows. In Section II, we introduce NNs with BLL. The marginal likelihood, which is maximized during training, is discussed in Section III. In Section IV, we discuss interpolation and extrapolation for NNs with BLL and present an algorithm to improve the predictive distribution in the extrapolation regime. Finally, we present the application of BLL to a probabilistic system identification example in Section VI. The paper is concluded in Section VII. ## II Bayesian last layer We investigate a dataset \(\mathcal{D}=(\mathbf{X},\mathbf{t})\) consisting of \(m\) data pairs of inputs \(\mathbf{x}\in\mathbb{R}^{n_{x}}\) and targets \(t\in\mathbb{R}\) from which the matrices \(\mathbf{X}=\left[\mathbf{x}_{1},\dots,\mathbf{x}_{m}\right]^{\top}\in\mathbb{R}^{m\times n _{x}}\) and \(\mathbf{t}=[t_{1},\dots,t_{m}]^{\top}\in\mathbb{R}^{m\times 1}\) are formed. We assume a scalar output for ease of notation and address the multivariate case in Section V. For the regression task, we introduce a feed-forward NN model with \(L\) hidden layers as \[y=NN(\mathbf{x};\mathbb{W}_{L+1})=g_{L+1}\circ h_{L+1}\circ\dots\circ g_{1}\circ h _{1}(\mathbf{x}), \tag{1}\] where \(\circ\) denotes function composition, \(g_{l}(\cdot),\forall l=1,\dots,L\) are activation functions and \[\mathbf{h}_{l} =h_{l}(\mathbf{\phi}_{l-1})=\left[\mathbf{\phi}_{l-1}^{\top},\ 1\right]\mathbf{W}_{l} \tag{2}\] \[\mathbf{\phi}_{l} =g_{l}(\mathbf{h}_{l}), \tag{3}\] are the operations with \(n_{\phi_{l}}\) neurons in layer \(l\). The set of weight matrices with cardinality \(L+1\) is denoted \(\mathbb{W}_{L+1}=\left\{\mathbf{W}_{1},\dots,\mathbf{W}_{L+1}\right\}\). As a requirement for BLL, we state the the following assumption. **Assumption 1**.: _The NN (1) has a linear activation function in the output layer, i.e. \(g_{L+1}(h_{L+1})=h_{L+1}\)._ With the linear mapping, the output of the last internal layer will be of particular importance, such that we introduce the simplified notation: \[\tilde{\mathbf{\phi}}=\mathbf{\phi}_{L},\ \text{and}\ \mathbf{\phi}=[\tilde{\mathbf{\phi}}^{ \top},\ 1]^{\top}, \tag{4}\] where \(\tilde{\mathbf{\phi}}\in\mathbb{R}^{n_{\tilde{\phi}}}\) are referred to as _affine features_ and \(\mathbf{\phi}\in\mathbb{R}^{n_{\phi}}\) are the corresponding _linear features_ with \(n_{\phi}=n_{\tilde{\phi}}+1\). With slight abuse of notation, we use \(\tilde{\mathbf{\phi}}=\tilde{\mathbf{\phi}}(\mathbf{x};\mathbb{W}_{L})\) and \(\mathbf{\phi}=\mathbf{\phi}(\mathbf{x};\mathbb{W}_{L})\) as both, the values of the features, and the function, parameterized with \(\mathbb{W}_{L}\). We require two additional assumptions to state Lemma 1 which formally describes a NN with BLL. **Assumption 2**.: _The NN (1) provides a feature space \(\mathbf{\phi}(\mathbf{x};\mathbb{W}_{L})\in\mathbb{R}^{n_{\phi}}\) from which the targets are obtained through a linear mapping, according to Assumption 1:_ \[\mathbf{t}=\mathbf{\phi}\left(\mathbf{X};\mathbb{W}_{L}\right)^{\top}\mathbf{w}+\epsilon=\mathbf{y }+\epsilon, \tag{5}\] _where we introduce the set \(\mathbb{W}_{L}=\left\{\mathbf{W}_{1},\dots,\mathbf{W}_{L}\right\}\) for all weights until layer \(L\) and have \(\mathbf{w}=\mathbf{W}_{L+1}\) the weights of the output layer. The additive noise \(\mathbf{\epsilon}\in\mathbb{R}^{m}\) is zero-mean Gaussian normal distributed, that is, \(\epsilon\sim\mathcal{N}(0,\mathbf{\Sigma}_{E})\)._ **Assumption 3**.: _We have a prior belief for the weights of the output layer \(\mathbf{w}\sim\mathcal{N}(0,\mathbf{\Sigma}_{\mathbf{W}})\)._ This is exactly the setting of BLR [24], for which we introduce hyperparameters \(\mathbf{\Theta}=\{\mathbb{W}_{L},\mathbf{\Sigma}_{\mathbf{E}},\mathbf{\Sigma}_{\mathbf{W}}\}\) and state the posterior distribution of the parameters \(\mathbf{w}\) using Bayes' law: \[p(\mathbf{w}|\mathcal{D},\mathbf{\Theta})=\frac{p(\mathcal{D}|\mathbf{w},\mathbf{ \Theta})p(\mathbf{w}|\mathbf{\Theta})}{p(\mathcal{D}|\mathbf{\Theta})} \tag{6}\] This allows to formulate the Lemma of Bayesian last layer. **Lemma 1** (Bayesian last layer [23]).: _If Assumptions 1-3 hold, we obtain a normal distribution for the predicted outputs:_ \[p(\mathbf{y}|\mathcal{D},\mathbf{\Theta},\mathbf{x}) =\mathcal{N}(\mathbf{\mu}_{y}^{\text{\tiny{N}}}(\mathbf{x}),\mathbf{\Sigma}_{y }^{\text{\tiny{N}}}(\mathbf{x})), \tag{7a}\] \[\mathbf{\mu}_{y}^{\text{\tiny{N}}}(\mathbf{x}) =\text{NN}(\mathbf{x};\mathbb{W}_{L+1}),\] (7b) \[\mathbf{\Sigma}_{y}^{\text{\tiny{N}}}(\mathbf{x}) =\mathbf{\phi}^{\top}\mathbf{\Lambda}_{\mathbf{\gamma}}^{-1}\mathbf{\phi},\] (7c) \[\mathbf{\Lambda}_{p}=\mathbf{\Sigma}_{p}^{-1} =\mathbf{\Phi}^{\top}\mathbf{\Sigma}_{E}^{-1}\mathbf{\Phi}+\mathbf{\Sigma}_{\mathbf{W }}^{-1}, \tag{7d}\] _where \(\mathbf{\Phi}=\mathbf{\phi}(\mathbf{X};\mathbb{W}_{L})\) is the feature matrix for the training data, \(\mathbf{\phi}=\mathbf{\phi}(\mathbf{x};\mathbb{W}_{L})\) is the feature matrix test data, and \(\mathbf{\Lambda}_{p}\) is the precision matrix._ Proof.: The posterior \(p(\mathbf{w}|\mathcal{D},\mathbf{\Theta})\) in (6) yields a normal distribution in the weights: \[\mathbf{w} \sim\mathcal{N}(\bar{\mathbf{w}},\mathbf{\Sigma}_{p}) \tag{8a}\] \[\text{with:}\quad\mathbf{\Sigma}_{p}^{-1}=\mathbf{\Lambda}_{p} =\mathbf{\Phi}^{\top}\mathbf{\Sigma}_{E}^{-1}\mathbf{\Phi}+\mathbf{\Sigma}_{W}^{-1},\] (8b) \[\bar{\mathbf{w}} =\mathbf{\Lambda}_{p}^{-1}\mathbf{\Phi}^{\top}\mathbf{\Sigma}_{E}^{-1}\mathbf{t}, \tag{8c}\] as shown for the case of arbitrary features in [24]. Finally, the predicted output \(\mathbf{y}\) is a linear transformation of the random variable \(\mathbf{w}\), yielding the distribution in (7). We can also obtain a posterior distribution for the targets, for which we consider (5) and obtain \[p(\mathbf{t}|\mathcal{D},\mathbf{\Theta},\mathbf{x}) =\mathcal{N}(\mathbf{\mu}_{y}^{\text{\tiny{N}}}(\mathbf{x}),\mathbf{\Sigma}_{t }^{\text{\tiny{N}}}(\mathbf{x})), \tag{9a}\] \[\mathbf{\Sigma}_{t}^{\text{\tiny{N}}}(\mathbf{x}) =\mathbf{\Sigma}_{y}^{\text{\tiny{N}}}(\mathbf{x})+\mathbf{\Sigma}_{\mathbf{E}}, \tag{9b}\] where \(\mathbf{\mu}_{y}^{\text{\tiny{N}}}(\mathbf{x})\) and \(\mathbf{\Sigma}_{y}^{\text{\tiny{N}}}(\mathbf{x})\) stem from (7). We will revisit (9) again for the definition of performance metrics. ## III Marginal likelihood maximization The hyperparameters \(\mathbf{\Theta}\) for NNs with BLL, BLR or GP models are typically trained by maximizing the LML in (6), which goes back to [27] and is coined _empirical Bayes_ or _type-2 maximum likelihood_. In BLR, that is, for a fixed feature space, the LML can be maximized as shown in [24]. Following this idea, the authors in [25] propose a straightforward BLL approach, where a fixed feature space is obtained through classical NN regression. However, a NN with BLL should approximate a full BNN where all weights are assumed to follow an unknown distribution function. It is therefore reasonable to include the set of weights \(\mathbb{W}_{L}\) until the last layer as hyperparameters and train them by maximizing the LML. Below we state the LML of a NN with BLL. **Lemma 2** (Log-marginal likelihood).: _If Assumptions 1-3 hold, the negative LML of (6), denoted as \(J(\mathbf{\Theta};\mathcal{D})=-\log(p(\mathbf{y}=\mathbf{t}|\mathbf{X},\mathbf{ \Theta}))\), results in:_ \[J(\mathbf{\Theta};\mathcal{D})=\frac{m}{2}\log(2\pi)+\frac{1}{2} \log\det(\mathbf{\Sigma}_{\mathbf{W}})+\frac{1}{2}\log\det(\mathbf{\Sigma}_{E}) \tag{10}\] \[\qquad+\frac{1}{2}\log\det(\mathbf{\Lambda}_{p})+\frac{1}{2}\|\mathbf{t} -\mathbf{y}\|_{\mathbf{\Sigma}_{E}^{-1}}^{2}+\frac{1}{2}\|\bar{\mathbf{w}}\|_{\mathbf{\Sigma} _{\mathbf{W}}^{-1}}^{2}.\] _In this formulation, we have \(\mathbf{\Lambda}_{p}\), \(\bar{\mathbf{w}}\) according to (8b), (8c), \(\mathbf{y}=\mathbf{\Phi}\bar{\mathbf{w}}\) and \(\mathbf{\Theta}=\{\mathbb{W}_{L},\mathbf{\Sigma}_{\mathbf{E}},\mathbf{\Sigma}_{\mathbf{W}}\}\)._ Proof.: The proof is analog to [24], where it is shown for fixed features. Unfortunately, it is typically intractable to determine the hyperparameters \(\mathbf{\Theta}\) by minimizing (10). In particular, we have that \(\mathbf{\Sigma}_{\mathbf{E}}\), which is a hyperparameter, and for which we need to compute the log-determinant, grows with the number of samples in the dataset. We therefore state a simplified formulation of (10) for which we require the following assumption. **Assumption 4**.: _The additive noise introduced in Assumption 2 is i.i.d. for all samples \(m\), yielding \(\mathbf{\Sigma}_{E}=\sigma_{e}^{2}\mathbf{I}_{m}\). The weight prior introduced in Assumption 3 is i.i.d. but we assume a flat prior for the bias, which is incorporated by stating \(\mathbf{\Sigma}_{w}^{-1}=\sigma_{w}^{-2}\mathrm{diag}(\mathbf{I}_{n_{\hat{\sigma}}}, \ 0)\). We introduce \(\tilde{\mathbf{I}}_{n_{\phi}}=\mathrm{diag}(\mathbf{I}_{n_{\hat{\sigma}}^{\text{}}}, \ 0)\)._ The assumption of a flat prior for the bias term will have a negligible effect in practice but is important for the theoretical results presented in Section IV. For ease of notation, we will reuse \(J(\mathbf{\Theta};\mathcal{D})\) and \(\mathbf{\Theta}\) in following results. **Result 1**.: _Let Assumptions 1-3 and Assumption 4 hold. The negative LML in (10) is:_ \[J(\mathbf{\Theta};\mathcal{D})=\frac{m}{2}\log(2\pi)+n_{\phi}\log (\sigma_{w})+m\log(\sigma_{e}) \tag{11}\] \[+\frac{1}{2}\log\det(\mathbf{\Lambda}_{p})+\frac{1}{2\sigma_{e}^{2}}\| \mathbf{t}-\mathbf{y}\|_{2}^{2}+\frac{1}{2\sigma_{w}^{2}}\|\bar{\mathbf{w}}\|_{2}^{2},\] _where (8b) and (8c) are now:_ \[\mathbf{\Lambda}_{p} =\sigma_{e}^{-2}\mathbf{\Phi}^{\top}\mathbf{\Phi}+\frac{1}{\sigma_ {w}^{2}}\tilde{\mathbf{I}}_{n_{\phi}}, \tag{12a}\] \[\bar{\mathbf{w}} =\sigma_{e}^{-2}\mathbf{\Lambda}_{p}^{-1}\mathbf{\Phi}^{\top}\mathbf{t}. \tag{12b}\] _In this setting, we denote \(\mathbf{\Theta}=\{\mathbb{W}_{L},\sigma_{e},\sigma_{w}\}\)._ ### _Augmented log-marginal likelihood maximization_ To train a NN with BLL we seek to minimize the negative LML: \[\min_{\mathbf{\Theta}}\quad J(\mathbf{\Theta};\mathcal{D}), \tag{13}\] with \(J(\mathbf{\Theta};\mathcal{D})\) and \(\mathbf{\Theta}\) according to Result 1. This problem excludes the weights in the last layer of the NN as they have been marginalized. A result of this marginalization is the expression (12b) which computes these weights explicitly. Unfortunately, this creates a major challenge when iteratively solving problem (13) for the optimal values \(\mathbf{\Theta}^{*}\), as the computational graph contains unfavorable expressions such as the inverse of \(\mathbf{\Lambda}_{p}\), which are both numerically challenging and computationally expensive. Furthermore, (12b) requires leveraging the entire training dataset for the computation of the gradient \(\nabla_{\mathbf{\Theta}}J(\mathbf{\Theta};\mathcal{D})\). The authors in [23] circumvent these issues by variational inference, replacing the LML objective by the evidence lower bound objective (ELBO). As the variational posterior they choose a Gaussian normal distribution, parameterized with mean and covariance. This is the obvious choice in the BLL setting where the true posterior is Gaussian as shown in (7) and, consequently, the ELBO objective is equivalent to the LML [23]. Variational inference comes at the cost, however, of introducing as optimization variables the parameters to describe the variational posterior. Furthermore, the variational inference training loop requires sampling this variational posterior, thus adding significant complexity to the algorithm. In this work, we present an alternative approach, which simultaneously avoids parameterizing the variational posterior and yields a computational graph with lower complexity than (11) suitable for fast gradient-based optimization. To obtain this result we reformulate (13) as \[\begin{split}\min_{\mathbf{\Theta},\bar{\mathbf{w}}}& J(\mathbf{\Theta},\bar{\mathbf{w}};\mathcal{D})\\ &\text{s.t.}\quad\bar{\mathbf{w}}=\frac{1}{\sigma_{e}^{2}}\mathbf{ \Lambda}_{p}^{-1}\mathbf{\Phi}^{\top}\mathbf{t},\end{split} \tag{14}\] with \(\mathbf{\Theta}=\{\mathbb{W}_{L},\sigma_{e},\sigma_{w}\}\). Importantly, we introduce \(\bar{\mathbf{w}}\) as an optimization variable and add an equality constraint corresponding to (12b). The optimal solution \(\mathbf{\Theta}^{*}\) of (14) is thus identical to the optimal solution of (13). As a main contribution of this work, we state the following theorem. **Theorem 1** (Augmented log-marginal likelihood maximization).: _The optimal solution \((\mathbf{\Theta}^{*},\bar{\mathbf{w}}^{*})\) of problem (14) is equivalent to the optimal solution obtained from the unconstrained problem:_ \[\min_{\mathbf{\Theta},\bar{\mathbf{w}}}\quad J(\mathbf{\Theta},\bar{\mathbf{w}};\mathcal{D}), \tag{15}\] _where, as the only difference to (13), \(\bar{\mathbf{w}}\) is now an optimization variable and, in comparison to (14), the equality constraint has been dropped._ Proof.: The Lagrangian of problem (14) can be written as: \[\begin{split}\mathcal{L}(\mathbf{\Theta},\bar{\mathbf{w}},\lambda; \mathcal{D})\\ =J(\mathbf{\Theta},\bar{\mathbf{w}};\mathcal{D})+\lambda^{\top}\left(\mathbf{ \Lambda}_{p}\bar{\mathbf{w}}-\frac{1}{\sigma_{e}^{2}}\mathbf{\Phi}^{\top}\mathbf{t}\right).\end{split} \tag{16}\] We then state the first-order condition of optimality for the optimization variable \(\bar{\mathbf{w}}\): \[\nabla_{\bar{\mathbf{w}}}\mathcal{L}(\mathbf{\Theta},\bar{\mathbf{w}},\lambda;\mathcal{D })=\nabla_{\bar{\mathbf{w}}}J(\mathbf{\Theta},\bar{\mathbf{w}};\mathcal{D})+\lambda^{\top }\mathbf{\Lambda}_{p}\overset{!}{=}0. \tag{17}\] Considering (11) and (5), that is, \(\mathbf{y}=\mathbf{\Phi}\bar{\mathbf{w}}\), we obtain: \[\nabla_{\bar{\mathbf{w}}} J(\mathbf{\Theta},\bar{\mathbf{w}};\mathcal{D}) \tag{18}\] \[=\nabla_{\bar{\mathbf{w}}}\left(\frac{1}{2\sigma_{e}^{2}}\|\mathbf{t}- \mathbf{\Phi}\bar{\mathbf{w}}\|_{2}^{2}+\frac{1}{2\sigma_{w}^{2}}\|\bar{\mathbf{w}}\|_{2}^ {2}\right)\] \[=\frac{2}{2\sigma_{e}^{2}}\left(\bar{\mathbf{w}}^{\top}\mathbf{\Phi}^{ \top}\mathbf{\Phi}-\mathbf{t}^{\top}\mathbf{\Phi}\right)+\frac{2}{2\sigma_{w}^{2}}\bar{\bm {w}}^{\top}\] (19) \[=\bar{\mathbf{w}}^{\top}\left(\frac{1}{\sigma_{e}^{2}}\mathbf{\Phi}^{\top }\mathbf{\Phi}+\frac{1}{\sigma_{w}^{2}}\tilde{\mathbf{I}}_{n_{\phi}}\right)-\frac{1}{ \sigma_{e}^{2}}\mathbf{t}^{\top}\mathbf{\Phi}\] (20) \[\overset{\eqref{eq:mpl}}{=}\bar{\mathbf{w}}^{\top}\mathbf{\Lambda}_{p}- \frac{1}{\sigma_{e}^{2}}\mathbf{t}^{\top}\mathbf{\Phi}. \tag{21}\] We substitute (21) into (17) and obtain: \[\lambda^{\top}\mathbf{\Lambda}_{p} =-\bar{\mathbf{w}}^{\top}\mathbf{\Lambda}_{p}+\frac{1}{\sigma_{e}^{2}} \mathbf{t}^{\top}\mathbf{\Phi}, \tag{22}\] \[\Leftrightarrow\lambda =-\mathbf{\Lambda}_{p}^{-1}\mathbf{\Lambda}_{p}\bar{\mathbf{w}}+\frac{1}{ \sigma_{e}^{2}}\mathbf{\Lambda}_{p}^{-1}\mathbf{\Phi}^{\top}\mathbf{t},\] (23) \[\Leftrightarrow\lambda =-\bar{\mathbf{w}}+\bar{\mathbf{w}}=0, \tag{24}\] where in (23) we have substituted (12b). From (24), we obtain that \(\lambda=0\) and the Lagrangian of problem (14) thus simplifies to: \[\mathcal{L}(\mathbf{\Theta},\bar{\mathbf{w}},\lambda;\mathcal{D})=J(\mathbf{\Theta},\bar{ \mathbf{w}};\mathcal{D}). \tag{25}\] This is exactly the Lagrangian of problem (15). Theorem 1 therefore enables us to maximize the LML stated in (11) without having to explicitly compute \(\bar{\mathbf{w}}\) according to Equation (12b). This means, in particular, that we are not required to compute the inverse of \(\mathbf{\Lambda}_{p}\) to express the LML. Consequentially, we can use back-propagation and gradient-based optimization to maximize the LML, which significantly simplifies training NNs with BLL. ### _Change of variables and scaling_ With Theorem 1 we can state the LML as a function of \(\bar{\mathbf{w}}\) which is now included in the set of hyperparameters \(\mathbf{\Theta}=\{\mathbb{W}_{L},\bar{\mathbf{w}},a,b\}=\{\mathbb{W}_{L+1},a,b\}\). Furthermore, we propose a change of variables and scale the objective function to improve numerical stability. In particular, we introduce: \[\alpha=\frac{\sigma_{w}^{2}}{\sigma_{e}^{2}}, \tag{26}\] which can be interpreted as a signal-to-noise ratio and \[a=\log(\alpha),\quad b=\log(\sigma_{e}). \tag{27}\] to ensure that \(\sigma_{e}>0\) and \(\sigma_{w}>0\) without constraining the problem. These changes are formalized in the the following result. **Result 2**.: _Considering the definition of \(\alpha\) in (26), we reformulate (12a):_ \[\begin{split}\mathbf{\Lambda}_{p}&=\sigma_{e}^{-2}\mathbf{ \Phi}^{\top}\mathbf{\Phi}+\sigma_{w}^{-2}\tilde{\mathbf{I}}_{n_{\phi}}\\ &=\sigma_{e}^{-2}\left(\mathbf{\Phi}^{\top}\mathbf{\Phi}+\alpha^{-1} \tilde{\mathbf{I}}_{n_{\phi}}\right)=\sigma_{e}^{-2}\tilde{\mathbf{\Lambda}}_{p},\end{split} \tag{28}\] _where_ \[\tilde{\mathbf{\Lambda}}_{p}=\mathbf{\Phi}^{\top}\mathbf{\Phi}+\alpha^{-1}\tilde{\mathbf{I}}_{n _{\phi}}. \tag{29}\] _The scaled negative LML from (11) can then be written as:_ \[\begin{split} J(\mathbf{\Theta};\mathcal{D})&=\frac{1}{ 2}\log(2\pi)+\frac{n_{\phi}}{2m}a+b\\ &+\frac{1}{2m}\log\det(\tilde{\mathbf{\Lambda}}_{p})+\frac{1}{2m}\exp( -2b)\|\mathbf{t}-\mathbf{y}\|_{2}^{2}\\ &+\frac{1}{2m}\exp\left(-a-2b\right)\|\bar{\mathbf{w}}\|_{2}^{2}\end{split} \tag{30}\] _with \(\mathbf{\Theta}=\{\mathbb{W}_{L+1},a,b\}\)._ To train a NN with BLL and univariate output we consider in the following the LML and hyperparameters in the form of Result 2. Additionally, the newly introduced parameter \(\alpha\) in (26) will play an important role in the following discussion on interpolation and extrapolation. ## IV Interpolation and extrapolation with BLL One of the main challenges of the BLL predictive distribution (7) is that for arbitrary extrapolation points the required assumptions for Lemma 1 will not hold. In this section, we discuss the behavior of the BLL predictive distribution in the interpolation and extrapolation regime and propose a method to improve the performance of BLL for extrapolation. To formalize the notion of interpolation and extrapolation, we follow the authors [26] definition of interpolation (thus implicitly defining extrapolation) for which we also need to define the convex hull. **Definition 1** (Convex hull).: _The convex hull of a set of samples \(\mathbf{X}\in\mathbb{R}^{m\times n_{x}}\) is defined as the set:_ \[\mathbb{C}_{\mathbf{X}}=\left\{\mathbf{X}^{\top}\mathbf{\nu}|\mathbf{\nu}\in\mathbb{R}^{m},\ \sum\mathbf{\nu}=1,\mathbf{\nu}\geq 0\right\}.\] **Definition 2** (Interpolation).: _A sample \(\mathbf{x}\) is considered to be an interpolation point of a set of samples \(\mathbf{X}\), given a feature space \(\mathbf{\hat{\Phi}}(\mathbf{X};\mathbb{W}_{L})\) which satisfies Assumption 1 and 2, if:_ \[\mathbf{\hat{\phi}}(\mathbf{x})\in\mathbb{C}_{\mathbf{\hat{\Phi}}(\mathbf{X};\mathbb{W}_{L})}.\] Interpolation is an attribute of the input space but its definition considers the learned feature space of the neural network. Considering the feature space in Definition 2 may seem counter-intuitive but applies well to reality, where nonlinear features for regression can show arbitrary behavior between data points, even for a univariate input. In this case, interpolation points in the input domain are rightly classified as extrapolation points by considering the feature domain. Classifying a point as interpolation or extrapolation is a binary decision. In reality this is a shortcoming, as different degrees of extrapolation are possible. That is, a point "close" to the convex hull might still lead to a trustworthy prediction. The distance to a set, e.g. the convex hull, is defined below. **Definition 3** (Distance).: _For a set \(\mathbb{X}\subset\mathbb{R}^{n_{x}}\) and a point \(\mathbf{x}\in\mathbb{R}^{n_{x}}\) we define the distance \(d(\mathbf{x},\mathbb{X})\) as:_ \[d(\mathbf{x},\mathbb{X})=\inf_{a\in\mathbb{X}}\|x-a\|_{2}^{2}. \tag{31}\] ### _Quantification of interpolation and extrapolation_ In the following, we seek to define a metric to quantify the degree of extrapolation for a nonlinear regression model with feature space. Intuitively, such a metric could be based on the distance, according to Definition 3, to the convex hull of the features. Unfortunately, the distance to the convex hull results in an optimization problem that scales with the number of samples and the feature dimension, which can be a limitation for practical applications. Instead, we propose an approximate metric for which we introduce the _affine cost_ in the following. But first, as related concepts of the affine cost, we define the well known _span_ and _affine hull_. **Definition 4** (Span).: _The span of a set of samples \(\mathbf{X}\in\mathbb{R}^{m\times n_{x}}\) is defined as the set:_ \[\mathbb{S}_{\mathbf{X}}=\left\{\mathbf{X}^{\top}\mathbf{\nu}|\mathbf{\nu}\in\mathbb{R}^{m} \right\}.\] **Definition 5** (Affine hull).: _The affine hull of a set of samples \(\mathbf{X}\in\mathbb{R}^{m\times n_{x}}\) is defined as the set:_ \[\mathbb{A}_{\mathbf{X}}=\left\{\mathbf{X}^{\top}\mathbf{\nu}|\mathbf{\nu}\in\mathbb{R}^{m},\ \sum\mathbf{\nu}=1\right\}.\] **Definition 6** (Affine cost).: _The affine cost of a set of samples \(\mathbf{X}\in\mathbb{R}^{m\times n_{x}}\) and for a test point \(\mathbf{x}\in\mathbb{R}^{n_{x}}\) is defined as the optimal cost:_ \[c_{\mathbb{A}_{\mathbf{X}}}(\mathbf{x})=\operatorname*{minimize}_{\mathbf{ \nu},\mathbf{e}} \|\mathbf{\nu}\|_{2}^{2}+\gamma\|\mathbf{e}\|_{2}^{2} \tag{32a}\] \[\operatorname{subject\ to:} \mathbf{X}^{\top}\mathbf{\nu}+\mathbf{e}=\mathbf{x},\] (32b) \[\sum\mathbf{\nu}=1, \tag{32c}\] _where spanning coefficient \(\mathbf{\nu}\in\mathbb{R}^{m}\) and residual variable \(\mathbf{e}\in\mathbb{R}^{n_{x}}\) are optimization variables and \(\gamma\in\mathbb{R}\) is a weighting factor for the residuals._ The affine cost naturally complements the definition of the affine hull by computing the norm of the respective spanning coefficients \(\mathbf{\nu}\) from Definition 5. Importantly, test values \(\mathbb{A}_{\mathbf{X}}\) also have a value assigned, for which the \(\gamma\)-weighted norm of the residuals \(\mathbf{e}\) is considered. The relationship of convex hull, span and affine hull as well as the affine cost can be inspected in Figure 2. In this figure, two exemplary sets of features \(\mathbf{\tilde{\Phi}}\in\mathbb{R}^{m\times n_{\hat{\phi}}}\), both with \(m=3\) and \(n_{\hat{\phi}}=2\) are presented and we compare the relationship of test to training samples. By comparing, for example Figure 2 a) and d), we can see that the affine cost has a strong relationship with the convex hull on which we have based the notion of interpolation in Definition 2. In particular, we consider the level set \(\mathbb{L}_{\mathbb{A}_{\mathbf{\phi}}}=\{\mathbf{\tilde{\phi}}\in\mathbb{R}^{n_{\hat{ \phi}}}|c_{\mathbb{A}_{\hat{\mathbf{\phi}}}}(\mathbf{\tilde{\phi}})\leq l\}\) obtained with the affine cost and suitable level \(l\) as a soft approximation of the convex hull. Such level sets can be seen in Figure 2 d) and h) as the contour lines of \(c_{\mathbb{A}_{\hat{\mathbf{\phi}}}}\). It holds that for a test point \(\mathbf{\tilde{\phi}}\), the affine cost grows with the distance to the level set \(\mathbb{L}_{\mathbb{A}_{\mathbf{\phi}}}\). In this sense, we consider the distance \(d(\mathbf{\tilde{\phi}},\mathbb{L}_{\mathbb{A}_{\mathbf{\phi}}})\) and, more directly, the affine cost \(c_{\mathbb{A}_{\mathbf{\phi}}}(\mathbf{\tilde{\phi}})\) itself as the desired metric for the degree of extrapolation For the behavior of this metric we distinguish two important cases. In the first case, small values of the affine cost are achieved for test points that are within the affine hull, i.e. \(\mathbf{\tilde{\phi}}\in\mathbb{A}_{\mathbf{\tilde{\Phi}}}\), and for small distances to the convex hull. According to Definition 2, these include all interpolation points and what we consider mild extrapolation. Both test points in Figure 2 h) are examples for this case. In the second case, a test point is not within the affine hull \(\mathbf{\tilde{\phi}}\notin\mathbb{A}_{\mathbf{\tilde{\Phi}}}\). The affine cost is now influenced primarily through the choice of the parameter \(\gamma\). This can be seen by inspection of (32), where the residuals \(\mathbf{e}\) must be used if \(\mathbf{\tilde{\phi}}\notin\mathbb{A}_{\mathbf{\tilde{\Phi}}}\). The cost may then be dominated by the term \(\|\mathbf{e}\|_{2}^{2}\) which is weighted with \(\gamma\). We reason that in the second case the test point can be considered an extrapolation point and \(\gamma\) can be interpreted as a penalty for extrapolation. This case be observed in Figure 2 d) for the test point with higher affine cost. ### _Relationship of affine cost and BLL_ As another main contribution of this work, we introduce Theorem 2 in this subsection to establish the relationship of the BLL covariance and the previously presented affine cost. **Theorem 2** (BLL affine cost).: _If Assumption 4 holds, and with \(\gamma=\alpha\), the affine cost \(c_{\mathbb{A}_{\mathbf{\tilde{\Phi}}}}(\mathbf{\tilde{\phi}}(\mathbf{x}))\), according to Definition 6, is equivalent to the scaled BLL covariance (7c):_ \[c_{\mathbb{A}_{\mathbf{\tilde{\Phi}}}}(\mathbf{\tilde{\phi}}(\mathbf{x}))=\sigma_{e}^{-2} \mathbf{\Sigma}_{\mathbf{\tilde{\phi}}}^{\text{\tiny{\rm{\rm{\rm{\rm{\tiny{\tiny{ \tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny{\tiny \leftleftleftleftleftleftleft({ \left({ \left( \left( \bm test points with \(\tilde{\mathbf{\phi}}(\mathbf{x})\notin\mathbb{A}_{\tilde{\mathbf{\Phi}}}\), clearly indicating extrapolation through high values of the affine cost. The effect can be seen in Figure 2 by comparing subplot d) and h). The application of \(\log\det\)-regularization to obtain matrices with low rank is well known [28] and also applied in other fields such as compressed sensing [29]. The second important implication of Theorem 2 is the interpretation of the parameter \(\alpha\) (or \(\gamma\) respectively) in the context of the affine cost from Definition 6. The parameter directly controls the affine cost and thus the variance for test points \(\tilde{\mathbf{\phi}}(\mathbf{x})\notin\mathbb{A}_{\tilde{\mathbf{\Phi}}}\). This causes a dilemma: Naturally, we have the situation that all training samples \(\tilde{\mathbf{\Phi}}\) are within the affine hull of themselves. Therefore, extrapolation in the sense of \(\tilde{\mathbf{\phi}}(\mathbf{x})\notin\mathbb{A}_{\tilde{\mathbf{\Phi}}}\) does not occur during training and \(\alpha^{*}\), which maximizes the LML, might not yield desirable results. To illustrate the issue we present a simple regression problem with \(n_{x}=n_{y}=1\) and \(m=3\) samples. We investigate a NN with \(n_{\hat{\phi}}=2\) which allows for a graphical representation of the feature space. The NN is trained by maximizing the LML (30), yielding the optimal parameters \(\mathbf{\Theta}^{*}\), with \(a^{*}=\log\alpha^{*}\), as introduced in (27). The predicted mean and standard deviation for the trained model using \(\alpha^{*}\) can be seen in Figure 3 a). The predicted mean of the NN, in light of the sparse training data, is suitable. However, the covariance shows that the prediction is overconfident. We show in Figure 3 b) and c) that this overconfidence can be tackled simply by increasing \(\alpha\) relative to the optimal value \(\alpha^{*}\). The reason for this effect of \(\alpha\) on the extrapolation uncertainty can be seen by inspecting Figure 3 d)-f), where the features (recall \(n_{\hat{\phi}}=2\)) for the training (\(\tilde{\mathbf{\phi}}\)) and the test points (\(\tilde{\mathbf{\Phi}}\)) are displayed. As desired, we have that \(\mathbb{A}_{\tilde{\mathbf{\Phi}}}\subset\mathbb{R}^{n_{\hat{\phi}}}\), that is, the training features lie in a subspace of \(\mathbb{R}^{2}\), which can be seen in Figure 3 where the training samples in the feature space could be connected by a straight line. This effect can be attributed to the \(\log\det\)-regularization in the LML, Extrapolation thus occurs for \(\tilde{\mathbf{\phi}}\notin\mathbb{A}_{\tilde{\mathbf{\Phi}}}\) and for these points the extrapolative uncertainty grows with increasing \(\alpha\). Importantly, by considering Definition 2, we also have extrapolation for test points that are within the convex hull of the input space, i.e. \(\mathbf{x}\in\mathbb{C}_{\mathbf{X}}\). In this example, the only true interpolation points are the training samples for which increasing \(\alpha\) has no significant effect on the predicted covariance. In Figure 4, we further investigate the effect of increasing \(\alpha\) for the same regression problem and NN architecture as displayed in Figure 3. To quantify the quality of the predictive distribution, we use the mean log-predictive density (LPD) [30]: \[\log\bar{p}(\mathbf{t}^{\text{test}})=\frac{1}{m_{\text{test}}}\sum_{i=1}^{m_{ \text{test}}}\log p(\mathfrak{t}=t_{i}^{\text{test}}|\mathcal{D},\mathbf{\Theta}, \mathbf{x}^{\text{test}}) \tag{42}\] which evaluates the logarithm of the posterior distribution of the targets (9) for all test values and computes the average thereof. Importantly, we assume that test data is affected by the same noise as the training data and therefore compute the distribution of the targets. While the output distribution \(\mathbf{y}\) is only affected by the posterior uncertainty of the weights, the target distribution \(\mathbf{t}\) in (5) also consider the additive noise. In Figure 4, we display log-predictive density (42) and the negative LML (30) for the optimal parameters \(\mathbf{\Theta}^{*}\) and as a function of \(\alpha\). As expected, \(\alpha^{*}\) minimizes the negative LML. We see, however, that the optimal value is almost at a plateau and that increasing \(\alpha\) has only a minor effect on the LML. We also see in the top diagram of Figure 4 that the log-predictive Fig. 3: NN with BLL: Predicted mean and standard deviation (7) and feature space with \(n_{\hat{\phi}}=2\) for \(m=3\) training samples. The effect of parameter \(\alpha\) on the extrapolation uncertainty is shown by comparing the optimal \(\alpha^{*}\) (maximization of LML (30)) with suggested improved \(\alpha^{\text{max}}\). density for the training points remains independent of \(\alpha\). On the other hand, we see that the log-predictive density for test points can be increased significantly by setting \(\alpha=\alpha^{\text{max}}\). Further increasing \(\alpha\) has a negative effect as the predicted posterior distribution becomes increasingly flat. As a consequence of this investigation we propose Algorithm 1 to obtain a NN with BLL, trained with LML maximization, and enhanced extrapolation uncertainty. ``` 0:\(\mathcal{D}^{\text{train}}\), \(\mathcal{D}^{\text{val}}\) 0: NN structure (\(L\), \(n_{\phi t},g_{l}(\cdot)\)\(\forall=1\ldots,L\)) \(\boldsymbol{\Theta}^{*}\leftarrow\arg\min_{\boldsymbol{\Theta}}J( \boldsymbol{\Theta};\mathcal{D}^{\text{train}})\)\(\triangleright\) (30) \(\alpha^{\text{max}}\leftarrow\arg\max_{\alpha}\log\tilde{p}(\boldsymbol{t}^{ \text{val}})\)\(\triangleright\) (42) ``` **Algorithm 1** LML optimization with adapted extrapolation penalty \(\alpha\) for enhanced BLL. Optimizing for the single parameter \(\alpha\) in Algorithm 1 is often trivial and we obtain inexact solutions with a grid search. ## V The multivariate case In general, we seek to investigate multivariate problems where, in contrast to Section II, we now have that \(\boldsymbol{t}\in\mathbb{R}^{n_{y}}\). As before, we consider a dataset \(\mathcal{D}=\left(\boldsymbol{X}_{\downarrow}\boldsymbol{T}\right)\) consisting of \(m\) samples and introduce \(\boldsymbol{T}=\left[\boldsymbol{t}_{1},\ldots,\boldsymbol{t}_{m}\right]^{+} \in\mathbb{R}^{m\times n_{y}}\). To obtain the setting in which Lemma 1 holds, we augment Equation (5) for the multivariate case: \[\boldsymbol{T}=\boldsymbol{\Phi}\boldsymbol{W}+\boldsymbol{E}, \tag{43}\] where \(\boldsymbol{E}\in\mathbb{R}^{m\times n_{y}}\) is the matrix of residuals of the regression model. We use the \(\operatorname{vec}(\cdot)\) operation as defined in [31, Defn. 11.5] and vectorize (43): \[\operatorname{vec}(\boldsymbol{T})=\operatorname{vec}(\boldsymbol{\Phi} \boldsymbol{W})+\operatorname{vec}(\boldsymbol{E}). \tag{44}\] Introducing \(\otimes\) as the Kronecker product, this equation can be reformulated as [31, Prop. 11.16(b)]: \[\operatorname{vec}(\boldsymbol{T})=(\boldsymbol{I}_{n_{y}}\otimes \boldsymbol{\Phi})\operatorname{vec}(\boldsymbol{W})+\operatorname{vec}( \boldsymbol{E}), \tag{45}\] and expressed as: \[\hat{\boldsymbol{t}}=\hat{\boldsymbol{\Phi}}\hat{\boldsymbol{w}}+\hat{ \boldsymbol{\epsilon}}. \tag{46}\] In the form of (46), Lemma 1 directly applies to the multivariate case where the prior and noise covariances from Assumption 2 and 3 now refer to: \[\hat{\boldsymbol{\epsilon}} \sim\mathcal{N}(0,\hat{\boldsymbol{\Sigma}}_{E}),\] \[\hat{\boldsymbol{w}} \sim\mathcal{N}(0,\hat{\boldsymbol{\Sigma}}_{\boldsymbol{W}}),\] and for which we need to consider the multivariate feature matrix \(\hat{\boldsymbol{\Phi}}\). ### _Simplified training_ The multivariate settings adds significant complexity to the marginal likelihood maximization introduced in Section III. To reduce the computational complexity, we present Result 3 and two required assumptions in the following. **Assumption 5**.: _Noise and prior, as introduced in Assumption 2 and 3, are uncorrelated for all \(n_{y}\) outputs and identical for all \(m\) samples and all \(n_{\phi}\) features, respectively. We denote \(\boldsymbol{\sigma}_{e}=\left[\sigma_{e,1},\ \ldots,\ \sigma_{e,n_{y}}\right]\) and \(\boldsymbol{\sigma}_{w}=\left[\sigma_{w,1},\ \ldots,\ \sigma_{w,n_{y}}\right]\) and obtain:_ \[\hat{\boldsymbol{\Sigma}}_{E} =\operatorname{diag}(\boldsymbol{\sigma}_{e})\otimes\boldsymbol{ I}_{m}, \tag{47}\] \[\hat{\boldsymbol{\Sigma}}_{W} =\operatorname{diag}(\boldsymbol{\sigma}_{w})\otimes\boldsymbol {I}_{n_{\phi}}. \tag{48}\] We introduce \(\boldsymbol{\alpha}=\frac{\boldsymbol{\sigma}_{w}^{2}}{\boldsymbol{\sigma}_{ e}^{2}}\), similarly to (26), and assume the following. **Assumption 6**.: _For all predicted outputs \(y_{i}\), we have the same parameter \(\alpha\), i.e.:_ \[\alpha_{1}=\cdots=\alpha_{n_{y}}\stackrel{{!}}{{=}}\alpha. \tag{49}\] **Result 3**.: _Let Assumption 5 and 6 hold. The scaled negative LML in (10) for the vectorized multivariate case (46) is:_ \[J(\boldsymbol{\Theta};\mathcal{D}) =\frac{n_{y}}{2m}\left(m\log(2\pi)+n_{\phi}a+\log\det(\bar{ \boldsymbol{\Lambda}}_{p})\right) \tag{50}\] \[+\sum_{i=1}^{n_{y}}\left(b_{i}+\frac{1}{2m}\exp(-2b_{i})\| \boldsymbol{t}_{i}-\boldsymbol{y}_{i}\|_{2}^{2}\right)\] \[+\sum_{i=1}^{n_{y}}\left(\frac{1}{2m}\exp\left(-a-2b_{i}\right)\| \bar{\boldsymbol{w}}_{i}\|_{2}^{2}\right)\] _with \(\boldsymbol{\Theta}=\left\{\mathbb{W}_{L+1},a,b_{1},\ldots,b_{n_{y}}\right\}\) and \(\bar{\boldsymbol{\Lambda}}_{p}\) according to (29). The full precision matrix \(\hat{\boldsymbol{\Lambda}}_{p}\) for the multivariate case can be obtained as:_ \[\hat{\boldsymbol{\Lambda}}_{p}=\operatorname{diag}(\boldsymbol{\sigma}_{e}^{-2 })\otimes\bar{\boldsymbol{\Lambda}}_{p}. \tag{51}\] Proof.: The result follows directly from the properties of the Kronecker product [31] applied to the log-marginal likelihood in (10) with (46), as well as Assumption 5 and 6. Result 3 shows that the LML can be easily expressed for the multivariate case, allowing for fast and efficient NN training. This is largely due to Assumption 5 and 6. While Assumption 5 is a natural extension of Assumption 4 for the multivariate case, Assumption 6 might be questioned. We argue again with our interpretation of \(\alpha\) as an extrapolation Fig. 4: Effect of \(\log(\alpha)\) on the LML (train points) for a trained NN and the mean log-predictive density (42) (test points). The same regression problem and NN as in Figure 3 is considered. penalty weight, as discussed in Section IV. Importantly, extrapolation, as defined in Definition 2, is a property of the feature space and occurs regardless of the number of outputs. Apart from simplifying the LML in (50), Assumption 5 and 6 also yield a simplified computation of the predictive distribution. The outputs are uncorrelated due to Assumption 5 and we can obtain independent covariance matrices: \[\mathbf{\Sigma}_{\hat{y}_{i}}^{\text{\tiny{max}}}(\mathbf{x})=\mathbf{\phi}^{\top}\mathbf{ \Lambda}_{p,i}^{-1}\mathbf{\phi},\quad\text{with:}\ \mathbf{\Lambda}_{p,i}=\sigma_{e,i}^{-2}\bar{\mathbf{\Lambda}}_{p}, \tag{52}\] where we have the same \(\bar{\mathbf{\Lambda}}_{p}\) for all outputs due to Assumption 6. Therefore, the complexity of evaluating the predictive distribution scales negligibly with number of outputs. This is a major advantage of NNs with BLL, in comparison to GPs, where it is common to fit an independent model for each output, ### _Toy example_ To showcase the multivariate NN with BLL we present a toy example in Figure 1. In the example, data is sampled from a function with \(n_{x}=1\) input and \(n_{y}=2\) outputs where both outputs are jointly learned by a single NN. Both outputs exhibit strong non-linear behavior with different noise-levels, in particular \(\sigma_{1}=0.05\) and \(\sigma_{2}=0.2\). We want to emphasize that these variances are assumed to be unknown. The network is trained following Algorithm 1, using the multivariate LML from Result 3. For the toy example, a suitable structure with \(L=2\), \(n_{\hat{\phi}_{1}}=n_{\hat{\phi}_{2}}=n_{\hat{\phi}_{3}}=20\) and \(g_{1}(\cdot)=g_{2}(\cdot)=g_{3}(\cdot)=\tanh(\cdot)\) is determined using trial and error. To maximize the LML, the Adam [32] optimizer is used. To avoid overfitting, we use early-stopping for which we monitor the validation loss (the LML of the validation data). Finally, we compute the standard deviation of the predicted target distribution according to (9). This distribution is visually easier to interpret, as it should contain the noise disturbed train and test samples with a high probability. In Figure 1 we see that the predictive distribution suitably describes both outputs. In particular, the predicted mean and variance is accurate in the interpolation regime where the true noise variance is \(\sigma_{1}=0.05\) and \(\sigma_{2}=0.2\) and the estimated variance \(\sigma_{1}=0.051\) and \(\sigma_{2}=0.17\). Furthermore, the extrapolation regime results in a variance that indicates extrapolation and approximates the true error. In Figure 1 we also compare the extrapolation variance obtained with the optimal value \(\alpha^{*}\) and \(\alpha^{\text{max}}\). Only the latter is suitable to describe the extrapolation regime. To quantify the improvement, we compute the (negative) LML, the log-predictive density and the mean-squared error for \(\alpha^{*}\) and \(\alpha^{\text{max}}\). These performance indicators are presented in Table I. For comparison, we train the identical NN structure by minimizing the mean-squared-error and then use the learned features for BLR as in previous works [5, 25]. The second step of Algorithm 1, that is updating \(\alpha\) subsequently with validation data, can also be applied in this setting and the resulting performance metrics are also shown in Table I. We have two important conclusions and a comment regarding the results in Table I. First, we see that updating \(\alpha\), as proposed in Algorithm 1, significantly improves the log-predictive density (42), both for BLL and BLR. Second, we see that the NN with BLL, which is trained according to Algorithm 1, outperforms BLR with respect to the log-predictive density. Finally, we want to comment on the NLML for the test data in Table I. This metric is displayed for the sake of completeness but has limited expressiveness when judging the models performance on the test data. The test data is chosen deliberately to contain extrapolation points for which the squared error between targets and predictions in (50) can be arbitrarily high. In contrast to the LPD in (42), where this error is weighted with the predicted variance of the targets, the NLML uses the estimated variance of the additive noise as weighting factors. This can lead to very poor results for the NLML if the error exceeds the magnitude of the noise variance, which is to be expected for extrapolation points. Consequentially, we propose to consider the LPD to evaluate the quality of uncertainty quantification. ## VI Bayesian last layer for system identification An important and promising application of NNs with BLL is the probabilistic identification of non-linear dynamic systems. In discrete-time formulation, a dynamic system can be described as: \[\mathbf{s}(k+1) =f_{\text{sys}}(\mathbf{s}(k),\mathbf{a}(k))+\mathbf{\epsilon}_{s}(k), \tag{53a}\] \[\mathbf{r}(k) =h_{\text{sys}}(\mathbf{s}(k),\mathbf{a}(k))+\mathbf{\epsilon}_{r}(k), \tag{53b}\] with states \(\mathbf{s}\in\mathbb{R}^{n_{x}}\), actions \(\mathbf{a}\in\mathbb{R}^{n_{a}}\) and measurements (readings) \(\mathbf{r}\in\mathbb{R}^{n_{r}}\). We denote with \(k\) the discrete time-step \(t_{k}\) and assume unknown additive process noise \(\mathbf{\epsilon}_{s}\in\mathbb{R}^{n_{x}}\) and measurement noise \(\mathbf{\epsilon}_{r}\in\mathbb{R}^{n_{r}}\). For the system identification task, we will generally only have access to the actions and measurements of the system. Assuming that system (53) is observable, it can be expressed as an nonlinear autoregressive model with exogenous inputs (NARX) [33]: \[\Delta\mathbf{r}(k+1)= \tag{54}\] \[f_{\textsc{NARX}}(\mathbf{r}(k),\ldots,\mathbf{r}(k-l),\mathbf{a}(k),\ldots, \mathbf{a}(k-l))+\mathbf{\epsilon},\] with parameter \(l\) and additive noise \(\mathbf{\epsilon}\). In (54) we predict \(\Delta\mathbf{r}(k+1)=\mathbf{r}(k+1)-\mathbf{r}(k)\), which is then used to obtain \(\mathbf{r}(k+1)\). In theory, this is equivalent to predicting \(\mathbf{r}(k+1)\) directly, but often shows better predictive performance in practice [34]. We also introduce \[\hat{\mathbf{s}}=\left[\mathbf{r}(k),\ldots,\mathbf{r}(k-l),\mathbf{a}(k-1),\ldots,\mathbf{a}(k-l )\right], \tag{55}\] as the NARX state, which is used to represent the system analogous to (53) as \[\hat{\mathbf{s}}(k+1)=\hat{f}_{\textsc{NARX}}(\hat{\mathbf{s}}(k),\mathbf{a}(k)). \tag{56}\] It is common to use NNs [35, 36] to approximate the NARX model \(f_{\textsc{NARX}}(\cdot)\). Learning a probabilistic NARX model with NN and BLL also estimates the covariance of the additive noise \(\mathbf{\epsilon}\) in (54) to approximate the effect of process and measurement noise in (53). ### _Linear system example_ We investigate the triple-mass-spring system described in [37] with the provided resources from Github2. The triple-mass-spring system is linear system with \(n_{s}=8\) states, \(n_{a}=2\) input actions and \(n_{r}=3\) measurements (the disc angles) with unknown and different additive noise. The motivation to investigate a linear system stems from the conviction that non-linear methods must first proof themselves in this simple setting. Footnote 2: [https://github.com/4flix/DecPC_Perspective](https://github.com/4flix/DecPC_Perspective) Data from a single simulation using a sequence of persistently exciting inputs is used to construct a dataset \(\mathcal{D}\) of inputs and targets for the NARX model (54) with parameter \(l=3\). This results in \(m=797\) samples used for training with \(n_{x}=15\) input features. We investigate a NN with \(L=2\) layers, \(n_{\widehat{\varphi}_{1}}=40\), \(n_{\widehat{\varphi}_{2}}=40\) and \(g_{1}(\cdot)=g_{2}(\cdot)=\tanh(\cdot)\) activation function. We again optimize with Adam and use early stopping based on the validation error to avoid overfitting. In Figure 5 we showcase the results of the NN with BLL (trained with Algorithm 1) by displaying parity plots for the predicted vs. the true output including the standard deviation of the predictions. The predictive distribution is again computed using (9), to consider the additive noise of the test data. We compare the results for validation data (same distribution as training data) and test data which is created using a greater maximum amplitude of actions. The results in Figure 5 show that for both, validation and test data, suitable predictions are obtained for all outputs. As expected, the test data often yields larger deviations from the true values but, importantly, this error is suitably described by the increased variance. We again compare the NN with BLL with BLR based on features from a trained (mean-squared-error) NN with the same architecture. These results are shown in Table II. We can see that the NN with BLL again outperforms the BLR Fig. 5: Parity plots for predicted \(\Delta\mathbf{r}(k+1)\) of the triple-mass-spring system. Prediction and standard deviation (shown as \(\pm 3\sigma\)-error bars) from NN with BLL. Comparison of validation data vs. test data (obtained with double the input amplitude to enforce extrapolation.) approach in terms of the LPD (42) with and without adapted \(\alpha\). Interestingly, we see that the LPD obtained with BLR benefits insignificantly from adapting \(\alpha\). We find that this is a result of an unsuitable feature space obtained from the trained (mean-squared-error) NN. In particular, this feature space has full rank, in which case the effect of \(\alpha\) on the predictive uncertainty is negligible, as discussed in Section IV. As a final result of this section, we perform an open-loop simulation of the identified NARX models (NN with BLL and BLR with NN features) and compare it to the true system response. All trajectories are created with the same initial state and input trajectories. For the the open-loop simulation, the probabilistic NARX model is evaluated recursively yielding a normal distribution for the predicted next outputs at each step. We propagate uncertainty to successive outputs, similarly to an extended Kalman filter, by linearizing the NARX system as the current state: \[\mathbf{A}(k)=\left.\frac{\partial\hat{f}_{\text{sys}}(\hat{\mathbf{s}},\mathbf{a})}{ \partial\hat{\mathbf{s}}}\right|_{\hat{\mathbf{s}}(k),\mathbf{a}(k)}. \tag{57}\] The results are presented in Figure 6. We see that the estimated system response and uncertainty of the NN with BLL is an excellent match for the true system response. The NARX model with BLR based on NN features performs worse in terms of the mean trajectories and unfortunately leads to an unsuitable uncertainty prediction. This is mostly due to the linearization of the system model which yields an unstable system matrix in this case. This can also be seen in the Figure, where we display the spectral norm of \(\mathbf{A}\). ## VII Conclusions Neural networks with Bayesian last layer are an attractive compromise between tractability and expressiveness in the field of Bayesian neural networks. They are strongly related to Bayesian linear regression in that they consider a learned nonlinear feature space and yield a Gaussian normal distribution as their prediction. As the main difference to Bayesian linear regression, a neural network with Bayesian last layer should be trained by maximizing the marginal likelihood which, importantly, considers all deterministic weights of the neural network as hyperparameters. This training has previously been difficult, as it requires sampling-based variational inference. To this end, our main contribution is a reformulation of the Bayesian last layer marginal likelihood to enable straightforward and fast gradient-based optimization. In comparison to Bayesian linear regression with features from a previously trained neural network, we find that training on the log-marginal likelihood also shows significant advantages in practice. Our second contribution, a simple algorithm to tune the extrapolative uncertainty also shows excellent results in our two presented simulation studies. Our presented methods are formulated for the multivariate case and investigated especially for the application of probabilistic system identification, where the predicted uncertainties suitably describe the approximation error. In future work, we seek to incorporate the probabilistic system model in a stochastic model predictive control framework.
2306.02886
Image Reconstruction for Accelerated MR Scan with Faster Fourier Convolutional Neural Networks
Partial scan is a common approach to accelerate Magnetic Resonance Imaging (MRI) data acquisition in both 2D and 3D settings. However, accurately reconstructing images from partial scan data (i.e., incomplete k-space matrices) remains challenging due to lack of an effectively global receptive field in both spatial and k-space domains. To address this problem, we propose the following: (1) a novel convolutional operator called Faster Fourier Convolution (FasterFC) to replace the two consecutive convolution operations typically used in convolutional neural networks (e.g., U-Net, ResNet). Based on the spectral convolution theorem in Fourier theory, FasterFC employs alternating kernels of size 1 in 3D case) in different domains to extend the dual-domain receptive field to the global and achieves faster calculation speed than traditional Fast Fourier Convolution (FFC). (2) A 2D accelerated MRI method, FasterFC-End-to-End-VarNet, which uses FasterFC to improve the sensitivity maps and reconstruction quality. (3) A multi-stage 3D accelerated MRI method called FasterFC-based Single-to-group Network (FAS-Net) that utilizes a single-to-group algorithm to guide k-space domain reconstruction, followed by FasterFC-based cascaded convolutional neural networks to expand the effective receptive field in the dual-domain. Experimental results on the fastMRI and Stanford MRI Data datasets demonstrate that FasterFC improves the quality of both 2D and 3D reconstruction. Moreover, FAS-Net, as a 3D high-resolution multi-coil (eight) accelerated MRI method, achieves superior reconstruction performance in both qualitative and quantitative results compared with state-of-the-art 2D and 3D methods.
Xiaohan Liu, Yanwei Pang, Xuebin Sun, Yiming Liu, Yonghong Hou, Zhenchang Wang, Xuelong Li
2023-06-05T13:53:57Z
http://arxiv.org/abs/2306.02886v1
# Image Reconstruction for Accelerated MR Scan with Faster Fourier Convolutional Neural Networks ###### Abstract Partial scan is a common approach to accelerate Magnetic Resonance Imaging (MRI) data acquisition in both 2D and 3D settings. However, accurately reconstructing images from partial scan data (i.e., incomplete \(k\)-space matrices) remains challenging due to lack of an effectively global receptive field in both spatial and \(k\)-space domains. To address this problem, we propose the following: (1) a novel convolutional operator called Faster Fourier Convolution (FasterFC) to replace the two consecutive convolution operations typically used in convolutional neural networks (e.g., U-Net, ResNet). Based on the spectral convolution theorem in Fourier theory, FasterFC employs alternating kernels of size 1\(\times\)1 (1\(\times\)1 in 3D case) in different domains to extend the dual-domain receptive field to the global and achieves faster calculation speed than traditional Fast Fourier Convolution (FFC). (2) A 2D accelerated MRI method, FasterFC-End-to-End-VarNet, which uses FasterFC to improve the sensitivity maps and reconstruction quality. (3) A multi-stage 3D accelerated MRI method called FasterFC-based Single-to-group Network (FAS-Net) that utilizes a single-to-group algorithm to guide \(k\)-space domain reconstruction, followed by FasterFC-based cascaded convolutional neural networks to expand the effective receptive field in the dual-domain. Experimental results on the fastMRI and Stanford MRI Data datasets demonstrate that FasterFC improves the quality of both 2D and 3D reconstruction. Moreover, FAS-Net, as a 3D high-resolution (320\(\times\)320\(\times\)256) multi-coil (eight) accelerated MRI method, achieves superior reconstruction performance in both qualitative and quantitative results compared with state-of-the-art 2D and 3D methods. image reconstruction, 3d MRI reconstruction, magnetic resonance imaging, faster Fourier convolution ## I Introduction Magnetic Resonance Imaging (MRI) is a non-invasive imaging technique that can provide better soft tissue contrast than many other imaging modalities. Nevertheless, the data acquisition process in MRI is inherently slow due to the sequential measurement collection in the \(k\)-space domain. This procedure yields a complete \(k\)-space matrix \(\mathbf{K}\) with \(\mathbf{K}\in\mathbb{C}^{N_{s}F,p}\) for 2D data and \(\mathbf{K}\in\mathbb{C}^{N_{s}F,p,S}\) for 3D data where \(N\) stands for the number of parallel coil arrays, \(F\) is the number of frequency-encoding lines, \(P\) and \(S\) are respectively the number of phase-encoding lines from different dimensions. Long measurement times reduce patient comfort, cause motion artifacts, and affect patient throughput. Especially in 3D MRI, the acquisition of high-resolution isotropic data will result in an extremely long scanning time, which severely limits the clinical application of related technologies. A common solution to this problem is to speed up the acquisition process by reducing the number of measurements to obtain an undersampled \(k\)-space matrix \(\overline{\mathbf{K}}\left(\overline{\mathbf{K}}\in\mathbb{C}^{N_{s}F,p}\right)\) for 2D data, \(\overline{\mathbf{K}}\in\mathbb{C}^{N_{s}F,p,S}\) for 3D data. The undersampling process is usually performed along the phase-encoding dimensions. The value of the undersampled position in \(\overline{\mathbf{K}}\) is set to zero. Images directly reconstructed from \(\overline{\mathbf{K}}\) often have many artifacts due to the non-satisfaction of the Nyquist sampling theorem. Compressed Sensing (CS) [1][36] and Parallel Imaging (PI) [23, 24] techniques have been developed to solve the problem of accelerating MRI reconstruction and are available on commercial scanners. Most modern scanners contain multiple receiver coils. In particular, the \(k\)-space sample measured by the \(i\)-th coil can be expressed as: \[\overline{\mathbf{K}}=\mathbf{M}\mathcal{F}(\mathbf{S},\mathbf{x})+\mathbf{ \varepsilon}_{i},i=1,2,...,N\,, \tag{1}\] where \(N\) is the number of coils used for the acquisition, \(\mathbf{\varepsilon}_{i}\) is the measurement noise, \(\mathcal{F}\) is the Fourier transform operator, \(\mathbf{M}\) is the undersampling mask, \(\mathbf{S}_{i}\) is a complex-valued diagonal matrix encoding the position dependent sensitivity map of the \(i\)-th coil, and \(\mathbf{x}\) is the target image to be reconstructed. CS methods usually solve an optimization problem stems from casting the reconstruction as an idealized inverse problem of (1). PI methods use multi-coil redundant information to interpolate values at unsampled locations in the \(k\)-space domain (such as GRAPPA [24], RAKI [25], and KerNL [42]_et al_.). The reconstruction weights are estimated using Auto-Calibration Signal (ACS) through an optimization method. However, such methods only exploit local information in a single data, lack the use of different data priors, are overly sensitive to the characteristics of the data itself, and are easily affected by motion and noise, resulting in a lack of robustness in the reconstruction results. Importantly, PI methods do not work well at high acceleration rates [34]. Recently, more and more methods exploited deep learning [2, 3, 5, 40, 41] for fast MRI reconstruction [16, 17, 18, 19, 20, 21, 22, 35, 38, 39, 43, 44]. Among them, a kind of method uses large-scale datasets to train neural networks to predict _k_-space data [38, 34]. Although _k_-space domain priors for different data are exploited to some extent, all data share the same reconstruction kernel weights, and hence they fail to make full use of the data's respective characteristics. Moreover, the receptive field of the convolutional neural network (CNN, e.g., U-Net [13] and ResNet [14]) is limited, making it challenging to use the information of the ACS when reconstructing the high-frequency region of _k_-space, which further affects the reconstruction performance. We propose a single-to-group _k_-space domain reconstruction algorithm, which can effectively introduce the ACS characteristics of the data itself during deep learning reconstruction and apply it to 3D reconstruction. MR image reconstruction can be reconstructed in either the image domain or the _k_-space domain, or simultaneously in the two domains. The more mainstream research direction is reconstructing MR images in the image domain or two domains (parallel or sequential) with deep learning. Sriram _et al_. proposed an unrolled iterative reconstruction method to use U-Net for reconstruction in the image domain [7]. Only simple data consistency operations are performed in the _k_-space domain. Complementary information from the _k_-space reconstruction is not used. Eo _et al_. established a cross-domain CNN to sequentially reconstruct MR data in the _k_-space and image domains [8]. It takes advantage of dual-domain reconstruction to a certain extent. However, the algorithm lacks dual-domain interaction and has a limited receptive field. It is hard for frequency domain networks to exploit ACS and symmetric position information. Image domain networks also struggle with global artifacts. Liu _et al_. and Ran _et al_. adopted a parallel reconstruction structure, which can better utilize dual-domain complementary information, but still lacks sufficient receptive fields [9, 10]. To alleviate this problem, we propose a novel convolutional operator called Faster Fourier Convolution (FasterFC) to replace the two consecutive convolution operations common in CNNs (e.g., U-Net, ResNet). FasterFC easily integrates dual-domain reconstruction into one network and dramatically expands the dual-domain receptive field based on the spectral convolution theorem in Fourier theory. In addition, experimental results demonstrate that FasterFC can improve the reconstruction performance and can be used in the sensitivity map estimation network in 2D and 3D tasks. In addition, we design a split-slice training strategy to cope with the vast computing resource requirements brought by 3D reconstruction. By integrating the single-to-group _k_-space reconstruction algorithm and FasterFC, a new 3D reconstruction framework is proposed. Compared with the traditional Fast Fourier Convolution (FFC) proposed by Chi _et al_. [11], FasterFC has fewer GFLOPs and a much faster calculation speed. Therefore, FasterFC is more desirable for computation-intensive 3D reconstruction tasks. There are few deep learning based reconstruction methods for 3D fast MRI. One of the primary challenges is the computational burden posed by 3D high-resolution multi-coil isotropic data. The memory usage required for typical 3D multi-coil reconstruction methods can easily surpass the maximum storage capacity of commercially available GPUs. As a result, it is challenging to directly extend the deep learning methods for 2D fast MRI reconstruction to 3D multi-coil tasks. The novelties and contributions of the paper are as follows: * A novel convolutional operator called FasterFC, is proposed to replace the two consecutive convolution operations common in CNNs of deep learning based MR image reconstruction from undersampled data. FasterFC results in the global respective field and is much more efficient than the traditional two consecutive convolution operators and classical FFC [11, 12]. * Applying FasterFC in U-Net [13] yields better reconstruction accuracy, training, and inferring efficiency for single-coil fast MRI. Implementing FasterFC in End-to-End Variational Networks (E2E-VarNet, a state-of-the-art multi-coil MR image reconstruction method) [7], consistently improves reconstruction accuracy in terms of NMSE, PSNR, and SSIM without an increase of model size. * We propose a 3D fast MR image reconstruction method, called FAS-Net, where FasterFC is employed for 3D sensitive map estimation and 3D image reconstruction. Moreover, we propose a single-to-group strategy for 3D reconstruction in _k_-space domain to employ local information in a single volume and group priors in a group of training volumes. The single-to-group _k_-space domain reconstruction together with the FasterFC image domain reconstruction yields promising reconstruction results. ## II Proposed Methods ### _Faster Fourier Convolution_ FasterFC (Fig. 1) is designed to replace two consecutive convolution operations (Fig. 1(a)) common in CNNs (e.g., U-Net, ResNet). The traditional two consecutive convolution operations have a very small size of the receptive field. By contrast, FasterFC has a global respective field. The 2D and 3D versions of FasterFC are shown in Fig. 1(b) and Fig. 1(c) and are suitable for 2D and 3D reconstruction, respectively. FasterFC takes an image or spatial domain feature \(f_{\textit{input}}\) as input and outputs a refined image or spatial domain feature \(f_{\textit{output}}\). Firstly, FasterFC employs a 1\(\times\)1 convolution to map the input \(f_{\textit{input}}\) to a feature map \(f_{i}\) with the number of channels same as the desired output: \[f_{i}=LReLU(InsNorm(Conv_{i,1}(f_{input}))),n)\,, \tag{2}\] where \(LReLU\) is leaky ReLU [37], \(n\) is the negative slope of the leaky ReLU, and \(InsNorm\) is instance normalization. Then \(f_{i}\) is input into a vanilla 3\(\times\)3 convolution with residual connection to expand the local receptive field and refine features in different positions and channels: \[f_{2}=LReLU(InsNorm(Conv_{i,3}(f_{i})),n)+f_{i}\,, \tag{3}\] where \(f_{2}\) is the output of the unique 3\(\times\)3 convolution in FasterFC. Then \(f_{2}\) is processed by a 1\(\times\)1 convolution operation to adjust the channel information and expand the receptive field in the \(k\)-space domain to all frequencies: \[f_{3}=LReLU(InsNorm(Conv_{i,1}(f_{2})),n)\,, \tag{4}\] where \(f_{3}\) is the output of the second 1\(\times\)1 convolution in FasterFC. Subsequently, a cross-domain 1\(\times\)1 convolution with residual connection takes \(f_{3}\) as input to extract features in the Fourier domain so that the receptive field of spatial domain input can be expanded into all positions. Generally, we designate the first half of the channels as real channels and the second half as imaginary channels. So \(f_{3}\) can be transformed into the frequency domain using the complex FFT. After FFT, a frequency domain feature map is obtained, which has the same resolution as \(f_{3}\). The 1\(\times\)1 convolution is then adopted to refine the frequency domain features. Finally, the Inverse FFT (IFFT) transforms the output of the convolution into the spatial domain: \[f_{4}=\mathcal{F}^{-1}(LReLU(InsNorm(Conv_{i,1}(\mathcal{F}(f_{3}))),n))+f_{3}\,. \tag{5}\] \(f_{3}\) and \(f_{4}\) are concatenated together in the channel dimension and the result is used as the input of the last 1\(\times\)1 convolution: \[f_{3,4}=Concatenate(f_{3},f_{4})\,. \tag{6}\] Finally, the last 1\(\times\)1 convolution is used to pick the most suitable features and restore channel dimensions to the predetermined size (half of the input of the last 1\(\times\)1 convolution): \[f_{output}=LReLU(InsNorm(Conv_{i,1}(f_{3,4})),n)\,. \tag{7}\] Traditional two consecutive convolution operations (two 3\(\times\)3 convolutions) have as small as 5\(\times\)5 receptive field size. Because FFT and IFFT are performed in FasterFC, FasterFC has global respective field size. As a result of substituting two convolutional layers with a solitary FasterFC, which solely necessitates a single domain transformation, the computational speed of FasterFC is nearly twofold in comparison to the FFC requiring two domain transformations. Notwithstanding, FasterFC maintains its proficiency in feature extraction and reconstruction performance without experiencing any degradation. ### _Faster Fourier Convolution Based U-Net_ This section details how 2D FasterFC works in U-Net [13] (a common CNN widely used in fast MRI tasks [7], [9]). U-Net has a symmetrical encoder-decoder structure, where the encoder undergoes multiple downsampling and the decoder employs multi-level upsampling to restore features to their original resolution. Each stage uses two convolution operations for feature extraction in both the encoder and the decoder. FasterFC replaces two consecutive convolution operations in every level of U-Net. This process is convenient and does not change the size of the input and output feature maps for each stage. The resultant network is called FasterFC-U-Net. The structure of U-Net, FasterFC-U-Net, and the replacement process are shown in Fig. 2. The parameter number of an \(L\)-level FasterFC-U-Net (downsampling \(L\) times) is as follows: \[\begin{split} N_{FastFC}=&\,4\times c+4\times c \times c+(c\times c)\times(3\times 3)\\ +&\sum_{i=1}^{L}2^{i-1}c\times 2^{i}c+4\times 2^{i}c \times 2^{i}c+(2^{i}c\times 2^{i}c)\times(3\times 3)\\ +&\sum_{i=1}^{L}(2^{i}c\times 2^{i-1}c+4\times 2 ^{i-1}c\times 2^{i-1}c\\ +&(2^{i-1}c\times 2^{i-1}c)\times(3\times 3))+(\sum_{i=1}^{L }2^{i}c\times 2^{i-1}c)\times(2\times 2).\end{split} \tag{8}\] For an \(L\)-level U-Net, the number of parameters is \(N_{u}\) : Fig. 1: The architecture of (a) traditional two consecutive convolutions, (b) 2D FasterFC, and (c) 3D FasterFC. \[\begin{split} N_{u}&=(2\times c+c\times c+\sum_{i=1}^{L-1}2^ {i-1}c\times 2^{i}c+2^{i}c\times 2^{i}c)\times(3\times 3)\\ &+2\times c+(\sum_{i=1}^{L}2^{i}c\times 2^{i-1}c+2^{i-1}c\times 2 ^{i-1}c)\times(3\times 3)\\ &+(2^{L-1}c\times 2^{L}c+2^{L}c\times 2^{L}c)\times(3\times 3) \\ &+(\sum_{i=1}^{L}2^{i}c\times 2^{i-1}c)\times(2\times 2). \end{split} \tag{9}\] The ratio \(r=N_{r_{\text{FastFC}}}/N_{u}\) between \(N_{r_{\text{FastFC}}}\) and \(N_{u}\) is a function of \(c\) and \(L\). The curves of \(r\) versus \(c\) and \(L\) are shown in Fig. 3. For the typical case of \(c=32\) and \(L=4\), \(r=0.86\) holds. That is, the model size of FasterFC-U-Net is 86% of that of U-Net. Therefore, compared with U-Net, FasterFC-U-Net is more lightweight but has better reconstruction accuracy due to its much larger receptive fields in both the image domain and frequency domain. ### _Faster Fourier Convolution Based E2E-VarNet_ FasterFC can also be used for 2D multi-coil MR image reconstruction. E2E-VarNet [7] is a classic 2D multi-coil MR reconstruction structure. It consists of two parts: one part uses U-Net to predict the sensitivity maps; the other part uses the estimated sensitivity maps and cascaded U-Nets to optimize the MR data iteratively: \[\mathbf{K}^{t+1}=\mathbf{K}^{t}-\eta^{t}\mathbf{M}(\mathbf{K}^{t}-\mathbf{ \vec{K}}^{t})+G(\mathbf{K}^{t})\, \tag{10}\] where \(\eta^{{}^{\prime}}\) is used to weight the data based on the distance from the raw measured value to balance the consistency and smoothness of the data. The refinement module \(G\) is defined as follows: \[G(\mathbf{K}^{t})=\mathcal{I}\circ\mathcal{E}\circ UNet(\mathcal{R}\circ \mathcal{F}^{-1}(\mathbf{K}^{t}))\, \tag{11}\] the operator \(\mathcal{E}\) denotes the expansion operator, which accepts the input of the image \(\mathbf{x}\) and sensitivity maps. In the idealized noise-free scenario, this operator calculates the image perceived by each coil: \[\mathcal{L}(\mathbf{x})=(\mathbf{x}_{1},...,\mathbf{x}_{{}_{N}})=(\mathbf{S},\mathbf{x},...,\mathbf{S}_{{}_{N}}\mathbf{x}). \tag{12}\] \(\mathcal{R}\) is the reduce operator to combine the images from all the coils: Fig. 4: The architecture of FAS-Net. Fig. 3: The ratio \(r=N_{r_{\text{randFC}}}/N_{u}\). Fig. 2: The architecture of U-Net, FasterFC-U-Net, and how FasterFC replaces two consecutive convolution operations in U-Net. \[\mathcal{K}(\mathbf{x}_{1},...,\mathbf{x}_{N})=\sum_{i-1}^{N}\mathbf{S}_{i}^{*} \mathbf{x}_{i}\, \tag{13}\] where \(\mathbf{S}_{i}\) are the sensitivity maps estimated by a U-Net, \(\mathbf{S}_{i}^{*}\) refers to the adjoint matrix of matrix \(\mathbf{S}_{i}\): \[\mathbf{S}=d\!S\circ UNet(\mathcal{F}^{-1}\circ\mathbf{M}_{center}(\overline{ \mathbf{K}})). \tag{14}\] The \(\mathbf{M}_{center}\) operator zeros out all lines except for the ACS lines. The \(d\!S\) operator normalizes the estimated sensitivity maps to satisfy: \[\sum_{i-1}^{N}\mathbf{S}_{i}^{*}\mathbf{S}_{i}=1\,. \tag{15}\] We propose to modify E2E-VarNet by using FasterFC. The modified method is called FasterFC-E2E-VarNet. Specifically, all U-Nets used in E2E-VarNet are replaced by FasterFC. The U-Net used for sensitivity maps estimation in (14) is replaced by FasterFC-U-Net and the sensitivity map is expressed as: \[\mathbf{S}=d\!S\circ FasterFCUNet(\mathcal{F}^{-1}\circ\mathbf{M}_{center}( \overline{\mathbf{K}}))\,. \tag{16}\] The U-Nets used for MR image refinement in (11) are replaced by FasterFC-U-Net to achieve dual-domain global receptive field: \[G(\mathbf{K}^{i})=\mathcal{F}\circ\mathcal{E}\circ FasterFCUNet(\mathcal{K} \circ\mathcal{F}^{-1}(\mathbf{K}^{i})). \tag{17}\] Both replacements can effectively improve the reconstruction performance of E2E-VarNet. ### _FasterFC Based Single-to-group Network for 3D Reconstruction_ We propose to adopt FasterFC for 3D high-resolution multi-coil fast MRI reconstruction. The proposed method is called FAS-Net. The FAS-Net (Fig. 4) begins with reconstruction in \(k\)-space domain by a single-to-group algorithm (Fig. 4(a)) followed by reconstruction in image domain by FasterFC based 3D sensitivity map estimation and image reconstruction (Fig. 4(b)). The single-to-group algorithm for \(k\)-space reconstruction consists of a single reconstruction stage (Fig. 4(\(\raisebox{-0.86pt}{\scalebox{1.2}{$\circ$}})\)) and a group reconstruction stage (Fig. 4(\(\raisebox{-0.86pt}{\scalebox{1.2}{$\circ$}}\))). In the single reconstruction stage, only a single volume (a set of slices) is used for training the learnable parameters independently. In the group reconstruction stage, all the volumes of the training dataset are used for learning parameters so that priors of the whole dataset can be exploited. Generally, a 3D image reconstruction algorithm is much more time-consuming and memory-consuming than a 2D image reconstruction algorithm. We propose three strategies to tackle these problems. (1) The single reconstruction stage, group reconstruction stage, and FasterFC stage are performed in a separate manner instead of an end-to-end manner. After training the current stage, its model is fixed and its output forms a new dataset for the subsequent stage. (2) Hight-weight networks (3D-RAKI and 3D K-Net) are designed for \(k\)-space domain reconstruction (i.e., single reconstruction followed by group reconstruction). (3) A split-slice strategy is proposed for image domain reconstruction (i.e., FasterFC stage). #### Iii-D1 Single Reconstruction Stage of k-space Domain Reconstruction Single reconstruction in \(k\)-space domain is a process of learning volume-specific parameters and reconstructing the volume with the parameters. The core is to embed the local \(k\)-space prior of an ACS region into regions beyond the ACS region. Classical algorithms such as GRAPPA [24] and RAKI [25] can be used for single reconstruction. But they are oriented to 2D reconstruction. We extend RAKI to a 3D version called 3D-RAKI. The inference process of 3D-RAKI is shown in the bottom of Fig. 4(a). The input of 3D-RAKI is the undersampled zero-filled \(k\)-space matrix \(\overline{\mathbf{K}}\in\mathbb{R}^{F\times p\times S\times 2N}\). Assume that the accelerate rates of the two orthogonal phase-encoding directions are identical. Let \(R\) be the acceleration rate in one direction. The total acceleration rate simultaneous in two directions is \(R^{2}\). The output of the 3D-RAKI for coil \(i\) is written as \(\widetilde{\mathbf{K}}\in\mathbb{R}^{F\times p\times S\times 2}\). There is a 3D CNN model \(g_{i}\) for coil \(i\) to map \(\overline{\mathbf{K}}\) to \(\widetilde{\mathbf{K}}\) : \[\widetilde{\mathbf{K}}_{i}=g_{i}(\overline{\mathbf{K}}). \tag{18}\] \(g_{1},...,g_{N}\) have the same shallow architecture of 3D CNN but their parameters are not shared. The 3D CNN model for a coil consists of three convolutional layers. The filters of three convolutional layers are expressed as \(\mathbf{w}_{1},\mathbf{w}_{2},\mathbf{w}_{3}\). The size of \(\mathbf{w}_{1},\mathbf{w}_{2},\mathbf{w}_{3}\) are \(b_{1}^{F}\times b_{1}^{F}\times b_{1}^{F}\times 2N\times n_{1}\), \(b_{2}^{F}\times b_{2}^{F}\times b_{2}^{F}\times n_{1}\times n_{2}\), and \(b_{3}^{F}\times b_{3}^{F}\times b_{3}^{F}\times n_{2}\times n_{out}\), respectively. Nonlinear activation function ReLU are applied for the first two layers and a linear activation function is applied for the third layer. The first layer is computed by: \[F_{1}(\overline{\mathbf{K}})=\text{ReLU}(\mathbf{w}_{1}\ast\overline{\mathbf{ K}})\,. \tag{19}\] The second layer takes the output of the first layer as input and can be computed by: \[F_{2}(F_{1}(\overline{\mathbf{K}}))=\text{ReLU}(\mathbf{w}_{2}\ast F_{1}( \overline{\mathbf{K}}))\,. \tag{20}\] With a linear activation function, the output of the third layer can be calculated by: \[F_{2}(F_{2}(F_{1}(\overline{\mathbf{K}})))=\mathbf{w}_{3}\ast F_{2}(F_{1}( \overline{\mathbf{K}}))\,. \tag{21}\] It is noted that all the layers employ dilation convolution with dilation rate being \(R\) for the purpose of making use of acquired encoding lines. The network parameters \(\mathbf{\theta}_{j}=\{\mathbf{w}_{1},\mathbf{w}_{2},\mathbf{w}_{3}\}\) is trained by gradient descent with backpropagation [28] and momentum [29]. Supervision is applied on the ACS region of \(\widetilde{\mathbf{K}}\). By filling all the undersampled \(k\)-space data of the dataset with 3D-RAKI separately, we obtain a new \(k\)-space dataset \(\{\widetilde{\mathbf{K}}_{1}^{30},...,\widetilde{\mathbf{K}}_{I}^{30}\}\) that is initially filled with local priors. Next, group reconstruction can be used for further \(k\)-space data refinement. To make use of the priors contained in a group of training volumes, we propose to generalize our previous work of K-Net [9]. For learning global priors present in different data, we have extended the K-Net to a 3D version in group reconstruction. A 3D K-Net, featuring a residual connection, is employed to reconstruct _k_-space domain data generated by the 3D-RAKI. The process of group reconstruction is illustrated in Fig. 4\(\backslash\)2. The architecture of the 3D K-Net is depicted in Fig. 5, which is nearly identical to that of a traditional 3D U-Net. The primary differences lie in the pooling and upsampling operators, which are replaced by 3D cross-domain pooling (bottom-left of Fig. 5) and 3D cross-domain upsampling (bottom-right of Fig. 5). In the proposed 3D cross-domain pooling, the input is transformed to image domain by 3D IFFT. Pooling is then applied in the image domain. Finally, 3D FFT is employed re-transform the pooled data to frequency domain. The 3D cross-domain upsampling has the same process with the pooling operation instead of upsampling. In the inference phase, the 3D K-Net with residual connection takes the 3D _k_-space data filled with 3D-RAKI as input, of size \(2N\times F\times S\). Then Soft DC [7] criterion is adopted in group reconstruction: \[k_{src}(j)=\begin{cases}\overline{k}(j)&\text{if }j\not\in\Omega,\\ \overline{k}(j)-\gamma(\overline{k}(j)-k(j))&\text{if }j\in\Omega.\end{cases}, \tag{22}\] where \(j\) represents the index of the vectorized representation of _k_-space data, \(\overline{k}\) denotes the output of a 3D K-Net, \(k\) means the raw incomplete _k_-space data, \(\Omega\) is the index set of sampling data, and \(\gamma\) is a trainable hyperparameter to balance predicted data and original sampling data. As defined in (22), if the position of the input _k_-space data point is not sampled ( \(j\not\in\Omega\) ), the predicted values are used directly. For the sampled points, \(\gamma\) is used to weigh the data based on the distance from the original measured value to balance the consistency and smoothness of the data. Finally, 3D IFFT transforms multi-coil refined _k_-space data into the spatial domain and is used as the input to FasterFC-based image reconstruction. This process can be formulated as: \[\overline{\mathbf{x}}^{\textit{K-Net}} =\mathcal{F}^{\cdot\cdot\cdot}\circ\overline{\mathbf{K}}^{\textit {X-Net}} \tag{23}\] \[=\mathcal{F}^{\cdot\cdot\cdot}\circ\textit{SoftDC}\circ(\textit{ KNet}(\tilde{\mathbf{K}}^{\textit{3D}})+\tilde{\mathbf{K}}^{\textit{3D}}).\] In the training phase, the output of the 3D K-Net is supervised by the ground truth (denoted by \(\mathbf{x}\) ) of fully sampled images obtained by the complete _k_-space matrices. The following Structural Similarity (SSIM) [4] loss function Figure 5: The architecture of 3D K-Net. Figure 6: The process of (a) split-slice training and (b) split-slice reconstruction. \[J(\bar{\mathbf{x}}^{K^{Nxt}},\mathbf{x})\ \ \text{is used to train the 3D K-Net:}\] \[J(\bar{\mathbf{x}}^{K^{Nxt}},\mathbf{x})=1\text{-}\mathit{SSIM}(\bar{ \mathbf{x}}^{K^{Nxt}},\mathbf{x})\,, \tag{24}\] where \(\mathit{SSIM}(\bar{\mathbf{x}}^{K^{Nxt}},\mathbf{x})\) is the value of SSIM between \(\bar{\mathbf{x}}^{K^{Nxt}}\) and \(\mathbf{x},\ \bar{\mathbf{x}}^{K^{Nxt}}=\mathit{RSS}\circ ab\circ\bar{\mathbf{x}}^{K^{Nxt}}\), and \(ab\mathbf{s}\) computes the absolute value of a complex valued data followed by a root-sum-squares (\(\mathit{RSS}\)) reduction for each pixel: \[\bar{\mathbf{x}}^{K^{Nxt}}=\mathit{RSS}(\overline{\mathbf{x}}_{1}^{K^{Nxt}},...,\overline{\mathbf{x}}_{N}^{K^{Nxt}})=\sqrt[\overline{\mathbf{x}}_{1}^{K^{ Nxt}}]^{2}. \tag{25}\] _3) 3D-FasterFC Based Image Reconstruction_ The output of the K-Net based group reconstruction is used as the input to 3D-FasterFC based image reconstruction. It is composed of 3D-FasterFC based 3D sensitivity estimation (top of Fig. 4(b)) and 3D-FasterFC based image reconstruction (bottom of Fig. 4(b)). **Split-slice strategy**: Directly applying the proposed FasterFC based method on 3D data is so memory-consuming that the memory consumption can easily exceed the maximum of memory of available GPUs. In fact, the memory consumption problem severely limits the research on 3D reconstruction. To tackle the problem, we propose a split-slice strategy for extract features with 3D convolutional filters. The specific process of the method is demonstrated in Fig. 6. In the training phase, every \(\overline{\mathbf{x}}^{K^{Nxt}}\) in the train set is split into several small slice blocks. The resolution of the slice block is \(N\times L\times P\times S\times 2\) ( 2 is the complex dimension consisting of the real and imaginary parts). The first slice block starts from the first slice. The next slice block starts from the \(L\) / 2-th slice. That is, the distance of starting position of adjacent slice blocks is \(L\) / 2, and adjacent blocks overlap with \(L\) / 2 slices. So, each \(\overline{\mathbf{x}}^{K^{Nxt}}\) can be split into \(2\times F\) / \(L\) - 1 blocks, denoted by \(N_{\text{slice\_block}}\). For an MR dataset that has \(N_{\text{train\_data}}\) high-resolution multi-coil 3D \(k\)-space data, \(N_{\text{slice\_block}}\times N_{\text{train\_data}}\) training data are obtained for split-slice training. The target data \(\mathbf{x}\) are processed by the same split-slice operation to get \(N_{\text{slice\_block}}\times N_{\text{train\_data}}\) target data. These new target data have a corresponding relationship with the input data, which are used as the ground truth for training the FasterFC-based network. The details of the training process are shown in Fig. 6(a). In the inference phase described in Fig. 6(b), the input data with size \(N\times F\times P\times S\times 2\) is first split into \(N_{\text{slice\_block}}=2\times F\) / \(L\) - 1 slice blocks through the split-slice operation. Each slice block with size \(N\times L\times P\times S\times 2\) is fed into the reconstruction network for forward propagation, resulting in a reconstructed 3D slice block. Then, all the \(2\times F\) / \(L\) - 1 refined 3D slice blocks compose a complete full-resolution 3D reconstructed image. The composition process follows the following principles: (1) The first slice block takes the first \(L\times 3\) / 4 slices; (2) The last slice block takes the last \(L\times 3\) / 4 slices; (3) The rest of the slice blocks take the middle \(L\) / 2 slices. Then all the selected slices are sequentially stitched into a complete 3D image with original size \(F\). The split-slice strategy can reduce the computational cost during training by a factor of \(F\) / \(L\) (when \(F\) = 320 and \(L\) = 16, the computational cost can be reduced to just \(1\) / 20 of the original). Furthermore, this method supervises all the \(L\) slices in a block at each training iteration. But in the inference phase, only the middle \(L\) / 2 slices are used for most of the slice blocks. These slices contain sufficient information from the surrounding slices and exhibit better reconstruction quality. **3D-FasterFC based 3D sensitivity map estimation and global receptive field reconstruction**: Now we describe how 3D-FasterFC can be used for the reconstruction method in the split-slice strategy. The core is to use 3D-FasterFC to form an encoder-decoder network which we called 3D-FasterFC-U-Net (Fig. 7). As shown in Fig. 4(b), one 3D-FasterFC-U-Net is used for estimating 3D sensitivity map and cascaded 3D-FasterFC-U-Nets are used for reconstruction. The cascade times are denoted by \(T\). As mentioned above, split-slice reconstruction takes in \(\overline{\mathbf{x}}^{K^{Nxt}}\) and splits it into \(2\times F\) / \(L\) - 1 slice blocks (as shown in the up-right of Fig. 4). During the inference phase, all slice blocks are fed into the reconstruction network (i.e., 3D-FasterFC-U-Net) for refinement. Each block is first fed into a 3D FasterFC-U-Net to estimate the sensitivity maps. Different coil channels share one sensitivity map estimation network. For notation convenience, 3D-FasterFC-U-Net is also written as \(FasterFCUNet_{3D}\). The sensitivity map estimation process can be formulated as: \[\mathbf{S}_{b}=\mathit{dSS}\circ\mathit{FasterFCUNet}_{3D}(\overline{\mathbf{x }}_{b}^{\text{scu}}),b=1,...,N_{\text{slice\_block}}. \tag{26}\] Next, we fuse the multi-coil images using the estimated sensitivity maps: \[\overline{\mathbf{x}}_{b}=\sum_{i=1}^{N}\mathbf{S}_{b,i}^{*}\mathbf{x}_{b,i},b= 1,...,N_{\text{slice\_block}}. \tag{27}\] A multi-stage FasterFC-U-Net network with residuals takes \(\overline{\mathbf{x}}_{b}\) as input for cascaded refinement: \[\overline{\mathbf{x}}_{b}^{\text{scu}+1}=\mathit{FasterFCUNet}_{3D}(\overline{ \mathbf{x}}_{b}^{*})+\overline{\mathbf{x}}_{b}^{*},t=1,...,\text{T}. \tag{28}\] Finally, all the \(\overline{\mathbf{x}}_{b}^{\text{scr}}\) merged into one full-resolution complex 3D image \(\overline{\mathbf{x}}_{c}\) as depicted in Fig. 6. The output \(\overline{\mathbf{x}}\) of FAS-Net then can be gotten after an absolution operation in the Figure 7: The architecture of 3D FasterFC-U-Net. complex channel. ## III Results ### _Data_ We demonstrate the effectiveness of FasterFC in multiple acquisition scenarios. For both 2D and 3D tasks, we employ Cartesian undersampling along the phase encoding direction. In the 2D single-coil and multi-coil tasks, we conduct experiments on the fastMRI dataset [31] using random Cartesian sampling with acceleration factor (AF) of 4 (where the middle 8% of the phase encoding lines are fully sampled and referred to as ACS region). This experimental setup is consistent with the requirements of the official fastMRI task. In the 3D multi-coil study, we utilize the Stanford MRI Data dataset [32], which has more slice numbers. To assess the adaptability of our proposed FAS-Net and evaluate the generalization of FasterFC, we adopt equispaced Cartesian undersampling with an AF of 4 (i.e., 2-times-accelerated equispaced sampling in the two-phase encoding directions, and the middle 16% phase-encoded lines are fully sampled). It should be noted that because the Stanford MRI Data dataset employs an elliptical sampling strategy, the total acceleration factor is approximately 5. Schematic illustrations of the two undersampling trajectories mentioned above are provided in Fig. 8. ### _FastMRI_ The fastMRI knee dataset contains raw _k_-space data and DICOM images, acquired by 3T and 1.5T MR devices. The dataset is organized into many volumes, each consisting of approximately 36 slices. The training, validation, and test sets comprise 973, 199, and 108 volumes, respectively. The data was acquired using a Cartesian 2D Turbo Spin Echo (TSE) sequence with a 15-channel phased array coil in the multi-coil dataset. Furthermore, the fastMRI dataset includes single-coil data generated from the multi-coil data. We verified the effectiveness of FasterFC on fastMRI single-coil dataset and demonstrated that FasterFC-U-Net has a faster calculation speed. Additionally, we validated the efficacy of FasterFC on the fastMRI multi-coil knee dataset. We do not perform 3D experiments with the fastMRI dataset because it has few slices, and 3D reconstruction networks will not be able to take full advantage of the slice dimension. _2) Stanford MRI Data_ We conducted 3D experiments on the Stanford MRI Data dataset, which was obtained from the Stanford Fully sampled 3D FSE Knees project. The data were collected using an 8-channel phased array coil by a 3T GE MEDICAL SYSTEMS scanner. The sequence parameters were defined as follows: matrix size was 320\(\times\)320\(\times\)1, field of view was 160\(mm\times\)160\(mm\times\)153.6\(mm\), number of slices was 256, and trajectory was cartesian. The Stanford MRI Data dataset contains 19 volumes. We divided the 19 volumes into 14, 3, 2 for the training, validation, and test set. As mentioned in [44], Stanford MRI Data contains raw data collected at isotropic resolution. So, its data type is perfect for 3D reconstruction experiments. However, due to the small number of volumes, there are few 3D methods based on Stanford MRI Data that can achieve performance superior to 2D methods. To address this limitation, we propose FAS-Net, which employs single-to-group algorithm and FasterFC methods to improve performance. Additionally, we employed a split-slice training strategy to increase the number of training iterations while reducing the amount of computation. These modifications enabled FAS-Net to achieve superior reconstruction performance compared to the 2D state-of-the-art method, even when the amount of data is limited. ### _Experimental Setup_ #### Iii-B1 Metrics Averaged Structural Similarity (SSIM), Peak Signal to Noise Ratio (PSNR), and Normalized Mean Squared Error (NMSE) are adopted to measure the quality of reconstructed images [4][31]. The parameters and definitions of the above three metrics are the same as described in the fastMRI paper [31]. _2) Implementation Details_ #### Iii-B2 Single-coil experimental implementation details For 2D single-coil experiments, we compare Faster-U-Net (Section III-B) with traditional U-Net baseline and FFC-U-Net. The experimental configuration of U-Net is consistent with the experiments in [31]. FFC-U-Net improves U-Net by changing each convolutional layer in the network to FFC [12]. Faster-U-Net replaces the network's adjacent two convolutional layers with one FasterFC module (as described in Fig. 2). Such comparative experiments can help understand the effectiveness of FasterFC, and can analyze various properties of the network, including performance, the number of parameters and calculation speed. The entry channel number \(c\) of these three networks is all 32, and downsampling rate is 4. The experiments are conducted on the fastMRI knee single-coil dataset. For the 2D multi-coil experiments, we verify the superiority of the proposed FasterFC-E2E-VarNet (Section III-C) over classic E2E-VarNet. In our 2D multi-coil experiments, we developed two improved networks: (1) FasterFC-Ref-E2E-VarNet, which replaces U-Nets in the refinement modules of E2E-VarNet with FasterFC-U-Net, and (2) FasterFC-E2E-VarNet, which replaces U-Net used for estimating sensitivity maps with FasterFC-U-Net in FasterFC-Ref-E2E-VarNet. By comparing the results of these three experiments, we can analyze the ability of FasterFC to enhance the performance of sensitivity map estimation and reconstruction. All experimental configurations were kept the same as in [7], except for the number of cascades, which was set to 4 in our experiment. #### Iv-Bc 3D multi-coil experimental implementation details The proposed FAS-Net (Section III-D) is compared with the following eight state-of-the-art 2D and 3D algorithms: CS [31], 2D U-Net Baseline [31], KIKI-net [8], D5C5 [6], ComplexMRI [33], Deep-SLR [30], E2E-VarNet [7], and 3D U-Net [45]. All experiments use the same mask matrix as FAS-Net, which is shown in Fig. 8(b). We used the same parameters in [31] for CS reconstruction. The 2D U-Net Baseline, a classic 2D spatial domain method, is implemented as [31]. KIKI-Net, D5C5, and ComplexMRI are three state-of-the-art methods utilizing the iterative network architecture. KIKI-net is also a dual-domain multi-stage reconstruction method to compare the effectiveness of FAS-Net's multi-stage strategy. ComplexMRI utilizes the complex convolution to process the complex values in the Stanford MRI data. Deep-SLR and E2E-VarNet are implemented strictly according to the original paper [7], [30] and source code. The 3D U-Net is a method that can flexibly adjust network parameters to adapt to the size of the memory of the experimental equipment, where the entry channels are set to 16, and the downsampling rate is set to 3. We specify that the metrics are computed on slices along the \(F\) dimension of the volumes in the 3D case. This is convenient for us to use the same mask for different methods. For the settings of 3D-RAKI in FAS-Net, the kernel sizes are set to (5,2,2), (1,1,1), (3,2,2) for the three 3D convolutional layers, the kernel numbers of the first two layers are 32 and 8, the learning rate is 0.003, and the number of training epochs is 1000. For the details of 3D K-Net in group Fig. 10: Comparison of FasterFC-E2E-VarNet with E2E-VarNet and FasterFC-Ref-E2E-VarNet on validation set. Fig. 9: Comparison of FasterFC-U-Net with image-domain U-Net and FFC-U-Net on validation set. reconstruction, the entry channel number is 16, the downsampling rate is set to 3, the initial learning rate is 0.001 and will decrease to 0.0001 from 240 epochs, and the total number of training epochs is 250. For the settings of FasterFC-U-Net in split-slice training, the entry channel number and downsampling rate of network used for sensitivity map estimation are respectively 8 and 2, used for MR image refinement are set to 18 and 4. \(T\) is set to 2, and \(L\) is set to 16. The learning rate is also set to 0.001 for the first 160 epochs and will decrease to 0.0001 in the later 100 epochs. The PyTorch framework is adopted for model implementation. A machine with NVIDIA RTX A6000 GPUs is used. ### _Quantitative Results_ #### Iii-C1 Results on the 2D Single-Coil FastMRI Dataset The quantitative results in Table I indicate that FasterFC-U-Net provides optimal balance between reconstruction performance and speed on the 2D single-coil fastMRI dataset. As depicted in Fig. 9, NSEM, PSNR, and SSIM curves are plotted against the training epoch number. Table I shows that FasterFC-U-Net outperforms other methods in terms of reconstruction metrics and GFLOPs while utilizing fewer parameters than U-Net. Although the NMSE, PSNR, and SSIM of FasterFC-U-Net is slightly better than those of FFC-U-Net, the reconstruction time in inference stage of FasterFC-U-Net is almost half of that of the FFC-U-Net. This is why we call our method FasterFC. #### Iii-C2 Results on the 2D Multi-Coil FastMRI Dataset Table II demonstrates that FasterFC-E2E-VarNet outperforms the comparison methods on the fastMRI multi-coil dataset. Fig. 10 illustrates how reconstruction performance varies with the epoch number. By replacing all the U-Net in the refinement modules of E2E-VarNet with FasterFC-U-Net, FasterFC-Ref-E2E-VarNet achieves better NMSE, SSIM, and PSNR with fewer parameters and GFLOPs. This result highlights that the global receptive field of FasterFC aids in improving the network's reconstruction ability. Furthermore, FasterFC-E2E-VarNet improves the final reconstruction performance by replacing the U-Net for sensitivity map estimation with FasterFC-U-Net. This enhancement improves the quality of the sensitivity map estimation while also reducing the number of network parameters and GFLOPs. The total reconstruction time of FAS-Net is about 82 seconds per 3D high-resolution multi-coil MR data. The E2E-VarNet method takes about 64 seconds (0.2\(\times\)320) to reconstruct all slices, slightly faster than FAS-Net. The bottleneck limiting the reconstruction speed of FAS-Net is that the calculation speed of 3D-RAKI (about 75s). The remaining two stages take 0.07 and 6.93 seconds, respectively, which can be ignored. In the future, we plan to design a faster single reconstruction method (i.e., Faster-RAKI) that can simultaneously calculate reconstruction networks for different coil in parallel, thereby increasing the reconstruction speed of FAS-Net by almost \(N\) times.
2308.06619
Can Unstructured Pruning Reduce the Depth in Deep Neural Networks?
Pruning is a widely used technique for reducing the size of deep neural networks while maintaining their performance. However, such a technique, despite being able to massively compress deep models, is hardly able to remove entire layers from a model (even when structured): is this an addressable task? In this study, we introduce EGP, an innovative Entropy Guided Pruning algorithm aimed at reducing the size of deep neural networks while preserving their performance. The key focus of EGP is to prioritize pruning connections in layers with low entropy, ultimately leading to their complete removal. Through extensive experiments conducted on popular models like ResNet-18 and Swin-T, our findings demonstrate that EGP effectively compresses deep neural networks while maintaining competitive performance levels. Our results not only shed light on the underlying mechanism behind the advantages of unstructured pruning, but also pave the way for further investigations into the intricate relationship between entropy, pruning techniques, and deep learning performance. The EGP algorithm and its insights hold great promise for advancing the field of network compression and optimization. The source code for EGP is released open-source.
Zhu Liao, Victor Quétu, Van-Tam Nguyen, Enzo Tartaglione
2023-08-12T17:27:49Z
http://arxiv.org/abs/2308.06619v2
# Can Unstructured Pruning Reduce the Depth in Deep Neural Networks? ###### Abstract Pruning is a widely used technique for reducing the size of deep neural networks while maintaining their performance. However, such a technique, despite being able to massively compress deep models, is hardly able to remove entire layers from a model (even when structured): is this an addressable task? In this study, we introduce EGP, an innovative Entropy Guided Pruning algorithm aimed at reducing the size of deep neural networks while preserving their performance. The key focus of EGP is to prioritize pruning connections in layers with low entropy, ultimately leading to their complete removal. Through extensive experiments conducted on popular models like ResNet-18 and Swin-T, our findings demonstrate that EGP effectively compresses deep neural networks while maintaining competitive performance levels. Our results not only shed light on the underlying mechanism behind the advantages of unstructured pruning, but also pave the way for further investigations into the intricate relationship between entropy, pruning techniques, and deep learning performance. The EGP algorithm and its insights hold great promise for advancing the field of network compression and optimization. The source code for EGP is released open-source. + Footnote †: This paper has been accepted for publication at the Workshop on Resource Efficient Deep Learning for Computer Vision (ICCVW). ## 1 Introduction Deep neural networks have become a cornerstone of artificial intelligence and machine learning, achieving remarkable success in a wide range of applications, from video recognition [1] and natural language processing [25] to robotics [21] and autonomous driving [2]. However, the large size of these models poses significant challenges in terms of storage, memory, and computational requirements. To address these issues, researchers have developed various techniques to reduce the size of neural networks without sacrificing their performance, including quantization [9, 26], compression [6, 24], and pruning [10, 11, 15, 16, 23]. Pruning, in particular, has emerged as a popular and effective method for reducing the number of parameters in a neural network [3, 15, 20]. The idea behind pruning is to selectively remove weights, neurons, or entire layers based on their magnitude or other criteria [7, 17, 27]. The pruned model can then be fine-tuned to recover its original performance, resulting in a smaller and more efficient network. Pruning is particularly effective for deep neural networks, which tend to be over-parameterized and therefore have many redundant or irrelevant weights. Despite the widespread use of pruning, its underlying mechanism and the factors that contribute to its benefits are not well understood. Previous work has investigated the effects of pruning on the sparsity and connectivity patterns of neural networks [4, 5, 8], as well as its impact on the generalization performance of the pruned models [10]. Nowadays, indeed, massive study around this subject is being conducted [14, 22]. Although some works used entropy Figure 1: Effect of unstructured pruning in ReLU-activated models: some neurons are always OFF (yellow) and others are consistently in the linear region (red). These can be removed with no impact on the performance. Some neurons are in both regions (blue). If no neuron is in both regions, the layer can be fused with the next one (it is a linear combination), and the depth can be decreased (the entire layer is removed - red cross). to drive pruning mechanisms [13], to the best of our knowledge, no previous work has explored the relationship between pruning and the entropy of activations in the network. In this work, we investigate the impact of unstructured pruning on the entropy of activations in the network. In the context of neural networks, entropy can provide insights into the complexity and diversity of the representations learned by the model. Leveraging this measure, we propose EGP, a strategy to drive the unstructured pruning mechanism to prune layers exhibiting low entropy. Our experiments show that unstructured pruning reduces the entropy of activations in the network (Fig. 1). This reduction in entropy suggests that pruning results in a more structured activation pattern, which may as well improve the ability of the network to generalize to new data. Interestingly, this approach overcomes the limits of structured pruning, which removes neurons persistently OFF. Our work provides a new perspective on the mechanism behind the benefits of unstructured pruning and sheds light on the relationship between entropy, pruning, and deep learning performance. These findings open up avenues for further exploration. We have also developed an entropy-based iterative pruning technology that shows promise in compressing neural networks more effectively. Despite other works proposing entropy-based approaches to drive pruning [13, 18, 19], to the best of our knowledge, EGP is the very first entropy-driven approach that can effectively reduce the depth of a deep neural network model without harming its performance. Different from previous entropy-based pruning methods which tried to remove a certain amount of parameters or neurons inside layers, EGP tries to remove whole layers. EGP is tested on popular models for computer vision, like ResNet-18 and Swin-T, and opens the roads to a new class of pruning algorithms. ## 2 Entropy Guided Pruning In this section, we will provide details on how we compute the entropy of the activations inside the neural network model and develop our entropy-based iterative pruning. Fig. 2 proposes an overview of the proposed entropy computing and pruning method. First, we introduce the entropy calculation method (Sec. 2.1), showing also how to handle critical cases (Sec. 2.2), and then we provide an overview of the entropy-based iterative pruning method (Sec. 2.3). ### Derivation Let us extract the output \(\mathbf{y}_{l,i}^{\xi}\) of the \(i\)-th neuron in the \(l\)-th layer (where \(N_{l}\) is the number of neurons in the \(l\)-th layer), given as input the \(\xi\)-th sample. Let us assume the activation function \(\phi_{n}(\cdot)\) for the \(l\)-th layer is ReLU. Toward this end, we can write \[\mathbf{y}_{l,i}^{\xi}=\text{ReLU}\left(\mathbf{z}_{l,i}^{\xi}\right), \tag{1}\] where \(\mathbf{z}_{l,i}\) is the _post-synaptic potential_ for the \(i\)-th neuron in the \(l\)-th layer. Please note that in convolutional layers the dimensionality for \(\mathbf{y}_{l,i}^{\xi}\) is not necessarily unitary, but is proportional to the input's size \(M_{l}=K_{1,l}\times K_{2,l}\), where \(K_{1,l}\) and \(K_{2,l}\) are the dimensions for the generated feature map. We assume, for the sake of simplicity, that the size of every \(\xi\) is the same for the whole dataset \(\Xi\). We know that ReLU-activated neurons have essentially two working regions: * an ON region, for \(z_{l,i,j}>0\); * an OFF region, for \(z_{l,i,j}\leq 0\). These working regions will be our possible "states". To identify the state \(s_{l,i,j}\) for the \(j\)-th feature extracted by the \(i\)-th neuron, we can apply the one-step function \(H(\cdot)\) to the post-synaptic potential, obtaining \(s_{l,i,j}^{\xi}=H(z_{l,i,j}^{\xi})\). At this point, we can obtain the frequency of the \(i\)-th neuron to be in the ON state, simply through \[p^{\text{ON}}(l,i|\Xi)=\frac{1}{\|\Xi\|_{0}\cdot M_{l}}\sum_{\xi\in\Xi}\sum_{j }(s_{l,i,j}^{\xi}), \tag{2}\] where \(\|\Xi\|_{0}\) is the cardinality of the dataset. Evidently, we know that in this case \(p^{\text{OFF}}(l,i|\Xi)=1-p^{\text{ON}}(l,i|\Xi)\). At this point, we can use the definition in (2) to write the entropy \(\mathcal{H}(l,i|\Xi)\): \[\mathcal{H}(l,i|\Xi)= -\frac{1}{\log(2)}\left\{p^{\text{ON}}(l,i|\Xi)\log\left[p^{ \text{ON}}(l,i|\Xi)\right]+\right.\] \[\left.+p^{\text{OFF}}(l,i|\Xi)\log\left[p^{\text{OFF}}(l,i|\Xi) \right]\right\}. \tag{3}\] ### When the entropy goes to zero The evaluation of the entropy proposed in (2.3) is not intended as a measure of information flowing through the given layer, but it gives us an important indication of the effective use of the ReLU non-linearity. More specifically, for the \(i\)-th neuron in the \(l\)-th layer, we will have \(\mathcal{H}(l,i|\Xi)=0\) in two possible cases: Figure 2: Overview of the EGP approach. * \(s^{\xi}_{l,i,j}=0,\forall j,\xi\). This case is achieved in three possible ways: either all the parameters \(\mathbf{w}_{l,i}\) of the \(i\)-th neuron are zero, or the input \(\mathbf{y}^{\xi}_{l-1}\) is zero \(\forall\xi\), or again \(z^{\xi}_{l,i,j}\leq 0,\forall j,\xi\). In these cases, the neuron's output will always be zero, and the entire neuron can be removed/pruned from the model, with no performance loss. * \(s^{\xi}_{l,i,j}=1,\forall j,\xi\). This case is achieved if \(z^{\xi}_{l,i,j}>0,\forall j,\xi\). In this state, the \(i\)-th neuron in the \(l\)-th layer uses only the linear region, becoming a linear neuron: its contribution can be "absorbed" by the next layer (as the neuron and the next layer are a linear combination), evidencing a collapse in the neural network's depth. In this work we will be looking for both: while the first is expected, and known to rise in high pruning regimes [3, 23], the second one is more surprising, but can potentially lead to similar gains as those obtained with pruning. It is possible to extend the proposed formulation to other activations, like the sigmoid and GeLU (we will test on Swin-T in Sec. 3). ### Entropy-based iterative pruning As our target is to reduce the depth of deep neural networks by removing zero-entropy layers, we implement iterative pruning based on the entropy of different layers to get more layers with entropy zero. Let us set the percentage of parameters to be pruned at each pruning iteration as \(\zeta\), and the total weight parameters of the considered \(L\) layers in the model as \(\|\theta\|_{0}\). Then, in each pruning iteration, the number of weight parameters to be pruned \(\|\theta\|_{0}^{\text{pruned}}\) is given by \[\|\theta\|_{0}^{\text{pruned}}=\zeta\cdot\|\theta\|_{0}. \tag{4}\] After calculating the entropy of each neuron belonging to the \(l\)-th layer, we can calculate an average entropy for it, simply through \[\hat{\mathcal{H}}(l|\Xi)=\frac{1}{N_{l}}\sum_{i}\mathcal{H}(l,i|\Xi). \tag{5}\] We would like to route the magnitude pruning algorithm towards removing more parameters in layers where the entropy is low. This is because manifesting a low entropy is a symptom of not necessarily requiring a non-linear activation in these layers, and for such reason, these layers are the most promising to remove. However, we know that \(\mathcal{H}(l,i|\Xi)\geq 0\forall l,i,\Xi\): this means that, when having \(\hat{\mathcal{H}}(l|\Xi)=0\Leftrightarrow\mathcal{H}(l,i|\Xi)=0\forall i\). When this happens, we know that we are able to completely remove such a layer, and we no longer need to prune it. In order to increase the number of layers with zero entropy, more pruning should be applied to layers with lower entropy (more likely to reach zero entropy). Simultaneously, to minimize the impact on model performance, more pruning should be done on smaller magnitude weights. To achieve both goals, we propose a _pruning irrelevance_ meter \(\mathcal{I}_{l}\) for the \(l\)-th layer \[\mathcal{I}_{l}=\hat{\mathcal{H}}(l|\Xi)\cdot\frac{1}{\|\theta_{l}\|_{0}}\sum _{i}|\theta_{l,i}|, \tag{6}\] where \(\|\theta_{l}\|_{0}\) is the cardinality of the non-zero weights in the \(l\)-th layer. Effectively, the larger this value is, the least we are interested in removing parameters from it. However, we are very interested in removing parameters from layers having very low pruning irrelevance: for such reason, we define the complementary measure of _pruning relevance_ \[\mathcal{R}_{l}=\left\{\begin{array}{cc}\frac{\sum_{j}\mathcal{I}_{j}}{ \mathcal{I}_{l}}&\mathcal{I}_{l}\neq 0\\ 0&\mathcal{I}_{l}=0.\end{array}\right. \tag{7}\] Finally, in order to assess the exact amount of parameters to be removed at the \(l\)-th layer we resort to a softmax smoothening, according to \[\|\theta_{l}\|_{0}^{\text{pruned}}=\|\theta\|_{0}^{\text{pruned}}\cdot\frac{ \exp[\mathcal{R}_{l}-\max_{k}(\mathcal{R}_{k})]}{\sum_{j}\exp[\mathcal{R}_{j}- \max_{k}(\mathcal{R}_{k})]}. \tag{8}\] If the number of parameters pruned assigned to a specific layer exceeds its remaining parameter count, then prune all parameters of that layer. Afterward, distribute the remaining number of pruning parameters to other layers following the methods outlined in (6) and (8). ## 3 Experiments In this section, we present our empirical results obtained on three different very common setups. We have performed our experiments on an NVIDIA GeForce RTX 2080 GPU and developed the code using PyTorch 1.13.1. Figure 3: Distributions of neuron states per layer for ResNet-18 trained on CIFAR-10 with 98.4% of pruned parameters for EGP. In blue neurons having non-zero entropy, in orange always OFF, and in red always ON. Footnote 1: We acknowledge this choice is computationally extensive and unnecessary with optimal hyper-parameter optimization: our objective here is not to be efficient at train time but to highlight neurons with zero entropy. **Setup.** We present results for ResNet-18 and Swin-T trained on CIFAR-10 and Tiny-ImageNet (Tint-INet). While for ResNet-18 ReLU is the non-linearity for the layers, in Swin-T the non-linear activation adopted is GELU. We adopt the same baseline training strategy as in [12]. Specifically for Swin-T, we prune just the GELU-activated layers (which are, for this model, 12). For all the sparse configurations, we set \(\zeta=0.5\).1 Footnote 1: We acknowledge this choice is computationally extensive and unnecessary with optimal hyper-parameter optimization: our objective here is not to be efficient at train time but to highlight neurons with zero entropy. **Results.** The main results are reported in Table 1. Here, we compare a vanilla iterative magnitude pruning strategy with EGP. It appears evident that plugging EGP as a scaling factor to drive the pruning process effectively removes entire layers from the model. Evidently, with a higher sparsity, a performance drop naturally occurs; however, the gap in performance between vanilla pruning and EGP (for the same sparsity) remains consistently narrow. We provide, in Fig. 3, a visualization of the activation distributions for CIFAR-10 at 98.4% sparsity for EGP. Interestingly, we observe that one layer only (#12) can be removed with traditional pruning approaches, while others (like #14), having also neurons in the ON state, would be overlooked: this shows the effectiveness of EGP and potentially opens the road to a new class of pruning algorithms. **Ablation study.** We propose here an ablation study on the effectiveness of EGP. Table 2 compares training from scratch a model with some layers removed to the same following EGP: we observe that in all cases EGP exhibits better Top-1 performance. Especially for Swin-T trained on Tiny-ImageNet, this architecture/dataset combination does not provide good results as the smaller model should be also pre-trained on a large dataset like the vanilla one. This phenomenon suggests that EGP enhances accessibility to rare, compressed states of the deep model. ## 4 Conclusion In this work, we have investigated the impact of unstructured pruning on the entropy of activations in DNNs. Our preliminary experiments on ReLU and GELU-activated models show that our pruning strategy, EGP, drives a consistent part of the neurons in the model to either ON or OFF regions. Unstructured pruning can provide a structured activation pattern and yes, it can reduce the model's depth! Our results provide new insights into the mechanisms behind the benefits of pruning and open avenues for further \begin{table} \begin{tabular}{c c c c c} \hline \hline **Model** & **Dataset** & **Lay. rem.** & **Method** & **Top-1** \\ \hline \multirow{4}{*}{Resnet-18} & \multirow{2}{*}{CIFAR-10} & \multirow{2}{*}{5/17} & from scratch & 91.10 \\ & & & EGP & **92.18** \\ \cline{2-4} & & & from scratch & 37.72 \\ & & & EGP & **39.80** \\ \hline \multirow{4}{*}{Swin-T} & \multirow{2}{*}{CIFAR-10} & \multirow{2}{*}{5/12} & from scratch & 61.00 \\ & & & EGP & **90.41** \\ \cline{2-4} & & & from scratch & 0.50 \\ \cline{1-1} & & & EGP & **71.48** \\ \hline \hline \end{tabular} \end{table} Table 2: Performance of entropy-based pruned model and reinitialized model. \begin{table} \begin{tabular}{c c c c c} \hline \hline **Model** & **Dataset** & **Lay. rem.** & **Method** & **Top-1** \\ \hline \multirow{4}{*}{Resnet-18} & \multirow{2}{*}{CIFAR-10} & \multirow{2}{*}{5/17} & from scratch & 91.10 \\ & & & EGP & **92.18** \\ \cline{2-4} & & & EGP & 37.72 \\ \cline{2-4} & Tiny-ImageNet & 4/17 & from scratch & 37.72 \\ & & & EGP & **39.80** \\ \hline \multirow{4}{*}{Swin-T} & \multirow{2}{*}{CIFAR-10} & \multirow{2}{*}{5/12} & from scratch & 61.00 \\ & & & EGP & **90.41** \\ \cline{2-4} & & & EGP & 0.50 \\ \cline{1-1} \cline{2-4} & Tiny-ImageNet & 1/12 & from scratch & 0.50 \\ \cline{1-1} & & & EGP & **71.48** \\ \hline \hline \end{tabular} \end{table} Table 2: Performance of entropy-based pruned model and reinitialized model. exploration into the relationship between entropy, pruning, and deep learning performance. Future work can explore the applicability of our findings to other activation functions and architectures as well as the design of a regularization function explicitly enforcing low entropy to favor the model's compressibility. Exploring the impact of pruning on the dynamics of the optimization process and the interpretability of the resulting models could lead to a better understanding of the mechanisms behind the benefits of pruning. **Acknowledgements.** The research leading to these results has received funding from the project titled "PC6-FITNESS" in the frame of the program "PEPR 5G et Reseaux du futur". Zhu Liao is funded by China Scholarship Council (CSC).
2310.17238
Joint Entity and Relation Extraction with Span Pruning and Hypergraph Neural Networks
Entity and Relation Extraction (ERE) is an important task in information extraction. Recent marker-based pipeline models achieve state-of-the-art performance, but still suffer from the error propagation issue. Also, most of current ERE models do not take into account higher-order interactions between multiple entities and relations, while higher-order modeling could be beneficial.In this work, we propose HyperGraph neural network for ERE ($\hgnn{}$), which is built upon the PL-marker (a state-of-the-art marker-based pipleline model). To alleviate error propagation,we use a high-recall pruner mechanism to transfer the burden of entity identification and labeling from the NER module to the joint module of our model. For higher-order modeling, we build a hypergraph, where nodes are entities (provided by the span pruner) and relations thereof, and hyperedges encode interactions between two different relations or between a relation and its associated subject and object entities. We then run a hypergraph neural network for higher-order inference by applying message passing over the built hypergraph. Experiments on three widely used benchmarks (\acef{}, \ace{} and \scierc{}) for ERE task show significant improvements over the previous state-of-the-art PL-marker.
Zhaohui Yan, Songlin Yang, Wei Liu, Kewei Tu
2023-10-26T08:36:39Z
http://arxiv.org/abs/2310.17238v1
# Joint Entity and Relation Extraction with Span Pruning and ###### Abstract Entity and Relation Extraction (ERE) is an important task in information extraction. Recent marker-based pipeline models achieve state-of-the-art performance, but still suffer from the error propagation issue. Also, most of current ERE models do not take into account higher-order interactions between multiple entities and relations, while higher-order modeling could be beneficial.In this work, we propose HyperGraph neural network for ERE (HGERE), which is built upon the PL-marker (a state-of-the-art marker-based pipeline model). To alleviate error propagation,we use a high-recall pruner mechanism to transfer the burden of entity identification and labeling from the NER module to the joint module of our model. For higher-order modeling, we build a hypergraph, where nodes are entities (provided by the span pruner) and relations thereof, and hyperedges encode interactions between two different relations or between a relation and its associated subject and object entities. We then run a hypergraph neural network for higher-order inference by applying message passing over the built hypergraph. Experiments on three widely used benchmarks (ACE2004, ACE2005 and SciERC) for ERE task show significant improvements over the previous state-of-the-art PL-marker. 1 Footnote 1: Source code is available at [https://github.com/yanzhh/HGERE](https://github.com/yanzhh/HGERE) ## 1 Introduction Entity and Relation Extraction (ERE) is a fundamental task in information extraction (IE), compromising two sub-tasks: Named Entity Recognition (NER) and Relation Extraction (RE). There is a long debate on joint vs. pipeline methods for ERE. Pipeline decoding extracts entities first and predicts relations solely on pairs of extracted entities, while joint decoding predicts entities and relations simultaneously. Recently, the seminal work of [22] shows that pipeline decoding with a frustratingly simple marker-based encoding strategy -- i.e., inserting solid markers [1, 20] around predicted subject and object spans in the input text -- achieves state-of-the-art RE performance. Modified sentences (with markers) are fed into powerful pre-trained large language models (LLM) to obtain more subject- and object-aware representations for RE classification, which is the key to the performance improvement. However, current marker-based pipeline models (e.g., the recent state-of-the-art ERE model PL-marker [23]) _only_ send predicted entities from the NER module to the RE module, therefore missing entities would never have the chance to be re-predicted, suffering from the _error propagation issue_. On the other hand, for joint decoding approaches (e.g. Table Filling methods [13, 21, 22])--though they do not suffer from the error propagation issue--it is hard to incorporate markers for leveraging LLMs, since entities are not predicted prior to relations. Our desire is to obtain the best of two worlds, being able to use marker-based encoding mechanism for enhancing RE performance and meanwhile alleviating the error propagation problem. We adopt PL-marker as the backbone of our proposed model and a span pruning strategy to mitigate error propagation. That is, instead of sending only predicted entity spans to the RE module, we _over-predict_ candidate spans so that the recall of gold entity spans is nearly perfect (but there also could be many non-entity spans), transferring the burden of entity classification and labeling from the NER module to the RE module of PL-marker. The number of over-predicted spans is upper-bounded, balancing the computational complexity of marker-based encoding and the recall of gold entity span. Empirically, we find this simple strategy by itself clearly improves PL-marker. We further incorporate a _higher-order_ interaction module into our model. Most previous ERE models either implicitly model the interactions between instances by shared parameters Wang and Lu (2020); Yan et al. (2021); Wang et al. (2021) or use a traditional graph neural network that models pairwise connections between a relation and an entity Sun et al. (2019). It is difficult for these approaches to explicitly model higher-order relationships among multi-instances, e.g. the dependency among a relation and its corresponding subject and object entities. Many recent works in structured prediction tasks show that explicit higher-order modeling is still beneficial even with powerful large pretrained encoders Zhang et al. (2020); Li et al. (2020); Yang and Tu (2022); Zhou et al. (2022), _inter alia_), motivating us to use an additional higher-order module to enhance performance. A common higher-order modeling approach is by means of probabilistic modeling (i.e., conditional random field (CRF)) with end-to-end Mean-Field Variational Inference (MFVI), which can be seamlessly integrated into neural networks as a recurrent neural network layer Zheng et al. (2015), and has been widely used in various structured prediction tasks, such as dependency parsing Wang et al. (2019), semantic role labeling Li et al. (2020); Zhou et al. (2022), and information extraction Jia et al. (2022). However, the limitations of CRF modeling with MFVI are i): CRF's potential functions are parameterized in log-linear forms with strong independence assumptions, suffering from low model capacities Qu et al. (2022), ii) MFVI uses fully-factorized Bernoulli distributions to approximate the otherwise multimodal true posterior distributions, oversimplifying the inference problem and thus is sub-optimal. Therefore we need more _expressive_ tools to improve the quality of higher-order inference. Fortunately, there are many recent works in the machine learning community showing that graph neural networks (GNN) can be used as an inference tool and outperform approximate statistical inference algorithms (e.g., MFVI) Yoon et al. (2018); Zhang et al. (2020); Kuck et al. (2020); Satorras and Welling (2021) (see Hua (2022) for a survey). Inspired by these works, we employ a hypergraph neural network (HyperGNN) instead of MFVI for high-order inference and propose our model HGERE (HyperGraph Neural Network for ERE). Concretely, we build a hypergraph where nodes are candidate subjects and objects (obtained from the span pruner) and relations thereof, and hyperedges encode the interactions between either two relations with shared entities or a relation and its associated subject and object entity spans. In contrast, existing GNN models for IE Sun et al. (2019); Nguyen et al. (2021) only model the pairwise interactions between a relation and one of its corrsponding entity. We empirically show the advantages of our higher-order interaction module (i.e., hypergraph neural network) over MFVI and traditional GNN models. Our contribution is three-fold: i) We adopt a simple and effective span pruning method to mitigate the error propagation issue, enforcing the power of marker-based encoding. ii) We propose a novel hypergraph neural network enhanced higher-order model, outperforming higher-order CRF-based models with MFVI. iii) We show great improvements over the prior state-of-the-art PL-marker on three commonly used benchmarks for ERE: ACE2004, ACE2005 and SciERC. ## 2 Background ### Problem formulation Given a sentence \(X\) with \(n\) tokens: \(x_{1},x_{2},...,x_{n}\), an entity span is a sequence of tokens labeled with an entity type and a relation is an entity span pair labeled with a relation type. We denote the set of all entity spans of the sentence with a span length limit \(L\) by \(S(X)=\{s_{1},s_{2},...,s_{m}\}\) and define \(\text{ST}(i)\) and \(\text{ED}(i)\) as the start and end token indices of the span \(s_{i}\). The joint ERE task is to simultaneously solve the NER and RE tasks. Let \(\mathcal{C}_{e}\) be the set of entity types and \(\mathcal{C}_{r}\) be the set of relation types. For each span \(s_{i}\in S(X)\), the NER task is to predict an entity type \(y_{e}(s_{i})\in\mathcal{C}_{e}\) or \(y_{e}(s_{i})=\texttt{null}\) if the span \(s_{i}\) is not an entity. The RE task is to predict a relation type \(y_{r}(r_{ij})\in\mathcal{C}_{r}\) or \(y_{r}(r_{ij})=\texttt{null}\) for each span \(r_{ij}=(s_{i},s_{j}),s_{i},s_{j}\in S(X)\). ### Packed levitated marker (PL-marker) Zhong and Chen (2021) insert two pairs of solid markers (i.e., \([S]\) and \([\backslash S]\)) to highlight both the subject and object entity spans in a given sentence, and this simple approach achieves state-of-the-art RE performance. We posit that this is because LLM is more aware of the subject and object spans (with markers) and thus can produce better span representations to improve RE. But this strategy needs to iterate over all possible entity span pairs and is thus slow. To tackle the efficiency problem, Zhong and Chen (2021) propose an approximated variant wherein each possible entity span is associated with a pair of levitated markers (i.e., \([O]\) and \([\setminus O]\)) whose representations are initialized with the positional embedding of the span's start and end tokens, and all such levitated markers are concatenated to the end of the sentence. As such, levitated-marker-based encoding needs only one pass, significantly improving efficiency at the cost of slight performance drop. Zhong and Chen (2021) also propose a masked attention mechanism such that the original input text tokens are not able to attend to markers, while markers can attend to paired markers (but not unpaired markers) and all input text tokens. As a consequence, the relative positions of levitated markers in the concatenated sentence do not matter at all, eliminating potential implausible inductive bias on the concatenation order. However, marker-base encoding is only used in RE, not in NER. To leverage marker-based encoding in the NER module for modeling span inter-relations, PL-marker (Ye et al., 2022) associates each possible span with two levitated markers and concatenates all of them to the end of the input sentence. However, this strategy could make the input sentence extremely long since there are quadratic number of spans. To solve this issue, PL-marker clusters the markers based on the starting position of their corresponding spans, and divides them into \(N\) groups. Then the input sentence is duplicated \(N\) times and each group of levitated markers is concatenated to the end of one sentence copy. Ye et al. (2022) refers to this strategy as _neighborhood-oriented packing scheme_. Furthermore, to balance the efficiency and the model expressiveness, Ye et al. (2022) combine solid markers and levitated markers, proposing _Subject-oriented Packing for Span Pair_ in the RE module. That is, if there are \(m\) entities, they copy the sentence for \(m\) times, and for each copy, they use solid markers to mark a different entity as the subject and concatenate the levitated markers of all other entities (as objects) at the end of the sentence. ## 3 Method Overview.Our method is built upon the state-of-the-art PL-marker. We employ a high-recall span pruner to obtain candidate entity spans, similar to the NER module in PL-marker. However, instead of aiming to accurately predict all possible entity spans, our pruner focuses on removing unlikely candidates to achieve a much higher recall. Then we feed the candidate span set to the RE module to obtain entity and relation representations, which are used to initialize the node representations of our hypergraph neural network for higher-order inference with a message passing scheme. Finally, we perform NER and RE based on the refined entity and relation representations. Fig. 1 depicts the neural architecture of our model. ### Span Pruner We adopt the neighborhood-oriented packing scheme from PL-marker for span encoding, except that we simply predict entity existence (i.e., binary classification) instead of predicting entity labels during the training phrase. See Appendix A.4 for Figure 1: Illustration of our framework details. To produce a candidate span set, we rank all the spans by their scores and take top \(K\) as our prediction \(S_{p}(X)\). We assume that the number of entity spans of a sentence is linear to its length \(n\), so \(K\) is set to \(\lambda\cdot n\) where \(\lambda\) is a coefficient. For a very long sentence, the number of entity spans is often sublinear to \(n\), while for a very short sentence, we wish to keep enough candidate spans, so we additionally set an upper and lower bound: \(K=\text{max}(l_{\text{min}},\text{min}(\lambda\cdot n,l_{\text{max}}))\). In practice, with our span pruner, more than 99% gold entity spans are included in the candidate set for all three datasets. If we predict entities as in PL-marker instead of pruning, only around 95% and 80% gold entities are kept in the predicted entities for ACE2005 and SciERC respectively, leading to severe error propagation (see SS5.1 for an ablation study). The span pruner is trained independently from the joint ERE model introduced in the next section. This is because the joint ERE training loss will be defined based on candidate entity spans produced by the span pruner. When sharing parameters, the pruner would provide a different candidate span set during training, leading to moving targets and thereby destabilizing the whole training process. ### Joint ERE Model: First-order Backbone The backbone module is based on the RE module of PL-marker. Concretely, given an input sentence \(X=\{x_{1},x_{2},...,x_{n}\}\) and a subject span \(s_{i}=(x_{\text{ST}(i)},x_{\text{ED}(i)})\in S_{p}(X)\) provided by the span pruner, every entity span \(s_{j}\in S_{p}(X),1\leq j\leq K,j\neq i\) could be a candidate object span of \(s_{i}\). The module inserts a pair of solid markers \([S]\) and \([\backslash S]\) before and after the subject span and assign every object span \(s_{j}\) a pair of levitated markers \([O]_{j}\) and \([\backslash O]_{j}\). As shown below, the levitated markers are packed together and inserted at the end of the input sequence to a PLM: \[x_{1},...,[S],x_{\text{ST}(i)},...,x_{\text{ED}(i)},[\backslash S ],...,x_{n},\] \[[O]_{1},...,[O]_{K},[\backslash O]_{1},...,[\backslash O]_{K}\] Then we obtain the contextualized hidden representation \(\mathbf{h}_{x}\) of the modified input sequence and the final subject representation is: \[\mathbf{h}_{s}(s_{i})=\text{FFN}_{s}([\mathbf{h}_{x}([S]);\mathbf{h}_{x}([ \backslash S])])\] FFN represents a single linear layer in this work. The object representation of \(s_{j}\) for the current subject \(s_{i}\) and the representation of relation \(r_{ij}=(s_{i},s_{j})\) are: \[\mathbf{h}_{o}^{i}(s_{j})=\text{FFN}_{o}([\mathbf{h}_{x}([O]_{j});\mathbf{h}_ {x}([\backslash O]_{j})])\] \[\mathbf{h}_{r}(r_{ij})=\text{FFN}_{r}([\mathbf{h}_{s}(s_{i});\mathbf{h}_{o}^{i }(s_{j})])\] Repeating \(K\) times, we get all \(K\) subject representations and \(K(K-1)\) relation representations. As the object representation of \(s_{j}\) is not identical for different subject span \(s_{i}\), there are \(K\) object representation sets \(\mathbf{h}_{o}^{i},1\leq i\leq K\). We apply a max-pooling layer to obtain a unique object representation for each object span \(s_{j}\in S_{p}(X)\): \[\mathbf{h}_{o}(s_{j})=\text{Maxpooling}_{1\leq i\leq K,i\neq j}(\mathbf{h}_{o} ^{i}(s_{j}))\] ### Joint ERE Model: Higher-order Inference with Hypergraph Neural Networks Hypergraph BuildingSo far, the representations of the entities and relations from the backbone module do not explicitly consider beneficial interactions among related instances. To model higher-order interactions among a relation and its associated subject and object entities as well as between any two relations sharing an entity, we build a hypergraph \(\mathcal{G}=(\mathcal{V},\mathcal{E})\) to connect the related instances.The nodes set \(\mathcal{V}\) is composed of candidate subjects, objects (provided by the span pruner) and all possible pairwise relations thereof, and we denote them as \(\mathcal{V}_{s}=\{v_{s}^{i}|i\in[1,K]\}\), \(\mathcal{V}_{o}=\{v_{s}^{i}|j\in[1,K]\}\) and \(\mathcal{V}_{r}=\{v_{r}^{ij}|i,j\in[1,K],i\neq j\}\). Hyperedges \(\mathcal{E}\) capture the interactions we are concerned with, and they can be divided into two categories: the subject-object-relation (sub-obj-rel) hyperedges \(\mathcal{E}_{sor}\) and the relation-relation (rel-rel) hyperedges \(\mathcal{E}_{rr}\). Each hyperedge \(e_{sor}^{ij}\in\mathcal{E}_{sor}\) connects a subject node \(v_{s}^{i}\), an object node \(v_{o}^{j}\) and the corresponding relation node \(v_{r}^{ij}\), and we refer to these hyperedges as _retany_ edges (_ter_ for short). Each rel-rel edge \(e_{rr}^{ijk}\in\mathcal{E}_{rr}\) connects two relation nodes with a shared subject or object entity. We assume in a relation, the subject is the parent node and the object is the child node, and then we can refine rel-rel edges into three subtypes, _sibling_ (_sib_, connecting \(v_{r}^{ij}\) and \(v_{r}^{ik}\)), _co-parent_ (_cop_, connecting \(v_{r}^{ij}\) and \(v_{r}^{kj}\)) and _grand-parent_ (_gp_, connecting \(v_{r}^{ij}\) and \(v_{r}^{jk}\)), following the common definitions in the dependency parsing literature. If we incorporate all aforementioned hyperedges into the hypergraph, we obtain the _tersibcopgp_ variant which is illustrated in Fig. 1. By removing some types of hyperedges we can get different variants, but without loss of generality we describe the message passing scheme in the following using _tersibcopgp_. As such, we can define a CRF on the hypergraph and leverage probabilistic inference algorithms such as MFVI for higher-order inference. However, as discussed in SS1, we can use a more expressive method to improve inference quality and introduce a HyperGraph Neural Network (HGNN) as described next. Initial node representationFor a relation node \(v_{r}^{ij}\) with its associated subject node \(v_{s}^{i}\) and object node \(v_{o}^{j}\), we use \(\mathbf{g}^{l}(v_{r}^{ij}),\mathbf{g}^{l}(v_{s}^{i})\), \(\mathbf{g}^{l}(v_{o}^{g})\) to denote their respective representation outputs from the \(l\)-th HGNN layer. Initial node representations (before being fed to a HGNN) are \(\mathbf{g}^{0}(v_{s}^{i})=\mathbf{h}_{s}(s_{i})\), \(\mathbf{g}^{0}(v_{o}^{j})=\mathbf{h}_{o}(s_{j})\) and \(\mathbf{g}^{0}(v_{r}^{ij})=\mathbf{h}_{r}(r_{ij})\), respectively (from the backbone module). Message representationA hyperedge connecting to nodes serve as the bridge for message passing between nodes connected by it. Let \(\mathcal{N}_{e}(v)\) be the set of hyperedges connecting to a node \(v\). For a _ter_ hyperedge \(e_{ter}^{ij}\in\mathcal{E}_{sor}\) connecting a subject node \(v_{s}^{i}\), a object node \(v_{o}^{j}\) and a relation node \(v_{r}^{ij}\), the message representation it carries is: \[\mathbf{h}\mathbf{r}_{ij}^{l} =\text{FFN}_{r}^{ter}(\mathbf{g}^{l-1}(v_{r}^{ij}))\] \[\mathbf{h}\mathbf{s}_{i}^{l} =\text{FFN}_{s}^{ter}(\mathbf{g}^{l-1}(v_{s}^{i}))\] \[\mathbf{h}\mathbf{o}_{j}^{l} =\text{FFN}_{o}^{ter}(\mathbf{g}^{l-1}(v_{o}^{j}))\] \[\mathbf{m}^{l}(e_{ter}^{ij}) =\text{FFN}_{e}^{ter}(\mathbf{h}\mathbf{r}_{ij}^{l}\circ\mathbf{ h}\mathbf{s}_{i}^{l}\circ\mathbf{h}\mathbf{o}_{j}^{l})\] where \(\circ\) is the Hadamard product. A rel-rel edge \(e_{2}^{ijk}\in\mathcal{E}_{rr},\mathtt{z}\in\{\mathit{sib},\mathit{cop}, \mathit{gp}\}\) connects two relations sharing an entity. For simplicity, we denote them relation \(a\) and \(b\). If we fix \(a\) as \(a\triangleq v_{r}^{ij}\), then as previously described, relation \(b\) is \(v_{r}^{ik}\) for _sib_ edge, \(v_{r}^{kj}\) for _cop_ edge, and \(v_{r}^{jk}\) for _gp_ edge. The message \(e_{z}^{ijk}\) carries is given by, \[\mathbf{h}_{z}^{l}(a)=\text{FFN}_{a}^{\mathtt{z}}(\mathbf{g}^{l -1}(a))\] \[\mathbf{h}_{z}^{l}(b)=\text{FFN}_{e}^{\mathtt{z}}(\mathbf{g}^{l -1}(b))\] \[\mathbf{m}^{l}(e_{z}^{ijk})=\text{FFN}_{e}^{\mathtt{z}}(\mathbf{ h}_{z}^{l}(a)\circ\mathbf{h}_{z}^{l}(b))\] Node representation updateWe aggregate messages for each node \(v\in\mathcal{V}\) from adjacent edges \(\mathcal{N}_{e}(v)\) with an attention mechanism by taking a learned weighted sum, and add the aggregated message to the prior node representation, \[\beta^{l}(e,v)=\mathbf{w}^{\top}\sigma(\mathbf{W}[\mathbf{g}^{l-1}(v); \mathbf{m}^{l}(e)]\] \[\alpha^{l}(e,v)=\frac{\exp\beta^{l}(e,v)}{\sum_{e^{\prime}\in \mathcal{N}_{e}(v)}\exp\beta^{l}(e^{\prime},v)}\] \[\mathbf{g}^{l}(v)=\mathbf{g}^{l-1}(v)+\sum_{e\in N_{e}(v)} \alpha^{l}(e,v)\mathbf{m}^{l}(e)\] where \(\sigma(\cdot)\) is a non-linear activator and \(\mathbf{w},\mathbf{W}\) are two trainable parameters. An entity node would receive messages only from _ter_ edges while a relation node would receive messages from both _ter_ edges and rel-rel edges. TrainingWe obtain refined \(\mathbf{g}^{l}(v)\) from the final layer of HGNN. Give an entity span \(s_{i}\in S_{p}(X)\), we concatenate the corresponding subject representation \(\mathbf{g}^{l}(v_{s}^{i})\) and object representation \(\mathbf{g}^{l}(v_{o}^{i})\) to obtain the entity representation, and compute the probability distribution over the types \(\{\mathcal{C}_{e}\}\bigcup\{\texttt{null}\}\): \[P_{e}(\hat{y}_{e}|s_{i})=\text{Softmax}(\text{FFN}_{e}^{cls}([\mathbf{g}^{l}(v _{s}^{i});\mathbf{g}^{l}(v_{o}^{i})]))\] Given a relation \(r_{ij}=(s_{i},s_{j}),s_{i},s_{j}\in S_{p}(X)\), we compute the probability distribution over the types \(\{\mathcal{C}_{r}\}\bigcup\{\texttt{null}\}\): \[P_{r}(\hat{y}_{r}|r_{ij})=\text{Softmax}(\text{FFN}_{r}^{cls}(\mathbf{g}^{l}( v_{r}^{ij})))\] We use the cross-entropy loss for both entity and relation prediction: \[L_{e} =-\sum_{s_{i}\in S_{p}(X)}\log(P_{e}(y_{e}^{*}(s_{i})|s_{i}))\] \[L_{r} =-\sum_{s_{i},s_{j}\in S_{p}(X)}\log(P_{r}((y_{r}^{*}(r_{ij})|r_{ ij}))\] where \(y_{e}^{*}\) and \(y_{r}^{*}\) are gold entity and relation types respectively. The total loss is \(L=L_{e}+L_{r}\). ## 4 Experiment DatasetsWe experiment on SciERC [1], ACE2004 [5] and ACE2005 [10]. We follow Ye et al. (2022) to split ACE2004 into 5 folds and split ACE2005 and SciERC into train/dev/test sets. See Appendix A.1 for detailed dataset statistics. Evaluation metricsWe report micro labeled F1 measures for NER and RE. For RE, the difference between Rel and Rel+ is that the former requires correct prediction of subject and object entity spans and the relation type between them, while the latter additionally requires correct prediction of subject and object entity types. BaselineOur baseline models include: i) **Backbone**. It is described in Sect. 3.2 and does not contain the higher-order interaction module. ii) **GCN**. It has a similar architecture to Sun et al. (2019); Nguyen et al. (2021) and does not contain higher-order hyperedges. See Appendix A.6 for a detailed description. iii) **MFVI**. It defines a CRF on the same hypergraph as our model and uses MFVI instead of hypergraph neural networks for higher-order inference. See Appendix A.5 for a detailed description. Implementation detailsFor a fair comparison with previous work, we use _bert-base-uncased_(Devlin et al., 2019) and _albert-xxlarge-v1_(Lan et al., 2020) as the base encoders for ACE2004 and ACE2005, _scibert-scivocab-uncased_(Beltagy et al., 2019) as the base encoder for SciERC. GCN and MFVI are also built upon Backbone. The implementation details of experiments are in Appendix A.3. Main resultsFor HGRE, we report the best results among the following variants of hypergraphs with different types of hyperedges: _ter_, _cop_, _sib_, _gp_, _terscib_, _tercp_, _terspb_, _terscipgp_, and _tersibcopgp_. The best variants of HGRE are _terscibcop_ on SciERC and ACE2005 (BERT\({}_{B}\)); _terscib_ on ACE2005 (ALBERT); _tercp_ on ACE2004. For MFVI we use the same variants as used in HGRE. Table 1 shows the main results. Surprisingly, Backbone outperforms prior approaches in almost all metrics by a large margin (except on ACE2004 with BERT\({}_{B}\) and ACE2005 with ALBERT), which we attribute to the reduction of error propagation with a span pruning mechanism. Our proposed model HGRE outperforms almost all baselines in all metrics (except the entity metric on ACE2004), validating that using hyperedges to encode higher-order interactions is effective (compared with GCN) and that using hypergraph neural networks for higher-order modeling and inference is better than CRF-based probabilistic modeling with MFVI. Finally, we remark that HGRE obtains state-of-the-art performances on all the three datasets. ## 5 Analysis ### Effectiveness of the span pruner To study the effectiveness of the span pruner, we replace it with an entity identifier which is the original NER module from PL-marker and is trained only on entity existence. The performance of the span pruner and the entity identifier (denoted by Eid) on entity existence is shown in Table 2. We can observe that if we replace the span pruner with the entity identifier, the recall of gold _unlabeled \begin{table} \begin{tabular}{l c c c c c c c c c c} \hline \hline \multirow{2}{*}{Models} & \multirow{2}{*}{Encoder} & \multicolumn{4}{c}{ACE2005} & \multicolumn{4}{c}{ACE2004} & \multicolumn{4}{c}{SciERC} \\ \cline{3-10} & & Ent & Rel & Rel+ & Ent & Rel & Rel+ & Ent & Rel & Rel+ \\ \hline (Wadden et al., 2019)\({}^{*}\) & & 88.6 & 63.4 & - & - & - & 67.5 & 48.4 & - \\ (Wang et al., 2021)\({}^{*}\) & & 88.8 & - & 64.3 & 87.7 & - & 60.0 & 68.4 & - & 36.9 \\ (Zhong and Chen, 2021)\({}^{*}\) & & 90.1 & 67.7 & 64.8 & 89.2 & 63.9 & 60.1 & 68.9 & 50.1 & 36.8 \\ (Yan et al., 2021) & & - & - & - & - & - & - & 66.8 & - & 38.4 \\ (Shen et al., 2021)\({}^{*}\) & BERT\({}_{B}\)/ & 87.6 & 66.5 & 62.8 & - & - & - & 70.2 & 52.4 & - \\ (Nguyen et al., 2021) & SciBERT & 88.9 & 68.9 & - & - & - & - & - & - & - \\ (Ye et al., 2022)\({}^{*}_{w}\) & & 89.1 & 68.3 & 65.1 & 88.5 & 66.3 & 62.2 & 68.8 & 51.1 & 38.3 \\ Backbone\({}^{*}\) & & 90.0 & 69.8 & 66.7 & 89.5 & 66.6 & 62.1 & 71.3 & 52.3 & 40.2 \\ GCN\({}^{*}\) & & 90.2 & 69.6 & 66.5 & **90.0** & 67.6 & 63.5 & 74.1 & 54.8 & 42.9 \\ MFVI\({}^{*}\) & & 90.2 & 69.7 & 67.1 & 89.7 & 67.4 & 63.4 & 73.3 & 54.7 & 42.5 \\ HGRE\({}^{*}\) (our model) & & 90.2 & **70.7** & **67.5** & 89.9 & **68.2** & **64.2** & **74.9** & **55.7** & **43.6** \\ \hline (Liu et al., 2022) & T5\({}_{3B}\) & 91.3 & 72.7 & 70.5 & - & - & - & - & - & - \\ \hline (Wang and Lu, 2020) & & 89.5 & 67.6 & 64.3 & 88.6 & 63.3 & 59.6 & - & - & - \\ (Wang et al., 2021)\({}^{*}\) & & 90.2 & - & 66.0 & 89.5 & - & 63.0 & - & - & - \\ (Zhong and Chen, 2021)\({}^{*}\) & & 90.9 & 69.4 & 67.0 & 90.3 & 66.1 & 62.2 & - & - & - \\ (Yan et al., 2021) & & 89.0 & - & 66.8 & 89.3 & - & 62.5 & - & - & - \\ (Ye et al., 2022)\({}^{*}_{w}\) & ALBERT & 91.3 & 72.5 & 70.5 & 90.5 & 69.3 & 66.1 & - & - & - \\ Backbone\({}^{*}\) & & 91.5 & 72.9 & 70.2 & 91.6 & 70.2 & 66.6 & - & - & - \\ GCN\({}^{*}\) & & 91.7 & 73.1 & 69.9 & **92.0** & 71.5 & 67.9 & - & - & - \\ MFVI\({}^{*}\) & & 91.6 & 72.7 & 70.1 & 89.9 & 68.5 & 65.1 & - & - & - \\ HGRE\({}^{*}\) (our model) & & **91.9** & **73.5** & **70.8** & 91.9 & **71.9** & **68.3** & - & - & - \\ \hline \hline \end{tabular} \end{table} Table 1: F1 scores and standard deviations on ACE2004, ACE2005 and SciERC. The models marked with \(\star\) leverage cross-sentence information. A model with subscript _re_ means we re-evaluate the model with the evaluation method commonly used in other work\({}^{2}\). Backbone, MFVI and GCN are our baseline models. entity spans drops from 99.2 to 78.7 on the SciERC test set, and drops from 99.8 to 95.8 on the ACE2005 test set. We further investigate how the choice of the span pruner vs. the entity identifier influences NER and RE performances. The results are shown in Table 3. We can see that without a span pruner, both NER and RE performances drop significantly, validating the usefulness of using a span pruner. Moreover, it has a consequent influence on the higher-order inference module (i.e., HGNN). Without a span pruner, the improvement from using a HGNN over Backbone is marginal compared to that with a span pruner. We posit that without a pruner many gold entity spans could not exist in the hypergraph of HGNNs, making true entities and relations less connected in the hypergraph and thus diminishing the usefulness of HGNNs. ### Effect of the choices of hyperedges We compare different variants of HGNN with different combinations of hyperedges. Note that if _ter_ is not used, entity nodes do not have any hyperedges connecting to them, so their representations would not be refined. We can see that in the _sib_ and _cop_ variants, the NER performance improves slightly, which we attribute to the shared encoder of NER and RE tasks 3. On the other hand, in the _ter_ variant, entity node representations are iteratively refined, resulting in significantly better NER performance than Backbone (74.2 vs. 71.3). Combining _ter_ edges with other rel-rel edges (e.g., _sib_) is generally better than using _ter_ alone in terms of NER performance, suggesting that joint (and higher-order) modeling of NER and RE indeed has a positive influence on NER, while prior pipeline approaches (e.g., PL-marker) cannot enjoy the benefit of such joint modeling. Footnote 3: Though Zhong and Chen (2021) argue that using shared encoders would suffer from the _feature confusion problem_, later works show that shared encoders can still outperform separated encoders Yan et al. (2021, 2022). For RE, _sib_ and _cop_ have positive effects on the performance (despite _gp_ having a negative effect somehow), showing the advantage of modeling interactions between two different relations. Further combining them with _ter_ improves RE performances in all cases, indicating that NER also has a positive effect on RE and confirming again the advantage of joint modeling of NER and RE. ### Inference speed of higher-order module To analyze the computing cost of our higher-order module, we present the inference speed of HGRE with three baseline models Backbone, GCN and MFVI on the test sets of SciERC and ACE2005. Inference speed is measured by the number of candidate entities processed per second. The results are shown in Table 5. We can observe that \begin{table} \begin{tabular}{l c c c} \hline \hline \multirow{2}{*}{HGRE} & \multicolumn{3}{c}{SciERC} \\ \cline{2-4} & Ent & Rel & Rel+ \\ \hline Backbone & 71.3 & 52.3 & 40.2 \\ _ter_ & 74.2 & 55.1 & 42.6 \\ _sib_ & 71.7 & 54.3 & 41.7 \\ _cop_ & 71.7 & 52.9 & 40.8 \\ _gp_ & 71.3 & 51.9 & 40.1 \\ _tersib_ & 74.7 & **55.9** & 43.3 \\ _tercop_ & 74.7 & 55.7 & **43.6** \\ _tergp_ & 74.5 & 54.9 & 42.4 \\ _tersibcop_ & **74.9** & 55.7 & **43.6** \\ _tersibgp_ & 74.2 & 54.1 & 41.8 \\ _tercopgp_ & 74.7 & 54.0 & 42.3 \\ _tersibcopgp_ & 74.3 & 54.6 & 41.7 \\ \hline \hline \end{tabular} \end{table} Table 4: F1 scores of HGRE with different graph topologies on the SciERC test set. \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline \multirow{2}{*}{} & \multicolumn{3}{c}{SciERC} & \multicolumn{3}{c}{ACE2005 (BERT\({}_{B}\))} \\ \cline{2-8} & & P & R & F1 & P & R & F1 \\ \hline \multirow{3}{*}{Eid} & train & 98.8 & 98.2 & 98.5 & 100.0 & 99.9 & 99.9 \\ & dev & 81.0 & 81.6 & 81.3 & 94.7 & 94.6 & 94.7 \\ & test & 80.4 & 78.7 & 79.5 & 95.6 & 95.8 & 95.7 \\ \hline \multirow{3}{*}{Pruner} & train & 38.0 & 99.2 & 54.9 & 37.2 & 99.9 & 54.2 \\ & dev & 38.1 & 99.1 & 55.0 & 36.4 & 99.7 & 53.3 \\ \cline{1-1} & test & 38.7 & 99.2 & 55.7 & 37.0 & 99.8 & 54.0 \\ \hline \end{tabular} \end{table} Table 2: Evaluation results on entity existence of the span pruner vs. an entity identifier. \begin{table} \begin{tabular}{l l c c c} \hline \hline \multirow{2}{*}{SciERC} & \multicolumn{3}{c}{Ent} & Rel & Rel+ \\ \hline \multirow{2}{*}{Eid} & Backbone & 69.4 & 50.3 & 39.0 \\ & HGRE & 69.4 & 51.5 & 39.5 \\ \hline \multirow{2}{*}{pruner} & Backbone & 71.3 & 52.3 & 40.2 \\ & HGRE & 74.9 & 55.7 & 43.6 \\ \hline \multirow{2}{*}{ACE2005 (BERT\({}_{B}\))} & Ent & Rel & Rel+ \\ \hline \multirow{2}{*}{Eid} & Backbone & 89.5 & 68.3 & 65.3 \\ & HGRE & 89.5 & 68.5 & 66.0 \\ \hline \multirow{2}{*}{pruner} & Backbone & 90.0 & 69.8 & 66.7 \\ & HGRE & 90.2 & 70.7 & 67.5 \\ \hline \hline \end{tabular} \end{table} Table 3: F1 scores of Backbone and HGRE with and without a pre-trained span pruner on the SciERC and ACE2005 (BERT\({}_{B}\)) test set. when utilizing a relatively smaller PLM, HGERE, GCN and MFVI were slightly slower than the first-order model Backbone. However, the difference in speed between HGERE and the other models was relatively small. When using ALBERT, which is much slower than BERT\({}_{B}\), all four models demonstrated comparable inference speeds. ### Error correction analysis We provide quantitative error correction analysis between our higher-order approach HGERE and the first-order baseline Backbone on the SciERC dataset in Fig. 2. We can see that most error corrections of entities and relations made by HGERE come from two categories. The first category is where Backbone incorrectly predicts a true entity or relation as null, and the second category is where Backbone incorrectly assigns a label to a null sample. ## 6 Related Work Entity and relation extractionThe entity and relation extraction task has been studied for a long time. The mainstream methods could be divided into pipeline and joint approaches. Pipeline methods tackle the two subtasks, named entity recognition and relation extraction, consecutively Zelenko et al. (2003); Chan and Roth (2011); Zhong and Chen (2021); Ye et al. (2022). By utilizing a new marker-based embedding method, Ye et al. (2022) becomes the new state-of-the-art ERE model. However, pipeline models have the inherent error propagation problem and they could not fully leverage interactions across the two subtasks. Joint approaches, on the other hand, can alleviate the problem by simultaneously tackling the two subtasks, as empirically revealed by Yan et al. (2022). Various joint approaches have been proposed to tackle ERE. Miwa and Bansal (2016); Katiyar and Cardie (2017) use a stacked model for joint learning through shared parameters. Miwa and Sasaki (2014); Gupta et al. (2016); Wang and Lu (2020); Wang et al. (2021); Yan et al. (2021) tackle both the NER and RE tasks as tagging entries of a table. Fu et al. (2019); Sun et al. (2019) leverage a graph convolutional network (GCN) on an instance dependency graph to enhance instance representations. Nguyen et al. (2021) propose a framework to tackle multiple Information Extraction tasks jointly including the ERE task where a GCN is used to capture the interactions between related instances. Another line of research is based on text-to-text models for structure prediction including ERE. Normally they are not task-specialized and could solve Figure 2: Error correction of entity and relation types on the SciERC dataset. Red color indicates positive corrections and blue color indicates negative corrections. Specifically, positive numbers on the diagonal of the matrix (in red color) indicate that HGERE makes more correct predictions compare to Backbone; negative numbers on non-diagonal entries (in red color) indicate that HGERE makes fewer wrong predictions compare to Backbone. Numbers in blue indicate the opposite. We do not count the null-null case. \begin{table} \begin{tabular}{l c c c} \hline \hline & \multicolumn{2}{c}{SciERC} & \multicolumn{2}{c}{ACE2005} \\ \cline{2-4} & SciBERT & BERT\({}_{B}\) & ALBERT \\ \hline Backbone & 19.4 & 38.0 & 6.1 \\ GCN & 15.7 & 33.8 & 6.3 \\ MFVI & 16.5 & 36.9 & 6.1 \\ HGERE & 15.7 & 30.7 & 6.0 \\ \hline \hline \end{tabular} \end{table} Table 5: Comparison of inference speed (#entities/sec) between HGERE and three baseline models on test sets of SciERC and ACE2005. several structure prediction tasks in a unified way (Paolini et al., 2021; Lu et al., 2022; Liu et al., 2022). This work is similar to Sun et al. (2019); Nguyen et al. (2021) for we both use a graph neural network to enhance the instance representations. The main difference is that the GCN they use cannot adequately model higher-order relationship among multiple instances, while our hypergraph neural network is designed for higher-order modeling. CRF-based higher-order modelA commonly used higher-order model utilizes approximate inference algorithms (mean-field variational inference or loopy belief propagation) on CRFs. Zheng et al. (2015) formulate the mean-field variational inference algorithm on CRFs as a stack of recurrent neural network layers, leading to an end-to-end model for training and inference. Many higher-order models employ this technique for various NLP tasks, such as semantic parsing (Wang et al., 2019; Wang and Tu, 2020) and information extraction (Jia et al., 2022). Hypergraph neural networkHypergraph neural network (HyperGNN) is another way to construct an higher-order model. Traditional Graph Neural Networks employ pairwise connections among nodes, whereas HyperGNNs use a hypergraph structure for data modeling. Feng et al. (2019) and Bai et al. (2021) proposed spectral-based HyperGNNs utilizing the normalized hypergraph Laplacian. Arya et al. (2020) is a spatial-based HyperGNN which aggregates messages in a two-stage procedure. Huang and Yang (2021) proposed _UniGNN_, a unified framework for interpreting the message passing process in HyperGNN. Gao et al. (2023) introduced a general high-order multi-modal data correlation modeling framework to learn an optimal representation in a single hypergraph based framework. ## 7 Conclusion In this paper, we present HGERE, a joint entity and relation extraction model equipped with a span pruning mechanism and a higher-order interaction module (i.e., HGNN). We found that simply using the span pruning mechanism by itself greatly improve the performance over prior state-of-the-art PL-marker, indicating the existence of the error propagation problem for pipeline methods. We compared our model with prior traditional GNN-based models which do not contain hyperedges connecting multiple instances and showed the improvement, suggesting that modeling higher-order interactions between multiple instances is beneficial. Finally, we compared our model with the most popular higher-order CRF models with MFVI and showed the advantages of HGNN in higher-order modeling. ## Limitations Our model achieves a significant improvement in most cases (on ACE2004, SciERC datasets and on ACE2005 with Bertbase). While on ACE2005 with stronger encoder (e.g., ALBERT) we observe less significant improvements. We posit that, with powerful encoders, the recall of gold entity spans would increase, thereby mitigating the error propagation issue and diminishing the benefit of using a span pruning mechanism. Another concern regarding our model is computational efficiency. The time complexity of the _Subject-oriented Packing for Span Pair_ encoding scheme from PL-marker grows linearly with the size of candidate span size. Recall that we over-predict many spans using a span pruning mechanism, which slows down the running time. In practice, our model's running time is around as three times as that of PL-marker. ## Acknowledgments This work was supported by the National Natural Science Foundation of China (61976139).
2310.02147
Finite-Time Analysis of Whittle Index based Q-Learning for Restless Multi-Armed Bandits with Neural Network Function Approximation
Whittle index policy is a heuristic to the intractable restless multi-armed bandits (RMAB) problem. Although it is provably asymptotically optimal, finding Whittle indices remains difficult. In this paper, we present Neural-Q-Whittle, a Whittle index based Q-learning algorithm for RMAB with neural network function approximation, which is an example of nonlinear two-timescale stochastic approximation with Q-function values updated on a faster timescale and Whittle indices on a slower timescale. Despite the empirical success of deep Q-learning, the non-asymptotic convergence rate of Neural-Q-Whittle, which couples neural networks with two-timescale Q-learning largely remains unclear. This paper provides a finite-time analysis of Neural-Q-Whittle, where data are generated from a Markov chain, and Q-function is approximated by a ReLU neural network. Our analysis leverages a Lyapunov drift approach to capture the evolution of two coupled parameters, and the nonlinearity in value function approximation further requires us to characterize the approximation error. Combing these provide Neural-Q-Whittle with $\mathcal{O}(1/k^{2/3})$ convergence rate, where $k$ is the number of iterations.
Guojun Xiong, Jian Li
2023-10-03T15:34:21Z
http://arxiv.org/abs/2310.02147v1
Finite-Time Analysis of Whittle Index based Q-Learning for Restless Multi-Armed Bandits with Neural Network Function Approximation ###### Abstract Whittle index policy is a heuristic to the intractable restless multi-armed bandits (RMAB) problem. Although it is provably asymptotically optimal, finding Whittle indices remains difficult. In this paper, we present Neural-Q-Whittle, a Whittle index based Q-learning algorithm for RMAB with neural network function approximation, which is an example of nonlinear two-timescale stochastic approximation with Q-function values updated on a faster timescale and Whittle indices on a slower timescale. Despite the empirical success of deep Q-learning, the non-asymptotic convergence rate of Neural-Q-Whittle, which couples neural networks with two-timescale Q-learning largely remains unclear. This paper provides a finite-time analysis of Neural-Q-Whittle, where data are generated from a Markov chain, and Q-function is approximated by a ReLU neural network. Our analysis leverages a Lyapunov drift approach to capture the evolution of two coupled parameters, and the nonlinearity in value function approximation further requires us to characterize the approximation error. Combing these provide Neural-Q-Whittle with \(\mathcal{O}(1/k^{2/3})\) convergence rate, where \(k\) is the number of iterations. ## 1 Introduction We consider the restless multi-armed bandits (RMAB) problem [56], where the decision maker (DM) repeatedly activates \(K\) out of \(N\) arms at each decision epoch. Each arm is described by a Markov decision process (MDP) [45], and evolves stochastically according to two different transition kernels, depending on whether the arm is activated or not. Rewards are generated with each transition. Although RMAB has been widely used to study constrained sequential decision making problems [5; 38; 12; 64; 29; 36; 35; 25], it is notoriously intractable due to the explosion of state space [44]. A celebrated heuristic is the Whittle index policy [56], which computes the Whittle index for each arm given its current state as the cost to pull the arm. Whittle index policy then activates the \(K\) highest indexed arms at each decision epoch, and is provably asymptotically optimal [54]. However, the computation of Whittle index requires full knowledge of the underlying MDP associated with each arm, which is often unavailable in practice. To this end, many recent efforts have focused on learning Whittle indices for making decisions in an online manner. First, model-free reinforcement learning (RL) solutions have been proposed [10; 23; 53; 8; 28; 57; 59; 61; 58; 3], among which [3] developed a Whittle index based Q-learning algorithm, which we call Q-Whittle for ease of exposition, and provided the first-ever rigorous asymptotic analysis. However, Q-Whittle suffers from slow convergence since it only updates the Whittle index of a specific state when that state is visited. In addition, Q-Whittle needs to store the Q-function values for all state-action pairs, which limits its applicability only to problems with small state space. Second, deep RL methods have been leveraged to predict Whittle indices via training neural networks [40; 41]. Though these methods are capable of dealing with large state space, there is no asymptotic or finite-time performance guarantee. Furthermore, training neural networks requires to tuning hyper-parameters. This introduces an additional layer of complexity to predict Whittle indices. Third, to address aforementioned deficiencies, [60] proposed Q-Whittle-LFA by coupling Q-Whittle with linear function approximation and provided a finite-time convergence analysis. One key limitation of Q-Whittle-LFA is the unrealistic assumption that all data used in Q-Whittle-LFA are sampled i.i.d. from a fixed stationary distribution. To tackle the aforementioned limitations and inspired by the empirical success of deep Q-learning in numerous applications, we develop Neural-Q-Whittle, a Whittle index based Q-learning algorithm with _neural network function approximation under Markovian observations_. Like [3; 60], the updates of Q-function values and Whittle indices form a two-timescale stochastic approximation (2TSA) with the former operating on a faster timescale and the later on a slower timescale. Unlike [3; 60], our Neural-Q-Whittle uses a deep neural network with the ReLU activation function to approximate the Q-function. However, Q-learning with neural network function approximation can in general diverge [2], and the theoretical convergence of Q-learning with neural network function approximation has been limited to special cases such as fitted Q-iteration with i.i.d. observations [22], which fails to capture the practical setting of Q-learning with neural network function approximation. In this paper, we study the non-asymptotic convergence of Neural-Q-Whittle with data generated from a Markov decision process. Compared with recent theoretical works for Q-learning with neural network function approximation [13; 22; 62], our Neural-Q-Whittle involves a two-timescale update between two coupled parameters, i.e., Q-function values and Whittle indices. This renders existing finite-time analysis in [13; 22; 62] not applicable to our Neural-Q-Whittle due to the fact that [13; 22; 62] only contains a single-timescale update on Q-function values. Furthermore, [13; 22; 62] required an additional projection step for the update of parameters of neural network function so as to guarantee the boundedness between the unknown parameter at any time step with the initialization. This in some cases is impractical. Hence, a natural question that arises is _Is it possible to provide a non-asymptotic convergence rate analysis of Neural-Q-Whittle with two coupled parameters updated in two timescales under Markovian observations without the extra projection step?_ The theoretical convergence guarantee of two-timescale Q-learning with neural network function approximation under Markovian observations remains largely an open problem, and in this paper, we provide an affirmative answer to this question. Our main contributions are summarized as follows: \(\bullet\) We propose Neural-Q-Whittle, a novel Whittle index based Q-learning algorithm with neural network function approximation for RMAB. Inspired by recent work on TD learning [48] and Q-learning [15] with linear function approximation, our Neural-Q-Whittle removes the additional impractical projection step in the neural network function parameter update. \(\bullet\) We establish the first finite-time analysis of Neural-Q-Whittle under Markovian observations. Due to the two-timescale nature for the updates of two coupled parameters (i.e., Q-function values and Whittle indices) in Neural-Q-Whittle, we focus on the convergence rate of these parameters rather than the convergence rate of approximated Q-functions as in [13; 22; 62]. Our key technique is to view Neural-Q-Whittle as a 2TSA for finding the solution of suitable nonlinear equations. Different from recent works on finite-time analysis of a general 2TSA [20] or with linear function approximation [60], the nonlinear parameterization of Q-function in Neural-Q-Whittle under Markovian observations imposes significant difficulty in finding the global optimum of the corresponding nonlinear equations. To mitigate this, we first approximate the original neural network function with a collection of local linearization and focus on finding a surrogate Q-function in the neural network function class that well approximates the optimum. Our finite-time analysis then requires us to consider two Lyapunov functions that carefully characterize the coupling between iterates of Q-function values and Whittle indices, with one Lyapunov function defined with respect to the true neural network function, and the other defined with respect to the locally linearized neural network function. We then characterize the errors between these two Lyapunov functions. Putting them together, we prove that Neural-Q-Whittle achieves a convergence in expectation at a rate \(\mathcal{O}(1/k^{2/3})\), where \(k\) is the number of iterations. \(\bullet\) Finally, we conduct experiments to validate the convergence performance of Neural-Q-Whittle, and verify the sufficiency of our proposed condition for the stability of Neural-Q-Whittle. ## 2 Preliminaries **RMAB.** We consider an infinite-horizon average-reward RMAB with each arm \(n\in\mathcal{N}\) described by a unichain MDP [45]\(\mathcal{M}_{n}:=(\mathcal{S},\mathcal{A},P_{n},r_{n})\), where \(\mathcal{S}\) is the state space with cardinality \(S<\infty\), \(\mathcal{A}\) is the action space with cardinality \(A\), \(P_{n}(s^{\prime}|s,a)\) is the transition probability of reaching state \(s^{\prime}\) by taking action \(a\) in state \(s\), and \(r_{n}(s,a)\) is the reward associated with state-action pair \((s,a)\). At each time slot \(t\), the DM activates \(K\) out of \(N\) arms. Arm \(n\) is "active" at time \(t\) when it is activated, i.e., \(A_{n}(t)=1\); otherwise, arm \(n\) is "passive", i.e., \(A_{n}(t)=0\). Let \(\Pi\) be the set of all possible policies for RMAB, and \(\pi\in\Pi\) is a feasible policy, satisfying \(\pi:\mathcal{F}_{t}\mapsto\mathcal{A}^{N}\), where \(\mathcal{F}_{t}\) is the sigma-algebra generated by random variables \(\{S_{n}(h),A_{n}(h):\forall n\in\mathcal{N},h\leq t\}\). The objective of the DM is to maximize the expected long-term average reward subject to an instantaneous constraint that only \(K\) arms can be activated at each time slot, i.e., \[\text{RMAB:}\quad\max_{\pi\in\Pi}\ \liminf_{T\to\infty}\frac{1}{T}\mathbb{E}_{ \pi}\left(\sum_{t=0}^{T}\sum_{n=1}^{N}r_{n}(t)\right),\quad\text{s.t.}\ \sum_{n=1}^{N}A_{n}(t)=K,\quad\forall t. \tag{1}\] **Whittle Index Policy.** It is well known that RMAB (1) suffers from the curse of dimensionality [44]. To address this challenge, Whittle [56] proposed an index policy through decomposition. Specifically, Whittle relaxed the constraint in (1) to be satisfied on average and obtained a unconstrained problem: \(\max_{\pi\in\Pi}\liminf_{T\to\infty}\frac{1}{T}\mathbb{E}_{\pi}\sum_{t=1}^{T} \sum_{n=1}^{N}\{r_{n}(t)+\lambda(1-A_{n}(t))\}\), where \(\lambda\) is the Lagrangian multiplier associated with the constraint. The key observation of Whittle is that this problem can be decomposed and its solution is obtained by combining solutions of \(N\) independent problems via solving the associated dynamic programming (DP): \(V_{n}(s)=\max_{a\in\{0,1\}}Q_{n}(s,a),\forall n\in\mathcal{N},\) where \[Q_{n}(s,a)+\beta=a\Big{(}r_{n}(s,a)+\sum_{s^{\prime}}p_{n}(s^{\prime}|s,1)V_{n} (s^{\prime})\Big{)}+(1-a)\Big{(}r_{n}(s,a)+\lambda+\sum_{s^{\prime}}p_{n}(s^{ \prime}|s,0)V_{n}(s^{\prime})\Big{)}, \tag{2}\] where \(\beta\) is unique and equals to the maximal long-term average reward of the unichain MDP, and \(V_{n}(s)\) is unique up to an additive constant, both of which depend on the Lagrangian multiplier \(\lambda\). The optimal decision \(a^{*}\) in state \(s\) then is the one which maximizes the right hand side of the above DP. The Whittle index associated with state \(s\) is defined as the value \(\lambda_{n}^{*}(s)\in\mathbb{R}\) such that actions \(0\) and \(1\) are equally favorable in state \(s\) for arm \(n\)[3; 23], satisfying \[\lambda_{n}^{*}(s):=r_{n}(s,1)+\sum_{s^{\prime}}p_{n}(s^{\prime}|s,1)V_{n}(s^{ \prime})-r_{n}(s,0)-\sum_{s^{\prime}}p_{n}(s^{\prime}|s,0)V_{n}(s^{\prime}). \tag{3}\] Whittle index policy then activates \(K\) arms with the largest Whittle indices at each time slot. Additional discussions are provided in Section B in supplementary materials. **Q-Learning for Whittle Index.** Since the underlying MDPs are often unknown, [3] proposed Q-Whittle, a tabular Whittle index based Q-learning algorithm, where the updates of Q-function values and Whittle indices form a 2TSA, with the former operating on a faster timescale for a given \(\lambda_{n}\) and the later on a slower timescale. Specifically, the Q-function values for \(\forall n\in\mathcal{N}\) are updated as \[Q_{n,k+1}(s,a):=Q_{n,k}(s,a)+\alpha_{n,k}\mathds{1}_{\{S_{n,k}=s,A_{n,k}=a\}}\Big{(}r_{n}(s,a)+(1-a)\lambda_{n,k}(s)\\ +\max_{a}Q_{n,k}(S_{n,k+1},a)-I_{n}(Q_{k})-Q_{n,k}(s,a)\Big{)}, \tag{4}\] where \(I_{n}(Q_{k})=\frac{1}{2S}\sum_{s\in\mathcal{S}}(Q_{n,k}(s,0)+Q_{n,k}(s,1))\) is standard in the relative Q-learning for long-term average MDP setting [1], which differs significantly from the discounted reward setting [45; 1]. \(\{\alpha_{n,k}\}\) is a step-size sequence satisfying \(\sum_{k}\alpha_{n,k}=\infty\) and \(\sum_{k}\alpha_{n,k}^{2}<\infty\). Accordingly, the Whittle index is updated as \[\lambda_{n,k+1}(s)=\lambda_{n,k}(s)+\eta_{n,k}(Q_{n,k}(s,1)-Q_{n,k}(s,0)), \tag{5}\] with the step-size sequence \(\{\eta_{n,k}\}\) satisfying \(\sum_{k}\eta_{n,k}=\infty\), \(\sum_{k}\eta_{n,k}^{2}<\infty\) and \(\eta_{n,k}=o(\alpha_{n,k})\). The coupled iterates (4) and (5) form a 2TSA, and [3] provided an asymptotic convergence analysis. ## 3 Neural Q-Learning for Whittle Index A closer look at (5) reveals that Q-Whittle only updates the Whittle index of a specific state when that state is visited. This makes Q-Whittle suffers from slow convergence. In addition, Q-Whittle needs to store the Q-function values for all state-action pairs, which limits its applicability only to problems with small state space. To address this challenge and inspired by the empirical success of deep Q-learning, we develop Neural-Q-Whittle through coupling Q-Whittle with neural network function approximation by using low-dimensional feature mapping and leveraging the strong representation power of neural networks. For ease of presentation, we drop the subscript \(n\) in (4) and (5), and discussions in the rest of the paper apply to any arm \(n\in\mathcal{N}\). Specifically, given a set of basis functions \(\phi_{\ell}:\mathcal{S}\times\mathcal{A}\mapsto\mathbb{R},\forall\ell=1, \cdots,d\) with \(d\ll SA\), the approximation of Q-function \(Q_{\boldsymbol{\theta}}(s,a)\) parameterized by a unknown weight vector \(\boldsymbol{\theta}\in\mathbb{R}^{md}\), is given by \(Q_{\boldsymbol{\theta}}(s,a)=f(\boldsymbol{\theta};\boldsymbol{\phi}(s,a)),\ \forall s \in\mathcal{S},a\in\mathcal{A}\), where \(f\) is a nonlinear neural network function parameterized by \(\boldsymbol{\theta}\) and \(\boldsymbol{\phi}(s,a)\), with \(\boldsymbol{\phi}(s,a)=(\phi_{1}(s,a),\cdots,\phi_{d}(s,a))^{\intercal}\). The feature vectors are assumed to be linearly independent and are normalized so that \(\|\boldsymbol{\phi}(s,a)\|\leq 1,\forall s\in\mathcal{S},a\in\mathcal{A}\). In particular, we parameterize the Q-function by using a two-layer neural network [13; 62] \[f(\boldsymbol{\theta};\boldsymbol{\phi}(s,a)):=\frac{1}{\sqrt{m}}\sum_{r=1}^{ m}b_{r}\sigma(\mathbf{w}_{r}^{\intercal}\boldsymbol{\phi}(s,a)), \tag{6}\] where \(\boldsymbol{\theta}=(b_{1},\ldots,b_{m},\mathbf{w}_{1}^{\intercal},\ldots, \mathbf{w}_{m}^{\intercal})^{\intercal}\) with \(b_{r}\in\mathbb{R}\) and \(\mathbf{w}_{r}\in\mathbb{R}^{d\times 1},\forall r\in[1,m]\). \(b_{r},\forall r\) are uniformly initialized in \(\{-1,1\}\) and \(w_{r},\forall r\) are initialized as a zero mean Gaussian distribution according to \(\mathcal{N}(\mathbf{0},\mathbf{I}_{d}/d)\). During training process, only \(\mathbf{w}_{r},\forall r\) are updated while \(b_{r},\forall r\) are fixed as the random initialization. Hence, we use \(\boldsymbol{\theta}\) and \(\mathbf{w}_{r},\forall r\) interchangeably throughout this paper. \(\sigma(x)=\max(0,x)\) is the rectified linear unit (ReLU) activation function1. Footnote 1: The finite-time analysis of Deep Q-Networks (DQN) [13; 22; 62] and references therein focuses on the ReLU activation function, as it has certain properties that make the analysis tractable. ReLU is piecewise linear and non-saturating, which can simplify the mathematical analysis. Applying the same analysis to other activation functions like the hyperbolic tangent (tanh) could be more complex, which is out of the scope of this work. Given (6), we can rewrite the Q-function value updates in (4) as \[\boldsymbol{\theta}_{k+1}=\boldsymbol{\theta}_{k}+\alpha_{k}\Delta_{k}\nabla _{\boldsymbol{\theta}}f(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(S_{k},A_{k} )), \tag{7}\] with \(\Delta_{k}\) being the temporal difference (TD) error defined as \(\Delta_{k}:=r(S_{k},A_{k})+(1-A_{k})\lambda_{k}(s)-I(\boldsymbol{\theta}_{k})+ \max_{a}f(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(S_{k+1},a))-f(\boldsymbol {\theta}_{k};\boldsymbol{\phi}(S_{k},A_{k}))\), where \(I(\boldsymbol{\theta}_{k})=\frac{1}{2S}\sum_{s\in\mathcal{S}}[f(\boldsymbol{ \theta}_{k};\boldsymbol{\phi}(s,0))+f(\boldsymbol{\theta}_{k};\boldsymbol{ \phi}(s,1))]\). Similarly, the Whittle index update (5) can be rewritten as \[\lambda_{k+1}(s)=\lambda_{k}(s)+\eta_{k}(f(\boldsymbol{\theta}_{k};\boldsymbol {\phi}(s,1))-f(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(s,0))). \tag{8}\] The coupled iterates in (7) and (8) form Neural-Q-Whittle as summarized in Algorithm 1, which aims to learn the coupled parameters \((\boldsymbol{\theta}^{\star},\lambda^{\star}(s))\) such that \(f(\boldsymbol{\theta}^{\star},\boldsymbol{\phi}(s,1))=f(\boldsymbol{\theta}^{ \star},\boldsymbol{\phi}(s,0)),\forall s\in\mathcal{S}\). ``` 1:Input:\(\boldsymbol{\phi}(s,a)\) for \(\forall s\in\mathcal{S},a\in\mathcal{A}\), and learning rates \(\{\alpha_{k}\}_{k=1,\ldots,T}\), \(\{\eta_{k}\}_{k=1,\ldots,T}\) 2:Initialization:\(b_{r}\sim\text{Unif}(\{-1,1\}),\mathbf{w}_{r,0}\sim\mathcal{N}(\mathbf{0}, \mathbf{I}_{d}/d),\forall r\in[1,m]\) and \(\lambda(s)=0\), \(\forall s\in\mathcal{S}\) 3:for\(s\in\mathcal{S}\)do 4:for\(k=1,\ldots,T\)do 5: Sample \((S_{k},A_{k},S_{k+1})\) according to the \(\epsilon\)-greedy policy; 6:\(\Delta_{k}\!=\!r(S_{k},A_{k})+(1-A_{k})\lambda_{k}(s)+\max_{a}f(\boldsymbol{ \theta}_{k};\boldsymbol{\phi}(S_{k+1},a))-I(\boldsymbol{\theta}_{k})\!-\!f( \boldsymbol{\theta}_{k};\boldsymbol{\phi}(S_{k},A_{k}))\); 7:\(\boldsymbol{\theta}_{k+1}=\boldsymbol{\theta}_{k}+\alpha_{k}\Delta_{k}\nabla _{\boldsymbol{\theta}}f(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(S_{k},A_{k}))\); 8:\(\lambda_{k+1}(s)=\lambda_{k}(s)+\eta_{k}(f(\boldsymbol{\theta}_{k};\boldsymbol{ \phi}(s,1))-f(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(s,0))\); 9:endfor 10:endfor 11:Return:\(\lambda(s),\forall s\in\mathcal{S}\). ``` **Algorithm 1** Neural-Q-Whittle: Neural Q-Learning for Whittle Index **Remark 1**.: _Unlike recent works for Q-learning with linear [6; 37; 67] or neural network function approximations [13; 22; 62], we do not assume an additional projection step of the updates of unknown parameters \(\boldsymbol{\theta}_{k}\) in (7) to confine \(\boldsymbol{\theta}_{k},\forall k\) into a bounded set. This projection step is often used to stabilize the iterates related to the unknown stationary distribution of the underlying Markov chain, which in some cases is impractical. More recently, [48] removed the extra projection step and established the finite-time convergence of TD learning, which is treated as a linear stochastic approximation algorithm. [15] extended it to the Q-learning with linear function approximation._ _However, these state-of-the-art works only contained a single-timescale update on Q-function values, i.e., with the only unknown parameter \(\mathbf{\theta}\), while our Neural-Q-Whittle involves a two-timescale update between two coupled unknown parameters \(\mathbf{\theta}\) and \(\lambda\) as in (7) and (8). Our goal in this paper is to expand the frontier by providing a finite-time bound for Neural-Q-Whittle under Markovian noise without requiring an additional projection step. We summarize the differences between our work and existing literature in Table 1._ ## 4 Finite-Time Analysis of Neural-Q-Whittle In this section, we present the finite-time analysis of Neural-Q-Whittle for learning Whittle index \(\lambda(s)\) of any state \(s\in\mathcal{S}\) when data are generated from a MDP. To simplify notation, we abbreviate \(\lambda(s)\) as \(\lambda\) in the rest of the paper. We start by first rewriting the updates of Neural-Q-Whittle in (7) and (8) as a nonlinear two-timescale stochastic approximation (2TSA) in Section 4.1. ### A Nonlinear 2TSA Formulation with Neural Network Function We first show that Neural-Q-Whittle can be rewritten as a variant of the nonlinear 2TSA. For any fixed policy \(\pi\), since the state of each arm \(\{S_{k}\}\) evolves according to a Markov chain, we can construct a new variable \(X_{k}=(S_{k},A_{k},S_{k+1})\), which also forms a Markov chain with state space \(\mathcal{X}:=\{(s,a,s^{\prime})|s\in\mathcal{S},\pi(a|s)\geq 0,p(s^{\prime}|s,a )>0\}\). Therefore, the coupled updates (7) and (8) of Neural-Q-Whittle can be rewritten in the form of a nonlinear 2TSA [20]: \[\mathbf{\theta}_{k+1}=\mathbf{\theta}_{k}+\alpha_{k}h(X_{k},\mathbf{\theta}_{k},\lambda_ {k}),\qquad\lambda_{k+1}=\lambda_{k}+\eta_{k}g(X_{k},\mathbf{\theta}_{k},\lambda_{ k}), \tag{9}\] where \(\mathbf{\theta}_{0}\) and \(\lambda_{0}\) being arbitrarily initialized in \(\mathbb{R}^{md}\) and \(\mathbb{R}\), respectively; and \(h(\cdot)\) and \(g(\cdot)\) satisfy \[h(X_{k},\mathbf{\theta}_{k},\lambda_{k}) :=\nabla_{\mathbf{\theta}}f(\mathbf{\theta}_{k};\mathbf{\phi}(S_{k},A_{k})) \Delta_{k},\qquad\mathbf{\theta}_{k}\in\mathbb{R}^{md},\lambda_{k}\in\mathbb{R}, \tag{10}\] \[g(X_{k},\mathbf{\theta}_{k},\lambda_{k}) :=f(\mathbf{\theta}_{k};\mathbf{\phi}(s,1))-f(\mathbf{\theta}_{k};\mathbf{\phi}(s,0)),\qquad\mathbf{\theta}_{k}\in\mathbb{R}^{md}. \tag{11}\] Since \(\eta_{k}\ll\alpha_{k}\), the dynamics of \(\mathbf{\theta}\) evolves much faster than those of \(\lambda\). We aim to establish the finite-time performance of the nonlinear 2TSA in (9), where \(f(\cdot)\) is the neural network function defined in (6). This is equivalent to find the root2\((\mathbf{\theta}^{*},\lambda^{*})\) of a system with _two coupled_ nonlinear equations \(h:\mathcal{X}\times\mathbb{R}^{md}\times\mathbb{R}\to\mathbb{R}^{md}\) and \(g:\mathcal{X}\times\mathbb{R}^{md}\times\mathbb{R}\to\mathbb{R}\) such that Footnote 2: The root \((\mathbf{\theta}^{*},\lambda^{*})\) of the nonlinear 2TSA (9) can be established by using the ODE method following the solution of suitably defined differential equations [9; 49; 3; 21; 19; 20], i.e., \(\hat{\mathbf{\theta}}=H(\mathbf{\theta},\lambda),\dot{\lambda}=\frac{\eta}{\alpha}G( \mathbf{\theta},\lambda)\), where a fixed stepsize is assumed for ease of expression at this moment. \[H(\mathbf{\theta},\lambda):=\mathbb{E}_{\mu}[h(X,\mathbf{\theta},\lambda)]=0,\qquad G (\mathbf{\theta},\lambda):=\mathbb{E}_{\mu}[g(X,\mathbf{\theta},\lambda)]=0, \tag{12}\] where \(X\) is a random variable in finite state space \(\mathcal{X}\) with unknown distribution \(\mu\). For a fixed \(\mathbf{\theta}\), to study the stability of \(\lambda\), we assume the condition on the existence of a mapping such that \(\lambda=y(\mathbf{\theta})\) is the unique solution of \(G(\mathbf{\theta},\lambda)=0\). In particular, \(y(\mathbf{\theta})\) is given as \[y(\mathbf{\theta})=r(s,1)+\sum_{s^{\prime}}p(s^{\prime}|s,1)\max_{a}f(\mathbf{\theta}; \mathbf{\phi}(s^{\prime},a))-r(s,0)-\sum_{s^{\prime}}p(s^{\prime}|s,0)\max_{a}f(\bm {\theta};\mathbf{\phi}(s^{\prime},a)). \tag{13}\] \begin{table} \begin{tabular}{|c|c|c|c|c|} \hline **Algorithm** & **Noise** & **Approximation** & **Timescale** & **Whittle index** \\ \hline \hline Q-Whittle [3] & _i.i.d._ & \(X\) & _two-timescale_ & ✓ \\ Q-Whittle-LFA [60; 3; 67] & _i.i.d._ & linear & _two-timescale_ & ✓ \\ Q-Learning-LFA [6; 37; 67] & _Markovian_ & linear & _single-timescale_ & ✗ \\ Q-Learning-NFA [13; 15; 22; 62] & _Markovian_ & _neural network_ & _single-timescale_ & ✗ \\ TD-Learning-LFA [48] & _Markovian_ & linear & _single-timescale_ & ✗ \\ 2TSA-IID [19; 21] & _i.i.d._ & ✗ & _two-timescale_ & ✗ \\ 2TSA-Markovian [20] & _Markovian_ & ✗ & _two-timescale_ & ✗ \\ \hline \hline Neural-Q-Whittle (**this work**) & _Markovian_ & _neural network_ & _two-timescale_ & ✓ \\ \hline \end{tabular} \end{table} Table 1: Comparison of settings in related works. ### Main Results As inspired by [20], the finite-time analysis of such a nonlinear 2TSA boils down to the choice of two step sizes \(\{\alpha_{k},\eta_{k},\forall k\}\) and a Lyapunov function that couples the two iterates in (9). To this end, we first define the following two error terms: \[\tilde{\mathbf{\theta}}_{k}=\mathbf{\theta}_{k}-\mathbf{\theta}^{*},\qquad\tilde{\lambda}_{ k}=\lambda_{k}-y(\mathbf{\theta}_{k}), \tag{14}\] which characterize the coupling between \(\mathbf{\theta}_{k}\) and \(\lambda_{k}\). If \(\tilde{\mathbf{\theta}}_{k}\) and \(\tilde{\lambda}_{k}\) go to zero simultaneously, the convergence of \((\mathbf{\theta}_{k},\lambda_{k})\) to \((\mathbf{\theta}^{*},\lambda^{*})\) can be established. Thus, to prove the convergence of \((\mathbf{\theta}_{k},\lambda_{k})\) of the nonlinear 2TSA in (9) to its true value \((\mathbf{\theta}^{*},\lambda^{*})\), we can equivalently study the convergence of \((\tilde{\mathbf{\theta}}_{k},\tilde{\lambda}_{k})\) by providing the finite-time analysis for the mean squared error generated by (9). To couple the fast and slow iterates, we define the following weighted Lyapunov function \[M(\mathbf{\theta}_{k},\lambda_{k}):=\frac{\eta_{k}}{\alpha_{k}}\|\tilde{\mathbf{\theta }}_{k}\|^{2}+\|\tilde{\lambda}_{k}\|^{2}=\frac{\eta_{k}}{\alpha_{k}}\|\mathbf{ \theta}_{k}-\mathbf{\theta}^{*}\|^{2}+\|\lambda_{k}-y(\mathbf{\theta}_{k})\|^{2}, \tag{15}\] where \(\|\cdot\|\) stands for the the Euclidean norm for vectors throughout the paper. It is clear that the Lyapunov function \(M(\mathbf{\theta}_{k},\lambda_{k})\) combines the updates of \(\mathbf{\theta}\) and \(\lambda\) with respect to the true neural network function \(f(\mathbf{\theta};\mathbf{\phi}(s,a))\) in (6). To this end, our goal turns to characterize finite-time convergence of \(\mathbb{E}[M(\mathbf{\theta}_{k},\lambda_{k})]\). However, it is challenging to directly finding the global optimum of the corresponding nonlinear equations due to the nonlinear parameterization of Q-function in Neural-Q-Whittle. In addition, the operators \(h(\cdot),g(\cdot)\) and \(y(\cdot)\) in (10), (11) and (13) directly relate with the convoluted neural network function \(f(\mathbf{\theta};\mathbf{\phi}(s,a))\) in (6), which hinders us to characterize the smoothness properties of theses operators. Such properties are often required for the analysis of stochastic approximation [15; 19; 21]. To mitigate this, **(Step 1)** we instead approximate the true neural network function \(f(\mathbf{\theta},\mathbf{\phi}(s,a))\) with a collection of local linearization \(f_{0}(\mathbf{\theta};\mathbf{\phi}(s,a))\) at the initial point \(\mathbf{\theta}_{0}\). Based on the surrogate stationary point \(\mathbf{\theta}_{0}^{*}\) of \(f_{0}(\mathbf{\theta};\mathbf{\phi}(s,a))\), we correspondingly define a modified Lyapunov function \(\hat{M}(\mathbf{\theta}_{k},\lambda_{k})\) combining updates of \(\mathbf{\theta}\) and \(\lambda\) with respect to such local linearization. Specifically, we have \[\hat{M}(\mathbf{\theta}_{k},\lambda_{k}):=\frac{\eta_{k}}{\alpha_{k}}\|\mathbf{\theta }_{k}-\mathbf{\theta}_{0}^{*}\|^{2}+\|\lambda_{k}-y_{0}(\mathbf{\theta}_{k})\|^{2}, \tag{16}\] where \(y_{0}(\cdot)\) is in the same expression as \(y(\cdot)\) in (13) by replacing \(f(\cdot)\) with \(f_{0}(\cdot)\), and we will describe this in details below. **(Step 2)** We then study the convergence rate of the nonlinear 2TSA using this modified Lyapunov function under general conditions. **(Step 3)** Finally, since the two coupled parameters \(\mathbf{\theta}\) and \(\lambda\) in (9) are updated with respect to the true neural network function \(f(\mathbf{\theta};\mathbf{\phi}(s,a))\) in (6) in Neural-Q-Whittle, while we characterize their convergence using the approximated neural network function in Step 2. Hence, this further requires us to characterize the approximation errors. We visualize the above three steps in Figure 1 and provide a proof sketch in Section 4.3. Combing them together gives rise to our main theoretical results on the finite-time performance of Neural-Q-Whittle, which is formally stated in the following theorem. **Theorem 1**.: _Consider iterates \(\{\mathbf{\theta}_{k}\}\) and \(\{\lambda_{k}\}\) generated by Neural-Q-Whittle in (7) and (8). Given \(\alpha_{k}=\frac{\alpha_{0}}{(k+1)},\eta_{k}=\frac{\eta_{0}}{(k+1)^{4/3}}\), we have for \(\forall k\geq\tau\)_ \[\mathbb{E}[M(\mathbf{\theta}_{k+1},\lambda_{k+1})|\mathcal{F}_{k-\tau }]\leq\frac{2\tau^{2}\mathbb{E}[\hat{M}(\mathbf{\theta}_{\tau},\lambda_{\tau})]}{ (k+1)^{2}}+\frac{1200\alpha_{0}^{3}}{\eta_{0}}\frac{(C_{1}+\|\hat{\mathbf{\theta}} _{0}\|)^{2}+(2C_{1}+\|\tilde{\lambda}_{0}\|)^{2}}{(k+1)^{2/3}}\] \[+\frac{2\eta_{0}c_{0}^{2}}{\alpha_{0}(1-\kappa)^{2}}\|span(\Pi_{ \mathcal{F}}f(\mathbf{\theta}^{*})-f(\mathbf{\theta}^{*}))\|^{2}+\bigg{(}\frac{2}{(k+ 1)^{2/3}}+2\bigg{)}\,\mathcal{O}\Big{(}\frac{c_{1}^{3}(\|\mathbf{\theta}_{0}\|+| \lambda_{0}|+1)^{3}}{m^{1/2}}\Big{)}, \tag{17}\] _where \(C_{1}:=c_{1}(\|\mathbf{\theta}_{0}\|+\|\lambda_{0}\|+1)\) with \(c_{1}\) being a proper chosen constant, \(c_{0}\) is a constant defined in Assumption 3, \(\tau\) is the mixing time defined in (22), \(span\) denotes for the span semi-norm [47], and \(\Pi_{\mathcal{F}}\) represents the projection to the set of \(\mathcal{F}\) containing all possible \(f_{0}(\mathbf{\theta};\mathbf{\phi}(s,a))\) in (18)._ The first term on the right hand side (17) corresponds to the bias compared to the Lyapunov function at the mixing time \(\tau\), which goes to zero at a rate of \(\mathcal{O}(1/k^{2})\). The second term corresponds to the accumulated estimation error of the nonlinear 2TSA due to Markovian noise, which vanishes at the rate \(\mathcal{O}(1/k^{2/3})\). Hence it dominates the overall convergence rate in (17). The third term captures the distance between the optimal solution \((\mathbf{\theta}^{*},\lambda^{*})\) to the true neural network function \(f(\mathbf{\theta}_{k};\mathbf{\phi}(s,a))\) in (6) and the optimal one \((\mathbf{\theta}^{*}_{0},y_{0}(\mathbf{\theta}^{*}_{0}))\) with local linearization \(f_{0}(\mathbf{\theta}_{k};\mathbf{\phi}(s,a))\) in (18), which quantifies the error when \(f(\mathbf{\theta}^{*})\) does not fall into the function class \(\mathcal{F}\). The last term characterizes the distance between \(f(\mathbf{\theta}_{k};\mathbf{\phi}(s,a))\) and \(f_{0}(\mathbf{\theta}_{k};\mathbf{\phi}(s,a))\) with any \(\mathbf{\theta}_{k}\). Both terms diminish as \(m\to\infty\). Theorem 1 implies the convergence to the optimal value \((\mathbf{\theta}^{*},\lambda^{*})\) is bounded by the approximation error, which will diminish to zero as representation power of \(f_{0}(\mathbf{\theta}_{k};\mathbf{\phi}(s,a))\) increases when \(m\to\infty\). Finally, we note that the right hand side (17) ends up in \(\mathcal{O}(1/k^{2})+\mathcal{O}(1/k^{2/3})+c\), where \(c\) is a constant and its value goes to \(0\) as \(m\to\infty\). This indicates the error bounds of linearization with the original neural network functions are controlled by the overparameterization value of \(m\). Need to mention that a constant step size will result in a non-vanishing accumulated error as in [15]. **Remark 2**.: _A finite-time analysis of nonlinear 2TSA was presented in [39]. However, [39] required a stability condition that \(\lim_{k\to\infty}(\mathbf{\theta}_{k},\lambda_{k})=(\mathbf{\theta}^{*},\lambda^{*})\), and both \(h\) and \(g\) are locally approximated as linear functions. [19; 60] relaxed these conditions and provided a finite-time analysis under i.i.d. noise. These results were later extended to Markovian noise [20] under the assumption that \(H\) function is strongly monotone in \(\mathbf{\theta}\) and \(G\) function is strongly monotone in \(\lambda\). Since [20] leveraged the techniques in [19], it needed to explicitly characterize the covariance between the error caused by Markovian noise and the parameters' residual error in (14), leading to the convergence analysis much more intrinsic. [15] exploited the mixing time to avoid the covariance between the error caused by Markovian noise and the parameters' residual error, however, it only considered the single timescale \(Q\)-learning with linear function approximation. Though our Neural-Q-Whittle can be rewritten as a nonlinear 2TSA, the nonlinear parameterization of \(Q\)-function caused by the neural network function approximation makes the aforementioned analysis not directly applicable to ours and requires additional characterization as highlighted in Figure 1. The explicit characterization of approximation errors further distinguish our work._ ### Proof Sketch In this section, we sketch the proofs of the three steps shown in Figure 1 as required for Theorem 1. #### 4.3.1 Step 1: Approximated Solution of Neural-Q-Whittle We first approximate the optimal solution by projecting the Q-function in (6) to some function classes parameterized by \(\mathbf{\theta}\). The common choice of the projected function classes is the local linearization of \(f(\mathbf{\theta};\mathbf{\phi}(s,a))\) at the initial point \(\mathbf{\theta}_{0}\)[13; 62], i.e., \(\mathcal{F}:=\{f_{0}(\mathbf{\theta};\mathbf{\phi}(s,a)),\forall\mathbf{\theta}\in\Theta\}\), where \[f_{0}(\mathbf{\theta};\mathbf{\phi}(s,a))=\frac{1}{\sqrt{m}}\sum_{r=1}^{m}b_{r}\mathds {1}\{\mathbf{w}_{r,0}^{\mathsf{T}}\mathbf{\phi}(s,a)>0\}\mathbf{w}_{r}^{\mathsf{T }}\mathbf{\phi}(s,a). \tag{18}\] Then, we define the approximate stationary point \(\mathbf{\theta}^{*}_{0}\) with respect to \(f_{0}(\mathbf{\theta};\mathbf{\phi}(s,a))\) as follows. **Definition 1**.: _[[13; 62]] A point \(\mathbf{\theta}^{*}_{0}\in\Theta\) is said to be the approximate stationary point of Algorithm 1 if for all feasible \(\mathbf{\theta}\in\Theta\) it holds that \(\mathbb{E}_{n,\pi,\mathcal{P}}[(\Delta_{0}\cdot\nabla_{\mathbf{\theta}}f_{0}(\mathbf{ \theta};\mathbf{\phi}(s,a)))^{\mathsf{T}}(\mathbf{\theta}-\mathbf{\theta}^{*}_{0})]\geq 0, \forall\mathbf{\theta}\in\Theta,\) with \(\Delta_{0}:=[r(s,a)+(1-a)\lambda^{*}-I_{0}(\mathbf{\theta})+\max_{a^{\prime}}f_{0} (\mathbf{\theta};\mathbf{\phi}(s^{\prime},a))-f_{0}(\mathbf{\theta};\mathbf{\phi}(s,a))]\), where \(I_{0}(\mathbf{\theta})=\frac{1}{2S}\sum_{s\in\mathcal{S}}[f_{0}(\mathbf{\theta};\mathbf{ \phi}(s,0))+f_{0}(\mathbf{\theta};\mathbf{\phi}(s,1))]\)._ Figure 1: Neural-Q-Whittle operates w.r.t. true neural function \(f(\cdot)\) with its finite-time performance given in Theorem 1 (indicated in dashed lines). Our proofs operate in three steps: (i) Step 1: Obtain local linearization \(f_{0}(\cdot)\) and define Lyapunov function \(\hat{M}(\cdot)\) w.r.t. \(f_{0}(\cdot)\). (ii) Step 2: Characterize the finite-time performance w.r.t. \(\hat{M}(\cdot)\) using Lyapunov drift method. Since Neural-Q-Whittle is updated w.r.t. \(f(\cdot)\), we need to characterize the gap between \(f(\cdot)\) and \(f_{0}(\cdot)\). (iii) Step 3: Similarly, we characterize the approximation errors between \(M(\cdot)\) and \(\hat{M}(\cdot)\). Though there is a gap between the true neural function (6) and the approximated local linearized function (18), the gap diminishes as the width of neural network i.e., \(m\), becomes large [13; 62]. With the approximated stationary point \(\boldsymbol{\theta}_{0}^{*}\), we can redefine the two error terms in (14) as \[\hat{\boldsymbol{\theta}}_{k}=\boldsymbol{\theta}_{k}-\boldsymbol{\theta}_{0}^ {*},\qquad\hat{\lambda}_{k}=\lambda_{k}-y_{0}(\boldsymbol{\theta}_{k}), \tag{19}\] using which we correspondingly define a modified Lyapunov function \(\hat{M}(\boldsymbol{\theta}_{k},\lambda_{k})\) in (16), where \[y_{0}(\boldsymbol{\theta})\!=\!r(s,\!1)\!+\!\sum_{s^{\prime}}\!p(s^{\prime}|s, 1)\max_{a}\!f_{0}(\boldsymbol{\theta};\boldsymbol{\phi}(s^{\prime},a))\!-\!r (s,\!0)\!\!-\!\!\sum_{s^{\prime}}p(s^{\prime}|s,0)\max_{a}\!f_{0}(\boldsymbol {\theta};\boldsymbol{\phi}(s^{\prime},a)). \tag{20}\] #### 4.3.2 Step 2: Convergence Rate of \(\hat{M}(\boldsymbol{\theta}_{k},\lambda_{k})\) in (16) Since we approximate the true neural network function \(f(\boldsymbol{\theta};\boldsymbol{\phi}(s,a))\) in (6) with the local linearized function \(f_{0}(\boldsymbol{\theta};\boldsymbol{\phi}(s,a))\) in (18), the operators \(h(\cdot)\) and \(g(\cdot)\) in (10)-(11) turn correspondingly to be \[h_{0}(X_{k},\boldsymbol{\theta}_{k},\lambda_{k})=\nabla_{\boldsymbol{\theta} }f_{0}(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(S_{k},A_{k}))\Delta_{k,0},\ g_{0}( \boldsymbol{\theta}_{k}):=f_{0}(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(s,1 ))-f_{0}(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(s,0)), \tag{21}\] with \(\Delta_{k,0}:=r(S_{k},A_{k})+(1-A_{k})\lambda_{k}-I_{0}(\boldsymbol{\theta}_{ k})+\max_{a}f_{0}(\boldsymbol{\theta}_{k};\boldsymbol{\phi}(S_{k+1},a))-f_{0}( \boldsymbol{\theta}_{k};\boldsymbol{\phi}(S_{k},A_{k})).\) Before we present the finite-time error bound of the nonlinear 2TSA (9) under Markovian noise, we first discuss the mixing time of the Markov chain \(\{X_{k}\}\) and our assumptions. **Definition 2** (Mixing time [15]).: _For any \(\delta>0\), define \(\tau_{\delta}\) as_ \[\tau_{\delta}=\!\min\{k\geq 1:\|\mathbb{E}[h_{0}(X_{k},\boldsymbol{\theta}, \lambda)|X_{0}=x]-H_{0}(\boldsymbol{\theta},\lambda)\|\leq\delta(\|\boldsymbol {\theta}-\boldsymbol{\theta}_{0}^{*}\|+\|\lambda-y_{0}(\boldsymbol{\theta}_{0 }^{*}\|\|)\}. \tag{22}\] **Assumption 1**.: _The Markov chain \(\{X_{k}\}\) is irreducible and aperiodic. Hence, there exists a unique stationary distribution \(\mu\)[32], and constants \(C>0\) and \(\rho\in(0,1)\) such that \(d_{TV}(P(X_{k}|X_{0}=x),\mu)\leq C\rho^{k},\forall k\geq 0,x\in\mathcal{X},\) where \(d_{TV}(\cdot,\cdot)\) is the total-variation (TV) distance [32]._ **Remark 3**.: _Assumption 1 is often assumed to study the asymptotic convergence of stochastic approximation under Markovian noise [4; 9; 15]._ **Lemma 1**.: _The function \(h_{0}(X,\boldsymbol{\theta},\lambda)\) defined in (21) is globally Lipschitz continuous w.r.t \(\boldsymbol{\theta}\) and \(\lambda\) uniformly in \(X\), i.e., \(\|h_{0}(X,\boldsymbol{\theta}_{1},\lambda_{1})\!-\!h_{0}(X,\boldsymbol{ \theta}_{2},\lambda_{2})\|\leq L_{h,1}\|\boldsymbol{\theta}_{1}-\boldsymbol{ \theta}_{2}\|+L_{h,2}\|\lambda_{1}-\lambda_{2}\|,\forall X\in\mathcal{X}\), and \(L_{h,1}=3,h_{h,2}=1\) are valid Lipschitz constants._ **Lemma 2**.: _The function \(g_{0}(\boldsymbol{\theta})\) defined in (21) is linear and thus Lipschitz continuous in \(\boldsymbol{\theta}\), i.e., \(\|g_{0}(\boldsymbol{\theta}_{1})-g_{0}(\boldsymbol{\theta}_{2})\|\leq L_{g} \|\boldsymbol{\theta}_{1}-\boldsymbol{\theta}_{2}\|\), and \(L_{g}=2\) is a valid Lipschitz constant._ **Lemma 3**.: _The function \(y_{0}(\boldsymbol{\theta})\) defined in (20) is linear and thus Lipschitz continuous in \(\boldsymbol{\theta}\), i.e., \(\|y_{0}(\boldsymbol{\theta}_{1})-y_{0}(\boldsymbol{\theta}_{2})\|\leq L_{y} \|\boldsymbol{\theta}_{1}-\boldsymbol{\theta}_{2}\|\), and \(L_{y}=2\) is a valid Lipschitz constant._ **Remark 4**.: _The Lipschitz continuity of \(h_{0}\) guarantees the existence of a solution \(\boldsymbol{\theta}\) to the ODE \(\dot{\boldsymbol{\theta}}\) for a fixed \(\lambda\), while the Lipschitz continuity of \(g_{0}\) and \(y_{0}\) ensures the existence of a solution \(\lambda\) to the ODE \(\dot{\lambda}\) when \(\boldsymbol{\theta}\) is fixed. These lemmas often serve as assumptions when proving the convergence rate for both linear and nonlinear 2TSA [31; 39; 18; 24; 19; 17; 27]._ **Lemma 4**.: _For a fixed \(\lambda\), there exists a constant \(\mu_{1}>0\) such that \(h_{0}(X,\boldsymbol{\theta},\lambda)\) defined in (10) satisfies_ \[\mathbb{E}[\dot{\boldsymbol{\theta}}^{\intercal}h_{0}(X,\boldsymbol{\theta}, \lambda)]\leq-\mu_{1}\|\hat{\boldsymbol{\theta}}\|^{2}.\] _For fixed \(\boldsymbol{\theta}\), there exists a constant \(\mu_{2}>0\) such that \(g_{0}(X,\boldsymbol{\theta},\lambda)\) defined in (11) satisfies_ \[\mathbb{E}[\dot{\lambda}g_{0}(X,\boldsymbol{\theta},\lambda)]\leq-\mu_{2}\| \hat{\lambda}\|^{2}.\] **Remark 5**.: _Lemma 4 guarantees the stability and uniqueness of the solution \(\boldsymbol{\theta}\) to the ODE \(\dot{\boldsymbol{\theta}}\) for a fixed \(\lambda\), and the uniqueness of the solution \(\lambda\) to the ODE \(\dot{\lambda}\) for a fixed \(\boldsymbol{\theta}\). This assumption can be viewed as a relaxation of the stronger monotone property of nonlinear mappings [19; 15], since it is automatically satisfied if \(h\) and \(g\) are strong monotone as assumed in [19]._ **Lemma 5**.: _Under Assumption 1 and Lemma 1, there exist constants \(C>0\), \(\rho\in(0,1)\) and \(L=\max(3,\max_{X}h_{0}(X,\boldsymbol{\theta}_{0}^{*}),y_{0}(\boldsymbol{\theta}_{0 }^{*}))\) such that_ \[\tau_{\delta}\leq\frac{\log(1/\delta)+\log(2LCmd)}{\log(1/\rho)}.\] **Remark 6**.: \(\tau_{\delta}\) _is equivalent to the mixing time of the underlying Markov chain satisfying \(\lim_{\delta\to 0}\delta\tau_{\delta}=0\)[15]. For simplicity, we remove the subscript and denote it as \(\tau\)._ We now present the finite-time error bound for the Lyapunov function \(\hat{M}(\boldsymbol{\theta}_{k},\lambda_{k})\) in (16). **Theorem 2**.: _Consider iterates \(\{\boldsymbol{\theta}_{k}\}\) and \(\{\lambda_{k}\}\) generated by_ Neural-Q-Whittle _in (7) and (8). Given Lemma 1-4, \(\alpha_{k}=\frac{\alpha_{0}}{(k+1)},\eta_{k}=\frac{\eta_{0}}{(k+1)^{4/3}}\), \(\hat{C}_{1}:=c_{1}(\|\boldsymbol{\theta}_{0}\|+\|\lambda_{0}\|+1)\) with a constant \(c_{1}\),_ \[\mathbb{E}[\hat{M}(\boldsymbol{\theta}_{k+1},\lambda_{k+1})| \mathcal{F}_{k-\tau}]\leq\frac{\tau^{2}\mathbb{E}[\hat{M}(\boldsymbol{\theta }_{\tau},\lambda_{\tau})]}{(k+1)^{2}}+\frac{600\alpha_{0}^{3}}{\eta_{0}}\frac {(C_{1}+\|\hat{\boldsymbol{\theta}}_{0}\|)^{2}+(2C_{1}+\|\hat{\lambda}_{0}\|) ^{2}}{(k+1)^{2/3}}\\ +\frac{\mathcal{O}\Big{(}c_{1}^{3}(\|\boldsymbol{\theta}_{0}\| \!+\!|\lambda_{0}|\!+\!1)^{3}m^{-1/2}\Big{)}}{(k+1)^{2/3}},\quad\forall k\geq\tau. \tag{23}\] 3.3 Step 3: Approximation Error between \(M(\boldsymbol{\theta}_{k},\lambda_{k})\) and \(\hat{M}(\boldsymbol{\theta}_{k},\lambda_{k})\) Finally, we characterize the approximation error between Lyapunov functions \(M(\boldsymbol{\theta}_{k},\lambda_{k})\) and \(\hat{M}(\boldsymbol{\theta}_{k},\lambda_{k})\). Since we are dealing with long-term average MDP, we assume that the total variation of the MDP is bounded [47]. **Assumption 2**.: _There exists \(0<\kappa<1\) such that \(\sup_{(s,a),(s^{\prime},a^{\prime})}\|p(\cdot|s,a)-p(\cdot|s^{\prime},a^{ \prime})\|_{TV}=2\kappa\)._ Hence, the Bellman operator is a span-contraction operator [47], i.e., \[span(\mathcal{T}f_{0}(\boldsymbol{\theta}_{0}^{*})-\mathcal{T}f(\boldsymbol{ \theta}^{*}))\leq\kappa\;span(f_{0}(\boldsymbol{\theta}_{0}^{*})-f(\boldsymbol {\theta}^{*})). \tag{24}\] **Assumption 3**.: \(\|\boldsymbol{\theta}_{0}^{*}-\boldsymbol{\theta}^{*}\|\leq c_{0}\|span(f_{0 }(\boldsymbol{\theta}_{0}^{*})-f(\boldsymbol{\theta}^{*}))\|\), _with \(c_{0}\) being a positive constant._ **Lemma 6**.: _For \(M(\boldsymbol{\theta}_{k},\lambda_{k})\) in (15) and \(\hat{M}(\boldsymbol{\theta}_{k},\lambda_{k})\) in (16), with constants \(c_{1}\) and \(c_{0}\) (Assumption 3),_ \[M(\boldsymbol{\theta}_{k},\lambda_{k})\leq 2\hat{M}(\boldsymbol{\theta}_{k}, \lambda_{k})+\frac{2\eta_{k}c_{0}^{2}}{\alpha_{k}(1-\kappa)}\|span(\Pi_{ \mathcal{F}}f(\boldsymbol{\theta}^{*})-f(\boldsymbol{\theta}^{*}))\|+2 \mathcal{O}\Big{(}\frac{c_{1}^{3}(\|\boldsymbol{\theta}_{0}\|\!+\!|\lambda_{0} |\!+\!1)^{3}}{m^{1/2}}\Big{)}.\] ## 5 Numerical Experiments We numerically evaluate the performance of Neural-Q-Whittle using an example of circulant dynamics [23; 3; 8]. The state space is \(\mathcal{S}=\{1,2,3,4\}\). Rewards are \(r(1,a)=-1,r(2,a)=r(3,a)=0,\) and \(r(4,a)=1\) for \(a\in\{0,1\}\). The dynamics of states are circulant and defined as \[P^{1}=\begin{bmatrix}0.5&0.5&0&0\\ 0&0.5&0.5&0\\ 0&0&0.5&0.5\\ 0.5&0&0&0.5\end{bmatrix}\text{ and }P^{0}=\begin{bmatrix}0.5&0&0&0.5\\ 0.5&0.5&0&0\\ 0&0.5&0.5&0\\ 0&0&0.5&0.5\end{bmatrix}.\] This indicates that the process either remains in its current state or increments if it is active (i.e., \(a=1\)), or it either remains the current state or decrements if it is passive (i.e., \(a=0\)). The exact value of Whittle indices [23] are \(\lambda(1)=-0.5,\lambda(2)=0.5,\lambda(3)=1,\) and \(\lambda(4)=-1\). In our experiments, we set the learning rates as \(\alpha_{k}=0.5/(k+1)\) and \(\eta_{k}=0.1/(k+1)^{4/3}\). We use \(\epsilon\)-greedy for the exploration and exploitation tradeoff with \(\epsilon=0.5\). We consider a two-layer neural network with the number of neurons in the hidden layer as \(m=200\). As described in Algorithm 1, \(b_{r},\forall r\) are uniformly initialized in \(\{-1,1\}\) and \(w_{r},\forall r\) are initialized as a zero mean Gaussian distribution according to \(\mathcal{N}(\textbf{0},\textbf{I}_{d}/d)\). These results are carried out by Monte Carlo simulations with 100 independent trials. Figure 2: Convergence of Neural-Q-Whittle. **Convergence to true Whittle index.** First, we verify that Neural-Q-Whittle convergences to true Whittle indices, and compare to Q-Whittle, the first Whittle index based Q-learning algorithm. As illustrated in Figure 1(a), Neural-Q-Whittle guarantees the convergence to true Whittle indices and outperforms Q-Whittle [3] in the convergence speed. This is due to the fact that Neural-Q-Whittle updates the Whittle index of a specific state even when the current visited state is not that state. Second, we further compare with other White index learning algorithms, i.e., Q-Whittle-LFA [60], WIQL [8] and QWIC [23]in Figure 3. As we observe from Figure 3, only Neural-Q-Whittle and Q-Whittle-LFA in [60] can converge to the true Whittle indices for each state, while the other two benchmarks algorithms do not guarantee the convergence of true Whittle indices. Interestingly, the learning Whittle indices converge and maintain a correct relative order of magnitude, which is still be able to be used in real world problems [60]. Moreover, we observe that Neural-Q-Whittle achieves similar convergence performance as Q-Whittle-LFA in the considered example, whereas the latter has been shown to achieve good performance in real world applications in [60]. Though this work focuses on the theoretical convergence analysis of Q-learning based whittle index under the neural network function approximation, it might be promising to implement it in real-world applications to fully leverage the strong representation ability of neural network functions, which serves as future investigation of this work. **Convergence of the Lyapunov function defined in (15).** We also evaluate the convergence of the proposed Lyapunov function defined in (15), which is presented in Figure 1(b). It depicts \(\mathbb{E}[M(\mathbf{\theta}_{k},\lambda_{k})]\) vs. the number of iterations in logarithmic scale. For ease of presentation, we only take state \(s=4\) as an illustrative example. It is clear that \(M(\mathbf{\theta}_{k},\lambda_{k})\) converges to zero as the number of iterations increases, which is in alignment with our theoretical results in Theorem 1. **Verification of Assumption 3.** We now verify Assumption 3 that the gap between \(\mathbf{\theta}_{0}^{*}\) and \(\mathbf{\theta}^{*}\) can be bounded by the span of \(f_{0}(\mathbf{\theta}_{0}^{*})\) and \(f(\mathbf{\theta}^{*})\) with a constant \(c_{0}\). In Figure 4, we show \(c_{0}\) as a function of the number of neurons in the hidden layer \(m\). It clearly indicates that constant \(c_{0}\) exists and decreases as the number of neurons grows larger. ## 6 Conclusion We presented Neural-Q-Whittle, a Whittle index based Q-learning algorithm for RMAB with neural network function approximation. We proved that Neural-Q-Whittle achieves an \(\mathcal{O}(1/k^{2/3})\) convergence rate, where \(k\) is the number of iterations when data are generated from a Markov chain and Q-function is approximated by a ReLU neural network. By viewing Neural-Q-Whittle as 2TSA and leveraging the Lyapunov drift method, we removed the projection step on parameter update of Q-learning with neural network function approximation. Extending the current framework to two-timescale Q-learning (i.e., the coupled iterates between Q-function values and Whittle indices) with general deep neural network approximation is our future work. Figure 4: Verification of Assumption 3 w.r.t the constant \(c_{0}\). Figure 3: Convergence comparison between Neural-Q-Whittle and benchmark algorithms. ## Acknowledgements This work was supported in part by the National Science Foundation (NSF) grant RINGS-2148309, and was supported in part by funds from OUSD R&E, NIST, and industry partners as specified in the Resilient & Intelligent NextG Systems (RINGS) program. This work was also supported in part by the U.S. Army Research Office (ARO) grant W911NF-23-1-0072, and the U.S. Department of Energy (DOE) grant DE-EE0009341. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the funding agencies.
2303.03407
Identification of tidal features in deep optical galaxy images with Convolutional Neural Networks
Interactions between galaxies leave distinguishable imprints in the form of tidal features which hold important clues about their mass assembly. Unfortunately, these structures are difficult to detect because they are low surface brightness features so deep observations are needed. Upcoming surveys promise several orders of magnitude increase in depth and sky coverage, for which automated methods for tidal feature detection will become mandatory. We test the ability of a convolutional neural network to reproduce human visual classifications for tidal detections. We use as training $\sim$6000 simulated images classified by professional astronomers. The mock Hyper Suprime Cam Subaru (HSC) images include variations with redshift, projection angle and surface brightness ($\mu_{lim}$ =26-35 mag arcsec$^{-2}$). We obtain satisfactory results with accuracy, precision and recall values of Acc=0.84, P=0.72 and R=0.85, respectively, for the test sample. While the accuracy and precision values are roughly constant for all surface brightness, the recall (completeness) is significantly affected by image depth. The recovery rate shows strong dependence on the type of tidal features: we recover all the images showing shell features and 87% of the tidal streams; these fractions are below 75% for mergers, tidal tails and bridges. When applied to real HSC images, the performance of the model worsens significantly. We speculate that this is due to the lack of realism of the simulations and take it as a warning on applying deep learning models to different data domains without prior testing on the actual data.
H. Domínguez Sánchez, G. Martin, I. Damjanov, F. Buitrago, M. Huertas-Company, C. Bottrell, M. Bernardi, J. H. Knapen, J. Vega-Ferrero, R. Hausen, E. Kado-Fong, D. Población-Criado, H. Souchereau, O. K. Leste, B. Robertson, B. Sahelices, K. V. Johnston
2023-03-06T19:00:01Z
http://arxiv.org/abs/2303.03407v1
# Identification of tidal features in deep optical galaxy images with Convolutional Neural Networks ###### Abstract Interactions between galaxies leave distinguishable imprints in the form of tidal features which hold important clues about their mass assembly. Unfortunately, these structures are difficult to detect because they are low surface brightness features so deep observations are needed. Upcoming surveys promise several orders of magnitude increase in depth and sky coverage, for which automated methods for tidal feature detection will become mandatory. We test the ability of a convolutional neural network to reproduce human visual classifications for tidal detections. We use as training \(\sim\)6000 simulated images classified by professional astronomers. The mock Hyper Suprime Cam Subaru (HSC) images include variations with redshift, projection angle and surface brightness (\(\mu_{lim}\)=26 - 35 mag arcsec\({}^{-2}\)). We obtain satisfactory results with accuracy, precision and recall values of Acc=0.84, P=0.72 and R=0.85 for the test sample. While the accuracy and precision values are roughly constant for all surface brightness, the recall (completeness) is significantly affected by image depth. The recovery rate shows strong dependence on the type of tidal features: we recover all the images showing _shell_ features and 87% of the tidal _streams_; these fractions are below 75% for _mergers_, _tidal tails_ and _bridges_. When applied to real HSC images, the performance of the model worsens significantly. We speculate that this is due to the lack of realism of the simulations and take it as a warning on applying deep learning models to different data domains without prior testing on the actual data. keywords: galaxies: structure - methods: observational - surveys ## 1 Introduction In the standard \(\Lambda\)-Cold Dark Matter (\(\Lambda\)CDM) cosmology scenario, small scale overdense perturbations in the early Universe collapse first and produce dark matter haloes that accumulate baryons at the centre. The small structures aggregate successively into larger structures via mergers in a process known as hierarchical growth (White & Rees, 1978; Fall & Efstathiou, 1980; White & Frenk, 1991; Lacey & Cole, 1993). In addition, accretion processes of small satellite galaxies or gas in filaments produce a vast and complex network of ultra-low surface brightness streams which should be present around all galaxies (e.g., Pillepich et al., 2014 and references therein). Therefore, galaxy mergers have a fundamental and critical role within the \(\Lambda\)CDM cosmogony. While there is a general consensus that the merger fraction increases with galaxy stellar mass, both from simulations (e.g., Rodriguez-Gomez et al., 2016; Husko et al., 2022) and observations (van Dokkum et al., 2010; Lopez-Sanjuan et al., 2012; Rodriguez-Puebla et al., 2017), the relative contribution of in-situ star formation and accreted stellar mass remains an open question across much of the galaxy mass spectrum (e.g., Qu et al., 2017; Fitts et al., 2018; Conselice et al., 2022). The rate of major and minor merger events, and their impact on galaxy mass assembly and morphological transformations, are also under debate (e.g. Lotz et al., 2011; Lofthouse et al., 2017; Martin et al., 2017, 2018, 2021). Minor mergers (with baryonic mass ratios below 1:4) are expected to be significantly more common than major ones (e.g., Cole et al., 2000; Lotz et al., 2011), and to remain frequent even at the present epoch (although this is still under debate, see for example O'Leary et al., 2021). As minor mergers do not necessarily destroy pre-existing stellar disks (e.g., Robertson et al., 2006), signs of recent or ongoing minor mergers should be apparent around galaxies in the form of stellar tidal features, which extend into the halo of the central galaxy. Merger remnants which are only a few dynamical periods old should leave distinguishable imprints in the outskirts of galaxies. The frequency and characteristics of these features hold vital clues to the nature of the events which have created them (Hernquist & Quinn, 1989; Mihos et al., 1998; Helmi & White, 1999; Martinez-Delgado et al., 2009; Hendel & Johnston, 2015; Spavone et al., 2020; Montes et al., 2020; Vera-Casanova et al., 2022) and can thus be used to disentangle the different formation channels. Following Duc et al. (2015), _tails_ are expected to be pulled out material from a gas-rich disc galaxy, while _streams_ would be stripped material from a low-mass companion being consumed by the primary galaxy. Other features such as _fans_ and _plumes_ are expected to come from dry, major mergers. In addition, _clouds_ and _shells_ are expected to be the result of interactions with radial orbits, while _great circles_ are more predominant for circular orbits events (Johnston et al., 2008). Unfortunately, the majority of tidal features have very low surface brightness, expected to be fainter than 29 mag arcsec\({}^{-2}\) in the \(r\)-band (Bullock & Johnston, 2005; Cooper et al., 2013), and extremely deep observations are necessary to detect them, as shown explicitly in Conselice et al. (2000); Ji et al. (2014); Bottrell et al. (2019); Thorp et al. (2021) and Mancillas et al. (2019), where the authors find two and three times more streams based on a surface brightness cut of 33 mag arcsec\({}^{-2}\) than with 29 mag arcsec\({}^{-2}\). Although there is an increasing interest in the literature on the identification and characterization of tidal features, most works focus on the detailed analysis of a small number of objects via visual inspection (e.g., Martinez-Delgado et al., 2010; Javanmardi et al., 2016; Morales et al., 2018; Martinez-Delgado et al., 2021; Valenzuela & Remus, 2022; Huang & Fan, 2022; Sola et al., 2022), some of them belonging to local groups or clusters of galaxies (e.g., Iodice et al., 2017; Mihos et al., 2017; Spavone et al., 2018). A sample of 92 ETGs galaxies from ATLAS\({}^{\rm{3D}}\) was presented in Duc et al. (2015), reporting signs of interactions or perturbed morphologies in more than half of them, thanks to an observing strategy and data reduction pipeline optimized for low surface brightness features. Hood et al. (2018) present a visual identification of galaxies with tidal features based on DECam Legacy Survey images (\(r\)-band 3\(\sigma\) depth of \(\sim\)27.9 mag arcsec\({}^{-2}\)) but due to the small area inspected (100 arcsec\({}^{2}\)), less than 200 of them have tidal features detected with high confidence. One of the largest catalogues of tidal detections up to date was presented in Kado-Fong et al. (2018) using The Hyper Suprime-Cam Subaru Strategic Program (HSC-SSP, Miyazaki et al., 2012) data. The authors applied applied a filtering algorithm that iteratively separates low and high spatial frequency features of images, resulting in a sample of \(\sim\)1200 galaxies with tidal detections from a sample of \(\sim\)20,000. With the arrival of large imaging surveys such as Euclid (Laureijs et al., 2011) and the Vera Rubin Observatory's Legacy Survey of Space and Time (LSST, Ivezic et al., 2019), the detection of these features via visual inspection is unfeasible and automated methods become imperative. The use of supervised deep learning for the analysis of galaxy images, such as convolutional neural networks (CNN), has proven to be extremely successful for classifying galaxy images (e.g, Dieleman et al., 2015; Huertas-Company et al., 2015; Dominguez Sanchez et al., 2022; Cheng et al., 2020; Vega-Ferrero et al., 2021; Walmsley et al., 2022; Hausen & Robertson, 2020; Ghosh et al., 2020), including classifications of relatively rare objects such as strong lensed galaxies (Lanusse et al., 2018; Cheng et al., 2020) or post-mergers (e.g., Bickley et al., 2021). However, one of the main drawbacks of supervised learning approaches is the need for a large sample of labelled galaxies (of the order of thousands) to train and test the algorithm and its performance in different regimes (see Huertas-Company & Lanusse, 2022 for a review on the topic). An alternative is the use of simulations: the viability of using galaxies from hydrodynamical simulations to train deep learning models to classify real galaxies and mergers has indeed been shown in Bottrell et al. (2019) and Huertas-Company et al. (2019). The scarcity of a large number of galaxies showing tidal features to be used as training data has prevented to develop automated supervised detection algorithms and so far there have been almost no attempts in the literature to this respect. A pioneering effort to develop a CNN for tidal stream detection was presented in Walmsley et al. (2019), where the authors used imaging for the Canada-France-Hawaii Telescope Legacy Survey-Wide Survey (Gwyn, 2012). However, the models only achieved a 76 percent accuracy, probably due to the small size of the training sample (\(\sim\) 1700 galaxies, of which only 305 showed tidal stream detections). In this work, we use synthetic HSC images of galaxies generated by the Newhorizon cosmological simulations (Dubois et al., 2021) to examine the viability of using CNNs to identify galaxies with tidal features. The original sample, described in Section 2, includes \(\sim\) 6000 images at different surface brightness limits classified by professional astronomers. This is the largest catalogue of tidal features based on visual classification up to date. We describe our CNN and training strategy in Section 3 and test the ability of the CNNs to recover human-like classifications in Section 4, where we present the performance of the model as a function of the feature class (Section 4.1), redshift (Section 4.2) and image depth (Section 4.3). The outcome of applying the models to real data are discussed in Section 5, including an attempt of using the Kado-Fong et al. (2018) classification as a training sample. We summarise our results and discuss their implications in Section 6. ## 2 Data We take advantage of the galaxy images and labelling presented in Martin et al. (2022, hereafter M22). The galaxies are generated with NewHorizon, state-of-the-art cosmological hydrodynamical simulations (Dubois et al., 2021), a zoom-in of the parent Horizon-AGN simulation (Dubois et al., 2014). NewHorizon combines high stellar mass (1.3\(\times\)10\({}^{4}\) M\({}_{\odot}\)) and spatial resolution (\(\sim\) 34 pc) with a contiguous volume of (16 Mpc)\({}^{3}\). Given the diffuse nature of galaxy stellar haloes, the trade off between resolution and volume is an important consideration. The simulations adopt the cosmological parameters from Komatsu et al. (2011, \(\Omega_{\rm m}=0.272\), \(\Omega_{\rm\Delta}=0.728\), \(\Omega_{\rm b}=0.045\), \(H_{0}=70.4\) km s\({}^{-1}\) Mpc\({}^{-1}\)). We refer the reader to M22 for more technical details on the simulations. ### Mock galaxy images The parent sample consists of 36 unique galaxies, with masses above 10\({}^{9}\)-5M\({}_{\odot}\) at z=0.2, and their progenitors at z=0.4, 0.6 and 0.8. Realistic HSC-like mock images are generated by convolving the smoothed star-particle fluxes with the \(g\)-band HSC 1D PSF (Montes et al., 2021). Three projections of each snapshot (\(xy\), \(xz\), \(yz\)) are created at 5 different distances (corresponding at z=0.05, 0.1, 0.2, 0.4 and 0.8). The physical field of view is 100 kpc (proper) cropped from the initial 1 Mpc cube. Mock images are produced for each galaxy by extracting star particles centred around each galaxy. The spectral energy distribution (SED) for each star particle is then calculated from a grid of Bruzual & Charlot (2003) simple stellar population models assuming a Salpeter (1955) IMF. They account for dust attenuation of the SEDs using a screen model in front of each particle for which a gas-to-dust ratio of 0.4 Draine et al. (2007) and a Weingartner & Draine (2001) R = 3.1 Milky Way dust grain model are assumed. After redshifting each particle SED, the flux of each particle is calculated by convolving with the appropriate bandpass transmission function. Finally, random Gaussian noise is added to the simulated images to reach different limiting surface brightness \(\mu_{T}^{lim}\) corresponding to 28, 29, 30, 31 and 35 mag arcsec\({}^{-2}\) (3\(\sigma\), 10\({}^{\circ}\)\(\times\)10\({}^{\prime}\)). The combination of these parameters results in 10800 unique simulated images. Since the pixel angular size is fixed, the difference in distance of the galaxies directly translates into cutouts of different sizes (26\(\times\)26, 36\(\times\)36, 60\(\times\)60, 108\(\times\)108, 204\(\times\)204 pixels, from z=0.8 to z=0.05). In order to increase the sample size and to have mock images which resemble current observations better, we have generated 2\(\times\)1453 additional snapshots with \(\mu_{lim}\)= 26 and 27 mag arcsec\({}^{-2}\) by adding Gaussian noise following Equation 3 from M22 to the deepest available image of each particular counterpart (i.e., with the corresponding ID, snapshot, redshift and projection). ### Tidal feature classification M22 performed a visual inspection of \(\sim\) 8 0001 unique images by 45 expert classifiers, with a random subset of them classified six times, by identifying the presence of tidal features and classifying them into stellar _streams_, _tidal tails_, _shells_, _tidal bridges_, _merger remnants_, _double nuclei_ or _miscalene_.2 The classification was summarized in a catalogue including 5 835 unique images. The missing images were not included in the classification catalogue for being too noisy. We use this catalogue as parent sample in our work. The visually classified images were created at HSC pixel angular scale of 0.2", but rescaled to 1", comparable to the FWHM of the PSF used (an observer might reasonably rebin like this in order to gain additional depth without losing any detail). This rebinning will have a significant impact when applying the models trained with these images to real HSC-SSP data, as we discuss in Section 5. In this work, we use the exact same images as those visually classified to train the deep learning algorithm, so that the labels are consistent. Footnote 1: Note that this number is smaller than 10 800 quoted on Section 2.1 due to missing progenitors at some snapshots which are too small to be detected by the structure finder at higher redshift. Footnote 2: The _plume_ and _asymmetric_ categories described in M22 are combined into a single _miscalene_ category in the catalogue, since there was a large degree of overlap between the two. Figure 1 shows the result of the classification for a particular galaxy image observed at redshift z=0.05 with different limiting surface brightness. Each image is classified by a number of astronomers (N) which assign the number of observed features (N\({}_{f}\)) of each class to the image. This means that more than one class can be assigned to each image and that the classification can change with \(\mu_{lim}\), but also due to projection effects or spatial resolution (redshift). For this particular example, the deepest image (\(\mu_{lim}\)=35 mag arcsec\({}^{-2}\)) was classified by N=3 astronomers which annotated features of _streams_, _shells_, _tidal tails_, _merger_ and _bridges_ adding up to a total of N\({}_{f}\) =9. On the other hand, the shallower image (\(\mu_{lim}\)=28 mag arcsec\({}^{-2}\)) was classified by N=5 astronomers, of whom only one annotated the feature class of _merger_ (N\({}_{f}\)=1). To the best of our knowledge, this is the sample with the largest number of tidal detections visually classified by professional astronomers up to date, making it the optimal sample for training a deep learning algorithm for automated detection of tidal features. Figure 1: Example of the classification performed in M22. Images of the same galaxy observed at z=0.05 with different \(\mu_{lim}\)(28, 29, 30, 31, 35 mag arcsec\({}^{-2}\), form left to right) were classified by a varying number of astronomers (N) into different categories. The number of observed features of each class is reported in the cutouts (St=streams, Sh=shells, T=tails, M=mergers, B=bridges) along with the total number of features (N\({}_{f}\)) and F\({}_{\rm Tidal}\)=N\({}_{f}\)/N. In this work we consider as positive examples those images with F\({}_{\rm Tidal}\)\(>\) 1, negative those with F\({}_{\rm Tidal}\)=0 and uncertain otherwise. Following this criteria, the images with \(\mu_{lim}\)=28 and 29 have an uncertain classification, while those with \(\mu_{lim}\)> 29 are classified as showing tidal features. The cutouts are normalized in the (0,1) range using _arcsinh stretch_, as described in Section 3.1. However, the example from Figure 1 illustrates the challenges of the visual identification of tidal features: the definition of the different classes of features is not objective and there is discrepancy between the classifiers. In some cases, the same images are classified as showing tidal features by some classifiers and as featureless by others. This is a warning about the reliability of the visual classifications and how much they should be trusted as the ground truth. Although we are well aware of these caveats, we continue to use this dataset in our analysis as is the largest and most complete galaxy sample with tidal feature labels up to date. To simplify the problem, in this work we focus on the identification of the presence (or not) of a tidal feature, regardless of its category and, thus, we consider all the tidal feature classes simultaneously. Since the images were classified by a varying number of experts, ranging from one to six, and more than one tidal feature category could be assigned to each image, we divide the number of tidal feature identifications by the number of classifiers. We refer to this quantity as the _fraction of tidal detections_, F\({}_{\rm Tidal}\)=N\({}_{f}\)/N, and consider certain classifications those with F\({}_{\rm Tidal}\) = 0 or F\({}_{\rm Tidal}\)\(\geq\)1 (corresponding to 39% and 38% of the sample, respectively). For the images with 0 \(<\) F\({}_{\rm Tidal}\) < 1 (the remaining 22%) the classification of different experts were inconsistent and we refer to these cases as uncertain classifications. To avoid including uncertain classifications in the loop, we remove the images with 0 \(<\) F\({}_{\rm Tidal}\) < 1 from the train and test samples. After visual inspection of some images, we found that the classes _misc_ and _double nucleus_ do not fit exactly into the tidal features we are aiming to detect. Therefore, images classified _only_ as _misc_ or _double nucleus_ are also removed from the analysis. The distribution in mass, surface brightness limit and redshift of the parent sample and the images classified as showing tidal features are shown in Figure 2. The detection of tidal features by humans is largely dependent on the depth of the images and on the image size (or redshift of the galaxy), as reported by M22 and clearly seen in Figure 2. This has important consequences for the performance of the algorithm for automated detection of tidal features, as we discuss in Section 4. ## 3 Methodology We use supervised learning for the identification of galaxies showing tidal features; i.e., we need to provide the algorithm with the ground truth we would like to recover in the form of labels (in this case, tidal feature detection or not). We use CNNs, a class of artificial neural networks consisting of convolution kernels that slide along input features and provide feature maps. These maps are then passed through a fully connected network that outputs a value, corresponding to a particular property that we want to learn. The final function (or weights of the model) is the one that minimizes the difference between the output and the input labels. In this work, the input to the CNN are single-band images in the HSC \(r\)-band (we use the \(r\)-band images since these were the images classified by the professional astronomers in M22) with their corresponding labels (0s for non-tidal detections and 1s for tidal features). The output of the model, P\({}_{\rm Tidal}\), is the probability that the image shows a tidal feature. ### Image pre-processing Before being fed to the CNN, the galaxy images are normalized in the range (0,1) to avoid operating with very large numbers. For the normalization, the commonly used _asinh stretch_ function 3 (see Lupton et al., 2004) is used, combined with a sigma clipping of 3% of the faintest and the brightest pixels of each image. This pre-processing enhances the detection of low surface brightness features. The images are converted to the same size, 69\(\times\)69, (the input to the CNN is an array of fixed dimensions) by rebinning or interpolating the pixel flux, depending on the original image size. We tested input sizes of 100\(\times\)100 without obtaining significant changes in the results. Throughout the paper we use the 69\(\times\)69 stamps as reference. Footnote 3: [https://docs.astropy.org/en/stable/api/astropy.visualization.AsinhStretch.html](https://docs.astropy.org/en/stable/api/astropy.visualization.AsinhStretch.html) ### Input Labels We use a binary classification to separate images which show tidal features (positive samples, labelled as 1s) from images without tidal signatures (negatives, labelled as 0s). Therefore, we unify all classes Figure 2: Distribution of stellar mass (left), limiting surface brightness (middle) and redshift (right) of the images from the parent sample presented in M22. The grey empty histograms represent the full sample (5835 images), the red filled histograms show the images labelled as positive examples of tidal features (i.e., with F\({}_{\rm Tidal}\) > 1), and the brown empty histograms correspond to images with uncertain classifications ( 0 \(<\) F\({}_{\rm Tidal}\) < 1 or labelled as _misc/double nucleus_ only). Note the large dependence of the fraction of tidal feature identification by the astronomers with surface brightness limit and redshift (or, equivalently, cutout size). of tidal features into a single one (detections or non-detections). As explained ins Section 2.2, we use the quantity F\({}_{\text{Tidal}}\) to select positive and negative examples, and leave out of the analysis images with uncertain classifications. For the images generated specifically for this work at \(\mu_{lim}\)=26, 27 mag arcsec\({}^{-2}\), we do not have classifications by the professional astronomers as these images were not part of the original M22 sample. We choose to use the labels of their counterpart images (i.e., with the same galaxy ID, snapshot, redshift and projection) at \(\mu_{lim}\)=28 mag arcsec\({}^{-2}\) as their 'ground truth' label. This exercise allows us to test whether or not the algorithm can recover visually classified features in images with surface brightness limit 2 mag arcsec\({}^{-2}\) shallower than the images used for their visual classification. We randomly split the sample in 85% for training (resulting in 4 418 images, out of which 1 539 are tidal detections) and reserve 15% for testing (820, out of which 223 are tidals). ### CNN architecture The CNN architecture discussed in the main text, based on the one presented in Walmsley et al. (2019), is summarized in Table 1. It consists on three 2D convolution layers with 32, 48 and 64 filters with sizes 3, 3, and 2, respectively and 2\(\times\)2 _max-pooling_ windows. They are followed by a fully connected layer with 64 neurons, Rectified Linear Unit (ReLU) non-linear activation function and 0.5 dropout rate. A final single neuron outputs values converted to the (0,1) range by applying a sigmoid function. Binary-crossentropy is used as loss function and Adam as optimizer. The number of free parameters of this CNN is 288 817 (for input sizes 69\(\times\)69\(\times\)1). We have tested other CNN architectures, namely the one commonly used by the authors (e.g., Dominguez Sanchez et al., 2018 and Dominguez Sanchez et al., 2022), consisting on four 2D convolutional layers with 32, 64, 128 and 128 filters with sizes 6, 5, 2 and 3, 2\(\times\)2 _max-pooling_ and 0.25 dropout4, followed by a fully connected layer with 64 neurons and 0.25 dropout. The number of free parameters is 2 600 545, almost ten times larger than in the Walmsley et al. (2019) CNN. A variation of the Dominguez Sanchez et al. (2018) architecture, with filter sizes (3, 3, 2, 3) and adding a fully connected layer with 16 neurons before the final layer, has also been tested. In addition, conventional networks such as ResNet-18,-50,-101 (He et al., 2016) and EfficientNet-B0,-B1, -B4 and -B7 (Tan & Le, 2019) have been attempted. As the use of more complicated CNNs did not significantly improve the results, we have decided to use the Walmsley et al. (2019) architecture as a reference due to its simplicity with respect to other algorithms. Footnote 4: This is a slight modification with respect to the original configuration. We use an overall standard strategy for training. We train for 100 epochs with a batch size of 100 and a validation split of 0.2 (from the training sample). Data augmentations are performed while training, including vertical and horizontal flip, weight and height shifts (by 0.05%), zoom in and out (0.75-1.3) and rotations (0, 90, 180, 270 degrees). We train 10 independent models, randomly changing the initialization weights and the training and validation sets. During the training we observed no signs of over-fitting. The results presented in the following sections are based on the average of the output of the 10 models, which we refer to as P\({}_{\text{Tidal}}\). ## 4 Results In this section, we study the performance of our models when applied to the test dataset. We consider two different tests sets: the one containing only the original simulations and labels by professional astronomers (i.e., surface brightness \(\mu_{lim}\)\(\geq\) 28 mag arcsec\({}^{-2}\)) and the test set which includes the original and the simulated images at \(\mu_{lim}\)=26, 27 mag arcsec\({}^{-2}\). We will refer to the former as the _original_ test sample and to the latter as the _original_+_shallow_ test sample. We use standard metrics for studying the performance of the models: \[\text{Accuracy}=\frac{\text{TP}+\text{TN}}{\text{TP}+\text{TN}+\text{FP}+ \text{FN}}=\frac{\text{TP}+\text{TN}}{\text{Total}} \tag{1}\] \[\text{Precision}=\frac{\text{TP}}{\text{TP}+\text{FP}}=\frac{\text{TP}}{\text {P}_{\text{pred.}}} \tag{2}\] \[\text{Recall}=\frac{\text{TP}}{\text{TP}+\text{FN}}=\frac{\text{TP}}{\text {P}_{\text{input}}} \tag{3}\] \[\text{F1}=2\times\frac{\text{P}\times\text{R}}{\text{(P}+\text{R})} \tag{4}\] where TP, TN, FP and FN stand for true positives, true negatives, false positive and false negative, respectively, while P\({}_{\text{pred}}\) and P\({}_{\text{input}}\) are the total number of predicted and input positives, respectively. To separate the instances into positive and negative predictions, we use the _binary classification threshold probability_, P\({}_{\text{th}}\), which is the value that optimizes the true positive rate (TPR, i.e. the fraction of correctly identified tidal detections) and the false positive rate (FPR, i.e., the fraction of non tidals classified as tidal detections) simultaneously. The number of galaxies in each test sample and the fraction of positives (labelled as tidal detections in the input catalog), as well as the accuracy, precision, recall and F1 score of each sample is reported in Table 2. The accuracy is the fraction of correctly classified instances, the precision is the fraction of TP among the instances classified as positive (analogue to the purity), while the recall is the fraction of TP among the positive \begin{table} \begin{tabular}{l c c} \hline \hline **Layer Type** & **Output shape** & **Parameters** \\ \hline Input & (69, 69, 1) & 0 \\ \hline Conv2D & (69, 69, 32) & 320 \\ \hline MaxPooling2D & (34, 34, 32) & 0 \\ \hline Conv2D & (34, 34, 48) & 13 872 \\ \hline MaxPooling2D & (17, 17, 48) & 0 \\ \hline Conv2D & (17, 17, 64) & 12 352 \\ \hline MaxPooling2D & ( 8, 8, 64) & 0 \\ \hline Flatten & (4 096) & 0 \\ \hline Dense & (64) & 262 208 \\ \hline Dense & (1) & 65 \\ \hline Total number of parameters & & 288 817 \\ \hline \end{tabular} \end{table} Table 1: Architecture of the CNN used in the main text. input instances (analogue to the completeness). Finally, the F1 score is the harmonic mean of the two. Figure 3 shows the receiver operating characteristic curve (ROC) that represents TPR versus FPR as the discrimination threshold (P\({}_{\rm th}\)) is varied. An adequate classifier would maximize the TPR while keeping the FPR low. The area under the ROC curve (AUC) is above 0.9 in both cases (a perfect classifier would have AUC=1). We also show the confusion matrices for the two test samples using as probability threshold the optimal value for each sample to separate the predictions into positive and negative classes. As reported in table 2, the accuracy (Equation 1) for the _original_ and _original+shallow_ test samples is 0.84 and 0.85, while the precision (or purity, Equation 2) is 0.72 and 0.71, respectively. These values are surprisingly similar, taking into account the inclusion of \(\sim\) 300 images with \(\mu_{lim}\)**< 28 in the _original+shallow_ test sample for which the ground truth is assumed to be the labels at \(\mu_{lim}\) = 28, i.e., those reported for images two magnitude deeper than the actually classified images. The main difference is in the recall (or completeness, Equation 3), that drops from 0.85 for the _original_ test sample to and 0.75 for the _original+shallow_ test sample. \begin{table} \begin{tabular}{l c c c c c c c} \hline \hline Test sample & N\({}_{\rm test}\) & \% Positives & P\({}_{\rm th}\) & Accuracy & Precision & Recall & F1 \\ \hline Original & 532 & 33 & 0.32 & 0.84 & 0.72 & 0.85 & 0.78 \\ Original+shallow & 820 & 27 & 0.31 & 0.85 & 0.71 & 0.75 & 0.73 \\ \hline \hline \end{tabular} \end{table} Table 2: Number of galaxies in the _original_ and _original+shallow_ test samples, and the fraction of those labelled as tidal features, as well as the accuracy, precision, recall and F1 score obtained when selecting as positive predictions the images with model scores above their corresponding P\({}_{\rm th}\). Figure 3: _Upper panel_: ROC curve - True Positive Rate as a function of False Positive Rate - for the _original_ (circles, colored coded by P\({}_{\rm th}\)) and _original+shallow_ (orange line) test samples. The red star marks the optimal threshold for the _original_ sample. _Bottom panels_: Confusion Matrix for the _original_ (left) and _original+shallow_ test sample (right) obtained when selecting positive samples as those above the corresponding P\({}_{\rm th}\) of each sample. Input labels are shown in the y-axis, predictions in the \(x\)-axis. The number of objects is reported in each quadrant, color coded by the fraction of that particular true class (also shown in parenthesis). As expected, it is more difficult for the algorithm to recover tidal detections in shallower images. We discuss the surface brightness dependence of the classification in Section 4.3. Since the precision values are very similar for the two test samples but recall is smaller for the _original+shallow_ test sample, the F1 score (Equation 4) is also lower for the _original+shallow_ (F1=0.73) than for the _original_ sample (F1=0.78). ### Dependence on tidal feature class Now we study the ability of our CNN to detect different classes of tidal features. Figure 4 shows the output probability of our model, \(\mathrm{P_{tidal}}\) (larger values correspond to more confident detection of tidal features), divided in the classes provided in the M22 catalogue. Clearly, there are classes which are easier to identify than others. For example, all the _shells_ in the test sample are recovered, and the TPR for the _streams_ is 0.84, while for _mergers_ or _tidal tails_ is below 0.7. It is also evident from Figure 4 that the model performs worse for the _shallow_ sample: the \(\mathrm{P_{tidal}}\) values are lower for the positive cases of this sub-sample. We discuss in more detail the effect of the \(\mu_{lim}\) in section 4.3. Figure 5 shows representative examples of TP identifications of _shells_, _streams_ and _mergers_ at different surface brightness limits. The features are very evident for the deep images (right panels) and, in some cases, it is surprising that the model is able to identify the tidal features in the more noisy images (left panels). Besides, the cutouts are displayed at their original size, not binned to 69\(\times\)69, which is the input to the CNN. These examples show that _shells_ and _streams_ are easier to identify by eye than _mergers_. We note, however, that the number of _shells_ in the test sample is small (12) and that there are no _shells_ in the _shallow_ test sample. This is due to the fact that there are no visually identified _shells_ in images shallower than \(\mu_{lim}\)=28 mag arcsec\({}^{-2}\), from which the labels for the _shallow_ sample come from. In other words, the fact that we are recovering more _shells_ may be due to these structures being identified by eye only in the deeper images. We note again that the different classes reported in the M22 catalogue are not mutually exclusive (see also Figure 1), and therefore images identified as _shells_ can also fall into other categories (this happens indeed for 10 out of 12 _shells_ in the test sample). FN cases are shown in Figure 6 for _streams_ and _mergers_. As all the _shells_ in the test sample are correctly identified by our model, there are no FN for this category. Even for the deeper images (right panels) it is difficult to identify the tidal features, while the shallower images (left panels) are dominated by noise. Therefore, it is not surprising that the model fails in these cases. ### Dependence with redshift In this section, we report the performance of the model when the test sample is divided into different redshift bins, which is directly related to the original stamp size (the stamps are then resampled into 69\(\times\)69 because the input to the CNN has fixed dimensions, see details in Section 2 and 3.1). Figure 7 shows the ROC curves as a function of redshift. As expected, the larger AUC is obtained in the lower redshift bin (\(z\)=0.05). However, the dependence on redshift is not very strong and not even linear. For example, the AUC is larger for \(z\)=0.4 (AUC=0.81) than for \(z\)=0.2 (AUC=0.76), probably due Figure 4: _Upper panels:_ Output probability distribution of the model for tidal detection, \(\mathrm{P_{tidal}}\), for the test sample divided into non-tidal visual classifications (left panel, blue) and tidal visual classifications (right panel, red). Darker colors represent the _original_ sample, lighter colors the _shallow_ sample. _Lower panels:_\(\mathrm{P_{tidal}}\), for the test sample divided into different categories, as stated in the legend. The dashed line is \(\mathrm{P_{th}}=0.31\), the threshold used to define a instance as positive or negative. The true positive rate (TPR) of each category for the _original+shallow_ sample is reported in the corresponding panel. to the lower fraction of visual detections at higher redshifts, which increases the overall accuracy. This is evident for \(z\)=0.8 (shown as a dotted line), where there are no galaxies classified as tidal detections in the test sample, neither in the input labels nor by our model, and therefore the accuracy is 100%. ### Dependence with surface brightness Finally, we study the dependence of the model performance on the surface brightness of the images to be classified. Figure 8 shows the ROC curve for the different \(\mu_{lim}\) values. The lower AUC correspond to the shallower images (\(\mu\)=26, 27), as expected, and the best results are obtained for \(\mu\)=30 mag arcsec\({}^{-2}\). We show the ROC curve for \(\mu\)=35 mag arcsec\({}^{-2}\) as dotted line because all the images from the test sample are classified as tidal detections, both in the input catalogue and by the model (just the opposite of what happens at \(z\)=0.8). Surprisingly, the AUC at \(\mu\)=31 mag arcsec\({}^{-2}\) is lower (AUC=0.87) than at \(\mu\)=30 mag arcsec\({}^{-2}\) (AUC=0.93) and comparable to the values obtained at \(\mu\)=28 mag arcsec\({}^{-2}\). To shed more light on the classification efficiency, Figure 9 shows the confusion matrices (generated by setting P\({}_{\rm th}\)=0.31) for three surface brightness limits (\(\mu\)=26, 30, 31 mag arcsec\({}^{-2}\)). These confusion matrices highlight the fact that the large AUC for \(\mu\)=26 mag arcsec\({}^{-2}\) is mainly driven by the ability of the classifier to correctly identify images without tidal detections (98% accuracy Figure 5: TP examples of shells, streams and mergers, from top to bottom. The cutouts have been processed as described in Section 3.1, but are shown at their original sizes (i.e., they are not binned to 69\(\sigma\)69, which is the input to the CNN), and the \(x\) and \(y\) axes correspond to the number of pixels. The information shown in each cutout corresponds to the redshift, the surface brightness limit (increasing from left to right) and the output probability of the model, P\({}_{\rm thal}\). Figure 8: Same as figure 7 for images at different surface brightness, color coded according to the legend. Note that at \(\mu\)=35 mag arcsec\({}^{-2}\) all images show tidal features and are correctly classified as such by our model (we plot the ROC curve as the brown dotted line) Figure 6: Same as figure 5 but for FN examples of _streams_ and _mergers_ (top and bottom panels, respectively). Note that there are no false negative shells (see Figure 4). The features are hard to detect by eye, so it is not surprising that the model fails in these cases. Figure 7: ROC curves for galaxies at different redshifts, color coded as indicated by the legend. The gray dashed line shows the ROC curve for the full _original_ sample. Note that there are no positive cases at \(z\)=0.8, and the model correctly classifies all the images at this \(z\) as negatives; hence we represent the ROC curve as the dotted purple line. for the negative subsample), while it struggles to correctly classify the tidal detections (only 33% are recovered in this surface brightness range). On the other hand, at \(\mu\)=31 mag arcsec\({}^{-2}\) the contrary happens: the model is able to correctly identify 89% of the tidal detections, at the cost of miscalasifying 35% of the non-detections. At \(\mu\)=30 mag arcsec\({}^{-2}\) the model is able to correctly identify 90% of the tidal detections while keeping the contamination (i.e., the number of FP) at 26%. While this trend could be expected, and is in line with the larger fraction of tidal detections obtained in deeper images by visual inspection (see Figure 2), it could be an indication that our model has, at least to some extent, learned the signal-to-noise of the images: it tends to classify deeper images more frequently as tidal detections. To test this assumption, Figure 10 shows the accuracy, precision and recall for each surface brightness bin, as well as the fraction of positive samples (tidal detections) in the input catalogue. As reflected by the confusion matrices, the recall (completness) of the model is highly dependent on the depth of the images to be classified, going from around R \(\sim\) 0.40 at \(\mu\)=26 mag arcsec\({}^{-2}\) to R \(\sim~{}0.90\) at \(\mu\)=31 mag arcsec\({}^{-2}\). However, this is not as clearly reflected in the precision (purity) values, roughly constant and above P \(\sim\) 0.60 at all surface brightness. In the same way, the accuracy is stable throughout the whole magnitude range (\(\sim\)80%), indicating that the model has not simply learned the signal-to-noise of the images. The fact that the accuracy does not improve with \(\mu_{lim}\), even if the recall (completness) does, can be explained by a larger fraction of FP. However, the increase in FP does not decrease the precision (purity) because of the larger fraction of tidal detections in the input catalogue at higher \(\mu_{lim}\)(black symbols in Figure 10), which together with the larger recall, increase the number of TP to counterbalance the larger number of FP. We would like to highlight here again that the labels used for the _shallow_ sample (\(\mu_{lim}\)\(\sim\)28 mag arcsec\({}^{-2}\)) correspond to the visual classification of the images with \(\mu\)=28 mag arcsec\({}^{-2}\), which explains the drop in completeness in this surface brightness regime. Indeed, it is remarkable that our model is able to recover 40% of the images with tidal detections, even when the images are 2 orders of magnitude shallower that the ones used for labelling. This is in agreement with recent results suggesting that CNNs trained with 'intrinsic' ground truth can recover astronomical features hidden to the human eye (see e.g., Vega-Ferrero et al., 2021). This result could have a large impact on the design strategy of future surveys. We emphasize that redshift and surface brightness limits are intertwined in the current analysis. Unfortunately, the test sample size is too small to examine the trends at each \(\mu_{lim}\)limit separately, at fixed redshift (or viceversa). ## 5 Application to real HSC-SSP data Our models are trained in HSC-like mock images. Therefore, it is important to test the performance of the algorithm in real data with similar characteristics to the training dataset. We thus use images from the HSC-SSP survey (Hyper Suprime-Cam Subaru Strategic Survey) Wide layer Aihara et al. 2018,b. The HSC Wide layer covers the largest on-sky area at a relatively shallow depth (\(i\sim\)26) relative to the Deep and UltraDeep Layers (\(i\sim\)27 and \(i\sim\)28, respectively). In particular, we have applied our models to the HSC-SSP images presented in Kado-Fong et al. (2018). These are \(\sim\)21,000 galaxies from the internal data release 516A, with spectroscopic redshifts from SDSS at \(0.05<z<0.45\). Kado-Fong et al. (2018) used a filtering algorithm to identify tidal features, combined with visual classification of the features detected by such filtering, resulting in a sample of \(\sim\)1,200 tidal feature detections. Our first approach to this work was to use the labels from Kado-Fong et al. (2018) sample to train the algorithm for tidal stream identification, but after exhaustive testing, the results were not good enough (F1=0.37), mostly due to the small completeness achieved by the models (R=0.26). As previously explored in the context of tidal feature classification of mock images (Section 2.2), one source of significant label noise is the reliability of visual inspection itself. Visual inspection of the full sample by three professional astronomers (I.D., H.S., Figure 9: Confusion matrices for three different surface brightness bins: \(\mu_{lim}\)=26, 30, 31 mag arcsec\({}^{-2}\), from top to bottom. The number of objects is reported in each quadrant, color coded by the fraction of that particular true class (also shown in parenthesis). O.K.L.) provided a new classification, which revealed that only 1/4 of the galaxies showing tidal features according to the filtering algorithm were classified as such by all visual classifiers. We believe that the combination of noisy labels, small positive training sample and low surface brightness features to be detected limited the performance of the algorithm. This was the main reason why we decided to use the HSC-like mock images for training the CNN. We note that the original classification by Kado-Fong et al. (2018) used both the images and the output of the filtering algorithm in order to detect features close to the host galaxy, so it is expected that the re-classification of the images alone would yield a lower tidal feature detection rate. On the other hand, as the original Kado-Fong et al. (2018) sample focused on the comparison of the properties of stream and shell hosts, the visual inspection was performed only for the images where a tidal detection was identified by their filtering algorithm, meaning that the completeness of the sample is uncertain. It is well known that deep learning models are sensitive to the characteristics of the training sample and that thus techniques such as transfer learning (e.g., Dominguez Sanchez et al. 2019) should be used for optimizing models trained on different datasets than the target sample. We attempted, without success, to use transfer learning to fine tune the models on real HSC-data, making exhaustive tests on the number of layers to be trained, the learning rate, etc. The best result we obtained is AUC=0.64, and the output values are concentrated towards the lower end (\(\rm{P_{Tidal}}<0.7\) ). These poor results emphasize the strong dependence of the model performance on the data they are trained with and warns us against carelessly applying models to different data domains. It also suggest that mock images from simulations are not as realistic as we might have expected. A possible explanation for the bad performance could be the differences in the way the mock images were created compared to real HSC data. For example, the angular resolution of the HSC-mock images is poorer (1" vs 0."167 for real HSC-SSP). In addition, the simulated images do not include real backgrounds, processing artifacts, contaminating sources, or sky subtraction residuals. This may compromise the model's ability to assess real data, as already discussed in Bottrell et al. (2019). The morphological classification of TNG simulated images presented in Huertas-Company et al. (2019) was significantly improved by adding realism to the simulated images. Unfortunately, adding realism to the images could change the visual classification used as 'ground truth' some features could become undetectable in the presence of brighter objects. Therefore, training the CNN with more realistic mock images and new labels is beyond the scope of the current analysis. We will investigate these possible improvements in the forthcoming studies. The reason why transfer learning might not solve the domain shift could be the fact that the \(\mu_{lim}\)in the simulated images is not fixed. This implies that the model needs to transfer from many sparsely sampled domains to another, instead of transferring from one well-sampled domain to another. Intuitively, the former may be harder. Another aspect which could have a significant effect is the small parent sample of galaxies used to produce the simulations, based on 36 galaxies only that may not represent the diversity of real galaxy populations. Since the observed sample is flux limited and the simulated sample is volume limited, the former should have a flatter mass distribution with more massive galaxies. Also, the real data have continuous redshift distribution, while the mock images are simulated in five redshift bins. All these differences combine together and it is not possible to investigate each aspect separately with the current sample. Thus, we cannot pinpoint the property that is the main cause of the poor model performance across domains. ## 6 Summary and conclusive remarks Tidal interactions are expected to play a critical role in galaxy mass assembly and evolution, but their low surface brightness make these features difficult to detect. Automated methods for the identification and classifications of tidal features will be compulsory for the analysis of large upcoming surveys such as LSST or Euclid. In this work, we take advantage of the catalogue presented in M22, that provides tidal feature classifications by professional astronomers for a sample of \(\sim\)6000 galaxy images from the Newhorizon simulations. This constitutes the largest catalogue of visual identifications of tidal features up to date. The galaxies are simulated at different evolutionary times and redshifts and HSC-like mock images with different surface brightness limits (\(\mu_{lim}\)=28-35 mag arcsec\({}^{-2}\)) were visually inspected by a varying number of professional astronomers (ranging from 2 to 6). We use a CNN to train a supervised deep learning binary model which aims to reproduce human visual identification of galaxies with tidal features. For this, we have labelled as positives all the images for which a tidal feature was identified by all the classifiers, regardless of the tidal feature category (\(\rm{F_{tidal}}>1\), as detailed in Section 3.2) and as negative those with no tidal identification (\(\rm{F_{tidal}}\) = 0). We do not use galaxies for which the presence of a tidal feature was uncertain (disagreement between classifiers). In addition to the original sample, we have created shallower images, more similar to current available observations, at \(\mu_{lim}\)=26, 27 mag arcsec\({}^{-2}\). These images were not classified in M22 and we use their corresponding labels at \(\mu_{lim}\)=28 mag arcsec\({}^{-2}\) as ground truth. We remark the fact that, since the visual classifications are used as input label to the model, any bias present in human classification would be passed on to the deep learning algorithm (see, for example, how the fraction of tidal detections depends on the image properties in Figure 2). Our main conclusions are: * The deep learning model is successful in reproducing the human identification of images with tidal features in the HSC-mock images, reaching accuracy, precision and recall values of Acc=0.84, P=0.72 Figure 10: Accuracy (blue), precision (red) and recall (green) obtained for the test sample as a function of the images’ surface brightness \(\mu_{lim}\). The fraction of tidal detections in the input catalogue is shown in black. The bins at \(\mu_{lim}\)=26, 27 mag arcsec\({}^{-2}\) are plotted as empty circles to highlight the fact that they are not part of the original sample from M22; the labels used for training and testing are the ones for their corresponding images at \(\mu\)=28 mag arcsec\({}^{-2}\). and R=0.85 for the original test sample, using the optimal threshold, P\({}_{\rm th}\)=0.31, to select positive cases of tidals. * The results are surprisingly similar in terms of global accuracy and purity (Acc=0.85, P=0.71) when the shallower test sample is included, even though these numbers are computed corresponding to the labeling of images one or two orders of magnitude deeper. * The completeness of the model for the _original+shallow_ test sample is smaller than for the _original_ one (R=0.75 vs R=0.85). There is indeed a clear dependence of the ability of the model to recover tidal features with respect to the image depth: while for \(\mu_{lim}\)\(>\) 30 mag arcsec\({}^{-2}\) around 90% of the tidal features are recovered, this quantity drops below 50% for \(\mu_{lim}\)< 28 mag arcsec\({}^{-2}\) (see Figures 9, 10). * The accuracy and purity are roughly constant at all surface brightness, hence we conclude that the model is not learning the signal-to-noise of the images, although it is evident that it impacts the classification performance, mostly in terms of completeness, as expected. * The trend with redshift is not so evident, with the larger AUC values obtained at redshift bins \(z\)=0.05 and \(z\)=0.4. The decrease of the fraction of visually identified tidal features at higher redshifts may explain this non-intuitive result (the model is able to correctly recover the true negatives). * Tidal _streams_ and _shells_ are the categories easier to identify by the model, with TPR=1 and TPR=0.87, respectively. On the other hand, _mergers_ and _tails_ reach only TPR=0.68, 0.69, respectively. * When applied to real HSC images with \(\mu_{lim}\)=26 mag arcsec\({}^{-2}\), the performance is significantly worse than on the simulated images (AUC=0.69), even when transfer learning is applied. This is probably related to the fact that the simulated images are not extremely realistic: they have lower spatial resolution than real images and do not include background effects. Besides, they span over a wide \(\mu_{lim}\) range, do not have a uniform redshift coverage and may not include examples of all observed morphological types and/or features. The results presented in this work represent an important step in the development of automated tidal feature detection techniques, even if the performance is lower than those found in other astronomical classification tasks like separating elliptical from disk galaxies (reaching accuracy above 97%). Tidal feature detection is a difficult task, given the low surface brightness of the subtle structures that we wish to detect. An additional limitation is the lack of a large, homogeneously observed training sample with certain classifications. One alternative would be to use 'intrinsic' labels from simulations, derived from dynamics or merger trees. The disadvantage of such labeling is that observational limitations may not always support the classification of an image in accordance with its intrinsic class. In this work, the training data is assembled from human labels. Labelling tidal features via visual inspection is not trivial and the image pre-processing has a significant impact. In addition, classifiers tend to disagree with each other quite often, as shown in M22. Biases in the identification of interacting galaxies by visual classifications have also been reported in Blumenthal et al. (2020). Therefore, it may not even be possible to achieve an accuracy similar to elliptical/spiral separation due to the much greater ambiguity of the classifications. We are aware of some important efforts of the scientific community towards building large and robust samples of tidal identifications, such as the detailed annotations presented in Sola et al. (2022); Bliek et al. (2020) or the on-going tidal stream survey by Martinez-Delgado et al. (2021), which will certainly help to construct a robust training sample to improve the algorithms for automated detection. Approaches such as domain adaptation (Ciprijanovic et al., 2022), the use of unsupervised learning (e.g., Sarriento et al., 2021; Cheng et al., 2021) or one-shot learning (Chen et al., 2019) could help to overcome the lack of positive training samples currently available, but we leave these approaches for the forthcoming analysis. The poorer performance of our tidal identification model in the real HSC-SSP images emphasizes the large dependence of deep learning algorithms on the data they are trained with. As already noted in Bottrell et al. (2019); Huertas-Company et al. (2019); Ciprijanovic et al. (2022), the importance of using realistic simulations for training the models, including background, real noise and artifacts, is fundamental to achieving robust results with real data. This should be taken as a warning against applying deep learning models to different data domains without previously assessing their performance on the new domain. Our results also highlight the need for deep surveys in order to construct complete samples of galaxies showing tidal interactions. Our predictions imply that we need images with \(\mu_{lim}\)\(>\) 30 mag arcsec\({}^{-2}\) to achieve completeness above 60%, although given the non-representative sample used for the statistical analysis presented in this work our current result is only suggestive of this requirement. For example, as already noted in Bottrell et al. (2019) and Bickley et al. (2021), for rare objects amongst large datasets (such as the upcoming LSST) the precision, largely dependent on the assumed fraction of positive instances, is paramount. One could increase the completeness by using larger value of P\({}_{\rm th}\), even if that would decrease the purity, and complement it with visual inspection of a much smaller sample of galaxies. The challenges facing the automated detection of tidal features should not prevent us from that endeavour. The scientific return of large samples of galaxies showing tidal features is huge. The detection and characterization of these faint tidal remnants - including measurements of their abundance, width, and shapes/morphology - probe the recent merger activity, disruption mechanisms and galaxy mass assembly. Furthermore, the characteristics of observed tidal features can constrain the global properties of the stellar and dark matter haloes (Johnston et al., 1999; Sanderson et al., 2015; Bovy et al., 2016; Pearson et al., 2022) and, consequently, are a complementary way to testing cosmological and dark matter theories. These are, indeed, some of the scientific objectives of the recently approved F-ESA mission ARRAKIIS5 (PI. R Guzman), that will image 50 deg\({}^{2}\) of the sky per year down to an unprecedented ultra-low surface brightness in visible infrared bands (31 and 30 mag arcsec\({}^{-2}\), respectively). The future of scientific analysis based on tidal features is bright and promising and this work undoubtedly represents an important step forward towards understanding the requirements of an optimal automated identification of such powerful ingredient for galaxy evolution and cosmological studies. Footnote 5: [https://www.cosmos.esa.int/documents/7423467/7423486/ESA-F2-ARRAKIIS-Phase-2-PUBLIC-v0.9.2.pdf/61b363d7-2a06-1196-5c40-c85au90c2113r=1667557422996](https://www.cosmos.esa.int/documents/7423467/7423486/ESA-F2-ARRAKIIS-Phase-2-PUBLIC-v0.9.2.pdf/61b363d7-2a06-1196-5c40-c85au90c2113r=1667557422996) ## Acknowledgements We thank the anonymous referee for their suggestions, which helped to improve the clarity of the paper. HDS acknowledges support by the PID2020-115098RJ-100 grant from
2301.01327
Operator theory, kernels, and Feedforward Neural Networks
In this paper we show how specific families of positive definite kernels serve as powerful tools in analyses of iteration algorithms for multiple layer feedforward Neural Network models. Our focus is on particular kernels that adapt well to learning algorithms for data-sets/features which display intrinsic self-similarities at feedforward iterations of scaling.
Palle E. T. Jorgensen, Myung-Sin Song, James Tian
2023-01-03T19:30:31Z
http://arxiv.org/abs/2301.01327v2
# Operator theory, kernels, and feedforward neural networks ###### Abstract. In this paper we show how specific families of positive definite kernels serve as powerful tools in analyses of iteration algorithms for multiple layer feedforward Neural Network models. Our focus is on particular kernels that adapt well to learning algorithms for data-sets/features which display intrinsic self-similarities at feedforward iterations of scaling. Key words and phrases:algorithms, multipliers, spectral resolutions, normal operators, iterated function systems, fractal measures, feedforward neural network, explicit kernels, ReLU, reproducing kernel Hilbert spaces, positive definite kernels, composition operators 2 believe that this then yields a more direct tool for kernel-based feedforward NN models. This advantage of our approach is based on two facts. First, we identify a direct notion of kernel iteration which accounts for traditional function theoretic feedforward NN steps. Secondly, our approach offers a more direct and natural choices of kernels which govern approximations involved in deep NN models, for example graph NN constructions. While positive definite kernels and their associated reproducing kernel Hilbert spaces have found diverse applications in pure and applied mathematics, we shall focus here on a new role of kernels in feedforward network models. In more detail, the main purpose of our paper is a presentation of choices of particular families of positive definite kernels which serve as powerful tools in analyses of multiple layer feedforward Neural Networks. In general, reproducing kernel constructions, and the corresponding RKHSs are powerful tools in diverse applications. In the present framework of kernel neural networks (KNNs), their role may be summarized as follows: Starting with the problem at hand, when we build our RKHS(\(\mu\)) via IFS iterations (e.g., via Cantor-like fractal limits), then the Cantor-like \(\mu\) activation functions arise as relative reproducing dipole functions for RKHS(\(\mu\)) as in Figure 3.1 below. ## 2. Neural networks (NN), and reproducing kernel Hilbert spaces (RKHS) A main theme in our paper is a development of new tools for design of feedforward Neural Network constructs. For this purpose we point out the use of positive definite kernels, and associated generating function for the NN algorithms. These kernel based functions include the more familiar ReLu functions, see Theorems 3.3 and 3.4 below. We stress that the particular RKHS constructs will be relative in the sense of Theorems 3.3 and 3.4, i.e., the inner product reproduces differences of function values. Our approach to the use of kernels and functions for feedforward Neural Network (NN) algorithms, is based on a systematic study of two classes of operators. They act as follows: (i) between prescribed kernel Hilbert spaces, and (ii) other operators acting at indexed levels in the network, i.e., operators acting at fixed levels, so within choices of kernel Hilbert spaces. Case (i) includes a systematic study of composition operators (see Corollaries 2.7 and 2.9) in the context of kernel Hilbert spaces; and case (ii), the study of multiplier operators and their adjoints, see e.g., Theorem 2.15. We emphasize that the two classes of operations discussed below depend on choices of kernels at each level in particular NN-network models. Together these families of operators allow for realizations of black box filter-entries in associated generalized multi-resolutions systems, including operators which consist of composition followed by multiplication. Specific 3D applications are presented in the subsequent sections, secs 3 and 4. **Conventions.** Inside the paper we shall work with Hilbert spaces of functions, e.g., reproducing kernel Hilbert spaces (RKHSs), \(L^{2}\) spaces, and Sobolev spaces. It will be assumed that these are Hilbert spaces of real valued functions. Inner products will be written \(\langle\cdot,\cdot\rangle\), and we shall use subscripts on \(\langle\cdot,\cdot\rangle\) to indicate the Hilbert space under consideration. Moreover, in our use of differentiation, or differential operators, we shall mean weak derivatives, i.e., differentiation in the sense of distributions, or making use of the natural duality for the spaces under consideration. Our restriction here to the real valued case is dictated by our present applications to feedforward Neural Networks. However, many of our general results in Section 2 below extend to complex RKHS theory. The latter in turn are important in the study of geometry and potential theory of complex domains, see e.g., [1]. The power of kernel machines derives in part from the following facts. First, kernel machines serve to map points in a low-dimensional data sets (typically non-linear) into higher dimensions. The dimensionality of this linear "hyperspace" may be infinite but is designed for optimization and efficient encoding of features. Hence the kernel method allows one to find coefficients of separating hyperplanes for the problem at hand via RKHS-inner products, one selected for each pair of high-dimensional features. While kernel machines of various types have been used for decades, it was with the invention of support vector machines (SVMs) that kernels have now taken center stage (see e.g., [1, 14, 15, 16, 17, 18]). By now, SVMs are used in diverse applications, including in bioinformatics (for finding similarities between different protein sequences), machine vision, and handwriting recognition. Deep neural networks (to be discussed in Sections 3 and 4 below) are made of layers of artificial neurons: input layer, an output layer, and multiple hidden layers in-between them. Deeper the networks have more hidden layers. The parameters of the network represent the strengths of the connections between layers. Training a network yield determination of values of parameters. Once trained, the ANN represents a model for turning an input (say, an image) into an output (a label or category). The variety of uses of forward Neural Network algorithms, the recent literature is substantial and diverse, especially with regards to applications. See e.g., [1, 1, 2, 10, 11]. The following lemma is a basic result in the theory of RKHSs. For details, see e.g., [11, 12, 13, 14, 15], and also [16] and the papers cited therein. **Lemma 2.1**.: _Fix a p.d. kernel \(X\times X\xrightarrow{K}\mathbb{R}\left(\text{or }\mathbb{C}\right)\), let \(\mathscr{H}_{K}\) denote the corresponding RKHS. Then a function \(F\) on \(X\) is in \(\mathscr{H}_{K}\) if and only if there exists a constant \(C_{F}<\infty\), such that the following estimate holds for all \(n\in\mathbb{N}\), all \(\left(\xi_{i}\right)_{i=1}^{n}\), \(\xi_{i}\in\mathbb{R}\left(\text{or }\mathbb{C}\right)\), and all \(\left(x_{i}\right)_{i=1}^{n}\), \(x_{i}\in X\):_ \[\left|\sum_{i=1}^{n}\xi_{i}F\left(x_{i}\right)\right|^{2}\leq C_{F}\sum_{i=1}^ {n}\sum_{j=1}^{n}\overline{\xi}_{i}\xi_{j}K\left(x_{i},x_{j}\right). \tag{2.1}\] _Remark 2.2_.: With the construction \(K\mapsto\mathscr{H}_{K}\) (referring to a RKHS of a fixed p.d. kernel \(K\)), we arrive at the following two conclusions: 1. For all \(x\in X\), the function \(K_{x}:=K\left(\cdot,x\right)\) is in \(\mathscr{H}_{K}\); and 2. For all \(F\in\mathscr{H}_{K}\), and \(x\in X\), we have \[F\left(x\right)=\left\langle F,K\left(\cdot,x\right)\right\rangle_{\mathscr{H} _{K}},\] (2.2) i.e., the values of functions \(F\) in \(\mathscr{H}_{K}\) are _reproduced_ via the inner product \(\left\langle\cdot,\cdot\right\rangle_{\mathscr{H}_{K}}\), and the kernel functions. In addition to (2.2), we shall also consider _relative reproducing kernels_, and _relative_ RKHSs. As noted in [1], the _relative_ reproducing property takes the following form \[F\left(y\right)-F\left(x\right)=\left\langle F,v_{x,y}\left(\cdot\right) \right\rangle_{\mathscr{H}_{\text{rel}}}, \tag{2.3}\] now valid for all pairs of points \(x,y\in X\). So this entails double-indexed kernel functions \(v_{x,y}\in\mathscr{H}_{rel}\). A particular class of \(\mathscr{H}_{rel}\) spaces are considered in Theorem 3.4 below. There the setting is \(X=\mathbb{R}\), and the relative kernel functions \(v_{a,b}\) take the form of activation functions for classes of feedforward-NN-algorithms, see e.g., Figure 3.1. A systematic study of (2.3) is undertaken in [1] where it is shown that the setting of relative reproducing is characterized by _conditionally negative definite functions_. We now recall the RKHS for the standard \(1\)-dimensional Brownian motion. (See e.g., [11, 12, 13, 14].) **Lemma 2.3**.: _When \(K\) is the Brownian motion kernel on \(\mathbb{R}_{\geq}\times\mathbb{R}_{\geq}\), i.e.,_ \[K\left(x,y\right)=x\wedge y=\frac{\left|x\right|+\left|y\right|-\left|x-y \right|}{2},\quad x,y\in\mathbb{R}_{\geq}, \tag{2.4}\] _the corresponding RKHS \(\mathscr{H}_{K}\) is the Hilbert space of absolutely continuous functions \(f\) on \(\mathbb{R}\) such that the derivative \(f^{\prime}=df/dx\) is in \(L^{2}\left(\mathbb{R}\right)\), and \(f\left(0\right)=0\). Moreover,_ \[\left\|f\right\|_{\mathscr{H}_{K}}^{2}=\int_{\mathbb{R}_{\geq}}\left|f^{ \prime}\left(x\right)\right|^{2}dx,\quad\text{for all }f\in\mathscr{H}_{K}. \tag{2.5}\] Proof.: The key observation is that, if \(x>0\), the function \[\mathbb{R}_{\geq}\ni y\longmapsto F_{x}\left(y\right):=K\left(y,x\right)= \begin{cases}y&\text{if }y\leq x\\ x&\text{if }y>x\end{cases} \tag{2.6}\] has weak derivative. Indeed, we have \[\frac{dF_{x}}{dy}=\chi_{\left[0,x\right]}, \tag{2.7}\] i.e., the indicator function of the interval \(\left[0,x\right]\). Hence if \(f\) is a function with \(f^{\prime}\in L^{2}\left(\mathbb{R}\right)\) and \(f\left(0\right)=0\), then \[f\left(x\right)=f\left(x\right)-f\left(0\right)=\int_{0}^{x}f^{\prime}\left( y\right)dy=\int_{\mathbb{R}}F_{x}^{\prime}\left(y\right)f^{\prime}\left(y \right)dy, \tag{2.8}\] and the RHS in (2.8) is the inner product from the Hilbert space defined by the RHS in (2.5). The corresponding implication follows from the general theory of RKHS. Recall that the RKHS of a kernel is a Hilbert space completion of the functions \[y\longmapsto K\left(x,y\right) \tag{2.9}\] as \(x\) varies over \(\mathbb{R}\). Moreover, for \(K\left(x,y\right)=x\wedge y\), \[\left\langle K\left(\cdot,x_{1}\right),K\left(\cdot,x_{2}\right)\right\rangle _{\mathscr{H}_{K}}=K\left(x_{1},x_{2}\right)=x_{1}\wedge x_{2},\] and we can compute as follows: \[\int_{\mathbb{R}}\left(\frac{d}{dy}K\left(\cdot,x_{1}\right) \right)\left(\frac{d}{dy}K\left(\cdot,x_{2}\right)\right)dy =\int_{\mathbb{R}}\chi_{\left[0,x_{1}\right]}\left(y\right)\chi_ {\left[0,x_{2}\right]}\left(y\right)dy\] \[=\lambda\left(\left[0,x_{1}\right]\cap\left[0,x_{2}\right]\right)\] \[=x_{1}\wedge x_{2}=K\left(x_{1},x_{2}\right)\] where \(\lambda=dy\) denotes the Lebesgue measure. _Remark 2.4_.: Note that the functions \(v_{a,b}\) (called dipoles) in \(\mathscr{H}_{K}\) which satisfy \[f\left(b\right)-f\left(a\right)=\left\langle f,v_{a,b}\right\rangle,\quad\text{ for all }f\in\mathscr{H}_{K}\] (see (2.5) and (2.8)) are as follows: \[v_{a,b}\left(x\right)=\begin{cases}0&\text{if }x<a\\ x-a&\text{if }a\leq x<b\\ b-a&\text{if }x>b,\end{cases}\] as illustrated in Figure 2.1. Also compare with Theorem 3.4 and Figure 3.1, and the iterations in Section 4. **Induced metrics** For a general p.d. kernel \(K\) on \(X\times X\), there is an induced metric on \(X\), \[d_{K}:X\times X\to\mathbb{R}_{+}\] defined as (see e.g., [1]) \[d_{K}\left(x,y\right)=\left\|K\left(\cdot,x\right)-K\left(\cdot,y\right)\right\| _{\mathscr{H}_{K}}^{2}. \tag{2.10}\] In particular, \[d_{K}\left(x,y\right)=K\left(x,x\right)+K\left(y,y\right)-2\Re\left\{K\left(x,y\right)\right\}.\] Note that \(d_{K}^{1/2}\) is also a metric on \(X\times X\). **Example 2.5**.: For \(K\left(x,y\right)=x\wedge y\) on \(\mathbb{R}\times\mathbb{R}\) as in (2.4), \[\left\|K\left(\cdot,s\right)-K\left(\cdot,t\right)\right\|_{ \mathscr{H}_{K}}^{2} =\left\|\left(\cdot\wedge s\right)^{\prime}-\left(\cdot\wedge t \right)^{\prime}\right\|_{L^{2}}^{2}\] \[=\left\|\chi_{[0,s]}-\chi_{[0,t]}\right\|_{L^{2}}^{2}\] \[=\left|s-t\right|.\] The results below deal with a general framework of pairs of sets \(X\) and \(Y\), each equipped with a positive definite kernel, \(K\) resp., \(L\), \(K\) on \(X\), and \(L\) on \(Y\). With view to realization of feedforward Neural Network-functions, we will present an explicit framework (see (2.11) and (2.20)) which allows us to pass from (nonlinear) functions \(f:X\to Y\) to linear operators \(T_{f}\) acting between the respective RKHSs \(\mathscr{H}_{K}\) and \(\mathscr{H}_{L}\). This will be a representation in the sense that composition of functions will map into products of the corresponding linear operators. Some care must be exercised as the linear operators \(T_{f}\) will in general be unbounded. Nonetheless, we shall show that the operators still fall in a class where spectral resolutions are available, see Theorem 2.11 and Corollary 2.12. Figure 2.1. The generating dipole function \(\left\{v_{a,b}\right\}\) indexed by pairs \(a,b\) such that \(a<b\). Compare with Figure 3.1 below. **Theorem 2.6**.: _Consider p.d. kernels \(X\times X\overset{K}{\longrightarrow}\mathbb{R}\) and \(Y\times Y\overset{L}{\longrightarrow}\mathbb{R}\). Let \(f:X\to Y\) be Lipschitz continuous with respect to the induced metrics \(d_{K},d_{L}\), i.e.,_ \[d_{L}\left(f\left(x\right),f\left(y\right)\right)\leq c_{f}d_{K}\left(x,y \right),\quad x,y\in X,\] _for some constant \(c_{f}\). Define the operator \(T_{f}:\mathscr{H}_{K}\rightarrow\mathscr{H}_{L}\) by_ \[T_{f}\left(K_{x}\right)\left(y\right)=L\left(f\left(x\right),y\right)\] _and extend it by linearity and density._ _Then, for any fixed \(c\in Y\), the function_ \[F_{f}:X\rightarrow\mathbb{R},\quad F_{f}\left(x\right):=L\left(f\left(x \right),c\right) \tag{2.11}\] _is in the RKHS \(\mathscr{H}_{K}\) if, and only if_ \[L_{c}\in dom(T_{f}^{*}), \tag{2.12}\] _the domain of the adjoint operator._ _Moreover,_ \[F_{f,y}\left(x\right):=L\left(f\left(x\right),y\right)\in\mathscr{H}_{K},\ \forall y\in Y\] \[\Updownarrow\] \[T_{f}\] _is closable._ _(See also Theorem 2.8.)_ Proof.: Let the setting be as in the statement of the theorem, i.e., \(X\overset{f}{\longrightarrow}Y\) assumed continuous with respect to the two metrics, \(d_{K}\) on \(X\) and \(d_{L}\) on \(Y\); so in particular, for pairs of points \(x_{1},x_{2}\in X\), we have \[d_{K}\left(x_{1},x_{2}\right) =\left\|K\left(\cdot,x_{1}\right)-K\left(\cdot,x_{2}\right)\right\| _{\mathscr{H}_{K}}^{2} \tag{2.13}\] \[=K\left(x_{1},x_{1}\right)+K\left(x_{2},x_{2}\right)-2K\left(x_{1 },x_{2}\right). \tag{2.14}\] We further fix a point \(c\in Y\), and set \(F=F_{f,c}\), specified as follows: \[F\left(x\right)=L\left(f\left(x\right),c\right),\text{ for all }x\in X,\] so \(F:X\rightarrow\mathbb{R}_{+}\cup\{0\}\). Now, for every \(N\), and every subset \(S_{N}=\left(x_{1},x_{2},\ldots,x_{N}\right)\subset X\), consider the following matrix operations (in \(N\) dimensions): \[\underbrace{F\big{|}_{N}:=\begin{bmatrix}F\left(x_{1}\right)\\ \vdots\\ F\left(x_{N}\right)\end{bmatrix}}_{\text{column vectors}},\text{ and }\quad \underbrace{Q_{N}:=\left|F\big{|}_{N}\left\rangle\left\langle\,F\big{|}_{N} \right|\right|}_{\text{matrix of a rank-1 operator}}\,, \tag{2.15}\] i.e., the rank-1 operator on \(\mathbb{R}^{N}\) written in Dirac's notation, defined as \[Q_{N}\left(\xi\right)=\left\langle F_{N},\xi\right\rangle F_{N} \tag{2.16}\] for all \(\xi\in\mathbb{R}^{N}\). Set \[K_{N}:=\left(K\left(x_{i},x_{j}\right)\right)_{i,j=1}^{N}=\begin{bmatrix}K \left(x_{1},x_{1}\right)&\cdots&K\left(x_{1},x_{N}\right)\\ \vdots&\ddots&\vdots\\ K\left(x_{N},x_{1}\right)&\cdots&K\left(x_{N},x_{N}\right)\end{bmatrix}, \tag{2.17}\] a sample matrix. For the convex cone of all positive definite \(N\times N\) matrices, we introduce the following familiar ordering, \(K\ll_{C}K^{\prime}\) iff (Def.) \(\exists C<\infty\) such that \[\xi^{T}K_{N}\xi\leq C\xi^{T}K_{N}^{\prime}\xi\text{ for all }\xi\in\mathbb{R}^{N}. \tag{2.18}\] Now an application of Lemma 2.1 above shows that the assertion in the theorem is equivalent to the existence of a finite constant \(C\) (independent of \(S_{N}=\left(x_{i}\right)_{i=1}^{N}\)) satisfying \(Q_{N}\ll_{C}K_{N}\), i.e., the estimate \[\left|\sum_{i}\xi L\left(f\left(x_{i}\right),c\right)\right|^{2}\leq C\sum_{i} \sum_{j}\xi_{i}K\left(x_{i},x_{j}\right)\xi_{j} \tag{2.19}\] holds for all \(N\), all \(S_{N}=\left\{x_{i}\right\}_{i=1}^{N}\), and all \(\xi\in\mathbb{R}^{N}\). We get this from the assumption on \(f\) in the theorem. See details below. **Summary of Theorem 2.6:** Start with \(K\) p.d. on \(X\times X\), \(L\) p.d. on \(Y\times Y\), and \(f:X\to Y\). We introduce the metrics \(d_{K}\) on \(X\), and \(d_{L}\) on \(Y\), and we consider \(f\) continuous, or Lipchitz. To get the desired conclusion \[\left(x\longmapsto L\left(f\left(x\right),y\right)\right)\in\mathscr{H}_{K},\] we must introduce an operator \(T_{f}:\mathscr{H}_{K}\to\mathscr{H}_{L}\). The right choice is \[L_{y}\in dom(T_{f}^{*}).\] See details below: Fixing two kernels \(K\) and \(L\), assumed p.d. on \(X\times X\), and on \(Y\times Y\). Pass to the corresponding RKHS \(\mathscr{H}_{K}\) and \(\mathscr{H}_{L}\). **Problem**.: Find conditions on functions \(X\overset{f}{\longrightarrow}Y\) with the property that, for \(\forall y\in Y\), then the induced function \[\underbrace{\left(X\ni x\longmapsto L\left(f\left(x\right),y\right)\right)}_{ F_{f},\left(\cdot\right)\text{ as a function on }X}\in\mathscr{H}_{K}. \tag{2.20}\] The argument stressed below is via dual operators (bounded) but the unbounded case is also interesting. Some remarks on the definition of the operator \(T_{f}:\mathscr{H}_{K}\to\mathscr{H}_{L}\) in the case when no additional assumptions are placed on \(X\overset{f}{\longrightarrow}Y\). We define \[T_{f}\left(K_{x}\right)\left(y\right)=L\left(f\left(x\right),y\right);\] and so we extend \(T_{f}\) to linear combinations: \[\mathscr{D}_{K}:=\big{\{}\underbrace{\sum_{i}c_{i}K_{x_{i}}}_{\text{function on }X}\xrightarrow{T_{f}}\underbrace{\sum_{i}c_{i}L\left(f\left(x_{i} \right),\cdot\right)}_{\text{function on }Y}. \tag{2.21}\] But to make sense of (2.21) so it is well defined, we must be careful with equivalence classes. If \(f:X\to Y\) is a general function, the (generalized) operator (2.21) may be non-closable. However, we can still define the adjoint \(T_{f}^{*}\), but its domain might be "small". Set \[\mathscr{D}_{K}:=span\left\{K_{x}\right\}_{x\in X}, \tag{2.22}\] then (Definition) a vector \(\psi\in\mathscr{H}_{L}\) is in \(dom(T_{f}^{*})\) iff \(\exists C_{\psi}<\infty\) s.t. \[\left|\left\langle T_{f}\varphi,\psi\right\rangle_{\mathscr{H}_{L}}\right| \leq C_{\psi}\left\|\varphi\right\|_{\mathscr{H}_{K}},\quad\forall\varphi \in\mathscr{D}_{K}. \tag{2.23}\] We then set \(T_{f}^{*}\psi=\) the solution to \[\left\langle T_{f}\varphi,\psi\right\rangle_{\mathscr{H}_{L}}=\left\langle \varphi,T_{f}^{*}\psi\right\rangle_{\mathscr{H}_{K}},\quad\forall\varphi\in \mathscr{D}_{K}. \tag{2.24}\] Let \(K,L,f\) be as specified, and assume for some \(y\in Y\), that we have \(L_{y}\in dom(T_{f}^{*})\), then (2.24) for \(L_{y}\in\mathscr{H}_{L}\overset{T_{f}^{*}}{\longrightarrow}\mathscr{H}_{K}\), \(\varphi=K_{x}\), \(\psi=L_{y}\) yields \[x\longmapsto T_{f}^{*}\left(L_{y}\right)\left(x\right)=L\left(f\left(x\right),y\right)\in\mathscr{H}_{K}.\] So the conclusion in Theorem 2.6 that \[\left(x\longmapsto L\left(f\left(x\right),y\right)\right)\in\mathscr{H}_{K} \tag{2.25}\] holds iff \(L_{y}\in dom(T_{f}^{*})\). In this case there are no difficulties with (2.21) and we get a dual pair \(T_{f}\) and \(T_{f}^{*}\), \[\left\langle T_{f}\varphi,\psi\right\rangle_{\mathscr{H}_{L}}=\left\langle \varphi,T_{f}^{*}\psi\right\rangle_{\mathscr{H}_{K}} \tag{2.26}\] for \(\forall\varphi\in\mathscr{D}_{K}\), and \(\psi\in\mathscr{D}_{L}\),. Setting \(\varphi=K_{x}\), and \(\psi=L_{y}\), (2.26) implies \[T_{f}^{*}\left(L_{y}\right)\left(x\right)=L\left(f\left(x\right),y\right)= \left(T_{f}\left(K_{x}\right)\right)\left(y\right). \tag{2.27}\] But the previous condition \(L_{y}\in dom(T_{f}^{*})\) (compare (2.26)) amounts to the assertion that \(T_{f}^{*}\left(L_{y}\right)\in\mathscr{H}_{K}\), and by (2.27), this is then the conclusion for Theorem 2.6. **Corollary 2.7** (composition operators).: _Let \(X\), \(Y\), \(K\) and \(L\) be as specified above; in particular, \(K\) is a fixed p.d. kernel on \(X\times X\), and the RKHS \(\mathscr{H}_{K}\) is a Hilbert space of scalar valued functions on \(X\). Similarly, \(\mathscr{H}_{L}\) is a Hilbert space of scalar valued functions on \(Y\). Both \(\mathscr{H}_{K}\) and \(\mathscr{H}_{L}\) satisfy the defining axioms for RKHSs; see Lemma 2.1 above. As noted, every function \(f\), \(X\overset{f}{\longrightarrow}Y\), induces a linear operator_ \[\mathscr{H}_{K}\overset{T_{f}}{\longrightarrow}\mathscr{H}_{L}, \tag{2.28}\] _with dense domain \(\mathscr{D}_{K}\); see the statement of Theorem 2.6. For the adjoint operator \(T_{f}^{*}\),_ \[\mathscr{H}_{L}\overset{T_{f}^{*}}{\longrightarrow}\mathscr{H}_{K}, \tag{2.29}\] _we have the following: For a function \(\psi\) in \(\mathscr{H}_{L}\), the two characterizations (2.30) and (2.31) hold:_ \[\psi\in dom(T_{f}^{*}) \tag{2.30}\] \[\Updownarrow\] \[\psi\circ f\in\mathscr{H}_{K}. \tag{2.31}\] _In the affirmative,_ \[T_{f}^{*}\left(\psi\right)=\psi\circ f:X\rightarrow\mathbb{R}, \tag{2.32}\] _i.e., \(T_{f}^{*}\) is the composition operator._ Proof.: (2.30)\(\Rightarrow\)(2.31). Assume (2.30), we then apply (2.23), and get \(C_{\psi}<\infty\) with: \[\left|\sum_{i}c_{i}\left(T_{f}^{*}\left(\psi\right)\right)\left(x_{i}\right) \right|^{2}\leq C_{\psi}\sum_{i}\sum_{j}c_{i}c_{j}K\left(x_{i},x_{j}\right). \tag{2.33}\] But \[T_{f}^{*}\left(\psi\right)\left(x_{i}\right) =\left\langle K_{x_{i}},T_{f}^{*}\left(\psi\right)\right\rangle_ {\mathscr{H}_{K}} \tag{2.34}\] \[=\left\langle T_{f}\left(K_{x_{i}}\right),\psi\right\rangle_{ \mathscr{H}_{L}}\] \[=\left\langle L\left(f\left(x_{i}\right),\cdot\right),\psi \right\rangle_{\mathscr{H}_{L}}\] \[=\psi\left(f\left(x_{i}\right)\right),\] where we used the RKHS property for \(\mathscr{H}_{L}\) in the last step. Substitution into (2.33) yields \[\left|\sum_{i}c_{i}\psi\left(f\left(x_{i}\right)\right)\right|^{2}\leq C_{\psi }\sum_{i}\sum_{j}c_{i}c_{j}K\left(x_{i},x_{j}\right), \tag{2.35}\] and, so by Lemma 2.1 applied to \(F=\psi\circ f\), conclusion in (2.31) follows. (2.31)\(\Rightarrow\)(2.30). Assume (2.31), we then reverse the above reasoning to get \[\left|\left\langle T_{f}\underbrace{\left(\sum_{i}c_{i}K_{x_{i}}\right)}_{ \in\mathscr{D}_{K}},\psi\right\rangle_{\mathscr{H}_{L}}\right|\leq\sqrt{C_{ \psi}}\left\|\sum_{i}c_{i}K_{x_{i}}\right\|_{\mathscr{H}_{K}} \tag{2.36}\] which states that \(\psi\in dom(T_{f}^{*})\), which is condition (2.30). Now combine this with (2.34), and we conclude that (2.32) is satisfied for \(\psi\), i.e., that \(T_{f}^{*}\psi=\psi\circ f\) holds. ### Basis approach Let \(X,Y,K,L,f\) be as usual, and define \(T_{f}:\mathscr{H}_{K}\rightarrow\mathscr{H}_{L}\). Since \(K\) is p.d. on \(X\times X\), the RKHS \(\mathscr{H}_{K}\) allows an ONB \(\left\{h_{i}\right\}_{i\in\mathbb{N}}\), \(h_{i}\in\mathscr{H}_{K}\); by general theory, we get the pointwise formula: \[K\left(x_{1},x_{2}\right)=\sum_{i\in\mathbb{N}}h_{i}\left(x_{1}\right)h_{i} \left(x_{2}\right). \tag{2.37}\] Then our condition in Theorem 2.6 is equivalent to the following: \[\left(X\ni x\longmapsto L\left(f\left(x\right),y\right)\right) \in\mathscr{H}_{K}\] (a) \[\Updownarrow\] \[\sum_{i\in\mathbb{N}}\left|\left(T_{f}\left(h_{i}\right)\right) \left(y\right)\right|^{2}<\infty.\] (b) Proof.: \(\left(a\right)\Rightarrow\left(b\right)\) is detailed below; but the converse implication will follow by the same argument. So by \(\left(a\right)\), \(L_{y}\in dom(T_{f}^{*})\) and therefore: \[T_{f}^{*}\left(L_{y}\right)\left(\cdot\right)\in\mathscr{H}_{K}. \tag{2.38}\] Since \(\left\{h_{i}\right\}\) is an ONB in \(\mathscr{H}_{K}\), \[\sum_{i}\left|\left\langle h_{i},\underbrace{T_{f}^{*}\left(L_{y}\right)}_{ \in\mathscr{H}_{K}}\right\rangle\right|^{2}=\left\|T_{f}^{*}\left(L_{y}\right) \right\|_{\mathscr{H}_{K}}^{2}<\infty. \tag{2.39}\] But from the LHS\({}_{\left(\ref{eq:2.39}\right)}\): and \(\left(b\right)\) follows. **Key Question: When is \(F_{f,y}\left(\cdot\right)\in\mathscr{H}_{K}\)?** The cleanest answer to the question of what functions \(X\overset{f}{\longrightarrow}Y\) have the property that \[F_{f,y}\left(x\right)=L\left(f\left(x\right),y\right)\text{ is in }\mathscr{H}_{K} \tag{2.40}\] is this: **Theorem 2.8**.: _Let \(K,L\) and \(f\) be given, then_ \[F_{f,y}\text{ in \eqref{eq:2.40} is in }\mathscr{H}_{K}\Longleftrightarrow L_{y}\in\] _dom \[\left(T_{f}^{*}\right)\],_ (2.41) _where the operator \(T_{f}:\mathscr{H}_{K}\rightarrow\mathscr{H}_{L}\) is given by_ \[T_{f}\left(K_{x}\right):=L\left(f\left(x\right),\cdot\right).\] _Moreover, (2.41) holds for all \(y\in Y\Longleftrightarrow T_{f}\) is closable._ ### Dual pairs of operators Consider a symmetric pair of operators with dense domains: (\(T=T_{f}\), since it will depend on \(f\)) where \[span\left\{K_{x}\right\}_{x\in X}\text{ is dense in }\mathscr{H}_{K} \tag{2.42}\] and \[span\left\{L_{y}\right\}_{y\in Y}\text{ is dense in }\mathscr{H}_{L} \tag{2.43}\] such that \[K_{x}\in dom(T_{f}),\text{ and } \tag{2.44}\] \[L_{y}\in dom(T_{f}^{*}) \tag{2.45}\] where "\(dom\)" denotes the respective operator domains. _Note._ We note that \[T_{f}\left(K_{x}\right)\left(\cdot\right)=L\left(f\left(x\right),\cdot\right) \in\mathscr{H}_{L}\] is always well defined, with dense domain, but the secret is \(T_{f}^{*}\). Also note that (2.45) is the condition in Theorem 2.6. Let \(f:X\to Y\) be as before, and the two p.d. kernels \(K\) and \(L\) are fixed. We then introduce the corresponding (densely defined) operator \(T_{f}:\mathscr{H}_{K}\rightarrow\mathscr{H}_{L}\) by setting \[T_{f}\left(K_{x}\right)=L\left(f\left(x\right),\cdot\right)\in\mathscr{H}_{L}. \tag{2.46}\] **Notation and convention.**\(K_{x}\left(\cdot\right)\) is the kernel function in \(\mathscr{H}_{K}\) as usual: \[K_{x}\left(t\right) =K\left(x,t\right),\;\forall t\in X\;\text{and similarly,} \tag{2.47}\] \[L_{y}\left(u\right) =L\left(y,u\right),\;\forall u\in Y. \tag{2.48}\] **Lemma 2.9**.: _When \(L_{y}\in dom(T_{f}^{\ast})\) then_ \[\left(T_{f}^{\ast}\left(L_{y}\right)\right)\left(x\right)=L\left(f\left(x \right),y\right)\;\text{on $X$,} \tag{2.49}\] _equivalently,_ \[T_{f}^{\ast}\left(L_{y}\right)\left(\cdot\right)=L\left(f\left(\cdot\right),y \right)\;\text{on $X$.} \tag{2.50}\] Proof of (2.49).: The conclusion (2.49) is equivalent to the following assertion: The conclusion (2.49) follows since the respective kernel functions span dense subspaces. Recall, \[\text{the function $x\longmapsto F_{f,y}\left(x\right)=L\left(f \left(x\right),y\right)\in\mathscr{H}_{K}$}\] \[\Updownarrow\] \[L_{y}\in dom(T_{f}^{\ast}).\] Assume that \(L_{y}\in dom(T_{f}^{\ast})\), then apply the condition for functions in \(\mathscr{H}_{K}\) to \(F_{f,y}\left(\cdot\right)\), so \(\forall n,\)\(\forall\left(x_{i}\right)_{1}^{n},\)\(\forall\left(c_{i}\right)_{1}^{n},\)\(c_{i}\in\mathbb{R}\): \[\left|\sum_{i}c_{i}F_{f,y}\left(x_{i}\right)\right|^{2} = \left|\sum_{i}c_{i}L\left(f\left(x_{i}\right),y\right)\right|^{2}\] \[\leq \left|\left\langle\sum_{i}c_{i}K_{x_{i}},T_{f}^{\ast}\left(L_{y} \right)\right\rangle_{\mathscr{H}_{K}}\right|^{2}\] \[\leq \left|\sum_{i}c_{i}K_{x_{i}}\right|^{2}_{\mathscr{H}_{K}}\left\| T_{f}^{\ast}\left(L_{y}\right)\right\|^{2}_{\mathscr{H}_{K}}\] \[= \sum_{i}\sum_{j}c_{i}c_{j}K\left(x_{i},x_{j}\right)\left\|T_{f}^{ \ast}\left(L_{y}\right)\right\|^{2}_{\mathscr{H}_{K}}.\] **Lemma 2.10**.: _The implication below is both directions:_ \[X\ni x\longmapsto L\left(f\left(x\right),y\right)\in\mathscr{H}_{K} \text{ for }\forall y\] \[\Updownarrow\] _the condition in (_2.6_) is satisfied._ _Even if we fix \(y\in Y\), then_ \[L_{y}\in dom(T_{f}^{\ast})\Longleftrightarrow\left(x\longmapsto L\left(f \left(x\right),y\right)\right)\in\mathscr{H}_{K}. \tag{2.51}\] Proof sketch.: By definition, \(L_{y}\in dom(T_{f}^{\ast})\), \(\exists C_{y}<\infty\Longleftrightarrow\) \[\left|\left\langle T_{f}\varphi,L_{y}\right\rangle_{\mathscr{H}_{L}}\right|= \left|\left(T_{f}\left(\varphi\right)\right)\left(y\right)\right|\leq C_{y} \left\|\varphi\right\|_{\mathscr{H}_{K}}\] holds for \(\forall\varphi\in span\left\{K_{x}\right\}_{x\in X}.\) But \[T_{f}\left(K_{x}\right)\left(y\right)=L\left(f\left(x\right),y\right),\text{ and } \tag{2.52}\] \[\left|\sum_{i}c_{i}\underbrace{L\left(f\left(x_{i}\right),y\right)}_{F_{f,y} \left(x_{i}\right)}\right|^{2} =\left|\left\langle\sum_{i}c_{i}K_{x_{i}},T_{f}^{\ast}\left(L_{y} \right)\right\rangle_{\mathscr{H}_{K}}\right|^{2} \tag{2.53}\] \[\leq\left\|T_{f}^{\ast}\left(L_{y}\right)\right\|_{\mathscr{H}_{K}}^{2} \underbrace{\sum_{i}\sum_{j}c_{i}c_{j}K\left(x_{i},x_{j}\right)}_{<\infty} \tag{2.54}\] and so by the basic lemma for \(\mathscr{H}_{K}\) (see the proof of Theorem 2.6), we conclude that functions \(F_{f,y}\in\mathscr{H}_{K}\), i.e., \(\left(x\longmapsto L\left(f\left(x\right),y\right)\right)\in\mathscr{H}_{K}\). **Conclusion:** the bi-implication \(\Longleftrightarrow\) in (2.51) is valid. ### Functions and Operators In general if \(T:\mathscr{H}_{1}\rightarrow\mathscr{H}_{2}\) is an operator with dense domain \(\mathscr{D}\subset\mathscr{H}_{1}\), where \(\mathscr{H}_{i}\), \(i=1,2\), are two Hilbert spaces, we know that \(T\) is closable \(\Longleftrightarrow T^{\ast}\) is densely defined, i.e., iff \(dom(T^{\ast})\) is dense in \(\mathscr{H}_{2}\) (see e.g., [11]). So we apply this to \(T=T_{f}\), \(\mathscr{H}_{1}=\mathscr{H}_{K}\), \(\mathscr{H}_{2}=\mathscr{H}_{L}\), and the condition in Theorem 2.6 holds \(\Longleftrightarrow L_{y}\in dom(T_{f}^{\ast})\)\(\forall y\in Y\). Since \(span\left\{L_{y}\right\}_{y\in Y}\) is dense in \(\mathscr{H}_{L}\), the condition in Theorem 2.6\(\Longrightarrow T_{f}\) is closable. Given \(K\) and \(L\) as above, introduce \[\mathscr{F}_{ub}\left(K,L\right) =\left\{f:T_{f}\text{ is closable}\right\},\text{ and } \tag{2.55}\] \[\mathscr{F}_{b}\left(K,L\right) =\left\{f:T_{f}\text{ is bounded from }\mathscr{H}_{K}\text{ into } \mathscr{H}_{L}\right\}. \tag{2.56}\] In both cases, the operators \(T=T_{f}\) depends on the choice of function \(X\xrightarrow{f}Y\), but the two conditions (2.55) and (2.56) are different: \[\left(T_{f}\left(K_{x}\right)\right)\left(y\right)=L\left(f\left(x\right),y \right)=\left(\left(T_{f}\right)^{\ast}\left(L_{y}\right)\right)\left(x\right), \tag{2.57}\] for all \(x\in X\), and \(y\in Y\). See details below: Some general comments about the operator \(T_{f}:\mathscr{H}_{K}\rightarrow\mathscr{H}_{L}\). As before, \(K\) and \(L\) are fixed p.d. kernels, and \(f:X\to Y\) is a function. We need to understand the conclusion from Theorem 2.6, i..e, when is \[\left(X\ni x\longmapsto L\left(f\left(x\right),y\right)\right)\in\mathscr{H}_{ K}\text{ for all }y\in Y? \tag{2.58}\] Answer: (2.58) \(\Longleftrightarrow\)\(L_{y}\in dom(T_{f}^{\ast})\). Note that then the function in (2.58) is \(T_{f}^{*}\left(L_{y}\right)\); see (2.57). But note that, starting with a function \(X\xrightarrow{f}Y\), there are requirements for having (2.57) yield a well defined linear operator \(T_{f}\) with dense domain in \(\mathscr{H}_{K}\), s.t. \[T_{f}\left(K_{x}\right)\left(\cdot\right)=L\left(f\left(x\right),\cdot\right). \tag{2.59}\] The case when \(T_{f}\) is bounded is easy since then \(dom(T_{f}^{*})=\mathscr{H}_{L}\). Notationally, \(L\left(f\left(x\right),\cdot\right)\in L_{f\left(x\right)}\in\mathscr{H}_{L}\), but we must also verify the implicit kernel function for all finite sums: \[\sum_{i}\sum_{j}c_{i}c_{j}K\left(x_{i},x_{j}\right)=0\Longrightarrow\sum_{i} \sum_{j}c_{i}c_{j}L\left(f\left(x_{i}\right),f\left(x_{j}\right)\right)=0.\] ### The case when \(K=l\) As demonstrated in Section 3 below, for applications to multi-level NNs, the recursive constructions simplify when the same p.d. kernel \(K\) is used at each level. Hence below, we specialize to the case when \(X=Y\), and \(K=L\); see the setting in Theorems 2.6 and 2.8. **Theorem 2.11**.: _Consider a positive definite kernel \(K\) on \(X\times X\), and the corresponding RKHS \(\mathscr{H}_{K}\), i.e., the Hilbert completion of \(\left\{K_{x}\right\}_{x\in X}\) where \(K_{x}:=K\left(\cdot,x\right)\). Fix a function \(X\xrightarrow{f}X\) with the property (see Theorem 2.6) that_ \[\left(X\ni x\longmapsto K\left(f\left(x\right),y\right)\right)\in\mathscr{H}_ {K}\,\text{for all }y\in X\,. \tag{2.60}\] _Hence, the operator \(T_{f}:\mathscr{H}_{K}\to\mathscr{H}_{K}\) defined by_ \[T_{f}\left(K\left(\cdot,y\right)\right):=K\left(f\left(\cdot\right),y\right) \tag{2.61}\] _is a densely defined operator from \(\mathscr{H}_{K}\) into \(\mathscr{H}_{K}\), with domain_ \[\mathscr{D}_{K}:=span\left\{K_{x}\right\}_{x\in X}. \tag{2.62}\] 1. _Then the closure of_ \(T_{f}\) _(also denoted_ \(T_{f}\)_) is well defined and normal, i.e., the two operators_ \(T_{f}\) _and_ \(T_{f}^{*}\) _commute._ 2. _In particular,_ \(T_{f}\) _has a projection-valued spectral resolution, i.e., there is a projection-valued measure_ \(Q\left(\cdot\right)\) _on_ \(\mathscr{B}_{\mathbb{C}}\left(=\text{the Borel subsets in }\mathbb{C}\right)\) _such that_ \[T_{f}=\int_{spect\left(T_{f}\right)}\lambda\,Q\left(\lambda\right):\mathscr{D} _{K}\to\mathscr{H}_{K}.\] (2.63) Proof.: Note that part (2) follows from (1) and the Spectral Theorem for normal operators (in the Hilbert space \(\mathscr{H}_{K}\).) Part (1). When the operator \(T_{f}^{*}\) is introduced, we get the following commutativity: which is the desired conclusion (1). Figure 2.2. Commutativity of \(T_{f}\) and \(T_{f}^{*}\). Given a function \(f:X\to X\) as in Theorem 2.11. Below we make use of the corresponding projection valued measure \(Q^{\left(f\right)}\) from Theorem 2.11 in order to establish an assignment from pairs \(\left(x,y\right)\) of points in \(X\), into systems of complex measures \(\mu_{\left(x,y\right)}\) on the spectrum of \(T_{f}\). In this assignment, \(n\)-fold composition-iteration of the function \(f\) yields the \(n\)th moment of each of the measures \(\mu_{\left(x,y\right)}\). **Corollary 2.12**.: _Let \(K,X\) and \(f\) be as specified in Theorem 2.11, and let \(Q=Q^{\left(K,f\right)}\left(\cdot\right)\) be the corresponding projection valued measure in (2.63). Then for every pair \(x,y\in X\), we get a corresponding Borel measure_ \[\mu_{x,y}^{\left(f\right)}\left(B\right)=\left\langle K_{x},Q\left(B\right)K _{y}\right\rangle_{\mathscr{H}_{K}}=\left(Q\left(B\right)\left(K_{y}\right) \right)\left(x\right), \tag{2.64}\] _for all \(B\in\mathscr{B}_{\mathbb{C}}\). Inductively, setting_ \[f^{\circ n}=\underbrace{f\circ\cdots\circ f}_{n\text{ fold}}\] _we arrive at the following moment formula for the respective complex measures:_ \[\mu_{f^{\circ n}\left(x\right),y}^{\left(f\right)}\left(B\right)=\int_{B} \lambda^{n}\,\mu_{x,y}^{\left(f\right)}\left(d\lambda\right). \tag{2.65}\] We now turn to the role of _multipliers_ in the RKHS \(\mathscr{H}_{K}\). **Definition 2.13**.: A scalar valued function \(\varphi\) on \(X\) is said to be a _multiplier_ for \(\mathscr{H}_{K}\) iff one of the two equivalent conditions hold: 1. The multiplication operator \(M_{\varphi}\) acting on \(\mathscr{H}_{K}\) via \(M_{\varphi}F=\varphi F\) (via pointwise product) leaves \(\mathscr{H}_{K}\) invariant. 2. We have the following identity for the adjoint operator: \[M_{\varphi}^{\ast}\left(K_{x}\right)=\varphi\left(x\right)K_{x}\text{ for all }x\in X\] (2.66) where \(K_{x}\) denotes the kernel function \(K_{x}=K\left(\cdot,x\right)\). _Remark 2.14_.: The equivalence of (1) and (2) follows from the standard reference on RKHSs; see e.g., [17]. **Theorem 2.15**.: _Let \(K\) be a fixed p.d. kernel on \(X\times X\), and let \(\mathscr{H}_{K}\) be the corresponding RKHS. Let \(X\xrightarrow{f}X\) be a function such that (2.60) holds, i.e., \(\left(X\ni x\longmapsto K\left(f\left(x\right),y\right)\right)\in\mathscr{H}_ {K}\) for all \(y\in X\)._ _Then for every multiplier \(\varphi\) for \(\mathscr{H}_{K}\), we have:_ \[M_{\left(\varphi\circ f\right)}T_{f}^{\ast}=T_{f}^{\ast}M_{\varphi}. \tag{2.67}\] Proof.: It is clear that the conclusion (2.67) has the following equivalent form: \[T_{f}M_{\left(\varphi\circ f\right)}^{\ast}=M_{\varphi}^{\ast}T_{f}; \tag{2.68}\] and below we shall prove (2.68). Let \(f\) and \(\varphi\) be as specified in the theorem. We then have the following commutative diagram: In the verification of the assertions in Figure 2.3, we used the conclusions in Theorems 2.6 and 2.8 above. ## 3. Neural Network-activation functions from p.d. kernels In the previous section we introduced the use of positive definite kernels, and associated generating function for the NN algorithms. Below we make use of the kernel analysis in design of the generating NN functions. The next definition makes use of the iterative generation of feedforward functions as in the literature, e.g., [1, 10, 11]. The recursive steps used here in the definition and Lemma 3.2 below serve as applications of our general framework from Theorems 2.6 and 2.8 above. **Definition 3.1**.: Let \(K\) be a positive definite kernel on \(\mathbb{R}\). An \(l\)-layer feedforward network with kernel \(K\) is a function of the form \[x\mapsto y_{1}=K\left(A_{1}x+b_{1},c_{1}\right)\mapsto y_{2}=K \left(A_{2}y_{1}+b_{2},c_{2}\right)\mapsto\cdots\\ \cdots\mapsto y_{l}=K\left(A_{l}y_{l-1}+b_{l},c_{l}\right)\mapsto y _{out}=K\left(\left\langle a_{l+1},y_{l}\right\rangle+b_{l+1},c_{l+1}\right)\] where * \(x\in\mathbb{R}^{n_{0}}\); * \(A_{j}\in\mathbb{R}^{n_{j}\times n_{j-1}}\), \(b_{j},c_{j}\in\mathbb{R}^{n_{j}}\) for \(j=1,\cdots,l\); * \(a_{l+1}\in\mathbb{R}^{n_{l}}\), \(b_{l+1},c_{l+1}\in\mathbb{R}\); and for vectors \(x,y\in\mathbb{R}^{m}\), \[K\left(x,y\right):=\left[K\left(x_{1},y_{1}\right),\cdots,K\left(x_{m},y_{m} \right)\right].\] **Lemma 3.2**.: _Let \(K\left(x,y\right)=\min\left(x,y\right)\), and \(a,b,c,d\) be nonzero constants. Then_ 1. \(K\left(ax+b,c\right)=aK\left(x,a^{-1}\left(c-b\right)\right)+b\)_;_ 2. \(K\left(K\left(x,a\right),b\right)=K\left(x,K\left(a,b\right)\right)\)_;_ 3. \(K\left(dK\left(ax+b,c\right)+e,f\right)=daK\left(x,K\left(a^{-1}\left(c-b \right),a^{-1}\left(d^{-1}\left(f-e\right)-b\right)\right)\right)+db+e\)_._ Proof.: 1. \(K\left(ax+b,c\right)=\begin{cases}ax+b&x<a^{-1}\left(c-b\right)\\ c&x>a^{-1}\left(c-b\right)\end{cases}\) 2. Assume \(a<b\), then \[K\left(K\left(x,a\right),b\right)=\begin{cases}x&x<a\\ a&x\geq a\end{cases}=K\left(x,a\right).\] The case \(a>b\) is similar. Figure 2.3. Commutative diagram corresponding to (2.68). 3. This follows from (1)-(2): \[K\left(dK\left(ax+b,c\right)+e,f\right)\] \[= dK\left(K\left(ax+b,c\right),d^{-1}\left(f-e\right)\right)+e\] \[= dK\left(aK\left(x,a^{-1}\left(c-b\right)\right)+b,d^{-1}\left(f-e \right)\right)+e\] \[= d\left\{aK\left(K\left(x,a^{-1}\left(c-b\right)\right),a^{-1} \left(d^{-1}\left(f-e\right)-b\right)\right)+b\right\}+e\] \[= daK\left(K\left(x,a^{-1}\left(c-b\right),a^{-1}\left(d^{-1}\left( f-e\right)-b\right)\right)+db+e\] \[= daK\left(x,K\left(a^{-1}\left(c-b\right),a^{-1}\left(d^{-1}\left( f-e\right)-b\right)\right)\right)+db+e\] In what follows, all the networks are restricted to be defined on compact subsets \(\Omega\) in \(\mathbb{R}^{d}\), e.g., \(\Omega=\left[0,1\right]^{d}\) (hypercubes). This is in consideration of standard normalizations in training neural networks. In Theorems 3.3 and 3.4, we present in detail the particular _relative Reproducing Kernel Hilbert Spaces_ which have as their respective dipole system (see (3.5)) the generalized ReLu functions illustrated here in Figures 2.1 and 3.1. Here we specify the kernel \(K_{1}\) for Brownian motion \(W\) indexed by \(\mathbb{R}\). As a result, the corresponding p.d. kernel on \(\mathbb{R}\times\mathbb{R}\) is as follows: \[K_{1}\left(x,y\right)=\begin{cases}\left|x\right|\wedge\left|y\right|=\min \left(\left|x\right|,\left|y\right|\right)&\text{if $xy\geq 0$ (so same sign)}\\ 0&\text{if $xy<0$, so opposite sign.}\end{cases} \tag{3.1}\] Proof.: The connection between the kernel \(K_{1}\) and the Brownian motion \(\left\{W_{x}\right\}_{x\in\mathbb{R}}\) is as follows: \[K_{1}\left(x,y\right)=\mathbb{E}\left(\left(W_{x}-W_{0}\right)\left(W_{y}-W_{ 0}\right)\right) \tag{3.2}\] for all \(x,y\in\mathbb{R}\). The asserted formula (3.1) follows from this, combined with the independence of increments for Brownian motion. **Theorem 3.3**.: _Let \(K_{1}\) be the p.d. kernel (3.1) on \(\mathbb{R}\times\mathbb{R}\), with the corresponding RKHS_ \[\mathscr{H}_{K_{1}}=\left\{f:f^{\prime}\in L^{2}\right\},\quad\left\|f\right\| _{\mathscr{H}_{K_{1}}}^{2}=\int\left|f^{\prime}\right|^{2}d\lambda_{1}.\] _On \(\Omega=\left[0,1\right]^{d}\), consider the p.d. kernel_ \[K_{d}\left(x,y\right)=K_{1}\left(x_{1},y_{1}\right)\cdots K_{1}\left(x_{d},y_ {d}\right),\] _so that_ \[\mathscr{H}_{K_{d}}=\left\{f:\nabla f\in L^{2}\right\},\quad\left\|f\right\| _{\mathscr{H}_{K_{d}}}^{2}=\int\left|\nabla f\right|^{2}d\lambda_{d},\] _where \(\lambda_{d}\) denotes the \(d\)-dimensional Lebesgue measure._ _Given \(f:\Omega\to\mathbb{R}\), and a fixed \(c\in\mathbb{R}\), set_ \[F:\mathbb{R}^{d}\to\mathbb{R}^{1},\quad F\left(x\right)=K_{1}\left(f\left(x \right),c\right).\] _Then,_ \[F\in\mathscr{H}_{K_{d}}\Longleftrightarrow\iint_{f^{-1}\left(\left[0,c\right] \right)}\left|\nabla f\right|^{2}d\lambda_{d}<\infty.\] **Theorem 3.4**.: _Let \(\mu\) be a non-atomic \(\sigma\)-finite measure on \(\left(\mathbb{R},\mathscr{B}_{\mathbb{R}}\right)\), and consider Stieltjes measures \(dF\) on \(\left(\mathbb{R},\mathscr{B}_{\mathbb{R}}\right)\) such that_ \[dF\ll\mu \tag{3.3}\] (absolutely continuous). _Then the relative RKHS \(\mathscr{H}_{\mu}\) for the p.d. kernel_ \[K_{\mu}\left(A,B\right)=\mu\left(A\cap B\right) \tag{3.4}\] _consists functions \(F\) such that_ \[F\left(b\right)-F\left(a\right)=\left\langle v_{a,b}^{\left(\mu\right)},F \right\rangle_{\mathscr{H}_{\mu}} \tag{3.5}\] \[\int_{\mathbb{R}}\left|\frac{dF}{d\mu}\right|^{2}d\mu<\infty \tag{3.6}\] _where the relative kernels \(v_{a,b}^{\left(\mu\right)}\) are as follows:_ \[\frac{dv_{a,b}^{\left(\mu\right)}}{d\mu}\left(x\right)=\chi_{\left[a,b\right] \left(x\right)},\] _see Figure 3.1._ Proof.: See [1, 2] and the details in the proof of Theorem 3.3. _Remark 3.5_.: The positive definite kernel \(K_{\mu}\) which is "responsible" for the relative RKHS \(\mathscr{H}_{\mu}\) is defined on \(\mathscr{B}\times\mathscr{B}\), where \(\mathscr{B}\) denotes the Borel \(\sigma\)-algebra of subsets of \(\mathbb{R}\). Using [2], one checks that \[K_{\mu}\left(A,B\right):=\mu\left(A\cap B\right)\text{ for all }A,B\in\mathscr{B}. \tag{3.7}\] We further note that \(K_{\mu}\) is the covariance for the generalized \(\mu\)-Brownian motion \(\{W_{A}^{\left(\mu\right)}\}_{A\in\mathscr{B}}\), i.e., subject to \[\mathbb{E}\left(W_{A}^{\left(\mu\right)}W_{B}^{\left(\mu\right)}\right)=\mu \left(A\cap B\right)\text{ for all }A,B\in\mathscr{B}. \tag{3.8}\] The corresponding Ito-lemma for \(W^{\left(\mu\right)}\) is defined for differentiable functions \(f\) on \(\mathbb{R}\) via \[f\left(W_{A}^{\left(\mu\right)}\right)-f\left(0\right)=\int_{A}f^{\prime} \left(W_{t}^{\left(\mu\right)}\right)dW_{t}^{\left(\mu\right)}+\frac{1}{2} \int_{A}f^{\prime\prime}\left(W_{t}^{\left(\mu\right)}\right)\mu\left(dt \right). \tag{3.9}\] In particular, the measure \(\mu\) is the quadratic variation of \(W_{t}^{\left(\mu\right)}\). Figure 3.1. Illustration dipole functions that reproduce differences of values of functions in the space \(\mathscr{H}_{\mu}\). Compare with Figure 2.1 above. ## 4. Applications to fractal images In recent decades, it has become evident that fractal features arise in diverse datasets, in time series and in image analysis, to mention two. (See e.g., [11, 12].) Perhaps the best known examples of fractal features include precise symmetries of scales. Via a prescribed system of affine maps, they take the form of self-similarity. And a special case, includes iterated function systems (IFS), and maximal-entropy measures, also called IFS measures. The more familiar Cantor constructions, e.g., scaling by \(3\) or scaling by \(4\), are examples of IFS measures. For each of these cases, the RKHS framework we present in Section 3, serve as ideal tools for such adapted NN algorithms. In particular, this may be illustrated with large numbers of images, say \(5000\) generated images, each one is a fractal, either \(2\)D or \(3\)D, with random rotation, with zooming, and coloring; half of them have scaling \(3\), the other half have scaling \(4\). This leads to training of a network serving to classify the images by scaling factors. In particular, the Cantor-type activation functions, or the cumulative functions of Cantor-like measures (Figure 3.1), have vanishing derivatives over structured subintervals of \([0,1]\). This feature may lead to several benefits in neural networks. For example, such functions can introduce sparsity and regularization into the network, which improves its generalization performance and reduces the risk of overfitting. Additionally, these functions can make the network more robust to noise and other perturbations in the input data, which improves its performance on unseen data. Furthermore, activation functions whose derivative is zero over subintervals allow the network to learn more complex and non-linear patterns in the data. This can improve the expressiveness and flexibility of the network, making it more accurate and effective for a wider range of tasks. Additionally, these functions can make the network easier to optimize and train, since the gradient of the activation function is well-structured, thus reduce the computational complexity and improve the convergence rate of the training algorithm. More generally, a neural network with a custom activation function (see e.g. the dipoles in Figure 2.1) uses a non-standard activation function with adjustable parameters that can be trained and optimized during the learning process. This allows the network to learn more complex and non-linear relationships between the input and output data, which can improve the accuracy of the network's predictions. The use of a custom activation function with trainable parameters can be useful in a variety of applications, such as image recognition, natural language processing, and time series forecasting. It can also be used to improve the performance of other machine learning algorithms, such as decision trees and support vector machines (see e.g., [1, 15, 16, 17, 18, 19, 20]). Below we apply a custom activation function in a ConvNet to classify fractal images. In this setting, the activation function should be designed to capture the complex, self-similar patterns that are characteristic of the fractal images. The network is trained on a dataset of fractal images with corresponding labels. It is optimized using a gradient-based algorithm, such as stochastic gradient descent. Once trained, the network will be used to classify new fractal images and predict their classes with high accuracy. In the example below, a dataset1 of 15,000 Cantor-like 3D images is generated in Mathematica. Parameters of each image, such as zoom factor, viewing angle, and scaling factor, are uniformly distributed. A sample of the images is shown in Figure 4.1. Footnote 1: Available at [https://www.kaggle.com/dsv/4791103](https://www.kaggle.com/dsv/4791103). The images are split into three categories according to their scaling factors, labeled as class "1", "2" and "3", respectively. The entire dataset is divided into a training set (size = 10,000), validation set (size = 2,500) and test set (size = 2,500). The task is to train a ternary classifier using the training set, along with the validation set (for model selection), whose performance is then tested on the test images. In the experiment, a small ConvNet is implemented in Keras. Its architecture is shown in Figure 4.2. The loss and accuracy of the model are recorded for 20 epochs (Figure 4.3). In comparison with a standard Relu network (Figure 4.3a) of the same architecture, the use of Cantor-like activation is better at reducing overfitting (Figure 4.3b); it is expected that with a systematic hyperparameter tuning, such a network has the potential to outperform Relu networks in certain applications. Figure 4.1. A random sample of the dataset of 3D Cantor images. Figure 4.2. A ConvNet for fractal image classification. Figure 4.3. Training loss and validation loss, illustrated with use of a ConvNet.
2306.16830
Sampling weights of deep neural networks
We introduce a probability distribution, combined with an efficient sampling algorithm, for weights and biases of fully-connected neural networks. In a supervised learning context, no iterative optimization or gradient computations of internal network parameters are needed to obtain a trained network. The sampling is based on the idea of random feature models. However, instead of a data-agnostic distribution, e.g., a normal distribution, we use both the input and the output training data to sample shallow and deep networks. We prove that sampled networks are universal approximators. For Barron functions, we show that the $L^2$-approximation error of sampled shallow networks decreases with the square root of the number of neurons. Our sampling scheme is invariant to rigid body transformations and scaling of the input data, which implies many popular pre-processing techniques are not required. In numerical experiments, we demonstrate that sampled networks achieve accuracy comparable to iteratively trained ones, but can be constructed orders of magnitude faster. Our test cases involve a classification benchmark from OpenML, sampling of neural operators to represent maps in function spaces, and transfer learning using well-known architectures.
Erik Lien Bolager, Iryna Burak, Chinmay Datar, Qing Sun, Felix Dietrich
2023-06-29T10:13:36Z
http://arxiv.org/abs/2306.16830v2
# Sampling weights of deep neural networks ###### Abstract We introduce a probability distribution, combined with an efficient sampling algorithm, for weights and biases of fully-connected neural networks. In a supervised learning context, no iterative optimization or gradient computations of internal network parameters are needed to obtain a trained network. The sampling is based on the idea of random feature models. However, instead of a data-agnostic distribution, e.g., a normal distribution, we use both the input and the output training data of the supervised learning problem to sample both shallow and deep networks. We prove that the sampled networks we construct are universal approximators. We also show that our sampling scheme is invariant to rigid body transformations and scaling of the input data. This implies many popular pre-processing techniques are no longer required. For Barron functions, we show that the \(L^{2}\)-approximation error of sampled shallow networks decreases with the square root of the number of neurons. In numerical experiments, we demonstrate that sampled networks achieve comparable accuracy as iteratively trained ones, but can be constructed orders of magnitude faster. Our test cases involve a classification benchmark from OpenML, sampling of neural operators to represent maps in function spaces, and transfer learning using well-known architectures. ## 1 Introduction Training deep neural networks involves finding all weights and biases. Typically, iterative, gradient-based methods are employed to solve this high-dimensional optimization problem. Randomly sampling all weights and biases before the last, linear layer circumvents this optimization. However, the drawback of this approach is that the high-dimensional probability distribution must be chosen. Random projection networks [46] or extreme learning machines [25] involve choosing the distribution completely problem- and data-agnostic, e.g., a normal distribution. In this work, we introduce a data-driven sampling scheme to construct weights and biases close to gradients of the target function. This idea provides a solution to three main challenges that have prevented randomly sampled networks to compete successfully against iterative optimization methods in the setting of supervised learning. Figure 1: Random feature models choose weights in a data-agnostic way, compared to sampling them where it matters: at large gradients. The arrows illustrate where the network weights are placed. **Deep neural networks** Random feature models and extreme learning machines are typically defined for networks with a single hidden layer. Our sampling scheme accounts for the high-dimensional ambient space that is introduced after this layer, and thus deep networks can be constructed efficiently. **Approximation accuracy** Gradient-based, iterative approximation can find accurate solutions with a relatively small number of neurons. Randomly sampling weights using a data-agnostic distribution often requires thousands of neurons to compete. Our sampling scheme takes into account the given data points and function values, leading to accurate and width-efficient approximations. **Interpretability** Sampling weights and biases completely randomly, i.e., without taking into account the given data, leads to networks that do not incorporate any information about the given problem. We employ and analyze a recently introduced weight construction technique [22] that uses the direction between pairs of data points to construct individual weights and biases. In addition, we propose a sampling distribution over these data pairs that leads to efficient use of weights; cf. Figure 1. The distribution also leads to invariance to orthogonal transformations and scaling of the input data, which makes many common pre-processing techniques redundant. ## 2 Related work Sampled weights are closely related to random Fourier features, Li et al. [36] and Liu et al. [38] review and unify its theory and algorithms. Shallow [12] and deep networks [24] with normally distributed random weights have been analyzed regarding classification accuracy. Similar to finite element methods in scientific computing, earlier work placed activation function at equally spaced collocation points [42; 8]. Gallicchio and Scardapane [23] provide a review of deep random feature models, and discuss autoencoders and reservoir computing (resp. echo-state networks [29]) in this context. The latter are randomly sampled, recurrent networks to model dynamical systems [5]. Barron spaces are very useful to study approximation errors and convergence rates of neural networks [1; 16], as well as regularization techniques, esp. Tikohnov and Total Variation [35]. A lot of work [46; 15; 13; 48; 54] surrounds the approximation rate of \(\mathcal{O}(m^{-1/2})\) for neural networks with one hidden layer, originally proved by Barron [1]. The rate with respect to width \(m\), but not the constant, is independent of the input space dimension. This implies that neural networks can mitigate the curse of dimensionality, as opposed to many approximation methods with fixed, non-trained basis functions [11], including random feature models with data-agnostic probability distributions. Regarding networks with more than one hidden layer, E and Wojtowytsch [13; 14] discuss simple examples that are not Barron functions, i.e., cannot be represented by shallow networks. However, they can be represented by deep networks. The convergence rates of over-parameterized networks with one hidden layer is considered in [15], with a comparison to the Monte-Carlo approximation. Fiedler et al. [19] and Fornasier et al. [20] prove that for given, comparatively small networks with one hidden layer, all weights and biases can be recovered exactly by evaluating the network at specific points in the input space. The work of Spek et al. [50] showed a certain duality between weight spaces and data spaces, albeit in a purely theoretical setting. Recent work from Bollt [6] analyzes individual weights in networks by visualizing the placement of ReLU activation functions in space. Weights are also sampled in Bayesian neural networks [43; 4; 21; 51]. The goal is to learn a good posterior distribution and ultimately express uncertainty around both weights and the output of the network. These methods are computationally often on par with or worse than iterative optimization. Most relevant to our work is the weight construction method by Galaris et al. [22], who proposed to use pairs of data points to construct weights. Their primary goal was to randomly sample weights that nevertheless capture a potentially low-dimensional structure in the data. No further analysis was provided, and only a uniform distribution over the data pairs was used. ## 3 Mathematical framework We introduce sampled networks, which are neural networks where for all hidden layers, each pair of weight and bias is completely determined by two points from the input space. This duality between weights and data has been shown theoretically [50], here, we provide an explicit relation. The weights are informed by the difference between the two points, and the bias is the inner product between the weight and one of the two points. After the weights and biases of the hidden layers are constructed, we must only solve an optimization problem for the coefficients of a linear layer, mapping the output from the last hidden layer to the final output. To formalize the construction of sampled networks, we start by introducing some notation. Let \(\mathcal{X}\subseteq\mathbb{R}^{D}\) be the input space, and \(\Phi\) a neural network with \(L\) hidden layers, parameters \(\{W_{l},b_{l}\}_{l=1}^{L+1}\), and activation function \(\phi:\mathbb{R}\rightarrow\mathbb{R}\). We write \(\Phi^{(l)}(x)=\phi(W_{l}\Phi^{(l-1)}(x)-b_{l})\) as the output of the \(l\)th layer, with \(\Phi^{(0)}(x)=x\) for all \(x\in\mathcal{X}\). The two activation functions we focus on in this work are the ReLU (rectified linear unit), \(\phi(x)=\max\{x,0\}\), and the tanh (hyperbolic tangent). We set \(N_{l}\) to be the number of neurons in the \(l\)th layer, with \(N_{0}=D\) and \(N_{L+1}\) as the output dimension. We write \(w_{l,i}\) for the \(i\)th row of \(W_{l}\) and \(b_{l,i}\) for the \(i\)th entry of \(b_{l}\). Building upon work of Galaris et al. [22], we now introduce sampled networks. We start with an arbitrary probability distribution over pairs of data points, and later refine it to include known function values. **Definition 1**.: _Let \(\Phi\) be a neural network with \(L\) hidden layers. For \(l=1,\ldots,L\), let \((x_{0,i}^{(1)},x_{0,i}^{(2)})_{i=1}^{N_{l}}\) be pairs of points sampled over \(\mathcal{X}\times\mathcal{X}\). We say \(\Phi\) is a sampled network if the weights and biases of every layer \(l=1,2,\ldots,L\) and neurons \(i=1,2,\ldots,N_{l}\), are of the form_ \[w_{l,i}=s_{1}\frac{x_{l-1,i}^{(2)}-x_{l-1,i}^{(1)}}{\|x_{l-1,i}^{(2)}-x_{l-1, i}^{(1)}\|^{2}},\quad b_{l,i}=\langle w_{l,i},x_{l-1,i}^{(1)}\rangle+s_{2} \tag{1}\] _where \(s_{1},s_{2}\in\mathbb{R}\) are constants, and \(x_{l-1,i}^{(j)}=\Phi^{(l-1)}(x_{0,i}^{(j)})\) for \(j=1,2\) and \(x_{l-1,i}^{(1)}\neq x_{l-1,i}^{(2)}\). The last set of weights and biases are \(W_{L+1},b_{L+1}=\arg\min\mathcal{L}(W_{L+1}\Phi^{(L)}(\cdot)-b_{L+1})\), where \(\mathcal{L}\) is a suitable loss._ The scalars are used to fix what values the points \(x^{(1)},x^{(2)}\) take on when the activation function is applied; cf. Figure 2. For ReLU, we set \(s_{1}=1\) and \(s_{2}=0\), to let \(x^{(1)}\) be mapped to zero and \(x^{(2)}\) to one. For tanh, we set \(s_{1}=2s_{2}\) and \(s_{2}=\ln(3)/2\), which implies \(x^{(1)}\) and \(x^{(2)}\) are mapped to \(\mp 1/2\) respectively, and the midpoint between the two points is assigned to zero. We choose the constants such that in a regression problem with ReLU, we linearly interpolate values between the two points. For classification, the tanh construction introduces a boundary if \(x^{(1)}\) belongs to a different class than \(x^{(2)}\). We will use this idea later to define a useful distribution over pairs of points (cf. Definition 2). The space of functions that sampled networks can approximate is not immediately clear. First, we are only using points in the input space to construct both the weights and the biases, instead of letting them take on any value. Second, there is a dependence between the bias and the direction of the weight. Third, for deep networks, the sampling space changes after each layer. These apparent restrictions require investigation into which functions we can approximate. We assume that the input space in Theorem 1 and Theorem 2 extends into its ambient space \(\mathbb{R}^{D}\) as follows. Let \(\mathcal{X}^{\prime}\) be any compact space of \(\mathbb{R}^{D}\) with reach \(\tau>0\). We then set the input space \(\mathcal{X}\) to be the space of points including \(\mathcal{X}^{\prime}\) and those that are at most \(\epsilon_{I}\) away from \(X^{\prime}\), given the canonical distance of \(\mathbb{R}^{D}\), where \(0<\epsilon_{I}<\tau\). In Theorem 1, we also consider \(L\) layers to show that the construction of weights in deep networks does not destroy the space of functions that networks with one hidden layer can approximate, even though we alter the space of weights we can construct when \(L>1\). **Theorem 1**.: _For any number of layers \(L\in\mathbb{N}_{>0}\), the space of sampled networks with \(L\) hidden layers, \(\Phi\colon\mathcal{X}\rightarrow\mathbb{R}^{N_{L+1}}\), with activation function ReLU is dense in \(C(\mathcal{X},\mathbb{R}^{N_{L+1}})\)._ _Sketch of proof:_ We show that the possible biases that sampled networks can produce are all we need inside a neuron, and the rest can be added in the last linear part and with additional neurons. We then show that we can approximate any neural network with one hidden layer with at most \(6\cdot N_{1}\) neurons Figure 2: Placement of the point pairs \(x^{(1)},x^{(2)}\) for activation functions ReLU (left) and tanh (right). -- which is not much, considering the cost of sampling versus backpropagation. We then show that we can construct weights so that we preserve the information of \(\mathcal{X}\) through the first \(L-1\) layers, and then we use the arbitrary width result applied to the last hidden layer. The full proof can be found in Appendix A.1. We also proved similar results for the case of tanh activation function with one hidden layer. The proof differs fundamentally because tanh is not positive homogeneous. We now show existence of sampled networks for which the \(L^{2}\) approximation error of Barron functions is bounded (cf. Theorem 2). We later demonstrate that we can actually construct such networks (cf. Section 4.1). The Barron space [1, 16] is defined as \[\mathcal{B}=\{f\colon f(x)=\int_{\Omega}w_{2}\phi(\langle w_{1},x\rangle-b)d \mu(b,w_{1},w_{2})\text{ and }\|f\|_{\mathcal{B}}<\infty\}\] with \(\phi\) being the ReLU function, \(\Omega=\mathbb{R}\times\mathbb{R}^{D}\times\mathbb{R}\), and \(\mu\) being a probability measure over it. The Barron norm is defined as \(\|f\|_{\mathcal{B}}=\inf_{\mu}\max_{(b,w_{1},w_{2})\in\text{supp}(\mu)}\{|w_{ 2}|(\|w_{1}\|_{1}+|b|)\}\). **Theorem 2**.: _Let \(f\in\mathcal{B}\) and \(\mathcal{X}=[0,1]^{D}\). For any \(N_{1}\in\mathbb{N}_{>0}\), \(\epsilon>0\), and an arbitrary probability measure \(\pi\), there exist sampled networks \(\Phi\) with one hidden layer, \(N_{1}\) neurons, and ReLU activation function, such that_ \[\|f-\Phi\|_{2}^{2}=\int_{\mathcal{X}}\lvert f(x)-\Phi(x)\rvert^{2}d\pi(x)< \frac{(3+\epsilon)\|f\|_{\mathcal{B}}^{2}}{N_{1}}.\] _Sketch of proof:_ It quickly follows from the results of E et al. [16], which showed it for regular neural networks, and Theorem 1. The full proof can be found in Appendix A.2. Up until now, we have been concerned with the space of sampling networks, but not with the distribution of the parameters. We found that the following distribution works well, putting emphasis on points that are close and differ a lot with respect to the output of the true function. The norms used to define the densities are arbitrary over their given space, denoted by the subscript. **Definition 2**.: _Let \(\mathcal{X}\) be the input space, and let \(\mathcal{Y}=f(\mathcal{X})\) be given function values. Let \(P\) be a continuous probability distribution defined through its conditional distribution with density \(p\), for \(l=1,2,\ldots,L\) and \(x_{0}^{(1)},x_{0}^{(2)}\in\mathcal{X}\), setting \(x_{l-1}^{(1)},x_{l-1}^{(2)}=\Phi^{(l-1)}(x_{0}^{(1)}),\Phi^{(l-1)}(x_{0}^{(2)})\),_ \[p\left(x_{0}^{(1)},x_{0}^{(2)}\mid\{W_{j},b_{j}\}_{j=1}^{l-1}\right)\propto \begin{cases}\frac{\|f(x_{0}^{(2)})-f(x_{0}^{(1)})\|_{\mathcal{Y}}}{\|x_{l-1}^ {(2)}-\ x_{l-1}^{(1)}\|_{\mathcal{X}_{l-1}}},&x_{l-1}^{(1)}\neq x_{l-1}^{(2)} \\ 0,&\text{otherwise},\end{cases} \tag{2}\] _where \(\Phi^{(l-1)}(\cdot)\) is the sampled network up to layer \(l-1\) with parameters \(\{W_{j},b_{j}\}_{j=1}^{l-1}\), and \(\mathcal{X}_{l-1}=\Phi^{(l-1)}(\mathcal{X})\)._ The conditional distribution \(P\) is defined over pairs of points, but as the network parameters are uniquely identified by these points through Definition 1, it is also a distribution over these parameters. Using this distribution also comes with the benefit that sampling and training are not affected by rigid body transformations (affine transformation with orthogonal matrix) and scaling, as long as the transformation is invariant with respect to the true function. If \(H\) is such a transformation, we say it is equivariant with respect to \(f\), if there exists a scalar and rigid body transformation \(H^{\prime}\) such that \(H^{\prime}f(x)=f(H(x))\) for all \(x\in\mathcal{X}\), and invariant if \(H^{\prime}\) is the identity function. We also assume that norms \(\|\cdot\|_{\mathcal{Y}}\) and \(\|\cdot\|_{\mathcal{X}_{0}}\) in Equation (2) are such that orthogonal matrix multiplication is an isometry. **Theorem 3**.: _Let \(f\) be the target function and \(H\) be a scalar and rigid body transformation, equivariant with respect to \(f\). If we have two sampled networks, \(\Phi,\hat{\Phi}\), with the same number of hidden layers \(L\) and neurons \(N_{1},\ldots,N_{L}\), where \(\Phi\colon\mathcal{X}\to\mathbb{R}^{N_{L+1}}\) and \(\hat{\Phi}\colon H(\mathcal{X})\to\mathbb{R}^{N_{L+1}}\), then the following statements hold:_ 1. _If_ \(\hat{x}_{0,i}^{(1)}=H(x_{0,i}^{(1)})\) _and_ \(\hat{x}_{0,i}^{(2)}=H(x_{0,i}^{(2)})\)_, for all_ \(i=1,2,\ldots,N_{1}\)_, then_ \(\Phi^{(1)}(x)=\hat{\Phi}^{(1)}(H(x))\)_, for all_ \(x\in\mathcal{X}\)_._ 2. _If_ \(H\) _is invariant w.r.t._ \(f\)_, then for any parameters of_ \(\Phi\)_, there exists parameters of_ \(\hat{\Phi}\) _such that_ \(\Phi(x)=\hat{\Phi}(H(x))\) _for all_ \(x\in\mathcal{X}\)_, and vice versa._ _._ 3. _The probability measure_ \(P\) _over the parameters is invariant under_ \(H\)_._ _Sketch of proof:_ Any neuron in the sampled network can be written as \(\phi(\langle s_{1}\frac{w}{\|w\|^{2}},x-x^{(1)}\rangle-s_{2})\). As we divide by the square of the norm of \(w\), the scalar in \(H\) cancels. There is a difference between two points in both inputs of \(\langle\cdot,\cdot\rangle\), which means the translation cancels. Orthogonal matrices cancel due to isometry. When \(H\) is invariant with respect to \(f\), the loss function is also unchanged and lead to the same output. Similar argument is made for \(P\), and the theorem follows. The complete proof can be found in Appendix A.3. If the input space is embedded in a larger ambient space \(\mathbb{R}^{D^{\prime}}\), with \(D<D^{\prime}\), we sample from a subspace with dimension \(\tilde{D}=\dim(\overline{\operatorname{span}\{\mathcal{X}\}})\leq D^{\prime}\). All the results presented in this section still hold due to orthogonal decomposition. However, the standard approach of backpropagation and initialization allows the weights to take on any value in \(\mathbb{R}^{D^{\prime}}\), which implies a lot of redundancy when \(\tilde{D}\ll D^{\prime}\). The biases are also more relevant to the input space than when initialized to zero -- potentially avoiding the issues highlighted by Holzmuller and Steinwart [27]. For these reasons, we have named the proposed method Sampling Where It Matters (SWIM), which is summarized in Algorithm 1. For computational reasons, we consider a random subset of all possible pairs of training points when sampling weights and biases. The subset size can be changed depending on the size of the training set and the number of neurons. ``` Constant:\(\boldsymbol{\epsilon}\in\mathbb{R}_{>0}\), \(\varsigma\in\mathbb{N}_{>0}\), \(L\in\mathbb{N}_{>0}\), \(\{N_{l}\in\mathbb{N}_{>0}\}_{l=1}^{L+1}\), and \(s_{1},s_{2}\in\mathbb{R}\) Data:\(X=\{x_{i}\colon x_{i}\in\mathbb{R}^{D},i=1,2,\ldots,M\}\), \(Y=\{y_{i}\colon f(x_{i})=y_{i}\in\mathbb{R}^{N_{L+1}},i=1,2,\ldots,M\}\) \(\Phi^{(0)}(x)=x\); for\(l=1,2,\ldots,L\)do \(\tilde{M}\leftarrow\varsigma\cdot\lceil\frac{N}{M}\rceil\cdot M\) ; \(P^{(l)}\in\mathbb{R}^{M}\); \(\tilde{X}=\{(x_{i}^{(1)},x_{i}^{(2)})\colon\Phi^{(l-1)}(x_{i}^{(1)})\neq\Phi^{ (l-1)}(x_{i}^{(2)})\}_{i=1}^{\tilde{M}}\sim\text{Uniform}(X\times X)\); for\(i=1,2,\ldots,\tilde{M}\)do \(\tilde{x}_{i}^{(1)},\tilde{x}_{i}^{(2)}\leftarrow\Phi^{(l-1)}(x_{i}^{(1)}), \Phi^{(l-1)}(x_{i}^{(2)})\); \(\tilde{y}_{i}^{(1)},\tilde{y}_{i}^{(2)}=f(x_{i}^{(1)}),f(x_{i}^{(2)})\); \(P_{i}^{(l)}\leftarrow\frac{\|\tilde{y}_{i}^{(2)}-\tilde{y}_{i}^{(1)}\|_{ \mathcal{Y}}}{\max\{\|\tilde{x}_{i}^{(2)}-\tilde{x}_{i}^{(1)}\|_{\mathcal{X}_ {i-1}}\epsilon\}}\); end for\(W_{l}\in\mathbb{R}^{N_{l},N_{l-1}},b_{l}\in\mathbb{R}^{N_{l}}\); for\(k=1,2,\ldots,N_{l}\)do Sample \((x^{(1)},x^{(2)})\) from \(\tilde{X}\), with replacement and with probability proportional to \(P^{(l)}\); \(\tilde{x}^{(1)},\tilde{x}^{(2)}\leftarrow\Phi^{(l-1)}(x^{(1)}),\Phi^{(l-1)}(x ^{(2)})\); \(W_{l}^{(k;\cdot)}\gets s_{1}\frac{\tilde{x}^{(2)}-\tilde{x}^{(1)}}{\| \tilde{x}^{(2)}-\tilde{x}^{(1)}\|}\hat{x}_{l}^{(1)}\hat{x}_{l}^{(k)}\gets \langle W_{l}^{(k;\cdot)},\tilde{x}^{(1)}\rangle+s_{2}\); end for\(\Phi^{(l)}(\cdot)\leftarrow\phi(W_{l}\,\Phi^{(l-1)}(\cdot)-b_{l})\); end for\(W_{L+1},b_{L+1}\leftarrow\operatorname*{arg\,min}_{\mathcal{L}}(\Phi^{(L)} (X),Y)\); return\(\{W_{l},b_{l}\}_{l=1}^{L+1}\) ``` **Algorithm 1**The SWIM algorithm, for activation function \(\phi\), and norms on input, output of the hidden layers, and output space, \(\|\cdot\|_{\mathcal{X}_{0}}\),\(\|\cdot\|_{\mathcal{X}_{l}}\), and \(\|\cdot\|_{\mathcal{Y}}\) respectively. Also, \(\mathcal{L}\) is a loss function, which in our case is always \(L^{2}\) loss, and \(\operatorname*{arg\,min}_{\mathcal{L}}\mathcal{L}(\cdot,\cdot)\) becomes a linear optimization problem. We end this section with a time and memory complexity analysis of Algorithm 1. In Table 1, we list runtime and memory usage for three increasingly strict assumptions. The main assumption is that the dimension of the output is less than or equal to the largest dimension of the hidden layers. This is true for the problems we consider, and the difference in runtime without this assumption is only reflected in the linear optimization part. The term \(\lceil N/M\rceil\) is required because only a subset of points are considered when sampling. For the full analysis, see Appendix F. ## 4 Numerical experiments We now demonstrate the performance of Algorithm 1 on numerical examples. Our implementation is based on the numpy and scipy Python libraries, and we run all experiments on a machine with 32GB system RAM (256GB in Section 4.3 and Section 4.4) and a GeForce 4x RTX 3080 Turbo GPU with 10GB RAM. The Appendix contains detailed information on all experiments. In Section 4.1 we compare sampling to random Fourier feature models, on the approximation of a Barron function. In Section 4.2 we compare classification accuracy of sampled networks to iterative, gradient-based optimization in a classification benchmark with real datasets. In Section 4.3 we demonstrate that more specialized architectures can be sampled, by constructing deep neural architectures as PDE solution operators. In Section 4.4 we show how to use sampling of fully-connected layers for transfer learning. For the probability distribution over the pairs in Algorithm 1, we always choose the \(L^{\infty}\) norm for \(\|\cdot\|_{\mathcal{Y}}\) and for \(l=1,2,\ldots,L\), we choose the \(L^{2}\) norm for \(\|\cdot\|_{\mathcal{X}_{l-1}}\). The code to reproduce the experiments from the paper can be found at [https://gitlab.com/felix.dietrich/swimnetworks-paper](https://gitlab.com/felix.dietrich/swimnetworks-paper) An up-to-date code base is maintained at [https://gitlab.com/felix.dietrich/swimnetworks](https://gitlab.com/felix.dietrich/swimnetworks) ### Illustrative example: approximating a Barron function We compare random Fourier features and our sampling procedure on a test function for neural networks [53]: \(f(x)=\sqrt{3/2}(\|x-a\|-\|x+a\|)\), with \(x\in\mathbb{R}^{D}\) and the constant vector \(a\in\mathbb{R}^{D}\) defined by \(a_{j}=2j/D-1\), \(j=1,2,\ldots,D\). This function is special in that its Barron norm is equal to one for all input dimensions, and it can be represented exactly with an infinitely wide network with one hidden layer, ReLU activation, and weights uniformly distributed on a sphere of radius \(D^{1/2}\). We approximate the function using networks of up to three hidden layers. We compare relative \(L^{2}\) approximation errors over the data domain \(\mathcal{X}=[-1,1]^{2}\) for the three approximation techniques, with \(10,000\) data points sampled uniformly, separately for training and test sets. For a given approximation \(\hat{f}\), the error is defined by \(e^{2}_{\text{rel}}=\sum_{x\in\mathcal{X}}(f(x)-\hat{f}(x))^{2}/\sum_{x\in \mathcal{X}}f(x)^{2}\). For the random feature method, we use \(w\sim N(0,1),\ b\sim U(-\pi,\pi)\), as proposed in [46], and \(\phi=\sin\). For sampling, we also use \(\phi=\sin\) to obtain a fair comparison. Close to \(x=0\), the sine function is similar to \(\tanh\), for which we proved universal approximation. We also observed very similar accuracy results when trying the experiment with the \(\tanh\) function in this example. We iterate over the number of neurons \(m\) in each hidden layers, from \(m=64\) up to \(m=4096\). Figure 3 shows results in \(D=5\) and \(D=10\) (results for \(D=2,3,4\) are similar, and contained in the Appendix B). The sampled networks can be constructed approximately as fast as the random feature method (see Appendix B for the comparison). What we observe is that random features have comparable accuracy for a network with a single hidden layer, but very poor performance for deeper networks. This can be explained by the much larger ambient space dimension of the data after it is processed through the first hidden layer. Conversely, our sampling method can be used to obtain accurate results with more layers, even outperforming the case with one hidden layer. We also observe that the convergence rate at two hidden layers is faster than the theoretical rate in dimensions \(D<10\). \begin{table} \begin{tabular}{c c c} & Runtime & Memory \\ \hline Assumption (I) & \(\mathcal{O}(L\cdot M(\min\{\lceil N/M\rceil,M\}+N^{2}))\) & \(\mathcal{O}(M\cdot\min\{\lceil N/M\rceil,M\}+LN^{2})\) \\ Assumption (II) & \(\mathcal{O}(L\cdot M(\lceil N/M\rceil+N^{2}))\) & \(\mathcal{O}(M\cdot\lceil N/M\rceil+LN^{2})\) \\ Assumption (III) & \(\mathcal{O}(M)\) & \(\mathcal{O}(M)\) \\ \end{tabular} \end{table} Table 1: Runtime and memory requirements for training sampled neural networks with the SWIM algorithm, where \(N=\max\{N_{0},N_{1},N_{2},\ldots,N_{L}\}\). Assumption (I) is that the output dimension is less than or equal to \(N\). Assumption (II) adds that \(N<M^{2}\), i.e., number of neurons and input dimension is less than the size of dataset squared. Assumption (III) requires a fixed architecture. ### Classification benchmark from OpenML We use the "OpenML-CC18 Curated Classification benchmark" [3] to compare our sampling method with the Adam optimizer [31]. With both methods, we separately perform neural architecture search over networks with \(500\) neurons in all of their hidden layers, with the number of hidden layers from \(1\) to \(5\). We evaluate each architecture with 10-fold cross-validation. Pre-processing failed in 11 of the 72 datasets contained in the benchmark, and we restricted the maximum number of points to \(5000\) to speed up the cross-validation times. For the Adam optimizer, we employ early stopping with patience=3, monitoring the loss value. The regularization of the least squares problem in sampling was set to \(10^{-10}\). We pre-process the labels of the classification task with one-hot encoding. Figure 4 shows the benchmark results. On all benchmark tasks, sampling networks is faster than training them iteratively (on average, \(30\) times faster). The classification accuracy is comparable (cf. Figure 4, second and third plot). The ideal number of layers for each problem seems to be slightly higher for the Adam optimizer, but in several instances, sampling deeper networks seems to perform better. ### Deep neural operators We sample several deep neural operators and compare their speed and accuracy to iterative gradient-based training of the same architectures. As a test problem, we consider the Burgers' equation on one-dimensional space, \(\frac{\partial u}{\partial t}+u\frac{\partial u}{\partial x}=\nu\frac{ \partial^{2}u}{\partial x^{2}},x\in(0,2\pi),t\in(0,1]\). We use periodic boundary conditions and set the viscosity parameter \(\nu=0.1\). The goal is to predict the solution at \(t=1\) from the initial condition at \(t=0\). Thus, the neural operators we construct will represent the map \(\mathcal{G}:u(x,0)\to u(x,1)\). We generate initial conditions by sampling five Fourier coefficients for the lowest frequencies and restoring the function values from these coefficients. Using a classical numerical solver, we generate 15000 pairs of \((u(x,0),u(x,1))\), and split them into the train (60%), validation (20%), and test sets (20%). Figure 5 shows samples from the generated dataset. #### 4.3.1 Fully-connected network in signal space The first baseline for the task is a fully-connected network (FCN) trained with tanh activation to predict the discretized solution from the discretized initial condition. We trained the classical version using the Adam optimizer and the mean squared error as a loss function. We also performed early Figure 4: Fitting time, accuracy, and number of layers using weight sampling, compared to training with the Adam optimizer. The best architecture is chosen separately for each method and each problem, by evaluating 10-fold cross-validation error over \(1\)-\(5\) layers with 500 neurons each. Figure 3: Relative \(L^{2}\) approximation error of a Barron function (test set), using random features and sampling, both with sine activation. Left: input dimension \(D=5\). Right: input dimension \(D=10\). stopping based on the mean relative \(L^{2}\)-error on the validation set. **For sampling**, we use Algorithm 1 to construct a fully-connected network with tanh as the activation function. #### 4.3.2 Fully-connected network in Fourier space Similarly to Poli et al. [45], we train a fully-connected network in Fourier space. During training, we perform a Fourier transform on the initial condition and the solution, keeping only the lowest frequencies of the resulting vectors. We then train a standard FCN on the transformed data, as in the previous section. To compute the reported metrics, we apply an inverse Fourier transform to the network predictions and compare them to the original solutions in the dataset. **For sampling**, we split complex coefficients into real and imaginary parts before passing them to the sampled fully-connected layers. We also perform the same pre-processing step for the Adam training, to ensure a fair comparison between the methods. #### 4.3.3 POD-DeepONet The third architecture considered here is a variation of DeepONet, a deep operator network architecture [39]. The original DeepONet consists of two trainable components: the trunk net, which transforms the coordinates of an evaluation point, and the branch net, which transforms the function values on some grid. The outputs of these nets are then combined into the predictions of the whole network \(\mathcal{G}(u)(y)=\sum_{k=1}^{p}b_{k}(u)t_{k}(y)+b_{0},\) where \(u\) is a discretized input function; \(y\) is an evaluation point; \([t_{1},\dots,t_{p}]^{T}\in\mathbb{R}^{p}\) are the \(p\) outputs of the trunk net; \([b_{1},\dots,b_{p}]^{T}\in\mathbb{R}^{p}\) are the \(p\) outputs of the branch net; and \(b_{0}\) is a bias. DeepONet sets no restrictions on the architecture of the two nets, but often the fully-connected networks are used for one-dimensional input. POD-DeepONet proposed by Lu et al. [41] first assumes that evaluation points lie on the input grid. Then, it performs proper orthogonal decomposition (POD) of discretized solutions in the train data and uses its components instead of the trunk net to compute the outputs \(\mathcal{G}(u)(\xi_{j})=\sum_{k=1}^{p}b_{k}(u)\psi_{k}(\xi_{j})\ +\psi_{0}(\xi_{j}).\) Here \([\psi_{1}(\xi_{j}),\dots,\psi_{p}(\xi_{j})]\) are \(p\) precomputed POD components for a point \(\xi_{j}\), and \(\psi_{0}(\xi_{j})\) is the mean of discretized solutions evaluated at \(\xi_{j}\). Hence, only the branch net is trained in POD-DeepONet. We followed Lu et al. [41] and applied scaling of \(1/p\) to the network output when training the model with Adam. **For sampling**, we employ the orthogonality of the components and turn POD-DeepONet into a fully-connected network. Let \(\xi=[\xi_{1},\dots,\xi_{n}]\) be the grid used to discretize the input function \(u\) and evaluate the output function \(\mathcal{G}(u)\). Then we can compute the POD components of the train data \(\Psi(\xi)=[\psi_{1}(\xi),\dots,\psi_{p}(\xi)]\in\mathbb{R}^{n\times p}\) for this grid. If \(b(u)\in\mathbb{R}^{p}\) is the output vector of the trunk net, the POD-DeepONet transformation can be written in matrix form \(\mathcal{G}(u)(\xi)=\Psi b(u)+\psi_{0}(\xi).\) As \(\Psi^{T}\Psi=I_{p}\), we can express the output of the trunk net as \(b(u)=\Psi^{T}(\mathcal{G}(u)(\xi)-\psi_{0}(\xi)).\) Using this equation, we can transform the training data to sample a fully-connected network for \(b(u)\). Similarly to previous cases, we use tanh as the activation function for sampling. #### 4.3.4 Fourier Neural Operator The concept of a Fourier Neural Operator (FNO) was introduced by Li et al. [37] to solve PDEs by performing part of the training in Fourier space. An FNO consists of Fourier blocks, combining a linear operator in the Fourier space and a skip connection in signal space. As a first step, FNO lifts an input signal to a higher dimensional channel space. Let \(v_{t}\in\mathbb{R}^{n\times d_{v}}\) be an input to a Fourier block having \(d_{v}\) channels and discretized with \(n\) points. Then, the output \(v_{t+1}\) of the Fourier block is computed as \(v_{t+1}=\phi(F_{k}^{-1}(R\cdot F_{k}(v_{t}))+W\circ v_{t})\in\mathbb{R}^{n\times d _{v}}.\) Here, \(F_{k}\) is a discrete Fourier transform keeping only the \(k\) lowest frequencies and \(F_{k}^{-1}\) is the corresponding inverse transform; \(\phi\) is an activation function; \(\cdot\) is a spectral convolution; \(\circ\) is a \(1\times 1\) convolution with bias; and \(R\in\mathbb{C}^{k\times d_{v}\times d_{v}}\), \(W\in\mathbb{R}^{d_{v}\times d_{v}}\) are learnable parameters. FNO stacks several Fourier blocks and then projects the output signal to the target dimension. The projection operator, as well as the lifting operator, are usually parameterized with neural networks. **For sampling**, the construction of convolution kernels is not possible yet, so we cannot sample FNO directly. Instead, we use the general idea of FNO to construct a comparably accurate neural operator. Similarly to the original FNO, we append grid coordinates to the input signal before the lifting operation. Then, we draw the weights from a uniform distribution on [-1, 1] to compute the \(1\times 1\) lifting convolution. We also normalize the input data before the lifting. We first apply the Fourier transform to both input and target data, and then train a fully-connected network for each channel in Fourier space. We also use skip connections, as in the original FNO, by removing the input data from the lifted target function during training, and then re-adding it before moving to the output of the block. After sampling and transforming the input data with the sampled networks in Fourier space, we apply the inverse Fourier transform. After the Fourier block(s), we sample a fully-connected network that maps the signal to the solution. The results of the experiments in Figure 5 show that sampled models are comparable to the Adam-trained ones. The sampled FNO model does not directly follow the original FNO architecture, as we are able to only sample fully-connected layers. This shows the advantage of gradient-based methods: as of now, they are applicable to much broader use cases. These experiments showcase one of the main advantages of sampled networks: speed of training. We run sampling on the CPU; nevertheless, we see a significant speed-up compared to Adam training performed on GPU. ### Transfer learning Training deep neural networks from scratch involves finding a suitable neural network architecture [17] and hyper-parameters [2; 55]. Transfer learning aims to improve performance on the target task by leveraging learned feature representations from the source task. This has been successful in image classification [30], multi-language text classification, and sentiment analysis [52; 7]. Here, we compare the performance of sampling with iterative training on an image classification transfer learning task. We choose the CIFAR-10 dataset [34], with 50000 training and 10000 test images. Each image has dimension \(32\times 32\times 3\) and must be classified into one of the ten classes. For this task, we consider ResNet50 [26], VGG19 [49], and Xception [9], all pre-trained on the ImageNet dataset [47]. We freeze the weights of all convolutional layers of these models and append two fully connected layers: one hidden layer and one output layer. We refer to these two layers as the classification head, which we sample with Algorithm 1 and compare the classification accuracy against iterative training with the Adam optimizer. Figure 5: Left: Samples of initial conditions \(u_{0}\) and the corresponding solutions \(u_{1}\) for the Burgers’ equation. Right: Parameters of the best model for each architecture, the mean relative \(L^{2}\) error on the test set, and the time required to train this model. We average the metrics across three runs with different random seeds. Figure 6: Left: Train and test accuracies with different widths for ResNet50 (averaged over 5 random seeds). Middle: Test accuracy with different models with and without fine-tuning (width = 2048). Right: Adam training and sampling times of the classification head (averaged over 5 experiments). Figure 6 (left) shows that for a pre-trained ResNet50, the test accuracy using the sampling approach is higher than the Adam training approach for a width greater than 1024. We observe similar qualitative behavior for VGG19 and Xception (figures in Appendix E). Figure 6 (middle) shows that the sampling approach results in a higher test accuracy with all three pre-trained models. Furthermore, the deviation in test accuracy obtained with the sampling algorithm is very low, demonstrating that the sampling approach is more robust to changing random seeds than iterative training. After fine-tuning the whole neural network with the Adam optimizer with a learning rate of \(10^{-5}\), the test accuracies of the sampled networks are close to the iterative approach. The highest test accuracy is obtained by sampling the classification head of the pre-trained Xception architecture, followed by fine-tuning. Thus, the sampled weights provide a good starting point for fine-tuning the entire model (a comparison of sampling and training approaches for the three models before and after fine-tuning for different widths is contained in Appendix E). Figure 6 (right) shows that the sampling approach can be up to 2 orders of magnitude faster than iterative training for lower widths, and is around 10 times faster for a width of 2048. In summary, Algorithm 1 is much faster than iterative training, yields a higher test accuracy for certain widths before fine-tuning, and is more robust with respect to changing random seeds. The sampled weights also provide a good starting point for the fine-tuning of the entire model. ## 5 Broader Impact Sampling weights through data pairs at large gradients of the target function offers improvements over random feature models. In terms of accuracy, networks with relatively large widths can even be competitive to iterative, gradient-based optimization. Constructing the weights through pairs of points also allows to sample deep architectures efficiently. Sampling networks offers a straightforward interpretation of the internal weights and biases, namely, which data pairs are important during sampling. Given the recent critical discussions around faster advancements in artificial intelligence, publishing work that potentially speeds up the development (concretely, training speed) in this area by orders of magnitude may seem irresponsible. The solid mathematical underpinning of random feature models and, now, sampled networks, combined with much greater interpretability of the individual steps during network construction, should mitigate some of these concerns. ## 6 Conclusion We present a data-driven sampling method for fully-connected neural networks that outperforms random feature models in terms of accuracy, and in many cases is competitive to iterative optimization. The time to obtain a trained network is orders of magnitude faster compared to iterative, gradient-based optimization. In addition, much fewer hyperparameters need to be optimized as well, mostly the regularization constant, as opposed to learning rate, number of training epochs, and type of optimizer. Several open issues remain, we list the most pressing here. Many architectures like convolutional or transformer networks cannot be sampled with our method yet, and thus must still be trained with iterative methods. Implicit problems, such as the solution to PDE without any training data, are a challenge, as our distribution over the data pairs relies on known function values from a supervised learning setting. Iteratively refining an initially random guess may prove useful here. On the theory side, convergence rates for Algorithm 1 beyond the default Monte-Carlo estimate are not available yet, but are important for robust applications in engineering. In the future, hyperparameter optimization, including neural architecture search, could benefit from improved training time of sampled networks. We already demonstrate benefits for transfer learning, which can now be exploited for other pre-trained models and tasks. Analyzing which data pairs are sampled during training may help to understand the datasets better. We did not show that our sampling distribution is optimal, so there is a possibility of even more efficient heuristics. Applications in scientific computing may benefit most from sampling networks, as data is often abundant, but accuracy and speed requirements are much higher than for classical tasks in machine learning. ## Acknowledgments and Disclosure of Funding The authors are grateful for discussions with Erik M. Bollt and Constantinos Siettos. E.B., I.B., and F.D. are funded by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) - project no. 468830823. C.D. is partially funded by the Institute for Advanced Study (IAS) at the Technical University of Munich. Q.S. is supported by the TUM Georg Nemetschek Institute - Artificial Intelligence for the Built World.