Bucket relative positions like T5

Why it matters T5, Flan-T5 and many encoder models use these buckets instead of absolute positions.

T5 learns one bias per bucket of relative distance: exact buckets for small distances and log-spaced buckets for far ones.

Write rel_bucket(rel, num_buckets=32, max_distance=128) for an int array of relative positions (key - query), bidirectional. Use n = num_buckets // 2: bucket offset n if rel > 0 else 0, then a = |rel|. If a < n // 2 the bucket adds a. Otherwise it adds n // 2 + int(log(a / (n // 2)) / log(max_distance / (n // 2)) * (n - n // 2)), capped at n - 1.

Signaturedef rel_bucket(rel, num_buckets=32, max_distance=128)

Example

rel_bucket([0, 1, -1, 100]) is [0, 17, 1, 31].

Understand the idea

T5 adds a learned bias to attention scores based on how far apart two tokens are. Instead of one bias per distance, distances are grouped into buckets: small distances get their own bucket, and far distances share log-spaced buckets. Half the buckets are for keys after the query, half for keys before. Worked example with 32 buckets, max_distance 128, so n = 16 and n // 2 = 8. rel = 3 is positive, offset 16, and 3 < 8, so bucket 19. rel = -5 has offset 0, bucket 5. rel = 20: offset 16, and 8 + int(log(20 / 8) / log(128 / 8) * 8) = 8 + int(0.330 * 8) = 8 + 2 = 10, so 26. rel = -200: 8 + int(log(25) / log(16) * 8) = 8 + 9 = 17, capped at 15. Rule: n = num_buckets // 2; offset n if rel > 0 else 0; a = |rel|; if a < n // 2, add a; else add min(n // 2 + int(log(a / (n // 2)) / log(max_distance / (n // 2)) * (n - n // 2)), n - 1). Used in: T5 and its descendants.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplerel_bucket([0, 1, -1, 100])
  • Sample 2: rangerel_bucket(np.arange(-10, 11))
  • Test 3: farrel_bucket([500, -500, 127, 128])