T5 Relative-Position Bias
T5 replaces position embeddings with a few hundred learned biases. How 32 buckets cover any distance, and why encoder and decoder split them differently.
Jump to a section
A few hundred numbers for all of position
T5 does not add position vectors to its token embeddings and does not rotate queries or keys. It adds one learned scalar to each attention score, chosen by how far apart the query and key are. In T5-Base, with 12 heads and 32 distance buckets, the encoder's whole positional mechanism is a table: 384 numbers, shared by every layer.
The T5 paper describes it in two sentences. There are 32 embeddings with ranges that grow logarithmically up to an offset of 128, beyond which all relative positions share one embedding. The parameters are shared across layers, while each head in a layer has its own learned value per bucket.
So distances that land in the same bucket share the same positional contribution. Their content-based scores, , can still differ; the bias only shifts the score before the softmax. The decoder's self-attention has a separate table of the same shape.
Direction first, then distance
A common description of T5's buckets is "8 exact plus 24 logarithmic". That misses the split between encoder and decoder. Direction is allocated before distance, and the two modes allocate differently.
Use the convention offset = key position − query position. A negative offset looks backward, a positive one forward.
In the encoder, attention is bidirectional, so the 32 slots split into two halves of 16: one for keys behind the query, one for keys ahead. Each half gives 8 slots to exact distances 0 to 7 and 8 slots to logarithmic ranges. In the decoder, attention is causal and there is no split: 16 slots are exact and 16 are logarithmic, all for looking backward. In this implementation offset zero selects bucket 0, and bidirectional bucket 16 is never selected.
Offset -17 selects bucket 10.
16 slots per direction; 8 exact and 8 logarithmic in each half. Zero uses bucket 0; bucket 16 is unused. Max distance: 128. Colors show allocation, not learned bias values.
Reference implementationTry −17, then +17. In the encoder they land in buckets 10 and 26: the same distance, mirrored into the forward half. In the decoder, −17 selects bucket 16, and +17 clamps to bucket 0, the same bucket as the query's own position.
That clamp does not let the decoder attend to future tokens. A separate causal mask blocks them. The bucket function only decides which learned scalar to add to a score that the mask may then remove.
The bucket formula
Let be the slots available after the direction split: 16 in bidirectional mode, 32 in causal mode. Set for the exact region and for the maximum distance. For a nonnegative distance , the index within a half is
In bidirectional mode, use the absolute offset and add 16 for a positive one. In causal mode, use the negated offset clamped at zero. Large distances saturate at the last slot.
Saturation starts at the lower edge of the final logarithmic bin, not at exactly 128. In the encoder, bucket 15 first appears at distance 91: . In the decoder, bucket 31 first appears at 113. Every greater distance, whether 200 or 20,000, shares that last bucket, so the bias cannot tell two distant keys apart.
In code
Download the complete executable example. Run python3 t5_buckets.py; it needs only the Python standard library. The script checks encoder and decoder outputs, plus the cache-position example below.
1from math import floor, log
2
3def bucket(offset, bidirectional=True):
4 slots = 16 if bidirectional else 32
5 exact = slots // 2
6 distance = abs(offset) if bidirectional else max(0, -offset)
7 direction = 16 if bidirectional and offset > 0 else 0
8 if distance < exact:
9 return direction + distance
10 growth = floor(log(distance / exact) / log(128 / exact) * exact)
11 return direction + min(slots - 1, exact + growth)
12
13assert [bucket(-17), bucket(17)] == [10, 26]
14assert [bucket(-17, False), bucket(17, False)] == [16, 0]
15assert bucket(-90) == 14 and bucket(-91) == 15 and bucket(-113, False) == 31This is a scalar teaching implementation for the default configuration, not a replacement for a vectorized attention kernel. It branches before taking the logarithm, so it never evaluates .
Bugs that keep valid shapes
Take a cached decoder at absolute query position 128, reading the key at position 124. The correct offset is −4, which selects causal bucket 4. If the query index is accidentally reset to zero, because the new token arrives as a tensor of length one, the offset becomes +124 and clamps to bucket 0. Nothing crashes, and the model receives the wrong relationship on every decoding step.
A useful test suite covers self-position, both signs, the boundary between exact and logarithmic buckets, saturation, and cached absolute positions. Test masking separately: a passing bucket test says nothing about whether future scores were excluded.
Changing the bucket count needs the same care. With 64 buckets and the maximum distance still 128, each bidirectional half gets 32 slots, 16 of them exact, while the causal mode keeps all 64 together with 32 exact. The logarithmic scale has to change with those values; resizing the table alone leaves a hard-coded mapping, like the one above, computing indices for the old layout.
Sources and further reading
- Hugging Face's T5 implementation, specifically
_relative_position_bucketandcompute_bias, reviewed October 14, 2026. The browser visual, Python script and debugging cases are authored teaching examples. - Raffel et al., Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (2019): the T5 paper, where the 32 logarithmic buckets and their sharing across layers are described.