| 1 | import copy |
| 2 | from dataclasses import dataclass |
| 3 | from typing import List, Optional, Tuple, Type, Union |
| 4 | |
| 5 | import mlx.core as mx |
| 6 | import mlx.nn as nn |
| 7 | import numpy as np |
| 8 | from scipy.ndimage import zoom |
| 9 | |
| 10 | |
| 11 | @dataclass |
| 12 | class SAMViTCfg: |
| 13 | image_size: Union[Tuple[int, int], int] = 1024 |
| 14 | width: int = 768 |
| 15 | layers: int = 12 |
| 16 | heads: int = 12 |
| 17 | patch_size: int = 16 |
| 18 | window_size: int = 14 |
| 19 | prompt_embed_dim: int = 256 |
| 20 | global_attn_indexes: Union[List[int], Tuple[int]] = (2, 5, 8, 11) |
| 21 | downsample_channels: Union[List[int], Tuple[int]] = (512, 1024) |
| 22 | |
| 23 | |
| 24 | class MLPBlock(nn.Module): |
| 25 | def __init__( |
| 26 | self, |
| 27 | embedding_dim: int, |
| 28 | mlp_dim: int, |
| 29 | act: Type[nn.Module] = nn.GELU, |
| 30 | ) -> None: |
| 31 | super().__init__() |
| 32 | self.lin1 = nn.Linear(embedding_dim, mlp_dim) |
| 33 | self.lin2 = nn.Linear(mlp_dim, embedding_dim) |
| 34 | self.act = act() |
| 35 | |
| 36 | def __call__(self, x: mx.array): |
| 37 | return self.lin2(self.act(self.lin1(x))) |
| 38 | |
| 39 | |
| 40 | def resize_image(image_np, new_size=(96, 96), order=1): |
| 41 | """ |
| 42 | Resize an image with multiple channels using bilinear interpolation. |
| 43 | Args: |
| 44 | image_np (numpy.ndarray): The input image array of shape (channels, height, width). |
| 45 | new_size (tuple): The target size as (height, width). |
| 46 | order (int): The order of the spline interpolation, 1 is bilinear. |
| 47 | |
| 48 | Returns: |
| 49 | numpy.ndarray: The resized image array. |
| 50 | """ |
| 51 | image_np = np.array(image_np[0]) |
| 52 | |
| 53 | # Calculate zoom factors for the spatial dimensions only |
| 54 | height_factor = new_size[0] / image_np.shape[1] |
| 55 | width_factor = new_size[1] / image_np.shape[2] |
| 56 | zoom_factors = (height_factor, width_factor) # Apply zoom to height and width only |
| 57 | |
| 58 | # Resize each channel separately and collect them in a list |
| 59 | resized_channels = [] |
| 60 | for channel in range(image_np.shape[0]): |
| 61 | # Apply zoom to the current channel and append to the list |
| 62 | resized_channel = zoom(image_np[channel], zoom_factors, order=order) |
| 63 | resized_channels.append(resized_channel) |
| 64 | |
| 65 | # Stack the resized channels back into a single array |
| 66 | resized_image_np = np.stack(resized_channels, axis=0) |
| 67 | |
| 68 | return mx.array(resized_image_np)[None, :] |
| 69 | |
| 70 | |
| 71 | class SAMEncoder(nn.Module): |
| 72 | def __init__( |
| 73 | self, |
| 74 | img_size: int = 1024, |
| 75 | patch_size: int = 16, |
| 76 | in_chans: int = 3, |
| 77 | embed_dim: int = 768, |
| 78 | depth: int = 12, |
| 79 | num_heads: int = 12, |
| 80 | mlp_ratio: float = 4.0, |
| 81 | out_chans: int = 256, |
| 82 | qkv_bias: bool = True, |
| 83 | norm_layer: Type[nn.Module] = nn.LayerNorm, |
| 84 | act_layer: Type[nn.Module] = nn.GELU, |
| 85 | use_abs_pos: bool = True, |
| 86 | use_rel_pos: bool = True, |
| 87 | rel_pos_zero_init: bool = True, |
| 88 | window_size: int = 14, |
| 89 | global_attn_indexes: Tuple[int, ...] = (2, 5, 8, 11), |
| 90 | downsample_channels: Tuple[int, ...] = (512, 1024), |
| 91 | ) -> None: |
| 92 | """ |
| 93 | Args: |
| 94 | img_size (int): Input image size. |
| 95 | patch_size (int): Patch size. |
| 96 | in_chans (int): Number of input image channels. |
| 97 | embed_dim (int): Patch embedding dimension. |
| 98 | depth (int): Depth of ViT. |
| 99 | num_heads (int): Number of attention heads in each ViT block. |
| 100 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. |
| 101 | qkv_bias (bool): If True, add a learnable bias to query, key, value. |
| 102 | norm_layer (nn.Module): Normalization layer. |
| 103 | act_layer (nn.Module): Activation layer. |
| 104 | use_abs_pos (bool): If True, use absolute positional embeddings. |
| 105 | use_rel_pos (bool): If True, add relative positional embeddings to the attention map. |
| 106 | rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. |
| 107 | window_size (int): Window size for window attention blocks. |
| 108 | global_attn_indexes (list): Indexes for blocks using global attention. |
| 109 | downsample_channels (list): Channels for downsampling layers. |
| 110 | """ |
| 111 | super().__init__() |
| 112 | self.img_size = img_size |
| 113 | |
| 114 | self.patch_embed = PatchEmbed( |
| 115 | kernel_size=(patch_size, patch_size), |
| 116 | stride=(patch_size, patch_size), |
| 117 | in_chans=in_chans, |
| 118 | embed_dim=embed_dim, |
| 119 | ) |
| 120 | |
| 121 | if use_abs_pos: |
| 122 | # Initialize absolute positional embedding with pretrain image size. |
| 123 | self.pos_embed = mx.zeros( |
| 124 | (img_size // patch_size, img_size // patch_size, embed_dim) |
| 125 | )[None, :] |
| 126 | |
| 127 | self.blocks = [] |
| 128 | for i in range(depth): |
| 129 | block = Block( |
| 130 | dim=embed_dim, |
| 131 | num_heads=num_heads, |
| 132 | mlp_ratio=mlp_ratio, |
| 133 | qkv_bias=qkv_bias, |
| 134 | norm_layer=norm_layer, |
| 135 | act_layer=act_layer, |
| 136 | use_rel_pos=use_rel_pos, |
| 137 | rel_pos_zero_init=rel_pos_zero_init, |
| 138 | window_size=window_size if i not in global_attn_indexes else 0, |
| 139 | input_size=(img_size // patch_size, img_size // patch_size), |
| 140 | ) |
| 141 | self.blocks.append(block) |
| 142 | |
| 143 | self.neck = [ |
| 144 | nn.Conv2d( |
| 145 | embed_dim, |
| 146 | out_chans, |
| 147 | kernel_size=1, |
| 148 | bias=False, |
| 149 | ), |
| 150 | nn.LayerNorm(out_chans), |
| 151 | nn.Conv2d( |
| 152 | out_chans, |
| 153 | out_chans, |
| 154 | kernel_size=3, |
| 155 | padding=1, |
| 156 | bias=False, |
| 157 | ), |
| 158 | nn.LayerNorm(out_chans), |
| 159 | ] |
| 160 | |
| 161 | in_channels = out_chans |
| 162 | self.downsamples = [] |
| 163 | for i in range(len(downsample_channels)): |
| 164 | out_channels = downsample_channels[i] |
| 165 | self.downsamples.append( |
| 166 | nn.Conv2d( |
| 167 | in_channels, |
| 168 | out_channels, |
| 169 | kernel_size=3, |
| 170 | stride=2, |
| 171 | padding=1, |
| 172 | bias=False, |
| 173 | ) |
| 174 | ) |
| 175 | in_channels = out_channels |
| 176 | |
| 177 | self.sam_hd = True |
| 178 | if self.sam_hd: |
| 179 | self.hd_alpha_downsamples = mx.zeros((1)) |
| 180 | self.neck_hd = copy.deepcopy(self.neck) |
| 181 | |
| 182 | def __call__(self, x: mx.array): |
| 183 | x = self.patch_embed(x) |
| 184 | if self.pos_embed is not None: |
| 185 | x += self.pos_embed |
| 186 | |
| 187 | global_features = [] |
| 188 | for _, blk in enumerate(self.blocks): |
| 189 | x = blk(x) |
| 190 | if self.sam_hd and blk.window_size == 0: |
| 191 | global_features.append(x) |
| 192 | |
| 193 | for _, n in enumerate(self.neck): |
| 194 | x = n(x) |
| 195 | |
| 196 | x = x.transpose(0, 3, 1, 2) |
| 197 | x = resize_image(x) |
| 198 | |
| 199 | x = x.transpose(0, 2, 3, 1) |
| 200 | |
| 201 | for _, downsample in enumerate(self.downsamples): |
| 202 | x = downsample(x) |
| 203 | |
| 204 | if self.sam_hd: |
| 205 | first_global_feature = global_features[0] |
| 206 | for _, n_hd in enumerate(self.neck_hd): |
| 207 | first_global_feature = n_hd(first_global_feature) |
| 208 | |
| 209 | first_global_feature = first_global_feature.transpose(0, 3, 1, 2) |
| 210 | |
| 211 | first_global_feature = resize_image(first_global_feature) |
| 212 | |
| 213 | first_global_feature = first_global_feature.transpose(0, 2, 3, 1) |
| 214 | for _, downsample in enumerate(self.downsamples): |
| 215 | first_global_feature = downsample(first_global_feature) |
| 216 | |
| 217 | x = x + first_global_feature * self.hd_alpha_downsamples |
| 218 | |
| 219 | return x |
| 220 | |
| 221 | |
| 222 | class Block(nn.Module): |
| 223 | """Transformer blocks with support of window attention and residual propagation blocks""" |
| 224 | |
| 225 | def __init__( |
| 226 | self, |
| 227 | dim: int, |
| 228 | num_heads: int, |
| 229 | mlp_ratio: float = 4.0, |
| 230 | qkv_bias: bool = True, |
| 231 | norm_layer: Type[nn.Module] = nn.LayerNorm, |
| 232 | act_layer: Type[nn.Module] = nn.GELU, |
| 233 | use_rel_pos: bool = False, |
| 234 | rel_pos_zero_init: bool = True, |
| 235 | window_size: int = 0, |
| 236 | input_size: Optional[Tuple[int, int]] = None, |
| 237 | ) -> None: |
| 238 | """ |
| 239 | Args: |
| 240 | dim (int): Number of input channels. |
| 241 | num_heads (int): Number of attention heads in each ViT block. |
| 242 | mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. |
| 243 | qkv_bias (bool): If True, add a learnable bias to query, key, value. |
| 244 | norm_layer (nn.Module): Normalization layer. |
| 245 | act_layer (nn.Module): Activation layer. |
| 246 | use_rel_pos (bool): If True, add relative positional embeddings to the attention map. |
| 247 | rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. |
| 248 | window_size (int): Window size for window attention blocks. If it equals 0, then |
| 249 | use global attention. |
| 250 | input_size (tuple(int, int) or None): Input resolution for calculating the relative |
| 251 | positional parameter size. |
| 252 | """ |
| 253 | super().__init__() |
| 254 | self.norm1 = norm_layer(dim) |
| 255 | self.attn = Attention( |
| 256 | dim, |
| 257 | num_heads=num_heads, |
| 258 | qkv_bias=qkv_bias, |
| 259 | use_rel_pos=use_rel_pos, |
| 260 | rel_pos_zero_init=rel_pos_zero_init, |
| 261 | input_size=input_size if window_size == 0 else (window_size, window_size), |
| 262 | ) |
| 263 | |
| 264 | self.norm2 = norm_layer(dim) |
| 265 | self.mlp = MLPBlock( |
| 266 | embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer |
| 267 | ) |
| 268 | |
| 269 | self.window_size = window_size |
| 270 | |
| 271 | def __call__(self, x: mx.array): |
| 272 | shortcut = x |
| 273 | x = self.norm1(x) |
| 274 | # Window partition |
| 275 | if self.window_size > 0: |
| 276 | H, W = x.shape[1], x.shape[2] |
| 277 | x, pad_hw = window_partition(x, self.window_size) |
| 278 | |
| 279 | x = self.attn(x) |
| 280 | # Reverse window partition |
| 281 | if self.window_size > 0: |
| 282 | x = window_unpartition(x, self.window_size, pad_hw, (H, W)) |
| 283 | |
| 284 | x = shortcut + x |
| 285 | x = x + self.mlp(self.norm2(x)) |
| 286 | |
| 287 | return x |
| 288 | |
| 289 | |
| 290 | class Attention(nn.Module): |
| 291 | """Multi-head Attention block with relative position embeddings.""" |
| 292 | |
| 293 | def __init__( |
| 294 | self, |
| 295 | dim: int, |
| 296 | num_heads: int = 8, |
| 297 | qkv_bias: bool = True, |
| 298 | use_rel_pos: bool = False, |
| 299 | rel_pos_zero_init: bool = True, |
| 300 | input_size: Optional[Tuple[int, int]] = None, |
| 301 | ) -> None: |
| 302 | """ |
| 303 | Args: |
| 304 | dim (int): Number of input channels. |
| 305 | num_heads (int): Number of attention heads. |
| 306 | qkv_bias (bool): If True, add a learnable bias to query, key, value. |
| 307 | rel_pos (bool): If True, add relative positional embeddings to the attention map. |
| 308 | rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. |
| 309 | input_size (tuple(int, int) or None): Input resolution for calculating the relative |
| 310 | positional parameter size. |
| 311 | """ |
| 312 | super().__init__() |
| 313 | self.num_heads = num_heads |
| 314 | head_dim = dim // num_heads |
| 315 | self.scale = head_dim**-0.5 |
| 316 | |
| 317 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) |
| 318 | self.proj = nn.Linear(dim, dim) |
| 319 | |
| 320 | self.use_rel_pos = use_rel_pos |
| 321 | if self.use_rel_pos: |
| 322 | assert ( |
| 323 | input_size is not None |
| 324 | ), "Input size must be provided if using relative positional encoding." |
| 325 | # initialize relative positional embeddings |
| 326 | |
| 327 | self.rel_pos_h = mx.zeros((2 * input_size[0] - 1, head_dim)) |
| 328 | self.rel_pos_w = mx.zeros((2 * input_size[1] - 1, head_dim)) |
| 329 | |
| 330 | def __call__(self, x: mx.array): |
| 331 | B, H, W, _ = x.shape |
| 332 | x = mx.array(x) |
| 333 | # qkv with shape (3, B, nHead, H * W, C) |
| 334 | qkv = ( |
| 335 | self.qkv(x) |
| 336 | .reshape(B, H * W, 3, self.num_heads, -1) |
| 337 | .transpose(2, 0, 3, 1, 4) |
| 338 | ) |
| 339 | # q, k, v with shape (B * nHead, H * W, C) |
| 340 | q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1) |
| 341 | |
| 342 | def do_attention(q, k, v): |
| 343 | attn = (q * self.scale) @ k.transpose(0, -1, -2) |
| 344 | if self.use_rel_pos: |
| 345 | attn = add_decomposed_rel_pos( |
| 346 | attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W) |
| 347 | ) |
| 348 | |
| 349 | attn = mx.softmax(attn, axis=-1) |
| 350 | x = ( |
| 351 | (attn @ v) |
| 352 | .reshape(B, self.num_heads, H, W, -1) |
| 353 | .transpose(0, 2, 3, 1, 4) |
| 354 | .reshape(B, H, W, -1) |
| 355 | ) |
| 356 | |
| 357 | return x |
| 358 | |
| 359 | x = do_attention(q, k, v) |
| 360 | x = self.proj(x) |
| 361 | |
| 362 | return x |
| 363 | |
| 364 | |
| 365 | def window_partition( |
| 366 | x: np.ndarray, window_size: int |
| 367 | ) -> Tuple[np.ndarray, Tuple[int, int]]: |
| 368 | """ |
| 369 | Partition into non-overlapping windows with padding if needed. |
| 370 | Args: |
| 371 | x (ndarray): input tokens with [B, H, W, C]. |
| 372 | window_size (int): window size. |
| 373 | |
| 374 | Returns: |
| 375 | windows: windows after partition with [B * num_windows, window_size, window_size, C]. |
| 376 | (Hp, Wp): padded height and width before partition |
| 377 | """ |
| 378 | B, H, W, C = x.shape |
| 379 | |
| 380 | pad_h = (window_size - H % window_size) % window_size |
| 381 | pad_w = (window_size - W % window_size) % window_size |
| 382 | if pad_h > 0 or pad_w > 0: |
| 383 | x = np.pad(x, ((0, 0), (0, pad_h), (0, pad_w), (0, 0))) |
| 384 | Hp, Wp = H + pad_h, W + pad_w |
| 385 | |
| 386 | x = x.reshape(B, Hp // window_size, window_size, Wp // window_size, window_size, C) |
| 387 | windows = x.transpose(0, 1, 3, 2, 4, 5).reshape(-1, window_size, window_size, C) |
| 388 | return windows, (Hp, Wp) |
| 389 | |
| 390 | |
| 391 | def window_unpartition( |
| 392 | windows: np.ndarray, |
| 393 | window_size: int, |
| 394 | pad_hw: Tuple[int, int], |
| 395 | hw: Tuple[int, int], |
| 396 | ): |
| 397 | """ |
| 398 | Window unpartition into original sequences and removing padding. |
| 399 | Args: |
| 400 | windows (ndarray): input tokens with [B * num_windows, window_size, window_size, C]. |
| 401 | window_size (int): window size. |
| 402 | pad_hw (Tuple): padded height and width (Hp, Wp). |
| 403 | hw (Tuple): original height and width (H, W) before padding. |
| 404 | |
| 405 | Returns: |
| 406 | x: unpartitioned sequences with [B, H, W, C]. |
| 407 | """ |
| 408 | Hp, Wp = pad_hw |
| 409 | H, W = hw |
| 410 | B = windows.shape[0] // (Hp * Wp // window_size // window_size) |
| 411 | x = windows.reshape( |
| 412 | B, Hp // window_size, Wp // window_size, window_size, window_size, -1 |
| 413 | ) |
| 414 | x = x.transpose(0, 1, 3, 2, 4, 5).reshape(B, Hp, Wp, -1) |
| 415 | |
| 416 | if Hp > H or Wp > W: |
| 417 | x = x[:, :H, :W, :] |
| 418 | return x |
| 419 | |
| 420 | |
| 421 | def get_rel_pos(q_size: int, k_size: int, rel_pos: np.ndarray) -> np.ndarray: |
| 422 | """ |
| 423 | Get relative positional embeddings according to the relative positions of |
| 424 | query and key sizes. |
| 425 | Args: |
| 426 | q_size (int): size of query q. |
| 427 | k_size (int): size of key k. |
| 428 | rel_pos (ndarray): relative position embeddings (L, C). |
| 429 | |
| 430 | Returns: |
| 431 | Extracted positional embeddings according to relative positions. |
| 432 | """ |
| 433 | rel_pos = np.array(rel_pos) |
| 434 | max_rel_dist = int(2 * max(q_size, k_size) - 1) |
| 435 | # Interpolate rel pos if needed. |
| 436 | if rel_pos.shape[0] != max_rel_dist: |
| 437 | # Interpolate rel pos. |
| 438 | rel_pos_resized = np.expand_dims(rel_pos, axis=0) |
| 439 | rel_pos_resized = np.transpose(rel_pos_resized, (0, 2, 1)) |
| 440 | rel_pos_resized = np.interp( |
| 441 | np.linspace(0, max_rel_dist - 1, num=max_rel_dist), |
| 442 | np.arange(rel_pos.shape[0]), |
| 443 | rel_pos_resized[0], |
| 444 | ) |
| 445 | rel_pos_resized = np.transpose(rel_pos_resized, (1, 0)) |
| 446 | else: |
| 447 | rel_pos_resized = rel_pos |
| 448 | |
| 449 | # Scale the coords with short length if shapes for q and k are different. |
| 450 | q_coords = np.arange(q_size)[:, np.newaxis] * max(k_size / q_size, 1.0) |
| 451 | k_coords = np.arange(k_size)[np.newaxis, :] * max(q_size / k_size, 1.0) |
| 452 | relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) |
| 453 | relative_coords = relative_coords.astype(np.int64) |
| 454 | return rel_pos_resized[relative_coords] |
| 455 | |
| 456 | |
| 457 | def add_decomposed_rel_pos( |
| 458 | attn: np.ndarray, |
| 459 | q: np.ndarray, |
| 460 | rel_pos_h: np.ndarray, |
| 461 | rel_pos_w: np.ndarray, |
| 462 | q_size: Tuple[int, int], |
| 463 | k_size: Tuple[int, int], |
| 464 | ) -> np.ndarray: |
| 465 | """ |
| 466 | Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. |
| 467 | https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 |
| 468 | Args: |
| 469 | attn (ndarray): attention map. |
| 470 | q (ndarray): query q in the attention layer with shape (B, q_h * q_w, C). |
| 471 | rel_pos_h (ndarray): relative position embeddings (Lh, C) for height axis. |
| 472 | rel_pos_w (ndarray): relative position embeddings (Lw, C) for width axis. |
| 473 | q_size (Tuple): spatial sequence size of query q with (q_h, q_w). |
| 474 | k_size (Tuple): spatial sequence size of key k with (k_h, k_w). |
| 475 | |
| 476 | Returns: |
| 477 | attn (ndarray): attention map with added relative positional embeddings. |
| 478 | """ |
| 479 | q_h, q_w = q_size |
| 480 | k_h, k_w = k_size |
| 481 | Rh = get_rel_pos(q_h, k_h, rel_pos_h) |
| 482 | Rw = get_rel_pos(q_w, k_w, rel_pos_w) |
| 483 | |
| 484 | B, _, dim = q.shape |
| 485 | r_q = q.reshape(B, q_h, q_w, dim) |
| 486 | |
| 487 | rel_h = np.einsum("bhwc,hkc->bhwk", r_q, Rh) |
| 488 | rel_w = np.einsum("bhwc,wkc->bhwk", r_q, Rw) |
| 489 | |
| 490 | attn = ( |
| 491 | attn.reshape(B, q_h, q_w, k_h, k_w) |
| 492 | + rel_h[:, :, :, :, np.newaxis] |
| 493 | + rel_w[:, :, :, np.newaxis, :] |
| 494 | ).reshape(B, q_h * q_w, k_h * k_w) |
| 495 | |
| 496 | return attn |
| 497 | |
| 498 | |
| 499 | class PatchEmbed(nn.Module): |
| 500 | """ |
| 501 | Image to Patch Embedding. |
| 502 | """ |
| 503 | |
| 504 | def __init__( |
| 505 | self, |
| 506 | kernel_size: Tuple[int, int] = (16, 16), |
| 507 | stride: Tuple[int, int] = (16, 16), |
| 508 | in_chans: int = 3, |
| 509 | embed_dim: int = 768, |
| 510 | ) -> None: |
| 511 | """ |
| 512 | Args: |
| 513 | kernel_size (Tuple): kernel size of the projection layer. |
| 514 | stride (Tuple): stride of the projection layer. |
| 515 | padding (Tuple): padding size of the projection layer. |
| 516 | in_chans (int): Number of input image channels. |
| 517 | embed_dim (int): Patch embedding dimension. |
| 518 | """ |
| 519 | super().__init__() |
| 520 | |
| 521 | self.proj = nn.Conv2d( |
| 522 | in_chans, embed_dim, kernel_size=kernel_size, stride=stride |
| 523 | ) |
| 524 | |
| 525 | def __call__(self, x: mx.array): |
| 526 | x = self.proj(x) |
| 527 | return x |