KERPLE: Kernelized Relative Positional Embedding for Length Extrapolation

Ta-Chung Chi, Ting-Han Fan, Peter J. Ramadge, Alexander I. Rudnicky

Introduction

Transformer-based models have excelled in various natural language processing tasks such as chatbot (Roller et al., 2021), code completion (Chen et al., 2021a), and paper abstract summarization (Zhang et al., 2020). These sequence modeling tasks often require the model to operate well on significantly longer text sequences than the fixed maximum length LL used at training time. Training (or retraining) the model using a substantially larger value of LL is often infeasible since the transformer training cost is O(L2)O(L^{2}). Hence, one desires a transformer that continues to perform well on longer sequences than those used during training; i.e., perform length extrapolation at inference time. Most transformer designs do not have this property (Press et al., 2022). While recent work on absolute positional embeddings demonstrated the extrapolation ability (Kiyono et al., 2021; Likhomanenko et al., 2021), it is believed that relative positional embeddings are more robust to input length change (Likhomanenko et al., 2021), for example, ALiBi (Press et al., 2022) and T5 (Raffel et al., 2020). Hence, we are motivated to study the inner workings of relative positional embeddings.

Relative positional embeddings (RPE) encode the idea of shift-invariance: for any shift pp, (m+p)−(n+p)=m−n(m+p)-(n+p)=m-n. It is often added directly to the self-attention matrix before Softmax normalization (Chen et al., 2021b). Inspired by shift-invariance and the ability of a kernel to define a similarity function, there have been studies on shift-invariant kernels for RPE (Wennberg and Henter, 2021) with a focus on Gaussian kernel. However, in our preliminary experiments, the Gaussian kernel demonstrates limited length extrapolation ability (see Appendix A.3). Hence, a distinct class of shift-invariant kernels is needed to achieve adequate length extrapolation.

To this end, we note a set of well-established conditionally positive definite (CPD) kernels suitable for modeling distance metrics (Schölkopf, 2000). However, CPD kernels do not conform to an inner product. We can remedy this issue by transforming a CPD kernel into a PD kernel by adding a sufficiently large constant. This constant offset is subsequently absorbed implicitly in the Softmax normalization (see the discussion below Eq. (2)). For example, ALiBi implicitly admits a PD kernel of the form c−∣m−n∣c-|m-n| (see the end of section 4), which is reduced to a CPD kernel −∣m−n∣-|m-n|. The CPD kernel and Softmax normalization combination opens the door to a sea of possible CPD kernels. We investigate structures from this class that exhibit a strong length extrapolation ability, like ALiBi.

Our main result is a framework for KErnelize Relative Positional Embedding for Length Extrapolation (KERPLE). The framework elucidates key principles that encourage the length extrapolation property. We show that ALiBi is a particular instance within our framework. Our subsequent experiments suggest that the proposed method yields better length extrapolation on large datasets such as OpenWebText2, GitHub, and ArXiv.

Background and Related Work

Since the operation is position-agnostic, it is believed that positional information helps model token interactions (Vaswani et al., 2017), which we survey in the next subsection.

2 Positional Embedding

Absolute positional embeddings assign a positional vector pm\bm{p}_{m} to each position mm and adds pm\bm{p}_{m} to the embedding vector em\bm{e}_{m}. The very first version of which is the predefined sinusoidal function (Vaswani et al., 2017). Followed by the success of BERT (Devlin et al., 2019), learnable absolute positional embeddings have been applied to the task of masked language modeling (Devlin et al., 2019; Liu et al., 2019; Clark et al., 2020; Lan et al., 2020), Autoregressive-decoding (Radford et al., 2018, 2019), and sequence-to-sequence (Gehring et al., 2017; Lewis et al., 2019) settings. Recent work studied ways to extrapolate sinusoidal positional embeddings to longer sequences by randomly shifting absolute positions during training (Kiyono et al., 2021) or augmenting with continuous signals (Likhomanenko et al., 2021).

Relative.

As opposed to the modeling of absolute position mm, relative positional embeddings (RPE) that model the positional difference m−nm-n has become popular in the literature (Shaw et al., 2018; Huang et al., 2019; Dai et al., 2019; Yang et al., 2019; Huang et al., 2020; He et al., 2021; Ke et al., 2021; Chen et al., 2021b). In particular, the T5 model that considers bucketed relative distances and log-binning has been shown to perform well on various transformer architectures (Raffel et al., 2020). Rotary positional embedding (Su et al., 2021) encodes the position with rotations: f(qm,m)=Rmqmf(\bm{q}_{m},m)=R_{m}\bm{q}_{m} where RmR_{m} is a rotation matrix with angles proportional to mm. With the rotation’s property, the query-key product exhibits a positional difference: f(qm,m)⊤f(kn,n)=qm⊤Rn−mknf(\bm{q}_{m},m)^{\top}f(\bm{k}_{n},n)=\bm{q}_{m}^{\top}R_{n-m}\bm{k}_{n}.

