modeling_ijepa.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/ijepa/modular_ijepa.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_ijepa.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. import collections.abc
  8. from typing import Callable, Optional, Union
  9. import torch
  10. import torch.nn as nn
  11. from ...activations import ACT2FN
  12. from ...modeling_layers import GradientCheckpointingLayer
  13. from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
  14. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  15. from ...processing_utils import Unpack
  16. from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
  17. from ...utils import TransformersKwargs, auto_docstring, torch_int
  18. from ...utils.generic import can_return_tuple, check_model_inputs
  19. from .configuration_ijepa import IJepaConfig
  20. class IJepaPatchEmbeddings(nn.Module):
  21. """
  22. This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
  23. `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
  24. Transformer.
  25. """
  26. def __init__(self, config: IJepaConfig):
  27. super().__init__()
  28. image_size, patch_size = config.image_size, config.patch_size
  29. num_channels, hidden_size = config.num_channels, config.hidden_size
  30. image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
  31. patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
  32. num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  33. self.image_size = image_size
  34. self.patch_size = patch_size
  35. self.num_channels = num_channels
  36. self.num_patches = num_patches
  37. self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
  38. def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
  39. batch_size, num_channels, height, width = pixel_values.shape
  40. if num_channels != self.num_channels:
  41. raise ValueError(
  42. "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
  43. f" Expected {self.num_channels} but got {num_channels}."
  44. )
  45. if not interpolate_pos_encoding:
  46. if height != self.image_size[0] or width != self.image_size[1]:
  47. raise ValueError(
  48. f"Input image size ({height}*{width}) doesn't match model"
  49. f" ({self.image_size[0]}*{self.image_size[1]})."
  50. )
  51. embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
  52. return embeddings
  53. class IJepaEmbeddings(nn.Module):
  54. """
  55. Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
  56. """
  57. def __init__(self, config: IJepaConfig, use_mask_token: bool = False) -> None:
  58. super().__init__()
  59. self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
  60. self.patch_embeddings = IJepaPatchEmbeddings(config)
  61. num_patches = self.patch_embeddings.num_patches
  62. self.position_embeddings = nn.Parameter(torch.randn(1, num_patches, config.hidden_size))
  63. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  64. self.patch_size = config.patch_size
  65. self.config = config
  66. def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
  67. """
  68. This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
  69. images. This method is also adapted to support torch.jit tracing.
  70. Adapted from:
  71. - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
  72. - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
  73. """
  74. num_patches = embeddings.shape[1]
  75. num_positions = self.position_embeddings.shape[1]
  76. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  77. if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
  78. return self.position_embeddings
  79. patch_pos_embed = self.position_embeddings
  80. dim = embeddings.shape[-1]
  81. new_height = height // self.patch_size
  82. new_width = width // self.patch_size
  83. sqrt_num_positions = torch_int(num_positions**0.5)
  84. patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
  85. patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
  86. patch_pos_embed = nn.functional.interpolate(
  87. patch_pos_embed,
  88. size=(new_height, new_width),
  89. mode="bicubic",
  90. align_corners=False,
  91. )
  92. patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
  93. return patch_pos_embed
  94. def forward(
  95. self,
  96. pixel_values: torch.Tensor,
  97. bool_masked_pos: Optional[torch.BoolTensor] = None,
  98. interpolate_pos_encoding: bool = False,
  99. ) -> torch.Tensor:
  100. batch_size, _, height, width = pixel_values.shape
  101. embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
  102. if bool_masked_pos is not None:
  103. seq_length = embeddings.shape[1]
  104. mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
  105. # replace the masked visual tokens by mask_tokens
  106. mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
  107. embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
  108. # add positional encoding to each token
  109. if interpolate_pos_encoding:
  110. embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
  111. else:
  112. embeddings = embeddings + self.position_embeddings
  113. embeddings = self.dropout(embeddings)
  114. return embeddings
  115. def eager_attention_forward(
  116. module: nn.Module,
  117. query: torch.Tensor,
  118. key: torch.Tensor,
  119. value: torch.Tensor,
  120. attention_mask: Optional[torch.Tensor],
  121. scaling: float,
  122. dropout: float = 0.0,
  123. **kwargs,
  124. ):
  125. # Take the dot product between "query" and "key" to get the raw attention scores.
  126. attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
  127. # Normalize the attention scores to probabilities.
  128. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  129. # This is actually dropping out entire tokens to attend to, which might
  130. # seem a bit unusual, but is taken from the original Transformer paper.
  131. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  132. # Mask heads if we want to
  133. if attention_mask is not None:
  134. attn_weights = attn_weights * attention_mask
  135. attn_output = torch.matmul(attn_weights, value)
  136. attn_output = attn_output.transpose(1, 2).contiguous()
  137. return attn_output, attn_weights
  138. class IJepaSelfAttention(nn.Module):
  139. def __init__(self, config: IJepaConfig):
  140. super().__init__()
  141. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  142. raise ValueError(
  143. f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
  144. f"heads {config.num_attention_heads}."
  145. )
  146. self.config = config
  147. self.num_attention_heads = config.num_attention_heads
  148. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  149. self.all_head_size = self.num_attention_heads * self.attention_head_size
  150. self.dropout_prob = config.attention_probs_dropout_prob
  151. self.scaling = self.attention_head_size**-0.5
  152. self.is_causal = False
  153. self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
  154. self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
  155. self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
  156. def forward(
  157. self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None
  158. ) -> tuple[torch.Tensor, torch.Tensor]:
  159. batch_size = hidden_states.shape[0]
  160. new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size
  161. key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2)
  162. value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2)
  163. query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2)
  164. attention_interface: Callable = eager_attention_forward
  165. if self.config._attn_implementation != "eager":
  166. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  167. context_layer, attention_probs = attention_interface(
  168. self,
  169. query_layer,
  170. key_layer,
  171. value_layer,
  172. head_mask,
  173. is_causal=self.is_causal,
  174. scaling=self.scaling,
  175. dropout=0.0 if not self.training else self.dropout_prob,
  176. )
  177. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  178. context_layer = context_layer.reshape(new_context_layer_shape)
  179. return context_layer, attention_probs
  180. class IJepaSelfOutput(nn.Module):
  181. """
  182. The residual connection is defined in IJepaLayer instead of here (as is the case with other models), due to the
  183. layernorm applied before each block.
  184. """
  185. def __init__(self, config: IJepaConfig):
  186. super().__init__()
  187. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  188. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  189. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  190. hidden_states = self.dense(hidden_states)
  191. hidden_states = self.dropout(hidden_states)
  192. return hidden_states
  193. class IJepaAttention(nn.Module):
  194. def __init__(self, config: IJepaConfig):
  195. super().__init__()
  196. self.attention = IJepaSelfAttention(config)
  197. self.output = IJepaSelfOutput(config)
  198. self.pruned_heads = set()
  199. def prune_heads(self, heads: set[int]):
  200. if len(heads) == 0:
  201. return
  202. heads, index = find_pruneable_heads_and_indices(
  203. heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
  204. )
  205. # Prune linear layers
  206. self.attention.query = prune_linear_layer(self.attention.query, index)
  207. self.attention.key = prune_linear_layer(self.attention.key, index)
  208. self.attention.value = prune_linear_layer(self.attention.value, index)
  209. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  210. # Update hyper params and store pruned heads
  211. self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
  212. self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
  213. self.pruned_heads = self.pruned_heads.union(heads)
  214. def forward(self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
  215. self_attn_output, _ = self.attention(hidden_states, head_mask)
  216. output = self.output(self_attn_output, hidden_states)
  217. return output
  218. class IJepaIntermediate(nn.Module):
  219. def __init__(self, config: IJepaConfig):
  220. super().__init__()
  221. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  222. if isinstance(config.hidden_act, str):
  223. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  224. else:
  225. self.intermediate_act_fn = config.hidden_act
  226. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  227. hidden_states = self.dense(hidden_states)
  228. hidden_states = self.intermediate_act_fn(hidden_states)
  229. return hidden_states
  230. class IJepaOutput(nn.Module):
  231. def __init__(self, config: IJepaConfig):
  232. super().__init__()
  233. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  234. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  235. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  236. hidden_states = self.dense(hidden_states)
  237. hidden_states = self.dropout(hidden_states)
  238. hidden_states = hidden_states + input_tensor
  239. return hidden_states
  240. class IJepaLayer(GradientCheckpointingLayer):
  241. """This corresponds to the Block class in the timm implementation."""
  242. def __init__(self, config: IJepaConfig):
  243. super().__init__()
  244. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  245. self.seq_len_dim = 1
  246. self.attention = IJepaAttention(config)
  247. self.intermediate = IJepaIntermediate(config)
  248. self.output = IJepaOutput(config)
  249. self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  250. self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  251. def forward(self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
  252. hidden_states_norm = self.layernorm_before(hidden_states)
  253. attention_output = self.attention(hidden_states_norm, head_mask)
  254. # first residual connection
  255. hidden_states = attention_output + hidden_states
  256. # in IJepa, layernorm is also applied after self-attention
  257. layer_output = self.layernorm_after(hidden_states)
  258. layer_output = self.intermediate(layer_output)
  259. # second residual connection is done here
  260. layer_output = self.output(layer_output, hidden_states)
  261. return layer_output
  262. @auto_docstring
  263. class IJepaPreTrainedModel(PreTrainedModel):
  264. config: IJepaConfig
  265. base_model_prefix = "ijepa"
  266. main_input_name = "pixel_values"
  267. supports_gradient_checkpointing = True
  268. _no_split_modules = ["IJepaEmbeddings", "IJepaLayer"]
  269. _supports_sdpa = True
  270. _supports_flash_attn = True
  271. _supports_flex_attn = True
  272. _supports_attention_backend = True
  273. _can_record_outputs = {
  274. "hidden_states": IJepaLayer,
  275. "attentions": IJepaSelfAttention,
  276. }
  277. def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
  278. """Initialize the weights"""
  279. if isinstance(module, (nn.Linear, nn.Conv2d)):
  280. # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
  281. # `trunc_normal_cpu` not implemented in `half` issues
  282. module.weight.data = nn.init.trunc_normal_(
  283. module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
  284. ).to(module.weight.dtype)
  285. if module.bias is not None:
  286. module.bias.data.zero_()
  287. elif isinstance(module, nn.LayerNorm):
  288. module.bias.data.zero_()
  289. module.weight.data.fill_(1.0)
  290. elif isinstance(module, IJepaEmbeddings):
  291. module.position_embeddings.data = nn.init.trunc_normal_(
  292. module.position_embeddings.data.to(torch.float32),
  293. mean=0.0,
  294. std=self.config.initializer_range,
  295. ).to(module.position_embeddings.dtype)
  296. if module.mask_token is not None:
  297. module.mask_token.data.zero_()
  298. class IJepaEncoder(nn.Module):
  299. def __init__(self, config: IJepaConfig):
  300. super().__init__()
  301. self.config = config
  302. self.layer = nn.ModuleList([IJepaLayer(config) for _ in range(config.num_hidden_layers)])
  303. self.gradient_checkpointing = False
  304. def forward(self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None) -> BaseModelOutput:
  305. for i, layer_module in enumerate(self.layer):
  306. layer_head_mask = head_mask[i] if head_mask is not None else None
  307. hidden_states = layer_module(hidden_states, layer_head_mask)
  308. return BaseModelOutput(last_hidden_state=hidden_states)
  309. class IJepaPooler(nn.Module):
  310. def __init__(self, config: IJepaConfig):
  311. super().__init__()
  312. self.dense = nn.Linear(config.hidden_size, config.pooler_output_size)
  313. self.activation = ACT2FN[config.pooler_act]
  314. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  315. # We "pool" the model by simply taking the hidden state corresponding
  316. # to the first token.
  317. first_token_tensor = hidden_states[:, 0]
  318. pooled_output = self.dense(first_token_tensor)
  319. pooled_output = self.activation(pooled_output)
  320. return pooled_output
  321. @auto_docstring
  322. class IJepaModel(IJepaPreTrainedModel):
  323. def __init__(self, config: IJepaConfig, add_pooling_layer: bool = False, use_mask_token: bool = False):
  324. r"""
  325. add_pooling_layer (bool, *optional*, defaults to `True`):
  326. Whether to add a pooling layer
  327. use_mask_token (`bool`, *optional*, defaults to `False`):
  328. Whether to use a mask token for masked image modeling.
  329. """
  330. super().__init__(config)
  331. self.config = config
  332. self.embeddings = IJepaEmbeddings(config, use_mask_token=use_mask_token)
  333. self.encoder = IJepaEncoder(config)
  334. self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  335. self.pooler = IJepaPooler(config) if add_pooling_layer else None
  336. # Initialize weights and apply final processing
  337. self.post_init()
  338. def get_input_embeddings(self) -> IJepaPatchEmbeddings:
  339. return self.embeddings.patch_embeddings
  340. def _prune_heads(self, heads_to_prune: dict[int, list[int]]):
  341. """
  342. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  343. class PreTrainedModel
  344. """
  345. for layer, heads in heads_to_prune.items():
  346. self.encoder.layer[layer].attention.prune_heads(heads)
  347. @check_model_inputs(tie_last_hidden_states=False)
  348. @auto_docstring
  349. def forward(
  350. self,
  351. pixel_values: Optional[torch.Tensor] = None,
  352. bool_masked_pos: Optional[torch.BoolTensor] = None,
  353. head_mask: Optional[torch.Tensor] = None,
  354. interpolate_pos_encoding: Optional[bool] = None,
  355. **kwargs: Unpack[TransformersKwargs],
  356. ) -> BaseModelOutputWithPooling:
  357. r"""
  358. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
  359. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  360. """
  361. if pixel_values is None:
  362. raise ValueError("You have to specify pixel_values")
  363. # Prepare head mask if needed
  364. # 1.0 in head_mask indicate we keep the head
  365. # attention_probs has shape bsz x n_heads x N x N
  366. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  367. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  368. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  369. # TODO: maybe have a cleaner way to cast the input (from `ImageProcessor` side?)
  370. expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
  371. if pixel_values.dtype != expected_dtype:
  372. pixel_values = pixel_values.to(expected_dtype)
  373. embedding_output = self.embeddings(
  374. pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
  375. )
  376. encoder_outputs: BaseModelOutput = self.encoder(embedding_output, head_mask=head_mask)
  377. sequence_output = encoder_outputs.last_hidden_state
  378. sequence_output = self.layernorm(sequence_output)
  379. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  380. return BaseModelOutputWithPooling(last_hidden_state=sequence_output, pooler_output=pooled_output)
  381. @auto_docstring(
  382. custom_intro="""
  383. IJepa Model transformer with an image classification head on top (a linear layer on top of the final hidden states)
  384. e.g. for ImageNet.
  385. <Tip>
  386. Note that it's possible to fine-tune IJepa on higher resolution images than the ones it has been trained on, by
  387. setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
  388. position embeddings to the higher resolution.
  389. </Tip>
  390. """
  391. )
  392. class IJepaForImageClassification(IJepaPreTrainedModel):
  393. def __init__(self, config: IJepaConfig):
  394. super().__init__(config)
  395. self.num_labels = config.num_labels
  396. self.ijepa = IJepaModel(config, add_pooling_layer=False)
  397. # Classifier head
  398. self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
  399. # Initialize weights and apply final processing
  400. self.post_init()
  401. @can_return_tuple
  402. @auto_docstring
  403. def forward(
  404. self,
  405. pixel_values: Optional[torch.Tensor] = None,
  406. head_mask: Optional[torch.Tensor] = None,
  407. labels: Optional[torch.Tensor] = None,
  408. interpolate_pos_encoding: Optional[bool] = None,
  409. **kwargs: Unpack[TransformersKwargs],
  410. ) -> ImageClassifierOutput:
  411. r"""
  412. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  413. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  414. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  415. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  416. """
  417. outputs: BaseModelOutputWithPooling = self.ijepa(
  418. pixel_values,
  419. head_mask=head_mask,
  420. interpolate_pos_encoding=interpolate_pos_encoding,
  421. **kwargs,
  422. )
  423. sequence_output = outputs.last_hidden_state
  424. logits = self.classifier(sequence_output.mean(dim=1))
  425. loss = None
  426. if labels is not None:
  427. loss = self.loss_function(labels, logits, self.config, **kwargs)
  428. return ImageClassifierOutput(
  429. loss=loss,
  430. logits=logits,
  431. hidden_states=outputs.hidden_states,
  432. attentions=outputs.attentions,
  433. )
  434. __all__ = ["IJepaPreTrainedModel", "IJepaModel", "IJepaForImageClassification"]