AI Logic

Positional Encodings

T5 Relative Position Bias

Updated:

How the T5 relative position bias works. The left shows the flow of an attention layer: nothing is added to the input, and in each layer a learned number per distance bucket is added to the score qΒ·k before softmax. The top right is a graph mapping the distance j βˆ’ i to a bucket index: fine near 0 and with wider steps farther away. The bottom right lists the distances covered by each bucket: 0–7 one each, then 8–11, 12–15 … 64–90, and everything 91 and above in the same bucket.

What is the T5 relative position bias?

The T5 relative position bias injects position information by adding a single learned number (a scalar) per query–key distance to the attention scores. It was used by Raffel et al. in 2019 in the paper on T5, a model that takes text as input and produces text as output (Section 2.1). No position is added to the input embeddings.

The scaled dot-product attention in the Transformer does not distinguish word order on its own. The original Transformer added sinusoidal positional encoding or learned positional embeddings to the input. The T5 paper adopts this method as a simplified form of relative position representations, which learn a vector per distance.

There are two simplifications.

  • Add a single number instead of a vector: Relative position representations add a vector of head size per distance to the keys and values, whereas T5 only adds one number to the score.
  • Group distances: Near distances are distinguished one by one, and farther distances are grouped into increasingly wide ranges (buckets). T5 uses 32 buckets, and every distance beyond about 128 falls into the same bucket.

Because the numbers are learned, each head can flexibly decide from data how distance should matter, such as "attend strongly to the adjacent word" or "ignore slightly distant words."

The left of the figure at the top of the article shows where position information is injected. It has the same layout as the figures in the articles on relative position representations, RoPE, and ALiBi, so the injection points can be compared directly. The right shows the computed mapping of distances to buckets.

Theory (adding a number per distance bucket to the scores)

The explanation follows Section 2.1 of the T5 paper and the official implementation used in the paper (Mesh TensorFlow). Let ii be the query position and jj the key position.

  1. Compute the score qiβ‹…kjq_i \cdot k_j as the usual query–key dot product.
  2. Convert the distance jβˆ’ij - i into a bucket index bucket(jβˆ’i)\mathrm{bucket}(j - i) by a fixed rule (table below).
  3. For each head hh, learn one number per bucket, bh(0),bh(1),…,bh(31)b_h(0), b_h(1), \dots, b_h(31), and add the number for the index from step 2 to the score.
  4. Apply softmax to get weights and take the weighted sum of the values. No position is added to the values.

Combining steps 1–4 gives the following equation.

Ξ±ij=softmaxj(qiβ‹…kj+bh(bucket(jβˆ’i)))\alpha_{ij} = \mathrm{softmax}_j\Bigl(q_i \cdot k_j + b_h\bigl(\mathrm{bucket}(j - i)\bigr)\Bigr)

The bucketing in step 2 for the encoder (attention that looks both forward and backward) is as follows. There are 16 buckets for earlier positions (j<ij < i) and 16 for later positions (j>ij > i), 32 in total.

Distance ∣jβˆ’i∣\lvert j - i \rvertBucketingCount (one side)
0–7A separate bucket for each8
8–90Wider ranges for farther distances: 8–11, 12–15, 16–22, 23–31, 32–45, 46–63, 64–907
91 and aboveAll in the same bucket1

From 8 onward, the bucket index grows in proportion to the logarithm of the distance. Thus distances 8 and 12 are distinguished, but 100 and 200 are not. The idea is to treat the arrangement of nearby words finely and distant words coarsely.

The numbers in step 3 are shared across all layers, and within a layer each head has its own values (Section 2.1 of the paper). The only learned parameters are "number of buckets Γ— number of heads"; with 12 heads, that is 32Γ—12=38432 \times 12 = 384.

The paper's text only says that it uses "32 embeddings for all of our models with ranges that increase in size logarithmically up to an offset of 128." The boundaries in the table above were computed with the Mesh TensorFlow code used in the paper and with _relative_position_bucket in Hugging Face Transformers, which ports it. Because of truncation to integers, the last bucket starts at 91 rather than 128. A causal decoder, which cannot look ahead, uses only the 32 buckets for earlier positions: 16 one by one and the rest logarithmically.

Why can a single number represent position?

In attention, position matters in the score, which decides "which words to attend to and how much." The T5 method simply raises or lowers the score uniformly for each distance, conveying to attention a tendency to attend more or less depending on distance. For example, if bh(bucket(βˆ’1))b_h(\mathrm{bucket}(-1)) is learned to be large in some head, that head attends more readily to "the previous word." It is similar to a map app nudging the ranking of candidates up or down according to their distance from the destination.