We note that the overview above focuses on the NLP domain. Recent work has applied positional embeddings to other domains such as vision (Wu et al., 2021a) and speech (Likhomanenko et al., 2021). A survey can be found in (Dufter et al., 2022).

3 Kernel and its Application in Transformer

The kernel trick is a classic approach to generalize the inner product to high dimensional spaces (Mika et al., 1998; Schölkopf, 2000; Leslie et al., 2001; Dhillon et al., 2004; Takeda et al., 2007). In the context of transformers, there has been interest in applying kernels to the self-attention structure to enhance the performance. Examples of such work include kernel for positional embeddings (Tsai et al., 2019; Wu et al., 2021b; Wennberg and Henter, 2021; Luo et al., 2021). Another line of research leverages the kernel’s feature map (Rahimi and Recht, 2007) to linearize the self-attention module and reduce the computational cost (Katharopoulos et al., 2020; Chen et al., 2021c; Xiong et al., 2021; Peng et al., 2021; Choromanski et al., 2021; Qin et al., 2022).

Theoretical Foundations of CPD Kernels

In this work, we use shift-invariant conditionally positive definite (CPD) kernels to model the effect of relative positional differences. We propose this formulation because the notion of relative is modeled by a shift-invariant function: a bivariate function kk over two positions (m,n)(m,n) such that k(m,n)=f(m−n)k(m,n)=f(m-n) for some univariate ff. The notion of positional difference m−nm-n is generalized by the CPD kernel. We review the definitions of PD and CPD kernels below.

Fact 1 suggests that CPD kernels generalize distance metrics to high dimensional spaces. Since we are interested in positional differences, we examine modeling the distance between positions using CPD kernels.

2 Constructing PD Kernels From CPD Kernels via Constant Shifts

In this subsection, we review a few properties of CPD kernels and use these to generate a variety of CPD kernels. Then, we present a lemma that transforms CPD kernels into PD kernels via constant shifts. This enables the production of a family of PD kernels from CPD kernels. Finally, we present our critical observation that the exact value of the constant shift is not needed, thanks to a nice property of Softmax normalization.

Below are some important facts about CPD kernels.

The negative squared distance −∥x−x′∥2-\|x-x^{\prime}\|^{2} is CPD.

The three Facts above jointly yield a rich family of CPD kernels as shown below.

We note that it is possible to keep iterating between Fact 2 and 3 and generate more complicated examples, e.g., −a∥x−x′∥p−b⋅log⁡(1+a∥x−x′∥p)-a\|x-x^{\prime}\|^{p}-b\cdot\log(1+a\|x-x^{\prime}\|^{p}) or −b⋅log⁡(1+a∥x−x′∥p)c-b\cdot\log(1+a\|x-x^{\prime}\|^{p})^{c} for 0<c<10<c<1. However, since relative positional embeddings are of our interest, we only consider simple CPD kernels. Those with complicated forms are deferred to future work.

Now that Corollary 1 has presented a few class of CPD kernels, we prove a lemma (in Appendix A.1) that constructs PD kernels from CPD kernels through shifting. Later in Eq. (2), we will see that the shifting construction is combined neatly with the Softmax normalization of self-attention.

While the CPD shift lemma is convenient, one can prove c−∥x−x′∥pc-\|x-x^{\prime}\|^{p} is PD for large enough cc using a kernel representation theorem in Schoenberg (1938). See Appendix A.2 for details.

Kernelized Relative Positional Embedding

Practical Choice.

kcomp([qm,m],[kn,n])=qm⊤kn+c−r1∣m−n∣r2k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}+c-r_{1}|m-n|^{r_{2}} with r1>0r_{1}>0 and 0<r2≤20<r_{2}\leq 2.

kcomp([qm,m],[kn,n])=qm⊤kn+c−r1⋅log⁡(1+r2∣m−n∣)k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}+c-r_{1}\cdot\log(1+r_{2}|m-n|) with r1,r2>0r_{1},r_{2}>0.

We note that these are not the only variants of the composite kernel. In section 5.3, we experiment with two more complicated variants, but only find lower training speeds and marginal improvement in perplexities (e.g., logarithmic variant vs. 3-para-log). Thus, based on our study, the choices above hold advantages in both performance and speed.

Connection to Prior Work.

