Here is a Python script that implements a grouped-query attention mechanism with a sliding window:
python
import torch
import torch.nn as nn
class GroupedQueryAttention(nn.Module):
def __init__(self, embed_dim, num_heads, window_size):
super().__init__()
self.num_heads = num_heads
self.embed_dim = embed_dim
self.head_dim = embed_dim // num_heads
self.window_size = window_size
self.qkv_proj = nn.Linear(embed_dim, 3*embed_dim)
self.out_proj = nn.Linear(embed_dim, embed_dim)
def forward(self, x):
B, L, D = x.shape
H = self.num_heads
qkv = self.qkv_proj(x) # B x L x 3D
q, k, v = torch.chunk(qkv, 3, dim=-1) # B x L x D
q = q.view(B, L, H, D//H).transpose(1, 2) # B x H x L x D/H
k = k.view(B, L, H, D//H) # B x L x H x D/H
v = v.view(B, L, H, D//H) # B x L x H x D/H
attn = torch.einsum('bhld,bhkd->bhlk', [q, k]) # B x H x L x K
# Sliding window
W = self.window_size
attn_windows = attn.unfold(2, W, 1) # B x H x L x K x W
attn_windows = attn_windows.transpose(3,4).contiguous() # B x H x L x W x K
attn_windows = attn_windows.view(-1, W, attn_windows.size(-1)) # B*H*L x W x K
attn_windows = F.softmax(attn_windows, dim=-1)
attn_windows = attn_windows.view(B, H, L, W, K)
attn_windows = attn_windows.transpose(3,4) # B x H x L x K x W
attn_windows = attn_windows.contiguous().view(B, H, L, -1)
v_windows = v.unfold(1, W, 1).transpose(2,3).contiguous() # B x H x W x L x D/H
v_windows = v_windows.view(-1, W, v_windows.size(-1)) # B*H*L x W x D/H
output = torch.einsum('bhlk,bhwk->bhlw', [attn_windows, v_windows]) # B x H x L x W x D/H
output = output.transpose(2,3).contiguous().view(B, L, -1) # B x L x H*W*D/H
output = self.out_proj(output) # B x L x D
return output
This implements a multi-head attention layer with grouped queries and a sliding window. The key components are:
Project the inputs to queries, keys and values using a linear layer
Split them into multiple heads
Apply sliding window to the attention matrix
Attend values within the window
Recombine heads and project back
The sliding window allows attending to local contexts as the window slides across the sequence. The grouping of queries implements an efficient approximation of full attention.