The method has the following properties.

  • It uses only relative position: The added number depends only on the distance jβˆ’ij - i, so a pair of words in the same arrangement is treated the same wherever it appears in the sentence.
  • It groups far distances: A single layer cannot distinguish differences in distance between words 91 or more apart. The paper explains that later layers can become sensitive to larger offsets by combining local information from earlier layers.
  • It can be computed for sequences longer than in training: No matter how far apart, the distance falls into the last bucket, so the added number is defined even beyond the training length.

The ALiBi paper notes that, like RoPE, the T5 method injects position information in every layer and not into the values, and suspected that this separation helps extrapolation to longer sequences. It also suggests that grouping far distances into the same bucket may help extrapolation.

Experimental results

The T5 paper does not compare position representations themselves (it leaves evaluating the effect of this change to future work). The effect can be seen from the ALiBi paper, which compared position representations by swapping only them in the same language model.

Evaluation on sequences longer than training (ALiBi paper, Appendix Table 2): Perplexity of language models trained on WikiText-103 with sequences of length L=512L = 512 and evaluated on longer sequences (lower is better).

Evaluation lengthSinusoidalRoPET5 relative position biasALiBi
512 (same as training)20.0520.0719.6519.73
111250.3622.0118.7718.68
2512132.4131.5820.4118.41
3512178.9735.5422.9118.40
12512373.1769.7064.9418.31

At the training length, the T5 relative position bias was the best of the four. As the length increases, perplexity keeps falling up to around 1112 (600 tokens longer than training) and then worsens. It degrades far less than sinusoidal encoding or RoPE, but it is not as robust to length as ALiBi. At 13512 and above, a 32 GB GPU ran out of memory.

Training and inference speed (ALiBi paper, Appendix Table 1): Speed (words per second) on a single V100 GPU.

MethodTraining lengthTraining speedInference speedTraining memory
Sinusoidal51228.5k82.1k15.3 GB
T5 relative position bias51214.4k21.8k16.9 GB
Sinusoidal307215.3k42.4k15.1 GB
T5 relative position bias30724.3k4.9k15.9 GB

With the ALiBi paper's implementation (PyTorch on GPU), training was more than twice as slow as with sinusoidal encoding. However, the ALiBi paper also notes that in another study (TensorFlow on TPU) it was only 8.7% slower than sinusoidal encoding, so the speed gap depends on the implementation and hardware.

Practical considerations

Because the T5 relative position bias adds a different number to the score for each head and each query–key pair, an nΓ—nn \times n bias matrix must be built and passed to attention. With the ALiBi paper's implementation, training was more than twice as slow as with sinusoidal encoding. When using a fast attention implementation (such as FlashAttention), check whether it supports adding an arbitrary bias.

Also keep the following in mind.

  • Match the bucket boundaries used in training: When using a pre-trained T5, keep the number of buckets (32), the maximum distance (128), and the encoder/decoder distinction the same as in the training implementation. If the boundaries change, the learned numbers get applied to the wrong distances.
  • A single layer cannot distinguish far distances: Differences in distance between words 91 or more apart look the same within one layer. Take this into account for tasks on long documents that need precise positions.
  • Extending the length too far lowers accuracy: It can extrapolate to some extent, but in the ALiBi paper's comparison, performance worsened from around twice the training length.

The Hugging Face Transformers implementation of T5 does not divide the scores by d\sqrt{d} (the division is folded into the weight initialization). That is why the PyTorch example below passes scale=1.0 to scaled_dot_product_attention. When adding the T5 method to other models, it is fine to divide by d\sqrt{d} as usual before adding the bias (this is the form used in the ALiBi paper's comparison).

Comparison with other position representations

MethodWhere position is injectedLearned parametersSequences longer than trainingMain uses
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmax⁑×dL_{\max} \times d)Cannot be representedBERT, GPT
Sinusoidal positional encodingAdded to the input embeddings (once)NoneValues can be computed, but accuracy drops sharplyOriginal Transformer
Relative position representationsPer-distance vectors added to scores and values in every layerYes (vectors for 2k+12k+1 distances)Computable because the distance is clippedTranslation, etc.
T5 relative position bias (this article)A learned number per distance bucket added to scores in every layerYes (32 buckets Γ— number of heads, shared across layers)Improves up to about 2Γ— the lengthT5, mT5
RoPEQueries and keys rotated by an angle proportional to position in every layerNoneOnly slightly longerLLaMA, etc.
ALiBiA penalty proportional to distance subtracted from scores in every layerNoneAccuracy is easier to maintainWhen sequences longer than training are needed
  • To let the model learn flexibly from data how distance matters, the T5 relative position bias is a good fit. It has far fewer parameters than relative position representations and has been reported to be more accurate at the training length.
  • To run inference on sequences longer than in training, or to prioritize speed, ALiBi is a strong choice. ALiBi can be seen as fixing T5's "number per distance" to a straight line instead of learning it, which makes the computation lighter.
  • To use fast attention implementations as is, RoPE, which needs no matrix added to the scores, is a candidate.

