BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges14 of 14 in topic

885. Relative position index matrix

EasyOptimization challenges

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.

Functiondef 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).
Topics
Optimization challenges
Similar questions
  • Rolling mean with a cumulative sumEasy
  • Count token frequencies fastEasy
  • Batched softmax without the row loopEasy
  • Padding mask from sequence lengthsEasy
All Optimization challenges problems
Report
885 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
import numpy as np
​
def relative_positions(T, max_dist):
out = np.zeros((T, T), dtype=int)
for i in range(T):
for j in range(T):
out[i, j] = min(max(j - i, -max_dist), max_dist) + max_dist
return out
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS