Pure Transformers are Powerful Graph Learners
Jinwoo Kim, Tien Dat Nguyen, Seonwoo Min, Sungjun Cho, Moontae Lee, Honglak Lee, Seunghoon Hong
Introduction
In recent years, Transformer has served as a versatile architecture in a broad class of machine learning problems, such as natural language processing , computer vision , and reinforcement learning , to name a few. It is because the fully-attentional structure of Transformer is general and powerful enough to take, process, and relate inputs and outputs of arbitrary structures, eliminating a need for data- and task-specific inductive bias to be baked into the network architecture. Combined with large-scale training, it opens up a new chapter for building a versatile model that can solve a wide range of problems involving diverse data modalities and even a mixture of modalities .
In graph learning domain, inspired by the breakthroughs, multiple works tried combining self-attention into graph neural network (GNN) architecture where message passing was previously dominant . As global self-attention across nodes cannot reflect the graph structure, however, these methods introduce graph-specific architectural modifications. This includes restricting self-attention to local neighborhoods , using global self-attention in conjunction with message-passing GNN , and injecting edge information into global self-attention via attention bias . Despite decent performance, such modifications can be a limiting constraint in terms of versatility, especially considering future integration to multi-task and multi-modal general-purpose attentional architectures . In addition, deviating from pure self-attention, these methods may inherit the issues of message-passing such as oversmoothing , and become incompatible with useful engineering techniques e.g., linear attention developed for standard self-attention.
Instead, we explore the opposite direction of applying a standard Transformer directly for graphs. For this, we treat all nodes and edges as independent tokens, augment them with appropriate token-wise embeddings, and feed the tokens as input to the standard Transformer. The model operates identically to Transformers used in language and vision; each node or edge is treated as a token, identical to the words in a sentence or patches of an image . Perhaps surprisingly, we show that this simple approach yields a powerful graph learner both in theory and practice.
As a key theoretical result, we prove that with appropriate token-wise embeddings, self-attention over the node and edge tokens can approximate any permutation equivariant linear operator on a graph . Remarkably, we show that a very simple choice of embedding composed of node identifiers and type identifiers is sufficient for accurate approximation. This provides a solid theoretical guarantee that, with the embeddings and enough attention heads, a Transformer is at least as expressive as a second-order invariant graph network (2-IGN) , which is already more expressive than all message-passing GNNs . This also immediately grants the model with the expressive power at least as good as the 2-dimensional Weisfeiler-Lehman (WL) graph isomorphism test , which is often sufficient for real-world graph data . We further extend our theoretical result to hypergraphs with order- hyperedges, showing that a Transformer with order- generalized token embeddings is at least as expressive as -IGN and, consequently -WL test.
We test our model, named Tokenized Graph Transformer (TokenGT), mainly on the PCQM4Mv2 large-scale quantum chemical property prediction dataset containing 3.7M molecular graphs . Even though TokenGT involves minimal graph-specific architectural modifications, it performs significantly better than all GNN baselines, showing that the advantages of Transformer architecture combined with large-scale training surpass the benefit of hard inductive bias of GNNs. Furthermore, TokenGT achieves competitive performance compared to Transformer variants with strong graph-specific modifications . Finally, we demonstrate that TokenGT can naturally utilize efficient approximations in Transformers in contrast to these variants, using kernel attention that enables linear computation cost without much degradation in performance.
Tokenized Graph Transformer (TokenGT)
In this section, we present the Tokenized Graph Transformer (TokenGT), a pure Transformer architecture for graphs with token-wise embeddings composed of node identifiers and type identifiers (Figure 1). Our goal in this section is to provide a practical overview – for theoretical analysis of the architecture, we guide the readers to Section 3.
The first component of token-wise embedding is the orthonormal node identifier that we use to represent the connectivity structure given in the input graph.
For each node , we augment the token as .
For each edge , we augment the token as .
Intuitively, a Transformer operating on the augmented tokens can fully recognize the connectivity structure of the graph since comparing the node identifiers between a pair of tokens reveals their incidence information. For instance, we can tell if an edge is connected with a node through dot-product (attention) since if and only if and 0 otherwise. This allows the Transformer to identify and exploit the connectivity structure of a graph, for instance by putting more weights on incident pairs when the local operation is important.
Notably, as the node identifiers are only required to be orthonormal, we have a large degree of freedom in implementation choices. We outline two practical methods below as examples. Their implementation details can be found in Appendix A.3.1.
Among the two methods, node identifiers generated as ORFs do not encode any information about the graph structure as they are entirely random. This means the Transformer that operates on the ORF-based node identifiers needs to compile and recognize graph structure only from the incidence information provided by the node identifiers. Although this is challenging, perhaps surprisingly, we empirically show in Section 5 that Transformers are strong enough to learn meaningful structural representations out of ORF-based node identifiers and outperform GNNs on large-scale task.
In contrast to ORFs, Laplacian eigenvectors provide a kind of graph positional embeddings (graph PEs) that describes the distance between nodes on a graph. Due to the positional information, it yields better performance compared to ORFs in our experiments in Section 5. One interesting aspect of Laplacian eigenvectors is that they can be viewed as a generalization of sinusoidal positional embeddings of NLP Transformers to graphs, as the eigenvectors of 1D chain graphs are sine and cosine functions . Thus, by choosing Laplacian eigenvectors as node identifiers, our approach can be interpreted as a direct extension of the NLP Transformer for inputs involving relational structures.
For each node , we augment the token as .
For each edge , we augment the token as .
These embeddings provide information on whether a given token is a node or an edge, which is critical, e.g., when an attention head tries to attend specifically to node tokens and ignore edge tokens.
Similar to Transformers in language and vision , Tokenized Graph Transformer treats input nodes and edges as independent tokens and applies self-attention to them. This approach leads to much less inductive bias than current GNNs, where the sparse graph structure, or more fundamentally, permutation symmetry of graphs is deliberately baked into each layer . For TokenGT, such information is provided entirely as a part of input using token-wise embeddings, and the model has to learn how to interpret and utilize the information from data. Although such weak inductive bias might raise questions on the expressiveness of the model, our theoretical analysis in Section 3 shows that TokenGT is a powerful graph learner thanks to the token-wise embeddings and expressive power of self-attention. For example, we show that TokenGT is more expressive than all message-passing GNNs under the framework of Gilmer et al. (2017) .
Theoretical Analysis
We now present our theory. Our key result is that TokenGT, a standard Transformer with node and type identifiers presented in Section 2, is provably at least as expressive as the second-order Invariant Graph Network (2-IGN ), which is built upon all possible permutation equivariant linear layers on a graph. This provides solid theoretical guarantees for TokenGT, such as being at least as powerful as the 2-WL graph isomorphism test and more expressive than all message-passing GNNs. Our theory is based on a general framework on hypergraphs represented as higher-order tensors, which leads to the formulation of order- TokenGT that is at least as expressive as order- IGN (-IGN ).
We mainly develop our theoretical analysis upon Invariant Graph Networks (IGNs) , a family of expressive graph networks derived from the permutation symmetry of tensor representation of graphs. Here we provide a summary. In general, we define:
A body of previous work have shown appealing theoretical properties of -IGN, including universal approximation and alignment to -Weisfeiler-Lehman (-WL) graph isomorphism test . In particular, it is known that -IGNs are theoretically at least as powerful as the -WL test . It is also known that 2-IGNs are already more expressive than all message-passing GNNs under the framework of Gilmer et al. (2017) .
The core building block of IGN is invariant and equivariant linear layers with maximal expressiveness while respecting node permutation symmetry. The layers are defined as follows:
We provide the definition of the equivalence classes and basis tensors in Appendix A.1.1. For now, it is sufficient to know that the basis tensors are binary tensors that form the orthogonal basis of the full space of linear equivariant layers. In general, in Eq. (2) it is known that there exists number of basis tensors for the weight and number of basis tensors for the bias.
2 Can Self-Attention Approximate Equivariant Basis?
Now, we present an intuition that connects Transformer (Section 2) and equivariant linear layer (Definition 2). For that, we write out the multihead self-attention layer as follows:
Now consider approximating basis tensor with an attention matrix . The approximation is accurate when -th query always only attends to -th key and ignores the rest. To achieve the attention structure consistently, i.e., agnostic to input , we need to provide auxiliary input that self-attention can "latch onto" to faithfully approximate . Without this, attention must entirely rely on the inputs , which is unreliable and can lead to approximation failure, e.g., when has repeated rows.
Thus, self-attention can utilize the auxiliary information to achieve an input-agnostic approximation of to . Notably, we can achieve a similar approximation for using the same by flipping the sign of keys, which gives due to orthonormality. By sending , now attention from the -th query to the -th key is suppressed, and we obtain the following:
Note that this approximation is accurate only up to row normalization as rows of always sum to one due to softmax, while is binary. In our proofs of the theoretical results, we perform appropriate denormalization with MLP after MSA to achieve an accurate approximation.
Overall, we see that simple auxiliary input suffices for two attention heads to approximate the equivariant basis of accurately. We now question the following. Given appropriate auxiliary information as input, can a Transformer layer with attention heads accurately approximate by having each head approximate each equivariant basis ? What would be the sufficient auxiliary input? We answer the question by showing that, with (order- generalized) node and type identifiers presented in Section 2, Transformer layers can accurately approximate equivariant layers via input-agnostic head-wise approximation of each equivariant basis.
3 Pure Transformers are Powerful Graph Learners
We now present our main theoretical results that extend the discussions in Section 3.2 to any order . Note that corresponds to TokenGT for graphs presented in Section 2. With , we naturally extend TokenGT to hypergraphs. All proofs can be found in Appendix A.1.
Let us exemplify. For (sets), each -th entry is augmented as , consistent with our discussion in Section 3.2. For (graphs), each -th entry is augmented as and each -th entry () is augmented as . This is consistent with TokenGT in Section 2, which augments nodes with and edges with .
Consequently, with the node and type identifiers, a collection of attention heads can approximate the collection of all basis tensors of order- equivariant layer. This leads to the following:
While the approximation in Lemma 1 is only accurate up to normalization over inputs (keys) due to softmax normalization, for the approximation in Theorem 1 we perform appropriate denormalization using MLP after multihead self-attention and can obtain an accurate approximation.
By extending the result to multiple layers, we arrive at the following:
This directly leads to the following corollary:
A Transformer on node and type identifiers in Theorem 2 is at least as expressive as -IGN composed of order- equivariant linear layers.
Corollary 1 allows us to draw previous theoretical results on the expressiveness of -IGN and use them to lower-bound the provable expressiveness of a standard Transformer:
A Transformer on node and type identifiers in Theorem 2 is at least as powerful as -WL graph isomorphism test and is more expressive than all message-passing GNNs within the framework of Gilmer et al. (2017) .
Related Work
We outline relevant work including equivariant neural networks, theory on expressive power of Transformers and their connection to modeling equivariance, and Transformers for graphs.
A machine learning task is often invariant or equivariant to specific symmetry of input data, e.g., image classification is invariant to the translation of an input image. A large body of literature advocated baking the invariance or equivariance into a neural network as a type of inductive bias (e.g., translation equivariance of image convolution), showing that it reduces the number of parameters and improves generalization for a wide range of learning tasks involving various geometric structures . Ravanbakhsh et al. (2017) showed that any equivariant layer for discrete group actions is equivalent to a specific parameter sharing structure. Zaheer et al. (2017) and Maron et al. (2019) derived the parameter sharing for node permutation-symmetric data (sets and (hyper)graphs), which gives the maximally expressive equivariant linear layers and -IGN in Section 3.1. The work on equivariant neural networks underlie our theory of how a standard Transformer can be a powerful learner for sets and (hyper)graphs.
Recent work involving Transformers often focus on minimizing the domain- and task-specific inductive bias and scaling the model and data so that any useful computation structure can be learned . The success of this approach is, to some degree, attributed to the high expressive power of Transformers that allows learning diverse functions suited for the data at hand . Recent theory has shown that Transformers are expressive enough to even model certain equivariant functions . Andreoli et al. (2019) cast self-attention and convolution into a unified framework using basis tensors similar to ones in Section 3.1. Cordonnier et al. (2020) advanced the idea and showed that Transformers with relative positional encodings can approximate any image convolution layers. Lee et al. (2019) and Kim et al. (2021) showed that Transformers can model equivariant linear layers for sets , which can be viewed as the first-order case of our theory (see Section 3.2). To our knowledge, our work is the first to show that standard Transformers are expressive enough to provably model maximally expressive equivariant layers and -IGN for (hyper)graphs with .
Unlike in language and vision, developing Transformers for graphs is challenging due to (1) the presence of edge connectivity and (2) the absence of canonical node ordering that prevents adopting simple positional encodings . To incorporate the connectivity of edges, early methods restricted self-attention to local neighborhoods (thus reducing to message-passing) or used global self-attention with auxiliary message-passing modules . As message-passing suffers from limited expressive power and oversmoothing , recent works often discard them and use global self-attention on nodes with heuristic modifications to process edges . Ying et al. (2021) proposed to inject edge encoding based on shortest paths through self-attention bias. Kreuzer et al. (2021) proposed to incorporate edges into self-attention matrix via elementwise multiplication. On the contrary, we leave the self-attention unmodified and provide both nodes and edges with certain token-wise embeddings (Section 2) as its input. To incorporate graph structure into nodes, on the other hand, some approaches focus on developing graph positional encoding, e.g., based on Laplacian eigenvectors . While these can be directly incorporated into our work via auxiliary node identifiers for better performance, we leave this as future work. We further note that current graph Transformers that utilize Laplacian positional encoding rely heavily on heuristic edge encoding while ours does not. Another closely related approach is the Higher-order Transformer which generalizes -IGN with masked self-attention. While it is highly complex to implement due to hard-coded head-wise equivariant masks, our method can be implemented effortlessly using any available implementation of standard Transformer. Furthermore, our method is more flexible as the model can choose to use different attention heads to focus on a specific equivariant operator (e.g., local propagation) if needed. We further discuss the difficulty in applying linear attention to graph Transformers in Appendix A.2.
Experiments
We first conduct a synthetic experiment that directly confirms our key claims in Lemma 1 (Section 3). Then, we empirically explore the capability of Tokenized Graph Transformer (TokenGT) (Section 2) using the PCQM4Mv2 large-scale quantum chemistry regression dataset . We further present experiments on transductive node classification datasets involving large graphs in Appendix A.4.3.
As in Theorem 1 and 2 (Section 3), our argument on the expressive power of TokenGT relies on its capability to approximate order- permutation equivariant linear layers (Definition 2). Specifically, Lemma 1 states that such capability depends on the ability of each self-attention head (Eq. (3)) to accurately approximate each equivariant basis (Definition 2) up to normalization.
We verify this claim for (second-order; graphs) in a synthetic setup using Barabási-Albert random graphs. We use a multihead self-attention layer (Eq. (3)) with heads and explicitly supervise head-wise attention scores to approximate each (normalized) equivariant basis tensor by minimizing L2 loss. Having the layer hyperparameters fixed, we provide different combinations of node and type identifiers, and test if multihead self-attention can jointly approximate all 15 equivariant basis on unseen graphs. We experiment with both dense and sparse graph representations; for graphs with nodes and edges, the dense graph considers all pair-wise edges as input as in Section 3, whereas the sparse graph considers only the present edges as in Section 2. Further details can be found in Appendix A.3.2.
We outline the results in Table LABEL:table:equivariant_basis_approximation_std. Consistent with Lemma 1, self-attention achieves accurate approximation of equivariant basis only when both the orthonormal node identifiers and type identifiers are given. Here, Laplacian eigenvectors (Lap, ) often yield slightly better results than orthogonal random features (ORF, ) presumably due to less stochasticity. Interestingly, we see that self-attention transfers the learned (pseudo-)equivariant self-attention structure to unseen graphs near perfectly. Non-orthogonal random embeddings lead to inaccurate approximation (Random, ), highlighting the importance of orthogonality of node identifiers. The approximation is also inaccurate when we sample ORF independently for each token (ORF (first-order), ) instead of using concatenated node identifiers for token . This supports our argument in Section 2 that the incidence information implicitly provided via node identifiers plays a key role in approximation.
In Figure 2, we provide a visualization of self-attention maps learned under various node and type identifier choices. Additional results can be found in Appendix A.4.1.
2 Large-Scale Graph Learning
An exclusive characteristic of TokenGT is its minimal graph-specific inductive bias, which requires it to learn internal computation structure largely from data. As such models are commonly known to work well with large-scale data , we explore the capability of TokenGT on the PCQM4Mv2 quantum chemistry regression dataset , one of the current largest with 3.7M molecular graphs.
For TokenGT, we use both node and type identifiers, and use main Transformer encoder configuration based on Graphormer with 12 layers, 768 hidden dimension, and 32 attention heads. We try both ORF and Laplacian eigenvector as node identifiers, and denote corresponding models as TokenGT (ORF) and TokenGT (Lap) respectively. As an ablation, we also experiment with the same Transformer without node and type identifiers, which we denote as Transformer. Finally, we apply the kernel attention that approximates the attention computation to linear cost (TokenGT (Lap) + Performer). We use AdamW optimizer with and weight decay 0.1, and 60k learning rate warmup steps followed by linear decay over 1M iteration with batch size 1024. For fine-tuning, we use 1k warmup, 0.1M training steps, and cosine learning rate decay. We train the models on 8 RTX 3090 GPUs for 3 days. Further details are in Appendix A.3.3.
We provide the results in Table LABEL:table:pcqm4mv2. A standard Transformer on the node and edge tokens cannot recognize graph structure and shows low performance (0.2340 valid MAE). Yet, the picture changes as soon as we augment the tokens with node and type identifiers. Notably, TokenGT (ORF) achieves 0.0962 MAE, which is already better than all GNN baselines. This is a somewhat surprising result, as both ORF and the Transformer are not aware of graph structures. This implies Transformer is strong enough to learn to interpret and reason over the incidence structure of tokens provided only implicitly by the node and type identifiers. By further switching to Laplacian eigenvectors that encode position on graphs , we observe a performance boost to 0.0910 MAE, competitive to Transformers with sophisticated graph-specific modifications (e.g., shortest path-based spatial encoding ). While such methods inject graph structure into attention matrix via bias term and therefore strictly require cost, TokenGT enables adopting kernelization for pure self-attention , resulting in TokenGT (Lap) + Performer with the best performance among models (0.0935 MAE). Further discussion on the empirical performance of TokenGT can be found in Appendix A.5.
While our theory in Section 3 guarantees that TokenGT can reduce to an equivariant layer by learning fixed equivariant basis at each attention head, in practice, it can freely utilize multihead self-attention to learn less restricted and more useful computation structure from data. To analyze such a structure, we compute the attention distance across heads and network depth by averaging pairwise token distances on a graph weighted by their attention scores (Figure 3). This distance is analogous to the number of hops in message-passing. In both TokenGT (ORF) and TokenGT (Lap), in the lowest layers, some heads attend globally over the graph while others consistently have small receptive fields (acting like a local message-passing operator). In deeper layers, the attention distances increase, and most heads attend globally. Interestingly, this behavior is highly consistent with Vision Transformers on image patches , suggesting that hybrid architectures based on convolution to aid ViT might also work well for graphs. While TokenGT (ORF) shows relatively consistent attention distance over heads, TokenGT (Lap) shows higher variance, implying that it learns more diverse attention patterns. Judging from the higher performance of TokenGT (Lap), this suggests that the graph structure information of the Laplacian eigenvector facilitates learning useful and diverse attention structures, which calls for future exploration of better node identifiers based on graph PEs .
Conclusion
We showed that Transformers directly applied to graphs can work well in both theory and practice. In the theoretical aspect, we proved that with appropriate token-wise embeddings, a Transformer on node and edge tokens is at least as expressive as -IGN and -WL test, making it more expressive than all message-passing GNNs. For such token-wise embeddings, we showed that a combination of simple orthonormal node identifiers and trainable type identifiers suffices, which we also verified with a synthetic experiment. In an experiment with PCQM4Mv2 large-scale dataset, we show that Tokenized Graph Transformer (TokenGT) performs significantly better than all GNNs and is competitive with Transformer variants with strong graph-specific architectural components .
While the results suggest a promising research direction, there are challenges to be addressed in future work. First, treating each node and edge as tokens requires asymptotic cost due to the quadratic nature of self-attention. While we address this to some degree with kernelization and achieve cost, other types of efficient Transformers (e.g., sparse) that can deliver better performance are left to be tested. Another issue is slightly lower performance compared to the state-of-the-art. Adopting Transformer engineering techniques from vision and language domains, such as data scaling , deepening , hybrid architectures , and self-supervision , are promising. In the societal aspect, to prevent the potential risky behavior in, e.g., decision making from graph-structured inputs, interpretability research regarding self-attention on graphs is desired.
We finish with interesting research directions that stem from our work. As our approach advocates viewing a graph as tokens , it opens up new paradigms of graph learning, including autoregressive decoding, in-context learning, prompting, and multimodal learning. Another interesting direction is to extend our theory and use self-attention to approximate equivariant basis for general discrete group actions, which might be a viable approach for learning equivariance from data.
This work was supported in part by Institute of Information & communications Technology Planning & Evaluation (IITP) (No. 2022-0-00926, 2022-0-00959, 2021-0-02068, and 2019-0-00075) and the National Research Foundation of Korea (NRF) (No. 2021R1C1C1012540) grants funded by the Korea government (MSIT).
References
Appendix A Appendix
We now provide the complete definition of invariant graph networks (IGNs) and maximally expressive equivariant linear layers summarized in Section 3.1. We first recall Definition 1 and 2:
We now define equivalence classes and basis tensors mentioned briefly in Definition 2. The equivalence classes are defined upon a specific equivalence relation on the index space of higher-order tensors as follows:
An order- equivalence class is an equivalence class of under the equivalence relation , where the equivalence relation on multi-index space relates if and only if for some node permutation .
We note that a multi-index has the same permutation-invariant equality pattern to any that satisfies , i.e., for all . Consequently, each equivalence class in Definition 3 is a distinct set of all order- multi-indices having a specific equality pattern.
Now, for each equivalence class, we define the corresponding basis tensor as follows:
For a given , it is known that there exist order- equivalence classes regardless of . This gives order- basis tensors accordingly. Thus, an equivariant linear layer in Definition 2 has weights and biases.
A.1.2 Proof of Lemma 1 (Section 3.3)
To prove Lemma 1, we need to show that each basis tensor (Eq. (14)) in weights of equivariant linear layers (Eq. (2)) can be approximated by the self-attention coefficient (Eq. (7)) to arbitrary precision up to normalization if its input is augmented by node and type identifiers (Section 3.3).
From Definition 4, each entry of basis tensor encodes whether or not. Here, our key idea is to break down the inclusion test into equivalent but simpler Boolean tests that can be implemented in self-attention (Eq. (8)) as dot product of -th query and -th key followed by softmax.
To achieve this, we show some supplementary Lemmas. We start with Lemma 2, which comes from Lemma 1 of Kim et al. (2021) (we repeat their proof here for completeness).
For any order- equivalence class , the set of all such that for some forms an order- equivalence class. Likewise, the set of all such that for some forms an order- equivalence class.
We only prove for as proof for is analogous. For some , let us denote the equivalence class of as (i.e., ). It is sufficient that we prove .
() For all , as , there exists some such that by definition. As acts on multi-indices entry-wise, we have . As holds by definition, we have , and thus . Therefore, for all , by setting we can always obtain .
() For all , as , there exists some such that . This gives and , leading to and therefore . ∎
Lemma 2 states that the equivalence classes of and of are identical for all . Based on this, we appropriately break down the test into a combination of several simpler tests, in particular including and :
For a given order- equivalence class , let and be equivalence classes of some respectively that satisfies . Then, for any and , holds if and only if the following conditions both hold:
and
for all , , and
() If , from Lemma 2 it follows that and . Also, as all including have the same equality pattern, it follows that for all , , and , if then and if then .
() We show that the conditions specify that the equivalence class of is .
For this, it is convenient to represent an order- equivalence class as an equivalent undirected graph defined on vertex set where the vertices and are connected, i.e., if and only if the equivalence class specifies . Then, for some multi-index , the inclusion holds if and only if the equivalence class of is represented as .
Given this, let us represent the equivalence classes , , and as graphs , , and respectively:
From the precondition that and are equivalence classes of that satisfies , we can see that and . That is, if we consider and as a graph cut of and write the cut-set (edges between and ) as , we obtain a partition of the edge set .
Let us assume the first condition that and , with the equivalence classes represented as and , respectively. Now, let us consider the equivalence class of represented by (unknown) graph . Considering and as a graph cut of , we can see that is partitioned as where is the cut-set (edges between and ).
Let us also assume the second condition for all , , and . This directly implies that , meaning that . As a result, we see that and are identical graphs, and therefore the equivalence class of is and holds.
In Figure 4, we provide an exemplary illustration of testing following the above discussion. ∎
With Lemma 3, we have a decomposition of into independent conditions on and combined with pairwise conditions between and . In the following Definition 5 and Property 1, we encode these tests into a single scoring function that can be later implemented by self-attention.
A scoring function is a map that, given an order- equivalence class and , takes multi-indices and gives the following:
An important property of the scoring function is that it gives the maximum possible value if and only if the input satisfies , as shown in the below Property 1.
For given order- equivalence class and positive real number , for any and , holds if and only if the scoring function (Eq. (19)) outputs the maximum possible value.
As shown in Lemma 3, holds if and only if the following two conditions are met.
and
for all , , and
Thus, the scoring function gives the maximum possible output if and only if . ∎
We now use self-attention on to perform an accurate approximation of the equivariant basis. Specifically, we use each self-attention matrix (Eq. (7)) to approximate each basis tensor of (Eq. (2)) to arbitrary precision up to normalization.
where is a positive real, is an identity matrix, and is the sign function defined in Eq. (23) (Definition 5). In Figure 5 we provide an illustration of the query and key weights .
With the parameters, -th query and -th key entries are computed as follows:
Then, scaled pairwise dot product of query and key is given as follows:
We now let the type identifiers be radially equispaced unit vectors on any two-dimensional subspace (Figure 6). This guarantees that any pair of type identifiers with have dot product . By setting , this can be equivalently written as . We additionally note that if and only if because .
Combining the above, Eq. (52), and Eq. (19), we have the following:
where and is the scoring function in Eq. (19) (Definition 5).
Thus, as shown in Eq. (55), the attention coefficient can arbitrarily accurately approximate the normalized basis tensor for given equivalence class . ∎
A.1.3 Proof of Theorem 1 (Section 3.3)
We continue from the proof of Lemma 1 and assume that each attention matrix in Eq. (7) head-wise approximates each normalized basis tensor respectively, i.e., . we handle the case later separately as mentioned in footnote 1.
Then, output projection applied after value projection of each -th input entry gives the following:
Based on the results, we compute the MSA with skip connection (Eq. (9)):
where , and are biases of the given equivariant linear layer with corresponding basis tensors (Eq. (2)).
Based on the results, we compute the feedforward MLP with skip connection (Eq. (10)), which is the output of Transformer layer :
In conclusion, a Transformer layer with self-attention heads that operates on augmented can approximate any given to arbitrary precision. ∎
A.1.4 Proof of Theorem 2 (Section 3.3)
We continue from the proof of Theorem 1, and assume that each Transformer layer can approximate a given by only updating the first channels.
Then, based on Theorem 1 we assume the following for each :
where . While Theorem 1 gives in the first channels, we add elementwise activation by absorbing it into the elementwise MLP in Eq. (66). Then, leveraging the property that each Transformer layer only updates the first channels, we stack Transformer layers , …, and obtain the following:
For the last layer , we follow the procedure in the proof of Theorem 1 to approximate , but slightly tweak Eq. (66) so that elementwise MLP copies each output entry in appropriate reserved channels. Specifically, we let the elementwise MLP approximate following :
where and we abbreviate with defined as same as in Eq. (66). Recall that if and only if . Therefore, with Eq. (78), we are simply duplicating each output entry to spare channel indices reserved for the equivalence class of ( that ).
With the choice of , the layer output (Eq. (10)) is computed as:
Then, by applying (Eq. (81)) on top of (Eq. (74)), we obtain the following:
where we abbreviate .
The remaining step is to utilize to approximate that tops . By sum-pooling over all indices , we obtain the following:
where the last equality comes from Definition 1.
Taken together, we arrive at the conclusion that can approximate to arbitrary precision. ∎
A.2 Additional Discussion on Linear Attention for Graph Transformers (Section 4)
Unfortunately, this modification immediately precludes the adaptation of many efficient attention techniques developed for pure self-attention. As representative examples, we take Performer , Linear Transformer , Efficient Transformer , and Random Feature Attention . The methods are based on kernelization of the operator as the following:
While above discussion regards kernelization, a wide range of other efficient Transformers, including Set Transformer , LUNA , Linformer , Nyströmformer , Perceiver , and Perceiver-IO are not applicable to Graphormer due to similar reasons.
A.3 Experimental Details (Section 5)
We provide detailed information on the datasets and models used in our experiments in Section 5. Dataset statistics can be found in Table 3.
For type identifiers , we set equal to the hidden dimension of the main encoder and initialize and train them jointly with the model.
For orthonormal node identifiers , we use normalized orthogonal random features (ORFs) or Laplacian eigenvectors obtained as follows:
As the Laplacian eigenvectors are defined up to the factor after normalized to unit length , we randomly flip their signs during training. For PCQM4Mv2 (Section 5.2), we apply random dropout on eigenvectors during training, similar to 2D channel dropout in ConvNets . In our experiments with PCQM4Mv2, we find that both sign flip and eigenvector dropout work as effective regularizers and improves performance on validation data.
A.3.2 Second-Order Equivariant Basis Approximation (Section 5.1)
For the equivariant basis approximation experiment, we use a synthetic dataset containing Barabási-Albert (BA) random graphs . With denoting discrete uniform distribution, each graph is generated by first sampling the number of nodes and the number for preferential attachment , then iteratively adding nodes by linking each new node to random previous nodes. We do not utilize node or edge attributes and only use edge connectivity. We generate 1152 graphs for training and 128 for testing. Further dataset statistics is provided in Table 3(a).
Each model tested in Table LABEL:table:equivariant_basis_approximation_std is a single multihead self-attention layer (Eq. (9)) with hidden dimension , heads , and head dimension . As for the node identifier dimension, we use for ORF and for Laplacian eigenvectors.
We train and evaluate all models with L2 loss between attention matrix and normalized basis tensor (involving [null] token) averaged over heads . We train all models with AdamW optimizer on 4 RTX 3090 GPUs each with 24GB. For sparse inputs we use batch size 512, and for dense inputs we use batch size 256 due to increased memory cost. We train all models for 3k steps (which takes about 1.5 hours) and apply linear learning rate warmup for 1k steps up to 1e-4 followed by linear decay to 0. For all models, we use dropout rate of 0.1 on the input to prevent overfitting.
A.3.3 Large-Scale Graph Learning (Section 5.2)
For large-scale learning, we use the PCQM4Mv2 quantum chemistry regression dataset from the OGB-LSC benchmark that contains 3.7M molecular graphs. Along with graph structure, we utilize both node and edge features e.g., atom and bond types following our standard procedure in Section 2. Dataset statistics is provided in Table 3(b).
All our models in Table LABEL:table:pcqm4mv2 (under Pure Transformers) have the same encoder configuration following Graphormer , with 12 layers, hidden dimension , heads , and head dimension . We adopt PreLN that places layer normalization before MSA layer (Eq. (9)), MLP layer (Eq. (10)), and the final output projection after the last encoder layer. We implement MLP (Eq. (10)) as a stack of two linear layers with GeLU nonlinearity in between. As for node identifier dimension, we use for ORF and for Laplacian eigenvectors.
As an additional GNN baseline, we run Graph Attention Network (GATv2) under several configurations. For GAT and GAT-VN in Table LABEL:table:pcqm4mv2, we use 5-layer GATv2 with hidden dimension 600 and a single attention head, having 6.7M parameters in total. For GAT-VN (large), we use a 10-layer GATv2 with hidden dimension 1200 and a single attention head, having 55.2M parameters in total. For GAT-VN and GAT-VN (large), we use virtual node that helps modeling global interaction .
We mainly report and compare the Mean Absolute Error (MAE) on the validation data, and report MAE on the hidden test data if possible. We train all models with L1 loss using AdamW optimizer with gradient clipping at global norm 5.0. We use batch size 1024 and train the models on 8 RTX 3090 GPUs with 24GB for 3 days. We train our models for 1M iterations, and apply linear lr warmup for 60k iterations up to 2e-4 followed by linear decay to 0. For our models in Table LABEL:table:pcqm4mv2 except TokenGT (Lap) + Performer, we use the following regularizers:
Stochastic depth with linearly increasing layer drop rate, reaching 0.1 at last layer
Eigenvector dropout rate 0.2 for TokenGT (Lap) (see Appendix A.3.1)
For TokenGT (Lap) + Performer in Table LABEL:table:pcqm4mv2, we load a trained model checkpoint of TokenGT (Lap), change its self-attention to FAVOR+ kernelized attention of Performer that can provably accurately approximate softmax attention, and fine-tune it with AdamW optimizer for 0.1M training steps with 1k warmup iterations and cosine learning rate decay. With batch size 1024 on 8 RTX 3090 GPUs, fine-tuning takes hours. We do not use stochastic depth and eigenvector dropout for fine-tuning. For GAT baselines in Table LABEL:table:pcqm4mv2, we use batch size 256 and train the models for 100 epochs with initial learning rate 0.001 decayed with a factor of 0.25 every 30 epochs.
A.4 Additional Experimental Results (Section 5)
We report additional experimental results and discussions that could not be included in the main text due to space restriction.
In addition to the Figure 2 in the main text that shows learned self-attention maps for dense input, in Figure 7, we provide an extended visualization of self-attention maps for both dense and sparse inputs. Consistent to Lemma 1 and Table LABEL:table:equivariant_basis_approximation_std, self-attention achieves accurate approximation of equivariant basis only when both the orthonormal node identifiers (ORF or Lap) and type identifiers are given.
A.4.2 Large-Scale Graph Learning (Section 5.2)
In addition to the Figure 3 in the main text that shows attention distance measured for the PCQM4Mv2 validation data, in Figure 8, we provide an extended figure of attention distance measured for the entire training set that contains 3M graphs. Overall we find similar trends as analyzed in Section 5.2.
A.4.3 Transductive Node Classification on Large Graphs (Section 5)
While our main experiment in Section 5.2 focuses on graph-level predictions, TokenGT can in principle be applied to a more broad class of node-level or edge-level graph understanding tasks by putting prediction head on appropriate output tokens. To demonstrate this, we conduct additional experiments on a variety of transductive node classification datasets. In contrast to PCQM4Mv2, they involve large graphs with up to tens of thousands of nodes, posing a challenge to complexity methods such as graph Transformers that rely on dense attention bias.
We use transductive node classification datasets, where each data is represented as a node in a large-scale graph, including co-authorship (CS, Physics) , co-purchase (Photo, Computers) , and Wikipedia page networks (Chameleon, Crocodile) . We randomly split the dataset into train, validation, and test sets by randomly reserving 30 random nodes per class for validation and test respectively, and use the rest of the nodes for training. Dataset statistics is provided in Table 4.
We utilize simple variants of TokenGT with Performer kernel attention of complexity. Due to the large number of nodes , an immediate challenge for TokenGT is dealing with the orthonormality assumption on the node identifiers (Lemma 1) as the maximal number of orthonormal node identifiers is bounded by dimension . In this case, it is reasonable to introduce near-orthonormal vectors as node identifiers, as it is theoretically guaranteed that we can draw an exponential number of -dimensional near-orthonormal vectors . For TokenGT (Near-ORF), we use -dimensional random node identifiers where each entry is sampled from with coin toss . For TokenGT (Lap), we use a subset of the Laplacian eigenvectors as node identifiers, specifically eigenvectors with lowest eigenvalues and eigenvectors with highest eigenvalues, and choose among - based on validation performance.
While Near-ORF and Lap can theoretically serve as an efficient low-rank approximation for orthonormal node identifiers, their approximation can affect the quality of modeled equivariant basis (Section 3). In particular, equivariant basis () represented as sparse basis tensor (; Definition 4) are expected to be affected more, as they require most entries to be zero. To remedy this, we take a simple approach of residually adding one of such sparse equivariant operators explicitly after each Transformer layer. We denote this variant as TokenGT (Lap) + Performer + SEB, where SEB abbreviates sparse equivariant basis. This fix is minimal, easy to implement, and highly efficient as it only requires a single torch.coalesce() call, and also empirically effective.
All our models in Table LABEL:table:transductive_node_classification utilize a linear prediction head on the node tokens obtained at the final Transformer layer to perform node-level classification. We perform an exploratory hyperparameter search over the number of layers from -, heads from -, hidden dimension from -, and dropout rate from , based on validation performance.
We employ strong message-passing GNN and graph Transformer baselines, including GCN , GAT , GIN which has 2-WL expressiveness similar to ours, and Graphormer based on fully-connected node self-attention. For message-passing GNNs, we use a 4-layer architecture and search hidden dimension from based on validation performance. For Graphormer, we perform an exploratory search on the number of layers from -, heads from -, and hidden dimension from - based on validation performance. We apply 0.5 dropout for all baselines.
We report and compare classification accuracy on the test nodes at best validation accuracy aggregated over 7 randomized runs. We train all models with node-level categorical cross-entropy loss using Adam optimizer on a single RTX 3090 GPU with 24GB. We train all models with a learning rate of 1e-3 for 300 epochs.
The results are in Table LABEL:table:transductive_node_classification. Graphormer suffers out-of-memory in the Physics dataset mainly due to the spatial encoding that requires memory. By constraining the model capacity appropriately, we were able to run Graphormer on other datasets. However, we observe a low performance, presumably due to the memory cost that prevents depth and head scaling. As the spatial encoding is incorporated into the model via attention bias, the model strictly requires memory and cannot be easily made more efficient. On the other hand, TokenGT variants are able to utilize Performer attention with cost, which allows using larger models to achieve the best performance in all but one dataset (Computers, where the performance is on par with the best model).
A.5 Additional Discussion on Performance on PCQM4Mv2 (Section 5.2)
As in the Table LABEL:table:pcqm4mv2 in the main text, TokenGT currently shows a slightly lower performance compared to the Graphormer and its successors in the PCQM4Mv2 benchmark. We conjecture this is partly because we intentionally keep its components simple to faithfully adhere to the equivariance theory. We discuss some engineering approaches that may enhance the performance of TokenGT at the cost of differentiating from the theory. We consider engineering TokenGT to match or outperform sophisticated graph Transformers as a promising and important next research direction.
Our best performing TokenGT (Lap) currently uses Laplacian eigenvectors as the node identifiers, which has been criticized for issues such as loss of structural information and sign ambiguity . Thus, one could try to relax the theoretical requirement for orthonormality of node identifiers and incorporate more powerful node positional encodings as node identifiers, which could potentially yield better performance in practice.
TokenGT currently treats an undirected input edge as if both directions and are present, leading to a pair of edge tokens and . Similarly, an undirected order- input hyperedge of an higher-order hypergraph is parsed to all possible orderings of node identifiers. While this is a common characteristic of tensor-based permutation equivariant neural networks , they can lead to memory overhead and redundancy since multiple tokens represent an identical undirected edge. To avoid this, one can use a single token for each undirected (hyper)edge and pool the node identifiers as . Combined with powerful node identifiers, this approach could potentially enhance the model performance.