mask_decoder.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
  2. # pyre-unsafe
  3. from typing import List, Optional, Tuple, Type
  4. import torch
  5. from torch import nn
  6. from torch.nn import functional as F
  7. from .common import LayerNorm2d
  8. class MaskDecoder(nn.Module):
  9. def __init__(
  10. self,
  11. *,
  12. transformer_dim: int,
  13. transformer: nn.Module,
  14. num_multimask_outputs: int = 3,
  15. activation: Type[nn.Module] = nn.GELU,
  16. iou_head_depth: int = 3,
  17. iou_head_hidden_dim: int = 256,
  18. use_high_res_features: bool = False,
  19. iou_prediction_use_sigmoid=False,
  20. dynamic_multimask_via_stability=False,
  21. dynamic_multimask_stability_delta=0.05,
  22. dynamic_multimask_stability_thresh=0.98,
  23. pred_obj_scores: bool = False,
  24. pred_obj_scores_mlp: bool = False,
  25. use_multimask_token_for_obj_ptr: bool = False,
  26. ) -> None:
  27. """
  28. Predicts masks given an image and prompt embeddings, using a
  29. transformer architecture.
  30. Arguments:
  31. transformer_dim (int): the channel dimension of the transformer
  32. transformer (nn.Module): the transformer used to predict masks
  33. num_multimask_outputs (int): the number of masks to predict
  34. when disambiguating masks
  35. activation (nn.Module): the type of activation to use when
  36. upscaling masks
  37. iou_head_depth (int): the depth of the MLP used to predict
  38. mask quality
  39. iou_head_hidden_dim (int): the hidden dimension of the MLP
  40. used to predict mask quality
  41. """
  42. super().__init__()
  43. self.transformer_dim = transformer_dim
  44. self.transformer = transformer
  45. self.num_multimask_outputs = num_multimask_outputs
  46. self.iou_token = nn.Embedding(1, transformer_dim)
  47. self.num_mask_tokens = num_multimask_outputs + 1
  48. self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
  49. self.pred_obj_scores = pred_obj_scores
  50. if self.pred_obj_scores:
  51. self.obj_score_token = nn.Embedding(1, transformer_dim)
  52. self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
  53. self.output_upscaling = nn.Sequential(
  54. nn.ConvTranspose2d(
  55. transformer_dim, transformer_dim // 4, kernel_size=2, stride=2
  56. ),
  57. LayerNorm2d(transformer_dim // 4),
  58. activation(),
  59. nn.ConvTranspose2d(
  60. transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2
  61. ),
  62. activation(),
  63. )
  64. self.use_high_res_features = use_high_res_features
  65. if use_high_res_features:
  66. self.conv_s0 = nn.Conv2d(
  67. transformer_dim, transformer_dim // 8, kernel_size=1, stride=1
  68. )
  69. self.conv_s1 = nn.Conv2d(
  70. transformer_dim, transformer_dim // 4, kernel_size=1, stride=1
  71. )
  72. self.output_hypernetworks_mlps = nn.ModuleList(
  73. [
  74. MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
  75. for i in range(self.num_mask_tokens)
  76. ]
  77. )
  78. self.iou_prediction_head = MLP(
  79. transformer_dim,
  80. iou_head_hidden_dim,
  81. self.num_mask_tokens,
  82. iou_head_depth,
  83. sigmoid_output=iou_prediction_use_sigmoid,
  84. )
  85. if self.pred_obj_scores:
  86. self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
  87. if pred_obj_scores_mlp:
  88. self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
  89. # When outputting a single mask, optionally we can dynamically fall back to the best
  90. # multimask output token if the single mask output token gives low stability scores.
  91. self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
  92. self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
  93. self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
  94. def forward(
  95. self,
  96. image_embeddings: torch.Tensor,
  97. image_pe: torch.Tensor,
  98. sparse_prompt_embeddings: torch.Tensor,
  99. dense_prompt_embeddings: torch.Tensor,
  100. multimask_output: bool,
  101. repeat_image: bool,
  102. high_res_features: Optional[List[torch.Tensor]] = None,
  103. ) -> Tuple[torch.Tensor, torch.Tensor]:
  104. """
  105. Predict masks given image and prompt embeddings.
  106. Arguments:
  107. image_embeddings (torch.Tensor): the embeddings from the image encoder
  108. image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
  109. sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
  110. dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
  111. multimask_output (bool): Whether to return multiple masks or a single
  112. mask.
  113. Returns:
  114. torch.Tensor: batched predicted masks
  115. torch.Tensor: batched predictions of mask quality
  116. torch.Tensor: batched SAM token for mask output
  117. """
  118. masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
  119. image_embeddings=image_embeddings,
  120. image_pe=image_pe,
  121. sparse_prompt_embeddings=sparse_prompt_embeddings,
  122. dense_prompt_embeddings=dense_prompt_embeddings,
  123. repeat_image=repeat_image,
  124. high_res_features=high_res_features,
  125. )
  126. # Select the correct mask or masks for output
  127. if multimask_output:
  128. masks = masks[:, 1:, :, :]
  129. iou_pred = iou_pred[:, 1:]
  130. elif self.dynamic_multimask_via_stability and not self.training:
  131. masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
  132. else:
  133. masks = masks[:, 0:1, :, :]
  134. iou_pred = iou_pred[:, 0:1]
  135. if multimask_output and self.use_multimask_token_for_obj_ptr:
  136. sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
  137. else:
  138. # Take the mask output token. Here we *always* use the token for single mask output.
  139. # At test time, even if we track after 1-click (and using multimask_output=True),
  140. # we still take the single mask token here. The rationale is that we always track
  141. # after multiple clicks during training, so the past tokens seen during training
  142. # are always the single mask token (and we'll let it be the object-memory token).
  143. sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
  144. # Prepare output
  145. return masks, iou_pred, sam_tokens_out, object_score_logits
  146. def predict_masks(
  147. self,
  148. image_embeddings: torch.Tensor,
  149. image_pe: torch.Tensor,
  150. sparse_prompt_embeddings: torch.Tensor,
  151. dense_prompt_embeddings: torch.Tensor,
  152. repeat_image: bool,
  153. high_res_features: Optional[List[torch.Tensor]] = None,
  154. ) -> Tuple[torch.Tensor, torch.Tensor]:
  155. """Predicts masks. See 'forward' for more details."""
  156. # Concatenate output tokens
  157. s = 0
  158. if self.pred_obj_scores:
  159. output_tokens = torch.cat(
  160. [
  161. self.obj_score_token.weight,
  162. self.iou_token.weight,
  163. self.mask_tokens.weight,
  164. ],
  165. dim=0,
  166. )
  167. s = 1
  168. else:
  169. output_tokens = torch.cat(
  170. [self.iou_token.weight, self.mask_tokens.weight], dim=0
  171. )
  172. output_tokens = output_tokens.unsqueeze(0).expand(
  173. sparse_prompt_embeddings.size(0), -1, -1
  174. )
  175. tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
  176. # Expand per-image data in batch direction to be per-mask
  177. if repeat_image:
  178. src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
  179. else:
  180. assert image_embeddings.shape[0] == tokens.shape[0]
  181. src = image_embeddings
  182. src = src + dense_prompt_embeddings
  183. assert image_pe.size(0) == 1, (
  184. "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
  185. )
  186. pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
  187. b, c, h, w = src.shape
  188. # Run the transformer
  189. hs, src = self.transformer(src, pos_src, tokens)
  190. iou_token_out = hs[:, s, :]
  191. mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
  192. # Upscale mask embeddings and predict masks using the mask tokens
  193. src = src.transpose(1, 2).view(b, c, h, w)
  194. if not self.use_high_res_features:
  195. upscaled_embedding = self.output_upscaling(src)
  196. else:
  197. dc1, ln1, act1, dc2, act2 = self.output_upscaling
  198. feat_s0, feat_s1 = high_res_features
  199. upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
  200. upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
  201. hyper_in_list: List[torch.Tensor] = []
  202. for i in range(self.num_mask_tokens):
  203. hyper_in_list.append(
  204. self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])
  205. )
  206. hyper_in = torch.stack(hyper_in_list, dim=1)
  207. b, c, h, w = upscaled_embedding.shape
  208. masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
  209. # Generate mask quality predictions
  210. iou_pred = self.iou_prediction_head(iou_token_out)
  211. if self.pred_obj_scores:
  212. assert s == 1
  213. object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
  214. else:
  215. # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
  216. object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
  217. return masks, iou_pred, mask_tokens_out, object_score_logits
  218. def _get_stability_scores(self, mask_logits):
  219. """
  220. Compute stability scores of the mask logits based on the IoU between upper and
  221. lower thresholds.
  222. """
  223. mask_logits = mask_logits.flatten(-2)
  224. stability_delta = self.dynamic_multimask_stability_delta
  225. area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
  226. area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
  227. stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
  228. return stability_scores
  229. def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
  230. """
  231. When outputting a single mask, if the stability score from the current single-mask
  232. output (based on output token 0) falls below a threshold, we instead select from
  233. multi-mask outputs (based on output token 1~3) the mask with the highest predicted
  234. IoU score. This is intended to ensure a valid mask for both clicking and tracking.
  235. """
  236. # The best mask from multimask output tokens (1~3)
  237. multimask_logits = all_mask_logits[:, 1:, :, :]
  238. multimask_iou_scores = all_iou_scores[:, 1:]
  239. best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
  240. batch_inds = torch.arange(
  241. multimask_iou_scores.size(0), device=all_iou_scores.device
  242. )
  243. best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
  244. best_multimask_logits = best_multimask_logits.unsqueeze(1)
  245. best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
  246. best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
  247. # The mask from singlemask output token 0 and its stability score
  248. singlemask_logits = all_mask_logits[:, 0:1, :, :]
  249. singlemask_iou_scores = all_iou_scores[:, 0:1]
  250. stability_scores = self._get_stability_scores(singlemask_logits)
  251. is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
  252. # Dynamically fall back to best multimask output upon low stability scores.
  253. mask_logits_out = torch.where(
  254. is_stable[..., None, None].expand_as(singlemask_logits),
  255. singlemask_logits,
  256. best_multimask_logits,
  257. )
  258. iou_scores_out = torch.where(
  259. is_stable.expand_as(singlemask_iou_scores),
  260. singlemask_iou_scores,
  261. best_multimask_iou_scores,
  262. )
  263. return mask_logits_out, iou_scores_out
  264. # Lightly adapted from
  265. # https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
  266. class MLP(nn.Module):
  267. def __init__(
  268. self,
  269. input_dim: int,
  270. hidden_dim: int,
  271. output_dim: int,
  272. num_layers: int,
  273. sigmoid_output: bool = False,
  274. ) -> None:
  275. super().__init__()
  276. self.num_layers = num_layers
  277. h = [hidden_dim] * (num_layers - 1)
  278. self.layers = nn.ModuleList(
  279. nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
  280. )
  281. self.sigmoid_output = sigmoid_output
  282. def forward(self, x):
  283. for i, layer in enumerate(self.layers):
  284. x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
  285. if self.sigmoid_output:
  286. x = F.sigmoid(x)
  287. return x