|
1 | 1 | from dataclasses import dataclass |
| 2 | +from functools import partial |
| 3 | +from typing import Literal |
2 | 4 |
|
3 | 5 | import torch |
4 | 6 | import torch.nn.functional as F |
|
7 | 9 |
|
8 | 10 | from eir.models.layers.norm_layers import LayerScale, RMSNorm |
9 | 11 |
|
| 12 | +SparseAttentionType = Literal["softmax", "entmax15", "sparsemax"] |
| 13 | + |
| 14 | + |
| 15 | +def _make_ix_like(input: Tensor, dim: int = -1) -> Tensor: |
| 16 | + d = input.size(dim) |
| 17 | + rho = torch.arange(start=1, end=d + 1, device=input.device, dtype=input.dtype) |
| 18 | + view = [1] * input.dim() |
| 19 | + view[dim] = -1 |
| 20 | + return rho.view(view) |
| 21 | + |
| 22 | + |
| 23 | +class _Entmax15Function(torch.autograd.Function): |
| 24 | + """ |
| 25 | + All entmax/sparsemax functionality adapted from: |
| 26 | + https://github.com/deep-spin/entmax/ |
| 27 | + """ |
| 28 | + |
| 29 | + @staticmethod |
| 30 | + def forward( |
| 31 | + ctx: torch.autograd.function.FunctionCtx, input: Tensor, dim: int = -1 |
| 32 | + ) -> Tensor: # type: ignore[override] |
| 33 | + ctx.dim = dim # type: ignore[attr-defined] |
| 34 | + |
| 35 | + max_val, _ = input.max(dim=dim, keepdim=True) |
| 36 | + input = input - max_val |
| 37 | + input = input / 2 |
| 38 | + |
| 39 | + x_srt, _ = torch.sort(input=input, descending=True, dim=dim) |
| 40 | + rho = _make_ix_like(input=input, dim=dim) |
| 41 | + mean = x_srt.cumsum(dim=dim) / rho |
| 42 | + mean_sq = (x_srt**2).cumsum(dim=dim) / rho |
| 43 | + ss = rho * (mean_sq - mean**2) |
| 44 | + delta = (1 - ss) / rho |
| 45 | + delta_nz = torch.clamp(input=delta, min=0) |
| 46 | + tau = mean - torch.sqrt(delta_nz) |
| 47 | + |
| 48 | + support_size = (tau <= x_srt).sum(dim=dim).unsqueeze(dim=dim) |
| 49 | + tau_star = tau.gather(dim=dim, index=support_size - 1) |
| 50 | + |
| 51 | + output = torch.clamp(input=input - tau_star, min=0) ** 2 |
| 52 | + ctx.save_for_backward(output) |
| 53 | + return output |
| 54 | + |
| 55 | + @staticmethod |
| 56 | + def backward( |
| 57 | + ctx: torch.autograd.function.FunctionCtx, grad_output: Tensor |
| 58 | + ) -> tuple[Tensor, None]: # type: ignore[override] |
| 59 | + (y,) = ctx.saved_tensors # type: ignore[attr-defined] |
| 60 | + dim = ctx.dim # type: ignore[attr-defined] |
| 61 | + |
| 62 | + gppr = y.sqrt() |
| 63 | + dx = grad_output * gppr |
| 64 | + q = dx.sum(dim=dim, keepdim=True) / gppr.sum(dim=dim, keepdim=True).clamp( |
| 65 | + min=1e-12 |
| 66 | + ) |
| 67 | + dx -= q * gppr |
| 68 | + dx *= (y > 0).float() |
| 69 | + |
| 70 | + return dx, None |
| 71 | + |
| 72 | + |
| 73 | +class _SparsemaxFunction(torch.autograd.Function): |
| 74 | + @staticmethod |
| 75 | + def forward( |
| 76 | + ctx: torch.autograd.function.FunctionCtx, input: Tensor, dim: int = -1 |
| 77 | + ) -> Tensor: # type: ignore[override] |
| 78 | + ctx.dim = dim # type: ignore[attr-defined] |
| 79 | + |
| 80 | + max_val, _ = input.max(dim=dim, keepdim=True) |
| 81 | + input = input - max_val |
| 82 | + |
| 83 | + z_sorted, _ = torch.sort(input=input, descending=True, dim=dim) |
| 84 | + z_cumsum = z_sorted.cumsum(dim=dim) |
| 85 | + k = _make_ix_like(input=input, dim=dim) |
| 86 | + support = (1 + k * z_sorted > z_cumsum).float() |
| 87 | + k_star = support.sum(dim=dim, keepdim=True) |
| 88 | + tau = (z_cumsum.gather(dim=dim, index=(k_star - 1).long()) - 1) / k_star |
| 89 | + |
| 90 | + output = torch.clamp(input=input - tau, min=0) |
| 91 | + ctx.save_for_backward(output) |
| 92 | + return output |
| 93 | + |
| 94 | + @staticmethod |
| 95 | + def backward( |
| 96 | + ctx: torch.autograd.function.FunctionCtx, grad_output: Tensor |
| 97 | + ) -> tuple[Tensor, None]: # type: ignore[override] |
| 98 | + (output,) = ctx.saved_tensors # type: ignore[attr-defined] |
| 99 | + dim = ctx.dim # type: ignore[attr-defined] |
| 100 | + |
| 101 | + nonzero = (output > 0).float() |
| 102 | + grad_input = grad_output * nonzero |
| 103 | + v_hat = grad_input.sum(dim=dim, keepdim=True) / nonzero.sum( |
| 104 | + dim=dim, keepdim=True |
| 105 | + ).clamp(min=1e-12) |
| 106 | + grad_input -= v_hat * nonzero |
| 107 | + return grad_input, None |
| 108 | + |
| 109 | + |
| 110 | +def entmax15(input: Tensor, dim: int = -1) -> Tensor: |
| 111 | + return _Entmax15Function.apply(input, dim) |
| 112 | + |
| 113 | + |
| 114 | +def sparsemax(input: Tensor, dim: int = -1) -> Tensor: |
| 115 | + return _SparsemaxFunction.apply(input, dim) |
| 116 | + |
| 117 | + |
| 118 | +class EntmaxMultiheadAttention(nn.Module): |
| 119 | + def __init__( |
| 120 | + self, |
| 121 | + embed_dim: int, |
| 122 | + num_heads: int, |
| 123 | + dropout_p: float = 0.0, |
| 124 | + attention_type: SparseAttentionType = "entmax15", |
| 125 | + ): |
| 126 | + super().__init__() |
| 127 | + assert embed_dim % num_heads == 0 |
| 128 | + |
| 129 | + self.embed_dim = embed_dim |
| 130 | + self.num_heads = num_heads |
| 131 | + self.head_dim = embed_dim // num_heads |
| 132 | + self.scale = self.head_dim**-0.5 |
| 133 | + self.attention_type = attention_type |
| 134 | + |
| 135 | + self.q_proj = nn.Linear( |
| 136 | + in_features=embed_dim, out_features=embed_dim, bias=False |
| 137 | + ) |
| 138 | + self.k_proj = nn.Linear( |
| 139 | + in_features=embed_dim, out_features=embed_dim, bias=False |
| 140 | + ) |
| 141 | + self.v_proj = nn.Linear( |
| 142 | + in_features=embed_dim, out_features=embed_dim, bias=False |
| 143 | + ) |
| 144 | + self.out_proj = nn.Linear( |
| 145 | + in_features=embed_dim, out_features=embed_dim, bias=False |
| 146 | + ) |
| 147 | + self.dropout = nn.Dropout(p=dropout_p) |
| 148 | + |
| 149 | + if attention_type == "entmax15": |
| 150 | + self._attn_fn = entmax15 |
| 151 | + elif attention_type == "sparsemax": |
| 152 | + self._attn_fn = sparsemax |
| 153 | + else: |
| 154 | + self._attn_fn = partial(F.softmax, dim=-1) |
| 155 | + |
| 156 | + def forward(self, x: Tensor) -> Tensor: |
| 157 | + b, s, _ = x.shape |
| 158 | + |
| 159 | + q = self.q_proj(x).view(b, s, self.num_heads, self.head_dim).transpose(1, 2) |
| 160 | + k = self.k_proj(x).view(b, s, self.num_heads, self.head_dim).transpose(1, 2) |
| 161 | + v = self.v_proj(x).view(b, s, self.num_heads, self.head_dim).transpose(1, 2) |
| 162 | + |
| 163 | + attn = (q @ k.transpose(-2, -1)) * self.scale |
| 164 | + attn = self._attn_fn(attn, dim=-1) |
| 165 | + attn = self.dropout(attn) |
| 166 | + |
| 167 | + out = (attn @ v).transpose(1, 2).contiguous().view(b, s, self.embed_dim) |
| 168 | + return self.out_proj(out) |
| 169 | + |
10 | 170 |
|
11 | 171 | class LinearAttention(nn.Module): |
12 | 172 | """ |
|
0 commit comments