When the bias kernel, Eq. (3), is a triangle kernel: c−∣m−n∣c-|m-n|, our model reduces to ALiBi (Press et al., 2022). Wennberg and Henter (2021) discuss the situation where the bias kernel is a Gaussian kernel. Tsai et al. (2019) is the case where there is no bias kernel and the attention product qm⊤kn\bm{q}_{m}^{\top}\bm{k}_{n} is multiplied by an exponentiated inner product kernel, exp⁡(x⊤y)\exp(\bm{x}^{\top}\bm{y}). Since ALiBi is the state-of-the-art and has great input length extrapolation, we will focus on comparison with ALiBi in our experiments.

The logarithmic variant has an implicit connection to T5 positional bias (Raffel et al., 2020). According to the official GitHub repository https://github.com/google-research/text-to-text-transfer-transformer and the HuggingFace Transformer (Wolf et al., 2020), T5 bias is implemented with a log-binning strategy. For each head of the transformer, they maintain a bucket of 32 learnable parameters and assign the relative positional bias bm−nb_{m-n} to these parameters as

where ⌊⋅⌋\lfloor\cdot\rfloor is the floor function. Note that the log factor is approximately 7.7log⁡m−n167.7\log\frac{m-n}{16}. Therefore, T5 is using a logarithmic bucket assignment, which turns out to extrapolate to different input lengths. Compared with T5, our logarithmic variant uses less parameters (2x12 vs. 32x12) but cannot learn non-monotonic relations (the log function is monotonic). We will conduct more comparisons with T5 bias in our experiments.

Experiments

We conduct experiments on OpenWebText2, GitHub, and ArXiv datasets gathered in Gao et al. (2020). OpenWebText2 includes recent content from Reddit submissions until 2020, content from multiple languages, document metadata, multiple dataset versions, and open-source replication code. GitHub includes open-source repositories written in primary coding languages such as Java, C/C++, Python, and Go. ArXiv includes papers written in LaTex in Math, Computer Science, Physics, and some related fields. These tasks are motivated by the downstream applications such as online chatting (Roller et al., 2021), code completion (Chen et al., 2021a), and academic paper summarization (Zhang et al., 2020).

Implementation.

We adapt our model from GPT-NeoX (Black et al., 2021), a transformer implementation by the EleutherAI team. The codebase is based on NVIDIA Megatron Language Model (Shoeybi et al., 2019) and further accelerated using Microsoft DeepSpeed library (Rasley et al., 2020).

Our model is trained on a machine with one NVIDIA A100 GPU with 40 GB of memory. We adopt almost all configurations of small GPT-NeoXhttps://github.com/EleutherAI/gpt-neox/blob/main/configs/small_bf16.yml, except that we change the train-micro-batch-size to 32, seq-length to 512, and max-position-embeddings to 512. Table 2 summarizes the important configurations fixed throughout our experiments.

In particular, the floating-point encoding is set as bfloat16 (Brain Floating Point, developed by Google Brain) so that the training can be accelerated by half-precision computation with reliable stability (Kalamkar et al., 2019). Hidden size 64 means that d=64d=64 in Eq. (1).

2 Experimental Results (Also c.f. Appendix A.4 to A.7)

We conduct experiments to cover aspects such as input length extrapolation, application on different domains, and comparison with the prior work. These are elaborated on below. (i) Motivated by the input length extrapolation demonstrated in (Press et al., 2022), we train our model with length 512 and test on lengths ranging from 512 to 16384. We hope that the emphasis on extrapolation enables the application of transformers to longer sequences. (ii) To evaluate the applicability of the model in different domains, we conduct experiments on OpenWebText2, GitHub, and ArXiv datasets. (iii) To validate the effectiveness of our method, we compare KERPLE with Sinusoidal (Vaswani et al., 2017), Rotary (Su et al., 2021), T5 (Raffel et al., 2020), and ALiBi (Press et al., 2022).

Table 3 reports the perplexities at different extrapolation lengths. We perform non-overlapping evaluation: Suppose text is segmented in a different manner for 512 and 1024 tokens, we have N sentences and N/2 correspondingly to evaluate. We also perform a paired two-sided t-test to validate the statistical significance (significance level=0.05). We compare each candidate RPE with our proposed logarithmic variant and mark the candidate with a † if the log variant is statistically significantly better. Table 4 reports the training speeds. These tables yield three conclusions. First, within the KERPLE framework, the logarithmic variant is better than the power variant. Secondly, the logarithmic variant is 9.7% faster than T5. In terms of extrapolation, the logarithmic variant generally does better than T5 but could be slightly worse than T5 at shorter lengths. Third, the logarithmic variant is slightly slower than some prior work (ALiBi, Rotary, and Sinusoidal) but consistently outperform these methods at all extrapolation lengths. More details are given below.

