Datasets:
Tasks:
Question Answering
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
100K - 1M
ArXiv:
License:
Add files using upload-large-folder tool
Browse filesFiles changed (50)
- md/train/2F_wnaioS6/2F_wnaioS6.mdAdded+250
- md/train/9DlCh34E1bN/9DlCh34E1bN.mdAdded+296
- md/train/AVx0r_GppCu/AVx0r_GppCu.mdAdded+461
- md/train/B1l6y0VFPr/B1l6y0VFPr.mdAdded+687
- md/train/BJC8LF9ex/BJC8LF9ex.mdAdded+375
- md/train/BJlVNY8llV/BJlVNY8llV.mdAdded+240
- md/train/BJxI5gHKDr/BJxI5gHKDr.mdAdded
- md/train/BkeqO7x0-/BkeqO7x0-.mdAdded+475
- md/train/BkxAUjRqY7/BkxAUjRqY7.mdAdded+569
- md/train/ByxRM0Ntvr/ByxRM0Ntvr.mdAdded
- md/train/CMsvjAnW1zE/CMsvjAnW1zE.mdAdded
- md/train/D8-iwC9UN3/D8-iwC9UN3.mdAdded+608
- md/train/EQbyD_KG6w-1h/EQbyD_KG6w-1h.mdAdded+258
- md/train/H11lAfbCW/H11lAfbCW.mdAdded+275
- md/train/HJnQJXbC-/HJnQJXbC-.mdAdded+268
- md/train/Hk91SGWR-/Hk91SGWR-.mdAdded+200
- md/train/HkenPn4KPH/HkenPn4KPH.mdAdded+322
- md/train/HkgTkhRcKQ/HkgTkhRcKQ.mdAdded+742
- md/train/Hkn7CBaTW/Hkn7CBaTW.mdAdded+492
- md/train/Hyg1G2AqtQ/Hyg1G2AqtQ.mdAdded
- md/train/S1gfu3EtDr/S1gfu3EtDr.mdAdded
- md/train/SJDaqqveg/SJDaqqveg.mdAdded
- md/train/SJgMK64Ywr/SJgMK64Ywr.mdAdded
- md/train/SJlPOCEKvH/SJlPOCEKvH.mdAdded
- md/train/SJxeI6EYwS/SJxeI6EYwS.mdAdded
- md/train/Sk7KsfW0-/Sk7KsfW0-.mdAdded
- md/train/Skh4jRcKQ/Skh4jRcKQ.mdAdded
- md/train/SyMWn05F7/SyMWn05F7.mdAdded
- md/train/T1STW1NYYKW/T1STW1NYYKW.mdAdded
- md/train/U7vVeHydyR/U7vVeHydyR.mdAdded
- md/train/jtrQswOMLrd/jtrQswOMLrd.mdAdded
- md/train/mrsx7ninrtU/mrsx7ninrtU.mdAdded
- md/train/ogciCC6fmBl/ogciCC6fmBl.mdAdded
- md/train/qGeqg4_hA2/qGeqg4_hA2.mdAdded
- md/train/r1GAsjC5Fm/r1GAsjC5Fm.mdAdded
- md/train/r1lohoCqY7/r1lohoCqY7.mdAdded
- md/train/rJg8yhAqKm/rJg8yhAqKm.mdAdded
- md/train/rJl8FoRcY7/rJl8FoRcY7.mdAdded
- md/train/rke41hC5Km/rke41hC5Km.mdAdded
- md/train/rkgMkCEtPB/rkgMkCEtPB.mdAdded
- md/train/rklp93EtwH/rklp93EtwH.mdAdded
- md/train/rm0I5y2zkG8/rm0I5y2zkG8.mdAdded
- md/train/ryxnHhRqFm/ryxnHhRqFm.mdAdded
- md/train/sjuuTm4vj0/sjuuTm4vj0.mdAdded
- md/train/uCQfPZwRaUu/uCQfPZwRaUu.mdAdded
- md/train/uIc4W6MtbDA/uIc4W6MtbDA.mdAdded
- md/train/uKhGRvM8QNH/uKhGRvM8QNH.mdAdded
- md/train/wZrOOO9XBn/wZrOOO9XBn.mdAdded
- md/train/yH2VrkpiCK6/yH2VrkpiCK6.mdAdded
- md/train/yxafu6ZtUux/yxafu6ZtUux.mdAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# A Hierarchical Reinforcement Learning Based Optimization Framework for Large-scale Dynamic Pickup and Delivery Problems
Yi $\mathbf { M } \mathbf { a } ^ { 1 }$ ∗, Xiaotian Hao1∗, Jianye $\mathbf { H } \mathbf { a } \mathbf { o } ^ { 1 2 }$ †, Jiawen $\mathbf { L } \mathbf { u } ^ { 2 }$ , Xing Liu2, Xialiang $\mathbf { T o n g } ^ { 2 }$ , Mingxuan Yuan2, Zhigang $\mathbf { L i } ^ { 1 }$ , Jie $\mathbf { T a n g } ^ { 3 }$ , Zhaopeng Meng1 1College of Intelligence and Computing, Tianjin University {mayi,xiaotianhao, jianye.hao, scs_lzg, mengzp} $@$ tju.edu.cn 2Noah’s Ark Lab, Huawei, {jiawen.lu, tongxialiang, Yuan.Mingxuan} $@$ huawei.com 3Tsinghua University, jietang $@$ tsinghua.edu.cn
# Abstract
The Dynamic Pickup and Delivery Problem (DPDP) is an essential problem in the logistics domain, which is NP-hard. The objective is to dynamically schedule vehicles among multiple sites to serve the online generated orders such that the overall transportation cost could be minimized. The critical challenge of DPDP is the orders are not known a priori, i.e., the orders are dynamically generated in real-time. To address this problem, existing methods partition the overall DPDP into fixed-size sub-problems by caching online generated orders and solve each sub-problem, or on this basis to utilize the predicted future orders to optimize each sub-problem further. However, the solution quality and efficiency of these methods are unsatisfactory, especially when the problem scale is very large. In this paper, we propose a novel hierarchical optimization framework to better solve large-scale DPDPs. Specifically, we design an upper-level agent to dynamically partition the DPDP into a series of sub-problems with different scales to optimize vehicles routes towards globally better solutions. Besides, a lower-level agent is designed to efficiently solve each sub-problem by incorporating the strengths of classical operational research-based methods with reinforcement learning-based policies. To verify the effectiveness of the proposed framework, real historical data is collected from the order dispatching system of Huawei Supply Chain Business Unit and used to build a functional simulator. Extensive offline simulation and online testing conducted on the industrial order dispatching system justify the superior performance of our framework over existing baselines.
# 1 Introduction
The Dynamic Pickup and Delivery Problem (DPDP) constitutes an important family of routing problems, which generally contains three key elements: orders, goods and vehicles as shown in Figure 1. Orders are generated in real-time. Different orders contain different types and quantities of goods. A number of vehicles are scheduled to serve the orders by transporting the desired goods from different origins to different destinations. The objective of DPDP is to dynamically assign each order to the most appropriate vehicle so that the overall transportation cost (e.g., overall distances) could be minimized. DPDPs are widespread in order dispatching systems of the supply chain, express mail delivery services and elsewhere.
DPDP is a complex variant of the Travelling Salesman Problem (TSP) and Vehicle Routing Problem (VRP), which are both NP-Hard combinatorial optimization problems [25]. The main difficulty of DPDP comes from the dynamically generated orders in real-time, thus the order dispatching decisions cannot be made beforehand in an offline style. Besides, compared with TSP and VRP, there exist various additional complex constraints in DPDP such as pickup and delivery constraint, Last-In-First-Out (LIFO) constraint, time window constraint, split demand constraint, etc.
Traditional methods for DPDP. Existing solutions for DPDP fall into two categories. The first category maintains a fixed buffer to cache the most recent generated orders and periodically dispatches all cached orders in a delayed mode. By this way, the overall dynamic problem is partitioned into a series of static sub-problems with subsets of known orders, i.e., static Pickup and Delivery Problems (PDPs). Then, operational research-based (OR) methods [22, 20], heuristic and
 Figure 1: Demonstration of DPDP
meta-heuristic methods [7, 16, 25, 4, 5, 3, 11, 26, 23, 9] are designed to solve each sub-problem. However, myopically optimizing each static sub-problem cannot guarantee the overall dynamic problem could be optimized from a long-term perspective since the split sub-problems are not independent of each other. The main reasons are previous orders assignment results will influence (1) the number of remaining orders to be dispatched, (2) the vehicle’s remaining capacity and (3) the relative positions to the following orders. To acquire better solutions, the second category methods [24, 8, 12] try to predict the distribution of future orders and take the predicted orders into consideration when computing the solution for each sub-problem. However, predicting future orders is not realistic due to the high uncertainty in the real world. Inaccurate predictions will mislead the order dispatcher and route planner, and result in poor solution quality.
Learning-based methods for VRP. Additionally, a common flaw of traditional OR and metaheuristic methods is that they are computationally expensive and normally unable to obtain a desired solution within the allowable time. Besides, the design of them heavily relies on complex domain knowledge. To improve the solution computing efficiency and ease the difficulty of the algorithm design, recently, several learning-based methods are proposed [27, 1, 18, 6, 13]. These methods have demonstrated that the solution computing efficiency can be significantly improved by leveraging the generalization ability of the trained models. Besides, they could obtain solutions with competitive qualities compared with the state-of-the-art traditional methods. Although these methods mainly focus on TSPs or VRPs, of which all orders’ information is known in advance and much fewer constraints are considered comparing with DPDP, learning-based methods have shown great potential to help solve large-scale DPDPs and reach superior performance.
In this paper, we propose a novel hierarchical reinforcement learning (RL) based optimization framework to solve the real-world large-scale DPDPs. Considering that order dispatching has a longterm impact on the overall optimization objective, the upper-level RL agent dynamically determines whether to wait longer at each moment for caching more future orders. In this way, the orders can be more flexibly assigned to vehicles (since each vehicle will have more candidate orders to choose) and the routes of vehicles could be optimized towards globally better solutions. The lower-level RL agent is responsible for assigning the cached orders to the most appropriate vehicles by sequentially manipulating heuristic operators to improve the solution quality iteratively. To verify the effectiveness of the framework, we collected real historical data from the order dispatching system of Huawei Supply Chain and built a simulator to simulate the order dispatching and vehicle transportation process. Further, we deployed our method on the company’s Supply Chain Business Unit. Extensive offline simulation and online testing showed the superior performance of our algorithm.
Our main contributions are as follows:
• We are the first to propose a practical hierarchical RL framework to efficiently and farsightedly compute superior solutions for the real-world large-scale DPDPs with complex constraints. • We design a simulator using real industrial data to be the experimental benchmark to verify the proposed method, which is available here for interested researchers. • We show that our approach considerably improves the optimization objectives compared with existing algorithms both in the offline evaluation and online testing. The ablation study indicates our approach can obtain high-quality solutions with fast running speed and has strong generalization ability.
# 2 Problem Formulation
We now give the formulation of DPDP in our logistics scenario. For the orders dynamically generated in real-time at different nodes (i.e., factories and warehouses) within a day, vehicles should be scheduled to transport the goods from pickup nodes to delivery nodes to fulfil the orders with minimal transportation cost. In our case, the objective is to minimize $K$ vehicles average travelling distances $D ( K )$ of the entire DPDP:
$$\operatorname* { m i n } D ( K )$$
while meeting several constraints: Pickup and Delivery Constraint, Capacity Constraint, LIFO Constraint, Time Window Constraint, etc. Detailed constraints are shown in Appendix A.
In practice, however, some orders are destined to violate time window constraints2. Thus, we add it to the objective function as an associated penalty to convert the hard time window constraint to a soft one. The penalty function is defined as the overtime beyond the specified completion time of each order. The optimization objective is then reformulated as minimizing the weighted sum 3 of average vehicles travelling distances (kilometers) $D ( K )$ and total overtime (seconds) $O T$ of all orders $C$ :
$$\operatorname* { m i n } D ( K ) + \lambda * O T ( C )$$
Apart from the various complex constraints mentioned above, the additional difficulties of this problem mainly come from two aspects:
(1) The problem scale is very large. In practical logistic scenarios of the company, millions of products and intermediate materials are manufactured every day. As these products and materials might be used in the subsequent phases (e.g., assembling or selling), they have to be scheduled and transported between hundreds of factories and warehouses by dozens of vehicles within stringent timeline constraints, which constitutes a very large-scale and complex DPDP. (2) Besides, as the orders are generated online in real-time, the schedule planning cannot be made aforehand in an offline style. From the oracle’s point of view, i.e., when all orders of a day are known in advance, the uncertainty is eliminated and this DPDP can be formulated as a complex Mixed Integer Programming (MIP) Problem, of which the optimal solution could be obtained utilizing exact algorithms (e.g., cutting plane algorithms, branch-and-bound algorithms or modern solvers such as Gurobi[20]) [22]. However, in reality, it’s impossible to know all the orders in advance, thus these approaches are not applicable.
To eliminate the uncertainties brought by the unknown orders, a practical way is to utilize a buffer to cache the most recent generated orders and periodically dispatches all cached orders in a little delayed mode. With the known orders in the cache, the static PDP can be formulated as an MIP as shown in Appendix A. We could resort to modern solvers to solve this MIP. However, even for the static PDP with very few orders, it still costs several hours to compute a feasible solution, which is beyond the acceptable limits (details are shown in Table 2 and 3). Besides, even if we could obtain the optimal solution for each fixed split static PDP, we still cannot guarantee the global DPDP can be optimized as these static sub-problems are not independent of each other.
# 3 Method
# 3.1 Overall Framework
 Figure 2: Hierarchical Optimization Framework
In this paper, considering the challenges mentioned above, we propose a novel hierarchical reinforcement learning based optimization framework, which contains two levels of agents. As shown in Figure 2, we maintain a buffer to cache the newly generated orders and periodically dispatch all cached orders at once. But instead of dispatching the cached orders of fixed numbers or predicting future orders, we design an upper-level agent to dynamically determine whether to wait longer for caching more future orders at each moment. Though waiting longer will postpone the dispatching and transportation of the earlier cached orders, additional future orders can be taken into account for the vehicle-order matching. In this way, each vehicle will have more candidate orders to choose, thus the overall travelling distances will be more potentially to be optimized for shorter4. This process could be regarded as sacrificing a little time in exchange for a precise estimation of future orders. However, waiting for too long will also increase the risk of overtime of the earlier cached orders. Thus, whether to wait longer to cache more orders at each moment will have a long-term impact on the overall dispatching results, and can be naturally modeled as a sequential decision-making problem. We model this procedure as a Markov Decision Process (MDP). Depending on whether to wait longer at each moment, the overall DPDP can be dynamically partitioned into a series of static sub-problems, each of which includes different numbers of orders. As shown in Figure 2, the generated orders are accumulated in the buffer until the upper-level agent decides to stop caching at time $t _ { i + k }$ . Then, the agent releases the cached orders to the lower-level agent and clears the buffer.
Given the released orders (which form a static sub-problem, i.e., a PDP), the lower-level agent is appointed to assign the orders to the most appropriate vehicles and arrange the transportation route of each vehicle, such that the transportation cost of these orders could be minimized. First, a set of basic operators are maintained, whose roles are converting one feasible solution to another. For instance, given an initial solution’s route $\{ \mathrm { A } \mathrm { - } \mathrm { > B } \mathrm { - } \mathrm { > C } \}$ with three nodes A, B and C, a typical operator is swapping two nodes[13], e.g., swapping A and B. After applying this operator, $\{ \mathrm { A } \mathrm { - } \mathrm { > B } \mathrm { - } \mathrm { > C } \}$ is converted to $\{ { \bf B } { \bf - } { \bf > } { \bf A } { \bf - } { \bf > } { \bf C } \}$ . If the travelling cost of $\{ { \bf B } { \cdot } { > } { \bf A } { \cdot } { > } { \bf C } \}$ is less than $\{ \mathrm { A } \mathrm { - } \mathrm { > B } \mathrm { - } \mathrm { > C } \}$ , the initial solution is improved. On this basis, we design the lower-level agent similar to the traditional metaheuristic algorithms which sequentially manipulates these operators to improve the solution of each PDP. The difference is that we model the process of sequentially manipulating these operators as an MDP and incorporate RL methods to optimize the policy instead of manually designing complex rules. Finally, the best found solution is adopted by the order dispatching system to assign the orders to the vehicles and arrange their transportation routes. In the following two subsections, we will go into more details of the designed two agents.
# 3.2 Upper-level Agent
# 3.2.1 Workflow
The workflow of the upper-level agent is described in Figure 2. We partition a day into $T = 1 4 4$ fixed time intervals, and the time span of each interval is ten minutes. Each time interval starts at time $t _ { i - 1 }$ and ends at time $t _ { i }$ , $i \leq T$ is a positive integer. We name $t _ { 1 } , . . . , t _ { i } , . . . , t _ { T }$ as decision points. At each decision point $t _ { i }$ , the upper-level agent decides whether to release the accumulated orders to the lower-level agent according to their overtime risk. Taking Figure 2 as an example, at decision point $t _ { i - 1 }$ , the buffer already cached some orders $O _ { i - 1 }$ . At $t _ { i - 1 }$ , the upper-level agent makes a decision and determines to wait longer and not to release $O _ { i - 1 }$ to the lower-level agent. Thus $O _ { i - 1 }$ are still maintained in the buffer. Thereafter, at all decision points before $t _ { i + k }$ , the upper-level agent makes the same decisions as at $t _ { i - 1 }$ , i.e., ’not release’. Therefore, new generated orders $\langle \bar { O _ { i } } , . . . , O _ { i + k } \rangle$ between $t _ { i - 1 }$ and $t _ { i + K }$ are all appended to the buffer as well. At $t _ { i + k }$ , the upper-level agent makes a change and determines to release all accumulated orders $\langle O _ { i - 1 } , O _ { i } , . . . , O _ { i + k } \rangle$ to the lower-level agent. At this time, all accumulated orders together with the remaining orders $O _ { \mathrm { r e m a i n } }$ (assigned to the vehicles before $t _ { i - 1 }$ but the goods of the orders are still not loaded onto the vehicles even at $t _ { i + k }$ ) will be released by the upper-level agent. In this way, we get a static sub-problem constituting of orders $\langle O _ { i - 1 } , O _ { i } , . . . , O _ { i + k } , O _ { \mathrm { r e m a i n } } \rangle$ for the lower-level agent. By analogy, the overall DPDP can be divided into a series of static PDPs with different scales. We model the procedure of whether to wait longer at each decision moment as an MDP described in the following subsection.
# 3.2.2 Markov Decision Process (MDP)
State: The state includes the number of orders accumulated in the buffer, the number of available vehicles, the amount of time left before exceeding the time limit of each order, etc. All these features are normalized and concatenated together. Detailed descriptions are postponed to the Appendix F due to the space limitation.
Action: The action is a binary variable indicates whether to release orders to the lower-level agent.
Reward: Our ultimate goal is to minimize the optimization objective for the entire dynamic problem. Therefore, we first get the the overtime of the orders completed and the corresponding vehicle travelling distances between two consecutive decision moments $t _ { i - 1 }$ and $t _ { i }$ as shown in Figure 2, i.e., avg_distance $+ \lambda *$ overtime. Then we set the immediate reward of action executed at $t _ { i - 1 }$ as $- ( \mathrm { a v g \_ d i s t a n c e } + \lambda *$ overtime). By this rule, the sum of the immediate rewards forms the negative value of the total objective for the entire dynamic problem. With this reward, the overall objective for the entire dynamic problem could be optimized. In other words, we encourage the upper-level agent to optimize the overall dynamic problem from a long-term perspective when making decisions.
# 3.2.3 Agent Model
For the upper-level agent, we use Deep Q Network (DQN) [17]. We parameterize a value function $Q \left( s , a ; \phi _ { l } \right)$ using the deep neural network of MLPs in which $\phi _ { l }$ are the parameters of the Q-network at updating iteration $l$ . When reaching decision point $t _ { i }$ , we obtain the state $s _ { t _ { i } }$ , action $\boldsymbol { a } _ { t _ { i } }$ , and reward $r _ { t _ { i } }$ according to Section 3.2.2 for the current static problem and save them to the replay buffer. When reaching decision point $t _ { i + 1 }$ , we obtain the state $s _ { t _ { i + 1 } }$ , which is the next state of the previous static sub-problem and we get a new transition $e _ { t _ { i } } = ( s _ { t _ { i } } , a _ { t _ { i } } , r _ { t _ { i } } , s _ { t _ { i + 1 } } )$ . We store the transitions into buffer $D = \{ e _ { t _ { 1 } } , \ldots , e _ { t _ { i } } , \ldots \}$ during the running of simulator. During the training, we apply Q-learning updates on uniformly sampled transitions $( s , a , r , s ^ { \prime } ) \sim U ( D )$ from the replay buffer. The model updates at iteration $l$ uses the following Temporal Difference (TD) loss function:
$$L _ { i } \left( \phi _ { l } \right) = \mathbb { E } _ { ( s , a , r , s ^ { \prime } ) \sim U ( D ) } \left[ \left( r + \gamma \operatorname* { m a x } _ { a ^ { \prime } } Q \left( s ^ { \prime } , a ^ { \prime } ; \phi _ { l } ^ { - } \right) - Q \left( s , a ; \phi _ { l } \right) \right) ^ { 2 } \right]$$
where $\gamma$ is the discount factor, $\phi _ { l }$ are the parameters of the Q-network at iteration $l$ and ${ \phi } _ { l } ^ { - }$ are the parameters of the target network at iteration $\it l$ .
 Figure 3: Workflow of Lower-level Agent
# 3.3 Lower-level Agent
# 3.3.1 Workflow
The workflow of the lower-level agent is described in Figure 3. We first generate a feasible initial solution of the static sub-problem using greedy algorithm (described in Section 4.2). Given the initial solution, the lower-level agent iteratively improves the solution by manipulating different operators according to solution states as mentioned in Section 3.1 (we call this step Improvement [6, 13]). When the improved solution reaches a local optimum (i.e., the solution could not be improved further for a series of steps), we will partially or entirely re-assigning the orders using the greedy algorithm (we call this step Reconstruction). The improvement of the next iteration will start from the reconstructed solution. Note that the lower-level agent only selects improvement operators as reconstruction operator has a long-lasting effect on solutions compared with improvement operators and we found mixing up them will lead to instability during the training. The process of improvement and reconstruction alternates until reaching the maximum number of steps or the maximum allowable running time. The best generated solution during the improvements and reconstructions will be adopted to dispatch orders to vehicles. Note that the final accepted solution is ensured to be at least as good as the initial solution. Overall, by transferring the knowledge learned from previously solved PDPs to the new ones, the agent could efficiently and monotonically improve the solution quality. The MDP definition of the operators-manipulating procedure is described in the following subsection.
# 3.3.2 Markov Decision Process (MDP)
State: The state of the current solution consists of the states of all nodes, i.e., $s = \{ s _ { 1 } , s _ { 2 } , . . . , s _ { | V | } \}$ where $s _ { v }$ is the state of node $v$ . Each $s _ { v }$ includes the position information, order information, vehicle information and objective-related information. Details can be found in Appendix F.
Action: The action set consists of 4 carefully designed operators, i.e., inner-exchange, inner-relocate, inter-exchange and inter-relocate. We provide a proof in Appendix G that any feasible solution (including the optimal one) could be obtained by iteratively applying these 4 operators from any given initial solution. Details are described in Appendix G.
Reward: We find that the total objective can be easily reduced by a large margin during the first few improvement steps of an initial solution or reconstructed solution in the experiments (See Figure 4). If we assign the actions at these improvement steps a large reward, it’s not fair for the actions in the subsequent steps. This is because the actions in the subsequent steps also play important roles in improving solutions in the complex solution space. Therefore, the overall objective $\mathrm { O B J } _ { b }$ of the sub-problem after the first iteration (e.g., Iteration 1 in Figure 3) is used as the baseline following [13]. For each subsequent iteration $i$ , we first get the optimized objective after the iteration as $\mathrm { O B J } _ { i }$ and then assign $( | \mathbf { O B } \mathbf { J } _ { b } - \mathbf { O B J } _ { i } | ) / n _ { i }$ to all $n _ { i }$ actions executed in iteration $i$ as reward.
# 3.3.3 Agent Policy Network
The policy network of the lower-level agent inputs the state of the current solution and outputs action probabilities of length $| A |$ where $A$ is the set of operators. In our case, a critical challenge of designing the policy network is the number of orders and the number of available vehicles are different for each static sub-problem. As the quantity of the combination of orders and vehicles are extremely huge, we cannot train a separate model for every combination of different numbers of orders and vehicles. Thus, the desired model should be able to transfer the knowledge learned from the previously solved problems and generalize to new problems of any scale without fine-tuning. Besides, the routes of a solution naturally form a certain topological graph structure as shown in Figure 3. Therefore, in this paper, we incorporate GIN (Graph Isomorphism Network)[30], a powerful Graph Neural Network (GNN), to be the basis of the policy network of the lower-level agent. We use the REINFORCE algorithm [28] to train the policy network. Details of the policy network are shown in Appendix H.
# 4 Offline Evaluation
# 4.1 Experiments Settings
We start with designing a simulator to shed light on the contributions of the proposed framework under more controlled settings. Details of the simulator can be found in Appendix C. To comprehensively verify the effectiveness of our approach on problems of different scales, we use four types of datasets of different sizes, i.e., 15 orders with 5 vehicles, 50 orders with 5 vehicles, 300 orders with 20 vehicles, 1000 orders with 50 vehicles (matching the practical problem of thousand scales). Note that the orders/vehicles ratios are set according to realistic business settings. Each type of datasets contains 10 datasets, including 7 training sets and 3 test sets according to the ratio of 7:3 (e.g., 300-1, 300-2 and 300-3 are test sets with 300 orders). The vehicles have the same load capacity. Details of the datasets are described in Appendix D. According to the realistic business settings, the time span between two consecutive decision points is set to 10 minutes in the simulator.
The comparisons of different methods proceed as follows. For our approach, we first train a shared model on each type of training datasets and then evaluate the model on the test datasets of the same size. At each decision point, the upper-level agent decides whether to release orders to the lower-level agent. The lower-level agent is executed for no more than 10 minutes after receiving orders from the upper-level agent. Both agents are trained simultaneously. This training process is relatively stable due to the following reasons. The iterative solution optimization process (starts from an initial greedy solution) of our lower-level agent can ensure the obtained solutions have relatively high quality even at the initial training stages. In other words, the solutions given by the lower-level agent are relatively stable. Therefore, the unstable issue of co-training both levels of policies in our case is negligible, and thus both levels can be trained simultaneously. For baselines showed in Section 4.2, we also run them for up to 10 minutes at each decision point. We run the simulator until all the orders of the dataset are dispatched and completed to ensure fair comparisons. All the results in the experiments are obtained by running each algorithm ten times to get the mean and variance value of the optimization objective.
# 4.2 Baselines
To help readers better understand the baselines, we name them in the format of ’upper-level method $^ +$ lower-level method’ except for the Optimal baseline. ’10min-Interval’ means the dynamic problem is partitioned into static sub-problems with a fixed interval of ten minutes. ’1order-Interval’ means the dynamic problem is partitioned into static sub-problems consists of a single order.
10min-Interval $^ +$ Greedy: Greedy [15] is the most widely-used method in industry, which is also the online deployed baseline method. The solution routes are expanded by greedily inserting new pickup and delivery nodes until all the orders are inserted.
10min-Interval $^ +$ ALNS: ALNS [29] is one of the most representative meta-heuristic local search frameworks for solving DPDP that uses a series of operators to improve the solution. In each iteration, an operator is selected to destroy the current solution, and an operator is selected to repair the solution.
1order-Interval $^ +$ E2ERL: According to [14], we use a DQN model to assign vehicles to each generated order and insert each order into the vehicle’s order queue using the Greedy algorithm. It’s an E2ERL (end-to-end RL) algorithm.
10min-Interval $^ +$ ST-DDGN: ST-DDGN [12] is the state-of-the-art method that predicts future orders of DPDP. Then both the predicted orders and real generated orders are considered when solving each sub-problem using E2ERL.
Optimal: We convert DPDPs to static PDPs as we can obtain all the orders’ information beforehand in offline style. Then we use Gurobi to solve the corresponding MIP model to get the optimal solution. As Gurobi can only solve small-scale PDPs within acceptable time due to the NP-hard property, we only compare with the optimal solution on problems of 15 and 50 orders in Section 4.4.1.
# 4.3 Main Results
Here we show part of the experimental results in Table 1. The complete results are shown in Table 6 of Appendix I. The objective improvement measurement is the improvement percentage of each algorithm compared with the Greedy algorithm. Our approach consistently outperforms all baselines
Table 1: Main results of different methods on test datasets
<table><tr><td>Dataset</td><td>Algorithm</td><td>Overtime</td><td>Avg_Dis</td><td>Objective</td><td>Obj Impro</td></tr><tr><td rowspan="5">50-1</td><td>10min-Interval + Greedy</td><td>0</td><td>109.30</td><td>109.30</td><td>0.00%</td></tr><tr><td>lorder-Interval +E2ERL</td><td>0</td><td>96.56</td><td>96.56</td><td>11.66%</td></tr><tr><td>10min-Interval + ALNS</td><td>0</td><td>107.95</td><td>107.95</td><td>1.24%</td></tr><tr><td>10min-Interval + ST-DDGN</td><td>0</td><td>108.95</td><td>108.95</td><td>0.32%</td></tr><tr><td>Our (Upper-level RL + Lower-level RL)</td><td>0</td><td>93.70</td><td>93.70</td><td>14.27%</td></tr><tr><td rowspan="5">300-1</td><td>10min-Interval+Greedy</td><td>0</td><td>147.78</td><td>147.78</td><td>0.00%</td></tr><tr><td>lorder-Interval + E2ERL</td><td>0</td><td>158.39</td><td>158.39</td><td>-7.18%</td></tr><tr><td>10min-Interval + ALNS</td><td>0</td><td>137.31</td><td>137.31</td><td>7.08%</td></tr><tr><td>10min-Interval + ST-DDGN</td><td>0</td><td>131.99</td><td>131.99</td><td>10.68%</td></tr><tr><td>Our (Upper-level RL + Lower-level RL)</td><td>0</td><td>122.42</td><td>122.42</td><td>17.16%</td></tr><tr><td rowspan="5">1000-1</td><td>10min-Interval+Greedy</td><td>0</td><td>183.04</td><td>183.04</td><td>0.00%</td></tr><tr><td>lorder-Interval + E2ERL</td><td>0</td><td>180.36</td><td>180.36</td><td>1.46%</td></tr><tr><td>10min-Interval + ALNS</td><td>0</td><td>174.68</td><td>174.68</td><td>4.57%</td></tr><tr><td>10min-Interval + ST-DDGN</td><td>0</td><td>171.09</td><td>171.09</td><td>6.53%</td></tr><tr><td>Our(Upper-level RL +Lower-level RL)</td><td>0</td><td>159.18</td><td>159.18</td><td>13.04%</td></tr></table>
on all datasets (lower total objective is better). On some datasets, the baselines have overtime results due to their lack of long-term planning and exhaustively optimization of each static problem from a myopic perspective. As a result, dispatching of some orders is delayed for too long, and finally, overtime is inevitable in any case. In contrast to this, our upper-level RL partitions the dynamic problem into sub-problems considering the balance between the orders overtime (seconds) risk and optimization of vehicle travelling distances (kilometers), and our lower-level RL is responsible for the optimization of each static sub-problem. The cooperation of the two agents enables our method to find solutions with less overtime and vehicle travelling distances on the overall dynamic problem from a long-term perspective. The comparison of the learning curves of all learning-based methods on 50-1 are shown in Figure 11 in Appendix I.
# 4.4 Ablation Studies
# 4.4.1 How far is our lower-level agent from the optimal one on static PDP?
We convert the DPDP to a single static PDP as described in Section 4.2. As the orders should be assigned to vehicles all at once, there is no need to use an upper-level agent. Similarly, without the prediction of future orders, ST-DDGN is essentially the same as E2ERL. Therefore we only use the lower-level agent and E2ERL in the static PDP. Each algorithm is run without time or step limitation to discover its full potential. As shown in Table 2 and 3, the difference of the total objective of our method with the optimal solution is much smaller than the baselines (as all the overtime is 0, the column is omitted from the two Tables). The time consumption is much shorter than ALNS and Gurobi. It is because our method can exert the generalization ability to quickly improve the initial solution by using the most appropriate operators based on the experiences obtained from training, without the need of manually designing complicated search as in ALNS and Gurobi. Note that the time consumption of Gurobi on problems of 50 orders is represented using hyphen symbol ’-’, which means we can’t get results even after 100 hours due to the various complex constraints as described in Appendix A. Comparing with baselines, our method is the most qualified to meet the online deployment requirements that the algorithm should obtain high-quality solutions with fast speed.
Table 2: Results on static 15-1, 15-2, 15-3
<table><tr><td>Algorithm</td><td>Avg_Dis</td><td>Objective</td><td>Obj Impro</td><td>Time</td></tr><tr><td>Greedy</td><td>53.85</td><td>53.85</td><td>0.00%</td><td>0.38s</td></tr><tr><td>E2ERL</td><td>51.70</td><td>51.70</td><td>3.99%</td><td>0.58s</td></tr><tr><td>ALNS</td><td>51.58</td><td>51.58</td><td>4.22%</td><td>405s</td></tr><tr><td>Our</td><td>45.72</td><td>45.72</td><td>15.10%</td><td>68.21s</td></tr><tr><td>(Lower-level RL) Optimal</td><td>44.35</td><td>44.35</td><td>17.64%</td><td>141360s</td></tr><tr><td>Greedy</td><td>69.61</td><td>69.61</td><td>0.00%</td><td>0.40s</td></tr><tr><td>E2ERL</td><td>68.00</td><td>68.00</td><td>2.31%</td><td>0.79s</td></tr><tr><td>ALNS</td><td>62.62</td><td>62.62</td><td>10.04%</td><td>606s</td></tr><tr><td>Our</td><td>62.32</td><td>62.32</td><td>10.47%</td><td>27.96s</td></tr><tr><td>(Lower-level RL) Optimal</td><td>57.48</td><td>57.48</td><td>17.43%</td><td>193680s</td></tr><tr><td>Greedy</td><td>78.73</td><td>78.73</td><td>0.00%</td><td>0.34s</td></tr><tr><td>E2ERL</td><td>59.02</td><td>59.02</td><td>25.03%</td><td>0.83s</td></tr><tr><td>ALNS</td><td>52.21</td><td>52.21</td><td>33.68%</td><td>920s</td></tr><tr><td>Our</td><td>50.95</td><td>50.95</td><td>35.29%</td><td>71.98s</td></tr><tr><td>(Lower-level RL) Optimal</td><td>50.75</td><td>50.75</td><td>35.54%</td><td>28651s</td></tr></table>
Table 3: Results on static 50-1, 50-2, 50-3
<table><tr><td>Algorithm</td><td>Avg_Dis</td><td>Objective</td><td>Obj Impro</td><td>Time</td></tr><tr><td>Greedy</td><td>98.68</td><td>98.68</td><td>0.00%</td><td>66.73s</td></tr><tr><td>E2ERL</td><td>94.94</td><td>94.94</td><td>3.79%</td><td>52.64s</td></tr><tr><td>ALNS</td><td>96.98</td><td>96.98</td><td>1.72%</td><td>10728.34s</td></tr><tr><td>Our (Lower-level RL)</td><td>82.43</td><td>82.43</td><td>16.47%</td><td>1459.23s</td></tr><tr><td>Optimal</td><td>-</td><td>-</td><td>-</td><td>-</td></tr><tr><td>Greedy</td><td>80.67</td><td>80.67</td><td>0.00%</td><td>22.27s</td></tr><tr><td>E2ERL</td><td>76.04</td><td>76.04</td><td>5.74%</td><td>16.66s</td></tr><tr><td>ALNS</td><td>65.31</td><td>65.31</td><td>19.04%</td><td>6012.56s</td></tr><tr><td>Our (Lower-level RL)</td><td>58.42</td><td>58.42</td><td>27.58%</td><td>1152.64s</td></tr><tr><td>Optimal</td><td>=</td><td>=</td><td>=</td><td>=</td></tr><tr><td>Greedy</td><td>83.34</td><td>83.34</td><td>0.00%</td><td>44.31s</td></tr><tr><td>E2ERL</td><td>80.92</td><td>80.92</td><td>2.90%</td><td>20.34s</td></tr><tr><td>ALNS</td><td>80.51</td><td>80.51</td><td>3.40%</td><td>4140.15s</td></tr><tr><td>Our (Lower-level RL)</td><td>72.66</td><td>72.66</td><td>12.81%</td><td>1998.09s</td></tr><tr><td>Optimal</td><td>-</td><td>-</td><td>-</td><td>-</td></tr></table>
# 4.4.2 Does lower-level agent learn how to select operators?
To verify that our lower-level agent learns to choose the most suitable operators at different states, we compare the results of different operator selection methods on both static problems and dynamic problems. We first compare the total objective during the solution improvement process on the static problems using the lower-level agent with the method that randomly selects operators. As the improvement-reconstruct iteration process designed in Section 3.3 ensures the quality of the solution can be monotonically improved, selecting operators randomly is also a powerful baseline that can achieve satisfactory performance for the static PDP.
Therefore, for the static problem, we mainly focus on whether the lower-level agent can improve the solving speed. As we can see in Figure 4, at the same step, choosing operators using lower-level RL can reach a better objective than randomly choosing operators, which indicates our lower-level method learned to accelerate the searching for better solutions. Since the static sub-problems of a dynamic problem are not independent of each other, the small gap between the above
 Figure 4: Comparison of different selection methods of operators on static problems
two methods in a static sub-problem will continue to enlarge in the subsequent sub-problems, resulting in a very large result gap on the entire dynamic problem. We compare the total objectives of the entire dynamic problems in Table 4. To ensure fairness, we control the upper-level methods to be ’10min-Interval’ and use the lower-level agent and random selection as lower-level methods, respectively. As we can see in Table 4, using the lower-level agent can help find better solutions on the entire dynamic problems.
# 4.4.3 Does the upper-level agent learn to partition DPDP from a long-term perspective?
To verify that our upper-level agent learns to partition the dynamic problem into static subproblems from a long-term perspective, we compare the results of differ
Table 4: Effectiveness of lower-level agent and upper-level agent
<table><tr><td>Dataset</td><td>Method</td><td>Overtime</td><td>Avg_Dis</td><td>Objective</td><td>ObjImpro</td></tr><tr><td rowspan="3">300-1</td><td>10min-Interval+Random Search</td><td>0</td><td>139.16 ± 8.59</td><td>139.16</td><td>0.00%</td></tr><tr><td>10min-Interval + Lower-level RL</td><td>0</td><td>126.95 ± 4.80</td><td>126.95</td><td>8.77%</td></tr><tr><td>Our(Upper-level RL +Lower-level RL)</td><td>0</td><td>122.42 ± 4.02</td><td>122.42</td><td>12.03%</td></tr><tr><td rowspan="3">300-2</td><td>10min-Interval+RandomSearch</td><td>0</td><td>166.31 ± 10.20</td><td>166.31</td><td>0.00%</td></tr><tr><td>10min-Interval + Lower-level RL</td><td>0</td><td>154.39 ± 8.13</td><td>154.39</td><td>7.17%</td></tr><tr><td>Our (Upper-level RL + Lower-level RL)</td><td>0</td><td>142.33 ± 7.47</td><td>142.33</td><td>14.42%</td></tr><tr><td rowspan="3">300-3</td><td>10min-Interval+RandomSearch</td><td>0</td><td>168.69±7.70</td><td>168.69</td><td>0.00%</td></tr><tr><td>10min-Interval + Lower-level RL</td><td>0</td><td>156.64 ± 7.50</td><td>156.64</td><td>7.14%</td></tr><tr><td>Our(Upper-level RL +Lower-level RL)</td><td>0</td><td>146.88 ±13.91</td><td>146.88</td><td>12.93%</td></tr></table>
ent static sub-problems partitioning methods. We compare our upper-level agent with the $\mathrm { \Omega } ^ { , } 1 0 \mathrm { m i n } .$ Interval’ method. As we can see in Table 4, using an upper-level agent to partition the dynamic problem reaches the best objective. The results illustrate that our upper-level agent can partition the problem from a long-term perspective to balance the orders overtime risk and optimization of vehicle travelling distances.
# 4.4.4 Can our method generalized to larger-scale problems?
To verify our method’s generalization ability, we evaluate the models trained using datasets of 300 orders / 20 vehicles on larger-scale datasets, i.e., 1000 orders / 50 vehicles. As shown in Table 5, the model trained on datasets of 300 orders achieves similar performance with the one trained on datasets of 1000 orders.
Table 5: Generalization verification
<table><tr><td>Dataset</td><td>Model</td><td>Overtime</td><td>Avg_Dis</td><td>Objective</td></tr><tr><td rowspan="2">1000-1</td><td>Trained on 1000</td><td>0</td><td>159.18 ± 4.10</td><td>159.18</td></tr><tr><td>Trained on 300</td><td>0</td><td>170.78 ± 10.27</td><td>170.78</td></tr><tr><td rowspan="2">1000-2</td><td>Trained on 1000</td><td>0</td><td>196.66± 9.52</td><td>196.66</td></tr><tr><td>Trained on 300</td><td>0</td><td>209.48±8.68</td><td>209.48</td></tr><tr><td rowspan="2">1000-3</td><td>Trained on 1000</td><td>0</td><td>176.39 ± 7.61</td><td>176.39</td></tr><tr><td>Trained on 300</td><td>0</td><td>182.83 ± 5.64</td><td>182.83</td></tr></table>
Note that the model trained on datasets of 300 orders also outperforms the baselines in Table 1. It verifies that our method can be generalized to new problems of different scales without fine-tuning after well trained on existing problems.
# 5 Online Testing
We deployed our method on the order dispatching system in Huawei supply chain. In the online experiments, we compare our method with the previously online deployed greedy algorithm (10min-Interval $^ +$ Greedy). For a fair comparison, we control the vehicles and the nodes (factories and warehouses) involved in the online testing to be the same. Normally, a standard A/B testing is required to be performed on homogeneous experimental groups using different methods
 Figure 5: Online Results
at the same time dimension. Then experimental data of each group are collected and evaluated to choose the best method. However, in our situation, it’s unrealistic to split each order into two sub-orders to ensure the experimental groups are homogeneous. Besides, a large number of offline experiments have demonstrated that our method is significantly better than the greedy algorithm. Even in the worst case when there is no improvement in each sub-problem, our method is still the same with Greedy. Thus, we directly replaced the greedy algorithm for online deployment. Figure 5 summarises the results from Nov 2020 to Apr 2021. The points of Nov and Dec 2020 shown in Figure 5 are generated by greedy algorithm and our method is deployed from Jan to Apr 2021. As we can see, our method can reduce the average orders’ overtime and vehicles’ travelling distances compared with the greedy baseline. Even with more orders, our method can still reach a better optimization objective. Note that in the actual business scenario, orders generated in each day follow a similar distribution with a small variance. These results indicate that our method could achieve a better performance in the realistic deployment environment with varied data distributions.
# 6 Conclusions
In this paper, we propose a novel hierarchical reinforcement learning based optimization framework to solve the large-scale DPDP in the real world. The upper-level agent is equipped with the far-sight ability whose target is to optimize the long-term cumulative objective. The lower-level agent exerts the generalization ability of GNN to quickly improve the solution quality by transferring the knowledge (policy) learned from training. The cooperation of the upper-level and lower-level agents enables our method to find globally better solutions. Extensive offline simulation on the simulator built on real historical data and online testing verify that our method can obtain higher-quality solutions with faster running speed.
The core idea of our learning-based framework are beneficial to a number of similar problems in the supply chain community that have time-evolving components (e.g., orders/customers/tasks), such as dynamic routing problems, dynamic flow shop scheduling, dynamic job shop scheduling, dynamic bin packing and so on. As orders/customers/tasks of all these dynamic problems are online generated that are not known a priori, the orders/customers/tasks should first be cached and then be dispatched. In this way, these problems can be modeled as hierarchical optimization problems like DPDP that the upper-level problem is ”how to cache orders/customers/tasks” and the lower-level problem is ”how to dispatch cached orders/customers/tasks”. We will verify our proposed framework in these fields in the future work.
# Acknowledgments and Disclosure of Funding
The work is supported by the National Natural Science Foundation of China (Grant Nos: U1836214) and the New Generation of Artificial Intelligence Science and Technology Major Project of Tianjin under grant: 19ZXZNGX00010.
References [1] Irwan Bello, Hieu Pham, Quoc V Le, Mohammad Norouzi, and Samy Bengio. Neural combinatorial optimization with reinforcement learning. arXiv preprint arXiv:1611.09940, 2016. [2] Enrique Benavent, Mercedes Landete, Enrique Mota, and Gregorio Tirado. The multiple vehicle pickup and delivery problem with lifo constraints. European Journal of Operational Research, 243(3):752–762, 2015. [3] Gerardo Berbeglia, Jean-François Cordeau, and Gilbert Laporte. Dynamic pickup and delivery problems. European journal of operational research, 202(1):8–15, 2010. [4] Francesco Carrabs, Jean-François Cordeau, and Gilbert Laporte. Variable neighborhood search for the pickup and delivery traveling salesman problem with lifo loading. INFORMS Journal on Computing, 19 (4):618–632, 2007. [5] Brenda Cheang, Xiang Gao, Andrew Lim, Hu Qin, and Wenbin Zhu. Multiple pickup and delivery traveling salesman problem with last-in-first-out loading and distance constraints. European journal of operational research, 223(1):60–75, 2012. [6] Xinyun Chen and Yuandong Tian. Learning to perform local rewriting for combinatorial optimization. In Hanna M. Wallach, Hugo Larochelle, Alina Beygelzimer, Florence d’Alché-Buc, Emily B. Fox, and Roman Garnett, editors, Advances in Neural Information Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada, pages 6278–6289, 2019. URL https://proceedings.neurips.cc/paper/2019/hash/ 131f383b434fdf48079bff1e44e2d9a5-Abstract.html. [7] Michel Gendreau, Francois Guertin, Jean-Yves Potvin, and René Séguin. Neighborhood search heuristics for a dynamic vehicle dispatching problem with pick-ups and deliveries. Transportation Research Part C: Emerging Technologies, 14(3):157–174, 2006. [8] Gianpaolo Ghiani, Emanuele Manni, Antonella Quaranta, and Chefi Triki. Anticipatory algorithms for same-day courier dispatching. Transportation Research Part E: Logistics and Transportation Review, 45 (1):96–106, 2009. [9] Péter Györgyi and Tamás Kis. A probabilistic approach to pickup and delivery problems with time window uncertainty. European Journal of Operational Research, 274(3):909–923, 2019. [10] Matheus Nohra Haddad, Rafael Martinelli, Thibaut Vidal, Simone Martins, Luiz Satoru Ochi, Marcone Jamilson Freitas Souza, and Richard Hartl. Large neighborhood-based metaheuristic and branch-and-price for the pickup and delivery problem with split loads. European Journal of Operational Research, 270(3): 1014–1027, 2018. [11] Farzaneh Karami, Wim Vancroonenburg, and Greet Vanden Berghe. A periodic optimization approach to dynamic pickup and delivery problems with time windows. Journal of Scheduling, 23(6):711–731, 2020. [12] Xijun Li, Weilin Luo, Mingxuan Yuan, Jun Wang, Jiawen Lu, Jie Wang, Jinhu Lv, and Jia Zeng. Learning to optimize industry-scale dynamic pickup and delivery problems. 37th IEEE International Conference on Data Engineering, 2021. [13] Hao Lu, Xingwen Zhang, and Shuang Yang. A learning-based iterative method for solving vehicle routing problems. In 8th International Conference on Learning Representations, ICLR 2020, Addis Ababa, Ethiopia, April 26-30, 2020. OpenReview.net, 2020. URL https://openreview.net/forum?id=BJe1334YDH. [14] Hongzi Mao, Malte Schwarzkopf, Shaileshh Bojja Venkatakrishnan, Zili Meng, and Mohammad Alizadeh. Learning scheduling algorithms for data processing clusters. In Proceedings of the ACM Special Interest Group on Data Communication, pages 270–288. 2019. [15] Snežana Mitrovic-Mini ´ c and Gilbert Laporte. Waiting strategies for the dynamic pickup and delivery ´ problem with time windows. Transportation Research Part B: Methodological, 38(7):635–655, 2004. [16] Snezana Mitrovic-Minic, Ramesh Krishnamurti, Gilbert Laporte, et al. Double-horizon based heuristics for the dynamic pickup and delivery problem with time windows. Transportation Research Part B: Methodological, 38(8):669–685, 2004. [17] Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A Rusu, Joel Veness, Marc G Bellemare, Alex Graves, Martin Riedmiller, Andreas K Fidjeland, Georg Ostrovski, et al. Human-level control through deep reinforcement learning. nature, 518(7540):529–533, 2015.
[18] MohammadReza Nazari, Afshin Oroojlooy, Lawrence V. Snyder, and Martin Takác. Reinforcement learning for solving the vehicle routing problem. In Samy Bengio, Hanna M. Wallach, Hugo Larochelle, Kristen Grauman, Nicolò Cesa-Bianchi, and Roman Garnett, editors, Advances in Neural Information Processing Systems 31: Annual Conference on Neural Information Processing Systems 2018, NeurIPS 2018, December 3-8, 2018, Montréal, Canada, pages 9861–9871, 2018. URL https://proceedings. neurips.cc/paper/2018/hash/9fb4651c05b2ed70fba5afe0b039a550-Abstract.html.
[19] Maciek Nowak, Özlem Ergun, and Chelsea C White III. Pickup and delivery with split loads. Transportation Science, 42(1):32–43, 2008.
[20] GUROBI OPTIMIZATION. Inc. gurobi optimizer reference manual, 2015. URL: http://www. gurobi. com, page 29, 2014.
[21] Bo Peng, Yuan Zhang, Zhipeng Lü, TCE Cheng, and Fred Glover. A learning-based memetic algorithm for the multiple vehicle pickup and delivery problem with lifo loading. Computers & Industrial Engineering, 142:106241, 2020.
[22] Martin Savelsbergh and Marc Sol. Drive: Dynamic routing of independent vehicles. Operations Research, 46(4):474–490, 1998.
[23] Zhiyuan Su, Wantao Li, Jicao Li, and Bin Cheng. Heterogeneous fleet vehicle scheduling problems for dynamic pickup and delivery problem with time windows in shared logistics platform: formulation, instances and algorithms. International Journal of Systems Science: Operations & Logistics, pages 1–25, 2021.
[24] Barrett W Thomas. Waiting strategies for anticipating service requests from known customer locations. Transportation Science, 41(3):319–331, 2007.
[25] Paolo Toth and Daniele Vigo. Vehicle routing: problems, methods, and applications. SIAM, 2014.
[26] Marlin W Ulmer, Barrett W Thomas, Ann Melissa Campbell, and Nicholas Woyak. The restaurant meal delivery problem: Dynamic pickup and delivery with deadlines and random ready times. Transportation Science, 55(1):75–100, 2021.
[27] Oriol Vinyals, Meire Fortunato, and Navdeep Jaitly. Pointer networks. In Corinna Cortes, Neil D. Lawrence, Daniel D. Lee, Masashi Sugiyama, and Roman Garnett, editors, Advances in Neural Information Processing Systems 28: Annual Conference on Neural Information Processing Systems 2015, December 7- 12, 2015, Montreal, Quebec, Canada, pages 2692–2700, 2015. URL https://proceedings.neurips. cc/paper/2015/hash/29921001f2f04bd3baee84a12e98098f-Abstract.html.
[28] Ronald J Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine learning, 8(3-4):229–256, 1992.
[29] David Wolfinger. A large neighborhood search for the pickup and delivery problem with time windows, split loads and transshipments. Computers & Operations Research, 126:105110.
[30] Keyulu Xu, Weihua Hu, Jure Leskovec, and Stefanie Jegelka. How powerful are graph neural networks? In 7th International Conference on Learning Representations, ICLR 2019, New Orleans, LA, USA, May 6-9, 2019. OpenReview.net, 2019. URL https://openreview.net/forum?id=ryGs6iA5Km.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296# On the Expressivity of Markov Reward
David Abel DeepMind dmabel@deepmind.com
Will Dabney DeepMind wdabney@deepmind.com
Anna Harutyunyan DeepMind harutyunyan@deepmind.com
Mark K. Ho Department of Computer Science Princeton University mho@princeton.edu
Michael L. Littman Department of Computer Science Brown University mlittman@cs.brown.edu
Doina Precup DeepMind doinap@deepmind.com
Satinder Singh DeepMind baveja@deepmind.com
# Abstract
Reward is the driving force for reinforcement-learning agents. This paper is dedicated to understanding the expressivity of reward as a way to capture tasks that we would want an agent to perform. We frame this study around three new abstract notions of “task” that might be desirable: (1) a set of acceptable behaviors, (2) a partial ordering over behaviors, or (3) a partial ordering over trajectories. Our main results prove that while reward can express many of these tasks, there exist instances of each task type that no Markov reward function can capture. We then provide a set of polynomial-time algorithms that construct a Markov reward function that allows an agent to optimize tasks of each of these three types, and correctly determine when no such reward function exists. We conclude with an empirical study that corroborates and illustrates our theoretical findings.
# 1 Introduction
How are we to use algorithms for reinforcement learning (RL) to solve problems of relevance in the world? Reward plays a significant role as a general purpose signal: For any desired behavior, task, or other characteristic of agency, there must exist a reward signal that can incentivize an agent to learn to realize these desires. Indeed, the expressivity of reward is taken as a backdrop assumption that frames RL, sometimes called the reward hypothesis: “...all of what we mean by goals and purposes can be well thought of as maximization of the expected value of the cumulative sum of a received scalar signal (reward)” [53, 29, 6]. In this paper, we establish first steps toward a systematic study of the reward hypothesis by examining the expressivity of reward as a signal. We proceed in three steps.
1. An Account of “Task”. As rewards encode tasks, goals, or desires, we first ask, “what is a task?”. We frame our study around a thought experiment (Figure 1) involving the interactions between a designer, Alice, and a learning agent, Bob, drawing inspiration from Ackley and Littman [2], Sorg [50], and Singh et al. [46]. In this thought experiment, we draw a distinction between how Alice thinks of a task (TASKQ) and the means by which Alice incentivizes Bob to pursue this task (EXPRESSIONQ). This distinction allows us to analyze the expressivity of reward as an answer to the latter question, conditioned on how we answer the former. Concretely, we study three answers to the TASKQ in the context of finite Markov Decision Processes (MDPs): A task is either (1) a set of acceptable behaviors (policies), (2) a partial ordering over behaviors, or (3) a partial ordering over trajectories. Further detail and motivation for these task types is provided in Section 3, but broadly they can be viewed as generalizations of typical notions of task such as a choice of goal or optimal behavior. Given these three answers to the TASKQ, we then examine the expressivity of reward.
 Figure 1: Alice, Bob, and the artifacts of task definition (blue) and task expression (purple).
2. Expressivity of Markov Reward. The core of our study asks whether there are tasks Alice would like to convey—as captured by the answers to the TASKQ—that admit no characterization in terms of a Markov reward function. Our emphasis on Markov reward functions, as opposed to arbitrary history-based reward functions, is motivated by several factors. First, disciplines such as computer science, psychology, biology, and economics typically rely on a notion of reward as a numerical proxy for the immediate worth of states of affairs (such as the financial cost of buying a solar panel or the fitness benefits of a phenotype). Given an appropriate way to describe states of affairs, Markov reward functions can represent immediate worth in an intuitive manner that also allows for reasoning about combinations, sequences, or re-occurrences of such states of affairs. Second, it is not clear that general history-based rewards are a reasonable target for learning as they suffer from the curse of dimensionality in the length of the history. Lastly, Markov reward functions are the standard in RL. A rigorous analysis of which tasks they can and cannot convey may provide guidance into when it is necessary to draw on alternative formulations of a problem. Given our focus on Markov rewards, we treat a reward function as accurately expressing a task just when the value function it induces in an environment adheres to the constraints of a given task.
3. Main Results. We find that, for all three task types, there are environment��task pairs for which there is no Markov reward function that realizes the task (Theorem 4.1). In light of this finding, we design polynomial-time algorithms that can determine, for any given task and environment, whether a reward function exists in the environment that captures the task (Theorem 4.3). When such a reward function does exist, the algorithms also return it. Finally, we conduct simple experiments with these procedures to provide empirical insight into the expressivity of reward (Section 5).
Collectively, our results demonstrate that there are tasks that cannot be expressed by Markov reward in a rigorous sense, but we can efficiently construct such reward functions when they do exist (and determine when they do not). We take these findings to shed light on the nature of reward maximization as a principle, and highlight many pathways for further investigation.
# 2 Background
RL defines the problem facing an agent that learns to improve its behavior over time by interacting with its environment. We make the typical assumption that the RL problem is well modeled by an agent interacting with a finite Markov Decision Process (MDP), defined by the tuple $( S , \mathcal { A } , R , T , \gamma , s _ { 0 } )$ . An MDP gives rise to deterministic behavioral policies, $\pi : { \mathcal { S } } A$ , and the value, $V ^ { \pi } : { \mathcal { S } } \mathbb { R }$ , and action–value, $Q ^ { \pi } : S \times \mathcal { A } \mathbb { R }$ , functions that measure their quality. We will refer to a Controlled Markov Process (CMP) as an MDP without a reward function, which we denote $E$ for environment. We assume that all reward functions are deterministic, and may be a function of either state, stateaction pairs, or state-action-state triples, but not history. Henceforth, we simply use “reward function” to refer to a deterministic Markov reward function for brevity, but note that more sophisticated settings beyond MDPs and deterministic Markov reward functions are important directions for future work. For more on MDPs or RL, see the books by Puterman [41] and Sutton and Barto [54] respectively.
# 2.1 Other Perspectives on Reward
We here briefly summarize relevant literature that provides distinct perspectives on reward.
Two Roles of Reward. As Sorg [50] identifies (Chapter 2), reward can both define the task the agent learns to solve, and define the “bread crumbs” that allow agents to efficiently learn to solve the task. This distinction has been raised elsewhere [2, 46, 47], and is similar to the extrinsic-intrinsic reward divide [45, 66]. Tools such as reward design [34, 51] or reward shaping [36] focus on offering more efficient learning in a variety of environments, so as to avoid issues of sparsity and long-term credit assignment. We concentrate primarily on reward’s capacity to express a task, and defer learning dynamics to an (important) stage of future work.
Discounts, Expectations, and Rationality. Another important facet of reward is how it is used in producing behavior. The classical view offered by the Bellman equation (and the reward hypothesis) is that the quantity of interest to maximize is expected, discounted, cumulative reward. Yet it is possible to disentangle reward from the expectation [5], to attend only to ordinal [60] or maximal rewards [26], or to adopt different forms of discounting [61, 11]. In this work, we take the standard view that agents will seek to maximize value for a particular discount factor $\gamma$ , but recognize that there are interesting directions beyond these commitments, such as inspecting the limits of reward in constrained MDPs as studied by Szepesvári [56]. We also note the particular importance of work by Pitis [40], who examines the relationship between classical decision theory [59] and MDPs by incorporating additional axioms that account for stochastic processes with discounting [24, 35, 48, 49]. Drawing inspiration from Pitis [40] and Sunehag and Hutter [52], we foresee valuable pathways for future work that further makes contact between RL and various axioms of rationality.
Preferences. In place of numerical rewards, preferences of different kinds may be used to evaluate an agent’s behaviors, drawing from the literature on preference-learning [25] and ordinal dynamic programming [8, 35, 48]. This premise gives rise to preference-based reinforcement learning (PbRL) in which an agent interacts with a CMP and receives evaluative signals in the form of preferences over states, actions, or trajectories. This kind of feedback inspires and closely parallels the task types we propose in this work. A comprehensive survey of PbRL by Wirth et al. [64] identifies critical differences in this setup from traditional RL, categorizes recent algorithmic approaches, and highlights important open questions. Recent work focuses on analysing the sample efficiency of such methods [65, 38] with close connections to learning from human feedback in real time [23, 32, 7].
Teaching and Inverse RL. The inverse RL (IRL) and apprenticeship learning literature examine the problem of learning directly from behavior [37, 1]. The classical problem of IRL is to identify which reward function (often up to an equivalence class) a given demonstrator is optimizing. We emphasize the relevance of two approaches: First, work by Syed et al. [55], who first illustrate the applicability of linear programming [22] to apprenticeship learning; and second, work by Amin et al. [4], who examine the repeated form of IRL. The methods of IRL have recently been expanded to include variations of cooperative IRL [14], and assistive learning [43], which offer different perspectives on how to frame interactive learning problems.
Reward Misspecification. Reward is also notoriously hard to specify. As pointed out by Littman et al. [30], “putting a meaningful dollar figure on scuffing a wall or dropping a clean fork is challenging.” Along these lines, Hadfield-Menell et al. [16] identify cases in which well-intentioned designers create reward functions that produce unintended behavior [39]. MacGlashan et al. [33] find that human-provided rewards tend to depend on a learning agent’s entire policy, rather than just the current state. Further, work by Hadfield-Menell et al. [15] and Kumar et al. [27] suggest that there are problems with reward as a learning mechanism due to misspecification and reward tampering [10]. These problems have given rise to approaches to reward learning, in which a reward function is inferred from some evidence such as behavior or comparisons thereof [20].
Other Notions of Task. As a final note, we highlight alternative approaches to task specification. Building on the Free Energy Principle [13, 12], Hafner et al. [17] consider a variety of task types in terms of minimization of distance to a desired target distribution [3]. Alternatively, Littman et al. [30] and Li et al. [28] propose variations of linear temporal logic (LTL) as a mechanism for specifying a task to RL agents, with related literature extending LTL to the multi-task [58] and multi-agent [18] settings, or using reward machines for capturing task structure [19]. Jothimurugan et al. [21] take a similar approach and propose a task specification language for RL based on logical formulas that evaluate whether trajectories satisfy the task, similar in spirit to the logical task compositions framework developed by Tasse et al. [57]. Many of these notions of task are more general than those we consider. A natural direction for future work broadens our analysis to include these kinds of task.
# 3 An Account of Reward’s Expressivity: The TASKQ and EXPRESSIONQ
Consider an onlooker, Alice, and an earnest learning agent, Bob, engaged in the interaction pictured in Figure 1. Suppose that Alice has a particular task in mind that she would like Bob to learn to solve, and that Alice constructs a reward function to incentivize Bob to pursue this task. Here, Alice is playing the role of “all of what we mean by goals and purposes” for Bob to pursue, with Bob playing the role of the standard reward-maximizing RL agent.
Two Questions About Task. To give us leverage to study the expressivity of reward, it is useful to draw a distinction between two stages of this process: 1) Alice thinks of a task that she would like Bob to learn to solve, and 2) Alice creates a reward function (and perhaps chooses $\gamma$ ) that conveys the chosen task to Bob. We inspect these two separately, framed by the following two questions. The first we call the task-definition question (TASKQ) which asks: What is a task? The second we call the task-expression question (EXPRESSIONQ) which asks: Which learning signal can be used as a mechanism for expressing any task to Bob?
Reward Answers The EXPRESSIONQ. We suggest that it may be useful to treat reward as an answer to the EXPRESSIONQ rather than the TASKQ. On this view, reward is treated as an expressive language for incentivizing reward-maximizing agents: Alice may attempt to translate any task into a reward function that incentivizes Bob to pursue the task, no matter which environment Bob inhabits, which task Alice has chosen, or how she has represented the task to herself. Indeed, it might be the case that Alice’s knowledge of the task far exceeds Bob’s representational or perceptual capacity. Alice may know every detail of the environment and define the task based on this holistic vantage, while Bob must learn to solve the task through interaction alone, relying only on a restricted class of functions for modeling and decision making.
Under this view, we can assess the expressivity of reward as an answer to the EXPRESSIONQ conditioned on how we answer the TASKQ. For example, if the TASKQ is answered in terms of natural language descriptions of desired states of affairs, then reward may fail to convey the chosen task due to the apparent mismatch in abstraction between natural language and reward (though some work has studied such a proposal [31, 62]).
# 3.1 Answers to the TASKQ: What is a Task?
In RL, tasks are often associated with a choice of goal, reward function $( R )$ , reward-discount pair $( R , \gamma )$ , or perhaps a choice of optimal policy (alongside those task types surveyed previously, such as LTL). However, it is unclear whether these constructs capture the entirety of what we mean by “task”.
For example, consider the Russell and Norvig [42] grid world: A $4 \times 3$ grid with one wall, one terminal fire state, and one terminal goal state (pictured with a particular reward function in Figure 4a). In such an environment, how might we think about tasks? A standard view is that the task is to reach the goal as quickly as possible. This account, however, fails to distinguish between the non-optimal behaviors, such as the costly behavior of the agent moving directly into the fire and the neutral behavior of the agent spending its existence in the start state. Indeed, characterizing a task in terms of choice of $\pi ^ { * }$ or goal fails to capture these distinctions. Our view is that a suitably rich account of task should allow for the characterization of this sort of preference, offering the flexibility to scale from specifying only the desirable behavior (or outcomes) to an arbitrary ordering over behaviors (or outcomes).
In light of these considerations, we propose three answers to the TASKQ that can convey general preferences over behavior or outcome: 1) A set of acceptable policies, 2) A partial ordering over policies, or 3) A partial ordering over trajectories. We adopt these three as they can capture many kinds of task while also allowing a great deal of flexibility in the level of detail of the specification.
<table><tr><td></td><td></td><td></td><td>NameNotation GeneralizesConstraints Induced by F</td></tr><tr><td>SOAPIIG</td><td></td><td>task-as-π*</td><td>equal: V"g(so)= V"g'(s0)> Vπb(s0),∀πg,πg∈IIG,πb∈IIB range: Vπg (so) > Vπb(so),∀πg∈llg,πb∈IIB</td></tr><tr><td>PO</td><td>LI</td><td>SOAP</td><td>(π1④π2)∈LI =→V1(so)④V″²(s0)</td></tr><tr><td>TO</td><td>LT,N</td><td></td><td>task-as-g0al (T1 ④ T2) ∈ LT,N =→ G(T1; So) ④ G(T2; S0)</td></tr></table>
Table 1: A summary of the three proposed task types. We further list the constraints that determine whether a reward function realizes each task type in an MDP, where we take $\oplus$ to be one of $\cdot _ { < } , \cdot >$ , or $" = "$ , and $G$ is the discounted return of the trajectory.
# 3.2 SOAPs, POs, and TOs
(SOAP) Set Of Acceptable Policies. A classical view of the equivalence of two reward functions is based on the optimal policies they induce. For instance, $\mathrm { N g }$ et al. [36] develop potential-based reward shaping by inspecting which shaped reward signals will ensure that the optimal policy is unchanged. Extrapolating, it is natural to say that for any environment $E$ , two reward functions are equivalent if the optimal policies they induce in $E$ are the same. In this way, a task is viewed as a choice of optimal policy. As discussed in the grid world example above, this notion of task fails to allow for the specification of the quality of other behaviors. For this reason, we generalize task-as-optimal-policy to a set of acceptable policies, defined as follows.
Definition 3.1. A set of acceptable policies $( S O A P )$ is a non-empty subset of the deterministic policies, $\Pi _ { G } \subseteq \Pi$ , with Π the set of all deterministic mappings from $s$ to $\mathcal { A }$ for a given $E$ .
With one task type defined, it is important to address what it means for a reward function to properly realize, express, or capture a task in a given environment. We offer the following account.
Definition 3.2. A reward function is said to realize a task $\mathcal { T }$ in an environment $E$ just when the start-state value (or return) induced by the reward function exactly adheres to the constraints of $\mathcal { T }$
Precise conditions for the realization of each task type are provided alongside each task definition, with a summary presented in column four of Table 1.
For SOAPs, we take the start-state value $V ^ { \pi } ( s _ { 0 } )$ to be the mechanism by which a reward function realizes a SOAP. That is, for a given $E$ and $\Pi _ { G }$ , a reward function $R$ is said to realize the $\Pi _ { G }$ in $E$ when the start-state value function is optimal for all good policies, and strictly higher than the start-state value of all other policies. It is clear that SOAP strictly generalizes a task in terms of a choice of optimal policy, as captured by the SOAP $\Pi _ { G } = \{ \pi ^ { * } \}$ .
We note that there are two natural ways for a reward function to realize a SOAP: First, each $\pi _ { g } \in \Pi _ { G }$ has optimal start-state value and all other policies are sub-optimal. We call this type equal-SOAP, or just SOAP for brevity. Alternatively, we might only require that the acceptable policies are each near-optimal, but are allowed to differ in start-state value so long as they are all better than every bad policy $\pi _ { b } \in \Pi _ { B }$ . That is, in this second kind, there exists an $\epsilon \geq 0$ such that every $\pi _ { g } \in \Pi _ { G }$ is $\epsilon$ -optimal in start-state value, $V ^ { \ast } ( s _ { 0 } ) - V ^ { \pi _ { g } } ( s _ { 0 } ) \leq \epsilon$ , while all other policies are worse. We call this second realization condition range-SOAP. We note that the range realization generalizes the equal one: Every equal-SOAP is a range-SOAP (by letting $\epsilon = 0$ ). However, there exist range-SOAPs that are expressible by Markov rewards that are not realizable as an equal-SOAP. We illustrate this fact with the following proposition. All proofs are presented in Appendix B.
Proposition 3.1. There exists a CMP, $E$ , and choice of $\Pi _ { G }$ such that $\Pi _ { G }$ can be realized under the range-SOAP criterion, but cannot be realized under the equal-SOAP criterion.
One such CMP is pictured Figure 2b. Consider the SOAP $\Pi _ { G } = \left\{ \pi _ { 1 1 } , \pi _ { 1 2 } , \pi _ { 2 1 } \right\}$ : Under the equalSOAP criterion, if each of these three policies are made optimal, any reward function will also make $\pi _ { 2 2 }$ (the only bad policy) optimal as well. In contrast, for the range criterion, we can choose a reward function that assigns lower rewards to $a _ { 2 }$ than $a _ { 1 }$ in both states. In general, we take the equal-SOAP realization as canonical, as it is naturally subsumed by our next task type.
(PO) Partial Ordering on Policies. Next, we suppose that Alice chooses a partial ordering on the deterministic policy space. That is, Alice might identify a some great policies, some good, and some bad policies to strictly avoid, and remain indifferent to the rest. POs strictly generalize equal SOAPs, as any such SOAP is a special choice of PO with only two equivalence classes. We offer the following definition of a PO.
Definition 3.3. A policy order $( P O )$ of the deterministic policies $\Pi$ is a partial order, denoted $L _ { \Pi }$
As with SOAPs, we take the start-state value $V ^ { \pi } ( s _ { 0 } )$ induced by a reward function $R$ as the mechanism by which policies are ordered. That is, given $E$ and $L _ { \Pi }$ , we say that a reward function $R$ realizes $L _ { \Pi }$ in $E$ if and only if the resulting MDP, $M = ( E , R )$ , produces a start-state value function that orders $\Pi$ according to $L _ { \Pi }$ .
(TO) Partial Ordering on Trajectories. A natural generalization of goal specification enriches a notion of task to include the details of how a goal is satisfied—that is, for Alice to relay some preference over trajectory space [63], as is done in preference based RL [64]. Concretely, we suppose Alice specifies a partial ordering on length $N$ trajectories of $( s , a )$ pairs, defined as follows.
Definition 3.4. A trajectory ordering $( T O )$ of length $N \in { \mathbb { N } }$ is a partial ordering $L _ { \tau , N }$ , with each trajectory $\tau$ consisting of $N$ state–action pairs, $\left\{ ( s _ { 0 } , a _ { 0 } ) , \ldots , ( a _ { N - 1 } , s _ { N - 1 } ) \right\}$ , with $s _ { 0 }$ the start state.
As with PO, we say that a reward function realizes a trajectory ordering $L _ { \tau , N }$ if the ordering determined by each trajectory’s cumulative discounted $N$ -step return from $s _ { 0 }$ , denoted $G ( \tau ; s _ { 0 } )$ , matches that of the given $L _ { \tau , N }$ . We note that trajectory orderings can generalize goal-based tasks at the expense of a larger specification. For instance, a TO can convey the task, “Safely reach the goal in less than thirty steps, or just get to the subgoal in less than twenty steps.”
Recap. We propose to assess the expressivity of reward by first answering the TASKQ in terms of SOAPs, POs, or TOs, as summarized by Table 1. We say that a task $\mathcal { T }$ is realized in an environment $E$ under reward function $R$ if the start-state value function (or return) produced by $R$ imposes the constraints specified by $\mathcal { T }$ , and are interested in whether reward can always realize a given task in any choice of $E$ . We make a number of assumptions along the way, including: (1) Reward functions are Markov and deterministic, (2) Policies of interest are deterministic, (3) The environment is a finite CMP, (4) $\gamma$ is part of the environment, (5) We ignore reward’s role in shaping the learning process, (6) Start-state value or return is the appropriate mechanism to determine if a reward function realizes a given task. Relaxation of these assumptions is a critical direction for future work.
# 4 Analysis: The Expressivity of Markov Reward
With our definitions and objectives in place, we now present our main results.
# 4.1 Express SOAPs, POs, and TOs
We first ask whether reward can always realize a given SOAP, PO, or TO, for an arbitrary $E$ . Our first result states that the answer is “no”—there are tasks that cannot be realized by any reward function.
Theorem 4.1. For each of SOAP, PO, and $T O$ , there exist $( E , \mathcal { T } )$ pairs for which no Markow reward function realizes $\mathcal { T }$ in $E$ .
Thus, reward is incapable of capturing certain tasks. What tasks are they, precisely? Intuitively, inexpressible tasks involve policies or trajectories that must be correlated in value in an MDP. That is, if two policies are nearly identical in behavior, it is unlikely that reward can capture the PO that places them at opposite ends of the ordering. A simple example is the “always move the same direction” task in a grid world, with state defined as an $( x , y )$ pair. The SOAP $\Pi _ { G } = \{ \pi _ { \left. } , \pi _ { \uparrow } , \pi _ { \right. } , \pi _ { \downarrow } \}$ conveys this task, but no Markov reward function can make these policies strictly higher in value than all others.
Example: Inexpressible SOAPs. Observe the two CMPs pictured in Figure 2, depicting two kinds of inexpressible SOAPs. On the left, we consider the SOAP $\bar { \Pi } _ { G } = \{ \pi _ { 2 1 } \}$ , containing only the policy that executes $a _ { 2 }$ in the left state $( s _ { 0 } )$ , and $a _ { 1 }$ in the right $( s _ { 1 } )$ . This SOAP is inexpressible through reward, but only because reward cannot distinguish the start-state value of $\pi _ { 2 1 }$ and $\pi _ { 2 2 }$ since the policies differ only in an unreachable state. This is reminiscent of Axiom 5 from Pitis [40], which explicitly excludes preferences of this sort. On the right, we find a more interesting case: The chosen SOAP is similar to the XOR function, $\Pi _ { G } = \{ \pi _ { 1 2 } , \pi _ { 2 1 } \}$ . Here, the task requires that the agent choose each action in exactly one state. However, there cannot exist a reward function that makes only these policies optimal, as by consequence, both policies $\pi _ { 1 1 }$ and $\pi _ { 2 2 }$ must be optimal as well.
 Figure 2: Two CMPs in which there is a SOAP that is not expressible under any Markov reward function. On the left, $\Pi _ { G } = \{ \pi _ { 2 1 } \}$ is not realizable, as $\pi _ { 2 1 }$ can not be made better than $\pi _ { 2 2 }$ because $s _ { 1 }$ is never reached. On the right, the XOR-like-SOAP, $\Pi _ { G } = \{ \pi _ { 1 2 } , \pi _ { 2 1 } \}$ is not realizable: To make these two policies optimal, it is entailed that $\pi _ { 2 2 }$ and $\pi _ { 1 1 }$ must be optimal, too.
Next, we show that Theorem 4.1 is not limited to a particular choice of transition function or $\gamma$
Proposition 4.2. There exist choices of $E _ { \neg T } = ( S , A , \gamma , s _ { 0 } )$ or $E _ { \neg \gamma } = ( S , A , T , s _ { 0 } )$ , together with a task $\mathcal { T }$ , such that there is no $( T , R )$ pair that realizes $\mathcal { T }$ in $E _ { \neg T }$ or $( R , \gamma )$ in $E _ { \neg \gamma }$ .
This result suggests that the scope of Theorem 4.1 is actually quite broad—even if the transition function or $\gamma$ are taken as part of the reward specification, there are tasks that cannot be expressed. We suspect there are ways to give a precise characterization of all inexpressible tasks from an axiomatic perspective, which we hope to study in future work.
# 4.2 Constructive Algorithms: Task to Reward
We now analyze how to determine whether an appropriate reward function can be constructed for any $( E , \mathcal { T } )$ pair. We pose a general form of the reward-design problem [34, 51, 9] as follows.
Definition 4.1. The REWARDDESIGN problem is: Given $E = ( \mathcal { S } , \mathcal { A } , T , \gamma , s _ { 0 } )$ , and a $\mathcal { T }$ , output a reward function $R _ { a l i c e }$ that ensures $\mathcal { T }$ is realized in $M = \left( E , R _ { a l i c e } \right)$ .
Indeed, for all three task types, there is an efficient algorithm for solving the reward-design problem. Theorem 4.3. The REWARDDESIGN problem can be solved in polynomial time, for any finite $E$ , and any $\mathcal { T }$ , so long as reward functions with infinitely many outputs are considered.
Therefore, for any choice of finite CMP, $E$ , and a SOAP, PO, or TO, we can find a reward function that perfectly realizes the task in the given environment, if such a reward function exists. Each of the three algorithms are based on forming a linear program that matches the constraints of the given task type, which is why reward functions with infinitely many outputs are required. Pseudo-code for SOAP-based reward design is presented in Algorithm 1. Intuitively, the algorithms compute the discounted expected-state visitation distribution for a collection of policies; in the case of SOAP, for instance, these policies include $\Pi _ { G }$ and what we call the “fringe”, the set of policies that differ from a $\pi _ { g } \in \Pi _ { G }$ by exactly one action. Then, we use these distributions to describe linear inequality constraints ensuring that the start-state value of the good policies are better than those of the fringe.
As highlighted by Theorem 4.1 there are SOAPs, POs, and TOs that are not realizable. Thus, it is important to determine how the algorithms mentioned in Theorem 4.3 will handle such cases. Our next corollary illustrates that the desirable outcome is achieved: For any $E$ and $\mathcal { T }$ , the algorithms will output a reward function that realizes $\mathcal { T }$ in $E$ , or output $_ { \perp } ,$ when no such function exists.
Corollary 4.4. For any task $\mathcal { T }$ and environment $E$ , deciding whether $\mathcal { T }$ is expressible in $E$ is solvable in polynomial time.
Together, Theorem 4.1 and Theorem 4.3 constitute our main results: There are environment–task pairs in which Markov reward cannot express the chosen task for each of SOAPs, POs, and TOs. However, there are efficient algorithms for deciding whether a task is expressible, and for constructing the realizing reward function when it exists. We will study the use of one of these algorithms in Section 5, but first attend to other aspects of reward’s expressivity.
# Algorithm 1 SOAP Reward Design
INPUT: $E = ( { \mathcal { S } } , A , T , \gamma , s _ { 0 } ) , \Pi _ { G }$ . OUTPUT: $R$ , or $\perp$ . 1: Πfringe = compute_fringe $\left( \Pi _ { G } \right)$ 2: for $\bar { \pi } _ { g , i } \in \Pi _ { G }$ do . Compute state-visitation distributions. 3: $\rho _ { g , i } =$ compute_exp_visit $( \pi _ { g , i } , E )$ 4: for $\pi _ { f , i } \in \Pi _ { \mathrm { f r i n g e } }$ do 5: $\rho _ { f , i } =$ compute_exp_visit $( \pi _ { f , i } , E )$ 6: $C _ { \mathrm { { e q } } } = \{ \}$ . Make Equality Constraints. 7: for $\pi _ { g , i } \in \Pi _ { G }$ do 8: $C _ { \mathrm { e q . } } \mathsf { a d d } ( \rho _ { g , 0 } ( s _ { 0 } ) \cdot X = \rho _ { g , i } ( s _ { 0 } ) \cdot X )$ 9: $C _ { \mathrm { i n e q } } = \{ \}$ . Make Inequality Constraints. 10: for $\bar { \pi } _ { f , j } \in \Pi _ { \mathrm { f r i n g e } }$ do 11: $\begin{array} { r } { \check { C } _ { \mathrm { i n e q . } } \mathsf { a d d } ( \check { \rho _ { f , j } } ( s _ { 0 } ) \cdot X + \epsilon \le \rho _ { g , 0 } ( s _ { 0 } ) \cdot X ) } \end{array}$ 12: $R _ { \mathrm { o u t } }$ , $\epsilon _ { \mathrm { o u t } } =$ linear_programming(obj. $= { \mathrm { m a x } } \epsilon$ , constraints $= C _ { \mathrm { i n e q } } , C _ { \mathrm { e q } } )$ . Solve LP. 13: if $\epsilon _ { \mathrm { o u t } } > 0$ then $\triangleright$ Check if successful. return $R _ { \mathrm { o u t } }$ 14: else return ⊥
# 4.3 Other Aspects of Reward’s Expressivity
We next briefly summarize other considerations about the expressivity of reward. As noted, Theorem 4.3 requires the use of a reward function that can produce infinitely many outputs. Our next result proves this requirement is strict for efficient reward design.
Theorem 4.5. A variant of the REWARDDESIGN problem with finite reward outputs is NP-hard.
We provide further details about the precise problem studied in Appendix B. Beyond reward functions with finitely-many outputs, we are also interested in extensions of our results to multiple environments. We next present a positive result indicating our algorithms can extend to the case where Alice would like to design a reward function for a single task across multiple environments.
Proposition 4.6. For any SOAP, PO, or TO, given a finite set of CMPs, $\mathcal { E } = \{ E _ { 1 } , \ldots , E _ { n } \}$ , with shared state–action space, there exists a polynomial time algorithm that outputs one reward function that realizes the task (when possible) in all CMPs in $\mathcal { E }$ .
A natural follow up question to the above result asks whether task realization is closed under a set of CMPs. Our next result answers this question in the negative.
Theorem 4.7. Task realization is not closed under sets of CMPs with shared state-action space. That is, there exist choices of $\mathcal { T }$ and $\mathcal { E } = \{ E _ { 1 } , \ldots , E _ { n } \}$ such that $\mathcal { T }$ is realizable in each $E _ { i } \in \mathcal { E }$ independently, but there is not a single reward function that realizes $\mathcal { T }$ in all $E _ { i } \in \mathcal { E }$ simultaneously.
Intuitively, this shows that Alice must know precisely which environment Bob will inhabit if she is to design an appropriate reward function. Otherwise, her uncertainty over $E$ may prevent her from designing a realizing reward function. We foresee iterative extensions of our algorithms in which Alice and Bob can react to one another, drawing inspiration from repeated IRL by Amin et al. [4].
# 5 Experiments
We next conduct experiments to shed further light on the findings of our analysis. Our focus is on SOAPs, though we anticipate the insights extend to POs and TOs as well with little complication. In the first experiment, we study the fraction of SOAPs that are expressible in small CMPs as we vary aspects of the environment or task (Figure 3). In the second, we use one algorithm from Theorem 4.3 to design a reward function, and contrast learning curves under a SOAP-designed reward function compared to standard rewards. Full details about the experiments are found in Appendix C.
 Figure 3: The approximate fraction of SOAPs that are expressible by reward in CMPs with a handful of states and actions, with $9 5 \%$ confidence intervals. In each plot, we vary a different parameter of the environment or task to illustrate how this change impacts the expressivity of reward, showing both equal (color) and range (grey) realization of SOAP.
SOAP Expressivity. First, we estimate the fraction of SOAPs that are expressible in small environments. For each data point, we sample 200 random SOAPs and run Algorithm 1 described by Theorem 4.3 to determine whether each SOAP is realizable in the given CMP. We ask this question for both the equal (color) variant of SOAP realization and the range (grey) variant. We inspect SOAP expressivity as we vary six different characteristics of $E$ or $\Pi _ { G }$ : The number of actions, the number of states, the discount $\gamma$ , the number of good policies in each SOAP, the Shannon entropy of $T$ at each $( s , a )$ pair, and the “spread” of each SOAP. The spread approximates average edit distance among policies in $\Pi _ { G }$ determined by randomly permuting actions of a reference policy by a coin weighted according to the value on the $\mathbf { X }$ -axis. We use the same set of CMPs for each environment up to any deviations explicitly made by the varied parameter (such as $\gamma$ or entropy). Unless otherwise stated, each CMP has four states and three actions, with a fixed but randomly chosen transition function.
Results are presented in Figure 3. We find that our theory is borne out in a number of ways. First, as Theorem 4.1 suggests, we find SOAP expressivity is strictly less than one in nearly all cases. This is evidence that inexpressible tasks are not only found in manufactured corner cases, but rather that expressivity is a spectrum. We further observe—as predicted by Proposition 3.1—clear separation between the expressivity of range-SOAP (grey) vs. equal-SOAP (color); there are many cases where we can find a reward function that makes the good policies near optimal and better than the bad, but cannot make those good policies all exactly optimal. Additionally, several trends emerge as we vary the parameter of environment or task, though we note that such trends are likely specific to the choice of CMP and may not hold in general. Perhaps the most striking trend is in Figure 3f, which shows a decrease in expressivity as the SOAPs become more spread out. This is quite sensible: A more spread out SOAP is likely to lead to more entailments of the kind discussed in Figure 2b.
Learning with SOAP-designed Rewards. Next, we contrast the learning performance of Qlearning under a SOAP-designed reward function (visualized in Figure 4a) with that of the regular goal-based reward in the Russell and Norvig [42] grid world. In this domain, there is 0.35 slip probability such that, on a ‘slip’ event, the agent randomly applies one of the two orthogonal action effects. The regular goal-based reward function provides $+ 1$ when the agent enters the terminal flag cell, and $- 1$ when the agent enters the terminal fire cell. The bottom left state is the start-state, and the black cell is an impassable wall.
 Figure 4: A SOAP-designed reward function (left) and the resulting learning curves (right) for Qlearning compared to the traditional reward function for the Russell and Norvig [42] grid world. Each series presents average performance over 50 runs of the experiment with $9 5 \%$ confidence intervals.
Results are presented in Figure 4. On the right, we present a particular kind of learning curve contrasting the performance of Q-learning with the SOAP reward (blue) and regular reward (green). The y-axis measures, at the end of each episode, the average (inverse) minimum edit distance between Q-learning’s greedy policy and any policy in the SOAP. Thus, when the series reaches 1.0, Q-learning’s greedy policy is identical to one of the two SOAP policies. We first find that Q-learning is able to quickly learn a $\pi _ { g } \in \Pi _ { G }$ under the designed reward function. We further observe that the typical reward does not induce a perfect match in policy—at convergence, the green curve hovers slightly below the blue, indicating that the default reward function is incentivizing different policies to be optimal. This is entirely sensible, as the two SOAP policies are extremely cautious around the fire; they choose the orthogonal (and thus, safe) action in fire-adjacent states, relying on slip probability to progress. Lastly, as expected given the amount of knowledge contained in the SOAP, the SOAP reward function allows Q-learning to rapidly identify a good policy compared to the typical reward.
# 6 Conclusion
We have here investigated the expressivity of Markov reward, framed around three new accounts of task. Our main results show that there exist choices of task and environment in which Markov reward cannot express the chosen task, but there are efficient algorithms that decide whether a task is expressible and construct a reward function that captures the task when such a function exists. We conclude with an empirical examination of our analysis, corroborating the findings of our theory. We take these to be first steps toward understanding the full scope of the reward hypothesis.
There are many routes forward. A key direction moves beyond the task types we study here, and relaxes our core assumptions—the environment might not be a finite CMP, Alice may not know the environment precisely, reward may be a function of history, or Alice may not know how Bob represents state. Along similar lines, a critical direction incorporates how reward impacts Bob’s learning dynamics rather than start-state value. Further, we note the potential relevance to the recent reward-is-enough hypothesis proposed by Silver et al. [44]; we foresee pathways to extend our analysis to examine this newer hypothesis, too. For instance, in future work, it is important to assess whether reward is capable of inducing the right kinds of attributes of cognition, not just behavior.
# Acknowledgments and Disclosure of Funding
The authors would like to thank André Barreto, Diana Borsa, Michael Bowling, Wilka Carvalho, Brian Christian, Jess Hamrick, Steven Hansen, Zac Kenton, Ramana Kumar, Katrina McKinney, Rémi Munos, Matt Overlan, Hado van Hasselt, and Ben Van Roy for helpful discussions. We would also like to thank the anonymous reviewers for their thoughtful feedback, and Brendan O’Donoghue for catching a typo in the appendix. Michael Littman was supported in part by funding from DARPA L2M, ONR MURI, NSF FMitF, and NSF RI.
References [1] Pieter Abbeel and Andrew Y. Ng. Apprenticeship learning via inverse reinforcement learning. In Proceedings of the International Conference on Machine learning, 2004. [2] David Ackley and Michael L. Littman. Interactions between learning and evolution. Artificial Life II, 1992. [3] Sundararaman Akshay, Nathalie Bertrand, Serge Haddad, and Loic Helouet. The steady-state control problem for Markov decision processes. In Proceedings of the International Conference on Quantitative Evaluation of Systems, 2013. [4] Kareem Amin, Nan Jiang, and Satinder Singh. Repeated inverse reinforcement learning. In Advances in Neural Information Processing Systems, 2017. [5] Marc G. Bellemare, Will Dabney, and Rémi Munos. A distributional perspective on reinforcement learning. In Proceedings of the International Conference on Machine Learning, 2017. [6] Brian Christian. The Alignment Problem: Machine Learning and Human Values, pages 130–131. Atlantic Books, 2021. [7] Paul F. Christiano, Jan Leike, Tom B. Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep reinforcement learning from human preferences. In Advances in Neural Information Processing Systems, 2017. [8] Gerard Debreu. Representation of a preference ordering by a numerical function. Decision Processes, 3:159–165, 1954. [9] Daniel Dewey. Reinforcement learning and the reward engineering principle. In Proceedings of the AAAI Spring Symposium Series, 2014. [10] Tom Everitt, Victoria Krakovna, Laurent Orseau, Marcus Hutter, and Shane Legg. Reinforcement learning with a corrupted reward channel. In Proceedings of the International Joint Conference on Artificial Intelligence, 2017. [11] William Fedus, Carles Gelada, Yoshua Bengio, Marc G. Bellemare, and Hugo Larochelle. Hyperbolic discounting and learning over multiple horizons. arXiv preprint arXiv:1902.06865, 2019. [12] Karl J. Friston. The free-energy principle: a unified brain theory? Nature reviews neuroscience, 11(2):127–138, 2010. [13] Karl J. Friston, Jean Daunizeau, and Stefan J. Kiebel. Reinforcement learning or active inference? PloS One, 4(7):e6421, 2009. [14] Dylan Hadfield-Menell, Anca Dragan, Pieter Abbeel, and Stuart Russell. Cooperative inverse reinforcement learning. In Advances in Neural Information Processing Systems, 2016. [15] Dylan Hadfield-Menell, Anca Dragan, Pieter Abbeel, and Stuart Russell. The off-switch game. In Proceedings of the International Joint Conference on Artificial Intelligence, 2017. [16] Dylan Hadfield-Menell, Smitha Milli, Pieter Abbeel, Stuart Russell, and Anca Dragan. Inverse reward design. In Advances in Neural Information Processing Systems, 2017. [17] Danijar Hafner, Pedro A. Ortega, Jimmy Ba, Thomas Parr, Karl J. Friston, and Nicolas Heess. Action and perception as divergence minimization. arXiv preprint arXiv:2009.01791, 2020. [18] Lewis Hammond, Alessandro Abate, Julian Gutierrez, and Michael Wooldridge. Multi-agent reinforcement learning with temporal logic specifications. In Proceedings of the International Conference on Autonomous Agents and Multiagent Systems, 2021. [19] Rodrigo Toro Icarte, Toryn Klassen, Richard Valenzano, and Sheila McIlraith. Using reward machines for high-level task specification and decomposition in reinforcement learning. In Proceedings of the International Conference on Machine Learning, 2018.
[20] Hong Jun Jeon, Smitha Milli, and Anca Dragan. Reward-rational (implicit) choice: A unifying formalism for reward learning. In Advances in Neural Information Processing Systems, 2020.
[21] Kishor Jothimurugan, Rajeev Alur, and Osbert Bastani. A composable specification language for reinforcement learning tasks. In Advances in Neural Information Processing Systems, 2020.
[22] Narendra Karmarkar. A new polynomial-time algorithm for linear programming. In Proceedings of the Annual ACM Symposium on Theory of Computing, 1984.
[23] W. Bradley Knox and Peter Stone. Interactively shaping agents via human reinforcement: The TAMER framework. In Proceedings of the International Conference on Knowledge Capture, 2009.
[24] Tjalling C. Koopmans. Stationary ordinal utility and impatience. Econometrica: Journal of the Econometric Society, pages 287–309, 1960.
[25] David Kreps. Notes on the Theory of Choice. Westview Press, 1988.
[26] Sai Krishna Gottipati, Yashaswi Pathak, Rohan Nuttall, Raviteja Chunduru, Ahmed Touati, Sriram Ganapathi Subramanian, Matthew E. Taylor, and Sarath Chandar. Maximum reward formulation in reinforcement learning. In NeurIPS Workshop on Deep Reinforcement Learning, 2020.
[27] Ramana Kumar, Jonathan Uesato, Richard Ngo, Tom Everitt, Victoria Krakovna, and Shane Legg. REALab: An embedded perspective on tampering. arXiv preprint arXiv:2011.08820, 2020.
[28] Xiao Li, Cristian-Ioan Vasile, and Calin Belta. Reinforcement learning with temporal logic rewards. In Proceedings of the International Conference on Intelligent Robots and Systems, 2017.
[29] Michael L. Littman. The reward hypothesis, 2017. URL https:// www.coursera.org/lecture/fundamentals-of-reinforcement-learning/ michael-littman-the-reward-hypothesis-q6x0e.
[30] Michael L. Littman, Ufuk Topcu, Jie Fu, Charles Isbell, Min Wen, and James MacGlashan. Environment-independent task specifications via GLTL. arXiv preprint arXiv:1704.04341, 2017.
[31] James MacGlashan, Monica Babes-Vroman, Marie desJardins, Michael L. Littman, Smaranda Muresan, Shawn Squire, Stefanie Tellex, Dilip Arumugam, and Lei Yang. Grounding English commands to reward functions. In Proceedings of Robotics: Science and Systems, 2015.
[32] James MacGlashan, Michael L. Littman, David L. Roberts, Robert Loftin, Bei Peng, and Matthew E. Taylor. Convergent actor critic by humans. In Proceedings of the International Conference on Intelligent Robots and Systems, 2016.
[33] James MacGlashan, Mark K. Ho, Robert Loftin, Bei Peng, Guan Wang, David L. Roberts, Matthew E. Taylor, and Michael L. Littman. Interactive learning from policy-dependent human feedback. In Proceedings of the International Conference on Machine Learning. PMLR, 2017.
[34] Maja J. Mataric. Reward functions for accelerated learning. In Proceedings of the International Conference on Machine Learning, 1994.
[35] L. G. Mitten. Preference order dynamic programming. Management Science, 21(1):43–46, 1974.
[36] Andrew Y. Ng, Daishi Harada, and Stuart Russell. Policy invariance under reward transformations: Theory and application to reward shaping. In Proceedings of the International Conference on Machine Learning, 1999.
[37] Andrew Y. Ng, Stuart J. Russell, et al. Algorithms for inverse reinforcement learning. In Proceedings of the International Conference on Machine Learning, 2000.
[38] Ellen Novoseller, Yibing Wei, Yanan Sui, Yisong Yue, and Joel Burdick. Dueling posterior sampling for preference-based reinforcement learning. In Proceedings of the Conference on Uncertainty in Artificial Intelligence, 2020. [39] Pedro A. Ortega, Vishal Maini, and the DeepMind Safety Team. Building safe artificial intelligence: specification, robustness, and assurance, 2018. URL https://medium.com/@deepmindsafetyresearch/ building-safe-artificial-intelligence-52f5f75058f1. [40] Silviu Pitis. Rethinking the discount factor in reinforcement learning: A decision theoretic approach. In Proceedings of the AAAI Conference on Artificial Intelligence, 2019. [41] Martin L. Puterman. Markov Decision Processes: Discrete Stochastic Dynamic Programming. John Wiley & Sons, 2014. [42] Stuart J. Russell and Peter Norvig. Artificial Intelligence: A Modern Approach. Prentice-Hall, Englewood Cliffs, NJ, 1994. ISBN 0-13-103805-2. [43] Rohin Shah, Pedro Freire, Neel Alex, Rachel Freedman, Dmitrii Krasheninnikov, Lawrence Chan, Michael D. Dennis, Pieter Abbeel, Anca Dragan, and Stuart Russell. Benefits of assistance over reward learning, 2021. URL https://openreview.net/forum?id $\ c =$ DFIoGDZejIB. [44] David Silver, Satinder Singh, Doina Precup, and Richard S. Sutton. Reward is enough. Artificial Intelligence, page 103535, 2021. [45] Satinder Singh, Andrew G. Barto, and Nuttapong Chentanez. Intrinsically motivated reinforcement learning. Technical report, University of Massachusetts at Amherst Department of Computer Science, 2005. [46] Satinder Singh, Richard L Lewis, and Andrew G Barto. Where do rewards come from? In Proceedings of the Annual Conference of the Cognitive Science Society, 2009. [47] Satinder Singh, Richard L. Lewis, Jonathan Sorg, Andrew G. Barto, and Akram Helou. On separating agent designer goals from agent goals: Breaking the preferences–parameters confound, 2010. [48] Matthew J. Sobel. Ordinal dynamic programming. Management science, 21(9):967–975, 1975. [49] Matthew J. Sobel. Discounting axioms imply risk neutrality. Annals of Operations Research, 208(1):417–432, 2013. [50] Jonathan Sorg. The Optimal Reward Problem: Designing Effective Reward for Bounded Agents. PhD thesis, University of Michigan, 2011. [51] Jonathan Sorg, Richard L. Lewis, and Satinder Singh. Reward design via online gradient ascent. Advances in Neural Information Processing Systems, 2010. [52] Peter Sunehag and Marcus Hutter. Axioms for rational reinforcement learning. In Proceedings of the International Conference on Algorithmic Learning Theory, 2011. [53] Richard S. Sutton. The reward hypothesis, 2004. URL http://incompleteideas.net/ rlai.cs.ualberta.ca/RLAI/rewardhypothesis.html. [54] Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. MIT Press, 2018. [55] Umar Syed, Michael Bowling, and Robert E. Schapire. Apprenticeship learning using linear programming. In Proceedings of the International Conference on Machine Learning, 2008. [56] Csaba Szepesvári. Constrained MDPs and the reward hypothesis, 2020. URL http:// readingsml.blogspot.com/2020/03/constrained-mdps-and-reward-hypothesis. html. [57] Geraud Nangue Tasse, Steven James, and Benjamin Rosman. A Boolean task algebra for reinforcement learning. In Advances in Neural Information Processing Systems, 2020. [58] Rodrigo Toro Icarte, Toryn Q. Klassen, Richard Valenzano, and Sheila A. McIlraith. Teaching multiple tasks to an RL agent using LTL. In Proceedings of the International Conference on Autonomous Agents and Multiagent Systems, 2018. [59] John von Neumann and Oskar Morgenstern. Theory of Games and Economic Behavior. Princeton University Press, 1953. [60] Paul Weng. Markov decision processes with ordinal rewards: Reference point-based preferences. In Proceedings of the International Conference on Automated Planning and Scheduling, 2011. [61] Martha White. Unifying task specification in reinforcement learning. In Proceedings of the International Conference on Machine Learning, 2017. [62] Edward C. Williams, Nakul Gopalan, Mine Rhee, and Stefanie Tellex. Learning to parse natural language to grounded reward functions with weak supervision. In Proceedings of the International Conference on Robotics and Automation, 2018. [63] Aaron Wilson, Alan Fern, and Prasad Tadepalli. A Bayesian approach for policy learning from trajectory preference queries. In Advances in Neural Information Processing Systems, 2012. [64] Christian Wirth, Riad Akrour, Gerhard Neumann, and Johannes Fürnkranz. A survey of preference-based reinforcement learning methods. The Journal of Machine Learning Research, 18(1):4945–4990, 2017. [65] Yichong Xu, Ruosong Wang, Lin Yang, Aarti Singh, and Artur Dubrawski. Preference-based reinforcement learning with finite-time guarantees. Advances in Neural Information Processing Systems, 33, 2020. [66] Zeyu Zheng, Junhyuk Oh, Matteo Hessel, Zhongwen Xu, Manuel Kroiss, Hado van Hasselt, David Silver, and Satinder Singh. What can learned intrinsic rewards capture? In Proceedings of the International Conference on Machine Learning, 2020.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461# Super-Acceleration with Cyclical Step-sizes
Anonymous Author(s) Affiliation Address email
# Abstract
1 Cyclical step-sizes are becoming increasingly popular in the optimization of deep 2 learning problems. Motivated by recent observations on the spectral gaps of 3 Hessians in machine learning, we show that these step-size schedules offer a 4 simple way to exploit them. More precisely, we develop a convergence rate 5 analysis for quadratic objectives that provides optimal parameters and shows that 6 cyclical learning rates can improve upon traditional lower complexity bounds. 7 We further propose a systematic approach to design optimal first order methods 8 for quadratic minimization with a given spectral structure. Finally, we provide a 9 local convergence rate analysis beyond quadratic minimization for the proposed 10 methods and illustrate our findings through benchmarks on least squares and 11 logistic regression problems.
# 12 1 Introduction
13 One of the most iconic methods in first order optimization is gradient descent with momentum, also 14 known as the heavy ball method [Polyak, 1964]. This method enjoys widespread popularity both in 15 its original formulation and in a stochastic variant that replaces the gradient by a stochastic estimate, 16 a method that is behind many of the recent breakthroughs in deep learning [Sutskever et al., 2013]. 17 A variant of the stochastic heavy ball where the step-sizes are chosen in cyclical order has recently 18 come to the forefront of machine learning research, showing state-of-the art results on different deep 19 learning benchmarks [Loshchilov and Hutter, 2017, Smith, 2017]. Inspired by this empirical success, 20 we aim to study the convergence of the heavy ball algorithm where step-sizes $h _ { 0 } , h _ { 1 } , \ldots$ are not fixed 21 or decreasing but instead chosen in cyclical order:
# Algorithm 1: Cyclical heavy ball $\mathrm { H B } _ { K } ( h _ { 0 } , \ldots , h _ { K - 1 } ; m )$
Input: Initialization $x _ { 0 }$ , momentum $m \in ( 0 , 1 )$ , step-sizes $\{ h _ { 0 } , \ldots , h _ { K - 1 } \}$ $\begin{array} { r l } & { x _ { 1 } = x _ { 0 } - \frac { h _ { 0 } } { 1 + m } \nabla f ( x _ { 0 } ) } \\ & { { \bf f o r } t = 1 , 2 , \dots { \bf d o } x _ { t + 1 } = x _ { t } - h _ { \mathrm { m o d } ( t , K ) } \nabla f ( x _ { t } ) + m ( x _ { t } - x _ { t - 1 } ) } \end{array}$ 1 end
22 The heavy ball method with constant step-sizes enjoys a mature theory, where it is known for example 23 to achieve optimal black-box worst-case complexity of quadratic convex optimization [Nemirovsky, 24 1992]. In stark contrast, little is known about the the convergence of the above variant with cyclical 25 step-sizes. Our main motivating question is
Do cyclical step-sizes improve convergence of heavy ball?
27 Our main contribution provides a positive answer to this question and, more importantly, quantifies 28 the speedup under different assumptions. In particular, we show that for quadratic problems, whenever 29 Hessian’s spectrum belongs to two or more disjoint intervals, the heavy ball method with cyclical step 30 sizes achieves a faster worst-case convergence rate. Recent works have shown that this assumption on 31 the spectrum is quite natural and occurs in many machine learning problems, including deep neural 32 networks [Sagun et al., 2017, Papyan, 2018, Ghorbani et al., 2019, Papyan, 2019]. More precisely, 33 we list our main contributions below. 34 • In sections 3 and 4, we provide a tight convergence rate analysis of the cyclical heavy ball method 35 (Theorems 3.1 and 3.2 for two step-sizes, and Theorem 4.8 for the general case). This analysis 36 highlights a regime under which this method achieves a faster worst-case rate than the accelerated 37 rate of heavy ball, a phenomenon we refer to as super-acceleration. Theorem 5.1 extends the (local) 38 convergence rate analysis results to non-quadratic objectives. 39 • As a byproduct of the convergence-rate analysis, we obtain an explicit expression for the optimal 40 parameters in in the case of cycles of length two (Algorithm 2) and an implicit expression in terms 41 of a system of $K$ equations in the general case.
• Section 6 presents numerical benchmarks illustrating the improved convergence of the cyclical approach on 4 problems involving quadratic and logistic losses on both synthetic and a handwritten digits recognition dataset.
• Finally, we conclude in Section 7 with a discussion of this work’s limitations.
# 46 2 Notation and Problem Setting
47 Throughout the paper, we consider the problem of minimizing quadratic functions of the form
$$\operatorname* { m i n } _ { \alpha \in \mathbb { B } ^ { d } } f ( x ) , \mathrm { w i t h } f \in \mathcal { C } _ { \Lambda } \triangleq \left\{ f : f ( x ) = \frac { 1 } { 2 } ( x - x _ { * } ) ^ { T } H ( x - x _ { * } ) + f _ { * } , \mathrm { S p } ( H ) \subseteq \Lambda \right\} ,$$
48 where $\mathcal { C } _ { \Lambda }$ is the class of quadratic functions whose spectrum $\operatorname { S p } ( H )$ is localized in $\Lambda \subseteq [ \mu , L ] \subseteq \mathbb { R } _ { > 0 }$ 49 We discuss more general settings beyond quadratic minimization in Section 5. 50 The condition $\Lambda \subseteq [ \mu , L ]$ implies all quadratic functions under consideration are $L$ -smooth and 51 $\mu$ -strongly convex. For this function class, we define $\kappa$ , the (inverse) condition number, and $\rho$ , the 52 ratio between the center of $\Lambda$ and its radius, as
$$\begin{array} { r l } { \kappa \triangleq \frac { \mu } { L } , \qquad \rho \triangleq \frac { L + \mu } { L - \mu } } & { = \left( \frac { 1 + \kappa } { 1 - \kappa } \right) . } \end{array}$$
53 Finally, for a method solving (OPT) that generates a sequence of iterates $\{ x _ { t } \}$ , we define its worst-case 54 rate $r _ { t }$ and its asymptotic rate factor $\tau$ as
$$r _ { t } \triangleq \operatorname* { s u p } _ { x _ { 0 } \in \mathbb { R } ^ { d } , f \in \mathcal { C } _ { \Lambda } } \frac { \Vert x _ { t } - x _ { * } \Vert } { \Vert x _ { 0 } - x _ { * } \Vert } , \qquad 1 - \tau \triangleq \operatorname* { l i m } _ { t \to \infty } \operatorname* { s u p } _ { \tau \in \mathcal { C } _ { \Lambda } } \sqrt { r _ { t } } .$$
# 55 3 Super-acceleration with Cyclical Step-sizes
<table><tr><td colspan="3">Algorithm 2: Cyclical (K = 2) heavy ball with with optimal parameters</td></tr><tr><td colspan="3">Input: Initialization xo,μ1<L1 < μ2<L2 (whereL1-μ1=L2-μ2)</td></tr><tr><td>Set: p = L2+μ1 R= μ2-L1 L2-μ1 L2-μ1</td><td colspan="2">Vp²-R2-√p2-1 2 m= √1-R²</td></tr><tr><td colspan="3">χ1= xo-∀f(xo)</td></tr><tr><td>for t = 1, 2,... do ht= 1+m</td><td></td><td></td></tr><tr><td></td><td>(if t is even), ht=1+m L1</td><td>(if t is odd) μ2</td></tr><tr><td></td><td>Xt+1= xt-htVf(xt)+m(xt-xt-1)</td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td>end</td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr></table>
56 In this section we develop one of our main contri 57 butions, a convergence rate analysis of the cyclical 58 heavy ball method with cycles of length 2. This analy 59 sis crucially depends on the location of the Hessian’s 60 eigenvalues; we assume that these are contained in a 61 set $\Lambda$ that is the union of 2 intervals of the same size
$$\Lambda = [ \mu _ { 1 } , L _ { 1 } ] \cup [ \mu _ { 2 } , L _ { 2 } ] , L _ { 1 } - \mu _ { 1 } = L _ { 2 } - \mu _ { 2 } .$$
62 By symmetry, this set is alternatively described by
$$\mu \triangleq \mu _ { 1 } , \quad L \triangleq L _ { 2 } \quad { \mathrm { a n d } } \quad R \triangleq { \frac { \mu _ { 2 } - L _ { 1 } } { L _ { 2 } - \mu _ { 1 } } } ,$$
63 where $R$ is the relative length of the gap $\mu _ { 2 } - L _ { 1 }$ 64 with respect to the diameter $L _ { \mathrm { 2 } } - \mu _ { \mathrm { 1 } }$ (see Figure 1). 65 This parametrization will reveal very convenient as 66 the relative gap will play a crucial role in the conver 67 gence rate analysis. Note also that the gap assumption 68 comes without loss of generality, as we allow $R = 0$ . 69 Through a correspondence between optimization 70 methods and polynomials that we expand upon in 71 Section 4, we can derive a worst-case analysis for the cyclical heavy ball method. The outcome of 72 this analysis is in the following theorem, that provides the asymptotic convergence rate of Algorithm 73 1 for cycles of length two. All proofs of results in this section can be found in Appendix D.3. 74 Theorem 3.1 (Rate factor of $\mathrm { H B } _ { 2 } ( h _ { 0 } , h _ { 1 } ; m ) )$ . Let $f \in { \mathcal { C } } _ { \Lambda }$ and $h _ { 0 } , h _ { 1 } , m \ge 0 .$ The asymptotic rate 75 factor of Algorithm 1 with cycles of length two is
 Figure 1: Hessian eigenvalue histogram for a quadratic objective on MNIST. The outlier eigenvalue at $L _ { 2 }$ generates a non-zero relative gap $R = 0 . 7 7$ . Under these conditions, the 2-cycle heavy ball method has a faster asymptotic rate than the single-cycle one (see Section 3.1).
$$\begin{array} { r l } & { 1 - \tau = \left\{ \begin{array} { l l } { \sqrt { m } } & { \mathrm { i f ~ } \sigma _ { \mathrm { s u p } } \leq 1 , } \\ { \sqrt { m } \left( \sigma _ { \mathrm { s u p } } + \sqrt { \sigma _ { \mathrm { s u p } } ^ { 2 } - 1 } \right) ^ { \frac { 1 } { 2 } } } & { \mathrm { i f ~ } \sigma _ { \mathrm { s u p } } \in \left( 1 , \frac { 1 + m ^ { 2 } } { 2 m } \right) , } \\ { \geq 1 \left( n o c o n v e r g e n c e \right) } & { \mathrm { i f ~ } \frac { 1 + m ^ { 2 } } { 2 m } \leq \sigma _ { \mathrm { s u p } } , } \end{array} \right. } \\ & { \sigma _ { \mathrm { s u p } } = \underset { \lambda \in \left\{ \mu _ { 1 } , L _ { 1 } , \mu _ { 2 } , L _ { 2 } , \frac { h _ { 0 } + h _ { 1 } } { 2 h _ { 0 } h _ { 1 } } \right\} \cap \Lambda } { \operatorname* { s u p } } \Big | 2 \left( \frac { 1 + m - \lambda h _ { 0 } } { 2 \sqrt { m } } \right) \left( \frac { 1 + m - \lambda h _ { 1 } } { 2 \sqrt { m } } \right) - 1 \Big | \ . } \end{array}$$
76
77 This theorem gives the convergence rate for all triplets $( m , h _ { 0 } , h _ { 1 } )$ . By evaluating this expression over a grid of step-sizes, Figure 2 shows how the rate changes as a function of both step-sizes:
 Figure 2: Asymptotic rate of cyclical $K = 2$ ) heavy ball in terms of its step-sizes $h _ { 0 } , h _ { 1 }$ across 3 different values of the relative gap $R$ . In the left plot, the relative gap is zero, and so the step-sizes with smallest rate coincide $h _ { 0 } = h _ { 1 } \mathrm { , }$ ). For non-zero values of $R$ (center and right), the optimal method instead alternates between two different step-sizes. In all plots the momentum parameter $m$ is set according to Algorithm 2.
79 From the asymptotic rate expression of Theorem 3.1 we can optimize over the parameters $( h _ { 0 } , h _ { 1 } , m )$ 80 to obtain the method with smallest convergence rate. This leads to our other main contribution of this 81 section, the asymptotically optimal Algorithm 2. This algorithm enjoys the following rate:
Corollary 3.2. The worst-case (asymptotic) rates 82 $r _ { t } ^ { A l g . 2 }$ and $1 - \tau ^ { A l g . 2 }$ of Algorithm 2 over $\mathcal { C } _ { \Lambda }$ are
$$\begin{array} { r } { r _ { t } ^ { A l g . ~ 2 } = \left( 1 + t \sqrt { \frac { \rho ^ { 2 } - 1 } { \rho ^ { 2 } - R ^ { 2 } } } \right) \left( \frac { \sqrt { \rho ^ { 2 } - R ^ { 2 } } - \sqrt { \rho ^ { 2 } - 1 } } { \sqrt { 1 - R ^ { 2 } } } \right) ^ { t } , \quad 1 - \tau ^ { A l g . ~ 2 } = \frac { \sqrt { \rho ^ { 2 } - R ^ { 2 } } - \sqrt { \rho ^ { 2 } - 1 } } { \sqrt { 1 - R ^ { 2 } } } \quad f _ { 0 } = \tau ^ { A l g . ~ 2 } , } \end{array}$$
# 83 3.1 Comparison with Polyak Heavy Ball
84 In the absence of eigenvalue gap $R = 0$ and $\Lambda = [ \mu , L ] )$ , Algorithm 2 reduces to Polyak heavy 85 ball (PHB) [Polyak, 1964], whose worst-case rate is detailed in Appendix B. Since the asymptotic rate 86 of Algorithm 2 is monotonically decreasing in $R$ , it is always better or equal than PHB. Furthermore, 87 in the ill-conditioned regime (small $\kappa$ ), the comparison is particularly simple: the optimal 2-cycle 88 algorithm has a $\sqrt { 1 - R ^ { 2 } }$ relative improvement over PHB, as provided by the next proposition. 89 A more thorough comparison for different support sets $\Lambda$ is discussed in Table 1.
Proposition 3.3. Let $R \in [ 0 , 1 )$ . The rate factors of respectively Algorithm 2 and PHB verify
$$\begin{array} { r l r } { 1 - \tau ^ { A l g . 2 } \underset { \kappa 0 } { = } 1 - \frac { 2 \sqrt { \kappa } } { \sqrt { 1 - R ^ { 2 } } } + o ( \sqrt { \kappa } ) , } & { } & { 1 - \tau ^ { P H B } \underset { \kappa 0 } { = } 1 - 2 \sqrt { \kappa } + o ( \sqrt { \kappa } ) . } \end{array}$$
<table><tr><td>Relative gap R</td><td>Set A</td><td></td><td>Rate factor TSpeedup T/7PHB</td></tr><tr><td>R ∈ [0,1)</td><td>[μ,μ+R(L-μ)]U[L-R(L-μ),L]</td><td>2√ 1-R</td><td>(1-R²)-</td></tr><tr><td>R=1-√K/2</td><td>[,μ+]U[-,]</td><td>2Vk</td><td>K</td></tr><tr><td>R=1-2γK</td><td>[μ,(1+γ)μ]U[L- γμ,L]</td><td> indep. of K</td><td>0(√)</td></tr></table>
Table 1: Case study of the convergence of Algorithm 2 as a function of $R$ , in the regime $\kappa 0$ . The first line corresponds to the regime where $R$ is independent of $\kappa$ , and we observe a constant gain w.r.t. PHB. The second line considers a setting in which $R$ depends on $\sqrt { \kappa }$ , that is, the two intervals in $\Lambda$ are relatively small. The asymptotic rate reads $( 1 - 2 \sqrt [ 4 ] { \kappa } ) ^ { t }$ , beating the classical $( 1 - 2 \sqrt { \kappa } ) ^ { t }$ lower bound, unimprovable when $R = 0$ . Finally, in the third line, $R$ depends on $\kappa$ , the two intervals in $\Lambda$ are so small that the convergence becomes $O ( 1 )$ , i.e., is independent of $\kappa$ .
# 91 4 A constructive Approach: Minimax Polynomials
92 This section presents a generic framework (Algorithm 3) that allows designing optimal momentum 93 and step-size cycles for given sets $\Lambda$ and cycle length $K$ .
# Algorithm 3: Optimal momentum method with cyclical step-sizes
Input: Eigenvalue localization $\Lambda$ , cycle length $K$ , initialization $x _ { 0 }$ . Preprocessing:
1. Find the polynomial $\sigma _ { K } ^ { \Lambda }$ such that it satisfies (16).
2. Set step-sizes $\{ h _ { i } \} _ { i = 0 , \dots , K - 1 }$ and momentum $m$ that satisfy resp. equations (21) and (22).
for $t = 1$ $x _ { 1 } = x _ { 0 } - \frac { h _ { 0 } } { 1 + m } \nabla f ( x _ { 0 } )$ , 2, . . . do $\begin{array} { r l } & { \nabla f ( x _ { 0 } ) } \\ & { \quad x _ { t + 1 } = x _ { t } - h _ { \mathrm { m o d } ( t , K ) } \nabla f ( x _ { t } ) + m ( x _ { t } - x _ { t - 1 } ) } \end{array}$ end
94 We first recall classical results that link optimal first order methods on quadratics and Chebyshev 95 polynomials. Then, we generalize the approach by showing that optimal methods can be viewed as
combinations of Chebyshev polynomials, and minimax polynomials 96 $\sigma _ { K } ^ { \Lambda }$ of degree $K$ over the set $\Lambda$ Finally, we show how to recover the step-size schedule from 97 $\sigma _ { K } ^ { \Lambda }$ .
# 4.1 First Order Methods on Quadratics and Polynomials
A key property that we will use extensively in the analysis is the following link between first order methods and polynomials (see [Hestenes and Stiefel, 1952]).
101 Proposition 4.1. Let $f \in { \mathcal { C } } _ { \Lambda }$ . The iterates $x _ { t }$ satisfy
$$x _ { t + 1 } \in x _ { 0 } + \operatorname { s p a n } \{ \nabla f ( x _ { 0 } ) , \ldots , \nabla f ( x _ { t } ) \} ,$$
102 where $x _ { 0 }$ is the initial approximation of $x _ { * }$ , if and only if there exists a sequence of polynomials 103 $( P _ { t } ) _ { t \in \mathbb { N } }$ , each of degree at most $I$ more than the highest degree of all previous polynomials and $P _ { 0 }$ of 104 degree $O$ (hence the degree of $P _ { t }$ is at most $t$ ), such that
$$\forall t \quad x _ { t } - x _ { * } = P _ { t } ( H ) ( x _ { 0 } - x _ { * } ) , \quad P _ { t } ( 0 ) = 1 .$$
05 Example 4.2 (Gradient descent). Consider the gradient descent algorithm with fixed step-size $h$ , 106 applied to problem (OPT). Then, after unrolling the update, we have
$$x _ { t + 1 } - x _ { * } = x _ { t } - x _ { * } - h \nabla f ( x _ { t } ) = x _ { t } - x _ { * } - h H ( x _ { t } - x _ { * } ) = ( I - h H ) ^ { t + 1 } ( x _ { 0 } - x _ { * } ) .$$
In this case, the polynomial associated to gradient descent is $P _ { t } ( \lambda ) = ( 1 - h \lambda ) ^ { t }$ .
108 The above proposition can be used to obtain worst-case rates for first order methods by bounding 109 their associated polynomials. Indeed, using the Cauchy-Schwartz inequality in (9) leads to
$$\| x _ { t } - x _ { * } \| \leq \operatorname* { s u p } _ { \lambda \in \Lambda } | P _ { t } ( \lambda ) | \ \| x _ { 0 } - x _ { * } \| \quad \Longrightarrow \quad r _ { t } = \operatorname* { s u p } _ { \lambda \in \Lambda } | P _ { t } ( \lambda ) | , \quad \mathrm { w h e r e } \ P ( 0 ) = 1 .$$
110 Therefore, finding the algorithm with the fastest worst-case rate can be equivalently framed as the 111 problem of finding the polynomial with smallest value on the eigenvalue support $\Lambda$ , subject to the 112 normalization condition $\dot { P _ { t } } ( 0 ) = 1$ . Such polynomials are referred to as minimax. Throughout the 113 paper, we use this polynomial-based approach to find methods with optimal rates. 114 An important property of minimax polynomials is their equioscillation on $\Lambda$ (see Theorem C.1 and 115 its proof for a formal statement). 116 Definition 4.3. (Equioscillation) A polynomial $P _ { t }$ equioscillates on $\Lambda$ if it verifies $P _ { t } ( 0 ) = 1$ and 117 there exist $\lambda _ { 0 } < \lambda _ { 1 } < . . . < \lambda _ { t } \in \Lambda$ such that
$$P _ { t } ( \lambda _ { i } ) = ( - 1 ) ^ { i } \operatorname* { m a x } _ { \lambda \in \Lambda } | P _ { t } ( \Lambda ) | .$$
118 Example 4.4 $\Lambda$ is an interval). The $t { \cdot }$ -th order Chebyshev polynomials of the first kind $T _ { t }$ satisfy 119 the equioscillation property on $[ - 1 , 1 ]$ . It follows that minimax polynomials on $\Lambda = [ \mu , L ]$ can be 120 obtained by composing the Chebyshev polynomial $T _ { t }$ with the linear transformation $\sigma _ { 1 } ^ { \Lambda }$ :
$$\frac { T _ { t } \left( \sigma _ { 1 } ^ { \Lambda } ( \lambda ) \right) } { T _ { t } \left( \sigma _ { 1 } ^ { \Lambda } ( 0 ) \right) } = \operatorname * { a r g m i n } _ { P \in \mathbb { R } _ { t } [ X ] , P ( 0 ) = 1 } \operatorname * { s u p } _ { \lambda \in \Lambda } \lvert P ( \lambda ) \rvert , \mathrm { w i t h } \sigma _ { 1 } ^ { \Lambda } ( \lambda ) = \frac { L + \mu } { L - \mu } - \frac { 2 } { L - \mu } \lambda ,$$
121 where $\sigma _ { 1 } ^ { \Lambda }$ maps the interval $[ \mu , L ]$ to $[ - 1 , 1 ]$ . The optimization method associated with this minimax 122 polynomial is the Chebyshev semi-terative method [Flanders and Shortley, 1950, Golub and Varga, 123 1961] (described also in Appendix B.1). This method achieves the lower complexity bound for 124 smooth strongly convex quadratic minimization, see for instance [Nemirovsky, 1995, Chapter 12] or 125 [Nemirovsky, 1992, Nesterov, 2003]. 126 The next proposition provides the main results in this subsection, which is key for obtaining Algo 127 rithm 2. It characterizes the even degree minimax polynomial in the setting of Section 3, that is, 128 129 when Cheb $\Lambda$ is the union of 2 intervals of same size. In this case, the minihev polynomials, but composed with a degree-two polynomial $\sigma _ { 2 } ^ { \Lambda }$ solution is also based on.
130 Proposition 4.5. Let $\Lambda = [ \mu _ { 1 } , L _ { 1 } ] \cup [ \mu _ { 2 } , L _ { 2 } ]$ be an union of two intervals of the same size 131 $( L _ { 1 } - \mu _ { 1 } = L _ { 2 } - \mu _ { 2 } )$ and let m be as defined in Algorithm 2. Then the minimax polynomial (solution to (12)) is, for all 132 $t = 2 n$ , $n \in \mathbb { N } _ { 0 } ^ { + }$ ,
$${ \frac { T _ { n } \left( \sigma _ { 2 } ^ { \Lambda } ( \lambda ) \right) } { T _ { n } \left( \sigma _ { 2 } ^ { \Lambda } ( 0 ) \right) } } = \underset { P ( 0 ) = 1 } { \operatorname { a r g m i n } } \ \underset { \lambda \in \Lambda } { \operatorname* { s u p } } | P ( \lambda ) | , \ w i t h \ \ \sigma _ { 2 } ^ { \Lambda } ( \lambda ) = 2 \left( { \frac { 1 + m } { 2 \sqrt { m } } } \right) ^ { 2 } \left( 1 - { \frac { \lambda } { L _ { 1 } } } \right) \left( 1 - { \frac { \lambda } { \mu _ { 2 } } } \right) - 1 .$$
134 The polynomial in Example 4.4 uses a linear link function $\sigma _ { 1 } ^ { \Lambda }$ to map $\Lambda$ to $[ - 1 , 1 ]$ . In Proposition 4.5, 135 we see that a degree two link function $\sigma _ { 2 } ^ { \Lambda }$ can be used to find the minimax polynomial when $\Lambda$ is the 136 union of two intervals. This section generalizes this approach and considers higher-order polynomials 137 for $\sigma _ { K }$ . We start with the following parametrization, with an arbitrary polynomial $\sigma _ { K }$ of degree $K$ ,
$$P _ { t } ( \lambda ; \sigma _ { K } ) \triangleq \frac { T _ { n } \left( \sigma _ { K } ( \lambda ) \right) } { T _ { n } \left( \sigma _ { K } ( 0 ) \right) } , \quad \forall t = K n , n \in \mathbb { N } _ { 0 } ^ { + } .$$
138 As we will see in the next subsection, this parametrization allows considering cycles of step-sizes. 139 Our goal now is to find the $\sigma _ { K }$ that obtains the fastest convergence rate possible. The next proposition 140 quantifies its impact on the asymptotic rate and its proof can be found in Appendix D.1. 141 Proposition 4.6. For a given $\sigma _ { K }$ such that $\operatorname* { s u p } _ { \lambda \in \Lambda } | \sigma _ { K } ( \lambda ) | = 1$ , the asymptotic rate factor $\tau ^ { \sigma _ { K } }$ of 142 the method associated to the polynomial (14) is
$$1 - \tau ^ { \sigma \kappa } = \operatorname * { l i m } _ { t \infty } \sqrt { \smash [ b ] { \operatorname { s u p } _ { \lambda \in \Lambda } | P _ { t } ( \lambda ; \sigma _ { K } ) | } } = ( \sigma _ { 0 } - \sqrt { \sigma _ { 0 } ^ { 2 } - 1 } ) ^ { \frac { 1 } { \kappa } } , \quad w i t h \ \sigma _ { 0 } \triangleq \sigma _ { K } ( 0 ) .$$
143 For a fixed $K$ , the asymptotic rate (15) is a decreasing function of $\sigma _ { 0 }$ . This motivates the introduction of the “optimal” degree 144 $K$ polynomial $\sigma _ { K } ^ { \Lambda }$ as the one that solves
$$\sigma _ { K } ^ { \Lambda } \triangleq \underset { \sigma \in \mathbb { R } _ { K } [ X ] } { \arg \operatorname* { m a x } } \sigma ( 0 ) \quad \mathrm { s . t . } ~ \underset { \lambda \in \Lambda } { \operatorname* { s u p } } | \sigma ( \lambda ) | = 1 .$$
Using the above definition, we recover the 145 $\sigma _ { 1 } ^ { \Lambda }$ and $\sigma _ { 2 } ^ { \Lambda }$ from Example 4.4 and Proposition 4.5.
146 Finding the polynomial. Finding an exact and explicit solution for the general $K$ and $\Lambda$ case 147 148 equations. Here we describe an approximate approach. Let σΛK (x) = PKi=0 σixi . We propose to 149
$$\begin{array} { r } { \underset { \sigma _ { i } } { \operatorname* { m a x } } \sigma _ { 0 } \quad \mathrm { ~ s . t . ~ } - 1 \leq \sum _ { i = 0 } ^ { K } \sigma _ { i } \lambda _ { j } ^ { i } \leq 1 , \quad \forall j = 1 , \ldots , N . } \end{array}$$
To check the optimality, it suffices to verify that the polynomial 50 $\sigma _ { K } ^ { \Lambda }$ satisfies the equioscillation 151 property (Definition 4.3), as depicted in Figure 3.
152 Remark 4.7 (Relationship between optimal and minimax polynomials). For later reference, we note 153 that the optimal polynomial $\sigma _ { K } ^ { \Lambda }$ is equivalent to finding a minimax polynomial on $\Lambda$ and to rescale it. 154 More precisely, $\sigma _ { K } ^ { \Lambda }$ is optimal if and only if $\sigma _ { K } ^ { \Lambda } / \sigma _ { K } ^ { \Lambda } ( 0 )$ is minimax.
# 155 4.3 Cyclical Heavy Ball and (Non-)asymptotic Rates of Convergence
We now describe the link between 156 $\sigma _ { K } ^ { \Lambda }$ and Algorithm 3. Using the recurrence for Chebyshev polynomials of the first kind in (14), we have 157 $\forall t = K n$ , $n \in \mathbb { N } _ { 0 } ^ { + }$ ,
$$\frac { T _ { n + 1 } ( \sigma _ { K } ^ { \Lambda } ( \lambda ) ) } { T _ { n + 1 } ( \sigma _ { K } ^ { \Lambda } ( 0 ) ) } = 2 \sigma _ { K } ^ { \Lambda } ( \lambda ) \left[ \frac { T _ { n } ( \sigma _ { K } ^ { \Lambda } ( \lambda ) ) } { T _ { n } ( \sigma _ { K } ^ { \Lambda } ( 0 ) ) } \right] \underbrace { \left[ \frac { T _ { n } ( \sigma _ { K } ^ { \Lambda } ( 0 ) ) } { T _ { n + 1 } ( \sigma _ { K } ^ { \Lambda } ( 0 ) ) } \right] } _ { = a _ { n } } - \left[ \frac { T _ { n - 1 } ( \sigma _ { K } ^ { \Lambda } ( \lambda ) ) } { T _ { n - 1 } ( \sigma _ { K } ^ { \Lambda } ( 0 ) ) } \right] \underbrace { \left[ \frac { T _ { n - 1 } ( \sigma _ { K } ^ { \Lambda } ( 0 ) ) } { T _ { n + 1 } ( \sigma _ { K } ^ { \Lambda } ( 0 ) ) } \right] } _ { = b _ { n } } .$$
158 It still remains to find an algorithm associated with this polynomial. To obtain one in the form of 159 Algorithm 1, one can use the stationary behavior of the recurrence. From [Scieur and Pedregosa, 160 2020], the coefficients $a _ { n }$ and $b _ { n }$ converge as $n \to \infty$ to their fixed-points $a _ { \infty }$ and $b _ { \infty }$ . We therefore 161 consider here an asymptotic polynomial $\big ( \bar { P } _ { t } ( \lambda ; \sigma _ { K } ^ { \Lambda } )$ , whose recurrence satisfies
$$\bar { P } _ { t } ( \lambda ; \sigma _ { K } ^ { \Lambda } ) = 2 a _ { \infty } \sigma _ { K } ^ { \Lambda } ( \lambda ) \bar { P } _ { t - K } ( \lambda ; \sigma _ { K } ^ { \Lambda } ) - b _ { \infty } \bar { P } _ { t - 2 K } ( \lambda ; \sigma _ { K } ^ { \Lambda } ) .$$
162 Similarly to $K = 1$ , where this limit recursion corresponds to PHB, this recursion corresponds to 163 an instance of Algorithm 3 (see Proposition 4.9 below), further motivating the cyclical heavy ball 164 algorithm. 165 The following theorem is the main result of this section and characterizes the convergence rate of 166 Algorithm 1 for arbitrary momentum and step-size sequences $\{ h _ { i } \} _ { i \in [ [ 1 , K ] ] }$ . By optimizing over these 167 J Kparameters, we obtain a method associated to (18), whose rate is described in Proposition 4.9. All 168 proofs can be found in Appendix D.2. 169 Theorem 4.8. The worst-case rate of convergence of Algorithm $^ { l }$ on $\mathcal { C } _ { \Lambda }$ with an arbitrary momentum 170 $m$ and an arbitrary sequence of step-sizes $\{ h _ { i } \}$ is
 Figure 3: Examples of optimal polynomials $\sigma _ { K } ^ { \Lambda }$ from (16), all of them verifying the equioscillation property (Definition 4.3). The $" \star "$ symbol highlights the degree of $\sigma _ { K } ^ { \Lambda }$ that achieves the best asymptotic rate $\tau ^ { \sigma _ { K } ^ { \Lambda } }$ in (15) amongst all $K$ (see Section 4.4). (Left) When $\Lambda$ is an unique interval, all 3 polynomials are equivalently optimal $\begin{array} { r l r } { \tau ^ { \sigma _ { 1 } ^ { \Lambda } } = } & { { } } & { = \tau ^ { \sigma _ { 3 } ^ { \Lambda } } } \end{array}$ . (Center) When $\Lambda$ is the union of two intervals of the same size, the degree 2 polynomial is optimal $\tau ^ { \sigma _ { 2 } ^ { \Lambda } } > \tau ^ { \sigma _ { 3 } ^ { \Lambda } } > \tau ^ { \sigma _ { 1 } ^ { \Lambda } }$ . This is expected given the result in Proposition 4.5. (Right) When $\Lambda$ is the union of two unbalanced intervals, the degree 3 polynomial instead achieves the best asymptotic rate $\tau ^ { \sigma _ { 3 } ^ { \Lambda } } > > > \tau ^ { \sigma _ { 1 } ^ { \Lambda } }$ (see Section 4.4).
$$1 - \tau = \left\{ \begin{array} { l l } { \sqrt { m } , } & { \mathrm { i f ~ } \sigma _ { \operatorname* { s u p } } \leq 1 } \\ { \sqrt { m } \left( \sigma _ { \operatorname* { s u p } } + \sqrt { \sigma _ { \operatorname* { s u p } } ^ { 2 } - 1 } \right) ^ { 1 / K } , } & { \mathrm { i f ~ } \sigma _ { \operatorname* { s u p } } \in \left( 1 , \displaystyle \frac { 1 + m ^ { K } } { 2 \left( \sqrt { m } \right) ^ { K } } \right) } \\ { \geq 1 \left( n o c o n v e r g e n c e \right) } & { \mathrm { i f ~ } \sigma _ { \operatorname* { s u p } } \geq \displaystyle \frac { 1 + m ^ { K } } { 2 \left( \sqrt { m } \right) ^ { K } } } \end{array} \right. ,$$
where 171 $\sigma _ { \operatorname* { s u p } } \triangleq \operatorname* { s u p } _ { \lambda \in \Lambda } \vert \sigma ( \lambda ; \{ h _ { i } \} , m ) \vert$ , and $\sigma ( \lambda ; \{ h _ { i } \} , m )$ is the $K$ -degree polynomial
$$\sigma ( \lambda ; \{ h _ { i } \} , m ) \triangleq \frac { 1 } { 2 } \mathrm { T r } \left( \left[ \begin{array} { c c c } { \frac { 1 + m - h _ { K - 1 } \lambda } { \sqrt { m } } } & { - 1 } \\ { 1 } & { 0 } \end{array} \right] \left[ \begin{array} { c c c } { \frac { 1 + m - h _ { K - 2 } \lambda } { \sqrt { m } } } & { - 1 } \\ { 1 } & { 0 } \end{array} \right] \cdots \left[ \begin{array} { c c } { \frac { 1 + m - h _ { 0 } \lambda } { \sqrt { m } } } & { - 1 } \\ { 1 } & { 0 } \end{array} \right] \right) .$$
172 Proposition 4.9. Let $\sigma ( \lambda ; \{ h _ { i } \} , m )$ be the polynomial defined by (20), and $\sigma _ { K } ^ { \Lambda }$ be the optimal link 173 function of degree $K$ defined by (16). If the momentum $m$ and the sequence of step-sizes $\{ h _ { i } \}$ satisfy
$$\sigma ( \lambda ; \{ h _ { i } \} , m ) = \sigma _ { K } ^ { \Lambda } ( \lambda ) ,$$
174 then 1) the parameters are optimal, in the sense that they minimize the asymptotic rate factor from 175 Theorem 4.8, 2) the optimal momentum parameter is
$$m = \left( \sigma _ { 0 } - \sqrt { \sigma _ { 0 } ^ { 2 } - 1 } \right) ^ { 2 / K } , \quad w h e r e \sigma _ { 0 } = \sigma _ { K } ^ { \Lambda } ( 0 ) ,$$
176 3) the iterates from Algo. 3 with parameters $\{ h _ { i } \}$ and $m$ form a polynomial with recurrence (18), and 4) Algorithm 3 achieves the worst-case rate 177 $r _ { t } ^ { A l g . \ 3 }$ and the asymptotic rate factor $1 - \tau ^ { A l g }$ . 3
$$r _ { t } ^ { A l g . ~ 3 } = O \left( t \left( \sigma _ { 0 } - \sqrt { \sigma _ { 0 } ^ { 2 } - 1 } \right) ^ { t / K } \right) , \qquad 1 - \tau ^ { A l g . ~ 3 } = \left( \sigma _ { 0 } - \sqrt { \sigma _ { 0 } ^ { 2 } - 1 } \right) ^ { 1 / K } .$$
178 Solving the system (21) The system is constructed by identification of the coefficients in both 179 polynomials $\bar { \sigma } _ { K } ^ { \Lambda }$ and $\sigma ( \lambda ; \{ h _ { i } \} , m )$ , which can be solved using a naive grid-search for instance. We 180 are not aware of any efficient algorithm to solve this system exactly, although it is possible to use 181 iterative methods such as steepest descent or Newton’s method.
This section discusses the (asymptotic) optimality of Algorithm 3. In Section 4.2, the polynomial $P _ { t } ( \cdot ; \sigma _ { K } ^ { \Lambda } )$ was written as a composition of Chebyshev polynomials with $\sigma _ { K } ^ { \Lambda }$ , defined in (16). The best the $K$ is chosen as follows: we solve (16) for several values of imizers of (15). However, following such steps does not $K$ , then pick the smallest arantee that the polyno $K$ aal $P _ { t , K } ^ { \Lambda }$ is minimax, as it is not guaranteed to minimize the worst-case rate $\operatorname* { s u p } _ { \lambda \in \Lambda } \left| P _ { t } ( \lambda ) \right|$ (see (11)).
We give here an optimality certificate, linked to a generalized version of equioscillation. In short, if we can find $K$ non overlapping intervals (more formally, whose interiors are disjoint) $\Lambda _ { i }$ in $\Lambda$ such that $\sigma _ { K } ^ { \Lambda } ( \Lambda _ { i } ) = [ - 1 , 1 ]$ then $P _ { t , K } ^ { \tilde { \Lambda } }$ is minimax for all $t = n K$ , $n \in \mathbb { N } _ { 0 } ^ { + }$ . The detailed result is provided by Theorem C.2. A direct consequence of this result is the asymptotic optimality of Algorithm 3, i.e., there exists no first order algorithm with a better asymptotic rate $1 - \tau$ for the function class $\mathcal { C } _ { \Lambda }$ .
It is possible that such $\sigma _ { K } ^ { \Lambda }$ does not exist for a given $\Lambda$ . A complete characterization of the set $\Lambda$ for which there exists such $\sigma _ { K } ^ { \Lambda }$ is out of the scope of this paper. A partial answer is given in [Fischer, 2011] when $\Lambda$ is the union of two intervals. However, the problem remains open in the general case.
# 96 5 Local Convergence for Non-Quadratic Functions
197 When $f$ is twice-differentiable, it is possible to show local convergence rates when $x _ { 0 }$ is close 198 enough to $x _ { * }$ [Polyak, 1964]. We give here a similar result that applies to Algorithm 1 (see proof in 199 Appendix E). Those results are only local, as it is possible to find pathological counter-examples for 200 which even PHB does not converge globally, for some specific initialization [Lessard et al., 2016]. 201 Theorem 5.1 (Local convergence). Let $f : \mathbb { R } ^ { d } \mapsto \mathbb { R }$ be a (potentially non-quadratic) twice continu 202 ously differentiable function, $x _ { * }$ a local minimizer, and $H$ be the Hessian of $f$ at $x _ { * }$ with $S p ( H ) \subseteq \Lambda$ 203 Let $x _ { t }$ denote the result of running Algorithm 1 with parameters $h _ { 1 } , h _ { 2 } , \cdot \cdot \cdot , h _ { K } , m$ , and let $1 - \tau$ be 204 the linear convergence rate on the quadratic objective (OPT). Then we have
$$\forall \varepsilon > 0 , \exists \mathrm { o p e n ~ s e t } \ : V _ { \varepsilon } : x _ { 0 } , x _ { * } \in V _ { \varepsilon } \implies \| x _ { t } - x _ { * } \| = O ( ( 1 - \tau + \varepsilon ) ^ { t } ) \| x _ { 0 } - x _ { * } \| .$$
205 In short, when Algorithm 1 is guaranteed to converge at rate $1 - \tau$ on (OPT), then the convergence 206 rate on a nonlinear functions can be arbitrary close to $1 - \tau$ when $x _ { 0 }$ is sufficiently close to $x _ { * }$ .
# 6 Experiments
In this section we present an empirical comparison of the cyclical heavy ball method for different length cycles across 4 different problems. We consider two different problems, quadratic and logistic regression, each applied on two datasets, the MNIST handwritten digits [Le Cun et al., 2010] and a synthetic dataset. The results of these experiments, together with a histogram of the Hessian’s eigenvalues are presented in Figure 4 (see caption for a discussion).
Dataset description. The MNIST dataset consists of a data matrix $A$ with 60000 images of handwritten digits each one with $2 8 \times 2 8 = 7 8 4$ pixels. The synthetic dataset is generated according to a spiked covariance model [Johnstone, 2001], which has been shown to be an accurate model of covariance matrices arising for instance in spectral clustering [Couillet and Benaych-Georges, 2016] and deep networks [Pennington and Worah, 2017, Granziol et al., 2020]. In this model, the data matrix $A = X Z$ is generated from a $m \times n$ random Gaussian matrix $X$ and an $m \times m$ deterministic matrix $Z$ . In our case, we take $n = 1 0 0 0 , m = 1 2 0 0$ and $Z$ is the identity where the first three entries are multiplied by 100 (this will lead to three outlier eigenvalues). We also generate an $n$ -dimensional target vector $b$ as $b = A x$ or $b = { \mathrm { s i g n } } ( A x )$ for the quadratic and logistic problem respectively.
Objective function For each dataset, we consider a quadratic and a logistic regression problem, leadin to 4 different problems. All pro ms are of the form $\begin{array} { r } { \operatorname* { m i n } _ { x \in \mathbb { R } ^ { p } } \frac { 1 } { n } \sum _ { i = 1 } ^ { n } \ell ( \breve { A } _ { i } ^ { \top } x , b _ { i } ) \stackrel { \cdot } { + } \lambda \| x \| ^ { 2 } } \end{array}$ , $\ell$ $A$ is the data matrix and $b$ are the target values. We set the regularization parameter to $\lambda = 1 0 ^ { - 3 } \Vert A \Vert ^ { 2 }$ . For logistic regression, since guarantees only hold at a neighborhood of the solution (even for the 1-cycle algorithm), we initialize the first iterate as the result of 100 iteration of gradient descent. In the case of logistic regression, the Hessian eigenvalues are computed at the optimum.
 Figure 4: Hessian Eigenvalue histogram (top row) and Benchmarks (bottom row). The top row shows the Hessian eigenvalue histogram at optimum for the 4 problems consider, together with the interval boundaries $\mu _ { 1 } < L _ { 1 } < \mu _ { 2 } < L _ { 2 }$ for the two-interval split of the eigenvalue support described in Section 3. In all cases, there’s a non-zero gap radius $R$ . This is shown in the bottom row, where we compare the suboptimality in terms of gradient norm as a function of the number of iterations. As predicted by the theory, the non-zero gap radius translates into a faster convergence of the cyclical approach, compared to PHB in all cases. The improvement is observed on both quadratic and logistic regression problems, even through the theory for the latter is limited to local convergence.
# 229 7 Conclusion
This work is motivated by two recent observations from the optimization practice of machine learning. First, cyclical step-sizes have been shown to enjoy excellent empirical convergence [Loshchilov and Hutter, 2017, Smith, 2017]. Second, spectral gaps are pervasive in the Hessian spectrum of deep learning models [Sagun et al., 2017, Papyan, 2018, Ghorbani et al., 2019, Papyan, 2019]. Based on the simpler context of quadratic convex minimization, we develop a convergence-rate analysis and optimal parameters for the heavy ball method with cyclical step-sizes. This analysis highlights the regimes under which cyclical step-sizes have faster rates than classical accelerated methods. Finally, we illustrate these findings through numerical benchmarks.
Main Limitations. In Section 3 we gave explicit formulas for the optimal parameters in the case of the 2-cycle heavy ball algorithm. These formulas depend not only on extremal eigenvalues—as is usual for accelerated methods—but also on the spectral gap $R$ . The gap can sometimes be computed after computed the top eigenvalues (e.g. top-2 eigenvalue for MNIST). However, in general, there is no guarantee on how many eigenvalues are needed to estimate it. Moreover, global convergence result rely heavily on the quadratic assumption.
244 Another limitation regards long cycles. For cycles longer than 2, we have only given an implicit 245 formula to set the optimal parameters (Proposition 4.9). This involves solving a set of non-linear 246 equations whose complexity increases with the cycle length. That being said, cyclical step-sizes 247 might significantly enhance convergence speeds both in terms of worst-case rates and empirically, 248 and this work advocates that new tuning practices involving different cycle lengths might be relevant.
Broader Impact. This work is mostly theoretical, and as such we believe it does not present direct societal consequences. However, the methods described in this paper can be used to train machine learning models which could themselves have societal consequences. For example, the deployment of machine learning models in decision-making has been shown to suffer from gender and racial bias and to amplify existing inequalities, see for instance [Hutchinson and Mitchell, 2019, Barocas et al., 2017, Obermeyer et al., 2019].
# References
256 Solon Barocas, Moritz Hardt, and Arvind Narayanan. Fairness in machine learning. Nips tutorial, 2017. 258 Dimitri P. Bertsekas. Nonlinear programming. Journal of the Operational Research Society, 1997. 59 Romain Couillet and Florent Benaych-Georges. Kernel spectral clustering of large dimensional data. Electronic Journal of Statistics, 2016. Bernd Fischer. Polynomial based iteration methods for symmetric linear systems. SIAM, 2011. Donald A. Flanders and George Shortley. Numerical determination of fundamental modes. Journal of Applied Physics, 1950. Behrooz Ghorbani, Shankar Krishnan, and Ying Xiao. An investigation into neural net optimization via hessian eigenvalue density. In International Conference on Machine Learning (ICML), 2019. Gene H. Golub and Richard S. Varga. Chebyshev semi-iterative methods, successive overrelaxation iterative methods, and second order Richardson iterative methods. Numerische Mathematik, 1961. Diego Granziol, Xingchen Wan, Samuel Albanie, and Stephen Roberts. Explaining the Adaptive Generalisation Gap. arXiv preprint arXiv:2011.08181, 2020. 70 Magnus R. Hestenes and Eduard Stiefel. Methods of conjugate gradients for solving linear systems, volume 49. NBS Washington, DC, 1952. Ben Hutchinson and Margaret Mitchell. 50 years of test (un) fairness: Lessons for machine learning. In Proceedings of the Conference on Fairness, Accountability, and Transparency, 2019. 274 Iain M. Johnstone. On the distribution of the largest eigenvalue in principal components analysis. Annals of statistics, 2001. 76 Yann Le Cun, Corinna Cortes, and Chris Burges. MNIST handwritten digit database. ATT Labs [Online], 2010. Laurent Lessard, Benjamin Recht, and Andrew Packard. Analysis and design of optimization algorithms via integral quadratic constraints. SIAM Journal on Optimization, 2016. Ilya Loshchilov and Frank Hutter. SGDR: stochastic gradient descent with warm restarts. In International Conference on Learning Representations (ICLR), 2017. 282 Arkadi S. Nemirovsky. Information-based complexity of linear operator equations. Journal of Complexity, 1992. 284 Arkadi S. Nemirovsky. Information-based complexity of convex programming. Lecture Notes, 1995. 285 Yurii Nesterov. Introductory Lectures on Convex Optimization. Springer, 2003. 286 Ziad Obermeyer, Brian Powers, Christine Vogeli, and Sendhil Mullainathan. Dissecting racial bias in an algorithm used to manage the health of populations. Science, 2019. Vardan Papyan. The full spectrum of deepnet hessians at scale: Dynamics with SGD training and sample size. arXiv preprint arXiv:1811.07062, 2018. Vardan Papyan. Measurements of Three-Level Hierarchical Structure in the Outliers in the Spectrum of Deepnet Hessians. In International Conference on Machine Learning (ICML), 2019. 92 Jeffrey Pennington and Pratik Worah. Nonlinear random matrix theory for deep learning. In Advances on Neural Information Processing Systems (NIPS), 2017. Boris T. Polyak. Some methods of speeding up the convergence of iteration methods. USSR computational mathematics and mathematical physics, 1964. Levent Sagun, Utku Evci, V. Ugur Guney, Yann Dauphin, and Leon Bottou. Empirical analysis of the Hessian of over-parametrized neural networks. arXiv preprint arXiv:1706.04454, 2017. 98 Damien Scieur and Fabian Pedregosa. Universal Asymptotic Optimality of Polyak Momentum. In International Conference on Machine Learning (ICML), 2020. Leslie N. Smith. Cyclical learning rates for training neural networks. In 2017 IEEE Winter Conference on Applications of Computer Vision (WACV). IEEE, 2017. 02 Ilya Sutskever, James Martens, George Dahl, and Geoffrey Hinton. On the importance of initialization and momentum in deep learning. In International Conference on Machine Learning (ICML), 2013.
1. For all authors...
(a) Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope? [Yes] The Introduction (Section 1) details where all results can be found. (b) Did you describe the limitations of your work? [Yes] There is a paragraph "Main Limitations" in the Conclusion (Section 7). (c) Did you discuss any potential negative societal impacts of your work? [N/A] As stated in the "Broader Impact" section, this work is mostly theoretical and as such we believe it doesn’t present a direct societal impact. (d) Have you read the ethics review guidelines and ensured that your paper conforms to them? [Yes]
2. If you are including theoretical results...
(a) Did you state the full set of assumptions of all theoretical results? [Yes] In each and every statement we make. (b) Did you include complete proofs of all theoretical results? [Yes] All proofs are available in the supplementary material.
3. If you ran experiments...
(a) Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? [Yes] URLs are provided in the supplementary material. (b) Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? [Yes] In the experiments section (Section 6). (c) Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? [No] . (d) Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? [Yes] , in Appendix F
4. If you are using existing assets (e.g., code, data, models) or curating/releasing new assets...
(a) If your work uses existing assets, did you cite the creators? [Yes] In the "Dataset description" paragraph of the Experiments section 6. (b) Did you mention the license of the assets? [N/A] (c) Did you include any new assets either in the supplemental material or as a URL? [N/A] There is no new asset. We used MNIST existing Dataset as well as a synthetic dataset whose construction is described in papers cited in the Experiments section 6. (d) Did you discuss whether and how consent was obtained from people whose data you’re using/curating? [N/A] (e) Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? [N/A]
5. If you used crowdsourcing or conducted research with human subjects...
(a) Did you include the full text of instructions given to participants and screenshots, if applicable? [N/A] (b) Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? [N/A] (c) Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? [N/A]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687# IDENTITY CRISIS: MEMORIZATION AND GENERALIZATION UNDER EXTREME OVERPARAMETERIZATION
Chiyuan Zhang & Samy Bengio Google Research, Brain Team Mountain View, CA 94043, USA {chiyuan,bengio}@google.com
Moritz Hardt University of California, Berkeley Berkeley, CA 94720, USA hardt@berkeley.edu
Michael C. Mozer Google Research, Brain Team Mountain View, CA 94043, USA mcmozer@google.com
Yoram Singer Princeton University Princeton, NJ 08544, USA y.s@princeton.edu
# ABSTRACT
We study the interplay between memorization and generalization of overparameterized networks in the extreme case of a single training example and an identitymapping task. We examine fully-connected and convolutional networks (FCN and CNN), both linear and nonlinear, initialized randomly and then trained to minimize the reconstruction error. The trained networks stereotypically take one of two forms: the constant function (memorization) and the identity function (generalization). We formally characterize generalization in single-layer FCNs and CNNs. We show empirically that different architectures exhibit strikingly different inductive biases. For example, CNNs of up to 10 layers are able to generalize from a single example, whereas FCNs cannot learn the identity function reliably from 60k examples. Deeper CNNs often fail, but nonetheless do astonishing work to memorize the training output: because CNN biases are location invariant, the model must progressively grow an output pattern from the image boundaries via the coordination of many layers. Our work helps to quantify and visualize the sensitivity of inductive biases to architectural choices such as depth, kernel width, and number of channels.
# 1 INTRODUCTION
The remarkable empirical success of deep neural networks is often attributed to the availability of large data sets for training. However, sample size does not provide a comprehensive rationale since complex models often outperform simple ones on a given data set, even when the model size exceeds the number of training examples.
What form of inductive bias leads to better generalization performance from highly overparameterized models? Numerous theoretical and empirical studies of inductive bias in deep learning have been conducted in recent years (Dziugaite & Roy, 2016; Kawaguchi et al., 2017; Bartlett et al., 2017; Neyshabur et al., 2017; Liang et al., 2017; Neyshabur et al., 2018; Arora et al., 2018; Zhou et al., 2019) but these postmortem analyses do not identify the root source of the bias.
One cult belief among researchers is that gradient-based optimization methods provide an implicit bias toward simple solutions (Neyshabur et al., 2014; Soudry et al., 2018; Shah et al., 2018; Arora et al., 2019). However, when a network is sufficiently large (e.g., the number of hidden units in each layer is polynomial in the input dimension and the number of training examples), then under some mild assumptions, gradient methods are guaranteed to fit the training set perfectly (Allen-Zhu et al., 2018b; Du et al., 2018a;b; Zou et al., 2018). These results do not distinguish a model trained on a data distribution with strong statistical regularities from one trained on the same inputs but with randomly shuffled labels. Although the former model might achieve good generalization, the latter can only memorize the training labels. Consequently, these analyses do not tell the whole story on the question of inductive bias.
 Figure 1: Predictions of three architectures trained on the identity mapping task with 60k MNIST examples. The red dashed line separates 3 training examples from the test examples.
Another line of research characterizes sufficient conditions on the input and label distribution that guarantee generalization from a trained network. These conditions range from linear separability (Brutzkus et al., 2018) to compact structures (Li & Liang, 2018). While very promising, this direction has thus far identified only structures that can be solved by linear or nearest neighbor classifiers over the original input space. The fact that in many applications deep neural networks significantly outperform these simpler models reveals a gap in our understanding of deep neural networks.
As a formal understanding of inductive bias in deep networks has been elusive, we conduct a novel exploration in a highly restrictive setting that admits visualization and quantification of inductive bias, allowing us to compare variations in architecture, optimization procedure, initialization scheme, and hyperparameters. The particular task we investigate is learning an identity mapping in a regression setting. The identity mapping is interesting for four reasons. First, it imposes a structural regularity between the input and output, the type of regularity that could in principle lead to systematic generalization (He et al., 2016; Hardt & Ma, 2017). Second, it requires that every input feature is transmitted to the output and thus provides a sensitive indicator of whether a model succeeds in passing activations (and gradients) between inputs and outputs. Third, conditional image generation is a popular task in the literature (e.g., Mirza & Osindero, 2014; Ledig et al., 2017); an identity mapping is the simplest form of such a generative process. Fourth, and perhaps most importantly, it admits detailed analysis and visualization of model behaviors and hidden representations.
Consider networks trained on the identity task with 60k MNIST digits. Although only digit images are presented during the training, one might expect the strong regularity of the task to lead to good generalization to images other than digits. Figure 1 compares three different architectures. The top row shows various input patterns, and the next three rows are outputs from a 20-layer convolutional net (CNN), a 10-layer fully connected net (FCN) with rectified-linear unit (ReLU) activation functions, and a 1-layer FCN. The 1-layer FCN amounts to a convex optimization problem with infinitely many solutions, however gradient decent converges to a unique closed-form solution. All nets perform well on the training set (first three columns) and transfer well to novel digits and digit blends (columns 4–6). Yet, outside of the hull of hand-printed digits, only the CNN discovers a reasonably good approximation to the identity function.
Figure 1 reflects architecture-specific inductive bias that persists even with 60k training examples. Despite this persistence, a model’s intrinsic bias is more likely to be revealed with a smaller training set. In this paper, we push this argument to the limit by studying learning with a single training example. Although models are free to reveal their natural proclivities in this maximally overparameterized regime, our initial intuition was that a single example would be uninteresting as models would be algebraically equivalent to the constant function (e.g., via biases on output units). Further, it seemed inconceivable that inductive biases would be sufficiently strong to learn a mapping close to the identity. Unexpectedly, our experiments show that model behavior is subtle and architecture dependent. In a broad set of experiments, we highlight model characteristics—including depth, initialization, and hyperparameters—that determine where a model lands on the continuum between memorization (learning a constant function) and generalization (learning the identity function). The simplicity of the training scenario permits rich characterization of inductive biases.
 Figure 2: Visualization of the outputs of fully connected networks trained on a single example. The first row shows the single training example (7) and a set of evaluation images consisting of a linear combination of two digits, random digits from MNIST test set, random images from Fashion MNIST, and some algorithmically generated image patterns. Each row below indicates an architecture and the output from that architecture for a given input.
# 2 RELATED WORK
The consequences of overparameterized models in deep learning have been extensively studied in recently years, on the optimization landscape and convergence of SGD (Allen-Zhu et al., 2018b; Du et al., 2018a;b; Bassily et al., 2018; Zou et al., 2018; Oymak & Soltanolkotabi, 2018), as well as the generalization guarantees under stronger structural assumptions of the data (Li & Liang, 2018; Brutzkus et al., 2018; Allen-Zhu et al., 2018a). Another line of related work is the study of the implicit regularization effects of SGD on training overparameterized models (Neyshabur et al., 2014; Zhang et al., 2017; Soudry et al., 2018; Shah et al., 2018; Arora et al., 2019).
The traits of memorization in learning are also explicitly studied from various perspectives such as prioritizing learning of simple patterns (Arpit et al., 2017) or perfect interpolation of the training set (Belkin et al., 2018; Feldman, 2019). More recently, coincidentally with the writing of this paper, Radhakrishnan et al. (2018) reported on the effects of the downsampling operator in convolutional auto-encoders on image memorization. Their empirical framework is similar to ours, fitting CNNs to the autoregression problem with few training examples. We focus on investigating the general inductive bias in the extreme overparameterization case, and study a broader range of network types without enforcing a bottleneck in the architectures.
# 3 EXPERIMENTS
We explore a progression of models: linear convex models, linear non-convex models (with multiple linear layers), fully-connected multilayered architectures with nonlinearities, and finally the case of greatest practical importance, fully convolutional networks. In all architectures we study, we ensure that there is a simple realization of the identity function (see Appendix B). We train networks by minimizing the mean squared error using standard gradient descent.
# 3.1 FULLY CONNECTED NETWORKS
Figure 2 shows examples of predictions from multi-layer fully connected networks. Infinitely many solutions exist for all models under this extreme over-parameterization, and the figure shows that all the models fit the training example perfectly. However, on new test examples, contrasting behaviors are observed between shallow and deep networks. In particular, deeper models bias toward predicting a constant output, whereas shallower networks tend to predict random white noises on unseen inputs. The random predictions can be characterized as follows (proof in Appendix C).
Theorem 1. A one-layer fully connected network, when trained with gradient descent on a single training example $\hat { x }$ , converges to a solution that makes the following prediction on a test example $x$ :
$$f ( x ) = \Pi _ { \parallel } ( x ) + \mathbf { R } \Pi _ { \perp } ( x ) ,$$
 Figure 3: Visualization of predictions from CNNs trained on a single example. The first row shows the single training example (7) and a set of test inputs. Each row below shows the output of a CNN whose depth is indicated to the left of the row. The hidden layers of the CNN consist of $5 \times 5$ convolution filters organized as 128 channels.
where $x = \Pi _ { \parallel } ( x ) + \Pi _ { \perp } ( x )$ decomposes $x$ into orthogonal components that are parallel and perpendicular to the training example $\hat { x }$ , respective. R is a random matrix from the network initialization, independent of the training data.
For test examples similar to the training example—i.e., where $\Pi _ { \parallel } ( x )$ dominates $\Pi _ { \perp } ( x )$ —the outputs resemble the training output; on the other hand, for test examples that are not highly correlated to the training example, $\bar { \Pi } _ { \perp } ( \bar { x } )$ dominates and the outputs looks like white noise due to the random projection by $\mathbf { R }$ . The behavior can be empirically verified from the second row in Figure 2. Specifically, the first test example is a mixture of the training and an unseen test example, and the corresponding output is a mixture of white noise and the training output. For the remaining test examples, the outputs appear random.
Although Theorem 1 characterizes only the 1-layer linear case, the empirical results in Figure 2 suggest that shallow (2 layer) networks tend to have this inductive bias. However, this inductive bias does not miraculously obtain good generalization: the trained model fails to learn either the identity or the constant function. Specifically, it predicts well in the vicinity (measured by correlations) of the training example $\hat { x }$ , but further away its predictions are random. In particular, when the test example $x$ is orthogonal to $\hat { x }$ , the prediction is completely random. In deeper (6 layer) nets, the deviations from the identity function take on a quite different characteristic form.
Interestingly, deeper linear networks behave more like deeper ReLU networks, with a strong bias towards a constant function that maps any input to the single training output. A multilayer linear network with no hidden-layer bottleneck has essentially the same representational power as a 1-layer linear network, but gradient descent produces different learning dynamics that alter the inductive biases. See Appendix $\mathrm { E }$ for more results and analysis on FCNs.
 Figure 4: Predictions of CNNs on test examples at different angles to the training image. The horizontal axis shows the train-test correlation, while the vertical axis indicate the number of hidden layers for the CNNs being evaluated. The heatmap shows the similarity (measured in correlation) between the model prediction and the reference function (the constant or the identity function).
# 3.2 CONVOLUTIONAL NETWORKS
We next study the inductive bias of convolutional neural networks with ReLU activation functions. Figure 3 shows predictions on various test patterns obtained by training CNNs of varying depths. Compared to FCNs, CNNs have strong structural constraints that limit the receptive field of each neuron to a spatially local neighborhood and the weights are tied and being used across the spatial array. These two constraints match the structure of the identity target function. (See Appendix B.3 for an example of constructing the identity function with CNNs.) Similar to the fully connected case, for one-layer CNN, we can bound the error as follows (proof in Appendix D).
Theorem 2. A one-layer convolutional neural network can learn the identity map from a single training example with the mean squared error over all output pixels bounded as
$$M S E \leq \tilde { \mathcal { O } } \left( \frac { m ( m / C - r ) } { C } \right)$$
where m is the number of network parameters, $C$ is the number of channels in the image, and $r \leq m / C$ is the rank of the subspace formed by the span of the local input patches.
The error grows with $m$ , the number of parameters in the network. For example, learning CNNs with larger receptive field sizes will be harder. Even though the bound seems to decrease with more (input and output) channels in the image, note that the number of channels $C$ also contributes to the number of parameters $( m = K _ { H } K _ { W } C ^ { 2 } )$ , so there is a trade-off. Unlike typical generalization bound that decays with number of i.i.d. training examples, we have only one training example here, and the key quantity that reduces the bound is the rank $r$ of the subspace formed by the local image patches. The size of the training image implicitly affects bounds as larger image generates more image patches. Note the rank $r$ also heavily depends on the contents of the training image. For example, simply padding the image with zeros on all boundaries will not reduce the error bound. With enough linearly independent image patches, the subspace becomes full rank $r = m / c$ , and learning of the global identity map is guaranteed.
The theorem guarantees only the one-layer case. Empirically—as shown in Figure 3—CNNs with depth up-to-5 layers learn a fairly accurate approximation to the identity function, with the exception of a few artifacts at the boundaries. For a quantitative evaluation, we measure the performance by calculating the correlation (See Appendix J for the results in MSE.) to two reference functions: the identity function and the constant function that maps every input to the training point $\hat { x }$ . To examine how a model’s response varies with similarity to the training image, we generate test images having correlation $\rho \in [ 0 , 1 ]$ to the training image by: (1) sampling an image with random pixels, (2) adding $\alpha \hat { x }$ to the image, picking $\alpha$ such that the correlation with $\hat { x }$ is $\rho$ ; (3) renormalizing the image to be of the same norm as $\hat { x }$ . For $\rho = 0$ , the test images are orthogonal to $\hat { x }$ , whereas for $\rho = 1$ , the test images equal $\hat { x }$ . The results for CNNs of different depths are shown in Figure 4. The quantitative findings are consistent with the visualizations: shallow CNNs are able to learn the identity function from only one training example; very deep CNNs bias towards the constant function; and CNNs of intermediate depth correlate well with neither the identity nor the constant function. However, unlike FCNs that produce white-noise-like predictions, from Figure 3 CNNs of intermediate depth behave like edge detectors.
 Figure 5: Illustration of the collapse of predictive power as function of layer’s depth. Error rate is measured by using the representations computed at each layer to a simple averaging based classifier on the MNIST test set. The error rate at each layer is plotted for a number of trained CNNs of different depth. The thick red line shows the curve of an untrained 20-layer CNN for reference.
To evaluate how much information is lost in the intermediate layers, we use the following simple criterion to assess the representation in each layer. We feed each image in the MNIST dataset through a network trained on our single example. We collect the representations at a given layer and perform a simple similarity-weighted classification. For each example $x _ { i }$ from the MNIST test set, we predict its class as a weighted average of the (one hot) label vector of each example $x _ { j }$ from the MNIST training set, where the weight is the inner-product of $x _ { i }$ and $x _ { j }$ .
This metric does not quantify how much information is preserved as the image representation propagates through the layers, because the representation could still be maintained yet not captured by the simple correlation-weighted classifier. It nonetheless provides a simple metric for exploring the (identity) mapping: using the input image as the baseline, if a layer represents the identity function, then the representation at that layer would obtain a similar error rate when using the input representation; on the other hand, if a layer degenerates into the constant function, then the corresponding representation would have error rate close to random guessing of the label. The results are plotted in Figure 5. The error curve for a randomly initialized 20-layer CNN is shown as reference: at random initialization, the smoothing effect renders the representations beyond the sixth layer unuseful for the averaging-based classifier. After training, the concave nonmonotonicity in the curves indicates loss and then recovery of the information present in the input. Trained networks try to recover the washed out intermediate layer representations as means to link the input and the output layer. However, if the depth is too large, the network tries to infer input-output relations using partial information, resulting in models that behave like edge detectors. Finally, for the case of 20 layers, the curve shows that the bottom few layers do get small improvements in error rate comparing to random initialization, but the big gap between the input and output layer drives the network to learn the constant function instead. On a first sight, this deems to underscore a vanishing gradient problem, but Figure 1 reveals that given a sufficient number of training examples, a 20-layer CNN can still learn the identity map. See also Appendix G for further discussions on vanishing gradients. Since CNNs preserve spatial structure, we can also visualize information loss in the intermediate layers. The visualization results, described in Appendix F, are consistent with the aforementioned observations.
# 3.3 ROBUSTNESS TO CHANGES IN INPUT SCALE
Whether a relatively shallow CNN learns the identity function from a single training example or a relatively deep CNN learns the constant function, both outcomes reflect an inductive bias because the training objective never explicitly mandates the model to learn one structure or another. The spatial structure of CNNs enables additional analyses of the encoding induced by the learned function. In particular, we examined how changing the size of the input by scaling the dimensions of the spatial map affects the model predictions. Figure 6 depicts the predictions of a 5-layer CNN trained on a $2 8 \times 2 8$ image and tested on $7 \times 7$ and $1 1 2 \times 1 1 2$ images. Although the learned identity map generally holds up against a larger-than-trained input, the identity map is disturbed on smaller-thantrained inputs. See Appendix H.1 for a comprehensive description of the results. Note that CNNs are capable of encoding the identity function for arbitrary input and filter sizes (Appendix B.3).
Figure 7 shows the predictions on the rescaled input patterns of Figure 6 by a 20-layer CNN that has learned the constant function on a $2 8 \times 2 8$ image. The learned constant map holds up over a smaller range of input sizes than the learned identity map in a 5-layer CNN. It is nonetheless interesting to see smooth changes as the input size increases to reveal the network’s own notion of “7”, clearly defined with respect to the corners of the input map (Figure 21 in Appendix H reveals interesting details on how the patterns progressively grow from image boundaries in intermediate layers). We performed additional experiments to directly feed test images to the upper subnet, which reveals more about the generative process by which the net synthesizes a constant output (Appendix H).
 Figure 6: Visualization of a 5-layer CNN on test images of different sizes. The two subfigures show the results on $7 \times 7$ inputs and $1 1 2 \times 1 1 2$ inputs, respectively.
 Figure 7: Visualization of the predictions of a 20-layer CNN on test images of different sizes (indicated by the number on each row). The input patterns are the same as in Figure 6 (constructed in different resolutions), which are not shown for brevity.
# 3.4 VARYING OTHER FACTORS DURING TRAINING
We studied a variety of common hyperparameters, including image dimensions, convolutional filter dimensions, number of kernels, weight initialization scheme, and the choice of gradient-based optimizer. With highly overparameterized networks, training converges to zero error for a wide range of hyperparameters. Within the models that all perform optimally on the training set, we now address how the particular hyperparameter settings affect the inductive bias. We briefly present some of the most interesting observations here; please refer to Appendix I for the full results and analyses.
Size of training image. Figure 8 shows, for varying training-image size, the mean correlation to the constant and the identity function at different depths within the network. The training examples are resized versions of the same image. The bias toward the constant function at a given depth increases with smaller training images. This finding makes sense considering that smaller images provide fewer pixel-to-pixel mapping constraints, which is aligned with Theorem 2.
Size of convolution filters. Figure 9 illustrates the inductive bias with convolution filter size varying from $5 \times 5$ to $5 7 \times 5 7$ . Predictions become blurrier as the filter size grows. With extremely large filters that cover the entire input array, CNNs exhibit a strong bias towards the constant function.
 Figure 8: Comparing bias towards constant and identity when trained with different image sizes. The xaxis is the depth of the CNNs, while the y-axis is the mean correlation (average of each row from the heatmaps like in Figure 4). Each curve corresponds to training with a different image size.
 Figure 9: Visualizing the predictions from 5-layer CNNs with various filter sizes. The first row shows the single training example (7) and a set of test inputs. Each row below shows the output of a CNN whose filter size is indicated by the number on the left. See Appendix I for more results.
 Figure 10: Visualization of the predictions from CNNs for various number of hidden channels. The first row shows a single training example (7) and a set of test inputs. Each row below shows the output of CNNs differing in the number of channels. This number is indicated on the left of each row; for intermediate layers, the number specifies both the input and output channel count.
Because the training inputs are of size $2 8 \times 2 8$ , a $2 9 \times 2 9$ filter size allows each neuron to see at least half of the spatial domain of the previous layer, assuming large boundary padding of the inputs. With $5 7 \times 5 7$ filters centered at any location within the image, each neuron sees the entire previous layer. This is also consistent with Theorem 2, in which the error bound deteriorates as the filter sizes increases. Note even with a large filter, CNNs do not perform the same elementary computation as FCNs because the (shared) convolution filter is repeatedly applied throughout the spatial domain.
Number of channels. Appendix B.3 shows that in principle two channels suffice to encode the identity function for gray-scale inputs via a straightforward construction. However, in practice the outcome of training may be quite different depending on the channel count, as shown in Figure 10(a). On the one hand, the aggressively overparameterized network with 1024 channels $\mathrm { \sim } 2 5 \mathrm { M }$ parameters per middle convolution layer) does not seem to suffer from overfitting. On the other hand, the results with three channels often lose content in the image center. The problem is not underfitting as the network reconstructs the training image (first column) correctly.
A potential reason why 3-channel CNNs do not learn the identity map well might be poor initialization when there are very few channels (Frankle & Carbin, 2019). This issue is demonstrated in Figure 29 of Appendix I. Our study of training with different initialization schemes indeed confirms that the random initial conditions have a big impact on the inductive bias (Appendix I).
Figure 10(b) shows the case for 20-layer CNNs. Surprisingly, having an order of magnitude more feature channels in every layer does not seem to help much at making the information flow through layers, as the network still learns to ignore the inputs and construct a constant output.
# 4 CONCLUSIONS
We presented an systematic study of the extreme case of overparameterization when learning from a single example. We investigated the interplay between memorization and generalization in deep neural networks. By restricting the learning task to the identity function, we sidestepped issues such as the underlying optimal Bayes error of the problem and the approximation error of the hypothesis classes. This choice also facilitated rich visualization and intuitive interpretation of the trained models. Under this setup, we investigated gradient-based learning procedures with explicit memorization-generalization characterization. Our results indicate that different architectures exhibit vastly different inductive bias towards memorization and generalization.
For future work, we plan to extend the study to other domains and neural network architectures, like natural language processing and recurrent neural networks, and aim for more qualitative relationship between the inductive bias and various architecture configurations.
# ACKNOWLEDGMENTS
We would like to thank Kunal Talwar, Hanie Sedghi, and Rong Ge for helpful discussions.
# REFERENCES
Zeyuan Allen-Zhu, Yuanzhi Li, and Yingyu Liang. Learning and generalization in overparameterized neural networks, going beyond two layers. CoRR, 1811.04918, 2018a.
Zeyuan Allen-Zhu, Yuanzhi Li, and Zhao Song. A convergence theory for deep learning via OverParameterization. CoRR, arXiv:1811.03962, 2018b.
Sanjeev Arora, Rong Ge, Behnam Neyshabur, and Yi Zhang. Stronger generalization bounds for deep nets via a compression approach. CoRR, arXiv:1802.05296, 2018.
Sanjeev Arora, Nadav Cohen, Wei Hu, and Yuping Luo. Implicit regularization in deep matrix factorization. arXiv preprint arXiv:1905.13655, 2019.
Devansh Arpit, Stanisław Jastrzebski, Nicolas Ballas, David Krueger, Emmanuel Bengio, Maxinder S Kanwal, Tegan Maharaj, Asja Fischer, Aaron Courville, Yoshua Bengio, et al. A closer look at memorization in deep networks. In International Conference on Machine Learning, 2017.
Peter L Bartlett, Dylan J Foster, and Matus J Telgarsky. Spectrally-normalized margin bounds for neural networks. In Advances in Neural Information Processing Systems, pp. 6240–6249, 2017.
Raef Bassily, Mikhail Belkin, and Siyuan Ma. On exponential convergence of SGD in non-convex over-parametrized learning. CoRR, arXiv:1811.02564, 2018.
Mikhail Belkin, Daniel Hsu, and Partha Mitra. Overfitting or perfect fitting? risk bounds for classification and regression rules that interpolate. In Advances in Neural Information Processing Systems, 2018.
Alon Brutzkus, Amir Globerson, Eran Malach, and Shai Shalev-Shwartz. SGD learns overparameterized networks that provably generalize on linearly separable data. In ICLR, 2018.
Simon S Du, Jason D Lee, Haochuan Li, Liwei Wang, and Xiyu Zhai. Gradient descent finds global minima of deep neural networks. CoRR, arXiv:1811.03804, 2018a.
Simon S Du, Xiyu Zhai, Barnabas Poczos, and Aarti Singh. Gradient descent provably optimizes over-parameterized neural networks. CoRR, arXiv:1810.02054, 2018b.
John Duchi, Elad Hazan, and Yoram Singer. Adaptive subgradient methods for online learning and stochastic optimization. Journal of Machine Learning Research, 12(Jul):2121–2159, 2011.
Gintare Karolina Dziugaite and Daniel M Roy. Computing nonvacuous generalization bounds for deep (stochastic) neural networks with many more parameters than training data. In UAI, 2016.
Vitaly Feldman. Does learning require memorization? a short tale about a long tail. arXiv preprint arXiv:1906.05271, 2019.
Jonathan Frankle and Michael Carbin. The lottery ticket hypothesis: Finding sparse, trainable neural networks. In ICLR, 2019.
Xavier Glorot and Yoshua Bengio. Understanding the difficulty of training deep feedforward neural networks. In Proceedings of the thirteenth international conference on artificial intelligence and statistics, pp. 249–256, 2010.
Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv:1308.0850, 2013.
Moritz Hardt and Tengyu Ma. Identity matters in deep learning. 2017.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Delving deep into rectifiers: Surpassing human-level performance on imagenet classification. In Proceedings of the IEEE international conference on computer vision, pp. 1026–1034, 2015.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Identity mappings in deep residual networks. In European conference on computer vision, pp. 630–645. Springer, 2016.
Kenji Kawaguchi, Leslie Pack Kaelbling, and Yoshua Bengio. Generalization in deep learning. CoRR, arXiv:1710.05468, 2017.
Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014.
Christian Ledig, Lucas Theis, Ferenc Huszar, Jose Caballero, Andrew Cunningham, Alejandro ´ Acosta, Andrew Aitken, Alykhan Tejani, Johannes Totz, Zehan Wang, et al. Photo-realistic single image super-resolution using a generative adversarial network. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 4681–4690, 2017.
Yuanzhi Li and Yingyu Liang. Learning overparameterized neural networks via stochastic gradient descent on structured data. In NIPS, 2018.
Tengyuan Liang, Tomaso Poggio, Alexander Rakhlin, and James Stokes. Fisher-rao metric, geometry, and complexity of neural networks. CoRR, arXiv:1711.01530, 2017.
Mehdi Mirza and Simon Osindero. Conditional generative adversarial nets. arXiv preprint arXiv:1411.1784, 2014.
Behnam Neyshabur, Ryota Tomioka, and Nathan Srebro. In search of the real inductive bias: On the role of implicit regularization in deep learning. CoRR, arXiv:1412.6614, 2014.
Behnam Neyshabur, Srinadh Bhojanapalli, David McAllester, and Nati Srebro. Exploring generalization in deep learning. In Advances in Neural Information Processing Systems, pp. 5947–5956, 2017.
Behnam Neyshabur, Srinadh Bhojanapalli, and Nathan Srebro. A PAC-Bayesian approach to Spectrally-Normalized margin bounds for neural networks. In ICLR, 2018.
Samet Oymak and Mahdi Soltanolkotabi. Overparameterized nonlinear learning: Gradient descent takes the shortest path? CoRR, arXiv:1812.10004, 2018.
Adityanarayanan Radhakrishnan, Mikhail Belkin, and Caroline Uhler. Downsampling leads to image memorization in convolutional autoencoders. CoRR, arXiv:1810.10333, 2018.
Andrew M Saxe, James L McClelland, and Surya Ganguli. Exact solutions to the nonlinear dynamics of learning in deep linear neural networks. In International Conference on Learning Representations, 2014.
Vatsal Shah, Anastasios Kyrillidis, and Sujay Sanghavi. Minimum norm solutions do not always generalize well for over-parameterized problems. CoRR, arXiv:1811.07055, 2018.
Daniel Soudry, Elad Hoffer, Mor Shpigel Nacson, Suriya Gunasekar, and Nathan Srebro. The implicit bias of gradient descent on separable data. Journal of Machine Learning Research, 19(70), 2018.
Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144, 2016.
Chiyuan Zhang, Samy Bengio, Moritz Hardt, Benjamin Recht, and Oriol Vinyals. Understanding deep learning requires rethinking generalization. In International Conference on Learning Representations, 2017.
Wenda Zhou, Victor Veitch, Morgane Austern, Ryan P Adams, and Peter Orbanz. Non-vacuous generalization bounds at the ImageNet scale: a PAC-Bayesian compression approach. In ICLR, 2019.
Difan Zou, Yuan Cao, Dongruo Zhou, and Quanquan Gu. Stochastic gradient descent optimizes over-parameterized deep ReLU networks. CoRR, arXiv:1811.08888, 2018.
# A EXPERIMENT DETAILS AND HYPER-PARAMETERS
We specify the experiment setups and the hyper-parameters here. Unless otherwise specified in each study (e.g. when we explicitly vary the number of convolution channels), all the hyper-parameters are set according to the default values here.
The main study is done with the MNIST dataset. It consists of grayscale images of hand written digits of size $2 8 \times 2 8$ . For training, we randomly sample one digit from the training set (a digit $^ { \bullet } 7 ^ { \bullet }$ ) with a fixed random seed. For testing, we use random images from the test set of MNIST and Fashion-MNIST, as well as algorithmically generated structured patterns and random images. The training and test images are all normalized by mapping the pixel values in $\{ 0 , 1 , \ldots , 2 5 5 \}$ to $[ 0 , 1 ]$ , and then standardize with the mean 0.1307 and standard deviation 0.3081 originally calculated on the (full) MNIST training set.
The models are trained by minimizing the mean squared error (MSE) loss with a vanilla SGD (base learning rate 0.01 and momentum 0.9). The learning rate is scheduled as stagewise constant that decays with a factor of 0.2 at the $30 \%$ , $60 \%$ and $80 \%$ of the total training steps (2,000,000). No weight decay is applied during training.
For neural network architectures, the rectified linear unit (ReLU) activation is used for both fully connected networks (FCNs) and convolutional networks (CNNs). The input and output dimensions are decided by the data. The hidden dimensions for the FCNs are 2,048 by default. The CNNs use $5 \times 5$ kernels with stride 1 and padding 2, so that the geometry does not change after each convolution layer.
# B REPRESENTATION OF THE IDENTITY FUNCTION USING DEEP NETWORKS
In this section, we provide explicit constructions on how common types of neural networks can represent the identity function. Those constructions are only proof for that the models in our study have the capacity to represent the target function. There are many different ways to construct the identity map for each network architecture, but we try to provide the most straightforward and explicit constructions. However, during our experiments, even when the SGD learns (approximately) the identity function, there is no evidence suggesting that it is encoding the functions in similar ways as described here. We put some mild constraints (e.g. no “bottleneck” in the hidden dimensions) to allow more straightforward realization of the identity function, but this by no means asserts that networks violating those constraints cannot encode the identity function.
# B.1 LINEAR MODELS
For a one-layer linear network $f ( x ) = W x$ , where $W \in \mathbb { R } ^ { d \times d }$ , setting $W$ to the identity matrix will realize the identity function. For a multi-layer linear network $\begin{array} { r } { f ( x ) { \stackrel { - } { = } } ( \prod _ { \ell } W _ { \ell } ) x } \end{array}$ , we need to require that all the hidden dimensions are not smaller than the input dimension. In this case, a simple concrete construction is to set each $W _ { \ell }$ to an identity matrix.
# B.2 MULTI-LAYER RELU NETWORKS
The ReLU activation function $\sigma ( \cdot ) = \operatorname* { m a x } ( 0 , \cdot )$ discards all the negative values. There are many ways one can encode the negative values and recover it after ReLU. We provide a simple approach that uses hidden dimensions twice the input dimension. Consider a ReLU network with one hidden layer $f ( x ) = W _ { 2 } \sigma ( W _ { 1 } x )$ , where $W _ { 2 } \in \mathbf { \tilde { \mathbb { R } } } ^ { d \times 2 d }$ , $W _ { 1 } \in \mathbb { R } ^ { 2 d \times d }$ . The idea is to store the positive and negative part of $x$ separately, and then re-construct. This can be achieved by setting
$$W _ { 1 } = \left( { \small { \frac { I _ { d } } { - I _ { d } } } } \right) , \quad W _ { 2 } = ( I _ { d } \quad - I _ { d } )$$
where $I _ { d }$ is the $d$ -dimensional identity matrix. For the case of more than two layers, we can use the bottom layer to split the positive and negative part, and the top layer to merge them back. All the intermediate layers can be set to $2 d$ -dimensional identity matrix. Since the bottom layer encode all the responsives in non-negative values, the ReLU in the middle layers will pass through.
# B.3 CONVOLUTIONAL NETWORKS
In particular, we consider 2D convolutional networks for data with the structure of multi-channel images. A mini-batch of data is usually formatted as a four-dimensional tensor of the shape $B \times C \times H \times W$ , where $B$ is the batch size, $C$ the number of channels (e.g. RGB or feature channels for intermediate layer representations), $H$ and $W$ are image height and width, respectively. A convolutional layer (ignoring the bias term) is parameterized with another four-dimensional tensor of the shape $\bar { C } ^ { \bullet } \times \bar { C } ^ { \bullet } K _ { H } \times K _ { W }$ , where $\bar { C }$ is the number of output feature channels, $K _ { H }$ and $K _ { W }$ are convolutional kernel height and width, respectively. The convolutional kernel is applied at local $K _ { H } \times K _ { W }$ patches of the input tensor, with optional padding and striding.
For one convolution layer to represent the identity function, we can use only the center slice of the kernel tensor and set all the other values to zero. Note it is very rare to use even numbers as kernel size, in which case the “center” of the kernel tensor is not well defined. When the kernel size is odd, we can set
$$W _ { \bar { c } c h w } = \left\{ \begin{array} { l l } { 1 } & { \bar { c } = c , \ h = \lfloor K _ { H } / 2 \rfloor , \ w = \lfloor K _ { W } / 2 \rfloor } \\ { 0 } & { \mathrm { o t h e r w i s e } } \end{array} \right.$$
By using only the center of the kernel, we essentially simulate a $1 \times 1$ convolution, and encode a local identity function for each (multi-channel) pixel.
For multi-layer convolutional networks with ReLU activation functions, the same idea as in multilayer fully-connected networks can be applied. Specifically, we ask for twice as many channels as the input channels for the hidden layers. At the bottom layer, separately the positive and negative part of the inputs, and reconstruct them at the top layer.
# C PROOF OF THEOREM 1
Consider the 1-layer linear model $f _ { W } ( x ) = W x$ , where $\boldsymbol { x } \in \mathbb { R } ^ { d }$ and $W \in \mathbb { R } ^ { d \times d }$ . Let $\hat { x }$ be the single training example. The training objective is to minimize the empirical risk $\hat { R } = 1 / 2 \lVert f _ { W } ( x ) - x \rVert _ { 2 } ^ { 2 }$ . The optimization problem is convex and well understood. Due to overparameterization, the solution of the empirical risk minimization is not unique. However, given randomly initialized weights $W ^ { 0 }$ , gradient descent obtains a unique global minimizer.
The gradient of the empirical risk is
$$\frac { \partial \hat { R } } { \partial W } = ( W - I ) \hat { x } \hat { x } ^ { \top }$$
Gradient descent with step sizes $\eta _ { t }$ and initialization weights $W ^ { 0 }$ updates weights as
$$\begin{array} { r l } { \displaystyle } & { \boldsymbol { W } ^ { T } = \boldsymbol { W } ^ { 0 } - \sum _ { t = 1 } ^ { T } \eta _ { t } \big ( \boldsymbol { W } ^ { t - 1 } - I ) \hat { \boldsymbol { x } } \hat { \boldsymbol { x } } ^ { \top } } \\ { : = \boldsymbol { W } ^ { 0 } + u _ { T } \hat { \boldsymbol { x } } ^ { \top } } \end{array}$$
where $u _ { T } \in \mathbb { R } ^ { d }$ is a vector decided via the accumulation in the optimization trajectory. Because of the form of the gradient, it is easy to see the solution found by gradient descent will always have such parameterization structure. Moreover, under this parameterization, a unique minimizer exists that solves the equation
$$\hat { x } = f _ { W } ( \hat { x } ) = W ^ { 0 } \hat { x } + u \hat { x } ^ { \top } \hat { x }$$
via
$$\hat { u } = \frac { ( I - W ^ { 0 } ) \hat { x } } { \Vert \hat { x } \Vert _ { 2 } ^ { 2 } }$$
Therefore, the global minimizer can be written as
$$\begin{array} { r l } { \hat { f } _ { W } ( x ) = ( W ^ { 0 } + \hat { u } \hat { x } ^ { \top } ) x } \\ { = } & { { } + W ^ { 0 } \left( x - \frac { \hat { x } ^ { \top } x } { \Vert \hat { x } \Vert _ { 2 } ^ { 2 } } \cdot \hat { x } \right) } \end{array}$$
For the one-layer network case, the optimization problem is convex. Under standard conditions in convex optimization, gradient descent will converge to the global minimizer shown above.
We can easily verify that the red term is exactly the projection of $x$ onto the training example $\hat { x }$ , while the blue term is the residual projection onto the orthogonal subspace.
# D PROOF OF THEOREM 2
Lemma 1. Consider the linear model $f ( x ) = W ^ { \top } x$ , where $\boldsymbol { x } \in \mathbb { R } ^ { D }$ , $W \in \mathbb { R } ^ { D \times d }$ . Let the training set be $\left\{ ( x _ { 1 } , y _ { 1 } ) , \dotsc ( x _ { N } , y _ { N } ) \right\}$ . Assume the model is overparameterized $\prime N \leq d )$ and there is no sample redundancy (rank of the data matrix is $N$ ). Fitting $f ( \cdot )$ by optimizing the square loss with gradient descent on the training set converges to $\hat { f } ( x ) = \hat { W } ^ { \top } x$ , where
$$\hat { W } = W ^ { 0 } + X ^ { \top } ( X X ^ { \top } ) ^ { - 1 } ( Y - X W ^ { 0 } ) .$$
$W ^ { 0 } \in \mathbb { R } ^ { D \times d }$ is the random initialization of weights, $\boldsymbol { X } = \left( x _ { 1 } , \ldots , x _ { N } \right) ^ { \top } \in \mathbb { R } ^ { N \times D }$ and $Y =$ $\left( y _ { 1 } , \ldots , y _ { N } \right) ^ { \top } \in \mathbb { R } ^ { N \times d }$ are the matrices formed by the inputs and outputs, respectively.
Lemma 2. With the same notation of Lemma $^ { l }$ , assume the model is underparameterized $N > d ,$ ) and there is no feature redundancy (rank of the data matrix is $d ,$ ). Fitting $f ( \cdot )$ by optimizing the square loss with gradient descent on the training set converges to $\hat { f } ( x ) = \hat { W } ^ { \top } x$ where
$$\hat { W } = \left( \boldsymbol { X } ^ { \top } \boldsymbol { X } \right) ^ { - 1 } \boldsymbol { X } ^ { \top } \boldsymbol { Y } ,$$
Proof of Theorem 2. Let $\hat { x } \in \mathbb { R } ^ { H \times W \times C }$ be the single training image of size $H \times W$ , and $C$ color channels. Let $K _ { H } \times K _ { W }$ be the convolution receptive field size, so the weights of convolution filters can be parameterized via a 4-dimensional tensor $\Theta \in \mathbb { R } ^ { K _ { H } \times K _ { W } \times C \times C }$ . Let $\Xi$ be the collection of 2D coordinates of the local patches from the input image that the convolutional filter is applied to, and $\mathsf { P } _ { i j } ( \hat { x } ) \in \mathbb { R } ^ { K _ { H } \times K _ { W } \times C }$ be the local patch of $\hat { x }$ centered at the coordinate $( i , j ) \in \Xi$ . Note for our case the input and output are of the same shape, so the convolution stride is one, and $| \Xi | = H \times W$ .
The empirical risk of fitting $\hat { x }$ with a one-layer convolution model can be written as
$$\hat { R } = \frac { 1 } { 2 } \sum _ { ( i , j ) \in \Xi } \sum _ { k = 1 } ^ { C } \left( \langle \Theta _ { : : : k } , \mathsf { P } _ { i j } ( \hat { x } ) \rangle - \hat { x } _ { i j k } \right) ^ { 2 } ,$$
where $\Theta _ { : : : k } \in \mathbb { R } ^ { K _ { H } \times K _ { W } \times C }$ is the subset of convolution weights corresponding to the $k$ -th output channel, and $\hat { x } _ { i j k }$ is the pixel value at coordinate $( i , j )$ and channel $k$ .
CASE 1 — overparameterization: $| \Xi | \le K _ { H } \times K _ { W } \times C \times C$ . Assumme the patches are linearly independent1, with slight abuse of notatons, we represent the empirical risk in matrix form with the
following matrices2:
$$\begin{array} { r l } & { W : = ( \Theta _ { : : : 1 } , \dots , \Theta _ { : : : C } ) \in \mathbb R ^ { ( K _ { H } K _ { W } C ) \times C } , } \\ & { X : = ( \dots , \mathsf { P } _ { i j } ( \hat { x } ) , \dots ) ^ { \top } \in \mathbb R ^ { | \Xi | \times ( K _ { H } K _ { W } C ) } , } \\ & { Y : = \left( \begin{array} { c c c } { \vdots } & { \vdots } & { \vdots } \\ { \hat { x } _ { i j 1 } } & { \dots } & { \hat { x } _ { i j C } } \\ { \vdots } & { \vdots } & { \vdots } \end{array} \right) \in \mathbb R ^ { | \Xi | \times C } , } \end{array}$$
and apply Lemma 1 to obtain $\hat { W }$ . For a test example $x$ , the prediction of the $( i , j )$ -th (multi-channel) pixel is
$$\begin{array} { r l } & { \hat { W } ^ { \top } { \mathsf P } _ { i j } ( x ) = \left( W ^ { 0 } + X ^ { \top } \left( X X ^ { \top } \right) ^ { - 1 } ( Y - X W ^ { 0 } ) \right) ^ { \top } { \mathsf P } _ { i j } ( x ) } \\ & { \qquad = W ^ { 0 \top } \left( I - X ^ { \top } \left( X X ^ { \top } \right) ^ { - 1 } X \right) { \mathsf P } _ { i j } ( x ) + Y ^ { \top } ( X X ^ { \top } ) ^ { - 1 } X { \mathsf P } _ { i j } ( x ) } \end{array}$$
Note we are learning the identity map, the $( i , j )$ -th row of the learning target matrix $Y$ is the (multi-channel) pixel at the $( i , j )$ -th coordinate of $\hat { x }$ . This is exactly the center of the $( i , j )$ -th patch $\mathsf P _ { i j } ( \hat { x } )$ , i.e. the $( i , j )$ -th row of the matrix $X$ . As a result, there is a linear projection matrix $\boldsymbol { \Lambda } \in \mathrm { \bar { \mathbb { R } } } ^ { ( K _ { H } K _ { W } C ) \times C }$ that maps $X$ to $Y \colon X \Lambda = Y$ . So
$$\begin{array} { r } { \hat { W } ^ { \top } P _ { i j } ( x ) = W ^ { 0 \top } \Pi _ { X } ^ { \bot } \mathsf { P } _ { i j } ( x ) + \Lambda ^ { \top } \Pi _ { X } ^ { \| } \mathsf { P } _ { i j } ( x ) } \end{array}$$
where $\Pi _ { X } ^ { \parallel } = X ^ { \top } ( X X ^ { \top } ) ^ { - 1 } X$ is the linear operator that projects a vector into the subspace spanned by the rows of $X$ , and $\Pi _ { X } ^ { \bot } = I - \Pi _ { X } ^ { \| }$ is the operator projecting into the orthogonal subspace.
To compute the prediction errors, it is suffice to look at the errors at each $( i , j )$ -th (multi-channel) pixel separately:
$$\begin{array} { r l } & { \mathrm { E r r o r } _ { i j } ^ { 2 } = \Vert \hat { f } ( x ) _ { i j } - \Lambda ^ { \top } \mathsf { P } _ { i j } ( x ) \Vert ^ { 2 } } \\ & { \qquad = \left. W ^ { 0 ^ { \top } } \Pi _ { X } ^ { \bot } \mathsf { P } _ { i j } ( x ) + \Lambda ^ { \top } \Pi _ { X } ^ { \| } \mathsf { P } _ { i j } ( x ) - \Lambda ^ { \top } \mathsf { P } _ { i j } ( x ) \right. ^ { 2 } } \\ & { \qquad = \left. ( W ^ { 0 } - \Lambda ) ^ { \top } \Pi _ { X } ^ { \bot } \mathsf { P } _ { i j } ( x ) \right. ^ { 2 } } \\ & { \qquad \le \left( \left( \left. W ^ { 0 ^ { \top } } \Pi _ { X } ^ { \bot } \right. + \left. \Lambda ^ { \top } \Pi _ { X } ^ { \bot } \right. \right) \left. \mathsf { P } _ { i j } ( x ) \right. \right) ^ { 2 } . } \end{array}$$
Assume the absolute value of pixel values are bounded by $B$ , then
$$\| \mathsf { P } _ { i j } ( x ) \| \leq B \sqrt { K _ { H } K _ { W } C } .$$
The first two terms can be bounded according to the rank r of the subspace projection $\Pi _ { X } ^ { \parallel }$ . Let the nullity of the projection be ${ \mathfrak { n } } = K _ { H } K _ { W } C - { \mathfrak { r } }$ . Note the projection matrix can be decomposed as
$$\Pi _ { X } ^ { \perp } = \sum _ { k = 1 } ^ { \mathfrak { n } } v _ { k } v _ { k } ^ { \top }$$
where $\{ v _ { k } \} _ { k }$ is a orthonormal basis for the projection subspace.
$$\begin{array} { r l } { \| \Lambda ^ { \top } \Pi _ { X } ^ { \perp } \| = \bigg \| \Lambda ^ { \top } \displaystyle \sum _ { k = 1 } ^ { n } v _ { k } v _ { k } ^ { \top } \bigg \| } & { } \\ { = \sqrt { \displaystyle \sum _ { k = 1 } ^ { n } \| \Lambda ^ { \top } v _ { k } \| ^ { 2 } } } & { } \\ { \leq \sqrt { \mathsf { n } \| \Lambda \| ^ { 2 } } } & { } \\ { = \sqrt { \mathsf { n } C } . } \end{array}$$
(sub-multiplicativity of the Frobenius norm)
Similarly,
$$\left\| W ^ { 0 ^ { \top } } \Pi _ { X } ^ { \perp } \right\| = \sqrt { \sum _ { k = 1 } ^ { \mathfrak n } \left\| W ^ { 0 ^ { \top } } v _ { k } \right\| ^ { 2 } }$$
Assume the entries of $W ^ { 0 }$ are initialized as i.i.d. Gaussians ${ \mathcal { N } } ( 0 , \sigma ^ { 2 } )$ . Since $\{ v _ { k } \} _ { k }$ are orthonormal vectors, for each $k$ , let $\rho _ { k } = \| \boldsymbol { W ^ { 0 \top } v _ { k } } \| ^ { 2 } / \sigma ^ { 2 }$ , then $\rho _ { k }$ is distributed according to $\hat { \chi } ^ { 2 }$ distribution with $C$ degree of freedom. For any $1 < \zeta \leq M$ , where $M$ is a constant chosen a priori, and for each $k = 1 , \ldots , \mathfrak { n }$ ,
(Markov’s inequality)
$$\begin{array} { r l } & { \mathsf { P } ( \rho _ { k } \ge \zeta C ) \le e ^ { - \zeta t C } \mathbb { E } [ e ^ { t \rho _ { k } } ] , } \\ & { \quad \quad \quad = e ^ { - \zeta t C } ( 1 - 2 t ) ^ { - C / 2 } , \quad \forall t < ^ { 1 / 2 } , } \\ & { \quad \quad \quad = \exp ( - C ( \zeta t + ^ { 1 } / 2 \log ( 1 - 2 t ) ) ) , } \\ & { \quad \quad \quad \le \exp ( - C / 2 ( \zeta - 1 + \log ( 1 / \zeta ) ) ) , } \\ & { \quad \quad \quad \le \exp ( - C / 2 ( \zeta - 1 + \log ( 1 / M ) ) ) . } \end{array}$$
By union bound,
$$\begin{array} { r } { \mathsf { P } \left( \exists k \in \{ 1 , \dots , \mathfrak { n } \} : \rho _ { k } \ge \zeta C \right) \le \mathsf { n e x p } \left( - C / 2 ( \zeta - 1 + \log ( 1 / M ) ) \right) . } \end{array}$$
Let $\delta$ equals the right hand side, and solve for $\zeta$ , we get for any $\delta \ge \delta _ { 0 } > 0$ , with probability at least $1 - \delta$
$$\forall k : \rho _ { k } < 2 \log \left( \frac { \mathfrak { n } } { \delta } \right) + C ( 1 + \log M )$$
where $\delta _ { 0 } \geq 2 \mathfrak { n } / ( C ( M - \log M - 1 ) )$ is chosen to satisfy $\zeta \leq M$ . We can also choose $\delta _ { 0 }$ first and set $M$ accordingly.
Putting everyting together, with probability at least $1 - \delta$ , the mean squared error (averaged over all output pixels)
$$\begin{array} { l } { \displaystyle \mathrm { E r r o r } ^ { 2 } = \frac { 1 } { | \Xi | C } \sum _ { i j \in \Xi } \mathrm { E r r o r } _ { i j } ^ { 2 } , } \\ { \displaystyle \mathrm { \quad } \le \left( \left( \sqrt { \mathfrak { n } \sigma ^ { 2 } \left( 2 \log \left( \frac { \mathfrak { n } } { \delta } \right) + C ( 1 + \log M ) \right) } + \sqrt { \mathfrak { n } C } \right) B \sqrt { K _ { H } K _ { W } C } \right) ^ { 2 } \Biggl / c , } \\ { \displaystyle \mathrm { \quad } = { \cal O } \left( \frac { K _ { H } K _ { W } C ^ { 2 } \mathfrak { n } ( 1 + 1 / C \log ( \mathfrak { n } / \delta ) ) } { C } \right) . } \end{array}$$
Note $K _ { H } K _ { W } C ^ { 2 }$ is the number of parameters in the convolution net.
CASE 2 — underparameterization: $| \Xi | > K _ { H } \times K _ { W } \times C \times C$ . Using the same notation above, assuming no redundant features, we apply Lemma 2 to get the prediction of the $( i , j )$ -th (multichannel) pixel of a test example $x$ as
$$\begin{array} { r l } & { \hat { W } ^ { \top } \mathsf { P } _ { i j } ( x ) = Y ^ { \top } X ( X ^ { \top } X ) ^ { - 1 } \mathsf { P } _ { i j } ( x ) } \\ & { \quad \quad = \Lambda ^ { \top } X ^ { \top } X ( X ^ { \top } X ) ^ { - 1 } \mathsf { P } _ { i j } ( x ) } \\ & { \quad \quad = \Lambda ^ { \top } \mathsf { P } _ { i j } ( x ) } \end{array}$$
Recall the definition of $\Lambda$ , which maps a patch to the corresponding (multi-channel) pixel. In this case, the prediction is exact, and the error is zero. Since in this case $\mathfrak { n }$ , this case can be merged with equation 12. □
Proof of Lemma $^ { l }$ . The proof is an extension of Theorem 1 to the case of more than one training examples. Using the notation in the Lemma, the training objective can be written as the matrix form
$$\hat { R } = \frac { 1 } { 2 } \left\| X W - Y \right\| _ { 2 } ^ { 2 } ,$$
and the gradient as
$$\frac { \partial \hat { R } } { \partial W } = X ^ { \top } ( X W - Y ) .$$
Since the model is overparameterized, and there is no unique minimizer to the empirical risk. However, gradient descent converges to a unique solution. Note the gradient descent step is:
$$\begin{array} { r c l } { { W ^ { t } } } & { { = } } & { { W ^ { t - 1 } - \eta _ { t } \left. \frac { \partial \hat { R } } { \partial W } \right| _ { W = W _ { t - 1 } } } } \\ { { } } & { { = } } & { { W ^ { t - 1 } - \eta _ { t } X ^ { \top } ( X W ^ { t - 1 } - Y ) } } \\ { { } } & { { = } } & { { W ^ { 0 } - { \displaystyle \sum _ { \tau = 1 } ^ { t - 1 } } \eta _ { \tau } X ^ { \top } ( X W ^ { \tau } - Y ) } } \\ { { } } & { { : = } } & { { W ^ { 0 } + X ^ { \top } U ^ { t } , } } \end{array}$$
where $\begin{array} { r } { U ^ { t } = - \sum _ { \tau = 1 } ^ { t - 1 } \eta _ { \tau } ( X W ^ { \tau } - Y ) \in \mathbb { R } ^ { N \times d } } \end{array}$ parameterizes the solution at iteration $t$ . Since $X X ^ { \top }$ is invertible in this case. A unique solution exists under this parameterization, which can be obtained by solving
$$\begin{array} { r l } & { X ( W ^ { 0 } + X ^ { \top } \hat { { \boldsymbol { U } } } ) = Y } \\ { \Rightarrow } & { \hat { { \boldsymbol { U } } } = \left( X X ^ { \top } \right) ^ { - 1 } ( Y - X W ^ { 0 } ) . } \end{array}$$
Plug this into the parameterization, we get
$$\hat { W } = W ^ { 0 } + X ^ { \top } \left( X X ^ { \top } \right) ^ { - 1 } ( Y - X W ^ { 0 } ) .$$
Proof of Lemma 2. Using the same notation as in the proof of Lemma 1, since the model is underparameterized, a unique minimizer of the empirical risk exists. Directly solving for the optimality condition $\partial \hat { R } / \partial W = 0$ , we get
$$\hat { W } = \left( X ^ { \top } X \right) ^ { - 1 } X ^ { \top } Y .$$
# E FULL RESULTS OF FULLY CONNECTED MULTI-LAYER NETWORKS
In this section, we present the detailed results on fully connected networks that are omitted from Section 3.1 due to space limit.
# E.1 FULLY CONNECTED LINEAR NETWORKS
Figure 11 shows the results on multi-layer linear networks with various number of hidden layers and hidden units. The depth of the architecture has a stronger effect on the inductive bias than the width. For example, the network with one hidden layer of dimension 2048 has 3.2M parameters, more than the $2 . 5 \mathrm { M }$ parameters of the network with three hidden layers of dimension 784. But the latter behaves less like the convex case.
# E.2 TWO-LAYER FULLY CONNECTED RELU NETWORKS
Li & Liang (2018) offer a theoretical characterization of learning in a two-layer ReLU neural network. They show that when the data consists of well separated clusters (i.e., the cluster diameters are much smaller than the distances between each cluster pair), training an overparameterized twolayer ReLU network will generalize well. To simplify the analysis, they study a special case where the weights in the top layer are randomly initialized and fixed; only the bottom layer weights are learned.
 Figure 11: Visualization of predictions from trained multi-layer linear networks. The first row shows the input images for evaluation, including the single training image “7” at the beginning of the row. The remaining rows shows the prediction from a trained linear network with 1, 3, and 5 hidden layers, respectively.
 Figure 12: Visualization of predictions from two-layer ReLU networks. The first row shows the input images for evaluation, including the single training image “7” at the beginning of the row. The remaining rows shows the predictions from trained models with hidden dimension 2,048 and 16,384, repectively.
We study the problem of learning a two-layer ReLU network under our identity-mapping task. Figure 12 compares the cases of learning the bottom layer only and learning both layers (left and right panels, respectively). The two cases demonstrate different inductive biases for predictions on unseen test images. When only the first layer is trained, the tendency is toward speckled noise, but when both layers are trained, the tendency is toward a constant output (the image used for training). Our observation does not contradict the theoretical results of Li & Liang (2018), which assume a well separated and clustered data distribution.
For bottom-layer only training, we can analyze it in a similar way to the one-layer networks. Let us denote
$$f _ { W } ( x ) = \langle \alpha , \operatorname { R e L U } ( z ) \rangle , \quad z = W x$$
where $W \in \mathbb { R } ^ { m \times d }$ is the learnable weight matrix, and $\alpha \in \mathbb { R } ^ { m }$ is randomly initialized and fixed. Although the trained weights no longer have a closed-form solution, the solution found by gradient descent is always parameterized as
$$W ^ { T } = W ^ { 0 } + u ^ { T } \hat { x } ^ { \top }$$
where $\hat { x }$ is the training example, and $\boldsymbol { u } ^ { T } \in \mathbb { R } ^ { m }$ summarizes the efforts of gradient descent up to time $T$ . In particular, the gradient of the empirical risk $\hat { R }$ with respect to each row $W _ { : r }$ of the learnable weight is
$$\frac { \partial \hat { R } } { \partial W _ { : r } } = \frac { \partial \hat { R } } { \partial z _ { r } } \frac { \partial z _ { r } } { \partial W _ { : r } } = \frac { \partial \hat { R } } { \partial z _ { r } } \hat { x } ^ { \top }$$
Putting it together, the full gradient is
$$\frac { \partial \hat { R } } { \partial W } = \frac { \partial \hat { R } } { \partial z } \cdot \hat { x } ^ { \top }$$
Since the gradient lives in the span of the training example $\hat { x }$ , the solution found by gradient descent is always parameterized as equation 16.
 Figure 13: Visualization of predictions from multi-layer ReLU networks. The first row shows the input images for evaluation, including the single training image “7” at the beginning of the row. The remaining rows show the predictions from trained multi-layer ReLU FCNs with 1, 3, and 9 hidden layers.
 Figure 14: Quantitative evaluation of the learned model on randomly generated test samples at various angles (correlation) to the training image. The horizontal axis shows the train-test correlation, while the vertical axis indicate the number of hidden layers for the FCNs being evaluated. The heatmap shows the similarity (measured in correlation) between the model prediction and the reference function (the constant function or the identity function). (a) shows the results for FCNs with the ReLU activation function; (b) shows the results for linear FCNs.
The same arguments applies to multi-layer neural networks. The prediction on any test example that is orthogonal to $\hat { x }$ will depend only on randomly initialized $W ^ { 0 }$ and upper layer weights. When only the bottom layer is trained, the upper layer weights will also be independent from the data, therefore the prediction is completely random. However, when all the layers are jointly trained, the arguments no longer apply. The empirical results presented in the main text that multi-layer networks bias towards the constant function verify this.
In particular, if the test example is orthogonal to $\hat { x }$ (i.e., $\hat { x } ^ { \top } x = 0 )$ ), the prediction depends solely on the randomly initialized values in $W ^ { 0 }$ and therefore can be characterized by the distribution used for parameter initialization.
However, when both layers are trained, the upper layer weights are also tuned to make the prediction fit the training output. In particular, the learned weights in the upper layer depend on $W ^ { 0 }$ . Therefore, the randomness arguments shown above no longer apply even for test examples orthogonal to $\hat { x }$ . As the empirical results show, the behavior is indeed different.
# E.3 NONLINEAR MULTI-LAYER FULLY CONNECTED NETWORKS
In this section, we consider the general case of multilayer fully connected networks (FCNs) with ReLU activation functions. Figure 13 visualizes predictions from trained ReLU FCNs with 1, 3, or 9 hidden layers. The deepest network encodes the constant map with high confidence; the shallowest network shows behavior similar to that of a one-layer linear net. Quantitative evaluations of the behaviors are shown in Figure 14, computed in the same way as Figure 4 for CNNs (see Section 3.2). The results for linear FCNs are also shown for comparison. The linear and ReLU FCNs behave similarly when measuring the correlation to the identity function: neither of them performs well for test images that are nearly orthogonal to $\hat { x }$ . For the correlation to the constant function, ReLU FCNs overfit sooner than linear FCNs when the depth increases. This is consistent with our previous visual inspections: for shallow models, the networks learn neither the constant nor the identity function, as the predictions on nearly orthogonal examples are random.
 Figure 15: Visualization the intermediate layers of CNNs with different number of layers. The first column shows a randomly initialized 20-layer CNN (random shallower CNNs look similar to the truncation of this). The rest of the columns show the trained CNNs with various number of layers.
# F VISUALIZATION OF THE INTERMEDIATE LAYER REPRESENTATIONS FOR CNNS
Unlike the FCNs, CNNs preserve the spatial relation between neurons in the hidden layers, so we can easily visualize the intermediate layers as images in comparison to the inputs and outputs, to gain more insights on how the networks are computing the functions layer-by-layer. In Figure 15, we visualize the intermediate layer representations on some test patterns for CNNs with different depths. In particular, for each example, the outputs from a convolutional layer in an intermediate layer is a three dimensional tensor of shape (#channel, height, width). To get a compact visualization for multiple channels in each layer, we compute flatten the 3D tensor to a matrix of shape (#channel, height $\times$ width), compute SVD and visualize the top singular vector as a one-channel image.
In the first column, we visualize a 20-layer CNN at random initialization3. As expected, the randomly initialized convolutional layers gradually smooth out the input images. The shape of the input images are (visually) wiped out after around 8 layers of (random) convolution. On the right of the figure, we show several trained CNNs with increasing depths. For a 7-layer CNN, the holistic structure of inputs are still visible all the way to the top at random initialization. After training, the network approximately renders an identity function at the output, and the intermediate activations also become less blurry. Next we show a 14-layer CNN, which fails to learn the identity function.
 Figure 16: Visualizing the intermediate layers of a trained 7-layer CNN. The three subfigures show for each layer: 1) the top singular vector across the channels; 2) the channel that maximally correlate with the input image; 2) a random channel, respectively.
 Figure 17: Visualizing the intermediate layers of a trained 14-layer CNN. The three subfigures show for each layer: 1) the top singular vector across the channels; 2) the channel that maximally correlate with the input image; 2) a random channel, respectively.
However, it manages to recover meaningful information in the higher layer activations that were (visually) lost in the random initialization. On the other hand, in the last column, the network is so deep that it fails to make connection from the input to the output. Instead, the network start from scratch and constructs the digit $\bullet \mathbf { 7 } ^ { \bullet }$ from empty and predict everything as ‘7’. However, note that around layer-8, we see the activations depict slightly more clear structures than the randomly initialized network. This suggests that some efforts have been made during the learning, as opposed to the case that the bottom layers not being learned due to complete gradient vanishing. Please refer to Appendix G for further details related to potential gradient vanishing problems.
Two alternative visualizations to the intermediate multi-channel representations are provided that show the channel that is maximally correlated with the input image, and a random channel (channel 0). Figure 16, Figure 17 and Figure 18 illustrate a 7-layer CNN, a 14-layer CNN and a 20-layer CNN, respectively.
# G MEASURING THE CHANGE IN WEIGHTS OF LAYERS POST TRAINING
In this section, we study the connection between the inductive bias of learning the constant function and the potential gradient vanishing problem. Instead of measuring the norm of gradient during training, we use a simple proxy that directly compute the distance of the weight tensor before and after training. In particular, for each weight tensor $W ^ { 0 }$ at initialization and $W ^ { \star }$ after training, we compute the relative $\ell _ { 2 }$ distance as
$$d ( W ^ { 0 } , W ^ { \star } ) : = \frac { \| W ^ { 0 } - W ^ { \star } \| } { \| W ^ { 0 } \| }$$
The results for CNNs with various depths are plotted in Figure 19(a). As a general pattern, we do see that as the network architecture gets deeper, the distances at lower layers do become smaller. But they are still non-zero, which is consistent with the visualization in Figure 15 showing that even for the 20-layer CNN, where the output layer fits to the constant function, the lower layers does get enough updates to allow them to be visually distinguished from the random initialization.
 Figure 18: Visualizing the intermediate layers of a trained 20-layer CNN. The three subfigures show for each layer: 1) the top singular vector across the channels; 2) the channel that maximally correlate with the input image; 2) a random channel, respectively.
 Figure 19: The relative $\ell _ { 2 }$ distance of the weight tensors before and after training at each layer. The curves compare models at different depth. Most of the networks have significantly larger distances on the top-most layer. To see a better resolution at the bottom layers, we cut off the top layer in the figures by manually restricting the y axis.
 Figure 20: Visualization of a 5-layer CNN on test images of different sizes. Every two rows show the inputs and model predictions. The numbers on the left indicate the input image size (both width and height).
In Figure 19(b) and (c), we show the same plots for linear FCNs and FCNs with ReLU activation, respectively. We see that especially for ReLU FCN with 11 hidden layers, the distances for the weight tensors at the lower 5 layers are near zero. However, recall from Figure 13 in Section E.3, the ReLU FCNs start to bias towards the constant function with only three hidden layers, which are by no means suffering from vanishing gradients as the plots here demonstrate.
# H FULL RESULTS ON ROBUSTNESS OF INDUCTIVE BIASES
# H.1 TESTING ON DIFFERENT INPUT IMAGE SIZES
Figure 6 in Section 3.3 visualize the predictions of a 5-layer CNN on inputs of the extreme sizes of $7 \times 7$ and $1 1 2 \times 1 1 2$ . Here in Figure 20 we provide more results on some intermediate image sizes.
We also test a trained 20-layer CNN on various input sizes (Figure 7). It is interesting that the constant map also holds robustly across a wide range of input sizes. Especially from the prediction on large input images, we found hints on how the CNNs actually compute the constant function. It seems the artifacts from the outside boundary due to convolution padding are used as cues to “grow” a pattern inwards to generate the digit “7”. The visualizations of the intermediate layer representatiosn in Figure 21 is consistent with our hypothesis: the CNN take the last several layers to realize this construction. This is very clever, because in CNNs, the same filter and bias is applied to all the spatial locations. Without relying on the artifacts on the boundaries, it would be very challenging to get a sense of the spatial location in order to construct an image with a holistic structure (e.g. the digit “7” in our case).
# H.2 THE UPPER SUBNETWORKS
In the visualization of intermediate layers (Figure 15), the intermediate layers actually represent the “lower” subnetwork from the inputs. Here we investigate the “upper” subnetwork. Thanks again to the spatial structure of CNNs, we can skip the lower layers and feed the test patterns directly to the intermediate layers and still get interpretable visualizations4. Figure 22 shows the results for the top-one layer from CNNs with various depths. A clear distinction can be found at 15-layer CNN, which according to Figure 3 is where the networks start to bias away from edge detector and towards the constant function.
 Figure 21: Visualization of intermediate representations when testing on images of different sizes from training images for a 20-layer trained CNN. The CNN is trained on a $2 8 \times 2 8$ image of the digit $\mathbf { \bar { \Psi } } ^ { 6 6 } 7 ^ { 9 }$ .
 Figure 22: Visualizing only the final layer in trained networks. The first row are the input images, which are directly fed into the final layer of trained networks (skipping the bottom layers). The remaining rows shows the predictions from the top layers of CNNs, with the numbers on the left indicating their (original) depth.
 Figure 23: Visualizing only the top two layers in trained networks. The first row are the input images, which are directly fed into the top two layer of trained networks (skipping the bottom layers). The remaining rows shows the predictions from the top two layers of CNNs, with the numbers on the left indicating their (original) depth. More specifically, each of the two top layers occupies one row. The colorful rows are the visualizations (as the top singular vector across channels) of the outputs of the second to the last layer from each network. The grayscale rows are the outputs of the final layer from each network.
The predictions from the final two layers of each network are visualized in Figure 23. Figure 24 focuses on the 20-layer CNN that learns the constant map, and visualize the upper 3 layers, 6 layers and 10 layers, respectively. In particular, the last visualization shows that the 20-layer CNN is already starting to construct the digit “7” from nowhere when using only the upper half of the model.
 Figure 24: Visualzing the top 3 layers, 6 layers and 10 layers of a 20-layer CNN. Visualizations formatted in the same way as Figure 23.
 Figure 25: Inductive bias of a 5-layer CNN with varying convolutional filter size. The heatmap is arranged similarly as Figure 4, except that the rows correspond to CNNs filter sizes.
# I FULL RESULTS ON VARYING DIFFERENT FACTORS WHEN TRAINING CNNS
The study on the effects of various hyperparameters on the inductive bias of trained CNNs is briefly presented in Section 3.4. The full results are shown here.
Convolution filter sizes Figure 25 and Figure 26 illustrate the inductive bias with varying convolution filter size from $5 \times 5$ to $5 7 \times 5 7$ . The visualization shows that the predictions become more and more blurry as the filter sizes grow. The heatmaps, especially the correlation to the identity function, are not as helpful in this case as the correlation metric is not very good at distinguishing images with different levels of blurry. With extremely large filter sizes that cover the whole inputs, the CNNs start to bias towards the constant function. Note our training inputs are of size $2 8 \times 2 8$ , so $2 9 \times 2 9$ filter size allows all the neurons to see no less than half of the spatial domain from the previous layer. $5 7 \times 5 7$ filters centered at any location within the image will be able to see the whole previous layer. On the other hand, the repeated application of the same convolution filter through out the spatial domain is still used (with very large boundary paddings in the inputs). So the CNNs are not trivially doing the same computation as FCNs.
Convolution channel depths Figure 10 in Section 3.4 shows that the learned identity function is severely corrupted when only 3 channels are used in the 5-layer CNNs. Figure 27 presents the correlation to the constant and the identity function when different numbers of convolution channels are used. The heatmap is consistent with the visualizations, showing that the 5-layer CNN fails to approximate the identity function when only three channels are used in each convolution layer.
Furthermore, Figure 28 visualize the predictions of trained 3-channel CNNs with various depths. The 3-channel CNNs beyond 8 layers fail to converge during training. The 5-layer and the 7-layer CNNs implement functions biased towards edge-detecting or countour-finding. But the 6-layer and the 8-layer CNNs demonstrate very different biases. The potential reason is that with only a few channels, the random initialization does not have enough randomness to smooth out “unlucky” bad cases. Therefore, the networks have higher chance to converge to various corner cases. Figure 29 and Figure 30 compare the random initialization with the converged network for a 3-channel CNN and a 128-channel CNN. From the visualizations of the intermediate layers, the 128-channel CNN already behave more smoothly than the 3-channel CNN at initialization.
 Figure 26: Visualizing the predictions from CNNs with various filter sizes. The first row is the inputs, including the single training image “7”. The remaining rows are predictions, with the numbers on the left showing the corresponding filter sizes.
 Figure 27: Correlation to the constant and the identity function for different convolution channels in a 5-layer CNN.
 Figure 28: Visualization predictions from CNNs with 3 convolution channels and with various number of layers (numbers on the left). The first row is the inputs, and the remaining rows illustrate the network predictions.
 Figure 29: Visualizing the randomly initialized models to compare two 5-layer CNNs with 3 convolution channels per layer and 128 convolution channels per layer, respectively. The subfigures visualize the predictions of intermediate layers of the two network at random initialization. The multi-channel intermediate layers are visualized as the top singular vectors.
 Figure 30: Comparing two 5-layer CNNs with 3 convolution channels per layer and 128 convolution channels per layer, respectively. Layout is similar to Figure 29.
Initialization schemes In transfer learning, it is well known that initializing with pre-trained network weights could affect the inductive bias of trained models. On the other hand, different random initialization schemes are mainly proposed to help with optimization by maintaining information flow or norms of representations at different depths. It turns out that they also strongly affect the inductive bias of the trained models. Figure 31 visualizes the different inductive biases. Let $f _ { i }$ , $f _ { o }$ be the fan in and fan out of the layer being initialized. We tested the following commonly used initialization schemes: 1) default: $\bar { \mathcal { N } } ( 0 , \sigma ^ { 2 } = 1 / ( f _ { i } f _ { o } ) ) ; 2$ ) Xavier (a.k.a. Glorot) init (Glorot & Bengio, 2010): $\mathcal { N } ( 0 , \sigma ^ { 2 } = 2 / ( f _ { i } + f _ { o } ) )$ ; 3) Kaiming init (He et al., 2015): $\mathcal { N } ( 0 , \sigma ^ { 2 } = 2 / f _ { i } )$ ; 4) Orthogonal init (Saxe et al., 2014). Variations with uniform distributions instead of Gaussian distributions are also evaluated for Xavier and Kaiming inits. All initialization schemes bias toward the identity function for shallow networks. But Kaiming init produces heavy artifacts on test predictions. For the bias towards the constant function in deep networks, Xavier init behaves similarly to the default init scheme, though more layers are needed to learn a visually good identity function. On the other hand, the corresponding results from the Kaiming init is less interpretable.
Optimizers First order stochastic optimizers are dorminately used in deep learning due to the huge model sizes and dataset sizes. To improve convergence speed, various adaptive methods are introduced (Duchi et al., 2011; Kingma & Ba, 2014; Graves, 2013). It is known that those methods lead to worse generalization performances in some applications (e.g. Wu et al. (2016)). But they are extremely popular in practice due to the superior convergence speed and easier hyper-parameter tuning than the vanilla SGD. We compare several popular optimizers in our framework, and confirm that different optimizers find different global minimizers, and those minimizers show drastically different inductive biases on test examples, as shown in Figure 32. Some optimizer requires a smaller base learning rate to avoid parameter exploding during training. In particular, we use base learning rate 0.001 for Adagrad and Adamax, 0.0001 for Adam and RMSprop. For comparison, we also include results from SGD with those corresponding base learning rates.
 Figure 31: Visualization of the predictions from CNNs trained with the D) default, Xn) Xavier normal, Xu) Xavier uniform, Kn) Kaiming normal, Ku) Kaiming uniform, and Or) orthogonal initialization schemes. The first row shows the inputs, and the remaining rows shows the predictions from each trained networks.
 Figure 32: Visualization of the predictions from CNNs trained with different optimizers. The first row shows the inputs, and the remaining rows shows the predictions from SGD (lr 0.01), SGD (lr 0.001), SGD (lr 0.0001), Adagrad, RMSprop, Aam, and Adamax respectively.
# J CORRELATION VS MSE
Figure 33, Figure 34 and Figure 35 can be compared to their corresponding figures in the main text. The figures here are plotted with the MSE metric between the prediction and the groundtruth, while the figures in the main text uses the correlation metric. Each corresponding pair of plots are overall consistent. But the correlation plots show the patterns more clearly and has a fixed value range of [0, 1] that is easier to interpret.
 Figure 33: Quantitative evaluation of linear FCNs. The same as Figure 14(a), except MSE is plotted here instead of correlation.
 Figure 34: Quantitative evaluation of ReLU FCNs. The same as Figure 14(b), except MSE is plotted here instead of correlation.
 Figure 35: Quantitative evaluation of CNNs. The same as Figure 4, except MSE is plotted here instead of correlation.
 mse to identity function
 Figure 36: Visualization of predictions from CNNs trained on a single example. The same training example is used as in the main text, but two extra runs of training and evaluation are listed to show the robustness of our main observations to the randomness in the experiments.
 Figure 37: Visualization of predictions from CNNs trained on a single example. Two different (randomly chosen) training images (a) digit 3, (b) digit 0, are shown to compare robustness of our main observations to different training images.
# K ROBUSTNESS OF OBSERVATIONS TO RANDOM SEEDS
We evaluate the robustness of our main observations to randomness from the experiments in this section. In Figure 36, two different runs of training and evaluation are compared side by side, and the results are very consistent. In Figure 37 we further perturb the random seeds for data loading, so that different (single) training images are loaded for training. We can see that the main observations hold for both cases: CNNs learn the identity map, edge detector and the constant map as the depth increases.
 Figure 38: Visualization of the predictions from networks trained with 2 examples. The first two columns are training examples, and the remaining columns are unseen test cases. H0—H9 shows fully connected networks with the corresponding number of hidden layers. C3—C24 shows CNNs with the corresponding number of layers.
# L LEARNING WITH MULTIPLE EXAMPLES
We focus on learning from a single example in this paper because the two extreme inductive biases of the identity map and the constant map can be precisely defined and tested against. When training with multiple examples, the constant map is no longer a viable solution to the optimization problem. Nevertheless, we can still qualitatively evaluate the inductive bias via visualization of predictions. Figure 38 shows the results on various networks trained with two examples. In particular, for networks that are known to overfit to the constant map when trained with one example (e.g. fully connected networks with 9 hidden layers, and 20-layer convolutional networks), similar overfitting behaviors are observed. In this case, a proper definition of a constant map no longer holds, as the network perfectly reconstruct each individual digit from the training set. On the test set, a notion of memorization can be recognized as always predicting a mixture of the training samples. Note sometimes the prediction is biased more towards one of the training samples depending on the input patterns.
Figure 39 shows the results with three examples, with similar observations. Figure 40 shows the situation when training with the full MNIST training set (60k examples). In this case, even the deepest convolutional networks we tried successfully learn the identity function. Fully connected networks learn the identity function on the manifold of digit inputs, but still cannot reconstruct meaningful results on other test patterns.
 Figure 39: Visualization of the predictions from networks trained with 3 examples. The first three columns are training examples, and the remaining columns are unseen test cases. H0—H9 shows fully connected networks with the corresponding number of hidden layers. C3—C24 shows CNNs with the corresponding number of layers.
 Figure 40: Visualization of the predictions from networks trained with 60k examples. The first three columns are (3 out of 60k) training examples, and the remaining columns are unseen test cases. H0—H9 show fully connected networks (ReLU activation) with the corresponding number of hidden layers. LinH1—LinH9 show linear fully connected networks (without activation) with the corresponding number of hidden layers. And C3—C24 show CNNs with the corresponding number of layers.
Table 1: Number of parameters of different neural network architectures used in this paper. The number of parameters are calculated for $2 8 \times 2 8$ grayscale input / output sizes.
<table><tr><td>FCN num layers</td><td>1</td><td>2</td><td>4</td><td>6</td><td>8</td><td>10</td></tr><tr><td>hidden dim = 784</td><td>614,656</td><td>1,229,312</td><td>2,458.624</td><td>3,687,936</td><td>4,917,248</td><td>6,146,560</td></tr><tr><td>hidden dim = 2048</td><td></td><td>3,211,264</td><td>11,599,872</td><td>19,988,480</td><td>28,377,088</td><td>36,765,696</td></tr><tr><td>CNN num layers</td><td>1</td><td>3</td><td>5</td><td>6</td><td>7</td><td>8</td></tr><tr><td>5 × 5 filter,3channels</td><td>25</td><td>375</td><td>825</td><td>1,050</td><td>1,275</td><td>1,500</td></tr><tr><td>5 × 5 filter,128 channels</td><td>25</td><td>416.000</td><td>1,235,200</td><td>1,644,800</td><td>2,054,400</td><td>2,464,000</td></tr><tr><td>5 × 5 filter,1024 channels</td><td></td><td></td><td>78,694,400</td><td></td><td>131,123,200</td><td></td></tr><tr><td>7 × 7 filter,3 channels</td><td>49</td><td>735</td><td>1,617</td><td>2.058</td><td>2,499</td><td>2,940</td></tr><tr><td>7 × 7 filter,128 channels 7 × 7 filter,1024 channels</td><td>49</td><td>815,360</td><td>2,420,992 154,241,024</td><td>3,223,808</td><td>4,026,624</td><td>4,829,440</td></tr><tr><td></td><td></td><td></td><td></td><td></td><td>257,001,472</td><td></td></tr><tr><td>CNN num layers</td><td>9</td><td>10</td><td>11</td><td>12</td><td>13</td><td>14</td></tr><tr><td>5 × 5 filter,3channels</td><td>1,725</td><td>1,950</td><td>2,175</td><td>2,400</td><td>2.625</td><td>2,850</td></tr><tr><td>5 × 5 filter,128 channels</td><td>2,873,600</td><td>3,283,200</td><td>3,692,800</td><td>4,102,400</td><td>4,512,000</td><td>4,921,600</td></tr><tr><td>5 × 5 filter,1024 channels</td><td></td><td></td><td></td><td>262,195,200</td><td></td><td>314,624,000</td></tr><tr><td>7 × 7 filter,3channels</td><td>3,381</td><td>3,822</td><td>4,263</td><td>4,704</td><td>5,145</td><td>5,586</td></tr><tr><td>7 × 7 filter,128 channels 7 × 7 filter,1024 channels</td><td>5,632,256</td><td>6,435,072</td><td>7,237,888</td><td>8,040,704</td><td>8,843,520</td><td>9,646,336</td></tr><tr><td></td><td></td><td></td><td></td><td>513,902,592</td><td></td><td>616,663,040</td></tr><tr><td>CNN num layers</td><td>15</td><td>16</td><td>17</td><td>19</td><td>20</td><td>24</td></tr><tr><td>5 × 5 filter,3channels</td><td>3,075</td><td>3,300</td><td>3,525</td><td>3,975</td><td>4,200</td><td>5,100</td></tr><tr><td>5 × 5 flter,128 channels</td><td>5,331,200</td><td>5,740,800</td><td>6,150,400</td><td>6,969,600</td><td>7,379,200</td><td>9,017,600</td></tr><tr><td>5 × 5 filter,1024 channels</td><td></td><td></td><td></td><td></td><td>471,910,400</td><td></td></tr><tr><td>7 × 7 filter,3channels</td><td>6,027</td><td>6.468</td><td>6,909</td><td>7,791</td><td>8.232</td><td>9,996</td></tr><tr><td>7 × 7 flter,128 channels 7 × 7 filter,1024 channels</td><td>10,449,152</td><td>11,251,968</td><td>12,054,784</td><td>13,660,416</td><td>14,463,232</td><td>17,674,496</td></tr><tr><td></td><td></td><td></td><td></td><td></td><td>924,944,384</td><td></td></tr><tr><td>CNN filter size</td><td>9×9</td><td>13×13</td><td>17× 17</td><td>25×25</td><td>29×29</td><td>57×57</td></tr><tr><td>5 layers,128 channels</td><td>4,002.048</td><td>8,349,952</td><td>14,278,912</td><td>30,880.000</td><td>41,552,128</td><td>160,526,592</td></tr></table>
# M PARAMETER COUNTS FOR NEURAL NETWORKS USED IN THIS PAPER
For convenience of cross comparing the results of different architectures with similar number of parameters, we list in Table 1 the architectures used in this paper and their associated number of parameters.
# N RESIDUAL NETWORKS
In this section, we evaluate training FCNs with residual connections. In particular, an identity skip connection is added for every two fully connected layers. In other words, the networks are built with two-layer blocks that computes $x \mapsto { \\\dot { x } } + \operatorname { R e L U } ( W _ { 2 } \mathrm { R e L U } ( W _ { 1 } x ) )$ , except that no ReLU is applied at the output layer. Adding skip connection after ReLU ensures the input gets passed directly to the output layer. Because the residual structure requires the same input-output shape for every block, we use 784 hidden dimensions.
Comparing Figure 41 with the vanilla FCNs in Figure 2, the identity skip connection strongly biased the FCNs towards learning the identity map. On the other hand, we can still observe that the prediction noises become stronger with larger number of hidden layers, suggesting that learning the identity function is non-trivial even with the explicit identity skip connections built into the architectures.
# O EXPERIMENTS ON CIFAR-10 IMAGES
In this section, we show experiments on some colored images from the CIFAR-10 dataset $( 3 2 \times 3 2$ RGB images). Figure 42 and Figure 43 show the results from two different randomly sampled training images, respectively. The network architectures used here are nearly identical to the ones used to train on MNIST digits in the main text of the paper: the CNNs are with 128 channels and $5 \times 5$ filters. The FCNs are slightly modified to have larger hidden dimensions $3 0 7 2 = 3 2 { \times } 3 2 { \times } 3$ , to avoid explicitly enforcing bottlenecks in the hidden representations. The training loss and optimization algorithms are the same as in the MNIST case.
 Figure 41: Visualization of predictions from multi-layer ReLU networks with residual connections. The first row shows the input images for evaluation, including the single training image “7” at the beginning of the row. The remaining rows show the predictions from trained multi-layer ReLU FCNs with residual connections, with the numbers on the left indicating the number of hidden layers.
The main observations are consistent the results on the MNIST digits. In particular, shallow FCNs produce random noisy predictions on unseen evaluation inputs, but deep FCNs bias towards memorization and hallucinate the training image on all test outputs. For CNNs, shallow networks are capable of learning the identity function, but deep networks learn the constant function instead.
 Figure 42: Visualization of predictions from various networks trained on a single CIFAR-10 image (dog). The first row shows the input images, where the first one is the training image and the rest are images for evaluation. The evaluation images consist of unseen images from the CIFAR-10 test set and artificially generated grayscale patterns. The grayscale patterns are duplicated into three channels before feeding into the networks. The remaining rows show the predictions from trained FCNs and CNNs. For FCNs, the numbers indicate the number of hidden layers. For example, $H 3$ means a 3-hidden-layer FCN. For CNNs, the numbers indicate the number of (convolutional) layers. For example, C16 means a 16-layer CNN.
 Figure 43: Visualization of predictions from various networks trained on a single CIFAR-10 image (air plane). The first row shows the input images, where the first one is the training image and the rest are images for evaluation. The evaluation images consist of unseen images from the CIFAR-10 test set and artificially generated grayscale patterns. The grayscale patterns are duplicated into three channels before feeding into the networks. The remaining rows show the predictions from trained FCNs and CNNs. For FCNs, the numbers indicate the number of hidden layers. For example, $H 3$ means a 3-hidden-layer FCN. For CNNs, the numbers indicate the number of (convolutional) layers. For example, C16 means a 16-layer CNN.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375# RECURRENT NEURAL NETWORKS FOR MULTIVARIATE TIME SERIES WITH MISSING VALUES
Zhengping Che, Sanjay Purushotham Department of Computer Science University of Southern California Los Angeles, CA 90089, USA {zche,spurusho}@usc.edu
# Yan Liu
Kyunghyun Cho, David Sontag Department of Computer Science New York University New York, NY 10012, USA kyunghyun.cho@nyu.edu,dsontag@cs.nyu.edu
Department of Computer Science University of Southern California Los Angeles, CA 90089, USA yanliu.cs@usc.edu
# ABSTRACT
Multivariate time series data in practical applications, such as health care, geoscience, and biology, are characterized by a variety of missing values. In time series prediction and other related tasks, it has been noted that missing values and their missing patterns are often correlated with the target labels, a.k.a., informative missingness. There is very limited work on exploiting the missing patterns for effective imputation and improving prediction performance. In this paper, we develop novel deep learning models, namely GRU-D, as one of the early attempts. GRU-D is based on Gated Recurrent Unit (GRU), a state-of-the-art recurrent neural network. It takes two representations of missing patterns, i.e., masking and time interval, and effectively incorporates them into a deep model architecture so that it not only captures the long-term temporal dependencies in time series, but also utilizes the missing patterns to achieve better prediction results. Experiments of time series classification tasks on real-world clinical datasets (MIMIC-III, PhysioNet) and synthetic datasets demonstrate that our models achieve state-of-the-art performance and provides useful insights for better understanding and utilization of missing values in time series analysis.
# 1 INTRODUCTION
Multivariate time series data are ubiquitous in many practical applications ranging from health care, geoscience, astronomy, to biology and others. They often inevitably carry missing observations due to various reasons, such as medical events, saving costs, anomalies, inconvenience and so on. It has been noted that these missing values are usually informative missingness (Rubin, 1976), i.e., the missing values and patterns provide rich information about target labels in supervised learning tasks (e.g, time series classification). To illustrate this idea, we show some examples from MIMIC-III, a real world health care dataset in Figure 1. We plot the Pearson correlation coefficient between variable missing rates, which indicates how often the variable is missing in the time series, and the labels of our interests such as mortality and ICD-9 diagnoses. We observe that the missing rate is correlated with the labels, and the missing rates with low rate values are usually highly (either positive or negative) correlated with the labels. These findings demonstrate the usefulness of missingness patterns in solving a prediction task.
In the past decades, various approaches have been developed to address missing values in time series (Schafer & Graham, 2002). A simple solution is to omit the missing data and to perform analysis only on the observed data. A variety of methods have been developed to fill in the missing values, such as smoothing or interpolation (Kreindler & Lumsden, 2012), spectral analysis (Mondal & Percival, 2010), kernel methods (Rehfeld et al., 2011), multiple imputation (White et al., 2011), and EM algorithm (Garc´ıa-Laencina et al., 2010). Schafer & Graham (2002) and references therein provide excellent reviews on related solutions. However, these solutions often result in a twostep process where imputations are disparate from prediction models and missing patterns are not effectively explored, thus leading to suboptimal analyses and predictions (Wells et al., 2013).
 Figure 1: Demonstrations of informative missingness on MIMIC-III dataset. Left figure shows variable missing rate $\mathbf { \dot { x } }$ -axis, missing rate; y-axis, input variable). Middle/right figures respectively shows the correlations between missing rate and mortality/ICD-9 diagnosis categories $\mathbf { \bar { X } }$ -axis, target label; y-axis, input variable; color, correlation value). Please refer to Appendix A.1 for more details.
In the meantime, Recurrent Neural Networks (RNNs), such as Long Short-Term Memory (LSTM) (Hochreiter & Schmidhuber, 1997) and Gated Recurrent Unit (GRU) (Cho et al., 2014), have shown to achieve the state-of-the-art results in many applications with time series or sequential data, including machine translation (Bahdanau et al., 2014; Sutskever et al., 2014) and speech recognition (Hinton et al., 2012). RNNs enjoy several nice properties such as strong prediction performance as well as the ability to capture long-term temporal dependencies and variable-length observations. RNNs for missing data has been studied in earlier works (Bengio & Gingras, 1996; Tresp & Briegel, 1998; Parveen & Green, 2001) and applied for speech recognition and blood-glucose prediction. Recent works (Lipton et al., 2016; Choi et al., 2015) tried to handle missingness in RNNs by concatenating missing entries or timestamps with the input or performing simple imputations. However, there have not been works which model missing patterns into a systematically modified RNN structure for time series classification problems. Exploiting the power of customized RNN models along with the informativeness of missing patterns is a new promising venue to effectively model multivariate time series and is the main motivation behind our work.
In this paper, we develop a novel deep learning model based on GRU, namely GRU-D, to effectively exploit two representations of informative missingness patterns, i.e., masking and time interval. Masking informs the model which inputs are observed (or missing), while time interval encapsulates the input observation patterns. Our model captures the observations and their dependencies by applying masking and time interval (using a decay term) to the inputs and network states of GRU, and jointly train all model components using back-propagation. Thus, our model not only captures the long-term temporal dependencies of time series observations but also utilizes the missing patterns to improve the prediction results. Empirical experiments on real-world clinical datasets as well as synthetic datasets demonstrate that our proposed model outperforms strong deep learning models built on GRU with imputation as well as other strong baselines. These experiments show that our proposed method is suitable for many time series classification problems with missing data, and in particular is readily applicable to the predictive tasks in emerging health care applications. Moreover, our method provides useful insights into more general research challenges of time series analysis with missing data beyond classification tasks, including 1) a general deep learning framework to handle time series with missing data, 2) effective solutions to characterize the missing patterns of not missing-completely-at-random time series data such as modeling masking and time interval, and 3) an insightful approach to study the impact of variable missingness on the prediction labels by decay analysis.
# 2 RNN MODELS FOR TIME SERIES WITH MISSING VARIABLES
We denote a multivariate time series with $D$ variables of length $T$ as ${ \pmb X } = \left( \pmb { x } _ { 1 } , \pmb { x } _ { 2 } , \ldots , \pmb { x } _ { T } \right) ^ { \mathrm { T } } \in$ $\mathbb { R } ^ { T \times D }$ , where for each $t \in \{ 1 , 2 , \ldots , T \}$ , $\pmb { x } _ { t } \in \mathbb { R } ^ { D }$ represents the tth observations (a.k.a., measurements) of all variables and $\boldsymbol { x } _ { t } ^ { d }$ denotes the measurement of $d$ th variable of $\mathbf { \Delta } _ { \mathbf { \mathcal { X } } _ { t } }$ . Let $s _ { t } \in \mathbb { R }$ denote the time-stamp when the tth observation is obtained and we assume that the first observation is made at
??: Input time series (2 variables); ??: Timestamps for $\pmb { X }$ ; ??: Masking for ??; ??: Time interval for $\pmb { X }$ .
$$\begin{array} { l l l l l l } { { M = \left[ \begin{array} { c c c c c c c } { { 1 } } & { { 1 } } & { { 0 } } & { { 1 } } & { { 0 } } & { { 1 } } & { { 1 } } \\ { { 0 } } & { { 1 } } & { { 1 } } & { { 0 } } & { { 0 } } & { { 0 } } & { { 1 } } \end{array} \right] } } \\ { { \Delta = \left[ \begin{array} { c c c c c c c } { { 0 . 0 } } & { { 0 . 1 } } & { { 0 . 5 } } & { { 1 . 5 } } & { { 0 . 6 } } & { { 0 . 9 } } & { { 0 . 6 } } \\ { { 0 . 0 } } & { { 0 . 1 } } & { { 0 . 5 } } & { { 1 . 0 } } & { { 1 . 6 } } & { { 1 . 9 } } & { { 2 . 5 } } \end{array} \right] } } \end{array}$$
Figure 2: An example of measurement vectors $\mathbf { \Delta } _ { \mathbf { \mathcal { X } } _ { t } }$ , time stamps $s _ { t }$ , masking ${ \mathbf { } } m _ { t }$ , and time interval $\delta _ { t }$ .
time-stamp 0 (i.e., $s _ { 1 } = 0$ ). A time series $\boldsymbol { X }$ could have missing values. We introduce a masking vector $m _ { t } \in \left\{ 0 , 1 \right\} ^ { D }$ to denote which variables are missing at time step $t$ . The masking vector for $\mathbf { \Delta } _ { \mathbf { \mathcal { X } } _ { t } }$ is given by
$$m _ { t } ^ { d } = { \left\{ \begin{array} { l l } { 1 , \ } & { { \mathrm { i f } } \ x _ { t } ^ { d } \ { \mathrm { i s ~ o b s e r v e d } } } \\ { 0 , \ } & { { \mathrm { o t h e r w i s e } } } \end{array} \right. }$$
For each variable $d$ , we also maintain the time interval $\delta _ { t } ^ { d } \in \mathbb { R }$ since its last observation as
$$\begin{array} { r } { \delta _ { t } ^ { d } = \left\{ \begin{array} { l l } { s _ { t } - s _ { t - 1 } + \delta _ { t - 1 } ^ { d } , } & { t > 1 , m _ { t - 1 } ^ { d } = 0 } \\ { s _ { t } - s _ { t - 1 } , } & { t > 1 , m _ { t - 1 } ^ { d } = 1 } \\ { 0 , } & { t = 1 } \end{array} \right. } \end{array}$$
An example of these notations is illustrated in Figure 2. In this paper, we are interested in the time series classification problem, where we predict the labels $l _ { n }$ given the time series data $\mathcal { D }$ , where $\mathcal { D } = \{ ( X _ { n } , s _ { n } , M _ { n } , \Delta _ { n } ) \} _ { n = 1 } ^ { N }$ , and $\bar { \mathbf { X } } _ { n } = \Big [ \pmb { x } _ { 1 } ^ { ( n ) } , \dotsc , \pmb { x } _ { T _ { n } } ^ { ( n ) } \Big ] , \bar { \pmb { s } } _ { n } = \Big [ \pmb { s } _ { 1 } ^ { ( n ) } , \dotsc , \pmb { s } _ { T _ { n } } ^ { ( n ) } \Big ] , \pmb { M } _ { n } =$ $\left[ m _ { 1 } ^ { \left( n \right) } , \ldots , m _ { T _ { n } } ^ { \left( n \right) } \right]$ , $\Delta _ { n } = \left[ \delta _ { 1 } ^ { ( n ) } , \dots , \delta _ { T _ { n } } ^ { ( n ) } \right]$ , and $l _ { n } \in \{ 1 , \ldots , L \}$ .
# 2.1 GRU-RNN FOR TIME SERIES CLASSIFICATION
We investigate the use of recurrent neural networks (RNN) for time-series classification, as their recursive formulation allow them to handle variable-length sequences naturally. Moreover, RNN shares the same parameters across all time steps which greatly reduces the total number of parameters we need to learn. Among different variants of the RNN, we specifically consider an RNN with gated recurrent units (Cho et al., 2014; Chung et al., 2014), but similar discussion and convolutions are also valid for other RNN models such as LSTM (Hochreiter & Schmidhuber, 1997).
The structure of GRU is shown in Figure 3(a). For each $j$ th hidden unit, GRU has a reset gate $r _ { t } ^ { j }$ and an update gate $ { \boldsymbol { z } } _ { t } ^ { j }$ to control the hidden state $h _ { t } ^ { j }$ at each time $t$ . The update functions are shown as follows:
$$\begin{array} { l l } { r _ { t } = \sigma \left( W _ { r } { \boldsymbol x } _ { t } + U _ { r } h _ { t - 1 } + b _ { r } \right) } & { z _ { t } = \sigma \left( W _ { z } { \boldsymbol x } _ { t } + U _ { z } h _ { t - 1 } + b _ { z } \right) } \\ { \tilde { h } _ { t } = \operatorname { t a n h } \left( W { \boldsymbol x } _ { t } + U ( { \boldsymbol r } _ { t } \odot h _ { t - 1 } ) + b \right) } & { h _ { t } = \left( 1 - z _ { t } \right) \odot h _ { t - 1 } + z _ { t } \odot \tilde { h } _ { t } } \end{array}$$
where matrices $W _ { z } , W _ { r } , W , U _ { z } , U _ { r } , U$ and vectors $\textstyle { b _ { z } , b _ { r } , b }$ are model parameters. We use $\sigma$ for element-wise sigmoid function, and $\odot$ for element-wise multiplication. This formulation assumes that all the variables are observed. A sigmoid or soft-max layer is then applied on the output of the GRU layer at the last time step for classification task.
Existing work on handling missing values lead to three possible solutions with no modification on GRU network structure. One straightforward approach is simply replacing each missing observation with the mean of the variable across the training examples. In the context of GRU, we have
 Figure 3: Graphical illustrations of the original GRU (left) and the proposed GRU-D (right) models.
$$x _ { t } ^ { d } \gets m _ { t } ^ { d } x _ { t } ^ { d } + ( 1 - m _ { t } ^ { d } ) \tilde { x } ^ { d }$$
where $\begin{array} { r } { \tilde { x } ^ { d } = \sum _ { n = 1 } ^ { N } \sum _ { t = 1 } ^ { T _ { n } } m _ { t , n } ^ { d } x _ { t , n } ^ { d } \Big / \sum _ { n = 1 } ^ { N } \sum _ { t = 1 } ^ { T _ { n } } m _ { t , n } ^ { d } . } \end{array}$ We refer to this approach as GRU-mean.
A second approach is exploiting the temporal structure in time series. For example, we may assume any missing value is same as its last measurement and use forward imputation (GRU-forward), i.e.,
$$x _ { t } ^ { d } m _ { t } ^ { d } x _ { t } ^ { d } + ( 1 - m _ { t } ^ { d } ) x _ { t ^ { \prime } } ^ { d }$$
where $t ^ { \prime } < t$ is the last time the $d$ -th variable was observed.
Instead of explicitly imputing missing values, the third approach simply indicates which variables are missing and how long they have been missing as a part of input, by concatenating the measurement, masking and time interval vectors as
$$\pmb { x } _ { t } ^ { ( n ) } \gets \Big [ \pmb { x } _ { t } ^ { ( n ) } ; \pmb { m } _ { t } ^ { ( n ) } ; \pmb { \delta } _ { t } ^ { ( n ) } \Big ]$$
$\mathbf { \pmb { x } } _ { t } ^ { ( n ) }$ can be either from Equation (1) or (2). We later refer to this approach as GRU-simple.
Several recent works (Lipton et al., 2016; Choi et al., 2015; Pham et al., 2016) use RNNs on EHR data to model diseases and to predict patient diagnosis from health care time series data with irregular time stamps or missing values, but none of them have explicitly attempted to capture and utilize the missing patterns into their RNNs via systematically modified network architectures. Choi et al. (2015) feeds medical codes along with its time stamps into GRU model to predict the next medical event. This feeding time stamps idea is equivalent to the baseline GRU-simple without feeding the masking, which we denote as GRU-simple (interval only). Pham et al. (2016) takes time stamps into LSTM model, and modify its forgetting gate by either time decay and parametric time both from time stamps. However, their non-trainable decay is not that flexible, and the parametric time also does not change RNN model structure and is similar to GRU-simple (interval only). In addition, neither of them consider missing values in time series medical records, and the time stamp input used in these two models is vector for one patient, but not matrix for each input variable of one patient as ours. Lipton et al. (2016) achieves their best performance on diagnosis prediction by feeding masking with zero-filled missing values. Their model is equivalent to GRU-simple without feeding the time interval, and no model structure modification is made for further capturing and utilizing missingness. We denote their best model as GRU-simple (masking only). Conclusively, our GRU-simple baseline can be considered as a generalization from all related RNN models mentioned above and as shown in the experiments these GRU-simple variations have quite close performance.
These approaches solve the missing value issue to a certain extent, However, it is known that imputing the missing value with mean or forward imputation cannot distinguish whether missing values are imputed or truly observed. Simply concatenating masking and time interval vectors fails to exploit the temporal structure of missing values. Thus none of them fully utilize missingness in data to achieve desirable performance.
# 2.2 GRU-D: MODEL WITH TRAINABLE DECAYS
To fundamentally address the issue of missing values in time series, we notice two important properties of the missing values in time series, especially in health care domains: First, the value of the missing variable tend to be close to some default value if its last observation happens a long time ago. This property usually exists in health care data for human body as homeostasis mechanisms and is considered to be critical for disease diagnosis and treatment (Vodovotz et al., 2013). Second, the influence of the input variables will fade away over time if the variable has been missing for a while. For example, one medical feature in electronic health records (EHRs) is only significant in a certain temporal context (Zhou & Hripcsak, 2007). Therefore we propose a GRU-based model called GRU-D, in which a decay mechanism is designed for the input variables and the hidden states to capture the aforementioned properties. We introduce decay rates in the model to control the decay mechanism by considering the following important factors. First, each input variable in health care time series has its own medical meaning and importance. The decay rates should be flexible to differ from variable to variable based on the underlying properties associated with the variables.
Second, as we see lots of missing patterns are informative in prediction tasks, the decay rate should be indicative of such patterns and benefits the prediction tasks. Furthermore, since the missing patterns are unknown and possibly complex, we aim at learning decay rates from the training data rather than being fixed a priori. That is, we model a vector of decay rates $\gamma$ as
$$\gamma _ { t } = \exp \left\{ - \operatorname* { m a x } \left( \mathbf { 0 } , W _ { \gamma } \delta _ { t } + b _ { \gamma } \right) \right\}$$
where $W _ { \gamma }$ and $b _ { \gamma }$ are model parameters that we train jointly with all the other parameters of the GRU. We chose the exponentiated negative rectifier in order to keep each decay rate monotonically decreasing in a reasonable range between 0 and 1. Note that other formulations such as a sigmoid function can be used instead, as long as the resulting decay is monotonic and is in the same range.
Our proposed GRU-D model incorporates two different trainable decays to utilize the missingness directly with the input feature values and implicitly in the RNN states. First, for a missing variable, we use an input decay $\gamma _ { x }$ to decay it over time toward the empirical mean (which we take as a default configuration), instead of using the last observation as it is. Under this assumption, the trainable decay scheme can be readily applied to the measurement vector by
$$x _ { t } ^ { d } \gets m _ { t } ^ { d } x _ { t } ^ { d } + ( 1 - m _ { t } ^ { d } ) \gamma _ { x t } { } ^ { d } x _ { t ^ { \prime } } ^ { d } + ( 1 - m _ { t } ^ { d } ) ( 1 - \gamma _ { x t } { } ^ { d } ) \tilde { x } ^ { d }$$
where $x _ { t ^ { \prime } } ^ { d }$ is the last observation of the $d$ -th variable $\left( t ^ { \prime } < t \right)$ and $\tilde { x } ^ { d }$ is the empirical mean of the dth variable. When decaying the input variable directly, we constrain $W _ { \gamma _ { x } }$ to be diagonal, which effectively makes the decay rate of each variable independent from the others. Sometimes the input decay may not fully capture the missing patterns since not all missingness information can be represented in decayed input values. In order to capture richer knowledge from missingness, we also have a hidden state decay $\gamma _ { h }$ in GRU-D. Intuitively, this has an effect of decaying the extracted features (GRU hidden states) rather than raw input variables directly. This is implemented by decaying the previous hidden state $\boldsymbol { h } _ { t - 1 }$ before computing the new hidden state $\boldsymbol { h } _ { t }$ as
$$\begin{array} { r } { \pmb { h } _ { t - 1 } \pmb { \gamma _ { h _ { t } } \odot h _ { t - 1 } } , } \end{array}$$
in which case we do not constrain $W _ { \gamma _ { h } }$ to be diagonal. In addition, we feed the masking vectors $( m _ { t } )$ directly into the model. The update functions of GRU-D are
$$\begin{array} { r l r l } & { z _ { t } = \sigma \left( W _ { z } x _ { t } + U _ { z } h _ { t - 1 } + V _ { z } m _ { t } + b _ { z } \right) } & { r _ { t } = \sigma \left( W _ { r } x _ { t } + U _ { r } h _ { t - 1 } + V _ { r } m _ { t } + b _ { r } \right) } \\ & { \tilde { h } _ { t } = \operatorname { t a n h } \left( W x _ { t } + U ( r _ { t } \odot h _ { t - 1 } ) + V m _ { t } + b \right) } & { h _ { t } = \left( \mathbf { 1 } - z _ { t } \right) \odot h _ { t - 1 } + z _ { t } \odot \tilde { h } _ { t } } \end{array}$$
where $\mathbf { \Delta } _ { \mathbf { \mathcal { X } } _ { t } }$ and $h _ { t - 1 }$ are respectively updated by Equation (5) and (6), and $V _ { z } , V _ { r } , V$ are new parameters for masking vector ${ \mathbf { } } m _ { t }$ .
To validate GRU-D model and demonstrate how it utilizes informative missing patterns, in Figure 4, we show the input decay $( \gamma _ { x } )$ plots and hidden decay $( \gamma _ { h } )$ histograms for all the variables for predicting mortality on PhysioNet dataset. For input decay, we notice that the decay rate is almost constant for the majority of variables. However, a few variables have large decay which means that the model relies less on the previous observations for prediction. For example, the changes in the variable values of weight, arterial $\mathrm { p H }$ , temperature, and respiration rate are known to impact the ICU patients health condition. The hidden decay histograms show the distribution of decay parameters related to each variable. We noticed that the parameters related to variables with smaller missing rate are more spread out. This indicates that the missingness of those variables has more impact on decaying or keeping the hidden states of the models.
Notice that the decay term can be generalized to LSTM straightforwardly. In practical applications, missing values in time series may contain useful information in a variety of ways. A better model should have the flexibility to capture different missing patterns. In order to demonstrate the capacity of our GRU-D model, we discuss some model variations in Appendix A.2.
# 3 EXPERIMENTS
# 3.1 DATASET DESCRIPTIONS AND EXPERIMENTAL DESIGN
We demonstrate the performance of our proposed models on one synthetic and two real-world health-care datasets1 and compare it to several strong machine learning and deep learning approaches (a) x-axis, time interval $\delta _ { t } ^ { d }$ between 0 and 24 hours; y-axis, value of decay rate $\gamma _ { \pmb { x } _ { t } } ^ { d }$ between 0 and 1.

 (b) $\mathbf { X }$ -axis, value of decay parameter $W _ { \gamma _ { h } }$ ; y-axis, count. Figure 4: Plots of input decay $\gamma _ { x t }$ (top) and histrograms of hidden state decay $\gamma _ { h t }$ (bottom) of all 33 variables in GRU-D model for predicting mortality on PhysioNet dataset. Variables in green are lab measurements; variables in red are vital signs; mr refers to missing rate.
in classification tasks. We evaluate our models for different settings such as early prediction and different training sizes and investigate the impact of informative missingness.
Gesture phase segmentation dataset (Gesture) This UCI dataset (Madeo et al., 2013) has multivariate time series features, regularly sampled and with no missing values, for 5 different gesticulations. We extracted 378 time series and generate 4 synthetic datasets for the purpose of understanding model behaviors with different missing patterns. We treat it as multi-class classification task.
PhysioNet Challenge 2012 dataset (PhysioNet) This dataset, from PhysioNet Challenge 2012 (Silva et al., 2012), is a publicly available collection of multivariate clinical time series from 8000 intensive care unit (ICU) records. Each record is a multivariate time series of roughly 48 hours and contains 33 variables such as Albumin, heart-rate, glucose etc. We used Training Set A subset in our experiments since outcomes (such as in-hospital mortality labels) are publicly available only for this subset. We conduct the following two prediction tasks on this dataset: 1) Mortality task: Predict whether the patient dies in the hospital. There are 554 patients with positive mortality label. We treat this as a binary classification problem. and 2) All 4 tasks: Predict 4 tasks: in-hospital mortality, length-of-stay less than 3 days, whether the patient had a cardiac condition, and whether the patient was recovering from surgery. We treat this as a multi-task classification problem.
MIMIC-III dataset (MIMIC-III) This public dataset (Johnson et al., 2016) has deidentified clinical care data collected at Beth Israel Deaconess Medical Center from 2001 to 2012. It contains over 58,000 hospital admission records. We extracted 99 time series features from 19714 admission records for 4 modalities including input-events (fluids into patient, e.g., insulin), output-events (fluids out of the patient, e.g., urine), lab-events (lab test results, e.g., pH values) and prescription-events (drugs prescribed by doctors, e.g., aspirin). These modalities are known to be extremely useful for monitoring ICU patients. We only use the first 48 hours data after admission from each time series. We perform following two predictive tasks: 1) Mortality task: Predict whether the patient dies in the hospital after 48 hours. There are 1716 patients with positive mortality label and we perform binary classification. and 2) ICD-9 Code tasks: Predict 20 ICD-9 diagnosis categories (e.g., respiratory system diagnosis) for each admission. We treat this as a multi-task classification problem.
# 3.2 METHODS AND IMPLEMENTATION DETAILS
We categorize all evaluated prediction models into three following groups:
• Non-RNN Baselines (Non-RNN): We evaluate logistic regression (LR), support vector machines (SVM) and Random Forest (RF) which are widely used in health care applications. • RNN Baselines (RNN): We take GRU-mean, GRU-forward, GRU-simple, and LSTM-mean (LSTM model with mean-imputation on the missing measurements) as RNN baselines. • Proposed Methods (Proposed): This is our proposed GRU-D model from Section 2.2.
 Figure 5: Classification performance on Gesture synthetic datasets. x-axis: average Pearson correlation of variable missing rates and target label in that dataset; y-axis: AUC score.
Table 1: Model performances measured by average AUC score $( m e a n \pm s t d )$ for multi-task predictions on real datasets. Results on each class are shown in Appendix A.3.3 for reference.
<table><tr><td>Models</td><td>MIMIC-III ICD-9 20 tasks</td><td>PhysioNet All 4 tasks</td></tr><tr><td>GRU-mean</td><td>0.7070 ± 0.001</td><td>0.8099 ± 0.011</td></tr><tr><td>GRU-forward</td><td>0.7077±0.001</td><td>0.8091±0.008</td></tr><tr><td>GRU-simple</td><td>0.7105 ± 0.001</td><td>0.8249 ± 0.010</td></tr><tr><td>GRU-D</td><td>0.7123 ± 0.003</td><td>0.8370± 0.012</td></tr></table>
The non-RNN baselines cannot handle missing data directly. We carefully design experiments for nonRNN models to capture the informative missingness as much as possible to have fair comparison with the RNN methods. Since non-RNN models only work with fixed length inputs, we regularly sample the time-series data to get a fixed length input and perform imputation to fill in the missing values. Similar to RNN baselines, we can concatenate the masking vector along with the measurements and feed it to non-RNN models. For PhysioNet dataset, we sample the time series on an hourly basis and propagate measurements forward (or backward) in time to fill gaps. For MIMIC-III dataset, we consider two hourly samples (in the first 48 hours) and do forward (or backward) imputation. Our preliminary experiments showed 2-hourly samples obtains better performance than one-hourly samples for MIMIC-III. We report results for both concatenation of input and masking vectors (i.e., SVM/LR/RF-simple) and only input vector without masking (i.e., SVM/LR/RF-forward). We use the scikit-learn (Pedregosa et al., 2011) for the non-RNN model implementation and tune the parameters by cross-validation. We choose RBF kernel for SVM since it performs better than other kernels.
For RNN models, we use a one layer RNN to model the sequence, and then apply a soft-max regressor on top of the last hidden state $h _ { T }$ to do classification. We use 100 and 64 hidden units in GRU-mean for MIMIC-III and PhysioNet datasets, respectively. All the other RNN models were constructed to have a comparable number of parameters.2 For GRU-simple, we use mean imputation for input as shown in Equation (1). Batch normalization (Ioffe & Szegedy, 2015) and dropout (Srivastava et al., 2014) of rate 0.5 are applied to the top regressor layer. We train all the RNN models with the Adam optimization method (Kingma & Ba, 2014) and use early stopping to find the best weights on the validation dataset. All the input variables are normalized to be 0 mean and 1 standard deviation. We report the results from 5-fold cross validation in terms of area under the ROC curve (AUC score). We provide more detailed comparisons of RNN baselines and variations in Appendix A.3.4 and evaluations on multilayer RNN models in Appendix A.3.5.
# 3.3 QUANTITATIVE RESULTS
Exploiting informative missingness on synthetic dataset As illustrated in Figure 1, missing patterns can be useful in solving prediction tasks. A robust model should exploit informative missingness properly and avoid inducing nonexistent relations between missingness and predictions. To evaluate the impact of modeling missingness we conduct experiments on the synthetic Gesture datasets. We process the data in 4 different settings with the same missing rate but different correlations between missing rate and the label. A higher correlation implies more informative missingness. Figure 5 shows the AUC score comparison of three GRU baseline models (GRU-mean, GRU-forward, GRU-simple) and the proposed GRU-D. Since GRU-mean and GRU-forward do not utilize any missingness (i.e., masking or time interval), they perform similarly across all 4 settings. GRU-simple and GRU-D benefit from utilizing the missingness, especially when the correlation is high. Our GRU-D achieves the best performance in all settings, while GRU-simple fails when the correlation is low. The results on synthetic datasets demonstrates that our proposed model can model and distinguish useful missing patterns in data properly compared with baselines.
Prediction task evaluation on real datasets We evaluate all methods in Section 3.2 on MIMIC-III and PhysioNet datasets. We noticed that dropout in the recurrent layer helps a lot for all RNN models on both of the datasets, probably because they contain more input variables and training samples than synthetic dataset. Similar to Gal (2015), we apply dropout rate of 0.3 with same dropout samples at each time step on weights $W , U , V$ . Table 2 shows the prediction performance of all the models on mortality task. All models except for random forest improve their performance when they feed missingness indicators along with inputs. The proposed GRU-D achieves the best AUC score on both datasets. We also conduct multi-task classification experiments for all 4 tasks on PhysioNet and 20 ICD-9 code tasks on MIMIC-III using all the GRU models. As shown in Table 1, GRU-D performs best in terms of average AUC score across all tasks and in most of the single tasks.
 Figure 6: Performance for early predicting mortality on MIMIC-III dataset. $\mathbf { X }$ -axis, # of hours after admission; y-axis, AUC score; Dash line, RF-simple results for 48 hours.
 Figure 7: Performance for predicting mortality on subsampled MIMIC-III dataset. x-axis, subsampled dataset size; y-axis, AUC score.
Table 2: Model performances measured by AUC score $( m e a n \pm s t d )$ for mortality prediction.
<table><tr><td colspan="2">Models</td><td>MIMIC-III</td><td>PhysioNet</td></tr><tr><td rowspan="6">Non-RNN</td><td>LR-forward</td><td>0.7589 ± 0.015</td><td>0.7423± 0.011</td></tr><tr><td>SVM-forward</td><td>0.7908±0.006</td><td>0.8131 ± 0.018</td></tr><tr><td>RF-forward</td><td>0.8293 ±0.004</td><td>0.8183 ± 0.015</td></tr><tr><td>LR-simple</td><td>0.7715 ± 0.015</td><td>0.7625± 0.004</td></tr><tr><td> SVM-simple</td><td>0.8146 ± 0.008</td><td>0.8277 ± 0.012</td></tr><tr><td>RF-simple</td><td>0.8294±0.007</td><td>0.8157 ± 0.013</td></tr><tr><td rowspan="4">RNN</td><td>LSTM-mean</td><td>0.8142 ± 0.014</td><td>0.8025 ± 0.013</td></tr><tr><td>GRU-mean</td><td>0.8192 ± 0.013</td><td>0.8195 ± 0.004</td></tr><tr><td>GRU-forward</td><td>0.8252 ±0.011</td><td>0.8162 ± 0.014</td></tr><tr><td>GRU-simple</td><td>0.8380±0.008</td><td>0.8155 ± 0.004</td></tr><tr><td>Proposed</td><td>GRU-D</td><td>0.8527 ± 0.003</td><td>0.8424 ± 0.012</td></tr></table>
# 3.4 DISCUSSIONS
Online prediction in early stage Although our model is trained on the first 48 hours data and makes prediction at the last time step, it can be used directly to make predictions before it sees all the time series and can make predictions on the fly. This is very useful in applications such as health care, where early decision making is beneficial and critical for patient care. Figure 6 shows the online prediction results for MIMIC-III mortality task. As we can see, AUC is around 0.7 at first 12 hours for all the GRU models and it keeps increasing when longer time series is fed into these models. GRU-D and GRU-simple, which explicitly handle missingness, perform consistently better than the other two methods. In addition, GRU-D outperforms GRU-simple when making predictions given time series of more than 24 hours, and has at least $2 . 5 \%$ higher AUC score after 30 hours. This indicates that GRU-D is able to capture and utilize long-range temporal missing patterns. Furthermore, GRU-D achieves similar prediction performance (i.e., same AUC) as best non-RNN baseline model with less time series data. As shown in the figure, GRU-D has same AUC performance at 36 hours as the best non-RNN baseline model (RF-simple) at 48 hours. This 12 hour improvement of GRU-D over non-RNN baseline is highly significant in hospital settings such as ICU where time-saving critical decisions demands accurate early predictions.
Model Scalability with growing data size In many practical applications, model scalability with large dataset size is very important. To evaluate the model performance with different training dataset size, we subsample three smaller datasets of 2000 and 10000 admissions from the entire MIMIC-III dataset while keeping the same mortality rate. We compare our proposed models with all GRU baselines and two most competitive non-RNN baselines (SVM-simple, RF-simple) and shows the prediction results in Figure 7. We observe that all models can achieve improved performance given more training samples. However, the improvements of non-RNN baselines are quite limited compared to GRU models, and our GRU-D model achieves the best results on the two larger datasets. These results indicate the performance gap between GRU-D and non-RNN baselines will continue to grow as more data become available.
# 4 SUMMARY
In this paper, we proposed novel GRU-based model to effectively handle missing values in multivariate time series data. Our model captures the informative missingness by incorporating masking and time interval directly inside the GRU architecture. Empirical experiments on both synthetic and real-world health care datasets showed promising results and provided insightful findings. In our future work, we will explore deep learning approaches to characterize missing-not-at-random data and we will conduct theoretical analysis to understand the behaviors of existing solutions for missing values.
# REFERENCES
Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. arXiv preprint arXiv:1409.0473, 2014.
Yoshua Bengio and Francois Gingras. Recurrent neural networks for missing or asynchronous data. Advances in neural information processing systems, pp. 395–401, 1996.
Zhengping Che, David Kale, Wenzhe Li, Mohammad Taha Bahadori, and Yan Liu. Deep computational phenotyping. In SIGKDD, 2015.
Kyunghyun Cho, Bart Van Merrienboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger ¨ Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. arXiv preprint arXiv:1406.1078, 2014.
Edward Choi, Mohammad Taha Bahadori, and Jimeng Sun. Doctor ai: Predicting clinical events via recurrent neural networks. arXiv preprint arXiv:1511.05942, 2015.
Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. arXiv preprint arXiv:1412.3555, 2014.
Yarin Gal. A theoretically grounded application of dropout in recurrent neural networks. arXiv preprint arXiv:1512.05287, 2015.
Pedro J Garc´ıa-Laencina, Jose-Luis Sancho-G ´ omez, and An ´ ´ıbal R Figueiras-Vidal. Pattern classification with missing data: a review. Neural Computing and Applications, 19(2), 2010.
Geoffrey Hinton, Li Deng, Dong Yu, George E Dahl, Abdel-rahman Mohamed, Navdeep Jaitly, Andrew Senior, Vincent Vanhoucke, Patrick Nguyen, Tara N Sainath, et al. Deep neural networks for acoustic modeling in speech recognition: The shared views of four research groups. Signal Processing Magazine, IEEE, 29(6):82–97, 2012.
Sepp Hochreiter and Jurgen Schmidhuber. Long short-term memory. ¨ Neural computation, 9(8): 1735–1780, 1997.
Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. arXiv preprint arXiv:1502.03167, 2015.
AEW Johnson, TJ Pollard, L Shen, L Lehman, M Feng, M Ghassemi, B Moody, P Szolovits, LA Celi, and RG Mark. Mimic-iii, a freely accessible critical care database. Scientific Data, 2016.
Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014.
Diederik P Kingma and Max Welling. Auto-encoding variational bayes. In ICLR, 2013.
David M Kreindler and Charles J Lumsden. The effects of the irregular sample and missing data in time series analysis. Nonlinear Dynamical Systems Analysis for the Behavioral Sciences Using Real Data, 2012.
Zachary C Lipton, David C Kale, and Randall Wetzel. Directly modeling missing data in sequences with rnns: Improved classification of clinical time series. arXiv preprint arXiv:1606.04130, 2016.
Renata CB Madeo, Clodoaldo AM Lima, and Sarajane M Peres. Gesture unit segmentation using support vector machines: segmenting gestures from rest positions. In SAC, 2013.
Tomas Mikolov, Martin Karafiat, Lukas Burget, Jan Cernock ´ y, and Sanjeev Khudanpur. Recurrent \` neural network based language model. In INTERSPEECH, volume 2, pp. 3, 2010.
Debashis Mondal and Donald B Percival. Wavelet variance analysis for gappy time series. Annals of the Institute of Statistical Mathematics, 62(5):943–966, 2010.
Shahla Parveen and P Green. Speech recognition with missing data using recurrent neural nets. In Advances in Neural Information Processing Systems, pp. 1189–1195, 2001.
F. Pedregosa, G. Varoquaux, A. Gramfort, V. Michel, B. Thirion, O. Grisel, M. Blondel, P. Prettenhofer, R. Weiss, V. Dubourg, J. Vanderplas, A. Passos, D. Cournapeau, M. Brucher, M. Perrot, and E. Duchesnay. Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12:2825–2830, 2011.
Trang Pham, Truyen Tran, Dinh Phung, and Svetha Venkatesh. Deepcare: A deep dynamic memory model for predictive medicine. In Advances in Knowledge Discovery and Data Mining. 2016.
Kira Rehfeld, Norbert Marwan, Jobst Heitzig, and Jurgen Kurths. Comparison of correlation analysis ¨ techniques for irregularly sampled time series. Nonlinear Processes in Geophysics, 18(3), 2011.
Danilo Jimenez Rezende, Shakir Mohamed, and Daan Wierstra. Stochastic backpropagation and approximate inference in deep generative models. In ICML, 2014.
Donald B Rubin. Inference and missing data. Biometrika, 63(3):581–592, 1976.
Joseph L Schafer and John W Graham. Missing data: our view of the state of the art. Psychological methods, 2002.
Ivanovitch Silva, Galan Moody, Daniel J Scott, Leo A Celi, and Roger G Mark. Predicting in-hospital mortality of icu patients: The physionet/computing in cardiology challenge 2012. In CinC, 2012.
Nitish Srivastava, Geoffrey E Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. Dropout: a simple way to prevent neural networks from overfitting. JMLR, 15(1), 2014.
Ilya Sutskever, Oriol Vinyals, and Quoc VV Le. Sequence to sequence learning with neural networks. In Advances in neural information processing systems, pp. 3104–3112, 2014.
Volker Tresp and Thomas Briegel. A solution for missing data in recurrent neural networks with an application to blood glucose prediction. NIPS, pp. 971–977, 1998.
Yoram Vodovotz, Gary An, and Ioannis P Androulakis. A systems engineering perspective on homeostasis and disease. Frontiers in bioengineering and biotechnology, 1, 2013.
Brian J Wells, Kevin M Chagin, Amy S Nowacki, and Michael W Kattan. Strategies for handling missing data in electronic health record derived data. EGEMS, 1(3), 2013.
Ian R White, Patrick Royston, and Angela M Wood. Multiple imputation using chained equations: issues and guidance for practice. Statistics in medicine, 30(4):377–399, 2011.
Li Zhou and George Hripcsak. Temporal reasoning with medical dataa review with emphasis on medical natural language processing. Journal of biomedical informatics, 40(2):183–202, 2007.
# A APPENDIX
# A.1 INVESTIGATION OF RELATION BETWEEN MISSINGNESS AND LABELS
In many time series applications, the pattern of missing variables in the time series is often informative and useful for prediction tasks. Here, we empirically confirm this claim on real health care dataset by investigating the correlation between the missingness and prediction labels (mortality and ICD9 diagnosis categories). We denote the missing rate for a variable $d$ as $p _ { X } ^ { d }$ and calculate it by $\begin{array} { r } { p _ { X } ^ { d } = 1 - \frac { 1 } { T } \sum _ { t = 1 } ^ { T } m _ { t } ^ { d } } \end{array}$ . Note that $p _ { X } ^ { d }$ is dependent on mask vector $( m _ { t } ^ { d } )$ and number of time steps $T$ . For each prediction task, we compute the Pearson correlation coefficient between $p _ { X } ^ { d }$ and label across all the time series. As shown in Figure 1, we observe that on MIMIC-III dataset the missing rates with low rate values are usually highly (either positive or negative) correlated with the labels. The distinct correlation between missingness and labels demonstrates usefulness of missingness patterns in solving prediction tasks.
# A.2 GRU-D MODEL VARIATIONS
In this section, we will discuss some variations of GRU-D model, and also compare some related RNN models which are used for time series with missing data with the proposed model.
 Figure 8: Graphical illustrations of variations of proposed GRU models.
# A.2.1 GRU MODEL WITH DIFFERENT TRAINABLE DECAYS
The proposed GRU-D applies trainable decays on both input and hidden state transitions in order to capture the temporal missing patterns explicitly. This decay idea can be straightforwardly generated to other parts inside the GRU models separately or jointly, given different assumptions on the impact of missingness. As comparisons, we also describe and evaluate several modifications of GRU-D model.
GRU-DI (Figure 8(a)) and GRU-DS (Figure 8(b)) decay only the input and only the hidden state by Equation (5) and (6), respectively. They can be considered as two simplified models of the proposed GRU-D. GRU-DI aims at capturing direct impact of missing values in the data, while GRU-DS captures more indirect impact of missingness. Another intuition comes from this perspective: if an input variable is just missing, we should pay more attention to this missingness; however, if an variable has been missing for a long time and keeps missing, the missingness becomes less important. We can utilize this assumption by decaying the masking. This brings us the model GRU-DM shown in Figure 8(c), where we replace the masking $m _ { t } ^ { d }$ fed into GRU-D in by
$$m _ { t } ^ { d } m _ { t } ^ { d } + ( 1 - m _ { t } ^ { d } ) { \gamma _ { m } } _ { t } ^ { d } ( 1 - m _ { t } ^ { d } ) = m _ { t } ^ { d } + ( 1 - m _ { t } ^ { d } ) { \gamma _ { m } } _ { t } ^ { d }$$
where the equality holds since $m _ { t } ^ { d }$ is either 0 or 1. We decay the masking for each variable independently from others by constraining $W _ { \gamma _ { m } }$ to be diagonal.
# A.2.2 GRU-IMP: GOAL-ORIENTED IMPUTATION MODEL
We may alternatively let the GRU-RNN predict the missing values in the next timestep on its own. When missing values occur only during test time, we simply train the model to predict the measurement vector of the next time step as a language model (Mikolov et al., 2010) and use it to fill the missing values during test time. This is unfortunately not applicable for some time series applications such as in health care domains, which also have missing data during training.
Instead, we propose goal-oriented imputation model here called GRU-IMP, and view missing values as latent variables in a probabilistic graphical model. Given a timeseries $\boldsymbol { X }$ , we denote all the missing variables by $\mathcal { M } _ { X }$ and all the observed ones by ${ \mathcal { O } } _ { X }$ . Then, training a time-series classifier with missing variables becomes equivalent to maximizing the marginalized log-conditional probability of a correct label $l$ , i.e., $\log p ( l | \mathcal { O } _ { X } )$ .
The exact marginalized log-conditional probability is however intractable to compute, and we instead maximize its lowerbound:
$$\log p ( l | \mathcal { O } _ { X } ) = \log \sum _ { M _ { X } } p \left( l | \mathcal { M } _ { X } , \mathcal { O } _ { X } \right) p \left( \mathcal { M } _ { X } | \mathcal { O } _ { X } \right) \geq \mathbb { E } _ { \mathcal { M } _ { X } \sim p \left( \mathcal { M } _ { X } | \mathcal { O } _ { X } \right) } \log p \left( l | \mathcal { M } _ { X } , \mathcal { O } _ { X } \right)$$
where we assume the distribution over the missing variables at each time step is only conditioned on all the previous observations:
$$p \left( \mathcal { M } _ { X } | \mathcal { O } _ { X } \right) = \prod _ { t = 1 } ^ { T } \prod _ { 1 \leq d \leq D } ^ { m _ { t } ^ { d } = 1 } p ( x _ { t } ^ { d } | \pmb { x } _ { 1 : ( t - 1 ) } , \pmb { m } _ { 1 : ( t - 1 ) } , \delta _ { 1 : ( t - 1 ) } )$$
Although this lowerbound is still intractable to compute exactly, we can approximate it by Monte Carlo method, which amounts to sampling the missing variables at each time as the RNN reads the input sequence from the beginning to the end, such that
$$x _ { t } ^ { d } \gets m _ { t } ^ { d } x _ { t } ^ { d } + ( 1 - m _ { t } ^ { d } ) \tilde { x } _ { t } ^ { d }$$
where $\tilde { \mathbf { x } } _ { t } \sim x _ { t } ^ { d } | \mathbf { x } _ { 1 : ( t - 1 ) } , \mathbf { m } _ { 1 : ( t - 1 ) } , \delta _ { 1 : ( t - 1 ) } .$
By further assuming that $\tilde { { \boldsymbol { x } } } _ { t } \sim \mathcal { N } \left( { \boldsymbol { \mu } } _ { t } , { \boldsymbol { \sigma } } _ { t } ^ { 2 } \right) , { \boldsymbol { \mu } } _ { t } = { \boldsymbol { \gamma } } _ { t } \odot \left( { \boldsymbol { W } } _ { x } { \boldsymbol { h } } _ { t - 1 } + { \boldsymbol { b } } _ { x } \right)$ and $\pmb { \sigma } _ { t } = \mathbf { 1 }$ , we can use a reparametrization technique widely used in stochastic variational inference (Kingma & Welling, 2013; Rezende et al., 2014) to estimate the gradient of the lowerbound efficiently. During the test time, we simply use the mean of the missing variable, i.e., $\tilde { \mathbfit { x } } _ { t } = \mu _ { t }$ , as we have not seen any improvement from Monte Carlo approximation in our preliminary experiments. We view this approach as a goal-oriented imputation method and show its structure in Figure 8(d). The whole model is trained to minimize the classification cross-entropy error $\ell _ { l o g \_ l o s s }$ and we take the negative log likelihood of the observed values as a regularizer.
$$\ell = \ell _ { l o g . l o s s } + \lambda \frac { 1 } { N } \sum _ { n = 1 } ^ { N } \frac { 1 } { T _ { n } } \sum _ { t = 1 } ^ { T _ { n } } \frac { \sum _ { d = 1 } ^ { D } m _ { t } ^ { d } \cdot \log p ( x _ { t } ^ { d } | \mu _ { t } ^ { d } , \sigma _ { t } ^ { d } ) } { \sum _ { d = 1 } ^ { D } m _ { t } ^ { d } }$$
# A.3 SUPPLEMENTARY EXPERIMENT DETAILS
# A.3.1 DATA STATISTICS
For each of the three datasets used in our experiments, we list the number of samples, the number of input variables, the mean and max number of time steps for all the samples, and the mean of all the variable missing rates in Table 3.
Table 3: Dataset statistics.
<table><tr><td></td><td>MIMIC-III</td><td>PhysioNet2012</td><td>Gesture</td></tr><tr><td># of samples (N)</td><td>19714</td><td>4000</td><td>378</td></tr><tr><td># of variables (D)</td><td>99</td><td>33</td><td>23</td></tr><tr><td>Mean of # of time steps</td><td>35.89</td><td>68.91</td><td>21.42</td></tr><tr><td>Maximum of # of time steps</td><td>150</td><td>155</td><td>31</td></tr><tr><td> Mean of variable missing rate</td><td>0.9621</td><td>0.8225</td><td>N/A</td></tr></table>
# A.3.2 GRU MODEL SIZE COMPARISON
In order to fairly compare the capacity of all GRU-RNN models, we build each model in proper size so they share similar number of parameters. Table 4 shows the statistics of all GRU-based models for on three datasets. We show the statistics for mortality prediction on the two real datasets, and it’s almost the same for multi-task classifications tasks on these datasets. In addition, having comparable number of parameters also makes all the models have number of iterations and training time close in the same scale in all the experiments.
Table 4: Comparison of GRU model size in our experiments. Size refers to the number of hidden states $( h )$ in GRU .
<table><tr><td rowspan="2">Models</td><td colspan="2">Gesture 18 input variables</td><td colspan="2">MIMIC-III 99 input variables</td><td colspan="2">PhysioNet 33 input variables</td></tr><tr><td>Size</td><td># of parameters</td><td>Size</td><td># of parameters</td><td>Size</td><td># of parameters</td></tr><tr><td>GRU-mean&forward</td><td>64</td><td>16281</td><td>100</td><td>60105</td><td>64</td><td>18885</td></tr><tr><td>GRU-simple</td><td>50</td><td>16025</td><td>56</td><td>59533</td><td>43</td><td>18495</td></tr><tr><td>GRU-D</td><td>55</td><td>16561</td><td>67</td><td>60436</td><td>49</td><td>18838</td></tr></table>
# A.3.3 MULTI-TASK PREDICTION DETAILS
The RNN models for multi-task learning with $m$ tasks is almost the same as that for binary classification, except that 1) the soft-max prediction layer is replaced by a fully connected layer with $n$ sigmoid logistic functions, and 2) a data-driven prior regularizer (Che et al., 2015), parameterized by comorbidity (co-occurrence) counts in training data, is applied to the prediction layer to improve the classification performance. We show the AUC scores for predicting 20 ICD-9 diagnosis categories on MIMIC-III dataset in Figure 9, and all 4 tasks on PhysioNet dataset in Figure 10. The proposed GRU-D achieves the best average AUC score on both datasets and wins 11 of the 20 ICD-9 prediction tasks.
 Figure 9: Performance for predicting 20 ICD-9 diagnosis categories on MIMIC-III dataset. $\mathbf { X }$ -axis, ICD-9 diagnosis category id; y-axis, AUC score.
 Figure 10: Performance for predicting all 4 tasks on PhysioNet dataset. mortality, in-hospital mortality; $l o s < 3$ , length-of-stay less than 3 days; surgery, whether the patient was recovering from surgery; cardiac, whether the patient had a cardiac condition; y-axis, AUC score.
# A.3.4 EMPIRICAL COMPARISON OF MODEL VARIATIONS
As a thorough empirical comparison, we test all GRU model variations mentioned in Appendix A.2 along with the proposed GRU-D. These include 1) 4 models with trainable decays (GRU-DI, GRU-DS, GRU-DM, GRU-IMP), and 2) two models simplified from GRU-simple (interval only and masking only). The results are shown in Table 5. As we can see, GRU-D performs best among these models.
Table 5: Model performances of GRU variations measured by AUC score $( m e a n \pm s t d )$ for mortality prediction.
<table><tr><td colspan="2">Models</td><td>MIMIC-III</td><td>PhysioNet</td></tr><tr><td rowspan="3">Baselines</td><td>GRU-simple (masking only)</td><td>0.8367 ± 0.009</td><td>0.8226 ± 0.010</td></tr><tr><td>GRU-simple (interval only)</td><td>0.8266 ± 0.009</td><td>0.8125 ± 0.005</td></tr><tr><td>GRU-simple</td><td>0.8380 ± 0.008</td><td>0.8155 ± 0.004</td></tr><tr><td rowspan="5">Proposed</td><td>GRU-DI</td><td>0.8345 ± 0.006</td><td>0.8328 ± 0.008</td></tr><tr><td>GRU-DS</td><td>0.8425 ± 0.006</td><td>0.8241 ± 0.009</td></tr><tr><td>GRU-DM</td><td>0.8342 ± 0.005</td><td>0.8248± 0.009</td></tr><tr><td>GRU-IMP</td><td>0.8248 ± 0.010</td><td>0.8231± 0.005</td></tr><tr><td>GRU-D</td><td>0.8527 ± 0.003</td><td>0.8424 ± 0.012</td></tr></table>
# A.3.5 EVALUATION ON MULTI-LAYER RNNS
We also conducted experiments on 2-layer RNN models to demonstrate the superiority of our proposed GRU-D models can be generalized to multi-layer RNNs. For all baseline and proposed GRU models, we add one standard GRU layer on top of the baseline or proposed GRU layer. We tested models both with similar number of parameters to single layer models and with more parameters. As shown in Table 6 and 7, our GRU-D model consistently outperforms other baselines in all cases, and models with moderate size perform as good as larger models with more parameters. Compared with 1-layer RNNs, all models with deeper structures perform much better on the large MIMIC-III dataset but no better on the relative small PhysioNet dataset.
Table 6: Comparison of multi-layer GRU models for mortality prediction on PhysioNet dataset. Size refers to the numbers of hidden states of 2 GRU layers.
<table><tr><td rowspan="2">Models</td><td rowspan="2"></td><td colspan="3">PhysioNet</td></tr><tr><td>Size</td><td># of params.</td><td>AUC score</td></tr><tr><td rowspan="4">Similar size</td><td>GRU-mean</td><td>40,40</td><td>18643</td><td>0.8157 ± 0.008</td></tr><tr><td>GRU-forward</td><td>40,40</td><td>18643</td><td>0.8205 ± 0.008</td></tr><tr><td>GRU-simple</td><td>32,32</td><td>18947</td><td>0.8159 ± 0.007</td></tr><tr><td>GRU-D</td><td>34,34</td><td>18599</td><td>0.8420 ± 0.009</td></tr><tr><td rowspan="4">Larger size</td><td>GRU-mean</td><td>64,64</td><td>43651</td><td>0.8199 ± 0.002</td></tr><tr><td>GRU-forward</td><td>64,64</td><td>43651</td><td>0.8112 ± 0.035</td></tr><tr><td>GRU-simple</td><td>43,64</td><td>39250</td><td>0.8208 ± 0.009</td></tr><tr><td>GRU-D</td><td>49,64</td><td>40739</td><td>0.8363 ± 0.013</td></tr></table>
Table 7: Comparison of multi-layer GRU models for mortality prediction on MIMIC-III dataset. Size refers to the numbers of hidden states of 2 GRU layers.
<table><tr><td rowspan="2">Models</td><td rowspan="2"></td><td colspan="3">MIMIC-III</td></tr><tr><td>Size</td><td># of params.</td><td>AUC score</td></tr><tr><td rowspan="4">Similar size</td><td>GRU-mean</td><td>66,66</td><td>59271</td><td>0.9538± 0.005</td></tr><tr><td>GRU-forward</td><td>66,66</td><td>59271</td><td>0.9441 ± 0.005</td></tr><tr><td>GRU-simple</td><td>46,46</td><td>60355</td><td>0.9527 ± 0.005</td></tr><tr><td>GRU-D</td><td>52,52</td><td>60989</td><td>0.9606 ± 0.002</td></tr><tr><td rowspan="8">Larger size</td><td>GRU-mean</td><td>100,64</td><td>91747</td><td>0.9523± 0.006</td></tr><tr><td>GRU-forward</td><td>100,64</td><td>91747</td><td>0.9443 3±0.003</td></tr><tr><td>GRU-simple</td><td>56,64</td><td>82771</td><td>0.9520 ± 0.003</td></tr><tr><td>GRU-D</td><td>67,64</td><td>85775</td><td>0.9604± 0.003</td></tr><tr><td>GRU-mean</td><td>100,128</td><td>148067</td><td>0.9539 ± 0.006</td></tr><tr><td>GRU-forward</td><td>100,128</td><td>148067</td><td>0.9457± 0.005</td></tr><tr><td>GRU-simple</td><td>56,128</td><td>130643</td><td>0.9523± 0.003</td></tr><tr><td>GRU-D</td><td>67,128</td><td>135759</td><td>0.9618 ± 0.002</td></tr></table>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240# Hybrid Rotation Invariant Networks for small sample size Deep Learning
Alexander Katzmann1,3 Marc-Steffen Seibel $^ { 1 , 3 }$ Alexander M¨uhlberg1 Michael S¨uhling1
alexander.katzmann@siemens.com marc-steffen.seibel@siemens.com alexander.muehlberg.ext@siemens.com michael.suehling@siemens.com $\bot$ Siemens Healthcare GmbH, Computed Tomography, 91301 Forchheim, Germany
Dominik N¨orenberg $^ { 2 }$ Stefan Maurus2 Thomas Huber2
dominik.noerenberg@med.uni-muenchen.de stefan.maurus@med.uni-muenchen.de thomas.huber@med.uni-muenchen.de
$^ 2$ University Hospital Grohadern, Ludwig-Maximilians-University Munich, Department of Radiology, 81377 Munich, Germany
Horst-Michael Groß3 horst-michael.gross@tu-ilmenau.de
3 Ilmenau, University of Technology, Neuroinformatics and Cognitive Robotics Lab, 98693 Ilmenau, Germany
Editors: Under Review for MIDL 2019
# Abstract
Medical image analysis using deep learning has become a topic of steadily growing interest. While model capacity is continiously increasing, limited data is still a major issue for deep learning in medical imaging. Virtually all past approaches work with a high amount of regularization as well as systematic data augmentation. In explorative tasks realistic data augmentation with affine transformations may not always be possible, which prevents models from effective generalization. Within this paper, we propose inherently rotationally invariant convolutional layers enabling the model to develop invariant features from limited training data. Our approach outperforms classical convolutions on the CIFAR-10, CIFAR100, and STL-10 datasets. We show the transferability to clinical scenarios by applying our approach on oncologic tasks for metastatic colorectal cancer treatment assessment and liver lesion segmentation in pancreatic cancer patients.
Keywords: rotational invariance, regularization, colorectal cancer, pancreatic cancer
# 1. Introduction
With the rise of deep learning and its success in a wide range of applications, within the last years (semi-)automated medical image analysis using deep learning has become a topic of steadily growing interest (Litjens et al., 2017; Shen et al., 2017). A major reason for the success of deep learning is its high model complexity. However, with an increasing amount of trainable parameters, deep learning models become highly prone to overfitting.
Most - or virtually all - medical applications of deep learning have to handle this problem, i.e. model regularization, in one or the other way. Standard techniques involve dropout (Srivastava et al., 2014), batch normalization (Ioffe and Szegedy, 2015), data augmentation and various forms of dimensionality or effective model complexity reduction, such as architectural bottlenecking through sparse representations or using denoising autoencoders (Vincent et al., 2008). Most of the mentioned techniques increase training set variance by (effectively) introducing semi-synthetically generated samples with no additional information, which eventually leads to a reduced model parameter variance, and thus, a reduced effective model complexity. This process can be seen as an a-priori knowledge-guided model regularization. However, the applied techniques differ: While dropout, batch-normalization, and architectural regularization tackle the problem from within the models training task, data augmentation is done from the outside. Non-augmenting model regularization induces invariance in a form which is part of the optimization process, thus making it possible for the model to learn more efficiently, while data augmentation assumes that semi-synthetically generated samples are semantically following some form of invariance visually perceived by human. This, however, might be a wrong assumption.
Neural networks apply a vast amount of non-linear projections. Meanwhile handy tools for visualization are existent, and while they can be considered as being generally helpful in neural network development, a) their introduction and distribution took considerably longer than the network advancements’, and predominantly b) current visualization and inspection tools are still just starting to be at the edge of what can genuinely be considered as intuitive or obvious. As a consequence, there is still a lack of knowledge on the emergence of concrete interactions within the network.
In turn, this means that while samples and their respective labels might for human observers seem invariant to affine transformations, e.g. shearing, rotation, or scaling, these transformations could in fact induce semantic label errors. This might be mostly assumed irrelevant in scenarios where humans significantly outperform machines, so their sense of invariance should be reasonable to a specific point. However, especially within the medical field one prospective speculation is the improvement of diagnostic performance beyond the level of human vision. Therefore, it might be advisable to optimize the network’s choice of transformations itself for maximizing the output accuracy.
Another factor is that data augmentation can be seen as inefficient with respect to training time. When invariance is encoded directly into the model, data augmentation can be kept as low as possible. For example, there have been many efforts to introduce rotational invariance into neural networks (Marcos et al., 2016; Winkels and Cohen, 2018; Cheng et al., 2016) with some of them reaching back to non-convolutional approaches (Fasel and GaticaPerez, 2006). Also there have been approaches to systematically learn steerable filters for convolutional neural networks being inherently rotationally invariant (Weiler et al., 2017) based on the work from Jacob and Unser (2003, 2004).
While differing in their choice of concrete methods, all these approaches have in common that they either create invariance a) by some form of rotated duplication of filters, or b) by constraining the network to only allow special filter configurations which are rotationally invariant themselves, e.g. via custom loss function or network constraints. While a) unintentionally reduces the effective network capacity, b) prevents the network from detecting actually non-invariant features.
Within this paper, we demonstrate that simple transformational layers within the network for invariance might significantly improve the network’s performance. We show this by introducing an inherently rotation-invariant convolutional layer, while preserving the input’s local pose. We show that our network outperforms classic convolutional neural networks which share the same model complexity, i.e. number of optimizable parameters, with respect to the final test set performance. In our experiments, we show that this especially holds true when data is limited, as it is typical within clinical scenarios. As a proof of concept, we provide an exhaustive evaluation with a variety of metrics on the well-known benchmark datasets CIFAR-10, CIFAR-100 and STL-10. We furthermore demonstrate the transferability to the clinical context using two self-acquired medical datasets with the tasks of oncological treatment response classification in metastatic colorectal cancer patients (mCRC) and liver lesion segmentation in pancreatic cancer patients.
# 2. Material and methods
Invariance to visual distortions is often important in terms of generalization performance. Common distortion types within visual perception comprise translation, scale, rotation, illumination, and many more. Deep learning research often relies on the belief that data amount might compensate for variance with respect to these distortions at least to some point. Still, most top-performing neural networks apply data augmentation even when trained on large datasets. Data augmentation induces additional variance into the training data which in turn increases the probability of the classifier being invariant to changes represented within the augmented data with respect to an output label. The applied transformations generally rely on the a-priori knowledge of label invariance regarding specific types of transformations based on visual-perception. More formally, the transformations are input-variant but label-invariant, or in simple terms: transformations are generally reasonable with respect to the actual label, i.e. with the example of the well-known CIFAR 10 dataset within a reasonable range of transformations the perceived class of an image of the class ”bird” will not change into one of the class ”frog” or vice-versa.
While this is immediately comprehensible for visually perceivable classes, the situation changes when deep learning is applied to explorative tasks where the ground-truth labels can not directly be perceived by human visual inspection. Assessment beyond human perception, however, is a major goal of many approaches within the clinical domain, e.g. by Radiomics (Gillies et al., 2015). Instead, transformations might induce unnatural variance in these cases and, thus, even worsen classification performance as labels might actually be rotationally and transformationally variant. With our approach, we show that it is feasible to make the search for invariant vs. variant features a matter of the network optimization process.
# 2.1. The ORB approach
Our approach is built upon the idea of ORB - Oriented FAST and Rotational Brief from Rublee et al. (2011). ORB was one of the most recognized approaches introducing rotational invariance into actually non-invariant visual patch recognition utilizing the intensity centroids described by Rosin (1999). For this purpose Rublee et al. determine image patch
moments as:
$$m _ { p q } = \sum _ { x , y } x ^ { p } y ^ { q } I ( x , y )$$
based on normalized image intensities $I$ at positions $( x , y )$ . Image patch moments can be used for finding the image centroid as:
$$C = \left( { \frac { m _ { 1 0 } } { m _ { 0 0 } } } , { \frac { m _ { 0 1 } } { m _ { 0 0 } } } \right)$$
which allows rotating the patch according to the inverse of its orientation $\Theta$ :
$$\Theta = \operatorname { a t a n 2 } ( m _ { 0 1 } , m _ { 1 0 } )$$
After rotation, originally non-invariant transformations can be applied to the image while preserving rotational invariance.

Figure 1: Left: image patches with various orientations. Within convolutional neural networks, these patches would have to be detected with respectively equally oriented filters. Right: Images after centroid rotation. With rotational invariance, all four patches would be mapped to the same orientation.
# 2.2. Hybrid Rotation Invariant Networks
As all aforementioned operations are differentiable, it is possible to transfer these operations to convolutional neural networks, which is reasonable as ORB was created to be applied on image patches itself. We limit this publication to only take into account the two-dimensional case, as the datasets we consider mostly consist of two-dimensional data only. However, the generalization to the n-dimensional case is straightforward. Analogously to classical 2D convolutional layers, our approach first extracts image patches parameterizable by kernel size, strides, extraction rate and border padding. In a second step, image centroids are derived according to Equation (2), and patches are rotated by their respective centroid rotation $\Theta$ from Equation (3). The data is rotated by multiplying the homogeneous extraction coordinates $( x , y , 1 )$ with the matrix $M$ :
$$( x ^ { \prime } , y ^ { \prime } , z ) = ( x , y , 1 ) \cdot M \quad { \mathrm { w i t h } } \quad M = { \left[ \begin{array} { l l l } { \cos \Theta } & { - \sin \Theta } & { 0 } \\ { \sin \Theta } & { \cos \Theta } & { 0 } \\ { 0 } & { 0 } & { 1 } \end{array} \right] }$$
When extraction coordinates $( x ^ { \prime } , y ^ { \prime } )$ lie between pixels, a bilinear interpolation is applied. While homogeneous and non-homogeneous coordinates result in the same image positions using the transformation matrix $M$ , i.e. $\begin{array} { r } { ( \frac { x ^ { \prime } } { z } , \frac { y ^ { \prime } } { z } ) = ( x ^ { \prime } , y ^ { \prime } ) } \end{array}$ , this matrix format shows that arbitrary transformations are easy to implement, making the approach feasible for invariance to other affine transformations, e.g. scale or sheering. Further approaches could include a learned transformation (see Section 4). Finally, the filter output is calculated analogously to classical convolutions with:
$$y = W * p + b$$
for each rotated $k \times k$ image patch $p$ , kernel size $k$ , weight matrix $W$ and filter bias $b$ .
# 2.2.1. Rotation invariance vs. rotational equivariance
Rotation invariance might be suboptimal, as the patches’ local rotation might constrain global relations. This is for example the case with face images, where the rotation of eyes or mouth generally have implications for valid rotations of nose and eyebrows. Thus each on its own is not invariant, but equivariant (invariant with knowledge on its pose), while the patches are covariant with respect to other patches (i.e. the rotation of patches is defining for the rotation of other patches). Rotational invariance would imply an arbitrary rotation for each of the subfeatures, meaning that the actual rotation of eyes or nose would have no implications for the rotation of the mouth features, etc.. To preserve rotational equivariance (resp. the knowledge of local rotation), for every rotationally invariant layer two additional filter maps are appended, containing the values $\sin \Theta ( x , y )$ and $\cos \Theta ( x , y )$ for the local rotation $\Theta$ (Equation (3)) at each filter position $( x , y )$ . Still, we can not preserve actual covariance between patches as it is possible with classical convolutions where different rotations are represented by separate filters. To address this issue, we propose a combination of rotationally invariant and classic convolutions called hybrid layers. We expect this mixture to yield significantly better performance: while rotationally invariant input image properties should fastly be covered by the rotationally invariant filters, the non-invariant properties can be treated using standard convolutions, without the need of learning rotated duplicates of the same filters. As we use hybrid layers, i.e. half of the filters are rotationally invariant, while the other half is not, rotation variance and invariance can be preserved at every abstraction stage within the network.
# 2.3. Working Hypotheses and Evaluation
Based on the assumptions mentioned above, we expect our approach to especially perform well when sample size is large enough for successful formation of simple filters but not for sufficiently developing rotated versions of these filters, or for discovering spatial covariances within deeper layers. We hypothesize that a) our approach should reach similar results as with classical convolutions with very small training sets, b) significantly outperform them with medium sample sizes, and c) eventually converge to a value comparable to noninvariant convolutions. Furthermore, we expect our approach to be especially beneficial for difficult learning tasks, as its rotational invariance allows it to develop comparably simple features more efficiently. To test these assumptions, we systematically modified training set sizes $S$ to be:
$$S _ { X } = \{ 2 ^ { n } \mid n _ { 0 } \leq n \leq \log _ { 2 } ( | X | ) \} \cup \{ | X | \}$$
for dataset $X$ . We chose a start value of $n _ { 0 } = 7$ resulting in the smallest set having a cardinality of $\operatorname* { m i n } ( S _ { X } ) = 2 ^ { 7 } = 1 2 8$ samples since the set with the highest amount of classes
has exactly 100 classes, meaning that ≈ 78% of classes are represented by only one sample within the training set.
# 2.3.1. Training details and sets
For training, we employed Keras (Chollet et al., 2015) using the Tensorflow backend (Abadi et al., 2015). As a proof of concept, we tested our approach on the well-known Cifar-10 and Cifar-100 datasets from Krizhevsky and Hinton (2009), as well as the STL-10 dataset from Coates et al. (2011). To show the impact for classification in typical clinical datasets, we trained our model with an extended version of the metastatic colorectal cancer dataset (mCRC) from Katzmann et al. (2018). To analyze whether our approach is transferable to other tasks, we also employed the aproach for liver lesion segmentation in pancreas carcinoma patients, using a newly acquired dataset. For each set size, we trained both models (i.e. rotationally invariant and classic) for three iterations with varying random seeds in each iteration. Within each iteration, seeds were fixed for both models for ensuring equal initialization and training sample order. For Cifar-10, Cifar-100 and STL-10, all results were evaluated on the respective full test set. For tumor growth prediction and liver lesion segmentation, we chose a 4-fold grouped stratified cross-validation as a tradeoff between training time and explanatory power, with $1 / 4$ of the training set to be used for validation. In every case we optimized using categorical cross entropy loss. The best model was chosen as the one maximizing the lower bound of the $9 5 \%$ bootstrapping confidence interval of ROC area-under-curve on the validation dataset, as this also takes into account metric variance and empirically provided clear advantages over using the validation loss with respect to the generalizability of the results. All results were obtained using bootstrapping until metrics convergence (Efron, 1982).
# 3. Results
# 3.1. Cifar-10, Cifar-100 and STL-10
The Cifar-10 and Cifar-100 datasets consist of 50,000 images each with a size of 32x32 from 10, respectively 100, different classes of everyday objects, e.g. planes, cars, or dogs. The test sets comprise 10,000 samples each. STL-10 is built up similarly to Cifar-10, but contains 5,000 images sized 96x96 pixels for training and 8,000 images for testing. As described above, we trained our model as well as an equivalently built one with classical convolutions while systematically varying the amount of training samples used as described in Section 2.3. The results are shown in Figure 2.
# 3.2. mCRC Dataset
Using an extended version of the dataset from Katzmann et al. (2018), we trained our model to predict disease progressions of patients with metastatic colorectal cancer based on baseline-followup-pairs of liver lesion slices from computed tomography images, that is, predicting growth at followup two relative to lesion size at followup one. This assesment was already shown to be partially predictive for biological information while providing benefits over the clinical standard Response Evaluation Criteria in Solid Tumors (RECIST v1.1) lesion assessment from Eisenhauer et al. (2009). Our target variable definition is defined
 Figure 2: Results of rotationally invariant vs. variant convolutional neural networks on the CIFAR-10, CIFAR-100 and STL-10 datasets. Results are shown with respect to accuracy, matthews correlation coefficient, and area under the receiver operating curve (ROC-AUC) using multiclass-macro-averaging. The metric’s $9 9 \%$ confidence intervals are given as shadowed areas. Expectedly, rotationally invariant layers outperform classical convolutions with medium sample sizes but become less significant with larger sets or lower-difficulty problems. With the more difficult problems from CIFAR-100 and STL-10, the differences between rotationally invariant and non-invariant layers become more significant.
as the RECIST lesion progressive disease status, thus a lesion growth of $\geq 2 0 \%$ is assumed progression. The dataset contains 592 baseline followup pairs of 320 lesions in 138 scans from 75 patients. The test results are shown in Table 1.
<table><tr><td></td><td>Our approach</td><td>CI 95</td><td>Classic</td><td>CI 95</td></tr><tr><td>Accuracy</td><td>.636</td><td>[.598, .674]</td><td>.724</td><td>[.689, .760]</td></tr><tr><td>F1</td><td>.335</td><td>[.273, .402]</td><td>.313</td><td>[.232, .390]</td></tr><tr><td>Sensitivity</td><td>.671</td><td>[.569, .774]</td><td>.463</td><td>[.360, .577]</td></tr><tr><td>Specificity</td><td>.631</td><td>[.587, .671]</td><td>.765</td><td>[.727, .801]</td></tr><tr><td>Matthews</td><td>.211</td><td>[.132, .291]</td><td>.177</td><td>[.089, .264]</td></tr><tr><td>AUC</td><td>.717</td><td>[.659, .776]</td><td>.639</td><td>[.561, .713]</td></tr></table>
Table 1: Results on the mCRC dataset for tumor growth prediction. Label distribution was 81 positive vs. 511 negative samples. While classifiers focused on different classes, the balanced Matthews correlation coefficient indicates superiority of rotationinvariant convolutions with significantly higher ROC AUC with $p < . 0 5$ (two-tailed $\boldsymbol { \mathrm { z } }$ -test).
# 3.3. Liver lesion segmentation in pancreatic cancer patients
We applied our approach for liver lesion segmentation using a modified 2D version of the UNet architecture from Ronneberger et al. (2015). The model is trained on a newly acquired dataset of pancreatic cancer patients. Segmenting liver lesions in pancreatic cancer patients can be seen as particulary difficult as one patient may suffer from more than a houndred liver lesions. The dataset consisted of 3481 samples from 135 volumes of 87 pancreas carcinoma patients with fully-volumetrically segmented livers and liver lesions. Metrics were tested with and without outlier detection. When applying outlier detection, surface distances $\geq 5 c m$ were expected to be misclassifications. The obtained results can be found in Table 2. An examplary segmentation result is shown in Figure 3.
<table><tr><td></td><td colspan="3">Our approach</td><td colspan="3">Classic</td></tr><tr><td>Metric</td><td>W</td><td></td><td>w/0</td><td>W</td><td></td><td>w/0</td></tr><tr><td>Mean SD</td><td>8.36 [8.16, 8.60]</td><td>26.6</td><td>[25.0, 28.6]</td><td>8.42 [8.16, 8.68]</td><td></td><td>27.6 [25.8, 29.6]</td></tr><tr><td>Median SD</td><td>2.98 [2.82, 4.00]</td><td>4.70 [.536, .566]</td><td>[4.48, 5.66]</td><td>2.82 [2.82, 4.00]</td><td></td><td>4.76 [4.48, 5.66]</td></tr><tr><td>Dice</td><td colspan="3">.552</td><td colspan="3">.542[.526, .559]</td></tr></table>
Table 2: Results for the pancreatic cancer dataset with hybrid (left) vs. classical convolutions (right). Surface metrics (in mm) were calculated with (w) and without (w/o) outlier removal. When applying outlier removal, both models performed similarly, while without outlier removal our model outperformed classical convolutions with respect to mean and median surface distance (SD).
 Figure 3: Examplary segmentation result using rotationally invariant filters. Left: original image; middle: segmentation result; right: overlay. True positives, false positives and false negatives are respectively marked as green, blue, and red.
# 4. Discussion
As shown in Section 3, our approach mostly outperformed classical convolutions for all tested datasets. As expected, this especially holds true when working with medium training set sizes and/or difficult problems, as shown on the example of Cifar-100 and STL-10 with the resulting differences being highly significant for all tested metrics ( $p \leq . 0 1 )$ ). However, more simple problems like Cifar-10 do not neccessarely benefit from the approach when large training sets are available. On medical data, our approach performed superior to classical convolutions, both, for classification ( $p _ { A U C } \leq . 0 5$ ) as well as for segmentation tasks. Though there generally is some understanding on how rotational invariance can be realized by rotationally non-invariant networks (Sauder, 2006), the introduction of inherently rotationally invariant networks might provide major benefits for various training problems especially within the medical domain, where training data is rare and models can easily suffer from overfitting. While deep neural networks are thought to develop even rotationally invariant features on their own, their capabilities are limited due to training data amount, training time and model complexity. Especially these issues major arguments for directly encoding invariance into the model itself.
In future work, the proposed approach should be expanded to explicitly learn invariance when needed, as the choice of using invariant vs. non-invariant features within this publication was realized by statically mixing both layer types only. Extending the given approach, the general form of the transformational matrices like shown in Section 2.2 could be used for making models inherently invariant to other affine transformations, e.g. scale or sheering.
# Acknowledgments
This work has received funding from the German Federal Ministry of Education and Research as part of the PANTHER project under grant agreement no. 13GW0163A. The concepts and information presented in this article are based on research and are not commercially available.
# References
Mart´ın Abadi, Ashish Agarwal, Paul Barham, Eugene Brevdo, Zhifeng Chen, Craig Citro, Greg S. Corrado, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Ian Goodfellow, Andrew Harp, Geoffrey Irving, Michael Isard, Yangqing Jia, Rafal Jozefowicz, Lukasz Kaiser, Manjunath Kudlur, Josh Levenberg, Dandelion Man´e, Rajat Monga, Sherry Moore, Derek Murray, Chris Olah, Mike Schuster, Jonathon Shlens, Benoit Steiner, Ilya Sutskever, Kunal Talwar, Paul Tucker, Vincent Vanhoucke, Vijay Vasudevan, Fernanda Vi´egas, Oriol Vinyals, Pete Warden, Martin Wattenberg, Martin Wicke, Yuan Yu, and Xiaoqiang Zheng. TensorFlow: Large-scale machine learning on heterogeneous systems, 2015. URL https://www.tensorflow.org/. Software available from tensorflow.org.
Gong Cheng, Junwei Han, Peicheng Zhou, and Dong Xu. Learning rotation-invariant and fisher discriminative convolutional neural networks for object detection. IEEE Transactions on Image Processing, 28(1):265–278, 2016.
Fran¸cois Chollet et al. Keras. https://keras.io, 2015.
Adam Coates, Andrew Ng, and Honglak Lee. An analysis of single-layer networks in unsupervised feature learning. In Proceedings of the fourteenth international conference on artificial intelligence and statistics, pages 215–223, 2011.
Bradley Efron. The jackknife, the bootstrap, and other resampling plans, volume 38. Siam, 1982.
Elizabeth A Eisenhauer, Patrick Therasse, Jan Bogaerts, Lawrence H Schwartz, D Sargent, Robert Ford, Janet Dancey, S Arbuck, Steve Gwyther, Margaret Mooney, et al. New response evaluation criteria in solid tumours: revised recist guideline (version 1.1). European journal of cancer, 45(2):228–247, 2009.
Beat Fasel and Daniel Gatica-Perez. Rotation-invariant neoperceptron. In Pattern Recognition, 2006. ICPR 2006. 18th International Conference on, volume 3, pages 336–339. IEEE, 2006.
Robert J Gillies, Paul E Kinahan, and Hedvig Hricak. Radiomics: images are more than pictures, they are data. Radiology, 278(2):563–577, 2015.
Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. arXiv preprint arXiv:1502.03167, 2015.
Mathews Jacob and Michael Unser. Optimal steerable filters for feature detection. In ICIP (3), pages 433–436, 2003.
Mathews Jacob and Michael Unser. Design of steerable filters for feature detection using canny-like criteria. IEEE transactions on pattern analysis and machine intelligence, 26 (8):1007–1019, 2004.
Alexander Katzmann, Alexander Muehlberg, Michael Suehling, Dominik Noerenberg, Julian Walter Holch, Volker Heinemann, and Horst-Michael Gross. Predicting lesion growth and patient survival in colorectal cancer patients using deep neural networks. 2018.
Alex Krizhevsky and Geoffrey Hinton. Learning multiple layers of features from tiny images. Technical report, Citeseer, 2009.
Geert Litjens, Thijs Kooi, Babak Ehteshami Bejnordi, Arnaud Arindra Adiyoso Setio, Francesco Ciompi, Mohsen Ghafoorian, Jeroen Awm Van Der Laak, Bram Van Ginneken, and Clara I S´anchez. A survey on deep learning in medical image analysis. Medical image analysis, 42:60–88, 2017.
Diego Marcos, Michele Volpi, and Devis Tuia. Learning rotation invariant convolutional filters for texture classification. In Pattern Recognition (ICPR), 2016 23rd International Conference on, pages 2012–2017. IEEE, 2016.
Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015.
Paul L Rosin. Measuring corner properties. Computer Vision and Image Understanding, 73(2):291–307, 1999.
Ethan Rublee, Vincent Rabaud, Kurt Konolige, and Gary Bradski. Orb: An efficient alternative to sift or surf. In Computer Vision (ICCV), 2011 IEEE international conference on, pages 2564–2571. IEEE, 2011.
Nathaniel Sauder. Encoded invariance in convolutional neural networks. University of Chicago, pages 2–6, 2006.
Dinggang Shen, Guorong Wu, and Heung-Il Suk. Deep learning in medical image analysis. Annual review of biomedical engineering, 19:221–248, 2017.
Nitish Srivastava, Geoffrey Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. Dropout: a simple way to prevent neural networks from overfitting. The Journal of Machine Learning Research, 15(1):1929–1958, 2014.
Pascal Vincent, Hugo Larochelle, Yoshua Bengio, and Pierre-Antoine Manzagol. Extracting and composing robust features with denoising autoencoders. In Proceedings of the 25th international conference on Machine learning, pages 1096–1103. ACM, 2008.
Maurice Weiler, Fred A Hamprecht, and Martin Storath. Learning steerable filters for rotation equivariant cnns. arXiv preprint arXiv:1711.07289, 2017.
Marysia Winkels and Taco S Cohen. 3d g-cnns for pulmonary nodule detection. arXiv preprint arXiv:1804.04656, 2018.
# Appendix A. Detailed dataset description
# A.1. Tumor growth dataset
The classification goal was defined analogously to the RECIST guideline (Eisenhauer et al., 2009) as a lesion having $\geq 2 0 \%$ growth at the next followup after the input timepoints. Each lesion was masked using fully-volumetric segmentations created by radiologists. All lesions were isotropically rescaled with a target voxel size of $1 m m \times 1 m m \times 1 m m$ using bicubic interpolation. For all lesions a lesion-centered window of $6 4 m m \times 6 4 m m \times 6 4 m m$ due to lesion diameter quantiles of $\left( \mathcal { Q } _ { P r ( \emptyset ) \leq . 1 } , \mathcal { Q } _ { P r ( \emptyset ) \geq . 9 } \right) = ( 1 0 . 5 \mathrm { m m } , 5 5 . 2 \mathrm { m m } )$ ). For each lesion, only the middle slice was classified. In total the dataset contained 592 valid samples, with 81 being positive (growth) vs. 511 being negative (non-growth). All samples underwent histogram equalization. Examplary data is shown in Figure 4.
 Figure 4: Example images of the CRC dataset after histogram equalization.
# A.2. Pancreas dataset
The complete dataset consisted of 135 volumes from 87 patients. Classification was done in 2D using single slices of masked livers. Isotropic resampling to $1 m m \times 1 m m \times 1 m m$ voxel size was applied using bicubic interpolation. All slices had a size of $5 1 2 \times 5 1 2$ voxels. Although only venous phases were used, data heterogeneity was high due to various treatments, kernels, scanners and comorbidities, such as fatty liver and cholestasis. All samples were resized to $2 5 6 \times 2 5 6$ pixels. All samples having at least one voxel of lesion tissue were involved in the dataset, resulting in a total quantity of 3536 valid liver slices. Again, all samples underwent histogram equalization. An example image is shown in Figure 3.
# Appendix B. Architectures
Following we list the architectures used to calculate the results from Section 3. The networks are given as convolutional networks. The respective hybrid networks are created by simply replacing the convolutional layers with hybrid layers as described in Section 2.2.
# B.1. Cifar-10, Cifar-100, STL-10
The architectures used for the classification results from Section 3.1 on CIFAR-10, CIFAR100 and STL-10 are shown in Table 3.
<table><tr><td>Description</td><td>CIFAR-10/-100</td><td>STL-10</td><td>filter size</td></tr><tr><td>input</td><td>(32,32,1)</td><td>(96,96,1)</td><td>1</td></tr><tr><td>conv + BN + leaky ReLU</td><td>(32,32,32)</td><td>(96,96,32)</td><td>(3,3)</td></tr><tr><td>max pooling conv + BN + leaky ReLU</td><td>(16,16,32)</td><td>(48,48,32)</td><td></td></tr><tr><td></td><td>(16,16,48)</td><td>(48,48,48)</td><td>(3,3)</td></tr><tr><td>max pooling</td><td>(8,8,48)</td><td>(24,24,48)</td><td>二</td></tr><tr><td>conv+1 BN +leaky ReLU</td><td>(8,8,64)</td><td>(24,24,64)</td><td>(3,3)</td></tr><tr><td>conv + BN + leaky ReLU fatten</td><td>(8,8,96)</td><td>(24,24,96)</td><td>(3,3)</td></tr><tr><td>dense + BN + leaky ReLU</td><td>(6144,)</td><td>(55296,)</td><td>=</td></tr><tr><td></td><td>(512,)</td><td>(512,)</td><td>一</td></tr><tr><td>softmax</td><td>(10,)/(100,)</td><td>(10,)</td><td></td></tr></table>
Table 3: For CIFAR-10, CIFAR-100 and STL-10, a very simple network architecture was chosen. It is based on a sequence of blocks of convolutional layers (conv), batch normalization (BN), leaky ReLU activation and max pooling, followed by one fully-connected as well as one softmax-output layer and is inspired by the keras example network for the CIFAR-10 dataset.
# B.2. Tumor growth
Tumor growth (Section 3.2) was classified using a two-laned convolutional neural network built analogously to the model from Katzmann et al. (2018) with baseline and followup being processed in one lane each. The network weights were initialized using autoencoder pretraining. The complete architecture is shown in Table 4.
# B.3. Liver lesion segmentation
The architecture for liver lesion segmentation (Section 3.3) is based on the U-Net approach from Ronneberger et al. (2015) with minor modifications. The full architecture is shown in Table 5.
<table><tr><td rowspan=1 colspan=2>Description</td><td rowspan=1 colspan=1>shape</td><td rowspan=1 colspan=1>filter size</td></tr><tr><td rowspan=1 colspan=2>input</td><td rowspan=1 colspan=1>(2,64,64,1)</td><td rowspan=1 colspan=1>1</td></tr><tr><td rowspan=2 colspan=1>2×</td><td rowspan=2 colspan=1>conv + BN + leaky ReLUmax poolingconv + BN + leaky ReLUmax poolingconv + BN + leaky ReLUmax poolingconv + BN + leaky ReLUmax poolingconv + BN + leaky ReLUfattendense+1BN +leaky ReLU</td><td rowspan=1 colspan=1>(64,64,8)</td><td rowspan=2 colspan=1>(5,5)1(5,5)1(5,5)=(5,5)1(5,5)1</td></tr><tr><td rowspan=1 colspan=1>(32,32,8)(32,32,16)(16,16,16)(16,16,24)(8,8,24)(8,8,32)(4,4,32)(4,4,40)(640,)(8,)</td></tr><tr><td rowspan=1 colspan=2>dense+BN + leaky ReLUdense+BN + leaky ReLU</td><td rowspan=1 colspan=1>(4,)(4,)</td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=1 colspan=2>softmax</td><td rowspan=1 colspan=1>(2,)</td><td rowspan=1 colspan=1></td></tr></table>
Table 4: Classifier architecture for tumor growth classification consisting of blocks of convolutional layers (conv), batch normalization (BN), leaky ReLU activation and max pooling layers, followed by two fully-connected as well as a softmax-output layer.
<table><tr><td rowspan=1 colspan=1>Description</td><td rowspan=1 colspan=1>shape</td><td rowspan=1 colspan=1>filter size</td></tr><tr><td rowspan=1 colspan=1>input</td><td rowspan=1 colspan=1>(256,256,1)</td><td rowspan=1 colspan=1></td></tr><tr><td rowspan=1 colspan=1>1 conv + BN + leaky ReLU max pooling</td><td rowspan=1 colspan=1>(256,256,4)(128,128,4)</td><td rowspan=1 colspan=1>(3,3)</td></tr><tr><td rowspan=1 colspan=1>2 conv +1BN+leakyReLUmaxpooling</td><td rowspan=1 colspan=1>(128,128,16)(64,64,16)</td><td rowspan=1 colspan=1>(3,3)</td></tr><tr><td rowspan=1 colspan=1>3 conv + BN + leaky ReLUmax pooling</td><td rowspan=1 colspan=1>(64,64,32)(32,32,32)</td><td rowspan=1 colspan=1>(3.3)</td></tr><tr><td rowspan=1 colspan=1>conv + BN +leakyReLU4 upsampling</td><td rowspan=1 colspan=1>(32,32,64)(64,64,64)</td><td rowspan=1 colspan=1>(3.3)</td></tr><tr><td rowspan=1 colspan=1>concat (3,4)conv + BN + leaky ReLU5 upsampling</td><td rowspan=1 colspan=1>(64,64,96)(64,64,32)(128,128,32)</td><td rowspan=1 colspan=1>(3,3)</td></tr><tr><td rowspan=1 colspan=1>concat (2,5)conv+1BN +leaky ReLU6 upsampling</td><td rowspan=1 colspan=1>(128,128,48)(128,128,16)(256,256,16)</td><td rowspan=1 colspan=1>(3.3)</td></tr><tr><td rowspan=1 colspan=1>concat(1,6)conv + BN + sig.</td><td rowspan=1 colspan=1>(256,256,20)(256,256,1)</td><td rowspan=1 colspan=1>(3.3)</td></tr></table>
Table 5: Segmentation network architecture used for liver lesion segmentation based on U-Net (Ronneberger et al., 2015). As in U-Net, the network convolves and downsamples the image with blocks of convolutional layers (conv), batch normalization (BN), and leaky ReLU activation. Afterwards the image is upsampled again and convolved with the information of the horizontal shortcuts (concat). The final output is generated using a sigmoid function (sig.).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475# UNSUPERVISED CIPHER CRACKING USING DISCRETE GANS
Aidan N. Gomez 1,2 aidan@cs.toronto.edu
Sicong Huang 1,2 huang@cs.toronto.edu
Ivan Zhang 2 ivan@ivanzhang.ca
Bryan M. Li 1,2 bryan@bryanli.io
Muhammad Osama 1,2 muhammad.osama@mcode.ca
Łukasz Kaiser 3 lukaszkaiser@google.com
1 Department of Computer Science, University of Toronto 2 FOR.ai 3 Google Brain
# ABSTRACT
This work details CipherGAN, an architecture inspired by CycleGAN used for inferring the underlying cipher mapping given banks of unpaired ciphertext and plaintext. We demonstrate that CipherGAN is capable of cracking language data enciphered using shift and Vigenere ciphers to a high degree of fidelity and for \` vocabularies much larger than previously achieved. We present how CycleGAN can be made compatible with discrete data and train in a stable way. We then prove that the technique used in CipherGAN avoids the common problem of uninformative discrimination associated with GANs applied to discrete data.
# 1 INTRODUCTION
Humans have been encoding messages for secrecy since before the ancient Greeks, and for the same amount of time, have been fascinated with trying to crack these codes using brute-force, frequency analysis, crib-dragging and even espionage. Simple ciphers have, in the past century, been rendered irrelevant in favor of the more secure encryption schemes enabled by modern computational resources. However, the question of cipher-cracking remains an interesting problem since it requires an intimate understanding of the structure in a language. Nearly all automated cipher cracking techniques have had to rely on a human-in-the-loop; grounding the automated techniques in a human’s preexisting knowledge of language to clean up the errors made by simple algorithms such as frequency analysis. Across a number of domains, the use of hand-crafted features has often been replaced by automatic feature extraction directly from data using end-to-end learning frameworks (Goodfellow et al., 2016). The question to be addressed is as follows:
Can a neural network be trained to deduce withheld ciphers from unaligned text, without the supplementation of preexisting human knowledge?
The implications for such a general framework would be far-reaching in the field of unsupervised translation, where each language can be treated as an enciphering of the other. The decoding of the Copiale cipher (Knight et al., 2011) stands as an excellent example of the potential for machine learning techniques to decode enciphered texts by treating the problem as language translation. The CycleGAN (Zhu et al., 2017) architecture is extremely general and we demonstrate our adaptation, CipherGAN, is capable of cracking ciphers to an extremely high degree of accuracy. CipherGAN requires little or no modification to be applied to plaintext and ciphertext banks generated by the user’s cipher of choice.
In addition to presenting a GAN that can crack ciphers, we contribute the following techniques:
• We show how to stabilize CycleGAN training: our CipherGAN achieves good performance in all training runs, compared to approximately $50 \%$ of runs for the original CycleGAN. We provide a theoretical description and analysis of the uninformative discrimination problem that impacts GANs applied to discrete data. • We introduce a solution to the above problem by operating in the embedding space and show that it works in practice.
# 1.1 SHIFT AND VIGENERE \` CIPHERS
The shift and Vigenere ciphers are well known historical substitution ciphers. The earliest known \` record of a substitution cipher is believed to have dated back to 58 BCE, when Julius Caesar replaced each letter in a message with the letter that was three places further down the alphabet (Singh, 2000).
 Figure 1: An example of a right-shift-3 cipher.
Using Figure 1, the message “attackatdawn” can be encrypted to “DWWDFNDWGDZQ”. This message can be easily deciphered by the intended recipient (who is aware of the particular shift number used) but looks meaningless to a third party. The shift cipher ensured secure communication between sender and receiver for centuries, until the ninth century polymath Al-Kindi introduced the concept of frequency analysis (Singh, 2000). He suggested that it would be possible to crack a cipher simply by analyzing the individual characters’ frequencies. For instance, in English the most frequently occurring letters are $\cdot _ { e } ,$ $( 1 2 . 7 \% )$ , $\cdot _ { t } ,$ $( 9 . 1 \% )$ and $\cdot _ { a } ,$ $( 8 . 2 \% )$ ; whereas $\mathbf { \dot { q } }$ , $\cdot _ { x } ,$ and $\cdot _ { z } ,$ each have frequency of less than $1 \%$ . Moreover, the code-breaker can also focus on bigrams of repeated letters; ‘ss’, ‘ee’, and ‘oo’ are the most common in English. This structure in language provides an exploit of efficiency to the code-breaker.
Polyalphabetic substitution ciphers, including the Vigenere cipher, were introduced to inhibit the \` use of n-gram frequency analysis in determining the cipher mapping. Instead, the encrypter further scrambles the message by using a separate shift cipher for each element of a key that is tiled to match the length of the plaintext. Increasing the key length greatly increases the number of possible combinations and thus prevents against basic frequency analysis. In the mid nineteenth century, Charles Babbage recognized that the length of the used key could be determined by counting the repetitions and spacing of sequences of letters in the cipher (Singh, 2000). Using the determined length, we can then apply frequency analysis on the index of the cipher base. This method makes it possible to break the Vigenere cipher, but is very time consuming and requires strong knowledge of \` the language itself.
There is a rich literature of automated shift-cipher cracking techniques (Ramesh et al., 1993; Forsyth & Safavi-Naini, 1993; Hasinoff, 2003; Knight et al., 2006; Verma et al., 2007; Raju et al., 2010; Knight et al., 2011) many of which achieve excellent results which is what one would expect from hand-crafted algorithms targeting specific ciphers and vocabularies. Work on automated cracking of polyalphabetic ciphers (Carroll & Martin, 1986; Toemeh & Arumugam, 2008; Omran et al., 2011) has seen similar success on small vocabularies. It is a difficult matter to compare the results of previous work with our own as their focus ranges from inferring cipher keys (Carroll & Martin, 1986; Ramesh et al., 1993; Omran et al., 2011), to inferring the mappings given limited quantities of ciphertext (determining unicity distance) (Carroll & Martin, 1986; Ramesh et al., 1993; Hasinoff, 2003; Verma et al., 2007), to analyzing the unicity distance required to solve small percentages of the cipher mappings (i.e. $20 \%$ in Carroll & Martin (1986)).
In comparison to these past works, we afford ourselves the advantage of an unconstrained corpus of ciphertext, however, we prescribe ourselves the following constraints: our model is not provided any prior knowledge of vocabulary element frequencies; and, no information about the cipher key is provided. Another complexity our work must overcome is our significantly larger vocabulary sizes; all previous work has addressed vocabularies of approximately 26 characters, while our model is capable of solving word-level ciphers with over 200 distinct vocabulary elements. As such, our methodology is notably ‘hands-off’ in comparison to previous work and can be easily applied to different forms of cipher, different underlying data and unsupervised text alignment tasks.
# 1.2 GANS AND WASSERSTEIN GANS
Generative Adversarial Networks (GANs) are a class of neural network architectures introduced by Goodfellow et al. (2014) as an alternative to optimizing likelihood under a true data distribution. Instead, GANs balance the optimization of a generator network which attempts to produce convincing samples from the data distribution, and a discriminator which is trained to distinguish between samples from the true data distribution and the generator’s synthetic samples. GANs have been shown to produce compelling results in the domain of image generation, but comparatively weak performance in domains using discrete data (discussed in Section 2).
The original GAN discriminator objective as introduced in Goodfellow et al. (2014) is:
$$D ^ { * } = \arg \operatorname* { m a x } _ { D } \mathbb { E } _ { x \sim \mathcal { X } } [ \log D ( x ) ] - \mathbb { E } _ { z \sim \mathcal { Z } } [ \log ( 1 - D ( F ( z ) ) ) ]$$
Where $F$ is the generator network and $D$ is the discriminator network. This loss is vulnerable to the problem of ‘mode collapse’ where the generative distribution collapses to produce a generating distribution with low diversity. In order to more broadly distribute the mass, the Wasserstein GAN (WGAN) objective (Arjovsky et al., 2017) considers the set of K-Lipschitz discriminator functions $D : X \mathbb { R }$ and minimizes the earth movers (1st Wasserstein) distance. The Lipschitz condition is enforced by clipping discriminators weights to fall within a predefined range.
$$D ^ { * } = \arg \operatorname* { m a x } _ { \| D \| _ { L } \leq K } \mathbb { E } _ { x \sim \mathcal { X } } [ D ( x ) ] - \mathbb { E } _ { z \sim \mathcal { Z } } [ D ( F ( z ) ) ]$$
An improved WGAN objective, introduced by Gulrajani et al. (2017), enforced the Lipschitz condition using a Jacobian regularization term instead of the originally proposed weight-clipping solution. This resulted in more stable training, avoiding capacity under-use and exploding gradients, and improved network performance over weight-clipping.
$$\begin{array} { r l } & { D ^ { * } = \arg \underset { D } { \operatorname* { m a x } } \mathbb { E } _ { x \sim \mathcal { X } } [ D ( x ) ] - \mathbb { E } _ { z \sim \mathcal { Z } } [ D ( F ( z ) ) ] + } \\ & { \qquad \quad \alpha \cdot \mathbb { E } _ { \hat { x } \sim \hat { \mathcal { X } } } [ ( \| \nabla _ { \hat { x } } D ( \hat { x } ) \| _ { 2 } - 1 ) ^ { 2 } ] } \end{array}$$
Here $\hat { \mathcal X }$ are samples taken along a line between the true data distribution $\mathcal { X }$ and the generator’s data distribution $\mathcal { X } _ { g } \overset { \cdot } { = } \{ F ( z ) | z \sim \bar { \mathcal { Z } } \}$ .
# 1.3 CYCLEGAN
CycleGAN (Zhu et al., 2017) is a generative adversarial network designed to learn a mapping between two data distributions without supervision. Three separate works (Zhu et al., 2017; Yi et al., 2017; Liu et al., 2017) share many of the core features we describe below, however, for simplicity we will refer to CycleGAN as the basis for our work as it is the most similar to our model. It acts on distributions $\mathcal { X }$ and $\mathcal { V }$ by using two mapping generators: $F : \mathcal { X } \mathcal { Y }$ and $G : \mathcal { V } \to \mathcal { X }$ ; and two discriminators: $D _ { \mathcal { X } } : \mathcal { X } [ 0 , 1 ]$ and $D y : \bar { \mathcal { Y } } \stackrel { \textstyle - } { \to } \bar { [ 0 , 1 ] }$ .
CycleGAN optimizes the standard GAN loss ${ \mathcal { L } } _ { \mathrm { G A N } }$ :
$${ \mathcal { L } } _ { \mathrm { G A N } } ( F , D _ { \mathcal { V } } , \chi , \mathcal { V } ) = \mathbb { E } _ { y \sim \mathcal { V } } [ \log D _ { \mathcal { V } } ( y ) ] + \mathbb { E } _ { x \sim \chi } [ \log ( 1 - D _ { \mathcal { V } } ( F ( x ) ) ) ]$$
While also considering a reconstruction loss, or ‘cycle’ loss $\mathcal { L } _ { \mathrm { c y c } }$ :
$$\begin{array} { r } { \mathcal { L } _ { \mathrm { c y c } } ( F , G , \mathcal { X } , \mathcal { Y } ) = \mathbb { E } _ { x \sim \mathcal { X } } [ \| G ( F ( x ) ) - x \| _ { 1 } ] + \mathbb { E } _ { y \sim \mathcal { Y } } [ \| F ( G ( y ) ) - y \| _ { 1 } ] } \end{array}$$
Taken together the losses are balanced using a hyperparameter $\lambda$ :
$$\begin{array} { r } { \mathcal { L } ( F , G , D _ { \mathcal { X } } , D _ { \mathcal { Y } } , \mathcal { X } , \mathcal { Y } ) = \mathcal { L } _ { \mathrm { G A N } } ( F , D _ { \mathcal { Y } } , \mathcal { X } , \mathcal { Y } ) + \mathcal { L } _ { \mathrm { G A N } } ( G , D _ { \mathcal { X } } , \mathcal { Y } , \mathcal { X } ) + \lambda \cdot \mathcal { L } _ { \mathrm { c y c } } ( F , G , \mathcal { X } , \mathcal { Y } ) } \end{array}$$
 Figure 2: Discriminators trained on the toy example of recognizing the bottom-right corner of a simplex as true data. From left to right the discriminators were regularized using: nothing; WGAN Jacobian norm regularization; and, the relaxed sampling technique.
This leads to the training objectives:
$$\begin{array} { r l } & { F ^ { * } = \arg \underset { F } { \operatorname* { m i n } } \mathcal { L } _ { \mathrm { c y c } } ( F , G , \mathcal { X } , \mathcal { Y } ) + \mathcal { L } _ { \mathrm { G A N } } ( F , D _ { \mathcal { Y } } , \mathcal { X } , \mathcal { Y } ) } \\ & { G ^ { * } = \arg \underset { G } { \operatorname* { m i n } } \mathcal { L } _ { \mathrm { c y c } } ( F , G , \mathcal { X } , \mathcal { Y } ) + \mathcal { L } _ { \mathrm { G A N } } ( G , D _ { \mathcal { X } } , \mathcal { Y } , \mathcal { X } ) } \\ & { D _ { \mathcal { X } } ^ { * } = \arg \underset { D _ { \mathcal { X } } } { \operatorname* { m a x } } \mathcal { L } _ { \mathrm { G A N } } ( G , D _ { \mathcal { X } } , \mathcal { Y } , \mathcal { X } ) } \\ & { D _ { \mathcal { Y } } ^ { * } = \arg \underset { D _ { \mathcal { Y } } } { \operatorname* { m a x } } \mathcal { L } _ { \mathrm { G A N } } ( F , D _ { \mathcal { Y } } , \mathcal { X } , \mathcal { Y } ) } \end{array}$$
CycleGAN uses $\mathcal { L } _ { \mathrm { c y c } }$ to avoid mode collapse by preserving reconstruction of mapping inputs from outputs. It has demonstrated excellent results in unpaired image translation between two visually similar categories. Our architecture is the first example of this unsupervised learning framework being successfully applied to discrete data such as language.
# 2 DISCRETE GANS
Applying GANs to discrete data generation is still an open research problem that has seen great interest and development. The primary difficulty with training discrete data generators in a GAN setting is the lack of a gradient through a discrete node in the computation graph. The alternatives to producing discrete outputs - for instance, generators producing a categorical distribution over discrete elements - are prone to uninformative discrimination (described below), in that, the discriminator may use an optimal discrimination criterion that is unrelated to the correctness of the re-discretized generated data. In our example of a continuous distribution over discrete elements, the produced samples all lie within the standard simplex $\Delta ^ { k }$ with dimension $k$ equal to the number of elements in the distribution. In this case, samples from the true data distribution always lie on a vertex $\mathbf { v } _ { i }$ of the simplex, while any sub-optimal generator will produce samples within the simplex’s interior ${ \Delta ^ { k } \backslash \{ \bf { v } _ { 1 } , . . . , \bf { v } _ { k } \} }$ . In this example, a discriminator which performs uninformative discrimination might evaluate a sample’s membership in the vertices of the simplex as an optimal discrimination criterion, which is entirely uninformative of the correctness of re-discretized samples from the generator.
A number of solutions to training generators with discrete outputs have been proposed: SeqGAN (Yu et al., 2017) uses the REINFORCE gradient estimate to train the generator; Boundary-seeking GANs (Hjelm et al., 2017) and maximum-likelihood augmented GANs (Che et al., 2017) proposed a gradient approximation with low bias and variance that resembles the REINFORCE (Williams, 1992) estimator. Gumbel-softmax GANs (Kusner & Hernandez-Lobato, 2016) replace discrete variables in ´ the simplex with continuous relaxations called Concrete (Maddison et al., 2016) or Gumbel-softmax (Jang et al., 2016) variables; WGANs (Arjovsky et al., 2017) were suggested as a remedy to the uninformative discrimination problem by ensuring that the discriminator’s rate of change with respect to its input is bound by some constant.
Our work utilizes both the Wasserstein GAN (Gulrajani et al., 2017; Arjovsky et al., 2017) and relaxation of discrete random variables (such as Concrete/Gumbel-softmax). It has been noted multiple times in implementations of CycleGAN as well as in the original paper itself that the architecture was sensitive to initialization and requires repeat attempts in order to converge to a satisfactory mapping (Bansal & Rathore, 2017; Sari, 2017). Our architecture suffered the same instability before the WGAN Jacobian norm regularization term was added to the discriminator’s loss. In addition, we found that having the discriminator operate over embedding space instead of directly over softmax vectors produced by our generator has improved performance.
Our hypothesis, which is justified by Proposition 1 below, is that the embedding vectors may act as continuous relaxations of discrete random variables as small, noisy updates are applied throughout training; Proposition 1 asserts that by replacing discrete random variables with continuous ones, our discriminator is prevented from arbitrarily approximating a Dirac delta distribution. Figure 2 shows simple discriminators trained on the toy task of identify a single vertex of a simplex as true data; it is clear that a lack of regularization leads to the discriminator collapsing to the vertex of the simplex, leaving approximately zero gradient everywhere; while the Jacobian regularization of Wasserstein GANs leads to the space covered by lines leading from the true data vertex to the generated data having a lower rate of change (note that the gradient is still close to zero in the remaining area of the simplex); and finally, replacing the discrete random variables of the true data with continuous samples about the vertex results in a much more gradual transition, which is desirable since it provides a stronger gradient signal from which to learn.
Unique to CycleGAN is the auxiliary cycle loss described in Section 1.3. The effect of this additional objective is the generated samples regularly being forced away from the discriminator’s minimum in favor of a mapping that better-satisfies reconstruction. For instance, it may be the case that the discriminator favors a particular cipher mapping that is not bijective; in this case, the model will receive a strong signal from the cycle loss away from the discriminator’s minimum. In these cases where the model moves against the gradient it receives from the discriminator it may be the case that this region has near zero curvature (as is visually discernible from Figure 2); this is because the WGAN curvature regularization (see Equation 3) has not been applied in this region.
‘Curvature’ here refers to the curvature of the discriminator’s output with respect to its input; this curvature determines the strength of the training signal received by the generator. Low curvature means little information for the generator to improve itself with. This motivates the benefits of having strong curvature globally, as opposed to linearly between the generators samples and the true data. Kodali et al. (2017) proposes regularizing in all directions about the generated samples, which would likely remedy the vanishing gradient in our case as well; for our experiments, the relaxed sampling technique proved effective. It should also be noted that Luc et al. (2016) propose something similar to relaxed sampling whereby they replace the ground-truth discrete tokens with a distribution over the vocabulary that distributes some of the mass across the remaining incorrect tokens.
Let us now introduce the definitions needed for the formal presentation of Proposition 1.
# Definitions.
• (Continuous relaxation of a discrete set). A continuous relaxation of a discrete set $\mathcal { X }$ is a proper, path-connected metric space $\overline { { \mathcal { X } } }$ satisfying $\chi _ { \mathrm { ~ C ~ } } \overline { { \mathcal { X } } }$ . • (Rediscretization function). A rediscretization function is an injective function $R : \overline { { \mathcal { X } } } \to \mathcal { X }$ from a continuous relaxation $\overline { { \mathcal { X } } }$ of discrete space $\mathcal { X }$ satisfying $\forall x \in \mathcal { X } , \exists \epsilon > 0$ s.t. $R \equiv$ $x$ on $B _ { \epsilon } [ x ]$ . Note that $R$ defines an equivalence relation in $\overline { { \mathcal { X } } }$ . • (Uninformative Discrimination). A discriminator $D _ { \mathcal { X } }$ is said to perform uninformative discrimination under rediscretization function $R$ if: $\exists x \in { \mathcal { X } } , { \bar { x } } \in { \overline { { \mathcal { X } } } }$ s.t. $R ( \bar { x } ) = x$ ) $\wedge$ $( D _ { \mathcal { X } } ( x ) \not \approx D _ { \mathcal { X } } ( \bar { x } ) )$ . • (Continuous relaxation of a function). A continuous relaxation of a function over discrete sets $F : \mathcal { X } \mathcal { V }$ is another function $\overline { { F } } : \overline { { \mathcal { X } } } \overline { { \mathcal { Y } } }$ (where $\overline { { \mathcal { X } } } , \overline { { \mathcal { V } } }$ are continuous relaxations of $x , y )$ such that $\overline { F }$ is continuous and ${ \overline { { F } } } ( x ) = F ( x ) , \forall x \in { \mathcal { X } }$ .
The following proposition (proved in the Appendix) forms the theoretical basis of the technique.
Proposition 1 (Reliable Fooling Via Relaxation).
Given:
• discrete spaces $\mathcal { X } , \mathcal { y }$ and continuous relaxations $\overline { { \mathcal { X } } } , \overline { { \mathcal { V } } }$ • generators $F : \overline { { \mathcal { X } } } \overline { { \mathcal { V } } } , G : \overline { { \mathcal { V } } } \overline { { \mathcal { X } } }$ bijections satisfying $F = G ^ { - 1 }$ • discrete discriminators $D _ { \mathcal { X } } , D _ { \mathcal { Y } }$ both optimal for fixed $F , G$ • rediscretization functions $R _ { \mathcal { X } } , R _ { \mathcal { Y } }$
Suppose: $F$ is approximately volume preserving in a small region about each $x \in \mathcal { X }$ . Consequently the same is true for $G$ about each $y \in \mathcal { V }$ .
If: during training, we replace discrete random variables from $\mathcal { X }$ which lie in the continuous metric space $\overline { { \mathcal { X } } }$ with samples from regions about them.
Then: the optimal relaxed discriminators $D _ { \overline { { \mathcal { X } } } }$ and $D _ { \overline { { { y } } } }$ have a non-empty region about each $x \in \mathcal { X }$ and $y \in \mathcal { V }$ where they are expected to assign values close to $D _ { \mathcal { X } } ( x )$ and $D _ { \mathcal { Y } } ( y )$ .
Figure 3 compares a model trained with embedding vectors versus one with only the softmax outputs. It becomes clear on a harder task, such as Vigenere, that the embeddings vastly outperforms \` softmax in terms of speed of convergence and final accuracy; however we found that the simpler task of a shift cipher showed little difference between embeddings and softmax, suggesting an increase in task complexity increases the benefits provided by the stronger gradient signal of embeddings.
# 3 METHOD
# 3.1 CIPHERGAN
GANs applied to text data have yet to produce truly convincing results (Kawthekar et al.). Previous attempts at discrete sequence generation with GANs have generally utilized a generator outputting a probability distribution over the token space (Gulrajani et al., 2017; Yu et al., 2017; Hjelm et al., 2017). This leads to the discriminator receiving a sequence of discrete random variables from the data distribution, and a sequence of continuous random variables from the generator distribution; making the task of discrimination trivial and uninformative of the underlying data distribution. In order to avoid such a scenario, we perform all discrimination within the embedding space by allowing the generator’s output distribution to define a convex combination of corresponding embeddings. This leads to the following losses:
$$\begin{array} { r l } & { \mathcal { L } _ { \mathrm { G A N } } ( F , D _ { \mathcal { V } } , \boldsymbol { \chi } , \mathcal { V } ) = \mathbb { E } _ { \boldsymbol { y } \sim \mathcal { V } } [ \log D _ { \mathcal { V } } ( \boldsymbol { y } \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) ] } \\ & { \qquad + \mathbb { E } _ { \boldsymbol { x } \sim \mathcal { X } } [ \log ( 1 - D _ { \mathcal { V } } ( \boldsymbol { F } ( \boldsymbol { x } \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) ) ] } \\ & { \qquad \mathcal { L } _ { \mathrm { c y c } } ( F , G , \boldsymbol { \chi } , \mathcal { V } ) = \mathbb { E } _ { \boldsymbol { x } \sim \mathcal { X } } [ \| G ( F ( \boldsymbol { x } \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) - \boldsymbol { x } \| _ { 1 } ] } \\ & { \qquad + \mathbb { E } _ { \boldsymbol { y } \sim \mathcal { Y } } [ \| F ( G ( \boldsymbol { y } \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) - \boldsymbol { y } \| _ { 1 } ] } \end{array}$$
We perform an inner product between the embeddings $W _ { E m b }$ and the one-hot vectors in $x$ as well as between the embeddings and the softmax vectors produced by generators $F$ and $G$ . The former is equivalent to a lookup operation over the table of embedding vectors, while the latter is a convex combination between all vectors in the vocabulary. The embeddings $W _ { E m b }$ are trained at each step to minimize $\mathcal { L } _ { \mathrm { c y c } }$ and maximize $\mathcal { L } _ { \mathrm { G A N } }$ , meaning the embeddings are easily mapped from and are easy to discriminate. As was discussed in Section 2, training with the above loss functions was unstable, with approximately three of every four experiments failing to produce compelling results. This is a problem we observed with the original CycleGAN horse-zebra experiment, and one that has been noted by multiple re-implementations online (Bansal & Rathore, 2017; Sari, 2017). We were able to significantly increase the stability by training the discriminator loss along with the Lipschitz conditioning term from the improved Wasserstein GAN (Gulrajani et al., 2017) (see Equation 3 and Fedus et al. (2017)), resulting in the following loss (DualGAN (Yi et al., 2017) opted to use weight-clipping to enforce the Lipschitz condition):
$$\begin{array} { r l } & { \mathcal { L } _ { \mathrm { G A N } } ( F , D _ { \mathcal { V } } , \boldsymbol { \chi } , \mathcal { V } ) = \mathbb { E } _ { y \sim \mathcal { V } } [ D _ { \mathcal { V } } ( \boldsymbol { y } \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) ] } \\ & { \qquad - \mathbb { E } _ { \boldsymbol { x } \sim \boldsymbol { x } } [ D _ { \mathcal { V } } ( F ( \boldsymbol { x } \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) \cdot \boldsymbol { W } _ { E m b } ^ { \top } ) ] } \\ & { \qquad + \alpha \cdot \mathbb { E } _ { \hat { \boldsymbol { y } } \sim \hat { \mathcal { V } } } [ ( \| \nabla _ { \hat { \boldsymbol { y } } } D _ { \mathcal { V } } ( \hat { \boldsymbol { y } } ) \| _ { 2 } - 1 ) ^ { 2 } ] } \end{array}$$
As a consequence of Proposition 1, discriminators trained on non-stationary embeddings will be unable to approximate Dirac delta distributions to arbitrary accuracy; implying there are dedicated ‘safe-zones’ about members of $\mathcal { X }$ where the generator can reliably fool the discriminator and uninformative discrimination is prevented.
In our experiments, we jointly train the embedding vectors as parameters of the model. The gradient updates applied to these vectors introduces noise between training iterations; we observed that embedding vectors tend to remain in a bounded region after the initial steps of training. We found
<table><tr><td>Work</td><td>Ciphertext Length</td><td>Accuracy</td></tr><tr><td>Hasinoff (2003)</td><td>500</td><td>~ 97%</td></tr><tr><td>Forsyth& Safavi-Naini (1993)</td><td>5000</td><td>~ 100%</td></tr><tr><td>Ramesh et al. (1993)</td><td>160</td><td>~ 78.5%</td></tr><tr><td>Verma et al. (2007)</td><td>1000</td><td>~ 87%</td></tr></table>
Table 1: Previous results on automated shift cipher cracking with limited ciphertext length.
that simply replacing the data with embedding vectors had a similar effect to performing the random sampling described in Proposition 1 (see Figure 3).
# 4 EXPERIMENTS
# 4.1 DATA
Our experiments use plaintext natural language samples from the Brown English text dataset (Francis $\&$ Kucera, 1979). We generate $2 *$ batch size plaintext samples, the first half are fed as the CycleGAN’s $\mathcal { X }$ distribution and the second half is passed through the cipher of choice and fed as the $\mathcal { V }$ distribution.
For our natural language plaintext data we used the Brown English-language corpus which consists of over one million words in 57340 sentences. We experiment with both word-level ”Brown-W” and character-level ”Brown- $\mathbf { \vec { C } } ^ { \mathbf { \vec { \mu } } }$ vocabularies. For word-level vocabularies, we control the size of the vocabulary by taking the top $k$ most frequent words and introducing an ‘unknown’ token which we use to replace all words that are not within the taken vocabulary. We demonstrate our method’s ability to scale to large vocabularies using the word-level vocabularies; more modern enciphering techniques rely on large substitution-boxes (S-boxes) with many (often hundreds of) elements.
# 4.2 TRAINING
As in Zhu et al. (2017) we replace the log-likelihood loss with a squared difference loss which was originally introduced by Mao et al. (2016). The original motivation for this replacement was improved stability in training and avoidance of the vanishing gradients problem. In this work we found the effect on training stability substantial.
$$\begin{array} { r l } & { \mathcal { L } _ { \mathrm { G A N } } ( F , D y , \mathcal { X } , \mathcal { Y } ) = \mathbb { E } _ { y \sim \mathcal { Y } } [ ( D y ( y \cdot W _ { E m b } ^ { \top } ) ) ^ { 2 } ] } \\ & { \qquad + \mathbb { E } _ { x \sim \mathcal { X } } [ ( 1 - D _ { \mathcal { V } } ( F ( x \cdot W _ { E m b } ^ { \top } ) \cdot W _ { E m b } ^ { \top } ) ) ^ { 2 } ] } \\ & { \qquad + \alpha \cdot \mathbb { E } _ { \hat { y } \sim \hat { \mathcal { Y } } } [ ( 1 - \| \nabla _ { \hat { y } } D y ( \hat { y } ) \| _ { 2 } ) ^ { 2 } ] } \end{array}$$
Hence, our total loss is:
$$\begin{array} { r l } { \mathcal { L } _ { \mathrm { T o t a l } } ( F , G , D _ { \mathcal { X } } , D _ { \mathcal { Y } } , \mathcal { X } , \mathcal { Y } ) = \mathcal { L } _ { \mathrm { c y c } } ( F , G , \mathcal { X } , \mathcal { Y } ) } & { } \\ { + \mathcal { L } _ { \mathrm { G A N } } ( F , D _ { \mathcal { V } } , \mathcal { X } , \mathcal { Y } ) } & { } \\ { + \mathcal { L } _ { \mathrm { G A N } } ( G , D _ { \mathcal { X } } , \mathcal { X } , \mathcal { Y } ) } \end{array}$$
We adapted the convolutional architecture for the generator and discriminator directly from Zhu et al. (2017). We simply replace all two dimensional convolutions with the one dimension variant and reduce the filter sizes in our generators to 1 (pointwise convolutions). Convolutional neural networks have recently been shown to be highly effective on language tasks and can speed up training significantly (Zhang & LeCun, 2015; Kalchbrenner et al., 2016; Yu et al., 2017). Both our generators and discriminators receive a sequence of vectors in embedding space; our generators produce a softmax distribution over the vocabulary, while our discriminator produces a scalar output. For all our experiments we use a cycle loss with regularization coefficient $\lambda = 1$ . In order to be compatible with the WGAN we replace batch normalization (Ioffe & Szegedy, 2015) with layer normalization (Ba et al., 2016). We train using the Adam optmizer (Kingma & Ba, 2014) with batch size 64 and learning rate $2 e - 4$ , $\beta _ { 1 } = 0$ and $\beta _ { 2 } = 0 . 9$ . Our learning rate is exponentially warmed up to $2 e - 4$ over 2500 steps, and held constant thereafter. We use learned embedding vectors with 256 dimensions. The WGAN Lipschitz conditioning parameter was set to $\alpha = 1 0$ as was prescribed in Gulrajani et al. (2017).
 Figure 3: Left: Comparison of different timing techniques for Brown-C Vigenere. Right: Compari- \` son of embedding vs. raw softmax on Brown-W with vocab size of 200.
Table 2: Average proportion of characters correctly mapped in a given sequence. The “Freq. Analysis” column is simple frequency analysis applied to the same corpus our model observes. For Vigenere we also show the score if the key were known (note: the key is left unknown to our \` model).
<table><tr><td>Data Vocab size</td><td>Brown-W 10</td><td>Brown-W 200</td><td>Brown-C 58</td><td>Freq. Analysis (With Key) 58</td><td>200</td></tr><tr><td>Cipher</td><td colspan="5">Shift/Permutation</td></tr><tr><td>Acc.</td><td>100%</td><td>98.7%</td><td>99.8%</td><td>80.9%</td><td>44.5%</td></tr><tr><td>Cipher</td><td colspan="5">Vigenere (Key: “345")</td></tr><tr><td>Acc.</td><td>99.7%</td><td>75.7%</td><td>99.0%</td><td>9.6% (78.1%)</td><td><0.1% (44.3%)</td></tr></table>
For the Vigenere cipher, positional information is critical to the network being able to perform the \` mapping. In order to facilitate this we experimented with adding the timing signal described in Vaswani et al. (2017) (”Transformer Timing” in Figure 3) and found that performance increased relative to no explicit timing signal; we found that the best option was concatenating a learned positional embedding vector specific to each position onto the sequence (”Concat Timing” in Figure 3), this dramatically improved performance, however this means that the architecture can not generalize to sequences longer than those in the training set. A potential solution to the issue of generalizing to longer sequences would be making a ’soft’ choice at each position for which positional embedding vector to concatenate using a softmax distribution over a set of embedding vectors larger than the expected key length, however, we leave this to future work.
# 4.3 DISCUSSION
Table 2 shows that CipherGAN was able to solve shift ciphers to near flawless accuracy, with all three vocabulary sizes being easily decoded by the model. CipherGAN performs extremely well on Vigenere, achieving excellent results on the character-level cipher and strong results on the chal- \` lenging word-level cipher with a vocabulary size of 200. The vocabulary size of 58 for our character level, containing punctuation and special characters, is more than double what has been previously explored. In comparison to the original CycleGAN architecture, we found CipherGAN to be extremely consistent in training and notably insensitive to the random initialization of weights; we attribute this stability to the Jacobian norm regularization term.
For both ciphers, the first mappings to be correctly determined were those of the most frequently occurring vocabulary elements, suggesting that the network does indeed perform some form of frequency analysis to distinguish outlier frequencies in the two banks of text. Another interesting observation is that of the mistakes made by the network: the network would frequently confuse punctuation marks with one another, perhaps suggesting that these vocabulary elements’ skip-gram signatures were similar enough to lead to the repeated confusion observed across many training runs.
# 5 CONCLUSION
CipherGAN is a compelling demonstration of the potential generative adversarial networks hold to act on discrete data to solve difficult tasks that rely on an extremely sensitive and nuanced discrimination criterion. Our work serves to redouble the promise of the CycleGAN architecture for unsupervised alignment tasks for multiple classes of data. CipherGAN presents an algorithm that is both stable and consistent in training, improving upon past implementations of the CycleGAN architecture. Our work theoretically motivates – and empirically confirms – the use of continuous relaxations of discrete variables, not only to facilitate the flow of gradients through discrete nodes, but also to prevent the oft-observed phenomena of uninformative discrimination. CipherGAN is highly general in its structure and can be directly applied to a variety of unsupervised text alignment tasks, without excess burden of adaptation. On the one hand, CipherGAN is an early step towards the goal of unsupervised translation between languages and has shown excellent performance on the simplified task of cipher map inference. On the other hand, the methods we introduce can be used more broadly in the field of text generation with adversarial networks.
# ACKNOWLEDGMENTS
Our thanks goes to Roger Grosse and Kelvin Shuangjian Zhang for their advice and support throughout. We also thank Otavio Good and Ian Goodfellow for meaningful early discussions and direction; as well as Michal Wiszniewski for his assistance in developing the code upon which the experiments were run. This work was made possible thanks to the AI Grant, which provided generous support throughout.
# REFERENCES
Martin Arjovsky, Soumith Chintala, and Leon Bottou. Wasserstein gan. ´ arXiv preprint arXiv:1701.07875, 2017. Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016. Hardik Bansal and Archit Rathore. Understanding and implementing cyclegan in tensorflow. https://hardikbansal.github.io/CycleGANBlog/, 2017. John M Carroll and Steve Martin. The automated cryptanalysis of substitution ciphers. Cryptologia, 10(4):193–209, 1986. Tong Che, Yanran Li, Ruixiang Zhang, R Devon Hjelm, Wenjie Li, Yangqiu Song, and Yoshua Bengio. Maximum-likelihood augmented discrete generative adversarial networks. arXiv preprint arXiv:1702.07983, 2017. William Fedus, Mihaela Rosca, Balaji Lakshminarayanan, Andrew M. Dai, Shakir Mohamed, and Ian Goodfellow. Many paths to equilibrium: Gans do not need to decrease a divergence at every step, 2017. William S Forsyth and Reihaneh Safavi-Naini. Automated cryptanalysis of substitution ciphers. Cryptologia, 17(4):407–418, 1993. W Nelson Francis and Henry Kucera. Brown corpus manual. Brown University, 2, 1979. Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, and Yoshua Bengio. Generative adversarial nets. In Advances in neural information processing systems, pp. 2672–2680, 2014. Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Deep Learning. MIT Press, 2016. http: //www.deeplearningbook.org.
Ishaan Gulrajani, Faruk Ahmed, Martin Arjovsky, Vincent Dumoulin, and Aaron Courville. Improved training of wasserstein gans. arXiv preprint arXiv:1704.00028, 2017.
Sam Hasinoff. Solving substitution ciphers. Department of Computer Science, University of Toronto, Tech. Rep, 2003.
R Devon Hjelm, Athul Paul Jacob, Tong Che, Kyunghyun Cho, and Yoshua Bengio. Boundaryseeking generative adversarial networks. arXiv preprint arXiv:1702.08431, 2017.
Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. In International Conference on Machine Learning, pp. 448–456, 2015.
Eric Jang, Shixiang Gu, and Ben Poole. Categorical reparameterization with gumbel-softmax. arXiv preprint arXiv:1611.01144, 2016.
Nal Kalchbrenner, Lasse Espeholt, Karen Simonyan, Aaron van den Oord, Alex Graves, and Koray Kavukcuoglu. Neural machine translation in linear time. arXiv preprint arXiv:1610.10099, 2016.
Prasad Kawthekar, Raunaq Rewari, and Suvrat Bhooshan. Evaluating generative models for text generation.
Diederik P. Kingma and Jimmy Ba. Adam: A method for stochastic optimization. CoRR, abs/1412.6980, 2014. URL http://arxiv.org/abs/1412.6980.
Kevin Knight, Anish Nair, Nishit Rathod, and Kenji Yamada. Unsupervised analysis for decipherment problems. In Proceedings of the COLING/ACL on Main conference poster sessions, pp. 499–506. Association for Computational Linguistics, 2006.
Kevin Knight, Beata Megyesi, and Christiane Schaefer. The copiale cipher. In ´ Proceedings of the 4th Workshop on Building and Using Comparable Corpora: Comparable Corpora and the Web, pp. 2–9. Association for Computational Linguistics, 2011.
Naveen Kodali, Jacob Abernethy, James Hays, and Zsolt Kira. How to train your dragan. arXiv preprint arXiv:1705.07215, 2017.
Matt J Kusner and Jose Miguel Hern ´ andez-Lobato. Gans for sequences of discrete elements with ´ the gumbel-softmax distribution. arXiv preprint arXiv:1611.04051, 2016.
Ming-Yu Liu, Thomas Breuel, and Jan Kautz. Unsupervised image-to-image translation networks. arXiv preprint arXiv:1703.00848, 2017.
Pauline Luc, Camille Couprie, Soumith Chintala, and Jakob Verbeek. Semantic segmentation using adversarial networks. arXiv preprint arXiv:1611.08408, 2016.
Chris J Maddison, Andriy Mnih, and Yee Whye Teh. The concrete distribution: A continuous relaxation of discrete random variables. arXiv preprint arXiv:1611.00712, 2016.
Xudong Mao, Qing Li, Haoran Xie, Raymond YK Lau, Zhen Wang, and Stephen Paul Smolley. Least squares generative adversarial networks. arXiv preprint ArXiv:1611.04076, 2016.
SS Omran, AS Al-Khalid, and DM Al-Saady. A cryptanalytic attack on vigenere cipher using \` genetic algorithm. In Open Systems (ICOS), 2011 IEEE Conference on, pp. 59–64. IEEE, 2011.
Bhadri Msvs Raju et al. Decipherment of substitution cipher using enhanced probability distribution. International Journal of Computer Applications, 5(8):34–40, 2010.
RS Ramesh, G Athithan, and K Thiruvengadam. An automated approach to solve simple substitution ciphers. Cryptologia, 17(2):202–218, 1993.
Eyyb Sari. tensorflow-cyclegan. https://github.com/Eyyub/tensorflow-cyclegan, 2017.
Simon Singh. The Code Book: The Science of Secrecy from Ancient Egypt to Quantum Cryptography. Anchor, 2000.
Ragheb Toemeh and Subbanagounder Arumugam. Applying genetic algorithms for searching keyspace of polyalphabetic substitution ciphers. International Arab Journal of Information Technology (IAJIT), 5(1), 2008.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. arXiv preprint arXiv:1706.03762, 2017.
AK Verma, Mayank Dave, and RC Joshi. Genetic algorithm and tabu search attack on the monoalphabetic substitution cipher i adhoc networks. In Journal of Computer science. Citeseer, 2007.
Ronald J Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine learning, 8(3-4):229–256, 1992.
Zili Yi, Hao Zhang, Ping Tan Gong, et al. Dualgan: Unsupervised dual learning for image-to-image translation. arXiv preprint arXiv:1704.02510, 2017.
Lantao Yu, Weinan Zhang, Jun Wang, and Yong Yu. Seqgan: Sequence generative adversarial nets with policy gradient. In AAAI, pp. 2852–2858, 2017.
Xiang Zhang and Yann LeCun. Text understanding from scratch. arXiv preprint arXiv:1502.01710, 2015.
Jun-Yan Zhu, Taesung Park, Phillip Isola, and Alexei A Efros. Unpaired image-to-image translation using cycle-consistent adversarial networks. arXiv preprint arXiv:1703.10593, 2017.
# APPENDIX
A ARCHITECTURAL DETAILS
For both the generator and discriminator architectures below, we assume the network is provided with a sequence of $N$ tokens denoted data laying in a $K$ -simplex. Therefore data is an $N$ by $K$ matrix.
For simplicity we define the following notation:
$$\begin{array} { r l } & { \mathrm { \mathrm { ~ 5 o n v L a y e r } } _ { f _ { c , f s = 1 , s = 1 } } ( x ) = R e L U ( L a y e r N o r m ( C o n v 1 D _ { f c , f s } ( x ) ) ) } \\ & { \qquad \mathrm { R e s B l o c k } _ { f _ { c , f s = 1 } } ( x ) = R e L U ( L a y e r N o r m ( x + C o n v 1 D _ { f c , f s } ( C o n v 1 D _ { f c , f s } ( x ) ) ) ) } \\ & { \mathrm { C o n v S t a c k } _ { n , f c , f s = 1 } ( x ) = } \\ & { \qquad \mathrm { C o n v L a y e r } _ { 1 , f s } \circ \mathrm { C o n v L a y e r } _ { 2 ^ { 1 } \cdot f c , f s , 2 } \circ \cdot \cdot \circ \mathrm { C o n v L a y e r } _ { 2 ^ { n } \cdot f c , f s , 2 } \circ \mathrm { C o n v L a y e r } _ { f c , f s , 2 } ( x ) } \end{array}$$
# A.1 GENERATOR
We define the following constants:
• $f c = 3 2$ : The base ’filter count‘, or number of filters in a convolution layer • $f s = 1$ : The ’filter size‘, or width of weight kernel used in convolution layers • $v s = 1$ : The ’vocab size‘, or number of elements in the vocabulary • $s = 1$ : The stride of the convolution layers • $E = 1 0 0$ : The dimensionality of the embedding vectors • $T = 1 0 0$ : The dimensionality of the concat timing weights
First, we first look up embedding vectors corresponding to the observed tokens. This is performed as a simple inner-product between data and a learning weight matrix of embeddings $W _ { \mathrm { E m b } } ^ { \mathbf { \Upsilon } ^ { \bullet } } \in \mathbb { R } ^ { K \times E }$ :
$$x = \mathrm { d a t a } \cdot W _ { \mathrm { E m b } }$$
Next, a timing signal is added using either:
• The Transformer method:
$$\begin{array} { c } { { \mathrm { s i g n a l } _ { n , 2 k } = \sin ( n / 1 e 5 ^ { 2 k / K } ) } } \\ { { \mathrm { s i g n a l } _ { n , 2 k + 1 } = \cos ( n / 1 e 5 ^ { 2 k / K } ) } } \\ { { \mathrm { t i m i n g } ( x ) = x + \mathrm { s i g n a l } } } \end{array}$$
• The concat method:
$$\begin{array} { r l } & { W _ { \mathrm { t i m e } } \in \mathbb { R } ^ { N \times T } } \\ & { t = \mathsf { t i m i n g } ( x ) = [ x \| _ { 2 } W _ { \mathrm { t i m e } } ] } \end{array}$$
Where $W _ { \mathrm { t i m e } }$ are trained parameters and $[ \cdot | | _ { k } \cdot ]$ denotes concatenation along the $k ^ { \mathrm { { t h } } }$ axis.
Then the generator is defined as follows:
$$\begin{array} { r l } & { \phantom { \frac { 1 } { 2 } } a ( x ) = \mathrm { C o n v L a y e r } _ { 4 \cdot f c } ( \mathrm { C o n v L a y e r } _ { 2 \cdot f c , f s } ( \mathrm { C o n v L a y e r } _ { f c } ( x ) ) ) } \\ & { \phantom { \frac { 1 } { 2 } } b ( x ) = \mathrm { R e s B l o c k } _ { 4 \cdot f c } ^ { ( 5 ) } ( x ) } \\ & { \circ \mathrm { u t } ( t ) = \mathrm { S o f t m a x } ( \mathrm { C o n v L a y e r } _ { v s } ( b ( a ( t ) ) ) ) } \end{array}$$
# A.2 DISCRIMINATOR
We define the following constants:
• $f c = 3 2$ : The base ’filter count‘, or number of filters in a convolution layer • $f s = 1 5$ : The ’filter size‘, or width of weight kernel used in convolution layers • $n = 5$ : The depth of the convolutional stack
Similar to the generator, a timing signal is added first. Leading to the following discriminator:
$$\mathsf { o u t } ( t ) = \mathbf { C o n v S t a c k } _ { n , f c , f s } ( \mathsf { d r o p o u t } _ { 0 . 5 } ( t ) )$$
B PROOF OF PROPOSITION 1
Proposition 1 (Reliable Fooling Via Relaxation).
Given:
• discrete spaces $\mathcal { X } , \mathcal { y }$ and continuous relaxations $\overline { { \mathcal { X } } } , \overline { { \mathcal { V } } }$ • generators $F : \overline { { \mathcal { X } } } \overline { { \mathcal { V } } } , G : \overline { { \mathcal { V } } } \overline { { \mathcal { X } } }$ bijections satisfying $F = G ^ { - 1 }$ • discrete discriminators $D _ { \mathcal { X } } , D _ { \mathcal { Y } }$ both optimal for fixed $F , G$ • rediscretization functions $R _ { \mathcal { X } } , R _ { \mathcal { Y } }$
Suppose: $F$ is approximately volume preserving in a small region about each $x \in \mathcal { X }$ . Consequently the same is true for $G$ about each $y \in \mathcal { V }$ . If: during training, we replace discrete random variables from $\mathcal { X }$ which lie in the continuous metric space $\overline { { \mathcal { X } } }$ with samples from regions about them. Then: the optimal relaxed discriminators $D _ { \overline { { \mathcal { X } } } }$ and $D _ { \overline { { { y } } } }$ have a non-empty region about each $x \in \mathcal { X }$ and $y \in \mathcal { V }$ where they are expected to assign values close to $D _ { \mathcal { X } } ( x )$ and $D _ { \mathcal { Y } } ( y )$ .
Proof. We’ll prove one side of the CipherGAN as the proof for both sides are similar.
Given bijective function between continuous relaxations of $\mathcal { X }$ and $\mathcal { V }$ : $F : ( \overline { { \mathcal { X } } } , d _ { \overline { { \mathcal { X } } } } ) ( \overline { { \mathcal { V } } } , d _ { \overline { { \mathcal { V } } } } )$ , where $\mathcal { X }$ and $\mathcal { V }$ contain finite sequences (length $n$ ) of vectors laying on the vertices of the simplex $\Delta ^ { k }$ , and are supports of data distributions $p _ { \mathscr { X } } , p _ { \mathscr { Y } }$ respectively.
Let:
• $\overline { { \mathcal { X } } } = \overline { { \mathcal { Y } } } = \underbrace { \Delta ^ { k } \times \cdots \times \Delta ^ { k } } _ { n }$ with $k$ equal to the number of elements in our vocabulary. • the rediscretization function $R _ { { \mathcal { X } } } : { \overline { { { \mathcal { X } } } } } { \mathcal { X } }$ : $R _ { { \mathcal K } } ( \bar { x } ) = \arg \operatorname* { m i n } _ { x \in { \mathcal K } } d _ { \overline { { { \mathcal K } } } } ( \bar { x } , x )$ ; similarly for $R _ { \mathcal { Y } }$ .
Now, for each $x \in \mathcal { X }$ consider the infinite set $S _ { x }$ with cardinality of the continuum constructed according to:
Equivalently,
$$S _ { x } = R _ { \chi } ^ { - 1 } ( x ) \cap F ^ { - 1 } ( R _ { \ y } ^ { - 1 } ( F ( x ) ) )$$
Note. $S _ { x }$ is never of cardinality less than the continuum since the following is implied by the definitions of $R _ { \mathcal { X } }$ , $S _ { x }$ and the fact that $F$ is continuous: $x \in \mathcal { X } \implies x \in S _ { x } \wedge \exists$ closed ball $B _ { \epsilon } [ x ]$ with radius
$$0 < \epsilon < \operatorname* { m i n } _ { \substack { z \in \overline { { \mathcal X } } } } d _ { \mathcal X } ( x , z )$$
So, for each element $x \in \mathcal { X }$ there exists a closed set of points in $\overline { { \mathcal { X } } }$ which are rediscretized, under $R _ { \mathcal { X } }$ , to $x$ . Since $S _ { x }$ is a Borel Set we can sample uniformly from it. Therefore, during training suppose we replace each element of $x \in \mathcal { X }$ with a sample $\bar { x } \sim S _ { x }$ :
We begin with the discrete objective:
$$\sum _ { x \in \mathcal { X } } p _ { \mathcal { X } } ( x ) \log ( D _ { \mathcal { X } } ( x ) ) + p _ { F } ( x ) \log ( 1 - D _ { \mathcal { X } } ( x ) )$$
As was noted in Goodfellow et al. (2014), this objective is optimized in $D _ { \mathcal { X } } : \mathcal { X } [ 0 , 1 ]$ when:
$$D _ { \mathcal { X } } = \frac { p _ { \mathcal { X } } } { p _ { \mathcal { X } } + p _ { G } }$$
which is undesirable as $p _ { \mathcal { X } }$ is a sum of Dirac delta distributions $\begin{array} { r } { p _ { \mathcal { X } } ( x ) = \sum _ { x _ { i } \in \mathcal { X } } \delta _ { x _ { i } } ( x ) } \end{array}$ and lacks a non-zero gradient to train the generator function with. Instead, let us consider a continuous relaxation $D _ { \overline { { \mathcal { X } } } } : \overline { { \mathcal { X } } } [ 0 , 1 ]$ of the discriminator $D _ { \mathcal { X } }$ and observe where it optimizes.
Suppose $\forall x \in \mathcal { X } , \exists \epsilon _ { x } \geq 0 , \forall \bar { x } \in S _ { x }$
$$\left( 1 - \epsilon _ { x } \right) \leq \left| \nabla _ { \bar { x } } F ( \bar { x } ) \right| \leq \left( 1 + \epsilon _ { x } \right)$$
That is, suppose $F$ is approximately volume preserving within a small region about each $x \in \mathcal { X }$ .
Lemma 1. $\forall y \in \mathcal { Y } , G ( S _ { y } ) = S _ { G ( y ) }$
Proof of Lemma $^ { l }$ . For all $y \in \mathcal { V }$ with $G ( y ) = x \Leftrightarrow y = F ( x )$ :
$$\begin{array} { r l } & { G ( S _ { y } ) = G [ R _ { y } ^ { - 1 } ( y ) \cap G ^ { - 1 } ( R _ { \chi } ^ { - 1 } ( G ( y ) ) ) ] } \\ & { \qquad = G ( R _ { y } ^ { - 1 } ( y ) ) \cap G ( G ^ { - 1 } ( R _ { \chi } ^ { - 1 } ( G ( y ) ) ) ) } \\ & { \qquad = G ( R _ { y } ^ { - 1 } ( y ) ) \cap R _ { \chi } ^ { - 1 } ( G ( y ) ) } \\ & { \qquad = F ^ { - 1 } ( R _ { y } ^ { - 1 } ( F ( x ) ) ) \cap R _ { \chi } ^ { - 1 } ( x ) } \\ & { \qquad = S _ { x } = S _ { G ( y ) } } \end{array}$$
Corollary 1.
$$\int _ { { \bar { x } } \sim S _ { G ( y ) } } { \frac { 1 } { \left| S _ { G ( y ) } \right| } } d { \bar { x } } = \int _ { { \bar { x } } \sim G ( S _ { y } ) } { \frac { \left| \nabla _ { \bar { x } } F ( { \bar { x } } ) \right| } { \left| S _ { y } \right| } } d { \bar { x } }$$
Proof of Corollary 1.
$$\begin{array} { r l } { \displaystyle \int _ { \bar { x } \sim S _ { G ( y ) } } \frac { 1 } { \vert S _ { G ( y ) } \vert } d \bar { x } = 1 = \int _ { \bar { y } \sim S _ { y } } \frac { 1 } { \vert S _ { y } \vert } d \bar { y } } & { { } } \\ { = \displaystyle \int _ { \bar { x } \sim G ( S _ { y } ) } \frac { \vert \nabla _ { \bar { x } } G ^ { - 1 } ( \bar { x } ) \vert } { \vert S _ { y } \vert } d \bar { x } } & { { } } \\ { = \displaystyle \int _ { \bar { x } \sim G ( S _ { y } ) } \frac { \vert \nabla _ { \bar { x } } F ( \bar { x } ) \vert } { \vert S _ { y } \vert } d \bar { x } } & { { } } \end{array}$$
Corollary 2.
$$\frac { 1 } { ( 1 - \epsilon _ { x } ) | S _ { G ( y ) } | } \geq \frac { 1 } { | S _ { y } | } \geq \frac { 1 } { ( 1 + \epsilon _ { x } ) | S _ { G ( y ) } | }$$
Proof of Corollary 2. By Equation 6 and Corollary 1:
$$\begin{array} { r l } & { \displaystyle \int _ { \bar { x } \sim S _ { G ( y ) } } \frac { 1 - \epsilon _ { x } } { | S _ { y } | } d \bar { x } \le \int _ { \bar { x } \sim S _ { G ( y ) } } \frac { 1 } { | S _ { G ( y ) } | } d \bar { x } \le \int _ { \bar { x } \sim S _ { G ( y ) } } \frac { 1 + \epsilon _ { x } } { | S _ { y } | } d \bar { x } } \\ & { \qquad \implies \frac { 1 - \epsilon _ { x } } { | S _ { y } | } | S _ { G ( y ) } | \le 1 \le \frac { 1 + \epsilon _ { x } } { | S _ { y } | } | S _ { G ( y ) } | } \\ & { \qquad \implies ( 1 - \epsilon _ { x } ) | S _ { G ( y ) } | \le | S _ { y } | \le ( 1 + \epsilon _ { x } ) | S _ { G ( y ) } | } \\ & { \qquad \implies \frac { 1 } { ( 1 - \epsilon _ { x } ) | S _ { G ( y ) } | } \ge \frac { 1 } { | S _ { y } | } \ge \frac { 1 } { ( 1 + \epsilon _ { x } ) | S _ { G ( y ) } | } } \end{array}$$
Corollary 1 leads to the following:
$$\begin{array} { r l } & { \mathbb { E } _ { \boldsymbol { x } \in \mathcal { X } } [ \mathbb { E } _ { \bar { \boldsymbol { x } } \in S _ { \boldsymbol { x } } } [ \mathrm { l o g } ( D _ { \overline { { \boldsymbol { x } } } } ( \bar { \boldsymbol { x } } ) ) ] ] + \mathbb { E } _ { \boldsymbol { y } \in \mathcal { Y } } [ \mathbb { E } _ { \bar { \boldsymbol { y } } \in S _ { \boldsymbol { y } } } [ \mathrm { l o g } ( 1 - D _ { \overline { { \mathcal { X } } } } ( G ( \bar { \boldsymbol { y } } ) ) ) ] ] } \\ & { = \displaystyle \sum _ { \boldsymbol { x } \in \mathcal { X } } p _ { \mathcal { X } } ( \boldsymbol { x } ) \int _ { \bar { \boldsymbol { x } } \sim S _ { \boldsymbol { x } } } \frac { 1 } { | S _ { \boldsymbol { x } } | } \log ( D _ { \overline { { \boldsymbol { x } } } } ( \bar { \boldsymbol { x } } ) ) d \bar { x } + \displaystyle \sum _ { \boldsymbol { y } \in \mathcal { Y } } p _ { \mathcal { Y } } ( \boldsymbol { y } ) \int _ { \bar { \boldsymbol { y } } \sim S _ { \boldsymbol { y } } } \frac { 1 } { | S _ { \boldsymbol { y } } | } \log ( 1 - D _ { \overline { { \boldsymbol { x } } } } ( G ( \bar { \boldsymbol { y } } ) ) ) d \bar { y } } \\ & { = \displaystyle \sum _ { \boldsymbol { x } \in \mathcal { X } } p _ { \mathcal { X } } ( \boldsymbol { x } ) \int _ { \bar { \boldsymbol { x } } \sim S _ { \boldsymbol { x } } } \frac { 1 } { | S _ { \boldsymbol { x } } | } \log ( D _ { \overline { { \boldsymbol { x } } } } ( \bar { \boldsymbol { x } } ) ) d \bar { x } + \displaystyle \sum _ { \boldsymbol { y } \in \mathcal { Y } } p _ { \mathcal { Y } } ( \boldsymbol { y } ) \int _ { \bar { \boldsymbol { x } } \sim G ( S _ { \boldsymbol { y } } ) } \frac { | \nabla _ { \bar { x } } F ( \bar { \boldsymbol { x } } ) | } { | S _ { \boldsymbol { y } } | } \log ( 1 - D _ { \overline { { \boldsymbol { x } } } } ( \bar { \boldsymbol { x } } ) ) d \bar { x } } \end{array}$$
Using Lemma 1 and Corollary 2, we obtain the following lower-bound of Equation 7:
$$\begin{array} { l } { { \displaystyle \geq \sum _ { x \in \mathcal { X } } p _ { \mathcal X } ( x ) \int _ { \overline { { x } } \sim S _ { \varepsilon } } \frac { 1 } { | S _ { x } | } \log ( D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } + \displaystyle \sum _ { y \in \mathcal { Y } } p _ { \mathcal Y } ( y ) \int _ { \overline { { x } } \sim G ( S _ { y } ) } \frac { 1 - \epsilon _ { x } } { | S _ { y } | } \log ( 1 - D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } } \ ~ } \\ { { \displaystyle \geq \sum _ { x \in \mathcal { X } } p _ { \mathcal X } ( x ) \int _ { \bar { x } \sim S _ { x } } \frac { 1 } { | S _ { x } | } \log ( D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } } \ ~ } \\ { { \displaystyle \qquad + p _ { \mathcal Y } ( F ( x ) ) \int _ { \bar { x } \sim S _ { G ( F ( x ) ) } } \frac { 1 - \epsilon _ { x } } { ( 1 + \epsilon _ { x } ) | S _ { G ( F ( x ) ) } | } \log ( 1 - D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } } \ ~ } \\ { { \displaystyle = \sum _ { x \in \mathcal { X } } \int _ { \bar { x } \sim S _ { x } } \frac { 1 } { | S _ { x } | } \left[ p _ { \mathcal X } ( x ) \log ( D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) + \frac { 1 - \epsilon _ { x } } { 1 + \epsilon _ { x } } p _ { G } ( x ) \log ( 1 - D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) \right] d \bar { x } } } \end{array}$$
Which is maximal at:
$$\begin{array} { c } { { D _ { \overline { { { \mathcal { X } } } } } ( \bar { x } \sim S _ { x } ) = \frac { p _ { \mathcal { X } } } { p _ { \mathcal { X } } + \frac { 1 - \epsilon _ { x } } { 1 + \epsilon _ { x } } p _ { G } } \stackrel { \epsilon _ { x } } { \approx } D _ { \mathcal { X } } } } \\ { { \Longrightarrow \mathbb { E } _ { \bar { x } \sim S _ { x } } [ D _ { \overline { { { \mathcal { X } } } } } ( \bar { x } ) ] \stackrel { \epsilon _ { x } } { \approx } D _ { \mathcal { X } } } } \end{array}$$
And similarly, we find Equation 7 is upper-bounded by:
$$\begin{array} { l } { { \displaystyle \leq \sum _ { x \in \mathcal { X } } p _ { \mathcal X } ( x ) \int _ { \overline { { x } } \sim S _ { z } } \frac { 1 } { | S _ { x } | } \log ( D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } + \displaystyle \sum _ { y \in \mathcal { Y } } p _ { \mathcal Y } ( y ) \int _ { \overline { { x } } \sim G ( S _ { y } ) } \frac { 1 + \epsilon _ { x } } { | S _ { y } | } \log ( 1 - D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } } } \\ { { \displaystyle \leq \sum _ { x \in \mathcal { X } } p _ { \mathcal X } ( x ) \int _ { \bar { x } \sim S _ { x } } \frac { 1 } { | S _ { x } | } \log ( D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } } } \\ { { \displaystyle \qquad + p _ { \mathcal Y } ( F ( x ) ) \int _ { \bar { x } \sim S _ { G ( F ( \bar { x } ) ) } } \frac { 1 + \epsilon _ { x } } { ( 1 - \epsilon _ { x } ) | S _ { G ( F ( \bar { x } ) ) } | } \log ( 1 - D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) d \bar { x } } } \\ { { \displaystyle = \sum _ { x \in \mathcal { X } } \int _ { \bar { x } \sim S _ { x } } \frac { 1 } { | S _ { x } | } \left[ p _ { \mathcal X } ( x ) \log ( D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) + \frac { 1 + \epsilon _ { x } } { 1 - \epsilon _ { x } } p _ { G } ( x ) \log ( 1 - D _ { \overline { { \mathcal X } } } ( \bar { x } ) ) \right] d \bar { x } } } \end{array}$$
Which is maximal in $D _ { \overline { { \mathcal { X } } } }$ at:
$$\begin{array} { c } { { D _ { \overline { { { \mathcal { X } } } } } ( \bar { x } \sim S _ { x } ) = \frac { p _ { \mathcal { X } } } { p _ { \mathcal { X } } + \frac { 1 + \epsilon _ { x } } { 1 - \epsilon _ { x } } p _ { G } } \stackrel { \epsilon _ { x } } { \approx } D _ { \mathcal { X } } } } \\ { { \Longrightarrow \mathbb { E } _ { \bar { x } \sim S _ { x } } [ D _ { \overline { { { \mathcal { X } } } } } ( \bar { x } ) ] \stackrel { \epsilon _ { x } } { \approx } D _ { \mathcal { X } } } } \end{array}$$
Hence, asymptotically as $F$ becomes approximately volume-preserving about each discrete $x \in \mathcal { X }$ the bounds maximize to the same loss value in the same class of functions $\mathbb { E } _ { { \bar { x } } \sim S _ { x } } [ D _ { \overline { { \mathcal { X } } } } ( { \bar { x } } ) ] = D _ { \mathcal { X } }$ , application of the squeeze theorem concludes the proof. □123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569# AN INFORMATION-THEORETIC METRIC OF TRANSFERABILITY FOR TASK TRANSFER LEARNING
Anonymous authors Paper under double-blind review
# ABSTRACT
An important question in task transfer learning is to determine task transferability, i.e. given a common input domain, estimating to what extent representations learned from a source task can help in learning a target task. Typically, transferability is either measured experimentally or inferred through task relatedness, which is often defined without a clear operational meaning. In this paper, we present a novel metric, $H$ -score, an easily-computable evaluation function that estimates the performance of transferred representations from one task to another in classification problems. Inspired by a principled information theoretic approach, H-score has a direct connection to the asymptotic error probability of the decision function based on the transferred feature. This formulation of transferability can further be used to select a suitable set of source tasks in task transfer learning problems or to devise efficient transfer learning policies. Experiments using both synthetic and real image data show that not only our formulation of transferability is meaningful in practice, but also it can generalize to inference problems beyond classification, such as recognition tasks for 3D indoor-scene understanding.
# 1 INTRODUCTION
Transfer learning is a learning paradigm that exploits relatedness between different learning tasks in order to gain certain benefits, e.g. reducing the demand for supervision (Pratt (1993)). In task transfer learning, we assume that the input domain of the different tasks are the same. Then for a target task $\mathcal { T } _ { T }$ , instead of learning a model from scratch, we can initialize the parameters from a previously trained model for some related source task $\mathcal { T } _ { S }$ . For example, deep convolutional neural networks trained for the ImageNet classification task have been used as the source network in transfer learning for target tasks with fewer labeled data (Donahue et al. (2014)), such as medical image analysis (Shie et al. (2015)) and structural damage recognition in buildings (Gao & Mosalam).
An imperative question in task transfer learning is transferability, i.e. when a transfer may work and to what extent. Given a metric capable of efficiently and accurately measuring transferability across arbitrary tasks, the problem of task transfer learning, to a large extent, is simplified to search procedures over potential transfer sources and targets as quantified by the metric. Traditionally, transferability is measured purely empirically using model loss or accuracy on the validation set (Yosinski et al. (2014); Zamir et al. (2018); Conneau et al. (2017)). There have been theoretical studies that focus on task relatedness (Baxter (2000); Maurer (2009); Pentina & Lampert (2014); Ben-David et al. (2003)). However, they either cannot be computed explicitly from data or do not directly explain task transfer performance. In this study, we aim to estimate transferability analytically, directly from the training data.
We quantify the transferability of feature representations across tasks via an approach grounded in statistics and information theory. The key idea of our method is to show that the error probability of using a feature of the input data to solve a learning task can be characterized by a linear projection of this feature between the input and output domains. Hence we adopt the projection length as a metric of the feature’s effectiveness for the given task, and refer to it as the $H$ -score of the feature. More generally, H-score can be applied to evaluate the performance of features in different tasks, and is particularly useful to quantify feature transferability among tasks. Using this idea, we define task transferability as the normalized H-score of the optimal source feature with respect to the target task.
As we demonstrate in this paper, the advantage of our transferability metric is threefold. (i) it has a strong operational meaning rooted in statistics and information theory; (ii) it can be computed directly and efficiently from the input data, with fewer samples than those needed for empirical learning; (iii) it can be shown to be strongly consistent with empirical transferability measurements.
In this paper, we will first present the theoretical results of the proposed transferability metric in Section 2-4. Section 5 presents several experiments on real image data , including image classificaton tasks using the Cifar 100 dataset and 3D indoor scene understanding tasks using the Taskonomy dataset created by Zamir et al. (2018). A brief review of the related works is included in Section 6.
# 2 BACKGROUND
In this section, we will introduce the notations used throughout this paper, as well as some related concepts in Euclidean information theory and statistics.
$X$ $, x , \chi$ and $P _ { X }$ represent a random variable, a value, the alphabet and the probability distribution respectively. $\sqrt { \mathrm { P } _ { X } }$ denotes the vector with entries $\sqrt { P _ { X } ( x ) }$ and $[ { \sqrt { \operatorname { P } _ { X } } } ]$ the diagonal matrix of $\sqrt { P _ { X } ( X ) }$ . For joint distribution $P _ { Y X }$ , $\operatorname { P } _ { Y X }$ represents the $| y | \times | \mathcal { X } |$ probability matrix. Depending on the context, $\operatorname { f } ( X )$ is either a $| \mathcal { X } |$ -dimensional vector whose entries are $f ( x )$ , or a $| { \mathcal { X } } | \times k$ feature matrix. Further, we define a task to be a tuple $\mathcal { T } = ( X , Y , P _ { X Y } )$ , where $X$ is the training features and $Y$ is the training label, and $P _ { X Y }$ the joint probability (possibly unknown). Subscripts $S$ and $T$ are used to distinguish the source task from the target task.
# 2.1 LOCAL INFORMATION GEOMETRY AND HYPOTHESIS TESTING
Our definiton of transferability uses concepts in local information geometry developed by Makur et al. (2015), which characterizes probability distributions as vectors in the information space. Consider the following binary hypothesis testing problem: test whether i.i.d. samples $\mathbf { x } ^ { m } = \{ x ^ { ( i ) } \} _ { i = 1 } ^ { m }$ )}mi=1 are drawn from distribution $P _ { 1 }$ or distribution $P _ { 2 }$ , where $P _ { 1 } , P _ { 2 }$ belong to an $\epsilon$ -neighborhood $\mathcal { N } _ { \epsilon } ( P _ { 0 } ) \overset { \Delta } { = }$ $\begin{array} { r } { \{ P \vert \sum _ { x \in \mathcal { X } } \frac { ( P ( x ) - P _ { 0 } ( x ) ) ^ { 2 } } { P _ { 0 } ( x ) } \leq \epsilon ^ { 2 } \} } \end{array}$ centered at a reference distributon $P _ { 0 }$ . And denote $\begin{array} { r } { \phi _ { i } = \frac { P _ { i } ( x ) - P _ { 0 } ( x ) } { \epsilon \sqrt { P _ { 0 } ( x ) } } } \end{array}$ as the information vector corresponding to $P _ { i }$ for $i = 1 , 2$ .
Given $k$ normalized feature functions $f ( x ) = [ f _ { 1 } ( x ) , \ldots , f _ { k } ( x ) ]$ , let $\Xi ( x ) = [ \xi _ { 1 } ( x ) , \dots , \xi _ { k } ( x ) ]$ be the matrix of feature vectors $\xi _ { i } ( x ) = \sqrt { P _ { 0 } ( x ) } f _ { i } ( x )$ . Given observations $\mathbf { x } ^ { m }$ , feature $f$ is associated with a $\mathbf { k }$ -dimensional statistics $\begin{array} { r } { l ( \mathbf { x } ^ { m } ) = \frac { 1 } { m } \sum _ { i = 1 } ^ { m } ( f ( x ^ { ( i ) } ) ) } \end{array}$ for the binary hypothesis testing problem. Let $E _ { f }$ be the error exponent of decision region $\{ \mathbf { x } ^ { m } \mid l ( \mathbf { x } ^ { m } ) > T \}$ for , which characterizes the asymptotic error probability $P _ { e }$ of $l$ (i.e. $\begin{array} { r } { \operatorname* { l i m } _ { m \infty } - \frac { 1 } { m } \log ( P _ { e } ) = E _ { f } ^ { k } } \end{array}$ ). $E _ { f }$ can be written as the squared length of a projection:
$$E _ { f } ^ { k } = \sum _ { i = 1 } ^ { k } E _ { f _ { i } } = \sum _ { i = l } ^ { k } \frac { \epsilon ^ { 2 } } { 8 } \left. \xi _ { i } , \phi _ { 1 } - \phi _ { 2 } \right. ^ { 2 } + o \left( \epsilon ^ { 2 } \right)$$
When the la $\begin{array} { r } { f ( x ) = \log \frac { P _ { 1 } ( x ) } { P _ { 2 } ( x ) } } \end{array}$ is tent $l$ m sufficient statistics that achievesby the Chernoff theorem. (See $\begin{array} { r } { E _ { f } ^ { k } = \sum _ { i = 1 } ^ { k } \frac { \epsilon ^ { 2 } } { 8 } | | \phi _ { 1 } - \phi _ { 2 } | | ^ { 2 } + o ( \epsilon ^ { 2 } ) } \end{array}$ Appendix A for details.) In the rest of this paper, we assume $\epsilon$ is small.
# 2.2 DIVERGENCE TRANSITION MATRIX
Definition 1. Matrix $\tilde { B }$ is the Divergence Transition Matrix (DTM) of a joint probability $P _ { Y X }$ if $\tilde { B } = \left[ \sqrt { \mathrm { P } _ { Y } } \right] ^ { - 1 } \mathrm { P } _ { Y X } \left[ \sqrt { \mathrm { P } _ { X } } \right] ^ { - 1 } - \sqrt { \mathrm { P } _ { Y } } \sqrt { \mathrm { P } _ { X } } ^ { \mathrm { T } }$ .
The singular values of $\tilde { B }$ satisfy that $1 \geq \sigma _ { 1 } \geq \cdot \cdot \cdot \geq \sigma _ { K } = 0 , K \triangleq \operatorname* { m i n } \{ | \mathcal { X } | , | \mathcal { V } | \}$ . Let $\Psi =$ $[ \psi _ { 1 } , \dots , \psi _ { K } ]$ and $\Phi = [ \phi _ { 1 } , \dots , \phi _ { K } ]$ be the left and right singular vectors of $\tilde { B }$ . Define functions $\begin{array} { r } { f _ { i } ^ { * } ( x ) = \frac { \phi _ { i } ( x ) } { \sqrt { P _ { X } ( x ) } } } \end{array}$ and $\begin{array} { r } { g _ { i } ^ { * } ( y ) = \frac { \psi _ { i } ( y ) } { \sqrt { P _ { Y } ( y ) } } } \end{array}$ for each $i = 1 , \ldots , K - 1$ . Makur et al. (2015) further
proved that $f _ { i } ^ { * }$ and $g _ { i } ^ { * }$ are solutions to the maximal HGR correlation problem studied by Hirschfeld (1935); Gebelein (1941); Renyi (1959), defined as follows: ´
$$\begin{array} { c } { \rho ( X ; Y ) = \displaystyle \operatorname* { s u p } _ { f : \mathcal { X } \to \mathbb { R } ^ { k } , g : \mathcal { Y } \to \mathbb { R } ^ { k } } \mathbb { E } [ f ( X ) ^ { T } g ( Y ) ] } \\ { \mathbb { E } [ f ( X ) ] = \mathbb { E } [ g ( Y ) ] = 0 } \\ { \mathbb { E } [ f ( X ) f ( X ) ^ { T } ] = I } \end{array}$$
The maximal HGR problem finds the $K$ strongest, independent modes in $P _ { X Y }$ from data. It can be solved efficiently using the Alternating Conditional Expectation (ACE) algorithm with provable error bound (see Appendix B). Huang et al. (2017) further showed that $f ^ { * }$ and $g ^ { * }$ are the universal minimum error probability features in the sense that they can achieve the smallest error probability over all possible inference tasks.
3 MEASURING THE EFFECTIVENESS OF FEATURES IN CLASSIFICATION TASKS
In this section, we present a performance metric of a given feature representation for a learning task.
# 3.1 H-SCORE
For a classification task involving input variable $X$ and label $Y$ , most learning algorithms work by finding a $k$ -dimensional functional representation $f ( x )$ of $X$ that is most discriminative for the classification. To measure how effective $f ( x )$ is in predicting $Y$ , rather than train the model via gradient descent and evaluate its accuracy, we present an analytical approach based on the definition below:
Definition 2. Given data matrix $\boldsymbol { X } ~ \in ~ \mathbb { R } ^ { m \times d }$ and label $Y \in \{ 1 , \dots , | y | \}$ . Let $f ( x )$ be a $k$ - dimensional, zero-mean feature function. The $H$ -Score of $f ( x )$ with respect to the learning task represented by $P _ { Y X }$ is:
$$\mathcal { H } ( f ) = \mathrm { t r } ( \mathrm { c o v } ( f ( X ) ) ^ { - 1 } \mathrm { c o v } ( \mathbb { E } _ { P _ { X | Y } } [ f ( X ) | Y ] ) )$$
This definition is intuitive from a nearest neighbor search perspective. i.e. a high $_ \mathrm { H }$ -score implies the inter-class variance c $\operatorname { o v } ( \mathbb { E } _ { P _ { X \mid Y } } [ f ( X ) | Y ] )$ of $f$ is large, while feature redundancy $\operatorname { t r } ( \operatorname { c o v } ( f ( X ) ) )$ is small. Such a feature is discriminative and efficient for learning label Y. More importantly, $\mathcal { H } ( f )$ has a deeper operational meaning related to the asymptotic error probability for a decision rule based on $f$ in the hypothesis testing context, discussed in the next section.
# 3.2 OPERATIONAL MEANING OF H-SCORE
Without loss of generality, we consider the binary classification task as a hypothesis testing problem defined in Section 2.1, with $P _ { 1 } = P _ { X | Y = 0 }$ , and $P _ { 2 } = P _ { X | Y = 1 }$ . For any $\mathbf { k }$ -dimensional feature representation $f ( x )$ , we can quantify its performance with respect to the learning task using its error exponent $E _ { f } ^ { k }$ .
Theorem 1. Given $P _ { X | Y = 0 } , P _ { X | Y = 1 } \in \mathcal { N } _ { \epsilon } ^ { \mathcal { X } } ( P _ { 0 , X } )$ and features $f$ such that $\mathbb { E } \left[ f ( X ) \right] = 0$ and $\mathbb { E } [ f ( X ) f ( X ) ^ { \mathrm { T } } ] = I$ , there exists some constant $c$ independent of $f$ such that $E _ { f } ^ { k } = c { \mathcal { H } } ( f )$ .
See Appendix C for the proof. The above theorem shows that $_ \mathrm { H }$ -score $\mathcal { H } ( f )$ is proportional to the error exponent of the decision region based on $f ( x )$ when $f ( x )$ is zero-mean with identity covariance. To compute the $_ \mathrm { H }$ -score of arbitrary $f$ , we can center the features $f _ { S } ( x ) - \mathbb { E } [ f _ { S } ( x ) ]$ , and incorporate normalization into the computation of the error exponent, which results in Definition 2. The details are presented in Appendix D.
The proof for Theorem 1 uses the fact that $\mathcal { H } ( f ) = \| \tilde { B } \Xi \| _ { F } ^ { 2 }$ , where $\tilde { B }$ is the DTM matrix, $\Xi \triangleq$ $[ \xi _ { 1 } \cdot \cdot \cdot \xi _ { k } ]$ is the matrix composed of information vectors $\xi _ { i }$ and $c$ is a constant. This allows us to infer an upper bound for the $_ \mathrm { H }$ -score of a given learning task:
Corollary 1. For all normalized feature $f ( x ) = [ f _ { 1 } ( x ) , \ldots , f _ { k } ( x ) ] ,$ , its $H .$ -score satisfies $\mathcal { H } ( f ) \leq$ $\textstyle \sum _ { i = 1 } ^ { k } \sigma _ { i } ^ { 2 } \leq k$ , where $\sigma _ { i }$ is the ith singular value of $\tilde { B }$ .
 Figure 1: A simple neural network topology for transfer learning
The first inequality is achieved when $\Xi$ is composed of the right singular vectors of $\tilde { B }$ , i.e. $\mathrm { m a x } _ { \Xi } | | \tilde { B } \Xi | | _ { F } ^ { 2 } = | | \tilde { B } _ { T } | | _ { F } ^ { 2 }$ . The corresponding feature functions $\mathrm { f _ { o p t } } ( X )$ is in fact the same as the universal minimum error probability features from the maximum HGR correlation problem. The final inequality in Corollary 1 is due to the fact all singular values of $\tilde { B }$ are less than or equal to 1.
# 4 TRANSFERABILITY
Next, we apply $_ \mathrm { H }$ -score to efficiently measure the effectiveness of task transfer learning. We will also discuss how this approach can be used to solve the source task selection problem.
# 4.1 TASK TRANSFERABILITY
A typical way to transfer knowledge from the source task $\mathcal { T } _ { S }$ to target task $\mathcal { T } _ { T }$ is to train the target task using source feature representation $f _ { S } ( x )$ . In a neural network setting, this idea can be implemented by copying the parameters from the first $\mathbf { N }$ layers in the trained source model to the target model, assuming the model architecture on those layers are the same. The target classifier then can be trained while freezing parameters in the copied layers (Figure 1). Under this model, a natural way to quantify transferability is as follows:
Definition 3 (Task transferability). Given source task $\tau _ { S }$ and target task $\mathcal { T } _ { T }$ , and trained source feature representation $f _ { S } ( x )$ , the transferability from $\mathcal { T } _ { S }$ to $\mathcal { T } _ { T }$ is $\begin{array} { r } { \mathfrak { T } ( S , T ) \triangleq \frac { \mathcal { H } _ { T } ( f _ { S } ) } { \mathcal { H } _ { T } ( f _ { T _ { \mathrm { o p t } } } ) } } \end{array}$ , where $f _ { T _ { \mathrm { o p t } } } ( x )$ is the minimum error probability feature of the target task.
The statement ${ \mathfrak { T } } ( S , T ) = r$ means the error exponent of transfering from $\mathcal { T } _ { S }$ via feature representation $f _ { S }$ is $\textstyle { \frac { 1 } { r } }$ of the optimal error exponent for predicting the target label $Y _ { T }$ . This definition also implies $0 \leq \mathfrak { T } ( S , T ) \leq 1$ , which satisfies the data processing inequality if we consider the transferred feature $f _ { S } ( X )$ as post-processing of input $X$ for solving the target task. And it can not increase information about predicting the target task $\tau$ .
A common technique in task transfer learning is fine-tuning, which adds before the target classifier additional free layers, whose parameters are optimized with respect to the target label. For the operational meaning of transferability to hold exactly, we require the fine tuning layers consist of only linear transformations, such as the model illustrated in Figure 2.a. It can be shown that under the local assumption, $\mathrm { H }$ -score is equivalent to the log-loss of the linear transfer model up to a constant offset (Appendix E). Nevertheless, later we will demonstrate empirically that this transferability metric can still be used for comparing the relative task transferability with fine-tuning.
# 4.2 EFFICIENT COMPUTATION OF TRANSFERABILITY
With a known $f$ , computing H-score from $m$ sample data only takes $O ( m k ^ { 2 } )$ time, where $k$ is the dimension of $f ( x )$ for $k < m$ . The majority of the computation time is spent on computing the sample covariance matrix $\operatorname { c o v } ( f ( X ) )$ .
The remaining question is how to obtain $f _ { T _ { o p t } }$ efficiently. We use the fact that $\mathcal { H } _ { T } ( f _ { \mathrm { o p t } } ) = | | \tilde { B } _ { T } | | _ { F } ^ { 2 } =$ $\mathbb { E } [ f ( X ) ^ { \mathrm { T } } g ( Y ) ]$ , where $f$ and $g$ are the solutions of the HGR-Maximum Correlation problem. This problem can be solved efficiently using the ACE algorithm for discrete variable $X$ . For a continuous random variable $X$ , we can obtain $f _ { o p t }$ through a different formulation of the HGR maximal
 Figure 2: a) Network topology of linear feature transfer. b) Architec- Figure 3: H-score and muture for the neural network implementation of the soft HGR problem tual information.
correlation problem:
$$\operatorname* { m a x } _ { f : \mathcal { X } \to \mathbb { R } ^ { k } , g : \mathcal { Y } \to \mathbb { R } ^ { k } } \mathbb { E } [ f ( X ) ^ { \mathrm { T } } g ( Y ) ] - \frac { 1 } { 2 } \mathrm { t r } ( \mathrm { c o v } ( f ( X ) ) \mathrm { c o v } ( g ( Y ) ) )$$
This is also known as the soft HGR problem studied by Wang et al. (2019), who reformulated the original maximal HGR correlation objective to eliminate the whitening constraints while having theoretically equivalent solution. In practice, we can utilize neural network layers to model functions $f$ and $g$ , as shown in Figure 2.b. Given two branches of $k$ output units for both $f$ and $g$ , the loss function can be evaluated in $O ( m k ^ { 2 } )$ , where $m$ is the batch size. Makur et al. (2015) showed that the sample complexity of ACE is only $1 / k$ of the complexity of estimating $P _ { Y , X }$ directly. This result also applies to the soft HGR problem due to their theoretical equivalence. Hence transferability can be computed with much less samples than actually training the transfer network.
It’s also worth noting that, when $\overline { f }$ is fixed, maximizing the objective in Equation 3 with respect to zero-mean function $g$ results in the definition of H-score. In many cases though, the computation of $H _ { T } ( f _ { o p t } )$ can even be skipped entirely, such as the problem below:
Definition 4 (Source task selection). Given $N$ source tasks $\mathcal { T } _ { S _ { 1 } } , \dots , \mathcal { T } _ { S _ { N } }$ with labels $Y _ { S _ { 1 } } , \dots , Y _ { S _ { N } }$ and a target task $\mathcal { T } _ { T }$ with label $Y _ { T }$ . Let $f _ { S _ { 1 } } , \dots , f _ { S _ { N } }$ be the minimum error probability feature functions of the source tasks. Find the source task $\mathcal { T } _ { S _ { i } }$ that maximizes the testing accuracy of predicting $Y _ { T }$ with feature $f _ { S _ { i } }$ .
We can solve this problem by selecting the source task with the largest transferability to $\mathcal { T } _ { T }$ . In fact, we only need to compute the numerator in the transferability definition since the denominator is the same for all source tasks, i.e. argmaxi $\mathfrak { T } ( S _ { i } , T ) = \mathrm { a r g m a x } _ { i } \overset { \cdot } { ( } \mathcal { H } _ { T } ( f _ { S _ { i , \mathrm { o p t } } } ) / \mathcal { H } _ { T } ( f _ { T _ { \mathrm { o p t } } } ) = \mathrm { a r g m a x } _ { i } \mathcal { H } ( f _ { S _ { i } } )$ .
# 4.3 RELATIONSHIP WITH MUTUAL INFORMATION
Under the local assumption that $P _ { X | Y } \in N _ { \epsilon } ( P _ { X } )$ , we can show that mutual information $I ( X ; Y ) =$ $\textstyle \frac { 1 } { 2 } | | B | | _ { F } ^ { 2 } + o ( \epsilon ^ { 2 } )$ . (See Appendix F for details.) Hence $_ \mathrm { H }$ -score is related to mutual information by $\bar { \mathcal { H } } ( f ( x ) ) \leq 2 I ( X ; Y )$ for any zero-mean features $f ( x )$ satisfying the aforementioned conditions.
Figure 3 compares the optimal H-score of a synthesized task when $| y | = 6$ with the mutual information between input and output variables, when the feature dimension $k$ changes. The value of H-score increases as $k$ increases, but reaches the upper bound when $k \geq 6$ , since the rank of the joint probability between $X$ and $Y _ { T }$ , as well as the rank of its DTM is 6. As expected, the H-score values are below $2 I ( X ; Y )$ , with a gap due to the constant $o ( \epsilon ^ { 2 } )$ . This relationship shows that H-score is consistent with mutual information with a sufficiently large feature dimension $k$ .
In practice, H-score is much easier to compute than mutual information when the input variable $X$ (or $f _ { S } ( X ) )$ is continous, as mutual information are either computed based on binning, which has extra bias due to bin size, or more sophisticated methods such as kernel density estimation or neural networks (Gabrie et al. (2018)). On the other hand,´ $_ \mathrm { H }$ -score only needs to estimate conditional expectations, which requires less samples.
# 5 EXPERIMENTS
In this section, we validate and analyze our transferability metric through experiments on real image data. 1 The tasks considered cover both object classification and non-classification tasks in computer vision, such as depth estimation and 3D (occlusion) edge detection.
# 5.1 VALIDATION OF TRANSFER PERFORMANCE
To demonstrate that our transferability metric is indeed a suitable measurement for task transfer performance, we compare it with the empirical performance of transfering features learned from ImageNet 1000-class classification (Krizhevsky et al. (2012)) to Cifar 100-class classification (Krizhevsky & Hinton (2009)), using a network similar to Figure 1. Comparing to ImageNet-1000, Cifar-100 has smaller sample size and its images have lower resolution. Therefore it is considered to be a more challenging task than ImageNet, making it a suitable case for transfer learning. In addition, we use a pretrained ResNet-50 as the source model due to its high performance and regular structure.
Validation of H-score. The training data for the target task in this experiemnt consists of 20, 000 images randomly sampled from Cifar-100. It is further split 9:1 into a training set and a testing set. The transfer network was trained using stochastic gradient descent with batch size 20, 000 for 100 epochs.
Figure 4.a compares the H-score of transferring from five different layers (4a-4f) in the source network with the target log-loss and test accuracy of the respective features. As H-score increases, log-loss of the target network decreases almost linearly while the training and testing accuracy increase. Such behavior is consistent with our expectation that H-score reflects the learning performance of the target task. We also demonstrated that target sample size does not affect the relationship between H-score and log-loss (Figure 4.b).
This experiment also showed another potential application of H-score for selecting the most suitable layer for fine-tuning in transfer learning. In the example, transfer performance is better when an upper layer of the source networks is transferred. This could be because the target task and the source task are inherently similar such that the representation learned for one task can still be discriminative for the other.
 Figure 4: H-score and transferability vs. the empirical transfer performance measured by log-loss, training and testing accuracy. a.) Performance of ImageNet-1000 features from layers 4a-4f for Cifar100 classification. b.) Effect of sample size (5K-50K) on H-score for Cifar 100. c.): Transferability from ImageNet-1000 to 4 different target tasks based on Cifar-100.
Validation of Transferability. We further tested our transferability metric for selecting the best target task for a given source task. In particular, we constructed 4 target classification tasks with 3, 5, 10, and 20 object categories from the Cifar-100 dataset. We then computed the transferability from ImageNet-1000 (using the feature representation of layer 4f) to the target tasks. The results are compared to the empirical transfer performance trained with batch size 64 for 50 epochs in Figure4.c. We observe a similar behavior as the H-score in the case of a single target task in Figure 4.a, showing that transferability can directly predict the empirical transfer performance.
# 5.2 TASK TRANSFER FOR 3D SCENE UNDERSTANDING
In this experiment, we solve the source task selection problem for a collection of 3D sceneunderstanding tasks using the Taskonomy dataset from Zamir et al. (2018). In the following, we will introduce the experiment setting and explain how we adapt the transferability metric to pixel-to-pixel recognition tasks. Then we compare transferability with task affinity, an empirical transferability metric proposed by Zamir et al. (2018).
Data and Tasks. The Taskonomy dataset contains 4,000,000 images of indoor scenes of 600 buildings. Every image has annotations for 26 computer vision tasks. We randomly sampled 20, 000 images as training data. Eight tasks were chosen for this experiment, covering both classifications and lower-level pixel-to-pixel tasks. Table 6 summaries the specifications of these tasks and sample outputs are shown in Figure 5.
 Figure 5: Ground truth of different tasks for a given query image.
Feature Extraction and Data Preprocessing. For each task, Zamir et al. (2018) trained a fully supervised network with an encoder-decoder structure. When testing the transfer performance from $\tau _ { S }$ to $\mathcal { T } _ { T }$ , the encoder output of $\mathcal { T } _ { S }$ is used for training the decoder of $\mathcal { T } _ { T }$ . For a fair comparison, we use the same trained encoders to extract source features. The output dimension of all encoders are $1 6 \times 1 6 \times 8$ and we flatten the output into a vector of length 2048. To reduce the computational complexity, we also resize the ground truth images into $6 4 \times 6 4$ .
For classification tasks, H-score can be easily calculated given the source features. But for pixel-topixel tasks such as Edges and Depth, their ground truths are represented as images, which can not be quantized easily. As a workaround, we cluster the pixel values in the ground truth images into a palette of 16 colors. Then compute the H-score of the source features with respect to each pixel, before aggregating them into a final score by averaging over the whole image.
We ran the experiment on a workstation with $3 . 4 0 \mathrm { G H z } \times 8 $ CPU and $1 6 \mathrm { \ G B }$ memory. Each pairwise H-score computation finished in less than one hour including preprocessing. Then we rank the source tasks according to their H-scores of a given target task and compare the ranking with that in Zamir et al. (2018).
<table><tr><td>Tasks</td><td>k</td><td>Output</td><td>Quantize -level</td></tr><tr><td>2D Edges</td><td>2048</td><td>images</td><td>16</td></tr><tr><td>3D Occlusion</td><td>2048</td><td>images</td><td>16</td></tr><tr><td>Edges 2D Keypoints</td><td>2048</td><td>images</td><td>16</td></tr><tr><td>3D Keypoints</td><td>2048</td><td>images</td><td>16</td></tr><tr><td>Reshading</td><td>2048</td><td>images</td><td>16</td></tr><tr><td>Depth</td><td>2048</td><td>images</td><td>16</td></tr><tr><td>Object Class.</td><td>2048</td><td>labels</td><td>none</td></tr><tr><td>Scene Class.</td><td>2048</td><td>labels</td><td>none</td></tr></table>
 Figure 6: Task descriptions Figure 7: Ranking comparison between transferability and affinity score.
Pairwise Transfer Results. Source task ranking results using transferability and affinity are visualized side by side in Figure 7, with columns representing source tasks and rows representing target tasks. For classification tasks (the bottom two rows in the transferability matrix), the top two transferable source tasks are identical for both methods. The best source task is the target task itself, as the encoder is trained on a task-specific network with much larger sample size. Scene Class. and Object Class. are ranked second for each other, as they are semantically related. Similar observations can be found in 2D pixel-to-pixel tasks (top two rows). The results on lower rankings are noisier.
A slightly larger difference between the two rankings can be found in 3D pixel-to-pixel tasks, especially 3D Occlusion Edges and 3D Keypoints. Though the top four ranked tasks of both methods are exactly the four 3D tasks. It could indicate that these low level vision tasks are closely related to each other so that the transferability among them are inherently ambiguous. We also computed the ranking correlations between transferability and affinity using Spearman’s R and Discounted Cumulative Gain (DCG). Both criterion show positive correlations for all target tasks. The correlation is especially strong with DCG as higher ranking entities are given larger weights.
The above observations inspire us to define a notion of task relatedness, as some tasks are frequently ranked high for each other. Specifically, we represent each task with a vector consisting of H-scores of all the source tasks, then apply agglomerative clustering over the task vectors. As shown in the dendrogram in Figure 7, 2D tasks and most 3D tasks are grouped into different clusters, but on a higher level, all pixel-to-pixel tasks are considered one category compared to the classifications tasks.
 Figure 8: Ranking of second order transferability for all recog- Figure 9: First and second order nition tasks pixel-wise transferability to Depth.
Higher Order Transfer. Sometimes we need to combine features from two or more source tasks for better transfer performance. A common way to combine features from multiple models in deep neural networks is feature concatenation. For such problems, our transferability definition can be easily adapted to high order feature transfer, by computing the H-score of the concatenated features.
Figure 8 shows the ranking results of all combinations of source task pairs for each target task. For all tasks except for 3D Occlusion Edges and Depth, the best seond-order source feature is the combination of the top two tasks of the first-order ranking. We examine the exception in Figure 9, by visualizing the pixel-by-pixel H-scores of first and second order transfers to Depth using a heatmap (lighter color implies a higher H-score). Note that different source tasks can be good at predicting different parts of the image. The top row shows the results of combining tasks with two different “transferability patterns” while the bottom row shows those with similar patterns. Combining tasks with different transferability patterns has a more significant improvement to the overall performance of the target task.
# 6 RELATED WORKS
Transfer learning. Transfer learning can be devided into two categories: domain adaptation, where knowledge transfer is achieved by making representations learned from one input domain work on a different input domain, e.g. adapt models for RGB images to infrared images (Wang & Deng (2018)); and task transfer learning, where knowledge is transferred between different tasks on the same input domain (Torrey & Shavlik (2010)). Our paper focus on the latter prolem.
Empirical studies on transferability. Yosinski et al. (2014) compared the transfer accuracy of features from different layers in a neural network between image classification tasks. A similar study was performed for NLP tasks by Conneau et al. (2017). Zamir et al. (2018) determined the optimal transfer hierarchy over a collection of perceptual indoor scene understanidng tasks, while transferability was measured by a non-parameteric score called ”task affinity” derived from neural network transfer losses coupled with an ordinal normalization scheme.
Task relatedness. One approach to define task relatedness is based on task generation. Generalization bounds have been derived for multi-task learning (Baxter (2000)), learning-to-learn (Maurer (2009)) and life-long learning (Pentina & Lampert (2014)). Although these studies show theoretical results on transferability, it is hard to infer from data whether the assumptions are satisfied. Another approach is estimating task relatedness from data, either explicitly (Bonilla et al. (2008); Zhang
(2013)) or implicitly as a regularization term on the network weights (Xue et al. (2007); Jacob et al. (2009)). Most works in this category are limited to shallow ones in terms of the model parameters.
Representation learning and evaluation. Selecting optimal features for a given task is traditionally performed via feature subset selection or feature weight learning. Subset selection chooses features with maximal relevance and minimal redundancy according to information theoretic or statistical criteria (Peng et al. (2005); Hall (1999)). The feature weight approach learns the task while regularizing feature weights with sparsity constraints, which is common in multi-task learningLiao & Carin (2006); Argyriou et al. (2007). In a different perspective, Huang et al. (2017) consider the universal feature selection problem, which finds the most informative features from data when the exact inference problem is unknown. When the target task is given, the universal feature is equivalent to the minimum error probability feature used in this work.
# 7 CONCLUSION
In this paper, we presented H-score, an information theoretic approach to estimating the performance of features when transferred across classification tasks. Then we used it to define a notion of task transferability in multi-task transfer learning problems, that is both time and sample complexity efficient. The resulting transferability metric also has a strong operational meaning as the ratio between the best achievable error exponent of the transferred representation and the minium error exponent of the target task.
Our transferability score successfully predicted the performance for transfering features from ImageNet-1000 classification task to Cifar-100 task. Moreover, we showed how the transferability metric can be applied to a set of diverse computer vision tasks using the Taskonomy dataset.
In future works, we plan to extend our theoretical results to non-classification tasks, as well as relaxing the local assumptions on the conditional distributions of the tasks. We will also investigate properties of higher order transferability, developing more scalable algorithms that avoid computing the H-score of all task pairs. On the application side, as transferability tells us how different tasks are related, we hope to use this information to design better task hierarchies for transfer learning.
# REFERENCES
Andreas Argyriou, Theodoros Evgeniou, and Massimiliano Pontil. Multi-task feature learning. In Advances in neural information processing systems, pp. 41–48, 2007. Jonathan Baxter. A model of inductive bias learning. Journal of artificial intelligence research, 12: 149–198, 2000. Shai Ben-David, Reba Schuller, et al. Exploiting task relatedness for multiple task learning. Lecture notes in computer science, pp. 567–580, 2003. Edwin V Bonilla, Kian M Chai, and Christopher Williams. Multi-task gaussian process prediction. In Advances in neural information processing systems, pp. 153–160, 2008. Leo Breiman and Jerome H Friedman. Estimating optimal transformations for multiple regression and correlation. Journal of the American statistical Association, 80(391):580–598, 1985. Alexis Conneau, Douwe Kiela, Holger Schwenk, Loic Barrault, and Antoine Bordes. Supervised learning of universal sentence representations from natural language inference data. arXiv preprint arXiv:1705.02364, 2017. Thomas M. Cover and Joy A. Thomas. Elements of Information Theory. Wiley-Interscience, New York, NY, USA, 1991. ISBN 0-471-06259-6. Jeff Donahue, Yangqing Jia, Oriol Vinyals, Judy Hoffman, Ning Zhang, Eric Tzeng, and Trevor Darrell. Decaf: A deep convolutional activation feature for generic visual recognition. In International conference on machine learning, pp. 647–655, 2014. Marylou Gabrie, Andre Manoel, Cl ´ ement Luneau, Jean Barbier, Nicolas Macris, Florent Krzakala, ´ and Lenka Zdeborova. Entropy and mutual information in models of deep neural networks. ´ CoRR, abs/1805.09785, 2018. URL http://arxiv.org/abs/1805.09785.
Yuqing Gao and Khalid M Mosalam. Deep transfer learning for image-based structural damage recognition. Computer-Aided Civil and Infrastructure Engineering.
Hans Gebelein. Das statistische problem der korrelation als variations-und eigenwertproblem und sein zusammenhang mit der ausgleichsrechnung. ZAMM-Journal of Applied Mathematics and Mechanics/Zeitschrift fur Angewandte Mathematik und Mechanik ¨ , 21(6):364–379, 1941.
Mark Andrew Hall. Correlation-based feature selection for machine learning. 1999.
Hermann O Hirschfeld. A connection between correlation and contingency. Mathematical Proceedings of the Cambridge Philosophical Society, 31(04):520–524, 1935.
Shao-Lun Huang, Anuran Makur, Lizhong Zheng, and Gregory W Wornell. An information-theoretic approach to universal feature selection in high-dimensional inference. In Information Theory (ISIT), 2017 IEEE International Symposium on, pp. 1336–1340. IEEE, 2017.
Laurent Jacob, Jean-philippe Vert, and Francis R Bach. Clustered multi-task learning: A convex formulation. In Advances in neural information processing systems, pp. 745–752, 2009.
Alex Krizhevsky and Geoffrey Hinton. Learning multiple layers of features from tiny images. 2009.
Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton. Imagenet classification with deep convolutional neural networks. In Advances in neural information processing systems, pp. 1097–1105, 2012.
Xuejun Liao and Lawrence Carin. Radial basis function network for multi-task learning. In Advances in Neural Information Processing Systems, pp. 792–802, 2006.
Anuran Makur, Fabian Kozynski, Shao-Lun Huang, and Lizhong Zheng. An efficient algorithm for ´ information decomposition and extraction. In Communication, Control, and Computing (Allerton), 2015 53rd Annual Allerton Conference on, pp. 972–979. IEEE, 2015.
Andreas Maurer. Transfer bounds for linear feature learning. Machine learning, 75(3):327–350, 2009.
Hanchuan Peng, Fuhui Long, and Chris Ding. Feature selection based on mutual information criteria of max-dependency, max-relevance, and min-redundancy. IEEE Transactions on pattern analysis and machine intelligence, 27(8):1226–1238, 2005.
Anastasia Pentina and Christoph H. Lampert. A pac-bayesian bound for lifelong learning. In International Conference on International Conference on Machine Learning, pp. II–991, 2014.
Lorien Y Pratt. Discriminability-based transfer between neural networks. In Advances in neural information processing systems, pp. 204–211, 1993.
Alfred R ´ enyi. On measures of dependence. ´ Acta mathematica hungarica, 10(3-4):441–451, 1959.
C. K. Shie, C. H. Chuang, C. N. Chou, M. H. Wu, and E. Y. Chang. Transfer representation learning for medical image analysis. In 2015 37th Annual International Conference of the IEEE Engineering in Medicine and Biology Society (EMBC), pp. 711–714, Aug 2015. doi: 10.1109/EMBC.2015.7318461.
Lisa Torrey and Jude Shavlik. Transfer learning. In Handbook of research on machine learning applications and trends: algorithms, methods, and techniques, pp. 242–264. IGI Global, 2010.
Lichen Wang, Jiaxiang Wu, Shao-Lun Huang, Lizhong Zheng, Xiangxiang Xu, Lin Zhang, and Junzhou Huang. An efficient approach to informative feature extraction from multimodal data. AAAI, 2019. URL https://arxiv.org/abs/1811.08979.
Mei Wang and Weihong Deng. Deep visual domain adaptation: A survey. Neurocomputing, 2018.
Ya Xue, Xuejun Liao, Lawrence Carin, and Balaji Krishnapuram. Multi-task learning for classification with dirichlet process priors. Journal of Machine Learning Research, 8(Jan):35–63, 2007.
Jason Yosinski, Jeff Clune, Yoshua Bengio, and Hod Lipson. How transferable are features in deep neural networks? In Advances in neural information processing systems, pp. 3320–3328, 2014.
Amir Zamir, Alexander Sax, William Shen, Leonidas Guibas, Jitendra Malik, and Silvio Savarese. Taskonomy: Disentangling task transfer learning. Computer Vision and Pattern Recognition (CVPR), 2018.
Yu Zhang. Heterogeneous-neighborhood-based multi-task local learning algorithms. In Advances in neural information processing systems, pp. 1896–1904, 2013.
# APPENDIX A INFERENCE USING LOCAL INFORMATION GEOMETRY
# A.1 A PRIMER ON ERROR EXPONENTS
To begin with, consider the binary hypothesis testing problem over $m$ i.i.d. sampled observations $\{ x ^ { ( i ) } \} _ { i = 1 } ^ { m } \triangleq x ^ { m }$ with the following hypotheses: $H _ { 0 } : x ^ { m } \sim P _ { 1 }$ or $H _ { 1 } : x ^ { m } \sim P _ { 2 }$ . Let $P _ { x ^ { m } }$ be the empirical distribution of the samples. The optimal test, i.e., the log likelihood ratio test can be stated in terms of information-theoretic quantities as follows:
$$\log { \frac { P _ { 1 } ( x ^ { m } ) } { P _ { 2 } ( x ^ { m } ) } } = m [ D ( P _ { x ^ { m } } | | P _ { 2 } ) - D ( P _ { x ^ { m } } | | P _ { 1 } ) ] \underset { H _ { 1 } } { \overset { H _ { 0 } } { \geq } } \log T$$
 Figure 10: The binary hypothesis testing problem. The blue curves shows the probility density functions for $P _ { 1 }$ and $P _ { 2 }$ . The rejection region and the acceptance region are highlighted in red and blue, respectively. The vertical line indicates the decision threshold.
Further, using Sannov’s theorem, we have that asymptotically the probability of type I error
$$\alpha = P _ { 1 } ( A ^ { c } ) \approx 2 ^ { - m D ( P _ { 1 } ^ { * } | | P _ { 1 } ) }$$
where $\begin{array} { r } { P _ { 1 } ^ { * } = \operatorname * { a r g m i n } _ { P \in A ^ { c } } D ( P | | P _ { 1 } ) } \end{array}$ and $\begin{array} { r } { A ^ { c } ( T ) = \{ x ^ { m } : D ( P _ { x ^ { m } } | | P _ { 2 } ) - D ( P _ { x ^ { m } } | | P _ { 1 } ) < \frac { 1 } { m } \log T \} } \end{array}$ denotes the rejection region. Similarly, for type II error
$$\beta = P _ { 2 } ( A ) \approx 2 ^ { - m D ( P _ { 2 } ^ { * } | | P _ { 2 } ) }$$
where $\begin{array} { r } { P _ { 2 } ^ { * } = \operatorname * { a r g m i n } _ { P \in A } D ( P | | P _ { 2 } ) } \end{array}$ and $\begin{array} { r } { A \ = \ \{ x ^ { m } : \ D ( P _ { x ^ { m } } | | P _ { 2 } ) - D ( P _ { x ^ { m } } | | P _ { 1 } ) > \frac { 1 } { m } \log T \} } \end{array}$ represents the acceptance region. (See Figure 10) The overall probability of error is $P _ { e } ^ { ( m ) } =$ $\alpha \bar { P } r ( H _ { 0 } ) + \beta P r ( \bar { H } _ { 1 } )$ and the best achievable exponent in the Bayesian probability of error (a.k.a. Chernoff exponent) is defined as:
$$E = \operatorname* { l i m } _ { m \infty } \operatorname* { m i n } _ { A \subseteq \mathcal { X } ^ { m } } - \frac { 1 } { m } \log P _ { e } ^ { ( m ) }$$
See Cover & Thomas (1991) for more background information on error exponents and its related theorems.
Now consider the same binary hypothesis testing problem, but with the local constraint $P _ { 1 } , P _ { 2 } \in$ $\mathcal { N } _ { \epsilon } ( P _ { 0 } ^ { \mathcal { X } } )$ . Let Pi(x)−P X0 (x)√ X denote the information vectors corresponding to Pi for i = 1, 2.
Makur et al. (2015) uses local information geometry to connect the error exponent in hypothesis testing to the length of certain information vectors, summarized in the following two lemmas.
Lemma 1. Given zero-mean, unit variance feature function $f ( x ) : \mathcal { X } \mathbb { R }$ , the optimal error exponent (a.k.a. Chernoff exponent) of this hypothesis testing problem is
$$E = \frac { \epsilon ^ { 2 } } { 8 } \left\| \phi _ { 1 } - \phi _ { 2 } \right\| ^ { 2 } + o ( \epsilon ^ { 2 } )$$
Lemma 2. Given zero-mean, unit variance feature function $f ( x ) : \mathcal { X } \mathbb { R } ,$ , the error exponent of a mismatched decision function of the form $\begin{array} { r } { l = \frac { 1 } { m } \sum _ { i = 1 } ^ { m } ( f ( x ^ { ( i ) } ) ) } \end{array}$ is
$$E _ { f } = \frac { \epsilon ^ { 2 } } { 8 } \langle \xi , \phi _ { 1 } - \phi _ { 2 } \rangle ^ { 2 } + o ( \epsilon ^ { 2 } )$$
where $\xi ( x ) = \sqrt { P _ { 0 } ( x ) } f ( x )$ is the feature vector associated with $f ( x )$ .
As our discussion of transferability mostly concerns with multi-dimensional features, we present the $k$ -dimensional generalization of Lemma 2 below: (Equation 1 in the main paper.)
Lemma 3. Given $k$ normalized feature functions $f ( x ) = [ f _ { 1 } ( x ) , \ldots , f _ { k } ( x ) ]$ , such that $\mathbb { E } [ f _ { i } ( X ) ] = 0$ for all $i$ , and $\operatorname { c o v } ( f ( X ) ) ~ = ~ { \bar { I } }$ , we define a $k$ -d statistics of the form $l ^ { k } = ( l _ { 1 } , . . . , l _ { k } )$ where $\begin{array} { r } { l _ { i } = \frac { 1 } { m } \sum _ { l = 1 } ^ { m } f _ { i } ( x ^ { ( l ) } ) } \end{array}$ . Let $\Xi ( x ) = [ \xi _ { 1 } ( x ) , \ldots , \xi _ { k } ( x ) ]$ be the corresponding feature vectors with $\xi _ { i } ( x ) = \sqrt { P _ { X } ( x ) } f _ { i } ( x )$ .
$$E _ { f } ^ { k } = \sum _ { i = 1 } ^ { k } E _ { f _ { i } } = \sum _ { i = l } ^ { k } \frac { \epsilon ^ { 2 } } { 8 } \left. \xi _ { i } , \phi _ { 1 } - \phi _ { 2 } \right. ^ { 2 } + o ( \epsilon ^ { 2 } )$$
Proof. According to Cramer’s theorem, the error exponent under ´ $P _ { i }$ is
$$E _ { i } ( \lambda ) = \operatorname* { m i n } _ { P \in \delta ( \lambda ) } D ( P | | P _ { i } )$$
where $\delta \left( \lambda \right) \triangleq \left\{ P : \mathbb { E } _ { P } [ f ( X ) ^ { k } ] = \lambda \mathbb { E } _ { P _ { 1 } } [ f ( X ) ^ { k } ] + ( 1 - \lambda ) \mathbb { E } _ { P _ { 2 } } [ f ( X ) ^ { k } ] \right\}$ . With the techniques developed in local information geometry, the above above problem is equivalent to the following problem:
$$E _ { i } ( \lambda ) = \operatorname* { m i n } _ { \tilde { \phi } _ { \theta ^ { k } } \in \sigma ( \lambda ) } \frac 1 2 \| \tilde { \phi } _ { \theta ^ { k } } - \phi _ { i } \| ^ { 2 }$$
where $\sigma ( \lambda ) \triangleq \left\{ \tilde { \phi } _ { \theta ^ { k } } : \left. \tilde { \phi } _ { \theta ^ { k } } , \xi _ { l } \right. = \langle \lambda \phi _ { 1 } + ( 1 - \lambda ) \phi _ { 2 } , \xi _ { l } \rangle , l = 1 , . . . , k \right\}$ and $i = 1 , 2$ . Further, using the equation $\begin{array} { r } { \tilde { \phi } _ { \theta ^ { k } } ( x ) = \sum _ { l = 1 } ^ { k } \theta _ { l } \xi _ { l } ( x ) + \phi _ { i } ( x ) - \alpha ( \theta ^ { k } ) \sqrt { P _ { 0 } ( x ) } + o ( \epsilon ) } \end{array}$ and the equation $\alpha ( \theta ^ { k } ) = o ( \epsilon ^ { 2 } )$ , it is easy to show that $E _ { 1 } ( \lambda ) = E _ { 1 } ( \lambda )$ when $\begin{array} { r } { \lambda = \frac { 1 } { 2 } } \end{array}$ . Then the overall error probability has the exponent as shown in Equation (1). □
# APPENDIX B HGR MAXIMAL CORRELATION AND THE ACE ALGORITHM
Given random variables $X$ and $Y$ , the HGR maximal correlation $\rho ( X ; Y )$ defined in Equation 2 is a generalization of the Pearson’s correlation coefficient to capture non-linear dependence between random variables. According to Renyi (1959), it satisfies all seven natural postulates of a suitable ´ dependence measure. Some notable properties are listed below:
1. $\rho ( X ; Y )$ is defined for any pair of random variables $X$ and $Y$ 2. $0 \leq \rho ( X ; Y ) \leq 1$ ; 3. $\rho ( X ; Y ) = 0$ if and only if $X$ and $Y$ are independent 4. $\rho ( X ; Y ) = 1$ if and only if $X$ and $Y$ are strictly dependent.
When the feature dimension is 1, the solution of the maximal HGR correlation is $\rho ( X ; Y ) = \sigma _ { 1 }$ , the largest singular value of the DTM matrix $\tilde { B }$ . For $k$ -dimensional features, $\textstyle \rho ( X ; Y ) = \sum _ { i } ^ { k } ( \sigma _ { i } )$ . However, computing $\tilde { B }$ requires estimating the joint probability $P _ { Y X }$ from data, which is inpractical in real applications. Breiman & Friedman (1985) proposed an efficient algorithm, alternating condition expectation (ACE), inspired by the power method for computing matrix singular values.
# Algorithm 1 The ACE algorithm
Require: training samples $\{ ( ( x ^ { ( i ) } , y ^ { ( i ) } ) : i = 1 , \ldots , m \}$
1: Initialize $g ( y ) \in \mathbb { R } ^ { k } , \forall y \in \mathcal { V }$ randomly 2: Center $g ( y ) g ( y ) - \mathbb { E } [ g ( y ) ]$ 3: repeat 4: $\bar { f } ( x ) \mathbb { E } [ g ( Y ) \mid X = x ] , \forall x \in \mathcal { X }$ 5: $f ( x ) \gets f ( x ) \mathbb { E } [ f ( X ) f ( X ) ^ { T } ] ^ { - \frac { 1 } { 2 } } , \forall x \in \mathcal { X }$ {Normalize f(x)} 6: $g ( y ) \mathbb { E } [ f ( X ) \mid Y = y ] , \forall y \in y$ 7: $g ( y ) g ( x ) \mathbb { E } [ g ( Y ) g ( Y ) ^ { T } ] ^ { - \frac { 1 } { 2 } } , \forall y \in \mathcal { Y }$ {Normalize g(y)} 8: until $\mathbb { E } [ f ( \dot { X } ) ^ { T } g \dot { ( Y ) } ]$ stops increasing
In Algorithm 1, we first initialize $g$ as a random $k$ -dimensional zero-mean function. Then iteratively update $f ( x )$ and $g ( y )$ for all $x \in X$ and $y \in Y$ . The conditional distributions on Line 4 and 6 are computed as the empirical average over $m$ samples. The normalization steps on Lines 5 and 7 can also be implemented using the Gram-Schmidt process. Note that the ACE algorithm has several variations in previous works, including a kernel-smoothed version (Breiman & Friedman (1985)) and a parallel version with improved efficiency (Huang et al. (2017)). An alternative formulation that supports continuous $X$ and large feature dimension $k$ has also been proposed recently (Wang et al. (2019)).
Next we look at the convergence property of the ACE algorithm. Let $f ( X ) , g ( Y )$ be the true maximal correlation functions, and let $\tilde { f } ( X ) , \tilde { g } ( Y )$ be estimations computed with Algorithm 1 from $m$ i.i.d. sampled training data. Similarly, denote by $\mathbb { E } [ f ( X ) g ( Y ) ]$ and $\hat { \mathbb { E } } _ { m } [ \tilde { f } ( X ) \tilde { g } ( Y ) ]$ the true and estimated maximal correlations, respectively. Using Sanov’s Theorem, we can show that for a small $\Delta > 0$ , the probability that the ratio between the true and estimated maximal correlation is within $1 \pm \Delta$ drops exponentially as the number of samples increases. Hence the ACE algorithm converges in exponential time. The following theorem gives the precise sampling complexity for $k = 1$ .
Theorem 2. For any random variables $X$ and $Y$ with joint probability distribution $P _ { Y X }$ , if $X$ and $Y$ are not independent, then for any $f : \mathcal { X } \to \mathbb { R }$ and $g : \mathcal { V } \to \mathbb { R }$ such that $\mathbb { E } [ f ^ { 2 } ( X ) ] = \mathbb { E } [ g ^ { 2 } ( Y ) ] = 1$ , we have that
$$- \operatorname* { l i m } _ { \Delta 0 ^ { + } } \frac { 1 } { \delta ^ { 2 } } \operatorname* { l i m } _ { m \infty } \frac { 1 } { m } \log [ P \{ | \frac { \hat { \mathbb { E } } _ { m } [ \tilde { f } ( X ) \tilde { g } ( Y ) ] } { \mathbb { E } [ f ( X ) g ( Y ) ] } - 1 | \geq \Delta \} ] = \frac { 1 } { 2 } \frac { \mathbb { E } [ f ( X ) g ( Y ) ] ^ { 2 } } { v a r [ f ( X ) g ( Y ) ] }$$
for any given $\Delta > 0$
# APPENDIX C PROOF OF THEOREM 1
To simplify the proof, we first consider the case when the feature function is 1-dimensional.i.e. $f : \mathcal { X } \to \mathbb { R }$ . We have the following lemma:
Lemma 4. Let $f : X \to \mathbb { R }$ be an arbitrary feature function of $X$ such that $\mathbb { E } [ f ( X ) ] = 0$ and $\mathbb { E } [ f ( X ) ^ { 2 } ] = 1$ , then $| | \tilde { B } \xi | | _ { F } ^ { 2 } = \mathbb { E } _ { P _ { Y } } [ ( \mathbb { E } [ f ( X ) | Y ] ) ^ { 2 } ]$ where $\xi$ is the feature vector corresponding to $f$ .
Proof. Since $\xi ( x ) = \sqrt { P _ { X } ( x ) } f ( x )$ , we have
$$\begin{array} { r l } & { \| \hat { B } \xi \| _ { F } ^ { 2 } = \xi ^ { \mathsf { T } } \hat { B } ^ { \mathsf { T } } \hat { B } \xi } \\ & { \qquad = \displaystyle \sum _ { y \in \mathcal { V } } \left( \displaystyle \sum _ { x \in \mathcal { X } } \left( \frac { P _ { Y X } ( y , x ) } { \sqrt { P _ { X } ( x ) } \sqrt { P _ { Y } ( y ) } } - \sqrt { P _ { X } ( x ) } \sqrt { P _ { Y } ( y ) } \right) \cdot \sqrt { P _ { X } ( x ) } f ( x ) \right) ^ { 2 } } \\ & { \qquad = \displaystyle \sum _ { y \in \mathcal { Y } } \left( \displaystyle \sum _ { x \in \mathcal { X } } \frac { P _ { Y X } ( y , x ) } { P _ { Y } ( y ) } \cdot f ( x ) - \displaystyle \sum _ { x \in \mathcal { X } } f ( x ) P _ { X } ( x ) \right) ^ { 2 } \cdot P _ { Y } ( y ) } \\ & { \qquad = \displaystyle \sum _ { y \in \mathcal { Y } } ( \mathbb { E } [ f ( X ) | Y = y ] - \mathbb { E } [ f ( x ) ] ) ^ { 2 } \cdot P _ { Y } ( y ) } \\ & { \qquad = \mathbb { E } _ { P _ { X } } [ ( \mathbb { E } [ f ( X ) | Y ] ) ^ { 2 } ] } \end{array}$$
The last equality uses the assumption that $\mathbb { E } [ f ( x ) ] = 0$ .
Theorem 3 (1D version of Theorem 1). Given $P _ { X | Y = 0 } , P _ { X | Y = 1 } \in \mathcal { N } _ { \epsilon } ^ { \mathcal { X } } ( P _ { 0 , X } )$ and features $f :$ $X \to \mathbb { R }$ such that $\mathbb { E } \left[ f ( X ) \right] = 0$ and $\mathbb { E } [ f ( X ) ^ { 2 } ] = 1$ , then there exists some constant $c$ independent of $f$ such that
$$\begin{array} { r } { E _ { f } = c \| \tilde { B } \xi \| _ { F } ^ { 2 } } \end{array}$$
Proof. From $\begin{array} { r } { \mathbb { E } [ f ( X ) ] = P _ { Y } ( 0 ) \mathbb { E } [ f ( X ) | Y = 0 ] + P _ { Y } ( 1 ) \mathbb { E } [ f ( X ) | Y = 1 ] = 0 } \end{array}$ , we first derive the following properties of the conditional expectations of $f ( x )$ :
$$\begin{array} { r l } & { \mathbb { E } [ f ( X ) | Y = 1 ] = - \left( \frac { P _ { Y } ( 0 ) } { P _ { Y } ( 1 ) } \right) \mathbb { E } [ f ( X ) | Y = 0 ] } \\ & { \mathbb { E } [ f ( X ) | Y = 0 ] = - \left( \frac { P _ { Y } ( 1 ) } { P _ { Y } ( 0 ) } \right) \mathbb { E } [ f ( X ) | Y = 1 ] } \end{array}$$
On the R.H.S. of Equation 5, we apply Lemma 4 to write
$$\begin{array} { r l } & { \| \tilde { B } \xi \| _ { F } ^ { 2 } = \mathbb { E } _ { P _ { Y } } \left[ ( \mathbb { E } \left[ f ( X ) | Y \right] ) ^ { 2 } \right] } \\ & { \qquad = \frac { P _ { Y } ( 0 ) P _ { Y } ( 1 ) + P _ { Y } ( 1 ) ^ { 2 } } { P _ { Y } ( 0 ) } ( \mathbb { E } \left[ f ( X ) | Y = 1 \right] ) ^ { 2 } } \end{array}$$
Next consider the L.H.S. of the equation, by Lemma 2, we have $\begin{array} { r } { E ( h ) = \frac { \epsilon ^ { 2 } } { 8 } \langle \xi , \phi _ { 1 } - \phi _ { 2 } \rangle ^ { 2 } + o ( \epsilon ^ { 2 } ) = } \end{array}$ $c _ { 0 } \langle \xi , \phi _ { 1 } - \phi _ { 2 } \rangle ^ { 2 }$ for some constant $c _ { 0 }$ .
$$\begin{array} { r l } & { \quad c _ { 0 } ( \xi , \dot { \phi } T _ { 1 } - \phi _ { T _ { 2 } } ) ^ { 2 } } \\ & { = - c _ { 0 } ( \displaystyle \sum _ { \ell \in \mathcal { X } } \frac { P _ { X } [ Y - ( X ) - ( P _ { X } ) ] ( Y - 1 ) } { \sqrt { P _ { X } ( X ) } } \cdot \sqrt { P _ { X } ( x ) } f ( x ) ) ^ { 2 } } \\ & { = c _ { 0 } ( | \mathbb { S } [ f ( X ) | Y = 0 ] - \mathbb { E } [ f ( X ) | Y = 1 ] ) ^ { 2 } } \\ & { = c _ { 0 } - \frac { ( P _ { Y } ( 0 ) + P _ { Y } ( 1 ) ) ^ { 2 } } { P _ { Y } ( 0 ) P _ { Y } ( 1 ) } \cdot ( \mathbb { E } [ f ( X ) | Y - 1 ] ) ( \mathbb { E } [ f ( X ) | Y = 0 ] ) } \\ & { = c _ { 0 } ( \frac { P _ { Y } ( 0 ) + P _ { Y } ( 1 ) } { P _ { Y } ( 0 ) } ) ^ { 2 } \cdot ( \mathbb { E } [ f ( X ) | Y - 1 ] ) ^ { 2 } } \\ & { = c _ { 0 } \frac { P _ { Y } ( 0 ) + P _ { Y } ( 1 ) } { P _ { Y } ( 0 ) P _ { Y } ( 1 ) } ( \frac { P _ { Y } ( 0 ) P _ { Y } ( 1 ) + P _ { Y } ( 1 ) ^ { 2 } } { P _ { Y } ( 0 ) } ) \cdot ( \mathbb { E } [ f ( X ) | Y - 1 ] ) ^ { 2 } } \\ & { = c _ { 0 } \frac { P _ { Y } ( 0 ) + P _ { Y } ( 1 ) } { P _ { Y } ( 0 ) P _ { Y } ( 1 ) } ( \frac { P _ { Y } ( 0 ) P _ { Y } ( 1 ) + P _ { Y } ( 1 ) ^ { 2 } } { P _ { Y } ( 0 ) } ) \cdot ( \mathbb { E } [ f ( X ) | Y - 1 ] ) ^ { 2 } } \\ & { = c _ { 1 } \| \mathbb { S } \xi | ^ { 2 } } \end{array}$$
For $k \geq 2$ , Lemma 4 can be restated as follows:
Lemma 5. Let $f ~ : ~ { { \cal { X } } } ~ \to ~ \mathbb { R } ^ { k }$ be a $k$ -dimensional feature function of $X$ , where $f ( x ) \ =$ $[ f _ { 1 } ( x ) , \ldots , f _ { k } ( x ) ]$ . Further we assume that $\mathbb { E } [ f ( X ) ] = { \dot { 0 } }$ and $\operatorname { c o v } ( f ( X ) ) = \mathbb { E } [ f ( X ) ^ { \mathrm { T } } f ( X ) ] = I$ . Then $| | \hat { B } \Xi | | _ { F } ^ { 2 } = \operatorname { t r } ( \operatorname { c o v } ( \mathbb { E } [ f ( X ) | Y ] ) )$ where columns of $\Xi$ are the information vectors corresponding to $f _ { 1 } ( x ) , \dots , f _ { k } ( x )$ .
Proof. First, note that
$$\begin{array} { r l } & { \tilde { B } \Xi = \left( \left[ \sqrt { \mathrm { P } _ { Y } } \right] ^ { - 1 } \mathrm { P } _ { Y X } \left[ \sqrt { \mathrm { P } _ { X } } \right] ^ { - 1 } - \sqrt { \mathrm { P } _ { Y } } \sqrt { \mathrm { P } _ { X } } ^ { \mathrm { T } } \right) \left[ \sqrt { \mathrm { P } _ { X } } \right] \mathrm { f } ( X ) } \\ & { \qquad = \left[ \sqrt { \mathrm { P } _ { Y } } \right] \left( \left[ \mathrm { P } _ { Y } \right] ^ { - 1 } \mathrm { P } _ { Y X } \mathrm { f } ( X ) - \mathbf { 1 } \cdot \mathbb { E } [ f ( X ) ] ^ { \mathrm { T } } \right) } \end{array}$$
where $\mathbf { 1 }$ is a column vector with all entries 1 and length $| \mathcal { D } |$ . Since $\mathbb { E } [ f ( X ) ] = 0$ , we have
$$\tilde { B } \Xi = \left[ \sqrt { \mathrm { P } _ { Y } } \right] \left( \left[ \mathrm { P } _ { Y } \right] ^ { - 1 } \mathrm { P } _ { Y X } \mathrm { f } ( X ) \right)$$
It follows that
$$\begin{array} { r l } & { | | \tilde { B } \Xi | | _ { F } ^ { 2 } = \mathrm { t r } ( \Xi ^ { \mathrm { T } } \tilde { B } ^ { \mathrm { T } } \tilde { B } \Xi ) } \\ & { \qquad = \mathrm { t r } ( ( [ \operatorname { P } _ { Y } ] ^ { - 1 } \operatorname { P } _ { Y X } \mathrm { f } ( X ) ) ^ { \mathrm { T } } [ \operatorname { P } _ { Y } ] ( [ \operatorname { P } _ { Y } ] ^ { - 1 } \operatorname { P } _ { Y X } \mathrm { f } ( X ) ) ) } \\ & { \qquad = \mathrm { t r } ( \mathbb { E } _ { P _ { Y } } [ ( \mathbb { E } [ f ( X ) | Y ] ] ^ { \mathrm { T } } ) ^ { \mathrm { T } } ( \mathbb { E } [ f ( X ) | Y ] ] ^ { \mathrm { T } } ) ] ) } \\ & { \qquad = \mathrm { t r } ( \mathrm { c o v } ( \mathbb { E } [ f ( X ) | Y ] ) ) } \end{array}$$
Finally, we derive the multi-dimensional case for Theorem 1.
Proof of Theorem 1. Using Lemma 5 and a similar argument as in the simplified proof, the R.H.S of the equation becomes
$$\begin{array} { r l } & { | | \tilde { B } \Xi | | _ { F } ^ { 2 } = \operatorname { t r } ( \operatorname { c o v } ( \mathbb { E } [ f ( X ) | Y ] ) ) } \\ & { \qquad = \operatorname { t r } ( \mathbb { E } _ { P _ { Y } } [ ( \mathbb { E } [ f ( X ) | Y ] ) ^ { \mathrm { T } } ) ^ { \mathrm { T } } ( \mathbb { E } [ f ( X ) | Y ] ^ { \mathrm { T } } ) ] ) } \\ & { \qquad = P _ { Y } ( 0 ) \mathbb { E } [ f ( X ) | Y = 0 ] ] ^ { \mathrm { T } } \mathbb { E } [ f ( X ) | Y = 0 ] ] + P _ { Y } ( 1 ) \mathbb { E } [ f ( X ) | Y = 1 ] ^ { \mathrm { T } } \mathbb { E } [ f ( X ) | Y = 1 ] } \\ & { \qquad = \frac { P _ { Y } ( 0 ) P _ { Y } ( 1 ) + P _ { Y } ( 1 ) ^ { 2 } } { P _ { Y } ( 0 ) } ( \mathbb { E } [ f ( X ) | Y = 1 ] ) ^ { \mathrm { T } } ( \mathbb { E } [ f ( X ) | Y = 1 ] ) } \end{array}$$
By Lemma 3, the L.H.S. of the equation can be written as $\begin{array} { r } { E _ { f } ^ { k } = c _ { 0 } \sum _ { i = l } ^ { k } \left. \xi _ { i } , \phi _ { 1 } - \phi _ { 2 } \right. ^ { 2 } } \end{array}$ for some constant $c _ { 0 }$ . It follows that
$$\begin{array} { r l } & { c _ { 0 } \displaystyle \sum _ { i = l } ^ { k } \left. \xi _ { i } , \phi _ { 1 } - \phi _ { 2 } \right. ^ { 2 } } \\ & { = c _ { 0 } \left( \left( \left( \mathbf { P } _ { X | Y = 0 } - \mathbf { P } _ { X | Y = 1 } \right) \right) ^ { \mathrm { { T } } } \mathbf { f } ( X ) \right) \left( \left( \left( \mathbf { P } _ { X | Y = 0 } - \mathbf { P } _ { X | Y = 1 } \right) \right) ^ { \mathrm { { T } } } \mathbf { f } ( X ) \right) ^ { \mathrm { { T } } } } \\ & { = c _ { 0 } \left( \mathbb { E } [ f ( X ) | Y = 0 ] - \mathbb { E } [ f ( X ) | Y = 1 ] \right) ^ { \mathrm { { T } } } \left( \mathbb { E } [ f ( X ) | Y = 0 ] - \mathbb { E } [ f ( X ) | Y = 1 ] \right) } \\ & { = c _ { 0 } \frac { P _ { Y } \left( 0 \right) + P _ { Y } \left( 1 \right) } { P _ { Y } \left( 0 \right) P _ { Y } \left( 1 \right) } \left( \frac { P _ { Y } \left( 0 \right) P _ { Y } \left( 1 \right) + P _ { Y } \left( 1 \right) ^ { 2 } } { P _ { Y } \left( 0 \right) } \right) \cdot \mathbb { E } \left[ f ( X ) | Y = 1 \right] ^ { \mathrm { { T } } } \mathbb { E } \left[ f ( X ) | Y = 1 \right] } \\ & { = c _ { 1 } \left. \tilde { B } \equiv \right. _ { L } ^ { 2 } } \end{array}$$
# APPENDIX D GENERALIZATION OF H-SCORE FOR ARBITRARY FEATURE SET
Since $\Xi = \left[ \sqrt { \mathrm { P } _ { X } } \right] \mathrm { f } ( X )$ and $\mathbb { E } [ f ( X ) ] = 0$ , we have
$$\Xi ^ { \mathrm { T } } \Xi = \left( \left[ { \sqrt { \operatorname { P } _ { X } } } \right] \operatorname { f } ( X ) \right) ^ { \mathrm { T } } \left( \left[ { \sqrt { \operatorname { P } _ { X } } } \right] \operatorname { f } ( X ) \right) = \mathbb { E } [ f ( X ) ^ { \mathrm { T } } f ( X ) ] = \operatorname { c o v } ( f ( X ) )$$
Equation (6) gives a more understandable expression of the normalization term. We can also write $\tilde { B } \Xi$ as follows:
$$\begin{array} { r l } & { \tilde { B } \Xi = \left( \left[ \sqrt { \mathrm { P } _ { Y } } \right] ^ { - 1 } \mathrm { P } _ { Y X } \left[ \sqrt { \mathrm { P } _ { X } } \right] ^ { - 1 } - \sqrt { \mathrm { P } _ { Y } } \sqrt { \mathrm { P } _ { X } } ^ { \mathrm { T } } \right) \left[ \sqrt { \mathrm { P } _ { X } } \right] \mathrm { f } ( X ) } \\ & { \qquad = \left[ \sqrt { \mathrm { P } _ { Y } } \right] \left( \left[ \mathrm { P } _ { Y } \right] ^ { - 1 } \mathrm { P } _ { Y X } \mathrm { f } ( X ) - \mathbf { 1 } \cdot \mathbb { E } [ f ( X ) ] ^ { \mathrm { T } } \right) } \end{array}$$
where 1 is a column vector with all entries 1 and length $| \mathcal { D } |$ , we have
$$\begin{array} { r l } & { \Xi ^ { \mathrm { T } } \tilde { B } ^ { \mathrm { T } } \tilde { B } \Xi = \left( [ \mathrm { P } _ { Y } ] ^ { - 1 } \operatorname* { P } _ { Y X } \mathrm { f } ( X ) - \mathbf { 1 } \cdot \mathbb { E } [ f ( X ) ] ^ { \mathrm { T } } \right) ^ { \mathrm { T } } [ \operatorname* { P } _ { Y } ] \left( [ \operatorname* { P } _ { Y } ] ^ { - 1 } \operatorname* { P } _ { Y X } \mathrm { f } ( X ) - \mathbf { 1 } \cdot \mathbb { E } [ f ( X ) ] ^ { \mathrm { T } } \right) } \\ & { \qquad = \mathbb { E } _ { P _ { Y } } \left[ ( \mathbb { E } [ f ( X ) | Y ] - \mathbf { 1 } \cdot \mathbb { E } [ f ( X ) ] ^ { \mathrm { T } } ) ^ { \mathrm { T } } ( \mathbb { E } [ f ( X ) | Y ] - \mathbf { 1 } \cdot \mathbb { E } [ f ( X ) ] ^ { \mathrm { T } } ) \right] } \\ & { \qquad = \mathrm { c o v } \left( \mathbb { E } [ f ( X ) | Y ] \right) \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \end{array}$$
On the other hand,
$$\begin{array} { r l } & { \lvert | \tilde { B } \Xi ( \Xi ^ { \mathrm { T } } \Xi ) ^ { - \frac { 1 } { 2 } } | | _ { F } ^ { 2 } = \mathrm { t r } \left( ( \Xi ^ { \mathrm { T } } \Xi ) ^ { - \frac { 1 } { 2 } } \Xi ^ { \mathrm { T } } \tilde { B } ^ { \mathrm { T } } \tilde { B } \Xi ( \Xi ^ { \mathrm { T } } \Xi ) ^ { - \frac { 1 } { 2 } } \right) } \\ & { \qquad = \mathrm { t r } \left( ( \Xi ^ { \mathrm { T } } \Xi ) ^ { - 1 } \Xi ^ { \mathrm { T } } \tilde { B } ^ { \mathrm { T } } \tilde { B } \Xi \right) } \\ & { \qquad = \mathrm { t r } \left( \mathrm { c o v } ( f ( X ) ) ^ { - 1 } \mathrm { c o v } ( \mathbb { E } [ f ( X ) | Y ] ) \right) } \end{array}$$
The last equality is derived by substituting (6) and (7) into (8).
# APPENDIX E H-SCORE AND SOFTMAX REGRESSION
In softmax regression, given $m$ training examples $\{ ( \boldsymbol { x } ^ { ( i ) } , \boldsymbol { y } ^ { ( i ) } ) \} _ { i = 1 } ^ { m }$ , the cross-entropy loss of the model is
$$\begin{array} { r l } & { \ell ( \boldsymbol { f } , \boldsymbol { \theta } ) = - \displaystyle \sum _ { i = 1 } ^ { m } \sum _ { k = 1 } ^ { | \mathcal { Y } | } \boldsymbol { 1 } \{ \boldsymbol { y } ^ { ( i ) } = k \} \log \frac { e ^ { - \theta _ { k } ^ { T } f ( \boldsymbol { x } ^ { ( i ) } ) } } { \sum _ { j = 1 } ^ { C } e ^ { - \theta _ { j } ^ { T } f ( \boldsymbol { x } ^ { ( i ) } ) } } } \\ & { \triangleq - \displaystyle \sum _ { i = 1 } ^ { m } \log Q _ { Y | \boldsymbol { X } } ( \boldsymbol { y } ^ { ( i ) } | \boldsymbol { x } ^ { ( i ) } ) } \\ & { = - \mathbb { E } _ { P _ { Y } } [ \log Q _ { Y | \boldsymbol { X } } ( Y | \boldsymbol { X } ) ] } \end{array}$$
Minimizing $\ell$ is equivalent to minimizing $D \left( P _ { Y X } | | P _ { X } Q _ { Y | X } \right)$ where $P _ { Y X }$ is the joint empirical distribution of $( X , Y )$ .
Using information geometry, it can be shown that under a local assumption
$$\underset { f , \theta } { \arg \operatorname* { m i n } } D \left( P _ { Y X } | | P _ { X } Q _ { Y | X } \right) = \underset { \Psi , \Phi } { \arg \operatorname* { m i n } } \frac { 1 } { 2 } | | \tilde { B } - \Psi \Phi ^ { \mathrm { T } } | | _ { F } ^ { 2 } + o ( \epsilon ^ { 2 } )$$
which reveals a close connection between log loss and the modal decomposition of $\tilde { B }$ . In consequence, it is reasonable to measure the classification performance with $\lVert \tilde { B } - \Psi \Phi ^ { \mathrm { T } } \rVert _ { F } ^ { 2 }$ given a pair of $( f , \theta )$ associated with $( \Psi , \Phi )$ .
In the context of estimating transferability, we are interested in a one-sided problem, where $\Phi _ { S }$ is given by the source feature and $\Psi$ becomes the only variable.
$$\operatorname* { m i n } _ { \Psi } \| \tilde { B } _ { T } - \Psi \Phi _ { S } ^ { \mathrm { T } } \|$$
 Figure 11: Comparing task transferability (H-score) and transfer log-loss on synthesized tasks.
Training the network is equivalent to finding the optimal weight $\Psi ^ { * }$ that minimizes the log-loss. By taking the derivative of the Objective function with respect to $\Psi$ , we get
$$\Psi ^ { * } = \tilde { B } _ { T } \Phi _ { S } ( \Phi _ { S } ^ { \mathrm { T } } \Phi _ { S } ) ^ { - 1 }$$
Substituting (14) in the Objective of (13), we can derive the following close-form solution for the log loss.
$$\| \tilde { B } _ { T } ^ { \mathrm { T } } \tilde { B } _ { T } \| _ { F } ^ { 2 } - \| \tilde { B } _ { T } \Phi _ { S } ( \Phi _ { S } ^ { \mathrm { T } } \Phi _ { S } ) ^ { - \frac { 1 } { 2 } } \| _ { F } ^ { 2 }$$
The first term in (15) is fixed given $\mathcal { T } _ { T }$ while the second term has exactly the form of $_ \mathrm { H }$ -score. This implies that log loss is negatively linearly related to $_ \mathrm { H }$ -score.
We demonstrates this relationship experimentally, using a collection of synthesized tasks (Figure 11). In particular, the target task is generated based on a random stochastic matrix $\mathrm { P } _ { Y _ { 0 } | X }$ , and 20 source tasks are generated with the conditional probability matrix $\mathrm { P } _ { Y _ { i } | X } = \mathrm { P } _ { Y _ { 0 } | X } + i \lambda \bar { I }$ for some positive constant $\lambda$ .
The universal minimum error probability features for each source task are used as the source features $f _ { S _ { i } } ( x )$ , while the respective log-loss are obtained through training a simple neural network in Figure 2 with cross-entropy loss. The relationship is clearly linear with a constant offset.
# APPENDIX F DTM AND MUTUAL INFORMATION
Proposition 1. Under the local assumption that $P _ { X | Y } \in N _ { \epsilon } ( P _ { X } )$ , mutual information $I ( X ; Y ) =$ $\frac { 1 } { 2 } | | \tilde { B } | | _ { F } ^ { 2 } + o ( \epsilon ^ { 2 } )$ , where $\tilde { B }$ of the DTM matrix of $X$ and $Y$ .
Proof. First, we define φX|Yy (x) = PX|Y (x|y)−PX(x)√ and let $\Phi ^ { X | Y } \in \mathbb { R } ^ { | \mathcal { X } | \times | y | }$ denote its matrix version. Then we have
$$\epsilon \Phi ^ { X | Y } [ \sqrt { P _ { Y } } ] = [ \sqrt { P _ { X } } ] ^ { - 1 } ( P _ { X Y } - P _ { X } ) [ \sqrt { P _ { Y } } ] = \tilde { B } ^ { T }$$
Next, we express the mutual information in terms of information vector $\phi ^ { X | Y }$ ,
$$\begin{array} { l } { { I ( X ; Y ) = I ( Y ; X ) = \displaystyle \sum _ { y \in \mathcal { Y } } P _ { Y } ( y ) D _ { K L } ( P _ { X | Y } | | P _ { X } ) } } \\ { { \displaystyle ~ = \frac { \epsilon ^ { 2 } } { 2 } \sum _ { y \in \mathcal { Y } } P _ { Y } ( y ) \| \phi _ { y } ^ { X | Y } | ^ { 2 } + o ( \epsilon ^ { 2 } ) } } \\ { { \displaystyle ~ = \frac { 1 } { 2 } | | \epsilon \Phi ^ { X | Y } [ \sqrt { P _ { Y } } ] | _ { F } ^ { 2 } + o ( \epsilon ^ { 2 } ) } } \\ { { \displaystyle ~ = \frac { 1 } { 2 } | | \tilde { B } | | _ { F } ^ { 2 } + o ( \epsilon ^ { 2 } ) } } \end{array}$$
# APPENDIX G SUPPLEMENTARY RESULTS ON EXPERIMENT 5.2
# G.1 COMPARISON OF H-SCORES AND AFFINITIES
Table 1, with columns representing source tasks and rows representing target tasks. For each target task, the upper row shows our results while the lower one shows the results in Zamir et al. (2018). Score values are included in parenteses.
Table 1: Transferability ranking comparison, between H-score’s estimation and task affinity
<table><tr><td>Tasks</td><td>2D Edges</td><td>2D Keypoints</td><td>3D Edges</td><td>3D Keypoints</td><td>Reshading</td><td>Depth</td><td>Object Class.</td><td>Scene Class.</td></tr><tr><td rowspan="2">2D Edges</td><td>1 (1.8216)</td><td>2(1.7334)</td><td>5 (1.5704)</td><td>6(1.5696)</td><td>4 (1.6146)</td><td>3 (1.6201)</td><td>7(1.5097)</td><td>8(1.4402)</td></tr><tr><td>1 (0.0389)</td><td>2 (0.0117)</td><td>4 (5.8920e-5)</td><td>3 (8.8011e-5)</td><td>7(2.9001e-5)</td><td>8 (2.2110e-5)</td><td>5 (4.9141e-5)</td><td>6(4.8720e-5)</td></tr><tr><td rowspan="2">2D Keypoints</td><td>2 (1.6698)</td><td>1 (1.7859)</td><td>7 (1.5248)</td><td>5 (1.5287)</td><td>4 (1.5481)</td><td>3 (1.5632)</td><td>6(1.5253)</td><td>8 (1.4725)</td></tr><tr><td>2 (0.0002)</td><td>1 (0.0542)</td><td>7 (7.7797e-5)</td><td>5 (8.1029e-5)</td><td>6 (7.8464e-5)</td><td>8 (7.2724e-5)</td><td>3 (0.0002)</td><td>4(0.0001)</td></tr><tr><td rowspan="2"> 3D Edges</td><td>5(1.4828)</td><td>4(1.4910)</td><td>3 (1.5167)</td><td>7 (1.4701)</td><td>2 (1.5405)</td><td>1 (1.6739)</td><td>8 (1.4644)</td><td>6 (1.4730)</td></tr><tr><td>6(0.0117)</td><td>7(0.0108)</td><td>1 (0.1179)</td><td>2 (0.0734)</td><td>4 (0.0622)</td><td>3(0.0636)</td><td>8(0.0094)</td><td>5(0.0151)</td></tr><tr><td rowspan="2">3DKeypoints</td><td>6(1.5375)</td><td>5 (1.5466)</td><td>4 (1.5910)</td><td>3 (1.6456)</td><td>1 (1.7198)</td><td>2 (1.7122)</td><td>7(1.4709)</td><td>8 (1.4121)</td></tr><tr><td>5(0.0141)</td><td>6(0.0136)</td><td>2 (0.0531)</td><td>1(0.1275)</td><td>3 (0.0400)</td><td>4 (0.0247)</td><td>7(0.0132)</td><td>8(0.0121)</td></tr><tr><td rowspan="2">Reshading</td><td>5 (1.5504)</td><td>6 (1.5426)</td><td>3 (1.8174)</td><td>4 (1.7990)</td><td>1 (2.2339)</td><td>2 (2.1200)</td><td>7 (1.4774)</td><td>8 (1.3804)</td></tr><tr><td>6(0.0147)</td><td>8 (0.0143)</td><td>2 (0.0781)</td><td>4(0.0545)</td><td>1(0.1121)</td><td>3(0.0765)</td><td>7(0.0144)</td><td>5(0.0174)</td></tr><tr><td rowspan="2">Depth</td><td>6(1.6542)</td><td>5(1.6870)</td><td>3 (1.8504)</td><td>4 (1.8176)</td><td>2 (2.1700)</td><td>1 (2.2441)</td><td>7(1.6008)</td><td>8 (1.5099)</td></tr><tr><td>7(0.0175)</td><td>8 (0.0154)</td><td>3(0.0595)</td><td>4(0.0617)</td><td>2 (0.0867)</td><td>1 (0.0989)</td><td>6(0.0217)</td><td>5 (0.0237)</td></tr><tr><td rowspan="2">Object Class.</td><td>5 (22.866)</td><td>4 (23.627)</td><td>7 (22.371)</td><td>8 (21.950)</td><td>6 (22.452)</td><td>3(23.697)</td><td>1 (33.468)</td><td>2 (28.013)</td></tr><tr><td>7(0.0205)</td><td>6(0.0217)</td><td>3 (0.0350)</td><td>4(0.0318)</td><td>5 (0.0286)</td><td>8(0.0147)</td><td>1 (0.0959)</td><td>2 (0.0774)</td></tr><tr><td rowspan="2">Scene Class.</td><td>5 (14.575)</td><td>4 (15.074)</td><td>7 (14.206)</td><td>8 (13.801)</td><td>6(14.332)</td><td>3 (15.474)</td><td>2 (25.750)</td><td>1 (25.962)</td></tr><tr><td>8(0.0149)</td><td>7(0.0165)</td><td>3(0.0335)</td><td>4(0.0305)</td><td>5(0.0263)</td><td>6(0.0198)</td><td>2 (0.0504)</td><td>1 (0.1474)</td></tr></table>
Here we present some detailed results on the comparison between H-score and the affinity score in Zamir et al. (2018) for pairwise transfer.
The results of the classification tasks are shown in Figure 12 and the results of Depth is shown in 13. We can see in general, although affinity and transferability have totally different value ranges, they tend to agree on the top few ranked tasks.
 Figure 12: Source task transferability ranking for classification tasks. For each target task, the left figure shows H-score results, and the right figure shows task affinity results.
# G.2 LABEL QUANTIZATION
During the quantization process of the pixel-to-pixel task labels (ground truth images), we are primarily concerned with two factors: computational complexity and information loss. Too much information loss will lead to bad approximation of the original problems. On the other hand, having little information loss requires larger cluster size and computation cost.
Figure (14) shows that even after quantization, much of the information in the images are retained.
To test the sensitivity of the cluster size, we used cluster centroids to recover the ground truth image pixel-by-pixel. The 3D occlusion Edge detection results on a sample image is shown in Figure 15. When the cluster number is set to $N = 5$ (right), most detected Edges in the ground truth image (left) are lost. We found that $N = 1 6$ strikes a good balance between recoverability and computation cost.
 transfer to Depth from the other tasks Figure 13: Comparison between source task rankings for Depth. with H-score results on the left and affinity scores Zamir et al. (2018) on the right. The Top 3 transferable source tasks in both methods are the same: Depth, Image Reshading and 3D Occlusion Edges.
 Figure 14: Quantization. Recover is done with the centroid of corresponding cluster of each pixel.
 Figure 15: Effect of quantization cluster size for 3D occlusion Edge detection.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608# Efficient and Modular Implicit Differentiation
Anonymous Author(s) Affiliation Address email
# Abstract
1 Automatic differentiation (autodiff) has revolutionized machine learning. It allows 2 expressing complex computations by composing elementary ones in creative ways 3 and removes the burden of computing their derivatives by hand. More recently, 4 differentiation of optimization problem solutions has attracted widespread attention 5 with applications such as optimization as a layer, and in bi-level problems such as 6 hyper-parameter optimization and meta-learning. However, the formulas for these 7 derivatives often involve case-by-case tedious mathematical derivations. In this 8 paper, we propose a unified, efficient and modular approach for implicit differentia 9 tion of optimization problems. In our approach, the user defines (in Python in the 10 case of our implementation) a function $F$ capturing the optimality conditions of 11 the problem to be differentiated. Once this is done, we leverage autodiff of $F$ and 12 implicit differentiation to automatically differentiate the optimization problem. Our 13 approach thus combines the benefits of implicit differentiation and autodiff. We 14 show that seemingly simple principles allow to recover many recently proposed im 15 plicit differentiation methods and create new ones easily. We demonstrate the ease 16 of formulating and solving bi-level optimization problems using our framework. 17 We also showcase an application to the sensitivity analysis of molecular dynamics.
# 18 1 Introduction
19 Automatic differentiation (autodiff) is now an inherent part of machine learning software. It allows 20 expressing complex computations by composing elementary ones in creative ways and removes 21 the tedious burden of computing their derivatives by hand. The differentiation of optimization 22 problem solutions has found many applications. A classical example is bi-level optimization, which 23 typically involves computing the derivatives of a nested optimization problem in order to solve 24 an outer one. Examples of applications in machine learning include hyper-parameter optimization 25 [19, 63, 57, 30, 10, 11], neural networks [46], and meta-learning [31, 59]. Another line of applications 26 is “optimization as a layer” [42, 6, 51, 27, 36, 7], which usually includes regularization or constraints 27 in the optimization problem in order to impose desirable structure on the layer output. In addition 28 to providing well sought-for interpretability, recent research indicates that such structure could be 29 beneficial in order to improve generalization of neural networks [20]. 30 Since optimization problem solutions typically do not enjoy an explicit formula in terms of their 31 inputs, autodiff cannot be used directly to differentiate these functions. In recent years, two main 32 approaches have been developed to circumvent this problem. The first one consists in unrolling the 33 iterations of an optimization algorithm and to use the final iteration as a proxy for the optimization 34 problem solution [68, 28, 25, 31]. An advantage of this approach is that autodiff through the algorithm 35 iterates can then be used transparently. However, this requires a reimplementation of the algorithm 36 using the autodiff system, and not all algorithms are necessarily autodiff friendly. Moreover, forward 37 mode autodiff has time complexity that scales linearly with the number of variables and reverse-mode 38 autodiff has memory complexity that scales linearly with the number of algorithm iterations. A second 39 approach is to see optimization problem solutions as implicitly-defined functions of certain optimality 40 conditions. Examples include stationary conditions [9, 46], KKT conditions [19, 35, 6, 53, 52] and 41 the proximal gradient fixed point [51, 10, 11]. An advantage of such implicit differentiation is that 42 a reimplementation is not needed, allowing to build upon state-of-the-art software. However, so 43 far, obtaining the implicit differentiation formulas required a case-by-case tedious mathematical 44 derivation. Recent work [2] attempts to address this issue by adding implicit differentiation on top of 45 cvxpy [26]. This works by reducing all convex optimization problems to a conic program and using 46 conic programming’s optimality conditions to derive an implicit differentiation formula. While this 47 approach is very generic, solving a convex optimization problem using a conic programming solver— 48 an ADMM-based splitting conic solver [54] in the case of cvxpy—is rarely the state-of-the-art 49 approach for each particular problem instance. 50 In this work, we adopt a different strategy, which allows to easily add implicit differentiation on top 51 of existing solvers. In our approach, the user defines (in Python in the case of our implementation) 52 a mapping function $F$ capturing the optimality conditions of the problem solved by the algorithm. 53 Once this is done, we leverage autodiff of $F$ combined with implicit differentiation techniques to 54 automatically differentiate the optimization problem solution. In this way, our approach is very 55 generic and still the efficiency of state-of-the-art solvers. It therefore combines the benefits of implicit 56 differentiation and autodiff. To summarize, we make the following contributions.
• We delineate extremely general principles for implicitly differentiating through an optimization problem solution. Our approach can be seen as “hybrid”, in the sense that it combines implicit differentiation with autodiff of the optimality conditions. • We show how to instantiate our framework in order to recover many recently-proposed implicit differentiation schemes, thereby providing a unifying perspective. We also obtain new implicit differentiation schemes, such as the one based on the mirror descent fixed point. • On the theoretical side, we provide new bounds on the Jacobian error when the optimization problem is only solved approximately. • We describe a JAX implementation and provide a blueprint for implementing our approach in other frameworks. We will open-source a full-fledged library for implicit differentiation in JAX. • We implement four illustrative applications, demonstrating our framework’s ease of use.
68 In essence, our implementation significantly extends JAX’s default autodiff system in context of the 69 numerical optimization domain. From an end user’s perspective, autodiff with JAX simply becomes 70 more efficient if they use solvers with implicit differentiation set up by our framework. 71 Notation. We denote the gradient and Hessian of $f \colon { \mathbb { R } ^ { d } } \to { \mathbb { R } }$ evaluated at $x \in \mathbb { R } ^ { d }$ by $\nabla f ( x ) \in$ 72 $\mathbb { R } ^ { d }$ and $\nabla ^ { 2 } f ( x ) \ \in \ \mathbb { R } ^ { d \times d }$ . We denote the Jacobian of $F \colon \mathbb { R } ^ { d } \ \ \mathbb { R } ^ { p }$ evaluated at $x \in \mathbb { R } ^ { d }$ by 73 $\partial F ( x ) \in \mathbb { R } ^ { p \times d }$ . When $f$ or $F$ have several arguments, we denote the gradient, Hessian and Jacobian 74 in the $i ^ { \mathrm { { t h } } }$ argument by $\nabla _ { i }$ , $\nabla _ { i } ^ { 2 }$ and $\partial _ { i }$ , respectively. The standard probability simplex is denoted 75 by $\triangle ^ { d } : = \{ x \in \mathbb { R } ^ { d } \colon \| x \| _ { 1 } = 1 , x \geq 0 \}$ . For any set $\mathcal { C } \subset \mathbb { R } ^ { d }$ , we denote by $I _ { \mathcal { C } }$ the function 76 $\mathbb { R } ^ { d } \to \mathbb { R } \cup \{ + \infty \}$ where $I _ { \mathit { C } } ( x ) = 0$ if $x \in { \mathcal { C } }$ , $I _ { C } ( x ) = + \infty$ otherwise. For a vector or matrix $A$ , we 77 note $\| A \|$ the Frobenius (or Euclidean) norm, and $\| A \| _ { \mathrm { o } p }$ the operator norm.
# 2 Proposed framework: combining implicit differentiation and autodiff
# 2.1 General principles
Overview. Contrary to unrolling of algorithm iterations, implicit differentiation typically involves a manual, sometimes complicated, mathematical derivation. For instance, numerous works [19, 35, 6, 53, 52] use Karush–Kuhn–Tucker (KKT) conditions in order to relate a constrained optimization problem’s solution to its inputs, and to manually derive a formula for its derivatives. The derivation and implementation is typically case-by-case.
85 In this work, we propose a general way to easily add implicit differentiation on top of existing solvers. 86 In our approach, the user defines (in Python in the case of our implementation) a mapping function 87 $F$ capturing the optimality conditions of the problem solved by the algorithm. We provide reusable 88 building blocks to easily express such $F$ . Once this is done, we leverage autodiff of $F$ combined with 89 implicit differentiation to automatically differentiate the optimization problem solution. A simple 90 illustrative example is given in Figure 1.
 Figure 1: Example: adding implicit differentiation on top of a ridge regression solver. The function $f ( x , \theta )$ defines the objective function and the mapping $F$ , here simply equation (4), captures the optimality conditions. The decorator @custom_root (provided by our library) automatically adds implicit differentiation to the solver for the user. The last line evaluates the Jacobian at $\theta = 1 0$ .
91 Differentiating a root. Let $F \colon { \mathbb { R } } ^ { d } \times { \mathbb { R } } ^ { n } \to { \mathbb { R } } ^ { d }$ be a user-provided mapping, capturing the optimality conditions of a problem. An optimal solution, denoted 92 $x ^ { \star } ( \theta )$ , should be a root of $F$ :
$$F ( x ^ { \star } ( \theta ) , \theta ) = 0 .$$
93 We can see $x ^ { \star } ( \theta )$ as an implicitly defined function of $\theta \in \mathbb { R } ^ { n }$ , i.e., $x ^ { \star } \colon { \mathbb { R } } ^ { n } \to { \mathbb { R } } ^ { d }$ . Our goal 94 is to differentiate $x ^ { \star } ( \theta )$ w.r.t. $\theta$ . From the implicit function theorem [44], if $F$ is continuously 95 differentiable and the Jacobian $\partial _ { 1 } F$ evaluated at $x ^ { \star } ( \theta ) \times \theta$ is a square invertible matrix, then ${ \partial x ^ { \star } ( \theta ) }$ 96 exists. Using the chain rule, we know that the Jacobian ${ \partial x ^ { \star } ( \theta ) }$ satisfies
$$\partial _ { 1 } F ( x ^ { \star } ( \theta ) , \theta ) \partial x ^ { \star } ( \theta ) + \partial _ { 2 } F ( x ^ { \star } ( \theta ) , \theta ) = 0 .$$
Computing 97 ${ \partial x ^ { \star } ( \theta ) }$ boils down to the resolution of the linear system of equations
$$\underbrace { - \partial _ { 1 } F ( x ^ { \star } ( \theta ) , \theta ) } _ { A \in \mathbb { R } ^ { d \times d } } \underbrace { \partial x ^ { \star } ( \theta ) } _ { J \in \mathbb { R } ^ { d \times n } } = \underbrace { \partial _ { 2 } F ( x ^ { \star } ( \theta ) , \theta ) } _ { B \in \mathbb { R } ^ { d \times n } }$$
98 When (1) is a one-dimensional root finding problem $\dot { d } = 1 \dot { }$ ), (2) becomes particularly simple since 99 $\nabla x ^ { \star } ( \theta ) = B ^ { \top } / A$ , where $A$ is a scalar value. 100 We will show that existing and new implicit differentiation methods all reduce to this simple principle. 101 We call our approach hybrid, since it combines implicit differentiation (it involves the resolution of a 102 linear system) with the autodiff of the optimality conditions $F$ . Our approach is efficient as it can be 103 added on top of any state-of-the-art solver and modular as the optimality conditon specification is 104 decoupled from the implicit differentiation mechanism.
Differentiating a fixed point. We will encounter numerous applications where 05 $x ^ { \star } ( \theta )$ is implicitly 06 defined through a fixed point iteration:
$$x ^ { \star } ( \theta ) = T ( x ^ { \star } ( \theta ) , \theta ) ,$$
where 107 $T \colon { \mathbb { R } } ^ { d } \times { \mathbb { R } } ^ { n } \to { \mathbb { R } } ^ { d }$ . This can be seen as a particular case of (1) with
$$F ( x ^ { \star } ( \theta ) , \theta ) = T ( x ^ { \star } ( \theta ) , \theta ) - x ^ { \star } ( \theta ) .$$
108 In this case, using the chain rule, we have
$$A = - \partial _ { 1 } F ( x ^ { \star } ( \theta ) , \theta ) = I - \partial _ { 1 } T ( x ^ { \star } ( \theta ) , \theta ) \quad \mathrm { a n d } \quad B = \partial _ { 2 } F ( x ^ { \star } ( \theta ) , \theta ) = \partial _ { 2 } T ( x ^ { \star } ( \theta ) , \theta ) .$$
109 Computing JVPs and VJPs. In practice, all we need to know from $F$ is how to left-multiply or 110 right-multiply $\partial _ { 1 } F$ and $\partial _ { 2 } F$ with a vector of appropriate size. These are called vector-Jacobian 111 product (VJP) and Jacobian-vector product (JVP), and are useful for integrating $x ^ { \star } ( \theta )$ with reverse 112 mode and forward-mode autodiff, respectively. Often times, $F$ will be explicitly defined. In this case, 113 computing the VJP or JVP can be done via autodiff. Other times, $F$ may itself be implicitly defined, 114 for instance when $F$ involves the solution of a variational problem. In this case, computing the VJP 115 or JVP will itself involve implicit differentiation. 116 The right-multiplication (JVP) between $J = \partial x ^ { \star } ( \theta )$ and a vector $v$ , $J v$ , can be computed efficiently 117 by solving $A ( J v ) = B v$ . The left-multiplication (VJP) of $v ^ { \top }$ with $J , v ^ { \top } J$ , can be computed by first 118 solving $A ^ { \top } u = v$ . Then, we can obtain $v ^ { \top } J$ by $\boldsymbol { v } ^ { \top } \boldsymbol { J } = \boldsymbol { u } ^ { \top } \boldsymbol { A } \boldsymbol { J } = \boldsymbol { u } ^ { \top } \boldsymbol { B }$ . Note that when $B$ changes 119 but $A$ and $v$ remain the same, we do not need to solve $A ^ { \top } u = v$ once again. This allows to compute 120 the VJP w.r.t. different variables while solving only one linear system. 121 To solve these linear systems, we can use the conjugate gradient method [39] when $A$ is positive 122 semi-definite and GMRES [61] or BiCGSTAB [66] when $A$ is not. All algorithms are matrix-free, 123 i.e., they only require matrix-vector products (linear maps). Thus, all we need from $F$ is its JVPs 124 or VJPs. An alternative to GMRES/BiCGSTAB is to solve the normal equation $A A ^ { \top } u = A v$ using 125 conjugate gradient, which we find faster in some scenarios. 126 Pre-processing and post-processing mappings. Often times, the goal is not to differentiate $\theta$ per 127 se, but the parameters of a function producing $\theta$ . One example of such pre-processing is to convert 128 the parameters to be differentiated from one form to another canonical form, such as a quadratic 129 program [6] or a conic program [2]. Another example is when $x ^ { \star } ( \theta )$ is used as the output of a neural 130 network layer, in which case $\theta$ is produced by the previous layer. Likewise, $x ^ { \star } ( \theta )$ will often not 131 be the final output we want to differentiate. One example of such post-processing is when $x ^ { \star } ( \theta )$ is 132 the solution of a dual program and we apply the dual-primal mapping to recover the solution of the 133 primal program. Another example is the application of a loss function, in order to reduce $x ^ { \star } ( \theta )$ to a 134 scalar value. In all these cases, we leave the differentiation of the pre/post-processing mappings to 135 the autodiff system, allowing us to compose functions in complex ways. 136 Usage and implementation details. Our implementation is based on JAX [17, 34]. JAX’s autodiff 137 features enter the picture in at least two ways: (i) we lean heavily on JAX within our implementation, 138 and (ii) we integrate the differentiation routines introduced by our framework into JAX’s existing 139 autodiff system. In doing the latter, we override JAX’s default autodiff behavior (e.g. of differentiating 140 transparently through an iterative solver’s unrolled iterations). 141 We delineate here what features are needed from an autodiff system to implement our proposed 142 framework. As mentioned, we only need access to $F$ through the JVP or VJP of $\partial _ { 1 } F$ and $\partial _ { 2 } F$ . 143 Since the definition of $F$ will often include a gradient mapping $\nabla _ { 1 } f ( x , \theta )$ (see examples in $\ S 2 . 2 \AA ,$ ), 144 second-order derivatives need also be supported. Our library provides two decorators, custom_root 145 and custom_fixed_point, for adding implicit differentiation on top of a solver, given optimality 146 conditions $F$ or fixed point iteration $T$ . This functionality requires the ability to add custom JVP 147 and/or VJP to a function. All these features are supported by recent autodiff systems, including JAX 148 [17], TensorFlow [1] and PyTorch [56]. Our implementation, made in JAX, also uses JAX-specific 149 features. We make extensive use of automatic batching with ${ \mathrm { j a x . v m a p } }$ , JAX’s vectorizing map 150 transformation. In order to solve the normal equation ${ \bar { A } } A ^ { \top } u \stackrel { = } { = } A v$ , we also use JAX’s ability to 151 automatically transpose a linear map using jax.linear_transpose [33].
# 2.2 Examples
We now give various examples of mapping $F$ or fixed point iteration $T$ , recovering existing implicit differentiation methods and creating new ones. Each choice of $F$ or $T$ implies different trade-offs in terms of computational oracles; see Table 1. Source code examples are given in Appendix A.
56 Stationary point condition. The simplest example is to differentiate through the implicit function
$$x ^ { \star } ( \theta ) = \operatorname * { a r g m i n } _ { x \in \mathbb { R } ^ { d } } f ( x , \theta ) ,$$
where 157 $f \colon { \mathbb { R } ^ { d } } \times { \mathbb { R } ^ { n } } \to { \mathbb { R } }$ is twice differentiable. In this case, $F$ is simply the gradient mapping
$$F ( x , \theta ) = \nabla _ { 1 } f ( x , \theta ) .$$
Table 1: Summary of optimality condition mappings. Oracles are accessed through their JVP or VJP.
<table><tr><td>Name</td><td>Equation</td><td>Solution needed</td><td>Oracles needed</td></tr><tr><td>Stationary</td><td>(4), (5)</td><td>Primal</td><td>Vif</td></tr><tr><td>KKT</td><td>(6)</td><td>Primal and dual</td><td>Vif,H,G,δH,δG</td></tr><tr><td>Proximal gradient</td><td>(7)</td><td>Primal</td><td>Vif,proxng</td></tr><tr><td>Projected gradient</td><td>(9)</td><td>Primal</td><td>Vif,projc</td></tr><tr><td>Mirror descent</td><td>(11)</td><td>Primal</td><td>V1f,proje,</td></tr><tr><td>Newton</td><td>(15)</td><td>Primal</td><td>[V²f(x,0)]-1,Vif(x,0)</td></tr><tr><td>Block proximal gradient</td><td>(16)</td><td>Primal</td><td>[Vif]j,[proXnglj</td></tr><tr><td>Conic programming</td><td>(20)</td><td>Residual map root</td><td>projRp ×K* ×R+</td></tr></table>
158 We then have $\partial _ { 1 } F ( x , \theta ) = \nabla _ { 1 } ^ { 2 } f ( x , \theta )$ and $\partial _ { 2 } F ( x , \theta ) = \partial _ { 2 } \nabla _ { 1 } f ( x , \theta )$ , the Hessian of $f$ in its first 159 argument and the Jacobian in the second argument of $\nabla _ { 1 } f ( x , \theta )$ . In practice, we use autodiff to 160 compute Jacobian products automatically. Equivalently, we can use the gradient descent fixed point
$$T ( x , \theta ) = x - \eta \nabla _ { 1 } f ( x , \theta ) ,$$
161 which holds for all step sizes $\eta > 0$ . Using (3), it is easy to verify that we end up with the same linear 162 system since $\eta$ cancels out. 163 KKT conditions. We now show that the KKT conditions, manually differentiated in several works 164 [19, 35, 6, 53, 52], fit our framework. As we will see, the key will be to group the optimal primal and 65 dual variables as our $x ^ { \star } ( \theta )$ . Let us consider the general problem
$$\operatorname { a r g m i n } _ { z \in \mathbb { R } ^ { p } } f ( z , \theta ) \quad { \mathrm { s u b j e c t ~ t o } } \quad G ( z , \theta ) \leq 0 , \ H ( z , \theta ) = 0 ,$$
where166 $z \in \mathbb { R } ^ { p }$ is the primal variable, $f \colon { \mathbb { R } } ^ { p } \times { \mathbb { R } } ^ { n } \to { \mathbb { R } }$ , $G \colon \mathbb { R } ^ { p } \times \mathbb { R } ^ { n } \to \mathbb { R } ^ { r }$ and $H \colon \mathbb { R } ^ { p } \times \mathbb { R } ^ { n } \to \mathbb { R } ^ { q }$ 167 The stationarity, primal feasibility and complementary slackness conditions give
$$\begin{array} { r } { \nabla _ { 1 } f ( z , \theta ) + \left[ \partial _ { 1 } G ( z , \theta ) \right] ^ { \top } \boldsymbol { \lambda } + \left[ \partial _ { 1 } H ( z , \theta ) \right] ^ { \top } \boldsymbol { \nu } = 0 } \\ { H ( z , \theta ) = 0 } \\ { \boldsymbol { \lambda } \circ G ( z , \theta ) = 0 , } \end{array}$$
168 where $\nu \in \mathbb { R } ^ { q }$ and $\lambda \in \mathbb { R } _ { + } ^ { r }$ are the dual variables, also known as KKT multipliers. The system of 169 (potentially nonlinear) equations (6) fits our framework, as we can group the primal and dual solutions 170 as $x ^ { \star } ( \theta ) = ( z ^ { \star } ( \theta ) , \nu ^ { \star } ( \theta ) , \lambda ^ { \star } ( \theta ) )$ to form the root of a function $F ( x ^ { \star } ( \theta ) , \theta )$ , where $F \colon \mathbb { R } ^ { d } \times \mathbb { R } ^ { n } $ 171 $\mathbb { R } ^ { d }$ and $d = p + q + r$ . The primal and dual solutions can be obtained from a generic solver, such as 172 an interior point method. In practice, the above mapping $F$ will be defined directly in Python (see 173 Figure 6 in Appendix A) and $F$ will be differentiated automatically via autodiff. 174 Proximal gradient fixed point. Unfortunately, not all algorithms return both primal and dual 175 solutions. Moreover, if the objective contains non-smooth terms, proximal gradient descent may be 176 more efficient. We now discuss its fixed point. Let $x ^ { \star } ( \theta )$ be implicitly defined as
$$x ^ { \star } ( \theta ) : = \operatornamewithlimits { a r g m i n } _ { x \in \mathbb { R } ^ { d } } f ( x , \theta ) + g ( x , \theta ) ,$$
where 177 $f \colon { \mathbb { R } ^ { d } } \times { \mathbb { R } ^ { n } } \to { \mathbb { R } }$ is twice-differentiable convex and $g \colon { \mathbb { R } } ^ { d } \times { \mathbb { R } } ^ { n } \to { \mathbb { R } }$ is convex but possibly 178 non-smooth. Let us define the proximity operator associated with $g$ by
$$\operatorname { p r o x } _ { g } ( y , \theta ) : = \underset { x \in \mathbb { R } ^ { d } } { \operatorname { a r g m i n } } \frac { 1 } { 2 } \| x - y \| _ { 2 } ^ { 2 } + g ( x , \theta ) .$$
To implicitly differentiate through 179 $x ^ { \star } ( \theta )$ , we use the fixed point mapping [55, p.150]
$$T ( x , \theta ) = \mathrm { p r o x } _ { \eta g } ( x - \eta \nabla _ { 1 } f ( x , \theta ) , \theta ) ,$$
180 for any step size $\eta > 0$ . The proximity operator is 1-Lipschitz continuous [50]. By Rademacher’s 181 theorem, it is differentiable almost everywhere. Many proximity operators enjoy a closed form and 182 can easily be differentiated, as discussed in Appendix $\mathbf { B }$ . 183 Projected gradient fixed point. As a special case, when $g ( x , \theta )$ is the indicator function $I _ { C ( \theta ) } ( x )$ , 184 where $\mathcal { C } ( \boldsymbol { \theta } )$ is a convex set depending on $\theta$ , we obtain
$$x ^ { \star } ( \theta ) = \operatorname * { a r g m i n } _ { x \in { \mathcal { C } } ( \theta ) } f ( x , \theta ) .$$
The proximity operator185 $\operatorname { p r o x } _ { g }$ becomes the Euclidean projection onto $\mathcal { C } ( \boldsymbol { \theta } )$
$${ \mathrm { p r o x } } _ { g } ( y , \theta ) = { \mathrm { p r o j } } _ { \mathcal { C } } ( y , \theta ) : = { \underset { x \in { \mathcal { C } } ( \theta ) } { \operatorname { a r g m i n } } } \| x - y \| _ { 2 } ^ { 2 }$$
186 and (7) becomes the projected gradient fixed point
$$T ( x , \theta ) = \mathrm { p r o j } _ { \mathcal { C } } ( x - \eta \nabla _ { 1 } f ( x , \theta ) , \theta ) .$$
187 Compared to the KKT conditions, this fixed point is particularly suitable when the projection enjoys 188 a closed form. We discuss how to compute the JVP $/$ VJP for a wealth of convex sets in Appendix B. 189 Mirror descent fixed point. We again consider the case when $x ^ { \star } ( \theta )$ is implicitly defined as the 190 solution of (8). We now generalize the projected gradient fixed point beyond Euclidean geometry. 191 Let the Bregman divergence $D _ { \varphi }$ : $\operatorname { d o m } ( \bar { \varphi } ) \cdot \operatorname { r e l i n t } ( \operatorname { d o m } ( \varphi ) ) \to \bar { \mathbb { R } } _ { + }$ generated by $\varphi$ be defined by
$$D _ { \varphi } ( x , y ) : = \varphi ( x ) - \varphi ( y ) - \langle \nabla \varphi ( y ) , x - y \rangle .$$
192 We define the Bregman projection of $y$ onto ${ \mathcal { C } } ( \theta ) \subseteq \mathrm { d o m } ( \varphi )$ by
$$\begin{array} { r } { \mathrm { p r o j } _ { \mathcal { C } } ^ { \varphi } ( y , \theta ) : = \underset { x \in \mathcal { C } ( \theta ) } { \mathrm { a r g m i n } } D _ { \varphi } ( x , \nabla \varphi ^ { \ast } ( y ) ) . } \end{array}$$
193 Definition (10) incudes the mirror map $\nabla \varphi ^ { * } ( y )$ for convenience. It can be seen as a mapping from 194 $\mathbb { R } ^ { d }$ to $\mathrm { d o m } ( \varphi )$ , ensuring that (10) is well-defined. The mirror descent fixed point mapping is then
$$\begin{array} { c } { \hat { x } = \nabla \varphi ( x ) } \\ { y = \hat { x } - \eta \nabla _ { 1 } f ( x , \theta ) } \\ { T ( x , \theta ) = \mathrm { p r o j } _ { \mathcal { C } } ^ { \varphi } ( y , \theta ) . } \end{array}$$
195 Because $T$ involves the composition of several functions, manually deriving its JVP/VJP is error 196 prone. This shows that our approach leveraging autodiff allows to handle more advanced fixed point 197 mappings. A common example of $\varphi$ is $\varphi ( \bar { x } ) \stackrel { - } { = } \langle x , \log x - 1 \rangle$ , where $\mathrm { d o m } ( \varphi ) = \mathbb { R } _ { + } ^ { d }$ . In this case, 198 $D _ { \varphi }$ is the Kullback-Leibler divergence. An advantage of the Kullback-Leibler projection is that it 199 sometimes easier to compute than the Euclidean projection, as we detail in Appendix B.
200 Other fixed points. More fixed points are described in Appendix C.
# 2.3 Jacobian bounds
In practice, either by the limitations of finite precision arithmetic or because we perform a finite number of iterations, we rarely reach the exact solution $x ^ { \star } ( \theta )$ , but instead only reach an approximate solution $\hat { x }$ and apply the implicit differentiation equation (2) at this approximate solution. This motivates the need for approximation guarantees of this approach
Definition 1. Let $F : \mathbb { R } ^ { d } \times \mathbb { R } ^ { n } \mathbb { R } ^ { d }$ be an optimality criterion mapping. Let $A : = - \partial _ { 1 } F$ and $B : = \partial _ { 2 } F$ . We define the Jacobian estimate at $( x , \theta )$ as the solution to the following linear equation $A ( x , \theta ) J ( x , \theta ) = B ( x , \theta )$ . It is a function $J : \mathbb { R } ^ { d } \times \mathbb { R } ^ { n } \mathbb { R } ^ { d \times n }$ .
209 It holds by construction that $J ( x ^ { \star } ( \theta ) , \theta ) = \partial x ^ { \star } ( \theta )$ . Computing $J ( \hat { x } , \theta )$ for an approximate solution 210 $\hat { x }$ of $x ^ { \star } ( { \boldsymbol { \theta } } )$ therefore allows to approximate the true Jacobian ${ \partial x ^ { \star } ( \theta ) }$ . In practice, an algorithm used 211 to solve (1) depends on $\theta$ . Note however that, what we compute is not the Jacobian of ${ \hat { x } } ( \theta )$ , unlike 212 works unrolling an algorithm that differentiate through its iterations, but an estimate of ${ \partial x ^ { \star } ( \theta ) }$ . We 213 therefore use the notation $\hat { x }$ , leaving the dependence on $\theta$ implicit. 214 We develop bounds of the form $\| J ( \hat { x } , \theta ) - \partial x ^ { \star } ( \theta ) \| < C \| \hat { x } - x ^ { \star } ( \theta ) \|$ , hence showing that the error 215 on the estimated Jacobian is at most of the same order as that of $\hat { x }$ as an approximation of $x ^ { \star } ( \theta )$ 216 These bounds are based on the following main theorem, whose proof is included in Appendix D.
 Figure 2: CPU runtime comparison of implicit differentiation and unrolling for hyperparameter optimization of multiclass SVMs for multiple problem sizes. Error bars represent $90 \%$ confidence intervals. (a) Mirror descent solver, with mirror descent fixed point for implicit differentiation. $\mathbf { ( b ) }$ Proximal gradient solver, with proximal gradient fixed point for implicit differentiation. (c) Block coordinate descent solver; for implicit differentiation we obtain $x ^ { \star } ( \theta )$ by BCD but perform differentiation with the mirror descent and proximal gradient fixed points. This showcases that the solver and fixed point can be independently chosen.
Theorem 1 (Jacobian estimate). Let 17 $F : \mathbb { R } ^ { d } \times \mathbb { R } ^ { n } \mathbb { R } ^ { d }$ . Assume that there exist $\alpha , \beta , \gamma , \varepsilon , R > 0$ such that 18 $A = - \partial _ { 1 } F$ and $B = \partial _ { 2 } F$ satisfy, for all $v \in \mathbb { R } ^ { d }$ , $\boldsymbol \theta \in \mathbb { R } ^ { n }$ and $x$ such that $\| x - x ^ { \star } ( \theta ) \| \leq \varepsilon$ :
$A$ is well-conditioned, Lipschitz: $\| A ( x , \theta ) v \| \geq \alpha \| v \| , \| A ( x , \theta ) - A ( x ^ { \star } ( \theta ) , \theta ) \| _ { o p } \leq \gamma \| x - x ^ { \star } ( \theta ) \| .$
20 $B$ is bounded and Lipschitz: $\begin{array} { r } { | B ( x ^ { \star } ( \theta ) , \theta ) | | \leq R , \| B ( x , \theta ) - B ( x ^ { \star } ( \theta ) , \theta ) \| \leq \beta \| x - x ^ { \star } ( \theta ) \| . } \end{array}$
Under these conditions, when 21 $\| { \hat { x } } - x ^ { \star } ( \theta ) \| \leq \varepsilon$ , we have
$$\begin{array} { r } { \| J ( \hat { x } , \theta ) - \partial x ^ { \star } ( \theta ) \| \leq \left( \beta \alpha ^ { - 1 } + \gamma R \alpha ^ { - 2 } \right) \| \hat { x } - x ^ { \star } ( \theta ) \| . } \end{array}$$
222 This result is similar to [40, Theorem 7.2], that is concerned with the stability of solutions to inverse 223 problems. Here we consider that $A ( \cdot , \theta )$ is uniformly well-conditioned, rather than only at $x ^ { \star } ( \theta )$ . 224 This does not affect the first order in $\varepsilon$ of this bound, and makes it valid for all $\hat { x }$ . It is also more 225 tailored to applications to equation-specific cases. 26 Indeed, Theorem 1 can be applied to specific functions $F$ or $T$ for some root and fixed-point equations. 27 In particular, for gradient descent fixed point, where $T ( x , \theta ) = x - \eta \nabla _ { 1 } f ( x , \theta )$ , this yields 228 This guarantees precision on the estimated Jacobian under regularity conditions on $f$ directly; see 229 Corollary 1 in Appendix D.
For proximal gradient descent, where 230 $T ( x , \theta ) = \mathrm { p r o x } _ { \eta g } ( x - \eta \nabla _ { 1 } f ( x , \theta ) , \theta )$ , this yields
$$\begin{array} { r l } & { A ( x , \theta ) = I - \partial _ { 1 } T ( x , \theta ) = I - ( I - \eta \nabla _ { 1 } ^ { 2 } f ( x , \theta ) ) \partial _ { 1 } \mathrm { p r o x } _ { \eta g } ( x - \eta \nabla _ { 1 } f ( x , \theta ) , \theta ) } \\ & { B ( x , \theta ) = \partial _ { 2 } \mathrm { p r o x } _ { \eta g } ( x - \eta \nabla _ { 1 } f ( x , \theta ) , \theta ) - \eta \partial _ { 2 } \nabla _ { 1 } f ( x , \theta ) \partial _ { 1 } \mathrm { p r o x } _ { \eta g } ( x - \eta \nabla _ { 1 } f ( x , \theta ) , \theta ) . } \end{array}$$
231 An important special case is that of a function to minimize in the form $f ( x , \theta ) + g ( x )$ , where the 232 prox function $g$ is smooth, and does not depend on $\theta$ , as is the case in our experiments in $\ S 3 . 2$ . For 233 this setting, we derive similar guarantees in Corollary 2 in Appendix D. Recent work also exploits 234 local smoothness of solutions to derive similar bounds [11, Theorem 13].
# 3 Experiments
To conclude this work, we demonstrate the ease of formulating and solving bi-level optimization problems with our modular framework. We also present an application to the sensitivity analysis of molecular dynamics.
# 3.1 Hyperparameter optimization of multiclass SVMs
40 In this example, we consider the hyperparamer optimization of multiclass SVMs [23] trained in the dual. Here, 41 $x ^ { \star } ( \theta )$ is the optimal dual solution, a matrix of shape $m \times k$ , where $m$ is the number of
Table 2: Mean AUC (and $9 5 \%$ confidence interval) for the cancer survival prediction problem.
<table><tr><td>Method</td><td>L1 logreg</td><td>L2 logreg</td><td>DictL + L2 logreg</td><td>Task-driven DictL</td></tr><tr><td>AUC (%)</td><td>71.6 ± 2.0</td><td>72.4± 2.8</td><td>68.3 ± 2.3</td><td>73.2 ± 2.1</td></tr></table>
242 training examples and $k$ is the number of classes, and $\theta \in \mathbb { R } _ { + }$ is the regularization parameter. The 243 challenge in differentiating $x ^ { \star } ( \theta )$ is that each row of $x ^ { \star } ( \theta )$ is constrained to belong to the probability 244 simplex $\triangle ^ { k }$ . More formally, let $X _ { \mathsf { t r } } \in \mathbb { R } ^ { m \times p }$ be the training feature matrix and $Y _ { \mathrm { t r } } \in \{ 0 , 1 \} ^ { m \times k }$ be 245 the training labels (in row-wise one-hot encoding). Let $W ( x , \theta ) : = X _ { \mathrm { t r } } ^ { \top } ( Y _ { \mathrm { t r } } - x ) / \theta \in \bar { \mathbb { R } } ^ { p \times k }$ be the 246 dual-primal mapping. Then, we consider the following bi-level optimization problem
$$\operatorname * { a r g m i n } _ { \boldsymbol { x } = \mathrm { e x p } ( \boldsymbol { x } ) } \frac { 1 } { 2 } \| X _ { \mathrm { v a l } } W ( \boldsymbol { x } ^ { \star } ( \boldsymbol { \theta } ) , \boldsymbol { \theta } ) - Y _ { \mathrm { v a l } } \| _ { F } ^ { 2 } \quad \mathrm { s u b j e c t ~ t o } \quad \boldsymbol { x } ^ { \star } ( \boldsymbol { \theta } ) = \operatorname * { a r g m i n } _ { \boldsymbol { x } \in \mathcal { C } } f ( \boldsymbol { x } , \boldsymbol { \theta } ) : = \frac { \theta } { 2 } \| W ( \boldsymbol { x } , \boldsymbol { \theta } ) \| _ { F } ^ { 2 } ,$$
247 where $\mathcal { C } = \triangle ^ { k } \times \cdot \cdot \cdot \times \triangle ^ { k }$ is the Cartesian product of $m$ probability simplices. We apply the change 248 of variable $\theta = \exp ( \lambda )$ in order to guarantee that the hyper-parameter $\theta$ is positive. The matrix 249 $W ( x ^ { \star } ( \theta ) , \theta ) \in \mathbb { R } ^ { p \times k }$ contains the optimal primal solution, the feature weights for each class. The 250 outer loss is computed against validation data $X _ { \mathtt { v a l } }$ and $Y _ { \tt v a l }$ . 251 In order to differentiate $x ^ { \star } ( \theta )$ , several ways are possible using our framework. The first one would be 252 to map (12) to a quadratic program form (18) and use the KKT conditions to form a mapping $F ( x , \theta )$ . 253 A more direct way is to use proximal gradient fixed point (9). Since $\mathcal { C }$ is a Cartesian product, the 254 projection can be easily computed by row-wise projections on the simplex, which we map over rows 255 (using vectorized operations) via ${ \mathrm { j a x . v m a p } }$ . As we explained in $\ S \mathbf { B } . 1$ , this projection’s Jacobian 256 enjoys a closed form. A third way to differentiate $x ^ { \star } ( \theta )$ is using the mirror descent fixed point 257 (11). Under the KL geometry, proj $\overset { \varphi } { c } ( y , \theta )$ corresponds to a row-wise softmax. It is therefore easy to 258 compute and differentiate. Figure 2 compares the runtime performance of implicit differentiation vs. 259 unrolling for the latter two fixed points. A code example is included in Figure 8 in the Appendix.
# 3.2 Task-driven dictionary learning
261 Task-driven dictionary learning was proposed to learn sparse codes for input data in such a way that 262 the codes solve an outer learning problem [47, 64, 70]. Formally, given a data matrix $X _ { \mathsf { t r } } \in \dot { \mathbb { R } } ^ { m \times p }$ 263 and a dictionary of $k$ atoms $\theta \in \mathbb { R } ^ { k \times p }$ , a sparse code is defined as a matrix $\boldsymbol { x } ^ { \star } ( \boldsymbol { \theta } ) \in \mathbb { R } ^ { m \times k }$ that 264 minimizes in $x$ a reconstruction loss $f ( x , \theta ) \mathrel { \mathop : } = \ell ( X _ { \mathrm { t r } } , x \theta )$ regularized by a sparsity-inducing penalty 265 $g ( x )$ . Instead of optimizing the dictionary $\theta$ to minimize the reconstruction loss, [47] proposed to 266 optimize an outer problem that depends on the code. For example, given a set of labels $Y _ { \mathbf { t r } } \in \{ 0 , 1 \} ^ { m }$ 267 we consider a logistic regression problem which results in the bilevel optimization problem:
$$\underbrace { \operatorname* { m i n } _ { \theta \in \mathbb { R } ^ { k \times p } , w \in \mathbb { R } ^ { k } , b \in \mathbb { R } } \sigma ( x ^ { \star } ( \theta ) w + b ; y _ { \mathrm { t r } } ) } _ { \mathrm { o u t e r ~ p r o b l e m } } \mathrm { ~ s u b j e c t ~ t o ~ } x ^ { \star } ( \theta ) \in \underbrace { \mathrm { a r g m i n ~ } f ( x , \theta ) + g ( x ) } _ { \mathrm { i n n e r ~ p r o b l e m } } .$$
268 When $\ell$ is the squared Frobenius distance between matrices, and $g$ the elastic net penalty, [47, Eq. 269 21] derive manually, using optimality conditions (notably the support of the codes selected at the 270 optimum), an explicit re-parameterization of $x ^ { \star } ( \theta )$ as a linear system involving $\theta$ . This closed 271 form allows for a direct computation of the Jacobian of $x ^ { \star }$ w.r.t. $\theta$ . Similarly, [64] derive first 272 order conditions in the case where $\ell$ is a $\beta$ -divergence, while [70] propose to use unrolling of ISTA 273 iterations. Our approach bypasses all of these computations, giving the user more leisure to focus 274 directly on modeling (loss, regularizer) aspects (see code snippet in Figure 9 in Appendix). 275 We illustrate this on a problem of breast cancer survival prediction from gene expression data, 276 framed as a binary classification problem to discriminate patients who survive longer than 5 years 277 $( m _ { 1 } = 2 0 0 )$ vs patients who die within 5 years of diagnosis $m _ { 0 } = 9 9 ,$ ), from $p = 1 , 0 0 0$ gene 278 expression values. As shown in Table 2, solving (13) (Task-driven DictL) reaches a classification 279 performance competitive with state-of-the-art $L _ { 1 }$ or $L _ { 2 }$ regularized logistic regression with 100 times 280 fewer variables. See Appendix E.2 for more details.
 Figure 3: Distilled MNIST dataset $\boldsymbol { \theta } \in \mathbb { R } ^ { k \times p }$ obtained by solving (14). We learn one image per class such that a logistic regression model trained on $\theta$ achieves the lowest logistic loss on the MNIST training set. Implicit differentiation was 4 times faster than unrolling.
# 281 3.3 Dataset distillation
282 Dataset distillation [67, 46] aims to learn a small synthetic training dataset such that a model trained 283 on this learned data set achieves small loss on the original training set. Formally, let $X _ { \mathsf { t r } } \in \mathbb { R } ^ { m \times p }$ and 284 $y _ { \mathrm { t r } } \in [ k ] ^ { m }$ denote the original training set. The distilled dataset will contain one prototype example 285 for each class and therefore $\boldsymbol { \theta } \in \mathbb { R } ^ { k \times p }$ . The dataset distillation problem can then naturally be cast as 286 a bi-level problem, where in the inner problem we estimate a logistic regression model $\dot { { \boldsymbol { x } } } ^ { \star } ( { \boldsymbol { \theta } } ) \in \mathbb { R } ^ { p }$ 287 trained on the distilled images $\boldsymbol { \theta } \in \mathbb { R } ^ { k \times p }$ , while in the outer problem we want to minimize the loss 288 achieved by $x ^ { \star } ( \theta )$ over the training set:
$$\operatorname * { a r g m i n } _ { \theta \in \mathbb { R } ^ { k \times p } } f ( x ^ { \star } ( \theta ) , X _ { \mathrm { t r } } ; y _ { \mathrm { t r } } ) \mathrm { ~ } \mathrm { ~ s u b j e c t ~ t o ~ } x ^ { \star } ( \theta ) \in \underset { x \in \mathbb { R } ^ { p } } { \operatorname { a r g m i n } } f ( x , \theta ; [ k ] ) + \varepsilon \| x \| ^ { 2 } ,$$
289 where $f ( x , X ; y ) : = \ell ( X x , y )$ , $\ell$ denotes the multiclass logistic regression loss, and $\varepsilon = 1 0 ^ { - 3 }$ is a 290 regularization parameter that we found had a very positive effect on convergence. In this problem, and unlike in the general hyperparameter optimization setup, both the inner and outer 2 problems are high-dimensional, making it an ideal test-bed for gradient-based bi-level optimization 93 methods. For this experiment, we use the MNIST dataset. The number of parameters in the inner 4 problem is $p = 2 8 ^ { 2 } \overset { \cdot } { = } 7 8 4$ . while the number of parameters of the outer loss is $k \times p = 7 8 4 0$ . We 95 solve this problem using gradient descent on both the inner and outer problem, with the gradient 96 of the outer loss computed using implicit differentiation, as described in $\ S 2$ . This is fundamentally 7 different from the approach used in the original paper, where they used differentiation of the unrolled 98 iterates instead. For the same solver, we found that the implicit differentiation approach was 4 times 99 faster than the original one. The obtained distilled images $\theta$ are visualized in Figure 3 and a code 00 example is given in Figure 10 in the Appendix.
# 3.4 Sensitivity analysis of molecular dynamics
302 Many applications of physical simulations require solving optimiza 303 tion problems, such as energy minimization in molecular [62] and 304 continuum [8] mechanics, structural optimization [41] and data 305 assimilation [32]. However, even fully differentiable simulators 306 may not have efficient or accurate derivatives. We revisit an exam 307 ple from JAX-MD [62], the problem of finding energy minimizing 308 configurations to a system of packed particles in an $m$ -dimensional 309 box of width $\ell$ ,
$$x ^ { \star } ( \theta ) = { \underset { x \in \mathbb { R } ^ { k \times m } } { \operatorname { a r g m i n } } } \sum _ { i j } U ( x _ { i j } \mod \ell , \theta ) ,$$
 Figure 4: Particle positions and position sensitivity vectors, with respect to increasing the diameter of the blue particles.
310 where $U ( x _ { i j } , \theta )$ is the pairwise potential energy function, with half 311 the particles at diameter 1 and half at diameter $\theta = 0 . 6$ , which we 312 optimize with a domain-specific optimizer [13]. Here we consider 313 sensitivity of particle position with respect to diameter ${ \partial x ^ { \star } ( \theta ) }$ , 314 rather than sensitivity of the total energy from the original experi 315 ment. Figure 4 shows results calculated via forward-mode implicit differentiation (JVP). Whereas 316 differentiating the unrolled optimizer happens to work for total energy, here it typically does not even 317 converge (see Appendix Fig. 15), due the discontinuous optimization method.
[1] M. Abadi, P. Barham, J. Chen, Z. Chen, A. Davis, J. Dean, M. Devin, S. Ghemawat, G. Irving, M. Isard, et al. Tensorflow: A system for large-scale machine learning. In 12th $\{ U S E N I X \}$ symposium on operating systems design and implementation $\langle \mathit { 5 O S D I } \} \mathit { 1 6 } \rangle$ , pages 265–283, 2016. [2] A. Agrawal, B. Amos, S. Barratt, S. Boyd, S. Diamond, and Z. Kolter. Differentiable convex optimization layers. arXiv preprint arXiv:1910.12430, 2019. [3] A. Agrawal, S. Barratt, S. Boyd, E. Busseti, and W. M. Moursi. Differentiating through a cone program. arXiv preprint arXiv:1904.09043, 2019. [4] A. Ali, E. Wong, and J. Z. Kolter. A semismooth newton method for fast, generic convex programming. In International Conference on Machine Learning, pages 70–79. PMLR, 2017. [5] B. Amos. Differentiable optimization-based modeling for machine learning. PhD thesis, PhD thesis. Carnegie Mellon University, 2019. [6] B. Amos and J. Z. Kolter. Optnet: Differentiable optimization as a layer in neural networks. In Proc. of ICML, pages 136–145, 2017. [7] S. Bai, J. Z. Kolter, and V. Koltun. Deep equilibrium models. arXiv preprint arXiv:1909.01377, 2019. [8] A. Beatson, J. Ash, G. Roeder, T. Xue, and R. P. Adams. Learning composable energy surrogates for pde order reduction. In H. Larochelle, M. Ranzato, R. Hadsell, M. F. Balcan, and H. Lin, editors, Advances in Neural Information Processing Systems, volume 33, pages 338–348. Curran Associates, Inc., 2020. [9] Y. Bengio. Gradient-based optimization of hyperparameters. Neural computation, 12(8):1889– 1900, 2000. [10] Q. Bertrand, Q. Klopfenstein, M. Blondel, S. Vaiter, A. Gramfort, and J. Salmon. Implicit differentiation of lasso-type models for hyperparameter optimization. In Proc. of ICML, pages 810–821, 2020. [11] Q. Bertrand, Q. Klopfenstein, M. Massias, M. Blondel, S. Vaiter, A. Gramfort, and J. Salmon. Implicit differentiation for fast hyperparameter selection in non-smooth convex learning. arXiv preprint arXiv:2105.01637, 2021. [12] M. J. Best, N. Chakravarti, and V. A. Ubhaya. Minimizing separable convex functions subject to simple chain constraints. SIAM Journal on Optimization, 10(3):658–672, 2000. [13] E. Bitzek, P. Koskinen, F. Gähler, M. Moseler, and P. Gumbsch. Structural relaxation made simple. Phys. Rev. Lett., 97:170201, Oct 2006. [14] M. Blondel. Structured prediction with projection oracles. In Proc. of NeurIPS, 2019. [15] M. Blondel, V. Seguy, and A. Rolet. Smooth and sparse optimal transport. In Proc. of AISTATS, pages 880–889. PMLR, 2018. [16] M. Blondel, O. Teboul, Q. Berthet, and J. Djolonga. Fast differentiable sorting and ranking. In Proc. of ICML, pages 950–959, 2020. [17] J. Bradbury, R. Frostig, P. Hawkins, M. J. Johnson, C. Leary, D. Maclaurin, and S. WandermanMilne. Jax: composable transformations of python $^ +$ numpy programs, 2018. URL http://github. com/google/jax, 4:16, 2020. [18] P. Brucker. An $O ( n )$ algorithm for quadratic knapsack problems. Operations Research Letters, 3(3):163–166, 1984. [19] O. Chapelle, V. Vapnik, O. Bousquet, and S. Mukherjee. Choosing multiple parameters for support vector machines. Machine learning, 46(1):131–159, 2002. [20] X. Chen, Y. Zhang, C. Reisinger, and L. Song. Understanding deep architecture with reasoning layer. Advances in Neural Information Processing Systems, 33, 2020. [21] H. Cherkaoui, J. Sulam, and T. Moreau. Learning to solve tv regularised problems with unrolled algorithms. Advances in Neural Information Processing Systems, 33, 2020. [22] L. Condat. Fast projection onto the simplex and the $\ell _ { 1 }$ ball. Mathematical Programming, 158(1-2):575–585, 2016. [23] K. Crammer and Y. Singer. On the algorithmic implementation of multiclass kernel-based vector machines. Journal of machine learning research, 2(Dec):265–292, 2001. [24] M. Cuturi. Sinkhorn distances: lightspeed computation of optimal transport. In Advances in Neural Information Processing Systems, volume 2, 2013. [25] C.-A. Deledalle, S. Vaiter, J. Fadili, and G. Peyré. Stein unbiased gradient estimator of the risk (sugar) for multiple parameter selection. SIAM Journal on Imaging Sciences, 7(4):2448–2487, 2014. [26] S. Diamond and S. Boyd. Cvxpy: A python-embedded modeling language for convex optimization. The Journal of Machine Learning Research, 17(1):2909–2913, 2016. [27] J. Djolonga and A. Krause. Differentiable learning of submodular models. Proc. of NeurIPS, 30:1013–1023, 2017. [28] J. Domke. Generic methods for optimization-based modeling. In Artificial Intelligence and Statistics, pages 318–326. PMLR, 2012. [29] J. C. Duchi, S. Shalev-Shwartz, Y. Singer, and T. Chandra. Efficient projections onto the $\ell _ { 1 }$ -ball for learning in high dimensions. In Proc. of ICML, 2008. [30] L. Franceschi, M. Donini, P. Frasconi, and M. Pontil. Forward and reverse gradient-based hyperparameter optimization. In International Conference on Machine Learning, pages 1165– 1173. PMLR, 2017. [31] L. Franceschi, P. Frasconi, S. Salzo, R. Grazzi, and M. Pontil. Bilevel programming for hyperparameter optimization and meta-learning. In International Conference on Machine Learning, pages 1568–1577. PMLR, 2018. [32] T. Frerix, D. Kochkov, J. A. Smith, D. Cremers, M. P. Brenner, and S. Hoyer. Variational data assimilation with a learned inverse observation operator. 2021. [33] R. Frostig, M. Johnson, D. Maclaurin, A. Paszke, and A. Radul. Decomposing reverse-mode automatic differentiation. In LAFI 2021 workshop at POPL, 2021. [34] R. Frostig, M. J. Johnson, and C. Leary. Compiling machine learning programs via high-level tracing. Machine Learning and Systems (MLSys), 2018. [35] S. Gould, B. Fernando, A. Cherian, P. Anderson, R. S. Cruz, and E. Guo. On differentiating parameterized argmin and argmax problems with application to bi-level optimization. arXiv preprint arXiv:1607.05447, 2016. [36] S. Gould, R. Hartley, and D. Campbell. Deep declarative networks: A new hope. arXiv preprint arXiv:1909.04866, 2019. [37] S. Grotzinger and C. Witzgall. Projections onto order simplexes. Applied mathematics and Optimization, 12(1):247–270, 1984. [38] I. Guyon. Design of experiments of the nips 2003 variable selection benchmark. In NIPS 2003 workshop on feature extraction and feature selection, volume 253, 2003. [39] M. R. Hestenes, E. Stiefel, et al. Methods of conjugate gradients for solving linear systems, volume 49. NBS Washington, DC, 1952. 407 [40] N. J. Higham. Accuracy and Stability of Numerical Algorithms. Society for Industrial and Applied Mathematics, second edition, 2002. 409 [41] S. Hoyer, J. Sohl-Dickstein, and S. Greydanus. Neural reparameterization improves structural optimization. 2019. [42] Y. Kim, C. Denton, L. Hoang, and A. M. Rush. Structured attention networks. arXiv preprint arXiv:1702.00887, 2017. 413 [43] D. P. Kingma and J. Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014. 415 [44] S. G. Krantz and H. R. Parks. The implicit function theorem: history, theory, and applications. Springer Science & Business Media, 2012. 417 [45] C. H. Lim and S. J. Wright. Efficient bregman projections onto the permutahedron and related polytopes. In Proc. of AISTATS, pages 1205–1213. PMLR, 2016. 419 [46] J. Lorraine, P. Vicol, and D. Duvenaud. Optimizing millions of hyperparameters by implicit differentiation. In International Conference on Artificial Intelligence and Statistics, pages 1540–1552. PMLR, 2020. 422 [47] J. Mairal, F. Bach, and J. Ponce. Task-driven dictionary learning. IEEE Transactions on Pattern Analysis and Machine Intelligence, 34(4):791–804, 2012. 424 [48] A. F. Martins and R. F. Astudillo. From softmax to sparsemax: A sparse model of attention and multi-label classification. In Proc. of ICML, 2016. 426 [49] C. Michelot. A finite algorithm for finding the projection of a point onto the canonical simplex of $\mathbb { R } ^ { n }$ . Journal of Optimization Theory and Applications, 50(1):195–200, 1986. 428 [50] J.-J. Moreau. Proximité et dualité dans un espace hilbertien. Bulletin de la S.M.F., 93:273–299, 1965. 430 [51] V. Niculae and M. Blondel. A regularized framework for sparse and structured neural attention. In Proc. of NeurIPS, 2017. 432 [52] V. Niculae and A. Martins. Lp-sparsemap: Differentiable relaxed optimization for sparse structured prediction. In International Conference on Machine Learning, pages 7348–7359, 2020. 435 [53] V. Niculae, A. Martins, M. Blondel, and C. Cardie. Sparsemap: Differentiable sparse structured inference. In International Conference on Machine Learning, pages 3799–3808. PMLR, 2018. 437 [54] B. O’Donoghue, E. Chu, N. Parikh, and S. Boyd. Conic optimization via operator splitting and homogeneous self-dual embedding. Journal of Optimization Theory and Applications, 169(3):1042–1068, 2016. 440 [55] N. Parikh and S. Boyd. Proximal algorithms. Foundations and Trends in optimization, 1(3):127– 239, 2014. 442 [56] A. Paszke, S. Gross, F. Massa, A. Lerer, J. Bradbury, G. Chanan, T. Killeen, Z. Lin, N. Gimelshein, L. Antiga, et al. Pytorch: An imperative style, high-performance deep learning library. arXiv preprint arXiv:1912.01703, 2019. 445 [57] F. Pedregosa. Hyperparameter optimization with approximate gradient. In International conference on machine learning. PMLR, 2016. 447 [58] F. Pedregosa, G. Varoquaux, A. Gramfort, V. Michel, B. Thirion, O. Grisel, M. Blondel, P. Prettenhofer, R. Weiss, V. Dubourg, J. Vanderplas, A. Passos, D. Cournapeau, M. Brucher, M. Perrot, and E. Duchesnay. Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12:2825–2830, 2011. [59] A. Rajeswaran, C. Finn, S. Kakade, and S. Levine. Meta-learning with implicit gradients. arXiv preprint arXiv:1909.04630, 2019.
453 [60] N. Rappoport and R. Shamir. Multi-omic and multi-view clustering algorithms: review and 454 cancer benchmark. Nucleic Acids Res., 46:10546–10562, 2018. 455 [61] Y. Saad and M. H. Schultz. Gmres: A generalized minimal residual algorithm for solving 456 nonsymmetric linear systems. SIAM Journal on scientific and statistical computing, 7(3):856– 457 869, 1986. 458 [62] S. Schoenholz and E. D. Cubuk. Jax md: A framework for differentiable physics. In 459 H. Larochelle, M. Ranzato, R. Hadsell, M. F. Balcan, and H. Lin, editors, Advances in Neural 460 Information Processing Systems, volume 33, pages 11428–11441. Curran Associates, Inc., 461 2020. 462 [63] M. W. Seeger. Cross-validation optimization for large scale structured classification kernel 463 methods. Journal of Machine Learning Research, 9(6), 2008. 464 [64] P. Sprechmann, A. M. Bronstein, and G. Sapiro. Supervised non-euclidean sparse nmf via 465 bilevel optimization with applications to speech enhancement. In 2014 4th Joint Workshop on 466 Hands-free Speech Communication and Microphone Arrays (HSCMA), pages 11–15. IEEE, 467 2014. 468 [65] S. Vaiter, C.-A. Deledalle, G. Peyré, C. Dossal, and J. Fadili. Local behavior of sparse analysis 469 regularization: Applications to risk estimation. Applied and Computational Harmonic Analysis, 470 35(3):433–451, 2013. 471 [66] H. A. v. d. Vorst and H. A. van der Vorst. Bi-CGSTAB: A fast and smoothly converging variant 472 of Bi-CG for the solution of nonsymmetric linear systems. SIAM Journal on Scientific and 473 Statistical Computing, 13(2):631–644, 1992. 474 [67] T. Wang, J.-Y. Zhu, A. Torralba, and A. A. Efros. Dataset distillation. arXiv preprint 475 arXiv:1811.10959, 2018. 476 [68] R. E. Wengert. A simple automatic derivative evaluation program. Communications of the ACM, 477 7(8):463–464, 1964. 478 [69] Y. Wu, M. Ren, R. Liao, and R. B. Grosse. Understanding short-horizon bias in stochastic 479 meta-optimization. In 6th International Conference on Learning Representations, ICLR 2018, 480 Vancouver, BC, Canada, April 30 - May 3, 2018, Conference Track Proceedings. OpenRe 481 view.net, 2018. 482 [70] J. Zarka, L. Thiry, T. Angles, and S. Mallat. Deep network classification by scattering and 483 homotopy dictionary learning. arXiv preprint arXiv:1910.03561, 2019.
1. For all authors...
(a) Do the main claims made in the abstract and introduction accurately reflect the paper’s contributions and scope? [Yes] Our paper builds on the premise that reinstantiating the implicit function theorem for every optimization problem a user may encounter is cumbersome. We make the case that a modular approach is needed to bypass that issue. This approach raises several challenges, notably in the way these implicit solvers can be automatically instantiated, consistently, across the large corpus of optimization approaches favored by users. (b) Did you describe the limitations of your work? [Yes] , We discuss several limitations in our work. For instance, implicit differentiation requires $\hat { x }$ to be sufficiently close to $x ^ { \star }$ to be meaningful. This is the main topic of $\ S 2 . 3$ (c) Did you discuss any potential negative societal impacts of your work? [N/A] As a purely methodological paper, we do not foresee negative societal impacts of our work. (d) Have you read the ethics review guidelines and ensured that your paper conforms to them? [Yes] We confirm our paper conforms to those guidelines.
2. If you are including theoretical results...
(a) Did you state the full set of assumptions of all theoretical results? [Yes] , The paper contains one theoretical section, $\ S 2 . 3$ . (b) Did you include complete proofs of all theoretical results? [Yes] , All proofs are included in the Appendix D
3. If you ran experiments...
(a) Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? [No] At the time of submission, we are in the course of an approval process for open-source release required by our organization. We believe that the library itself comprises a contribution, and will have it available in open source by the time of this paper’s publication (at the latest). (b) Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? [Yes] , Experiments were mostly run with minimal parameter tuning to reflect the simplicity of the approach we advocate. This is reflected in $\ S 3$ and Appendix E (c) Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? [Yes] , see Figure 2 and std for the dictionary learning task. (d) Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? [Yes] , see Appendix E
4. If you are using existing assets (e.g., code, data, models) or curating/releasing new assets...
(a) If your work uses existing assets, did you cite the creators? [Yes] , see $\ S 3$ and Appendix E (b) Did you mention the license of the assets? [Yes] , see Appendix E (c) Did you include any new assets either in the supplemental material or as a URL? [N/A] (d) Did you discuss whether and how consent was obtained from people whose data you’re using/curating? [N/A] (e) Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? [N/A]
5. If you used crowdsourcing or conducted research with human subjects...
(a) Did you include the full text of instructions given to participants and screenshots, if applicable? [N/A] (b) Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? [N/A] (c) Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? [N/A]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258# Self-Supervised Bug Detection and Repair
Miltiadis Allamanis, Henry Jackson-Flux∗, Marc Brockschmidt Microsoft Research, Cambridge, UK {miallama, mabrocks}@microsoft.com
# Abstract
Machine learning-based program analyses have recently shown the promise of integrating formal and probabilistic reasoning towards aiding software development. However, in the absence of large annotated corpora, training these analyses is challenging. Towards addressing this, we present BUGLAB, an approach for selfsupervised learning of bug detection and repair. BUGLAB co-trains two models: (1) a detector model that learns to detect and repair bugs in code, (2) a selector model that learns to create buggy code for the detector to use as training data. A Python implementation of BUGLAB improves by up to $30 \%$ upon baseline methods on a test dataset of 2374 real-life bugs and finds 19 previously unknown bugs in open-source software.
# 1 Introduction
Detecting and repairing bugs in source code requires strong reasoning skills over formal structures (e.g. data and control flow) and ambiguous information (e.g. identifier names, coding idioms, and comments). Traditional program analyses are able to detect critical bugs through formal reasoning and combinatorial search, but need to be manually coded by experts. That is a lengthy and costly process, which misses the opportunity to use ambiguous information pervasive within code.
Towards broadening the applicability of such methods, and utilizing ambiguous information, deep learning-based bug detection methods are being investigated [22, 3, 13]. These methods have the potential to further improve the engineering of software we rely on every day. However, many challenges in the area remain open, such as creating robust bug detection and repair methods that cover a wide range of common bugs in the absence of large supervised training corpora. Existing work focuses on randomly inserted bugs [22, 13], Cloze test proxy tasks [3], corpora of small code edits that may contain bugs [9] or build errors [28]. All these approaches rely on datasets of very limited size or ones known not to be representative of the characteristics of bugs found in real code.
In this work, we propose BUGLAB, a self-supervised approach that trains robust bug detectors by co-training a bug selector that learns to create hard-to-detect bugs (Sec. 2). For example, for a given code snippet with two well-named variables, a variable misuse bug may be easy to detect and repair, whereas an incorrect comparison operator might be significantly harder to identify. We propose a neural architecture for BUGLAB (Sec. 3) and implement it for Python (Sec. 4). Our implementation considers four broad classes of seemingly simple, yet hard-to-detect bugs and shows improved performance over training with randomly-inserted bugs on PYPIBUGS, a new, manually curated test set of 2374 real-life bugs (Sec. 5). Furthermore, we tested our trained models on popular open-source Python packages and identified 19 previously unreported bugs, though false positive rates of $\sim 9 8 \%$ remain impractical. We hope that creating machine learning methods that can detect these bugs early and assist developers will speed up software development and allow engineers to deliver more robust software. We release PyPIBugs and our code at https://github.com/ microsoft/neurips21-self-supervised-bug-detection-and-repair.
# 2 Self-Supervised Bug Detection
In this section, we first introduce the concept of code rewriting, and then use it to define BUGLAB as a framework for self-supervised learning of bug detection and repair.
Code Rewriting Rewriting is common within compilers and their optimizations, test-driven searchbased bug repair tools, mutation testing, and refactoring tools. Rewrites can be semantics-preserving (e.g. renamings of local variables), or semantics-altering (e.g. replacing $> = \log ~ ! = )$ .
Let $s$ denote the set of all syntax trees (not necessarily rooted in the start symbol of the language grammar). Syntax tree locations $\ell \in \{ \epsilon \} \cup \mathbb { N } ^ { * }$ in a syntax tree $\mathrm { s } \in { \mathcal { S } }$ are recursively defined, where $\mathrm { s } _ { \vert \epsilon } = \mathrm { s }$ and $\mathrm { s } _ { | \ell }$ for $\ell = \ell ^ { \prime } \circ i$ is the $i$ -th child of $\mathrm { s } _ { \vert \ell ^ { \prime } }$ (i.e. s|(2,3) denotes the third child of the second child of s). We define a rewrite rule $\rho = ( \mathrm { m } _ { \rho } , \mathrm { t } _ { \rho } )$ as a pair of a matching function $\operatorname { m } _ { \rho } : S \{ t r u e , f a l s e \}$ and a transformation function $\mathrm { t } _ { \rho } : { \mathcal { S } } { \mathcal { S } }$ . The matching function $\mathrm { m } _ { \rho } ( \mathrm { s } )$ yields true iff the rule $\rho$ is applicable at the root of a subtree s. The transformation function can be applied to obtain a transformed syntax tree. For convenience, we define $\mathrm { t } _ { \rho } ( \mathrm { s } ) = \mathrm { s }$ iff $\mathrm { m } _ { \rho } ( \mathrm { s } ) = f a l s e$ . We then write $\rho ( \mathrm { s } )$ to indicate the modification of a syntax tree s using $\rho$ when possible, and otherwise the identity function. For reversible rewrite rules $\rho$ , we denote the inverse rule as $\rho ^ { - 1 }$ such that $\rho ^ { - 1 } ( \rho ( \mathrm { s } ) ) = \mathbf { \dot { s } }$ holds. We discuss concrete rewrite rules $\rho$ in Sec. 4.
Given a set of rewrite rules $\mathcal { R }$ we define the set of “potential rewrites” in a syntax tree s as $R _ { \mathrm { s } } ^ { \mathcal { R } } =$ $\{ \langle \ell , \rho \rangle \mid \rho \in { \mathcal { R } } , \ell$ location in s, $, \mathbf { m } _ { \rho } ( \mathbf { s } _ { | \ell } ) = t r u e \}$ . For each tuple $\langle \ell , \rho \rangle \in R _ { \mathrm { s } } ^ { \mathcal { R } }$ , we use $\mathrm { s } ^ { \prime } = \mathrm { s } [ \rho ] \varrho$ to denote the new syntax tree obtained by applying $\rho$ at location $\ell$ of s. In BUGLAB, we train models that use rewrites from $R _ { \mathrm { s } } ^ { \mathcal { R } }$ to insert and repair bugs. We will discuss such neural models in Sec. 3.
BUGLAB In BUGLAB, we are interested in selfsupervised training of a robust bug detector model $D _ { \theta }$ with parameters $\theta$ on an unannotated codebase $C$ . Let $\mathcal { R }$ be a set of rewrite rules2 that allows to insert and repair bugs. We train $D _ { \theta }$ to be able to recognize the “hardest” possible rewrites that could be applied on our codebase $C$ For this, we consider the loss $\mathcal { L } _ { D _ { \theta } }$ of $D _ { \theta }$ on a rewritten code snippet $\mathrm { s } [ \rho ] _ { \ell }$ , for which the model needs to predict the repairing rewrite $\langle \ell , \rho ^ { - 1 } \rangle$ . Formally, we want to minimize the objective
$$E _ { \mathrm { s } \sim C } \left[ \operatorname* { m a x } _ { \langle \ell , \rho \rangle \in R _ { \mathrm { s } } ^ { \mathcal { R } } } \mathcal { L } _ { D _ { \theta } } \left( \mathrm { s } [ \rho ] _ { \ell } , \left. \ell , \rho ^ { - 1 } \right. \right) \right] .$$
 Figure 1: BUGLAB overview: a selector model $S _ { \phi }$ decides which (bugintroducing) rewrite to apply to an input code snippet. Then a bug detector $D _ { \theta }$ tries to locate and repair the inserted bug (if one was inserted).
However, for any useful detector the set of rewrites $R _ { \mathrm { s } } ^ { \mathcal { R } }$ is commonly very large or unbounded and computing the maximum over all $\langle \bar { \ell , } \rho \rangle \in R _ { \mathrm { s } } ^ { \mathcal { R } }$ is practically intractable. To address this, BUGLAB introduces a bug selector model $S _ { \phi }$ (with parameters $\phi _ { , }$ ), whose goal is to approximate the intractable $\mathrm { m a x } _ { \langle \ell , \rho \rangle \in R _ { \mathrm { s } } ^ { \mathcal { R } } } \mathcal { L } _ { D _ { \theta } } \left( \cdot \right)$ . We can then sample rewrites from $S _ { \phi }$ instead of computing the maximum. We denote this as $\langle \ell , \rho \rangle \sim S _ { \phi } ( s )$ and the overall BUGLAB training objective can be written as a min-max optimization problem:
$$\operatorname* { m a x } _ { \phi } \operatorname* { m i n } _ { \theta } E _ { \mathrm { s } \sim C } \left[ E _ { \langle \ell , \rho \rangle \sim S _ { \phi } ( \mathrm { s } ) } \left[ \mathcal { L } _ { D _ { \theta } } \left( \mathrm { s } [ \rho ] _ { \ell } , \langle \ell , \rho ^ { - 1 } \rangle \right) \right] \right] .$$
The two models $S$ and $D$ in BUGLAB are “symmetric” in the sense that they both predict rewrites on code snippets, and only differ in their objectives — one aiming to introduce bugs and one aiming to repair them. In practice, we can and do use the same architecture to model both $S$ and $D$ , which we will discuss in the next section. At test time, we discard $S$ and only use the trained detector $D$ to locate and repair bugs.
# 3 Neural Models
In this section, we discuss how we represent code in BUGLAB and the neural models we use to learn how to rewrite code in the selector and detector models.
Code Representation We consider source code as a set of entities $v _ { i } ~ \in ~ V$ which relate to each other with a set of typed relations $e _ { k } \in E$ , where a relation $e _ { k } = ( v _ { i } , r , v _ { j } )$ denotes a relationship between entities $v _ { i }$ and $v _ { j }$ with type $r$ . The entities and relations can be thought as a heterogeneous graph $G = ( V , E )$ . The choice of code entities and their relationships is a form of high-level feature extraction. We discuss concrete entities and relationships for Python in Sec. 4. We also define a projection function $\mathbb { P } _ { t o k }$ that accepts $V$ and $E$ and returns a sequence $V _ { t o k }$ of the token entities in $V$ with the nodes appearing in relations in $E$ deterministically mapped to elements of $V _ { t o k }$ , i.e. $E _ { t o k } = \{ ( p ( v _ { i } ) , r , p ( \hat { v _ { j } } ) ) \}$ , where $p$ maps the entities in $V$ to $V _ { t o k } . \mathbb { P } _ { t o k }$ will be used for relational transformer models.
To learn a neural representation of the code entities $v _ { i }$ , first we define an embedding function $e ( v _ { i } )$ which maps the content of each entity to an initial $D$ -dimensional representation. Throughout this work — similar to Allamanis et al. [4] and other previous work — we deterministically split the string representation of each node into subtokens (e.g., fooBar is split into foo and bar), embed them through a learned embedding matrix, and use max pooling to get a single vector. We then “contextualize” the entity representations within $G$ using one of two models: a MLP-based GNN model with max message aggregation and the GREAT relational transformer of Hellendoorn et al. [13] over the token sequence and relations $V _ { t o k } , E _ { t o k } = \mathbb { P } _ { t o k } ( V , E )$ . GREAT uses both positional encodings and the projected relations in $E _ { t o k }$ . See Appx. A for detailed architecture descriptions. Other models to compute entity representations can be used, but were not explored in this work.
We use $\mathbfit { \Delta } \mathbf { r } _ { \ell }$ to denote the computed vector representation of the entity at location $\ell$ , independent of the model used to produce it. We use these representations to define our code rewriting models.
Probabilistic Code Rewriting Models Both bug selection and bug detection require to model the probability of applying a specific rewrite at a location in a code snippet s, either to introduce or repair a bug. For this, we factorize this task into localization and rewrite-given-location models, i.e.
$$p \left( \langle \ell , \rho \rangle \mid \mathrm { s } , R _ { \mathrm { s } } ^ { \mathcal { R } } \right) = p _ { l o c } { \big ( } \ell \mid \mathrm { s } , R _ { \mathrm { s } } ^ { \mathcal { R } } { \big ) } p _ { r e w } { \big ( } \rho \mid \ell , \mathrm { s } , R _ { \mathrm { s } } ^ { \mathcal { R } } { \big ) } .$$
We model $p _ { l o c }$ as a probability distribution over the relevant locations $\{ \ell \mid \langle \ell , \rho \rangle \in R _ { \mathrm { s } } ^ { \mathcal { R } } \} \cup \{ \mathrm { N o B U G } \}$ , where NoBug is a special location used to indicate that the code is not buggy. In practice, we implement this similar to a pointer net [19] using the representations $\mathbfit { \Delta } \mathbf { r } _ { \ell }$ (see Appx. A for details).
To select rewrites, we use rewrite type-specific learnable rule score functions $w _ { \rho } \left( r _ { \ell } , \mathcal { M } _ { \rho } ( \mathrm { s } , \ell ) \right)$ . This function maps a vector representation of an entity $\mathbf { \Delta } _ { \mathbf { \lambda } ^ { \mathbf { r } } \ell }$ and potential additional metadata onto a scalar score. The rule-specific metadata $\mathcal { M } _ { \rho } ( \mathrm { s } , \ell )$ is defined for some rewrites, e.g. containing representations of other entities that could be used in the location $\ell$ . We will discuss three concrete rule score functions in Sec. 4. The rewrite probability distribution $p _ { r e w }$ is then modeled by a softmax over the scores of all applicable rewrites at a target location $\ell$ , i.e.
$$p _ { r e w } \left( \rho \mid \ell , \mathbf { s } , R _ { \mathbf { s } } ^ { \mathcal { R } } \right) = \operatorname * { s o f t m a x } _ { \langle \ell , \rho ^ { \prime } \rangle \in R _ { \mathbf { s } } ^ { \mathcal { R } } } \left( w _ { \rho ^ { \prime } } \left( r _ { \ell } , \mathcal { M } _ { \rho ^ { \prime } } ( \mathbf { s } , \ell ) \right) \right) .$$
# 4 A Python Implementation
This section presents an implementation of BUGLAB for Python called PYBUGLAB. PYBUGLAB currently tackles a large subset of “stupid simple bugs” [16]. Fixing these bugs requires small changes to the code, but commonly has significant impact on code correctness. Such bugs may be thought as a form of a typographical mistake or a copy-paste error, and are often relatively hard to locate by humans but obvious after the fact. They are also quite common, as observed in the empirical statistics of Karampatsis and Sutton [16] and Just et al. [14]. Future work may focus on a broader set of rewrite rules or even learnable rewrites, but as we will observe in Sec. 5 more work is needed towards this. Almost all ideas in PYBUGLAB transfer straightforwardly to other programming languages other than Python, but would require some engineering effort to implement.
PYBUGLAB Code Entities and Relations In this work, we follow related literature (see Sec. 6 for more) and extract entities and relationships that are readily available by tokenizers, parsers, existing simple program analyses, or other Python-specific program analysis tools. The complete list of entities and relationships can be found in Appx. B and include syntactic entities and relations, relations about the intraprocedural data and control flow, types, and documentation. Some notable entities include SyntaxNodes, Tokens, and Symbols (references to variables and functions). Fig. 4 in Appx. B shows a graph of the entities and relationships of the snippet in Fig. 2.
 Figure 2: Code snippet and rewrites available to PYBUGLAB.
# 4.1 Bug-Inducing PYBUGLAB Rewrite Rules
PYBUGLAB focuses on four common kinds of bugs. Fig. 2 shows a code snippet and the rewrites allowed for each location, which number 63 even for this small example.
Variable Misuse Originally defined by Allamanis et al. [3] as a Cloze test for source code, Vasic et al. [30] and Hellendoorn et al. [13] reformulated the task to localizing a variable misuse bug (if any) within a snippet and repairing it. PYBUGLAB uses the latter representation. Variable misuse bugs are common, with $1 2 . 8 \AA - 1 4 . 8 \%$ found in the ManySStuBs4J corpus [16] and about $6 \%$ of them caught during Java compilation in the Google build system [28]. To insert and repair variable misuse bugs, PYBUGLAB supports variable-swapping rewrites, such as in locations $l _ { 1 }$ , $l _ { 3 }$ and $l _ { 4 }$ (amongst others) in Fig. 2. To score a variable-swapping rewrite, we use the representation of the rewrite location $\mathbfit { \Delta } \mathbf { r } _ { \ell }$ along with the representation $\mathbf { \Delta } _ { r _ { \sigma } }$ of a variable Symbol $\sigma$ that could replace the current variable, i.e. is in-scope and has been defined before $\ell$ . The rule score function $w _ { \rho }$ for replacing the variable at $\ell$ with the symbol $\sigma$ is then computed as the inner product $\boldsymbol { r } _ { \ell } ^ { \top } \boldsymbol { r } _ { \sigma }$ .
Argument Swapping (or Argument Selection) First coined by Rice et al. [26], it refers to swapping the arguments of a function invocation, e.g. in $l _ { 6 }$ of Fig. 2. Rice et al. [26] and DeepBugs [22] tackled this problem when all arguments are single identifiers. PYBUGLAB extends this to swapping arbitrary argument expressions. The rule score function $w _ { \rho }$ for an argument swapping rewrite is a two-layer MLP applied to the concatenation of the output representations of the representation of the parameter and the to-be-swapped arguments arg1, and arg2: MLP $\left( [ r _ { \mathrm { p a r a m s } } , r _ { \mathrm { a r g 1 } } , r _ { \mathrm { a r g 2 } } ] \right)$ .
Wrong Operator Corrupting operators has a long history in mutation testing [14]. Detecting incorrect operators with deep learning was first tackled by DeepBugs [22] by using learnable embeddings of operators, operands and literals for arithmetic and comparison operators. DeepBugs focused only on binary operators. In PYBUGLAB we tackle all binary operators, including Boolean, arithmetic and comparison operators and two unary operators: logical and arithmetic negation. Locations $l _ { 1 1 }$ , $l _ { 1 4 }$ , $l _ { 1 6 }$ , and $l _ { 2 0 }$ in Fig. 2 are rewrites related to wrong operators. The rule score function $w _ { \rho }$ for an operator rewrite again uses an inner product, $\boldsymbol { r } _ { \ell } ^ { \top } \boldsymbol { r } _ { \mathtt { \diamond p } }$ , where $\pmb { r } _ { \tt o p }$ is a learned embedding for operator op. Note that we rewrite operators only to compatible operators (e.g. $<$ to $>$ but not $^ +$ ).
Wrong Literal Corrupting operands, and specifically, literals appearing in the source code, is also a common strategy in mutation testing. As in mutation testing, PYBUGLAB handles a limited number of commonly used literals, allowing rewrites to replace integer literals within the set of $- 2 , - 1 , 0 , 1 , 2$ and swapping the Boolean literal True with False and vice versa. The scoring function is identical to the operator rewrite, using a learnable embedding ${ \bf { r } } _ { \mathrm { { 1 i t } } }$ for each literal lit.
# 4.2 PYBUGLAB Rewrite Rules for Data Augmentation
We additionally consider more rewrite rules that are not meant to change the program semantics, using them as a form of data augmentation. This is in spirit similar to ideas in computer vision where images are transformed (e.g. rotated, cropped) but maintain their original content. Such rewrites
Require: Code dataset $C$ , initial detector/selector model parameters $\theta ^ { ( 0 ) }$ , $\phi ^ { ( 0 ) }$
1: for meta-epoch $i = 0$ to $I$ do 2: // Create dataset of buggy programs: 3: $C _ { D } ^ { ( i ) } \gets \left\{ \left( \mathrm { s } [ \rho ] _ { \ell } , \left. \ell , \rho ^ { - 1 } \right. \right) \mid \mathrm { s } \in C , k \mathrm { \ s a m p l e s \ } \left. \ell , \rho \right. \sim S _ { \phi ^ { ( i ) } } ( \mathrm { s } ) \right\}$ 4: $\theta ^ { ( i + 1 ) } $ update $\theta ^ { ( i ) }$ by training $D$ on $C _ { D } ^ { ( i ) }$ 5: // Create dataset of hard-to-detect bugs: 6: $\begin{array} { r } { C _ { S } ^ { ( i ) } \gets \left\{ \left( \mathrm { s } , \mathrm { a r g } \operatorname* { m a x } _ { \langle \ell , \rho \rangle \in R _ { \mathrm { s } } ^ { \mathcal { R } } } \left( \mathcal { L } _ { D _ { \theta ^ { ( i + 1 ) } } } \left( \mathrm { s } [ \rho ] _ { \ell } , \langle \ell , \rho ^ { - 1 } \rangle \right) \right) \right) \mid \mathrm { s } \in C \right\} } \end{array}$ 7: $\phi ^ { ( i + 1 ) } $ update $\phi ^ { ( i ) }$ by training $S$ on $C _ { S } ^ { ( i ) }$
have been shown to yield adversarially robust models of code [23]. Although our goal is not to provide adversarial robustness, we believe that such rewrites can help generalization. PYBUGLAB implements the following rewrites for this purpose:
• Variable Renaming renames a local variable to a random name not already in scope. • Comment Deletion removes code comments, including docstrings and inline comments. Such comments commonly contain natural language information that is useful for code comprehension, but usually do not affect program semantics. • Comparison Expression Mirroring swaps the two sides of a comparison operator and changes it appropriately. For example, $\mathtt { a } < \mathtt { b }$ is transformed to $\mathtt { b } > \mathtt { a }$ . Note that in cases such as $\mathbf { f } \circ \circ ( ) \ < \ \mathsf { b a r } ( )$ , this will change the order of execution of foo and bar, possibly altering program semantics. • If-Else Branch Swapping negates the test condition of an if-else statement or a ternary expressions using DeMorgan’s law and swaps the then body with the else body.
# 4.3 Implementation Details
To make the training computationally tractable we approximate Eq. 1. A simplified, sequential version of our training procedure is shown in Alg. 1. Intuitively, we alternate between training the two models, as the (discrete) sampling of rewrite rules in the selector models precludes direct endto-end training. We first use the current state of the selector model to generate “hard” samples and train the detector model on these samples (we always include the unmodified (i.e., NoBug case) as a sample). Then, we use the loss of the detector model to identify those generated samples that were hardest to detect and train the selector model to produce such samples.
In practice, we implemented the training procedure as a system of asynchronously communi$C _ { D / S } ^ { ( 0 ) } , \bar { C } _ { D / S } ^ { ( 1 ) } , \dots$ , and all of the described steps happen in parallel. We do not use “generations”of datasets, but instead use two constantly updated “pools” of training data, one state of the corresponding data pool. We remove samples from the data pool once they have been sampled $\nu$ times for use in training, in spirit similar to replay buffers in reinforcement learning. In our experiments, $\nu$ was set to 4. We regularly (in separate, concurrent processes) take snapshots of the the current state of the $D$ and $S$ models to generate new elements that are updated to the data pools, matching the procedure described in Alg. 1. We approximate the arg max in line 6 by only considering the $k$ samples chosen in line 3 for each input program. During training of $S$ , we then mask out the unobserved choices before computing the loss.
# 5 Evaluation
We now discuss our new dataset and evaluate PYBUGLAB. We $\divideontimes$ . . . . . . . . . .highlight. . . . .key . . . . . . . .results.
Datasets To train PYBUGLAB we retrieve the 4k most downloaded packages in the Python package index (PyPI) and take $3 . 4 \mathrm { k }$ of them as training packages, using the rest for test purposes. During training, PYBUGLAB installs each package along with all its dependencies. Installing all the dependencies is important for extracting the entities and the relations beyond local syntactic ones (e.g. type inference, method resolution). For each file, PYBUGLAB checks if it is a duplicate of a file that has already been seen in the training following the method of Allamanis [1] and runs all the relevant program analyses to extract the entities and relationships in each function. When we use additional rewrites for data augmentation, these are applied at the input of the PYBUGLAB pipeline as a form of pre-processing. Following Alg. 1, the bug selector $S$ selects $k = 5$ bugs to introduce, rewrites the source code text, and then the program analyses extract the new entities and relationships for the rewritten code snippets. The initial and rewritten code snippets are then used to create the training data for the detector and selector models.
We use two testsets to measure performance. First, we create RANDOMBUGS, a testset of 761 445 snippets derived from functions from the $6 0 0 \mathrm { P y P I }$ test packages (not seen during training). For each function we find within these packages we add it to the dataset along with 9 rewritten functions with a randomly inserted bug. On average graphs have 260 nodes, 601 edges, 25 rewrite locations, and 130 possible rewrites. We also collect a testset of real bugs. Although we conjecture that, in practice, the vast majority of bugs like those discussed in Sec. 4.1 are fixed when developers locally test their software, a few of those slip and then are fixed across different revisions checked into a version control systems. We have crawled the accessible repositories of all $2 8 5 \mathrm { k }$ packages in the Python Package Index (PyPI), collected and manually filtered bugs captured by the rewrites from Sec. 4.1. $\divideontimes$ . . . . .This. . . . . .new . . . . . . . . .dataset, . . . . . . . . . . . . . . .PYPIBUGS,. . . . . . . . . .contains. . . . . . .2374 . . . . . . . . . . . . .real-world,. . . . . . .small . . . . . . .bugs. We describe the data collection process in detail in Appx. D. In addition, we consider PYPIBUGS-PostFix: the examples from PYPIBUGS after a bug was fixed - we believe these samples are very likely to not contain any bugs anymore. We publish the dataset at https://www.microsoft.com/en-us/download/103554 and include it in the supplementary material.
# 5.1 Quantitative Evaluation
Our first experiment aims to evaluate whether the BUGLAB training framework yields more precise bug detectors. We consider two model architectures, using either GNNs or the GREAT transformer to compute embeddings of code entities (architecture details and hyperparameter choices can be found in Appx. A). We use four different training strategies: “supervised” is training only a bug detector on a fixed dataset of 1 million functions from the $3 . 4 \mathrm { k }$ training packages with randomly inserted bugs. “Random Selector” refers to a variant of PYBUGLAB using a bug selector model that uniformly at random picks a rewrite to insert bugs. Finally, PYBUGLAB and PYBUGLAB $+ \mathrm { A u g }$ use our framework from Sec. 2, with the latter also using additional rewrites to augment our code corpus. For the fully supervised model, we train with early stopping over a validation set; the other models are trained for a fixed number of 300 epochs (with $2 0 0 \mathrm { k }$ training samples per epoch) for the bug detector3 and the last detector model is used for evaluation.
Table 1: Accuracies $( \% )$ for different training strategies and model architectures on RANDOMBUGS.
<table><tr><td rowspan="3"></td><td colspan="6">RANDOMBUGS</td></tr><tr><td></td><td>GNN</td><td></td><td></td><td>GREAT</td><td></td></tr><tr><td>Joint</td><td>Loc</td><td>Repair</td><td>Joint</td><td>Loc</td><td>Repair</td></tr><tr><td>Supervised</td><td>62.4</td><td>73.6</td><td>81.2</td><td>51.0</td><td>61.9</td><td>76.3</td></tr><tr><td>Random Selector</td><td>69.4</td><td>79.6</td><td>84.0</td><td>63.9</td><td>73.6</td><td>82.0</td></tr><tr><td>PYBUGLAB</td><td>69.6</td><td>80.4</td><td>84.2</td><td>64.0</td><td>74.3</td><td>82.3</td></tr><tr><td>PYBUGLAB +Aug</td><td>70.3</td><td>81.1</td><td>84.5</td><td>65.3</td><td>75.3</td><td>82.5</td></tr></table>
Effectiveness of BUGLAB Training We first consider the performance of different models on the synthetic RANDOMBUGS dataset. Tbl. 1 shows the accuracy of predicting a full bug repair correctly (“Joint”) and analogous to Eq. 2 break this up into a localization accuracy (“Loc”) of predicting the correct location (or NoBug for correct examples) and a repair accuracy (“Repair”) for selecting the correct rewrite given the buggy location.
We observe that $\divideontimes$ . . . . . . . . . . . . . . . . . . . . .BUGLAB-training. . . . . . .leads. . . .to . . . . . . .more. . . . . . . .robust. . . . . .bug . . . . . . . . . . .detectors. . . . . . . . . . . . .compared. . .to. . . . . . . .other methods .......... for both GNNs and GREAT. Random selector models — a form of data augmentation — improve performance over supervised methods but mostly on in-distribution RANDOMBUGS samples. As expected, $\divideontimes$ . . . . . . . . . . . . .augmenting. . . . .the . . . . . .code. . . . . . . . .dataset. . . . . . .helps . . . . . . . . . . . . . . . . .generalization, but does not make a substantial difference. Expanding the kinds of rewrites used to augment the data and learning to select them may improve performance in the future.
Table 2: Results for different training strategies and model architectures on PYPIBUGS.
<table><tr><td></td><td colspan="6">PYPIBUGS</td><td colspan="4">PYPIBUGS-PostFix</td></tr><tr><td></td><td colspan="3">GNN</td><td colspan="3">GREAT</td><td colspan="2">GNN</td><td colspan="2">GREAT</td></tr><tr><td></td><td>Joint</td><td>Loc</td><td>Repair</td><td>Joint</td><td>Loc</td><td>Repair</td><td>Loc</td><td>Joint AUC</td><td>Loc</td><td>Joint AUC</td></tr><tr><td>Supervised</td><td>20.0</td><td>28.4</td><td>61.8</td><td>16.8</td><td>25.8</td><td>58.6</td><td>17.8</td><td>0.087</td><td>20.7</td><td>0.044</td></tr><tr><td>Random Selector</td><td>21.2</td><td>27.0</td><td>69.2</td><td>20.6</td><td>26.8</td><td>67.2</td><td>47.5</td><td>0.108</td><td>52.5</td><td>0.117</td></tr><tr><td>PYBUGLAB</td><td>24.2</td><td>31.3</td><td>70.7</td><td>24.0</td><td>32.8</td><td>67.9</td><td>32.9</td><td>0.160</td><td>28.6</td><td>0.140</td></tr><tr><td>PYBUGLAB +Aug</td><td>26.4</td><td>33.5</td><td>72.0</td><td>23.2</td><td>29.7</td><td>68.8</td><td>32.6</td><td>0.187</td><td>48.2</td><td>0.129</td></tr></table>
Table 3: Localization and Repair Accuracy $( \% )$ per bug kind for the PYBUGLAB +Aug model.
<table><tr><td rowspan="3">Bug Type</td><td colspan="4">RANDOMBUGS</td><td colspan="4">PYPIBUGS</td></tr><tr><td colspan="2">GNN</td><td colspan="2">GREAT</td><td colspan="2">GNN</td><td colspan="2">GREAT</td></tr><tr><td>Loc</td><td>Repair</td><td>Loc</td><td>Repair</td><td>Loc</td><td>Repair</td><td>Loc</td><td>Repair</td></tr><tr><td>Argument Swapping</td><td>85.0</td><td>57.3</td><td>65.5</td><td>57.2</td><td>33.2</td><td>73.9</td><td>24.3</td><td>72.7</td></tr><tr><td>Wrong Assign Op</td><td>96.1</td><td>99.1</td><td>94.5</td><td>98.6</td><td>20.0</td><td>68.9</td><td>14.0</td><td>58.1</td></tr><tr><td>Wrong Binary Op</td><td>83.0</td><td>85.2</td><td>77.3</td><td>81.4</td><td>27.2</td><td>54.3</td><td>36.6</td><td>43.7</td></tr><tr><td>Wrong Boolean Op</td><td>71.8</td><td>99.5</td><td>43.6</td><td>99.5</td><td>27.6</td><td>96.9</td><td>15.7</td><td>97.2</td></tr><tr><td>Wrong Comparison Op</td><td>83.9</td><td>79.3</td><td>80.0</td><td>76.4</td><td>33.7</td><td>66.1</td><td>31.1</td><td>53.5</td></tr><tr><td>Wrong Literal</td><td>71.7</td><td>74.7</td><td>66.6</td><td>71.6</td><td>21.6</td><td>78.4</td><td>17.9</td><td>79.5</td></tr><tr><td>Variable Misuse</td><td>84.9</td><td>88.4</td><td>78.2</td><td>86.3</td><td>35.3</td><td>70.5</td><td>34.0</td><td>69.4</td></tr><tr><td>NoBUG</td><td>53.8</td><td></td><td>62.5</td><td></td><td></td><td></td><td></td><td></td></tr></table>
Furthermore, $\ast { \mathrm { l o u g } } .$ . . . . . . . . . . . . . .localization . . .is . . . . . . .much . . . . . . . .harder. . . . . .than . . . . . . . .repair . . .at . .a . . . . . . .given . . . . . . . . . .location. This is somewhat expected: there are many more candidate locations compared to potential repairs at a given location. However, this suggests that research should focus on the localization problem rather than repair.
We now turn to the results on PYPIBUGS, shown in Tbl. 2, which also includes the accuracy of choosing the special NoBug location on the PYPIBUGS-PostFix dataset, as well as the area under the precision recall curve for the results on both PYPIBUGS and PYPIBUGS-PostFix.
We find that $\divideontimes$ . . . . . . . . . .detecting. . . . .and. . . . . . . . . . . .repairing . . . . . . . . .real-life. . . . . . .bugs . .is. . . . . . . . . . . . . . .significantly. . . . . . . .harder. . . . . .than. . . . . . . . . . .handling . . . . . . . . . . . .randomly . . . . . . . . .inserted. . . . . .bugs. As PYBUGLAB models trained using a learned bug selector outperform those using a “Random Selector”, we speculate that the learned selector avoids generating easy-to-detect bugs, focusing the detector model on recognizing deeper semantic patterns. Despite this, improvements in RANDOMBUGS often correlate with improvements in PYPIBUGS. This is encouraging: collecting PYPIBUGS-like datasets is costly; corpora with random bugs can help measure relative improvements to some extent. Finally, we find that $\divideontimes$ . . . . . . . . . . . . . .recognizing . . . . . . . . . . . . .non-buggy . . . . . . . . . .samples. . .is . . . . . .very . . . . . .hard, and in particular, does not always profit from training in PYBUGLAB.
In our qualitative analysis (Sec. 5.2), we observed that the models raised some confident but incorrect warnings at very “odd” locations. However, these warnings were different across models. We have tested an ensembling strategy averaging the output probabilities of five separately trained GNN models. This results in localization and repair accuracies of $8 3 . 0 \%$ and $8 5 . 4 \%$ on RANDOMBUGS (vs. $8 1 . 1 \%$ and $8 4 . 5 \%$ ) and $3 4 . 4 \%$ and $7 2 . 2 \%$ on PYPIBUGS (vs. $3 3 . 5 \%$ and $7 2 . 0 \%$ ). As we discuss in Sec. 5.2 finding the cause of the “spurious” warnings is important future work.
Per-Bug Evaluation To better understand which bugs are hard to detect, we break down the results the best-performing PYBUGLAB $+ \mathrm { A u g }$ models on RANDOMBUGS by type of bug in Tbl. 3. We observe that incorrect literals are some of the hardest bugs to detect. Incorrect assignment operators $( e . g . = \mathrm { a n d } + = )$ ) are easy to detect in RANDOMBUGS, but significantly harder in PYPIBUGS. This may be attributed to class imbalance, with simple assignment $( = )$ being the majority class. $\divideontimes$ Detecting . . . . . . . . . . . . . .if .a. . . . . . . . .snippet. . . . .has . .a . . . . .bug . . .or . . . .not. . . . . . . .seems . . .to . . .be. . . .the. . . . . . . . .hardest. . . . . .task:. . . .no. . . . . . . .model . . . . . . . . . .achieves. . . . . . . . . . .accuracy. . . . . . . . .beyond. $6 3 \%$ .
We note that in our experiments, GNNs-based models seem to often outperform GREAT, somewhat contradicting the results of Hellendoorn et al. [13]. We have performed substantial additional experiments to investigate and verify these results, cf. Sec. A.2. This may have to do with the performance of these models on long sequences or that the GNN has access to more fine-grained information, instead of relations over the projected token sequences. For example, this could be attributed to the lack of syntax and symbol nodes in the representation used in GREAT. Nevertheless, GREAT is noticeably better ( $6 2 . 5 \%$ vs. $5 3 . 8 \%$ ) at detecting NoBug and locating wrong binary operators in PYPIBUGS.
Table 5: Bug distribution $( \% )$ in different datasets
<table><tr><td>Bug Kind</td><td>PYPIBUGS</td><td>RANDOMBUGS</td><td>Selector Samples</td></tr><tr><td>Argument Swapping</td><td>11.9</td><td>8.4</td><td>23.8</td></tr><tr><td>Wrong Assignment</td><td>1.9</td><td>8.5</td><td>5.3</td></tr><tr><td>Wrong Binary Operator</td><td>3.4</td><td>2.4</td><td>2.3</td></tr><tr><td>Wrong Boolean Operator</td><td>8.1</td><td>2.2</td><td>6.4</td></tr><tr><td>Wrong Comparison Operator</td><td>17.1</td><td>8.2</td><td>7.4</td></tr><tr><td>Wrong Literal</td><td>3.7</td><td>11.6</td><td>12.4</td></tr><tr><td>Variable Misuse</td><td>53.8</td><td>58.6</td><td>42.5</td></tr></table>
Bug Selector Performance To understand how training of the bug selector proceeds, we perform two experiments. In our first experiment, we take a snapshot of the selector model during training of the PYBUGLAB $+ \mathrm { A u g }$ (GNN) model every 24 hours, after an initial burn-in phase of 12 hours. We then generate 10000 buggy samples using each of these snapshots and then test a fixed model on each of these snapshots. The results of this are shown in Tbl. 4, using a fully trained PYBUGLAB $+ \mathrm { A u g }$ (GNN) model from another training run as a fixed model. We conclude that . . . . . . . . . . . . . . . . . . . . . . . . .PYBUGLAB succeeds. . . .in . . . . . . . . . .learning . . .to . . . . . . . . . .generate. . . . . . . .harder. . .to find ..........bugs, though we can observe the selector model trading off “harder-to-localize” and “harder-tofix” properties. Tests on other models show similar trends, confirming the robustness of this result.
Table 4: Development of Performance on Bug Selector Samples
<table><tr><td>Training' Time</td><td>Joint</td><td>Loc</td><td>Repair</td></tr><tr><td>0.5 days</td><td>64.2</td><td>83.8</td><td>72.1</td></tr><tr><td>1.5 days</td><td>62.5</td><td>80.7</td><td>72.9</td></tr><tr><td>2.5 days</td><td>62.0</td><td>83.0</td><td>69.8</td></tr><tr><td>3.5 days</td><td>61.7</td><td>82.5</td><td>69.8</td></tr><tr><td>4.5 days</td><td>61.9</td><td>83.0</td><td>69.5</td></tr><tr><td>5.5 days</td><td>61.1</td><td>83.0</td><td>68.6</td></tr><tr><td>6.5 days</td><td>60.5</td><td>78.7</td><td>72.4</td></tr></table>
In a second experiment, we compare the distribution of different bug kinds in PYPIBUGS and RANDOMBUGS with the distribution of bugs sampled from the final snapshot of our selector model from above. The results are shown in Tbl. 5, where we can see that a number of bugs (argument swapping, use of wrong literals and of assignment operators) are substantially over-represented, whereas mistakes in comparison operators and variable misuse are under-represented. This indicates that . . . . . . . . . . . . . . . . . . . . . . . . . .PYBUGLAB generates. . . . . .hard . . .to . . . . . .find, . . . .but. . . .not. . . . . . . . . . . . . .necessarily . . . . . . . . . .realistic . . . . . .bugs.
Comparison to CuBERT Finally, we compare our models to CuBERT [15], which uses a masked language modeling objective to pre-train a BERT-like model and then learns bug detectors specific to a class of bugs (e.g., wrong binary operators) on top of this pre-trained model. Note that CuBERT detects $i f$ a bug exists but does not localize it. For the comparison, we create two sub-datasets of PYPIBUGS: PYPIBUGS-WrongOp contains the 501 samples that involve the binary operators supported by CuBERT, and PYPIBUGS-VarMisuse, which contains the 1278 bugs that involve variable misuses. We complete both of these datasets with 501 (resp. 1278) random NoBug code samples from our RANDOMBUGS, to match the 1:1 buggy/non-buggy distribution used in CuBERT’s training. Since CuBERT classification models focus on a single bug type, to compare to PYBUGLAB we mask out all code locations that do not correspond to a bug that could be detected by the corresponding CuBERT model. We then treat the prediction of the NoBug location as a “non-buggy” prediction and all other locations as a “buggy” prediction. For example, for the snippet in Fig. 2, only the locations $l _ { 2 }$ , $l _ { 1 1 }$ , $l _ { 1 4 }$ , $l _ { 1 6 }$ , and $l _ { 2 0 }$ and their corresponding rewrites are considered by PYBUGLAB for the comparison on PYPIBUGS-WrongOp.
Tbl. 6 shows the results of comparing the released CuBERT snapshots with the PYBUGLAB +Aug GNN model. We observe that $\divideontimes$ . . . .the . . . . . . . . . . . . . . . . . . . . . . . . .PYBUGLAB models
Table 6: Comparison with CuBERT [15]
<table><tr><td rowspan="2"></td><td colspan="3">CuBERT</td><td colspan="3">PYBUGLAB (GNN)</td></tr><tr><td>Prec</td><td>Recall</td><td>F1</td><td>Prec</td><td>Recall</td><td>F1</td></tr><tr><td>PYPIBUGs-WrongOp</td><td>0.764</td><td>0.251</td><td>0.378</td><td>0.730</td><td>0.764</td><td>0.746</td></tr><tr><td>PYPIBUGS-VarMisuse</td><td>0.632</td><td>0.403</td><td>0.493</td><td>0.740</td><td>0.840</td><td>0.787</td></tr></table>
. . . . .have. . . . . . . . . . . . . . . .substantially . . . . . . .better. . . . . . .recall. . . . . .than. . . . . . . . . . . . . . . . . . .CuBERT-based . . . . . . . . .models, even though they were trained to detect more bug types. When calibrating the CuBERT models to have a recall equal to PYBUGLAB, heir precision drops substantially. In particular, on PYPIBUGS-WrongOp, it is reduced to 0.609, and
1 def make_id(name): 2 $\mathbf { r } \ =$ get_rand_string(12) 3 if len(name) <= 22: 4 name $=$ name[:22] 5 return name $\textrm { + } \textrm { -- } \textrm { + } \textrm { \pmb { r } }$ (a) A wrong comparison operator bug (red box) in PYPIBUGS detected and repaired by the GNN PYBUGLAB +Aug models.
1 def update(self, roomId, 2 title, \*\*request_params): 3 check_type(roomId, basestring) 4 check_type(roomId, basestring) 5 [...]
(b) A variable misuse (red box) caught in an open-source project. GNN PYBUGLAB $+ \mathrm { A u g }$ suggests to rewrite roomId to title. The fixing pull request is found here.
Figure 3: Bugs found by PYBUGLAB. Snippets reformatted and abbreviated to fit figure.
on PYPIBUGS-VarMisuse, it is reduced to 0.613; in both cases, PYBUGLAB outperforms CuBERT substantially.
# 5.2 Qualitative Inspection of Raised Warnings
We now take a qualitative look at the raised warnings raised by PYBUGLAB. As example, Fig. 3a shows a sample of PYPIBUGS where the developer used an incorrect comparison operator. Once pointed to it, it is clear to a human that the truncation statement in line 4 has no effect (under the reasonable assumption that name is a string), and that a different comparison operator $( > )$ is necessary.
To gain an understanding of the performance of PYBUGLAB on realistic data, we performed an indepth analysis of the cases flagged as bugs by our best-performing model on the code found within the 4k top PyPI packages. We observed a mixture of false positives with few previously unseen real-life bugs, matching the quantitative results in Tbl. 3. First, we find that the majority of the false positives are “incorrect literal” detections. This suggests that learning to detect such bugs is a hard problem. Furthermore, many literals serve as default “configurations” (e.g. the number of retries for a network request) and different values are not bugs. We posit that a large percentage of literal replacements the selector learns to make fall in this category.
We also found that some repairs suggested by the model actually produce semantically equivalent code. For example, the model lacks knowledge that two variables refer to the same object in memory (aliasing), and so attempts to “repair” variable misuse bugs by switching between these. Other examples includes checking the return values of standard functions such as Python’s str.find, which returns $^ { - 1 }$ if the query string is not found. In such cases, PYBUGLAB often suggested to rewrite an if $\mathbf { x } \lrcorner \mathbf { f i n d } ( \mathbf { y } ) \ \ll \ - 1$ to if $\mathbf { x } \lrcorner \mathbf { f i n d } ( \mathbf { y } ) \ = - 1$ , which makes no difference in practice. These false negatives can be attributed to the fact that the bug selector model considers such changes as introducing bugs, even though they are not actually changing behavior. This suggests that for better results, the rewrite rules need to ensure that the rewrites are not semantics-preserving and represent bugs.
Finally, some reported issues were sufficiently complex that it took us (the human authors) a couple of minutes of thought to conclude that a warning is spurious. Simultaneously, there are some warnings that are “obviously” incorrect to us, but the reasons why the neural models raise them is unclear. This highlights the importance of research on explainability techniques along with better ways to calibrate model confidence. The fact that selectors may introduce spurious “bugs” may also be affecting how the detector model learns. Ideas that have appeared in reinforcement learning, such as the one of Dennis et al. [8], may allow models to improve their performance in spite of spurious bugs.
Overall, $\yen 123,456,7$ . . .of. . . . .the . . . . . .1000. . . . . . . . . . .reported . . . . . . . . . . .warnings . . . . . .were. . . . . . . .found . . .to . . .be. . . . . . . . . .real-life. . . . . . .bugs. Of these 19, we reported 11 on GitHub (6 already merged, 5 pending approval). See Appx. G for details. 3 other bugs had already been fixed between the version PYBUGLAB processed and the current version or the project was deprecated, whereas another 5 bugs are minor and we decided not to report them. One of the detected bugs is shown in Fig. 3b. Overall, most of the detected bugs appear within unit tests, logging, or exception handling, possibly because bugs there do not impact the core functionality of a project. However, given the number of such bugs we collected in PYPIBUGS, we believe that such bugs arise equally often in other code, but that they are detected and fixed more quickly.
Although our analysis only forms a lower bound on the precision of PYBUGLAB and related methods, it suggests that there is still ample room for future improvements towards making machine learningbased bug detection and repair practically useful.
# 6 Related Work
Detecting bugs in source code has been researched since the early days of computing. Traditionally, bug detection is tackled as a formal task, where any code that cannot be proved to satisfy some correctness property may contain a bug. This is essential for security- and safety-critical bugs, but not for other — equally common — bugs. In the last decade, software engineering and programming language research have increasingly realized ambiguous information within code (e.g. variable names, comments) contains valuable information and using this information can yield valuable results [2]. The main premise is that patterns in source code, such as patterns in names, control, and data flow can be informative. This information can also be exploited to detect some bugs. For example, Ray et al. [24] noted that even simple language models tend to assign lower probability to buggy code.
Multiple static analysis methods have been researched that combine some form of data-oriented bug detection. This ranges from language model-based tools, such as the early work of Wang et al. [32] to specification-mining tools such as the work of Eberhardt et al. [10]. BUGLAB is related to DeepBugs [22] which uses an MLP over a limited window of code tokens and train separate models to detect wrong operators, operands, and argument swappings. BUGLAB opts for a more structured representation of code and a single model. Allamanis et al. [3], Vasic et al. [30], Hellendoorn et al. [13] tackle variable misuse bugs (one of the kinds of bugs included in PYBUGLAB) but either by randomly introducing the bugs in code or using a Cloze-like test. Instead, BUGLAB opts for a selfsupervised approach and tackles a broader range of bugs. Concurrently to this work, Patra and Pradel [21] showed an alternative method for learning to generate realistic bugs. Dinella et al. [9] learn a supervised sequential model that performs graph transformations that replicate small edits in code (refactoring, introducing functionality, bug fixing, etc.). Their model — Hoppity — could serve as a learnable rewrite operation in BUGLAB in future work. Dynamic analysis methods have also been researched with promising results [31], but collecting representative dynamic traces over a diverse set of programs at scale (e.g. from the top Python packages used in this work) is practically impossible.
BUGLAB is related to ideas around self-supervised learning recently explored in deep learning, computer vision, and NLP. In our case, we aim to train a bug detection model without using training data from real-life bugs. BUGLAB resembles ELECTRA [6], with the important difference that the rewrites to the input code go beyond single token replacement that need to respect strict constraints of programming languages (syntax, variable scopes) and the model is directly used for bug detection, rather than for pre-training. The main BUGLAB objective Eq. 1 also resembles GANs [12] with the exception that the objective is non-differentiable (introducing a bug alters the discrete data representation), the selector is a structured probabilistic code rewriting model, and that we are mainly interested in the bug detector (analogous to the discriminator) rather than the selector.
# 7 Discussion and Conclusions
Learned program analyses offer the promise to improve how we develop software. They also offer a great opportunity to study machine learning models that combine formal and probabilistic reasoning. Towards achieving these we presented BUGLAB, a self-supervised approach for learning program analyses, that improves upon baseline methods and detects bugs in real-life code. We also empirically show the limitations of existing bug-detecting machine learning methods, which suffer from impractical false-positive rates. Importantly, we show the large gap of performance of existing methods on corpora of randomly inserted bugs — commonly used in prior work — and real-life bugs.
# Acknowledgements
We want to thank Sebastian Nowozin and Marwin Segler for helpful discussions, Marwin Segler for comments on a draft of this work, and the anonymous reviewers for useful questions and suggestions. Finally, we would like to thank the contributors to the following open-source tools used: PyTorch [20], PyDriller [27], MessagePack, LibCST, Jedi, Kubernetes, Helm.
References [1] M. Allamanis. The adverse effects of code duplication in machine learning models of code. In Proceedings of the 2019 ACM SIGPLAN International Symposium on New Ideas, New Paradigms, and Reflections on Programming and Software, pages 143–153, 2019. [2] M. Allamanis, E. T. Barr, P. Devanbu, and C. Sutton. A survey of machine learning for big code and naturalness. ACM Computing Surveys (CSUR), 51(4):1–37, 2018. [3] M. Allamanis, M. Brockschmidt, and M. Khademi. Learning to represent programs with graphs. In International Conference on Learning Representations (ICLR), 2018. [4] M. Allamanis, E. Barr, S. Ducousso, and Z. Gao. Typilus: Neural type hints. In Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI), pages 91–105. Association for Computing Machinery (ACM), 2020. [5] T. Bachlechner, B. P. Majumder, H. H. Mao, G. W. Cottrell, and J. McAuley. Rezero is all you need: Fast convergence at large depth. arXiv preprint arXiv:2003.04887, 2020. [6] K. Clark, M.-T. Luong, Q. V. Le, and C. D. Manning. ELECTRA: Pre-training text encoders as discriminators rather than generators. arXiv preprint arXiv:2003.10555, 2020. [7] M. Cvitkovic, B. Singh, and A. Anandkumar. Deep learning on code with an unbounded vocabulary. In Machine Learning 4 Programming, 2018. [8] M. Dennis, N. Jaques, E. Vinitsky, A. Bayen, S. Russell, A. Critch, and S. Levine. Emergent complexity and zero-shot transfer via unsupervised environment design. arXiv preprint arXiv:2012.02096, 2020. [9] E. Dinella, H. Dai, Z. Li, M. Naik, L. Song, and K. Wang. Hoppity: Learning graph transformations to detect and fix bugs in programs. In International Conference on Learning Representations, 2019. [10] J. Eberhardt, S. Steffen, V. Raychev, and M. Vechev. Unsupervised learning of API aliasing specifications. In Proceedings of the 40th ACM SIGPLAN Conference on Programming Language Design and Implementation, pages 745–759, 2019. [11] J. Gilmer, S. S. Schoenholz, P. F. Riley, O. Vinyals, and G. E. Dahl. Neural message passing for quantum chemistry. In International Conference on Machine Learning, pages 1263–1272, 2017. [12] I. J. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, and Y. Bengio. Generative adversarial networks. arXiv preprint arXiv:1406.2661, 2014. [13] V. J. Hellendoorn, C. Sutton, R. Singh, P. Maniatis, and D. Bieber. Global relational models of source code. In International Conference on Learning Representations, 2020. [14] R. Just, D. Jalali, L. Inozemtseva, M. D. Ernst, R. Holmes, and G. Fraser. Are mutants a valid substitute for real faults in software testing? In Proceedings of the 22nd ACM SIGSOFT International Symposium on Foundations of Software Engineering, pages 654–665, 2014. [15] A. Kanade, P. Maniatis, G. Balakrishnan, and K. Shi. Learning and evaluating contextual embedding of source code. In International Conference on Machine Learning (ICML), 2020. [16] R.-M. Karampatsis and C. Sutton. How often do single-statement bugs occur? the ManySStuBs4J dataset. In Proceedings of the 17th International Conference on Mining Software Repositories, pages 573–577, 2020. [17] J. Katz. Libraries.io Open Source Repository and Dependency Metadata, Jan. 2020. URL https://doi.org/10.5281/zenodo.3626071. [18] Y. Li, D. Tarlow, M. Brockschmidt, and R. Zemel. Gated graph sequence neural networks. In International Conference on Learning Representations (ICLR), 2016.
[19] S. Merity, C. Xiong, J. Bradbury, and R. Socher. Pointer sentinel mixture models. In International Conference on Learning Representations (ICLR), 2017.
[20] A. Paszke, S. Gross, S. Chintala, G. Chanan, E. Yang, Z. DeVito, Z. Lin, A. Desmaison, L. Antiga, and A. Lerer. Automatic differentiation in PyTorch. 2017. [21] J. Patra and M. Pradel. Semantic bug seeding: a learning-based approach for creating realistic bugs. In Proceedings of the 29th ACM Joint Meeting on European Software Engineering Conference and Symposium on the Foundations of Software Engineering, pages 906–918, 2021. [22] M. Pradel and K. Sen. DeepBugs: A learning approach to name-based bug detection. Proceedings of the ACM on Programming Languages, 2(OOPSLA):1–25, 2018. [23] G. Ramakrishnan, J. Henkel, Z. Wang, A. Albarghouthi, S. Jha, and T. Reps. Semantic robustness of models of source code. arXiv preprint arXiv:2002.03043, 2020. [24] B. Ray, V. Hellendoorn, S. Godhane, Z. Tu, A. Bacchelli, and P. Devanbu. On the ”naturalness” of buggy code. In 2016 IEEE/ACM 38th International Conference on Software Engineering (ICSE), pages 428–439. IEEE, 2016. [25] V. Raychev, M. Vechev, and A. Krause. Predicting program properties from Big Code. In Principles of Programming Languages (POPL), 2015. [26] A. Rice, E. Aftandilian, C. Jaspan, E. Johnston, M. Pradel, and Y. Arroyo-Paredes. Detecting argument selection defects. Proceedings of the ACM on Programming Languages, 1(OOPSLA): 1–22, 2017. [27] D. Spadini, M. Aniche, and A. Bacchelli. PyDriller: Python framework for mining software repositories. In Proceedings of the 2018 26th ACM Joint Meeting on European Software Engineering Conference and Symposium on the Foundations of Software Engineering - ESEC/FSE 2018, pages 908–911, New York, New York, USA, 2018. ACM Press. ISBN 9781450355735. doi: 10.1145/3236024.3264598. URL http://dl.acm.org/citation. cfm?doid $\equiv$ 3236024.3264598. [28] D. Tarlow, S. Moitra, A. Rice, Z. Chen, P.-A. Manzagol, C. Sutton, and E. Aftandilian. Learning to fix build errors with Graph2Diff neural networks. In Proceedings of the IEEE/ACM 42nd International Conference on Software Engineering Workshops, pages 19–20, 2020. [29] H. Touvron, M. Cord, A. Sablayrolles, G. Synnaeve, and H. Jegou. Going deeper with image ´ transformers. arXiv preprint arXiv:2103.17239, 2021. [30] M. Vasic, A. Kanade, P. Maniatis, D. Bieber, and R. Singh. Neural program repair by jointly learning to localize and repair. arXiv preprint arXiv:1904.01720, 2019. [31] K. Wang and Z. Su. Blended, precise semantic program embeddings. In Proceedings of the 41st ACM SIGPLAN Conference on Programming Language Design and Implementation, pages 121–134, 2020. [32] S. Wang, D. Chollak, D. Movshovitz-Attias, and L. Tan. Bugram: bug detection with n-gram language models. In Proceedings of the 31st IEEE/ACM International Conference on Automated Software Engineering, pages 708–719, 2016. [33] J. Wei, M. Goyal, G. Durrett, and I. Dillig. LambdaNet: Probabilistic type inference using graph neural networks. arXiv preprint arXiv:2005.02161, 2020.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275# ON CHARACTERIZING THE CAPACITY OF NEURAL NETWORKS USING ALGEBRAIC TOPOLOGY
Anonymous authors Paper under double-blind review
# ABSTRACT
The learnability of different neural architectures can be characterized directly by computable measures of data complexity. In this paper, we reframe the problem of architecture selection as understanding how data determines the most expressive and generalizable architectures suited to that data, beyond inductive bias. After suggesting algebraic topology as a measure for data complexity, we show that the power of a network to express the topological complexity of a dataset in its decision boundary is a strictly limiting factor in its ability to generalize. We then provide the first empirical characterization of the topological capacity of neural networks. Our empirical analysis shows that at every level of dataset complexity, neural networks exhibit topological phase transitions and stratification. This observation allowed us to connect existing theory to empirically driven conjectures on the choice of architectures for a single hidden layer neural networks.
# 1 INTRODUCTION
Deep learning has rapidly become one of the most pervasively applied techniques in machine learning. From computer vision (Krizhevsky et al. (2012)) and reinforcement learning (Mnih et al. (2013)) to natural language processing (Wu et al. (2016)) and speech recognition (Hinton et al. (2012)), the core principles of hierarchical representation and optimization central to deep learning have revolutionized the state of the art; see Goodfellow et al. (2016). In each domain, a major difficulty lies in selecting the architectures of models that most optimally take advantage of structure in the data. In computer vision, for example, a large body of work (Simonyan & Zisserman (2014), Szegedy et al. (2014), He et al. (2015), etc.) focuses on improving the initial architectural choices of Krizhevsky et al. (2012) by developing novel network topologies and optimization schemes specific to vision tasks. Despite the success of this approach, there are still not general principles for choosing architectures in arbitrary settings, and in order for deep learning to scale efficiently to new problems and domains without expert architecture designers, the problem of architecture selection must be better understood.
Theoretically, substantial analysis has explored how various properties of neural networks, (eg. the depth, width, and connectivity) relate to their expressivity and generalization capability (Raghu et al. (2016), Daniely et al. (2016), Guss (2016)). However, the foregoing theory can only be used to determine an architecture in practice if it is understood how expressive a model need be in order to solve a problem. On the other hand, neural architecture search (NAS) views architecture selection as a compositional hyperparameter search (Saxena & Verbeek (2016), Fernando et al. (2017), Zoph & Le (2017)). As a result NAS ideally yields expressive and powerful architectures, but it is often difficult to interperate the resulting architectures beyond justifying their use from their emperical optimality.
We propose a third alternative to the foregoing: data-first architecture selection. In practice, experts design architectures with some inductive bias about the data, and more generally, like any hyperparameter selection problem, the most expressive neural architectures for learning on a particular dataset are solely determined by the nature of the true data distribution. Therefore, architecture selection can be rephrased as follows: given a learning problem (some dataset), which architectures are suitably regularized and expressive enough to learn and generalize on that problem?
A natural approach to this question is to develop some objective measure of data complexity, and then characterize neural architectures by their ability to learn subject to that complexity. Then given some new dataset, the problem of architecture selection is distilled to computing the data complexity and chosing the appropriate architecture.
 Figure 1: The positive label outptus of single hidden layer neural networks, $h _ { 1 2 }$ and $h _ { 2 6 }$ , of 2 inputs with 12 and 26 hidden units respectively after training on datasets $\mathcal { D } _ { 1 }$ and $\mathcal { D } _ { 2 }$ with positive examples in red. Highlighted regions of the output constitute the positive decision region.
For example, take the two datasets $\mathcal { D } _ { 1 }$ and $\mathcal { D } _ { 2 }$ given in Figure 1(ab) and Figure 1(cd) respectively. The first dataset, $\mathcal { D } _ { 1 }$ , consists of positive examples sampled from two disks and negative examples from their compliment. On the right, dataset $\mathcal { D } _ { 2 }$ consists of positive points sampled from two disks and two rings with hollow centers. Under some geometric measure of complexity $\mathcal { D } _ { 2 }$ appears more ’complicated’ than $\mathcal { D } _ { 1 }$ because it contains more holes and clusters. As one trains single layer neural networks of increasing hidden dimension on both datasets, the minimum number of hidden units required to achieve zero testing error is ordered according to this geometric complexity. Visually in Figure 1, regardless of initialization no single hidden layer neural network with $\leq 1 2$ units, denoted $h _ { \leq 1 2 }$ , can express the two holes and clusters in $\mathcal { D } _ { 2 }$ . Whereas on the simpler $\mathcal { D } _ { 1 }$ , both $h _ { 1 2 }$ and $h _ { 2 6 }$ can express the decision boundary perfectly. Returning to architecture selection, one wonders if this characterization can be extrapolated; that is, is it true that for datasets with ’similar’ geometric complexity to $\mathcal { D } _ { 1 }$ , any architecture with $\geq 1 2$ hidden learns perfectly, and likewise for those datasets similar in complexity to $\mathcal { D } _ { 2 }$ , architectures with $\leq 1 2$ hidden units can never learn to completion?
# 1.1 OUR CONTRIBUTION
In this paper, we formalize the above of geometric complexity in the language of algebraic topology. We show that questions of architecture selection can be answered by understanding the ’topological capacity’ of different neural networks. In particular, a geometric complexity measure, called persistent homology, characterizes the capacity of neural architectures in direct relation to their ability to generalize on data. Using persistent homology, we develop a method which gives the first empirical insight into the learnability of different architectures as data complexity increases. In addition, our method allows us to generate conjectures which tighten known theoretical bounds on the expressivity of neural networks. Finally, we show that topological characterizations of architectures are possible and useful for architecture selection in practice by computing the persistent homology of CIFAR-10 and several UCI datasets.
# 2 BACKGROUND
# 2.1 GENERAL TOPOLOGY
In order to more formally describe notions of geometric complexity in datasets, we will turn to the language of topology. Broadly speaking, topology is a branch of mathematics that deals with characterizing shapes, spaces, and sets by their connectivity. In the context of characterizing neural networks, we will work towards defining the topological complexity of a dataset in terms of how that dataset is ’connected’, and then group neural networks by their capacity to produce decision regions of the same connectivity.
In topology, one understands the relationships between two different spaces of points by the continuous maps between them. Informally, we say that two topological spaces $A$ and $B$ are equivalent $A \cong B$ ) if there is a continuous function $f : A B$ that has an inverse $f ^ { - 1 }$ that is also continuous. When $f$ exists, we say that $A$ and $B$ are homeomorphic and $f$ is their homeomorphism; for a more detailed treatment of general topology see Bredon (2013). Take for example, the classic example of the coffee cup and the donut in
 Figure 2: A continuous deformation of a coffee cup into a donut, showing that both are topologically equivalent (Kato et al. (2014)).
Figure 2. They are homeomorphic because one can define a continuous deformation of one into the other which shrinks, twists, and morphs without tearing or gluing, as in Figure 2. Note that if the donut had two holes, it would no longer be equivalent to the mug. Likewise, in an informal way, $\mathcal { D } _ { 1 } \not \cong \mathcal { D } _ { 2 }$ in Figure 1 since if there were a homeomorphism $f : \mathcal { D } _ { 1 } \mathcal { D } _ { 2 }$ at least one of the clusters in $\mathcal { D } _ { 1 }$ would need to be split in order to produce the four different regions in $\mathcal { D } _ { 2 }$ .
The power of topology lies in its capacity to differentiate sets (topological spaces) in a meaningful geometric way that discards certain irrelevant properties such as rotation, translation, curvature, etc. For the purposes of defining geometric complexity, non-topological properties1 like curvature would further fine-tune architecture selection–say if $\mathcal { D } _ { 2 }$ had the same regions but with squigly (differentially complex) boundaries, certain architectures might not converge–but as we will show, grouping neural networks by ’topological capacity’ provides a powerful minimality condition. That is, we will show that if a certain architecture is incapable of expressing a decision region that is equivalent in topology to training data, then there is no hope of it ever generalizing to the true data.
# 2.2 ALGEBRAIC TOPOLOGY
Algebraic topology provides the tools necessary to not only build the foregoing notion of topological equivalence into a measure of geometric complexity, but also to compute that measure on real data (Betti (1872), Dey et al. (1998), Bredon (2013)). At its core, algebraic topology takes topological spaces (shapes and sets with certain properties) and assigns them algebraic objects such as groups, chains, and other more exotic constructs. In doing so, two spaces can be shown to be topologically equivalent (or distinct) if the algebraic objects to which they are assigned are isomorphic (or not). Thus algebraic topology will allow us to compare the complexity of decision boundaries and datasets by the objects to which they are assigned.
Although there are many flavors of algebraic topology, a powerful and computationally realizable tool is homology.
Definition 2.1 (Informal, Bredon (2013)). If $X$ is a topological space, then $H _ { n } ( X ) = \mathbb { Z } ^ { \beta _ { n } }$ is called the nth homology group of $X$ if the power $\beta _ { n }$ is the number of ’holes’ of dimension $n$ in $X$ . Note that $\beta _ { 0 }$ is the number of separate connected components. We call $\beta _ { n } ( X )$ the nth Betti number of $X$ . Finally, the homology2 of $X$ is defined as $H ( X ) = \{ H _ { n } ( X ) \} _ { n = 0 } ^ { \infty }$ .
Immediately homology brings us closer to defining the complexity of $\mathcal { D } _ { 1 }$ and $\mathcal { D } _ { 2 }$ . If we assume that $\mathcal { D } _ { 1 }$ is not actually a collection of $N$ datapoints, but really the union of 2 solid balls, and likewise that $\mathcal { D } _ { 2 }$ is the union of 2 solid balls and 2 rings, then we can compute the homology directly. In this case $H _ { 0 } ( \mathcal { D } _ { 1 } ) = \mathbb { Z } ^ { 2 }$ since there are two connected components3; $H _ { 1 } ( \mathcal { D } _ { 1 } ) = \{ 0 \}$ since there are no circles (one-dimensional holes); and clearly, $H _ { n } ( \mathcal { D } _ { 1 } ) = { \overline { { \{ 0 \} } } }$ for $n \geq 2$ . Performing the same computation in the second case, we get $H _ { 0 } ( \mathcal { D } _ { 2 } ) = \mathbb { Z } ^ { 4 }$ and $H _ { 1 } ( \dot { \mathcal { D } } _ { 2 } ) = \mathbb { Z } ^ { 2 }$ as there are 4 seperate clusters and 2 rings/holes. With respect to any reasonable ordering on homology, $\mathcal { D } _ { 2 }$ is more complex than $\mathcal { D } _ { 1 }$ . The measure yields non-trivial differentiation of spaces in higher dimension. For example, the homology of a hollow donut is $\{ \mathbb { Z } ^ { 1 } , \mathbb { Z } ^ { 2 } , \mathbb { Z } ^ { 1 } , 0 , \dots \}$ .
Surprisingly, the homology of a space contains a great deal of information about its topological complexity1. The following theorem suggests the absolute power of homology to group topologically similar spaces, and therefore neural networks with topologically similar decision regions.
Theorem 2.2 (Informal). Let $X$ and $Y$ be topological spaces. If $X \cong Y$ then $H ( X ) = H ( Y )$ . 4
Intuitively, Theorem 2.2 states that number of ’holes’ (and in the case of $H _ { 0 } ( X )$ , connected components) are topologically invariant, and can be used to show that two shapes (or decision regions) are different.
# 2.3 COMPUTATIONAL METHODS FOR HOMOLOGICAL COMPLEXITY
In order to compute the homology of both $\mathcal { D } _ { 1 }$ and $\mathcal { D } _ { 2 }$ we needed to assume that they were actually the geometric shapes from which they were sampled. Without such assumptions, for any dataset $\mathcal { D }$ a $\mathbf { \bar { \theta } } _ { H ( \mathcal { D } ) } = \{ \mathbb { Z } ^ { N } , 0 , \dots \}$ where $N$ is the number of data points. This is because, at small enough scales each data point can be isolated as its own connected component; that is, as sets each pair of different positive points $d _ { 1 } , d _ { 2 } \in \mathcal { D }$ are disjoint. To properly utilize homological complexity in better understanding architecture selection, we need to be able to compute the homology of the data directly and still capture meaningful topological information.
 Figure 3: Left: The local disconnectedness of datasets prevents direct computation of their homology. Right: An illustration of computing persistent homology on a collection of points (Topaz et al. (2015))
Persistent homology, introduced in Zomorodian & Carlsson (2005), avoids the trivialization of computation of dataset homology by providing an algorithm to calculate the homology of a filtration of a space. Specifically, a filtration is a topological space $X$ equipped with a sequence of subspaces $X _ { 0 } \subset X _ { 1 } \subset \cdots \subset X$ . In Figure 3 one such particular filtration is given by growing balls of size $\epsilon$ centered at each point, and then letting $X _ { \epsilon }$ be the resulting subspace in the filtration. Define $\beta _ { n } ( X )$ to be the nth Betti number of the homology $H ( X _ { \epsilon } )$ of $X _ { \epsilon }$ . Then for example at $\epsilon = 1 . 5$ , $\beta _ { 0 } ( X _ { \epsilon } ) = 1 9$ and $\beta _ { 1 } ( X _ { \epsilon } ) = 0$ as every ball is disjoint. At $\epsilon = 5 . 0$ some connected components merge and $\beta _ { 0 } ( X _ { \epsilon } ) = 1 2$ and $\beta _ { 1 } ( X _ { \epsilon } ) = 0$ . Finally at $\epsilon = 7$ , the union of the balls forms a hole towards the center of the dataset and $\beta _ { 1 } ( X _ { \epsilon } ) > 0$ with $\beta _ { 0 } ( X _ { \epsilon } ) = 4$ .
All together the change in homology and therefore Betti numbers for $X _ { \epsilon }$ as $\epsilon$ changes can be summarized succinctly in the persistence barcode diagram given in Figure 3. Each bar in the section $\beta _ { n } ( X )$ denotes a ’hole’ of dimension $n$ . The left endpoint of the bar is the point at which homology detects that particular component, and the right endpoint is when that component becomes indistinguishable in the filtration. When calculating the persistent homology of datasets we will frequently use these diagrams.
With the foregoing algorithms established, we are now equipped with the tools to study the capacity of neural networks in the language of algebraic topology.
# 3 HOMOLOGICAL CHARACTERIZATION OF NEURAL ARCHITECTURES
In the forthcoming section, we will apply persistent homology to emperically characterize the power of certain neural architectures. To understand why homological complexity is a powerful measure for differentiating architectures, we present the following principle.
Suppose that $\mathcal { D }$ is some dataset drawn from a joint distribution $F$ with continuous CDF on some topological space $X \times \{ 0 , 1 \}$ . Let $X ^ { + }$ denote the support of the distribution of points with positive labels, and $X ^ { - }$ denote that of the points with negative labels. Then let $H _ { S } ( f ) \mathrel { \mathop : } = H [ f ^ { - 1 } ( \dot { ( 0 , \infty ) } ) ]$ denote the support homology of some function $f : X \to \{ 0 , 1 \}$ . Essentially $H _ { S } ( f )$ is homology of the set of $x$ such that $f ( x ) > 0$ . For a binary classifier, $f$ , $H _ { S } ( f )$ is roughly a characterization of how many ’holes’ are in the positive decision region of $f$ . We will sometimes use $\beta _ { n } ( f )$ to denote the $n$ th Betti number of this support homology. Finally let ${ \mathcal { F } } = \{ f : X \to \{ 0 , 1 \} \}$ be some family of binary classifiers on $X$ .
Theorem 3.1 (The Homological Principle of Generalization). If $X = X ^ { - } \sqcup X ^ { + }$ and for all $f \in { \mathcal { F } }$ with $H _ { S } ( f ) \neq H ( X ^ { + } )$ , then for all $f \in { \mathcal { F } }$ there exists $A \subset X ^ { + }$ so $f$ misclassifies every $x \in A$ .
Essential Theorem 3.1 says that if an architecture (a family of models $\mathcal { F }$ ) is incapable of producing a certain homological complexity, then for any model using that architecture there will always be a set $A$ of true data points on which the model will fail. Note that the above principle holds regardless of how $f \in { \mathcal { F } }$ is attained, learned or otherwise. However, the principle does imply that no matter how well some $\mathcal { F }$ learns to correctly classify $\mathcal { D }$ there will always be a counter examples in the true data.
In the context of architecture selection, the foregoing minimality condition significantly reduces the size of the search space by eliminating smaller architectures which cannot even express the ’holes’ (persistent homology) of the data $H ( \mathcal D )$ . This allows us to return to our original question of finding suitably expressive and generalizeable architectures but in the very computable language of homological complexity: Let ${ \mathcal { F } } _ { A }$ the set of all neural networks with ’architecture’ $A$ , then
Given a dataset $\mathcal { D }$ , for which architectures $A$ does there exist a neural network $f \in { \mathcal { F } } _ { A }$ such that $H _ { S } ( f ) = H ( \mathcal { D } )$ ?
We will resurface a contemporary theoretical view on this question, and thereafter make the first steps towards an emperical characterization of the capacity of neural architectures in the view of topology.
# 3.1 THEORETICAL BASIS FOR NEURAL HOMOLOGY
Theoretically, the homological complexity of neural network can be framed in terms of the sum of the number of holes expressible by certain architectures. In particular, Bianchini et al. (2014) gives an analysis of how the maximum sum of Betti numbers grows as ${ \mathcal { F } } _ { A }$ changes. The results, summarized in Table 1, show that the width, depth, and activation of a fully connected architecture effect its topological expressivity to varying polynomial and exponential degrees. What is unclear from this analysis is how these bounds describe expressivity in terms of individual Betti numbers. For example, with a tanh activation function, $n$ inputs, $\ell$ layers, and $h$ hidden units, there is no description of what the number of connected components $\operatorname* { m a x } _ { f \in { \mathcal { F } } _ { A } } \beta _ { 0 } ( f )$ or 1-dimensional holes $\operatorname* { m a x } _ { f \in { \mathcal { F } } _ { A } } { \beta _ { 1 } ( f ) }$ actually is. With regards to tighter bounds Bianchini et al. (2014) stipulate that improvements to their results are deeply tied to several unsolved problems in algebraic topology.
Table 1: Upper bounds on homological expressivity of neural architectures (Bianchini et al. (2014).)
<table><tr><td colspan="4">Architecture A</td><td>maxfeFA∑=1 βk(f)</td></tr><tr><td></td><td>Inputs Layers Units</td><td></td><td>Activation</td><td></td></tr><tr><td>n</td><td>3</td><td>h</td><td>threshold</td><td>O(hn)</td></tr><tr><td>n</td><td>3</td><td>h</td><td>arctan</td><td>O((n + h)n+2)</td></tr><tr><td>n</td><td>3</td><td>h</td><td>polynomial, deg. r</td><td>1(2+r)(1+r)n-1</td></tr><tr><td>1</td><td>3</td><td>h</td><td>arctan</td><td>h</td></tr><tr><td>n</td><td>l</td><td>h</td><td>arctan</td><td>2h(2h-1)O(nl + n)n+2h)</td></tr><tr><td>n</td><td>l</td><td>h</td><td>tanh</td><td>2h(h-1)/20(nl + n)n+h)</td></tr><tr><td>n</td><td>l</td><td>h</td><td>polynomial, deg. r</td><td>1(2+r)(1+r)n-1)</td></tr></table>
 Figure 4: Topological phase transitions in low dimensional neural networks as the homological complexity of the data increases. The upper right corner of each plot is a dataset on which the neural networks of increasing hidden dimension are trained.
# 3.2 EMPIRICAL RESULTS
To understand how the homology of data determines expressive architectures we turn to an empirical characterization of neural networks. In this setting, we can tighten the bounds given in Table 1 by training different architectures on datasets with known homologies and then recording the decision regions observed over the course of training.
# 3.2.1 HOMOLOGICAL CAPACITY OF HIDDEN UNITS.
In the most basic case, one is interested in studying how the number of hidden units in a single hidden layer neural network affect its homological capacity. The results of Bianchini et al. (2014) say for certain activation functions we should expect a polynomial dependence on the sum of Betti numbers $\sum \beta _ { n }$ , but is this true of individual numbers? Having an individual characterization would allow for architecture selection by computing the homology of the dataset, and then finding which architectures meet the minimal criterion for each Betti number $\beta _ { n }$ .
Restricting5 our analysis to the case of two inputs, $n = 2$ , we characterize the capacities of architectures with an increasing number of hidden units to learn on datasets with homological complexities ranging from $\{ \mathbb { Z } ^ { 1 } , 0 \}$ to $\{ \mathbb { Z } ^ { 2 0 } , \mathbb { Z } ^ { 2 0 } \}$ . In our experiment, we generate datasets of each particular homological complexity by sampling different combinations of balls, rings, and scaling, twisting, and gluing them at random. After generating the foregoing datasets with $N \approx 9 0 0 0 0$ samples we train 100 randomly (truncated normal) initialized single hidden layer architectures with hidden units $h \in \{ 1 , \ldots , 2 5 5 \}$ and tanh activation functions for $\mathrm { \bar { 1 0 ^ { 6 } } }$ minibatches of size 128. During training, every 2500 batches we sample the decision boundary of each neural network over a grid of $5 0 0 \times 5 0 0$ samples, producing $1 . 0 2 \times 1 \bar { 0 } ^ { 6 }$ recorded decision boundaries. Using the resulting data, we not only characterize different architectures but observed interesting topological phenomena during learning.
 Figure 5: Several different views of the probability of converging to zero-error for single hidden layer neural networks on datasets with different homological complexities.
 Figure 6: An example of topological stratification for single hidden layer networks. (a) The number of connected components in the decision regions during training. (b) Correlation of Betti numbers.
First, neural networks exhibit a statistically significant topological phase transition in their convergence which depends directly on the homological complexity of the data. For any dataset in the experiment and any random homeomorphism applied thereto, the best test error of architectures with $h$ hidden units is strictly ordered in magnitude and convergence time for $h < h _ { p h a s e }$ where $h _ { p h a s e }$ is a number of hidden units required to express the homology of the data. In Figure 4 we plot the best performing test error of architectures $h \in \{ 1 , \ldots , 1 5 \}$ on some example datasets $\mathcal { D } _ { 0 } , \mathcal { D } _ { 1 }$ , and $\mathcal { D } _ { 2 }$ with $H ( \tilde { \mathcal { D } _ { 0 } } ) \approx \{ \mathbb { Z } ^ { 2 } , 0 \}$ , $H ( \mathcal { D } _ { 1 } ) \approx \{ \mathbb { Z } ^ { 3 } , 0 \}$ , $H ( \mathcal { D } _ { 2 } ) \overset { \cdot } { \approx } \{ \mathbb Z ^ { 3 } , \mathbb Z ^ { 2 } \}$ . In this example $h _ { p h a s e } ( \mathcal { D } _ { 0 } ) = 4 , h _ { p h a s e } ( \mathcal { D } _ { 1 } ) = 6$ , and $h _ { p h a s e } ( \mathcal { D } _ { 2 } ) = 1 0$ . Surprisingly, leading up to the phase transition point, each different architecture falls into its own band of optimal convergence. This suggests that additional hidden units do in fact add to the topological capacity of an architecture in a consistent way.
Using topological phase transitions we now return to the original question of existence of expressive architectures. In Figure 5, we accumulate the probabilities that neural networks of varying hidden dimension train to zero-error on datasets of different homological complexities. The table gives different views into how expressive an architecture need be in order to converge, and therefore we are able to conjecture tighter bounds on the capacity of hidden units. Extrapolating from the first view, if $H _ { 0 } ( \mathcal { D } ) = \mathbb { Z } ^ { m }$ then there exists a single hidden layer neural network with $h = m + 2$ that converges to zero error on $\mathcal { D }$ . Likewise we claim that if $H _ { 0 } ( \mathcal { D } ) = \mathbb { Z } ^ { m }$ and $H _ { 1 } ( \mathcal { D } ) = 1$ then the same holds with $h \geq 3 m - 1$ . Further empirical analysis of convergence probabilities yields additional conjectures. However, claiming converse conjectures about a failure to generalize in the view of Theorem 3.1 requires exhaustive computation of decision boundary homologies.
By applying persistent homology to the decision boundaries of certain networks during training, we observe that given sufficient data, neural networks exhibit topological stratification. For example, consider the homologies of different architecture decision regions as training progresses in Figure 6(a). At the beginning of training every model captures the global topological information of the dataset and is homologically correlated with one another. However as training continues, the architectures stratify into two groups with homological complexities ordered by the capacities of the models. In this example, $h _ { 3 } , h _ { 4 }$ , and $h _ { 5 }$ are unable to express as many holes as the other architectures and so never specialize to more complex and local topological properties of the data. Figure 6(b) depicts topological stratification in terms of the correlation between Betti numbers. Topologically speaking, networks with less than 6 hidden units are distinct from those with more for most of training. Furthermore, this correlative view shows that stratification is consistent with topological phase transition; that is, across all decision boundary homologies recorded during the experiment stratification occurs just when the number of hidden units is slightly less than $h _ { p h a s e }$ .
# 4 THE TOPOLOGY OF REAL DATA
We have thus far demonstrated the discriminatory power of homological complexity in determining the expressivity of architectures. However, for homological complexity to have any practical use in architecture selection, it must be computable on real data, and more generally real data must have non-trivial homology; if all data were topologically simple our characterization would have no predictive power. In the following section we will compute the persistent homologies up to dimension 2 of different real world datasets.
 Figure 7: The persistent homology barcodes of classes in the CIFAR-10 and UCI Protein Localization Datasets. Left: The bardcode for dimension 0 and 1 of the ’CYT’ class along side its local linear embedding into $\mathbb { R } ^ { 2 }$ . Right: The barcode for the dimensions 0 and 1 for the ’cars’ class along side different samples thereof in CIFAR-10. Note how different orientations are shown.
CIFAR-10. We compute the persistent homology of several classes of CIFAR-10 using the Python library Dionysus. Currently algorithms for persistent homology do not deal well with high dimensional data, so we embed the entire dataset in $\mathbb { R } ^ { 3 }$ using local linear embedding (LLE; Saul & Roweis (2000)) with $K = 1 2 0$ neighbors. After embedding the dataset, we take a sample of 1000 points from example class ’car’ and build a persistent filtration by constructing a Vietoris-Rips complex on the data. The resulting complex has 20833750 simplices and took $4 . 3 \mathrm { { m i n } }$ . to generate. Finally, computation of the persistence diagram shown in Figure 7 took $8 . 4 \mathrm { { m i n } }$ . locked to a single thread on a Intel Core i7 processor. The one-time cost of computing persistent homology could easily augment any neural architecture search.
Although we only give an analysis of dimension 2 topological features–and there is certainly higher dimensional homological information in CIFAR-10–the persistence barcode diagram is rich with different components in both $H _ { 0 } ( \mathcal { D } )$ and $H _ { 1 } ( \mathcal { D } )$ . Intuitively, CIFAR contains pictures of cars rotated accross a range of different orientations and this is exhibited in the homology. In particular, several holes are born and die in the range $\epsilon \in [ 0 . 1 5 , 0 . 3 7 5 ]$ and one large loop from $\epsilon \in [ 0 . 6 2 5 , 0 . 8 2 ]$ .
UCI Datasets. We further compute the homology of three low dimensional UCI datasets and attempt to assert the of non-trivial , $h _ { p h a s e }$ . Specifically, we compute the persistent homology of the majority classes in the Yeast Protein Localization Sites, UCI Ecoli Protein Localization Sites, and HTRU2 datasets. For these datasets no dimensionality reduction was used. In Figure 7(left), the persistence barcode exhibits two seperate significant loops (holes) at $\epsilon \in [ 0 . 1 9 , 0 . 3 1 ]$ and $\epsilon \in [ 0 . 7 6 , 0 . 8 5 ]$ , as well as two major connected components in $\beta _ { 0 } ( \mathcal { D } )$ . The Other persistence diagrams are relegated to the appendix.
Existing Data. Outside of the primary machine learning literature, topological data analysis yields non-trivial computations in wide variety of fields and datasets. Of particular interest is the work of Carlsson et al. (2008), which computes the homological complexity of collections of $n \times n$ patches of natural images. Even in these simple collections of images, the authors found topologies of Klein Bottles $( \mathbf { \bar { \cal H } } ( \cdot ) = \{ \mathbb { Z } , \mathbb { Z } ^ { 2 } / 2 \mathbb { Z } , 0 \ldots \} )$ and other exotic topological objects. Other authors have calculated non-trivial dataset homologies in biological (Topaz et al. (2015)), natural language (Michel et al. (2017)), and other domains (Wu et al. (2017), Xia & Wei (2014)).
# 5 RELATED WORK
We will place this work in the context of deep learning theory as it relates to expressivity. Since the seminal work of Cybenko (1989) which established standard universal approximation results for neural networks, many theorists have endeavored to understand the expressivity of certain neural architectures. Pascanu et al. (2013) and MacKay (2003) provided the first analysis relating the depth and width of architectures to the complexitity of the sublevel sets they can express. Motivated therefrom, Bianchini et al. (2014) expressed this theme in the language of Pfefferian functions, thereby bounding the sum of Betti numbers expressed by sublevel sets. Finally Guss (2016) gave an account of how topological assumptions on the input data lead to optimally expressive architectures. In parallel, Eldan & Shamir (2016) presented the first analytical minimality result in expressivity theory; that is, the authors show that there are simple functions that cannot be expressed by two layer neural networks with out exponential dependence on input dimension. This work spurred the work ofPoole et al. (2016), Raghu et al. (2016) which reframed expressivity in a differential geometric lense.
Our work presents the first method to derive expressivity results empirically. Our topological viewpoint sits dually with its differential geometric counterpart, and in conjunction with the work of Poole et al. (2016) and Bianchini et al. (2014), this duallity implies that when topological expression is not possible, exponential differential expressivity allows networks to bypass homological constaints at the cost of adversarial sets. Furthermore, our work opens a practical connectio nbetween the foregoing theory on neural expressivity and architecture selection, with the potential to drastically improve neural architecture search (Zoph & Le (2017)) by directly computing the capacities of different architectures.
# 6 CONCLUSION
Architectural power is deeply related to the algebraic topology of decision boundaries. In this work we distilled neural network expressivity into an empirical question of the generalization capabilities of architectures with respect to the homological complexity of learning problems. This view allowed us to provide an empirical method for developing tighter characterizations on the the capacity of different architectures in addition to a principled approach to guiding architecture selection by computation of persistent homology on real data.
There are several potential avenues of future research in using homological complexity to better understand neural architectures. First, a full characterization of neural networks with many layers or convolutional linearities is a crucial next step. Our empirical results suggest that the their are exact formulas describing the of power of neural networks to express decision boundaries with certain properties. Future theoretical work in determining these forms would significantly increase the efficiency and power of neural architecture search, constraining the search space by the persistent homology of the data. Additionally, we intend on studying how the topological complexity of data changes as it is propagated through deeper architectures.
# REFERENCES
E Betti. Il nuovo cimento. Series, 2:7, 1872.
Monica Bianchini et al. On the complexity of shallow and deep neural network classifiers. In ESANN, 2014.
Glen E Bredon. Topology and geometry, volume 139. Springer Science & Business Media, 2013.
Gunnar Carlsson, Tigran Ishkhanov, Vin De Silva, and Afra Zomorodian. On the local behavior of spaces of natural images. International journal of computer vision, 76(1):1–12, 2008.
Frédéric Chazal, Brittany Fasy, Fabrizio Lecci, Bertrand Michel, Alessandro Rinaldo, and Larry Wasserman. Subsampling methods for persistent homology. In Proceedings of the 32nd International Conference on Machine Learning (ICML-15), pp. 2143–2151, 2015.
George Cybenko. Approximation by superpositions of a sigmoidal function. Mathematics of Control, Signals, and Systems (MCSS), 2(4):303–314, 1989.
Amit Daniely, Roy Frostig, and Yoram Singer. Toward deeper understanding of neural networks: The power of initialization and a dual view on expressivity. In Advances In Neural Information Processing Systems, pp. 2253–2261, 2016.
TK Dey, H Edelsbrunner, and S Guha. Computational topology, invited paper in advances in discrete and computational geometry, eds. b. chazelle, je goodmann and r. pollack. Contemporary Mathematics, AMS, 1998.
Ronen Eldan and Ohad Shamir. The power of depth for feedforward neural networks. In Conference on Learning Theory, pp. 907–940, 2016.
Chrisantha Fernando, Dylan Banarse, Charles Blundell, Yori Zwols, David Ha, Andrei A. Rusu, Alexander Pritzel, and Daan Wierstra. Pathnet: Evolution channels gradient descent in super neural networks. CoRR, abs/1701.08734, 2017. URL http://arxiv.org/abs/1701.08734.
Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Deep Learning. MIT Press, 2016. http: //www.deeplearningbook.org.
William H Guss. Deep function machines: Generalized neural networks for topological layer expression. arXiv preprint arXiv:1612.04799, 2016.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. CoRR, abs/1512.03385, 2015. URL http://arxiv.org/abs/1512.03385.
Geoffrey Hinton, Li Deng, Dong Yu, George E Dahl, Abdel-rahman Mohamed, Navdeep Jaitly, Andrew Senior, Vincent Vanhoucke, Patrick Nguyen, Tara N Sainath, et al. Deep neural networks for acoustic modeling in speech recognition: The shared views of four research groups. IEEE Signal Processing Magazine, 29(6):82–97, 2012.
Yasuyuki Kato, Daisuke Yamamoto, and Ippei Danshita. Quantum tricriticality at the superfluidinsulator transition of binary bose mixtures. Phys. Rev. Lett., 112:055301, Feb 2014. doi: 10.1103/PhysRevLett.112.055301. URL https://link.aps.org/doi/10.1103/ PhysRevLett.112.055301.
Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton. Imagenet classification with deep convolutional neural networks. In Advances in neural information processing systems, pp. 1097–1105, 2012.
David JC MacKay. Information theory, inference and learning algorithms. Cambridge university press, 2003.
Paul Michel, Abhilasha Ravichander, and Shruti Rijhwani. Does the geometry of word embeddings help document classification? a case study on persistent homology based representations. arXiv preprint arXiv:1705.10900, 2017.
Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Alex Graves, Ioannis Antonoglou, Daan Wierstra, and Martin Riedmiller. Playing atari with deep reinforcement learning. arXiv preprint arXiv:1312.5602, 2013.
Razvan Pascanu, Guido Montufar, and Yoshua Bengio. On the number of response regions of deep feed forward networks with piece-wise linear activations. arXiv preprint arXiv:1312.6098, 2013.
Ben Poole, Subhaneil Lahiri, Maithreyi Raghu, Jascha Sohl-Dickstein, and Surya Ganguli. Exponential expressivity in deep neural networks through transient chaos. In Advances In Neural Information Processing Systems, pp. 3360–3368, 2016.
Maithra Raghu, Ben Poole, Jon Kleinberg, Surya Ganguli, and Jascha Sohl-Dickstein. On the expressive power of deep neural networks. arXiv preprint arXiv:1606.05336, 2016.
Lawrence K Saul and Sam T Roweis. An introduction to locally linear embedding. unpublished. Available at: http://www. cs. toronto. edu/˜ roweis/lle/publications. html, 2000.
Shreyas Saxena and Jakob Verbeek. Convolutional neural fabrics. CoRR, abs/1606.02492, 2016. URL http://arxiv.org/abs/1606.02492.
Karen Simonyan and Andrew Zisserman. Very deep convolutional networks for large-scale image recognition. CoRR, abs/1409.1556, 2014. URL http://arxiv.org/abs/1409.1556.
Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott E. Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, and Andrew Rabinovich. Going deeper with convolutions. CoRR, abs/1409.4842, 2014. URL http://arxiv.org/abs/1409.4842.
Chad M Topaz, Lori Ziegelmeier, and Tom Halverson. Topological data analysis of biological aggregation models. PloS one, 10(5):e0126383, 2015.
Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144, 2016.
Yu Wu, Gabriel Shindnes, Vaibhav Karve, Derrek Yager, Daniel B Work, Arnab Chakraborty, and Richard B Sowers. Congestion barcodes: Exploring the topology of urban congestion using persistent homology. arXiv preprint arXiv:1707.08557, 2017.
Kelin Xia and Guo-Wei Wei. Persistent homology analysis of protein structure, flexibility, and folding. International journal for numerical methods in biomedical engineering, 30(8):814–844, 2014.
Afra Zomorodian and Gunnar Carlsson. Computing persistent homology. Discrete & Computational Geometry, 33(2):249–274, 2005.
Barret Zoph and Quoc V. Le. Neural architecture search with reinforcement learning. 2017. URL https://arxiv.org/abs/1611.01578.
# A PROOFS, CONJECTURES, AND FORMAL DEFINITIONS
# A.1 HOMOLOGY
Homology is naturally described using the language of category theory. Let $T o p ^ { 2 }$ denote the category of topological spaces and $A b$ the category of abelian groups.
Definition A.1 (Homology Theory, Bredon (2013)). A homology theory on the on $T o p ^ { 2 }$ is a function $H : T o p ^ { 2 } A b$ assigning to each pair $( X , A )$ of spaces a graded (abelian) group $\{ H _ { p } ( X , A ) \}$ , and to each map $f : ( X , A ) \to ( Y , B )$ , homomorphisms $f _ { * } : H _ { p } ( X , A ) \to H _ { p } ( Y , B )$ , together with a natural transformation of functors $\partial _ { * } : H _ { p } ( X , A ) \to H _ { p - 1 } ( X , A )$ , called the connecting homomorphism (where we use $H _ { * } ( A )$ to denote $H _ { * } ( A , \varnothing )$ ) such that the following five axioms are satisfied.
1. If $f \simeq g : ( X , A ) ( Y , B )$ then $f _ { * } = g _ { * } : H _ { * } ( X , A ) \to H _ { * } ( Y , B ) .$
2. For the inclusions $i : A \to X$ and $j : X \to ( X , A )$ the sequence sequence of inclusions and connecting homomorphisms are exact.
3. Given the pair $( X , A )$ and an open set $U \subset X$ such that $c l ( U ) \subset i n t ( A )$ then the inclusion $k : ( X - U , A - U ) \to ( X , A )$ induces an isomorphism $k _ { * } : H _ { * } ( X - U , A - U ) \to$ $H _ { * } ( X , A )$
4. For a one point space $P , H _ { i } ( P ) = 0$ for all $i \neq 0$ .
5. For a topological sum $X = + _ { \alpha } X _ { \alpha }$ the homomorphism
$$\bigoplus ( i _ { \alpha } ) _ { * } : \bigoplus H _ { n } ( X _ { \alpha } ) \to H _ { n } ( X )$$
is an isomorphism, where $i _ { \alpha } : X _ { \alpha } \to X$ is the inclusion.
For related definitions and requisite notions we refer the reader to Bredon (2013).
# A.2 PROOF OF THEOREM 3.1
Theorem A.2. Let $X$ be a topological space and $X ^ { + }$ be some open subspace. If ${ \mathcal { F } } \subset 2 ^ { X }$ such that $f \in { \mathcal { F } }$ implies $H _ { S } ( f ) \neq H ( \bar { X } ^ { + } )$ , then for all $f \in { \mathcal { F } }$ there exists $A \subset X$ so that $f ( A \cap X ^ { + } ) = \{ 0 \}$ and $f ( A \cap ( X \setminus X ^ { + } ) ) = \{ 1 \}$ .
Proof. Suppose the for the sake of contraiction that for all $f \in { \mathcal { F } }$ , $H _ { S } ( f ) \ne H ( X ^ { + } )$ and yet there exists an $f$ such that for all $A \subset X$ , there exists an $x \in A$ such that $f ( x ) = 1$ . Then take $\mathcal { A } = \{ x \} _ { x \in X }$ , and note that $f$ maps each singleton into its proper partition on $X$ . We have that for any open subset of $V \subset X ^ { + }$ , $f ( \bar { V } ) = \{ 1 \}$ , and for any closed subset $W \subset X \setminus X ^ { + }$ , $f ( W ) = \{ 0 \}$ . Therefore X+ = SA∈τX+∩X $X ^ { + } = \textstyle \bigcup _ { A \in \tau _ { X ^ { + } \cap X } } A \subset s u p p ( f )$ as the subspace topology $\tau _ { X ^ { + } \cap X } = \tau _ { X ^ { + } } \cap \tau _ { X }$ where $\tau _ { X ^ { + } } = \{ A \in \tau _ { X } | A \subset { \dot { X } } ^ { + } \}$ and $\tau _ { X }$ denotes the topology of $X$ . Likewise, $i n t ( X ^ { - } ) \subset X \backslash s u p p ( F )$ under the same logic. Therefore $s u p p ( f )$ has the exact same topology as $X ^ { + }$ and so by Theorem 2.2 $H ( X ^ { + } ) = H ( s u \bar { p } p ( f ) )$ but this is a contradiction. This completes the proof. □
# A.3 THE NEURAL HOMOLOGY PRINCIPLE
Conjecture A.3. If $N$ is some neural network with $\ell$ layers and $h$ hidden units, and $H _ { S } ( N ) \neq$ $H ( X ^ { + } )$ then $\mathbb { E } [ L ( \mathrm { \bar { N } } , \mathcal { D } ) ] > c$ for some fixed $c ( \ell , h ) > 0$ .
 Figure 8: Topological phase transitions for datasets with $\beta ( \mathcal { D } ) \in \{ ( 2 , 0 ) , ( 2 , 1 ) , ( 3 , 0 ) , ( 3 , 1 ) \}$
 Figure 9: Topological phase transitions for datasets with $\beta ( \mathcal { D } ) \in \{ ( 3 , 2 ) , ( 4 , 0 ) , ( 4 , 1 ) , ( 4 , 2 ) \}$
 Figure 10: Topological phase transitions for datasets with $\beta ( \mathcal { D } ) \in \{ ( 4 , 3 ) , ( 5 , 0 ) \}$
# C EXAMPLE TOPOLOGICAL STRATIFICATIONS
 Figure 11: Topological stratification for $\{ h _ { 3 } , . . . , h _ { 1 5 } \}$ on a random dataset $\mathcal { D }$ with $\beta _ { 0 } ( \mathcal { D } ) = 2 5$ , $\beta _ { 1 } ( \mathcal { D } ) = 1 6$ .
 Figure 12: Topological stratification for $\{ h _ { 1 } , \ldots , h _ { 5 } \}$ on a random dataset $\mathcal { D }$ with $\beta _ { 0 } ( \mathcal { D } ) = 3$ , $\beta _ { 1 } \mathsf { \bar { ( } } D ) = 0$ .
 Figure 13: Topological stratification for $\{ h _ { 3 } , \ldots , h _ { 7 } \}$ on a random dataset $\mathcal { D }$ with $\beta _ { 0 } ( \mathcal { D } ) = 3$ , $\beta _ { 1 } ( \mathcal { D } ) = 0$ .
D ADDITIONAL TOPOLOGY OF REAL DATA
 Figure 14: The persistence diagrams of other data.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268# AMPNET: ASYNCHRONOUS MODEL-PARALLEL TRAINING FOR DYNAMIC NEURAL NETWORKS
Anonymous authors Paper under double-blind review
# ABSTRACT
New types of compute hardware in development and entering the market hold the promise of revolutionizing deep learning in a manner as profound as GPUs. However, existing software frameworks and training algorithms for deep learning have yet to evolve to fully leverage the capability of the new wave of silicon. In particular, models that exploit structured input via complex and instance-dependent control flow are difficult to accelerate using existing algorithms and hardware that typically rely on minibatching. We present an asynchronous model-parallel (AMP) training algorithm that is specifically motivated by training on networks of interconnected devices. Through an implementation on multi-core CPUs, we show that AMP training converges to the same accuracy as conventional synchronous training algorithms in a similar number of epochs, but utilizes the available hardware more efficiently, even for small minibatch sizes, resulting in shorter overall training times. Our framework opens the door for scaling up a new class of deep learning models that cannot be efficiently trained today.
# 1 INTRODUCTION
An emerging category of neural networks show the common trait of reacting in dynamic and unique ways to properties of their input. Networks like tree-structured recursive neural networks (Socher et al., 2013; Tai et al., 2015) and graph neural networks (GNNs) (Scarselli et al., 2009; Li et al., 2015; Gilmer et al., 2017) take structured data types as input and and execute a computation that depends on the input structure. This defies the moden GPU-driven paradigm of minibatch-based processing, and we refer to this new class of models with dynamic control flow as dynamic neural networks.
The development of dynamic neural network frameworks – Chainer (Tokui et al., 2015), DyNet (Neubig et al., 2017a), and PyTorch (PyTorch core team) – speaks to the importance of this class of models and highlights the challenge of how to make it easy for users to describe them. Yet there is another big challenge: how can we train these models efficiently?
Managing minibatches to keep GPUs fully utilized is typically considered a user’s responsibility in these dynamic frameworks (with the exception of DyNet’s autobatching feature; see Sec. 7). This means that users have to think about how to change their data feeding pipeline or even the model itself to run efficiently on GPUs, rather spending time innovating to improve the model accuracy.
What if we had a hypothetical device with low memory overhead that allows perfect scaling without batching; i.e., processing 1 item is simply $1 0 0 \mathrm { x }$ faster than processing 100 items? Recent work on FPGAs and other specialized hardware (Farabet et al., 2011; Caulfield et al., 2016; Jouppi et al., 2017) for deep learning encourages us to investigate this question. Our premises are
1. No batching is required for efficient processing. 2. Each device may not have enough memory to hold the entire model (this is a realistic constraint for current memory systems that approach the perfect scaling we require)
Based on these premises, we propose an asynchronous model-parallel (AMP) training algorithm. Our idea is illustrated in Figure 1. We need model parallelism because each device may be too small to hold the entire model (premise 2). However, if we perform synchronous parameter updates following the full forward and backward propagations, the only way to increase device utilization is by pipelining multiple instances into the system (see e.g., Chen et al., 2012). Pipeline parallelism with synchronous updates is at odds with convergence speed due to a decreased parameter update frequency; compare Fig. 1 (a) and (b).
 Figure 1: Gantt charts comparing pipelined synchronous model parallelism and asynchronous model parallelism. Orange, blue, and yellow boxes correspond to forward, backward, and parameter update operations, respectively. The numbers in the boxes indicate instance IDs.
To overcome this problem, we propose asynchronous parameter updates that occur without global synchronization whenever a pre-specified number of gradients have been accumulated; see Fig. 1 (c). With this design we aim for both high device utilization and update frequency.
In this setting, however, model parameters may be updated between the forward and the backward computation of an instance, introducing gradient “staleness”. Despite staleness, we show that AMP training can converge fast with good hardware utilization. Specifically, our contributions are:
• We present the asynchronous model parallel training algorithm for efficient distributed training of dynamic networks. We present an intermediate representation (IR) with explicit constructs for branching and joining control flow that supports AMP training. Unlike previous work that considers static computation graphs for static control flow (e.g., Caffe), and dynamic computation graphs for dynamic control flow (e.g., Chainer), our IR encodes a static computation graph to execute dynamic control flow1. This makes training easy to distribute and parallelize. We show that our IR can readily encode replicas, a form of data parallelism (see Sec. 5). In addition, our IR includes operators for data aggregation, which recover a form of batching, enabling our methods to be applied even on hardware where batching is beneficial. • We implement AMP training on a multi-core CPU and empirically demonstrate that AMP training converges to similar accuracies as synchronous algorithms on a variety of dynamic neural network models including Tree RNN and gated graph neural networks (GGNN).
In summary, our work demonstrates the benefits of AMP training and gives a novel way to design and deploy neural network libraries with dynamic control flow. In addition, we use our implementation to estimate the performance on a hypothetical device satisfying premises 1 & 2, with 1TFLOPS compute capability (see Appendix C). Together, these contributions open up new ways to scale up dynamic networks on interconnected compute devices.
# 2 NEURAL NETWORKS WITH DYNAMIC CONTROL FLOW
Below we highlight three models with dynamic control flow that will be studied in depth in this paper:
Variable-length RNNs iterate over the tokens of variable-length sequences. Pseudo-code for a simple vanilla RNN is given in Figure 2. The linear (fully connected) layer and rectified linear unit (ReLU) can be substituted with a more sophisticated unit such as a gated recurrent unit (Chung et al., 2014). Though each instance has a different length, it is possible to add padding to enable batching. However this may lead to significant redundant compute due to variability in sequence lengths.
 Figure 2: Variable-length RNN in IR and pseudocode (colors denote IR node types)
<table><tr><td>Algorithm 1 Asynchronous Model-Parallel training</td></tr><tr><td>while training not done do</td></tr><tr><td>for all workers in parallel do</td></tr><tr><td>Wait until a message arrives</td></tr><tr><td>msg ←the highest priority message from the input queue</td></tr><tr><td>op ← sink node of the message msg</td></tr><tr><td>if msg is forward type then Compute forward: out_msgs ← op(msg)</td></tr><tr><td>Enqueue the resulting message(s) into the queue(s) of the workers hosting the child nodes.</td></tr><tr><td>else if msg is backward type then</td></tr><tr><td>Compute backward: out_msgs ← op*(msg,fwd_msg)</td></tr><tr><td>Enqueue the resulting message(s) into the queue(s) of the workers hosting the parent nodes.</td></tr><tr><td>else if msg isupdate type then</td></tr><tr><td>Perform parameter updates on op</td></tr><tr><td>end if</td></tr><tr><td>end for</td></tr><tr><td>end while</td></tr></table>
Tree-structured neural networks are powerful models used for parsing of natural language and images, semantic representation, and sentiment analysis (Socher et al., 2011; Bowman et al., 2016; Socher et al., 2013; Tai et al., 2015). They require evaluation of (potentially multiple) trees with shared parameters but different topology for each instance. Each tree structure is instance-specific and batching requires nontrivial planning (Looks et al., 2017). A simple form of tree neural network performs a bottom up traversal of the instance, starting from an embedding of the leaves. At each level the values from the child nodes are concatenated and sent through a specialized unit (e.g. LSTM). The result is then propagated further up the tree. Backpropagation over the tree structure is known as backpropagation through structure (Goller and Kuchler, 1996).
Graph neural networks (Scarselli et al., 2009; Li et al., 2015; Gilmer et al., 2017) combine both the temporal recurrence and recurrence over the structure. GNNs can be seen as performing aggregation/distribution operations over a general graph structure with shared parameters.
Apart from the models above, there exist many recently proposed models with flexible control flow (e.g. hierarchical memory networks (Chandar et al., 2016), neural programmer interpreters (Reed and De Freitas, 2015), adaptive computation networks (Graves, 2016; Figurnov et al., 2016), and sparsely-gated mixture of experts (Shazeer et al., 2017), to which our framework can be applied.
# 3 ASYNCHRONOUS MODEL-PARALLEL TRAINING
In AMP training, each node of a computation graph (including control flow nodes – see next section) is associated with a worker, which is an abstraction of a compute device. Neural network training and inference is carried out by message passing among workers following algorithm 1. All workers run in parallel without synchronization. Each message contains a payload (float or int tensor), as well as a state that includes the IDs of the source and sink nodes and a label indicating the type of message (forward, backward, or update). The state is used to keep track of algorithm and control flow information. For example, in a variable-length RNN the state also contains the instance identifier, the current position in the sequence, and the total sequence length for the instance. More generally, if the neural model use (possibly nested) loops, then the state for the messages that arrive to and are produced from nodes that logically belong in loop bodies will contain sets of loop counters that together with the instance id uniquely identify the messages throughout the course of the computation.
When a worker receives a message labeled as forward (or backward) then it performs the operation of the node indicated by the sink node ID on the supplied payload. This produces one or more outgoing messages that are then enqueued into the queues of the workers hosting the next sink nodes in the computation graph. The final loss layer initiates backward propagation. If the message type is update, the worker will carry out weight updates on the sink node using gradients accumulated in the appropriate slot in the worker’s local memory. Since both the operation weights and weight gradients can be stored locally on the worker then workers only need to communicate activations and activation gradients, which are typically an order of magnitude smaller than the weights. The update message is typically sent from the sink node to itself as part of the backward process but it can also be sent from a controller node to simulate synchronous pipelined training.
There are two important details that are not fully spelled out in Algorithm 1. First, since the messages arrive asynchronously (and possibly out of order), any operation that has more than one parent nodes need to store the payload into its local cache until all the parents send the corresponding payloads. Thus output message(s) can only be produced when all the payloads become available. The cache needs to be able to distinguish payloads received from different parents and payloads with different instance ID, and different counters (all encoded in the message states). The same is true in the backward pass for a node with multiple child nodes. Second, ${ \tt o p } ^ { * }$ denotes the adjoint operation of op and takes the backward message msg and potentially the forward message fwd msg stored in the cache. For a nonlinear activation node (e.g., ReLU), the node will not change the state of the message in the forward pass. Thus in the backward pass, the adjoint operation will just multiply the partial derivative of the activation function to the payload of the received backward message keeping the state unchanged. By contrast, an operation that only changes the state of the message in the forward pass (e.g., increment the loop counter) will reverse the change in the backward pass leaving the payload unchanged.
In the experiments we vary two hyper parameters to control the effect of asynchrony:
min update interval: determines the minimum number of gradients that a parameterized operation needs to accumulate before it can update its parameters (using the update message). The staleness of a gradient can be measured by the number of updates between the forward and backward computation that produces the gradient. Small min update interval may increase gradient staleness. On the other hand, large min update interval can reduce the variance of the gradient but can result in very infrequent updates and also slow down convergence.
max active keys: controls the maximum number of active instances that are in-flight at any point in time. By setting max active key $\mathbf { \boldsymbol { s } } = 1$ we restrict to single-instance processing, typically equivalent to synchronous training. More in-flight messages generally increase hardware utilization, but may also increase gradient staleness. Section 6 demonstrates the effects of these parameters in a multi-core CPU runtime.
# 3.1 WORKER AFFINITY
In our asynchronous execution model, the optimal assignment of $N$ neural network computation graph nodes to $W$ workers (referred to as affinitization) is in general a non-trivial scheduling problem. We investigated several heuristics for assigning affinities (for example $\mathbf { k }$ -hop coloring (Ichrak et al., 2012) to ensure subsequent heavy operations were assigned different workers). However, we find that the following procedure achieves high performance in practice in our multi-core CPU implementation, and is adopted throughout our experiments for simplicity. We first partition the nodes into $H$ ’heavy’ operations (namely matrix multiplies) and $( N - H )$ ’light’ operations, and then balance the heavy nodes across the workers by affinitizing the $h ^ { \mathrm { t h } }$ with the $( h \mod W ) ^ { \mathrm { t h } }$ worker. Finally, the light operations are affinitized randomly among the rest of the workers. Note that in scenarios where communication is over a physical network affinitization will become more critical for high performance.
 Figure 3: Distribution based on dynamic information
# 4 A STATIC INTERMEDIATE REPRESENTATION FOR DYNAMIC CONTROL FLOW
Overview Computation graphs are expressed using a static intermediate representation (IR) that can be a compilation target for high-level libraries (e.g. TensorFlow or our own Python and $\mathrm { C } { + + }$ frontends), and can itself admit multiple backends (e.g. the multi-core CPU runtime in this paper, or a network of accelerators). Static means that the IR graph is instance-independent. Nevertheless, it can execute dynamic and instance-dependent control flow decisions, in a forward and backward manner, by storing instance- and iteration-dependent information as the computation evolves. Each IR node comes with a forward and a backward semantics. A model is specified by (i) an IR graph, and (ii) a specialized controller loop that pumps instances and other data (e.g. initial hidden states or labels), and is responsible for throttling asynchrony. In the rest of this section we discuss the most important IR nodes along with their operational semantics, and show how they are used in the example models.
Payload transformations Parameterized payload transform (PPT) nodes can be used to encode, for instance, fully connected layers. They apply a transform in the forward pass, but also record the activation in order to use it to compute gradients in the backward pass. An activation is recorded by keying on the state of the message, allowing thus to process forward and backwards messages completely asynchronously, and – in the extreme case – out of order. A PPT node requires specification of the forward and the backward transformation. It may decide to independently apply accumulated gradients to update its parameters. For transformations that do not involve parameters (e.g. ReLUs) our IR offers a simpler non-parameterized payload transform.
Loops, state, and control flow A condition node (Cond $f$ ) is parameterized by a function $f$ that queries the state (but not the payload) of the incoming message and, based on the response, routes the input to one of the successor nodes. A join node (Phi) propagates the messages it receives from each of its ancestor nodes but records the origin (using the state of the message as the key) so that in the backward pass it can backpropagate them to the correct origin. An invertible state update node $( \mathtt { I s u } \ f \ f ^ { - 1 } )$ is parameterized by two functions $f$ and $f ^ { - 1 }$ that operate on the state of a message, and satisfy $\bar { f } ^ { - 1 } ( f ( \bar { x } ) ) = x$ . Typically these are loop counter update functions.
Figure 2 shows how to encode an RNN. The loop at the heart of the RNN is implemented with Cond, Phi and Isu nodes. The controller pumps sequences in a lookup table (just another PPT layer), and our Ungroup node (to be described in the next section) generates a stream of tensors each corresponding to a single token, tagged with the current time-step (loop counter). For each forward message, the Isu node increments the time-step, and the conditional node tests whether the end of the sequence has been reached. Depending on the answer it either propagates the hidden state back to Phi, or pushes the hidden state to the final linear and loss layers. In backward mode, messages pass through the Isu (which decrements the time-step), and reach the Phi node. The Phi node will (based on information from the forward phase) either back-propagate to the Cond node, or to the controller to terminate. Hence the loop is executed in both the forward and backward direction.
 Figure 4: IR graphs for (a) Gated Graph Neural Network and (b) RNN-with-replicas. The RNNCell in (a) denotes a recurrent structure (e.g. GRU, LSTM), the details of which we omit. Cond modId in (b) implements a round-robin branching to different replicas by computing (instance ID mod 3).
Aggregation and disaggregation Our IR offers several constructs for aggregation and disagreggation; for example RNN requires us to concatenate (Concat) hidden states and embeddings with matching timesteps and instance ids (states). We offer a construct for broadcasting (Bcast) a message to multiple successors. We offer an ungrouping construct (Ungroup) that ungroups a matrix and emits all resulting messages tagged with an extra user-provided increasing loop counter. This allows us to insert the stream of token embeddings in the middle of the RNN loop in Figure 2. In backward mode Ungroup groups back all the incoming gradients. A simpler variant of Ungroup is Replicate, which replicates a message with an extra loop counter in the state. In backwards mode Replicate sums up all incoming gradients that correspond to the state without the extra loop counter.
Figure 4(a) describes a GNN that combines aggregation on the structure of a graph instance with an outer loop. The controller pumps data that contain the feature embeddings of all nodes of an input graph. In addition it pumps in a map specifiying graph topology. The Distribute node uses that information along with the graph itself to create sub-matrices (here each corresponding to edge types) and pass them through linear (fully connected) layers. The Collect node collects and re-groups the results based on graph topology. These nodes correspond to a form of dynamic partition and merging. Schematically the Distribute behaviour is given in Figure 3. In backward mode, based on the control information received during the forward pass (gray line) re-groups the gradients and sums together those that correspond to the same index. The Collect operator is essentially symmetric.
# 5 DATA PARALLELISM IN MODEL PARALLELISM
Pipelined model parallelism can often be augmented with forms of data parallelism. Consider the RNN in Fig. 2. The only heavy operation (Linear-1) in the body of the loop will act as a bottleneck for computation. One solution is to split the linear layer into smaller tiles and compute them in parallel. This is expressible in our IR but the linear operation needs to be large enough to benefit from tiling in this way. Another approach is to replicate the linear layer in full. This requires only minimal new machinery – we can replicate the linear layer and place the replicas inside Cond and Phi nodes as in Figure 4(b). Different instances or messages from the same instance but with different position in the sequence can be processed in an (pipeline-)parallel fashion by being sent to one of the replicas chosen by a random or deterministic function of the message state. To enable parameters to be shared among the replicas, we use infrequent end-of-epoch replica synchronization (averaging) that incurs negligible communication cost. We also tried more elaborate message-passing protocols for group synchronization, but found that infrequent global synchronization was sufficient for fast convergence.
# 6 EXPERIMENTS
We evaluate AMPNet using the dynamic models introduced in Section 2. For completeness, we additionally consider a multi-layer perceptron (MLP) as an example of a static, batched network
that AMPNet is not specifically designed to tackle. Brief details of the models and data sets in the experiments are presented below, and further details are given in Appendix B.
<table><tr><td>Model</td><td>Data set</td><td>Difficulty</td><td>Experiment purpose</td></tr><tr><td>MLP</td><td>MNIST</td><td>toy</td><td>The standard deep learning bench- mark (for which AMPNet is not</td></tr><tr><td>RNN</td><td>List reduction</td><td>toy</td><td>specifically designed) The simplest architecture with dy-</td></tr><tr><td>Tree-LSTM</td><td>Stanford Sentiment Treebankreal-world</td><td></td><td>namic control flow (a for loop) The TensorFlow Fold benchmark for</td></tr><tr><td>GNN</td><td>QM9</td><td>real-world</td><td>backpropagation through structure Complex control flow with loops over time and structure</td></tr></table>
Results Our asynchronous runtime is motivated by the promise of emerging hardware (e.g. FPGA accelerators) that fulfill the premises in section 1 and are well suited to dynamic neural network execution. Here we are primarily interested in how the performance of our runtime improves as we increase the degree of asynchrony (by varying max active keys) while keeping other factors fixed. The aim is to answer the question of whether AMP training is a promising direction for novel distributed hardware that deviates from the CPU/GPU batching paradigm. To answer this question using resources available today we run the AMPNet training using a multi-core CPU runtime where each worker is a hardware thread (see Appendix A). Additionally we forecast the performance on a hypothetical 1TFLOPS device satisfying our premises by replacing all computation nodes by configurable sleep nodes. This allows us to estimate the performance on a new hardware keeping the control flow decisions dynamic. See Appendix C.
It is also interesting to compare how the raw CPU performance of the AMP runtime compares with existing frameworks (TensorFlow, TensorFlow Fold and DyNet) to see that our implementation is already competitive with state of the art methods even on CPUs that do not conform to our target hardware model. We provide additional analysis for each experiment below.
On MNIST, Table 1 shows $_ { 3 \mathrm { X } }$ speedup from synchrony (max active keys $: = 1$ ) to asynchrony (max active key $s = 4$ ) in terms of throughput. This is almost ideal as the first three linear layers are the heaviest operations. The number of epochs to reach the target validation accuracy increases from 3 to 4 but the overall speedup in terms of the wall clock time is $2 . 2 \mathbf { x }$ . We have also compared AMP training against pipeline parallel training (Fig. 1 (b)). Figure 5(a) shows that while AMP training achieves 3x throughput gain already with $\mathtt { m a x \mathrm { _ { - } a c t i v e \mathrm { _ { - } k e y s = 4 } } }$ , pipeline parallelism can only achieve $2 \mathbf { x }$ (in fact from Fig. 1 (b), $3 m / ( m + 2 )$ is the best case for max active key $s = m$ )
Table 1: Time to convergence to target validation accuracy. The time to convergence can be broken down into number of epochs and the throughput (instances/s). The target accuracy is shown inside parentheses next to each dataset. mak is a short-hand for max active keys defined in Sec. 3; $\mathrm { m a k } = 1$ corresponds to synchronous training for MNIST and minimal asynchrony arising from just one in-flight instance for other models with recursive structures.
<table><tr><td rowspan="2"></td><td colspan="4">AMP</td><td colspan="3">TensorFlow</td></tr><tr><td>mak</td><td>time (s)</td><td>epochs</td><td>inst/s</td><td>time (s)</td><td>epochs</td><td>inst/s</td></tr><tr><td rowspan="2">MNIST (97%)</td><td>1</td><td>91.1</td><td>3</td><td>2076</td><td>34.5</td><td>3</td><td>5880</td></tr><tr><td>4</td><td>40.4 (2.2x)</td><td>4</td><td>6268</td><td></td><td></td><td></td></tr><tr><td rowspan="3">List reduction (97%)</td><td>1</td><td>78</td><td>10</td><td>13k</td><td>46</td><td>7</td><td>18k</td></tr><tr><td>4</td><td>66 (1.2x)</td><td>10.5</td><td>16k</td><td></td><td></td><td></td></tr><tr><td>16</td><td>60 (1.3x)</td><td>9.5</td><td>16k</td><td></td><td></td><td></td></tr><tr><td>(2 replicas)</td><td>4</td><td>38(2x)</td><td>12</td><td>35k</td><td></td><td></td><td></td></tr><tr><td>(4 replicas)</td><td>8</td><td>21 (3.8x)</td><td>13</td><td>71k</td><td></td><td></td><td></td></tr><tr><td rowspan="3">Sentiment (82%)</td><td>1</td><td>185</td><td>2</td><td>102</td><td>208</td><td>5</td><td>265</td></tr><tr><td>8</td><td>82 (2.3x)</td><td>2</td><td>222</td><td></td><td></td><td></td></tr><tr><td>16</td><td>104 (1.8x)</td><td>3</td><td>258</td><td></td><td></td><td></td></tr><tr><td rowspan="2">QM9 (4.6)</td><td>4</td><td>N/A</td><td>N/A</td><td>988</td><td>6696</td><td>66</td><td>1217</td></tr><tr><td>16</td><td>5227</td><td>76.5</td><td>1797</td><td></td><td></td><td></td></tr></table>
 (a) Comparison against pipeline parallelism (Fig. 1 (b)) (b) Performance of an 8-replica RNN model on the list reducfor 4-layer MLP on MNIST. tion dataset as a function of asynchrony hyperparameters. Figure 5: Throughput-convergence trade-off as a function of mode of parallelism and asynchrony hyper-parameters. Solid gray lines show constant convergence time trajectories; mak and mui stand for max active keys and min update interval, respectively.
and higher throughput at max active keys $= 8$ is achieved at the cost of the sharp increase in the number of epochs to convergence.
The list reduction dataset demonstrates the power of replicas. As there is only one heavy operation (Linear-1, Figure 2), the speedup from asynchrony is mild (1.3x). However we get $2 . 5 \mathrm { x }$ and $3 . 5 \mathrm { x }$ speedup for 2 and 4 replicas, respectively, which is nearly ideal. Again, the # of epochs to convergence is not affected by increasing max active keys. The slowdown in convergence for 4 replicas is due to the increased effective minibatch size – also commonly observed in data parallel training.
Next the sentiment tree-RNN dataset shows that our runtime is competitive without batching to TensorFlow Fold (Looks et al., 2017) using dynamic batching of batch size 100. It is worth mentioning that our runtime allows us to specify different min update interval parameter for each parameterized operation. We set this parameter to 1000 for the embedding layer, which is initialized by Glove vectors, and 50 for all other layers. This reduced gradient staleness in the embedding layer.
The QM9 dataset demonstrates that increasing asynchrony helps on real-world tasks with complex control flow, and our method outperforms an efficient TensorFlow implementation on CPUs.
Finally, we have implemented the BiLSTM w/ char model in Neubig et al. (2017b) on Wikiner dataset Nothman et al. (2013). Our preliminary implementation without any batching achieves 130 sentences/s at max active keys $= 3 2$ without any noticeable loss in accuracy (around $94 \%$ after one epoch). This is competitive with DyNet’s performance on the same machine (23 sentences/s without and 220 with autobatching, respectively); See Sec. B.5 for details.
Asynchrony Finally we provide additional analysis on the effect of asynchrony. The degree of asynchrony is controlled by hyperparameters min update interval and max active keys. In Fig. 5(b) we use an 8-replica RNN model on the list reduction dataset to investigate how these parameters affect the data and time required to converge to $96 \%$ validation accuracy. We find, in analogy with minibatch size in traditional systems, that min update interval must neither be too large nor too small. Increasing max active keys (increasing asynchrony) monotonically increases performance when the number of keys is similar to the number of individually affinitized heavy operations in the model 8 in this case). Increasing max active keys significantly beyond this point produces diminishing returns.
# 7 RELATED WORK
One approach to the task of training networks with instance dependent control flow is to define the computation graph dynamically per-instance. This approach is taken in Chainer (Tokui et al.,
2015), DyNet (Neubig et al., 2017a), and PyTorch (PyTorch core team). There are key challenges in accelerating this approach: Model parallelism would require the dynamically generated computation graph to be scheduled on-the-fly, and BLAS level parallelism would require operations to be batched on-the-fly. Automatic dynamic batching has been implemented in DyNet (Neubig et al., 2017a), and is an interesting alternative to our asynchronous execution. Similar methods are used in TensorFlow Fold (Looks et al., 2017). The basic idea is to inspect and merge together (by depth) the unrolled computation graphs of several instances to create batched BLAS operations. The effectiveness of automatic batching greatly depends on the model – for example, it would not perform well on random permutations of a sequence of operations. By contrast, our IR would very succinctly express and achieve pipeline parallelism using a static computation graph that is easy to distribute and optimize.
Theano (Al-Rfou et al., 2016) and TensorFlow (TF)(Abadi et al., 2016) can syntactically handle instance dependent control flow with abstractions for conditional execution (ifelse in Theano and cond in TF) and loops (scan and while loop, respectively); TF also provides higher-order functions, such as map, foldl, foldr, and scan. The main difference between AMPNet and the above frameworks is that AMPNet is streaming and asynchronous whereas Theano is non-streaming and synchronous. Although not designed for streaming, TF can support streaming programmatically as it exposes first-class queues, as well as data prefetching with so called input pipelines. In our IR, all the queuing is implicit and stream-based execution is the default. TF additionally does support static description of dynamic control flow and state update, but we depart from the classic dataflow architecture that TF follows (Arvind and Culler, 1986): First, instead of having nodes that represent mutable reference cells, we encapsulate the state with which a message should be processed through the graph in the message itself. Second, because we encapsulate algorithmic state in the messages, we do not introduce the notion of control dependencies (which can be used to impose a specific execution order on TF operations). Our choices complicate algorithmic state management from a programming point of view and make the task of designing a high-level compiler non-trivial, but allow every node to run asynchronously and independently without a scheduler and without the need for control messages: For example, nodes that dynamically take a control flow path or split the data simply consult the state of the incoming message, instead of having to accept additional control inputs. For “small” states (e.g. nested loop counters or edge and node ids) this might be preferable than out-of-band signaling. Our IR can implement loops by simply using state-update, conditional, and phi nodes, because the state accompanies the payload throughout its lifetime, whereas TF introduces specialized operators from timely dataflow (Murray et al., 2016) to achieve the same effect.
Asynchronous data parallel training (Recht et al., 2011; Dean et al., 2012; Chilimbi et al., 2014) is another popular approach to scale out optimization by removing synchronization (orthogonal to and combinable with model-parallel training). For example, convolutional layers are more amenable to data-parallel training than fully connected layers, because the weights are smaller than the activations. Moreover, when control flow differs per data instance, data parallelism is one way to get an effective minibatch size $> 1$ , which may improve convergence by reducing variance. The impact of staleness on convergence (Recht et al., 2011) and optimization dynamics (Mitliagkas et al., 2016) have been studied for data parallelism. It would be interesting to extend those results to our setting.
Jaderberg et al. (2016), like us, aim to to train different parts of a model in a decoupled or asynchronous manner. More precisely, their goal is to approximate a gradient with a synthetic gradient computed by a small neural network that is locally attached to each layer. Hence, the local gradient calculation becomes independent of other layers (except for the training of the gradient predictor network) and allows asynchronous parameter updates. This would be especially useful if the evaluation of the local network is cheaper than the computation of the real gradient; for example, if the computation of the real gradient required significant communication of forward/backward messages between devices.
# 8 CONCLUSION AND OUTLOOK
We have presented an asynchronous model-parallel SGD algorithm for distributed neural network training. We have described an IR and multi-core CPU runtime for models with irregular and/or instance-dependent control flow. Looking forward, we aim to deploy our system on specialized hardware. Equally importantly, we plan to build a compiler that automatically deduces the information to be placed in the states and generates state keying functions from a higher-level description of the models. By unlocking scalable distributed training of dynamic models, we hope to enable exploration of this class of models that are currently only on the horizon but may become more mainstream in the future.
REFERENCES M. Abadi, A. Agarwal, P. Barham, E. Brevdo, Z. Chen, C. Citro, G. S. Corrado, A. Davis, J. Dean, M. Devin, et al. TensorFlow: Large-scale machine learning on heterogeneous distributed systems. arXiv preprint arXiv:1603.04467, 2016. R. Al-Rfou, G. Alain, A. Almahairi, C. Angermueller, D. Bahdanau, N. Ballas, F. Bastien, J. Bayer, A. Belikov, et al. Theano: A python framework for fast computation of mathematical expressions. arXiv preprint arXiv:1605.02688, 2016. Arvind and D. E. Culler. Dataflow architectures. Annual Review of Computer Science, 1(1):225–253, 1986. URL http://csg.csail.mit.edu/pubs/memos/Memo-261-1/Memo-261-2.pdf. S. R. Bowman, J. Gauthier, A. Rastogi, R. Gupta, C. D. Manning, and C. Potts. A fast unified model for parsing and sentence understanding. arXiv preprint arXiv:1603.06021, 2016. A. M. Caulfield, E. S. Chung, A. Putnam, H. Angepat, J. Fowers, M. Haselman, S. Heil, M. Humphrey, P. Kaur, J.-Y. Kim, et al. A cloud-scale acceleration architecture. In Microarchitecture (MICRO), 2016 49th Annual IEEE/ACM International Symposium on, pages 1–13. IEEE, 2016. S. Chandar, S. Ahn, H. Larochelle, P. Vincent, G. Tesauro, and Y. Bengio. Hierarchical memory networks. arXiv preprint arXiv:1605.07427, 2016. X. Chen, A. Eversole, G. Li, D. Yu, and F. Seide. Pipelined back-propagation for context-dependent deep neural networks. In Interspeech, pages 26–29, 2012. T. M. Chilimbi, Y. Suzue, J. Apacible, and K. Kalyanaraman. Project Adam: Building an efficient and scalable deep learning training system. In OSDI, volume 14, pages 571–582, 2014. J. Chung, C. Gulcehre, K. Cho, and Y. Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. arXiv preprint arXiv:1412.3555, 2014. J. Dean, G. Corrado, R. Monga, K. Chen, M. Devin, M. Mao, A. Senior, P. Tucker, K. Yang, Q. V. Le, et al. Large scale distributed deep networks. In Advances in neural information processing systems, pages 1223–1231, 2012. C. Farabet, Y. LeCun, K. Kavukcuoglu, E. Culurciello, B. Martini, P. Akselrod, and S. Talay. Large-scale FPGA-based convolutional networks. Scaling up Machine Learning: Parallel and Distributed Approaches, pages 399–419, 2011. M. Figurnov, M. D. Collins, Y. Zhu, L. Zhang, J. Huang, D. Vetrov, and R. Salakhutdinov. Spatially adaptive computation time for residual networks. arXiv preprint arXiv:1612.02297, 2016. J. Gilmer, S. S. Schoenholz, P. F. Riley, O. Vinyals, and G. E. Dahl. Neural message passing for quantum chemistry. arXiv preprint arXiv:1704.01212, 2017. C. Goller and A. Kuchler. Learning task-dependent distributed representations by backpropagation through structure. In Neural Networks, 1996., IEEE International Conference on, volume 1, pages 347–352. IEEE, 1996. A. Graves. Adaptive computation time for recurrent neural networks. arXiv preprint arXiv:1603.08983, 2016. A. Ichrak, P. Minet, and C. Adjih. Node coloring in wireless networks: Complexity results and grid coloring. 09 2012. M. Jaderberg, W. M. Czarnecki, S. Osindero, O. Vinyals, A. Graves, and K. Kavukcuoglu. Decoupled neural interfaces using synthetic gradients. arXiv preprint arXiv:1608.05343, 2016. N. P. Jouppi, C. Young, N. Patil, D. Patterson, G. Agrawal, R. Bajwa, S. Bates, S. Bhatia, N. Boden, A. Borchers, et al. In-datacenter performance analysis of a tensor processing unit. arXiv preprint arXiv:1704.04760, 2017. D. P. Kingma and J. Ba. Adam: A method for stochastic optimization. CoRR, abs/1412.6980, 2014. URL http://arxiv.org/abs/1412.6980. Y. LeCun and C. Cortes. The MNIST database of handwritten digits, 1998. Y. Li, D. Tarlow, M. Brockschmidt, and R. Zemel. Gated graph sequence neural networks. arXiv preprint arXiv:1511.05493, 2015. M. Looks, M. Herreshoff, D. Hutchins, and P. Norvig. Deep learning with dynamic computation graphs. arXiv preprint arXiv:1702.02181, 2017. Sentiment Tree Bank example: https://github.com/ tensorflow/fold/blob/master/tensorflow_fold/g3doc/sentiment.ipynb. I. Mitliagkas, C. Zhang, S. Hadjis, and C. Re. Asynchrony begets momentum, with an application to deep ´ learning. arXiv preprint arXiv:1605.09774, 2016. D. G. Murray, F. McSherry, M. Isard, R. Isaacs, P. Barham, and M. Abadi. Incremental, iterative data processing with timely dataflow. Commun. ACM, 59(10):75–83, Sept. 2016. ISSN 0001-0782. G. Neubig, C. Dyer, Y. Goldberg, A. Matthews, W. Ammar, A. Anastasopoulos, M. Ballesteros, D. Chiang, D. Clothiaux, T. Cohn, et al. Dynet: The dynamic neural network toolkit. arXiv preprint arXiv:1701.03980, 2017a. G. Neubig, Y. Goldberg, and C. Dyer. On-the-fly operation batching in dynamic computation graphs. arXiv preprint arXiv:1705.07860, 2017b. J. Nothman, N. Ringland, W. Radford, T. Murphy, and J. R. Curran. Learning multilingual named entity recognition from wikipedia. Artificial Intelligence, 194:151–175, 2013. PyTorch core team. PyTorch. URL http://pytorch.org/. R. Ramakrishnan, P. O. Dral, M. Rupp, and O. A. von Lilienfeld. Quantum chemistry structures and properties of 134 kilo molecules. Scientific Data, 1, 2014. B. Recht, C. Re, S. Wright, and F. Niu. Hogwild: A lock-free approach to parallelizing stochastic gradient descent. In Advances in Neural Information Processing Systems, pages 693–701, 2011. S. Reed and N. De Freitas. Neural programmer-interpreters. arXiv preprint arXiv:1511.06279, 2015. L. Ruddigkeit, R. Van Deursen, L. C. Blum, and J.-L. Reymond. Enumeration of 166 billion organic small molecules in the chemical universe database gdb-17. Journal of chemical information and modeling, 52(11): 2864–2875, 2012. F. Scarselli, M. Gori, A. C. Tsoi, M. Hagenbuchner, and G. Monfardini. The graph neural network model. IEEE Transactions on Neural Networks, 20(1):61–80, 2009. S. Semeniuta, A. Severyn, and E. Barth. Recurrent dropout without memory loss. arXiv preprint arXiv:1603.05118, 2016. N. Shazeer, A. Mirhoseini, K. Maziarz, A. Davis, Q. Le, G. Hinton, and J. Dean. Outrageously large neural networks: The sparsely-gated mixture-of-experts layer. arXiv preprint arXiv:1701.06538, 2017. R. Socher, C. C. Lin, C. Manning, and A. Y. Ng. Parsing natural scenes and natural language with recursive neural networks. In Proceedings of the 28th international conference on machine learning (ICML-11), pages 129–136, 2011. R. Socher, A. Perelygin, J. Y. Wu, J. Chuang, C. D. Manning, A. Y. Ng, C. Potts, et al. Recursive deep models for semantic compositionality over a sentiment treebank. In Proceedings of the conference on empirical methods in natural language processing (EMNLP), volume 1631, page 1642, 2013. Dataset: https://nlp.stanford.edu/sentiment/treebank.html. K. S. Tai, R. Socher, and C. D. Manning. Improved semantic representations from tree-structured long short-term memory networks. arXiv preprint arXiv:1503.00075, 2015. S. Tokui, K. Oono, S. Hido, and J. Clayton. Chainer: a next-generation open source framework for deep learning. In Proceedings of workshop on machine learning systems (LearningSys) in the twenty-ninth annual conference on neural information processing systems (NIPS), 2015.
# A AMPNET RUNTIME IMPLEMENTATION
We have implemented an AMPNet runtime for multi-core CPUs. Our runtime spawns multiple workers each associated with a hardware thread and hosting one or more IR nodes – in a more general setting each worker corresponds to a compute device. To remain faithful to a distributed environment communication is only through message passing. Each worker is equipped with a multiple-producer single-consumer queue that can accept messages for any IR node hosted on that worker.
The main worker loop periodically offloads messages from the concurrent queue to a worker-local priority queue that assigns higher priority to backward messages. Backward prioritization is designed for situations when multiple IR nodes with a dependency on the IR graph end up hosted on the same worker. As a consequence, backpropagation can complete faster and new instances can be pumped in by the controller. We dequeue the top message and invoke the forward or backward method of the target IR node. These methods may update internal IR node state (such as cache the state of the incoming message and wait for more messages) or post new forward or backward messages.
How to update the parameters using the gradients is a configuration option that selects amongst a range of optimization algorithms. We have implemented runtime configuration options for selecting several well-known schemes such as (momentum-)SGD and Adam Kingma and Ba (2014), and for controlling the training hyper-parameters.
# B DETAILS OF THE EXPERIMENTAL RESULTS
We provide more details of the experiment and analysis in this section. All experiments were carried out on machines with 16 cores and 112 GB of RAM. The validation curves were averaged over at least 20 independent runs. The time/epoch to reach a target accuracy was calculated as median of the time an algorithm takes to reach the target accuracy over the repetitions. We found this approach to be more reliable than reporting the time/epoch when the averaged accuracy reaches the target. Table 2 shows both the training and validation throughputs we obtained with AMPNet and our TensorFlow baselines.
# B.1 MNIST
We train a 4-layer perceptron with ReLUs and 784-dimensional hidden units on MNIST (LeCun and Cortes, 1998). Both the AMP runtime and a TensorFlow baseline use SGD with learning rate 0.1 and batch size of 100.
Figure 6(a) shows the validation accuracy vs. time, validation accuracy vs. epochs, and throughputs of synchronous and asynchronous versions of AMPNet as well as TensorFlow. The throughput greatly increases from synchronous (max active key $\mathfrak { s } = 1$ ) to asynchronous (max active key $s = 4$ ) while the speed of convergence (middle panel) is hardly affected for mild amount of asynchrony. Taking higher max active keys $= 8$ increase throughput only very little (because there is no more work) and seems to rather make the convergence more unstable. This is due to the fact that our current scheduler is greedy and pumps in a forward message whenever the first layer is unoccupied, which leads to large gradient staleness. Clearly a better scheduling will remove this sensitivity.
# B.2 LIST REDUCTION DATASET
We train a vanilla RNN to perform reduction operations on variable length lists of digits. Each training instance is a sequence of at most 10 tokens: The first token indicates which of 4 reduction operations 2 is to be performed, and the remaining tokens represent the list of digits. The output is the result of the calculation rounded modulo 10. The dataset consists of $1 0 ^ { 5 }$ training and $1 0 ^ { 4 }$ validation instances.
We present this task as a classification problem to a vanilla RNN with ReLU activation and a hidden dimension of 128. All parameterized operations are affinitized on individual workers. We bucket training instances into batches of 100 sequences (in the baseline and in AMPNet).
 Figure 6(b) shows the validation accuracy vs. time and the number of epochs, and throughputs of the methods we discussed in the main text on the list reduction dataset. We first notice that increasing the asynchrony from synchronous (max active key $\tt { 3 = } 1$ ) to max active key $ \textrm { s } = 4$ and max active keys $= 1 6$ affects the convergence very little at least in average. However, there


is also very little speedup without introducing replicas as we discussed in the main text. Increasing the number of replicas increases the throughput almost linearly from $1 3 \mathrm { k }$ sequences/s (synchronous) to 35k sequences/s (2 replicas) and over 70k sequences/s (4 replicas). Convergence is almost unaffected for 2 replicas. This was rather surprising because the parameters of the replicas are only synchronized after each epoch as we described in Sec. 5. A slight slow-down in convergence can be noticed for 4 replicas. Since even max active keys $= 1 6$ has almost no effect on the convergence without replicas, this is not due to asynchrony. We also tried to synchronize more frequently but this did not help. Thus we believe that the slow-down is due to the increase in the effective minibatch size resulting in reduced number of updates per epoch, which is commonly observed in data parallel training.
 Figure 6: Convergence plots.
Table 2: Training and validation throughputs.
<table><tr><td rowspan="2"></td><td colspan="2">number of instances</td><td colspan="3">AMP</td><td colspan="2">TensorFlow</td></tr><tr><td>train</td><td>valid</td><td>mak</td><td>train inst/s</td><td>valid inst/s</td><td>train inst/s</td><td>valid inst/s</td></tr><tr><td>MNIST (97%)</td><td>60k</td><td>10k</td><td>1</td><td>2076</td><td>6094</td><td>5880</td><td>8037</td></tr><tr><td></td><td></td><td></td><td>4</td><td>6268</td><td>18973</td><td></td><td></td></tr><tr><td>List reduction (97%)</td><td>100k</td><td>10k</td><td>1</td><td>13k</td><td>39k</td><td>18k</td><td>43k</td></tr><tr><td></td><td></td><td></td><td>4</td><td>16k</td><td>55k</td><td></td><td></td></tr><tr><td></td><td></td><td></td><td>16</td><td>16k</td><td>56k</td><td></td><td></td></tr><tr><td>(2 replicas)</td><td></td><td></td><td>4</td><td>35k</td><td>100k</td><td></td><td></td></tr><tr><td>(4 replicas) Sentiment (82%)</td><td></td><td></td><td>8</td><td>71k</td><td>178k</td><td></td><td></td></tr><tr><td></td><td>8511</td><td>1101</td><td>1</td><td>102</td><td>280</td><td>265</td><td>1583</td></tr><tr><td></td><td></td><td></td><td>4</td><td>188</td><td>692</td><td></td><td></td></tr><tr><td>QM9 (4.6)</td><td></td><td></td><td>16</td><td>258</td><td>822</td><td></td><td></td></tr><tr><td></td><td>117k</td><td>13k</td><td>1</td><td>302</td><td>710</td><td>1217</td><td>3218</td></tr><tr><td></td><td></td><td></td><td>4</td><td>1007</td><td>2585</td><td></td><td></td></tr><tr><td></td><td></td><td></td><td>16</td><td>1797</td><td>4845</td><td></td><td></td></tr><tr><td>Wikiner (94 %)</td><td>142k</td><td>1.7k</td><td>1</td><td>41</td><td>101</td><td></td><td></td></tr><tr><td></td><td></td><td></td><td>4</td><td>86</td><td>284</td><td></td><td></td></tr><tr><td></td><td></td><td></td><td>32</td><td>130</td><td>426</td><td></td><td></td></tr></table>
# B.3 SENTIMENT TREE BANK DATASET
We consider the sentiment classification dataset from Socher et al. (2013) consisting of binarized constituency parse trees of English sentences with sentiment labels at each node. Following Tai et al. Tai et al. (2015), we use 8,544 trees for training, 1,101 trees for validation, and 2,210 trees for testing.
We use a Tree LSTM for this classification task based on the TensorFlow Fold Looks et al. (2017) benchmark model. Both the AMP and Fold models are trained following Tai et al. (2015) with the additional architectural modifications proposed by Looks et al. (2017); Semeniuta et al. (2016). Furthermore, we split our Tree-LSTM cell into Leaf LSTM and Branch LSTM cells. This does not affect the expressiveness of the model because the LSTM cell receives either zero input (on branch) or zero hidden states (on leaves); i.e., the two cells do not share weights except for the bias parameters, which are learned independently in our implementation. We compare the time to reach $82 \%$ fine grained (5 classes) accuracy (averaged over all the nodes) on the validation set.
Figure 6(c) shows the averaged fine grained validation accuracy for the tree RNN model with different max active keyson the Stanford Sentiment Tree Bank dataset. Interestingly although TensorFlow Fold achieves higher throughput, AMPNet converges faster (in terms of the number of epochs). This speedup is mainly due to the fact that we are not batching and updating whenever we have accumulated 50 gradients (except for the lookup table node that updates every 1000 gradients); 50 gradients correspond to roughly 2 trees. The reason for the lower throughput compared to
TensorFlow Fold is that we are only grouping the leaf operations and not the branch operations. Grouping the branch operations is possible by extending our IR nodes and we are actively working on it.
Figure 6(d) shows the same information for fixed max active keys $\qquad = \quad 1 6$ and different min update interval. We can see that as we increase min update interval from the originally used 50 to larger values, the peak of the validation accuracy shifts later and lower becoming closer to the curve obtained by TensorFlow Fold. This is consistent with the parallels between min update interval and minibatch size we drew in Section 6. The min update interval parameter has marginal influence on the training throughput.
# B.4 QM9 DATASET
We study a real-world application for GNNs: prediction of organic molecule properties from structural formulae in the QM9 dataset Ruddigkeit et al. (2012); Ramakrishnan et al. (2014). GNNs have previously been applied to this task in Gilmer et al. (2017).
We concentrate on prediction of the norm of a molecule’s dipole moment using a regression layer build on the propagation model from Li et al. (2015) (corresponding to the simplest setting in Gilmer et al. (2017)). We use a hidden dimension of 100 and 4 propagation steps, initializing the graph nodes (atoms) following Gilmer et al. (2017). The molecules contain up to 29 atoms and in a TensorFlow baseline we bucket molecules into batches of 20 with atom counts differing by at most 1 within a batch. Following Gilmer et al. (2017), we report regression accuracies in multiples of a target accuracy from the chemistry community.
Figure 6(e) shows that GGNN can tolerate relatively large max active key $s = 1 6$ , and increased the throughput significantly from 300 graphs/s (synchronous) to 1797 graphs/s (see Table 2).
# B.5 WIKINER DATASET
We compare the performance of AMP training with DyNet with and without autobatching using the BiLSTM tagger w/ char model from the DyNet benchmark suite3. This model consists of both character-level and word-level bidirectional LSTMs. The model uses a learnable word embedding for frequent words (more than 5 times in the corpus) and character-level bidirectional LSTMs for infrequent words. We use our Distribute and Collect nodes to dynamically route the messages depending on the word frequencies.
Wikiner dataset4 is a named entity recognition dataset extracted from Wikipedia by Nothman et al. (2013). We use the training/validation split provided by the DyNet benchmark suite with 142,153 and 1,696 sentences, respectively.
The result is shown in Fig. 6(f). We achieve more than $3 \mathbf { x }$ in throughput from max active keys $=$ 1 to max active key $s = 3 2$ without any noticeable loss in the validation accuracy after 2 or 3 epochs. The slight decrease in the validation accuracy after the third epoch is due to overfitting and it is not related to asynchrony.
# C THROUGHPUT ESTIMATION FOR A HYPOTHETICAL 1 TFLOPS DEVICE
In order to estimate the performance of AMPNet on a hypothetical device with 1 TFLOPS compute capability, we replaced all fully connected layers in the network with a dummy operation that simply waits for a specified time. The dummy operation waits for $2 \cdot k \cdot d _ { \mathrm { i n } } \cdot d _ { \mathrm { o u t } } \cdot 1 0 ^ { - 1 2 }$ seconds when the input is $k \times d _ { \mathrm { i n } }$ and the weight matrix is $d _ { \mathrm { i n } } \times d _ { \mathrm { o u t } }$ for forward, backward, and gradient accumulation operation. It waits for $d _ { \mathrm { i n } } \cdot \dot { d } _ { \mathrm { o u t } } \cdot 1 0 ^ { - 1 2 }$ seconds for weight update. In this way we can maintain all the data-dependent control decisions (e.g., sequence length) identical to the original network and also measure the real time spent for all the other operations. In order to calculate the time to reach target accuracy, we take the median number of epochs the original network required to reach the target
accuracy and calculate the time as
$$\mathrm { \Delta t \ i m e = e p o c h s \cdot \left( \frac { { n _ { \mathrm { t r a i n } } } } { t h r o u g h p u t _ { \mathrm { t r a i n } } } + \frac { { n _ { \mathrm { v a l } } } } { t h r o u g h p u t _ { \mathrm { v a l } } } \right) , }$$
where $n _ { \mathrm { t r a i n } }$ and $n _ { \mathrm { v a l } }$ are the number of training and validation instances, respectively, and throughput $\operatorname { t r a i n }$ and throughput $\mathrm { v a l }$ are the throughput for training and validation, respectively.
The results are shown in Table 3. For the 4-way replicated RNN, we estimate roughly 260k instances/s, which is a $3 . 7 \mathbf { x }$ speedup compared to our CPU runtime. For tree RNN and GGSNN, we estimate milder $30 - 7 0 \%$ speedups mainly due to the fact that they have more complicated operations like Distribute and Collect, which we did not attempt to extrapolate the computation time because the implementation on a new hardware may be drastically different from the current CPU runtime.
Table 3: Estimated time to convergence to target validation accuracy and training throughput with a hypothetical 1 TFLOPS device. mak is a short-hand for max active keys defined in Sec. 3; $\mathrm { m a k } = 1$ corresponds to synchronous training for MNIST and minimal asynchrony arising from just one in-flight instance for other models with recursive structures.
<table><tr><td colspan="2"></td><td colspan="4">AMP</td><td colspan="2">1 TFLOPS (estimated)</td></tr><tr><td></td><td>targetaccuracy</td><td>mak</td><td>time (s)</td><td>epochs</td><td>inst/s</td><td>time (s)</td><td>inst/s</td></tr><tr><td>List reduction</td><td>97%</td><td>1</td><td>78</td><td>10</td><td>13k</td><td></td><td></td></tr><tr><td rowspan="2">(4 replicas) Sentiment</td><td></td><td>8</td><td>21</td><td>13</td><td>71k</td><td>5.15</td><td>268k</td></tr><tr><td>82%</td><td>1</td><td>185</td><td>2</td><td>102</td><td></td><td></td></tr><tr><td></td><td></td><td>16</td><td>104</td><td>3</td><td>258</td><td>60.6</td><td>440</td></tr><tr><td>QM9</td><td>4.6</td><td>16</td><td>5227</td><td>76.5</td><td>1797</td><td>3827</td><td>2455</td></tr></table>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200# INVESTIGATING HUMAN PRIORS FOR PLAYING VIDEO GAMES
Rachit Dubey, Pulkit Agrawal, Deepak Pathak, Thomas L. Griffiths, and Alexei A. Efros
University of California, Berkeley
# ABSTRACT
What makes humans so good at solving seemingly complex video games? Unlike computers, humans bring in a great deal of prior knowledge about the world, enabling efficient decision making. This paper investigates the role of human priors for solving video games. Given a sample game, we conduct a series of ablation studies to quantify the importance of various priors. We do this by modifying the video game environment to systematically mask different types of visual information that could be used by humans as priors. We find that removal of some prior knowledge causes a drastic degradation in the speed with which human players solve the game, e.g. from 2 minutes to over 20 minutes. Furthermore, our results indicate that general priors, such as the importance of objects and visual consistency, are critical for efficient game-play.
# 1 INTRODUCTION
While deep Reinforcement Learning (RL) methods have shown impressive performance on a variety of video games (Mnih et al., 2015), they remain woefully inefficient compared to human players, taking millions of action inputs to solve even the simplest Atari games. Much research is currently focused on improving sample efficiency of RL algorithms (Oh et al., 2017; Gu et al., 2016). However, there is an orthogonal issue that is often overlooked: RL agents attack each problem tabula rasa, whereas humans come in with a wealth of prior knowledge about the world, from physics to semantics to affordances.
Consider the following motivating example: you are tasked with playing an unfamiliar computer game shown in Figure 1(a). No manual or instructions are provided; you don’t even know which game sprite is controlled by you. Indeed, the only feedback you are ever given is “terminal”, i.e. once you successfully finish the game. Would you be able to successfully finish this game? How long would it take? We recruited forty human subjects to play this game and found that subjects finished it quite easily, taking just under 1 minute of game-play or 3000 action inputs. This is not overly surprising as one could easily guess that the game’s goal is to move the robot sprite towards the princess by stepping on the brick-like objects and using ladders to reach the higher platforms while avoiding the angry pink and the fire objects.
Now consider a second scenario in which this same simple game is re-rendered with new textures, getting rid of semantic and affordance (Gibson, 2014) cues, as shown in Figure 1(b). How would human performance change? We recruited another forty subjects to play this game and found that, on average, it took the players more than twice the time (2 minutes) and action inputs ( 6500) to complete the game. The second game is clearly much harder for humans, likely because it is now more difficult to guess the game structure and goal, as well as to spot obstacles.
For comparison, we can also examine how modern RL algorithms perform on these games. This is not so simple, as most standard RL approaches expect very dense rewards (e.g. continuously updated game-score (Mnih et al., 2015)), whereas we provide only a terminal reward, to mimic how most humans play video games. In such sparse reward scenarios, standard methods like A3C (Mnih et al., 2016) are too sample-inefficient and were too slow to finish the games. Hence, we used a curiosity-based RL algorithm specifically tailored to sparse-reward settings (Pathak et al., 2017), which was able to solve both games. Unlike humans, RL did not show much difference between the two games, taking about 4 million action inputs to solve each one. This should not be surprising: since RL did not have any prior knowledge about the world, both these games carried roughly the same amount of information from the perspective of the agent.
 Figure 1: Motivating example. (a) A simple platformer game. (b) The same game modified by re-rendering the textures. Despite the two games being structurally the same, human players took twice as long to finish the second game as the first one. In comparison, the performance of an RL agent was approximately the same for the two games.
This simple motivating experiment highlights the importance of prior knowledge that humans draw upon to quickly solve tasks given to them (Lake et al., 2016; Tsividis et al., 2017). Developmental psychologists have begun documenting the prior knowledge that children draw upon in learning about the world (Spelke & Kinzler, 2007; Carey, 2009). However, these studies have not explicitly quantified the relative importance of the various priors for problem-solving.
In this work, we systematically quantify the importance of different types of priors humans bring to bear while solving one particular kind of problem – video games. We chose video games as the task for our investigation because it is relatively easy to methodically change the game to include or mask different kinds of knowledge and run large-scale human studies. Furthermore, video games, such as ATARI, are a popular choice in the reinforcement learning community.
The paper consists of a series of ablation studies on a specially-designed game environment, systematically masking out various types of visual information that could be used by humans as priors. The full game (unlike the motivating example above) was designed to be sufficiently complex and difficult for humans to easily measure changes in performance between different testing conditions.
We find that removal of some prior knowledge causes a drastic degradation in the performance of human players from 1 minute to over 20 minutes. Another key finding of our investigation is that while specific knowledge, such as “ladders are to be climbed”, “keys are used to open doors”, “jumping on spikes is dangerous”, is important for humans to quickly solve games, more general priors about the importance of objects and visual consistency are even more critical.
# 2 METHOD
To investigate the aspects of visual information that enable humans to efficiently solve video games, we designed a browser-based platform game consisting of an agent sprite, platforms, ladders, angry pink object that kills the agent, spikes that are dangerous to jump on, a key, and a door (see Figure 2 (a)). The agent sprite can be moved with the help of arrow keys. A terminal reward of $+ 1$ is provided when the agent reaches the door after having to taken the key, thereby terminating the game. The game is reset whenever the agent touches the enemy, jumps on the spike, or falls below the lowest platform. We made this game to resemble the exploration problems faced in the classic ATARI game of Montezuma’s Revenge that has proven to be very challenging for deep reinforcement learning techniques (Bellemare et al., 2016; Mnih et al., 2015). Unlike the motivating example, this game is too large-scale to be solved by RL agents, but provides the complexity we need to run a wide range of human experiments.
We created different versions of the video game by re-rendering various entities such as ladders, enemies, keys, platforms etc. using alternate textures (Figure 2). These textures were chosen to mask various forms of prior knowledge that are described in the experiments section. We also changed various physical properties of the game, such as the effect of gravity, and the way the agent interacts with its environment. Note that all the games were exactly the same in their underlying structure and reward, as well as the shortest path to reach the goal, thereby ensuring that the change in human performance (if any) is only due to masking of the priors.
 Figure 2: Various game manipulations. (a) Original version of the game. (b) Game with masked objects to ablate semantics prior. (c) Game with reversed associations as an alternate way to ablate semantics prior. (d) Game with masked objects and distractor objects to ablate the concept of object. (e) Game with background textures to ablate affordance prior. (f) Game with background textures and different colors for all platforms to ablate similarity prior. (g) Game with modified ladder to hinder participant’s prior about ladder interactions. (h) Rotated game to change participant’s prior about gravity.
We quantified human performance on each version of the game by recruiting 120 participants from Amazon Mechanical Turk. Each participant was instructed to finish the game as quickly as possible using the arrow keys as controls, but no information about the goals or the reward structure of the game was communicated. Each participant was paid $\$ 1$ for successfully completing the game. The maximum time allowed for playing the game was set to 30 minutes. For each participant, we recorded the $( x , y )$ position of the player at every step of the game, the total time taken by the participant to finish the game and the total number of deaths before finishing the game. We used this data to quantify the performance of each participant. Note that each participant was only allowed to complete a game once, and could not participate again (i.e. different 120 participants played each version of the game).
# 3 QUANTIFYING THE IMPORTANCE OF OBJECT PRIORS
The original game (available to play at this link) is shown in Figure 2(a). A single glance at this game is enough to inform human players that the agent sprite has to reach the key to open the door while avoiding the dangerous objects like spikes and angry pink slime. Unsurprisingly, humans quickly solve this game. Figure 3(a) shows that the average time taken to complete the game is 1.8 minutes (blue bar) and the average number of deaths (3.3, orange bar) and unique game states visited (3011, yellow bar) are all quite small.
# 3.1 SEMANTICS
To study the importance of prior knowledge about object semantics, we rendered objects and ladders with blocks of uniform color as shown in Figure 2(b). This game can be played at this link. In this version, the visual appearance of objects conveys no information about their semantics. Results in Figure 3(b) show that human players take more than twice the time (4.3 minutes), have higher number of deaths (11.1), and explore significantly larger number of states (7205) as compared to the original game (p-value: $p < 0 . 0 1 $ ). This clearly demonstrates that masking semantics hurts human performance.
A natural question is how do humans make use of semantic information? One hypothesis is that knowledge of semantics enables humans to infer the latent reward structure of the game. If this indeed is the case, then in the original game, where the key and the door are both visible, players should first visit the key and then go to the door, while in the version of the game without semantics, players should not exhibit such bias. We found that in the original game, nearly all participants reached the key first, while in the version with masked semantics only 42 out of 120 participants reached the key before the door (see Figure 4(a)). Moreover, human players took significantly longer to reach the door after taking the key as compared to the original game (see Figure 4(b)). This result provides further evidence that in the absence of semantics, humans are unable to infer the reward structure and consequently significantly increase their exploration. To rule out the possibility that increase in time is simply due to the fact players take longer to finish the game without semantics, the time to reach the door after taking the key was normalized by the total amount of time spent by the player to complete the game.
 Figure 3: Quantifying the influence of various object priors. The blue bar shows average time taken by humans (in minutes), orange bar shows the average number of deaths, and yellow bar shows the number of unique states visited by players to solve the various games. For visualization purposes, the number of deaths is divided by 2, and the number of states is divided by 1000 respectively.
To further quantify the importance of semantics, instead of simply masking, we manipulated the semantic prior by swapping the semantics between different entities. As seen on Figure 4(c), we replaced the pink enemy and spikes by coins and ice-cream objects respectively which have a positive connotation; the ladder by fire, the key and the door by spikes and enemies which have negative connotations (see game link). As shown in Figure 3(c), the participants took longer to solve this game (6.1 minutes, $p < 0 . 0 1 $ ). The average number of deaths (13.7) was also significantly more and the participants explored more states (9400) compared to the original version $\mathit { p } < 0 . 0 1$ for both). Interestingly, the participants also took longer compared to the masked semantics version $( p < 0 . 0 5 )$ implying that when we reverse semantic information, humans find the game even tougher.
# 3.2 OBJECTS AS SUB-GOALS FOR EXPLORATION
While blocks of uniform color in the game shown in Figure 2(b) convey no semantics, they are distinct from the background and seem to attract human attention. It is possible that humans infer these distinct entities (or objects) as sub-goals, which results in more efficient exploration than random search. That is, there is something special about objects that draws human attention compared to any random piece of texture. To test this, we modified the game to cover each space on the platform with a block of different color to hide where the objects are (see Figure 2(d), game link). Most colored blocks are placebos and do not correspond to any object and the actual objects have the same color and form as in the previous version of the game with masked semantics (i.e., Figure 2(b)). If the prior knowledge that visibly distinct entities are interesting to explore is critical, this game manipulation should lead to a significant drop in human performance.
Results in Figure 3(d) show that masking the concept of objects leads to drastic deterioration in performance. The average time taken by human players to solve the game is nearly four times longer (7.7 minutes), the number of deaths is nearly six times greater (20.2), and humans explore four times as many game states (12, 232) as compared to the original game. When compared to the game version in which only semantic information was removed (Figure 3(b)), the time taken, number of deaths and number of states are all significantly greater $( p < 0 . 0 1 )$ ). When only semantics are removed, after encountering one object, human players become aware of what possible locations might be interesting to explore next. However, when concept of objects is also masked, it is unclear what to explore next. This effect can be seen by the increase in normalized time taken to reach the door from the key as compared to the game where only semantics are masked (Figure 4(b)). All these results suggest that concept of objects i.e. knowing that visibly distinct entities are interesting and can be used as sub-goals for exploration, is a critical prior and perhaps more important than knowledge of semantics.
 Figure 4: Change in behavior upon ablation of various priors. (a) Graph comparing number of participants that reached the key before the door in the original version, game without semantics, and game without object prior. (b) Amount of time taken by participants to reach the door once they obtained the key. (c) Average number of steps taken by participants to reach various vertical levels in original version, game without affordance, and game without similarity.
# 3.3 AFFORDANCES
Until now, we manipulated objects in ways that made inferring the underlying reward structure of the game non-trivial. However, in these games it was obvious for humans that platforms can support agent sprites, ladders could be climbed to reach different platforms (even when the ladders were colored in uniform red in games shown in Figure 2(b,c), the connectivity pattern revealed where the ladders were) and black parts of the game constitute free space. Here, the platforms and ladders afford the actions of walking and climbing (Gibson, 2014), irrespective of their appearance. In the next set of experiments, we manipulated the game to mask the affordance prior.
One way to mask affordances is to fill free space with random textures, which are visually similar to textures used for rendering ladders and platforms (see Figure 2(e), game link). Note that in this game manipulation, objects and their semantics are clearly observable. When tasked to play this game, as shown in Figure 3(e), humans require significantly more time (4.7 minutes), die more often (10.7), and visit more states (7031) compared to the original game $\mathit { p } < 0 . 0 1 )$ ). On the other hand, there is no significant difference in performance compared to the game without semantics, i.e., Figure 2(b), implying that the affordance prior is as important as the semantics prior in our setup.
# 3.4 THINGS THAT LOOK SIMILARLY, BEHAVE SIMILARLY
In the previous game, although we masked affordance information, once the player realizes that it is possible to stand on a particular texture and climb a specific texture, it is easy to use color/texture similarity to identify other platforms and ladders in the game. Similarly, in the game with masked semantics (Figure 2(b)), visual similarity can be used to identify other enemies and spikes. These considerations suggest that a general prior of the form that things that look the same act the same might help humans efficiently explore environments where semantics or affordances are hidden.
We tested this hypothesis by modifying the masked affordance game in a way that none of the platforms and ladders had the same visual signature (Figure 2(f), game link). Such rendering prevented human players from using the similarity prior. Figure 3(f)) shows that performance of humans was significantly worse in comparison to the original game (Figure 2(a)), the game with masked semantics (Figure 2(b)) and the game with masked affordances (Figure 2(e)) $\mathit { p } < 0 . 0 1 )$ . When compared to the game with no object information (Figure 2(d)), the time to complete the game (7.6 minutes) and the number of states explored by players were similar (11, 715), but the number of deaths (14.8) was significantly lower $( p < 0 . 0 1 )$ ). These results suggest that visual similarity is the second most important prior used by humans in gameplay after the knowledge of directing exploration towards objects.
 Figure 5: Masking all object priors drastically affects human performance. (a) Original game. (b) Version without any object priors. (c) Graph depicting difference in participant’s performance for both the games. (d) Exploration trajectory for original version and (e) for no object prior version.
In order to gain insight into how this prior knowledge affects humans, we investigated the exploration pattern of human players. In the game when all information is visible we expected that the progress of humans would be uniform in time. In the case when affordances are removed, the human players would initially take some time to figure out what visual pattern corresponds to what entity and then quickly make progress in the game. Finally, in the case when the similarity prior is removed, we would expect human players to be unable to generalize any knowledge across the game and to take large amounts of time exploring the environment even towards the end. We investigated if this indeed was true by computing the time taken by each player to reach different vertical distances in the game for the first time. Note that the door is on the top of the game, so the moving up corresponds to getting closer to solving the game. The results of this analysis are shown in Figure 4(c). The horizontal-axis shows the height reached by the player and the vertical-axis show the average time taken by the players. As the figure shows, the results confirm our hypothesis.
# 3.5 HOW TO INTERACT WITH OBJECTS
Until now we have analyzed the prior knowledge used by humans to interpret the visual structure in the game. However, interpretation of visual structure is only useful if the player understands what to do with the interpretation. Humans seem to possess prior knowledge about how to interact with different objects. For example, monsters can be avoided by jumping over them, ladders can be climbed by pressing the up key repeatedly etc. Deep reinforcement learning agents, on the other hand, do not possess such priors and must learn how to interact with objects by mere trial and error.
To test how critical such prior knowledge is, we created a version of the game in which the ladders couldn’t be climbed by simply pressing the up key. Instead, the ladders were zigzag in nature and in order to climb the ladder players had to press the up key, followed by alternating presses between the right and left key. Note that the ladders in this version looked like normal ladders, so players couldn’t infer the properties of the ladder by simply looking at them (see Figure $2 ( \mathbf { g } )$ , game link). As shown in Figure $3 ( \mathbf { g } )$ , changing the property of the ladder increases the time taken (3.6 minutes), number of deaths (6), and states explored (5942) when compared to the original game $( p < 0 . 0 1 )$ ).
# 4 TAXONOMY OF OBJECT PRIORS
In previous sections, we studied how different priors about objects affect human performance one at a time. To quantify human performance when all object priors investigated so far are simultaneously masked, we created the game shown in Figure 5(b) that hid all information about objects, semantics, affordance, and similarity(game link). Results in Figure 5(c) show that humans found it extremely hard to play this game. The average time taken to solve the game increased to 20 minutes and the average number of deaths rose sharply to 40. Remarkably, the exploration trajectory of humans is now almost completely random as shown in Figure 5(e) with the number of unique states visited by the human players increasing by a factor of 9 as compared to the original game. Due to difficulty in completing this game, we noticed a high dropout of human participants before they finished the game. We had to increase the pay to $\$ 2.25$ to encourage participants not to quit. Many participants noted that they could solve the game only by memorizing it.
Even though we preserved priors related to physics (e.g., objects fall down) and motor control (e.g., pressing left key moves the agent sprite to the left), just by rendering the game in a way that makes it impossible to use prior knowledge about how to visually interpret the game screen makes the game extremely hard to play. To further test the limits of human ability, we designed a harder game where we also reversed gravity and randomly re-mapped the key presses to how it affect’s the motion of agent’s sprite. We, the creators of the game, having played a previous version of the game hundreds of times had an extremely hard time trying to complete this version of the game. This game placed us in the shoes of reinforcement learning (RL) agents that start off without the immense prior knowledge that humans possess. While improvements in the performance of RL agents with better algorithms and better computational resources is inevitable, our results make a strong case for developing algorithms that incorporate prior knowledge as a way to improve the performance of artificial agents.
 Figure 6: Taxonomy of object priors. The earlier an object prior is obtained during childhood, the more critical that object prior is in human problem solving in video games.
While there are many possible directions on how to incorporate priors in RL and more generally AI agents, it is informative to study how humans acquire such priors. Studies in developmental psychology suggest that human infants as young as 2 months old possess a primitive notion of objects and expect them to move as connected and bounded wholes that allows them to perceive object boundaries and therefore possibly distinguish them from the background (Spelke, 1990; Spelke & Kinzler, 2007). At this stage, infants do not reason about object categories. By the age of 3-5 months, infants start exhibiting categorization behavior based on similarity and familiarity (Mandler, 1998; Mareschal & Quinn, 2001). The ability to recognize individual objects rapidly and accurately emerges comparatively late in development (usually by the time babies are 18-24 months old (Pereira & Smith, 2009)). Similarly, while young infants exhibit some knowledge about affordances early during development, the ability to distinguish a walkable step from a cliff emerges only by the time they are 18 months old (Kretch & Adolph, 2013).
These results in infant development suggest that starting with a primitive notion of objects, infants gradually learn about visual similarity and eventually about object semantics and affordances. It is quite interesting to note that the order in which infants increase their knowledge matches the importance of different object priors such as the existence of objects as sub-goals for exploration, visual similarity, object semantics, and affordances. Based on these results, we suggest a possible taxonomy and ranking of object priors in Figure 6. We put ‘object interaction’ at the bottom as in the context of our problem, knowledge about how to interact with specific objects can be only learned once recognition is performed.
# 5 PHYSICS AND MOTOR CONTROL PRIORS
In addition to prior knowledge about objects, humans also bring in rich prior knowledge about intuitive physics and strong motor control priors when they approach a new task (Hespos et al., 2009; Baillargeon, 2004; 1994; Wolpert & Ghahramani, 2000). Here, we have taken some initial steps to explore the importance of such priors in context of human gameplay.
# 5.1 GRAVITY
One of the most obvious forms of knowledge that we have about the physical world is with regards to gravity, i.e., things fall from up to down. To mask this prior, we created a version of the game in which the whole game window was rotated $9 0 ^ { \circ }$ (refer to Figure $2 ( \mathrm { h } ) _ { \cdot }$ ). In this way, the gravity was reversed from left to right (as opposed to up to down). As shown in Figure 7, participants spent more time to solve this game compared to the original version with average time taken close to 3 minutes $( p < 0 . 0 1 )$ . The average number of deaths and number of states explored was also significantly larger than the original version $( p < 0 . 0 1 )$ .
 Figure 7: Quantifying physics and motor control priors. Graph shows performance of participants in original version, game with gravity reversed, and game with key controls reversed. Number of deaths is divided by 2 and number of states is divided by 1000.
# 5.2 MUSCLE MEMORY
Human players also come with knowledge about the consequences of actions such as pressing arrow keys moves the agent sprite in the corresponding directions (i.e., pressing up makes the agent sprite jump, pressing left makes the agent sprite go left and so forth). We created a version of the game in which we reversed the arrow key controls. Thus, pressing the left arrow key made the agent sprite go right, pressing the right key moved the sprite left, pressing the down key made the player jump (or go up the stairs), and pressing the up key made the player go down the stairs. Participants again took longer to solve this game compared to the original version with average time taken close to 3 minutes (refer to Figure 7). The average number of deaths and number of states explored was also significantly larger than the original version $( p \ < \ 0 . 0 1 )$ . Interestingly, the performance of players when the gravity was reversed, and key controls were reversed is similar, with no significant difference between the two conditions.
# 6 CONTROLLING FOR CHANGE IN COMPLEXITY
So far in this paper, we have manipulated various visual priors while keeping the underlying game and reward structure exactly the same. We have assumed that this will influence human performance while keeping RL agent performance unchanged, since RL does not have any priors to begin with. However, one possible confound is that the visual complexity of the modified games might have changed from the original game version, because masking out priors without changing visual complexity is extremely difficult.
To control for this confound, we investigated the performance of an RL agent on the various game manipulations. If RL agents are not affected by the game manipulations, then it would suggest that prior knowledge and not visual complexity is the main reason behind the change in human performance. Note that this confound is not present in the physics and motor control experiments as the visual input stays the same as the original game.
To this end, we systematically created different versions of the game in Figure 1(a) to ablate semantics, the concept of object, affordance, and similarity as shown in Figure 8. Note that the game used for human experiments shown in Figure 2 is more complex than the game used for RL experiments in Figure 8. This is because the larger game was simply too hard for state-of-the-art RL agents to solve. Apart from the difference in the game size, we tried to make the games as similar as possible. Even though this version of the game is simpler (regarding size, number of objects etc.), we note that this game is still non-trivial for an RL agent. For instance, due to the sparse reward structure of the game, both A3C (Mnih et al., 2016) and breadth-first search didn’t come close to solving the game even after 10 million steps. Hence, for our purpose, we used an RL algorithm augmented with a curiosity based exploration strategy (Pathak et al., 2017). For each game version, we report the mean performance of five random seeds that succeeded.
As shown in Figure 8(e), the RL agent was unaffected by the removal of semantics, the concept of objects, as well as affordances – there is no significant difference between the mean score of the RL agent on these games when compared to the performance on the original game $( p > 0 . 0 5 )$ . This suggests that the drop in human performance in these game manipulations is not due to the change in visual complexity, but it is rather due to the masking of the various priors. On the other hand, the performance of the RL agent does worsen when visual similarity is masked as it takes nearly twice as many interactions to complete the game compared to the original version. We believe this is due to to the use of convolutional neural networks that implicitly impose the prior of visual similarity rather than simply due to the change in visual complexity.
 Figure 8: Quantifying the performance of RL agent. (a) Game without semantic information. (b) Game with masked and distractor objects to ablate concept of objects. (c) Game without affordance information. (d) Game without similarity information. (e) Performance of RL agent on various game manipulations (steps shown in order of million). Error bars indicate standard error of mean for the 5 random seeds. The RL agent performs similarly on all games except for the one without visual similarity.
# 7 DISCUSSION
While there is no doubt that the performance of deep RL algorithms is impressive, there is much to be learned from human cognition if our goal is to enable RL agents to solve sparse reward tasks with human-like efficiency. Humans have the amazing ability to use their past knowledge (i.e., priors) to solve new tasks quickly. Success in such scenarios critically depends on the agent’s ability to explore its environment and then promptly learn from its successes (Daw et al., 2006; Cohen et al., 2007). In this vein, our results demonstrate the importance of prior knowledge in helping humans explore efficiently in these sparse reward environments (Knox et al., 2012; Gershman & Niv, 2015).
However, being equipped with strong prior knowledge can sometimes lead to constrained exploration that might not be optimal in all environments (Lucas et al., 2014; Bonawitz et al., 2011). For instance, consider the game shown in Figure 9 consisting of a robot and a princess object. The game environment also includes rewards in hidden locations (shown as dashed yellow boxes only for illustration). When tasked to play this game, human participants $\mathrm { ( n { = } 3 0 } ) _ { , }$ ) immediately assume that princess is the goal and do not explore the free space containing hidden rewards. They directly reach the princess and thereby terminate the game with sub-optimal rewards. In contrast, a random agent (30 seeds) ends up obtaining almost four times more reward than human players as shown in Figure 9. Thus, while incorporating prior knowledge in RL agents has many potential benefits, future work should also consider challenges regarding under-constrained exploration in certain kinds of settings.
While our paper primarily investigated object priors (and physics priors to some extent), humans also possess rich prior knowledge about the world in the form of intuitive psychology and also bring in various priors about general video game playing such as that moving up and to the right in games is generally correlated with progress, games have goals, etc. Studying the importance of such priors will be an interesting future direction of research.
Building RL algorithms that require fewer interactions to reach the goal (i.e., sample efficient algorithms) is an active area of research, and further progress is inevitable. In addition to developing better optimization methods, we believe that instead of always initializing learning from scratch, either incorporating prior knowledge directly or constructing mechanisms for condensing experience into reusable knowledge (i.e., learning priors through continual learning) might be critical for building RL agents with human-like efficiency. Our work takes first steps toward quantifying the importance of various priors that humans employ in solving video games and in understanding how prior knowledge makes humans good at such complex tasks. We believe that our results will inspire researchers to think about different mechanisms of incorporating prior knowledge in the design of RL agents. We also hope that our experimental platform of video games, available in open-source, will fuel more detailed studies investigating human priors and a benchmark for quantifying the efficacy of different mechanisms of incorporating prior knowledge into RL agents.
 Figure 9: Prior information constrains human exploration. (Left) A very simple game with hidden rewards (shown in dashed yellow). (Right) Average rewards accumulated by human players vs a random agent.
# ACKNOWLEDGEMENT
We thank Jordan Suchow, Michael Chang, Shubham Tulsiani, Alison Gopnik, and other members of the BAIR community for helpful discussions and comments. This work has been supported, in part, by Google, ONR MURI N00014-14-1-0671, Berkeley DeepDrive, NVIDIA Graduate Fellowship to DP, and the Valrhona Reinforcement Learning Fellowship.
# REFERENCES
Renee Baillargeon. How do infants learn about the physical world? Current Directions in Psychological Science, 3(5):133–140, 1994.
Renee Baillargeon. Infants’ physical world. ´ Current directions in psychological science, 13(3): 89–94, 2004.
Marc Bellemare, Sriram Srinivasan, Georg Ostrovski, Tom Schaul, David Saxton, and Remi Munos. Unifying count-based exploration and intrinsic motivation. In NIPS, 2016.
Elizabeth Bonawitz, Patrick Shafto, Hyowon Gweon, Noah D Goodman, Elizabeth Spelke, and Laura Schulz. The double-edged sword of pedagogy: Instruction limits spontaneous exploration and discovery. Cognition, 120(3):322–330, 2011.
Susan Carey. The origin of concepts. Oxford University Press, 2009.
Jonathan D Cohen, Samuel M McClure, and J Yu Angela. Should i stay or should i go? how the human brain manages the trade-off between exploitation and exploration. Philosophical Transactions of the Royal Society B: Biological Sciences, 362(1481):933–942, 2007.
Nathaniel D Daw, John P O’Doherty, Peter Dayan, Ben Seymour, and Raymond J Dolan. Cortical substrates for exploratory decisions in humans. Nature, 441(7095):876–879, 2006.
Samuel J Gershman and Yael Niv. Novelty and inductive generalization in human reinforcement learning. Topics in cognitive science, 7(3):391–415, 2015.
James J Gibson. The ecological approach to visual perception: classic edition. Psychology Press, 2014.
Shixiang Gu, Timothy Lillicrap, Ilya Sutskever, and Sergey Levine. Continuous deep q-learning with model-based acceleration. In ICML, 2016.
Susan J Hespos, Alissa L Ferry, and Lance J Rips. Five-month-old infants have different expectations for solids and liquids. Psychological Science, 20(5):603–611, 2009.
W Bradley Knox, A Ross Otto, Peter Stone, and Bradley Love. The nature of belief-directed exploratory choice in human decision-making. Frontiers in psychology, 2:398, 2012.
Kari S Kretch and Karen E Adolph. Cliff or step? posture-specific learning at the edge of a drop-off. Child Development, 84(1):226–240, 2013.
Brenden M Lake, Tomer D Ullman, Joshua B Tenenbaum, and Samuel J Gershman. Building machines that learn and think like people. Behavioral and Brain Sciences, pp. 1–101, 2016.
Christopher G Lucas, Sophie Bridgers, Thomas L Griffiths, and Alison Gopnik. When children are better (or at least more open-minded) learners than adults: Developmental differences in learning the forms of causal relationships. Cognition, 131(2):284–299, 2014.
Jean M. Mandler. Representation. In Cognition, perception, and language: Handbook of child psychology. John Wiley & Sons Inc, 1998.
Denis Mareschal and Paul C Quinn. Categorization in infancy. Trends in cognitive sciences, 5(10): 443–450, 2001.
Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A Rusu, Joel Veness, Marc G Bellemare, Alex Graves, Martin Riedmiller, Andreas K Fidjeland, Georg Ostrovski, et al. Human-level control through deep reinforcement learning. Nature, 2015.
Volodymyr Mnih, Adria Puigdomenech Badia, Mehdi Mirza, Alex Graves, Timothy P Lillicrap, Tim Harley, David Silver, and Koray Kavukcuoglu. Asynchronous methods for deep reinforcement learning. In ICML, 2016.
Junhyuk Oh, Satinder Singh, and Honglak Lee. Value prediction network. In NIPS, 2017.
Deepak Pathak, Pulkit Agrawal, Alexei A Efros, and Trevor Darrell. Curiosity-driven exploration by self-supervised prediction. arXiv preprint arXiv:1705.05363, 2017.
Alfredo F Pereira and Linda B Smith. Developmental changes in visual object recognition between 18 and 24 months of age. Developmental science, 12(1):67–80, 2009.
Elizabeth S Spelke. Principles of object perception. Cognitive science, 14(1):29–56, 1990.
Elizabeth S Spelke and Katherine D Kinzler. Core knowledge. Developmental science, 10(1):89–96, 2007.
Pedro A Tsividis, Thomas Pouncy, Jacqueline L Xu, Joshua B Tenenbaum, and Samuel J Gershman. Human learning in atari. In The AAAI 2017 Spring Symposium on Science of Intelligence: Computational Principles of Natural and Artificial Intelligence, 2017.
Daniel M Wolpert and Zoubin Ghahramani. Computational principles of movement neuroscience. Nature neuroscience, 3:1212–1217, 2000.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322# WHEN DOES SELF-SUPERVISION IMPROVE FEW-SHOT LEARNING?
Anonymous authors Paper under double-blind review
# ABSTRACT
We present a technique to improve the generalization of deep representations learned on small labeled datasets by introducing self-supervised tasks as auxiliary loss functions. Although recent research has shown benefits of self-supervised learning (SSL) on large unlabeled datasets, its utility on small datasets is unknown. We find that SSL reduces the relative error rate of few-shot meta-learners by $4 \% - 2 7 \%$ , even when the datasets are small and only utilizing images within the datasets. The improvements are greater when the training set is smaller or the task is more challenging. Though the benefits of SSL may increase with larger training sets, we observe that SSL can have a negative impact on performance when there is a domain shift between distribution of images used for meta-learning and SSL. Based on this analysis we present a technique that automatically select images for SSL from a large, generic pool of unlabeled images for a given dataset using a domain classifier that provides further improvements. We present results using several meta-learners and self-supervised tasks across datasets with varying degrees of domain shifts and label sizes to characterize the effectiveness of SSL for few-shot learning.
# 1 INTRODUCTION
Current machine learning algorithms require enormous amounts of training data to learn new tasks. This is a problem for many practical problems across domains such as biology and medicine where labeled data is hard to come by. In contrast, we humans can quickly learn new concepts from limited training data. We are able to do this by relying on our past “visual experience”. Recent work attempts to emulate this by training a feature representation to classify a training dataset of “base” classes with the hope that the resulting representation generalizes not just to unseen examples of the same classes but also to novel classes, which may have very few training examples (called fewshot learning). However, training for base class classification can force the network to only encode features that are useful for distinguishing between base classes. In the process, it might discard semantic information that is irrelevant for base classes but critical for novel classes. This might be especially true when the base dataset is small or when the class distinctions are challenging.
One way to recover this useful semantic information is to leverage representation learning techniques that do not use class labels, namely, unsupervised or self-supervised learning. The key idea is to learn about statistical regularities (e.g., spatial relationship between patches, orientation of an images) that might be a cue to semantics. Despite recent advances, these techniques have only been applied to a few domains (e.g., entry-level classes on internet imagery), and under the assumption that large amounts of unlabeled images are available. Their applicability to the general few-shot scenario described above is unclear. In particular, can these techniques help prevent overfitting to base classes and improve performance on novel classes in the few-shot setting? If so, does the benefit generalize across domains and to more challenging tasks? Moreover, can we use self-supervised training to boost performance in domains where even unlabeled images are hard to get?
This paper seeks to answer these questions. We show that with no additional training data, adding a self-supervised task as an auxiliary task (Figure 1) improves the performance of existing few-shot techniques on benchmarks across a multitude of domains (Figure 2). Intriguingly, we find that the benefits of self-supervision increase with the difficulty of the task, for example when training from a smaller base dataset, or with degraded inputs such as low resolution or greyscale images (Figure 3).
One might surmise that as with traditional SSL, additional unlabeled images might improve performance further. But what unlabeled images should we use for novel problem domains where unlabeled data is not freely available? To answer this, we conduct a series of experiments with additional unlabeled data from different domains. We find that adding more unlabeled images improves performance only when the images used for self-supervision are within the same domain as the base classes (Figure 4a); otherwise they can even negatively impact the performance of the few-shot learner (Figure 4b, 4c, 4d). Based on this analysis we present a simple approach that uses a domain classifier to pick similar-domain unlabeled images for self-supervision from a large, generic pool of images. The resulting method improves over the performance of a model trained with self-supervised learning from images within the domain (Figure 4c). Taken together, this results in a powerful, general and practical approach for improving few-shot learning from small datasets in novel domains. Finally, these benefits are also observed on standard classification tasks (Appendix A.3).
# 2 RELATED WORK
Few-shot learning Few-shot learning aims to learn representations that generalize well to the novel classes where only few images are available. To this end several meta-learning approaches have been proposed that evaluate representations by sampling many few-shot tasks within the domain of a base dataset. These include optimization-based meta-learners, such as model-agnostic meta-learner (MAML) (Finn et al., 2017), gradient unrolling (Ravi & Larochelle, 2017), closed form solvers (Bertinetto et al., 2019), convex learners (Lee et al., 2019), etc. Others such as matching networks (Vinyals et al., 2016) and prototypical networks (Snell et al., 2017) rely on distance based classifiers, while Garcia & Bruna (2018) models higher-order relationships in data using a graph network. Another class of methods (Gidaris & Komodakis, 2018; Qi et al., 2018; Qiao et al., 2018) model the mapping between training data and classifier weights using a feed-forward network.
While the literature is rapidly growing, a recent study by Chen et al. (2019) has shown that the differences between meta-learners are diminished when deeper network architectures are used and they develop a strong baseline for few-shot learning based on ResNet18 architecture and prototypical networks Snell et al. (2017). We build our experiments on top of this work and show that auxiliary self-supervised tasks provide additional benefits with state-of-the-art deep networks across several few-shot benchmarks. We also find that prototypical networks are often the best performing, though the benefits of SSL generalize across meta-learners such as MAML.
Self-supervised learning Human labels are expensive to collect and hard to scale up. To this end, there has been increasing research interest to investigate learning representations from unlabeled data. In particular, the image itself already contains structural information which can be utilized. Self-supervised learning approaches attempt to capture this.
There is a rich line of work on self-supervised learning. One class of methods removes part of the visual data, and tasks the network with predicting what has been removed from the rest in a discriminative manner (Larsson et al., 2016; Zhang et al., 2016; 2017). Doersch et al. (2015) proposed to predict the relative position of patches cropped from images. Wang & Gupta (2015) used the similarity of patches obtained from tracking as a self-supervised task and combined position and similarity predictions of patches (Wang et al., 2017). Other tasks include predicting rotation (Gidaris et al., 2018), noise (Bojanowski & Joulin, 2017), clusters (Caron et al., 2018; 2019; Wu et al., 2018), number of objects (Noroozi et al., 2017), missing patches (Pathak et al., 2016; Trinh et al., 2019), motion segmentation labels (Pathak et al., 2017), artifacts (Jenni & Favaro, 2018), next patch feature (Oord et al., 2018; Henaff et al. ´ , 2019), or by maximizing mutual information (Hjelm et al., 2019; Bachman et al., 2019), and training an adversarial generative model (Donahue & Simonyan, 2019). Doersch & Zisserman (2017) jointly trained four self-supervised tasks and found it to be beneficial. Recently, Goyal et al. (2019) and Kolesnikov et al. (2019) compared various self-supervised learning tasks at scale and concluded that solving jigsaw puzzles and predicting image rotations are among the most effective, motivating the choice of self-supervised tasks in our experiments.
The focus of most prior works on self-supervised learning is to supplant traditional fully supervised representation learning with unsupervised learning on large unlabeled datasets for downstream tasks. Crucially in almost all prior works, self-supervised representations consistently lag behind fullysupervised representations trained on the same dataset with the same architecture (Goyal et al., 2019; Kolesnikov et al., 2019). In contrast, our work focuses on an important counterexample: selfsupervision can in fact augment standard supervised training for few-shot transfer learning in the low training data regime without relying on any external dataset. Our work also investigates the effect of domain shifts across datasets used for SSL and a given task.
 Figure 1: Our framework combines supervised and self-supervised losses to learn representations on small datasets. Self-supervised tasks, such as jigsaw puzzle or rotation prediction, can be derived from the images alone and act as a data-dependent regularizer for the shared feature backbone.
Multi-task learning Our work is related to multi-task learning, a class of techniques that train on multiple task objectives together to improve each one. Previous works in the computer vision literature have shown moderate benefits by combining tasks such as edge, normal, and saliency estimation for images, or part segmentation and detection for humans (Kokkinos, 2017; Maninis et al., 2019; Ren & Lee, 2018). However, there is significant evidence that training on multiple tasks together often hurts performance on individual tasks (Kokkinos, 2017; Maninis et al., 2019). Only certain task combinations appear to be mutually beneficial, and sometimes specific architectures are needed. Our key contribution here is showing that self-supervised tasks and few-shot learning are indeed mutually beneficial in this sense. The fact that self-supervised tasks require no annotations makes our finding especially practically significant.
Concurrent works At the time of submission several concurrent works appear to draw similar conclusions to ours. We briefly describe these, deferring a detailed comparison to the future when code and experimental details become available. Asano et al. (2019) finds that self-supervised pretraining is useful even with a single image. However, very large images and extreme data augmentations are used. Carlucci et al. (2019) uses self-supervision to improve domain generalization. Gidaris et al. (2019), the most related work to ours, also shows that self-supervision improves few-shot learning. Although this initial result is the same, we further show these benefits on smaller datasets with harder recognition problems (fine-grained classification) and with deeper models. Moreover, we also present a novel analysis of the impact of the domain of unlabeled data, and a new, simple approach to automatically select similar-domain unlabeled data for self-supervision.
# 3 METHOD
We adopt the commonly used setup for few-shot learning where one is provided with labeled training data for a set of base classes $\mathcal { D } _ { b }$ and a much smaller training set (typically 1-5 examples per class) for novel classes $\mathcal { D } _ { n }$ . The goal of the few-shot learner is to learn representations on the base classes that lead to good generalization on novel classes. Although in theory the base classes are assumed to have a large number of labeled examples, in practice this number can be quite small for novel domains, e.g. less than 5000 examples for the birds dataset (Welinder et al., 2010), making it challenging to learn a generalizable representation.
Our framework, as seen in Figure 1, combines meta-learning approaches for few-shot learning that rely on supervised labels with self-supervised learning on unlabeled images. Denote a training dataset as $\mathbf { \dot { \{ ( x _ { i } , } } y _ { i } ) \mathbf \} _ { i = 1 } ^ { n }$ consisting of pairs of images $x _ { i } \in \mathcal X$ and labels $y _ { i } \in \mathcal { V }$ . A feed-forward convolutional network $f ( x )$ maps the input to an embedding space, which is then mapped to the label space using a classifier $g$ . The overall mapping from the input to the label can be written as $g \circ f ( { \bar { x } } ) : \mathcal { X } \to { \bar { \mathcal { V } } }$ . Learning consists of estimating functions $f$ and $g$ that minimize a loss $\ell$ on the predicted labels on the training data along with suitable regularization $\mathcal { R }$ over the functions $f$ and $g$ . This can be written as:
$$\mathcal { L } _ { s } : = \sum _ { i } \ell \big ( g \circ f ( x _ { i } ) , y _ { i } \big ) + \mathcal { R } ( f , g ) .$$
A commonly used loss is the cross-entropy loss and a regularizer is the $\ell _ { 2 }$ norm of the parameters of the functions. For transfer $g$ is discarded and relearned on training data for novel classes.
In addition, we consider self-supervised losses $\mathcal { L } _ { s s }$ based on labeled data $x ( \hat { x } , \hat { y } )$ that can be derived from inputs $x$ alone. Figure 1 shows two examples: the jigsaw task rearranges the input image and uses the index of the permutation as the target label, while the rotation task uses the angle of the rotated image as the target label. In our framework, a separate function $h$ is used to predict these labels from the shared feature backbone $f$ with a self-supervised loss:
$$\mathcal { L } _ { s s } : = \sum _ { i } \ell \big ( h \circ f ( \hat { x } _ { i } ) , \hat { y } _ { i } \big ) .$$
Our final loss function combines the two losses: $\mathcal { L } : = \mathcal { L } _ { s } + \mathcal { L } _ { s s }$ , and thus the self-supervised losses act as a data-dependent regularizer for representation learning. Note that the domain of images used for supervised and self-supervised losses denoted by $\mathcal { D } _ { s }$ and $\mathcal { D } _ { s s }$ need not be identical. In particular we often would like to use significantly larger sets of images for self-supervised learning from related domains. Below we describe various losses we consider for image classification tasks.
# 3.1 SUPERVISED LOSSES $( \mathcal { L } _ { s } )$
Most of our results are presented using a meta-learner based on prototypical networks (Snell et al., 2017) that perform episodic training and testing over sampled datasets in stages called meta-training and meta-testing. During meta-training, we randomly sample $N$ classes from the base set $\mathcal { D } _ { b }$ , then we select a support set $\boldsymbol { S _ { b } }$ with $K$ images per class and another query set $\mathcal { Q } _ { b }$ with $M$ images per class. We call this an $N$ -way $K$ -shot classification task. The embeddings are trained to predict the labels of the query set $\mathcal { Q } _ { b }$ conditioned on the support set $\boldsymbol { S _ { b } }$ using a nearest mean (prototype) model. The objective is to minimize the prediction loss on the query set. Once training is complete, given the novel dataset $\mathcal { D } _ { n }$ , class prototypes are recomputed for classification and query examples are classified based on the distances to the class prototypes.
Prototypical networks are related to distance-based learners such as matching networks (Vinyals et al., 2016) or metric-learning based on label similarity (Koch et al., 2015). In the Appendix we also present few-shot classification results using a gradient-based meta-learner called MAML (Finn et al., 2017), and one trained with a standard cross-entropy loss on the base classes. We also present standard classification results where the test set contains images from the same base categories.
# 3.2 SELF-SUPERVISED LOSSES $( \mathcal { L } _ { s s } )$
We consider two losses motivated by a recent large-scale comparison of the effectiveness of selfsupervised learning tasks (Goyal et al., 2019) described below:
Jigsaw puzzle task loss. In this case the input image $x$ is tiled into $3 \times 3$ regions and permuted randomly to obtain an input $\hat { x }$ . The target label $\hat { y }$ is the index of the permutation. The index (one of 9!) is reduced to one of 35 following the procedure outlined in Noroozi & Favaro (2016), which grouped the possible permutations based on hamming distance to control the difficulty of the task.
Rotation task loss. We follow the method of Gidaris et al. (2018) where the input image $x$ is rotated by an angle $\theta \in \{ 0 ^ { \circ } , 9 0 ^ { \circ } , 1 8 0 ^ { \circ } , 2 7 0 ^ { \circ } \}$ to obtain $\hat { x }$ and the target label $\hat { y }$ is the index of the angle.
In both cases we use the cross-entropy loss between the target and prediction.
# 3.3 STOCHASTIC SAMPLING AND TRAINING
When the source of images used for SSL and meta-learning are identical the same batch of images are used for computing $\mathcal { L } _ { s }$ and $\mathcal { L } _ { s s }$ . For experiments investigating domain shifts (Sec. 4.2), where SSL and meta-learner are trained on different distribution of images, a different batch (size of 64) is used for computing $\mathcal { L } _ { s s }$ . After the two forward passes, one for the supervised task and one for the
self-supervised task, the two losses are combined. While other techniques exist (Chen et al., 2018; Kendall et al., 2018; Sener & Koltun, 2018), simply combining the two losses performed well.
# 4 EXPERIMENTS
We first describe the datasets and experimental details. We then present results for few-shot learning on different datasets and SSL tasks in Section 4.1. Last, we investigate the effectiveness of SSL with unlabeled data sampled from different domains in Section 4.2.
Datasets and benchmarks We experiment with datasets across diverse domains: Caltech-UCSD birds (Welinder et al., 2010), Stanford cars (Krause et al., 2013), FGVC aircrafts (Maji et al., 2013), Stanford dogs (Khosla et al., 2011), and Oxford flowers (Nilsback & Zisserman, 2006). Each dataset contains between 100 to 200 classes with a few thousands of images. We also experiment with the widely-used mini-ImageNet (Vinyals et al., 2016) and tiered-ImageNet (Ren et al., 2018) benchmarks for few-shot learning. In mini-ImageNet, each class has 600 images, where in tiered-ImageNet each class has 732 to 1300 images.
We split classes within a dataset into three disjoint sets: base, val, and novel. For each class all the images in the dataset are used in the corresponding set. A model is trained on the base set of categories, validated on the val set, and tested on the novel set of categories given a few examples per class. For birds, we use the same split as Chen et al. (2019), where $\{ b a s e , \nu a l , n o \nu e l \}$ sets have $\{ 1 0 0 , 5 0 , 5 0 \}$ classes respectively. The same ratio is used for the other four fine-grained datasets. We use the original splits for mini-ImageNet and tiered-ImageNet.
We also present results on a setting where the base set is “degraded” either by reducing the resolution, removing color, or the number of training examples to $20 \%$ of the original set. This allows us to study the effectiveness of SSL on even smaller datasets and as a function of the difficulty of the task. Further details of the datasets are in the Appendix A.1.
Meta-learners and feature backbone We follow the best practices and use the codebase for fewshot learning described in Chen et al. (2019). In particular, we use a prototypical network (Snell et al., 2017) with a ResNet18 (He et al., 2016) as the feature backbone. Their experiments found this to often be the best performing; however, we also experiment our method with other meta-learners such as MAML (Finn et al., 2017) and softmax classifiers.
Learning and optimization We use 5-way (classes) and 5-shot (examples per-class) with 16 query images for training. For experiments using $20 \%$ of labeled data, we use 5 query images for training since the minimum number of images per class is 10. The models are trained with ADAM (Kingma & Ba, 2015) with a learning rate of 0.001 for 60,000 episodes. We report the mean accuracy and $9 5 \%$ confidence interval over 600 test experiments. In each test episode, $N$ classes are selected from the novel set, and for each class 5 support images and 16 query images (or 5 query images when using $20 \%$ labeled data) are used. We report results for $N = \{ 5 , 2 0 \}$ classes.
Image sampling and data augmentation Data augmentation has a significant impact on few-shot learning performance. We follow the data augmentation procedure outlined in Chen et al. (2019) which resulted in a strong baseline performance of meta-learning. For label and rotation predictions, images are first resized to 224 pixels for the shorter edge while maintaining the aspect ratio, from which a central crop of $2 2 4 \times 2 2 4$ is obtained. For jigsaw puzzles, we first randomly crop $2 5 5 \times 2 5 5$ region from the original image with random scaling between [0.5, 1.0], then split into $3 \times 3$ regions, from which a random crop of size $6 4 \times 6 4$ is picked. While it might appear that with self-supervision the model effectively sees more images, we wish to point out that all the experiments use significant data augmentation, including cropping, flipping, and color jittering, which also significantly increases the amount of training data. The gains from the self-supervised auxiliary tasks are over and above any gains from data augmentation alone. More experimental details are in Appendix A.5.
Other experimental results In Appendix A.3, we show the benefits of using self-supervision for standard classification tasks when training the model from scratch. We further visualize these models in Appendix A.4 to show that models trained with self-supervision tend to avoid accidental correlation of background features to class labels.
 Figure 2: Benefits of SSL for few-shot learning tasks. We show the accuracy over the ProtoNet baseline of using different SSL tasks. The jigsaw task results in an improvement of the 5-way 5-shot classification accuracy for a ProtoNet across datasets. Combining SSL tasks can be beneficial for some datasets. Here SSL was performed on images within the base classes only. See Table 2 in the Appendix for a tabular version and results for 20-way 5-shot classification.
 Figure 3: Benefits of SSL for harder few-shot learning tasks. We show the accuracy of using jigsaw puzzle task over ProtoNet baseline on harder versions of the datasets. We see that SSL is effective even on smaller datasets and the relative benefits are higher.
# 4.1 RESULTS ON FEW-SHOT LEARNING
Self-supervised learning improves few-shot learning Figure 2 shows the accuracies of various models for 5-way 5-shot classification on few-shot benchmarks. Our ProtoNet baseline matches the results of the mini-ImageNet and birds datasets presented in Chen et al. (2019) (in their Table A5). Our results show that jigsaw puzzle task improves the ProtoNet baseline on all seven datasets. Specifically, it reduces the relative error rate by $4 . 0 \%$ , $8 . 7 \%$ , $1 9 . 7 \%$ , $8 . 4 \%$ , $4 . 7 \%$ , $1 5 . 9 \%$ , and $2 7 . 8 \%$ on mini-ImageNet, tiered-ImageNet, birds, cars, aircrafts, dogs, and flowers datasets respectively. Predicting rotations also improves the ProtoNet baseline on most of the datasets, except for aircrafts and flowers. We speculate this is because most flower images are symmetrical, and airplanes are usually horizontal, making the rotation task too hard or too trivial to benefit main task. In addition, combining these two SSL tasks can be beneficial sometimes. Our results also echo those of Gidaris et al. (2019) who find that the rotation task improves on mini- and tiered-ImageNet. A tabular version of the figure and the results for 20-way classification are included in Table 2 in Appendix A.2.
Gains are larger for harder tasks Figure 3 shows the performance on the degraded version of the same datasets (first five groups). For cars and aircrafts we use low-resolution images where the images are down-sampled by a factor of four and up-sampled back to $2 2 4 \times 2 2 4$ with bilinear interpolation. For natural categories we discard color. Low-resolution images are considerably harder to classify for man-made categories while color information is most useful for natural categories (Su & Maji, 2017). On birds and dogs datasets, the improvements using self-supervision ( $3 . 2 \%$ and $2 . 9 \%$ on 5-way 5-shot) are higher compared to color images ( $2 . 5 \%$ and $2 . 7 \%$ ), similarly on the cars and aircrafts datasets with low-resolution images $2 . 2 \%$ and $2 . 1 \%$ vs. $0 . 7 \%$ and $0 . 4 \%$ ). We also conduct an experiment where only $20 \%$ of the images in the base categories are used for both SSL and meta-learning (last five groups in Figure 3). This results in a much smaller training set than standard few-shot benchmarks: $20 \%$ of the birds dataset amounts to only roughly $3 \%$ of the popular mini-ImageNet dataset. We find larger benefits from SSL in this setting. For example, the gain from the jigsaw puzzle loss for 5-way 5-shot car classification increases from $0 . 7 \%$ (original dataset) to $7 . 0 \%$ ( $20 \%$ training data).
 (d) Effectiveness of SSL as a function of domain distance between $\mathcal { D } _ { s }$ and $\mathcal { D } _ { s s }$ (shown on top) Figure 4: Effect of size and domain of SSL on 5-way 5-shot accuracy. (a) More unlabeled data from the same domain for SSL improves the performance of the meta-learner. $\mathbf { ( b ) }$ Replacing a fraction $\mathbf { \bar { X } }$ -axis) of the images with those from other domains makes SSL less effective. (c) A comparison of approaches to sample images from a pool for SSL. With random sampling, the extra unlabeled data often hurts the performance, while those sampled using the “domain weighs” improves performance on most datasets. When the pool contains images from related domains, e.g., birds and dogs, the performance using selected images matches that of using $100 \%$ within-dataset images. (d) Accuracy of the meta-learner with SSL on different domains as function of distance between the supervised domain $\mathcal { D } _ { s }$ and the self-supervised domain $\mathcal { D } _ { s s }$ . See text for details.
Improvements generalize to other meta-learners We combine SSL with other meta-learners and find the combination to be effective. In particular we use MAML (Finn et al., 2017) and a standard feature extractor trained with cross-entropy loss (softmax). We observe that the average 5-way 5- shot accuracies across five fine-grained datasets for softmax, MAML, and ProtoNet improve from $8 5 . 5 \%$ , $8 2 . 6 \%$ and $8 8 . 5 \%$ to $8 6 . 6 \%$ , $8 3 . 8 \%$ and $9 0 . 4 \%$ respectively when combined with the jigsaw puzzle task. Detailed results are shown in Table 4 in Appendix A.2.
Self-supervision alone is not enough SSL alone significantly lags behind supervised learning in our experiments. For example, a ResNet18 trained with SSL alone achieve $3 2 . 9 \%$ (w/ jigsaw) and $3 3 . 7 \%$ (w/ rotation) 5-way 5-shot accuracy averaged across five fine-grained datasets. While this is better than a random initialization $( 2 9 . 5 \% )$ , it is dramatically worse than one trained with a simple cross-entropy loss $( 8 5 . 5 \% )$ on the labels (Details in Table 2). Surprisingly, we found that initialization with SSL followed by meta-learning did not yield improvements over meta-learning starting from random initialization, supporting the view that SSL acts as a feature regularizer.
# 4.2 SELECTING DOMAINS FOR SELF-SUPERVISION
A promising direction of research in SSL is by scaling it to massive unlabeled datasets which are readily available for some domains. However, does more unlabeled data always help for a task in hand? This question hasn’t been sufficiently addressed in the literature as most prior works study the effectiveness of SSL on a curated set of images, such as ImageNet, and their transferability to a handful of tasks. In this section we conduct a series of experiments to characterize effect of size and distribution $\mathcal { D } _ { s s }$ of images used for SSL in the context of few-shot learning on a domain $\mathcal { D } _ { s }$ .
First we investigate if SSL on unlabeled data from the same domain improves the meta-learner. We use $20 \%$ of the images in the base categories for meta-learning identical to setting in Figure 3. The labels of the remaining $80 \%$ data are withheld and only the images are used for SSL. We systematically vary the number of images used by the SSL from $20 \%$ to $100 \%$ . Results are presented in Figure 4a. The accuracy improves with the size of the unlabeled set with diminishing returns. Note that $0 \%$ corresponds to no SSL and $20 \%$ corresponds to using only the labeled images for SSL.
Figure $\cdot$ shows an experiment where a fraction of the unlabeled images are replaced with images from other datasets. For example $20 \%$ along the $\mathbf { X }$ -axis for birds indicate that $20 \%$ of the images in base set are replaced by images drawn uniformly at random from other datasets. Since the number of images used for SSL are identical, the $\mathbf { X }$ -axis from left to right represents increasing amounts of domain shifts between $\mathcal { D } _ { s }$ and $\mathcal { D } _ { s s }$ . We observe that the effectiveness of SSL decreases as the fraction of out-of-domain images increases. Importantly, training with SSL on the available $20 \%$ within domain images (shown as crosses) is often (3 out of 5 datasets) better than increasing the set of images by five times to include out of domain images.
Figure 4d analyzes how the magnitude of the domain shift affects performance. Here all the images in base classes are used (instead of using $20 \%$ data in previous experiment), and all the images for SSL are sampled from different datasets. In addition to the five datasets (birds, cars, aircrafts, dogs, flowers), we include 1) 5000 images of Aves from iNaturalist 2018 dataset (iNat) (Van Horn et al., 2018), 2) 5000 images of other super-classes from iNat, and 3) 5760 images sampled from miniImageNet. These domains are roughly of the same sizes (between $5 \mathrm { k }$ to 10k images each) but exhibit varying degrees of domain shifts. To compute a “distance” between a pair of domains, we first estimate an embedding for each domain $\mathcal { D }$ using the mean image feature: $\begin{array} { r } { \Phi ( { \mathcal { D } } ) = \sum _ { x _ { i } \in { \mathcal { D } } } \phi ( x _ { i } ) / N } \end{array}$ , where $N$ is the number of images within $\mathcal { D }$ , and use the Euclidean distance between their embeddings. Here $\phi ( x )$ is an image embedding from a ResNet101 network pretrained on ImageNet. Figure 4d shows the accuracy of the meta-learner when combined with SSL on different domains as a function of the domain distance between $\mathcal { D } _ { s }$ and $\mathcal { D } _ { s s }$ . Once again we see that the effectiveness of SSL decreases with the distance from the supervised domain across all datasets.
Based on the above analysis we propose a simple method to select images for SSL from a large, generic pool of unlabeled images in a dataset dependent manner. We use a “domain weighted” model to select the top images based on a domain classifier, in our case a binary logistic regression model trained with images from the source domain $\mathcal { D } _ { s }$ as the positive class and from pool $\mathcal { D } _ { p }$ as the negative class based on ResNet101 image features. The top images are selected according to the ratio $\bar { p ( x \in \mathcal { D } _ { s } ) / p ( x \in \mathcal { D } _ { p } ) }$ . Note that these importance weights account for the domain shift. We evaluate this approach using a pool of images from all five datasets as well as 30000 images each from Aves of iNat, other super-classes of iNat and mini-ImageNet. For each dataset we use $20 \%$ of the labeled images for meta-learning, then use the pool in a leave-one-out manner: all images from a dataset are excluded from the pool to simulate a scenario where one does not have additional within-domain images. The compositions of the selected images are shown in Appendix A.6.
Figure 4c shows results across datasets with meta-learner trained on $20 \%$ labeled examples. SSL with $20 \%$ and $100 \%$ dataset denotes baselines when SSL uses $20 \%$ and $100 \%$ of the images within domain. The latter is a reference “upper bound”. SSL pool “(random)” and “(weight)” denote two approaches for selecting the remaining $80 \%$ of images from the pool. The former selects images uniformly at random, which is detrimental for cars, dogs, and flowers. For dogs the performance is even worse than no SSL. The pool selected according to the importance weights provides significant improvements on birds and dogs as the pool has relevant images, and outperforms the random selection on most datasets. These results are likely to improve by collecting an even larger pool.
# 5 CONCLUSION
We have shown that self-supervision improves transferability of representations on few-shot learning tasks across a range of different domains. Surprisingly, we found that self-supervision is more beneficial for more challenging problems, especially when the number of images used for selfsupervision is small, orders of magnitude smaller than previously reported results. This has a practical benefit that the images within small datasets can be used for self-supervision without relying on a large-scale external dataset. We have also shown that additional unlabeled images can improve performance only if they are from the same or similar domains. Finally, for domains where unlabeled data is limited, we present a novel, simple approach to automatically identify such similar-domain images from a larger pool.
# REFERENCES
Yuki M Asano, Christian Rupprecht, and Andrea Vedaldi. Surprising effectiveness of few-image unsupervised feature learning. arXiv preprint arXiv:1904.13132, 2019. 3
Philip Bachman, R Devon Hjelm, and William Buchwalter. Learning representations by maximizing mutual information across views. arXiv preprint arXiv:1906.00910, 2019. 2
Luca Bertinetto, Joao F Henriques, Philip HS Torr, and Andrea Vedaldi. Meta-learning with differentiable closed-form solvers. International Conference on Learning Representations (ICLR), 2019. 2
Piotr Bojanowski and Armand Joulin. Unsupervised learning by predicting noise. In International Conference on Machine Learning (ICML), 2017. 2
Fabio M Carlucci, Antonio D’Innocente, Silvia Bucci, Barbara Caputo, and Tatiana Tommasi. Domain generalization by solving jigsaw puzzles. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2019. 3
Mathilde Caron, Piotr Bojanowski, Armand Joulin, and Matthijs Douze. Deep clustering for unsupervised learning of visual features. In European Conference on Computer Vision (ECCV), 2018. 2
Mathilde Caron, Piotr Bojanowski, Julien Mairal, and Armand Joulin. Leveraging large-scale uncurated data for unsupervised pre-training of visual features. arXiv preprint arXiv:1905.01278, 2019. 2
Wei-Yu Chen, Yen-Cheng Liu, Zsolt Kira, Yu-Chiang Wang, and Jia-Bin Huang. A Closer Look at Few-shot Classification. In International Conference on Learning Representations (ICLR), 2019. 2, 5, 6, 15
Zhao Chen, Vijay Badrinarayanan, Chen-Yu Lee, and Andrew Rabinovich. Gradnorm: Gradient normalization for adaptive loss balancing in deep multitask networks. In International Conference on Machine Learning (ICML), 2018. 5
Carl Doersch and Andrew Zisserman. Multi-task self-supervised visual learning. In International Conference on Computer Vision (ICCV), 2017. 2
Carl Doersch, Abhinav Gupta, and Alexei A Efros. Unsupervised visual representation learning by context prediction. In International Conference on Computer Vision (ICCV), 2015. 2
Jeff Donahue and Karen Simonyan. Large scale adversarial representation learning. arXiv preprint arXiv:1907.02544, 2019. 2
Chelsea Finn, Pieter Abbeel, and Sergey Levine. Model-agnostic meta-learning for fast adaptation of deep networks. In International Conference on Machine Learning (ICML), 2017. 2, 4, 5, 7
Victor Garcia and Joan Bruna. Few-shot learning with graph neural networks. In International Conference on Learning Representations (ICLR), 2018. 2
Spyros Gidaris and Nikos Komodakis. Dynamic few-shot visual learning without forgetting. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2018. 2
Spyros Gidaris, Praveer Singh, and Nikos Komodakis. Unsupervised representation learning by predicting image rotations. In International Conference on Learning Representations (ICLR), 2018. 2, 4
Spyros Gidaris, Andrei Bursuc, Nikos Komodakis, Patrick Perez, and Matthieu Cord. Boosting ´ few-shot visual learning with self-supervision. arXiv preprint arXiv:1906.05186, 2019. 3, 6
Priya Goyal, Dhruv Mahajan, Abhinav Gupta, and Ishan Misra. Scaling and benchmarking selfsupervised visual representation learning. arXiv preprint arXiv:1905.01235, 2019. 2, 4
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Computer Vision and Pattern Recognition (CVPR), 2016. 5
Olivier J Henaff, Ali Razavi, Carl Doersch, SM Eslami, and Aaron van den Oord. Data-efficient ´ image recognition with contrastive predictive coding. arXiv preprint arXiv:1905.09272, 2019. 2
R Devon Hjelm, Alex Fedorov, Samuel Lavoie-Marchildon, Karan Grewal, Phil Bachman, Adam Trischler, and Yoshua Bengio. Learning deep representations by mutual information estimation and maximization. In International Conference on Learning Representations (ICLR), 2019. 2
Simon Jenni and Paolo Favaro. Self-supervised feature learning by learning to spot artifacts. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2018. 2
Alex Kendall, Yarin Gal, and Roberto Cipolla. Multi-task learning using uncertainty to weigh losses for scene geometry and semantics. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2018. 5
Aditya Khosla, Nityananda Jayadevaprakash, Bangpeng Yao, and Li Fei-Fei. Novel dataset for finegrained image categorization. In First Workshop on Fine-Grained Visual Categorization, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2011. 5
Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In International Conference on Learning Representations (ICLR), 2015. 5
Gregory Koch, Richard Zemel, and Ruslan Salakhutdinov. Siamese neural networks for one-shot image recognition. In ICML deep learning workshop, volume 2, 2015. 4
Iasonas Kokkinos. Ubernet: Training a universal convolutional neural network for low-, mid-, and high-level vision using diverse datasets and limited memory. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017. 3
Alexander Kolesnikov, Xiaohua Zhai, and Lucas Beyer. Revisiting self-supervised visual representation learning. arXiv preprint arXiv:1901.09005, 2019. 2
Jonathan Krause, Michael Stark, Jia Deng, and Li Fei-Fei. 3D Object Representations for FineGrained Categorization. In 4th International IEEE Workshop on 3D Representation and Recognition (3dRR-13), Sydney, Australia, 2013. 5
Gustav Larsson, Michael Maire, and Gregory Shakhnarovich. Learning representations for automatic colorization. In European Conference on Computer Vision (ECCV), 2016. 2
Kwonjoon Lee, Subhransu Maji, Avinash Ravichandran, and Stefano Soatto. Meta-learning with differentiable convex optimization. In Computer Vision and Pattern Recognition (CVPR), 2019. 2
Subhransu Maji, Esa Rahtu, Juho Kannala, Matthew Blaschko, and Andrea Vedaldi. Fine-grained visual classification of aircraft. arXiv preprint arXiv:1306.5151, 2013. 5
Kevis-Kokitsi Maninis, Ilija Radosavovic, and Iasonas Kokkinos. Attentive single-tasking of multiple tasks. arXiv preprint arXiv:1904.08918, 2019. 3
M-E. Nilsback and A. Zisserman. A visual vocabulary for flower classification. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), volume 2, 2006. 5
Mehdi Noroozi and Paolo Favaro. Unsupervised learning of visual representations by solving jigsaw puzzles. In European Conference on Computer Vision (ECCV), 2016. 4, 15
Mehdi Noroozi, Hamed Pirsiavash, and Paolo Favaro. Representation learning by learning to count. In Proceedings of the IEEE International Conference on Computer Vision (ICCV), 2017. 2
Aaron van den Oord, Yazhe Li, and Oriol Vinyals. Representation learning with contrastive predictive coding. arXiv preprint arXiv:1807.03748, 2018. 2
Adam Paszke, Sam Gross, Soumith Chintala, Gregory Chanan, Edward Yang, Zachary DeVito, Zeming Lin, Alban Desmaison, Luca Antiga, and Adam Lerer. Automatic differentiation in pytorch. In NeurIPS Autodiff Workshop, 2017. 15
Deepak Pathak, Philipp Krahenb ¨ uhl, Jeff Donahue, Trevor Darrell, and Alexei A. Efros. Context ¨ encoders: Feature learning by inpainting. In Computer Vision and Pattern Recognition (CVPR), 2016. 2
Deepak Pathak, Ross B. Girshick, Piotr Dollar, Trevor Darrell, and Bharath Hariharan. Learning ´ features by watching objects move. In Computer Vision and Pattern Recognition (CVPR), 2017. 2
Hang Qi, Matthew Brown, and David G Lowe. Low-shot learning with imprinted weights. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2018. 2
Siyuan Qiao, Chenxi Liu, Wei Shen, and Alan L Yuille. Few-shot image recognition by predicting parameters from activations. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2018. 2
Sachin Ravi and Hugo Larochelle. Optimization as a model for few-shot learning. In International Conference on Learning Representations (ICLR), 2017. 2
Mengye Ren, Eleni Triantafillou, Sachin Ravi, Jake Snell, Kevin Swersky, Joshua B Tenenbaum, Hugo Larochelle, and Richard S Zemel. Meta-learning for semi-supervised few-shot classification. International Conference on Learning Representations (ICLR), 2018. 5
Zhongzheng Ren and Yong Jae Lee. Cross-domain self-supervised multi-task feature learning using synthetic imagery. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2018. 3
Ozan Sener and Vladlen Koltun. Multi-task learning as multi-objective optimization. In Advances in Neural Information Processing Systems (NeurIPS), 2018. 5
Jake Snell, Kevin Swersky, and Richard Zemel. Prototypical networks for few-shot learning. In Advances in Neural Information Processing Systems (NeurIPS), 2017. 2, 4, 5
Jong-Chyi Su and Subhransu Maji. Adapting models to signal degradation using distillation. In British Machine Vision Conference (BMVC), 2017. 6
Trieu H Trinh, Minh-Thang Luong, and Quoc V Le. Selfie: Self-supervised pretraining for image embedding. arXiv preprint arXiv:1906.02940, 2019. 2
Grant Van Horn, Oisin Mac Aodha, Yang Song, Yin Cui, Chen Sun, Alex Shepard, Hartwig Adam, Pietro Perona, and Serge Belongie. The inaturalist species classification and detection dataset. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2018. 8
Oriol Vinyals, Charles Blundell, Timothy Lillicrap, Daan Wierstra, et al. Matching networks for one shot learning. In Advances in neural information processing systems (NeurIPS), 2016. 2, 4, 5
Xiaolong Wang and Abhinav Gupta. Unsupervised learning of visual representations using videos. In International Conference on Computer Vision (ICCV), 2015. 2
Xiaolong Wang, Kaiming He, and Abhinav Gupta. Transitive invariance for self-supervised visual representation learning. In International Conference on Computer Vision (ICCV), 2017. 2
P. Welinder, S. Branson, T. Mita, C. Wah, F. Schroff, S. Belongie, and P. Perona. Caltech-UCSD Birds 200. Technical Report CNS-TR-2010-001, California Institute of Technology, 2010. 3, 5
Davis Wertheimer and Bharath Hariharan. Few-shot learning with localization in realistic settings. In Computer Vision and Pattern Recognition (CVPR), 2019. 14
Zhirong Wu, Yuanjun Xiong, Stella X. Yu, and Dahua Lin. Unsupervised feature learning via nonparametric instance discrimination. In Computer Vision and Pattern Recognition (CVPR), 2018. 2
Richard Zhang, Phillip Isola, and Alexei A Efros. Colorful image colorization. In European Conference on Computer Vision (ECCV), 2016. 2
Richard Zhang, Phillip Isola, and Alexei A Efros. Split-brain autoencoders: Unsupervised learning by cross-channel prediction. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017. 2
# A APPENDIX
# A.1 DATASET DETAILS
The statistics of various datasets used in our experiments are shown in Table 1. We show results on several fine-grained classification datasets in addition to standard few-shot benchmarks such as mini- and tiered-ImageNet. Notably, the fine-grained datasets are significantly smaller.
<table><tr><td rowspan=1 colspan=18>Birds Cars Aircrafts Dogs Flowers</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=2></td><td rowspan=1 colspan=2></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=2></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>*</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=2></td><td rowspan=1 colspan=8></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1></td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td rowspan=1 colspan=2>福</td><td rowspan=6 colspan=1></td></tr><tr><td></td><td></td><td></td><td></td><td></td><td></td><td rowspan=1 colspan=2>mini-ImageNet</td><td rowspan=1 colspan=2>tiered-ImageNet</td><td rowspan=1 colspan=1>Birds</td><td rowspan=1 colspan=1>Cars</td><td></td><td rowspan=1 colspan=2>Aircrafts</td><td rowspan=1 colspan=1>Dogs</td><td rowspan=1 colspan=2>Flowers</td></tr><tr><td></td><td></td><td rowspan=1 colspan=2>Base</td><td rowspan=1 colspan=2>#class#images</td><td rowspan=1 colspan=2>6438,400</td><td rowspan=1 colspan=2>351448,695</td><td rowspan=1 colspan=1>1005885</td><td rowspan=1 colspan=1>988162</td><td></td><td rowspan=1 colspan=2>505000</td><td rowspan=1 colspan=1>6010337</td><td rowspan=1 colspan=2>514129</td></tr><tr><td></td><td></td><td rowspan=1 colspan=2>Val</td><td rowspan=1 colspan=2>#class#images</td><td rowspan=1 colspan=2>169,600</td><td rowspan=1 colspan=2>97124,261</td><td rowspan=1 colspan=1>502950</td><td rowspan=1 colspan=1>493993</td><td></td><td rowspan=1 colspan=2>252500</td><td rowspan=1 colspan=1>305128</td><td rowspan=1 colspan=2>262113</td></tr><tr><td></td><td></td><td rowspan=2 colspan=2>Novel</td><td rowspan=2 colspan=2>#class#images</td><td rowspan=2 colspan=2>2012.000</td><td rowspan=2 colspan=2>160206,209</td><td rowspan=2 colspan=1>502953</td><td rowspan=1 colspan=1>49</td><td></td><td rowspan=1 colspan=2>25</td><td rowspan=1 colspan=1>30</td><td rowspan=1 colspan=2>25</td></tr><tr><td></td><td></td><td rowspan=1 colspan=1>4030</td><td></td><td rowspan=1 colspan=2>2500</td><td rowspan=1 colspan=1>5115</td><td rowspan=1 colspan=2>1947</td></tr></table>
Table 1: Example images and dataset statistics. For few-shot learning experiments the classes are split into base, val, and novel set. Image representations learned on base set are evaluated on the novel set while val set is used for cross-validation. These datasets vary in the number of classes but are orders of magnitude smaller than ImageNet dataset.
# A.2 RESULTS ON FEW-SHOT LEARNING
Table 2 shows the performance of ProtoNet with different self-supervision on seven datasets. We also test the accuracy of the model on novel classes when trained only with self-supervision on the base set of images. Compared to the randomly initialized model (“None” rows), training the network to predict rotations gives around $2 \%$ to $21 \%$ improvements on all datasets, while solving jigsaw puzzles only improves on aircrafts and flowers. However, these numbers are significantly worse than learning with supervised labels on the base set, in line with the current literature.
Table 3 shows the performance of ProtoNet with jigsaw puzzle loss on harder benchmarks. The results on degraded version of the datasets are shown in the top part, and the bottom part shows the results of using only $20 \%$ of the images in the base categories. The gains using SSL are higher in this setting.
Table 4 compares meta-learners based on a ResNet18 network trained with and without jigsaw puzzle loss. Self-supervision improves the performance across different meta-learners and different datasets. ProtoNet trained with self-supervision is the best model across all datasets.
Table 2: Performance on few-shot transfer task. The mean accuracy $( \% )$ and the $9 5 \%$ confidence interval of 600 randomly chosen test experiments are reported for various combinations of loss functions. The top part shows the accuracy on 5-way 5-shot classification tasks, while the bottom part shows the same on 20-way 5-shot. Adding self-supervised losses to the ProtoNet loss improves the performance on all seven datasets on 5-way classification results. On 20-way classification, the improvements are even larger. The last row indicates results with a randomly initialized network. The top part of this table corresponds to Figure 2.
<table><tr><td rowspan=2 colspan=4>Loss</td><td rowspan=1 colspan=1>mini-ImageNet</td><td rowspan=1 colspan=1>tiered-ImageNet</td><td rowspan=1 colspan=1>Birds</td><td rowspan=1 colspan=1>Cars</td><td rowspan=1 colspan=1>Aircrafts</td><td rowspan=1 colspan=1>Dogs</td><td rowspan=1 colspan=1>Flowers</td></tr><tr><td rowspan=1 colspan=7> 5-way 5-shot</td></tr><tr><td rowspan=1 colspan=4>ProtoNet</td><td rowspan=1 colspan=1>75.2±0.6</td><td rowspan=1 colspan=1>75.9±0.7</td><td rowspan=1 colspan=1>87.3±0.5</td><td rowspan=1 colspan=1>91.7±0.4</td><td rowspan=1 colspan=1>91.4±0.4</td><td rowspan=1 colspan=1>83.0±0.6</td><td rowspan=1 colspan=1>89.2±0.6</td></tr><tr><td rowspan=1 colspan=4>ProtoNet + JigsawRel. error reduction</td><td rowspan=1 colspan=1>76.2±0.64.0%</td><td rowspan=1 colspan=1>78.0±0.78.7%</td><td rowspan=1 colspan=1>89.8±0.419.7%</td><td rowspan=1 colspan=1>92.4±0.48.4%</td><td rowspan=1 colspan=1>91.8±0.44.7%</td><td rowspan=1 colspan=1>85.7±0.515.9%</td><td rowspan=1 colspan=1>92.2±0.427.8%</td></tr><tr><td rowspan=1 colspan=2>J</td><td rowspan=1 colspan=1>1。</td><td rowspan=1 colspan=1>Jigsaw</td><td rowspan=1 colspan=1>25.6±0.5</td><td rowspan=1 colspan=1>24.9±0.4</td><td rowspan=1 colspan=1>25.7±0.5</td><td rowspan=1 colspan=1>25.3±0.5</td><td rowspan=1 colspan=1>38.8±0.6</td><td rowspan=1 colspan=1>24.3±0.5</td><td rowspan=1 colspan=1>50.5±0.7</td></tr><tr><td rowspan=1 colspan=4>ProtoNet+Rotation</td><td rowspan=1 colspan=1>76.0±0.6</td><td rowspan=1 colspan=1>78.9±0.7</td><td rowspan=1 colspan=1>89.4±0.4</td><td rowspan=1 colspan=1>92.3±0.4</td><td rowspan=1 colspan=1>91.4±0.4</td><td rowspan=2 colspan=1>84.3±0.527.3±0.5</td><td rowspan=2 colspan=1>89.0±0.549.4±0.7</td></tr><tr><td rowspan=2 colspan=4>RotationProtoNet + Jig. + Rot.</td><td rowspan=1 colspan=1>51.4±0.7</td><td rowspan=1 colspan=1>50.7±0.8</td><td rowspan=1 colspan=1>33.1±0.6</td><td rowspan=1 colspan=1>29.4±0.5</td><td rowspan=1 colspan=1>29.5±0.5</td></tr><tr><td rowspan=1 colspan=1>76.6±0.7</td><td rowspan=1 colspan=1>77.2±0.7</td><td rowspan=1 colspan=1>90.2±0.4</td><td rowspan=1 colspan=1>92.7±0.4</td><td rowspan=1 colspan=1>91.9±0.4</td><td rowspan=1 colspan=1>85.9±0.5</td><td rowspan=1 colspan=1>91.4±0.5</td></tr><tr><td rowspan=1 colspan=4>None</td><td rowspan=1 colspan=1>31.0±0.5</td><td rowspan=1 colspan=1>28.9±0.5</td><td rowspan=1 colspan=1>26.7±0.5</td><td rowspan=1 colspan=1>25.2±0.5</td><td rowspan=1 colspan=1>28.1±0.5</td><td rowspan=1 colspan=1>25.3±0.5</td><td rowspan=1 colspan=1>42.3±0.8</td></tr><tr><td rowspan=1 colspan=4></td><td rowspan=1 colspan=7>20-way 5-shot</td></tr><tr><td rowspan=1 colspan=4>ProtoNet</td><td rowspan=1 colspan=1>46.6±0.3</td><td rowspan=1 colspan=1>49.7±0.4</td><td rowspan=1 colspan=1>69.3±0.3</td><td rowspan=1 colspan=1>78.7±0.3</td><td rowspan=1 colspan=1>78.6±0.3</td><td rowspan=1 colspan=1>61.6±0.3</td><td rowspan=1 colspan=1>75.4±0.3</td></tr><tr><td rowspan=1 colspan=4>ProtoNet + Jigsaw</td><td rowspan=1 colspan=1>47.8±0.3</td><td rowspan=1 colspan=1>52.4±0.4</td><td rowspan=1 colspan=1>73.7±0.3</td><td rowspan=1 colspan=1>79.1±0.3</td><td rowspan=1 colspan=1>79.1±0.2</td><td rowspan=1 colspan=1>65.4±0.3</td><td rowspan=1 colspan=1>79.2±0.3</td></tr><tr><td rowspan=2 colspan=4>JigsawProtoNet + Rotation</td><td rowspan=1 colspan=1>9.2±0.2</td><td rowspan=1 colspan=1>7.5±0.1</td><td rowspan=1 colspan=1>8.1±0.1</td><td rowspan=1 colspan=1>7.1±0.1</td><td rowspan=1 colspan=1>15.4±0.2</td><td rowspan=1 colspan=1>7.1±0.1</td><td rowspan=1 colspan=1>25.7±0.2</td></tr><tr><td rowspan=1 colspan=1>48.2±0.3</td><td rowspan=1 colspan=1>52.4±0.4</td><td rowspan=1 colspan=1>72.9±0.3</td><td rowspan=1 colspan=1>80.0±0.3</td><td rowspan=1 colspan=1>78.4±0.2</td><td rowspan=1 colspan=1>63.4±0.3</td><td rowspan=1 colspan=1>73.9±0.3</td></tr><tr><td rowspan=2 colspan=4>RotationProtoNet + Jig.+ Rot.</td><td rowspan=1 colspan=1>27.4±0.2</td><td rowspan=1 colspan=1>25.7±0.3</td><td rowspan=1 colspan=1>12.9±0.2</td><td rowspan=1 colspan=1>9.3±0.2</td><td rowspan=1 colspan=1>9.8±0.2</td><td rowspan=1 colspan=1>8.8±0.1</td><td rowspan=1 colspan=1>26.3±0.2</td></tr><tr><td rowspan=1 colspan=1>49.0±0.3</td><td rowspan=1 colspan=1>51.2±0.4</td><td rowspan=1 colspan=1>75.0±0.3</td><td rowspan=1 colspan=1>79.8±0.3</td><td rowspan=1 colspan=1>79.0±0.2</td><td rowspan=1 colspan=1>66.2±0.3</td><td rowspan=1 colspan=1>78.6±0.3</td></tr><tr><td rowspan=1 colspan=4>None</td><td rowspan=1 colspan=1>10.8±0.1</td><td rowspan=1 colspan=1>11.0±0.2</td><td rowspan=1 colspan=1>9.3±0.2</td><td rowspan=1 colspan=1>7.5±0.1</td><td rowspan=1 colspan=1>8.9±0.1</td><td rowspan=1 colspan=1>7.8±0.1</td><td rowspan=1 colspan=1>22.6±0.2</td></tr></table>
Table 3: Performance on few-shot transfer task with degraded inputs or less training data. Accuracies are reported on novel set for 5-way 5-shot and 20-way 5-shot classification with degraded inputs, and with a subset $( 2 0 \% )$ of the images in the base set. The loss of color or resolution, and the smaller training set size make the tasks more challenging as seen by the drop in the performance of the ProtoNet baseline. However the improvements of using the jigsaw puzzle loss are higher in comparison to the results presented in Table 2.
<table><tr><td>Loss</td><td>Birds Greyscale</td><td>Cars Low-resolution</td><td>Aircrafts Low-resolution</td><td>Dogs Greyscale</td><td>Flowers Greyscale</td></tr><tr><td></td><td colspan="5">5-way 5-shot</td></tr><tr><td>ProtoNet</td><td>82.2±0.6</td><td>84.8±0.5</td><td>85.0±0.5</td><td>80.7±0.6</td><td>86.1±0.6</td></tr><tr><td>ProtoNet + Jigsaw</td><td>85.4±0.6</td><td>87.0±0.5</td><td>87.1±0.5</td><td>83.6±0.5</td><td>87.6±0.5</td></tr><tr><td>ProtoNet</td><td>64.7±0.3</td><td></td><td>20-way 5-shot 64.1±0.3</td><td>57.4±0.3</td><td>69.7±0.3</td></tr><tr><td>ProtoNet + Jigsaw</td><td>60.8±0.4 65.7±0.3</td><td>68.6±0.3</td><td>68.3±0.3</td><td>61.2±0.3</td><td>71.6±0.3</td></tr><tr><td>Loss</td><td>20% Birds</td><td>20% Cars</td><td>20% Aircrafts</td><td>20% Dogs</td><td>20% Flowers</td></tr><tr><td></td><td colspan="5">5-way 5-shot</td></tr><tr><td>ProtoNet</td><td>73.0±0.7</td><td>75.8±0.7</td><td>77.7±0.6</td><td>68.5±0.7</td><td>82.2±0.7</td></tr><tr><td>ProtoNet + Jigsaw</td><td>75.4±0.7</td><td>82.8±0.6</td><td>78.4±0.6</td><td>69.1±0.7</td><td>86.0±0.6</td></tr><tr><td></td><td colspan="5">20-way 5-shot</td></tr><tr><td>ProtoNet</td><td>46.4±0.3</td><td>51.8±0.4</td><td>52.3±0.3</td><td>40.8±0.3</td><td>62.8±0.3</td></tr><tr><td>ProtoNet + Jigsaw</td><td>49.8±0.3</td><td>61.5±0.4</td><td>53.6±0.3</td><td>42.2±0.3</td><td>68.5±0.3</td></tr></table>
Table 4: Performance on few-shot transfer task using different meta-learners. Using jigsaw puzzle loss gives improvements across different meta-learners on most of the datasets. ProtoNet with jigsaw loss performs the best on all five datasets.
<table><tr><td rowspan="2">Loss</td><td>Birds</td><td>Cars</td><td>Aircrafts</td><td>Dogs</td><td>Flowers</td></tr><tr><td colspan="4">5-way 5-shot</td></tr><tr><td>Softmax</td><td>81.5±0.5</td><td>87.7±0.5</td><td>89.2±0.4</td><td>77.6±0.6</td><td>91.3±0.5</td></tr><tr><td>Softmax + Jigsaw</td><td>83.9±0.5</td><td>90.6±0.5</td><td>89.6±0.4</td><td>77.8±0.6</td><td>90.9±0.5</td></tr><tr><td>MAML</td><td>81.2±0.7</td><td>86.9±0.6</td><td>88.8±0.5</td><td>77.3±0.7</td><td>79.0±0.9</td></tr><tr><td>MAML + Jigsaw</td><td>81.1±0.7</td><td>89.0±0.5</td><td>89.1±0.5</td><td>77.3±0.7</td><td>82.6±0.7</td></tr><tr><td>ProtoNet</td><td>87.3±0.5</td><td>91.7±0.4</td><td>91.4±0.4</td><td>83.0±0.6</td><td>89.2±0.6</td></tr><tr><td>ProtoNet + Jigsaw</td><td>89.8±0.4</td><td>92.4±0.4</td><td>91.8±0.4</td><td>85.7±0.5</td><td>92.2±0.4</td></tr></table>
# A.3 RESULTS ON STANDARD FINE-GRAINED CLASSIFICATION
Here we present results on standard classification task. Different from few-shot transfer learning, all the classes are seen in the training set and test set contains novel images from the same classes. We use the standard training and test splits provided in the datasets. We investigate if SSL can improve training of deep networks (e.g. ResNet18 network) when trained from scratch (i.e. with random initialization) using images and labels in the training set only. The accuracy using various loss functions are shown in Table 5. Training with self-supervision improves performance across datasets. On birds, cars, and dogs, predicting rotation gives $4 . 1 \%$ , $3 . 1 \%$ , and $3 . 0 \%$ improvements, while on aircrafts and flowers, the jigsaw puzzle loss yields $0 . 9 \%$ and $3 . 6 \%$ improvements.
Table 5: Performance on standard classification task. Per-image accuracy $( \% )$ on the test set are reported. Using self-supervision improves the accuracy of a ResNet18 network trained from scratch over the baseline of supervised training with cross-entropy (softmax) loss on all five datasets.
<table><tr><td>Loss</td><td>Birds</td><td>Cars</td><td>Aircrafts</td><td>Dogs</td><td>Flowers</td></tr><tr><td>Softmax</td><td>47.0</td><td>72.6</td><td>69.9</td><td>51.4</td><td>72.8</td></tr><tr><td>Softmax + Jigsaw</td><td>49.2</td><td>73.2</td><td>70.8</td><td>53.5</td><td>76.4</td></tr><tr><td>Softmax + Rotation</td><td>51.1</td><td>75.7</td><td>70.0</td><td>54.4</td><td>73.5</td></tr></table>
# A.4 VISUALIZATION OF LEARNED MODELS
To understand why the representation generalizes, we visualize what pixels contribute the most to the correct classification for various models. In particular, for each image and model we compute the gradient of the logits (predictions before softmax) for the correct class with respect to the input image. The magnitude of the gradient at each pixel is a proxy for its importance and is visualized as “saliency maps”. Figure 5 shows these maps for various images and models trained with and without self-supervision on the standard classification task. It appears that the self-supervised models tend to focus more on the foreground regions, as seen by the amount of bright pixels within the bounding box. One hypothesis is that self-supervised tasks force the model to rely less on background features, which might be accidentally correlated to the class labels. For fine-grained recognition, localization indeed improves performance when training from few examples (see Wertheimer & Hariharan (2019) for a contemporary evaluation of the role of localization for few-shot learning).
# A.5 EXPERIMENTAL DETAILS
Additional optimization details on few-shot learning During training, especially for jigsaw puzzle task, we found it to be beneficial to not track the running mean and variance for the batch normalization layer, and instead estimate them for each batch independently. We hypothesize that this is because the inputs contain both full-sized images and small patches, which might have different statistics. At test time we do the same. We found the accuracy goes up as the batch size increases but saturates at size of 64.
 Figure 5: Saliency maps for various images and models. For each image we visualize the magnitude of the gradient with respect to the correct class for models trained with various loss functions. The magnitudes are scaled to the same range for easier visualization. The models trained with selfsupervision often have lower energy on the background regions when there is clutter. We highlight a few examples with blue borders and the bounding-box of the object for each image is shown in red.
When training with supervised and self-supervised loss, a trade-off term $\lambda$ between the losses can be used, thus the total loss is $\mathcal { L } = ( 1 - \lambda ) \bar { \mathcal { L } } _ { s } + \lambda \mathcal { L } _ { s s }$ . We find that simply use $\lambda = 0 . 5$ works the best, except for training on mini- and tiered-ImageNet with jigsaw loss, where we set $\lambda = 0 . 3$ . We suspect that this is because the variation of the image size and the categories are higher, making the self-supervision harder to train with limited data. When both jigsaw and rotation losses are used, we set $\lambda = 0 . 5$ and the two self-supervised losses are averaged for $\mathcal { L } _ { s s }$ .
For training meta-learners, we use 16 query images per class for each training episode. When only $20 \%$ of labeled data are used, 5 query images per class are used. For MAML, we use 10 query images and the approximation method for backpropagation as proposed in Chen et al. (2019) to reduce the GPU memory usage. When training with self-supervised loss, it is added when computing the loss in the outer loop. We use PyTorch (Paszke et al., 2017) for our experiments.
For the domain classifier, we first obtain features from the penultimate-layer (2048 dimensional) from a ResNet101 model pretrained on ImageNet. We then train a binary logistic regression model with weight decay using LBFGS for 1000 iterations. The images from labeled dataset are the positive class and images from pool are the negative. A loss for the positive class is scaled by the inverse of its frequency to account for the significantly larger number of negative examples.
Optimization details for standard classification For standard classification (Appendix A.3) we train a ResNet18 network from scratch. All the models are trained with ADAM optimizer with a learning rate of 0.001 for 600 epochs with a batch size of 16. We track the running statistics for the batch normalization layer for the softmax baselines following the conventional setting, i.e. w/o self-supervised loss, but do not track these statistics when training with self-supervision.
Architectures for self-supervised tasks For jigsaw puzzle task, we follow the architecture of Noroozi & Favaro (2016) where it was first proposed. The ResNet18 results in a 512-dimensional feature for each input, and we add a fully-connected (fc) layer with 512-units on top. The nine patches gives nine 512-dimensional feature vectors, which are concatenated. This is followed by a fc layer, projecting the feature vector from 4608 to 4096 dimensions, and a fc layer with 35- dimensional outputs corresponding to the 35 permutations for the jigsaw task.
For the rotation task, the 512-dimensional output of ResNet18 is passed through three fc layers with $\{ 5 1 2 , 1 2 8 , 1 2 8 , 4 \}$ units. The predictions correspond to the four rotation angles. Between each $\pounds _ { C }$ layer, a ReLU activation and a dropout layer with dropout probability of 0.5 are added.
# A.6 DETAILS OF THE DATASET SELECTED FROM POOL
Table 6 describes the composition of the unlabeled images sampled from a generic pool for SSL experiments presented in Section 4.2 (Figure 4c). “Random sampling” uniformly samples images proportional to the size of each dataset, while the “domain weighted” one tends to pick more images from related domains. This is also indicated by the domain distance of the sampled images with respect to the source domain. The improvements are larger when the domain distance is small, e.g., for birds, dogs, and flowers.
<table><tr><td rowspan=4 colspan=3>Dataset</td><td rowspan=1 colspan=10>Labeled dataset</td></tr><tr><td rowspan=1 colspan=2>20% Birds</td><td rowspan=1 colspan=2>20% Cars</td><td rowspan=1 colspan=2>20% Aircrafts</td><td rowspan=1 colspan=2>20% Dogs</td><td rowspan=1 colspan=2>20% Flowers</td></tr><tr><td rowspan=1 colspan=10>Selection method</td></tr><tr><td rowspan=1 colspan=1>randomy</td><td rowspan=1 colspan=1>weight</td><td rowspan=1 colspan=1>random</td><td rowspan=1 colspan=1>weight</td><td rowspan=1 colspan=1>random</td><td rowspan=1 colspan=1>weight</td><td rowspan=1 colspan=1>random</td><td rowspan=1 colspan=1>weight</td><td rowspan=1 colspan=1>trandom</td><td rowspan=1 colspan=1>weight</td></tr><tr><td rowspan=8 colspan=3>BirdsCarsAircraftsDogsFlowersiNat avesiNat othersmini-ImageNet</td><td rowspan=1 colspan=1>1177</td><td rowspan=1 colspan=1>1177</td><td rowspan=1 colspan=1>325</td><td rowspan=1 colspan=1>87</td><td rowspan=1 colspan=1>184</td><td rowspan=1 colspan=1>114</td><td rowspan=1 colspan=1>410</td><td rowspan=1 colspan=1>118</td><td rowspan=1 colspan=1>156</td><td rowspan=1 colspan=1>9</td></tr><tr><td rowspan=1 colspan=1>303</td><td rowspan=1 colspan=1>2</td><td rowspan=1 colspan=1>1632</td><td rowspan=1 colspan=1>1632</td><td rowspan=1 colspan=1>242</td><td rowspan=1 colspan=1>466</td><td rowspan=1 colspan=1>532</td><td rowspan=1 colspan=1>594</td><td rowspan=1 colspan=1>230</td><td rowspan=1 colspan=1>12</td></tr><tr><td rowspan=1 colspan=1>214</td><td rowspan=1 colspan=1>3</td><td rowspan=1 colspan=1>259</td><td rowspan=1 colspan=1>259</td><td rowspan=1 colspan=1>1000</td><td rowspan=1 colspan=1>1000</td><td rowspan=1 colspan=1>356</td><td rowspan=2 colspan=1>2852067</td><td rowspan=2 colspan=1>129283</td><td rowspan=2 colspan=1>091</td></tr><tr><td rowspan=1 colspan=1></td><td rowspan=1 colspan=1>413</td><td rowspan=1 colspan=1>19</td><td rowspan=1 colspan=1>554</td><td rowspan=1 colspan=1>657</td><td rowspan=1 colspan=1>334</td><td rowspan=1 colspan=1>251</td><td rowspan=1 colspan=1>2067</td></tr><tr><td rowspan=1 colspan=2>Flowers</td><td rowspan=1 colspan=1>167</td><td rowspan=1 colspan=1>3</td><td rowspan=1 colspan=1>230</td><td rowspan=1 colspan=1>162</td><td rowspan=1 colspan=1>140</td><td rowspan=1 colspan=1>40</td><td rowspan=1 colspan=1>290</td><td rowspan=2 colspan=1>145744</td><td rowspan=3 colspan=1>825767793</td><td rowspan=3 colspan=1>8251192533</td></tr><tr><td rowspan=1 colspan=1>1133</td><td rowspan=1 colspan=1>4176</td><td rowspan=1 colspan=1>1599</td><td rowspan=1 colspan=1>792</td><td rowspan=1 colspan=1>957</td><td rowspan=1 colspan=1>815</td><td rowspan=1 colspan=1>1997</td></tr><tr><td rowspan=1 colspan=1>1089</td><td rowspan=1 colspan=1>108</td><td rowspan=1 colspan=1>1546</td><td rowspan=1 colspan=1>1555</td><td rowspan=1 colspan=1>935</td><td rowspan=1 colspan=1>240</td><td rowspan=1 colspan=1>2048</td><td rowspan=1 colspan=1>964</td></tr><tr><td rowspan=1 colspan=1>1389</td><td rowspan=1 colspan=1>397</td><td rowspan=1 colspan=1>2017</td><td rowspan=1 colspan=1>3018</td><td rowspan=1 colspan=1>1208</td><td rowspan=1 colspan=1>2074</td><td rowspan=1 colspan=1>2637</td><td rowspan=1 colspan=1>5420</td><td rowspan=1 colspan=1>946</td><td rowspan=1 colspan=1>540</td></tr><tr><td rowspan=1 colspan=3>Domain distance →</td><td rowspan=1 colspan=1>6.69</td><td rowspan=1 colspan=1>0.94</td><td rowspan=1 colspan=1>11.42</td><td rowspan=1 colspan=1>9.69</td><td rowspan=1 colspan=1>13.41</td><td rowspan=1 colspan=1>11.13</td><td rowspan=1 colspan=1>8.72</td><td rowspan=1 colspan=1>3.68</td><td rowspan=1 colspan=1>13.38</td><td rowspan=1 colspan=1>4.57</td></tr><tr><td rowspan=1 colspan=3>Accuracy (%)→</td><td rowspan=1 colspan=1>75.7</td><td rowspan=1 colspan=1>78.5</td><td rowspan=1 colspan=1>79.2</td><td rowspan=1 colspan=1>80.8</td><td rowspan=1 colspan=1>79.7</td><td rowspan=1 colspan=1>79.2</td><td rowspan=1 colspan=1>66.6</td><td rowspan=1 colspan=1>74.6</td><td rowspan=1 colspan=1>83.4</td><td rowspan=1 colspan=1>85.6</td></tr></table>
Table 6: Composition of the unlabeled datasets selected from a pool of images used in Figure 4c. We list the number of images in each source datasets. We also provide domain distance between the selected images and the labeled dataset. The 5-way 5-shot accuracy of the models trained with SSL are shown in the last row. The performance correlates with domain distance: when the distribution of unlabeled data is closer to labeled data, the performance is better.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742# ADASHIFT: DECORRELATION AND CONVERGENCE OF ADAPTIVE LEARNING RATE METHODS
Zhiming Zhou∗†, Qingru Zhang∗‡, Guansong Lu, Hongwei Wang, Weinan Zhang, Yong Yu Shanghai Jiao Tong University †heyohai@apex.sjtu.edu.cn,‡neverquit@sjtu.edu.cn
# ABSTRACT
Adam is shown not being able to converge to the optimal solution in certain cases. Researchers recently propose several algorithms to avoid the issue of nonconvergence of Adam, but their efficiency turns out to be unsatisfactory in practice. In this paper, we provide a new insight into the non-convergence issue of Adam as well as other adaptive learning rate methods. We argue that there exists an inappropriate correlation between gradient $g _ { t }$ and the second moment term $v _ { t }$ in Adam $t$ is the timestep), which results in that a large gradient is likely to have small step size while a small gradient may have a large step size. We demonstrate that such unbalanced step sizes are the fundamental cause of non-convergence of Adam, and we further prove that decorrelating $v _ { t }$ and $g _ { t }$ will lead to unbiased step size for each gradient, thus solving the non-convergence problem of Adam. Finally, we propose AdaShift, a novel adaptive learning rate method that decorrelates $v _ { t }$ and $g _ { t }$ by temporal shifting, i.e., using temporally shifted gradient $g _ { t - n }$ to calculate $v _ { t }$ . The experiment results demonstrate that AdaShift is able to address the non-convergence issue of Adam, while still maintaining a competitive performance with Adam in terms of both training speed and generalization.
# 1 INTRODUCTION
First-order optimization algorithms with adaptive learning rate play an important role in deep learning due to their efficiency in solving large-scale optimization problems. Denote $g _ { t } \in \mathbb { R } ^ { n }$ as the gradient of loss function $f$ with respect to its parameters $\boldsymbol \theta \in \mathbb { R } ^ { n }$ at timestep $t$ , then the general updating rule of these algorithms can be written as follows (Reddi et al., 2018):
$$\theta _ { t + 1 } = \theta _ { t } - { \frac { \alpha _ { t } } { \sqrt { v _ { t } } } } m _ { t } .$$
In the above equation, $m _ { t } \triangleq \phi ( g _ { 1 } , \ldots , g _ { t } ) \in \mathbb { R } ^ { n }$ is a function of the historical gradients; $v _ { t } \ { \stackrel { \triangle } { = } }$ $\psi ( g _ { 1 } , \ldots , g _ { t } ) \in \mathbb { R } _ { + } ^ { n }$ is an $n$ -dimension vector with non-negative elements, which adapts the learning rate for the $n$ elements in $g _ { t }$ respectively; $\alpha _ { t }$ is the base learning rate; and √αtv is the adaptive step size for $m _ { t }$ .
One common choice of $\phi ( g _ { 1 } , \ldots , g _ { t } )$ is the exponential moving average of the gradients used in Momentum (Qian, 1999) and Adam (Kingma & Ba, 2014), which helps alleviate gradient oscillations. The commonly-used $\psi ( g _ { 1 } , \dots , g _ { t } )$ in deep learning community is the exponential moving average of squared gradients, such as Adadelta (Zeiler, 2012), RMSProp (Tieleman & Hinton, 2012), Adam (Kingma & Ba, 2014) and Nadam (Dozat, 2016).
Adam (Kingma & Ba, 2014) is a typical adaptive learning rate method, which assembles the idea of using exponential moving average of first and second moments and bias correction. In general, Adam is robust and efficient in both dense and sparse gradient cases, and is popular in deep learning research. However, Adam is shown not being able to converge to optimal solution in certain cases. Reddi et al. (2018) point out that the key issue in the convergence proof of Adam lies in the quantity
$$\Gamma _ { t } \triangleq \bigg ( \frac { \sqrt { v _ { t } } } { \alpha _ { t } } - \frac { \sqrt { v _ { t - 1 } } } { \alpha _ { t - 1 } } \bigg ) ,$$
which is assumed to be positive, but unfortunately, such an assumption does not always hold in Adam. They provide a set of counterexamples and demonstrate that the violation of positiveness of $\Gamma _ { t }$ will lead to undesirable convergence behavior in Adam.
Reddi et al. (2018) then propose two variants, AMSGrad and AdamNC, to address the issue by keeping $\Gamma _ { t }$ positive. Specifically, AMSGrad defines $\hat { v _ { t } }$ as the historical maximum of $v _ { t }$ , i.e., $\hat { v _ { t } } =$ max $\{ v _ { i } \} _ { i = 1 } ^ { t }$ , and replaces $v _ { t }$ with $\hat { v _ { t } }$ to keep $v _ { t }$ non-decreasing and therefore forces $\Gamma _ { t }$ to be positive; while AdamNC forces $v _ { t }$ to have “long-term memory” of past gradients and calculates $v _ { t }$ as their average to make it stable. Though these two algorithms solve the non-convergence problem of Adam to a certain extent, they turn out to be inefficient in practice: they have to maintain a very large $v _ { t }$ once a large gradient appears, and a large $v _ { t }$ decreases the adaptive learning rate $\frac { \alpha _ { t } } { \sqrt { v _ { t } } }$ and slows down the training process.
In this paper, we provide a new insight into adaptive learning rate methods, which brings a new perspective on solving the non-convergence issue of Adam. Specifically, in Section 3, we study the counterexamples provided by Reddi et al. (2018) via analyzing the accumulated step size of each gradient $g _ { t }$ . We observe that in the common adaptive learning rate methods, a large gradient tends to have a relatively small step size, while a small gradient is likely to have a relatively large step size. We show that the unbalanced step sizes stem from the inappropriate positive correlation between $v _ { t }$ and $g _ { t }$ , and we argue that this is the fundamental cause of the non-convergence issue of Adam.
In Section 4, we further prove that decorrelating $v _ { t }$ and $g _ { t }$ leads to equal and unbiased expected step size for each gradient, thus solving the non-convergence issue of Adam. We subsequently propose AdaShift, a decorrelated variant of adaptive learning rate methods, which achieves decorrelation between $v _ { t }$ and $g _ { t }$ by calculating $v _ { t }$ using temporally shifted gradients. Finally, in Section 5, we study the performance of our proposed AdaShift, and demonstrate that it solves the non-convergence issue of Adam, while still maintaining a decent performance compared with Adam in terms of both training speed and generalization.
# 2 PRELIMINARIES
Adam. In Adam, $m _ { t }$ and $v _ { t }$ are defined as the exponential moving average of $g _ { t }$ and $g _ { t } ^ { 2 }$
$$m _ { t } = \beta _ { 1 } m _ { t - 1 } + ( 1 - \beta _ { 1 } ) g _ { t } { \mathrm { a n d } } v _ { t } = \beta _ { 2 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) g _ { t } ^ { 2 } ,$$
where $\beta _ { 1 } \in [ 0 , 1 )$ and $\beta _ { 2 } \in [ 0 , 1 )$ are the exponential decay rates for $m _ { t }$ and $v _ { t }$ , respectively, with $m _ { 0 } = 0$ and $v _ { 0 } = 0$ . They can also be written as:
$$m _ { t } = ( 1 - \beta _ { 1 } ) \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } g _ { i } \mathrm { a n d } v _ { t } = ( 1 - \beta _ { 2 } ) \sum _ { i = 1 } ^ { t } \beta _ { 2 } ^ { t - i } g _ { i } ^ { 2 } .$$
To avoid the bias in the estimation of the expected value at the initial timesteps, Kingma & Ba (2014) propose to apply bias correction to $m _ { t }$ and $v _ { t }$ . Using $m _ { t }$ as instance, it works as follows:
$$m _ { t } = \frac { ( 1 - \beta _ { 1 } ) \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } g _ { i } } { ( 1 - \beta _ { 1 } ) \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } } = \frac { \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } g _ { i } } { \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } } = \frac { ( 1 - \beta _ { 1 } ) \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } g _ { i } } { 1 - \beta _ { 1 } ^ { t } } .$$
Online optimization problem. An online optimization problem consists of a sequence of cost functions ${ \bf \bar { \phi } } _ { f _ { 1 } ( \theta ) , \dots , f _ { t } ( \theta ) , . . . , f _ { T } ( \theta ) }$ , where the optimizer predicts the parameter $\theta _ { t }$ at each timestep $t$ and evaluate it on an unknown cost function $f _ { t } ( \theta )$ . The performance of the optimizer is usually evaluated by regreonline prediction $\begin{array} { r } { R ( T ) \stackrel { \Delta } { = } \sum _ { t = 1 } ^ { T } [ f _ { t } ( \theta _ { t } ) - f _ { t } ( \theta ^ { * } ) ] } \end{array}$ , which is the sum oarameter prediction fference between thefor all the previous $f _ { t } ( \theta _ { t } )$ $f _ { t } ( \theta ^ { * } )$ steps, where $\begin{array} { r } { \theta ^ { * } = \arg \operatorname* { m i n } _ { \theta \in \vartheta } \sum _ { t = 1 } ^ { T } f _ { t } ( \theta ) } \end{array}$ is the best fixed-point parameter from a feasible set $\vartheta$ .
Counterexamples. Reddi et al. (2018) highlight that for any fixed $\beta _ { 1 }$ and $\beta _ { 2 }$ , there exists an online optimization problem where Adam has non-zero average regret, i.e., Adam does not converge to optimal solution . The counterexamples in the sequential version are given as follows:
$$f _ { t } ( \theta ) = { \left\{ \begin{array} { l l } { C \theta , } & { { \mathrm { i f ~ t ~ m o d ~ } } d = 1 ; } \\ { - \theta , } & { { \mathrm { o t h e r w i s e } } , } \end{array} \right. }$$
where $C$ is a relatively large constant and $d$ is the length of an epoch. In Equation 6, most gradients of $f _ { t } ( \theta )$ with respect to $\theta$ are $- 1$ , but the large positive gradient $C$ at the beginning of each epoch makes the overall gradient of each epoch positive, which means that one should decrease $\theta _ { t }$ to minimize the loss. However, according to (Reddi et al., 2018), the accumulated update of $\theta$ in Adam under some circumstance is opposite (i.e., $\theta _ { t }$ is increased), thus Adam cannot converge in such case. Reddi et al. (2018) argue that the reason of the non-convergence of Adam lies in that the positive assumption of $\Gamma _ { t } \triangleq ( \sqrt { v _ { t } } / \alpha _ { t } - \sqrt { v _ { t - 1 } } / \alpha _ { t - 1 } )$ does not always hold in Adam.
The counterexamples are also extended to stochastic cases in (Reddi et al., 2018), where a finite set of cost functions appear in a stochastic order. Compared with sequential online optimization counterexample, the stochastic version is more general and closer to the practical situation. For the simplest one dimensional case, at each timestep $t$ , the function $f _ { t } ( \theta )$ is chosen as i.i.d.:
$$\begin{array} { r } { f _ { t } ( \theta ) = \left\{ \begin{array} { l l } { C \theta , } & { \mathrm { w i t h } \mathrm { p r o b a b i l i t y } p = \frac { 1 + \delta } { C + 1 } ; } \\ { - \theta , } & { \mathrm { w i t h } \mathrm { p r o b a b i l i t y } 1 - p = \frac { C - \delta } { C + 1 } , } \end{array} \right. } \end{array}$$
where $\delta$ is a small positive constant that is smaller than $C$ . The expected cost function of the above problem is $\begin{array} { r } { F ( \theta ) \stackrel { \bullet } { = } \frac { 1 + \delta } { C + 1 } C \theta - \frac { C - \delta } { C + 1 } \theta = \delta \theta } \end{array}$ C−δC+1 θ = δθ, therefore, one should decrease θ to minimize the loss. Reddi et al. (2018) prove that when $C$ is large enough, the expectation of accumulated parameter update in Adam is positive and results in increasing $\theta$ .
Basic Solutions Reddi et al. (2018) propose maintaining the strict positiveness of $\Gamma _ { t }$ as solution, for example, keeping $v _ { t }$ non-decreasing or using increasing $\beta _ { 2 }$ . In fact, keeping $\Gamma _ { t }$ positive is not the only way to guarantee the convergence of Adam. Another important observation is that for any fixed sequential online optimization problem with infinitely repeating epochs (e.g., Equation 6), Adam will converge as long as $\beta _ { 1 }$ is large enough. Formally, we have the following theorem:
Theorem 1 (The influence of $\beta _ { 1 }$ ). For any fixed sequential online convex optimization problem with infinitely repeating of finite length epochs ( $d$ is the length of an epoch), if $\exists G \in \mathbb { R }$ such that $\| \nabla f _ { t } ( \theta ) \| _ { \infty } \leq G$ and $\exists T \in \mathbb { N } , \exists \epsilon _ { 2 } > \epsilon _ { 1 } > 0$ such that $\begin{array} { r } { \epsilon _ { 1 } < \bar { \phi } _ { t } \bar { G } ^ { 2 } < \bar { \epsilon } _ { 2 } } \end{array}$ holds for all $t > T$ , then, for any fixed $\beta _ { 2 } \in [ 0 , 1 )$ , there exists a $\beta _ { 1 } \in [ 0 , 1 )$ such that Adam has average regret $\leq \epsilon _ { 2 }$ ;
The intuition behind Theorem 1 is that, if $\beta _ { 1 } 1$ , then $\begin{array} { r } { m _ { t } \sum _ { i = 1 } ^ { d } g _ { i } / d } \end{array}$ , i.e., $m _ { t }$ approaches the average gradient of an epoch, according to Equation 5. Therefore, no matter what the adaptive learning rate $\alpha _ { t } / \sqrt { v _ { t } }$ is, Adam will always converge along the correct direction.
# 3 THE CAUSE OF NON-CONVERGENCE: UNBALANCED STEP SIZE
In this section, we study the non-convergence issue by analyzing the counterexamples provided by Reddi et al. (2018). We show that the fundamental problem of common adaptive learning rate methods is that: √ $v _ { t }$ is positively correlated to the scale of gradient $g _ { t }$ , which results in a small step size $\alpha _ { t } / \sqrt { v _ { t } }$ for a large gradient, and a large step size for a small gradient. We argue that such an unbalanced step size is the cause of non-convergence.
We will first define net update factor for the analysis of the accumulated influence of each gradient $g _ { t }$ , then apply the net update factor to study the behaviors of Adam using Equation 6 as an example. The argument will be extended to the stochastic online optimization problem and general cases.
# 3.1 NET UPDATE FACTOR
When $\beta _ { 1 } \neq 0$ , due to the exponential moving effect of $m _ { t }$ , the influence of $g _ { t }$ exists in all of its following timesteps. For timestep $i$ $( i \geq t )$ , the weight of $g _ { t }$ is $( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { i - t }$ . We accordingly define a new tool for our analysis: the net update $n e t ( g _ { t } )$ of each gradient $g _ { t }$ , which is its accumulated influence on the entire optimization process:
$$n e t ( g _ { t } ) \triangleq \sum _ { i = t } ^ { \infty } \frac { \alpha _ { i } } { \sqrt { v _ { i } } } [ ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { i - t } g _ { t } ] = k ( g _ { t } ) \cdot g _ { t } , \mathrm { ~ w h e r e ~ } k ( g _ { t } ) = \sum _ { i = t } ^ { \infty } \frac { \alpha _ { i } } { \sqrt { v _ { i } } } ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { i - t } ,$$
and we call $k ( g _ { t } )$ the net update factor of $g _ { t }$ , which is the equivalent accumulated step size for gradient $g _ { t }$ . Note that $k ( g _ { t } )$ depends on $\{ v _ { i } \} _ { i = t } ^ { \infty }$ , and in Adam, if $\beta _ { 1 } \neq 0$ , then all elements in $\bar { \{ } v _ { i } \} _ { i = t } ^ { \infty }$ are related to $g _ { t }$ . Therefore, $k ( g _ { t } )$ is a function of $g _ { t }$ .
It is worth noticing that in Momentum method, $v _ { t }$ is equivalently set as 1. Therefore, we have $k ( g _ { t } ) = \alpha _ { t }$ and $n e t ( g _ { t } ) = \alpha _ { t } g _ { t }$ , which means that the accumulated influence of each gradient $g _ { t }$ in Momentum is the same as vanilla SGD (Stochastic Gradient Decent). Hence, the convergence of Momentum is similar to vanilla SGD. However, in adaptive learning rate methods, $v _ { t }$ is function over the past gradients, which makes its convergence nontrivial.
# 3.2 ANALYSIS ON ONLINE OPTIMIZATION COUNTEREXAMPLES
Note that $v _ { t }$ exists in the definition of net update factor (Equation 8). Before further analyzing the convergence of Adam using the net update factor, we first study the pattern of $v _ { t }$ in the sequential online optimization problem in Equation 6. Since Equation 6 is deterministic, we can derive the formula of $v _ { t }$ as follows:
Lemma 2. In the sequential online optimization problem in Equation 6, denote $\beta _ { 1 } , \beta _ { 2 } \in [ 0 , 1 )$ as the decay rates, $d \in \mathbb { N }$ as the length of an epoch, $n \in \mathbb { N }$ as the index of epoch, and $i \in \{ 1 , 2 , . . . , d \}$ as the index of timestep in one epoch. Then the limit of $v _ { n d + i }$ when $n \to \infty$ is:
$$\operatorname * { l i m } _ { n \infty } v _ { n d + i } = \frac { 1 - \beta _ { 2 } } { 1 - \beta _ { 2 } ^ { d } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { i - 1 } + 1 .$$
Given the formula of $v _ { t }$ in Equation 9, we now study the net update factor of each gradient. We start with a simple case where $\beta _ { 1 } = 0$ . In this case we have
$$\operatorname* { l i m } _ { n \to \infty } k ( g _ { n d + i } ) = \operatorname* { l i m } _ { n \to \infty } \frac { \alpha _ { t } } { \sqrt { v _ { n d + i } } } .$$
Since the limit of $v _ { n d + i }$ in each epoch monotonically decreases with the increase of index $i$ according to Equation 9, the limit of $k ( g _ { n d + i } )$ monotonically increases in each epoch. Specifically, the first gradient $g _ { n d + 1 } = C$ in epoch $n$ represents the correct updating direction, but its influence is the smallest in this epoch. In contrast, the net update factor of the subsequent gradients $- 1$ are relatively larger, though they indicate a wrong updating direction.
We further consider the general case where $\beta _ { 1 } \neq 0$ . The result is presented in the following lemma:
Lemma 3. In the sequential online optimization problem in Equation 6, when $n \to \infty$ , the limit of net update factor $k ( g _ { n d + i } )$ of epoch $n$ satisfies: $\exists 1 \leq j \leq d$ such that
$$\operatorname* { l i m } _ { n \to \infty } k ( C ) = \operatorname* { l i m } _ { n \to \infty } k ( g _ { n d + 1 } ) < \operatorname* { l i m } _ { n \to \infty } k ( g _ { n d + 2 } ) < \cdots < \operatorname* { l i m } _ { n \to \infty } k ( g _ { n d + j } ) ,$$
and
$$\operatorname* { l i m } _ { n \to \infty } k ( g _ { n d + j } ) > \operatorname* { l i m } _ { n \to \infty } k ( g _ { n d + j + 1 } ) > \cdots > \operatorname* { l i m } _ { n \to \infty } k ( g _ { n d + d + 1 } ) = \operatorname* { l i m } _ { n \to \infty } k ( C ) ,$$
where $k ( C )$ denotes the net update factor for gradient $g _ { i } = C$ .
Lemma 3 tells us that, in sequential online optimization problem in Equation 6, the net update factors are unbalanced. Specifically, the net update factor for the large gradient $C$ is the smallest in the entire epoch, while all gradients $- 1$ have larger net update factors. Such unbalanced net update factors will possibly lead Adam to a wrong accumulated update direction.
Similar conclusion also holds in the stochastic online optimization problem in Equation 7. We derive the expectation of the net update factor for each gradient in the following lemma:
Lemma 4. In the stochastic online optimization problem in Equation 7, assuming $\alpha _ { t } = 1$ , it holds that $k ( C ) < k ( - 1 )$ , where $k ( C )$ denote the expectation net update factor for $g _ { i } = C$ and $k ( - 1 )$ denote the expectation net update factor for $g _ { i } = - 1$ .
Though the formulas of net update factors in the stochastic case are more complicated than those in deterministic case, the analysis is actually more easier: the gradients with the same scale share the same expected net update factor, so we only need to analyze $k ( C )$ and $k ( - 1 )$ . From Lemma 4, we can see that in terms of the expectation net update factor, $k ( C )$ is smaller than $k ( - 1 )$ , which means the accumulated influence of gradient $C$ is smaller than gradient $- 1$ .
# 3.3 ANALYSIS ON NON-CONVERGENCE OF ADAM
As we have observed in the previous section, a common characteristic of these counterexamples is that the net update factor for the gradient with large magnitude is smaller than these with small magnitude. The above observation can also be interpreted as a direct consequence of inappropriate correlation between $v _ { t }$ and $g _ { t }$ . Recall that $v _ { t } = \beta _ { 2 } { v _ { t - 1 } } + ( 1 - \beta _ { 2 } ) g _ { t } ^ { 2 }$ . Assuming $v _ { t - 1 }$ is independent of $g _ { t }$ , then: when a new gradient $g _ { t }$ arrives, if $g _ { t }$ is large, $v _ { t }$ is likely to be larger; and if $g _ { t }$ is small, $v _ { t }$ is also likely to be smaller. If $\beta _ { 1 } = 0$ , then $k ( g _ { t } ) = \alpha _ { t } / \sqrt { v _ { t } }$ . As a result, a large gradient is likely to have a small net update factor, while a small gradient is likely to have a large net update factor in Adam.
When it comes to the scenario where $\beta _ { 1 } > 0$ , the arguments are actually quite similar. Given $v _ { t } =$ $\beta _ { 2 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) g _ { t } ^ { 2 }$ . Assuming $v _ { t - 1 }$ and $\{ g _ { t + i } \} _ { i = 1 } ^ { \infty }$ are independent from $g _ { t }$ , then: not only does $v _ { t }$ positively correlate with the magnitude of , but also the entire infinite sequence $\{ v _ { i } \} _ { i = t } ^ { \infty }$ positively correlates with the magnitude of $g _ { t }$ . Since the net update factor $\begin{array} { r } { k ( g _ { t } ) = \sum _ { i = t } ^ { \infty } \ \alpha _ { i } / \sqrt { v _ { i } } ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { i - t } } \end{array}$ negatively correlates with each $v _ { i }$ in $\{ v _ { i } \} _ { i = t } ^ { \infty }$ , it is thus negatively correlated with the magnitude of $g _ { t }$ . That is, $k ( g _ { t } )$ for a large gradient is likely to be smaller, while $k ( g _ { t } )$ for a small gradient is likely to be larger.
The unbalanced net update factors cause the non-convergence problem of Adam as well as all other adaptive learning rate methods where $v _ { t }$ correlates with $g _ { t }$ . To construct a counterexample, the same pattern is that: the large gradient is along the “correct” direction, while the small gradient is along the opposite direction. Due to the fact that the accumulated influence of a large gradient is small while the accumulated influence of a small gradient is large, Adam may update parameters along the wrong direction.
Finally, we would like to emphasize that even if Adam updates parameters along the right direction in general, the unbalanced net update factors are still unfavorable since they slow down the convergence.
# 4 THE PROPOSED METHOD: DECORRELATION VIA TEMPORAL SHIFTING
According to the previous discussion, we conclude that the main cause of the non-convergence of Adam is the inappropriate correlation between $v _ { t }$ and $g _ { t }$ . Currently we have two possible solutions: (1) making $v _ { t }$ act like a constant, which declines the correlation, e.g., using a large $\beta _ { 2 }$ or keep $v _ { t }$ nondecreasing (Reddi et al., 2018); (2) using a large $\beta _ { 1 }$ (Theorem 1), where the aggressive momentum term helps to mitigate the impact of unbalanced net update factors. However, neither of them solves the problem fundamentally.
The dilemma caused by $v _ { t }$ enforces us to rethink its role. In adaptive learning rate methods, $v _ { t }$ plays the role of estimating the second moments of gradients, which reflects the scale of gradient on average. With the adaptive learning rate $\alpha _ { t } / \sqrt { v _ { t } }$ , the update step of $g _ { t }$ is scaled down by $\sqrt { v _ { t } }$ and achieves rescaling invariance with respect to the scale of $g _ { t }$ , which is practically useful to make the training process easy to control and the training system robust. However, the current scheme of $v _ { t }$ , i.e., $v _ { t } = \beta _ { 2 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) g _ { t } ^ { 2 }$ , brings a positive correlation between $v _ { t }$ and $g _ { t }$ , which results in reducing the effect of large gradients and increasing the effect of small gradients, and finally causes the non-convergence problem. Therefore, the key is to let $v _ { t }$ be a quantity that reflects the scale of the gradients, while at the same time, be decorrelated with current gradient $g _ { t }$ . Formally, we have the following theorem:
Theorem 5 (Decorrelation leads to convergence). For any fixed online optimization problem with infinitely repeating of a finite set of cost functions $\{ f _ { 1 } ( { \boldsymbol { \theta } } ) , \dots , f _ { t } ( { \boldsymbol { \theta } } ) , \dots { \bar { f } } _ { n } ( { \boldsymbol { \theta } } ) \}$ , assuming $\beta _ { 1 } = 0$ and $\alpha _ { t }$ is fixed, we have, if $v _ { t }$ follows a fixed distribution and is independent of the current gradient $g _ { t }$ , then the expected net update factor for each gradient is identical.
Let $P _ { v }$ denote the distribution of $v _ { t }$ . In the infinitely repeating online optimization scheme, the expectation of net update factor for each gradient $g _ { t }$ is
$$\mathbb { E } [ k ( g _ { t } ) ] = \sum _ { i = t } ^ { \infty } \mathbb { E } _ { v _ { i } \sim P _ { v } } [ \frac { \alpha _ { i } } { \sqrt { v _ { i } } } ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { i - t } ] .$$
Given $P _ { v }$ is independent of $g _ { t }$ , the expectation of the net update factor $\mathbb { E } [ k ( g _ { t } ) ]$ is independent of $g _ { t }$ and remains the same for different gradients. With the expected net update factor being a fixed constant, the convergence of the adaptive learning rate method reduces to vanilla SGD.
Momentum (Qian, 1999) can be viewed as setting $v _ { t }$ as a constant, which makes $v _ { t }$ and $g _ { t }$ independent. Furthermore, in our view, using an increasing $\beta _ { 2 }$ (AdamNC) or keeping $\hat { v _ { t } }$ as the largest $v _ { t }$ (AMSGrad) is also to make $v _ { t }$ almost fixed. However, fixing $v _ { t }$ is not a desirable solution, because it damages the adaptability of Adam with respect to the adapting of step size.
We next introduce the proposed solution to make $v _ { t }$ independent of $g _ { t }$ , which is based on temporal independent assumption among gradients. We first introduce the idea of temporal decorrelation, then extend our solution to make use of the spatial information of gradients. Finally, we incorporate first moment estimation. The pseudo code of the proposed algorithm is presented as follows.
# Algorithm 1 AdaShift: Temporal Shifting with Block-wise Spatial Operation
Input: $n , \beta _ { 1 } , \beta _ { 2 } , \phi , \theta _ { 0 } , \{ f _ { t } ( \theta ) \} _ { t = 1 } ^ { T } , \{ \alpha _ { t } \} _ { t = 1 } ^ { T } , \{ g _ { - t } \} _ { t = 0 } ^ { n - 1 } ,$ , $v _ { 0 } = 0$ 2: for $t = 1$ to $T$ do 3: $g _ { t } = \nabla f _ { t } ( \theta _ { t } )$ 4: $\begin{array} { r } { m _ { t } = \sum _ { i = 0 } ^ { n - 1 } \beta _ { 1 } ^ { i } g _ { t - i } / \sum _ { i = 0 } ^ { n - 1 } \beta _ { 1 } ^ { i } } \end{array}$ 5: for $i = 1$ to M do 6: $v _ { t } [ i ] = \beta _ { 2 } v _ { t - 1 } [ i ] + ( 1 - \beta _ { 2 } ) \phi ( g _ { t - n } ^ { 2 } [ i ] )$ 7: $\theta _ { t } [ i ] = \theta _ { t - 1 } [ i ] - \alpha _ { t } / \sqrt { v _ { t } [ i ] } \cdot m _ { t } [ i$ ] 8: end for 9: end for 10: // We ignore the bias-correction, epsilon and other misc for the sake of clarity
# 4.1 TEMPORAL DECORRELATION
In practical setting, $f _ { t } ( \theta )$ usually involves different mini-batches $x _ { t }$ , i.e., $f _ { t } ( \theta ) = f ( \theta ; x _ { t } )$ . Given the randomness of mini-batch, we assume that the mini-batch $x _ { t }$ is independent of each other and further assume that $f ( \theta ; x )$ keeps unchanged over time, then the gradient $g _ { t } = \nabla f ( \theta ; x _ { t } )$ of each mini-batch is independent of each other.
Therefore, we could change the update rule for $v _ { t }$ to involve $g _ { t - n }$ instead of $g _ { t }$ , which makes $v _ { t }$ and $g _ { t }$ temporally shifted and hence decorrelated:
$$v _ { t } = \beta _ { 2 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) g _ { t - n } ^ { 2 } .$$
Note that in the sequential online optimization problem, the assumption $^ { \bullet } g _ { t }$ is independent of each other” does not hold. However, in the stochastic online optimization problem and practical neural network settings, our assumption generally holds.
# 4.2 MAKING USE OF THE SPATIAL ELEMENTS OF PREVIOUS TIMESTEPS
Most optimization schemes involve a great many parameters. The dimension of $\theta$ is high, thus $g _ { t }$ and $v _ { t }$ are also of high dimension. However, $v _ { t }$ is element-wisely computed in Equation 14. Specifically, we only use the $i$ -th dimension of $g _ { t - n }$ to calculate the $i$ -th dimension of $v _ { t }$ . In other words, it only makes use of the independence between $g _ { t - n } [ i ]$ and $g _ { t } [ i ]$ , where $g _ { t } [ i ]$ denotes the $i$ -th element of $g _ { t }$ . Actually, in the case of high-dimensional $g _ { t }$ and $v _ { t }$ , we can further assume that all elements of gradient $g _ { t - n }$ at previous timesteps are independent with the $i$ -th dimension of $g _ { t }$ . Therefore, all elements in $g _ { t - n }$ can be used to compute $v _ { t }$ without introducing correlation. To this end, we propose introducing a function $\phi$ over all elements of $g _ { t - n } ^ { 2 }$ , i.e.,
$$v _ { t } = \beta _ { 2 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) \phi ( g _ { t - n } ^ { 2 } ) .$$
For easy reference, we name the elements of $g _ { t - n }$ other than $g _ { t - n } [ i ]$ as the spatial elements of $g _ { t - n }$ and name $\phi$ the spatial function or spatial operation. There is no restriction on the choice of $\phi$ , and we use $\phi ( x ) = \mathrm { m a x } _ { i } x [ i ]$ for most of our experiments, which is shown to be a good choice. The $\operatorname* { m a x } _ { i } x [ i ]$ operation has a side effect that turns the adaptive learning rate $v _ { t }$ into a shared scalar.
An important thing here is that, we no longer interpret $v _ { t }$ as the second moment of $g _ { t }$ . It is merely a random variable that is independent of $g _ { t }$ , while at the same time, reflects the overall gradient scale. We leave further investigations on $\phi$ as future work.
# 4.3 BLOCK-WISE ADAPTIVE LEARNING RATE SGD
In practical setting, e.g., deep neural network, $\theta$ usually consists of many parameter blocks, e.g., the weight and bias for each layer. In deep neural network, the gradient scales (i.e., the variance) for different layers tend to be different (Glorot & Bengio, 2010; He et al., 2015). Different gradient scales make it hard to find a learning rate that is suitable for all layers, when using SGD and Momentum methods. In traditional adaptive learning rate methods, they apply element-wise rescaling for each gradient dimension, which achieves rescaling-invariance and somehow solves the above problem. However, Adam sometimes does not generalize better than SGD (Wilson et al., 2017; Keskar & Socher, 2017), which might relate to the excessive learning rate adaptation in Adam.
In our temporal decorrelation with spatial operation scheme, we can solve the “different gradient scales” issue more naturally, by applying $\phi$ block-wisely and outputs a shared adaptive learning rate scalar $v _ { t } [ i ]$ for each block:
$$v _ { t } [ i ] = \beta _ { 2 } v _ { t - 1 } [ i ] + ( 1 - \beta _ { 2 } ) \phi ( g _ { t - n } ^ { 2 } [ i ] ) .$$
It makes the algorithm work like an adaptive learning rate SGD, where each block has an adaptive learning rate $\alpha _ { t } / \sqrt { v _ { t } [ i ] }$ while the relative gradient scale among in-block elements keep unchanged. As illustrated in Algorithm 1, the parameters $\theta _ { t }$ including the related $g _ { t }$ and $v _ { t }$ are divided into $M$ blocks. Every block contains the parameters of the same type or same layer in neural network.
# 4.4 INCORPORATING FIRST MOMENT ESTIMATION: MOVING AVERAGING WINDOWS
First moment estimation, i.e., defining $m _ { t }$ as a moving average of $g _ { t }$ , is an important technique of modern first order optimization algorithms, which alleviates mini-batch oscillations. In this section, we extend our algorithm to incorporate first moment estimation.
We have argued that $v _ { t }$ needs to be decorrelated with $g _ { t }$ . Analogously, when introducing the first moment estimation, we need to make $v _ { t }$ and $m _ { t }$ independent to make the expected net update factor unbiased. Based on our assumption of temporal independence, we further keep out the latest $n$ gradients $\{ g _ { t - i } \} _ { i = 0 } ^ { n - 1 }$ , and update $v _ { t }$ and $m _ { t }$ via
$$v _ { t } = \beta _ { 2 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) \phi ( g _ { t - n } ^ { 2 } ) \mathrm { a n d } m _ { t } = \frac { \sum _ { i = 0 } ^ { n - 1 } \beta _ { 1 } ^ { i } g _ { t - i } } { \sum _ { i = 0 } ^ { n - 1 } \beta _ { 1 } ^ { i } } .$$
In Equation 17, $\beta _ { 1 } \in [ 0 , 1 ]$ plays the role of decay rate for temporal elements. It can be viewed as a truncated version of exponential moving average that only applied to the latest few elements. Since we use truncating, it is feasible to use large $\beta _ { 1 }$ without taking the risk of using too old gradients. In the extreme case where $\beta _ { 1 } = 1$ , it becomes vanilla averaging.
The pseudo code of the algorithm that unifies all proposed techniques is presented in Algorithm 1 and a more detailed version can be found in the Appendix. It has the following parameters: spatial operation $\phi$ , $n \in \mathbb { N } ^ { + }$ , $\beta _ { 1 } \in [ 0 , 1 ]$ , $\beta _ { 2 } \in [ 0 , 1 )$ and $\alpha _ { t }$ .
Summary The key difference between Adam and the proposed method is that the latter temporally shifts the gradient $g _ { t }$ for $n$ -step, i.e., using $g _ { t - n }$ for calculating $v _ { t }$ and using the kept-out $n$ gradients to evaluate $m _ { t }$ (Equation 17), which makes $v _ { t }$ and $m _ { t }$ decorrelated and consequently solves the nonconvergence issue. In addition, based on our new perspective on adaptive learning rate methods, $v _ { t }$ is not necessarily the second moment and it is valid to further involve the calculation of $v _ { t }$ with the spatial elements of previous gradients. We thus proposed to introduce the spatial operation $\phi$ that outputs a shared scalar for each block. The resulting algorithm turns out to be closely related to SGD, where each block has an overall adaptive learning rate and the relative gradient scale in each block is maintained. We name the proposed method that makes use of temporal-shifting to decorrelated $v _ { t }$ and $m _ { t }$ AdaShift, which means “ADAptive learning rate method with temporal SHIFTing”.
# 5 EXPERIMENTS
In this section, we empirically study the proposed method and compare them with Adam, AMSGrad and SGD, on various tasks in terms of training performance and generalization. Without additional declaration, the reported result for each algorithm is the best we have found via parameter grid search. The anonymous code is provided at http://bit.ly/2NDXX6x.
# 5.1 ONLINE OPTIMIZATION COUNTEREXAMPLES
Firstly, we verify our analysis on the stochastic online optimization problem in Equation 7, where we set $C = 1 0 1$ and $\delta = 0 . 0 2$ . We compare Adam, AMSGrad and AdaShift in this experiment. For fair comparison, we set $\alpha = 0 . 0 0 1$ , $\beta _ { 1 } = 0$ and $\beta _ { 2 } = 0 . 9 9 9$ for all these methods. The results are shown in Figure 1a. We can see that Adam tends to increase $\theta$ , that is, the accumulate update of $\theta$ in Adam is along the wrong direction, while AMSGrad and AdaShift update $\theta$ in the correct direction. Furthermore, given the same learning rate, AdaShift decreases $\theta$ faster than AMSGrad, which validates our argument that AMSGrad has a relatively higher $v _ { t }$ that slows down the training.
In this experiment, we also verify Theorem 1. As shown in Figure 1b, Adam is also able to converge to the correct direction with a sufficiently large $\beta _ { 1 }$ and $\beta _ { 2 }$ . Note that (1) AdaShift still converges with the fastest speed; (2) a small $\beta _ { 1 }$ (e.g., $\beta _ { 1 } = 0 . 9$ , the light-blue line in Figure 1b) does not make Adam converge to the correct direction. We do not conduct the experiments on the sequential online optimization problem in Equation 6, because it does not fit our temporal independence assumption. To make it converge, one can use a large $\beta _ { 1 }$ or $\beta _ { 2 }$ , or set $v _ { t }$ as a constant.
 Figure 1: Experiments on stochastic counterexample.
5.2 LOGISTIC REGRESSION AND MULTILAYER PERCEPTRON ON MNIST
We further compare the proposed method with Adam, AMSGrad and SGD by using Logistic Regression and Multilayer Perceptron on MNIST, where the Multilayer Perceptron has two hidden layers and each has 256 hidden units with no internal activation. The results are shown in Figure 2 and Figure 3, respectively. We find that in Logistic Regression, these learning algorithms achieve very similar final results in terms of both training speed and generalization. In Multilayer Perceptron, we compare Adam, AMSGrad and AdaShift with reduce-max spatial operation (max-AdaShift) and without spatial operation (non-AdaShift). We observe that max-AdaShift achieves the lowest training loss, while non-AdaShift has mild training loss oscillation and at the same time achieves better generalization. The worse generalization of max-AdaShift may be due to overfitting in this task, and the better generalization of non-AdaShift may stem from the regularization effect of its relatively unstable step size.
# 5.3 DENSENET AND RESNET ON CIFAR-10
ResNet (He et al., 2016) and DenseNet (Huang et al., 2017) are two typical modern neural networks, which are efficient and widely-used. We test our algorithm with ResNet and DenseNet on CIFAR10 datasets. We use a 18-layer ResNet and 100-layer DenseNet in our experiments. We plot the best results of Adam, AMSGrad and AdaShift in Figure 4 and Figure 5 for ResNet and DenseNet, respectively. We can see that AMSGrad is relatively worse in terms of both training speed and generalization. Adam and AdaShift share competitive results, while AdaShift is generally slightly better, especially the test accuracy of ResNet and the training loss of DenseNet.
 Figure 2: Logistic Regression on MNIST.
 Figure 3: Multilayer Perceptron on MNIST.
 Figure 4: ResNet on Cifar-10.
 Figure 5: DenseNet on Cifar-10.
# 5.4 DENSENET WITH TINY-IMAGENET
We further increase the complexity of dataset, switching from CIFAR-10 to Tiny-ImageNet, and compare the performance of Adam, AMSGrad and AdaShift with DenseNet. The results are shown in Figure 6, from which we can see that the training curves of Adam and AdaShift are basically overlapped, but AdaShift achieves higher test accuracy than Adam. AMSGrad has relatively higher training loss, and its test accuracy is relatively lower at the initial stage.
# 5.5 GENERATIVE MODEL AND RECURRENT MODEL
We also test our algorithm on the training of generative model and recurrent model. We choose WGAN-GP (Gulrajani et al., 2017) that involves Lipschitz continuity condition (which is hard to optimize), and Neural Machine Translation (NMT) (Luong et al., 2017) that involves typical recurrent unit LSTM, respectively. In Figure 7a, we compare the performance of Adam, AMSGrad and AdaShift in the training of WGAN-GP discriminator, given a fixed generator. We notice that AdaShift is significantly better than Adam, while the performance of AMSGrad is relatively unsatisfactory. The test performance in terms of BLEU of NMT is shown in Figure 7b, where AdaShift achieves a higher BLEU than Adam and AMSGrad.
 Figure 6: DenseNet on Tiny-ImageNet.
 Figure 7: Generative and Recurrent model.
# 6 CONCLUSION
In this paper, we study the non-convergence issue of adaptive learning rate methods from the perspective of the equivalent accumulated step size of each gradient, i.e., the net update factor defined in this paper. We show that there exists an inappropriate correlation between $v _ { t }$ and $g _ { t }$ , which leads to unbalanced net update factor for each gradient. We demonstrate that such unbalanced step sizes are the fundamental cause of non-convergence of Adam, and we further prove that decorrelating $v _ { t }$ and $g _ { t }$ will lead to unbiased expected step size for each gradient, thus solving the non-convergence problem of Adam. Finally, we propose AdaShift, a novel adaptive learning rate method that decorrelates $v _ { t }$ and $g _ { t }$ via calculating $v _ { t }$ using temporally shifted gradient $g _ { t - n }$ .
In addition, based on our new perspective on adaptive learning rate methods, $v _ { t }$ is no longer necessarily the second moment of $g _ { t }$ , but a random variable that is independent of $g _ { t }$ and reflects the overall gradient scale. Thus, it is valid to calculate $v _ { t }$ with the spatial elements of previous gradients. We further found that when the spatial operation $\phi$ outputs a shared scalar for each block, the resulting algorithm turns out to be closely related to SGD, where each block has an overall adaptive learning rate and the relative gradient scale in each block is maintained. The experiment results demonstrate that AdaShift is able to solve the non-convergence issue of Adam. In the meantime, AdaShift achieves competitive and even better training and testing performance when compared with Adam.
# REFERENCES
Timothy Dozat. Incorporating nesterov momentum into adam. International Conference on Learning Representations, Workshop track, 2016.
Xavier Glorot and Yoshua Bengio. Understanding the difficulty of training deep feedforward neural networks. In Proceedings of the thirteenth international conference on artificial intelligence and statistics, pp. 249–256, 2010.
Ishaan Gulrajani, Faruk Ahmed, Martin Arjovsky, Vincent Dumoulin, and Aaron C Courville. Improved training of wasserstein gans. In Advances in Neural Information Processing Systems, pp. 5767–5777, 2017.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Delving deep into rectifiers: Surpassing human-level performance on imagenet classification. In Proceedings of the IEEE international conference on computer vision, pp. 1026–1034, 2015.
Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 770–778, 2016.
Gao Huang, Zhuang Liu, Laurens Van Der Maaten, and Kilian Q Weinberger. Densely connected convolutional networks. 2017.
Nitish Shirish Keskar and Richard Socher. Improving generalization performance by switching from adam to sgd. arXiv preprint arXiv:1712.07628, 2017.
Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014.
Minh-Thang Luong, Eugene Brevdo, and Rui Zhao. Neural machine translation (seq2seq) tutorial. https://github.com/tensorflow/nmt, 2017.
Ning Qian. On the momentum term in gradient descent learning algorithms. Neural networks, 12 (1):145–151, 1999.
Ali Rahimi and Ben Recht. test of time talk at nips 2017. URL http://www.argmin.net/ 2017/12/11/alchemy-addendum/.
Sashank J. Reddi, Satyen Kale, and Sanjiv Kumar. On the convergence of adam and beyond. In International Conference on Learning Representations, 2018. URL https://openreview. net/forum?id=ryQu7f-RZ.
Tijmen Tieleman and Geoffrey Hinton. Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude. COURSERA: Neural networks for machine learning, 4(2):26– 31, 2012.
Ashia C Wilson, Rebecca Roelofs, Mitchell Stern, Nati Srebro, and Benjamin Recht. The marginal value of adaptive gradient methods in machine learning. In Advances in Neural Information Processing Systems, pp. 4148–4158, 2017.
Matthew D Zeiler. Adadelta: an adaptive learning rate method. arXiv preprint arXiv:1212.5701, 2012.

 (a) Final result of $\theta$ for sequential problem after 2000 updates, varied with $\beta _ { 1 }$ and $\beta _ { 2 }$ .
(b) Critical value of $C$ with varying $\beta _ { 1 }$ and $\beta _ { 2 }$ under the sequential optimization setting.

 (d) Critical value of $C$ with varying $\beta _ { 1 }$ and $\beta _ { 2 }$ under the stochastic optimization setting.
(c) Final result of $\theta$ for stochastic problem after 2000 updates, varied with $\beta _ { 1 }$ and $\beta _ { 2 }$ .
Figure 8: Both $\beta _ { 1 }$ and $\beta _ { 2 }$ influence the direction and speed of optimization in Adam. Critical value of $C _ { t }$ , at which Adam gets into non-convergence, increases as $\beta _ { 1 }$ and $\beta _ { 2 }$ getting large. Leftmost two for the sequential online optimization problem and rightmost two for stochastic online problem.
# A THE RELATION AMONG $\beta _ { 1 }$ , $\beta _ { 2 }$ AND $C$
To provide an intuitive impression on the relation among $C , d , \beta _ { 1 } , \beta _ { 2 }$ and the convergence of Adam, we let $C = d = 6 $ , initialize $\theta _ { 1 } = 0$ , vary $\beta _ { 1 }$ and $\beta _ { 2 }$ among $[ 0 , 1 )$ and let Adam go through 2000 timesteps (iterations). The final result of $\theta$ is shown in Figure 8a. It suggests that for a fixed sequential online optimization problem, both of $\beta _ { 1 }$ and $\beta _ { 2 }$ determine the direction and speed of Adam optimization process. Furthermore, we also study the threshold point of $C$ and $d$ , under which Adam will change to the incorrect direction, for each fixed $\beta _ { 1 }$ and $\beta _ { 2 }$ that vary among $[ 0 , 1 )$ . To simplify the experiments, we keep $d = C$ such that the overall gradient of each epoch being $+ 1$ . The result is shown in Figure 8b, which suggests, at the condition of larger $\beta _ { 1 }$ or larger $\beta _ { 2 }$ , it needs a larger $C$ to make Adam stride on the opposite direction. In other words, large $\beta _ { 1 }$ and $\beta _ { 2 }$ will make the non-convergence rare to happen.
We also conduct the experiment in the stochastic problem to analyze the relation among $C$ , $\beta _ { 1 }$ , $\beta _ { 2 }$ and the convergence behavior of Adam. Results are shown in the Figure 8c and Figure 8d and the observations are similar to the previous: larger $C$ will cause non-convergence more easily and a larger $\beta _ { 1 }$ or $\beta _ { 2 }$ somehow help to resolve non-convergence issue. In this experiment, we set $\delta = 1$ .
Lemma 6 (Critical condition). In the sequential online optimization problem Equation 6, let $\alpha _ { t }$ being fixed, define $S ( \beta _ { 1 } , \beta _ { 2 } , C , d )$ to be the sum of the limits of step updates in a $d$ -step epoch:
$$\begin{array} { l } { \displaystyle { S ( \beta _ { 1 } , \beta _ { 2 } , C ) \triangleq \sum _ { i = 1 } ^ { d } \operatorname* { l i m } _ { n d \infty } \frac { m _ { n d + i } } { \sqrt { v _ { n d + i } } } . } } \end{array}$$
Let $S ( \beta _ { 1 } , \beta _ { 2 } , C ) = 0$ , assuming $\beta _ { 2 }$ and $C$ are large enough such that $v _ { t } \gg 1$ , we get the equation:
$$C + 1 = \frac { ( 1 - \beta _ { 1 } ^ { d } ) ( \sqrt { \beta _ { 2 } ^ { d } } - \beta _ { 1 } ^ { d } ) ( 1 - \sqrt { \beta _ { 2 } } ) } { ( 1 - \beta _ { 1 } ) ( \sqrt { \beta _ { 2 } } - \beta _ { 1 } ) ( 1 - \sqrt { \beta _ { 2 } ^ { d } } ) } .$$
Equation 19, though being quite complex, tells that both $\beta _ { 1 }$ and $\beta _ { 2 }$ are closely related to the counterexamples, and there exists a critical condition among these parameters.
# B THE ADASHIFT PSEUDO CODE
Algorithm 2 AdaShift: We use a first-in-first-out queue $Q$ to denote the averaging window with the
<table><tr><td>length of n. Push(Q,gt) denotes pushing vector gt to the tail of Q, while Pop(Q) pops and returns the head vector of Q.And W is the weight vector calculated via β1.</td></tr><tr><td>Input: n,β1,β2,,∈,00,{ft(0)}T=1,{at}T=1</td></tr><tr><td>1:set vo = O,po =1 2:W=[-1,Br-2,., 1,1/∑= 7</td></tr><tr><td>3:fort=i toTdo</td></tr><tr><td>4: gt=Vft(0t)</td></tr><tr><td>5: ift≤nthen</td></tr><tr><td>6: Push(Q,gt) 7: else</td></tr><tr><td>8: 9t-n = Pop(Q)</td></tr><tr><td>9: Push(Q,gt)</td></tr><tr><td>10: mt =W.Q</td></tr><tr><td>11: Pt =Pt-1β2</td></tr><tr><td>12: fori=1 to M do</td></tr><tr><td>13: Ut[i]=β2Ut-1[i]+(1-β2)(g²-n[i])</td></tr><tr><td>14: 0t[i]=0t-1[i]-αt/(√Ut[i]/(1-pt)+∈)·mt[i]</td></tr><tr><td>15: end for</td></tr><tr><td>16: end if 17: end for</td></tr></table>
We provided the anonymous code where a Tensorflow implementation of this algorithm is available.
# C CORRELATION BETWEEN $g _ { t }$ AND $v _ { t }$
In order to verify the correlation between $g _ { t }$ and $v _ { t }$ in Adam and AdaShift, we conduct experiments to calculate the correlation coefficient between $g _ { t }$ and $v _ { t }$ . We train the Multilayer Perceptron on MNIST until converge and gather the gradient of the second hidden layer of each step. Based on these data, we calculate $v _ { t }$ and the correlation coefficient between $g _ { t } [ i ]$ and $g _ { t - n } [ i ]$ , between $g _ { t } [ i ]$ and $g _ { t - n } [ j ]$ and between $g _ { t } [ i ]$ and $v _ { t } [ i ]$ of the last 10 epochs using the Pearson correlation coefficient, which is formulated as follows:
$$\rho = \frac { \sum _ { i = 1 } ^ { n } ( X _ { i } - \bar { X } ) ( Y _ { i } - \bar { Y } ) } { \sqrt { \sum _ { i = 1 } ^ { n } ( X _ { i } - \bar { X } ) ^ { 2 } } \sqrt { \sum _ { i = 1 } ^ { n } ( Y _ { i } - \bar { Y } ) ^ { 2 } } } .$$
To verify the temporal correlation between $g _ { t } [ i ]$ and $g _ { t - n } [ i ]$ , we range $n$ from 1 to 10 and calculate the average temporal correlation coefficient of all variables $i$ . Results are shown in Table 1.
Table 1: Temporal correlation coefficient between $g _ { t } [ i ]$ and $g _ { t - n } [ i ]$ .
<table><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>1</td><td rowspan=1 colspan=1>2</td><td rowspan=1 colspan=1>3</td><td rowspan=1 colspan=1>4</td><td rowspan=1 colspan=1>5</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>-0.000368929</td><td rowspan=1 colspan=1>-0.000989286</td><td rowspan=1 colspan=1>-0.001540511</td><td rowspan=1 colspan=1>-0.00116966</td><td rowspan=1 colspan=1>-0.001613395</td></tr><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>6</td><td rowspan=1 colspan=1>7</td><td rowspan=1 colspan=1>8</td><td rowspan=1 colspan=1>9</td><td rowspan=1 colspan=1>10</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>-0.001211721</td><td rowspan=1 colspan=1>0.000357474</td><td rowspan=1 colspan=1>-0.00082293</td><td rowspan=1 colspan=1>-0.001755237</td><td rowspan=1 colspan=1>-0.001267641</td></tr></table>
To verify the spatial correlation between $g _ { t } [ i ]$ and $g _ { t - n } [ j ]$ , we again range $n$ from 1 to 10 and randomly sample some pairs of $i$ and $j$ and calculate the average spatial correlation coefficient of all the selected pairs. Results are shown in Table 2.
To verify the correlation between $g _ { t } [ i ]$ and $v _ { t } [ i ]$ within Adam, we calculate $v _ { t }$ and the average correlation coefficient between $g _ { t } ^ { 2 }$ and $v _ { t }$ of all variables $i$ . The result is 0.435885276.
To verify the correlation between $g _ { t - n } [ i ]$ and $v _ { t } [ i ]$ within non-AdaShift and between $g _ { t - n } [ i ]$ and $v _ { t }$ within max-AdaShift, we range the keep number $n$ from 1 to 10 to calculate $v _ { t }$ and the average correlation coefficient of all variables $i$ . The result is shown in Table 3 and Table 4.
Table 2: Spatial correlation coefficient between $g _ { t } [ i ]$ and $g _ { t - n } [ j ]$ .
<table><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>1</td><td rowspan=1 colspan=1>2</td><td rowspan=1 colspan=1>3</td><td rowspan=1 colspan=1>4</td><td rowspan=1 colspan=1>5</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>-0.000609471</td><td rowspan=1 colspan=1>-0.001948853</td><td rowspan=1 colspan=1>-0.001426661</td><td rowspan=1 colspan=1>0.000904615</td><td rowspan=1 colspan=1>0.000329359</td></tr><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>6</td><td rowspan=1 colspan=1>7</td><td rowspan=1 colspan=1>8</td><td rowspan=1 colspan=1>9</td><td rowspan=1 colspan=1>10</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>0.000971337</td><td rowspan=1 colspan=1>-0.000644563</td><td rowspan=1 colspan=1>-0.00137805</td><td rowspan=1 colspan=1>-0.001147973</td><td rowspan=1 colspan=1>-0.000592037</td></tr></table>
Table 3: Correlation coefficient between $g _ { t - n } ^ { 2 } [ i ]$ and $v _ { t } [ i ]$ in non-AdaShift.
<table><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>1</td><td rowspan=1 colspan=1>2</td><td rowspan=1 colspan=1>3</td><td rowspan=1 colspan=1>4</td><td rowspan=1 colspan=1>5</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>-0.010897023</td><td rowspan=1 colspan=1>-0.010952548</td><td rowspan=1 colspan=1>-0.010890854</td><td rowspan=1 colspan=1>-0.010853069</td><td rowspan=1 colspan=1>-0.010810747</td></tr><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>6</td><td rowspan=1 colspan=1>7</td><td rowspan=1 colspan=1>8</td><td rowspan=1 colspan=1>9</td><td rowspan=1 colspan=1>10</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>-0.010777789</td><td rowspan=1 colspan=1>-0.01075946</td><td rowspan=1 colspan=1>-0.010739279</td><td rowspan=1 colspan=1>-0.010728553</td><td rowspan=1 colspan=1>-0.010720019</td></tr></table>
Table 4: Correlation coefficient between $g _ { t - n } ^ { 2 } [ i ]$ and $v _ { t }$ in max-AdaShift.
<table><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>1</td><td rowspan=1 colspan=1>2</td><td rowspan=1 colspan=1>3</td><td rowspan=1 colspan=1>4</td><td rowspan=1 colspan=1>5</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>-0.000706289</td><td rowspan=1 colspan=1>-0.000794959</td><td rowspan=1 colspan=1>-0.00076306</td><td rowspan=1 colspan=1>-0.000712474</td><td rowspan=1 colspan=1>-0.000668459</td></tr><tr><td rowspan=1 colspan=1>n</td><td rowspan=1 colspan=1>6</td><td rowspan=1 colspan=1>7</td><td rowspan=1 colspan=1>8</td><td rowspan=1 colspan=1>9</td><td rowspan=1 colspan=1>10</td></tr><tr><td rowspan=1 colspan=1>p</td><td rowspan=1 colspan=1>-0.000623162</td><td rowspan=1 colspan=1>-0.000566573</td><td rowspan=1 colspan=1>-0.000542046</td><td rowspan=1 colspan=1>-0.000598015</td><td rowspan=1 colspan=1>-0.000592707</td></tr></table>
# D PROOF OF THEOREM 1
Proof.
With bias correction, the formulation of $m _ { t }$ is written as follows
$$m _ { t } = \frac { ( 1 - \beta _ { 1 } ) \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } g _ { i } } { ( 1 - \beta _ { 1 } ) \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } } = \frac { \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } g _ { i } } { \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } } .$$
According to L’Hospitals rule, we can draw the following:
$$\operatorname* { l i m } _ { \beta _ { 1 } \to 1 } \sum _ { i = 1 } ^ { t } \beta _ { 1 } ^ { t - i } = \operatorname* { l i m } _ { \beta _ { 1 } \to 1 } \frac { 1 - \beta _ { 1 } ^ { t } } { 1 - \beta _ { 1 } } = t .$$
Thus,
$$\operatorname* { l i m } _ { \beta _ { 1 } \to 1 } m _ { t } = \frac { \sum _ { i = 1 } ^ { t } g _ { i } } { t } .$$
According to the definition of limitation, let $\begin{array} { r } { g ^ { * } = \frac { \sum _ { i = 1 } ^ { t } g _ { i } } { t } } \end{array}$ , we have, $\forall \epsilon > 0$ , $\exists \beta _ { 1 } \in ( 0 , 1 )$ , such that
$$\| m _ { t } - g ^ { * } \| _ { \infty } < \epsilon .$$
We set $\epsilon$ to be $\big | \frac { g ^ { * } } { 2 } \big |$ , then for each dimension of $m _ { t }$ , i.e. $m _ { t } [ i ]$ ,
$$\frac { g ^ { * } [ i ] } { 2 } \leq m _ { t } [ i ] \leq \frac { 3 g ^ { * } [ i ] } { 2 }$$
So, $m _ { t }$ shares the same sign with $g ^ { * }$ in every dimension.
Given it is a convex optimization problem, let the optimal parameter be $\theta ^ { * }$ , and the maximum step size is $\frac { \alpha _ { t } } { \sqrt { v _ { t } } } G$ that holds $\begin{array} { r } { \epsilon _ { 1 } / G < \frac { \bar { \alpha } _ { t } } { \sqrt { v _ { t } } } G < \epsilon _ { 2 } / G } \end{array}$ , we have,
$$\operatorname* { l i m } _ { t \to \infty } \| \theta _ { t } - \theta ^ { * } \| _ { \infty } < \epsilon _ { 2 } / G .$$
Given $\| \nabla f _ { t } ( \theta ) \| _ { \infty } \leq G$ , we have $f _ { t } ( \theta ) - f _ { t } ( \theta ^ { * } ) < \epsilon _ { 2 }$ , which implies the average regret
$$R ( T ) / T = \sum _ { t = 1 } ^ { T } [ f _ { t } ( \theta _ { t } ) - f _ { t } ( \theta ^ { * } ) ] / T < \epsilon _ { 2 } .$$
# E PROOF OF LEMMA 2
Proof. Let $\beta _ { 1 } , \beta _ { 2 } \in [ 0 , 1 )$ , $d \in \mathbb { N }$ , $1 \leq i \leq d$ and $i \in \mathbb N$ .
$$\begin{array} { l } { { \displaystyle m _ { n d + i } = ( 1 - \beta _ { 1 } ) \sum _ { j = 1 } ^ { n d + i } \beta _ { 1 } ^ { n d + i - j } g _ { j } } } \\ { { \displaystyle \quad \quad = ( 1 - \beta _ { 1 } ) \left[ ( C + 1 ) \sum _ { j = 0 } ^ { n } \beta _ { 1 } ^ { j d + i - 1 } - \sum _ { j = 0 } ^ { n d + i - 1 } \beta _ { 1 } ^ { j } \right] } } \\ { { \displaystyle \quad \quad = ( 1 - \beta _ { 1 } ) \left[ \frac { 1 - \beta _ { 1 } ^ { ( n + 1 ) d } } { 1 - \beta _ { 1 } ^ { d } } \beta _ { 1 } ^ { i - 1 } ( C + 1 ) - \frac { 1 - \beta _ { 1 } ^ { n d + i } } { 1 - \beta _ { 1 } } \right] } } \\ { { \displaystyle \quad \quad = \frac { 1 - \beta _ { 1 } ^ { ( n + 1 ) d } } { 1 - \beta _ { 1 } ^ { d } } ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { i - 1 } ( C + 1 ) - ( 1 - \beta _ { 1 } ^ { n d + i } ) } } \end{array}$$
For a fixed $d$ , as $n$ approach infinity, we get the limit of $m _ { n d + i }$ as:
$$\operatorname* { l i m } _ { n d \infty } m _ { n d + i } = \frac { 1 - \beta _ { 1 } } { 1 - \beta _ { 1 } ^ { d } } ( C + 1 ) \beta _ { 1 } ^ { i - 1 } - 1$$
Similarly, for $v _ { n d + i }$ :
$$\begin{array} { l } { { \displaystyle v _ { n d + i } = \left( 1 - \beta _ { 2 } \right) \sum _ { j = 1 } ^ { n d + i } \beta _ { 2 } ^ { n d + i - j } g _ { j } ^ { 2 } } } \\ { { \displaystyle \qquad = \left( 1 - \beta _ { 2 } \right) \left[ ( C ^ { 2 } - 1 ) \sum _ { j = 0 } ^ { n } \beta _ { 2 } ^ { j d + i - 1 } + \sum _ { j = 0 } ^ { n d + i - 1 } \beta _ { 2 } ^ { j } \right] } } \\ { { \displaystyle \qquad = \left( 1 - \beta _ { 2 } \right) \left[ \frac { 1 - \beta _ { 2 } ^ { ( n + 1 ) d } } { 1 - \beta _ { 2 } ^ { d } } \beta _ { 2 } ^ { i - 1 } ( C ^ { 2 } - 1 ) + \frac { 1 - \beta _ { 2 } ^ { n d + i } } { 1 - \beta _ { 2 } } \right] } } \\ { { \displaystyle \qquad = \frac { 1 - \beta _ { 2 } ^ { ( n + 1 ) d } } { 1 - \beta _ { 2 } ^ { d } } \left( 1 - \beta _ { 2 } \right) \beta _ { 2 } ^ { i - 1 } ( C + 1 ) - \left( 1 - \beta _ { 2 } ^ { n d + i } \right) } } \end{array}$$
For a fixed $d$ , as $n$ approach infinity, we get the limit of $v _ { n d + i }$ as:
$$\operatorname * { l i m } _ { n d \infty } v _ { n d + i } = \frac { 1 - \beta _ { 2 } } { 1 - \beta _ { 2 } ^ { d } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { i - 1 } + 1 .$$
# F PROOF OF LEMMA 3
Proof. First, we define $\widetilde { V } _ { i }$ as:
$$\widetilde V _ { i } = \operatorname* { l i m } _ { n d \infty } \frac { 1 } { \sqrt { v _ { n d + i } } } = \frac { 1 } { \sqrt { \frac { 1 - \beta _ { 2 } } { 1 - \beta _ { 2 } ^ { d } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { ( i - 1 ) } + 1 } }$$
where $1 \leq i \leq d$ and $i \in \mathbb N$ . And $\widetilde { V } _ { i }$ has a period of $d$ . Let $t ^ { ' } = t - n d$ , then we can draw:
$$\begin{array} { r l } { \underset { \mathrm { C } ^ { \prime } \times \mathrm { R } ^ { \prime } } { = } } & { V _ { \mathrm { { o } } } ( \lambda _ { 2 , 1 } ) = : - \underset { \mathrm { C } ^ { \prime } \times \mathrm { R } ^ { \prime } } { \overset { \cdot } { \sum } } \underset { \mathrm { C } ^ { \prime } \times \mathrm { R } ^ { \prime } } { = } \langle \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } \rangle _ { \mathrm { C } ^ { \prime } } ^ { 2 } \mathrm { { R } } \mathrm { { R } } ^ { - 1 } } \\ & { - \underset { \mathrm { C } ^ { \prime } \times \mathrm { R } ^ { \prime } } { = } \langle \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } \rangle _ { \mathrm { C } ^ { \prime } } ^ { 2 } \mathrm { { R } } \mathrm { { R } } ^ { - 1 } + 1 } \\ & { - \underset { \mathrm { C } ^ { \prime } \times \mathrm { R } ^ { \prime } } { = } \langle \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } \rangle _ { \mathrm { C } ^ { \prime } } ^ { 2 } \mathrm { { R } } \mathrm { { R } } ^ { - 1 } } \\ & { - \underset { \mathrm { C } ^ { \prime } \times \mathrm { R } ^ { \prime } } { = } \langle \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } \rangle _ { \mathrm { C } ^ { \prime } } ^ { 2 } \mathrm { { R } } \mathrm { { R } } ^ { - 1 } } \\ & - \underset { \mathrm { C } ^ { \prime } \times \mathrm { R } ^ { \prime } } { = } \langle \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } , \frac { \mathrm { S } } { \mathrm { R } ^ { \prime } } \rangle _ { \mathrm { C } ^ { \prime } } \\ & - \underset \mathrm { C } ^ { \prime } \times \mathrm \end{array}$$
Thus, we can get the forward difference of $k ( g _ { n d + i } )$ as:
$$\begin{array} { l } { \underset { \displaystyle \mathcal { A } \to \infty } { \operatorname* { l i m } } k ( g _ { n d + i + 1 } ) - \underset { n d \to \infty } { \operatorname* { l i m } } k ( g _ { n d + i } ) = \displaystyle \sum _ { l = 1 } ^ { \infty } \beta _ { 1 } ^ { ( l - 1 ) d } \left[ ( 1 - \beta _ { 1 } ) ^ { 2 } \displaystyle \sum _ { j = 0 } ^ { \infty } \beta _ { 1 } ^ { j } \cdot \widetilde { V } _ { j + i + 1 } + ( 1 - \beta _ { 1 } ) ^ { 2 } \displaystyle \sum _ { j = 0 } ^ { \infty } \beta _ { 1 } ^ { j } \cdot \widetilde { V } _ { j + i + 1 } \right. + } \\ { \left. \left. = ( 1 - \beta _ { 1 } ) ^ { 2 } \displaystyle \sum _ { l = 1 } ^ { \infty } \beta _ { 1 } ^ { ( l - 1 ) d } \displaystyle \sum _ { j = 0 } ^ { d - 1 } \beta _ { 1 } ^ { j } \cdot \left[ \widetilde { V } _ { j + i + 1 } - \widetilde { V } _ { i } \right] \right. \right. } \end{array}$$
$\widetilde { V } _ { n d + 1 i }$ monotonically increases within one period, when $1 \leq i \leq d$ and $i \in \mathbb N$ . And the weigh $\beta _ { 1 } ^ { j }$ for every difference term $\left[ \widetilde { V } _ { j + i + 1 } - \widetilde { V } _ { i } \right]$ is fixed when $i$ varies. Thus, the weighted summation Pd−1j=0 βj1 · h $\begin{array} { r } { \sum _ { j = 0 } ^ { d - 1 } \beta _ { 1 } ^ { j } \cdot \left[ \widetilde { V } _ { j + i + 1 } - \widetilde { V } _ { i } \right] } \\ { . } \end{array}$ is monotonically decreasing from positive to negative. In other words, the forward difference is monotonically decreasing, such that there exists $j$ , $1 \leq j \leq d$ and $\operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + 1 } )$ is the maximum among all net updates. Moreover, it is obvious that $\operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + 1 } )$ is the minimum.
Hence, we can draw the conclusion: $\exists 1 \leq j \leq d$ , such that
$$\operatorname* { l i m } _ { n d \to \infty } k ( C ) = \operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + 1 } ) < \operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + 2 } ) < \cdots < \operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + j } )$$
and
$$\operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + j } ) > \operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + j + 1 } ) > \cdots > \operatorname* { l i m } _ { n d \to \infty } k ( g _ { n d + d + 1 } ) = \operatorname* { l i m } _ { n d \to \infty } k ( C ) ,$$
where $K ( C )$ is the net update factor for gradient $g _ { i } = C$ .
# G PROOF OF LEMMA 4
Lemma 7. 1 For a bounded random variable $X$ and a differentiable function $f ( x )$ , the expectation of $f ( X )$ is as follows:
$$\mathbb { E } [ f ( X ) ] = f ( \mathbb { E } [ X ] ) + \frac { f ^ { \prime \prime } ( \mathbb { E } [ X ] ) } { 2 } D ( X ) + R _ { 3 }$$
where $D ( X )$ is variance of $X$ , and $R _ { 3 }$ is as follows:
$$\begin{array} { r l } & { R _ { 3 } = \displaystyle \frac { f ^ { [ 3 ] } ( \alpha ) } { 3 } \mathbb { E } ( X - \mathbb { E } [ X ] ) ^ { 3 } + } \\ & { \quad + \displaystyle \int _ { | x - \mathbb { E } [ X ] | > c } \left( f ( \mathbb { E } [ X ] ) + f ^ { ' } ( \mathbb { E } [ X ] ) ( x - \mathbb { E } [ X ] ) ^ { 2 } + f ( X ) \right) d F ( x ) } \end{array}$$
$F ( x )$ is the distribution function of $X , R _ { 3 }$ is a small quantity under some condition. And $c$ is large enough, such that: for any $\epsilon > 0$ ,
$$P ( X \in [ \mathbb { E } [ X ] - c , \mathbb { E } [ X ] + c ] ) = P ( | X - \mathbb { E } [ X ] | \leq c ) \leq 1 - \epsilon$$
Proof. (Proof of Lemma 4 ) In the stochastic online optimization problem equation 7, the gradient subjects the distribution as:
$$g _ { i } = \left\{ \begin{array} { l l } { { C , } } & { { \mathrm { w i t h ~ p r o b a b i l i t y } \ : p : = \frac { 1 + \delta } { C + 1 } ; } } \\ { { - 1 , } } & { { \mathrm { w i t h ~ p r o b a b i l i t y } \ : 1 - p : = \frac { C - \delta } { C + 1 } . } } \end{array} \right. ,$$
Then we can get the expectation of $g _ { i }$ :
$$\begin{array} { c } { { \cdot \qquad \mathbb { E } [ g _ { i } ] = \delta } } \\ { { \mathbb { E } [ g _ { i } ^ { 2 } ] = C ^ { 2 } \cdot \displaystyle \frac { 1 + \delta } { C + 1 } + \displaystyle \frac { C - \delta } { C + 1 } = C + \delta ( C + 1 ) } } \\ { { D [ g _ { i } ] = C + \delta ( C + 1 ) - \delta ^ { 2 } } } \\ { { \mathbb { E } [ g _ { i } ^ { 4 } ] = C ( C ^ { 2 } - C + 1 ) + \delta ( C - 1 ) ( C ^ { 2 } + 1 ) } } \\ { { D [ g _ { i } ^ { 2 } ] = C ^ { 3 } - 2 C ^ { 2 } + C + \delta ( C ^ { 3 } - 3 C ^ { 2 } - C - 1 ) - \delta ^ { 2 } ( C + 1 ) ^ { 2 } } } \end{array}$$
Meanwhile, under the assumption that gradients are i.i.d., the expectation and variance of $v _ { i }$ are as following when $n d \infty$ :
$$\mathbb { E } [ v _ { i } ] = \operatorname* { l i m } _ { i \to \infty } ( 1 - \beta _ { 2 } ) \sum _ { j = 1 } ^ { i } \beta _ { 2 } ^ { i - j } \mathbb { E } [ g _ { j } ^ { 2 } ] = \operatorname* { l i m } _ { i \to \infty } ( 1 - \beta _ { 2 } ^ { i } ) \mathbb { E } [ g _ { j } ^ { 2 } ] = C + \delta ( C + 1 )$$
$$D [ v _ { i } ] = \operatorname * { l i m } _ { i \to \infty } ( 1 - \beta _ { 2 } ) \sum _ { j = 1 } ^ { i } \beta _ { 2 } ^ { i - j } D [ g _ { j } ^ { 2 } ] = \operatorname * { l i m } _ { i \to \infty } ( 1 - \beta _ { 2 } ^ { i } ) D [ g _ { j } ^ { 2 } ] = D [ g _ { j } ^ { 2 } ]$$
Then, for the gradient $g _ { i }$ , the net update factor is as follows:
$$k ( g _ { i } ) = \sum _ { t = 0 } ^ { \infty } \frac { ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { t } } { \sqrt { \beta _ { 2 } ^ { t + 1 } v _ { i - 1 } + ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } \cdot g _ { i } ^ { 2 } + ( 1 - \beta _ { 2 } ) \sum _ { j = 1 } ^ { t } \beta _ { 2 } ^ { t - j } g _ { i + j } ^ { 2 } } }$$
It should to be clarified that we define $\textstyle \sum _ { j = 1 } ^ { t } \beta _ { 2 } ^ { t - j } g _ { i + j } ^ { 2 }$ equal to zero when $t = 0$ . Then we define $X _ { t }$ as:
$$\begin{array} { r l } & { \quad X _ { t } = \beta _ { 2 } ^ { t + 1 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } \cdot g _ { t } ^ { 2 } + ( 1 - \beta _ { 2 } ) \sum _ { j = 0 } ^ { \ell - 1 } g _ { t + j } ^ { 2 } } \\ & { \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & { \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad } \\ & \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \end{array}$$
For the function $\textstyle f ( x ) = { \frac { 1 } { \sqrt { x } } }$ :
$$f ^ { ^ { \prime \prime } } ( x ) = { \frac { 3 \cdot x ^ { - 5 / 2 } } { 8 } }$$
According to lemma 7, we can the expectation of $f ( X _ { t } )$ as follows:
$$\mathbb { E } [ f ( X _ { t } ) ] = \left( \mathbb { E } [ X _ { t } ] \right) ^ { - 1 / 2 } + { \frac { 3 } { 8 } } { \big ( } \mathbb { E } [ X _ { t } ] { \big ) } ^ { - 5 / 2 } \cdot D [ X _ { t } ]$$
$\mathbb { E } [ X _ { t } ]$ and $D [ X _ { t } ]$ are expressed by equation 35 and equation 38. Then we can obtain the expectation expression of net update factor as follows:
$$\begin{array} { r } { k ( g _ { i } ) = \sum _ { t = 0 } ^ { \infty } ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { t } \left[ \frac { 1 } { \sqrt { ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } g _ { i } ^ { 2 } + ( 1 + \beta _ { 2 } ^ { t + 1 } - \beta _ { 2 } ^ { k } ) \mathbb { E } [ g _ { i } ^ { 2 } ] } } + \frac { 3 D _ { t } } { 8 [ ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } g _ { i } ^ { 2 } + ( 1 + \beta _ { 2 } ^ { t + 1 } - \beta _ { 2 } ^ { t } ) \mathbb { E } [ g _ { i } ^ { 2 } ] ] ^ { \frac { 5 } { 2 } } } \right] } \end{array}$$
where $D _ { t } = D [ X _ { k } ]$ . Then for gradient $C$ and $- 1$ , the net update factor is as follows:
$$\begin{array} { r } { k ( C ) = \sum _ { t = 0 } ^ { \infty } ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { t } \left[ \frac { 1 } { \sqrt { ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } C ^ { 2 } + ( 1 + \beta _ { 2 } ^ { t + 1 } - \beta _ { 2 } ^ { k } ) \mathbb E [ g _ { i } ^ { 2 } ] } } + \frac { 3 D _ { t } } { 8 [ ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } C ^ { 2 } + ( 1 + \beta _ { 2 } ^ { t + 1 } - \beta _ { 2 } ^ { t } ) \mathbb E [ g _ { i } ^ { 2 } ] ] ^ { \frac { 5 } { 2 } } } \right] } \end{array}$$
and
$$\begin{array} { r } { k ( - 1 ) = \sum _ { t = 0 } ^ { \infty } ( 1 - \beta _ { 1 } ) \beta _ { 1 } ^ { t } \left[ \frac { 1 } { \sqrt { ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } + ( 1 + \beta _ { 2 } ^ { t + 1 } - \beta _ { 2 } ^ { k } ) \mathbb { E } [ g _ { \ast } ^ { 2 } ] } } + \frac { 3 D _ { t } } { 8 [ ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { t } + ( 1 + \beta _ { 2 } ^ { t + 1 } - \beta _ { 2 } ^ { t } ) \mathbb { E } [ g _ { \ast } ^ { 2 } ] ] ^ { \frac { 5 } { 2 } } } \right] } \end{array}$$
We can see that each term in the infinite series of $k ( C )$ is smaller than the corresponding one in $k ( - 1 )$ . Thus, $k ( C ) < k ( - 1 )$ .
# H PROOF OF LEMMA 6
Proof. From Lemma 2, we can get:
$$\operatorname* { l i m } _ { n d \infty } { \frac { m _ { n d + i } } { \sqrt { v _ { n d + i } } } } = { \frac { { \frac { 1 - \beta _ { 1 } } { 1 - \beta _ { 1 } ^ { d } } } ( C + 1 ) \beta _ { 1 } ^ { i - 1 } - 1 } { \sqrt { { \frac { 1 - \beta _ { 2 } } { 1 - \beta _ { 2 } ^ { d } } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { i - 1 } + 1 } } }$$
We sum up all updates in an epoch, and define the summation as $S ( \beta _ { 1 } , \beta _ { 2 } , C )$ .
$$\displaystyle { \mathcal { S } } ( \beta _ { 1 } , \beta _ { 2 } , C ) = \sum _ { i = 1 } ^ { d } \operatorname* { l i m } _ { n d \infty } { \frac { m _ { n d + i } } { \sqrt { v _ { n d + i } } } }$$
Assume $\beta _ { 2 }$ and $C$ are large enough such that $v _ { t } \gg 1$ , we get the approximation of limit of $v _ { n d + i }$ as:
$$\operatorname* { l i m } _ { n d \infty } v _ { n d + i } \approx \frac { 1 - \beta _ { 2 } } { 1 - \beta _ { 2 } ^ { d } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { i - 1 }$$
Then we can draw the expression of $S ( \beta _ { 1 } , \beta _ { 2 } , C )$ as:
$$\begin{array} { r l } { \xi ( \beta _ { 1 } , \beta _ { 2 } , C ) = \displaystyle \sum _ { i = 1 } ^ { d } \frac { \frac { 1 - \beta _ { i } } { 2 \beta _ { 2 } ^ { i } } ( C + 1 ) \beta _ { 1 } ^ { i - 1 } - 1 } { \sqrt { \frac { 1 - \beta _ { i } } { 1 - \beta _ { 2 } ^ { i } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { i - 1 } } } } \\ { = \displaystyle \sum _ { i = 1 } ^ { d } \frac { \frac { 1 - \beta _ { i } } { 2 \beta _ { 1 } ^ { i } } ( C + 1 ) \beta _ { 1 } ^ { i - 1 } } { \sqrt { \frac { 1 - \beta _ { i } } { 1 - \beta _ { 2 } ^ { i } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { i - 1 } } } - \displaystyle \sum _ { i = 1 } ^ { d } \frac { 1 } { \sqrt { \frac { 1 - \beta _ { 2 } } { 1 - \beta _ { 2 } ^ { i } } ( C ^ { 2 } - 1 ) \beta _ { 2 } ^ { i - 1 } } } } \\ { = \displaystyle \sqrt { \frac { 1 - \beta _ { 2 } ^ { d } } { ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { d - 1 } } } \sqrt { \frac { C + 1 } { C - 1 } } \cdot \frac { 1 - \beta _ { 1 } } { 1 - \beta _ { 1 } ^ { d } } \cdot \sqrt { \frac { \beta _ { 2 } ^ { d } - \beta _ { 1 } ^ { d } } { \sqrt { 2 } - \beta _ { 1 } } } - \sqrt { \frac { 1 - \beta _ { 2 } ^ { d } } { ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { d - 1 } } } \cdot \frac { 1 } { \sqrt { C ^ { 2 } - 1 } } \frac { \sqrt { \beta _ { 2 } ^ { d } } } { \sqrt { \beta _ { 2 } } } } \\ = \displaystyle \sqrt { \frac { 1 - \beta _ { 2 } ^ { d } } { ( 1 - \beta _ { 2 } ) \beta _ { 2 } ^ { d - 1 } ( C - 1 ) } } [ \frac { ( 1 - \beta _ { 1 } ) ( \beta _ { 2 } ^ { d } - \beta _ { 1 } ^ { d } ) \sqrt { C + 1 } } { ( 1 - \beta _ { 1 } ^ { d } ) ( \sqrt { 2 } - \beta _ { 1 } ) } - \frac { \sqrt { \beta _ { 2 } ^ { d } } - 1 } \sqrt { C + 1 } ( \sqrt { \beta _ { 2 } } - \end{array}$$
Let $S ( \beta _ { 1 } , \beta _ { 2 } , C ) = 0$ , we get the equation about critical condition:
$$C + 1 = \frac { ( 1 - \beta _ { 1 } ^ { d } ) ( \sqrt { \beta _ { 2 } ^ { d } } - \beta _ { 1 } ^ { d } ) ( 1 - \sqrt { \beta _ { 2 } } ) } { ( 1 - \beta _ { 1 } ) ( \sqrt { \beta _ { 2 } } - \beta _ { 1 } ) ( 1 - \sqrt { \beta _ { 2 } ^ { d } } ) }$$
# I HYPER-PARAMETERS INVESTIGATION
# I.1 HYPER-PARAMETERS SETTING
Here, we list all hyper-parameter setting of all above experiments.
Table 5: Hyper-parameter setting of logistic regression in Figure 2.
<table><tr><td rowspan=1 colspan=1>Optimizer</td><td rowspan=1 colspan=1>learning rate</td><td rowspan=1 colspan=1>β1</td><td rowspan=1 colspan=1>β</td><td rowspan=1 colspan=1>n</td></tr><tr><td rowspan=1 colspan=1>SGD</td><td rowspan=1 colspan=1>0.1</td><td rowspan=1 colspan=1>N/A</td><td rowspan=1 colspan=1>N/A</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>Adam</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AMSGrad</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>non-AdaShift</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>1</td></tr><tr><td rowspan=1 colspan=1>max-AdaShift</td><td rowspan=1 colspan=1>0.01</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>1</td></tr></table>
Table 6: Hyper-parameter setting of Multilayer Perceptron on MNIST in Figure 3.
<table><tr><td rowspan=1 colspan=1>Optimizer</td><td rowspan=1 colspan=1>learning rate</td><td rowspan=1 colspan=1>β1</td><td rowspan=1 colspan=1>β2</td><td rowspan=1 colspan=1>n</td></tr><tr><td rowspan=1 colspan=1>SGD</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>N/A</td><td rowspan=1 colspan=1>N/A</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>Adam</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AMSGrad</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>non-AdaShift</td><td rowspan=1 colspan=1>0.0005</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>1</td></tr><tr><td rowspan=1 colspan=1>max-AdaShift</td><td rowspan=1 colspan=1>0.01</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>1</td></tr></table>
Table 7: Hyper-parameter setting of WGAN-GP in Figure 7a.
<table><tr><td rowspan=1 colspan=1>Optimizer</td><td rowspan=1 colspan=1>learning rate</td><td rowspan=1 colspan=1>β1</td><td rowspan=1 colspan=1>β</td><td rowspan=1 colspan=1>n</td></tr><tr><td rowspan=1 colspan=1>Adam</td><td rowspan=1 colspan=1>1e-5</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AMSGrad</td><td rowspan=1 colspan=1>1e-5</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AdaShift</td><td rowspan=1 colspan=1>1.5e-4</td><td rowspan=1 colspan=1>0</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>1</td></tr></table>
Table 8: Hyper-parameter setting of Neural Machine Translation BLEU in Figure 7b.
<table><tr><td rowspan=1 colspan=1>Optimizer</td><td rowspan=1 colspan=1>learning rate</td><td rowspan=1 colspan=1>β1</td><td rowspan=1 colspan=1>β</td><td rowspan=1 colspan=1>n</td></tr><tr><td rowspan=1 colspan=1>Adam</td><td rowspan=1 colspan=1>0.0001</td><td rowspan=1 colspan=1>0.9</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AMSGrad</td><td rowspan=1 colspan=1>0.0001</td><td rowspan=1 colspan=1>0.9</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AdaShift</td><td rowspan=1 colspan=1>0.01</td><td rowspan=1 colspan=1>0.9</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>30</td></tr></table>
Table 9: Hyper-parameter setting of ResNet on Cifar-10 in Figure 4, DenseNet on Cifar-10 in Figure 5 and DenseNet on Tiny-Imagenet in Figure 6.
<table><tr><td rowspan=1 colspan=1>Optimizer</td><td rowspan=1 colspan=1>learning rate</td><td rowspan=1 colspan=1>β1</td><td rowspan=1 colspan=1>β</td><td rowspan=1 colspan=1>n</td></tr><tr><td rowspan=1 colspan=1>Adam</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>0.9</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AMSGrad</td><td rowspan=1 colspan=1>0.001</td><td rowspan=1 colspan=1>0.9</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>N/A</td></tr><tr><td rowspan=1 colspan=1>AdaShift</td><td rowspan=1 colspan=1>0.01</td><td rowspan=1 colspan=1>0.9</td><td rowspan=1 colspan=1>0.999</td><td rowspan=1 colspan=1>10</td></tr></table>
# I.2 LEARNING RATE $\alpha _ { t }$ SENSITIVITY
In this section, we discuss the learning rate $\alpha _ { t }$ sensitivity of AdaShift. We set $\alpha _ { t } \in$ $\{ 0 . 1 , 0 . 0 1 , 0 . 0 0 1 \}$ and let $n = 1 0$ , $\beta _ { 1 } = 0 . 9$ and $\beta _ { 2 } ~ = ~ 0 . 9 9 9$ . The results are shown in Figure 9 and Figure 10. Empirically, we found that when using the max spatial operation, the best learning rate for AdaShift is around ten times of Adam.
 Figure 9: Learning rate sensitivity experiment with ResNet on CIFAR-10.
 Figure 10: Learning rate sensitivity experiment with DenseNet on CIFAR-10.
# I.3 $\beta _ { 1 }$ AND $\beta _ { 2 }$ SENSITIVITY
In this section, we discuss the $\beta _ { 1 }$ and $\beta _ { 2 }$ sensitivity of AdaShift. We set $\alpha = 0 . 0 1$ , $n = 1 0$ and let $\beta _ { 1 } \in \{ 0 , 0 . 9 \}$ and $\beta _ { 2 } \in \{ 0 . 9 , 0 . 9 9 , 0 . 9 9 9 \}$ . The results are shown in Figure 11 and Figure 12. According to the results, AdaShift holds a low sensitivity to $\beta _ { 1 }$ and $\beta _ { 2 }$ . In some tasks, using the first moment estimation (with $\beta _ { 1 } = 0 . 9$ and $n = 1 0$ ) or using a large $\beta _ { 2 }$ , e.g., 0.999 can attain better performance. The suggested parameters setting is $n = 1 0 , \beta _ { 1 } = 0 . 9 , \beta _ { 2 } = 0 . 9 9 9$ .
 Figure 11: $\beta _ { 1 }$ and $\beta _ { 2 }$ sensitivity experiment with ResNet on CIFAR-10.
 Figure 12: $\beta _ { 1 }$ and $\beta _ { 2 }$ sensitivity experiment with DenseNet on CIFAR-10.
# I.4 $n$ AND $m$ SENSITIVITY
In this section, we discuss the $n$ sensitivity of AdaShift. Here we also test a extended version of first moment estimation where it only uses the latest $m$ gradients $( m \leq n )$ ):
$$v _ { t } = \beta _ { 2 } v _ { t - 1 } + ( 1 - \beta _ { 2 } ) \phi ( g _ { t - n } ^ { 2 } ) \mathrm { a n d } m _ { t } = \frac { \sum _ { i = 0 } ^ { m - 1 } \beta _ { 1 } ^ { i } g _ { t - i } } { \sum _ { i = 0 } ^ { m - 1 } \beta _ { 1 } ^ { i } } .$$
We set $\beta _ { 1 } = 0 . 9$ , $\beta _ { 2 } = 0 . 9 9 9$ . The results are shown in Figure 13, Figure 14 and Figure 15. In these experiments, AdaShift is fairly stable when changing $n$ and $m$ . We have not find a clear pattern on the performance change with respect to $n$ and $m$ .
 Figure 13: $n$ sensitivity experiment with DenseNet on Tiny-ImageNet.
 Figure 14: $m$ sensitivity experiment with DenseNet on Tiny-ImageNet.
 Figure 15: $n$ and $m$ sensitivity experiment with Neural Machine Translation BLEU.
# J TEMPORAL-ONLY AND SPATIAL-ONLY
In our proposed algorithm, we apply a spatial operation on the temporally shifted gradient $g _ { t - n }$ to update $v _ { t }$ : $v _ { t } [ i ] \ \stackrel { } { = } \ \beta _ { 2 } v _ { t - 1 } [ i ] \ \stackrel { } { + } \ ( 1 - \stackrel { } { \beta } _ { 2 } ) \phi ( g _ { t - n } ^ { \bar { 2 } } [ i ] )$ . It is based on the temporal independent assumption, i.e., $g _ { t - n }$ is independent of $g _ { t }$ . And according to our argument in Section 4.2, one can further assume every element in $g _ { t - n }$ is independent of the $i$ -th dimension of $g _ { t }$ .
We purposely avoid involving the spatial elements of the current gradient $g _ { t }$ , where the independence might not holds: when a sample which is rare and has a large gradient appear in the mini-batch $x _ { t }$ , the overall scale of gradient $g _ { t }$ might increase. However, for the temporally already decorrelation $g _ { t - i }$ , further taking the advantage of the spatial irrelevance will not suffer from this problem.
We here provide extended experiments on two variants of AdaShift: (i) AdaShift (temporal-only), which only uses the vanilla temporal independent assumption and evaluate $v _ { t }$ with: $v _ { t } = \beta _ { 2 } v _ { t - 1 } +$ $( 1 - \beta _ { 2 } ) g _ { t - n } ^ { \bar { 2 } }$ ; (ii) AdaShift (spatial-only), which directly uses the spatial elements without temporal shifting.
 Figure 16: ResNet on CIFAR-10.
 Figure 17: DenseNet on CIFAR-10.
According to our experiments, AdaShift (temporal-only), i.e., without the spatial operation, is less stable than AdaShift. In some tasks, AdaShift (temporal-only) works just fine; while in some other cases, AdaShift (temporal-only) suffers from explosive gradient and requires a relatively small learning rate. The performance of AdaShift (spatial-only) is close to Adam. More experiments for AdaShift (spatial-only) are included in the next section.
# K EXTENDED EXPERIMENTS: NADAM AND ADASHIFT(SPACE ONLY)
In this section, we extend the experiments and add the comparisons with Nadam and AdaShift (spatial-only). The results are shown in Figure 18, Figure19 and Figure20. According to these experiments, Nadam and AdaShift (spatial-only) share similar performence as Adam.
 Figure 18: ResNet on CIFAR-10.
 Figure 19: DenseNet on CIFAR-10.
 Figure 20: DenseNet on Tiny-ImageNet.
Rahimi & Recht raise the point, at test of time talk at NIPS 2017, that it is suspicious that gradient descent (aka back-propagation) is ultimate solution for optimization. A ill-conditioned quadratic problem with Two Layer Linear Net is showed to be challenging for gradient descent based methods, while alternative solutions, e.g., Levenberg-Marquardt, may converge faster and better. The problem is defined as follows:
$$L ( W _ { 1 } , W _ { 2 } ; A ) = \mathbb { E } _ { x \in N ( 0 , 1 ) } \| W _ { 1 } W _ { 2 } x - A x \| ^ { 2 }$$
where $A$ is some known badly conditioned matrix $k = 1 0 ^ { 2 0 }$ or $1 0 ^ { 5 }$ ), and $W _ { 1 }$ and $W _ { 2 }$ are the trainable parameters.
We test SGD, Adam and AdaShift with this problem, the results are shown in Figure 21, Figure 24. It turns out as long as the training goes enough long, SGD, Adam, AdaShift all basically converge in this problem. Though SGD is significantly better than Adam and AdaShift.
We would tend to believe this is a general issue of adaptive learning rate method when comparing with vanilla SGD. Because these adaptive learning rate methods generally are scale-invariance, i.e., the step-size in terms of $g _ { t } / s q r t ( v _ { t } )$ is basically around one, which makes it hard to converge very well in such a ill-conditioning quadratic problem. SGD, in contrast, has a step-size $g _ { t }$ ; as the training converges SGD would have a decreasing step-size, makes it much easier to converge better. The above analysis is confirmed with Figure 22 and Figure 23, with a decreasing learning rate, Adam and AdaShfit both converge very good.
 Figure 21: Ill-conditioned quadratic problem, with fixed learning rate.
 Figure 22: Ill-conditioned quadratic problem, with linear learning rate decay.
 Figure 23: Ill-conditioned quadratic problem, with exp learning rate decay.
 Figure 24: Ill-conditioned quadratic problem, with fixed learning rate and insufficient iterations.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492# LEARNING HOW TO EXPLAIN NEURAL NETWORKS: PATTERNNET AND PATTERNATTRIBUTION
Pieter-Jan Kindermans∗ Google Brain pikinder@google.com
Kristof T. Schutt & Maximilian Alber ¨ TU Berlin {kristof.schuett,maximilian.alber}@tu-berlin.de
# Klaus-Robert Muller ¨ †
TU Berlin klaus-robert.mueller@tu-berlin.de
Dumitru Erhan & Been Kim Google Brain {dumitru,beenkim}@google.com
# Sven Dahne ¨ ‡
TU Berlin sven.daehne@tu-berlin.de
# ABSTRACT
DeConvNet, Guided BackProp, LRP, were invented to better understand deep neural networks. We show that these methods do not produce the theoretically correct explanation for a linear model. Yet they are used on multi-layer networks with millions of parameters. This is a cause for concern since linear models are simple neural networks. We argue that explanation methods for neural nets should work reliably in the limit of simplicity, the linear models. Based on our analysis of linear models we propose a generalization that yields two explanation techniques (PatternNet and PatternAttribution) that are theoretically sound for linear models and produce improved explanations for deep networks.
# 1 INTRODUCTION
Deep learning made a huge impact on a wide variety of applications (Krizhevsky et al., 2012; Sutskever et al., 2014; LeCun et al., 2015; Schmidhuber, 2015; Mnih et al., 2015; Silver et al., 2016) and recent neural network classifiers have become excellent at detecting relevant signals (e.g., the presence of a cat) contained in input data points such as images by filtering out all other, nonrelevant and distracting components also present in the data. This separation of signal and distractors is achieved by passing the input through many layers with millions of parameters and nonlinear activation functions in between, until finally at the output layer, these models yield a highly condensed version of the signal, e.g. a single number indicating the probability of a cat being in the image.
While deep neural networks learn efficient and powerful representations, they are often considered a ‘black-box’. In order to better understand classifier decisions and to gain insight into how these models operate, a variety techniques have been proposed (Simonyan et al., 2014; Yosinski et al., 2015; Nguyen et al., 2016; Baehrens et al., 2010; Bach et al., 2015; Montavon et al., 2017; Zeiler & Fergus, 2014; Springenberg et al., 2015; Zintgraf et al., 2017; Sundararajan et al., 2017; Smilkov et al., 2017). These methods for explaining classifier decisions operate under the assumption that it is possible to propagate the condensed output signal back through the classifier to arrive at something that shows how the relevant signal was encoded in the input and thereby explains the classifier decision. Simply put, if the classifier detected a cat, the visualization should point to the cat-relevant aspects of the input image from the perspective of the network. Techniques that are based on this principle include saliency maps from network gradients (Baehrens et al., 2010; Simonyan et al., 2014), DeConvNet (Zeiler & Fergus, 2014, DCN), Guided BackProp (Springenberg et al., 2015, GBP),
 Figure 1: Illustration of explanation approaches. Function and signal approximators visualize the explanation using the original color channels. The attribution is visualized as a heat map of pixelwise contributions to the output
Layer-wise Relevance Propagation (Bach et al., 2015, LRP) and the Deep Taylor Decomposition (Montavon et al., 2017, DTD), Integrated Gradients (Sundararajan et al., 2017) and SmoothGrad (Smilkov et al., 2017).
The merit of explanation methods is often demonstrated by applying them to state-of-the-art deep learning models in the context of high dimensional real world data, such as ImageNet, where the provided explanation is intuitive to humans. Unfortunately, theoretical analysis as well as quantitative empirical evaluations of these methods are lacking.
Deep neural networks are essentially a composition of linear transformations connected with nonlinear activation functions. Since approaches, such as DeConvNet, Guided BackProp, and LRP, back-propagate the explanations in a layer-wise fashion, it is crucial that the individual linear layers are handled correctly. In this work we show that these gradient-based methods fail to recover the signal even for a single-layer architecture, i.e. a linear model. We argue that therefore they cannot be expected to reliably explain a deep neural network and demonstrate this with quantitative and qualitative experiments. In particular, we provide the following key contributions:
• We analyze the performance of existing explanation approaches in the controlled setting of a linear model (Sections 2 and 3). • We categorize explanation methods into three groups – functions, signals and attribution (see Fig. 1) – that require fundamentally different interpretations and are complementary in terms of information about the neural network (Section 3). • We propose two novel explanation methods – PatternNet and PatternAttribution – that alleviate shortcomings of current approaches, as discovered during our analysis, and improve explanations in real-world deep neural networks visually and quantitatively (Sections 4 and 5).
This presents a step towards a thorough analysis of explanation methods and suggests qualitatively and measurably improved explanations. These are crucial requirements for reliable explanation techniques, in particular in domains, where explanations are not necessarily intuitive, e.g. in health and the sciences Schutt et al. (2017). ¨
Notation and scope Scalars are lowercase letters $( i )$ , column vectors are bold $( \pmb { u } )$ , element-wise multiplication is $( \odot )$ . The covariance between $\textbf { \em u }$ and $\textbf { { v } }$ is $\boldsymbol { \mathbf { \rho } } _ { \mathbf { 0 } } \mathbf { v } [ \pmb { u } , \pmb { v } ]$ , the covariance of $\textbf { \em u }$ and $i$ is $\mathrm { c o v } [ \bar { \boldsymbol { u } } , i ]$ . The variance of a scalar random variable $i$ is $\sigma _ { i } ^ { 2 }$ . Estimates of random variables will have a hat $( \hat { u } )$ . We analyze neural networks excluding the final soft-max output layer. To allow for analytical treatment, we only consider networks with linear neurons optionally followed by a rectified linear unit (ReLU), max-pooling or soft-max. We analyze linear neurons and nonlinearities independently such that every neuron has its own weight vector. These restrictions are similar to those in the saliency map (Simonyan et al., 2014), DCN (Zeiler & Fergus, 2014), GBP (Springenberg et al., 2015), LRP (Bach et al., 2015) and DTD (Montavon et al., 2017). Without loss of generality, biases are considered constant neurons to enhance clarity.
 Figure 2: For linear models, i.e., a simple neural network, the weight vector does not explain the signal it detects Haufe et al. (2014). The data ${ \pmb x } = y { \pmb a } _ { s } + \epsilon { \pmb a } _ { d }$ is color-coded w.r.t. the output $\mathbf { \Psi } y = \pmb { w } ^ { T } \mathbf { \em x }$ . Only the signal $\mathit { s } = y \mathbf { a } _ { s }$ contributes to $y$ . The weight vector $\pmb { w }$ does not agree with the signal direction, since its primary objective is canceling the distractor. Therefore, rotations of the basis vector $\mathbf { \mu } _ { a _ { d } }$ of the distractor with constant signal $\pmb { s }$ lead to rotations of the weight vector (right).
# 2 UNDERSTANDING LINEAR MODELS
In this section, we analyze explanation methods for deep neural network, starting with the simplest neural network setting: a purely linear model and data sampled from a linear generative model. This setup allows us to (i) fully control how signal and distractor components are encoded in the input data and (ii) analytically track how the resulting explanation relates to the known signal component. This analysis allows us then to highlight shortcomings of current explanation approaches that carry over to deep neural networks.
Consider the following toy example (see Fig. 2) where we generate data $_ { \textbf { \em x } }$ as:
$$\begin{array} { r l r l r l r l } { x = s + d } & { } & & { \quad s = a _ { s } y , } & { \quad } & { \mathrm { ~ w i t h ~ } a _ { s } = \left( 1 , 0 \right) ^ { T } , } & { } & { \quad y \in [ - 1 , 1 ] } \\ & { } & & { \quad d = a _ { d } \epsilon , } & { } & & { \mathrm { ~ w i t h ~ } a _ { d } = \left( 1 , 1 \right) ^ { T } , } & { } & { \epsilon \sim \mathcal { N } \left( \mu , \sigma ^ { 2 } \right) . } \end{array}$$
We train a linear regression model to extract $y$ from $_ { \textbf { \em x } }$ . By construction, $\pmb { s }$ is the signal in our data, i.e., the part of $_ { \textbf { \em x } }$ containing information about $y$ . Using the terminology of Haufe et al. (2014) the distractor $^ d$ obfuscates the signal making the detection task more difficult. To optimally extract $y$ , our model has to be able to filter out the distractor $^ d$ . This is why the weight vector is also called the filter. In the example, $\mathbf { \boldsymbol { w } } = \left[ 1 , - 1 \right] ^ { T }$ fulfills this convex task.
From this example, we can make several observations: The optimal weight vector $\textbf { \em w }$ does not align, in general, with the signal direction $\mathbf { \delta } _ \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathbf { \delta } \mathrm { \delta } \mathbf { \delta } \mathbf { \delta } \mathrm { \delta } \mathbf { \delta } \mathrm { \delta } \mathbf { \delta } \mathrm { \delta } \mathbf { \delta } \mathrm { \delta } \mathbf { \delta } \mathrm { \delta } \mathrm { \delta } \mathbf { \delta } \mathrm { \delta } \mathrm { \delta } \mathbf { \delta } \mathrm { \delta } \mathrm { \delta } \mathrm { \delta } \mathrm { \delta } \mathrm \mathbf { \delta } \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm { \delta } \mathrm \mathrm \mathrm { \delta } \mathrm \mathrm \mathrm { \delta } \mathrm \mathrm \delta \mathrm \mathrm { \delta } \delta \mathrm \mathrm \delta \mathrm \mathrm \mathrm { \delta } \delta \delta \mathrm \delta \mathrm \mathrm \delta \mathrm \delta \mathrm \delta \mathrm \delta \mathrm \delta \mathrm \delta \mathrm \delta \delta \mathrm \delta \delta \delta \mathrm \delta \delta \delta \delta \delta \delta \mathrm \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta \delta$ , but tries to filter the contribution of the distractor (see Fig. 2). This is optimally solved when the weight vector is orthogonal to the distractor ${ \pmb w } ^ { T } { \pmb d } = 0$ . Therefore, when the direction of the distractor $\mathbf { \delta } _ { \mathbf { \alpha } \mathbf { \delta } \mathbf { \alpha } \mathbf { \textit { a } } }$ changes, $\textbf { \em w }$ must follow, as illustrated on the right hand side of the figure. On the other hand, a change in signal direction $\mathbf { \delta } _ { a _ { s } }$ can be compensated for by a change in sign and magnitude of $\pmb { w }$ such that $\mathbf { \bar { w } } ^ { T } \pmb { a } _ { s } \equiv 1$ , but the direction stays constant.
The fact that the direction of the weight vector in a linear model is largely determined by the distractor implies that given only the weight vector, we cannot know what part of the input produces the output $y$ . On the contrary, the direction $\mathbf { \delta } _ { a _ { s } }$ must be learned from data.
Now assume that we have additive isotropic Gaussian noise. The mean of the noise can easily be compensated for with a bias change. Therefore, we only have to consider the zero-mean case. Since isotropic Gaussian noise does not contain any correlations or structure, the only way to remove it is by averaging over different measurements. It is not possible to cancel it out effectively by using a well-chosen weight vector. However, it is well known that adding Gaussian noise shrinks the weight vector and corresponds to L2 regularization. In the absence of a structured distractor, the smallest weight vector $\textbf { \em w }$ such that ${ \pmb w } ^ { T } { \pmb a } _ { s } = 1$ is the one in the direction of the signal. Therefore in practice both these effects influence the actual weight vector.
As already indicated above, deep neural networks are essentially a composition of linear layers and non-linear activation functions. In the next section, we will show that gradient-based methods, e.g., DeConvNet, Guided BackProp, and LRP, are not able to distinguish signal from distractor in a linear model and therefore back-propagate sub-optimal explanations in deeper networks. This analysis allows us to develop improved layer-wise explanation techniques and to demonstrate quantitative and qualitative better explanations for deep neural networks.
Terminology Throughout this manuscript we will use the following terminology: The filter $\pmb { w }$ tells us how to extract the output $y$ optimally from data $_ { \textbf { \em x } }$ . The pattern $\mathbf { \delta } _ { a _ { s } }$ is the direction in the data along which the desired output $y$ varies. Both constitute the signal $\textbf { \em s } = \textbf { \em a } _ { s } y$ , i.e., the contributing part of $_ { \textbf { \em x } }$ . The distractor $^ d$ is the component of the data that does not contain information about the desired output.
# 3 OVERVIEW OF EXPLANATION APPROACHES AND THEIR BEHAVIOR
In this section, we take a look at a subset of explanation methods for individual classifier decisions and discuss how they are connected to our analysis of linear models in the previous section. Fig. 1 gives an overview of the different types of explanation methods which can be divided into function, signal and attribution visualizations. These three groups all present different information about the network and complement each other.
Functions – gradients, saliency map Explaining the function in input space corresponds to describing the operations the model uses to extract $y$ from $_ { \textbf { \em x } }$ . Since deep neural networks are highly nonlinear, this can only be approximated. The saliency map estimates how moving along a particular direction in input space influences $y$ (i.e., sensitivity analysis) where the direction is given by the model gradient (Baehrens et al., 2010; Simonyan et al., 2014). In case of a linear model $y = \dot { \pmb { w } } ^ { T } \pmb { x }$ , the saliency map reduces to analyzing the weights $\partial y / \partial x = w$ . Since it is mostly determined by the distractor, as demonstrated above, it is not representing the signal. It tells us how to extract the signal, not what the signal is in a deep neural network.
Signal – DeConvNet, Guided BackProp, PatternNet The signal $\pmb { s }$ detected by the neural network is the component of the data that caused the networks activations. Zeiler & Fergus (2014) formulated the goal of these methods as ”[...] to map these activities back to the input pixel space, showing what input pattern originally caused a given activation in the feature maps”.
In a linear model, the signal corresponds to $\mathbf { \boldsymbol { s } } = \mathbf { \boldsymbol { a } } _ { s } \boldsymbol { y }$ . The pattern $\mathbf { \delta } _ { \mathbf { \alpha } \mathbf { \delta } _ { a _ { s } } }$ contains the signal direction, i.e., it tells us where a change of the output variable is expected to be measurable in the input (Haufe et al., 2014). Attempts to visualize the signal for deep neural networks were made using DeConvNet (Zeiler & Fergus, 2014) and Guided BackProp (Springenberg et al., 2015). These use the same algorithm as the saliency map, but treat the rectifiers differently (see Fig. 1): DeConvNet leaves out the rectifiers from the forward pass, but adds additional ReLUs after each deconvolution, while Guided BackProp uses the ReLUs from the forward pass as well as additional ones. The back-projections for the linear components of the network correspond to a superposition of what are assumed to be the signal directions of each neuron. For this reason, these projections must be seen as an approximation of the features that activated the higher layer neuron. It is not a reconstruction in input space (Zeiler & Fergus, 2014).
For the simplest of neural networks – the linear model – these visualizations reduce to the gradient1. They show the filter $\pmb { w }$ and neither the pattern $\mathbf { \delta } _ { a _ { s } }$ , nor the signal $\pmb { s }$ . Hence, DeConvNet and Guided BackProp do not guarantee to produce the detected signal for a linear model, which is proven by our toy example in Fig. 2. Since they do produce compelling visualizations, we will later investigate whether the direction of the filter $\pmb { w }$ coincides with the direction of the signal $\pmb { s }$ . We will show that this is not the case and propose a new approach, PatternNet (see Fig. 1), to estimate the correct direction that improves upon the DeConvNet and Guided BackProp visualizations.
Attribution – LRP, Deep Taylor Decomposition, PatternAttribution Finally, we can look at how much the signal dimensions contribute to the output through the layers. This will be referred to as the attribution. For a linear model, the optimal attribution would be obtained by element-wise multiplying the signal with the weight vector: $\mathbf { \boldsymbol { r } } ^ { i n p u t } = \mathbf { \boldsymbol { w } } \odot \mathbf { \boldsymbol { a } } y$ , with $\odot$ the element-wise multiplication. Bach et al. (2015) introduced layer-wise relevance propagation (LRP) as a decomposition of pixel-wise contributions (called relevances). Montavon et al. (2017) extended this idea and proposed the deep Taylor decomposition (DTD). The key idea of DTD is to decompose the activation of a neuron in terms of contributions from its inputs. This is achieved using a first-order Taylor expansion around a root point $\scriptstyle { \mathbf { { \mathit { x } } } } _ { 0 }$ with ${ \pmb w } ^ { T } { \pmb x } _ { 0 } = 0$ . The relevance of the selected output neuron $i$ is initialized with its output from the forward pass. The relevance from neuron $i$ in layer $l$ is re-distributed towards its input as:
$$r _ { i } ^ { o u t p u t } = y , \qquad r _ { j \neq i } ^ { o u t p u t } = 0 , \qquad r ^ { l - 1 , i } = \frac { w \odot ( x - x _ { 0 } ) } { w ^ { T } x } r _ { i } ^ { l } .$$
To obtain the relevance for neuron $i$ in layer $l - 1$ the incoming relevances from all connected neurons $j$ in layer $l$ are summed
$$r _ { i } ^ { l - 1 } = \sum _ { j } r _ { i } ^ { l - 1 , j } .$$
Here we can safely assume that ${ \pmb w } ^ { T } { \pmb x } > 0$ because a non-active ReLU unit from the forward pass stops the re-distribution in the backward pass. This is identical to how a ReLU stops the propagation of the gradient. The difficulty in the application of the deep Taylor decomposition is the choice of the root point $\scriptstyle { \pmb x } _ { 0 }$ , for which many options are available. It is important to recognize at this point that selecting a root point for the DTD corresponds to estimating the distractor $\scriptstyle { \pmb { x } } _ { 0 } = { \pmb { d } }$ and, by that, the signal $\hat { \pmb { s } } = \pmb { x } - \pmb { x } _ { 0 }$ . PatternAttribution is a DTD extension that learns from data how to set the root point.
Summarizing, the function extracts the signal from the data by removing the distractor. The attribution of output values to input dimensions shows how much an individual component of the signal contributes to the output, which is what LRP calls relevance.
# 4 LEARNING TO ESTIMATE THE SIGNAL
Visualizing the function has proven to be straightforward (Baehrens et al., 2010; Simonyan et al., 2014). In contrast, visualizing the signal (Haufe et al., 2014; Zeiler & Fergus, 2014; Springenberg et al., 2015) and the attribution (Bach et al., 2015; Montavon et al., 2017; Sundararajan et al., 2017) is more difficult. It requires a good estimate of what is the signal and what is the distractor. In the following section we first propose a quality measure for neuron-wise signal estimators. This allows us to evaluate existing approaches and, finally, derive signal estimators that optimize this criterion. These estimators will then be used to explain the signal (PatternNet) and the attribution (PatternAttribution). All mentioned techniques as well as our proposed signal estimators treat neurons independently, i.e., the full explanation will be a superposition of neuron-wise explanations.
# 4.1 QUALITY CRITERION FOR SIGNAL ESTIMATORS
Recall that the input data $_ { \textbf { \em x } }$ comprises both signal and distractor: ${ \pmb x } = { \pmb s } + { \pmb d }$ , and that the signal contributes to the output but the distractor does not. Assuming the filter $\textbf { \em w }$ has been trained sufficiently well to extract $y$ , we have
$$\begin{array} { r } { \boldsymbol { w } ^ { T } \boldsymbol { x } = \boldsymbol { y } , \quad \boldsymbol { w } ^ { T } \boldsymbol { s } = \boldsymbol { y } , \quad \boldsymbol { w } ^ { T } \boldsymbol { d } = 0 . } \end{array}$$
Note that estimating the signal based on these conditions alone is an ill-posed problem. We could limit ourselves to linear estimators of the form $\hat { \pmb { s } } = \pmb { u } ( \pmb { w } ^ { T } \pmb { u } ) ^ { - 1 } \pmb { y }$ , with $\textbf { \em u }$ a random vector such that $\pmb { w } ^ { T } \pmb { u } \neq 0$ . For such an estimator, the signal estimate $\hat { \pmb { s } } = \pmb { u } \left( \pmb { w } ^ { T } \pmb { u } \right) ^ { - 1 } \ b { y }$ satisfies $\mathbf { \boldsymbol { w } } ^ { T } \hat { \mathbf { \boldsymbol { s } } } = \boldsymbol { y }$ . This implies the existence of an infinite number of possible rules for the DTD as well as infinitely many back-projections for the DeConvNet family.
To alleviate this issue, we introduce the following quality measure $\rho$ for a signal estimator $S ( { \pmb x } ) = \hat { \pmb s }$ that will be written with explicit variances and covariances using the shorthands $\hat { \pmb { d } } = \pmb { x } - \pmb { S } ( \pmb { x } )$ and
$$y = \pmb { w } ^ { T } \pmb { x } \colon$$
$$\rho ( S ) = 1 - \operatorname* { m a x } _ { \pmb { v } } c o r r \left( \pmb { w } ^ { T } \pmb { x } , \pmb { v } ^ { T } \left( \pmb { x } - S ( \pmb { x } ) \right) \right) = 1 - \operatorname* { m a x } _ { \pmb { v } } \frac { \pmb { v } ^ { T } \mathrm { c o v } [ \hat { d } , y ] } { \sqrt { \sigma _ { \pmb { v } ^ { T } \hat { d } } ^ { 2 } \sigma _ { y } ^ { 2 } } } .$$
This criterion introduces an additional constraint by measuring how much information about $y$ can be reconstructed from the residuals $\mathbf { \Delta } \mathbf { x } - \hat { \mathbf { \mu } } _ { s }$ using a linear projection. The best signal estimators remove most of the information iinvariant to scaling, we constrain ${ \pmb v } ^ { T } \hat { \pmb d }$ residuals and thto have varian $\sigma _ { v ^ { T } \hat { d } } ^ { 2 } = \sigma _ { y } ^ { 2 }$ $\rho ( S )$ . Since the correlding the optimal $\textbf { { v } }$ ion isfor a fixed amounts to a least-squares regression from $\hat { \ b { d } }$ to $y$ . This enables us to assess the quality of signal estimators efficiently.
# 4.2 EXISTING SIGNAL ESTIMATORS
Let us now discuss two signal estimators that have been used in previous approaches.
$S _ { x }$ – the identity estimator The naive approach to signal estimation is to assume the entire data is signal and there are no distractors:
$$S _ { x } ( { \pmb x } ) = { \pmb x } .$$
With this being plugged into the deep Taylor framework, we obtain the $z$ -rule (Montavon et al., 2017) which is equivalent to LRP (Bach et al., 2015). For a linear model, this corresponds to $\mathbf { \Delta } \mathbf { \mathbf { \mathit { r } } } = \mathbf { \mathit { w } } \odot \mathbf { \mathbf { \mathit { x } } }$ as the attribution. It can be shown that for ReLU and max-pooling networks, the $z$ -rule reduces to the element-wise multiplication of the input and the saliency map (Shrikumar et al., 2016; Kindermans et al., 2016). This means that for a whole network, the assumed signal is simply the original input image. It also implies that, if there are distractors present in the data, they are included in the attribution:
$$\pmb { r } = \pmb { w } \odot \pmb { x } = \pmb { w } \odot \pmb { s } + \pmb { w } \odot \pmb { d } .$$
When moving through the layers by applying the filters $\pmb { w }$ during the forward pass, the contributions from the distractor $^ d$ are cancelled out. However, they cannot be cancelled in the backward pass by the element-wise multiplication. The distractor contributions $\omega \odot d$ that are included in the LRP explanation cause the noisy nature of the visualizations based on the $z$ -rule.
$S _ { w }$ – the filter based estimator The implicit assumption made by DeConvNet and Guided BackProp is that the detected signal varies in the direction of the weight vector $\pmb { w }$ . This weight vector has to be normalized in order to be a valid signal estimator. In the deep Taylor decomposition framework this corresponds to the $w ^ { 2 }$ -rule and results in the following signal estimator:
$$S _ { \pmb { w } } ( \pmb { x } ) = \frac { \pmb { w } } { \pmb { w } ^ { T } \pmb { w } } \pmb { w } ^ { T } \pmb { x } .$$
For a linear model, this produces an attribution of the form $\frac { { \pmb w } \odot { \pmb w } } { { \pmb w } ^ { T } . { \pmb w } } \textcircled { y }$ . This estimator does not reconstruct the proper signal in the toy example of section 2. Empirically it is also sub-optimal in our experiment in Fig. 3.
# 4.3 PATTERNNET AND PATTERNATTRIBUTION
We suggest to learn the signal estimator $S$ from data by optimizing the previously established criterion. A signal estimator $S$ is optimal with respect to Eq. (1) if the correlation is zero for all possible ${ \pmb v } \colon \forall { \pmb v } , \mathrm { c o v } [ y , \hat { \pmb d } ] { \pmb v } = { \bf 0 }$ . This is the case when there is no covariance between $y$ and $\hat { \ b { d } }$ . Because of linearity of the covariance and since $\hat { \pmb { d } } = \pmb { x } - \pmb { S } ( \pmb { x } )$ the above condition leads to
$$\mathrm { c o v } [ y , \hat { d } ] = { \bf 0 } \Rightarrow \mathrm { c o v } [ { \pmb x } , y ] = \mathrm { c o v } [ S ( { \pmb x } ) , y ] .$$
It is important to recognize that the covariance is a summarizing statistic and consequently the problem can still be solved in multiple ways. We will present two possible solutions to this problem. Note that when optimizing the estimator, the contribution from the bias neuron will be considered 0 since it does not covary with the output $y$ .
$S _ { a }$ – The linear estimator A linear neuron can only extract linear signals $\pmb { s }$ from its input $_ { \textbf { \em x } }$ . Therefore, we could assume a linear dependency between $\pmb { s }$ and $y$ , yielding a signal estimator:
$$\begin{array} { r } { S _ { \pmb { a } } ( \pmb { x } ) = \pmb { a } \pmb { w } ^ { T } \pmb { x } . } \end{array}$$
Plugging this into Eq. (2) and optimising for $^ { a }$ yields
$$\operatorname { c o v } [ { \pmb x } , { \pmb y } ] = \operatorname { c o v } [ { \pmb a } { \pmb w } ^ { T } { \pmb x } , { \pmb y } ] = { \pmb a } \mathrm { c o v } [ { \pmb y } , { \pmb y } ] \Rightarrow { \pmb a } = \frac { \mathrm { c o v } [ { \pmb x } , { \pmb y } ] } { \sigma _ { y } ^ { 2 } } .$$
Note that this solution is equivalent to the approach commonly used in neuro-imaging (Haufe et al., 2014) despite different derivation. With this approach we can recover the signal of our toy example in section 2. It is equivalent to the filter-based approach only if the distractors are orthogonal to the signal. We found that the linear estimator works well for the convolutional layers. However, when using this signal estimator with ReLUs in the dense layers, there is still a considerable correlation left in the distractor component (see Fig. 3).
$S _ { a _ { + - } }$ – The two-component estimator To move beyond the linear signal estimator, it is crucial to understand how the rectifier influences the training. Since the gate of the ReLU closes for negative activations, the weights only need to filter the distractor component of neurons with $y > 0$ . Since this allows the neural network to apply filters locally, we cannot assume a global distractor component. We rather need to distinguish between the positive and negative regime:
$$\pmb { x } = \left\{ \begin{array} { l l } { \pmb { s } _ { + } + \pmb { d } _ { + } } & { \mathrm { i f } \ y > 0 } \\ { \pmb { s } _ { - } + \pmb { d } _ { - } } & { \mathrm { o t h e r w i s e } } \end{array} \right.$$
Even though signal and distractor of the negative regime are canceled by the following ReLU, we still need to make this distinction in order to approximate the signal. Otherwise, information about whether a neuron fired would be retained in the distractor. Thus, we propose the two-component signal estimator:
$$\begin{array} { r } { S _ { \boldsymbol { a } + - } ( \boldsymbol { x } ) = \left\{ \begin{array} { l l } { \boldsymbol { a } _ { + } \boldsymbol { w } ^ { T } \boldsymbol { x } , \quad \mathrm { i f } \ \boldsymbol { w } ^ { T } \boldsymbol { x } > 0 } \\ { \boldsymbol { a } _ { - } \boldsymbol { w } ^ { T } \boldsymbol { x } , \quad \mathrm { o t h e r w i s e } } \end{array} \right. } \end{array}$$
Next, we derive expressions for the patterns ${ \pmb a } _ { + }$ and $\mathbf { \delta } \mathbf { a } _ { - }$ . We denote expectations over $_ { \textbf { \em x } }$ within the positive and negative regime with $\bar { \mathbb { E } _ { + } } \left[ x \right]$ and $\mathbb { E } _ { - } \left[ { \pmb x } \right]$ , respectively. Let $\pi _ { + }$ be the expected ratio of inputs $_ { \textbf { \em x } }$ with $\mathbf { \Sigma } \mathbf { w } ^ { T } \mathbf { x } > 0$ . The covariance of data/signal and output become:
$$\begin{array} { r l r } { \mathrm { c o v } [ { \pmb x } , { y } ] = } & { } & { \pi _ { + } \left( \mathbb { E } _ { + } \left[ { \pmb x } { \pmb y } \right] - \mathbb { E } _ { + } \left[ { \pmb x } \right] \mathbb { E } \left[ { \pmb y } \right] \right) + \frac { } { } \left( 1 - \pi _ { + } \right) \left( \mathbb { E } _ { - } \left[ { \pmb x } { \pmb y } \right] - \mathbb { E } _ { - } \left[ { \pmb x } \right] \mathbb { E } \left[ { \pmb y } \right] \right) } \\ { \mathrm { c o v } [ { \pmb s } , { y } ] = } & { } & { \pi _ { + } \left( \mathbb { E } _ { + } \left[ { \pmb s } { \pmb y } \right] - \mathbb { E } _ { + } \left[ { \pmb s } \right] \mathbb { E } \left[ { \pmb y } \right] \right) + \frac { } { } \left( 1 - \pi _ { + } \right) \left( \mathbb { E } _ { - } \left[ { \pmb s } { \pmb y } \right] - \mathbb { E } _ { - } \left[ { \pmb s } \right] \mathbb { E } \left[ { \pmb y } \right] \right) } \end{array}$$
Assuming both covariances are equal, we can treat the positive and negative regime separately using Eq. (2) to optimize the signal estimator:
$$\begin{array} { r l r } { { \mathbb E } _ { + } \left[ { \pmb x } { \pmb y } \right] - { \mathbb E } _ { + } \left[ { \pmb x } \right] { \mathbb E } \left[ { \pmb y } \right] } & { = } & { { \mathbb E } _ { + } \left[ { \pmb s } { \pmb y } \right] - { \mathbb E } _ { + } \left[ { \pmb s } \right] { \mathbb E } \left[ { \pmb y } \right] } \end{array}$$
Plugging in Eq. (5) and solving for ${ \pmb a } _ { + }$ yields the required parameter $( a _ { - }$ analogous).
$$\begin{array} { r l r } { \pmb { a } _ { + } } & { = } & { \frac { \mathbb { E } _ { + } \left[ \pmb { x } \pmb { y } \right] - \mathbb { E } _ { + } \left[ \pmb { x } \right] \mathbb { E } \left[ \pmb { y } \right] } { \pmb { w } ^ { T } \mathbb { E } _ { + } \left[ \pmb { x } \pmb { y } \right] - \pmb { w } ^ { T } \mathbb { E } _ { + } \left[ \pmb { x } \right] \mathbb { E } \left[ \pmb { y } \right] } } \end{array}$$
The solution for $S _ { a + - }$ reduces to the linear estimator when the relation between input and output is linear. Therefore, it solves our introductory linear example correctly.
PatternNet and PatternAttribution Based on the presented analysis, we propose PatternNet and PatternAttribution as illustrated in Fig. 1. PatternNet yields a layer-wise back-projection of the estimated signal to input space. The signal estimator is approximated as a superposition of neuron-wise, nonlinear signal estimators $S _ { a + - }$ in each layer. It is equal to the computation of the gradient where during the backward pass the weights of the network are replaced by the informative directions. In Fig. 1, a visual improvement over DeConvNet and Guided Backprop is apparent.
PatternAttribution exposes the attribution ${ \pmb w } \odot { \pmb a } _ { + }$ and improves upon the layer-wise relevance propagation (LRP) framework (Bach et al., 2015). It can be seen as a root point estimator for the DeepTaylor Decomposition (DTD). Here, the explanation consists of neuron-wise contributions of the estimated signal to the classification score. By ignoring the distractor, PatternAttribution can reduce the noise and produces much clearer heat maps. By working out the back-projection steps in the Deep-Taylor Decomposition with the proposed root point selection method, it becomes obvious that PatternAttribution is also analogous to the backpropagation operation. In this case, the weights are replaced during the backward pass by ${ \pmb w } \odot { \pmb a } _ { + }$ .
 Figure 3: Evaluating $\rho ( S )$ for VGG-16 on ImageNet. Higher values are better. The gradient $( S _ { w } )$ , linear estimator $( S _ { a } )$ and nonlinear estimator $( S _ { a _ { + - } } )$ are compared. An estimator using random directions is the baseline. The network has 5 blocks with 2/3 convolutional layers and 1 max-pooling layer each, followed by 3 dense layers.
 Figure 4: Image degradation experiment on all 50.000 images in the ImageNet validation set. The effect on the classifier output is measured. A steeper decrease is better.
# 5 EXPERIMENTS AND DISCUSSION
To evaluate the quality of the explanations, we focus on the task of image classification. Nevertheless, our method is not restricted to networks operating on image inputs. We used Theano (Bergstra et al., 2010) and Lasagne (Dieleman et al., 2015) for our implementation. We restrict the analysis to the well-known ImageNet dataset (Russakovsky et al., 2015) using the pre-trained VGG-16 model (Simonyan & Zisserman, 2015). Images were rescaled and cropped to $2 2 4 \mathbf { x } 2 2 4$ pixels. The signal estimators are trained on the first half of the training dataset.
The vector $\pmb { v }$ , used to measure the quality of the signal estimator $\rho ( { \pmb x } )$ in Eq. (1), is optimized on the second half of the training dataset. This enables us to test the signal estimators for generalization. All the results presented here were obtained using the official validation set of 50000 samples. The validation set was not used for training the signal estimators, nor for training the vector $\pmb { v }$ to measure the quality. Consequently our results are obtained on previously unseen data.
The linear and the two component signal estimators are obtained by solving their respective closed form solutions (Eq. (4) and Eq. (8)). With a highly parallelized implementation using 4 GPUs this could be done in 3-4 hours. This can be considered reasonable given that several days are required to train the actual network. The quality of a signal estimator is assessed with Eq. (1). Solving it with the closed form solution is computationally prohibitive since it must be repeated for every single weight vector in the network. Therefore we optimize the equivalent least-squares problem using stochastic mini-batch gradient descent with ADAM Kingma & Ba (2015) until convergence. This was implemented on a NVIDIA Tesla K40 and took about 24 hours per optimized signal estimator.
After learning to explain, individual explanations are computationally cheap since they can be implemented as a back-propagation pass with a modified weight vector. As a result, our method produces explanations at least as fast as the work by Dabkowski & Gal (2017) on real time saliency. However, our method has the advantage that it is not only applicable to image models but is a generalization of the theory commonly used in neuroimaging Haufe et al. (2014).
 Figure 5: Top: signal. Bottom: attribution. For the trivial estimator $S _ { x }$ the original input is the signal. This is not informative w.r.t. how the network operates.
Measuring the quality of signal estimators In Fig. 3 we present the results from the correlation measure $\rho ( { \pmb x } )$ , where higher values are better. We use random directions as baseline signal estimators. Clearly, this approach removes almost no correlation. The filter-based estimator $S _ { w }$ succeeds in removing some of the information in the first layer. This indicates that the filters are similar to the patterns in this layer. However, the gradient removes much less information in the higher layers. Overall, it does not perform much better than the random estimator. This implies that the weights do not correspond to the detected stimulus in a neural network. Hence the implicit assumptions about the signal made by DeConvNet and Guided BackProp is not valid. The optimized estimators remove much more of the correlations across the board. For convolutional layers, $S _ { a }$ and $S _ { a + - }$ perform comparably in all but one layer. The two component estimator $S _ { a + - }$ is best in the dense layers.
Image degradation The first experiment was a direct measurement of the quality of the signal estimators of individual neurons. The second one is an indirect measurement of the quality, but it considers the whole network. We measure how the prediction (after the soft-max) for the initially selected class changes as a function of corrupting more and more patches based on the ordering assigned by the attribution (see Samek et al., 2016). This is also related to the work by Zintgraf et al. (2017). In this experiment, we split the image in non-overlapping patches of $9 \mathrm { x } 9$ pixels. We compute the attribution and sum all the values within a patch. We sort the patches in decreasing order based on the aggregate heat map value. In step $n = 1 . . 1 0 0$ we replace the first $n$ patches with the their mean per color channel to remove the information in this patch. Then, we measure how this influences the classifiers output. We use the estimators from the previous experiment to obtain the function-signal attribution heat maps for evaluation. A steeper decay indicates a better heat map.
Results are shown in Fig. 4. The baseline, in which the patches are randomly ordered, performs worst. The linear optimized estimator $S _ { a }$ performs quite poorly, followed by the filter-based estimator $S _ { w }$ . The trivial signal estimator $S _ { x }$ performs just slightly better. However, the two component model $S _ { a + - }$ leads to the fastest decrease in confidence in the original prediction by a large margin. Its excellent quantitative performance is also backed up by the visualizations discussed next.
Qualitative evaluation In Fig. 5, we compare all signal estimators on a single input image. For the trivial estimator $S _ { x }$ , the signal is by definition the original input image and, thus, includes the distractor. Therefore, its noisy attribution heat map shows contributions that cancel each other in the neural network. The $S _ { w }$ estimator captures some of the structure. The optimized estimator $S _ { a }$ results in slightly more structure but struggles on color information and produces dense heat maps. The two component model $S _ { a + - }$ on the right captures the original input during signal estimation and produces a crisp heat map of the attribution.
Fig. 6 shows the visualizations for six randomly selected images from ImageNet. PatternNet is able to recover a signal close to the original without having to resort to the inclusion of additional rectifiers in contrast to DeConvNet and Guided BackProp. We argue that this is due to the fact that the optimization of the pattern allows for capturing the important directions in input space. This contrasts with the commonly used methods DeConvNet, Guided BackProp, LRP and DTD, for which the correlation experiment indicates that their implicit signal estimator cannot capture the true signal in the data. Overall, the proposed approach produces the most crisp visualization in addition to being measurably better, as shown in the previous section. Additonally, we also contrast our methods to the prediction-differences analysis by Zintgraf et al. (2017) in the supplementary material.
 Figure 6: Visualization of random images from ImageNet (validation set). In the leftmost shows column the ground truth, the predicted label and the classifier’s confidence. Methods should only be compared within their group. PatternNet, Guided Backprop, DeConvNet and the Gradient (saliency map) are back-projections to input space with the original color channels. They are normalized using $\begin{array} { r } { x _ { n o r m } = \frac { \bar { x } } { 2 \operatorname* { m a x } | x | } + \frac { 1 } { 2 } } \end{array}$ to maximize contrast. LRP and PatternAttribution are heat maps showing pixel-wise contributions.
Relation to previous methods Our method can be thought of as a generalization of the work by Haufe et al. (2014), making it applicable on deep neural networks. Remarkably, our proposed approach can solve the toy example in section 2 optimally while none of the previously published methods for deep learning are able to solve this (Bach et al., 2015; Montavon et al., 2017; Smilkov et al., 2017; Sundararajan et al., 2017; Zintgraf et al., 2017; Dabkowski & Gal, 2017; Zeiler & Fergus, 2014; Springenberg et al., 2015). Our method shares the idea that to explain a model properly one has to learn how to explain it with Zintgraf et al. (2017) and Dabkowski & Gal (2017). Furthermore, since our approach is after training just as expensive as a single back-propagation step, it can be applied in a real-time context, which is also possible for the work done by Dabkowski & Gal (2017) but not for Zintgraf et al. (2017).
# 6 CONCLUSION
Understanding and explaining nonlinear methods is an important challenge in machine learning. Algorithms for visualizing nonlinear models have emerged but theoretical contributions are scarce. We have shown that the direction of the model gradient does not necessarily provide an estimate for the signal in the data. Instead it reflects the relation between the signal direction and the distracting noise contributions ( Fig. 2). This implies that popular explanation approaches for neural networks (DeConvNet, Guided BackProp, LRP) do not provide the correct explanation, even for a simple linear model. Our reasoning can be extended to nonlinear models. We have proposed an objective function for neuron-wise explanations. This can be optimized to correct the signal visualizations (PatternNet) and the decomposition methods (PatternAttribution) by taking the data distribution into account. We have demonstrated that our methods constitute a theoretical, qualitative and quantitative improvement towards understanding deep neural networks.
# ACKNOWLEDGMENTS
This project has received funding from the European Union’s Horizon 2020 research and innovation programme under the Marie Sklodowska-Curie grant agreement NO 657679, the BMBF for the Berlin Big Data Center BBDC (01IS14013A), a hardware donation from NVIDIA. We thank Sander Dieleman, Jonas Degraeve, Ira Korshunova, Stefan Chmiela, Malte Esders, Sarah Hooker, Vincent Vanhoucke for their comments to improve this manuscript. We are grateful to Chris Olah and Gregoire Montavon for the valuable discussions.
# REFERENCES
Sebastian Bach, Alexander Binder, Gregoire Montavon, Frederick Klauschen, Klaus-Robert M ´ uller, ¨ and Wojciech Samek. On pixel-wise explanations for non-linear classifier decisions by layer-wise relevance propagation. PloS one, 10(7):e0130140, 2015.
David Baehrens, Timon Schroeter, Stefan Harmeling, Motoaki Kawanabe, Katja Hansen, and KlausRobert Muller. How to explain individual classification decisions. ¨ Journal of Machine Learning Research, 11(Jun):1803–1831, 2010.
James Bergstra, Olivier Breuleux, Fred´ eric Bastien, Pascal Lamblin, Razvan Pascanu, Guillaume ´ Desjardins, Joseph Turian, David Warde-Farley, and Yoshua Bengio. Theano: A cpu and gpu math compiler in python. In Proc. 9th Python in Science Conf, pp. 1–7, 2010.
Piotr Dabkowski and Yarin Gal. Real time image saliency for black box classifiers. In NIPS 2017, 2017.
Sander Dieleman, Jan Schluter, Colin Raffel, Eben Olson, Søren Kaae Sønderby, Daniel Nouri, ¨ Daniel Maturana, Martin Thoma, Eric Battenberg, Jack Kelly, et al. Lasagne: First release. Zenodo: Geneva, Switzerland, 2015.
Stefan Haufe, Frank Meinecke, Kai Gorgen, Sven D ¨ ahne, John-Dylan Haynes, Benjamin Blankertz, ¨ and Felix Bießmann. On the interpretation of weight vectors of linear models in multivariate neuroimaging. Neuroimage, 87:96–110, 2014.
Pieter-Jan Kindermans, Kristof Schutt, Klaus-Robert M ¨ uller, and Sven D ¨ ahne. Investigating the ¨ influence of noise and distractors on the interpretation of neural networks. arXiv preprint arXiv:1611.07270, 2016.
Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In ICLR, 2015.
Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton. Imagenet classification with deep convolutional neural networks. In Advances in neural information processing systems, pp. 1097–1105, 2012.
Yann LeCun, Yoshua Bengio, and Geoffrey Hinton. Deep learning. Nature, 521(7553):436–444, 2015. doi: 10.1038/nature14539.
Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A Rusu, Joel Veness, Marc G Bellemare, Alex Graves, Martin Riedmiller, Andreas K Fidjeland, Georg Ostrovski, et al. Human-level control through deep reinforcement learning. Nature, 518(7540):529–533, 2015.
Gregoire Montavon, Sebastian Lapuschkin, Alexander Binder, Wojciech Samek, and Klaus-Robert ´ Muller. Explaining nonlinear classification decisions with deep taylor decomposition. ¨ Pattern Recognition, 65:211–222, 2017.
Anh Nguyen, Alexey Dosovitskiy, Jason Yosinski, Thomas Brox, and Jeff Clune. Synthesizing the preferred inputs for neurons in neural networks via deep generator networks. In Advances in Neural Information Processing Systems, pp. 3387–3395, 2016.
Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy, Aditya Khosla, Michael Bernstein, et al. Imagenet large scale visual recognition challenge. International Journal of Computer Vision, 115(3):211–252, 2015.
Wojciech Samek, Alexander Binder, Gregoire Montavon, Sebastian Lapuschkin, and Klaus-Robert ´ Muller. Evaluating the visualization of what a deep neural network has learned. ¨ IEEE Transactions on Neural Networks and Learning Systems, 2016. doi: 10.1109/TNNLS.2016.2599820.
Jurgen Schmidhuber. Deep learning in neural networks: An overview. ¨ Neural networks, 61:85–117, 2015.
Kristof T Schutt, Farhad Arbabzadah, Stefan Chmiela, Klaus-Robert M ¨ uller, and Alexandre ¨ Tkatchenko. Quantum-chemical insights from deep tensor neural networks. Nature Comm., 8: 13890, 2017. doi: 10.1038/ncomms13890.
Avanti Shrikumar, Peyton Greenside, Anna Shcherbina, and Anshul Kundaje. Not just a black box: Learning important features through propagating activation differences. CoRR, abs/1605.01713, 2016. URL http://arxiv.org/abs/1605.01713.
David Silver, Aja Huang, Chris J Maddison, Arthur Guez, Laurent Sifre, George Van Den Driessche, Julian Schrittwieser, Ioannis Antonoglou, Veda Panneershelvam, Marc Lanctot, et al. Mastering the game of go with deep neural networks and tree search. Nature, 529(7587):484–489, 2016. doi: 10.1038/nature16961.
Karen Simonyan and Andrew Zisserman. Very deep convolutional networks for large-scale image recognition. In ICLR, 2015.
Karen Simonyan, Andrea Vedaldi, and Andrew Zisserman. Deep inside convolutional networks: Visualising image classification models and saliency maps. In ICLR, 2014.
Daniel Smilkov, Nikhil Thorat, Been Kim, Fernanda Viegas, and Martin Wattenberg. Smoothgrad: ´ removing noise by adding noise. arXiv preprint arXiv:1706.03825, 2017.
Jost Tobias Springenberg, Alexey Dosovitskiy, Thomas Brox, and Martin Riedmiller. Striving for simplicity: The all convolutional net. In ICLR, 2015.
Mukund Sundararajan, Ankur Taly, and Qiqi Yan. Axiomatic attribution for deep networks. In ICML 2017, 2017.
Ilya Sutskever, Oriol Vinyals, and Quoc V Le. Sequence to sequence learning with neural networks. In Advances in neural information processing systems, pp. 3104–3112, 2014.
Jason Yosinski, Jeff Clune, Thomas Fuchs, and Hod Lipson. Understanding neural networks through deep visualization. In ICML Workshop on Deep Learning, 2015.
Matthew D Zeiler and Rob Fergus. Visualizing and understanding convolutional networks. In European Conference on Computer Vision, pp. 818–833. Springer, 2014.
Luisa M Zintgraf, Taco S Cohen, Tameem Adel, and Max Welling. Visualizing deep neural network decisions: Prediction difference analysis. In ICLR, 2017.
# A ALGORITHMS
In this section we will give an overview of the visualization algorithms to clarify their actual implementation for ReLu networks. This shows the similarities and the differences between all approaches. For all visualization approaches, the back-projection through a max-pooling layer is only through the path that was active in the forward pass.
A.1.1 GRADIENT WITH RESPECT TO THE INPUT
Initialization To compute the gradient of an output neuron w.r.t. to the input, we can initialize the gradient at the output neuron with a single 1, for the non-selected output neurons we initialize it at 0.
$$g _ { i } ^ { o u t p u t } = y , \qquad g _ { j \neq i } ^ { o u t p u t } = 0 .$$
Linear or convolutional layer If it is a linear layer, the gradients from neuron $i$ in layer $l$ can be projected back to its input along the weight vector
$$\begin{array} { r } { \pmb { g } ^ { l - 1 , i } = \pmb { w g } _ { i } ^ { l } . } \end{array}$$
The gradient of neuron $i$ at layer $l - 1$ is the sum of all incoming gradients from the layer above:
$$g _ { i } ^ { l - 1 } = \sum _ { j } g _ { i } ^ { l - 1 , j } .$$
ReLu layer To propagate through a ReLu, the propagation is blocked if the ReLu was not active in the forward pass.
$$g _ { i } ^ { l - 1 } = { \left\{ \begin{array} { l l } { g _ { i } ^ { l } } & { x _ { i } ^ { l } > 0 } \\ { 0 } & { { \mathrm { o t h e r w i s e } } } \end{array} \right. }$$
# A.2 SIGNAL VISUALIZATION
# A.2.1 DECONVNET
The DeConvNet visualization is highly similar to the computation of the gradient. The key difference is how the ReLu’s are treated.
Initialization To compute the visualization of the signal of an output neuron w.r.t. to the input, we can initialize it at the output neuron with the output value $y$ , for the non-selected output neurons we initialize it at 0.
$$s _ { i } ^ { o u t p u t } = y , \qquad s _ { j \neq i } ^ { o u t p u t } = 0 .$$
Linear or convolutional layer If it is a linear layer, the signal from neuron $i$ in layer $l$ can be projected back to its input along the weight vector.
$$\begin{array} { r } { \pmb { s } ^ { l - 1 , i } = \pmb { w s } _ { i } ^ { l } . } \end{array}$$
The signal of neuron $i$ at layer $l - 1$ is the sum of all incoming signals from the layer above:
$$s _ { i } ^ { l - 1 } = \sum _ { j } s _ { i } ^ { l - 1 , j } .$$
ReLu layer To propagate through a ReLu, the propagation is blocked if the signal is negative
$$s _ { i } ^ { l - 1 } = \left\{ \begin{array} { l l } { s _ { i } ^ { l } } & { s _ { i } ^ { l } > 0 } \\ { 0 } & { \mathrm { o t h e r w i s e } } \end{array} \right.$$
# A.2.2 GUIDED BACKPROPAGATION
The Guided Backpropagation visualization is highly similar to the computation of the gradient. and to DeConvNet. The only difference is how the ReLu’s are treated.
Initialization To compute the visualization of the signal of an output neuron w.r.t. to the input, we can initialize it at the output neuron with the output value $y$ , for the non-selected output neurons we initialize it at 0.
$$s _ { i } ^ { o u t p u t } = y , \qquad s _ { j \neq i } ^ { o u t p u t } = 0 .$$
Linear or convolutional layer If it is a linear layer, the signal from neuron $i$ in layer $l$ can be projected back to its input along the weight vector
$$\begin{array} { r } { \pmb { s } ^ { l - 1 , i } = \pmb { w s } _ { i } ^ { l } . } \end{array}$$
The signal of neuron $i$ at layer $l - 1$ is the sum of all incoming signals from the layer above:
$$s _ { i } ^ { l - 1 } = \sum _ { j } s _ { i } ^ { l - 1 , j } .$$
ReLu layer To propagate through a ReLu, the propagation is blocked if the signal is negative or if the neuron was not active in the forward pass
$$s _ { i } ^ { l - 1 } = \left\{ \begin{array} { l l } { s _ { i } ^ { l } } & { s _ { i } ^ { l } > 0 \mathrm { a n d } x _ { i } ^ { l } > 0 } \\ { 0 } & { \mathrm { o t h e r w i s e } } \end{array} \right.$$
# A.2.3 PATTERNNET
The PatternNet computation is analogous to the gradient computation. The key difference is that during the backward pass patterns are used instead of weights.
Initialization To compute the visualization of the signal of an output neuron w.r.t. to the input, we can initialize it at the output neuron with the output value $y$ , for the non-selected output neurons we initialize it at 0.
$$s _ { i } ^ { o u t p u t } = y , \qquad s _ { j \neq i } ^ { o u t p u t } = 0 .$$
Linear or convolutional layer If it is a linear layer, the signal from neuron $i$ in layer $l$ can be projected back to its input along the pattern vector.
$$\pmb { s } ^ { l - 1 , i } = \pmb { a } s _ { i } ^ { l } .$$
In our case where we use the $S _ { a + - } ( x )$ estimator, this vector is always the positive components ${ \pmb a } _ { + }$ since non-active ReLu’s block the propagation.
The signal of neuron $i$ at layer $l - 1$ is the sum of all incoming signals from the layer above:
$$s _ { i } ^ { l - 1 } = \sum _ { j } s _ { i } ^ { l - 1 , j } .$$
ReLu layer To propagate through a ReLu, the propagation is blocked if the neuron was not active in the forward pass
$$s _ { i } ^ { l - 1 } = \left\{ \begin{array} { l l } { s _ { i } ^ { l } } & { x _ { i } ^ { l } > 0 } \\ { 0 } & { \mathrm { o t h e r w i s e } } \end{array} \right.$$
# A.3 ATTRIBUTION VISUALIZATION
# A.3.1 DEEP-TAYLOR DECOMPOSITION
Initialization To compute the attribution of an output neuron, we can initialize it at the output neuron with the output value $y$ , for the non-selected output neurons we initialize it at 0.
$$r _ { i } ^ { o u t p u t } = y , \qquad r _ { j \neq i } ^ { o u t p u t } = 0 .$$
Linear or convolutional layer If it is a linear layer, the signal from neuron $i$ in layer $l$ can be projected back to its input w.r.t. a reference point $\scriptstyle { \mathbf { { \mathit { x } } } } _ { 0 }$
$$\pmb { r } ^ { l - 1 , i } = \frac { \pmb { w } \odot ( \pmb { x } - \pmb { x } _ { 0 } ) } { \pmb { w } ^ { T } \pmb { x } } r _ { i } ^ { l } .$$
In this work we use the $S _ { a + - } ( x )$ estimator. Since a non-active ReLu blocks the propagation, we only have to use the positive component $\mathbf { \pmb { a } } _ { + }$ .
The attribution of neuron $i$ at layer $l - 1$ is the sum of all incoming attributions from the layer above:
$$r _ { i } ^ { l - 1 } = \sum _ { j } r _ { i } ^ { l - 1 , j } .$$
ReLu layer To propagate through a ReLu, the propagation is blocked if the ReLu was not active in the forward pass.
$$r _ { i } ^ { l - 1 } = { \left\{ \begin{array} { l l } { r _ { i } ^ { l } } & { x _ { i } ^ { l } > 0 } \\ { 0 } & { { \mathrm { o t h e r w i s e } } } \end{array} \right. }$$
# A.3.2 LRP
LRP corresponds to $\mathbf { \delta x } _ { 0 } = \mathbf { \delta 0 }$ . This allows us to re-write the distribution rule for the linear and convolutional layers as:
$$r ^ { l - 1 , i } = \frac { { \pmb w } \odot { \pmb x } } { { \pmb w } ^ { T } { \pmb x } } r _ { i } ^ { l } .$$
Division by zero is not an issue since the propagation is blocked at the ReLu if ${ \pmb w } ^ { T } { \pmb x } < = 0$
# A.3.3 PATTERNATTRIBUTION WITH $S _ { a + - } ( x )$
PatternAttributions corresponds to ${ \pmb x } _ { 0 } = { \pmb x } - S _ { { \pmb a } + - } ( { \pmb x } )$ . Because propagation is blocked at the ReLu if ${ \pmb w } ^ { T } { \pmb x } < = 0$ , we can always use $\pmb { x } _ { 0 } = \pmb { x } - \pmb { a } _ { + } \pmb { w } ^ { T } \pmb { x } .$
This allows us to re-write the distribution rule for the linear and convolutional layers as:
$$\pmb { r } ^ { l - 1 , i } = \frac { \pmb { w } \odot \left( \pmb { x } - \pmb { x } + \pmb { a } _ { + } \pmb { w } ^ { T } \pmb { x } \right) } { \pmb { w } ^ { T } \pmb { x } } r _ { i } ^ { l } .$$
This can be simplified to
$$r ^ { l - 1 , i } = { \pmb w } \odot { \pmb a } _ { + } r _ { i } ^ { l }$$
since division by zero is not an issue because the propagation is blocked at the ReLu if ${ \pmb w } ^ { T } { \pmb x } < = 0$ .
# B QUALITATIVE COMPARISON TO PREDICTION-DIFFERENCES ANALYSIS
To create the Predictive-Differences analysis visualizations Zintgraf et al. (2017), we used the opensource code provided by the authors with the default parameter settings provided for VGG.
 Figure 7: Visualization of random images from ImageNet (validation set). In the leftmost shows column the ground truth, the predicted label and the classifier’s confidence. Comparison between the proposed methods PatternNet and PatternAttribution to the Prediction-Differences approach by Zintgraf et al. (2017).md/train/2F_wnaioS6/2F_wnaioS6.mdAdded+250
md/train/9DlCh34E1bN/9DlCh34E1bN.mdAdded+296
md/train/AVx0r_GppCu/AVx0r_GppCu.mdAdded+461
md/train/B1l6y0VFPr/B1l6y0VFPr.mdAdded+687
md/train/BJC8LF9ex/BJC8LF9ex.mdAdded+375
md/train/BJlVNY8llV/BJlVNY8llV.mdAdded+240
md/train/BJxI5gHKDr/BJxI5gHKDr.mdAdded
md/train/BkeqO7x0-/BkeqO7x0-.mdAdded+475
md/train/BkxAUjRqY7/BkxAUjRqY7.mdAdded+569
md/train/ByxRM0Ntvr/ByxRM0Ntvr.mdAdded
md/train/CMsvjAnW1zE/CMsvjAnW1zE.mdAdded
md/train/D8-iwC9UN3/D8-iwC9UN3.mdAdded+608
md/train/EQbyD_KG6w-1h/EQbyD_KG6w-1h.mdAdded+258
md/train/H11lAfbCW/H11lAfbCW.mdAdded+275
md/train/HJnQJXbC-/HJnQJXbC-.mdAdded+268
md/train/Hk91SGWR-/Hk91SGWR-.mdAdded+200
md/train/HkenPn4KPH/HkenPn4KPH.mdAdded+322
md/train/HkgTkhRcKQ/HkgTkhRcKQ.mdAdded+742
md/train/Hkn7CBaTW/Hkn7CBaTW.mdAdded+492
md/train/Hyg1G2AqtQ/Hyg1G2AqtQ.mdAdded
md/train/S1gfu3EtDr/S1gfu3EtDr.mdAdded
md/train/SJDaqqveg/SJDaqqveg.mdAdded
md/train/SJgMK64Ywr/SJgMK64Ywr.mdAdded
md/train/SJlPOCEKvH/SJlPOCEKvH.mdAdded
md/train/SJxeI6EYwS/SJxeI6EYwS.mdAdded
md/train/Sk7KsfW0-/Sk7KsfW0-.mdAdded
md/train/Skh4jRcKQ/Skh4jRcKQ.mdAdded
md/train/SyMWn05F7/SyMWn05F7.mdAdded
md/train/T1STW1NYYKW/T1STW1NYYKW.mdAdded
md/train/U7vVeHydyR/U7vVeHydyR.mdAdded
md/train/jtrQswOMLrd/jtrQswOMLrd.mdAdded
md/train/mrsx7ninrtU/mrsx7ninrtU.mdAdded
md/train/ogciCC6fmBl/ogciCC6fmBl.mdAdded
md/train/qGeqg4_hA2/qGeqg4_hA2.mdAdded
md/train/r1GAsjC5Fm/r1GAsjC5Fm.mdAdded
md/train/r1lohoCqY7/r1lohoCqY7.mdAdded
md/train/rJg8yhAqKm/rJg8yhAqKm.mdAdded
md/train/rJl8FoRcY7/rJl8FoRcY7.mdAdded
md/train/rke41hC5Km/rke41hC5Km.mdAdded
md/train/rkgMkCEtPB/rkgMkCEtPB.mdAdded
md/train/rklp93EtwH/rklp93EtwH.mdAdded
md/train/rm0I5y2zkG8/rm0I5y2zkG8.mdAdded
md/train/ryxnHhRqFm/ryxnHhRqFm.mdAdded
md/train/sjuuTm4vj0/sjuuTm4vj0.mdAdded
md/train/uCQfPZwRaUu/uCQfPZwRaUu.mdAdded
md/train/uIc4W6MtbDA/uIc4W6MtbDA.mdAdded
md/train/uKhGRvM8QNH/uKhGRvM8QNH.mdAdded
md/train/wZrOOO9XBn/wZrOOO9XBn.mdAdded
md/train/yH2VrkpiCK6/yH2VrkpiCK6.mdAdded
md/train/yxafu6ZtUux/yxafu6ZtUux.mdAdded