modular_ijepa.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. from typing import Optional, Union
  2. import torch
  3. import torch.nn as nn
  4. from transformers.models.ijepa.configuration_ijepa import IJepaConfig
  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: Optional[torch.BoolTensor] = 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. def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
  68. """Initialize the weights"""
  69. if isinstance(module, (nn.Linear, nn.Conv2d)):
  70. # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
  71. # `trunc_normal_cpu` not implemented in `half` issues
  72. module.weight.data = nn.init.trunc_normal_(
  73. module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
  74. ).to(module.weight.dtype)
  75. if module.bias is not None:
  76. module.bias.data.zero_()
  77. elif isinstance(module, nn.LayerNorm):
  78. module.bias.data.zero_()
  79. module.weight.data.fill_(1.0)
  80. elif isinstance(module, IJepaEmbeddings):
  81. module.position_embeddings.data = nn.init.trunc_normal_(
  82. module.position_embeddings.data.to(torch.float32),
  83. mean=0.0,
  84. std=self.config.initializer_range,
  85. ).to(module.position_embeddings.dtype)
  86. if module.mask_token is not None:
  87. module.mask_token.data.zero_()
  88. class IJepaModel(IJepaPreTrainedModel, ViTModel):
  89. def __init__(self, config: IJepaConfig, add_pooling_layer: bool = False, use_mask_token: bool = False):
  90. r"""
  91. add_pooling_layer (bool, *optional*, defaults to `True`):
  92. Whether to add a pooling layer
  93. use_mask_token (`bool`, *optional*, defaults to `False`):
  94. Whether to use a mask token for masked image modeling.
  95. """
  96. super().__init__(config)
  97. self.config = config
  98. self.embeddings = IJepaEmbeddings(config, use_mask_token=use_mask_token)
  99. @auto_docstring(
  100. custom_intro="""
  101. IJepa Model transformer with an image classification head on top (a linear layer on top of the final hidden states)
  102. e.g. for ImageNet.
  103. <Tip>
  104. Note that it's possible to fine-tune IJepa on higher resolution images than the ones it has been trained on, by
  105. setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
  106. position embeddings to the higher resolution.
  107. </Tip>
  108. """
  109. )
  110. class IJepaForImageClassification(IJepaPreTrainedModel, ViTForImageClassification):
  111. def __init__(self, config: IJepaConfig):
  112. super().__init__(config)
  113. self.ijepa = IJepaModel(config, add_pooling_layer=False)
  114. self.post_init()
  115. def forward(
  116. self,
  117. pixel_values: Optional[torch.Tensor] = None,
  118. head_mask: Optional[torch.Tensor] = None,
  119. labels: Optional[torch.Tensor] = None,
  120. interpolate_pos_encoding: Optional[bool] = None,
  121. **kwargs: Unpack[TransformersKwargs],
  122. ) -> ImageClassifierOutput:
  123. r"""
  124. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  125. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  126. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  127. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  128. """
  129. outputs: BaseModelOutputWithPooling = self.ijepa(
  130. pixel_values,
  131. head_mask=head_mask,
  132. interpolate_pos_encoding=interpolate_pos_encoding,
  133. **kwargs,
  134. )
  135. sequence_output = outputs.last_hidden_state
  136. logits = self.classifier(sequence_output.mean(dim=1))
  137. loss = None
  138. if labels is not None:
  139. loss = self.loss_function(labels, logits, self.config, **kwargs)
  140. return ImageClassifierOutput(
  141. loss=loss,
  142. logits=logits,
  143. hidden_states=outputs.hidden_states,
  144. attentions=outputs.attentions,
  145. )
  146. __all__ = [
  147. "IJepaPreTrainedModel",
  148. "IJepaModel",
  149. "IJepaForImageClassification",
  150. ]