modeling_slanext.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/slanext/modular_slanext.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_slanext.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # Copyright 2026 The PaddlePaddle Team and The HuggingFace Inc. team. All rights reserved.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. import collections
  21. import math
  22. from dataclasses import dataclass
  23. import torch
  24. import torch.nn as nn
  25. import torch.nn.functional as F
  26. from ... import initialization as init
  27. from ...activations import ACT2CLS, ACT2FN
  28. from ...backbone_utils import filter_output_hidden_states
  29. from ...modeling_layers import GradientCheckpointingLayer
  30. from ...modeling_outputs import BaseModelOutput, ModelOutput
  31. from ...modeling_utils import PreTrainedModel
  32. from ...processing_utils import Unpack
  33. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
  34. from ...utils.generic import merge_with_config_defaults
  35. from ...utils.output_capturing import capture_outputs
  36. from .configuration_slanext import SLANeXtConfig, SLANeXtVisionConfig
  37. class SLANeXtVisionAttention(nn.Module):
  38. """Multi-head Attention block with relative position embeddings."""
  39. def __init__(self, config, window_size):
  40. super().__init__()
  41. input_size = (
  42. (config.image_size // config.patch_size, config.image_size // config.patch_size)
  43. if window_size == 0
  44. else (window_size, window_size)
  45. )
  46. self.num_attention_heads = config.num_attention_heads
  47. head_dim = config.hidden_size // config.num_attention_heads
  48. self.scale = head_dim**-0.5
  49. self.dropout = config.attention_dropout
  50. self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
  51. self.proj = nn.Linear(config.hidden_size, config.hidden_size)
  52. self.use_rel_pos = config.use_rel_pos
  53. if self.use_rel_pos:
  54. if input_size is None:
  55. raise ValueError("Input size must be provided if using relative positional encoding.")
  56. # initialize relative positional embeddings
  57. self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
  58. self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
  59. def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
  60. """
  61. Get relative positional embeddings according to the relative positions of
  62. query and key sizes.
  63. Args:
  64. q_size (int):
  65. size of the query.
  66. k_size (int):
  67. size of key k.
  68. rel_pos (`torch.Tensor`):
  69. relative position embeddings (L, channel).
  70. Returns:
  71. Extracted positional embeddings according to relative positions.
  72. """
  73. max_rel_dist = int(2 * max(q_size, k_size) - 1)
  74. # Interpolate rel pos.
  75. rel_pos_resized = F.interpolate(
  76. rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
  77. size=max_rel_dist,
  78. mode="linear",
  79. )
  80. rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
  81. # Scale the coords with short length if shapes for q and k are different.
  82. q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
  83. k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
  84. relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
  85. return rel_pos_resized[relative_coords.long()]
  86. def get_decomposed_rel_pos(
  87. self,
  88. query: torch.Tensor,
  89. rel_pos_h: torch.Tensor,
  90. rel_pos_w: torch.Tensor,
  91. q_size: tuple[int, int],
  92. k_size: tuple[int, int],
  93. ) -> torch.Tensor:
  94. """
  95. Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
  96. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
  97. Args:
  98. query (`torch.Tensor`):
  99. query q in the attention layer with shape (batch_size, query_height * query_width, channel).
  100. rel_pos_h (`torch.Tensor`):
  101. relative position embeddings (Lh, channel) for height axis.
  102. rel_pos_w (`torch.Tensor`):
  103. relative position embeddings (Lw, channel) for width axis.
  104. q_size (tuple):
  105. spatial sequence size of query q with (query_height, query_width).
  106. k_size (tuple):
  107. spatial sequence size of key k with (key_height, key_width).
  108. Returns:
  109. decomposed_rel_pos (`torch.Tensor`):
  110. decomposed relative position embeddings.
  111. """
  112. query_height, query_width = q_size
  113. key_height, key_width = k_size
  114. relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
  115. relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)
  116. batch_size, _, dim = query.shape
  117. reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
  118. rel_h = torch.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
  119. rel_w = torch.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
  120. decomposed_rel_pos = rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
  121. return decomposed_rel_pos
  122. def forward(self, hidden_states: torch.Tensor, output_attentions=None) -> tuple[torch.Tensor, torch.Tensor]:
  123. batch_size, height, width, _ = hidden_states.shape
  124. # qkv with shape (3, batch_size, nHead, height * width, channel)
  125. qkv = (
  126. self.qkv(hidden_states)
  127. .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
  128. .permute(2, 0, 3, 1, 4)
  129. )
  130. # q, k, v with shape (batch_size * nHead, height * width, channel)
  131. query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)
  132. attn_weights = (query * self.scale) @ key.transpose(-2, -1)
  133. if self.use_rel_pos:
  134. decomposed_rel_pos = self.get_decomposed_rel_pos(
  135. query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
  136. )
  137. decomposed_rel_pos = decomposed_rel_pos.reshape_as(attn_weights)
  138. attn_weights = attn_weights + decomposed_rel_pos
  139. attn_weights = torch.nn.functional.softmax(attn_weights, dtype=torch.float32, dim=-1).to(query.dtype)
  140. attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
  141. attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
  142. attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)
  143. attn_output = self.proj(attn_output)
  144. return attn_output, attn_weights
  145. class SLANeXtAttentionGRUCell(nn.Module):
  146. def __init__(self, input_size, hidden_size, num_embeddings):
  147. super().__init__()
  148. self.input_to_hidden = nn.Linear(input_size, hidden_size, bias=False)
  149. self.hidden_to_hidden = nn.Linear(hidden_size, hidden_size)
  150. self.score = nn.Linear(hidden_size, 1, bias=False)
  151. self.rnn = nn.GRUCell(input_size + num_embeddings, hidden_size)
  152. def forward(
  153. self,
  154. prev_hidden: torch.FloatTensor,
  155. batch_hidden: torch.FloatTensor,
  156. char_onehots: torch.FloatTensor,
  157. **kwargs: Unpack[TransformersKwargs],
  158. ):
  159. batch_hidden_proj = self.input_to_hidden(batch_hidden)
  160. prev_hidden_proj = self.hidden_to_hidden(prev_hidden).unsqueeze(1)
  161. attention_scores = batch_hidden_proj + prev_hidden_proj
  162. attention_scores = torch.tanh(attention_scores)
  163. attention_scores = self.score(attention_scores)
  164. attn_weights = F.softmax(attention_scores, dim=1, dtype=torch.float32).to(attention_scores.dtype)
  165. attn_weights = attn_weights.transpose(1, 2)
  166. context = torch.matmul(attn_weights, batch_hidden).squeeze(1)
  167. concat_context = torch.cat([context, char_onehots], 1)
  168. hidden_states = self.rnn(concat_context, prev_hidden)
  169. return hidden_states, attn_weights
  170. class SLANeXtMLP(nn.Module):
  171. def __init__(self, hidden_size, out_channels, activation=None):
  172. super().__init__()
  173. self.fc1 = nn.Linear(hidden_size, hidden_size)
  174. self.fc2 = nn.Linear(hidden_size, out_channels)
  175. self.act_fn = nn.Identity() if activation is None else ACT2CLS[activation]()
  176. def forward(self, hidden_states):
  177. hidden_states = self.fc1(hidden_states)
  178. hidden_states = self.fc2(hidden_states)
  179. hidden_states = self.act_fn(hidden_states)
  180. return hidden_states
  181. class SLANeXtPreTrainedModel(PreTrainedModel):
  182. config: SLANeXtConfig
  183. base_model_prefix = "backbone"
  184. main_input_name = "pixel_values"
  185. input_modalities = ("image",)
  186. supports_gradient_checkpointing = True
  187. _keep_in_fp32_modules_strict = ["structure_attention_cell", "structure_generator"]
  188. @torch.no_grad()
  189. def _init_weights(self, module):
  190. """Initialize the weights"""
  191. super()._init_weights(module)
  192. # Initialize positional embeddings to zero (SLANeXtVisionEncoder holds pos_embed)
  193. if isinstance(module, SLANeXtVisionEncoder):
  194. if module.pos_embed is not None:
  195. init.constant_(module.pos_embed, 0.0)
  196. # Initialize relative positional embeddings to zero (SLANeXtVisionAttention holds rel_pos_h/w)
  197. if isinstance(module, SLANeXtVisionAttention):
  198. if module.use_rel_pos:
  199. init.constant_(module.rel_pos_h, 0.0)
  200. init.constant_(module.rel_pos_w, 0.0)
  201. # Initialize GRUCell (replicates PyTorch default reset_parameters)
  202. if isinstance(module, nn.GRUCell):
  203. std = 1.0 / math.sqrt(module.hidden_size) if module.hidden_size > 0 else 0
  204. init.uniform_(module.weight_ih, -std, std)
  205. init.uniform_(module.weight_hh, -std, std)
  206. if module.bias_ih is not None:
  207. init.uniform_(module.bias_ih, -std, std)
  208. if module.bias_hh is not None:
  209. init.uniform_(module.bias_hh, -std, std)
  210. # Initialize SLAHead layers
  211. if isinstance(module, SLANeXtSLAHead):
  212. std = 1.0 / math.sqrt(self.config.hidden_size * 1.0)
  213. # Initialize structure_generator and loc_generator layers
  214. for generator in (module.structure_generator,):
  215. for layer in generator.children():
  216. if isinstance(layer, nn.Linear):
  217. init.uniform_(layer.weight, -std, std)
  218. if layer.bias is not None:
  219. init.uniform_(layer.bias, -std, std)
  220. class SLANeXtMLPBlock(nn.Module):
  221. def __init__(self, config):
  222. super().__init__()
  223. self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
  224. self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
  225. self.act = ACT2FN[config.hidden_act]
  226. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  227. hidden_states = self.lin1(hidden_states)
  228. hidden_states = self.act(hidden_states)
  229. hidden_states = self.lin2(hidden_states)
  230. return hidden_states
  231. class SLANeXtVisionLayer(GradientCheckpointingLayer):
  232. def __init__(self, config, window_size):
  233. super().__init__()
  234. self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  235. self.attn = SLANeXtVisionAttention(config, window_size)
  236. self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  237. self.mlp = SLANeXtMLPBlock(config)
  238. self.window_size = window_size
  239. def window_partition(self, hidden_states: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
  240. """
  241. Args:
  242. Partition into non-overlapping windows with padding if needed.
  243. hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
  244. size.
  245. Returns:
  246. windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
  247. (pad_height, pad_width): padded height and width before partition
  248. """
  249. batch_size, height, width, channel = hidden_states.shape
  250. pad_h = (window_size - height % window_size) % window_size
  251. pad_w = (window_size - width % window_size) % window_size
  252. hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
  253. pad_height, pad_width = height + pad_h, width + pad_w
  254. hidden_states = hidden_states.reshape(
  255. batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
  256. )
  257. windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(-1, window_size, window_size, channel)
  258. return windows, (pad_height, pad_width)
  259. def window_unpartition(
  260. self, windows: torch.Tensor, window_size: int, padding_shape: tuple[int, int], original_shape: tuple[int, int]
  261. ) -> torch.Tensor:
  262. """
  263. Args:
  264. Window unpartition into original sequences and removing padding.
  265. hidden_states (tensor):
  266. input tokens with [batch_size * num_windows, window_size, window_size, channel].
  267. window_size (int):
  268. window size.
  269. padding_shape (Tuple):
  270. padded height and width (pad_height, pad_width).
  271. original_shape (Tuple): original height and width (height, width) before padding.
  272. Returns:
  273. hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
  274. """
  275. pad_height, pad_width = padding_shape
  276. height, width = original_shape
  277. batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
  278. hidden_states = windows.reshape(
  279. batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
  280. )
  281. hidden_states = (
  282. hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().reshape(batch_size, pad_height, pad_width, -1)
  283. )
  284. hidden_states = hidden_states[:, :height, :width, :].contiguous()
  285. return hidden_states
  286. def forward(self, hidden_states: torch.Tensor) -> tuple[torch.FloatTensor]:
  287. residual = hidden_states
  288. hidden_states = self.layer_norm1(hidden_states)
  289. # Window partition
  290. if self.window_size > 0:
  291. height, width = hidden_states.shape[1], hidden_states.shape[2]
  292. hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)
  293. hidden_states, attn_weights = self.attn(
  294. hidden_states=hidden_states,
  295. )
  296. # Reverse window partition
  297. if self.window_size > 0:
  298. hidden_states = self.window_unpartition(hidden_states, self.window_size, padding_shape, (height, width))
  299. hidden_states = residual + hidden_states
  300. layernorm_output = self.layer_norm2(hidden_states)
  301. hidden_states = hidden_states + self.mlp(layernorm_output)
  302. return hidden_states
  303. @dataclass
  304. @auto_docstring(
  305. custom_intro="""
  306. Base class for slanext vision model's outputs that also contains image embeddings obtained by applying the projection
  307. layer to the pooler_output.
  308. """
  309. )
  310. class SLANeXtVisionEncoderOutput(ModelOutput):
  311. r"""
  312. image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
  313. The image embeddings obtained by applying the projection layer to the pooler_output.
  314. """
  315. image_embeds: torch.FloatTensor | None = None
  316. last_hidden_state: torch.FloatTensor | None = None
  317. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  318. attentions: tuple[torch.FloatTensor, ...] | None = None
  319. class SLANeXtPatchEmbeddings(nn.Module):
  320. """
  321. This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
  322. `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
  323. Transformer.
  324. """
  325. def __init__(self, config):
  326. super().__init__()
  327. image_size, patch_size = config.image_size, config.patch_size
  328. num_channels, hidden_size = config.num_channels, config.hidden_size
  329. image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
  330. patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
  331. num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  332. self.image_size = image_size
  333. self.patch_size = patch_size
  334. self.num_channels = num_channels
  335. self.num_patches = num_patches
  336. self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
  337. def forward(self, pixel_values):
  338. batch_size, num_channels, height, width = pixel_values.shape
  339. if num_channels != self.num_channels:
  340. raise ValueError(
  341. "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
  342. )
  343. if height != self.image_size[0] or width != self.image_size[1]:
  344. raise ValueError(
  345. f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
  346. )
  347. embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
  348. return embeddings
  349. class SLANeXtLayerNorm(nn.LayerNorm):
  350. r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
  351. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
  352. width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
  353. """
  354. def __init__(self, normalized_shape, *, eps=1e-6, data_format="channels_last", **kwargs):
  355. super().__init__(normalized_shape, eps=eps, **kwargs)
  356. if data_format not in ["channels_last", "channels_first"]:
  357. raise NotImplementedError(f"Unsupported data format: {data_format}")
  358. self.data_format = data_format
  359. def forward(self, features: torch.Tensor) -> torch.Tensor:
  360. """
  361. Args:
  362. features: Tensor of shape (batch_size, channels, height, width) OR (batch_size, height, width, channels)
  363. """
  364. if self.data_format == "channels_first":
  365. features = features.permute(0, 2, 3, 1)
  366. features = super().forward(features)
  367. features = features.permute(0, 3, 1, 2)
  368. else:
  369. features = super().forward(features)
  370. return features
  371. class SLANeXtVisionNeck(nn.Module):
  372. def __init__(self, config: SLANeXtVisionConfig):
  373. super().__init__()
  374. self.config = config
  375. self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
  376. self.layer_norm1 = SLANeXtLayerNorm(config.output_channels, data_format="channels_first")
  377. self.conv2 = nn.Conv2d(config.output_channels, config.output_channels, kernel_size=3, padding=1, bias=False)
  378. self.layer_norm2 = SLANeXtLayerNorm(config.output_channels, data_format="channels_first")
  379. def forward(self, hidden_states):
  380. hidden_states = hidden_states.permute(0, 3, 1, 2)
  381. hidden_states = self.conv1(hidden_states)
  382. hidden_states = self.layer_norm1(hidden_states)
  383. hidden_states = self.conv2(hidden_states)
  384. hidden_states = self.layer_norm2(hidden_states)
  385. return hidden_states
  386. class SLANeXtVisionEncoder(SLANeXtPreTrainedModel):
  387. _can_record_outputs = {"hidden_states": SLANeXtVisionLayer, "attentions": SLANeXtVisionAttention}
  388. input_modalities = ("image",)
  389. def __init__(self, config: SLANeXtVisionConfig):
  390. super().__init__(config)
  391. self.config = config
  392. self.image_size = config.image_size
  393. self.patch_embed = SLANeXtPatchEmbeddings(config)
  394. self.pos_embed = None
  395. if config.use_abs_pos:
  396. # Initialize absolute positional embedding with pretrain image size.
  397. self.pos_embed = nn.Parameter(
  398. torch.zeros(
  399. 1,
  400. config.image_size // config.patch_size,
  401. config.image_size // config.patch_size,
  402. config.hidden_size,
  403. )
  404. )
  405. self.layers = nn.ModuleList()
  406. for i in range(config.num_hidden_layers):
  407. layer = SLANeXtVisionLayer(
  408. config,
  409. window_size=config.window_size if i not in config.global_attn_indexes else 0,
  410. )
  411. self.layers.append(layer)
  412. self.neck = SLANeXtVisionNeck(config)
  413. self.gradient_checkpointing = False
  414. self.post_init()
  415. def get_input_embeddings(self):
  416. return self.patch_embed
  417. @merge_with_config_defaults
  418. @capture_outputs(tie_last_hidden_states=False)
  419. def forward(
  420. self, pixel_values: torch.FloatTensor | None = None, **kwargs: Unpack[TransformersKwargs]
  421. ) -> tuple | SLANeXtVisionEncoderOutput:
  422. if pixel_values is None:
  423. raise ValueError("You have to specify pixel_values")
  424. hidden_states = self.patch_embed(pixel_values)
  425. if self.pos_embed is not None:
  426. hidden_states = hidden_states + self.pos_embed
  427. for layer_module in self.layers:
  428. hidden_states = layer_module(hidden_states)
  429. hidden_states = self.neck(hidden_states)
  430. return SLANeXtVisionEncoderOutput(
  431. last_hidden_state=hidden_states,
  432. )
  433. class SLANeXtBackbone(SLANeXtPreTrainedModel):
  434. def __init__(
  435. self,
  436. config: dict | None = None,
  437. **kwargs,
  438. ):
  439. super().__init__(config)
  440. self.vision_tower = SLANeXtVisionEncoder(config.vision_config)
  441. self.post_conv = nn.Conv2d(
  442. config.post_conv_in_channels, config.post_conv_out_channels, kernel_size=3, stride=2, padding=1, bias=False
  443. )
  444. self.post_init()
  445. def forward(self, hidden_states: torch.Tensor, **kwargs: Unpack[TransformersKwargs]):
  446. vision_output = self.vision_tower(hidden_states, **kwargs)
  447. hidden_states = self.post_conv(vision_output.last_hidden_state)
  448. hidden_states = hidden_states.flatten(2).transpose(1, 2)
  449. return BaseModelOutput(
  450. last_hidden_state=hidden_states,
  451. hidden_states=vision_output.hidden_states,
  452. attentions=vision_output.attentions,
  453. )
  454. class SLANeXtSLAHead(SLANeXtPreTrainedModel):
  455. _can_record_outputs = {
  456. "attentions": SLANeXtAttentionGRUCell,
  457. }
  458. def __init__(
  459. self,
  460. config: dict | None = None,
  461. **kwargs,
  462. ):
  463. super().__init__(config)
  464. self.structure_attention_cell = SLANeXtAttentionGRUCell(
  465. config.post_conv_out_channels, config.hidden_size, config.out_channels
  466. )
  467. self.structure_generator = SLANeXtMLP(config.hidden_size, config.out_channels)
  468. self.post_init()
  469. @merge_with_config_defaults
  470. @capture_outputs
  471. @filter_output_hidden_states
  472. def forward(
  473. self,
  474. hidden_states: torch.FloatTensor,
  475. targets: torch.Tensor | None = None,
  476. **kwargs: Unpack[TransformersKwargs],
  477. ):
  478. features = torch.zeros(
  479. (hidden_states.shape[0], self.config.hidden_size), dtype=torch.float32, device=hidden_states.device
  480. )
  481. predicted_chars = torch.zeros(size=[hidden_states.shape[0]], dtype=torch.long, device=hidden_states.device)
  482. structure_preds_list = []
  483. structure_ids_list = []
  484. for _ in range(self.config.max_text_length + 1):
  485. embedding_feature = F.one_hot(predicted_chars, self.config.out_channels).float()
  486. features, _ = self.structure_attention_cell(features, hidden_states.float(), embedding_feature)
  487. structure_step = self.structure_generator(features)
  488. predicted_chars = structure_step.argmax(dim=1)
  489. structure_preds_list.append(structure_step)
  490. structure_ids_list.append(predicted_chars)
  491. if torch.stack(structure_ids_list, dim=1).eq(self.config.out_channels - 1).any(-1).all():
  492. break
  493. structure_preds = F.softmax(torch.stack(structure_preds_list, dim=1), dim=-1, dtype=torch.float32).to(
  494. hidden_states.dtype
  495. )
  496. return BaseModelOutput(last_hidden_state=structure_preds, hidden_states=structure_preds_list)
  497. @dataclass
  498. @auto_docstring
  499. class SLANeXtForTableRecognitionOutput(BaseModelOutput):
  500. r"""
  501. head_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  502. Hidden-states of the SLANeXtSLAHead at each prediction step, varies up to max `self.config.max_text_length` states (depending on early exits).
  503. head_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  504. Attentions of the SLANeXtSLAHead at each prediction step, varies up to max `self.config.max_text_length` attentions (depending on early exits).
  505. """
  506. head_hidden_states: torch.FloatTensor | None = None
  507. head_attentions: torch.FloatTensor | None = None
  508. @auto_docstring(
  509. custom_intro="""
  510. SLANeXt Table Recognition model for table recognition tasks. Wraps the core SLANeXtPreTrainedModel
  511. and returns outputs compatible with the Transformers table recognition API.
  512. """
  513. )
  514. class SLANeXtForTableRecognition(SLANeXtPreTrainedModel):
  515. def __init__(self, config: SLANeXtConfig):
  516. super().__init__(config)
  517. self.backbone = SLANeXtBackbone(config=config)
  518. self.head = SLANeXtSLAHead(config=config)
  519. self.post_init()
  520. @can_return_tuple
  521. @auto_docstring
  522. def forward(
  523. self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs]
  524. ) -> tuple[torch.FloatTensor] | SLANeXtForTableRecognitionOutput:
  525. backbone_outputs = self.backbone(pixel_values, **kwargs)
  526. head_outputs = self.head(backbone_outputs.last_hidden_state, **kwargs)
  527. return SLANeXtForTableRecognitionOutput(
  528. last_hidden_state=head_outputs.last_hidden_state,
  529. hidden_states=backbone_outputs.hidden_states,
  530. attentions=backbone_outputs.attentions,
  531. head_hidden_states=head_outputs.hidden_states,
  532. head_attentions=head_outputs.attentions,
  533. )
  534. __all__ = ["SLANeXtSLAHead", "SLANeXtBackbone", "SLANeXtForTableRecognition", "SLANeXtPreTrainedModel"]