A module which performs QKV attention and splits in a different order.
| 449 | |
| 450 | |
| 451 | class QKVAttention(nn.Module): |
| 452 | """ |
| 453 | A module which performs QKV attention and splits in a different order. |
| 454 | """ |
| 455 | |
| 456 | def __init__(self, n_heads): |
| 457 | super().__init__() |
| 458 | self.n_heads = n_heads |
| 459 | |
| 460 | def forward(self, qkv): |
| 461 | """ |
| 462 | Apply QKV attention. |
| 463 | :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. |
| 464 | :return: an [N x (H * C) x T] tensor after attention. |
| 465 | """ |
| 466 | bs, width, length = qkv.shape |
| 467 | assert width % (3 * self.n_heads) == 0 |
| 468 | ch = width // (3 * self.n_heads) |
| 469 | q, k, v = qkv.chunk(3, dim=1) |
| 470 | scale = 1 / math.sqrt(math.sqrt(ch)) |
| 471 | weight = th.einsum( |
| 472 | "bct,bcs->bts", |
| 473 | (q * scale).view(bs * self.n_heads, ch, length), |
| 474 | (k * scale).view(bs * self.n_heads, ch, length), |
| 475 | ) # More stable with f16 than dividing afterwards |
| 476 | weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) |
| 477 | a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) |
| 478 | return a.reshape(bs, -1, length) |
| 479 | |
| 480 | @staticmethod |
| 481 | def count_flops(model, _x, y): |
| 482 | return count_flops_attn(model, _x, y) |
| 483 | |
| 484 | |
| 485 | class Timestep(nn.Module): |