In our proposed KERPLE framework, the logarithmic variant is better than the power variant. Precisely, the logarithmic variant is 4.4% faster and has lower perplexities across all extrapolation lengths and all tasks.

Logarithmic Variant vs. T5.

In terms of speed, the logarithmic variant is 9.7% faster than T5. In terms of extrapolation perplexity, the logarithmic variant is close to or slightly worse than T5 when the extrapolation length is shorter than 2048, and consistently excels T5 at longer extrapolation lengths. The tendency of extrapolation holds for all datasets evaluated in this work.

Logarithmic Variant vs. ALiBi, Rotary, and Sinusoidal.

The logarithmic variant is 1.6% slower, 7.5% faster, and 3.0% slower than ALiBi, Rotary, and Sinusoidal. The speed comparison makes sense because we require only a limited amount of learnable parameters for RPEs (at most 3⋅H3\cdot H). Also, the logarithmic variant consistently outperforms prior work at all extrapolation lengths and tasks.

3 Experiments on Complicated Kernels

In addition to the practical variants (power & logarithmic) in section 4, we consider two complicated versions of the composite kernel, Eq. (4), as follows.

bias + weight: kcomp([qm,m],[kn,n])=qm⊤kn⋅exp⁡(−r3∣m−n∣r4)+c−r1∣m−n∣r2k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}\cdot\exp(-r_{3}|m-n|^{r_{4}})+c-r_{1}|m-n|^{r_{2}} with r1,r3>0r_{1},r_{3}>0 and 0<r2,r4≤20<r_{2},r_{4}\leq 2.

3-parameter-logarithmic: kcomp([qm,m],[kn,n])=qm⊤kn+c−r1⋅log⁡(1+r2∣m−n∣r3)k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}+c-r_{1}\cdot\log(1+r_{2}|m-n|^{r_{3}}) with r1,r2>0r_{1},r_{2}>0 and 0<r3≤20<r_{3}\leq 2.

Recall the tensor product property of a kernel: if k1k_{1} is a kernel on X\mathcal{X} and k2k_{2} is a kernel on Y\mathcal{Y}, then k((x,y),(x′,y′))=k1(x,x′)k2(y,y′)k((x,y),(x^{\prime},y^{\prime}))=k_{1}(x,x^{\prime})k_{2}(y,y^{\prime}) is a kernel on X×Y\mathcal{X}\times\mathcal{Y}. Therefore, (bias+wht) is the setting where we train a weight exp⁡(−r3∣m−n∣r4)\exp(-r_{3}|m-n|^{r_{4}}) and a bias kernel c−r1∣m−n∣r2c-r_{1}|m-n|^{r_{2}}. qm⊤kn\bm{q}_{m}^{\top}\bm{k}_{n} is multiplied by the weight kernel and then added with the bias kernel. (3-para-log) is the setting where we consider ∣m−n∣r3|m-n|^{r_{3}} in the log. When r3=1r_{3}=1, it is reduced to the logarithmic variant proposed in section 4.

We plug in these composite kernel kcompk^{\text{comp}} into our KERPLE framework, Eq. (2), and test the performance of these RPE. Compared with section 5.2, Table 5 suggests that these variants do not have clear advantage in extrapolation performance, e.g., 3-para-log is slightly better in perplexity than the (two-parameter) logarithmic variant. Thus, enlarging the complexity of kernels does not necessarily give better performance in the context of RPE.

4 Plots of Kernel Functions

We plot kernel functions including the power, log variants, and ALiBi for different heads to see their contributions to softmax. We use the GitHub dataset for demonstration. Please see Figure 2, 3, and 4. Both ALiBi and its generalized power variant quickly reach a very negative value. In contrast, the log variant successfully discovers several flat kernels, effectively extending the window attention. This corroborates our previous observation that KERPLE-log can utilize more distant token information.

5 Position-wise Perplexity Evaluation

We plot the position-wise perplexity with evaluation length=4096 in Figure 5. Please see Appendix A.6 for similar length=16384 result. The evaluation is done by measuring the loss at each position in each sequence and averaging over the sequences.

We note that PPL@512 of KERPLE-log is the lowest among all model variants. We can derive several critical observations for evaluation length=4096 in Figure 5: First, KERPLE-log lies below KERPLE-log-windowed@512, indicating its usage of more distant information than window attention: If our model does not use more information other than a fixed-window=512, the y-values after position=512 should overlap with the line windowed at 512. This is clearly not the case. In addition, the PPL of KERPLE-log continues to decrease till the end of 4096 positions (Not plateauing). Second, T5 lies below KERPLE-log-windowed@512 most of the time and fluctuates around KERPLE-log-windowed@512 after length=3000. It is still worse than KERPLE-log. Third, ALiBi lies above KERPLE-log-windowed@512 for almost all the positions, indicating that window attention might be a better choice than ALiBi.

Although window attention is a strong baseline, our KERPLE-log is almost like a free lunch compared to window attention: With only 24 additional learnable parameters (2 para. for each head), the almost same training speed, and the same train length=512 as window attention, it is able to achieve lower PPLs across different positions.

Conclusion and Future Work

A general framework, KERPLE, is proposed to kernelize relative positional embeddings for length extrapolation. At the core of this framework is the application of CPD kernels and the derivation of practical variants. We show that these CPD kernels can be implicitly converted to PD kernels, which keep the inner product interpretation of self-attention. We also demonstrate that the logarithmic variant achieves exceptional extrapolation performance on three large language modeling datasets. We believe our work paves the way for some interesting future directions that resolve our limitations. For instance, we can consider general kernel families and model non-monotonic effects due to positional differences. In addition, the use of learnable parameters in KERPLE might enable better generalization to inputs higher than one-dimensional. Last but not least, there is always room for improving memory efficiency by adjusting the model architecture and training procedure.

Broader Impact

Our work develops a better understanding of relative positional embedding for transformers based on expressive kernel classes that adapt well to various datasets. The results apply to domains where the positional information is helpful in the modeling, e.g., natural language, programming language, and DNA/protein sequences for biology/medicine. The studies of transformers may have positive economic effects by enabling new tasks which cannot be done by humans or enhancing accuracy and efficiency. But inappropriate use can have negative societal impacts. These include job loss due to automation, the ethical challenges from improper text generation, and the privacy issues in the data collection process. These implications apply to any research on natural language processing and are not associated with any specific work.

Acknowledgement

We thank the anonymous reviewers for their insightful feedback and suggestions. We thank Princeton Research Computing for the technical support on the Della and the Adroit clusters. The third author acknowledges support from NSF MRI Award: 1919452.

References

Appendix A Appendix

We want to show there exists a large enough cc such that fc(v)≥0f_{c}(v)\geq 0 for all v∈{v:∥v∥=1}v\in\{v:\|v\|=1\}.

It is sufficient to consider a∗=min⁡v:∥v∥=1v⊤Kv<0.\boldsymbol{a^{*}=\min_{v:\|v\|=1}v^{\top}Kv<0.}

Let a∗a^{*} be the solution to the minimization:

Since v⊤Kvv^{\top}Kv is continuous in vv and {v:∥v∥=1}\{v:\|v\|=1\} is compact (i.e., closed and bounded), a∗a^{*} must exist. If a∗≥0a^{*}\geq 0, KK is positive semidefinite and fc(v)≥0f_{c}(v)\geq 0 for c≥0c\geq 0. Thus, without loss of generality, we assume a∗<0a^{*}<0.

It is sufficient to consider K\boldsymbol{K} without zero eigenvalues (i.e., full rank).

If there exists v0v_{0} such that Kv0=0Kv_{0}=0, then c≥0c\geq 0 is enough to satisfy fc(v0)≥0f_{c}(v_{0})\geq 0. For any v1v_{1} satisfying v1⊤v0=0v_{1}^{\top}v_{0}=0, we have (v1+v0)⊤K(v1+v0)=v1⊤Kv1(v_{1}+v_{0})^{\top}K(v_{1}+v_{0})=v_{1}^{\top}Kv_{1}. Therefore, whether there exists cc to have fc(v)≥0f_{c}(v)\geq 0 doesn’t depend on the eigenvector corresponding to zero eigenvalue (if there is such a vector). This means it is enough to consider KK without zero eigenvalues.

It is sufficient to show there exists (small enough) δ>0\boldsymbol{\delta>0} such that v′∈Tδ⇒v′⊤Kv′>0\boldsymbol{v^{\prime}\in T_{\delta}\Rightarrow v^{\prime\top}Kv^{\prime}>0}.

Then, fc(v)≥0f_{c}(v)\geq 0 when c≥−a∗δ2c\geq\frac{-a^{*}}{\delta^{2}}. Therefore, we need to prove v′∈Tδ⇒v′⊤Kv′>0v^{\prime}\in T_{\delta}\Rightarrow v^{\prime\top}Kv^{\prime}>0 for small enough δ\delta.

To see this, taking v′=v+pv^{\prime}=v+p with ∥p∥<δ2\|p\|<\delta_{2}, we have

