885. Relative position index matrix
Why it matters Relative position biases index a small learned table with (j - i). Building the index matrix is a broadcasting warm-up that shows up in vision and text transformers.
relative_positions(T, max_dist) builds the index matrix used by learned relative position biases (as in T5 or Swin): out[i, j] = clip(j - i, -max_dist, max_dist) + max_dist, so every entry is an int in [0, 2 * max_dist].
Inputs: T is an int >= 0 (sequence length). max_dist is an int >= 0.
Return an ndarray of ints with shape (T, T).
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 20 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def relative_positions(T, max_dist)Example 1
Input: relative_positions(3, 1)
Output: [[1, 2, 2], [0, 1, 2], [0, 0, 1]]
Example 2
Input: T = 4, max_dist = 5
Output: [[5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
Example 3
Input: T = 0, max_dist = 2
Output: np.zeros((0, 0), dtype=int)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Start from r = np.arange(T).
Hint 2
r[None, :] - r[:, None] gives j - i.
Hint 3
np.clip, then add max_dist.
Common mistakes
- Computing i - j, which transposes the table.
- Forgetting the shift, which leaves negative indices.
- Returning floats.
Understand the idea
A column of query positions minus a row of key positions gives every offset j - i at once; broadcasting a (1, T) row against a (T, 1) column builds the (T, T) table. np.clip bounds the offsets and adding max_dist shifts them to valid table indices. The double loop does 1.44 million Python steps for T = 1200.
Shapes and data flow
r[None, :]: (1, T). r[:, None]: (T, 1). Output: (T, T).