|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch import nn, arange, cat, stack, Tensor |
| 5 | +from torch.nn import Module, ModuleList |
| 6 | +import torch.nn.functional as F |
| 7 | + |
| 8 | +from einops import rearrange, repeat, reduce |
| 9 | +from einops.layers.torch import Rearrange |
| 10 | + |
| 11 | +# helpers |
| 12 | + |
| 13 | +def exists(val): |
| 14 | + return val is not None |
| 15 | + |
| 16 | +def l2norm(t): |
| 17 | + return F.normalize(t, dim = -1, p = 2) |
| 18 | + |
| 19 | +def join(arr, delimiter = ' '): |
| 20 | + return delimiter.join(arr) |
| 21 | + |
| 22 | +def ensure_tuple(t, length): |
| 23 | + if isinstance(t, (tuple, list)): |
| 24 | + assert len(t) == length, f'Expected tuple of length {length}, got {len(t)}' |
| 25 | + return tuple(t) |
| 26 | + return (t,) * length |
| 27 | + |
| 28 | +# golden gate rotary - Jerry Xiong, PhD student at UIUC |
| 29 | +# https://jerryxio.ng/posts/nd-rope/ |
| 30 | + |
| 31 | +def _phi(m: int) -> float: |
| 32 | + x = 2.0 |
| 33 | + for _ in range(10): |
| 34 | + x = (1 + x) ** (1.0 / (m + 1.0)) |
| 35 | + return x |
| 36 | + |
| 37 | +def make_directions(n: int, d: int) -> Tensor: |
| 38 | + g = _phi(d) |
| 39 | + alpha = (1.0 / g) ** arange(1, d + 1, dtype = torch.float64) |
| 40 | + i = arange(1, n + 1, dtype = torch.float64).unsqueeze(1) |
| 41 | + z = torch.fmod(i * alpha, 1.0) |
| 42 | + directions = torch.erfinv(2.0 * z - 1.0) |
| 43 | + directions = l2norm(directions) |
| 44 | + return directions.float() |
| 45 | + |
| 46 | +class GoldenGateRoPENd(Module): |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + dim_pos: int, |
| 50 | + heads: int, |
| 51 | + dim_head: int, |
| 52 | + rope_min_freq: float = 1.0, |
| 53 | + rope_max_freq: float = 10000.0, |
| 54 | + rope_p_zero_freqs: float = 0.0, # proportion of frequencies set to 0 |
| 55 | + ): |
| 56 | + super().__init__() |
| 57 | + n_freqs = dim_head // 2 |
| 58 | + n_zero_freqs = round(rope_p_zero_freqs * n_freqs) |
| 59 | + |
| 60 | + omega = cat(( |
| 61 | + torch.zeros(n_zero_freqs), |
| 62 | + rope_min_freq * (rope_max_freq / rope_min_freq) ** torch.linspace(0, 1, n_freqs - n_zero_freqs), |
| 63 | + )) |
| 64 | + |
| 65 | + directions = rearrange( |
| 66 | + make_directions(heads * n_freqs, dim_pos), |
| 67 | + '(h f) p -> h f p', |
| 68 | + h = heads |
| 69 | + ) |
| 70 | + |
| 71 | + omega_expanded = rearrange(omega, 'f -> f 1') |
| 72 | + self.register_buffer('freqs', directions * omega_expanded) # shape: (h, f, p) |
| 73 | + |
| 74 | + def forward(self, input: Tensor, pos: Tensor) -> Tensor: |
| 75 | + # input shape: (b, h, n, d) where d = head_dim |
| 76 | + # pos shape: (b, n, p) where p = pos_dim |
| 77 | + # self.freqs shape: (h, f, p) where f = d // 2 |
| 78 | + |
| 79 | + x, y = input.float().chunk(2, dim = -1) # both (b, h, n, f) |
| 80 | + |
| 81 | + # Expand dimensions for broadcasting |
| 82 | + freqs = rearrange(self.freqs, 'h f p -> 1 h 1 f p') |
| 83 | + positions = rearrange(pos.float(), 'b n p -> b 1 n 1 p') |
| 84 | + |
| 85 | + # Compute theta for each (batch, head, seq, freq) |
| 86 | + theta = reduce(freqs * positions, 'b h n f p -> b h n f', 'sum') |
| 87 | + |
| 88 | + cos_theta = torch.cos(theta) |
| 89 | + sin_theta = torch.sin(theta) |
| 90 | + |
| 91 | + # Apply rotation |
| 92 | + x_out = x * cos_theta - y * sin_theta |
| 93 | + y_out = x * sin_theta + y * cos_theta |
| 94 | + |
| 95 | + output = cat((x_out, y_out), dim=-1) |
| 96 | + return output.type_as(input) |
| 97 | + |
| 98 | +# classes |
| 99 | + |
| 100 | +class FeedForward(Module): |
| 101 | + def __init__(self, dim, hidden_dim, dropout = 0.): |
| 102 | + super().__init__() |
| 103 | + self.net = nn.Sequential( |
| 104 | + nn.LayerNorm(dim), |
| 105 | + nn.Linear(dim, hidden_dim), |
| 106 | + nn.GELU(), |
| 107 | + nn.Dropout(dropout), |
| 108 | + nn.Linear(hidden_dim, dim), |
| 109 | + nn.Dropout(dropout) |
| 110 | + ) |
| 111 | + |
| 112 | + def forward(self, x): |
| 113 | + return self.net(x) |
| 114 | + |
| 115 | +class Attention(Module): |
| 116 | + def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0., rotary_emb = None): |
| 117 | + super().__init__() |
| 118 | + inner_dim = dim_head * heads |
| 119 | + project_out = not (heads == 1 and dim_head == dim) |
| 120 | + |
| 121 | + self.heads = heads |
| 122 | + self.scale = dim_head ** -0.5 |
| 123 | + self.rotary_emb = rotary_emb |
| 124 | + |
| 125 | + self.norm = nn.LayerNorm(dim) |
| 126 | + self.attend = nn.Softmax(dim = -1) |
| 127 | + self.dropout = nn.Dropout(dropout) |
| 128 | + |
| 129 | + self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) |
| 130 | + |
| 131 | + self.to_out = nn.Sequential( |
| 132 | + nn.Linear(inner_dim, dim), |
| 133 | + nn.Dropout(dropout) |
| 134 | + ) if project_out else nn.Identity() |
| 135 | + |
| 136 | + def forward(self, x, pos = None): |
| 137 | + x = self.norm(x) |
| 138 | + qkv = self.to_qkv(x).chunk(3, dim = -1) |
| 139 | + q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv) |
| 140 | + |
| 141 | + # Apply rotary embeddings if available |
| 142 | + if exists(self.rotary_emb): |
| 143 | + assert exists(pos) |
| 144 | + q = self.rotary_emb(q, pos) |
| 145 | + k = self.rotary_emb(k, pos) |
| 146 | + |
| 147 | + dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale |
| 148 | + |
| 149 | + attn = self.attend(dots) |
| 150 | + attn = self.dropout(attn) |
| 151 | + |
| 152 | + out = torch.matmul(attn, v) |
| 153 | + out = rearrange(out, 'b h n d -> b n (h d)') |
| 154 | + return self.to_out(out) |
| 155 | + |
| 156 | +class Transformer(Module): |
| 157 | + def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0., rotary_emb = None): |
| 158 | + super().__init__() |
| 159 | + self.norm = nn.LayerNorm(dim) |
| 160 | + self.layers = ModuleList([]) |
| 161 | + for _ in range(depth): |
| 162 | + self.layers.append(ModuleList([ |
| 163 | + Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout, rotary_emb = rotary_emb), |
| 164 | + FeedForward(dim, mlp_dim, dropout = dropout) |
| 165 | + ])) |
| 166 | + |
| 167 | + def forward(self, x, pos = None): |
| 168 | + for attn, ff in self.layers: |
| 169 | + x = attn(x, pos) + x |
| 170 | + x = ff(x) + x |
| 171 | + return self.norm(x) |
| 172 | + |
| 173 | +class ViTND(Module): |
| 174 | + def __init__( |
| 175 | + self, |
| 176 | + *, |
| 177 | + ndim: int, |
| 178 | + input_shape: int | tuple[int, ...], |
| 179 | + patch_size: int | tuple[int, ...], |
| 180 | + num_classes: int, |
| 181 | + dim: int, |
| 182 | + depth: int, |
| 183 | + heads: int, |
| 184 | + mlp_dim: int, |
| 185 | + channels: int = 3, |
| 186 | + dim_head: int = 64, |
| 187 | + dropout: float = 0., |
| 188 | + emb_dropout: float = 0., |
| 189 | + rope_min_freq: float = 1.0, |
| 190 | + rope_max_freq: float = 10000.0, |
| 191 | + rope_p_zero_freqs: float = 0.0 |
| 192 | + ): |
| 193 | + super().__init__() |
| 194 | + |
| 195 | + assert 1 <= ndim <= 7, 'ndim must be between 1 and 7' |
| 196 | + |
| 197 | + self.ndim = ndim |
| 198 | + |
| 199 | + input_shape = ensure_tuple(input_shape, ndim) |
| 200 | + patch_size = ensure_tuple(patch_size, ndim) |
| 201 | + |
| 202 | + for i, (inp_dim, patch_dim) in enumerate(zip(input_shape, patch_size)): |
| 203 | + assert inp_dim % patch_dim == 0, f'Input dimension {i} ({inp_dim}) must be divisible by patch size ({patch_dim})' |
| 204 | + |
| 205 | + num_patches_per_dim = [inp_dim // patch_dim for inp_dim, patch_dim in zip(input_shape, patch_size)] |
| 206 | + num_patches = 1 |
| 207 | + for n in num_patches_per_dim: |
| 208 | + num_patches *= n |
| 209 | + |
| 210 | + patch_dim = channels |
| 211 | + for p in patch_size: |
| 212 | + patch_dim *= p |
| 213 | + |
| 214 | + dim_names = 'fghijkl'[:ndim] |
| 215 | + |
| 216 | + input_dims = [f'({d} p{i})' for i, d in enumerate(dim_names)] |
| 217 | + patch_dims = [f'p{i}' for i in range(ndim)] |
| 218 | + |
| 219 | + input_pattern = f'b c {join(input_dims)}' |
| 220 | + output_pattern = f'b {join(dim_names)} ({join(patch_dims)} c)' |
| 221 | + rearrange_str = f'{input_pattern} -> {output_pattern}' |
| 222 | + |
| 223 | + rearrange_kwargs = {f'p{i}': p for i, p in enumerate(patch_size)} |
| 224 | + |
| 225 | + self.to_patch_embedding = nn.Sequential( |
| 226 | + Rearrange(rearrange_str, **rearrange_kwargs), |
| 227 | + nn.Linear(patch_dim, dim), |
| 228 | + nn.LayerNorm(dim), |
| 229 | + ) |
| 230 | + |
| 231 | + self.dropout = nn.Dropout(emb_dropout) |
| 232 | + |
| 233 | + # Create rotary embeddings |
| 234 | + self.rotary_emb = GoldenGateRoPENd( |
| 235 | + dim_pos = ndim, |
| 236 | + heads = heads, |
| 237 | + dim_head = dim_head, |
| 238 | + rope_min_freq = rope_min_freq, |
| 239 | + rope_max_freq = rope_max_freq, |
| 240 | + rope_p_zero_freqs = rope_p_zero_freqs |
| 241 | + ) |
| 242 | + |
| 243 | + self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout, rotary_emb = self.rotary_emb) |
| 244 | + |
| 245 | + self.to_latent = nn.Identity() |
| 246 | + self.mlp_head = nn.Linear(dim, num_classes) |
| 247 | + |
| 248 | + def forward(self, x): |
| 249 | + x = self.to_patch_embedding(x) # (b, *spatial_dims, patch_dim) |
| 250 | + |
| 251 | + batch, *spatial_dims, _, device = *x.shape, x.device |
| 252 | + |
| 253 | + # Generate position coordinates |
| 254 | + |
| 255 | + grids = [arange(d, device = device, dtype = torch.float32) for d in spatial_dims] |
| 256 | + grid = torch.meshgrid(*grids, indexing = 'ij') |
| 257 | + pos = stack(grid, dim = -1) # (*spatial_dims, ndim) |
| 258 | + |
| 259 | + # flatten spatial dimensions for attention with nd rotary |
| 260 | + |
| 261 | + pos = repeat(pos, '... p -> b (...) p', b = batch) |
| 262 | + x = rearrange(x, 'b ... d -> b (...) d') |
| 263 | + |
| 264 | + x = self.dropout(x) |
| 265 | + |
| 266 | + x = self.transformer(x, pos) |
| 267 | + |
| 268 | + x = reduce(x, 'b n d -> b d', 'mean') |
| 269 | + |
| 270 | + x = self.to_latent(x) |
| 271 | + return self.mlp_head(x) |
| 272 | + |
| 273 | + |
| 274 | +if __name__ == '__main__': |
| 275 | + |
| 276 | + model = ViTND( |
| 277 | + ndim = 5, |
| 278 | + input_shape = (4, 8, 16, 32, 64), |
| 279 | + patch_size = (2, 2, 4, 4, 8), |
| 280 | + num_classes = 1000, |
| 281 | + dim = 512, |
| 282 | + depth = 6, |
| 283 | + heads = 8, |
| 284 | + mlp_dim = 2048, |
| 285 | + channels = 3, |
| 286 | + dropout = 0.1, |
| 287 | + emb_dropout = 0.1 |
| 288 | + ) |
| 289 | + |
| 290 | + data = torch.randn(2, 3, 4, 8, 16, 32, 64) |
| 291 | + |
| 292 | + logits = model(data) |
0 commit comments