A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
| 346 | |
| 347 | |
| 348 | class QKVAttentionLegacy(nn.Module): |
| 349 | """ |
| 350 | A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping |
| 351 | """ |
| 352 | |
| 353 | def __init__(self, n_heads): |
| 354 | super().__init__() |
| 355 | self.n_heads = n_heads |
| 356 | |
| 357 | def forward(self, qkv): |
| 358 | """ |
| 359 | Apply QKV attention. |
| 360 | :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. |
| 361 | :return: an [N x (H * C) x T] tensor after attention. |
| 362 | """ |
| 363 | bs, width, length = qkv.shape |
| 364 | assert width % (3 * self.n_heads) == 0 |
| 365 | ch = width // (3 * self.n_heads) |
| 366 | q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) |
| 367 | scale = 1 / math.sqrt(math.sqrt(ch)) |
| 368 | weight = th.einsum( |
| 369 | "bct,bcs->bts", q * scale, k * scale |
| 370 | ) # More stable with f16 than dividing afterwards |
| 371 | weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) |
| 372 | a = th.einsum("bts,bcs->bct", weight, v) |
| 373 | return a.reshape(bs, -1, length) |
| 374 | |
| 375 | @staticmethod |
| 376 | def count_flops(model, _x, y): |
| 377 | return count_flops_attn(model, _x, y) |
| 378 | |
| 379 | |
| 380 | class QKVAttention(nn.Module): |