x: [B, L1, C]. context: [B, L2, C] or None. mask: [B, L2] or [B, L1, L2] or None.
(self, x, context=None, mask=None, pos_bias=None)
| 53 | self.dropout = nn.Dropout(dropout) |
| 54 | |
| 55 | def forward(self, x, context=None, mask=None, pos_bias=None): |
| 56 | """ |
| 57 | x: [B, L1, C]. |
| 58 | context: [B, L2, C] or None. |
| 59 | mask: [B, L2] or [B, L1, L2] or None. |
| 60 | """ |
| 61 | # check inputs |
| 62 | context = x if context is None else context |
| 63 | b, n, c = x.size(0), self.num_heads, self.head_dim |
| 64 | |
| 65 | # compute query, key, value |
| 66 | q = self.q(x).view(b, -1, n, c) |
| 67 | k = self.k(context).view(b, -1, n, c) |
| 68 | v = self.v(context).view(b, -1, n, c) |
| 69 | |
| 70 | # attention bias |
| 71 | attn_bias = x.new_zeros(b, n, q.size(1), k.size(1)) |
| 72 | if pos_bias is not None: |
| 73 | attn_bias += pos_bias |
| 74 | if mask is not None: |
| 75 | assert mask.ndim in [2, 3] |
| 76 | mask = mask.view(b, 1, 1, |
| 77 | -1) if mask.ndim == 2 else mask.unsqueeze(1) |
| 78 | attn_bias.masked_fill_(mask == 0, torch.finfo(x.dtype).min) |
| 79 | |
| 80 | # compute attention (T5 does not use scaling) |
| 81 | attn = torch.einsum('binc,bjnc->bnij', q, k) + attn_bias |
| 82 | attn = F.softmax(attn.float(), dim=-1).type_as(attn) |
| 83 | x = torch.einsum('bnij,bjnc->binc', attn, v) |
| 84 | |
| 85 | # output |
| 86 | x = x.reshape(b, -1, n * c) |
| 87 | x = self.o(x) |
| 88 | x = self.dropout(x) |
| 89 | return x |
| 90 | |
| 91 | |
| 92 | class T5FeedForward(nn.Module): |
nothing calls this directly
no outgoing calls
no test coverage detected