modeling_hiera.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. # coding=utf-8
  2. # Copyright 2024 Meta 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 Hiera model."""
  16. import math
  17. from dataclasses import dataclass
  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 (
  24. BackboneOutput,
  25. BaseModelOutput,
  26. BaseModelOutputWithPooling,
  27. ImageClassifierOutput,
  28. ModelOutput,
  29. )
  30. from ...modeling_utils import PreTrainedModel
  31. from ...utils import auto_docstring, logging, torch_int
  32. from ...utils.backbone_utils import BackboneMixin
  33. from .configuration_hiera import HieraConfig
  34. logger = logging.get_logger(__name__)
  35. @dataclass
  36. @auto_docstring(
  37. custom_intro="""
  38. Hiera encoder's outputs, with potential hidden states and attentions.
  39. """
  40. )
  41. class HieraEncoderOutput(ModelOutput):
  42. r"""
  43. reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  44. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
  45. shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
  46. Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
  47. include the spatial dimensions.
  48. """
  49. last_hidden_state: Optional[torch.FloatTensor] = None
  50. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  51. attentions: Optional[tuple[torch.FloatTensor, ...]] = None
  52. reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  53. @dataclass
  54. @auto_docstring(
  55. custom_intro="""
  56. Hiera model's outputs that also contains a pooling of the last hidden states.
  57. """
  58. )
  59. class HieraModelOutput(ModelOutput):
  60. r"""
  61. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
  62. Average pooling of the last layer hidden-state.
  63. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
  64. Tensor indicating which patches are masked (0) and which are not (1).
  65. ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  66. Tensor containing the original index of the (shuffled) masked patches.
  67. reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  68. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
  69. shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
  70. Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
  71. include the spatial dimensions.
  72. """
  73. last_hidden_state: Optional[torch.FloatTensor] = None
  74. pooler_output: Optional[torch.FloatTensor] = None
  75. bool_masked_pos: Optional[torch.BoolTensor] = None
  76. ids_restore: Optional[torch.LongTensor] = None
  77. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  78. attentions: Optional[tuple[torch.FloatTensor, ...]] = None
  79. reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  80. @dataclass
  81. @auto_docstring(
  82. custom_intro="""
  83. Hiera image classification outputs.
  84. """
  85. )
  86. class HieraForImageClassificationOutput(ImageClassifierOutput):
  87. r"""
  88. loss (`torch.FloatTensor` of shape `(1,)`, `optional`):
  89. Loss value for the training task.
  90. logits (`torch.FloatTensor` of shape `(batch_size, num_labels)`):
  91. Prediction scores of the classification head (logits of the output layer).
  92. hidden_states (`tuple(torch.FloatTensor)`, `optional`):
  93. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
  94. shape `(batch_size, sequence_length, hidden_size)`. These are the unrolled hidden states of the model.
  95. Hidden-states of the model at the output of each layer plus the initial embedding outputs.
  96. attentions (`tuple(torch.FloatTensor)`, `optional`):
  97. Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
  98. sequence_length)`.
  99. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
  100. heads.
  101. reshaped_hidden_states (`tuple(torch.FloatTensor)`, `optional`):
  102. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
  103. shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
  104. Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
  105. include the spatial dimensions.
  106. """
  107. loss: Optional[torch.FloatTensor] = None
  108. logits: Optional[torch.FloatTensor] = None
  109. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  110. attentions: Optional[tuple[torch.FloatTensor, ...]] = None
  111. reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  112. @dataclass
  113. @auto_docstring(
  114. custom_intro="""
  115. Class for HieraForPreTraining's outputs, with potential hidden states and attentions.
  116. """
  117. )
  118. class HieraForPreTrainingOutput(ModelOutput):
  119. r"""
  120. loss (`torch.FloatTensor` of shape `(1,)`):
  121. Pixel reconstruction loss.
  122. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
  123. Pixel reconstruction logits.
  124. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
  125. Tensor indicating which patches are masked (0) and which are not (1).
  126. ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  127. Tensor containing the original index of the (shuffled) masked patches.
  128. reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  129. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  130. shape `(batch_size, height, width, hidden_size)`. Hidden-states of the model at the output of each layer
  131. plus the initial embedding outputs reshaped to include the spatial dimensions.
  132. """
  133. loss: Optional[torch.FloatTensor] = None
  134. logits: Optional[torch.FloatTensor] = None
  135. bool_masked_pos: Optional[torch.BoolTensor] = None
  136. ids_restore: Optional[torch.LongTensor] = None
  137. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  138. attentions: Optional[tuple[torch.FloatTensor]] = None
  139. reshaped_hidden_states: Optional[tuple[torch.FloatTensor]] = None
  140. class HieraPatchEmbeddings(nn.Module):
  141. """
  142. This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
  143. `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
  144. Transformer.
  145. """
  146. def __init__(self, config, is_mae: bool = False):
  147. super().__init__()
  148. # Support any number of spatial dimensions
  149. self.spatial_dims = len(config.patch_size)
  150. if self.spatial_dims != 2:
  151. raise ValueError(f"The number of dimensions of the input image should be 2, but got {self.spatial_dims}.")
  152. self.num_channels = config.num_channels
  153. self.image_size = config.image_size[-2:]
  154. self.tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
  155. self.mask_spatial_shape = [i // s for i, s in zip(self.tokens_spatial_shape, config.masked_unit_size)]
  156. self.mask_ratio = config.mask_ratio
  157. self.is_mae = is_mae
  158. self.projection = nn.Conv2d(
  159. self.num_channels,
  160. config.embed_dim,
  161. kernel_size=config.patch_size,
  162. stride=config.patch_stride,
  163. padding=config.patch_padding,
  164. )
  165. def masked_conv(
  166. self, pixel_values: torch.FloatTensor, bool_masked_pos: Optional[torch.BoolTensor] = None
  167. ) -> torch.Tensor:
  168. """Zero-out the masked regions of the input before conv.
  169. Prevents leakage of masked regions when using overlapping kernels.
  170. """
  171. if bool_masked_pos is None:
  172. return self.projection(pixel_values)
  173. target_size = pixel_values.shape[2:]
  174. # Reshape bool_masked_pos to (batch_size, 1, mask_unit_height, mask_unit_width)
  175. bool_masked_pos = bool_masked_pos.view(pixel_values.shape[0], 1, *self.mask_spatial_shape)
  176. bool_masked_pos = nn.functional.interpolate(bool_masked_pos.float(), size=target_size)
  177. return self.projection(pixel_values * bool_masked_pos)
  178. def random_masking(
  179. self, pixel_values: torch.FloatTensor, noise: Optional[torch.FloatTensor] = None
  180. ) -> tuple[torch.BoolTensor, torch.LongTensor]:
  181. """
  182. Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random
  183. noise.
  184. Args:
  185. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`)
  186. noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*) which is
  187. mainly used for testing purposes to control randomness and maintain the reproducibility
  188. """
  189. batch_size = pixel_values.shape[0]
  190. # Tokens selected for masking at mask unit level
  191. num_windows = math.prod(self.mask_spatial_shape)
  192. len_keep = int(num_windows * (1 - self.mask_ratio))
  193. if noise is None:
  194. noise = torch.rand(batch_size, num_windows, device=pixel_values.device)
  195. # Sort noise for each sample
  196. ids_shuffle = torch.argsort(noise, dim=1)
  197. # ascend: small is keep, large is remove
  198. ids_restore = torch.argsort(ids_shuffle, dim=1).to(pixel_values.device)
  199. # Generate the binary bool_masked_pos: 1 is *keep*, 0 is *remove*
  200. # Note this is opposite to original MAE
  201. bool_masked_pos = torch.zeros([batch_size, num_windows], device=pixel_values.device)
  202. bool_masked_pos[:, :len_keep] = 1
  203. # Unshuffle to get the binary bool_masked_pos
  204. bool_masked_pos = torch.gather(bool_masked_pos, dim=1, index=ids_restore).bool()
  205. return bool_masked_pos, ids_restore
  206. def forward(
  207. self,
  208. pixel_values: torch.FloatTensor,
  209. noise: Optional[torch.FloatTensor] = None,
  210. ) -> tuple[torch.Tensor, Optional[torch.BoolTensor], Optional[torch.LongTensor]]:
  211. (bool_masked_pos, ids_restore) = (
  212. self.random_masking(pixel_values, noise=noise) if self.is_mae else (None, None)
  213. )
  214. embeddings = self.masked_conv(pixel_values, bool_masked_pos)
  215. embeddings = embeddings.flatten(2).transpose(2, 1)
  216. return embeddings, bool_masked_pos, ids_restore
  217. class HieraEmbeddings(nn.Module):
  218. """
  219. Construct position and patch embeddings.
  220. """
  221. def __init__(self, config: HieraConfig, is_mae: bool = False) -> None:
  222. super().__init__()
  223. self.patch_stride = config.patch_stride
  224. tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
  225. self.mask_spatial_shape = [i // s for i, s in zip(tokens_spatial_shape, config.masked_unit_size)]
  226. self.num_tokens = math.prod(tokens_spatial_shape)
  227. self.is_mae = is_mae
  228. self.patch_embeddings = HieraPatchEmbeddings(config, is_mae=is_mae)
  229. self.position_embeddings = nn.Parameter(torch.zeros(1, self.num_tokens, config.embed_dim))
  230. def interpolate_pos_encoding(
  231. self, embeddings: torch.Tensor, pos_embeds: torch.Tensor, height: int, width: int
  232. ) -> torch.Tensor:
  233. """
  234. This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
  235. images. This method is also adapted to support torch.jit tracing, no class embeddings, and different patch strides.
  236. Adapted from:
  237. - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
  238. - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
  239. """
  240. num_patches = embeddings.shape[1]
  241. num_positions = pos_embeds.shape[1]
  242. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  243. if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
  244. return pos_embeds
  245. dim = embeddings.shape[-1]
  246. new_height = height // self.patch_stride[0]
  247. new_width = width // self.patch_stride[1]
  248. sqrt_num_positions = torch_int(num_positions**0.5)
  249. pos_embeds = pos_embeds.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
  250. pos_embeds = pos_embeds.permute(0, 3, 1, 2)
  251. pos_embeds = nn.functional.interpolate(
  252. pos_embeds,
  253. size=(new_height, new_width),
  254. mode="bicubic",
  255. align_corners=False,
  256. )
  257. pos_embeds = pos_embeds.permute(0, 2, 3, 1).view(1, -1, dim)
  258. return pos_embeds
  259. def get_position_embedding(
  260. self, embeddings: torch.Tensor, height: int, width: int, interpolate_pos_encoding: bool
  261. ) -> torch.FloatTensor:
  262. return (
  263. self.interpolate_pos_encoding(embeddings, self.position_embeddings, height, width)
  264. if interpolate_pos_encoding
  265. else self.position_embeddings
  266. )
  267. def forward(
  268. self,
  269. pixel_values: torch.FloatTensor,
  270. noise: Optional[torch.FloatTensor] = None,
  271. interpolate_pos_encoding: bool = False,
  272. ) -> tuple[torch.Tensor, Optional[torch.BoolTensor], Optional[torch.LongTensor]]:
  273. height, width = pixel_values.shape[-2:]
  274. embeddings, bool_masked_pos, ids_restore = self.patch_embeddings(pixel_values, noise=noise)
  275. embeddings = embeddings + self.get_position_embedding(embeddings, height, width, interpolate_pos_encoding)
  276. return embeddings, bool_masked_pos, ids_restore
  277. class HieraMaskUnitAttention(nn.Module):
  278. """
  279. Computes either Mask Unit or Global Attention. Also is able to perform query pooling.
  280. Note: this assumes the tokens have already been flattened and unrolled into mask units.
  281. """
  282. def __init__(
  283. self,
  284. hidden_size: int,
  285. hidden_size_output: int,
  286. num_heads: int,
  287. query_stride: int = 1,
  288. window_size: int = 0,
  289. use_mask_unit_attn: bool = False,
  290. ) -> None:
  291. super().__init__()
  292. self.num_heads = num_heads
  293. self.query_stride = query_stride
  294. self.hidden_size_output = hidden_size_output
  295. self.head_dim = hidden_size_output // num_heads
  296. self.scale = (self.head_dim) ** -0.5
  297. self.qkv = nn.Linear(hidden_size, 3 * hidden_size_output)
  298. self.proj = nn.Linear(hidden_size_output, hidden_size_output)
  299. self.window_size = window_size
  300. self.use_mask_unit_attn = use_mask_unit_attn
  301. def forward(
  302. self,
  303. hidden_states: torch.Tensor,
  304. head_mask: Optional[torch.FloatTensor] = None,
  305. output_attentions: bool = False,
  306. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  307. """Input should be of shape [batch, tokens, channels]."""
  308. batch_size, seq_len, _ = hidden_states.shape
  309. num_windows = 1
  310. if self.use_mask_unit_attn:
  311. num_windows = seq_len // (self.query_stride * self.window_size)
  312. qkv = self.qkv(hidden_states)
  313. qkv = qkv.reshape(batch_size, -1, num_windows, 3, self.num_heads, self.head_dim)
  314. qkv = qkv.permute(3, 0, 4, 2, 1, 5)
  315. query, key, value = qkv.unbind(0)
  316. if self.query_stride > 1:
  317. # Refer to unroll to see how this performs a maxpool-Nd
  318. query = query.view(batch_size, self.num_heads, num_windows, self.query_stride, -1, self.head_dim)
  319. query = query.max(dim=3).values
  320. attn_weights = (query * self.scale) @ key.transpose(-1, -2)
  321. attn_weights = attn_weights.softmax(dim=-1)
  322. # Mask heads if we want to
  323. if head_mask is not None:
  324. attn_weights = attn_weights * head_mask
  325. attn_output = attn_weights @ value
  326. attn_output = attn_output.transpose(1, 3).reshape(batch_size, -1, self.hidden_size_output)
  327. attn_output = self.proj(attn_output)
  328. return (attn_output, attn_weights) if output_attentions else (attn_output, None)
  329. # Copied from transformers.models.beit.modeling_beit.drop_path
  330. def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
  331. """
  332. Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  333. Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
  334. however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  335. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
  336. layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
  337. argument.
  338. """
  339. if drop_prob == 0.0 or not training:
  340. return input
  341. keep_prob = 1 - drop_prob
  342. shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  343. random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
  344. random_tensor.floor_() # binarize
  345. output = input.div(keep_prob) * random_tensor
  346. return output
  347. # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->Hiera
  348. class HieraDropPath(nn.Module):
  349. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  350. def __init__(self, drop_prob: Optional[float] = None) -> None:
  351. super().__init__()
  352. self.drop_prob = drop_prob
  353. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  354. return drop_path(hidden_states, self.drop_prob, self.training)
  355. def extra_repr(self) -> str:
  356. return f"p={self.drop_prob}"
  357. class HieraMlp(nn.Module):
  358. def __init__(self, config, dim: int) -> None:
  359. super().__init__()
  360. self.activation_fn = ACT2FN[config.hidden_act]
  361. self.fc1 = nn.Linear(dim, int(dim * config.mlp_ratio))
  362. self.fc2 = nn.Linear(int(dim * config.mlp_ratio), dim)
  363. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  364. hidden_states = self.fc1(hidden_states)
  365. hidden_states = self.activation_fn(hidden_states)
  366. hidden_states = self.fc2(hidden_states)
  367. return hidden_states
  368. class HieraLayer(nn.Module):
  369. def __init__(
  370. self,
  371. config,
  372. hidden_size: int,
  373. hidden_size_output: int,
  374. num_heads: int,
  375. drop_path: float = 0.0,
  376. query_stride: int = 1,
  377. window_size: int = 0,
  378. use_mask_unit_attn: bool = False,
  379. ) -> None:
  380. super().__init__()
  381. self.hidden_size = hidden_size
  382. self.hidden_size_output = hidden_size_output
  383. self.query_stride = query_stride
  384. self.layernorm_before = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
  385. self.attn = HieraMaskUnitAttention(
  386. hidden_size=hidden_size,
  387. hidden_size_output=hidden_size_output,
  388. num_heads=num_heads,
  389. query_stride=query_stride,
  390. window_size=window_size,
  391. use_mask_unit_attn=use_mask_unit_attn,
  392. )
  393. self.layernorm_after = nn.LayerNorm(hidden_size_output, eps=config.layer_norm_eps)
  394. self.mlp = HieraMlp(config, hidden_size_output)
  395. self.drop_path = HieraDropPath(drop_path) if drop_path > 0 else nn.Identity()
  396. if hidden_size != hidden_size_output:
  397. self.proj = nn.Linear(hidden_size, hidden_size_output)
  398. def forward(
  399. self,
  400. hidden_states: torch.Tensor,
  401. head_mask: Optional[torch.FloatTensor] = None,
  402. output_attentions: bool = False,
  403. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  404. batch_size, seq_len, _ = hidden_states.shape
  405. # Attention + Q Pooling
  406. hidden_states_norm = self.layernorm_before(hidden_states)
  407. if self.hidden_size != self.hidden_size_output:
  408. hidden_states = self.proj(hidden_states_norm)
  409. # Refer to unroll to see how this performs a maxpool-Nd
  410. hidden_states = (
  411. hidden_states.view(batch_size, self.query_stride, -1, self.hidden_size_output).max(dim=1).values
  412. )
  413. (hidden_states_norm, attn_weights) = self.attn(
  414. hidden_states_norm, head_mask, output_attentions=output_attentions
  415. )
  416. hidden_states = hidden_states + self.drop_path(hidden_states_norm)
  417. residual = hidden_states
  418. hidden_states = self.layernorm_after(hidden_states)
  419. hidden_states = self.mlp(hidden_states)
  420. hidden_states = residual + self.drop_path(hidden_states)
  421. return (hidden_states, attn_weights)
  422. class HieraStage(GradientCheckpointingLayer):
  423. def __init__(
  424. self,
  425. config,
  426. depth: int,
  427. hidden_size: int,
  428. hidden_size_output: int,
  429. num_heads: int,
  430. drop_path: list[float],
  431. query_stride: list[int],
  432. window_size: int,
  433. use_mask_unit_attn: bool,
  434. stage_num: Optional[int] = None,
  435. ) -> None:
  436. super().__init__()
  437. # we need to know if the previous stage used masked attention
  438. # mask unit or global attention.
  439. # lag by 1 layer, so that global attention,
  440. # applied post pooling on lower resolution
  441. previous_stage_used_masked_attention = False
  442. if stage_num is not None:
  443. previous_stage_used_masked_attention = config.masked_unit_attention[stage_num - 1 if stage_num > 0 else 0]
  444. self.layers = nn.ModuleList(
  445. [
  446. HieraLayer(
  447. config=config,
  448. hidden_size=hidden_size if i == 0 else hidden_size_output,
  449. hidden_size_output=hidden_size_output,
  450. num_heads=num_heads,
  451. drop_path=drop_path[i],
  452. query_stride=query_stride[i],
  453. window_size=window_size,
  454. use_mask_unit_attn=use_mask_unit_attn or (previous_stage_used_masked_attention and i == 0),
  455. )
  456. for i in range(depth)
  457. ]
  458. )
  459. def forward(
  460. self, hidden_states: torch.Tensor, head_mask: Optional[torch.FloatTensor], output_attentions: bool = False
  461. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  462. for i, layer_module in enumerate(self.layers):
  463. layer_head_mask = head_mask[i] if head_mask is not None else None
  464. (hidden_states, attn_weights) = layer_module(
  465. hidden_states, layer_head_mask, output_attentions=output_attentions
  466. )
  467. return hidden_states, attn_weights
  468. def undo_windowing(hidden_states: torch.Tensor, shape: list[int], mask_unit_shape: list[int]) -> torch.Tensor:
  469. """
  470. Restore spatial organization by undoing windowed organization of mask units.
  471. Args:
  472. hidden_states (`torch.Tensor`): The hidden states tensor of shape `[batch_size, num_mask_unit_height*num_mask_unit_width, hidden_size]`.
  473. shape (`list[int]`): The original shape of the hidden states tensor before windowing.
  474. mask_unit_shape (`list[int]`): The shape of the mask units used for windowing.
  475. Returns:
  476. torch.Tensor: The restored hidden states tensor of shape [batch_size, num_mask_unit_height*mask_unit_height, num_mask_unit_width*mask_unit_width, hidden_size].
  477. """
  478. batch_size, hidden_size = hidden_states.shape[0], hidden_states.shape[-1]
  479. # From: [batch_size, num_mask_unit_height*num_mask_unit_width, hidden_size]
  480. # To: [batch_size, num_mask_unit_height, num_mask_unit_width, mask_unit_height, mask_unit_width, hidden_size]
  481. num_mask_units = [s // mu for s, mu in zip(shape, mask_unit_shape)]
  482. hidden_states = hidden_states.view(batch_size, *num_mask_units, *mask_unit_shape, hidden_size)
  483. # From: [batch_size, num_mask_unit_height, num_mask_unit_width, mask_unit_height, mask_unit_width, hidden_size]
  484. # To: [batch_size, num_mask_unit_height*mask_unit_height, num_mask_unit_width*mask_unit_width, hidden_size]
  485. hidden_states = hidden_states.permute(0, 1, 3, 2, 4, 5)
  486. hidden_states = hidden_states.reshape(batch_size, *shape, hidden_size)
  487. return hidden_states
  488. class HieraEncoder(nn.Module):
  489. def __init__(self, config: HieraConfig) -> None:
  490. super().__init__()
  491. total_depth = sum(config.depths)
  492. # stochastic depth decay rule
  493. dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, total_depth, device="cpu")]
  494. # query strides rule
  495. cumulative_depths = torch.tensor(config.depths, device="cpu").cumsum(0).tolist()
  496. query_pool_layer = cumulative_depths[: config.num_query_pool]
  497. query_strides = [math.prod(config.query_stride) if i in query_pool_layer else 1 for i in range(total_depth)]
  498. # Transformer blocks
  499. self.stages = nn.ModuleList()
  500. hidden_size = config.embed_dim
  501. stage_ends = [0] + cumulative_depths
  502. masked_unit_area = math.prod(config.masked_unit_size)
  503. query_stride_area = math.prod(config.query_stride)
  504. for idx_stage, depth in enumerate(config.depths):
  505. hidden_size_output = int(config.embed_dim * config.embed_dim_multiplier**idx_stage)
  506. stage = HieraStage(
  507. config=config,
  508. depth=depth,
  509. hidden_size=hidden_size,
  510. hidden_size_output=hidden_size_output,
  511. num_heads=config.num_heads[idx_stage],
  512. drop_path=dpr[stage_ends[idx_stage] : stage_ends[idx_stage + 1]],
  513. query_stride=query_strides[stage_ends[idx_stage] : stage_ends[idx_stage + 1]],
  514. window_size=int(masked_unit_area * query_stride_area**-idx_stage),
  515. use_mask_unit_attn=config.masked_unit_attention[idx_stage],
  516. stage_num=idx_stage,
  517. )
  518. hidden_size = hidden_size_output
  519. self.stages.append(stage)
  520. # Setting reroll schedule
  521. # The first stage has to reverse everything
  522. # The next stage has to reverse all but the first unroll, etc.
  523. stage_size = [i // s for i, s in zip(config.image_size, config.patch_stride)]
  524. unroll_schedule = [config.query_stride] * len(config.depths[:-1])
  525. self.schedule = {}
  526. for idx_stage in range(len(config.depths)):
  527. self.schedule[idx_stage] = unroll_schedule, stage_size
  528. if idx_stage < config.num_query_pool:
  529. stage_size = [i // s for i, s in zip(stage_size, config.query_stride)]
  530. unroll_schedule = unroll_schedule[1:]
  531. self.gradient_checkpointing = False
  532. def reroll(
  533. self, hidden_states: torch.Tensor, stage_idx: int, bool_masked_pos: Optional[torch.BoolTensor] = None
  534. ) -> torch.Tensor:
  535. """
  536. Roll the given tensor back up to spatial order assuming it's from the given block.
  537. If no bool_masked_pos is provided returns:
  538. - [batch_size, height, width, hidden_size]
  539. If a bool_masked_pos is provided returns:
  540. - [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
  541. """
  542. schedule, size = self.schedule[stage_idx]
  543. batch_size, seq_len, hidden_size = hidden_states.shape
  544. num_dim = len(size)
  545. mask_unit_shape = [1] * num_dim
  546. for strides in schedule:
  547. # Extract the current patch from seq_len
  548. hidden_states = hidden_states.view(
  549. batch_size, *strides, seq_len // math.prod(strides), *mask_unit_shape, hidden_size
  550. )
  551. # Move that patch into the current MU
  552. # Input: [batch_size, stride, stride, seq_len//(stride*stride), mask_unit_height, mask_unit_width, hidden_size]
  553. # Output: [batch_size, seq_len//(stride*stride), stride, mask_unit_height, stride, mask_unit_width, hidden_size]
  554. hidden_states = hidden_states.permute(0, 3, 1, 4, 2, 5, 6)
  555. # Reshape to [batch_size, seq_len//(stride*stride), *mask_units, hidden_size]
  556. for i in range(num_dim):
  557. mask_unit_shape[i] *= strides[i]
  558. hidden_states = hidden_states.reshape(batch_size, -1, *mask_unit_shape, hidden_size)
  559. seq_len = hidden_states.shape[1]
  560. # Current shape (e.g., 2d: [batch_size, #num_mask_units_height*#num_mask_units_width, mask_unit_height, mask_unit_width, hidden_size])
  561. hidden_states = hidden_states.view(batch_size, seq_len, *mask_unit_shape, hidden_size)
  562. # If masked, return [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
  563. if bool_masked_pos is not None:
  564. return hidden_states
  565. # If not masked, we can return [batch_size, height, width, hidden_size]
  566. hidden_states = undo_windowing(hidden_states, size, mask_unit_shape)
  567. return hidden_states
  568. def forward(
  569. self,
  570. hidden_states: torch.Tensor,
  571. bool_masked_pos: Optional[torch.BoolTensor] = None,
  572. head_mask: Optional[torch.FloatTensor] = None,
  573. output_attentions: bool = False,
  574. output_hidden_states: bool = False,
  575. return_dict: bool = True,
  576. ) -> Union[tuple, BaseModelOutput]:
  577. all_hidden_states = () if output_hidden_states else None
  578. all_reshaped_hidden_states = () if output_hidden_states else None
  579. all_self_attentions = () if output_attentions else None
  580. if output_hidden_states:
  581. all_hidden_states = all_hidden_states + (hidden_states,)
  582. reshaped_hidden_states = self.reroll(hidden_states, stage_idx=0, bool_masked_pos=bool_masked_pos)
  583. all_reshaped_hidden_states = all_reshaped_hidden_states + (reshaped_hidden_states,)
  584. for i, stage_module in enumerate(self.stages):
  585. layer_head_mask = head_mask[i] if head_mask is not None else None
  586. layer_outputs = stage_module(hidden_states, layer_head_mask, output_attentions)
  587. hidden_states = layer_outputs[0]
  588. if output_attentions:
  589. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  590. if output_hidden_states:
  591. all_hidden_states = all_hidden_states + (hidden_states,)
  592. reshaped_hidden_states = self.reroll(hidden_states, stage_idx=i, bool_masked_pos=bool_masked_pos)
  593. all_reshaped_hidden_states = all_reshaped_hidden_states + (reshaped_hidden_states,)
  594. if not return_dict:
  595. return tuple(
  596. v
  597. for v in [hidden_states, all_hidden_states, all_self_attentions, all_reshaped_hidden_states]
  598. if v is not None
  599. )
  600. return HieraEncoderOutput(
  601. last_hidden_state=hidden_states,
  602. hidden_states=all_hidden_states,
  603. attentions=all_self_attentions,
  604. reshaped_hidden_states=all_reshaped_hidden_states,
  605. )
  606. def unroll(
  607. hidden_states: torch.Tensor, image_shape: tuple[int, int], patch_stride: tuple[int, int], schedule: list[list[int]]
  608. ) -> torch.Tensor:
  609. """
  610. Reorders the tokens such that patches are contiguous in memory.
  611. E.g., given [batch_size, (height, width), hidden_size] and stride of (stride, stride), this will re-order the tokens as
  612. [batch_size, (stride, stride, height // stride, width // stride), hidden_size]
  613. This allows operations like Max2d to be computed as x.view(batch_size, stride*stride, -1, hidden_size).max(dim=1).
  614. Not only is this faster, but it also makes it easy to support inputs of arbitrary
  615. dimensions in addition to patch-wise sparsity.
  616. Performing this operation multiple times in sequence puts entire windows as contiguous
  617. in memory. For instance, if you applied the stride (2, 2) 3 times, entire windows of
  618. size 8x8 would be contiguous in memory, allowing operations like mask unit attention
  619. computed easily and efficiently, while also allowing max to be applied sequentially.
  620. Note: This means that intermediate values of the model are not in height x width order, so they
  621. need to be re-rolled if you want to use the intermediate values as a height x width feature map.
  622. The last block of the network is fine though, since by then the strides are all consumed.
  623. """
  624. batch_size, _, hidden_size = hidden_states.shape
  625. size = [i // s for i, s in zip(image_shape, patch_stride)]
  626. current_size = size
  627. hidden_states = hidden_states.view(*([batch_size] + current_size + [hidden_size]))
  628. for strides in schedule:
  629. # Move patches with the given strides to the batch dimension
  630. # Create a view of the tensor with the patch stride as separate dims
  631. # For example in 2d: [batch_size, height // stride, stride, width // stride, stride, C]
  632. current_size = [i // s for i, s in zip(current_size, strides)]
  633. # initialize new_shape with [height // stride, stride, width // stride, stride]
  634. new_shape = [item for pair in zip(current_size, strides) for item in pair]
  635. # add batch_size and hidden_size to new_shape
  636. new_shape = [batch_size] + new_shape + [hidden_size]
  637. hidden_states = hidden_states.view(new_shape)
  638. # Move the patch stride into the batch dimension
  639. # For example in 2d: [batch_size, stride, stride, height // stride, width // stride, hidden_size]
  640. num_dims = len(new_shape)
  641. permute = [0] + list(range(2, num_dims - 1, 2)) + list(range(1, num_dims - 1, 2)) + [num_dims - 1]
  642. hidden_states = hidden_states.permute(permute)
  643. # Now finally flatten the relevant dims into the batch dimension
  644. hidden_states = hidden_states.flatten(0, len(strides))
  645. batch_size *= math.prod(strides)
  646. hidden_states = hidden_states.reshape(-1, math.prod(size), hidden_size)
  647. return hidden_states
  648. @auto_docstring
  649. class HieraPreTrainedModel(PreTrainedModel):
  650. config: HieraConfig
  651. base_model_prefix = "hiera"
  652. main_input_name = "pixel_values"
  653. supports_gradient_checkpointing = True
  654. def _init_weights(self, module) -> None:
  655. """Initialize the weights"""
  656. std = self.config.initializer_range
  657. if isinstance(module, HieraEmbeddings):
  658. nn.init.trunc_normal_(module.position_embeddings, std=std)
  659. elif isinstance(module, HieraDecoder):
  660. nn.init.trunc_normal_(module.mask_token, std=std)
  661. nn.init.trunc_normal_(module.decoder_position_embeddings, std=std)
  662. elif isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv2d)):
  663. nn.init.trunc_normal_(module.weight, std=std)
  664. if module.bias is not None:
  665. nn.init.constant_(module.bias, std)
  666. elif isinstance(module, nn.LayerNorm):
  667. nn.init.constant_(module.bias, std)
  668. nn.init.constant_(module.weight, self.config.layer_norm_init)
  669. class HieraPooler(nn.Module):
  670. def __init__(self, config: HieraConfig):
  671. super().__init__()
  672. num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
  673. self.layernorm = nn.LayerNorm(num_features, eps=config.layer_norm_eps)
  674. self.pooler = nn.AdaptiveAvgPool1d(1)
  675. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  676. hidden_states = hidden_states.transpose(1, 2)
  677. pooled_output = self.pooler(hidden_states)
  678. pooled_output = torch.flatten(pooled_output, 1)
  679. pooled_output = self.layernorm(pooled_output)
  680. return pooled_output
  681. @auto_docstring
  682. class HieraModel(HieraPreTrainedModel):
  683. def __init__(self, config: HieraConfig, add_pooling_layer: bool = True, is_mae: bool = False):
  684. r"""
  685. add_pooling_layer (`bool`, *optional*, defaults to `True`):
  686. Whether or not to apply pooling layer.
  687. is_mae (`bool`, *optional*, defaults to `False`):
  688. Whether or not to run the model on MAE mode.
  689. """
  690. super().__init__(config)
  691. self.num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
  692. self.embeddings = HieraEmbeddings(config, is_mae=is_mae)
  693. self.encoder = HieraEncoder(config)
  694. self.unroll_schedule = [config.query_stride] * len(config.depths[:-1])
  695. self.pooler = HieraPooler(config) if add_pooling_layer else None
  696. # Initialize weights and apply final processing
  697. self.post_init()
  698. def get_input_embeddings(self) -> HieraPatchEmbeddings:
  699. return self.embeddings.patch_embeddings
  700. def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
  701. """
  702. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  703. class PreTrainedModel
  704. """
  705. for layer, heads in heads_to_prune.items():
  706. self.encoder.layer[layer].attention.prune_heads(heads)
  707. @auto_docstring
  708. def forward(
  709. self,
  710. pixel_values: Optional[torch.Tensor] = None,
  711. noise: Optional[torch.FloatTensor] = None,
  712. head_mask: Optional[torch.Tensor] = None,
  713. output_attentions: Optional[bool] = None,
  714. output_hidden_states: Optional[bool] = None,
  715. interpolate_pos_encoding: Optional[bool] = None,
  716. return_dict: Optional[bool] = None,
  717. ) -> Union[tuple, BaseModelOutputWithPooling]:
  718. r"""
  719. noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*):
  720. Mainly used for testing purposes to control randomness and maintain the reproducibility
  721. """
  722. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  723. output_hidden_states = (
  724. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  725. )
  726. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  727. if pixel_values is None:
  728. raise ValueError("You have to specify pixel_values")
  729. # Prepare head mask if needed
  730. # 1.0 in head_mask indicate we keep the head
  731. # attention_probs has shape bsz x n_heads x N x N
  732. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  733. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  734. head_mask = self.get_head_mask(head_mask, len(self.config.depths))
  735. embedding_output, bool_masked_pos, ids_restore = self.embeddings(
  736. pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, noise=noise
  737. )
  738. image_shape = (pixel_values.shape[-2], pixel_values.shape[-1])
  739. hidden_states = unroll(
  740. embedding_output,
  741. image_shape=image_shape,
  742. patch_stride=self.config.patch_stride,
  743. schedule=self.unroll_schedule,
  744. )
  745. # Discard masked tokens if bool_masked_pos is provided
  746. if bool_masked_pos is not None:
  747. mask_unit_area = math.prod(self.config.masked_unit_size)
  748. batch_size, _, hidden_size = hidden_states.shape
  749. positions = bool_masked_pos.unsqueeze(-1).tile(1, mask_unit_area, hidden_size)
  750. hidden_states = hidden_states[positions]
  751. hidden_states = hidden_states.view(batch_size, -1, hidden_size)
  752. encoder_outputs = self.encoder(
  753. hidden_states,
  754. bool_masked_pos=bool_masked_pos,
  755. head_mask=head_mask,
  756. output_attentions=output_attentions,
  757. output_hidden_states=output_hidden_states,
  758. return_dict=return_dict,
  759. )
  760. sequence_output = encoder_outputs[0]
  761. pooled_output = None
  762. if self.pooler is not None:
  763. pooled_output = self.pooler(sequence_output)
  764. if not return_dict:
  765. head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
  766. head_outputs = (
  767. head_outputs + (bool_masked_pos, ids_restore) if bool_masked_pos is not None else head_outputs
  768. )
  769. return head_outputs + encoder_outputs[1:]
  770. return HieraModelOutput(
  771. last_hidden_state=sequence_output,
  772. pooler_output=pooled_output,
  773. bool_masked_pos=bool_masked_pos,
  774. ids_restore=ids_restore,
  775. hidden_states=encoder_outputs.hidden_states,
  776. attentions=encoder_outputs.attentions,
  777. reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
  778. )
  779. class HieraDecoder(nn.Module):
  780. def __init__(self, config: HieraConfig):
  781. super().__init__()
  782. num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
  783. tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
  784. self.tokens_spatial_shape_final = [
  785. i // s ** (config.num_query_pool) for i, s in zip(tokens_spatial_shape, config.query_stride)
  786. ]
  787. self.mask_unit_spatial_shape_final = [
  788. i // s ** (config.num_query_pool) for i, s in zip(config.masked_unit_size, config.query_stride)
  789. ]
  790. self.decoder_embeddings = nn.Linear(num_features, config.decoder_hidden_size)
  791. self.mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
  792. self.decoder_position_embeddings = nn.Parameter(
  793. torch.zeros(1, math.prod(self.tokens_spatial_shape_final), config.decoder_hidden_size)
  794. )
  795. self.decoder_block = HieraStage(
  796. config=config,
  797. hidden_size=config.decoder_hidden_size,
  798. hidden_size_output=config.decoder_hidden_size,
  799. num_heads=config.decoder_num_heads,
  800. depth=config.decoder_depth,
  801. use_mask_unit_attn=False,
  802. drop_path=[0.0] * config.decoder_depth,
  803. query_stride=[1] * config.decoder_depth,
  804. window_size=0,
  805. )
  806. self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
  807. # patch stride of prediction
  808. self.pred_stride = config.patch_stride[-1] * (config.query_stride[-1] ** config.num_query_pool)
  809. pred_dim = (self.pred_stride ** len(config.query_stride)) * config.num_channels
  810. self.decoder_pred = nn.Linear(config.decoder_hidden_size, pred_dim)
  811. def forward(
  812. self,
  813. encoder_hidden_states: torch.Tensor,
  814. bool_masked_pos: torch.BoolTensor,
  815. head_mask: Optional[torch.Tensor] = None,
  816. output_attentions: bool = False,
  817. ) -> tuple[torch.Tensor, torch.BoolTensor]:
  818. # Embed tokens
  819. hidden_states = self.decoder_embeddings(encoder_hidden_states)
  820. # Combine visible and bool_masked_pos tokens
  821. # hidden_states : [batch_size, num_mask_units_visible, *mask_unit_spatial_shape_final, decoder_hidden_size]
  822. # bool_masked_pos: [batch_size, num_mask_units]
  823. mask_unit_height, mask_unit_width, decoder_hidden_size = hidden_states.shape[2:]
  824. batch_size, num_mask_units = bool_masked_pos.shape
  825. decoder_hidden_states = torch.zeros(
  826. batch_size,
  827. num_mask_units,
  828. mask_unit_height,
  829. mask_unit_width,
  830. decoder_hidden_size,
  831. device=hidden_states.device,
  832. dtype=hidden_states.dtype,
  833. )
  834. mask_tokens = self.mask_token.view(1, 1, 1, 1, -1)
  835. bool_masked_pos = bool_masked_pos.reshape(batch_size, num_mask_units, 1, 1, 1)
  836. bool_masked_pos = bool_masked_pos.expand(-1, -1, mask_unit_height, mask_unit_width, decoder_hidden_size)
  837. decoder_hidden_states[bool_masked_pos] = hidden_states.flatten()
  838. decoder_hidden_states = (
  839. 1 - bool_masked_pos.float()
  840. ) * mask_tokens + bool_masked_pos.float() * decoder_hidden_states
  841. # Get back spatial order
  842. hidden_states = undo_windowing(
  843. decoder_hidden_states,
  844. self.tokens_spatial_shape_final,
  845. self.mask_unit_spatial_shape_final,
  846. )
  847. bool_masked_pos = undo_windowing(
  848. bool_masked_pos[..., 0:1],
  849. self.tokens_spatial_shape_final,
  850. self.mask_unit_spatial_shape_final,
  851. )
  852. # Flatten
  853. hidden_states = hidden_states.reshape(hidden_states.shape[0], -1, hidden_states.shape[-1])
  854. bool_masked_pos = bool_masked_pos.view(hidden_states.shape[0], -1)
  855. # Add pos embed
  856. hidden_states = hidden_states + self.decoder_position_embeddings
  857. # Apply decoder blocks
  858. hidden_states, attn_weights = self.decoder_block(
  859. hidden_states, head_mask=head_mask, output_attentions=output_attentions
  860. )
  861. hidden_states = self.decoder_norm(hidden_states)
  862. # Predictor projection
  863. hidden_states = self.decoder_pred(hidden_states)
  864. return hidden_states, bool_masked_pos
  865. class HieraMultiScaleHead(nn.Module):
  866. def __init__(self, config: HieraConfig):
  867. super().__init__()
  868. self.mask_unit_spatial_shape_final = [
  869. i // s ** (config.num_query_pool) for i, s in zip(config.masked_unit_size, config.query_stride)
  870. ]
  871. self.stage_dimensions = [
  872. int(config.embed_dim * config.embed_dim_multiplier**i) for i in range(len(config.depths))
  873. ]
  874. current_masked_unit_size = config.masked_unit_size
  875. self.multi_scale_fusion_heads = nn.ModuleList()
  876. for idx in range(config.num_query_pool):
  877. kernel = [i // s for i, s in zip(current_masked_unit_size, self.mask_unit_spatial_shape_final)]
  878. current_masked_unit_size = [i // s for i, s in zip(current_masked_unit_size, config.query_stride)]
  879. self.multi_scale_fusion_heads.append(
  880. nn.Conv2d(
  881. self.stage_dimensions[idx],
  882. self.stage_dimensions[-1],
  883. kernel_size=kernel,
  884. stride=kernel,
  885. )
  886. )
  887. self.multi_scale_fusion_heads.append(nn.Identity())
  888. def apply_fusion_head(self, head: nn.Module, hidden_states: torch.Tensor) -> torch.Tensor:
  889. if isinstance(head, nn.Identity):
  890. return hidden_states
  891. # Doing explicit to avoid problems with torch.fx
  892. batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size = hidden_states.shape
  893. # From: [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
  894. # To: head([batch_size * num_mask_units, hidden_size, mask_unit_height, mask_unit_width])
  895. hidden_states = hidden_states.reshape(
  896. batch_size * num_mask_units, mask_unit_height, mask_unit_width, hidden_size
  897. )
  898. hidden_states = hidden_states.permute(0, 3, 1, 2)
  899. hidden_states = head(hidden_states)
  900. # Restore original layout
  901. hidden_states = hidden_states.permute(0, 2, 3, 1)
  902. mask_unit_height_final, mask_unit_width_final, hidden_size = hidden_states.shape[1:]
  903. hidden_states = hidden_states.reshape(
  904. batch_size, num_mask_units, mask_unit_height_final, mask_unit_width_final, hidden_size
  905. )
  906. return hidden_states
  907. def forward(self, feature_maps: list[torch.Tensor]) -> torch.Tensor:
  908. # Multi-scale fusion
  909. hidden_states = 0.0
  910. for head, feature_map in zip(self.multi_scale_fusion_heads, feature_maps):
  911. hidden_states = hidden_states + self.apply_fusion_head(head, feature_map)
  912. return hidden_states
  913. @auto_docstring(
  914. custom_intro="""
  915. The Hiera Model transformer with the decoder on top for self-supervised pre-training.
  916. <Tip>
  917. Note that we provide a script to pre-train this model on custom data in our [examples
  918. directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
  919. </Tip>
  920. """
  921. )
  922. class HieraForPreTraining(HieraPreTrainedModel):
  923. def __init__(self, config: HieraConfig) -> None:
  924. super().__init__(config)
  925. # Encoder
  926. self.hiera = HieraModel(config, add_pooling_layer=False, is_mae=True)
  927. self.encoder_norm = nn.LayerNorm(self.hiera.num_features, eps=config.layer_norm_eps)
  928. # Multi-scale fusion heads
  929. self.multiscale_fusion = HieraMultiScaleHead(config)
  930. # Decoder
  931. self.decoder = HieraDecoder(config)
  932. self.pred_stride = self.decoder.pred_stride
  933. # Initialize weights and apply final processing
  934. self.post_init()
  935. def get_pixel_label_2d(self, pixel_values: torch.Tensor, bool_masked_pos: torch.BoolTensor) -> torch.Tensor:
  936. # bool_masked_pos (boolean tensor): True means *masked*
  937. pixel_values = pixel_values.permute(0, 2, 3, 1)
  938. size = self.pred_stride
  939. label = pixel_values.unfold(1, size, size).unfold(2, size, size)
  940. label = label.flatten(1, 2).flatten(2)
  941. label = label[bool_masked_pos]
  942. if self.config.normalize_pixel_loss:
  943. mean = label.mean(dim=-1, keepdim=True)
  944. var = label.var(dim=-1, keepdim=True)
  945. label = (label - mean) / (var + 1.0e-6) ** 0.5
  946. return label
  947. def forward_loss(self, pixel_values: torch.Tensor, logits: torch.Tensor, bool_masked_pos: torch.BoolTensor):
  948. # We invert the bool_masked_pos such that 1.0 is *masked*
  949. bool_masked_pos = ~bool_masked_pos
  950. label = self.get_pixel_label_2d(pixel_values, bool_masked_pos)
  951. logits = logits[bool_masked_pos]
  952. loss = (logits - label) ** 2
  953. loss = loss.mean()
  954. return loss
  955. @auto_docstring
  956. def forward(
  957. self,
  958. pixel_values: Optional[torch.Tensor] = None,
  959. noise: Optional[torch.FloatTensor] = None,
  960. head_mask: Optional[torch.Tensor] = None,
  961. output_attentions: Optional[bool] = None,
  962. output_hidden_states: Optional[bool] = None,
  963. interpolate_pos_encoding: Optional[bool] = None,
  964. return_dict: Optional[bool] = None,
  965. ) -> Union[tuple, HieraForPreTrainingOutput]:
  966. r"""
  967. noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*):
  968. Mainly used for testing purposes to control randomness and maintain the reproducibility
  969. Examples:
  970. ```python
  971. >>> from transformers import AutoImageProcessor, HieraForPreTraining
  972. >>> import torch
  973. >>> from PIL import Image
  974. >>> import requests
  975. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  976. >>> image = Image.open(requests.get(url, stream=True).raw)
  977. >>> image_processor = AutoImageProcessor.from_pretrained("facebook/hiera-tiny-224-mae-hf")
  978. >>> model = HieraForPreTraining.from_pretrained("facebook/hiera-tiny-224-mae-hf")
  979. >>> inputs = image_processor(images=image, return_tensors="pt")
  980. >>> outputs = model(**inputs)
  981. >>> logits = outputs.logits
  982. >>> loss = outputs.loss
  983. >>> print(list(logits.shape))
  984. [1, 196, 768]
  985. ```"""
  986. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  987. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  988. output_hidden_states = (
  989. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  990. )
  991. outputs = self.hiera(
  992. pixel_values,
  993. noise=noise,
  994. head_mask=head_mask,
  995. output_attentions=output_attentions,
  996. output_hidden_states=True,
  997. interpolate_pos_encoding=interpolate_pos_encoding,
  998. return_dict=return_dict,
  999. )
  1000. feature_maps = outputs[-1]
  1001. bool_masked_pos = outputs[1]
  1002. ids_to_restore = outputs[2]
  1003. # Take only the query pooled and last hidden states
  1004. feature_maps = feature_maps[1 : self.hiera.config.num_query_pool + 1] + (feature_maps[-1],)
  1005. fused_hidden_states = self.multiscale_fusion(feature_maps)
  1006. fused_hidden_states = self.encoder_norm(fused_hidden_states)
  1007. # Reconstruct pixel values
  1008. logits, bool_masked_pos = self.decoder(
  1009. fused_hidden_states,
  1010. bool_masked_pos=bool_masked_pos,
  1011. head_mask=head_mask,
  1012. output_attentions=output_attentions,
  1013. )
  1014. loss = self.forward_loss(pixel_values, logits, bool_masked_pos)
  1015. if not return_dict:
  1016. output = (logits, bool_masked_pos, ids_to_restore)
  1017. if output_hidden_states:
  1018. output = output + (outputs[3],)
  1019. if output_attentions:
  1020. output = output + (outputs[4],)
  1021. if output_hidden_states:
  1022. output = output + (outputs[-1],)
  1023. return ((loss,) + output) if loss is not None else output
  1024. return HieraForPreTrainingOutput(
  1025. loss=loss,
  1026. logits=logits,
  1027. bool_masked_pos=bool_masked_pos,
  1028. ids_restore=ids_to_restore,
  1029. hidden_states=outputs.hidden_states if output_hidden_states else None,
  1030. attentions=outputs.attentions,
  1031. reshaped_hidden_states=outputs.reshaped_hidden_states if output_hidden_states else None,
  1032. )
  1033. @auto_docstring(
  1034. custom_intro="""
  1035. Hiera Model transformer with an image classification head on top (a linear layer on top of the final hidden state with
  1036. average pooling) e.g. for ImageNet.
  1037. <Tip>
  1038. Note that it's possible to fine-tune Hiera on higher resolution images than the ones it has been trained on, by
  1039. setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
  1040. position embeddings to the higher resolution.
  1041. </Tip>
  1042. """
  1043. )
  1044. class HieraForImageClassification(HieraPreTrainedModel):
  1045. def __init__(self, config: HieraConfig) -> None:
  1046. super().__init__(config)
  1047. self.num_labels = config.num_labels
  1048. self.hiera = HieraModel(config, add_pooling_layer=True, is_mae=False)
  1049. # Classifier head
  1050. self.classifier = (
  1051. nn.Linear(self.hiera.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
  1052. )
  1053. # Initialize weights and apply final processing
  1054. self.post_init()
  1055. @auto_docstring
  1056. def forward(
  1057. self,
  1058. pixel_values,
  1059. head_mask: Optional[torch.Tensor] = None,
  1060. labels: Optional[torch.Tensor] = None,
  1061. output_attentions: Optional[bool] = None,
  1062. output_hidden_states: Optional[bool] = None,
  1063. interpolate_pos_encoding: Optional[bool] = None,
  1064. return_dict: Optional[bool] = None,
  1065. ) -> Union[tuple, HieraForImageClassificationOutput]:
  1066. r"""
  1067. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1068. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  1069. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1070. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1071. """
  1072. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1073. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1074. output_hidden_states = (
  1075. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1076. )
  1077. outputs = self.hiera(
  1078. pixel_values,
  1079. head_mask=head_mask,
  1080. output_attentions=output_attentions,
  1081. output_hidden_states=output_hidden_states,
  1082. interpolate_pos_encoding=interpolate_pos_encoding,
  1083. return_dict=return_dict,
  1084. )
  1085. pooled_output = outputs[1]
  1086. logits = self.classifier(pooled_output)
  1087. loss = None
  1088. if labels is not None:
  1089. loss = self.loss_function(labels, logits, self.config)
  1090. if not return_dict:
  1091. output = (logits,) + outputs[2:]
  1092. return ((loss,) + output) if loss is not None else output
  1093. return HieraForImageClassificationOutput(
  1094. loss=loss,
  1095. logits=logits,
  1096. hidden_states=outputs.hidden_states,
  1097. attentions=outputs.attentions,
  1098. reshaped_hidden_states=outputs.reshaped_hidden_states,
  1099. )
  1100. @auto_docstring(
  1101. custom_intro="""
  1102. Hiera backbone, to be used with frameworks like DETR and MaskFormer.
  1103. """
  1104. )
  1105. class HieraBackbone(HieraPreTrainedModel, BackboneMixin):
  1106. def __init__(self, config: HieraConfig):
  1107. super().__init__(config)
  1108. super()._init_backbone(config)
  1109. self.num_features = [config.embed_dim] + [
  1110. int(config.embed_dim * config.embed_dim_multiplier**i) for i in range(len(config.depths))
  1111. ]
  1112. self.embeddings = HieraEmbeddings(config, is_mae=False)
  1113. self.encoder = HieraEncoder(config)
  1114. # Add layer norms to hidden states of out_features
  1115. hidden_states_norms = {}
  1116. for stage, num_channels in zip(self._out_features, self.channels):
  1117. hidden_states_norms[stage] = nn.LayerNorm(num_channels)
  1118. self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
  1119. # Initialize weights and apply final processing
  1120. self.post_init()
  1121. def get_input_embeddings(self):
  1122. return self.embeddings.patch_embeddings
  1123. def forward(
  1124. self,
  1125. pixel_values: torch.Tensor,
  1126. output_hidden_states: Optional[bool] = None,
  1127. output_attentions: Optional[bool] = None,
  1128. return_dict: Optional[bool] = None,
  1129. ) -> BackboneOutput:
  1130. """
  1131. Returns:
  1132. Examples:
  1133. ```python
  1134. >>> from transformers import AutoImageProcessor, AutoBackbone
  1135. >>> import torch
  1136. >>> from PIL import Image
  1137. >>> import requests
  1138. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1139. >>> image = Image.open(requests.get(url, stream=True).raw)
  1140. >>> processor = AutoImageProcessor.from_pretrained("facebook/hiera-tiny-224-hf")
  1141. >>> model = AutoBackbone.from_pretrained(
  1142. ... "facebook/hiera-tiny-224-hf", out_features=["stage1", "stage2", "stage3", "stage4"]
  1143. ... )
  1144. >>> inputs = processor(image, return_tensors="pt")
  1145. >>> outputs = model(**inputs)
  1146. >>> feature_maps = outputs.feature_maps
  1147. >>> list(feature_maps[-1].shape)
  1148. [1, 768, 7, 7]
  1149. ```"""
  1150. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1151. output_hidden_states = (
  1152. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1153. )
  1154. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1155. embedding_output, _, _ = self.embeddings(pixel_values)
  1156. outputs = self.encoder(
  1157. embedding_output,
  1158. head_mask=None,
  1159. output_attentions=output_attentions,
  1160. output_hidden_states=True,
  1161. return_dict=return_dict,
  1162. )
  1163. hidden_states = outputs[-1]
  1164. feature_maps = ()
  1165. for stage, hidden_state in zip(self.stage_names, hidden_states):
  1166. if stage in self.out_features:
  1167. batch_size, height, width, num_channels = hidden_state.shape
  1168. hidden_state = hidden_state.view(batch_size, height * width, num_channels)
  1169. hidden_state = self.hidden_states_norms[stage](hidden_state)
  1170. hidden_state = hidden_state.view(batch_size, height, width, num_channels)
  1171. hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
  1172. feature_maps += (hidden_state,)
  1173. if not return_dict:
  1174. output = (feature_maps,)
  1175. if output_hidden_states:
  1176. output += (outputs[1],)
  1177. if output_attentions:
  1178. output += (outputs[2],)
  1179. return output
  1180. return BackboneOutput(
  1181. feature_maps=feature_maps,
  1182. hidden_states=outputs[1] if output_hidden_states else None,
  1183. attentions=outputs[2] if output_attentions else None,
  1184. )
  1185. __all__ = ["HieraForImageClassification", "HieraForPreTraining", "HieraBackbone", "HieraModel", "HieraPreTrainedModel"]