Build the ALiBi attention bias for every head

ALiBi (Press et al. 2021) drops position embeddings and instead adds a penalty to each attention score that grows with the distance between query and key. Each head uses a different slope, so some heads look far back and others stay local.

Write alibi_bias(n_heads, seq_len) returning an array of shape (n_heads, seq_len, seq_len) to be added to causal attention scores.
- Head h (0-based) has slope m = 2 ** (-8 * (h + 1) / n_heads).
- For a key at or before the query (j <= i): bias[h, i, j] = -m * (i - j).
- For a future key (j > i): bias[h, i, j] = -1e9 (the causal mask).

Signaturedef alibi_bias(n_heads, seq_len)

Example

n_heads = 2, seq_len = 3. The slopes are 0.0625 and 0.00390625, and head 0, row 2 is [-0.125, -0.0625, 0.0].

Understand the idea

ALiBi skips position embeddings. Instead it lowers each attention score by an amount that grows with how far back the key is, so distant tokens matter less. Each head gets its own slope, so some heads stay local and others look far back. Future keys are blocked with a huge negative value, the causal mask. Worked example: n_heads = 4. Slopes m = 2^(-8 * (h + 1) / 4) for h = 0..3: 2^-2 = 0.25, 2^-4 = 0.0625, 2^-6 = 0.015625, 2^-8 = 0.00390625. For head 0 and query position i = 3, keys j = 0, 1, 2, 3 are 3, 2, 1, 0 steps back, giving [-0.75, -0.5, -0.25, 0]. Row i = 1 of head 0 is [-0.25, 0, -1e9, -1e9]. Rule: bias[h, i, j] = -m_h * (i - j) when j <= i, and -1e9 when j > i, returned with shape (n_heads, seq_len, seq_len). Note the exponent uses h + 1, so the first head's slope is not 1. ALiBi lets models run on longer sequences than they were trained on, and was used in BLOOM and MPT.

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

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

  • Sample 1: examplealibi_bias(2, 3)
  • Sample 2: 8 heads, 4 tokensalibi_bias(8, 4)
  • Test 3: one headalibi_bias(1, 5)
  • Test 4: row sums of last headalibi_bias(4, 6)[3].clip(-10, 0).sum(axis=1)