Therefore, 0<δ2<1+ϵ/∥K∥−10<\delta_{2}<\sqrt{1+\epsilon/\|K\|}-1 is enough to have ∣v′⊤Kv′−v⊤Kv∣<ϵ|v^{\prime\top}Kv^{\prime}-v^{\top}Kv|<\epsilon.

By definition of strict CPD, we know min⁡v∈Sv⊤Kv=λ>0\min_{v\in S}v^{\top}Kv=\lambda>0. Thus, take ϵ<λ\epsilon<\lambda, a small enough δ2\delta_{2} gives v′⊤Kv′>v⊤Kv−ϵ>=λ−ϵ>0v^{\prime\top}Kv^{\prime}>v^{\top}Kv-\epsilon>=\lambda-\epsilon>0. In other words, there exists a small enough δ2\delta_{2} such that v′⊤Kv′>0v^{\prime\top}Kv^{\prime}>0 for v′∈Sδ2={v′:∥v′−v∥<δ2, v∈S}v^{\prime}\in S_{\delta_{2}}=\{v^{\prime}:\|v^{\prime}-v\|<\delta_{2},~{}v\in S\}.

Proving ∃ δ>0 s.t. v′∈Tδ⇒v′⊤Kv′>0\boldsymbol{\exists~{}\delta>0~{}\text{s.t.}~{}v^{\prime}\in T_{\delta}\Rightarrow v^{\prime\top}Kv^{\prime}>0}.

Thus, ∥v′−v∥=O(∣r∣n)≤O(δn)<δ2\|v^{\prime}-v\|=O(\frac{|r|}{\sqrt{n}})\leq O(\frac{\delta}{\sqrt{n}})<\delta_{2} for small enough δ\delta. This implies that, with a small enough δ\delta, for any v′∈Tδv^{\prime}\in T_{\delta}, we can find v∈Sv\in S such that ∥v′−v∥<δ2\|v^{\prime}-v\|<\delta_{2}. Thus, v′∈Sδ2v^{\prime}\in S_{\delta_{2}}, and by (v), we arrive at v′⊤Kv′>0v^{\prime\top}Kv^{\prime}>0.

A.2 Shift-invariant Kernels with Bounded and Unbounded Ranges

We will interchange the ideas of shift-invariant kernels and positive definite functions because they are equivalent by definition. Any statement in positive definite functions can be translated into shift-invariant kernels, and vice versa. Because of this, we will use some facts about the positive definite functions to derive the shift-invariant kernels of our interest.

In the literature, there have been studies on applying kernels in the attention mechanism [Tsai et al., 2019, Choromanski et al., 2021, Peng et al., 2021]. One of the most common approaches is to consider the Gaussian kernel:

Note the Gaussian kernel is bounded (k(m,n)∈(0,1]k(m,n)\in(0,1] for the case above). To generalize it to a broader class of bounded shift-invariant kernels, observe that the Gaussian kernel generated by a positive definite function of the form f(x)=exp⁡(−∣x∣2)f(x)=\exp(-|x|^{2}). Since there is no strong reason to stick to the power of 2, one may generalize it to a broader class of positive definite functions as below.

exp⁡(−∣x∣p)\exp(-|x|^{p}) is positive definite if 0<p≤20<p\leq 2 and not positive definite if p>2p>2.

Fact 5 implies that, if one wants to find a class of bounded shift-invariant kernel (i.e., k(m,n)k(m,n) is within some fixed interval for any m,nm,n), then k(m,n)=exp⁡(−a∣m−n∣p)k(m,n)=\exp(-a|m-n|^{p}) with a>0a>0 and p∈(0,2]p\in(0,2] may be of interest.

Constructing Unbounded Shift-invariant Kernels.

A limitation of Fact 5 is that it only generates kernels with a bounded range (here, the range is bounded in (0,1](0,1]). In situations where there are no explicit bounds, one might want to consider kernels with unbounded range. To construct such kernels, we utilize a kernel representation theorem presented in Schoenberg :

f(x)f(x) is bounded away from zero (f(x)>0f(x)>0) and its positive powers f(x)λf(x)^{\lambda} (λ>0\lambda>0) are all positive definite if and only if f(x)f(x) is of the form

where ψ(x)\psi(x) is positive definite and cc is a real constant.

Since Fact 6 works for non-negative kernels, we combine it with Fact 5 and show the following class of shift-invariant kernel with an unbounded range.

is a positive definite kernel. When p>2p>2, there is no cc to make k(m,n)k(m,n) positive definite.

