Single-query attention over valid KV positions, batched. q: [b, num_heads, head_dim] K, V: [b, num_kv_heads, max_len, head_dim] pos: int or LongTensor [b] (valid positions, 0-indexed inclusive; an int applies to every row) Returns [b, num_heads, head_dim] with GQA (K/V hea
(q, K, V, pos)
| 48 | |
| 49 | |
| 50 | def decode_attn(q, K, V, pos): |
| 51 | """Single-query attention over valid KV positions, batched. |
| 52 | |
| 53 | q: [b, num_heads, head_dim] |
| 54 | K, V: [b, num_kv_heads, max_len, head_dim] |
| 55 | pos: int or LongTensor [b] (valid positions, 0-indexed inclusive; |
| 56 | an int applies to every row) |
| 57 | |
| 58 | Returns [b, num_heads, head_dim] with GQA (K/V heads shared across query |
| 59 | heads). |
| 60 | """ |
| 61 | num_q_heads = q.shape[-2] |
| 62 | num_kv_heads = K.shape[-3] |
| 63 | head_dim = q.shape[-1] |
| 64 | n_rep = num_q_heads // num_kv_heads |
| 65 | scale = 1.0 / math.sqrt(head_dim) |
| 66 | |
| 67 | lens = (pos + 1).tolist() if torch.is_tensor(pos) else [pos + 1] * q.shape[0] |
| 68 | out = torch.empty(q.shape, dtype=torch.float32, device=q.device) |
| 69 | for r in range(q.shape[0]): |
| 70 | K_valid = K[r, :, :lens[r], :] # [nkv, len, hd] |
| 71 | V_valid = V[r, :, :lens[r], :] |
| 72 | if n_rep > 1: |
| 73 | K_valid = K_valid.repeat_interleave(n_rep, dim=0) |
| 74 | V_valid = V_valid.repeat_interleave(n_rep, dim=0) |
| 75 | scores = torch.einsum('hd,hld->hl', q[r].float(), K_valid.float()) * scale |
| 76 | weights = torch.softmax(scores, dim=-1) |
| 77 | out[r] = torch.einsum('hl,hld->hd', weights, V_valid.float()) |
| 78 | return out.to(q.dtype) |
| 79 | |
| 80 | |
| 81 | def silu_mul(gu, n): |