Hopfield Networks is All You Need
Hubert Ramsauer, Bernhard Schäfl, Johannes Lehner, Philipp Seidl, Michael Widrich, Thomas Adler, Lukas Gruber, Markus Holzleitner, Milena Pavlović, Geir Kjetil Sandve, Victor Greiff, David Kreil, Michael Kopp, Günter Klambauer, Johannes Brandstetter, Sepp Hochreiter
Introduction
Contribution of this work: (i) introducing novel deep learning layers that are equipped with a memory via modern Hopfield networks, (ii) introducing a novel energy function and a novel update rule for continuous modern Hopfield networks that are differentiable and typically retrieve patterns after one update. Differentiability is required for gradient descent parameter updates and retrieval with one update is compatible with activating the layers of deep networks.
We suggest using modern Hopfield networks to store information or learned prototypes in different layers of neural networks. Binary Hopfield networks were introduced as associative memories that can store and retrieve patterns (Hopfield, 1982). A query pattern can retrieve the pattern to which it is most similar or an average over similar patterns. Hopfield networks seem to be an ancient technique, however, new energy functions improved their properties. The stability of spurious states or metastable states was sensibly reduced (Barra et al., 2018). The largest and most impactful successes are reported on increasing the storage capacity of Hopfield networks. In a -dimensional space, the standard Hopfield model can store uncorrelated patterns without errors but only random patterns with for a fixed stable pattern or if all patterns are stable (McEliece et al., 1987). The same bound holds for nonlinear learning rules (Mazza, 1997). Using tricks-of-trade and allowing small retrieval errors, the storage capacity is about (Crisanti et al., 1986; Hertz et al., 1991; Torres et al., 2002). If the learning rule is not related to the Hebb rule, then up to patterns can be stored (Abu-Mostafa & StJacques, 1985). For Hopfield networks with non-zero diagonal matrices, the storage can be increased to (Folli et al., 2017). In contrast to the storage capacity, the number of energy minima (spurious states, stable states) of Hopfield networks is exponential in (Tanaka & Edwards, 1980; Bruck & Roychowdhury, 1990; Wainrib & Touboul, 2013).
The standard binary Hopfield network has an energy function that can be expressed as the sum of interaction functions with . Modern Hopfield networks, also called “dense associative memory” (DAM) models, use an energy function with interaction functions of the form and, thereby, achieve a storage capacity proportional to (Krotov & Hopfield, 2016; 2018). The energy function of modern Hopfield networks makes them robust against adversarial attacks (Krotov & Hopfield, 2018). Modern binary Hopfield networks with energy functions based on interaction functions of the form even lead to storage capacity of , where all stored binary patterns are fixed points but the radius of attraction vanishes (Demircigil et al., 2017). However, in order to integrate Hopfield networks into deep learning architectures, it is necessary to make them differentiable, that is, we require continuous Hopfield networks (Hopfield, 1984; Koiran, 1994).
Therefore, we generalize the energy function of Demircigil et al. (2017) that builds on exponential interaction functions to continuous patterns and states and obtain a new modern Hopfield network. We also propose a new update rule which ensures global convergence to stationary points of the energy (local minima or saddle points). We prove that our new modern Hopfield network typically retrieves patterns in one update step (-close to the fixed point) with an exponentially low error and has a storage capacity proportional to (reasonable settings for and are given in Theorem 3). The retrieval of patterns with one update is important to integrate Hopfield networks in deep learning architectures, where layers are activated only once. Surprisingly, our new update rule is also the key-value attention as used in transformer and BERT models (see Fig. 1). Our modern Hopfield networks can be integrated as a new layer in deep learning architectures for pooling, memory, prototype learning, and attention. We test these new layers on different benchmark datasets and tasks like immune repertoire classification.
Modern Hopfield Nets with Continuous States
In order to integrate modern Hopfield networks into deep learning architectures, we have to make them continuous. To allow for continuous states, we propose a new energy function that is a modification of the energy of modern Hopfield networks (Demircigil et al., 2017). We also propose a new update rule which can be proven to converge to stationary points of the energy (local minima or saddle points).
The next theorem states that the update rule Eq. (3) converges globally. The proof uses the Concave-Convex Procedure (CCCP) (Yuille & Rangarajan, 2002; 2003), which is equivalent to Legendre minimization (Rangarajan et al., 1996; 1999) algorithms (Yuille & Rangarajan, 2003).
The next theorem gives the results on the storage capacity of our new continuous state modern Hopfield network. We first define what we mean by storing and retrieving patterns using a modern Hopfield network with continuous states.
We assume a failure probability and randomly chosen patterns on the sphere with radius . We define , , and , where is the upper branch of the Lambert function (Olver et al., 2010, (4.13)), and ensure . Then with probability , the number of random patterns that can be stored is
Therefore it is proven for with , , and () and proven for with , , , and ().
The next theorem states that the update rule typically retrieves patterns after one update. Retrieval of a pattern for fixed point and query is defined via an by , that is, the update is -close to the fixed point. Retrieval with one update is crucial to integrate modern Hopfield networks into deep learning architectures, where layers are activated only once. First we need the concept of separation of a pattern. For pattern we define its separation to other patterns by:
The update rule retrieves patterns with one update for well separated patterns, that is, patterns with large .
For given and sufficient large , we have , that is, retrieval with one update.
At the same time, the retrieval error decreases exponentially with the separation .
The retrieval error of pattern is bounded by
and for together with by
The left part of Eq. (10) is the transformer attention. In the transformer self-attention , and replaced by just . Besides the attention mechanism, Hopfield networks allow for other functionalities in deep network architectures, which we introduce via specific layers in the next section. The right part of Eq. (10) serves to explain these specific layers.
New Hopfield Layers for Deep Learning
Modern Hopfield networks with continuous states can be integrated into deep learning architectures, because they are continuous and differentiable with respect to their parameters. Furthermore, they typically retrieve patterns with one update, which is conform to deep learning layers that are activated only once. For these two reasons, modern Hopfield networks can serve as specialized layers in deep networks to equip them with memories. Below, we introduce three types of Hopfield layers: Hopfield, HopfieldPooling, and HopfieldLayer. Possible applications of Hopfield layers in deep network architectures comprise:
multiple instance learning (MIL) (Dietterich et al., 1997),
processing of and learning with point sets (Qi et al., 2017a; b; Xu et al., 2018),
set-based and permutation invariant learning (Guttenberg et al., 2016; Ravanbakhsh et al., 2016; Zaheer et al., 2017; Korshunova et al., 2018; Ilse et al., 2018; Zhai et al., 2020),
attention-based learning (Vaswani et al., 2017a),
deep learning with associative memories (Graves et al., 2014; Weston et al., 2014; Ba et al., 2016a; b; Schlag & Schmidhuber, 2018; Schlag et al., 2019),
natural language processing (Devlin et al., 2018; 2019),
sequence analysis and time series prediction (Hochreiter, 1991; Hochreiter & Schmidhuber, 1997; Cho et al., 2014), and
storing and retrieving reference data, e.g. the training data, outliers, high error data points, prototypes or cluster centers, support vectors & border cases.
Hopfield network layers can substitute existing layers like pooling layers, permutation equivariant layers (Guttenberg et al., 2016; Ravanbakhsh et al., 2016), GRU (Cho et al., 2014) & LSTM (Hochreiter, 1991; Hochreiter & Schmidhuber, 1997) layers, and attention layers (Vaswani et al., 2017a; b; Bahdanau et al., 2014).
We consider two types of feed-forward neural networks: (I) Neural networks that propagate an activation vector from the input layer to the output layer. Examples are fully-connected or convolutional neural networks. (II) Neural networks that propagate a set of vectors from the input layer to the output layer, where each layer applies the same operation to each element of the set and the output layer may summarize the set via a vector. An example is the transformer. Recurrent neural networks are networks of type (I), which are iteratively applied to a set or a sequence, where intermediate results are stored in a memory and can be reused. Modern Hopfield networks can be integrated into both types of neural network architectures and enable to equip each of their layers with associative memories. See Fig. 2.
We introduce three types of Hopfield layers: Hopfield, HopfieldPooling, and HopfieldLayer. The continuous modern Hopfield network results in a plethora of new deep learning architectures, since we can (a) propagate sets or single vectors, (b) propagate queries, stored patterns, or both, (c) learn static queries or stored patterns, (d) fill the memory by training sets, prototypes, or external data. Next, we provide three useful types of Hopfield layers. The implementation is available at: https://github.com/ml-jku/hopfield-layers
(1) Layer Hopfield for networks that propagate sets of vectors via state (query) patterns and stored (key) patterns . The layer Hopfield is the realization of formula (10). The memory of the Hopfield layer can be filled with sets from the input or previous layers, see Fig. 3. The memory may be filled with a reference set, which is covered by providing the reference set as additional input. Thus, the layer Hopfield allows the association of two sets. A prominent example of a layer that performs such association is the transformer attention mechanism, which associates keys and queries, e.g. two point sets that have to be compared. This layer allows for different kinds of sequence-to-sequence learning, point set operations, and retrieval-based methods. The layer Hopfield with skip connections in a ResNet architecture is identical to the popular transformer and BERT models. In the experiments, we analyzed these Hopfield layers in transformer architectures. In our experiments in which we compare machine learning methods on small datasets of the UCI benchmark collection the layer Hopfield is also used.
(2) Layer HopfieldPooling for networks that propagate patterns via the stored (key) patterns . This layer performs a pooling or summarization of sets obtained from queries in previous layers or the input. The memory of the HopfieldPooling layer is filled with sets from the input or previous layers. The HopfieldPooling layer uses the queries to search for patterns in the memory, the stored set. If more patterns are similar to a particular search pattern (query), then the result is an average over these patterns. The state (query) patterns of each layer are static and can be learned. Multiple queries supply a set to the next layer, where each query corresponds to one element of the set. Thus, the layer HopfieldPooling enables fixed pattern search, pooling operations, and memories like LSTMs or GRUs. The static pattern functionality is typically needed if particular patterns must be identified in the data. A single HopfieldPooling layer allows for multiple instance learning. Static state (query) patterns together with position encoding in the keys allows for performing pooling operations. The position encoding can be two-dimensional, where standard convolutional filters can be constructed as in convolutional neural networks (CNNs). The HopfieldPooling layer can substitute pooling, averaging, LSTM, and permutation equivariant layers. See Fig. 4. The layer HopfieldPooling is used for experiments with multiple instance learning tasks, e.g. for immune repertoire classification in the experiments.
(3) Layer HopfieldLayer for networks that propagate a vector or a set of vectors via state (query) patterns . The queries can be input vectors or queries that are computed from the output of previous layers. The memory of the HopfieldLayer layer is filled with a fixed set, which can be the training set, a reference set, prototype set, or a learned set (a learned matrix). The stored (key) patterns are static and can be learned. If the training set is stored in the memory, then each layer constructs a new set of queries based on the query results of previous layers. The stored patterns can be initialized by the training set or a reference set and then learned, in which case they deviate from the training set. The stored patterns can be interpreted as weights from the state (query) to hidden neurons that have a softmax activation function (Krotov & Hopfield, 2020). The layer HopfieldLayer can substitute a fully connected layer, see Fig. 5. A single HopfieldLayer layer also allows for approaches similar to support vector machines (SVMs), approaches similar to -nearest neighbor, approaches similar to learning vector quantization, and pattern search. For classification, the raw data can be the concatenation of input and target . In this case, the matrices and can be designed such that inside the softmax the input is used and outside the softmax the target . Thus, the softmax provides a weighted average of the target vectors based on the similarity between the query and the inputs. Also SVM models, -nearest neighbor, and learning vector quantization can be considered as weighted averages of the targets. The encoder-decoder attention layer of the transformers are a HopfieldLayer layer, where the memory is filled with the encoder output set. In our experiments with the drug design benchmark datasets, the layer HopfieldLayer has been applied and compared to other machine learning methods.
The insights about energy, convergence, and storage properties provide all new Hopfield layers with additional functionalities: i) multiple updates to control how precise fixed points are found without additional parameters needed. ii) variable to determine the kind of fixed points such as the size of metastable states. The variable controls over how many patterns is averaged. As observed in the experiments, the variable is relevant in combination with the learning rate to steer the learning dynamics. The parameter governs the fixed point dynamics and can be learned, too. iii) controlling the storage capacity via the dimension of the associative space. The storage capacity can be relevant for tasks with a huge number of instances as in the immune repertoire classification experiment. iv) pattern normalization controls, like the layernorm, the fixed point dynamics by the norm and shift of the patterns. For more details see appendix, Section A.6.
Experiments
We show that our proposed Hopfield layers can be applied successfully to a wide range of tasks. The tasks are from natural language processing, contain multiple instance learning problems, a collection of small classification tasks, and drug design problems.
For multiple instance learning (MIL) (Dietterich et al., 1997), we integrate our new Hopfield network via the layer HopfieldPooling into deep learning architectures. Recently, deep learning methods have been applied to MIL problems (Ilse et al., 2018), but still the performance on many datasets lacks improvement. Thus, MIL datasets still pose an interesting challenge, in which Hopfield layers equipped with memory are a promising approach.
•Immune Repertoire Classification. The first MIL task is immune repertoire classification, where a deep learning architecture with HopfieldPooling (DeepRC) was used (Widrich et al., 2020a; b). Immune repertoire classification (Emerson et al., 2017) typically requires to extract few patterns from a large set of sequences, the repertoire, that are indicative for the respective immune status. The datasets contain 300,000 instances per immune repertoire, which represents one of the largest multiple instance learning experiments ever conducted (Carbonneau et al., 2018). Most MIL methods fail due the large number of instances. This experiment comprises real-world and simulated datasets. Simulated datasets are generated by implanting sequence motifs (Akbar et al., 2019; Weber et al., 2020) with low frequency into simulated or experimentally-observed immune receptor sequences. The performance of DeepRC was compared with other machine learning methods: (i) known motif, (ii) SVM using -mers and MinMax or Jaccard kernel, (iii) -Nearest Neighbor (KNN) with -mers, (iv) logistic regression with -mers, (v) burden test with -mers, and (vi) logistic multiple instance learning (lMIL). On the real-world dataset DeepRC achieved an AUC of , followed by the SVM with MinMax kernel (AUC ) and the burden test with an AUC of . Across datasets, DeepRC outperformed all competing methods with respect to average AUC (Widrich et al., 2020a; b).
•MIL benchmark datasets. We apply Hopfield layers to further MIL datasets (Ilse et al., 2018; Küçükaşcı & Baydoğan, 2018; Cheplygina et al., 2016): Elephant, Fox and Tiger for image annotation (Andrews et al., 2003). These datasets consist of color images from the Corel dataset that have been preprocessed and segmented. An image consists of a set of segments (or blobs), each characterized by color, texture and shape descriptors. The datasets have 100 positive and 100 negative example images. The latter have been randomly drawn from a pool of photos of other animals. Elephant comprises 1,391 instances and 230 features, Fox 1,320 instances and 230 features, and Tiger has 1,220 instances and 230 features. Furthermore, we use the UCSB breast cancer classification (Kandemir et al., 2014) dataset, which consists of 2,002 instances across 58 input objects. An instance represents a patch of a histopathological image of cancerous or normal tissue. The layer HopfieldPooling is used, which allows for computing a per-input-object representation by extracting an average of instances that are indicative for one of the two classes. The input to the layer HopfieldPooling is a set of embedded instances . A trainable but fixed state (query) pattern is used for averaging over class-indicative instances. This averaging enables a compression of variable-sized bags to a fixed-sized representation to discriminate the bags. More details in appendix Sec. A.5.2. Our approach has set a new state-of-the-art and has outperformed other methods (Küçükaşcı & Baydoğan, 2018; Carbonneau et al., 2016) on the datasets Tiger, Elephant and UCSB Breast Cancer (see Table 1).
So far deep learning struggled with small datasets. However, Hopfield networks are promising for handling small datasets, since they can store the training data points or their representations to perform similarity-based, nearest neighbor, or learning vector quantization methods. Therefore, we test the Hopfield layer Hopfield on the small datasets of the UC Irvine (UCI) Machine Learning Repository that have been used to benchmark supervised learning methods (Fernández-Delgado et al., 2014; Wainberg et al., 2016; Khan et al., 2018) and also feed-forward neural networks (Klambauer et al., 2017a; Wu et al., 2018), where our Hopfield networks could exploit their memory. The whole 121 datasets in the collection vary strongly with respect to their size, number of features, and difficulties (Fernández-Delgado et al., 2014), such that they have been divided into 75 “small datasets” with less than 1,000 samples and 45 “large datasets” with more than or equal to 1,000 samples in Klambauer et al. (2017a).
On the 75 small datasets, Random Forests (RFs) and Support Vector Machines (SVM) are highly accurate, whereas on the large datasets, deep learning methods and neural networks are in the lead (Klambauer et al., 2017a; b; Wu et al., 2018). We applied a modern Hopfield network via the layer HopfieldLayer, where a self-normalizing net (SNN) maps the input vector to and . The output of HopfieldLayer enters a softmax output. We compared our modern Hopfield networks against deep learning methods (e.g. SNNs, resnet), RFs, SVMs, boosting, bagging, and many other machine learning methods of Fernández-Delgado et al. (2014). Since for each method, multiple variants and implementations had been included, we used method groups and representatives as defined by Klambauer et al. (2017a). For each dataset, a ranking of the methods was calculated which is presented in Table 2. We found that Hopfield networks outperform all other methods on the small datasets, setting a new state-of-the-art for 10 datasets. The difference is significant except for the first three runner-up methods (Wilcoxon signed rank test). See appendix Section A.5.3 for details.
Drug Design Benchmark Datasets. We test the Hopfield layer HopfieldLayer, on four drug design datasets. These datasets represent four main areas of modeling tasks in drug design, concretely to develop accurate models for predicting a) new anti-virals (HIV) by the Drug Therapeutics Program (DTP) AIDS Antiviral Screen, b) new protein inhibitors, concretely human -secretase (BACE) inhibitors by Subramanian et al. (2016), c) metabolic effects as blood-brain barrier permeability (BBBP) (Martins et al., 2012) and d) side effects of a chemical compound from the Side Effect Resource (SIDER) Kuhn et al. (2016). We applied the Hopfield layer HopfieldLayer, where the training data is used as stored patterns , the input vector as state pattern , and the corresponding training label to project the output of the Hopfield layer . Our architecture with HopfieldLayer has reached state-of-the-art for predicting side effects on SIDER as well as for predicting -secretase BACE . For details, see Table A.5 in the appendix.
Conclusion. We have introduced a modern Hopfield network with continuous states and the corresponding new update rule. This network can store exponentially many patterns, retrieves patterns with one update, and has exponentially small retrieval errors. We analyzed the attention heads of BERT models. The new modern Hopfield networks have been integrated into deep learning architectures as layers to allow the storage of and access to raw input data, intermediate results, or learned prototypes. These Hopfield layers enable new ways of deep learning, beyond fully-connected, convolutional, or recurrent networks, and provide pooling, memory, association, and attention mechanisms. Hopfield layers that equip neural network layers with memories improved state-of-the-art in three out of four considered multiple instance learning problems and on immune repertoire classification, and on two drug design dataset. They yielded the best results among different machine learning methods on the UCI benchmark collections of small classification tasks.
Acknowledgments
The ELLIS Unit Linz, the LIT AI Lab and the Institute for Machine Learning are supported by the Land Oberösterreich, LIT grants DeepToxGen (LIT-2017-3-YOU-003), and AI-SNN (LIT-2018-6-YOU-214), the Medical Cognitive Computing Center (MC3), Janssen Pharmaceutica, UCB Biopharma, Merck Group, Audi.JKU Deep Learning Center, Audi Electronic Venture GmbH, TGW, Primal, S3AI (FFG-872172), Silicon Austria Labs (SAL), Anyline, FILL, EnliteAI, Google Brain, ZF Friedrichshafen AG, Robert Bosch GmbH, TÜV Austria, DCS, and the NVIDIA Corporation. IARAI is supported by Here Technologies.
Appendix A Appendix
This appendix consists of six sections (A.1–A.6). Section A.1 introduces the new modern Hopfield network with continuous states and its update rule. Furthermore, Section A.1 provides a thorough and profound theoretical analysis of this new Hopfield network. Section A.2 provides the mathematical background for Section A.1. Section A.3 reviews binary Modern Hopfield Networks of Krotov & Hopfield. Section A.4 shows that the Hopfield update rule is the attention mechanism of the transformer. Section A.5 gives details on the experiments. Section A.6 describes the PyTorch implementation of layers based on the new Hopfield networks and how to use them.
In Section A.1 our new modern Hopfield network is introduced. In Subsection A.1.2 we present the new energy function. Then in Subsection A.1.3, our new update rule is introduced. In Subsection A.1.4, we show that this update rule ensures global convergence. We show that all the limit points of any sequence generated by the update rule are the stationary points (local minima or saddle points) of the energy function. In Section A.1.5, we consider the local convergence of the update rule and see that patterns are retrieved with one update. In Subsection A.1.6, we consider the properties of the fixed points that are associated with the stored patterns. In Subsection A.1.6.1, we show that exponentially many patterns can be stored. The main result is given in Theorem A5: For random patterns on a sphere we can store and retrieve exponentially (in the dimension of the Hopfield space) many patterns. Subsection A.1.6.2 reports that patterns are typically retrieved with one update step and that the retrieval error is exponentially small.
In Subsection A.1.7, we consider how associations for the new Hopfield networks can be learned. In Subsection A.1.7.2, we analyze if the association is learned directly by a bilinear form. In Subsection A.1.7.3, we analyze if stored patterns and query patterns are mapped to the space of the Hopfield network. Therefore, we treat the architecture of the transformer and BERT. In Subsection A.1.8, we introduce a temporal component into the new Hopfield network that leads to a forgetting behavior. The forgetting allows us to treat infinite memory capacity in Subsection A.1.8.1. In Subsection A.1.8.2, we consider the controlled forgetting behavior.
In Section A.2, we provide the mathematical background that is needed for our proofs. In particular we give lemmas on properties of the softmax, the log-sum-exponential, the Legendre transform, and the Lambert function.
In Section A.3, we review the new Hopfield network as introduced by Krotov and Hopfield in 2016. However in contrast to our new Hopfield network, the Hopfield network of Krotov and Hopfield is binary, that is, a network with binary states. In Subsection A.3.1, we give an introduction to neural networks equipped with associative memories and new Hopfield networks. In Subsection A.3.1.1, we discuss neural networks that are enhanced by an additional external memory and by attention mechanisms. In Subsection A.3.1.2, we give an overview over the modern Hopfield networks. Finally, in Subsection A.3.2, we present the energy function and the update rule for the modern, binary Hopfield networks.
A.1.2 New Energy Function
We have patterns that are represented by the matrix
The query or state of the Hopfield network is .
We start by deriving the lower bound of zero. The pattern most similar to query or state is :
The energy is zero and, therefore, the bound attained, if all are equal, that is, for all and .
as the term involving the logarithm is non-positive.
Next we derive the second upper bound, for which we need the mean of the patterns
where for the first inequality we again applied Lemma A19 with and . This inequality also follows from Jensen’s inequality. The second inequality uses the Cauchy-Schwarz inequality. The last inequality uses
A.1.3 New Update Rule
A.1.4 Global Convergence of the Update Rule
We are interested in the global convergence, that is, convergence from each initial point, of the iteration
where does not depend on .
Although the objective converges in all cases, it does not necessarily converge to a local minimum (Lipp & Boyd, 2016).
However the convergence proof of CCCP in Yuille & Rangarajan (2002; 2003) was not as rigorous as required. In Sriperumbudur & Lanckriet (2009) a rigorous analysis of the convergence of CCCP is performed using Zangwill’s global convergence theory of iterative algorithms.
In Sriperumbudur & Lanckriet (2009) the minimization problem
where does not depend on . Since we do not have constraints, is defined as
Since we do not have constraints, is the minimum of
For a minimum not at the border, the derivative has to be the zero vector
and the Hessian must be positive semi-definite
where does not depend on .
A.1.5 Local Convergence of the Update Rule: Fixed Point Iteration
For the proof of local convergence to a fixed point we will apply Banach fixed point theorem. For the rate of convergence we will rely on properties of a contraction mapping.
To analyze the local convergence of the iteration, we distinguish between the following three cases (see also Fig. A.1). Here we only provide an informal discussion to give the reader some intuition. A rigorous formulation of the results can be found in the corresponding subsections.
If the patterns are not well separated, the iteration goes to a fixed point close to the arithmetic mean of the vectors. In this case is close to .
If the patterns are well separated, then the iteration goes to the pattern to which the initial is similar. If the initial is similar to a vector then it will converge to a vector close to and will converge to a vector close to .
If some vectors are similar to each other but well separated from all other vectors, then a so called metastable state between the similar vectors exists. Iterations that start near the metastable state converge to this metastable state.
We begin with a bound on the Jacobian of the iteration, thereby heavily relying on the Jacobian of the softmax from Lemma A24.
If , then for the spectral norm of the Jacobian holds
With , Eq. (476) from Lemma A24 is
The spectral norm is bounded by the Frobenius norm which can be expressed by the norm squared of its column vectors:
Therefore, we obtain the first statement of the lemma:
With Eq. (480) in Lemma A24 is
Using this inequality, we obtain the second statement of the lemma:
We now define the “separation” of a pattern from data here, since it has an important role for the convergence properties of the iteration.
We define , i.e. the separation of pattern from data as:
The pattern is separated from the other data if . Using the parallelogram identity, can also be expressed as
For we have .
Analog we say for a query and data , that is least separated from while being separated from other with if
Next we consider the case where the iteration has only one stable fixed point.
We start with the case where no pattern is well separated from the others.
•Global fixed point near the global mean: Analysis using the data center.
is the covariance matrix of data when its vectors are selected according to the probability :
The largest eigenvalue of the covariance matrix (equal to the largest singular value) is the variance in the direction of the eigenvector associated with the largest eigenvalue.
is the arithmetic mean (the center) of the patterns. is the maximal distance of the patterns to the center .
The maximal distance to the center allows the derivation of a bound on the norm of the Jacobian.
Next lemma gives a condition for a global fixed point.
For there exists a unique fixed point (global fixed point) of iteration in each compact set.
In order to bound the variance we compute the vector that minimizes
The Hessian of is positive definite since
and is a convex function. Hence, the mean
minimizes . Therefore, we have
Let us quickly recall that the spectral norm of an outer product of two vectors is the product of the Euclidean norms of the vectors:
since has eigenvector with eigenvalue and otherwise zero eigenvalues.
We now bound the variance of the patterns:
Therefore, the tightness of the bound depends on eigenvalues which are not the largest. Hence variations which are not along the largest variation weaken the bound.
Next we investigate the location of fixed points which existence is ensured by the global convergence stated in Theorem A2. For patterns , we consider the iteration
In particular normalization methods like batch normalization would promote the mean as a fixed point.
We consider the differences of dot products for : , for fixed point : , and for the center : . Using the Cauchy-Schwarz inequality, we get
where we used , , and . In particular
Let , therefore the maximal softmax component is . For the maximal softmax component we have:
Analogously we obtain for , a bound on the maximal softmax component if the center is put into the iteration:
Analog we obtain a bound for on the maximal softmax component of the fixed point:
The two important terms are , the variance or spread of the data and , which tells how well the data is centered. For a contraction mapping we already required , therefore the first term in the exponent is . The second term is small if the data is centered.
•Global fixed point near the global mean: Analysis using softmax values.
If for all and , then and we have . For we obtain from Lemma A2:
The local fixed point is with .
We now treat this case more formally. First we discuss conditions that ensure that the iteration is a contraction mapping. We consider the iteration Eq. (57) in the variable :
With , Eq. (476) from Lemma A24 is
Since , the previous bounds can be combined as follows:
where we used Eq. (170). , therefore is times the maximal second moment of the data squared.
Obviously, is a contraction mapping in compact sets, where
For the 1-norm, we use Lemma A24 and to obtain from Eq. (115):
where , , , (maximal absolute row sum norm), and . Let us quickly mention some auxiliary estimates related to :
where the first inequaltiy is from Hölder’s inequality. We used
where the first inequality is from Hölder’s inequality (here the same as the Cauchy-Schwarz inequality). See proof of Lemma A24 for the 1-norm bound on . Everything else follows from the fact that the 1-norm is sub-multiplicative as induced matrix norm.
We consider the minimal .
The solution to this minimization problem is . Therefore, we have and Using Eq. (119) we obtain
We move on to the next case, where the patterns are well separated. In this case the iteration goes to the pattern to which the initial is most similar. If the initial is similar to a vector then it will converge to and will be . The main ingredients are again Banach’s Theorem and estimates on the Jacobian norm.
•Proof of a fixed point by Banach Fixed Point Theorem.
Mapped Vectors Stay in a Compact Environment. We show that if is sufficient dissimilar to other then there is an compact environment of (a sphere) where the fixed point iteration maps this environment into itself. The idea of the proof is to define a sphere around for which points from the sphere are mapped by into the sphere.
We first need following lemma which bounds the distance , where is the pattern that is least separated from but separated from other patterns.
For a query and data , there exists a that is least separated from while being separated from other with :
We now can bound :
We define , i.e. the separation of pattern from data as:
The pattern is separated from the other data if . Using the parallelogram identity, can also be expressed as
For we have .
Next we define the sphere where we want to apply Banach fixed point theorem.
With given, if the assumptions
data point is well separated from the other data:
Using the Cauchy-Schwarz inequality, we obtain for :
where we used the assumption (A1) of the lemma.
•Banach Fixed Point Theorem. Now we have all ingredients to apply Banach fixed point theorem.
We used that the spectral norm is bounded by the Frobenius norm which can be expressed by the norm squared of its column vectors:
The norm of Jacobian of the fixed point iteration is bounded
The separation of pattern from data is
We can bound the spectral norm of the Jacobian, which upper bounds the Lipschitz constant:
Solving this inequality for gives
In an environment around in which Eq. (183) holds, is a contraction mapping and every point converges under the iteration to when the iteration stays in the environment. After every iteration the mapped point is closer to the fixed point than the original point :
For large the iteration is close to the fixed point even after one update. This has been confirmed in several experiments.
The proof concept is the same as for a single pattern but now for the arithmetic mean of similar patterns.
The Jacobian of the fixed point iteration is
is the covariance matrix of data when its vectors are selected according to the probability :
It’s clear that the largest eigenvalue of the covariance matrix (equal to the largest singular value) is the variance in the direction of the eigenvector associated with the largest eigenvalue.
Furthermore the variance goes to zero as one goes to one, since only one pattern is chosen and there is no variance.
The variance is reasonable small if all patterns are chosen with equal probability.
The variance is small if few similar patterns are chosen with high probability. If the patterns are sufficient similar, then the spectral norm of the covariance matrix is smaller than one.
The first three issues have already been adressed. Now we focus on the last one in greater detail. We assume that the first patterns are much more probable (and similar to one another) than the other patterns. Therefore, we define:
The variance of the first patterns is
The spectral norm of an outer product of two vectors is the product of the Euclidean norms of the vectors:
since has eigenvector with eigenvalue and otherwise zero eigenvalues.
We now bound the norms of some matrices and vectors:
In order to bound the variance of the first patterns, we compute the vector that minimizes
The Hessian of is positive definite since
and is a convex function. Hence, the mean
minimizes . Therefore, we have
We now bound the variance on the first patterns:
Combining the previous two estimates immediately leads to Eq. (201).
Therefore, the tightness of the bound depends on eigenvalues which are not the largest. That is variations which are not along the strongest variation weaken the bound.
•Proof of a fixed point by Banach Fixed Point Theorem.
Without restricting the generality, we assume that the first patterns are much more probable (and similar to one another) than the other patterns. Therefore, we define:
•Mapped vectors stay in a compact environment. We show that if is sufficient dissimilar to other with then there is an compact environment of (a sphere) where the fixed point iteration maps this environment into itself. The idea of the proof is to define a sphere around for which the points from the sphere are mapped by into the sphere.
We first need following lemma which bounds the distance of a which is close to .
For a query and data , we define
Let , therefore . For softmax components with we have
since for each with , therefore
We now can bound :
where we applied Eq. (233) in the penultimate inequality. This is the statement of the lemma. ∎
The separation of the center (the arithmetic mean) of the first from data is , defined as
The center is separated from the other data with if . By the same arguments as in Eq. (140), can also be expressed as
For we have .
Next we define the sphere where we want to apply Banach fixed point theorem.
With given, if the assumptions
the center is well separated from other data with :
the distance of similar patterns to the center is sufficient small:
Using the Cauchy-Schwarz inequality, we obtain for :
where we used the assumption (A1) of the lemma.
For the last but one inequality we used .
•Banach Fixed Point Theorem. Now we have all ingredients to apply Banach fixed point theorem.
We assume that the first patterns are much more probable (and similar to one another) than the other patterns. Therefore, we define:
The variance of the first patterns is
From the last condition we require for a contraction mapping:
We want to see how large is. The separation of center from data is
A.1.6 Properties of Fixed Points Near Stored Pattern
In Subsection A.1.5.3 many stable states that are fixed points near the stored patterns are considered. We now consider this case. In the fist subsection we investigate the storage capacity if all patterns are sufficiently separated so that metastable states do not appear. In the next subsection we look into the updates required and error when retrieving the stored patterns. For metastable states we can do the same analyses if each metastable state is treated as one state like one pattern.
We see a trade-off that is known from classical Hopfield networks and for modern Hopfield networks. Small separation of the pattern from the other patterns gives high storage capacity. However the convergence speed is lower and the retrieval error higher. In contrast, large separation of the pattern from the other pattern allows the retrieval of patterns with one update step and exponentially low error.
From Subsection A.1.5.3 need some definitions. We assume to have patterns, the separation of pattern from the other patterns is , defined as
The pattern is separated from the other data if . The separation can also be expressed as
The maximal length of a pattern is .
We next define what we mean with storing and retrieving a pattern.
the inequality follows from following master inequality
Therefore, we have using the Cauchy-Schwarz inequality:
The last inequality is a contraction to Eq. (302) if we assume that
For simplicity and in accordance with the results of the classical Hopfield network, we assume all patterns being on a sphere with radius :
Under assumption Eq. (305) we have only to show that the master inequality Eq. (307) is fulfilled for each to have a separate fixed point near each .
We defined as the angle between and . The minimal angle between two data points is
therefore it is sufficient to show the master inequality on the sphere:
Under assumption Eq. (305) we have only to show that the master inequality Eq. (307) is fulfilled for . We consider patterns on the sphere, therefore the master inequality Eq. (307) becomes Eq. (311). First we show results when pattern positions on the sphere are constructed and is ensured. Then we move on to random patterns on a sphere, where becomes a random variable.
•Storage capacity for patterns placed on the sphere.
Next theorem says how many patterns we can stored (fixed point with attraction basin near pattern) if we are allowed to place them on the sphere.
We assume and patterns on the sphere with radius . If and the dimension of the space is or if and the dimension of the space is , then the number of patterns that can be stored (fixed point with attraction basin near pattern) is at least
For random patterns on the sphere, we have to show that the master inequality Eq. (311) holds:
We now place the patterns equidistant on the sphere where the pattern are separated by an angle :
points on the sphere. In a spherical coordinate system a pattern differs from its most closest patterns by an angle and there are angles. Solving for gives
The number of patterns that can be stored is determined by the largest that fulfils
We set and obtain for Eq. (317):
The last inequality can be fulfilled with and proper . For , and the inequality is fulfilled. The left hand side minus the right hand side is . Its derivative with respect to is strict positive. Therefore, the inequality holds for .
For , and the inequality is fulfilled. The left hand side minus the right hand side is . Its derivative with respect to is strict positive. Therefore, the inequality holds for .
If we want to store considerably more patterns, then we have to increase the length of the vectors or the dimension of the space where the vectors live. The next theorem shows results for the number of patterns with .
We assume and patterns on the sphere with radius . If and the dimension of the space is or if and the dimension of the space is , then the number of patterns that can be stored (fixed point with attraction basin near pattern) is at least
We set and obtain for Eq. (317):
The last inequality can be fulfilled with and proper . For , and the inequality is fulfilled. The left hand side minus the right hand side is . Its derivative with respect to is strict positive. Therefore, the inequality holds for .
For , and the inequality is fulfilled. The left hand side minus the right hand side is . Its derivative with respect to is strict positive. Therefore, the inequality holds for .
•Storage capacity for random patterns on the sphere.
Next we investigate random points on the sphere. Under assumption Eq. (305) we have to show that the master inequality Eq. (311) is fulfilled for , where now is now a random variable. We use results on the distribution of the minimal angles between random patterns on a sphere according to Cai et al. (2013) and Brauchart et al. (2018). Theorem 2 in Cai et al. (2013) gives the distribution of the minimal angle for random patterns on the unit sphere. Proposition 3.5 in Brauchart et al. (2018) gives a lower bound on the probability of the minimal angle being larger than a given constant. We require this proposition to derive the probability of pattern having a minimal angle . Proposition 3.6 in Brauchart et al. (2018) gives the expectation of the minimal angle.
We will prove high probability bounds for the expected storage capacity. We need the following tail-bound on (the minimal angle of random patterns on a sphere):
Let be the dimension of the pattern space,
and such that . Then
The statement of the lemma is Eq. (3-6) from Proposition 3.5 in Brauchart et al. (2018). ∎
Next we derive upper and lower bounds on the constant since we require them later for proving storage capacity bounds.
For defined in Eq. (323) we have the following bounds for every :
We use for the following bound related to Stirling’s approximation formula for the gamma function, c.f. (Olver et al., 2010, (5.6.1)):
Using Stirling’s formula Eq. (326), we upper bound :
For the first inequality, we applied Eq. (326), while for the second we used for .
Next, we lower bound by again applying Stirling’s formula Eq. (326):
where the last inequality holds because of monotonicity of and using the fact that for it takes on the value 2. ∎
We require a bound on to bound the master inequality Eq. (311).
For the function can be upper bounded by:
We use the infinite product representation of , c.f. (Olver et al., 2010, (4.22.2)):
for and , we can get the following upper bound on Eq. (330):
The last but one inequality uses , which implies . Thus Eq. (329) is proven.
•Exponential storage capacity: the base as a function of the parameter , the radius of the sphere , the probability , and the dimension of the space.
We express the number of stored patterns by an exponential function with base and an exponent linear in . We derive constraints on he base as a function of , the radius of the sphere , the probability that all patterns can be stored, and the dimension of the space. With , , and (to ensure a sphere), the following theorem gives our main result.
We assume a failure probability and randomly chosen patterns on the sphere with radius . We define
where is the upper branch of the Lambert function (Olver et al., 2010, (4.13)) and ensure
Then with probability , the number of random patterns that can be stored is
Therefore it is proven for with , , and () and proven for with , , , and ().
We consider the probability that the master inequality Eq. (311) is fulfilled:
Therefore, with probability the storage capacity is largest that fulfills
For Eq. (339) to be fulfilled, it is sufficient that
If we insert the assumption Eq. (334) of the theorem into Eq. (335), then we obtain . We now apply the upper bound from Eq. (325) and the upper bound from to inequality Eq. (341). In the resulting inequality we insert to check whether it is fulfilled with this special value of and obtain:
Dividing by , inserting , and exponentiation of the left and right side by gives:
After some algebraic manipulation, this inequality can be written as
We determine the value of which makes the inequality Eq. (344) equal to zero. We solve
where is the upper branch of the Lambert function (see Def. A6). Hence, the solution is
The solution exist, since the Lambert function (Olver et al., 2010, (4.13)) is defined for and we have .
Since fulfills inequality Eq. (344) and therefore also Eq. (342), we have a lower bound on the storage capacity :
Next we aim at a lower bound on which does not use the Lambert function (Olver et al., 2010, (4.13)). Therefore, we upper bound to obtain a lower bound on , therefore, also a lower bound on the storage capacity . The lower bound is given in the next corollary.
We assume a failure probability and randomly chosen patterns on the sphere with radius . We define
Using the omega constant we set
Then with probability , the number of random patterns that can be stored is
Examples are for , , and () and for , , and ().
We lower bound the defined in Theorem A5. According to (Hoorfar & Hassani, 2008, Theorem 2.3) we have for any real and :
To upper bound for , we set
See for these equations the special values of the Lambert function in Lemma A31. We have the upper bound on :
At the right hand side of interval $u=0\exp(u)=1$ and get:
Therefore, the bound is tight at the right hand side of of interval $\exp(u)=1u=0W_{0}(\exp(u))\exp(u)\inu\in[-\infty,0]. We obtain from Hoorfar & Hassani (2008, Corollary 2.6) the following bound onW_{0}(\exp(u))1<\exp(u)0
A lower bound on is obtained via the upper bounds Eq. (357) and Eq. (355) on as . We set and obtain
We insert this bound into Eq. (347), the solution for , to obtain the statement of the theorem.
•Exponential storage capacity: the dimension of the space as a function of the parameter , the radius of the sphere , and the probability .
We express the number of stored patterns by an exponential function with base and an exponent linear in . We derive constraints on the dimension of the space as a function of , the radius of the sphere , the probability that all patterns can be stored, and the base of the exponential storage capacity. The following theorem gives this result.
We assume a failure probability and randomly chosen patterns on the sphere with radius . We define
where is the Lambert function (Olver et al., 2010, (4.13)). For the function is the upper branch and for we use the lower branch . If we ensure that
then with probability , the number of random patterns that can be stored is
We consider the probability that the master inequality Eq. (311) is fulfilled:
Therefore, with probability the storage capacity is largest that fulfills
For Eq. (365) to be fulfilled, it is sufficient that
If we insert the assumption Eq. (360) of the theorem into Eq. (361), then we obtain . We now apply the upper bound from Eq. (325) and the upper bound from to inequality Eq. (367). In the resulting inequality we insert to check whether it is fulfilled with this special value of and obtain:
Dividing by , inserting , and exponentiation of the left and right side by gives:
This inequality Eq. (369) can be reformulated as:
We determine the value of which makes the inequality Eq. (372) equal to zero. We solve
where is the Lambert function (see Def. A6). For we have to use the upper branch of the Lambert function and for we use the lower branch of the Lambert function (Olver et al., 2010, (4.13)). We have to ensure that for a solution to exist. For we have .
Since fulfills inequality Eq. (369) and therefore also Eq. (368), we have a lower bound on the storage capacity :
We assume a failure probability and randomly chosen patterns on the sphere with radius . We define
then with probability , the number of random patterns that can be stored is
Setting , , and yields .
For the Eq. (359) from Theorem (A6) can be written as
From Alzahrani & Salem (2018, Theorem 3.1) we get the following bound on :
for . We apply Eq. (381) to Eq. (380) with .
•Storage capacity for the expected minimal separation instead of the probability that all patterns can be stored. In contrast to the previous paragraph, we want to argue about the storage capacity for the expected minimal separation. Therefore, we will use the following bound on the expectation of (minimal angle), which gives also a bound on the expected of (minimal separation):
We have the following lower bound on the expectation of :
The bound is valid for all and .
Let us start with some preliminary estimates. First of all we need some asymptotics for the constant in Eq. (383):
The following estimate holds for :
The recursion formula for the Gamma function is (Olver et al., 2010, (5.5.1)):
We use Eq. (325) and the fact that for to obtain:
where in the last step we used the elementary inequality , which follows from the mean value theorem. ∎
The next theorem states the number of stored patterns for the expected minimal separation.
We assume patterns on the sphere with radius that are randomly chosen. Then for all values for which
holds, the number of stored patterns for the expected minimal separation is at least
The inequality Eq. (387) is e.g. fulfilled with , , and .
Instead of considering the probability that the master inequality Eq. (311) is fulfilled we now consider whether this inequality is fulfilled for the expected minimal distance. We consider the expectation of the minimal distance :
For this expectation, the master inequality Eq. (311) becomes
We want to find the largest that fulfills this inequality.
We apply Eq. (329) and Jensen’s inequality to deduce the following lower bound:
Now we use Eq. (383) and Eq. (384) to arrive at
for sufficiently large . Thus in order to fulfill Eq. (390), it is enough to find values that satisfy Eq. (387).
Retrieval of a pattern for fixed point and query is defined via an by , that is, the update is -close to the fixed point. The update rule retrieves a pattern with one update for well separated patterns, that is, is large.
For given and sufficient large , we have , that is, retrieval with one update.
After every iteration the mapped point is closer to the fixed point than the original point :
We want to estimate how large is. For we have:
The variance of the separation of two points with normally distributed components is
The expected value for the separation of two random vectors gives:
The retrieval error decreases exponentially with the separation .
The retrieval error of pattern is bounded by
and for together with by
We compute the retrieval error which is just . From Lemma A4 we have
For and Eq. (404) gives
A.1.7 Learning Associations
We consider three cases of learning associations, i.e. three cases of how sets are associated. (i) Non of the sets is mapped in an associative space. The raw state pattern is the state (query) pattern , i.e. , and the raw stored pattern is the stored pattern (key), i.e. . (ii) Either one of the sets is mapped to the space of the other set or an association matrix is learned. (iia) The state patterns are equal to the raw patterns, i.e. , and raw stored patterns are mapped via to the space of the state patterns, i.e. . (iib) The stored patterns are equal to the raw patterns, i.e. , and raw state patterns are mapped via to the space of the stored patterns, i.e. . (iic) The matrix is an association matrix. We will compute the derivative of the new state pattern with respect to , which is valid for all sub-cases (iib)–(iic). (iii) Both set of patterns are mapped in a common associative space. A raw state pattern is mapped by to a state pattern (query) , that is . A raw stored pattern is mapped via to stored pattern (key) , that is . We will compute the derivative of the new state pattern with respect to both and .
The sets are associated via their raw patterns, i.e. the raw state pattern is the state (query) pattern , i.e. , and raw stored pattern is the stored pattern (key), i.e. . There is no mapping in an associative space.
The derivative with respect to is
The derivative with respect to is
These derivatives allow to apply the chain rule if a Hopfield layer is integrated into a deep neural network.
Only one of the sets or is mapped in the space of the patterns of the other set. Case (a): the state patterns are equal to the raw patterns and raw stored patterns are mapped via to the space of the state patterns, i.e. . Case (b): the stored patterns are equal to the raw patterns and raw state patterns are mapped via to the space of the stored patterns, i.e. . Case (c): the matrix associates the sets and . This case also includes that , which is treated in next subsection. The next subsection focuses on a low rank approximation of by defining the dimension of associative space and use the matrices and to define , or equivalently to map and into the associative space.
From a mathematical point of view all these case are equal as they lead to the same update rule. Therefore, we consider in the following Case (a) with and . Still, the following formula are valid for all three cases (a)–(c).
For multiple updates this update rule has to be used. However for a single update, or the last update we consider a simplified update rule.
The derivative with respect to is
We have the product of the 3-dimensional tensor with the vector which gives a 2-dimensional tensor, i.e. a matrix:
To obtain the derivative of the full update rule Eq. (412) we have to add the term
Both sets and are mapped in an associative space. Every raw state pattern is mapped via to a state pattern (query) . Every raw stored pattern is mapped via to a stored pattern (key) . In the last subsection we considered a single matrix . For we have the case of the last subsection. However in this subsection we are looking for a low rank approximation of . Toward this end we define the dimension of associative space and use the matrices and to map to the associative space.
We consider raw state patterns that are mapped to state patterns with and raw stored pattern that are mapped to stored patterns with . The update rule is
•Derivative with respect to . The derivative with respect to is
We have the product of the 3-dimensional tensor with the vector which gives a 2-dimensional tensor, i.e. a matrix:
To obtain the derivative of the full update rule Eq. (423) we have to include the factor , then get
•Derivative with respect to . The derivative with respect to is
We have the product of the 3-dimensional tensor with the vector which gives a 2-dimensional tensor, i.e. a matrix:
To obtain the derivative of the full update rule Eq. (423) we have to add the term
and to include the factor , then get
A.1.8 Infinite Many Patterns and Forgetting Patterns
In the next subsection we show how the new Hopfield networks can be used for auto-regressive tasks by causal masking. In the following subsection, we introduce forgetting to the new Hopfield networks by adding a negative value to the softmax which is larger if the pattern was observed more in the past.
The new Hopfield networks can be used for auto-regressive tasks, that is time series prediction and similar. Causal masking masks out the future by a large negative value in the softmax.
We assume to have infinite many stored patterns (keys) that are represented by the infinite matrix
The pattern index is now a time index, that is, we observe at time .
We can use an infinite pattern matrix with an infinite softmax when using causal masking. The pattern matrix at time is
For and this becomes
We introduce forgetting to the new Hopfield networks by adding a negative value in the softmax which increases with patterns that are more in the past.
We assume to have infinite many patterns that are represented by the infinite matrix
The pattern index is now a time index, that is, we observe at time .
A.1.9 Number of Spurious States
where is a positive constant, and is the Gaussian with mean and covariance matrix .
In Carreira-Perpiñán & Williams (2003) it was shown that Eq. (458) can have more than modes, that is, more than maxima.
A.2 Properties of Softmax, Log-Sum-Exponential, Legendre Transform, Lambert W Function
In particular, the base can be used to speed up computations.
Eq. (466) is obtained from Equation (8) in Gao & Pavel (2017) and Eq. (467) from Equation (11) in Gao & Pavel (2017). ∎
Next we consider the Jacobian of the softmax and its properties.
Alternatively can be viewed as the expected second moment minus the mean squared which gives the variance that is larger equal to zero.
The Jacobian is times a positive semi-definite matrix, which is a positive semi-definite matrix. ∎
Moreover, the softmax is a monotonic map, as described in the next lemma.
If , then for the spectral norm of the Jacobian holds
We consider the maximum absolute column sum norm
The last inequality is a direct consequence of Hölder’s inequality.
For , we have . Therefore, for all values of .
If (), then and for . The derivative for , therefore increases with for . Using and for , we obtain for all . Consequently, we have . ∎
Using the bounds on the norm of the Jacobian, we give some Lipschitz properties of the softmax function.
From Lemma A24 we know globally. For we have according to Lemma A24: . ∎
For completeness we present a result about cocoercivity of the softmax:
We apply the Baillon-Haddad theorem (e.g. Theorem 1 in Gao & Pavel (2017)) together with Lemma A25. ∎
The Convex Conjugate (Legendre-Fenchel transform) of a function from a Hilbert Space to is which is defined as
See page 219 Def. 13.1 in Bauschke & Combettes (2017) and page 134 in Garling (2017). Next we define the Legendre transform, which is a more restrictive version of the convex conjugate.
See page 91 in Boyd & Vandenberghe (2009).
Let and be two functions from to , then the infimal convolution (or epi-sum) of and is
See Def. 12.1 in Bauschke & Combettes (2017).
Let and be functions from to . Then the following hold:
Convex Conjugate of affine transformation of the arguments. Let be a non-singular matrix and a vector
Since is a non-negative convex function and we have because of Proposition 11.3.3 in Garling (2017) that . Additionally, by example (a) on page 137 we get for and that . Putting all together we get the desired result. The same result can also be deduced from page 222 Example 13.6 in Bauschke & Combettes (2017).
Follows immediately from the definition since
From Proposition 13.24 (i) in Bauschke & Combettes (2017) and Proposition 11.4.2 in Garling (2017) we get
the Legendre transform is the negative entropy function, restricted to the probability simplex:
For the negative entropy function, restricted to the probability simplex:
the Legendre transform is the log-sum exponential
See page 93 Example 3.25 in Boyd & Vandenberghe (2009) and (Gao & Pavel, 2017). If is a regular convex function (lower semi-continuous convex function), then according to page 135 Exercise 11.2.3 in Garling (2017). If is lower semi-continuous and convex, then according to Theorem 13.37 (Fenchel-Moreau) in Bauschke & Combettes (2017). The log-sum-exponential is continuous and convex. ∎
Let be non-singular and a Hilbert space. We define
We use the definition of the Legendre transform:
where we used .
If is a regular convex function (lower semi-continuous convex function), then according to page 135 Exercise 11.2.3 in Garling (2017). If is lower semi-continuous and convex, then according to Theorem 13.37 (Fenchel-Moreau) in Bauschke & Combettes (2017). Consequently we have
We introduce the Lambert function and some of its properties, since it is needed to derive bounds on the storage capacity of our new Hopfield networks.
The Lambert function (Olver et al., 2010, (4.13)) is the inverse function of
The Lambert function has an upper branch for and a lower branch for . We use if a formula holds for both branches. We have
We present some identities for the Lambert function (Olver et al., 2010, (4.13)):
Identities for the Lambert function are
We also present some special values for the Lambert function (Olver et al., 2010, (4.13)):
We need in some proofs a version of the mean value theorem as given in the next lemma.
where is the Jacobian of and the integral of the matrix is component-wise.
The statement follows since the Jacobian has as entries . ∎
A.3 Modern Hopfield Networks: Binary States (Krotov and Hopfield)
To enhance RNNs with additional associative memory like Hopfield networks have been proposed (Ba et al., 2016a; b). The associative memory stores hidden states of the RNN, retrieves stored states if they are similar to actual ones, and has a forgetting parameter. The forgetting and storing parameters of the RNN associative memory have been generalized to learned matrices (Zhang & Zhou, 2017). LSTMs with associative memory via Holographic Reduced Representations have been proposed (Danihelka et al., 2016).
The storage capacity of classical binary Hopfield networks (Hopfield, 1982) has been shown to be very limited. In a -dimensional space, the standard Hopfield model can store uncorrelated patterns without errors but only random patterns with for a fixed stable pattern or if all patterns are stable (McEliece et al., 1987). The same bound holds for nonlinear learning rules (Mazza, 1997). Using tricks-of-trade and allowing small retrieval errors, the storage capacity is about (Crisanti et al., 1986; Hertz et al., 1991; Torres et al., 2002). If the learning rule is not related to the Hebb rule then up to patterns can be stored (Abu-Mostafa & StJacques, 1985). Using Hopfield networks with non-zero diagonal matrices, the storage can be increased to (Folli et al., 2017). In contrast to the storage capacity, the number of energy minima (spurious states, stable states) of Hopfield networks is exponentially in (Tanaka & Edwards, 1980; Bruck & Roychowdhury, 1990; Wainrib & Touboul, 2013).
Recent advances in the field of binary Hopfield networks (Hopfield, 1982) led to new properties of Hopfield networks. The stability of spurious states or metastable states was sensibly reduced by a Hamiltonian treatment for the new relativistic Hopfield model (Barra et al., 2018). Recently the storage capacity of Hopfield networks could be increased by new energy functions. Interaction functions of the form lead to storage capacity of , where depends on the allowed error probability (Krotov & Hopfield, 2016; 2018; Demircigil et al., 2017) (see (Krotov & Hopfield, 2018) for the non-binary case). Interaction functions of the form lead to storage capacity of for (Demircigil et al., 2017).
Interaction functions of the form lead to exponential storage capacity of where all stored patterns are fixed points but the radius of attraction vanishes (Demircigil et al., 2017). It has been shown that the network converges with high probability after one update (Demircigil et al., 2017).
A.3.2 Energy and Update Rule for Binary Modern Hopfield Networks
We follow (Demircigil et al., 2017) where the goal is to store a set of input data that are represented by the matrix
with , where gives the energy function of the classical Hopfield network. This allows to store patterns (Krotov & Hopfield, 2016). Krotov and Hopfield (Krotov & Hopfield, 2016) suggested for minimizing this energy an asynchronous updating dynamics for component :
While Krotov and Hopfield used , Demircigil et al. (Demircigil et al., 2017) went a step further and analyzed the model with the energy function , which leads to an exponential storage capacity of . Furthermore with a single update the final pattern is recovered with high probability. These statements are given in next theorem.
Consider the generalized Hopfield model with the dynamics described in Eq. (545) and interaction function given by . For a fixed let and let be patterns chosen uniformly at random from . Moreover fix . For any and any taken uniformly at random from the Hamming sphere with radius centered in , , where is assumed to be an integer, it holds that
if is chosen in dependence of such that
The proof can be found in Demircigil et al. (2017). ∎
The number of patterns is exponential in the number of components. The result
means that one update for each component is sufficient to recover the pattern with high probability. The constraint on gives the trade-off between the radius of attraction and the number of pattern that can be stored.
as , i.e. with a probability converging to , all the patterns are fixed points of the dynamics. In this case we can have .
where is the Cartesian unit vector with a one at position and zeros elsewhere, is the projection to the -th component, and
A.4 Hopfield Update Rule is Attention of The Transformer
The left part of Eq. (548) is the transformer attention. Besides the attention mechanism, Hopfield networks allow for other functionalities in deep network architectures, which we introduce via specific layers in the next section. The right part of Eq. (548) serves as starting point for these specific layers.
A.5 Experiments
We analyzed pre-trained BERT models from Hugging Face Inc. (Wolf et al., 2019) according to these operating classes. In Fig. A.3 in the appendix the distribution of the pre-trained bert-base-cased model is depicted (for other models see appendix Section A.5.1.4). Operating classes (II) (large metastable states) and (IV) (small metastable states) are often observed in the middle layers. Operating class (I) (averaging over a very large number of patterns) is abundant in lower layers. Similar observations have been reported in other studies (Toneva & Wehbe, 2019a; b; Tay et al., 2020). Operating class (III) (medium metastable states) is predominant in the last layers.
Transformer architectures are known for their high computational demands. To investigate the learning dynamics of such a model and at the same time keeping training time manageable, we adopted the BERT-small setting from ELECTRA (Clark et al., 2020). It has layers, heads and a reduced hidden size, the sequence length is shortened from to tokens and the batch size is reduced from to . Additionally, the hidden dimension is reduced from to and the embedding dimension is reduced from to (Clark et al., 2020). The training of such a BERT-small model for million update steps takes roughly four days on a single NVIDIA V100 GPU.
As the code base we use the transformers repository from Hugging Face, Inc (Wolf et al., 2019). We aim to reproduce the dataset of Devlin et al. (2019) as close as possible, which consists of the English Wikipedia dataset and the Toronto BookCorpus dataset (Zhu et al., 2015). Due to recent copyright claims the later is not publicly available anymore. Therefore, the pre-training experiments use an uncased snapshot of the original BookCorpus dataset.
To better understand how operation modes in attention heads develop, we tracked the distribution of counts (see main paper) over time in a BERT-small model. At the end of training we visualized the count distribution, grouped into four classes (see Figure A.4). The thresholds for the classes were chosen according to the thresholds of Figure 2 in the main paper. However, they are divided by a factor of to adapt to the shorter sequence length of compared to . From this plot it is clear, that the attention in heads of Class IV commit very early to the operating class of small metastable states.
The attention from the -th token to the -th position is calculated as
where normalizes the -th row of the attention matrix to sum up to one:
For initialization we uniformly sample a location vector and a scale vector per head. A simple way to consider the individual position of each token at initialization is to use the supporting points (see Figure A.6). In practice no difference to the random initialization was observed.
A.5.2 Experiment 2: Multiple Instance Learning Datasets.
An architecture called DeepRC, is based on our modern Hopfield networks, for immune repertoire classification and compared to other machine learning approaches. For DeepRC, we consider immune repertoires as input objects, which are represented as bags of instances. In a bag, each instance is an immune receptor sequence and each bag can contain a large number of sequences. At its core, DeepRC consists of a modern Hopfield network that extracts information from each repertoire. The stored patterns (keys) are representations of the immune amino acid sequences (instances) that are obtained by an 1D convolutional network with position encoding. Each state pattern (query) is static and learned via backpropagation. For details see Widrich et al. (2020a; b).
Our new Hopfield network has been integrated into a deep learning architecture for immune repertoire classification, a massive multiple instance learning task (Widrich et al., 2020a; b). Theorem 3 states that modern Hopfield networks possess an exponential storage capacity which enables to tackle massive multiple instance learning (MIL) problems (Dietterich et al., 1997). Immune repertoire classification (Emerson et al., 2017) typically requires to extract few patterns from a large set of sequences, the repertoire, that are indicative for the respective immune status. Most MIL methods fail due the large number of instances.
Data is obtained by experimentally observed immune receptors as well as simulated sequences sequence motifs (Akbar et al., 2019; Weber et al., 2020) with low yet varying degrees of frequency are implanted. Four different categories of datasets are constructed: (a) Simulated immunosequencing data with implanted motifs, (b) immunosequencing data generated by long short-term memory (LSTM) with implanted motifs, (c) real-world immunosequencing data with implanted motifs, and (d) real-world immunosequencing data with known immune status (Emerson et al., 2017). Categories (a), (b), and (d) contain approx. 300,000 instances per immune repertoire. With over 30 billion sequences in total, this represents one of the largest multiple instance learning experiments ever conducted (Carbonneau et al., 2018). Despite the massive number of instances as well as the low frequency of sequences indicative of the respective immune status, deep learning architectures with modern Hopfield networks outperform all competing methods with respect to average area under the ROC curve in all four categories, (a), (b), (c) and (d) (for details see Widrich et al. (2020a)).
We evaluate and compare the performance of DeepRC to a set of machine learning methods that serve as baseline, were suggested, or can readily be adapted to immune repertoire classification. The methods comprise (i) known motif, which counts how often the known implanted motifs occur, (ii) Support Vector Machine (SVM) approach that uses a fixed mapping from a bag of sequences to the corresponding -mer counts and used the MinMax and Jaccard kernel, (iii) -Nearest Neighbor (KNN) with -mer representation, transforming MinMax and Jaccard kernel to distances, (iv) logistic regression on the -mer representation, (v) burden test that first identifies sequences or -mers and then computes a burden score per individual, and (vi) logistic multiple instance learning (lMIL). On the real-world dataset DeepRC achieved an AUC of , followed by the SVM with MinMax kernel (AUC ) and the burden test with an AUC of . Overall on all datasets, DeepRC outperformed all competing methods with respect to average AUC (see Widrich et al. (2020a; b)).
Table A.1 reports the average performance in the simulated immunosequencing datasets (last column) and the performance on datasets of the remaining three categories. DeepRC outperforms all competing methods with respect to average AUC. Across categories, the runner-up methods are either the SVM for MIL problems with MinMax kernel or the burden test.
Classical benchmarking datasets comprise UCSB breast cancer classification (Kandemir et al., 2014), and the Elephant, Fox, Tiger datasets (Andrews et al., 2003).
Elephant, Fox and Tiger are MIL datasets for image annotation which comprise color images from the Corel dataset that have been preprocessed and segmented. An image consists of a set of segments (or blobs), each characterized by color, texture and shape descriptors. The datasets have 100 positive and 100 negative example images. The latter have been randomly drawn from a pool of photos of other animals. Elephant has 1391 instances and 230 features. Fox has 1320 instances and 230 features. Tiger has 1220 instances and 230 features. Furthermore, we use the UCSB breast cancer classification (Kandemir et al., 2014) dataset, which consists of 2,002 instances across 58 input objects. An instance represents a patch of a histopathological image of cancerous or normal tissue. The layer HopfieldPooling is used, which allows for computing a per-input-object representation by extracting an average of instances that are indicative for one of the two classes. The input to the HopfieldPooling layer is a set of embedded instances and a trainable but fixed state (query) pattern used for averaging of class-indicative instances. This averaging enables a compression of variable-sized bags to a fixed-sized representation to discriminate the bags. We performed a manual hyperparameter search on a validation set. In detail, we used the following architecture to perform the given task on the Elephant, Fox, Tiger and UCSCB breast cancer datasets: (I) we apply fully connected linear embedding layers with ReLU activation. (II) The output of this embedding serves as the input to our HopfieldPooling layer where the above described pooling operation is performed. (III) Thereafter we use ’ReLU - Linear blocks’ as the final linear output layers that perform the classification. Among other hyperparameters, different hidden layer widths (for the fully connected pre- and post-HopfieldPooling layers), learning rates and batch sizes were tried. Additionally our focus resided on the hyperparameters of the HopfieldPooling layer. Among those were the number of heads, the head dimension and the scaling factor \textbeta.
All models were trained for 160 epochs using the AdamW optimizer (Loshchilov & Hutter, 2017) with exponential learning rate decay (see Table A.2), and validated by 10-fold nested cross validation repeated five times with different splits on the data sets. The reported ROC AUC scores are the average of these repetitions. As overfitting imposed quite a problem, bag dropout was applied as the regularization technique of choice.
A.5.3 Experiment 3: Classification on Small UCI Benchmark Datasets
Datasets with a small number of samples, like the UCI benchmark datasets, are particularly difficult for neural networks to generalize on. In contrast to their performance on larger datasets, they are consistently outperformed by methods like e.g. gradient boosting, random forests (RF) and support vector machines (SVMs). Finding samples or even learning prototypes that are highly indicative for the class of a sample (query) suggest the use of Hopfield networks. We applied a modern Hopfield network via the layer Hopfield. The input vector is mapped to using a self-normalizing net (SNN) and is learned, where the dimension of (the number of stored fixed pattern) is a hyperparameter. The output of Hopfield enters the output layer.
Modern Hopfield networks via the layer Hopfield are compared to 17 groups of methods (Fernández-Delgado et al., 2014; Klambauer et al., 2017a):
Multivariate adaptive regression splines (MARS)
Logistic and Multinomial Regression (LMR)
Neural Networks (standard NN, BatchNorm, WeighNorm, MSRAinit, LayerNorm, ResNet, Self-Normalizing Nets)
Partial Least Squares and Principal Component Regression (PLSR)
As specified in the main paper, we consider datasets of the UC Irvine Machine Learning Repository, which contain less than samples per dataset, following the dataset separation into large and small dataset in Klambauer et al. (2017a). On each dataset, we performed a grid-search to determine the best hyperparameter setting and model per dataset. The hyperparameter search-space of the grid-search is listed in Table A.3. All models were trained for epochs with a mini-batch size of samples using the cross entropy loss and the PyTorch SGD module for stochastic gradient descent without momentum and without weight decay or dropout. After each epoch, the model accuracy was computed on a separated validation set. Using early stopping, the model with the best validation set accuracy averaged over consecutive epochs was selected as final model. This final model was then evaluated against a separated test set to determine the accuracy, as reported in Tables 2 and Table uci_detailed_results.csv in the supplemental materials.
As network architecture, we use fully connected embedding layers with SELU Klambauer et al. (2017a) activation functions and hidden units per embedding layer. These embedding layers are followed by the layer Hopfield. The number of hidden units is also used as number of dimensions for the Hopfield association space with a number of heads. The layer Hopfield is followed by a mapping to the output vector, which has as dimension the number of classes. Finally, the softmax function is applied to obtain the predicted probability for a class.
We compared the performance of 25 methods based on their method rank. For this we computed the rank per method per dataset based on the accuracy on the test set, which was then averaged over all 75 datasets for each method to obtain the method rank. For the baseline methods we used the scores summarized by (Klambauer et al., 2017a).
A.5.4 Experiment 4: Drug Design Benchmark Datasets
We test Hopfield layers on 4 classification datasets from MoleculeNet (Wu et al., 2017), which are challenging for deep learning methods. The first dataset is HIV, which was introduced by the Drug Therapeutics Program (DTP) AIDS Antiviral Screen. The second dataset is BACE, which has IC50 measurements for binding affinities of inhibitors (molecules) to the human -secretase 1 (BACE-1). The third dataset is BBBP (blood-brain barrier permeability), which stems from modeling and predicting the blood-brain barrier permeability (Martins et al., 2012). The fourth dataset is SIDER (Side Effect Resource) Kuhn et al. (2016) and contains 1427 approved drugs. These datasets represent four areas of modeling tasks in drug discovery, concretely to develop accurate models for predicting a) new anti-virals (HIV), b) new protein inhibitors (BACE), c) metabolic effects (BBBP), and d) side effects of a chemical compound (SIDER).
We implemented a Hopfield layer HopfieldLayer, in which we used the training-input as stored-pattern or key, the training-label as pattern-projection or value and the input as state-pattern or query. As described in section A.6 by concatenation of input and target the matrices and can be designed such that inside the softmax the input is used and outside the softmax the target .
All hyperparameters were selected on separate validation sets and we selected the model with the highest validation AUC on five different random splits.
We compared the Hopfield layer Hopfieldlayer to Support Vector Machines (SVMs) (Cortes & Vapnik, 1995; Schölkopf & Smola, 2002), Extreme Gradient Boosting (XGBoost) (Chen & Guestrin, 2016), Random Forest (RF) (Breiman, 2001), Deep Neural Networks (DNNs) (LeCun et al., 2015; Schmidhuber, 2015), and to graph neural networks (GNN) like Graph Convolutional Networks (GCNs) (Kipf & Welling, 2016), Graph Attention Networks (GATs) (Velic̆ković et al., 2018), Message Passing Neural Networks (MPNNs) (Gilmer et al., 2017), and Attentive FP (Xiong et al., 2020). Our architecture with HopfieldLayer has reached state-of-the-art for predicting side effects on SIDER as well as for predicting -secretase BACE . See Table A.5 for all results, where the results of other methods are taken from Jiang et al. (2020).
A.6 PyTorch Implementation of Hopfield Layers
The implementation is available at: https://github.com/ml-jku/hopfield-layers
In this section, we describe the implementation of Hopfield layers in PyTorch (Paszke et al., 2017; 2019) and, additionally, provide a brief usage manual. Possible applications for a Hopfield layer in a deep network architecture comprise:
multiple instance learning (MIL) (Dietterich et al., 1997),
processing of and learning with point sets (Qi et al., 2017a; b; Xu et al., 2018),
set-based and permutation invariant learning (Guttenberg et al., 2016; Ravanbakhsh et al., 2016; Zaheer et al., 2017; Korshunova et al., 2018; Ilse et al., 2018; Zhai et al., 2020),
attention-based learning (Vaswani et al., 2017a),
sequence analysis and time series prediction, and
storing and retrieving reference or experienced data, e.g. to store training data and retrieve it by the model or to store experiences for reinforcement learning.
The Hopfield layer in a deep neural network architecture can implement:
a memory (storage) with associative retrieval (Danihelka et al., 2016; Ba et al., 2016a),
conditional pooling and averaging operations (Wang et al., 2018; Ilse et al., 2020),
combining data by associations (Agrawal et al., 1993),
associative credit assignment (e.g. Rescorla-Wagner model or value estimation) (Sutton & Barto, 2018), and
attention mechanisms (Vaswani et al., 2017a; Bahdanau et al., 2014).
In particular, a Hopfield layer can substitute attention layers in architectures of transformer and BERT models. The Hopfield layer is designed to be used as plug-in replacement for existing layers like
pooling layers (max-pooling or average pooling),
permutation equivariant layers (Guttenberg et al., 2016; Ravanbakhsh et al., 2016),
In contrast to classical Hopfield networks, the Hopfield layer is based on the modern Hopfield networks with continuous states that have increased storage capacity, as discussed in the main paper. Like classical Hopfield networks, the dynamics of the single heads of a Hopfield layer follow a energy minimization dynamics. The energy minimization empowers our Hopfield layer with several advantages over other architectural designs like memory cells, associative memory, or attention mechanisms. For example, the Hopfield layer has more functionality than a transformer self-attention layer (Vaswani et al., 2017a) as described in Sec. A.6.2. Possible use cases are given in Sec. A.6.3. Source code will be provided under github.
A.6.2 Functionality
Non-standard functionalities that are added by a Hopfield layer are
Multiple Updates for precise fixed points,
Variable Beta that determines the kind of fixed points,
Dimension of the associative space for controlling the storage capacity,
Static Patterns for fixed pattern search, and
Pattern Normalization to control the fixed point dynamics by norm of the patterns and shift of the patterns.
A functional sketch of our Hopfield layer is shown in Fig. A.7.
•Association of two sets. The Hopfield layer makes it possible to associate two sets of vectors. This general functionality allows
for time series prediction (maybe with positional encoding),
for combining data sources by associations,
for averaging and pooling operations, and
In the main paper, Eq. (3) defines the novel update rule:
These matrices allow to rewrite Eq. (552) as:
•Variable . In the main paper, we have identified as a crucial parameter for the fixed point dynamics of the Hopfield network, which governs the operating mode of the attention heads. In appendix, e.g. in Lemma A7 or in Eq. (102) and Eq. (103), we showed that the characteristics of the fixed points of the new modern Hopfield network are determined by: , (maximal pattern norm), (spread of the similar patterns), and (center of the similar patterns). Low values of induce global averaging and higher values of metastable states. In the transformer attention, the parameter is set to as in Eq. (555). The Hopfield layer, however, allows to freely choose , since the fixed point dynamics does not only depend on the dimension of the associative space . Additionally, heavily influences the gradient flow to the matrices and . Thus, finding the right for the respective application can be crucial.
•Pattern Normalization. In the appendix, e.g. in Lemma A7 or in Eq. (102) and Eq. (103), we showed that the characteristics of the fixed points of the new modern Hopfield network are determined by: , (maximal pattern norm), (spread of the similar patterns), and (center of the similar patterns). We already discussed the parameter while the spread of the similar patterns is given by the data. The remaining variables and that both control the fixed point dynamics are adjusted pattern normalization. is the maximal pattern norm and the center of the similar patterns. Theorem A5 says that larger allows for more patterns to be stored. However, the size of metastable states will decrease with increasing . The vector says how well the (similar) patterns are centered. If the norm is large, then this leads to smaller metastable states. The two parameters and are controlled by pattern normalization and determine the size and convergence properties of metastable states. These two parameters are important for creating large gradients if heads start with global averaging which has small gradient. These two parameters can shift a head towards small metastable states which have largest gradient as shown in Fig. A.5(b). We allow for three different pattern normalizations, where the first is the default setting:
pattern normalization of the input patterns,
pattern normalization after mapping into the associative space,
A.6.3 Usage
As outlined in Sec. A.6.1, there are a variety of possible use cases for the Hopfield layer, e.g. to build memory networks or transformer models. The goal of the implementation is therefore to provide an easy to use Hopfield module that can be used in a wide range of applications, be it as part of a larger architecture or as a standalone module. Consequently, the focus of the Hopfield layer interface is set on its core parameters: the association of two sets, the scaling parameter , the maximum number of updates, the dimension of the associative space, the possible usage of static patterns, and the pattern normalization. The integration into the PyTorch framework is built such that with all the above functionalities disabled, the “HopfieldEncoderLayer” and the “HopfieldDecoderLayer”, both extensions of the Hopfield module, can be used as a one-to-one plug-in replacement for the TransformerEncoderLayer and the TransformerDecoderLayer, respectively, of the PyTorch transformer module.
The Hopfield layer can be used to implement or to substitute different layers:
Pooling layers: We consider the Hopfield layer as a pooling layer if only one static state (query) pattern exists. Then, it is de facto a pooling over the sequence, which results from the softmax values applied on the stored patterns. Therefore, our Hopfield layer can act as a pooling layer.
Permutation equivariant layers: Our Hopfield layer can be used as a plug-in replacement for permutation equivariant layers. Since the Hopfield layer is an associative memory it assumes no dependency between the input patterns.
GRU & LSTM layers: Our Hopfield layer can be used as a plug-in replacement for GRU & LSTM layers. Optionally, for substituting GRU & LSTM layers, positional encoding might be considered.
Attention layers: Our Hopfield layer can act as an attention layer, where state (query) and stored (key) patterns are different, and need to be associated.
Finally, the extensions of the Hopfield layer are able to operate as a self-attention layer (HopfieldEncoderLayer) and as cross-attention layer (HopfieldDecoderLayer), as described in (Vaswani et al., 2017a). As such, it can be used as building block of transformer-based or general architectures.