modular_ijepa.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import torch
  2. import torch.nn as nn
  3. from transformers.models.ijepa.configuration_ijepa import IJepaConfig
  4. from ... import initialization as init
  5. from ...modeling_outputs import BaseModelOutputWithPooling, ImageClassifierOutput
  6. from ...processing_utils import Unpack
  7. from ...utils import TransformersKwargs, auto_docstring, torch_int
  8. from ..vit.modeling_vit import ViTEmbeddings, ViTForImageClassification, ViTModel, ViTPreTrainedModel
  9. class IJepaEmbeddings(ViTEmbeddings):
  10. def __init__(self, config: IJepaConfig, use_mask_token: bool = False) -> None:
  11. super().__init__(config, use_mask_token)
  12. # Remove cls_token from IJepaEmbeddings, as it is not used in the model
  13. del self.cls_token
  14. num_patches = self.patch_embeddings.num_patches
  15. self.position_embeddings = nn.Parameter(torch.randn(1, num_patches, config.hidden_size))
  16. def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
  17. """
  18. This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
  19. images. This method is also adapted to support torch.jit tracing.
  20. Adapted from:
  21. - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
  22. - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
  23. """
  24. num_patches = embeddings.shape[1]
  25. num_positions = self.position_embeddings.shape[1]
  26. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  27. if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
  28. return self.position_embeddings
  29. patch_pos_embed = self.position_embeddings
  30. dim = embeddings.shape[-1]
  31. new_height = height // self.patch_size
  32. new_width = width // self.patch_size
  33. sqrt_num_positions = torch_int(num_positions**0.5)
  34. patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
  35. patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
  36. patch_pos_embed = nn.functional.interpolate(
  37. patch_pos_embed,
  38. size=(new_height, new_width),
  39. mode="bicubic",
  40. align_corners=False,
  41. )
  42. patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
  43. return patch_pos_embed
  44. def forward(
  45. self,
  46. pixel_values: torch.Tensor,
  47. bool_masked_pos: torch.BoolTensor | None = None,
  48. interpolate_pos_encoding: bool = False,
  49. ) -> torch.Tensor:
  50. batch_size, _, height, width = pixel_values.shape
  51. embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
  52. if bool_masked_pos is not None:
  53. seq_length = embeddings.shape[1]
  54. mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
  55. # replace the masked visual tokens by mask_tokens
  56. mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
  57. embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
  58. # add positional encoding to each token
  59. if interpolate_pos_encoding:
  60. embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
  61. else:
  62. embeddings = embeddings + self.position_embeddings
  63. embeddings = self.dropout(embeddings)
  64. return embeddings
  65. @auto_docstring
  66. class IJepaPreTrainedModel(ViTPreTrainedModel):
  67. @torch.no_grad()
  68. def _init_weights(self, module: nn.Linear | nn.Conv2d | nn.LayerNorm) -> None:
  69. """Initialize the weights"""
  70. if isinstance(module, (nn.Linear, nn.Conv2d)):
  71. init.trunc_normal_(module.weight, mean=0.0, std=self.config.initializer_range)
  72. if module.bias is not None:
  73. init.zeros_(module.bias)
  74. elif isinstance(module, nn.LayerNorm):
  75. init.zeros_(module.bias)
  76. init.ones_(module.weight)
  77. elif isinstance(module, IJepaEmbeddings):
  78. init.trunc_normal_(module.position_embeddings, mean=0.0, std=self.config.initializer_range)
  79. if module.mask_token is not None:
  80. init.zeros_(module.mask_token)
  81. class IJepaModel(IJepaPreTrainedModel, ViTModel):
  82. def __init__(self, config: IJepaConfig, add_pooling_layer: bool = False, use_mask_token: bool = False):
  83. r"""
  84. add_pooling_layer (bool, *optional*, defaults to `True`):
  85. Whether to add a pooling layer
  86. use_mask_token (`bool`, *optional*, defaults to `False`):
  87. Whether to use a mask token for masked image modeling.
  88. """
  89. super().__init__(config)
  90. self.config = config
  91. self.embeddings = IJepaEmbeddings(config, use_mask_token=use_mask_token)
  92. @auto_docstring(
  93. custom_intro="""
  94. IJepa Model transformer with an image classification head on top (a linear layer on top of the final hidden states)
  95. e.g. for ImageNet.
  96. <Tip>
  97. Note that it's possible to fine-tune IJepa on higher resolution images than the ones it has been trained on, by
  98. setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
  99. position embeddings to the higher resolution.
  100. </Tip>
  101. """
  102. )
  103. class IJepaForImageClassification(IJepaPreTrainedModel, ViTForImageClassification):
  104. def __init__(self, config: IJepaConfig):
  105. super().__init__(config)
  106. self.ijepa = IJepaModel(config, add_pooling_layer=False)
  107. self.post_init()
  108. def forward(
  109. self,
  110. pixel_values: torch.Tensor | None = None,
  111. labels: torch.Tensor | None = None,
  112. interpolate_pos_encoding: bool | None = None,
  113. **kwargs: Unpack[TransformersKwargs],
  114. ) -> ImageClassifierOutput:
  115. r"""
  116. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  117. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  118. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  119. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  120. """
  121. outputs: BaseModelOutputWithPooling = self.ijepa(
  122. pixel_values,
  123. interpolate_pos_encoding=interpolate_pos_encoding,
  124. **kwargs,
  125. )
  126. sequence_output = outputs.last_hidden_state
  127. logits = self.classifier(sequence_output.mean(dim=1))
  128. loss = None
  129. if labels is not None:
  130. loss = self.loss_function(labels, logits, self.config, **kwargs)
  131. return ImageClassifierOutput(
  132. loss=loss,
  133. logits=logits,
  134. hidden_states=outputs.hidden_states,
  135. attentions=outputs.attentions,
  136. )
  137. __all__ = [
  138. "IJepaPreTrainedModel",
  139. "IJepaModel",
  140. "IJepaForImageClassification",
  141. ]