modeling_seggpt.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch SegGpt model."""
  16. import collections.abc
  17. from dataclasses import dataclass
  18. from typing import Optional, Union
  19. import torch
  20. from torch import nn
  21. from torch.nn import functional as F
  22. from ...activations import ACT2FN
  23. from ...modeling_layers import GradientCheckpointingLayer
  24. from ...modeling_utils import PreTrainedModel
  25. from ...utils import ModelOutput, auto_docstring, logging, torch_int
  26. from .configuration_seggpt import SegGptConfig
  27. logger = logging.get_logger(__name__)
  28. @dataclass
  29. @auto_docstring(
  30. custom_intro="""
  31. Output type of [`SegGptEncoderOutput`].
  32. """
  33. )
  34. class SegGptEncoderOutput(ModelOutput):
  35. r"""
  36. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, patch_height, patch_width, hidden_size)`):
  37. Sequence of hidden-states at the output of the last layer of the model.
  38. hidden_states (`tuple[torch.FloatTensor]`, `optional`, returned when `config.output_hidden_states=True`):
  39. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
  40. of shape `(batch_size, patch_height, patch_width, hidden_size)`.
  41. attentions (`tuple[torch.FloatTensor]`, `optional`, returned when `config.output_attentions=True`):
  42. Tuple of *torch.FloatTensor* (one for each layer) of shape
  43. `(batch_size, num_heads, seq_len, seq_len)`.
  44. intermediate_hidden_states (`tuple[torch.FloatTensor]`, *optional*, returned when `config.intermediate_hidden_state_indices` is set):
  45. Tuple of `torch.FloatTensor` of shape `(batch_size, patch_height, patch_width, hidden_size)`.
  46. Each element in the Tuple corresponds to the output of the layer specified in `config.intermediate_hidden_state_indices`.
  47. Additionally, each feature passes through a LayerNorm.
  48. """
  49. last_hidden_state: torch.FloatTensor
  50. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  51. attentions: Optional[tuple[torch.FloatTensor]] = None
  52. intermediate_hidden_states: Optional[tuple[torch.FloatTensor]] = None
  53. @dataclass
  54. @auto_docstring(
  55. custom_intro="""
  56. Output type of [`SegGptImageSegmentationOutput`].
  57. """
  58. )
  59. class SegGptImageSegmentationOutput(ModelOutput):
  60. r"""
  61. loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
  62. The loss value.
  63. pred_masks (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  64. The predicted masks.
  65. hidden_states (`tuple[torch.FloatTensor]`, `optional`, returned when `config.output_hidden_states=True`):
  66. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
  67. of shape `(batch_size, patch_height, patch_width, hidden_size)`.
  68. attentions (`tuple[torch.FloatTensor]`, `optional`, returned when `config.output_attentions=True`):
  69. Tuple of `torch.FloatTensor` (one for each layer) of shape
  70. `(batch_size, num_heads, seq_len, seq_len)`.
  71. """
  72. loss: Optional[torch.FloatTensor] = None
  73. pred_masks: Optional[torch.FloatTensor] = None
  74. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  75. attentions: Optional[tuple[torch.FloatTensor]] = None
  76. # Copied from transformers.models.sam.modeling_sam.SamPatchEmbeddings with Sam->SegGpt
  77. class SegGptPatchEmbeddings(nn.Module):
  78. """
  79. This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
  80. `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
  81. Transformer.
  82. """
  83. def __init__(self, config):
  84. super().__init__()
  85. image_size, patch_size = config.image_size, config.patch_size
  86. num_channels, hidden_size = config.num_channels, config.hidden_size
  87. image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
  88. patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
  89. num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  90. self.image_size = image_size
  91. self.patch_size = patch_size
  92. self.num_channels = num_channels
  93. self.num_patches = num_patches
  94. self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
  95. def forward(self, pixel_values):
  96. batch_size, num_channels, height, width = pixel_values.shape
  97. if num_channels != self.num_channels:
  98. raise ValueError(
  99. "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
  100. )
  101. if height != self.image_size[0] or width != self.image_size[1]:
  102. raise ValueError(
  103. f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
  104. )
  105. embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
  106. return embeddings
  107. class SegGptEmbeddings(nn.Module):
  108. """
  109. Construct the embeddings from patch, position embeddings for input and prompt.
  110. """
  111. def __init__(self, config: SegGptConfig) -> None:
  112. super().__init__()
  113. self.mask_token = nn.Parameter(torch.zeros(1, 1, 1, config.hidden_size))
  114. self.segment_token_input = nn.Parameter(torch.zeros(1, 1, 1, config.hidden_size))
  115. self.segment_token_prompt = nn.Parameter(torch.zeros(1, 1, 1, config.hidden_size))
  116. # token for seg types
  117. self.type_token_semantic = nn.Parameter(torch.zeros(1, 1, 1, config.hidden_size))
  118. self.type_token_instance = nn.Parameter(torch.zeros(1, 1, 1, config.hidden_size))
  119. self.patch_embeddings = SegGptPatchEmbeddings(config)
  120. num_positions = (config.pretrain_image_size // config.patch_size) ** 2 + 1
  121. self.position_embeddings = nn.Parameter(torch.randn(1, num_positions, config.hidden_size))
  122. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  123. def interpolate_pos_encoding(self, height: int, width: int) -> torch.Tensor:
  124. patch_pos_embed = self.position_embeddings[:, 1:]
  125. num_patches = patch_pos_embed.shape[1]
  126. pretrain_patch_size = torch_int(num_patches**0.5)
  127. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  128. if torch.jit.is_tracing() or pretrain_patch_size != height or pretrain_patch_size != width:
  129. patch_pos_embed = F.interpolate(
  130. patch_pos_embed.reshape(1, pretrain_patch_size, pretrain_patch_size, -1).permute(0, 3, 1, 2),
  131. size=(height, width),
  132. mode="bicubic",
  133. align_corners=False,
  134. )
  135. return patch_pos_embed.permute(0, 2, 3, 1)
  136. else:
  137. return patch_pos_embed.reshape(1, height, width, -1)
  138. def forward(
  139. self,
  140. pixel_values: torch.Tensor,
  141. prompt_pixel_values: torch.Tensor,
  142. bool_masked_pos: Optional[torch.BoolTensor] = None,
  143. embedding_type: Optional[str] = None,
  144. ) -> torch.Tensor:
  145. input_embeddings = self.patch_embeddings(pixel_values)
  146. prompt_embeddings = self.patch_embeddings(prompt_pixel_values)
  147. batch_size, patch_height, patch_width, _ = input_embeddings.shape
  148. mask_token = self.mask_token.expand(batch_size, patch_height, patch_width, -1)
  149. # replace the masked visual tokens by mask_token
  150. w = bool_masked_pos.unsqueeze(-1).type_as(mask_token).reshape(-1, patch_height, patch_width, 1)
  151. prompt_embeddings = prompt_embeddings * (1 - w) + mask_token * w
  152. embedding_type = embedding_type if embedding_type is not None else "instance"
  153. # add positional encoding to each token
  154. pos_embed = self.interpolate_pos_encoding(patch_height, patch_width)
  155. # add segment token
  156. input_embeddings = input_embeddings + self.segment_token_input
  157. prompt_embeddings = prompt_embeddings + self.segment_token_prompt
  158. # add position embedding skipping CLS
  159. input_embeddings = input_embeddings + pos_embed
  160. prompt_embeddings = prompt_embeddings + pos_embed
  161. # add type embedding to each token
  162. if embedding_type == "semantic":
  163. type_embedding = self.type_token_semantic
  164. elif embedding_type == "instance":
  165. type_embedding = self.type_token_instance
  166. else:
  167. raise ValueError(f"Embedding type should be either 'semantic' or 'instance', but got {embedding_type}")
  168. input_embeddings = input_embeddings + type_embedding
  169. prompt_embeddings = prompt_embeddings + type_embedding
  170. embeddings = torch.cat((input_embeddings, prompt_embeddings), dim=0)
  171. return embeddings
  172. class SegGptAttention(nn.Module):
  173. """Multi-head Attention block with relative position embeddings."""
  174. def __init__(self, config):
  175. super().__init__()
  176. image_size, patch_size = config.image_size, config.patch_size
  177. image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
  178. patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
  179. input_size = (image_size[0] // config.patch_size, image_size[1] // config.patch_size)
  180. head_dim = config.hidden_size // config.num_attention_heads
  181. self.num_attention_heads = config.num_attention_heads
  182. self.scale = head_dim**-0.5
  183. self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
  184. self.proj = nn.Linear(config.hidden_size, config.hidden_size)
  185. self.use_relative_position_embeddings = config.use_relative_position_embeddings
  186. if self.use_relative_position_embeddings:
  187. if input_size is None:
  188. raise ValueError("Input size must be provided if using relative positional encoding.")
  189. # initialize relative positional embeddings
  190. self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
  191. self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
  192. def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
  193. """
  194. Get relative positional embeddings according to the relative positions of
  195. query and key sizes.
  196. Args:
  197. q_size (int):
  198. size of the query.
  199. k_size (int):
  200. size of key k.
  201. rel_pos (`torch.Tensor`):
  202. relative position embeddings (L, channel).
  203. Returns:
  204. Extracted positional embeddings according to relative positions.
  205. """
  206. max_rel_dist = int(2 * max(q_size, k_size) - 1)
  207. # Interpolate rel pos.
  208. rel_pos_resized = F.interpolate(
  209. rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
  210. size=max_rel_dist,
  211. mode="linear",
  212. )
  213. rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
  214. # Scale the coords with short length if shapes for q and k are different.
  215. q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
  216. k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
  217. relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
  218. return rel_pos_resized[relative_coords.long()]
  219. def add_decomposed_rel_pos(
  220. self,
  221. attn: torch.Tensor,
  222. query: torch.Tensor,
  223. rel_pos_h: torch.Tensor,
  224. rel_pos_w: torch.Tensor,
  225. q_size: tuple[int, int],
  226. k_size: tuple[int, int],
  227. ) -> torch.Tensor:
  228. """
  229. Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
  230. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
  231. Args:
  232. attn (`torch.Tensor`):
  233. attention map.
  234. query (`torch.Tensor`):
  235. query q in the attention layer with shape (batch_size, query_height * query_width, channel).
  236. rel_pos_h (`torch.Tensor`):
  237. relative position embeddings (Lh, channel) for height axis.
  238. rel_pos_w (`torch.Tensor`):
  239. relative position embeddings (Lw, channel) for width axis.
  240. q_size (tuple):
  241. spatial sequence size of query q with (query_height, query_width).
  242. k_size (tuple):
  243. spatial sequence size of key k with (key_height, key_width).
  244. Returns:
  245. attn (`torch.Tensor`):
  246. attention map with added relative positional embeddings.
  247. """
  248. query_height, query_width = q_size
  249. key_height, key_width = k_size
  250. relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
  251. relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
  252. batch_size, _, dim = query.shape
  253. reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
  254. rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
  255. rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
  256. attn = attn.reshape(batch_size, query_height, query_width, key_height, key_width)
  257. attn = attn + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
  258. attn = attn.reshape(batch_size, query_height * query_width, key_height * key_width)
  259. return attn
  260. def forward(self, hidden_states: torch.Tensor, output_attentions=False) -> torch.Tensor:
  261. batch_size, height, width, _ = hidden_states.shape
  262. # qkv with shape (3, batch_size, nHead, height * width, channel)
  263. qkv = (
  264. self.qkv(hidden_states)
  265. .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
  266. .permute(2, 0, 3, 1, 4)
  267. )
  268. # q, k, v with shape (batch_size * nHead, height * width, channel)
  269. query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
  270. attn_weights = (query * self.scale) @ key.transpose(-2, -1)
  271. if self.use_relative_position_embeddings:
  272. attn_weights = self.add_decomposed_rel_pos(
  273. attn_weights, query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
  274. )
  275. attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
  276. if output_attentions:
  277. # this operation is a bit awkward, but it's required to
  278. # make sure that attn_weights keeps its gradient.
  279. # In order to do so, attn_weights have to reshaped
  280. # twice and have to be reused in the following
  281. attn_weights_reshaped = attn_weights.view(batch_size, self.num_attention_heads, height * width, -1)
  282. attn_weights = attn_weights_reshaped.view(batch_size * self.num_attention_heads, height * width, -1)
  283. else:
  284. attn_weights_reshaped = None
  285. attn_output = (attn_weights @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
  286. attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
  287. attn_output = self.proj(attn_output)
  288. return (attn_output, attn_weights_reshaped)
  289. # Copied from transformers.models.sam.modeling_sam.SamMLPBlock with SamMLPBlock->SegGptMlp
  290. class SegGptMlp(nn.Module):
  291. def __init__(self, config):
  292. super().__init__()
  293. self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
  294. self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
  295. self.act = ACT2FN[config.hidden_act]
  296. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  297. hidden_states = self.lin1(hidden_states)
  298. hidden_states = self.act(hidden_states)
  299. hidden_states = self.lin2(hidden_states)
  300. return hidden_states
  301. # Copied from transformers.models.beit.modeling_beit.drop_path
  302. def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
  303. """
  304. Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  305. Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
  306. however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  307. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
  308. layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
  309. argument.
  310. """
  311. if drop_prob == 0.0 or not training:
  312. return input
  313. keep_prob = 1 - drop_prob
  314. shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  315. random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
  316. random_tensor.floor_() # binarize
  317. output = input.div(keep_prob) * random_tensor
  318. return output
  319. # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->SegGpt
  320. class SegGptDropPath(nn.Module):
  321. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  322. def __init__(self, drop_prob: Optional[float] = None) -> None:
  323. super().__init__()
  324. self.drop_prob = drop_prob
  325. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  326. return drop_path(hidden_states, self.drop_prob, self.training)
  327. def extra_repr(self) -> str:
  328. return f"p={self.drop_prob}"
  329. class SegGptLayer(GradientCheckpointingLayer):
  330. def __init__(self, config: SegGptConfig, drop_path_rate: float) -> None:
  331. super().__init__()
  332. self.attention = SegGptAttention(config)
  333. self.mlp = SegGptMlp(config)
  334. self.drop_path = SegGptDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
  335. self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  336. self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  337. def forward(
  338. self,
  339. hidden_states: torch.Tensor,
  340. ensemble_cond: int,
  341. feature_ensemble: bool = False,
  342. output_attentions: bool = False,
  343. ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
  344. self_attention_outputs = self.attention(
  345. self.layernorm_before(hidden_states), # in SegGpt, layernorm is applied before self-attention
  346. output_attentions=output_attentions,
  347. )
  348. attention_output = self_attention_outputs[0]
  349. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  350. if feature_ensemble and attention_output.shape[0] // 2 >= ensemble_cond:
  351. prompt, inputs = attention_output.split(attention_output.shape[1] // 2, dim=1)
  352. if ensemble_cond == 2:
  353. num_prompts = attention_output.shape[0] // 2
  354. inputs = inputs.reshape(2, num_prompts, -1)
  355. inputs = inputs.mean(dim=1, keepdim=True).expand_as(inputs)
  356. inputs = inputs.reshape(*prompt.shape)
  357. else:
  358. inputs = inputs.mean(dim=0, keepdim=True).expand_as(inputs)
  359. attention_output = torch.cat([prompt, inputs], dim=1)
  360. # first residual connection
  361. hidden_states = self.drop_path(attention_output) + hidden_states
  362. residual = hidden_states
  363. hidden_states = self.layernorm_after(hidden_states)
  364. hidden_states = self.mlp(hidden_states)
  365. hidden_states = residual + self.drop_path(hidden_states)
  366. outputs = (hidden_states,) + outputs
  367. return outputs
  368. class SegGptEncoder(nn.Module):
  369. def __init__(self, config: SegGptConfig) -> None:
  370. super().__init__()
  371. self.config = config
  372. dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers, device="cpu")]
  373. self.layers = nn.ModuleList([SegGptLayer(config, dpr[i]) for i in range(config.num_hidden_layers)])
  374. self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  375. self.gradient_checkpointing = False
  376. def forward(
  377. self,
  378. hidden_states: torch.Tensor,
  379. feature_ensemble: bool = False,
  380. output_attentions: bool = False,
  381. output_hidden_states: bool = False,
  382. return_dict: bool = True,
  383. ) -> Union[tuple, SegGptEncoderOutput]:
  384. all_hidden_states = () if output_hidden_states else None
  385. all_self_attentions = () if output_attentions else None
  386. intermediate_hidden_states = []
  387. for i, layer_module in enumerate(self.layers):
  388. if output_hidden_states:
  389. all_hidden_states = all_hidden_states + (hidden_states,)
  390. # Condition to check if we have the appropriate number of prompts to ensemble
  391. ensemble_cond = 2 if self.config.merge_index > i else 1
  392. layer_outputs = layer_module(hidden_states, ensemble_cond, feature_ensemble, output_attentions)
  393. hidden_states = layer_outputs[0]
  394. if i == self.config.merge_index:
  395. hidden_states = (
  396. hidden_states[: hidden_states.shape[0] // 2] + hidden_states[hidden_states.shape[0] // 2 :]
  397. ) * 0.5
  398. if i in self.config.intermediate_hidden_state_indices:
  399. intermediate_hidden_states.append(self.layernorm(hidden_states))
  400. if output_attentions:
  401. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  402. if output_hidden_states:
  403. all_hidden_states = all_hidden_states + (hidden_states,)
  404. if not return_dict:
  405. return tuple(
  406. v
  407. for v in [hidden_states, all_hidden_states, all_self_attentions, intermediate_hidden_states]
  408. if v is not None
  409. )
  410. return SegGptEncoderOutput(
  411. last_hidden_state=hidden_states,
  412. hidden_states=all_hidden_states,
  413. attentions=all_self_attentions,
  414. intermediate_hidden_states=intermediate_hidden_states,
  415. )
  416. # Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->SegGpt
  417. class SegGptLayerNorm(nn.LayerNorm):
  418. r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
  419. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
  420. width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
  421. """
  422. def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
  423. super().__init__(normalized_shape, eps=eps, **kwargs)
  424. if data_format not in ["channels_last", "channels_first"]:
  425. raise NotImplementedError(f"Unsupported data format: {data_format}")
  426. self.data_format = data_format
  427. def forward(self, features: torch.Tensor) -> torch.Tensor:
  428. """
  429. Args:
  430. features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
  431. """
  432. if self.data_format == "channels_first":
  433. features = features.permute(0, 2, 3, 1)
  434. features = super().forward(features)
  435. features = features.permute(0, 3, 1, 2)
  436. else:
  437. features = super().forward(features)
  438. return features
  439. class SegGptDecoderHead(nn.Module):
  440. def __init__(self, config):
  441. super().__init__()
  442. self.conv = nn.Conv2d(
  443. config.decoder_hidden_size,
  444. config.decoder_hidden_size,
  445. kernel_size=3,
  446. padding=1,
  447. )
  448. self.layernorm = SegGptLayerNorm(
  449. normalized_shape=config.decoder_hidden_size, eps=config.layer_norm_eps, data_format="channels_first"
  450. )
  451. self.act_fct = ACT2FN[config.hidden_act]
  452. self.head = nn.Conv2d(config.decoder_hidden_size, 3, kernel_size=1, bias=True) # decoder to patch
  453. def forward(self, hidden_states: torch.FloatTensor):
  454. hidden_states = self.conv(hidden_states)
  455. hidden_states = self.layernorm(hidden_states)
  456. hidden_states = self.act_fct(hidden_states)
  457. hidden_states = self.head(hidden_states)
  458. return hidden_states
  459. class SegGptDecoder(nn.Module):
  460. def __init__(self, config):
  461. super().__init__()
  462. self.decoder_embed = nn.Linear(
  463. config.hidden_size * len(config.intermediate_hidden_state_indices),
  464. config.patch_size**2 * config.decoder_hidden_size,
  465. bias=True,
  466. )
  467. self.decoder_pred = SegGptDecoderHead(config)
  468. self.patch_size = config.patch_size
  469. self.decoder_hidden_size = config.decoder_hidden_size
  470. self.config = config
  471. def _reshape_hidden_states(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
  472. batch_size, patch_height, patch_width, _ = hidden_states.shape
  473. hidden_states = hidden_states.reshape(
  474. batch_size, patch_height, patch_width, self.patch_size, self.patch_size, self.decoder_hidden_size
  475. )
  476. hidden_states = hidden_states.permute(0, 5, 1, 3, 2, 4)
  477. hidden_states = hidden_states.reshape(
  478. shape=(batch_size, -1, patch_height * self.patch_size, patch_width * self.patch_size)
  479. )
  480. return hidden_states
  481. def forward(self, hidden_states: torch.FloatTensor):
  482. hidden_states = self.decoder_embed(hidden_states)
  483. hidden_states = self._reshape_hidden_states(hidden_states)
  484. hidden_states = self.decoder_pred(hidden_states)
  485. return hidden_states
  486. @auto_docstring
  487. class SegGptPreTrainedModel(PreTrainedModel):
  488. config: SegGptConfig
  489. base_model_prefix = "model"
  490. main_input_name = "pixel_values"
  491. supports_gradient_checkpointing = True
  492. _no_split_modules = ["SegGptEmbeddings", "SegGptLayer"]
  493. def _init_weights(self, module: nn.Module) -> None:
  494. """Initialize the weights"""
  495. std = self.config.initializer_range
  496. if isinstance(module, (nn.Linear, nn.Conv2d)):
  497. # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
  498. # `trunc_normal_cpu` not implemented in `half` issues
  499. module.weight.data = nn.init.trunc_normal_(module.weight.data.to(torch.float32), mean=0.0, std=std).to(
  500. module.weight.dtype
  501. )
  502. if module.bias is not None:
  503. module.bias.data.zero_()
  504. elif isinstance(module, (nn.LayerNorm, SegGptLayerNorm)):
  505. module.bias.data.zero_()
  506. module.weight.data.fill_(1.0)
  507. elif isinstance(module, SegGptAttention):
  508. module.rel_pos_h.data = nn.init.trunc_normal_(
  509. module.rel_pos_h.data.to(torch.float32),
  510. mean=0.0,
  511. std=std,
  512. ).to(module.rel_pos_h.dtype)
  513. module.rel_pos_w.data = nn.init.trunc_normal_(
  514. module.rel_pos_w.data.to(torch.float32),
  515. mean=0.0,
  516. std=std,
  517. ).to(module.rel_pos_w.dtype)
  518. elif isinstance(module, SegGptEmbeddings):
  519. module.position_embeddings.data = nn.init.trunc_normal_(
  520. module.position_embeddings.data.to(torch.float32),
  521. mean=0.0,
  522. std=std,
  523. ).to(module.position_embeddings.dtype)
  524. torch.nn.init.normal_(module.mask_token, std=std)
  525. torch.nn.init.normal_(module.segment_token_input, std=std)
  526. torch.nn.init.normal_(module.segment_token_prompt, std=std)
  527. torch.nn.init.normal_(module.type_token_semantic, std=std)
  528. torch.nn.init.normal_(module.type_token_instance, std=std)
  529. @auto_docstring
  530. class SegGptModel(SegGptPreTrainedModel):
  531. def __init__(self, config: SegGptConfig):
  532. super().__init__(config)
  533. self.config = config
  534. self.embeddings = SegGptEmbeddings(config)
  535. self.encoder = SegGptEncoder(config)
  536. # Initialize weights and apply final processing
  537. self.post_init()
  538. def get_input_embeddings(self) -> SegGptPatchEmbeddings:
  539. return self.embeddings.patch_embeddings
  540. def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
  541. """
  542. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  543. class PreTrainedModel
  544. """
  545. for layer, heads in heads_to_prune.items():
  546. self.encoder.layer[layer].attention.prune_heads(heads)
  547. @auto_docstring
  548. def forward(
  549. self,
  550. pixel_values: torch.Tensor,
  551. prompt_pixel_values: torch.Tensor,
  552. prompt_masks: torch.Tensor,
  553. bool_masked_pos: Optional[torch.BoolTensor] = None,
  554. feature_ensemble: Optional[bool] = None,
  555. embedding_type: Optional[str] = None,
  556. labels: Optional[torch.FloatTensor] = None,
  557. output_attentions: Optional[bool] = None,
  558. output_hidden_states: Optional[bool] = None,
  559. return_dict: Optional[bool] = None,
  560. ) -> Union[tuple, SegGptEncoderOutput]:
  561. r"""
  562. prompt_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  563. Prompt pixel values. Prompt pixel values can be obtained using [`AutoImageProcessor`]. See
  564. [`SegGptImageProcessor.__call__`] for details.
  565. prompt_masks (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  566. Prompt mask. Prompt mask can be obtained using [`AutoImageProcessor`]. See [`SegGptImageProcessor.__call__`] for
  567. details.
  568. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
  569. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  570. feature_ensemble (`bool`, *optional*):
  571. Boolean indicating whether to use feature ensemble or not. If `True`, the model will use feature ensemble
  572. if we have at least two prompts. If `False`, the model will not use feature ensemble. This argument should
  573. be considered when doing few-shot inference on an input image i.e. more than one prompt for the same image.
  574. embedding_type (`str`, *optional*):
  575. Embedding type. Indicates whether the prompt is a semantic or instance embedding. Can be either
  576. instance or semantic.
  577. labels (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`, `optional`):
  578. Ground truth mask for input images.
  579. Examples:
  580. ```python
  581. >>> from transformers import SegGptImageProcessor, SegGptModel
  582. >>> from PIL import Image
  583. >>> import requests
  584. >>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
  585. >>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
  586. >>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"
  587. >>> image_input = Image.open(requests.get(image_input_url, stream=True).raw)
  588. >>> image_prompt = Image.open(requests.get(image_prompt_url, stream=True).raw)
  589. >>> mask_prompt = Image.open(requests.get(mask_prompt_url, stream=True).raw).convert("L")
  590. >>> checkpoint = "BAAI/seggpt-vit-large"
  591. >>> model = SegGptModel.from_pretrained(checkpoint)
  592. >>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)
  593. >>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")
  594. >>> outputs = model(**inputs)
  595. >>> list(outputs.last_hidden_state.shape)
  596. [1, 56, 28, 1024]
  597. ```
  598. """
  599. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  600. output_hidden_states = (
  601. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  602. )
  603. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  604. feature_ensemble = feature_ensemble if feature_ensemble is not None else False
  605. expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
  606. pixel_values = pixel_values.to(expected_dtype)
  607. prompt_pixel_values = prompt_pixel_values.to(expected_dtype)
  608. # Prepare inputs
  609. pixel_values = torch.cat((prompt_pixel_values, pixel_values), dim=2)
  610. prompt_pixel_values = (
  611. torch.cat((prompt_masks, prompt_masks), dim=2)
  612. if labels is None
  613. else torch.cat((prompt_masks, labels), dim=2)
  614. )
  615. if bool_masked_pos is None and labels is not None:
  616. logger.warning_once(
  617. "Labels were provided, but bool_masked_pos were not. It will be set to default value. If you're training the model, make sure to provide a bool_masked_pos."
  618. )
  619. # We concat on height axis so SegGPT can handle as a single image, hence we need to mask the portion
  620. # of the mask prompt pixels that will be destinated to the prediction as they don't add any information.
  621. # This is only the case for inference. In training, the model concat of prompt mask and label is masked
  622. # and reconstructed together (In-Context Painting).
  623. if bool_masked_pos is None:
  624. num_patches = self.embeddings.patch_embeddings.num_patches
  625. bool_masked_pos_zeros = torch.zeros(num_patches // 2, dtype=torch.bool, device=pixel_values.device)
  626. bool_masked_pos_ones = torch.ones(
  627. num_patches - num_patches // 2, dtype=torch.bool, device=pixel_values.device
  628. )
  629. bool_masked_pos = torch.cat([bool_masked_pos_zeros, bool_masked_pos_ones])
  630. bool_masked_pos = bool_masked_pos.unsqueeze(0)
  631. embedding_output = self.embeddings(
  632. pixel_values, prompt_pixel_values, embedding_type=embedding_type, bool_masked_pos=bool_masked_pos
  633. )
  634. encoder_outputs = self.encoder(
  635. embedding_output,
  636. feature_ensemble=feature_ensemble,
  637. output_attentions=output_attentions,
  638. output_hidden_states=output_hidden_states,
  639. return_dict=return_dict,
  640. )
  641. return encoder_outputs
  642. def patchify(tensor: torch.Tensor, patch_size: int) -> torch.Tensor:
  643. batch_size, num_channels, height, width = tensor.shape
  644. patch_height = height // patch_size
  645. patch_width = width // patch_size
  646. tensor = tensor.reshape(shape=(batch_size, num_channels, patch_height, patch_size, patch_width, patch_size))
  647. tensor = tensor.permute(0, 2, 4, 3, 5, 1)
  648. tensor = tensor.reshape(shape=(batch_size, patch_height * patch_width, patch_size**2 * 3))
  649. return tensor
  650. def unpatchify(tensor: torch.Tensor, patch_height: int, patch_width: int) -> torch.Tensor:
  651. batch_size = tensor.shape[0]
  652. patch_size = int((tensor.shape[-1] / 3) ** 0.5)
  653. if patch_height * patch_width != tensor.shape[1]:
  654. raise ValueError(
  655. f"Number of patches {tensor.shape[1]} does not match patch height ({patch_height}) and width ({patch_width})."
  656. )
  657. tensor = tensor.reshape(shape=(batch_size, patch_height, patch_width, patch_size, patch_size, 3))
  658. tensor = tensor.permute(0, 5, 1, 3, 2, 4)
  659. tensor = tensor.reshape(shape=(batch_size, 3, patch_height * patch_size, patch_width * patch_size))
  660. return tensor
  661. class SegGptLoss(nn.Module):
  662. def __init__(self, config):
  663. super().__init__()
  664. self.beta = config.beta
  665. self.patch_size = config.patch_size
  666. def forward(
  667. self,
  668. prompt_masks: torch.FloatTensor,
  669. pred_masks: torch.FloatTensor,
  670. labels: torch.FloatTensor,
  671. bool_masked_pos: torch.BoolTensor,
  672. ):
  673. """Computes the L1 loss between the predicted masks and the ground truth masks.
  674. Args:
  675. prompt_masks (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  676. Pixel values from mask prompt.
  677. pred_masks (`torch.FloatTensor` of shape `(batch_size, num_channels, 2*height, width)`):
  678. Predicted masks.
  679. labels (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  680. Ground truth mask for input images.
  681. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
  682. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  683. Returns:
  684. `torch.FloatTensor`: The mean L1 loss between the predicted masks and the ground truth masks.
  685. """
  686. ground_truth = torch.cat((prompt_masks, labels), dim=2)
  687. mask = bool_masked_pos[:, :, None].repeat(1, 1, self.patch_size**2 * 3)
  688. mask = unpatchify(mask, ground_truth.shape[2] // self.patch_size, ground_truth.shape[3] // self.patch_size)
  689. loss = F.smooth_l1_loss(pred_masks, ground_truth, reduction="none", beta=self.beta)
  690. loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
  691. return loss
  692. @auto_docstring(
  693. custom_intro="""
  694. SegGpt model with a decoder on top for one-shot image segmentation.
  695. """
  696. )
  697. class SegGptForImageSegmentation(SegGptPreTrainedModel):
  698. def __init__(self, config: SegGptConfig):
  699. super().__init__(config)
  700. self.config = config
  701. self.model = SegGptModel(config)
  702. self.decoder = SegGptDecoder(config)
  703. # Initialize weights and apply final processing
  704. self.post_init()
  705. @auto_docstring
  706. def forward(
  707. self,
  708. pixel_values: torch.Tensor,
  709. prompt_pixel_values: torch.Tensor,
  710. prompt_masks: torch.Tensor,
  711. bool_masked_pos: Optional[torch.BoolTensor] = None,
  712. feature_ensemble: Optional[bool] = None,
  713. embedding_type: Optional[str] = None,
  714. labels: Optional[torch.FloatTensor] = None,
  715. output_attentions: Optional[bool] = None,
  716. output_hidden_states: Optional[bool] = None,
  717. return_dict: Optional[bool] = None,
  718. ) -> Union[tuple, SegGptImageSegmentationOutput]:
  719. r"""
  720. prompt_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  721. Prompt pixel values. Prompt pixel values can be obtained using [`AutoImageProcessor`]. See
  722. [`SegGptImageProcessor.__call__`] for details.
  723. prompt_masks (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  724. Prompt mask. Prompt mask can be obtained using [`AutoImageProcessor`]. See [`SegGptImageProcessor.__call__`] for
  725. details.
  726. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
  727. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  728. feature_ensemble (`bool`, *optional*):
  729. Boolean indicating whether to use feature ensemble or not. If `True`, the model will use feature ensemble
  730. if we have at least two prompts. If `False`, the model will not use feature ensemble. This argument should
  731. be considered when doing few-shot inference on an input image i.e. more than one prompt for the same image.
  732. embedding_type (`str`, *optional*):
  733. Embedding type. Indicates whether the prompt is a semantic or instance embedding. Can be either
  734. instance or semantic.
  735. labels (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`, `optional`):
  736. Ground truth mask for input images.
  737. Examples:
  738. ```python
  739. >>> from transformers import SegGptImageProcessor, SegGptForImageSegmentation
  740. >>> from PIL import Image
  741. >>> import requests
  742. >>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
  743. >>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
  744. >>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"
  745. >>> image_input = Image.open(requests.get(image_input_url, stream=True).raw)
  746. >>> image_prompt = Image.open(requests.get(image_prompt_url, stream=True).raw)
  747. >>> mask_prompt = Image.open(requests.get(mask_prompt_url, stream=True).raw).convert("L")
  748. >>> checkpoint = "BAAI/seggpt-vit-large"
  749. >>> model = SegGptForImageSegmentation.from_pretrained(checkpoint)
  750. >>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)
  751. >>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")
  752. >>> outputs = model(**inputs)
  753. >>> result = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[(image_input.height, image_input.width)])[0]
  754. >>> print(list(result.shape))
  755. [170, 297]
  756. ```
  757. """
  758. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  759. output_hidden_states = (
  760. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  761. )
  762. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  763. if bool_masked_pos is None:
  764. num_patches = self.model.embeddings.patch_embeddings.num_patches
  765. bool_masked_pos_zeros = torch.zeros(num_patches // 2, dtype=torch.bool, device=pixel_values.device)
  766. bool_masked_pos_ones = torch.ones(
  767. num_patches - num_patches // 2, dtype=torch.bool, device=pixel_values.device
  768. )
  769. bool_masked_pos = torch.cat([bool_masked_pos_zeros, bool_masked_pos_ones])
  770. bool_masked_pos = bool_masked_pos.unsqueeze(0)
  771. outputs = self.model(
  772. pixel_values=pixel_values,
  773. prompt_pixel_values=prompt_pixel_values,
  774. prompt_masks=prompt_masks,
  775. bool_masked_pos=bool_masked_pos,
  776. feature_ensemble=feature_ensemble,
  777. embedding_type=embedding_type,
  778. labels=labels,
  779. output_attentions=output_attentions,
  780. output_hidden_states=output_hidden_states,
  781. return_dict=return_dict,
  782. )
  783. intermediate_hidden_states = outputs.intermediate_hidden_states if return_dict else outputs[-1]
  784. intermediate_hidden_states = torch.cat(intermediate_hidden_states, dim=-1)
  785. pred_masks = self.decoder(intermediate_hidden_states)
  786. loss = None
  787. if labels is not None:
  788. loss_fn = SegGptLoss(self.config)
  789. loss = loss_fn(prompt_masks, pred_masks, labels, bool_masked_pos)
  790. if not return_dict:
  791. output = (pred_masks,)
  792. if output_hidden_states:
  793. output = output + (outputs[1],)
  794. if output_attentions:
  795. idx = 2 if output_hidden_states else 1
  796. output = output + (outputs[idx],)
  797. if loss is not None:
  798. output = (loss,) + output
  799. return output
  800. return SegGptImageSegmentationOutput(
  801. loss=loss,
  802. pred_masks=pred_masks,
  803. hidden_states=outputs.hidden_states,
  804. attentions=outputs.attentions,
  805. )
  806. __all__ = ["SegGptModel", "SegGptPreTrainedModel", "SegGptForImageSegmentation"]