modeling_vitdet.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. # coding=utf-8
  2. # Copyright 2023 Meta AI and 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 ViTDet backbone."""
  16. import collections.abc
  17. import math
  18. from typing import Optional, Union
  19. import torch
  20. from torch import nn
  21. from ...activations import ACT2FN
  22. from ...modeling_layers import GradientCheckpointingLayer
  23. from ...modeling_outputs import BackboneOutput, BaseModelOutput
  24. from ...modeling_utils import PreTrainedModel
  25. from ...utils import auto_docstring, logging
  26. from ...utils.backbone_utils import BackboneMixin
  27. from .configuration_vitdet import VitDetConfig
  28. logger = logging.get_logger(__name__)
  29. class VitDetEmbeddings(nn.Module):
  30. """
  31. This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
  32. `hidden_states` (patch embeddings) to be consumed by a Transformer.
  33. """
  34. def __init__(self, config):
  35. super().__init__()
  36. image_size, patch_size = config.pretrain_image_size, config.patch_size
  37. num_channels, hidden_size = config.num_channels, config.hidden_size
  38. image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
  39. patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
  40. num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  41. self.image_size = image_size
  42. self.patch_size = patch_size
  43. self.num_channels = num_channels
  44. self.num_patches = num_patches
  45. if config.use_absolute_position_embeddings:
  46. # Initialize absolute positional embedding with pretrain image size.
  47. num_positions = num_patches + 1
  48. self.position_embeddings = nn.Parameter(torch.zeros(1, num_positions, config.hidden_size))
  49. else:
  50. self.position_embeddings = None
  51. self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
  52. def get_absolute_positions(self, abs_pos_embeddings, has_cls_token, height, width):
  53. """
  54. Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token dimension for the
  55. original embeddings.
  56. Args:
  57. abs_pos_embeddings (`torch.Tensor`):
  58. Absolute positional embeddings with (1, num_position, num_channels).
  59. has_cls_token (`bool`):
  60. If true, has 1 embedding in abs_pos_embeddings for cls token.
  61. height (`int`):
  62. Height of input image tokens.
  63. width (`int`):
  64. Width of input image tokens.
  65. Returns:
  66. Absolute positional embeddings after processing with shape (1, height, width, num_channels)
  67. """
  68. if has_cls_token:
  69. abs_pos_embeddings = abs_pos_embeddings[:, 1:]
  70. num_position = abs_pos_embeddings.shape[1]
  71. size = int(math.sqrt(num_position)) # This is a constant and can be recorded as such in the ONNX export.
  72. if size * size != num_position:
  73. raise ValueError("Absolute position embeddings must be a square number.")
  74. if torch.jit.is_tracing() or (size != height or size != width):
  75. # nn.functional.interpolate is a noop in case size == height and size == width - we need to always capture this path with jit.trace.
  76. new_abs_pos_embeddings = nn.functional.interpolate(
  77. abs_pos_embeddings.reshape(1, size, size, -1).permute(0, 3, 1, 2),
  78. size=(height, width),
  79. mode="bicubic",
  80. align_corners=False,
  81. )
  82. return new_abs_pos_embeddings.permute(0, 2, 3, 1)
  83. else:
  84. return abs_pos_embeddings.reshape(1, height, width, -1)
  85. def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
  86. num_channels = pixel_values.shape[1]
  87. if num_channels != self.num_channels:
  88. raise ValueError(
  89. "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
  90. f" Expected {self.num_channels} but got {num_channels}."
  91. )
  92. embeddings = self.projection(pixel_values)
  93. if self.position_embeddings is not None:
  94. # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
  95. embeddings = embeddings.permute(0, 2, 3, 1)
  96. # add position embeddings
  97. embeddings = embeddings + self.get_absolute_positions(
  98. self.position_embeddings, True, embeddings.shape[1], embeddings.shape[2]
  99. )
  100. # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
  101. embeddings = embeddings.permute(0, 3, 1, 2)
  102. return embeddings
  103. @torch.jit.script_if_tracing # nn.functional.interpolate's `size` needs to be dynamic.
  104. def get_rel_pos(q_size, k_size, rel_pos):
  105. """
  106. Get relative positional embeddings according to the relative positions of query and key sizes.
  107. Args:
  108. q_size (`int`):
  109. Size of query q.
  110. k_size (`int`):
  111. Size of key k.
  112. rel_pos (`torch.Tensor`):
  113. Relative position embeddings (num_embeddings, num_channels).
  114. Returns:
  115. Extracted positional embeddings according to relative positions.
  116. """
  117. max_rel_dist = int(2 * max(q_size, k_size) - 1)
  118. # Interpolate rel pos if needed.
  119. if rel_pos.shape[0] != max_rel_dist:
  120. # Interpolate rel position embeddings.
  121. rel_pos_resized = nn.functional.interpolate(
  122. rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
  123. size=max_rel_dist,
  124. mode="linear",
  125. )
  126. rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
  127. else:
  128. rel_pos_resized = rel_pos
  129. # Scale the coords with short length if shapes for q and k are different.
  130. q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
  131. k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
  132. relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
  133. return rel_pos_resized[relative_coords.long()]
  134. def add_decomposed_relative_positions(attn, queries, rel_pos_h, rel_pos_w, q_size, k_size):
  135. """
  136. Calculate decomposed Relative Positional Embeddings as introduced in
  137. [MViT2](https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py).
  138. Args:
  139. attn (`torch.Tensor`):
  140. Attention map.
  141. queries (`torch.Tensor`):
  142. Query q in the attention layer with shape (batch_size, queries_height * queries_width, num_channels).
  143. rel_pos_h (`torch.Tensor`):
  144. Relative position embeddings (Lh, num_channels) for height axis.
  145. rel_pos_w (`torch.Tensor`):
  146. Relative position embeddings (Lw, num_channels) for width axis.
  147. q_size (`tuple[int]`):
  148. Spatial sequence size of query q with (queries_height, queries_width).
  149. k_size (`tuple[int]`):
  150. Spatial sequence size of key k with (keys_height, keys_width).
  151. Returns:
  152. attn (Tensor): attention map with added relative positional embeddings.
  153. """
  154. queries_height, queries_width = q_size
  155. keys_height, keys_width = k_size
  156. relative_height = get_rel_pos(queries_height, keys_height, rel_pos_h)
  157. relative_width = get_rel_pos(queries_width, keys_width, rel_pos_w)
  158. batch_size, _, dim = queries.shape
  159. r_q = queries.reshape(batch_size, queries_height, queries_width, dim)
  160. relative_height = torch.einsum("bhwc,hkc->bhwk", r_q, relative_height)
  161. relative_weight = torch.einsum("bhwc,wkc->bhwk", r_q, relative_width)
  162. attn = (
  163. attn.view(batch_size, queries_height, queries_width, keys_height, keys_width)
  164. + relative_height[:, :, :, :, None]
  165. + relative_weight[:, :, :, None, :]
  166. ).view(batch_size, queries_height * queries_width, keys_height * keys_width)
  167. return attn
  168. class VitDetAttention(nn.Module):
  169. """Multi-head Attention block with relative position embeddings."""
  170. def __init__(self, config, input_size=None):
  171. """
  172. Args:
  173. config (`VitDetConfig`):
  174. Model configuration.
  175. input_size (`tuple[int]`, *optional*):
  176. Input resolution, only required in case relative position embeddings are added.
  177. """
  178. super().__init__()
  179. dim = config.hidden_size
  180. num_heads = config.num_attention_heads
  181. self.num_heads = num_heads
  182. head_dim = dim // num_heads
  183. self.scale = head_dim**-0.5
  184. self.qkv = nn.Linear(dim, dim * 3, bias=config.qkv_bias)
  185. self.proj = nn.Linear(dim, dim)
  186. self.use_relative_position_embeddings = config.use_relative_position_embeddings
  187. if self.use_relative_position_embeddings:
  188. # initialize relative positional embeddings
  189. self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
  190. self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
  191. def forward(self, hidden_state, output_attentions=False):
  192. batch_size, height, width, _ = hidden_state.shape
  193. # qkv with shape (3, batch_size, num_heads, height * width, num_channels)
  194. qkv = self.qkv(hidden_state).reshape(batch_size, height * width, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
  195. # queries, keys and values have shape (batch_size * num_heads, height * width, num_channels)
  196. queries, keys, values = qkv.reshape(3, batch_size * self.num_heads, height * width, -1).unbind(0)
  197. attention_scores = (queries * self.scale) @ keys.transpose(-2, -1)
  198. if self.use_relative_position_embeddings:
  199. attention_scores = add_decomposed_relative_positions(
  200. attention_scores, queries, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
  201. )
  202. attention_probs = attention_scores.softmax(dim=-1)
  203. hidden_state = attention_probs @ values
  204. hidden_state = hidden_state.view(batch_size, self.num_heads, height, width, -1)
  205. hidden_state = hidden_state.permute(0, 2, 3, 1, 4)
  206. hidden_state = hidden_state.reshape(batch_size, height, width, -1)
  207. hidden_state = self.proj(hidden_state)
  208. if output_attentions:
  209. attention_probs = attention_probs.reshape(
  210. batch_size, self.num_heads, attention_probs.shape[-2], attention_probs.shape[-1]
  211. )
  212. outputs = (hidden_state, attention_probs)
  213. else:
  214. outputs = (hidden_state,)
  215. return outputs
  216. # Copied from transformers.models.beit.modeling_beit.drop_path
  217. def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
  218. """
  219. Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  220. Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
  221. however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  222. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
  223. layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
  224. argument.
  225. """
  226. if drop_prob == 0.0 or not training:
  227. return input
  228. keep_prob = 1 - drop_prob
  229. shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  230. random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
  231. random_tensor.floor_() # binarize
  232. output = input.div(keep_prob) * random_tensor
  233. return output
  234. # Copied from transformers.models.beit.modeling_beit.BeitDropPath
  235. class VitDetDropPath(nn.Module):
  236. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  237. def __init__(self, drop_prob: Optional[float] = None) -> None:
  238. super().__init__()
  239. self.drop_prob = drop_prob
  240. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  241. return drop_path(hidden_states, self.drop_prob, self.training)
  242. def extra_repr(self) -> str:
  243. return f"p={self.drop_prob}"
  244. class VitDetLayerNorm(nn.Module):
  245. """
  246. A LayerNorm variant, popularized by Transformers, that performs point-wise mean and variance normalization over the
  247. channel dimension for inputs that have shape (batch_size, channels, height, width).
  248. https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119
  249. """
  250. def __init__(self, normalized_shape, eps=1e-6):
  251. super().__init__()
  252. self.weight = nn.Parameter(torch.ones(normalized_shape))
  253. self.bias = nn.Parameter(torch.zeros(normalized_shape))
  254. self.eps = eps
  255. self.normalized_shape = (normalized_shape,)
  256. def forward(self, x):
  257. u = x.mean(1, keepdim=True)
  258. s = (x - u).pow(2).mean(1, keepdim=True)
  259. x = (x - u) / torch.sqrt(s + self.eps)
  260. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  261. return x
  262. class VitDetResBottleneckBlock(nn.Module):
  263. """
  264. The standard bottleneck residual block without the last activation layer. It contains 3 conv layers with kernels
  265. 1x1, 3x3, 1x1.
  266. """
  267. def __init__(self, config, in_channels, out_channels, bottleneck_channels):
  268. """
  269. Args:
  270. config (`VitDetConfig`):
  271. Model configuration.
  272. in_channels (`int`):
  273. Number of input channels.
  274. out_channels (`int`):
  275. Number of output channels.
  276. bottleneck_channels (`int`):
  277. Number of output channels for the 3x3 "bottleneck" conv layers.
  278. """
  279. super().__init__()
  280. self.conv1 = nn.Conv2d(in_channels, bottleneck_channels, 1, bias=False)
  281. self.norm1 = VitDetLayerNorm(bottleneck_channels)
  282. self.act1 = ACT2FN[config.hidden_act]
  283. self.conv2 = nn.Conv2d(bottleneck_channels, bottleneck_channels, 3, padding=1, bias=False)
  284. self.norm2 = VitDetLayerNorm(bottleneck_channels)
  285. self.act2 = ACT2FN[config.hidden_act]
  286. self.conv3 = nn.Conv2d(bottleneck_channels, out_channels, 1, bias=False)
  287. self.norm3 = VitDetLayerNorm(out_channels)
  288. def forward(self, x):
  289. out = x
  290. for layer in self.children():
  291. out = layer(out)
  292. out = x + out
  293. return out
  294. class VitDetMlp(nn.Module):
  295. def __init__(self, config, in_features: int, hidden_features: int) -> None:
  296. super().__init__()
  297. self.fc1 = nn.Linear(in_features, hidden_features)
  298. self.act = ACT2FN[config.hidden_act]
  299. self.fc2 = nn.Linear(hidden_features, in_features)
  300. self.drop = nn.Dropout(config.dropout_prob)
  301. def forward(self, x: torch.Tensor) -> torch.Tensor:
  302. x = self.fc1(x)
  303. x = self.act(x)
  304. x = self.drop(x)
  305. x = self.fc2(x)
  306. x = self.drop(x)
  307. return x
  308. def window_partition(hidden_state, window_size):
  309. """
  310. Partition into non-overlapping windows with padding if needed.
  311. Args:
  312. hidden_state (`torch.Tensor`):
  313. Input tokens with [batch_size, height, width, num_channels].
  314. window_size (`int`):
  315. Window size.
  316. Returns:
  317. `tuple(torch.FloatTensor)` comprising various elements:
  318. - windows: windows after partition with [batch_size * num_windows, window_size, window_size, num_channels].
  319. - (padded_height, padded_width): padded height and width before partition
  320. """
  321. batch_size, height, width, num_channels = hidden_state.shape
  322. pad_height = (window_size - height % window_size) % window_size
  323. pad_width = (window_size - width % window_size) % window_size
  324. # Noop in case pad_width == 0 and pad_height == 0.
  325. hidden_state = nn.functional.pad(hidden_state, (0, 0, 0, pad_width, 0, pad_height))
  326. padded_height, padded_width = height + pad_height, width + pad_width
  327. hidden_state = hidden_state.view(
  328. batch_size, padded_height // window_size, window_size, padded_width // window_size, window_size, num_channels
  329. )
  330. windows = hidden_state.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
  331. return windows, (padded_height, padded_width)
  332. def window_unpartition(windows, window_size, pad_height_width, height_width):
  333. """
  334. Window unpartition into original sequences and removing padding.
  335. Args:
  336. windows (`torch.Tensor`):
  337. Input tokens with [batch_size * num_windows, window_size, window_size, num_channels].
  338. window_size (`int`):
  339. Window size.
  340. pad_height_width (`tuple[int]`):
  341. Padded height and width (padded_height, padded_width).
  342. height_width (`tuple[int]`):
  343. Original height and width before padding.
  344. Returns:
  345. hidden_state: unpartitioned sequences with [batch_size, height, width, num_channels].
  346. """
  347. padded_height, padded_width = pad_height_width
  348. height, width = height_width
  349. batch_size = windows.shape[0] // (padded_height * padded_width // window_size // window_size)
  350. hidden_state = windows.view(
  351. batch_size, padded_height // window_size, padded_width // window_size, window_size, window_size, -1
  352. )
  353. hidden_state = hidden_state.permute(0, 1, 3, 2, 4, 5).contiguous()
  354. hidden_state = hidden_state.view(batch_size, padded_height, padded_width, -1)
  355. # We always have height <= padded_height and width <= padded_width
  356. hidden_state = hidden_state[:, :height, :width, :].contiguous()
  357. return hidden_state
  358. class VitDetLayer(GradientCheckpointingLayer):
  359. """This corresponds to the Block class in the original implementation."""
  360. def __init__(
  361. self, config: VitDetConfig, drop_path_rate: float = 0, window_size: int = 0, use_residual_block: bool = False
  362. ) -> None:
  363. super().__init__()
  364. dim = config.hidden_size
  365. image_size = config.image_size
  366. image_size = image_size if isinstance(image_size, (list, tuple)) else (image_size, image_size)
  367. patch_size = config.patch_size
  368. patch_size = patch_size if isinstance(patch_size, (list, tuple)) else (patch_size, patch_size)
  369. input_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
  370. self.norm1 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
  371. self.attention = VitDetAttention(
  372. config, input_size=input_size if window_size == 0 else (window_size, window_size)
  373. )
  374. self.drop_path = VitDetDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
  375. self.norm2 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
  376. self.mlp = VitDetMlp(config=config, in_features=dim, hidden_features=int(dim * config.mlp_ratio))
  377. self.window_size = window_size
  378. self.use_residual_block = use_residual_block
  379. if self.use_residual_block:
  380. # Use a residual block with bottleneck channel as dim // 2
  381. self.residual = VitDetResBottleneckBlock(
  382. config=config,
  383. in_channels=dim,
  384. out_channels=dim,
  385. bottleneck_channels=dim // 2,
  386. )
  387. def forward(
  388. self,
  389. hidden_states: torch.Tensor,
  390. head_mask: Optional[torch.Tensor] = None,
  391. output_attentions: bool = False,
  392. ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
  393. hidden_states = hidden_states.permute(0, 2, 3, 1)
  394. shortcut = hidden_states
  395. hidden_states = self.norm1(hidden_states)
  396. # Window partition
  397. if self.window_size > 0:
  398. height, width = hidden_states.shape[1], hidden_states.shape[2]
  399. hidden_states, pad_height_width = window_partition(hidden_states, self.window_size)
  400. self_attention_outputs = self.attention(
  401. hidden_states,
  402. output_attentions=output_attentions,
  403. )
  404. hidden_states = self_attention_outputs[0]
  405. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  406. # Reverse window partition
  407. if self.window_size > 0:
  408. hidden_states = window_unpartition(hidden_states, self.window_size, pad_height_width, (height, width))
  409. # first residual connection
  410. hidden_states = shortcut + self.drop_path(hidden_states)
  411. hidden_states = hidden_states + self.drop_path(self.mlp(self.norm2(hidden_states)))
  412. hidden_states = hidden_states.permute(0, 3, 1, 2)
  413. if self.use_residual_block:
  414. hidden_states = self.residual(hidden_states)
  415. outputs = (hidden_states,) + outputs
  416. return outputs
  417. class VitDetEncoder(nn.Module):
  418. def __init__(self, config: VitDetConfig) -> None:
  419. super().__init__()
  420. self.config = config
  421. depth = config.num_hidden_layers
  422. # stochastic depth decay rule
  423. drop_path_rate = [x.item() for x in torch.linspace(0, config.drop_path_rate, depth, device="cpu")]
  424. layers = []
  425. for i in range(depth):
  426. layers.append(
  427. VitDetLayer(
  428. config,
  429. drop_path_rate=drop_path_rate[i],
  430. window_size=config.window_size if i in config.window_block_indices else 0,
  431. use_residual_block=i in config.residual_block_indices,
  432. )
  433. )
  434. self.layer = nn.ModuleList(layers)
  435. self.gradient_checkpointing = False
  436. def forward(
  437. self,
  438. hidden_states: torch.Tensor,
  439. head_mask: Optional[torch.Tensor] = None,
  440. output_attentions: bool = False,
  441. output_hidden_states: bool = False,
  442. return_dict: bool = True,
  443. ) -> Union[tuple, BaseModelOutput]:
  444. all_hidden_states = () if output_hidden_states else None
  445. all_self_attentions = () if output_attentions else None
  446. for i, layer_module in enumerate(self.layer):
  447. if output_hidden_states:
  448. all_hidden_states = all_hidden_states + (hidden_states,)
  449. layer_head_mask = head_mask[i] if head_mask is not None else None
  450. layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
  451. hidden_states = layer_outputs[0]
  452. if output_attentions:
  453. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  454. if output_hidden_states:
  455. all_hidden_states = all_hidden_states + (hidden_states,)
  456. if not return_dict:
  457. return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
  458. return BaseModelOutput(
  459. last_hidden_state=hidden_states,
  460. hidden_states=all_hidden_states,
  461. attentions=all_self_attentions,
  462. )
  463. def caffe2_msra_fill(module: nn.Module) -> None:
  464. """
  465. Initialize `module.weight` using the "MSRAFill" implemented in Caffe2. Also initializes `module.bias` to 0.
  466. Source: https://detectron2.readthedocs.io/en/latest/_modules/fvcore/nn/weight_init.html.
  467. Args:
  468. module (torch.nn.Module): module to initialize.
  469. """
  470. nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
  471. if module.bias is not None:
  472. nn.init.constant_(module.bias, 0)
  473. @auto_docstring
  474. class VitDetPreTrainedModel(PreTrainedModel):
  475. config: VitDetConfig
  476. base_model_prefix = "vitdet"
  477. main_input_name = "pixel_values"
  478. supports_gradient_checkpointing = True
  479. _no_split_modules = []
  480. def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
  481. """Initialize the weights"""
  482. if isinstance(module, (nn.Linear, nn.Conv2d)):
  483. # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
  484. # `trunc_normal_cpu` not implemented in `half` issues
  485. module.weight.data = nn.init.trunc_normal_(
  486. module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
  487. ).to(module.weight.dtype)
  488. if module.bias is not None:
  489. module.bias.data.zero_()
  490. elif isinstance(module, nn.LayerNorm):
  491. module.bias.data.zero_()
  492. module.weight.data.fill_(1.0)
  493. elif isinstance(module, VitDetEmbeddings):
  494. module.position_embeddings.data = nn.init.trunc_normal_(
  495. module.position_embeddings.data.to(torch.float32),
  496. mean=0.0,
  497. std=self.config.initializer_range,
  498. ).to(module.position_embeddings.dtype)
  499. elif isinstance(module, VitDetAttention) and self.config.use_relative_position_embeddings:
  500. module.rel_pos_h.data = nn.init.trunc_normal_(
  501. module.rel_pos_h.data.to(torch.float32),
  502. mean=0.0,
  503. std=self.config.initializer_range,
  504. )
  505. module.rel_pos_w.data = nn.init.trunc_normal_(
  506. module.rel_pos_w.data.to(torch.float32),
  507. mean=0.0,
  508. std=self.config.initializer_range,
  509. )
  510. elif isinstance(module, VitDetResBottleneckBlock):
  511. for layer in [module.conv1, module.conv2, module.conv3]:
  512. caffe2_msra_fill(layer)
  513. for layer in [module.norm1, module.norm2]:
  514. layer.weight.data.fill_(1.0)
  515. layer.bias.data.zero_()
  516. # zero init last norm layer.
  517. module.norm3.weight.data.zero_()
  518. module.norm3.bias.data.zero_()
  519. @auto_docstring
  520. class VitDetModel(VitDetPreTrainedModel):
  521. def __init__(self, config: VitDetConfig):
  522. super().__init__(config)
  523. self.config = config
  524. self.embeddings = VitDetEmbeddings(config)
  525. self.encoder = VitDetEncoder(config)
  526. # Initialize weights and apply final processing
  527. self.post_init()
  528. def get_input_embeddings(self) -> VitDetEmbeddings:
  529. return self.embeddings.projection
  530. def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
  531. """
  532. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  533. class PreTrainedModel
  534. """
  535. for layer, heads in heads_to_prune.items():
  536. self.encoder.layer[layer].attention.prune_heads(heads)
  537. @auto_docstring
  538. def forward(
  539. self,
  540. pixel_values: Optional[torch.Tensor] = None,
  541. head_mask: Optional[torch.Tensor] = None,
  542. output_attentions: Optional[bool] = None,
  543. output_hidden_states: Optional[bool] = None,
  544. return_dict: Optional[bool] = None,
  545. ) -> Union[tuple, BaseModelOutput]:
  546. r"""
  547. Examples:
  548. ```python
  549. >>> from transformers import VitDetConfig, VitDetModel
  550. >>> import torch
  551. >>> config = VitDetConfig()
  552. >>> model = VitDetModel(config)
  553. >>> pixel_values = torch.randn(1, 3, 224, 224)
  554. >>> with torch.no_grad():
  555. ... outputs = model(pixel_values)
  556. >>> last_hidden_states = outputs.last_hidden_state
  557. >>> list(last_hidden_states.shape)
  558. [1, 768, 14, 14]
  559. ```"""
  560. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  561. output_hidden_states = (
  562. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  563. )
  564. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  565. if pixel_values is None:
  566. raise ValueError("You have to specify pixel_values")
  567. # Prepare head mask if needed
  568. # 1.0 in head_mask indicate we keep the head
  569. # attention_probs has shape bsz x n_heads x N x N
  570. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  571. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  572. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  573. embedding_output = self.embeddings(pixel_values)
  574. encoder_outputs = self.encoder(
  575. embedding_output,
  576. head_mask=head_mask,
  577. output_attentions=output_attentions,
  578. output_hidden_states=output_hidden_states,
  579. return_dict=return_dict,
  580. )
  581. sequence_output = encoder_outputs[0]
  582. if not return_dict:
  583. return (sequence_output,) + encoder_outputs[1:]
  584. return BaseModelOutput(
  585. last_hidden_state=sequence_output,
  586. hidden_states=encoder_outputs.hidden_states,
  587. attentions=encoder_outputs.attentions,
  588. )
  589. @auto_docstring(
  590. custom_intro="""
  591. ViTDet backbone, to be used with frameworks like Mask R-CNN.
  592. """
  593. )
  594. class VitDetBackbone(VitDetPreTrainedModel, BackboneMixin):
  595. def __init__(self, config):
  596. super().__init__(config)
  597. super()._init_backbone(config)
  598. self.embeddings = VitDetEmbeddings(config)
  599. self.encoder = VitDetEncoder(config)
  600. self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
  601. # initialize weights and apply final processing
  602. self.post_init()
  603. def get_input_embeddings(self) -> VitDetEmbeddings:
  604. return self.embeddings.projection
  605. @auto_docstring
  606. def forward(
  607. self,
  608. pixel_values: torch.Tensor,
  609. output_hidden_states: Optional[bool] = None,
  610. output_attentions: Optional[bool] = None,
  611. return_dict: Optional[bool] = None,
  612. ) -> BackboneOutput:
  613. r"""
  614. Examples:
  615. ```python
  616. >>> from transformers import VitDetConfig, VitDetBackbone
  617. >>> import torch
  618. >>> config = VitDetConfig()
  619. >>> model = VitDetBackbone(config)
  620. >>> pixel_values = torch.randn(1, 3, 224, 224)
  621. >>> with torch.no_grad():
  622. ... outputs = model(pixel_values)
  623. >>> feature_maps = outputs.feature_maps
  624. >>> list(feature_maps[-1].shape)
  625. [1, 768, 14, 14]
  626. ```"""
  627. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  628. output_hidden_states = (
  629. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  630. )
  631. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  632. embedding_output = self.embeddings(pixel_values)
  633. outputs = self.encoder(
  634. embedding_output,
  635. output_hidden_states=True,
  636. output_attentions=output_attentions,
  637. return_dict=return_dict,
  638. )
  639. hidden_states = outputs.hidden_states if return_dict else outputs[1]
  640. feature_maps = ()
  641. for stage, hidden_state in zip(self.stage_names, hidden_states):
  642. if stage in self.out_features:
  643. feature_maps += (hidden_state,)
  644. if not return_dict:
  645. if output_hidden_states:
  646. output = (feature_maps,) + outputs[1:]
  647. else:
  648. output = (feature_maps,) + outputs[2:]
  649. return output
  650. return BackboneOutput(
  651. feature_maps=feature_maps,
  652. hidden_states=outputs.hidden_states if output_hidden_states else None,
  653. attentions=outputs.attentions,
  654. )
  655. __all__ = ["VitDetModel", "VitDetPreTrainedModel", "VitDetBackbone"]