Transformer-XL relative positional encoding is another method that injects relative distance into the scores. It represents distance with sinusoidal vectors and combines them with learned vectors.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F


def relative_position_bucket(rel: torch.Tensor, bidirectional: bool = True,
                             num_buckets: int = 32, max_distance: int = 128) -> torch.Tensor:
    """Convert the distance rel = j - i (key position - query position) to a bucket index (same as the Mesh TensorFlow implementation)"""
    bucket = torch.zeros_like(rel)
    if bidirectional:                       # encoder: half for earlier, half for later
        num_buckets //= 2
        bucket += (rel > 0).long() * num_buckets
        n = rel.abs()
    else:                                   # decoder: earlier positions (j <= i) only
        n = (-rel).clamp(min=0)
    max_exact = num_buckets // 2            # half are one distance each
    is_small = n < max_exact
    # the other half widen in proportion to log distance up to max_distance
    large = max_exact + (
        torch.log(n.float().clamp(min=1) / max_exact) / math.log(max_distance / max_exact)
        * (num_buckets - max_exact)
    ).long()
    large = large.clamp(max=num_buckets - 1)
    return bucket + torch.where(is_small, n, large)


class T5RelativeBias(nn.Module):
    """Learn a number per bucket and head and return a [1, heads, n_q, n_k] bias. One instance is shared by all layers"""

    def __init__(self, n_heads: int, num_buckets: int = 32, max_distance: int = 128, bidirectional: bool = True):
        super().__init__()
        self.num_buckets, self.max_distance, self.bidirectional = num_buckets, max_distance, bidirectional
        self.bias = nn.Embedding(num_buckets, n_heads)

    def forward(self, n_q: int, n_k: int) -> torch.Tensor:
        rel = torch.arange(n_k)[None, :] - torch.arange(n_q)[:, None]          # j - i
        b = relative_position_bucket(rel, self.bidirectional, self.num_buckets, self.max_distance)
        return self.bias(b).permute(2, 0, 1).unsqueeze(0)                     # [1, heads, n_q, n_k]


# Buckets for distances 0, 1, 7, 8, 12, 20, 50, 100, 200 (later positions get index + 16)
print(relative_position_bucket(torch.tensor([0, 1, 7, 8, 12, 20, 50, 100, 200])))
# tensor([ 0, 17, 23, 24, 25, 26, 29, 31, 31])

# Use in attention: no position embedding is added to the input
B, h, n, d = 2, 8, 16, 64
rel_bias = T5RelativeBias(n_heads=h)                 # one for the whole model
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
# A float matrix passed as attn_mask is added to the scores. As in T5, do not divide by √d (scale=1.0)
out = F.scaled_dot_product_attention(q, k, v, attn_mask=rel_bias(n, n), scale=1.0)
print(out.shape)                                      # torch.Size([2, 8, 16, 64])

FAQ

Q. How does it differ from relative position representations (the method of Shaw et al.)?
A.

Relative position representations learn a vector of head size per distance and add it to the keys and values. The T5 method learns a single number per distance and adds it only to the scores. Also, instead of clipping the distance at kk, it splits distances into buckets that cover wider ranges the farther they are. It needs fewer parameters and less computation.

Q. Why is it fine to group far distances together?
A.

The idea is that between words far apart, the exact distance (100 or 120 words ahead) rarely matters for prediction. The paper explains that even if a single layer cannot distinguish distances beyond about 128, stacking layers lets the model combine local information from earlier layers and become sensitive to larger offsets.

Q. Is it fine to feed inputs longer than the training length?
A.

All far distances fall into the last bucket, so the computation works. In the ALiBi paper's comparison, a model trained at length 512 kept improving in perplexity up to about 1112 but worsened beyond that. To extend the length substantially, consider ALiBi or similar methods.

References

  1. C. Raffel, N. Shazeer, A. Roberts, K. Lee, S. Narang, M. Matena, Y. Zhou, W. Li, and P. J. Liu, "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer," JMLR, 2020.
  2. P. Shaw, J. Uszkoreit, and A. Vaswani, "Self-Attention with Relative Position Representations," NAACL, 2018.
  3. O. Press, N. A. Smith, and M. Lewis, "Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation," ICLR, 2022.
  4. Hugging Face Transformers, modeling_t5.py(T5Attention._relative_position_bucket)