ALiBi linear attention biases (Press et al.) instead of position embeddings

ALiBi ("Train Short, Test Long", Press, Smith and Lewis) drops position embeddings and instead adds a penalty to each attention score that grows linearly with the distance between query and key. Each head uses a different slope, so some heads look locally and others look far back, and the model can run on longer inputs than it was trained on.

Write alibi_attention(q, k, v). q, k, v have shape (H, T, d), with H a power of 2.
- slope for head h (h = 0..H-1) is m_h = 2 ** (-8 * (h + 1) / H). For H = 8 that is 1/2, 1/4, ..., 1/256.
- scores[h, i, j] = q[h, i] . k[h, j] / sqrt(d) - m_h * (i - j)
- causal: key j is allowed only if j <= i
- softmax over j, then weight v
Return the output of shape (H, T, d).

Signaturedef alibi_attention(q, k, v)

Understand the idea

This problem builds full causal attention with ALiBi biases. Instead of position embeddings, each head lowers a score in proportion to how far back the key is, with its own slope, so the model prefers recent tokens at different rates per head. Slopes form a geometric sequence starting at 2^(-8 / H), not at 1. Worked example: H = 2, so slopes are 2^-4 = 0.0625 and 2^-8 = 0.0039. Suppose all q . k are 0. For head 0, query i = 1 sees keys 0 and 1 with scores [-0.0625, 0]. Softmax gives [0.4844, 0.5156], so the newer key gets a bit more weight. For query 0 only key 0 is allowed, weight 1. Rule: scores[h, i, j] = q[h, i] . k[h, j] / sqrt(d) - m_h * (i - j) for j <= i, masked for j > i; m_h = 2^(-8 * (h + 1) / H); softmax over j and multiply by v, giving shape (H, T, d). Because the bias depends only on distance, the model can run on inputs longer than it saw in training. ALiBi was used in BLOOM and MPT.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: 4 heads, 5 tokensalibi_attention(_q, _k, _v)
  • Sample 2: zero queries: pure distance biasalibi_attention(np.zeros((2, 4, 2)), np.zeros((2, 4, 2)), np.arange(16.0).reshape(2, 4, 2))