Prop. 1 introduces a kernel with unbounded range (k(m,n)∈(∞,c]k(m,n)\in(\infty,c]) and is adapted from the p-th power of the distance ∣m−n∣|m-n|. Since the distance is a notion of "dissimilarity", −∣m−n∣p-|m-n|^{p} becomes a notion of "similarity", which gives a sense of kernel. Thereby, we can interpret the constant cc as the required value to shift −∣m−n∣p-|m-n|^{p} such that c−∣m−n∣pc-|m-n|^{p} becomes a positive definite kernel.

In fact, −∣m−n∣p-|m-n|^{p} is a conditional positive definite kernel for p∈(0,2]p\in(0,2] Schölkopf . Therefore, the fact that −∣m−n∣p-|m-n|^{p} can become a positive definite kernel by shifting is not a coincidence, as it has already had an intimate relation to positive definite kernels.

A.3 Experiments on Gaussian-like Kernels

Since the prior work on shift-invariant kernels mainly focuses on Gaussian kernels, we present preliminary experiments on Gaussian-like kernels. Compared with section 5.2, the perplexities of these kernels are large at every extrapolation length. This verifies our previous assertion that the Gaussian-like kernels have limited extrapolation ability.

Because the kernel can be used as a weight or a bias, we consider four kinds of the composite kernel (see section 4) as follows.

r1,r2>0r_{1},r_{2}>0. kcomp([qm,m],[kn,n])=qm⊤kn+r1exp⁡(−r2∣m−n∣2)k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}+r_{1}\exp(-r_{2}|m-n|^{2}).

r1,r2>0r_{1},r_{2}>0 and 0<r3≤20<r_{3}\leq 2. kcomp([qm,m],[kn,n])=qm⊤kn+r1exp⁡(−r2∣m−n∣r3)k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}+r_{1}\exp(-r_{2}|m-n|^{r_{3}}).

r1>0r_{1}>0. kcomp([qm,m],[kn,n])=qm⊤kn⋅exp⁡(−r1∣m−n∣2)k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}\cdot\exp(-r_{1}|m-n|^{2}).

r1>0r_{1}>0 and 0<r2≤20<r_{2}\leq 2. kcomp([qm,m],[kn,n])=qm⊤kn⋅exp⁡(−r1∣m−n∣r2)k^{\text{comp}}([\bm{q}_{m},m],[\bm{k}_{n},n])=\bm{q}_{m}^{\top}\bm{k}_{n}\cdot\exp(-r_{1}|m-n|^{r_{2}}).

(2-para-bias) and (1-para-wht) are the settings where we put the Gaussian kernel as a bias and a weight, respectively. (3-para-bias) and (2-para-wht) generalize these settings by considering a learnable power between 0 and 2. Note we must constrain the power in (0,2]; otherwise, the function is not positive definite. See Fact 5 for details.

These composite kernel kcompk^{\text{comp}} are plugged into the KERPLE framework, Eq. (2), and are evaluated on OpenWebText2, GitHub, and ArXiv datasets. Table 6 shows the Gaussian-like kernel is better to be a weight instead of a bias. As discussed in Appendix A.2, the Gaussian-like kernels are bounded. To some extent, this implies that the bounded positive kernel can model a weight. However, compared with section 5.2 the Gaussian-like kernels have limited advantages in extrapolation. Although the performance might be improved if the power of exp⁡(−∣x∣p)\exp(-|x|^{p}) is relaxed from p=2p=2 to p∈(0,2]p\in(0,2], still it cannot be as good as the logarithmic variant as we demonstrate in section 5.2. Therefore, while the Gaussian kernel is frequently used in the literature, we need a better class of shift-invariant kernels to tackle the length extrapolation challenge.

A.4 Experiments on Large Model, Longer Training Length, and Wikitext-103

In this subsection, we present additional experiments on (a) large models, (b) longer training length, and (c) Wikitext-103. Below is the summary of the experiments.

The 1.3B large model is trained on a machine with two NVIDIA A100 GPU with 40 GB of memory. We adopt almost all configurations of XL GPT-NeoXhttps://github.com/EleutherAI/gpt-neox/blob/main/configs/XL.yml, except that we change the train-micro-batch-size to 16, model-parallel-size to 2, seq-length to 512, and max-position-embeddings to 512. Table 8 summarizes the configurations of the 1.3B model.

The 162M Model with training sequence length=1024 follows the same configurations as the ones in Table 2 except that the train seq. length is changed to 1024.

The Wikitext-103 model is implemented on ALiBi’s GitHubhttps://github.com/ofirpress/attention_with_linear_biases with exactly the same configurations (247M parameters), except that the function buffered_future_mask() at line 1011 of attention_with_linear_biases/fairseq/models/transformer.py is adapted to our KERPLE-log.

Table 9 shows the results on the large model (1.3B). Compared with the small model results in Table 3, we see that T5 bias becomes weaker than KERPLE-log and ALiBi, and KERPLE-log remains stronger than ALiBi on GitHub and ArXiv datasets. This is explained by the tendency of overfitting. Observe that both T5 and KERPLE learn the positional embeddings while ALiBi uses fixed ones. T5 and KERPLE have a higher tendency of overfitting. A larger model (1.3B > 162M) or a noisy dataset (OpenWebText2 > GitHub, ArXiv) posits a higher risk of overfitting. Hence, we see that T5 bias is weak on a large model, and KERPLE-log only extrapolates well on GitHub and ArXiv.

Again, Table 9 shows the results on long training length (1024). compared with the short training length (512) in Table 3, KERPLE-log remains better than ALiBi and T5 bias, especially on longer evaluation length. This shows the robustness of KERPLE-log over different training lengths.

Table 10 compares KERPLE-log with ALiBi using ALiBi’s implementation and configurations. The results show that KERPLE-log is superior to ALiBi on Wikitext-103.

A.5 Additional Analyses

Since the power and logarithmic variants derived from KERPLE achieve superior performance on length extrapolation across various datasets, we investigate the underlying reason by visualizing the effective length as shown in Figure 6b. The visualization works in the following procedure.

Then, for each ∣m−n∣∈[0,...,20480]|m-n|\in[0,...,20480], we count the number of heads that satisfies eff(h)≤∣m−n∣\text{eff}^{(h)}\leq|m-n|. This gives a cumulative plot as shown in Figure 6b, where the x-axis is ∣m−n∣|m-n| and the y-axis is Count({h: h∈[1,...,12], eff(h)≤∣m−n∣})\text{Count}(\{h:~{}h\in[1,...,12],~{}\text{eff}^{(h)}\leq|m-n|\}).

Repeat the above steps for other datasets and kernels.

For a point (x,y)(x,y) on a curve, it means that there are yy heads with at least −2-2 bias when the token distance ∣m−n∣|m-n| is greater than xx. In other words, the slower the yy converges to 12, the longer the inter-token range that the model focuses on.

The Advantage of Learnable Parameters.

We observe that ALiBi [Press et al., 2022] produces the same curve no matter which dataset is used. The reason is that ALiBi selects a fixed parameter r=2−8hHr=2^{\frac{-8h}{H}} at head hh for its linear bias −r∣m−n∣-r|m-n| (HH heads in total) regardless of the dataset. While this strategy is useful for extrapolation, we hypothesize that different datasets might have different characteristics, e.g., the average distance of highly related tokens should differ among the datasets as shown in Figure 6b. These characteristics are easier adapted by learnable parameters. Thus, we believe that learnable parameters have more advantages in capturing the dataset-dependent characteristics.

Trends Across Datasets.

We notice that both kernels trained on OpenWebText2 tend to focus more on distant relations. This makes sense because OpenWebText2 has the highest perplexity scores among all datasets, implying that more context is needed to disambiguate the next predicted token. The opposite trend holds for Arxiv and GitHub datasets, which is reasonable considering their lower perplexity scores.

Characteristics Learned by Kernels.

Under any dataset, the logarithmic variant tends to focus more on distant relations than the power variant does. We can explain it through their functional forms. Because logarithm (−alog⁡(1+b∣m−n∣)-a\log(1+b|m-n|)) decays much slower than power (−a∣m−n∣p-a|m-n|^{p}) does, the log variant might encourage the focus on distant relations.

A.6 Position-wise Perplexity for Length=16384

We can draw similar conclusions from Figure 7:

KERPLE-log lies below KERPLE-log-windowed@512 most of the time, indicating its usage of more distant information than window attention.

The PPL of ALiBi does not explode, but it is still worse than window attention, i.e. lies above KERPLE-log-windowed@512.

A.7 The Choice of codebase and Hyperparameters

We adopt almost all the hyperparameters (except batch size to fit in our GPU) and all implementations of the T5 bias, ALiBi, Rotary, and Sinusoidal baselines from the GPT-NeoX codebase. To ensure fair comparisons, we did not fine-tune hyper-parameters for KERPLE. The datasets we used are exactly the same as the ones released with the GPT-NeoX codebase. We just ran their prepare_data.py script to automatically download and parse the datasets. All our code was uploaded with the submission on openreview, and https://github.com/EleutherAI/gpt-neox is the original GitHub repository. As a side note, we chose this codebase and adopted their parameter settings because it is built by EleutherAI, which is a well-known and truly non-profit group of researchers publishing various famous pretrained models for academia including GPT-J-6B and GPT-NeoX-20B.