def alibi(self, T, device):
"""ALiBi bias -m_h (i - j) of every head, (num_heads, T, T)."""
h = torch.arange(1, self.num_heads + 1, device=device)
slopes = 2.0 ** (-8.0 * h / self.num_heads)
pos = torch.arange(T, device=device, dtype=torch.float32)
return slopes[:, None, None] * (pos[None, :] - pos[:, None])
def attend(self, blk, H):
"""Output of attention block blk on the stream H, and its weights."""
B, T, D = H.shape
q, k, v = blk['qkv'](H).chunk(3, -1)
q, k, v = (u.reshape(B, T, self.num_heads, -1).transpose(1, 2)
for u in (q, k, v))
if self.pos == 'rope':
q = rope(q, base=self.rope_base, scale=self.rope_scale)
k = rope(k, base=self.rope_base, scale=self.rope_scale)
scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
if self.pos == 'alibi':
scores = scores + self.alibi(T, H.device)
weights = d2l.masked_softmax(scores, d2l.causal_mask(T, device=H.device))
out = (weights @ v).transpose(1, 2).reshape(B, T, D)
return blk['proj'](out), weights