modeling_flava.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  1. # coding=utf-8
  2. # Copyright 2022 Meta Platforms authors and The HuggingFace 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 FLAVA model."""
  16. import collections
  17. import math
  18. from collections import OrderedDict
  19. from dataclasses import dataclass
  20. from typing import Any, Optional, Union
  21. import torch
  22. from torch import nn
  23. from ...activations import ACT2FN
  24. from ...modeling_layers import GradientCheckpointingLayer
  25. from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
  26. from ...modeling_utils import PreTrainedModel
  27. from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
  28. from ...utils import ModelOutput, auto_docstring, filter_out_non_signature_kwargs, logging, torch_int
  29. from .configuration_flava import (
  30. FlavaConfig,
  31. FlavaImageCodebookConfig,
  32. FlavaImageConfig,
  33. FlavaMultimodalConfig,
  34. FlavaTextConfig,
  35. )
  36. logger = logging.get_logger(__name__)
  37. _CHECKPOINT_FOR_CODEBOOK_DOC = "facebook/flava-image-codebook"
  38. LOGIT_SCALE_CLAMP_MIN = 0
  39. LOGIT_SCALE_CLAMP_MAX = 4.6052
  40. FlavaPossibleConfigs = Union[FlavaTextConfig, FlavaImageConfig, FlavaMultimodalConfig]
  41. @dataclass
  42. @auto_docstring(
  43. custom_intro="""
  44. Output from FlavaModel containing embeddings and outputs from individual encoders.
  45. Note that `image_embeddings` and `text_embeddigns` returned are similar to pooled output returned from a
  46. transformer. If you want embeddings for contrastive loss or retrieval use a FLAVA model's `image_projection` and
  47. `text_projection` layers on `image_embeddings` and `text_embeddings` respectively.
  48. """
  49. )
  50. class FlavaModelOutput(ModelOutput):
  51. r"""
  52. image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `pixel_values` are present):
  53. The image embeddings which are basically the pooled output of [`FlavaImageModel`].
  54. image_output (`BaseModelOutputWithPooling`, *optional*, returned when `pixel_values` are present):
  55. The output of the [`FlavaImageModel`].
  56. text_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` are present):
  57. The text embeddings which are basically the pooled output of [`FlavaTextModel`].
  58. text_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids` are present):
  59. The output of the [`FlavaTextModel`].
  60. multimodal_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` and `pixel_values` are present and `skip_multimodal_encoder` is `None` or `False`):
  61. The multimodal embeddings which are basically the pooled output of [`FlavaTextModel`].
  62. multimodal_output (`BaseModelOutputWithPooling`, returned when `input_ids` and `pixel_values` are present and `skip_multimodal_encoder` is `None` or `False`):
  63. The output of the [`FlavaMultimodalModel`].
  64. """
  65. image_embeddings: Optional[torch.FloatTensor] = None
  66. image_output: Optional[BaseModelOutputWithPooling] = None
  67. text_embeddings: Optional[torch.FloatTensor] = None
  68. text_output: Optional[BaseModelOutputWithPooling] = None
  69. multimodal_embeddings: Optional[torch.FloatTensor] = None
  70. multimodal_output: Optional[BaseModelOutputWithPooling] = None
  71. def to_tuple(self) -> tuple[Any]:
  72. return tuple(
  73. self[k] if k not in ["text_output", "image_output", "multimodal_output"] else getattr(self, k).to_tuple()
  74. for k in self.keys()
  75. )
  76. @dataclass
  77. @auto_docstring(
  78. custom_intro="""
  79. Class representing pretraining losses from FLAVA model
  80. """
  81. )
  82. class FlavaLosses(ModelOutput):
  83. r"""
  84. mim (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mim_labels` and `pixel_values` are present, `input_ids_masked` is absent and `mim_weight` > 0.):
  85. Masked Image Modeling loss as used in BeIT calculated only for unimodal image data.
  86. mlm (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mlm_labels` and `input_ids_masked` are present, `pixel_values` is absent and `mlm_weight` > 0.):
  87. Masked Language Modeling loss as used in BERT calculated only for unimodal text data.
  88. itm (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `itm_labels`, `input_ids_masked`, `pixel_values` are present and `itm_weight` > 0.):
  89. Image Text Matching (ITM) loss calculated for paired image-text data. Note that ITM loss is calculated on
  90. masked pairs in FLAVA.
  91. global_contrastive (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `input_ids` and `pixel_values` are present and `global_contrastive_weight` > 0.):
  92. Contrastive loss for image-text similarity similar to CLIP but calculated globally for paired image-text
  93. data. This is calculated on unmasked images and texts.
  94. mmm_image (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mim_labels`, `pixel_values` and `input_ids_masked` are present and `mmm_image_weight` > 0.):
  95. Masked Multimodal Modeling loss's image component calculated on paired image-text data.
  96. mmm_text (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mlm_labels`, `pixel_values` and `input_ids_masked` are present and `mmm_text_weight` > 0.):
  97. Masked Multimodal Modeling loss's text component calculated on paired image-text data.
  98. """
  99. mim: Optional[torch.FloatTensor] = None
  100. mlm: Optional[torch.FloatTensor] = None
  101. itm: Optional[torch.FloatTensor] = None
  102. global_contrastive: Optional[torch.FloatTensor] = None
  103. mmm_image: Optional[torch.FloatTensor] = None
  104. mmm_text: Optional[torch.FloatTensor] = None
  105. def all_none(self) -> bool:
  106. all_none = True
  107. for v in self.values():
  108. if v is not None:
  109. all_none = False
  110. break
  111. return all_none
  112. @dataclass
  113. @auto_docstring(
  114. custom_intro="""
  115. Output from FlavaForPreTraining containing embeddings, and outputs from individual encoders.
  116. Note that `image_embeddings` and `text_embeddings` returned are similar to pooled output returned from a
  117. transformer. If you want embeddings for contrastive loss or retrieval use a FLAVA model's `image_projection` and
  118. `text_projection` layers on `image_embeddings` and `text_embeddings` respectively.
  119. """
  120. )
  121. class FlavaForPreTrainingOutput(ModelOutput):
  122. r"""
  123. loss (`torch.FloatTensor`, *optional*, returned when `return_loss` is True):
  124. Total loss calculated for this model.
  125. loss_info (`FlavaLosses`):
  126. Detailed info for FLAVA Pretraining losses. Check `FlavaLosses` class description for the information on
  127. the keys.
  128. image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `pixel_values` are present):
  129. The image embeddings which are basically the pooled output of [`FlavaImageModel`].
  130. image_output (`BaseModelOutputWithPooling`, *optional*, returned when `pixel_values` are present):
  131. The output of the [`FlavaImageModel`].
  132. text_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` are present):
  133. The text embeddings which are basically the pooled output of [`FlavaTextModel`].
  134. text_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids` are present):
  135. The output of the [`FlavaTextModel`].
  136. multimodal_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` and `pixel_values` are present and `skip_unmasked_multimodal_encoder` is `None` or `False`):
  137. The multimodal embeddings which are basically the pooled output of [`FlavaTextModel`].
  138. multimodal_output (`BaseModelOutputWithPooling`, returned when `input_ids` and `pixel_values` are present and `skip_unmasked_multimodal_encoder` is `None` or `False`):
  139. The output of the [`FlavaMultimodalModel`].
  140. image_masked_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `pixel_values` are present):
  141. The image embeddings which are basically the pooled output of [`FlavaImageModel`]. Uses `bool_masked_pos`
  142. to create masked images.
  143. image_masked_output (`BaseModelOutputWithPooling`, *optional*, returned when `pixel_values` are present):
  144. The output of the [`FlavaImageModel`]. Uses `bool_masked_pos` to create masked images.
  145. text_masked_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids_masked` are present):
  146. The text embeddings which are basically the pooled output of [`FlavaTextModel`].
  147. text_masked_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids_masked` are present):
  148. The output of the [`FlavaTextModel`].
  149. multimodal_masked_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` and `pixel_values` are present):
  150. The multimodal embeddings which are basically the pooled output of [`FlavaTextModel`].
  151. multimodal_masked_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids_masked` and `pixel_values` are present):
  152. The output of the [`FlavaMultimodalModel`].
  153. mim_logits (`torch.FloatTensor` of shape `(batch_size, num_image_patches, image_vocab_size)` or of shape `(total_masked_patches, image_vocab_size)` , *optional*, returned when `pixel_values` are present and `input_ids_masked` are not):
  154. The logits for MIM unimodal loss. Uses `book_masked_pos` to get masked patches. The flattened output is
  155. returned when `bool_masked_pos` has some of the patches masked.
  156. mlm_logits (`torch.FloatTensor` of shape `(batch_size, text_seq_length, text_vocab_size)` or of shape `(total_masked_seq_length, text_vocab_size)`, *optional*, returned when `input_ids_masked` are present and `pixel_values` are not):
  157. The logits for MLM unimodal loss. The flattened output is returned when `input_ids_masked` has some of
  158. the tokens masked.
  159. itm_logits (`torch.FloatTensor` of shape `(batch_size, 2)`, *optional*, returned when `input_ids_masked` and `pixel_values` are present):
  160. The logits for ITM loss. Note that ITM loss is calculated on masked pairs in FLAVA.
  161. contrastive_logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
  162. The scaled dot product scores between `image_embeddings` and `text_embeddings` but passed through FLAVA's
  163. `image_projection` and `text_projection` layers respectively. This represents the image-text similarity
  164. scores. This is calculated on unmasked images and texts.
  165. contrastive_logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
  166. The scaled dot product scores between `text_embeddings` and `image_embeddings` but passed through FLAVA's
  167. `text_projection` and `image_projection` layers respectively. This is calculated on unmasked images and
  168. texts.
  169. mmm_image_logits (`torch.FloatTensor` of shape `(batch_size, num_image_patches, image_vocab_size)` or of shape`(total_masked_patches, image_vocab_size)`, *optional*, returned when `pixel_values` and `input_ids_masked` are present):
  170. The logits for MMM image multimodal loss. Uses `book_masked_pos` to get masked patches. The flattened
  171. output is returned when `bool_masked_pos` has some of the patches masked.
  172. mmm_text_logits (`torch.FloatTensor` of shape `(batch_size, text_seq_length, text_vocab_size)` or of shape `(`(total_masked_seq_length, text_vocab_size)`), *optional*, returned when `pixel_values` and `input_ids_masked` are present):
  173. The logits for MMM text multimodal loss. The flattened output is returned when `input_ids_masked` has
  174. some of the tokens masked.
  175. """
  176. loss: Optional[torch.FloatTensor] = None
  177. loss_info: FlavaLosses = None
  178. image_embeddings: Optional[torch.FloatTensor] = None
  179. image_output: Optional[BaseModelOutputWithPooling] = None
  180. text_embeddings: Optional[torch.FloatTensor] = None
  181. text_output: Optional[BaseModelOutputWithPooling] = None
  182. multimodal_embeddings: Optional[torch.FloatTensor] = None
  183. multimodal_output: Optional[BaseModelOutputWithPooling] = None
  184. image_masked_embeddings: Optional[torch.FloatTensor] = None
  185. image_masked_output: Optional[BaseModelOutputWithPooling] = None
  186. text_masked_embeddings: Optional[torch.FloatTensor] = None
  187. text_masked_output: Optional[BaseModelOutputWithPooling] = None
  188. multimodal_masked_embeddings: Optional[torch.FloatTensor] = None
  189. multimodal_masked_output: Optional[BaseModelOutputWithPooling] = None
  190. mim_logits: Optional[torch.FloatTensor] = None
  191. mlm_logits: Optional[torch.FloatTensor] = None
  192. itm_logits: Optional[torch.FloatTensor] = None
  193. contrastive_logits_per_image: Optional[torch.FloatTensor] = None
  194. contrastive_logits_per_text: Optional[torch.FloatTensor] = None
  195. mmm_image_logits: Optional[torch.FloatTensor] = None
  196. mmm_text_logits: Optional[torch.FloatTensor] = None
  197. def to_tuple(self) -> tuple[Any]:
  198. transformer_outputs = [
  199. "text_output",
  200. "image_output",
  201. "multimodal_output",
  202. "text_masked_output",
  203. "image_masked_output",
  204. "multimodal_masked_output",
  205. ]
  206. return tuple(self[k] if k not in transformer_outputs else getattr(self, k).to_tuple() for k in self.keys())
  207. # Based on timm implementation, which can be found here:
  208. # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/image_transformer.py
  209. class FlavaImageEmbeddings(nn.Module):
  210. """
  211. Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
  212. """
  213. def __init__(self, config: FlavaImageConfig, use_mask_token: bool = False) -> None:
  214. super().__init__()
  215. use_mask_token = use_mask_token or config.mask_token
  216. self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
  217. self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
  218. self.patch_embeddings = PatchEmbeddings(
  219. image_size=config.image_size,
  220. patch_size=config.patch_size,
  221. num_channels=config.num_channels,
  222. embed_dim=config.hidden_size,
  223. )
  224. num_patches = self.patch_embeddings.num_patches
  225. self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
  226. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  227. self.patch_size = config.patch_size
  228. self.config = config
  229. # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
  230. def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
  231. """
  232. This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
  233. images. This method is also adapted to support torch.jit tracing.
  234. Adapted from:
  235. - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
  236. - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
  237. """
  238. num_patches = embeddings.shape[1] - 1
  239. num_positions = self.position_embeddings.shape[1] - 1
  240. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  241. if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
  242. return self.position_embeddings
  243. class_pos_embed = self.position_embeddings[:, :1]
  244. patch_pos_embed = self.position_embeddings[:, 1:]
  245. dim = embeddings.shape[-1]
  246. new_height = height // self.patch_size
  247. new_width = width // self.patch_size
  248. sqrt_num_positions = torch_int(num_positions**0.5)
  249. patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
  250. patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
  251. patch_pos_embed = nn.functional.interpolate(
  252. patch_pos_embed,
  253. size=(new_height, new_width),
  254. mode="bicubic",
  255. align_corners=False,
  256. )
  257. patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
  258. return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
  259. def forward(
  260. self,
  261. pixel_values: torch.Tensor,
  262. bool_masked_pos: Optional[torch.BoolTensor] = None,
  263. interpolate_pos_encoding: bool = False,
  264. ) -> torch.Tensor:
  265. batch_size, num_channels, height, width = pixel_values.shape
  266. embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
  267. batch_size, seq_len, _ = embeddings.size()
  268. if bool_masked_pos is not None:
  269. mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
  270. # B X H X W = B X HW
  271. if bool_masked_pos.dim() == 3:
  272. bool_masked_pos = bool_masked_pos.view(bool_masked_pos.size(0), -1)
  273. # replace the masked visual tokens by mask_tokens
  274. mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
  275. embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
  276. # add the [CLS] token to the embedded patch tokens
  277. cls_tokens = self.cls_token.expand(batch_size, -1, -1)
  278. embeddings = torch.cat((cls_tokens, embeddings), dim=1)
  279. # add positional encoding to each token
  280. if interpolate_pos_encoding:
  281. embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
  282. else:
  283. embeddings = embeddings + self.position_embeddings
  284. embeddings = self.dropout(embeddings)
  285. return embeddings
  286. # Based on timm implementation, which can be found here:
  287. # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/image_transformer.py
  288. class PatchEmbeddings(nn.Module):
  289. """
  290. Image to Patch Embedding.
  291. """
  292. def __init__(
  293. self,
  294. image_size: int = 224,
  295. patch_size: Union[int, tuple[int, int]] = 16,
  296. num_channels: int = 3,
  297. embed_dim: int = 768,
  298. ):
  299. super().__init__()
  300. if not isinstance(image_size, collections.abc.Iterable):
  301. image_size = (image_size, image_size)
  302. if not isinstance(patch_size, collections.abc.Iterable):
  303. patch_size = (patch_size, patch_size)
  304. num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  305. self.image_size = image_size
  306. self.patch_size = patch_size
  307. self.num_patches = num_patches
  308. self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
  309. def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
  310. batch_size, num_channels, height, width = pixel_values.shape
  311. if not interpolate_pos_encoding:
  312. if height != self.image_size[0] or width != self.image_size[1]:
  313. raise ValueError(
  314. f"Input image size ({height}*{width}) doesn't match model"
  315. f" ({self.image_size[0]}*{self.image_size[1]})."
  316. )
  317. x = self.projection(pixel_values).flatten(2).transpose(1, 2)
  318. return x
  319. class FlavaTextEmbeddings(nn.Module):
  320. """Construct the embeddings from word, position and token_type embeddings."""
  321. def __init__(self, config):
  322. super().__init__()
  323. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  324. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  325. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  326. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  327. # any TensorFlow checkpoint file
  328. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  329. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  330. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  331. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  332. self.register_buffer(
  333. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  334. )
  335. self.register_buffer(
  336. "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
  337. )
  338. def forward(
  339. self,
  340. input_ids: Optional[torch.Tensor] = None,
  341. token_type_ids: Optional[torch.Tensor] = None,
  342. position_ids: Optional[torch.Tensor] = None,
  343. ):
  344. input_shape = input_ids.size()
  345. seq_length = input_shape[1]
  346. if position_ids is None:
  347. position_ids = self.position_ids[:, :seq_length]
  348. # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
  349. # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
  350. # issue #5664
  351. if token_type_ids is None:
  352. if hasattr(self, "token_type_ids"):
  353. buffered_token_type_ids = self.token_type_ids[:, :seq_length]
  354. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
  355. token_type_ids = buffered_token_type_ids_expanded
  356. else:
  357. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  358. inputs_embeds = self.word_embeddings(input_ids)
  359. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  360. embeddings = inputs_embeds + token_type_embeddings
  361. if self.position_embedding_type == "absolute":
  362. position_embeddings = self.position_embeddings(position_ids)
  363. embeddings += position_embeddings
  364. embeddings = self.LayerNorm(embeddings)
  365. embeddings = self.dropout(embeddings)
  366. return embeddings
  367. class FlavaSelfAttention(nn.Module):
  368. def __init__(self, config: FlavaPossibleConfigs) -> None:
  369. super().__init__()
  370. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  371. raise ValueError(
  372. f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
  373. f"heads {config.num_attention_heads}."
  374. )
  375. self.num_attention_heads = config.num_attention_heads
  376. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  377. self.all_head_size = self.num_attention_heads * self.attention_head_size
  378. self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
  379. self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
  380. self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
  381. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  382. def forward(
  383. self,
  384. hidden_states: torch.Tensor,
  385. attention_mask: Optional[torch.Tensor] = None,
  386. head_mask: Optional[torch.Tensor] = None,
  387. output_attentions: bool = False,
  388. ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
  389. batch_size, seq_length, _ = hidden_states.shape
  390. query_layer = (
  391. self.query(hidden_states)
  392. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  393. .transpose(1, 2)
  394. )
  395. key_layer = (
  396. self.key(hidden_states)
  397. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  398. .transpose(1, 2)
  399. )
  400. value_layer = (
  401. self.value(hidden_states)
  402. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  403. .transpose(1, 2)
  404. )
  405. # Take the dot product between "query" and "key" to get the raw attention scores.
  406. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  407. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  408. if attention_mask is not None:
  409. # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
  410. attention_scores = attention_scores + attention_mask
  411. # Normalize the attention scores to probabilities.
  412. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  413. # This is actually dropping out entire tokens to attend to, which might
  414. # seem a bit unusual, but is taken from the original Transformer paper.
  415. attention_probs = self.dropout(attention_probs)
  416. # Mask heads if we want to
  417. if head_mask is not None:
  418. attention_probs = attention_probs * head_mask
  419. context_layer = torch.matmul(attention_probs, value_layer)
  420. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  421. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  422. context_layer = context_layer.view(*new_context_layer_shape)
  423. outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
  424. return outputs
  425. class FlavaSelfOutput(nn.Module):
  426. """
  427. The residual connection is defined in FlavaLayer (same as ViTLayer) instead of here (as is the case with other
  428. models), due to the layernorm applied before each block.
  429. """
  430. def __init__(self, config: FlavaPossibleConfigs) -> None:
  431. super().__init__()
  432. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  433. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  434. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  435. hidden_states = self.dense(hidden_states)
  436. hidden_states = self.dropout(hidden_states)
  437. return hidden_states
  438. class FlavaAttention(nn.Module):
  439. def __init__(self, config: FlavaPossibleConfigs) -> None:
  440. super().__init__()
  441. self.attention = FlavaSelfAttention(config)
  442. self.output = FlavaSelfOutput(config)
  443. self.pruned_heads = set()
  444. def prune_heads(self, heads: set[int]) -> None:
  445. if len(heads) == 0:
  446. return
  447. heads, index = find_pruneable_heads_and_indices(
  448. heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
  449. )
  450. # Prune linear layers
  451. self.attention.query = prune_linear_layer(self.attention.query, index)
  452. self.attention.key = prune_linear_layer(self.attention.key, index)
  453. self.attention.value = prune_linear_layer(self.attention.value, index)
  454. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  455. # Update hyper params and store pruned heads
  456. self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
  457. self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
  458. self.pruned_heads = self.pruned_heads.union(heads)
  459. def forward(
  460. self,
  461. hidden_states: torch.Tensor,
  462. attention_mask: Optional[torch.Tensor] = None,
  463. head_mask: Optional[torch.Tensor] = None,
  464. output_attentions: bool = False,
  465. ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
  466. self_outputs = self.attention(
  467. hidden_states, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions
  468. )
  469. attention_output = self.output(self_outputs[0], hidden_states)
  470. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  471. return outputs
  472. class FlavaIntermediate(nn.Module):
  473. def __init__(self, config: FlavaPossibleConfigs) -> None:
  474. super().__init__()
  475. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  476. if isinstance(config.hidden_act, str):
  477. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  478. else:
  479. self.intermediate_act_fn = config.hidden_act
  480. # Copied from transformers.models.vit.modeling_vit.ViTIntermediate.forward
  481. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  482. hidden_states = self.dense(hidden_states)
  483. hidden_states = self.intermediate_act_fn(hidden_states)
  484. return hidden_states
  485. class FlavaOutput(nn.Module):
  486. def __init__(self, config: FlavaPossibleConfigs) -> None:
  487. super().__init__()
  488. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  489. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  490. # Copied from transformers.models.vit.modeling_vit.ViTOutput.forward
  491. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  492. hidden_states = self.dense(hidden_states)
  493. hidden_states = self.dropout(hidden_states)
  494. hidden_states = hidden_states + input_tensor
  495. return hidden_states
  496. class FlavaLayer(GradientCheckpointingLayer):
  497. """This corresponds to the Block class in the timm implementation."""
  498. def __init__(self, config: FlavaPossibleConfigs) -> None:
  499. super().__init__()
  500. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  501. self.seq_len_dim = 1
  502. self.attention = FlavaAttention(config)
  503. self.intermediate = FlavaIntermediate(config)
  504. self.output = FlavaOutput(config)
  505. # TODO: Check fp32 layer norm possibility
  506. self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  507. self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  508. def forward(
  509. self,
  510. hidden_states: torch.Tensor,
  511. attention_mask: Optional[torch.Tensor] = None,
  512. head_mask: Optional[torch.Tensor] = None,
  513. output_attentions: bool = False,
  514. ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
  515. self_attention_outputs = self.attention(
  516. self.layernorm_before(hidden_states), # in ViT, layernorm is applied before self-attention
  517. attention_mask=attention_mask,
  518. head_mask=head_mask,
  519. output_attentions=output_attentions,
  520. )
  521. attention_output = self_attention_outputs[0]
  522. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  523. # first residual connection
  524. hidden_states = attention_output + hidden_states
  525. # in ViT, layernorm is also applied after self-attention
  526. layer_output = self.layernorm_after(hidden_states)
  527. layer_output = self.intermediate(layer_output)
  528. # second residual connection is done here
  529. layer_output = self.output(layer_output, hidden_states)
  530. outputs = (layer_output,) + outputs
  531. return outputs
  532. class FlavaEncoder(nn.Module):
  533. def __init__(self, config: FlavaConfig) -> None:
  534. super().__init__()
  535. self.config = config
  536. self.layer = nn.ModuleList([FlavaLayer(config) for _ in range(config.num_hidden_layers)])
  537. self.gradient_checkpointing = False
  538. def forward(
  539. self,
  540. hidden_states: torch.Tensor,
  541. attention_mask: Optional[torch.Tensor] = None,
  542. head_mask: Optional[torch.Tensor] = None,
  543. output_attentions: bool = False,
  544. output_hidden_states: bool = False,
  545. return_dict: bool = True,
  546. ) -> Union[tuple, BaseModelOutput]:
  547. all_hidden_states = () if output_hidden_states else None
  548. all_self_attentions = () if output_attentions else None
  549. for i, layer_module in enumerate(self.layer):
  550. if output_hidden_states:
  551. all_hidden_states = all_hidden_states + (hidden_states,)
  552. layer_head_mask = head_mask[i] if head_mask is not None else None
  553. layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
  554. hidden_states = layer_outputs[0]
  555. if output_attentions:
  556. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  557. if output_hidden_states:
  558. all_hidden_states = all_hidden_states + (hidden_states,)
  559. if not return_dict:
  560. return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
  561. return BaseModelOutput(
  562. last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions
  563. )
  564. class FlavaPooler(nn.Module):
  565. def __init__(self, config: FlavaPossibleConfigs):
  566. super().__init__()
  567. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  568. self.activation = nn.Tanh()
  569. def forward(self, hidden_states: torch.Tensor):
  570. # We "pool" the model by simply taking the hidden state corresponding
  571. # to the first token.
  572. first_token_tensor = hidden_states[:, 0]
  573. pooled_output = self.dense(first_token_tensor)
  574. pooled_output = self.activation(pooled_output)
  575. return pooled_output
  576. @auto_docstring
  577. class FlavaPreTrainedModel(PreTrainedModel):
  578. config: FlavaConfig
  579. base_model_prefix = "flava"
  580. supports_gradient_checkpointing = True
  581. def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
  582. """Initialize the weights"""
  583. if isinstance(module, (nn.Linear, nn.Conv2d)):
  584. # Slightly different from the TF version which uses truncated_normal for initialization
  585. # cf https://github.com/pytorch/pytorch/pull/5617
  586. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  587. if module.bias is not None:
  588. module.bias.data.zero_()
  589. elif isinstance(module, nn.Embedding):
  590. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  591. if module.padding_idx is not None:
  592. module.weight.data[module.padding_idx].zero_()
  593. elif isinstance(module, nn.LayerNorm):
  594. module.bias.data.zero_()
  595. module.weight.data.fill_(1.0)
  596. elif isinstance(module, FlavaMaskedPredictionHead):
  597. module.bias.data.zero_()
  598. elif isinstance(module, FlavaImageEmbeddings):
  599. module.cls_token.data.zero_()
  600. module.position_embeddings.data.zero_()
  601. if module.mask_token is not None:
  602. module.mask_token.data.zero_()
  603. elif isinstance(module, FlavaMultimodalModel):
  604. if module.use_cls_token:
  605. module.cls_token.data.zero_()
  606. elif isinstance(module, FlavaModel):
  607. module.logit_scale.data.fill_(self.config.logit_scale_init_value)
  608. @auto_docstring
  609. class FlavaImageModel(FlavaPreTrainedModel):
  610. config: FlavaImageConfig
  611. # This override allows us to load FlavaImageModel from FlavaModel/FlavaForPreTraining checkpoints.
  612. base_model_prefix = "flava.image_model"
  613. main_input_name = "pixel_values"
  614. def __init__(self, config: FlavaImageConfig, add_pooling_layer: bool = True):
  615. r"""
  616. add_pooling_layer (bool, *optional*, defaults to `True`):
  617. Whether to add a pooling layer
  618. """
  619. super().__init__(config)
  620. self.config = config
  621. self.embeddings = FlavaImageEmbeddings(config)
  622. self.encoder = FlavaEncoder(config)
  623. self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  624. self.pooler = FlavaPooler(config) if add_pooling_layer else None
  625. self.post_init()
  626. def get_input_embeddings(self) -> nn.Module:
  627. return self.embeddings.patch_embeddings
  628. def set_input_embeddings(self, value: nn.Module):
  629. self.embeddings.patch_embeddings = value
  630. def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
  631. """
  632. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  633. class PreTrainedModel
  634. """
  635. for layer, heads in heads_to_prune.items():
  636. self.encoder.layer[layer].attention.prune_heads(heads)
  637. @auto_docstring
  638. def forward(
  639. self,
  640. pixel_values: Optional[torch.Tensor] = None,
  641. bool_masked_pos: Optional[torch.BoolTensor] = None,
  642. interpolate_pos_encoding: Optional[bool] = None,
  643. attention_mask: Optional[torch.Tensor] = None,
  644. head_mask: Optional[torch.Tensor] = None,
  645. output_attentions: Optional[bool] = None,
  646. output_hidden_states: Optional[bool] = None,
  647. return_dict: Optional[bool] = None,
  648. ) -> Union[tuple, BaseModelOutputWithPooling]:
  649. r"""
  650. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, image_num_patches)`):
  651. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  652. """
  653. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  654. output_hidden_states = (
  655. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  656. )
  657. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  658. if pixel_values is None:
  659. raise ValueError("You have to specify pixel_values")
  660. # Prepare head mask if needed
  661. # 1.0 in head_mask indicate we keep the head
  662. # attention_probs has shape bsz x n_heads x N x N
  663. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  664. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  665. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  666. embedding_output = self.embeddings(
  667. pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
  668. )
  669. encoder_outputs = self.encoder(
  670. embedding_output,
  671. attention_mask=attention_mask,
  672. head_mask=head_mask,
  673. output_attentions=output_attentions,
  674. output_hidden_states=output_hidden_states,
  675. return_dict=return_dict,
  676. )
  677. sequence_output = encoder_outputs[0]
  678. sequence_output = self.layernorm(sequence_output)
  679. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  680. if not return_dict:
  681. return (sequence_output, pooled_output) + encoder_outputs[1:]
  682. return BaseModelOutputWithPooling(
  683. last_hidden_state=sequence_output,
  684. pooler_output=pooled_output,
  685. hidden_states=encoder_outputs.hidden_states,
  686. attentions=encoder_outputs.attentions,
  687. )
  688. @auto_docstring
  689. class FlavaTextModel(FlavaPreTrainedModel):
  690. config: FlavaTextConfig
  691. # This override allows us to load FlavaTextModel from FlavaModel/FlavaForPreTraining checkpoints.
  692. base_model_prefix = "flava.text_model"
  693. def __init__(self, config: FlavaTextConfig, add_pooling_layer: bool = True):
  694. r"""
  695. add_pooling_layer (bool, *optional*, defaults to `True`):
  696. Whether to add a pooling layer
  697. """
  698. super().__init__(config)
  699. self.config = config
  700. self.embeddings = FlavaTextEmbeddings(config)
  701. self.encoder = FlavaEncoder(config)
  702. self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  703. self.pooler = FlavaPooler(config) if add_pooling_layer else None
  704. self.post_init()
  705. def get_input_embeddings(self) -> PatchEmbeddings:
  706. return self.embeddings.word_embeddings
  707. def set_input_embeddings(self, value: nn.Module):
  708. self.embeddings.word_embeddings = value
  709. def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
  710. """
  711. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  712. class PreTrainedModel
  713. """
  714. for layer, heads in heads_to_prune.items():
  715. self.encoder.layer[layer].attention.prune_heads(heads)
  716. @auto_docstring
  717. def forward(
  718. self,
  719. input_ids: Optional[torch.Tensor] = None,
  720. attention_mask: Optional[torch.Tensor] = None,
  721. token_type_ids: Optional[torch.Tensor] = None,
  722. position_ids: Optional[torch.Tensor] = None,
  723. head_mask: Optional[torch.Tensor] = None,
  724. output_attentions: Optional[bool] = None,
  725. output_hidden_states: Optional[bool] = None,
  726. return_dict: Optional[bool] = None,
  727. ) -> Union[tuple, BaseModelOutputWithPooling]:
  728. r"""
  729. input_ids (`torch.LongTensor` of shape `(batch_size, text_seq_length)`):
  730. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  731. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  732. IDs?](../glossary#input-ids)
  733. token_type_ids (`torch.LongTensor` of shape `(batch_size, text_seq_length)`, *optional*):
  734. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  735. 1]`:
  736. - 0 corresponds to a *sentence A* token,
  737. - 1 corresponds to a *sentence B* token.
  738. [What are token type IDs?](../glossary#token-type-ids)
  739. """
  740. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  741. output_hidden_states = (
  742. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  743. )
  744. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  745. if input_ids is None:
  746. raise ValueError("You have to specify input_ids")
  747. input_shape = input_ids.size()
  748. if attention_mask is None:
  749. attention_mask = torch.ones(input_shape, device=input_ids.device)
  750. # Prepare head mask if needed
  751. # 1.0 in head_mask indicate we keep the head
  752. # attention_probs has shape bsz x n_heads x N x N
  753. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  754. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  755. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  756. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
  757. attention_mask, input_shape, input_ids.device
  758. )
  759. embedding_output = self.embeddings(
  760. input_ids=input_ids,
  761. token_type_ids=token_type_ids,
  762. position_ids=position_ids,
  763. )
  764. encoder_outputs = self.encoder(
  765. embedding_output,
  766. attention_mask=extended_attention_mask,
  767. head_mask=head_mask,
  768. output_attentions=output_attentions,
  769. output_hidden_states=output_hidden_states,
  770. return_dict=return_dict,
  771. )
  772. sequence_output = encoder_outputs[0]
  773. sequence_output = self.layernorm(sequence_output)
  774. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  775. if not return_dict:
  776. return (sequence_output, pooled_output) + encoder_outputs[1:]
  777. return BaseModelOutputWithPooling(
  778. last_hidden_state=sequence_output,
  779. pooler_output=pooled_output,
  780. hidden_states=encoder_outputs.hidden_states,
  781. attentions=encoder_outputs.attentions,
  782. )
  783. @auto_docstring
  784. class FlavaMultimodalModel(FlavaPreTrainedModel):
  785. config: FlavaMultimodalConfig
  786. # This override allows us to load FlavaMultimodalModel from FlavaModel/FlavaForPreTraining checkpoints.
  787. base_model_prefix = "flava.multimodal_model"
  788. main_input_name = "hidden_states"
  789. def __init__(self, config: FlavaMultimodalConfig, add_pooling_layer=True):
  790. r"""
  791. add_pooling_layer (bool, *optional*, defaults to `True`):
  792. Whether to add a pooling layer
  793. """
  794. super().__init__(config)
  795. self.config = config
  796. self.use_cls_token = self.config.use_cls_token
  797. if self.use_cls_token:
  798. self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
  799. self.encoder = FlavaEncoder(config)
  800. self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  801. self.pooler = FlavaPooler(config) if add_pooling_layer else None
  802. self.post_init()
  803. def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
  804. """
  805. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  806. class PreTrainedModel
  807. """
  808. for layer, heads in heads_to_prune.items():
  809. self.encoder.layer[layer].attention.prune_heads(heads)
  810. @auto_docstring
  811. def forward(
  812. self,
  813. hidden_states: torch.Tensor,
  814. attention_mask: Optional[torch.Tensor] = None,
  815. head_mask: Optional[torch.Tensor] = None,
  816. output_attentions: Optional[bool] = None,
  817. output_hidden_states: Optional[bool] = None,
  818. return_dict: Optional[bool] = None,
  819. ) -> Union[tuple, BaseModelOutputWithPooling]:
  820. r"""
  821. hidden_states (`torch.FloatTensor` of shape `(batch_size, image_num_patches + text_seq_len, hidden_size)`):
  822. The concatenated hidden states of unimodal encoders.
  823. """
  824. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  825. output_hidden_states = (
  826. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  827. )
  828. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  829. batch_size, seq_length, _ = hidden_states.size()
  830. if self.use_cls_token:
  831. cls_tokens = self.cls_token.expand(batch_size, -1, -1)
  832. hidden_states = torch.cat((cls_tokens, hidden_states), dim=1)
  833. seq_length += 1
  834. if attention_mask is None:
  835. attention_mask = torch.ones((batch_size, seq_length), device=hidden_states.device)
  836. # Prepare head mask if needed
  837. # 1.0 in head_mask indicate we keep the head
  838. # attention_probs has shape bsz x n_heads x N x N
  839. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  840. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  841. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  842. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
  843. attention_mask, (batch_size, seq_length), hidden_states.device
  844. )
  845. encoder_outputs = self.encoder(
  846. hidden_states,
  847. attention_mask=extended_attention_mask,
  848. head_mask=head_mask,
  849. output_attentions=output_attentions,
  850. output_hidden_states=output_hidden_states,
  851. return_dict=return_dict,
  852. )
  853. sequence_output = encoder_outputs[0]
  854. sequence_output = self.layernorm(sequence_output)
  855. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  856. if not return_dict:
  857. return (sequence_output, pooled_output) + encoder_outputs[1:]
  858. return BaseModelOutputWithPooling(
  859. last_hidden_state=sequence_output,
  860. pooler_output=pooled_output,
  861. hidden_states=encoder_outputs.hidden_states,
  862. attentions=encoder_outputs.attentions,
  863. )
  864. @auto_docstring
  865. class FlavaModel(FlavaPreTrainedModel):
  866. config: FlavaConfig
  867. def __init__(self, config: FlavaConfig):
  868. super().__init__(config)
  869. if not isinstance(config.text_config, FlavaTextConfig):
  870. raise TypeError(
  871. "config.text_config is expected to be of type FlavaTextConfig but is of type"
  872. f" {type(config.text_config)}."
  873. )
  874. if not isinstance(config.image_config, FlavaImageConfig):
  875. raise TypeError(
  876. "config.image_config is expected to be of type FlavaImageConfig but is of type"
  877. f" {type(config.image_config)}."
  878. )
  879. if not isinstance(config.multimodal_config, FlavaMultimodalConfig):
  880. raise TypeError(
  881. "config.multimodal_config is expected to be of type FlavaMultimodalConfig but "
  882. + f"is of type {type(config.multimodal_config)}."
  883. )
  884. text_config = config.text_config
  885. image_config = config.image_config
  886. multimodal_config = config.multimodal_config
  887. self.projection_dim = config.projection_dim
  888. self.text_hidden_size = text_config.hidden_size
  889. self.image_hidden_size = image_config.hidden_size
  890. self.mm_hidden_size = multimodal_config.hidden_size
  891. self.text_model = FlavaTextModel(text_config)
  892. self.image_model = FlavaImageModel(image_config)
  893. self.multimodal_model = FlavaMultimodalModel(multimodal_config)
  894. self.image_projection = nn.Linear(self.image_hidden_size, self.projection_dim)
  895. self.text_projection = nn.Linear(self.text_hidden_size, self.projection_dim)
  896. self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
  897. self.image_to_mm_projection = nn.Linear(self.image_hidden_size, self.mm_hidden_size)
  898. self.text_to_mm_projection = nn.Linear(self.text_hidden_size, self.mm_hidden_size)
  899. # Initialize weights and apply final processing
  900. self.post_init()
  901. @filter_out_non_signature_kwargs()
  902. @auto_docstring
  903. def get_text_features(
  904. self,
  905. input_ids: torch.Tensor,
  906. attention_mask: Optional[torch.Tensor] = None,
  907. token_type_ids: Optional[torch.Tensor] = None,
  908. position_ids: Optional[torch.Tensor] = None,
  909. ) -> torch.FloatTensor:
  910. r"""
  911. input_ids (`torch.LongTensor` of shape `(batch_size, text_seq_length)`):
  912. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  913. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  914. IDs?](../glossary#input-ids)
  915. token_type_ids (`torch.LongTensor` of shape `(batch_size, text_seq_length)`, *optional*):
  916. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  917. 1]`:
  918. - 0 corresponds to a *sentence A* token,
  919. - 1 corresponds to a *sentence B* token.
  920. [What are token type IDs?](../glossary#token-type-ids)
  921. Returns:
  922. text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
  923. applying the projection layer to the pooled output of [`FlavaTextModel`].
  924. Examples:
  925. ```python
  926. >>> import torch
  927. >>> from transformers import AutoProcessor, FlavaModel
  928. >>> model = FlavaModel.from_pretrained("{0}")
  929. >>> processor = AutoProcessor.from_pretrained("{0}")
  930. >>> inputs = processor(
  931. ... text=["a photo of a cat", "a photo of a dog"], max_length=77, padding="max_length", return_tensors="pt"
  932. ... )
  933. >>> with torch.inference_mode():
  934. ... text_features = model.get_text_features(**inputs)
  935. ```
  936. """
  937. text_outputs: BaseModelOutputWithPooling = self.text_model(
  938. input_ids=input_ids,
  939. attention_mask=attention_mask,
  940. token_type_ids=token_type_ids,
  941. position_ids=position_ids,
  942. )
  943. pooled_output = text_outputs.last_hidden_state
  944. text_features = self.text_projection(pooled_output)
  945. return text_features
  946. @filter_out_non_signature_kwargs()
  947. @auto_docstring
  948. def get_image_features(
  949. self,
  950. pixel_values: torch.Tensor,
  951. bool_masked_pos: Optional[torch.BoolTensor] = None,
  952. interpolate_pos_encoding: Optional[bool] = None,
  953. attention_mask: Optional[torch.Tensor] = None,
  954. head_mask: Optional[torch.Tensor] = None,
  955. ) -> torch.FloatTensor:
  956. r"""
  957. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, image_num_patches)`):
  958. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  959. Returns:
  960. image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
  961. applying the projection layer to the pooled output of [`FlavaImageModel`].
  962. Examples:
  963. ```python
  964. >>> import torch
  965. >>> from transformers import AutoProcessor, FlavaModel
  966. >>> from transformers.image_utils import load_image
  967. >>> model = FlavaModel.from_pretrained("{0}")
  968. >>> processor = AutoProcessor.from_pretrained("{0}")
  969. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  970. >>> image = load_image(url)
  971. >>> inputs = processor(images=image, return_tensors="pt")
  972. >>> with torch.inference_mode():
  973. ... image_features = model.get_image_features(**inputs)
  974. ```
  975. """
  976. image_outputs: BaseModelOutputWithPooling = self.image_model(
  977. pixel_values=pixel_values,
  978. bool_masked_pos=bool_masked_pos,
  979. attention_mask=attention_mask,
  980. head_mask=head_mask,
  981. interpolate_pos_encoding=interpolate_pos_encoding,
  982. )
  983. pooled_output = image_outputs.last_hidden_state
  984. image_features = self.image_projection(pooled_output)
  985. return image_features
  986. @auto_docstring
  987. def forward(
  988. self,
  989. input_ids: Optional[torch.LongTensor] = None,
  990. pixel_values: Optional[torch.FloatTensor] = None,
  991. attention_mask: Optional[torch.Tensor] = None,
  992. token_type_ids: Optional[torch.Tensor] = None,
  993. bool_masked_pos: Optional[torch.Tensor] = None,
  994. position_ids: Optional[torch.LongTensor] = None,
  995. image_attention_mask: Optional[torch.Tensor] = None,
  996. skip_multimodal_encoder: Optional[bool] = None,
  997. output_attentions: Optional[bool] = None,
  998. output_hidden_states: bool = True,
  999. return_dict: Optional[bool] = None,
  1000. ) -> Union[tuple, FlavaOutput]:
  1001. r"""
  1002. input_ids (`torch.LongTensor` of shape `(batch_size, image_num_patches + text_seq_len)`):
  1003. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  1004. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  1005. IDs?](../glossary#input-ids)
  1006. token_type_ids (`torch.LongTensor` of shape `(batch_size, image_num_patches + text_seq_len)`, *optional*):
  1007. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1008. 1]`:
  1009. - 0 corresponds to a *sentence A* token,
  1010. - 1 corresponds to a *sentence B* token.
  1011. [What are token type IDs?](../glossary#token-type-ids)
  1012. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, image_num_patches)`):
  1013. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  1014. image_attention_mask (`torch.Tensor` of shape `(batch_size, image_num_patches)`, *optional*):
  1015. Mask to avoid performing attention on padding pixel values for image inputs. Mask values selected in `[0, 1]`:
  1016. - 1 for pixel values that are real (i.e., **not masked**),
  1017. - 0 for pixel values that are padding (i.e., **masked**).
  1018. skip_multimodal_encoder (*bool*, *optional*):
  1019. Skip any calculations for multimodal encoder. Useful if multimodal encoding is not going to be used.
  1020. Examples:
  1021. ```python
  1022. >>> from PIL import Image
  1023. >>> import requests
  1024. >>> from transformers import AutoProcessor, FlavaModel
  1025. >>> model = FlavaModel.from_pretrained("facebook/flava-full")
  1026. >>> processor = AutoProcessor.from_pretrained("facebook/flava-full")
  1027. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1028. >>> image = Image.open(requests.get(url, stream=True).raw)
  1029. >>> inputs = processor(text=["a photo of a cat"], images=image, return_tensors="pt", padding=True)
  1030. >>> outputs = model(**inputs)
  1031. >>> image_embeddings = outputs.image_embeddings
  1032. >>> text_embeddings = outputs.text_embeddings
  1033. >>> multimodal_embeddings = outputs.multimodal_embeddings
  1034. >>> outputs.image_embeddings.shape
  1035. torch.Size([1, 197, 768])
  1036. >>> text_embeddings.shape
  1037. torch.Size([1, 7, 768])
  1038. >>> multimodal_embeddings.shape
  1039. torch.Size([1, 205, 768])
  1040. ```
  1041. """
  1042. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1043. if not output_hidden_states:
  1044. raise ValueError("FLAVA model requires hidden states to work. Please set `output_hidden_states=True`")
  1045. image_embeddings = None
  1046. image_states = None
  1047. image_mm_projection = None
  1048. image_output = None
  1049. if pixel_values is not None:
  1050. image_output = self.image_model(
  1051. pixel_values=pixel_values,
  1052. bool_masked_pos=bool_masked_pos,
  1053. attention_mask=image_attention_mask,
  1054. output_attentions=output_attentions,
  1055. output_hidden_states=output_hidden_states,
  1056. return_dict=return_dict,
  1057. )
  1058. image_embeddings, image_states = image_output[0], image_output[2]
  1059. # Note that these states don't use final layernorm in the transformer model
  1060. image_mm_projection = self.image_to_mm_projection(image_states[-1])
  1061. text_embeddings = None
  1062. text_states = None
  1063. text_mm_projection = None
  1064. text_output = None
  1065. if input_ids is not None:
  1066. text_output = self.text_model(
  1067. input_ids=input_ids,
  1068. attention_mask=attention_mask,
  1069. position_ids=position_ids,
  1070. token_type_ids=token_type_ids,
  1071. output_attentions=output_attentions,
  1072. output_hidden_states=output_hidden_states,
  1073. return_dict=return_dict,
  1074. )
  1075. text_embeddings, text_states = text_output[0], text_output[2]
  1076. # Note that these states don't use final layernorm in the transformer model
  1077. text_mm_projection = self.text_to_mm_projection(text_states[-1])
  1078. multimodal_embeddings = None
  1079. multimodal_output = None
  1080. if image_mm_projection is not None and text_mm_projection is not None and not skip_multimodal_encoder:
  1081. if attention_mask is not None:
  1082. batch_size, seq_len, _ = image_mm_projection.shape
  1083. if self.multimodal_model.use_cls_token:
  1084. seq_len += 1
  1085. attention_mask_image = torch.ones(batch_size, seq_len, device=image_mm_projection.device)
  1086. attention_multimodal = torch.cat([attention_mask_image, attention_mask], dim=1)
  1087. else:
  1088. attention_multimodal = None
  1089. multimodal_input = torch.cat([image_mm_projection, text_mm_projection], dim=1)
  1090. multimodal_output = self.multimodal_model(
  1091. multimodal_input, attention_mask=attention_multimodal, return_dict=return_dict
  1092. )
  1093. multimodal_embeddings = multimodal_output[0]
  1094. if not return_dict:
  1095. return (
  1096. image_embeddings,
  1097. image_output,
  1098. text_embeddings,
  1099. text_output,
  1100. multimodal_embeddings,
  1101. multimodal_output,
  1102. )
  1103. return FlavaModelOutput(
  1104. image_embeddings=image_embeddings,
  1105. image_output=image_output,
  1106. text_embeddings=text_embeddings,
  1107. text_output=text_output,
  1108. multimodal_embeddings=multimodal_embeddings,
  1109. multimodal_output=multimodal_output,
  1110. )
  1111. class FlavaImageCodebookResPath(nn.Module):
  1112. def __init__(self, in_size: int, out_size: int, **kwargs):
  1113. super().__init__()
  1114. hid_size = out_size // 4
  1115. path = OrderedDict()
  1116. path["relu_1"] = nn.ReLU()
  1117. path["conv_1"] = nn.Conv2d(in_size, hid_size, kernel_size=3, padding=1)
  1118. path["relu_2"] = nn.ReLU()
  1119. path["conv_2"] = nn.Conv2d(hid_size, hid_size, kernel_size=3, padding=1)
  1120. path["relu_3"] = nn.ReLU()
  1121. path["conv_3"] = nn.Conv2d(hid_size, hid_size, kernel_size=3, padding=1)
  1122. path["relu_4"] = nn.ReLU()
  1123. path["conv_4"] = nn.Conv2d(hid_size, out_size, kernel_size=1, padding=0)
  1124. self.path = nn.Sequential(path)
  1125. def forward(self, x: torch.Tensor) -> torch.Tensor:
  1126. return self.path(x)
  1127. class FlavaImageCodebookBlock(nn.Module):
  1128. def __init__(self, in_size: int, out_size: int, num_layers: int, **kwargs):
  1129. super().__init__()
  1130. self.post_gain = 1 / (num_layers**2)
  1131. if in_size != out_size:
  1132. self.id_path = nn.Conv2d(in_size, out_size, kernel_size=1, padding=0)
  1133. else:
  1134. self.id_path = nn.Identity()
  1135. self.res_path = FlavaImageCodebookResPath(in_size, out_size)
  1136. def forward(self, x: torch.Tensor) -> torch.Tensor:
  1137. return self.id_path(x) + self.post_gain * self.res_path(x)
  1138. class FlavaImageCodebookLayerGroup(nn.Module):
  1139. def __init__(self, num_blocks: int, num_layers: int, in_size: int, out_size: int, use_pool: bool = True):
  1140. super().__init__()
  1141. blocks = OrderedDict()
  1142. for i in range(num_blocks):
  1143. if i == 0:
  1144. blocks[f"block_{i + 1}"] = FlavaImageCodebookBlock(in_size, out_size, num_layers)
  1145. else:
  1146. blocks[f"block_{i + 1}"] = FlavaImageCodebookBlock(out_size, out_size, num_layers)
  1147. if use_pool:
  1148. blocks["pool"] = nn.MaxPool2d(kernel_size=2)
  1149. self.group = nn.Sequential(blocks)
  1150. def forward(self, x: torch.Tensor) -> torch.Tensor:
  1151. return self.group(x)
  1152. # Inspired by DALLE Encoder in https://github.com/openai/DALL-E/blob/5be4b236bc3ade6943662354117a0e83752cc322/dall_e/encoder.py#L42
  1153. @auto_docstring(
  1154. custom_intro="""
  1155. The FLAVA's image codebook model inspired from DALL-E's original encoder. Outputs raw hidden states and can be used
  1156. to generate image tokens for an image based on DALL-E's vocab. Used to generate labels for MIM. Use
  1157. `get_codebook_indices` to get image tokens for an image.
  1158. """
  1159. )
  1160. class FlavaImageCodebook(FlavaPreTrainedModel):
  1161. base_model_prefix = ""
  1162. config: FlavaImageCodebookConfig
  1163. main_input_name = "pixel_values"
  1164. supports_gradient_checkpointing = False
  1165. def __init__(
  1166. self,
  1167. config: FlavaImageCodebookConfig,
  1168. **kwargs: Any,
  1169. ):
  1170. super().__init__(config)
  1171. self.config = config
  1172. self.num_groups = config.num_groups
  1173. self.input_channels = config.input_channels
  1174. self.num_blocks_per_group = config.num_blocks_per_group
  1175. self.hidden_size = config.hidden_size
  1176. self.vocab_size = config.vocab_size
  1177. num_layers = self.num_groups * self.num_blocks_per_group
  1178. output_blocks = OrderedDict()
  1179. output_blocks["relu"] = nn.ReLU()
  1180. output_blocks["conv"] = nn.Conv2d(8 * self.hidden_size, self.vocab_size, kernel_size=1, padding=0)
  1181. blocks = OrderedDict()
  1182. blocks["input"] = nn.Conv2d(self.input_channels, 1 * self.hidden_size, kernel_size=7, padding=3)
  1183. blocks["group_1"] = FlavaImageCodebookLayerGroup(
  1184. self.num_blocks_per_group, num_layers, 1 * self.hidden_size, 1 * self.hidden_size
  1185. )
  1186. blocks["group_2"] = FlavaImageCodebookLayerGroup(
  1187. self.num_blocks_per_group, num_layers, 1 * self.hidden_size, 2 * self.hidden_size
  1188. )
  1189. blocks["group_3"] = FlavaImageCodebookLayerGroup(
  1190. self.num_blocks_per_group, num_layers, 2 * self.hidden_size, 4 * self.hidden_size
  1191. )
  1192. blocks["group_4"] = FlavaImageCodebookLayerGroup(
  1193. self.num_blocks_per_group, num_layers, 4 * self.hidden_size, 8 * self.hidden_size, use_pool=False
  1194. )
  1195. blocks["output"] = nn.Sequential(output_blocks)
  1196. self.blocks = nn.Sequential(blocks)
  1197. self.post_init()
  1198. if self.config.freeze:
  1199. for param in self.parameters():
  1200. param.requires_grad = False
  1201. def get_codebook_indices(self, pixel_values: torch.Tensor) -> torch.Tensor:
  1202. f"""
  1203. Args:
  1204. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  1205. Pixel values. Codebook pixel values can be obtained using [`AutoImageProcessor`] by passing
  1206. `return_codebook_pixels=True`. See [`FlavaImageProcessor.__call__`] for details.
  1207. Examples:
  1208. ```python
  1209. >>> from PIL import Image
  1210. >>> import requests
  1211. >>> from transformers import AutoImageProcessor, FlavaImageCodebook
  1212. >>> model = FlavaImageCodebook.from_pretrained("{_CHECKPOINT_FOR_CODEBOOK_DOC}")
  1213. >>> image_processor = AutoImageProcessor.from_pretrained("{_CHECKPOINT_FOR_CODEBOOK_DOC}")
  1214. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1215. >>> image = Image.open(requests.get(url, stream=True).raw)
  1216. >>> inputs = image_processor([image], return_codebook_pixels=True, return_tensors="pt")
  1217. >>> inputs = dict(pixel_values=inputs.codebook_pixel_values)
  1218. >>> outputs = model.get_codebook_indices(**inputs)
  1219. ```
  1220. """
  1221. z_logits = self.blocks(pixel_values)
  1222. return torch.argmax(z_logits, axis=1)
  1223. def get_codebook_probs(self, pixel_values: torch.Tensor) -> torch.Tensor:
  1224. z_logits = self.blocks(pixel_values)
  1225. return nn.Softmax(dim=1)(z_logits)
  1226. def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
  1227. f"""
  1228. Args:
  1229. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  1230. Pixel values. Codebook pixel values can be obtained using [`AutoImageProcessor`] by passing
  1231. `return_codebook_pixels=True`. See [`FlavaImageProcessor.__call__`] for details.
  1232. Examples:
  1233. ```python
  1234. >>> from PIL import Image
  1235. >>> import requests
  1236. >>> from transformers import AutoImageProcessor, FlavaImageCodebook
  1237. >>> model = FlavaImageCodebook.from_pretrained("{_CHECKPOINT_FOR_CODEBOOK_DOC}")
  1238. >>> image_processor = AutoImageProcessor.from_pretrained("{_CHECKPOINT_FOR_CODEBOOK_DOC}")
  1239. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1240. >>> image = Image.open(requests.get(url, stream=True).raw)
  1241. >>> inputs = image_processor([image], return_codebook_pixels=True, return_tensors="pt")
  1242. >>> inputs = dict(pixel_values=inputs.codebook_pixel_values)
  1243. >>> outputs = model(**inputs)
  1244. >>> print(outputs.shape)
  1245. (1, 196)
  1246. ```
  1247. """
  1248. if len(pixel_values.shape) != 4:
  1249. raise ValueError(f"input shape {pixel_values.shape} is not 4d")
  1250. if pixel_values.shape[1] != self.input_channels:
  1251. raise ValueError(f"input has {pixel_values.shape[1]} channels but model built for {self.input_channels}")
  1252. return self.blocks(pixel_values)
  1253. class FlavaPredictionHeadTransform(nn.Module):
  1254. def __init__(self, config):
  1255. super().__init__()
  1256. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  1257. if isinstance(config.hidden_act, str):
  1258. self.transform_act_fn = ACT2FN[config.hidden_act]
  1259. else:
  1260. self.transform_act_fn = config.hidden_act
  1261. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  1262. def forward(self, hidden_states):
  1263. hidden_states = self.dense(hidden_states)
  1264. hidden_states = self.transform_act_fn(hidden_states)
  1265. hidden_states = self.LayerNorm(hidden_states)
  1266. return hidden_states
  1267. class FlavaMaskedPredictionHead(nn.Module):
  1268. def __init__(self, config, weight=None):
  1269. super().__init__()
  1270. self.config = config
  1271. self.transform = FlavaPredictionHeadTransform(config)
  1272. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  1273. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  1274. if weight is not None:
  1275. self.decoder.weight = weight
  1276. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  1277. self.decoder.bias = self.bias
  1278. def _tie_weights(self):
  1279. self.decoder.bias = self.bias
  1280. def forward(self, x):
  1281. x = self.transform(x)
  1282. x = self.decoder(x)
  1283. return x
  1284. class FlavaITMHead(nn.Module):
  1285. def __init__(self, config):
  1286. super().__init__()
  1287. self.config = config
  1288. self.pooler = FlavaPooler(config)
  1289. self.seq_relationship = nn.Linear(config.hidden_size, 2)
  1290. def forward(self, x):
  1291. x = self.pooler(x)
  1292. x = self.seq_relationship(x)
  1293. return x
  1294. class FlavaGlobalContrastiveHead(nn.Module):
  1295. def __init__(self, config):
  1296. super().__init__()
  1297. self.config = config
  1298. self.global_backprop_contrastive = config.global_backprop_contrastive
  1299. def forward(self, image_embeddings, text_embeddings, logit_scale):
  1300. temperature = torch.exp(logit_scale)
  1301. if not torch.distributed.is_available() or not torch.distributed.is_initialized():
  1302. labels = torch.arange(image_embeddings.size(0), device=image_embeddings.device)
  1303. image_embeddings_all = [image_embeddings]
  1304. text_embeddings_all = [text_embeddings]
  1305. else:
  1306. local_batch_size = image_embeddings.size(0)
  1307. world_size = torch.distributed.get_world_size()
  1308. if self.global_backprop_contrastive:
  1309. # `torch.distributed.nn.functional.all_gather` does backprop on all active workers
  1310. # whereas `torch.distributed.all_gather` does only backpropagates on the current worker.
  1311. image_embeddings_all = torch.distributed.nn.functional.all_gather(image_embeddings)
  1312. text_embeddings_all = torch.distributed.nn.functional.all_gather(text_embeddings)
  1313. else:
  1314. image_embeddings_all = [torch.zeros_like(text_embeddings) for _ in range(world_size)]
  1315. text_embeddings_all = [torch.zeros_like(image_embeddings) for _ in range(world_size)]
  1316. torch.distributed.all_gather(image_embeddings_all, image_embeddings)
  1317. torch.distributed.all_gather(text_embeddings_all, text_embeddings)
  1318. labels = local_batch_size * torch.distributed.get_rank() + torch.arange(
  1319. local_batch_size, device=image_embeddings.device
  1320. )
  1321. image_embeddings_all = torch.cat(image_embeddings_all)
  1322. text_embeddings_all = torch.cat(text_embeddings_all)
  1323. logits_per_image = torch.matmul(image_embeddings, text_embeddings_all.transpose(0, 1)) * temperature
  1324. logits_per_text = torch.matmul(text_embeddings, image_embeddings_all.transpose(0, 1)) * temperature
  1325. return logits_per_image, logits_per_text, labels
  1326. @auto_docstring(
  1327. custom_intro="""
  1328. The FLAVA model for pretraining which outputs losses, embeddings, logits and transformer outputs.
  1329. """
  1330. )
  1331. class FlavaForPreTraining(FlavaPreTrainedModel):
  1332. # Those are linked to xxx.bias
  1333. _tied_weights_keys = [
  1334. "mmm_text_head.decoder.bias",
  1335. "mmm_image_head.decoder.bias",
  1336. "mlm_head.decoder.bias",
  1337. "mim_head.decoder.bias",
  1338. ]
  1339. def __init__(self, config: FlavaConfig, image_codebook: Optional[nn.Module] = None):
  1340. r"""
  1341. image_codebook ([`nn.Module`]):
  1342. If passed, the image codebook will be set to this. Otherwise, it will be initialized using the
  1343. image_codebook_config defined in the config first as the first parameter.
  1344. """
  1345. super().__init__(config)
  1346. self.flava = FlavaModel(config)
  1347. self.image_codebook = image_codebook
  1348. if self.image_codebook is None and config.init_codebook:
  1349. self.image_codebook = FlavaImageCodebook(config.image_codebook_config)
  1350. # Levarage text and image encoder configs to create the masked
  1351. # head since it has the right vocab
  1352. self.mim_head = FlavaMaskedPredictionHead(config.image_config)
  1353. self.mlm_head = FlavaMaskedPredictionHead(config.text_config)
  1354. self.itm_head = FlavaITMHead(config)
  1355. self.mmm_image_head = FlavaMaskedPredictionHead(config.image_config)
  1356. self.mmm_text_head = FlavaMaskedPredictionHead(config.text_config)
  1357. self.global_contrastive_head = FlavaGlobalContrastiveHead(config)
  1358. self.image_vocab_size = config.image_config.vocab_size
  1359. self.text_vocab_size = config.text_config.vocab_size
  1360. self.mlm_weight = config.mlm_weight
  1361. self.mim_weight = config.mim_weight
  1362. self.global_contrastive_weight = config.global_contrastive_weight
  1363. self.ce_ignore_index = config.ce_ignore_index
  1364. self.itm_weight = config.itm_weight
  1365. self.mmm_image_weight = config.mmm_image_weight
  1366. self.mmm_text_weight = config.mmm_text_weight
  1367. self.skip_unmasked_multimodal_encoder = config.skip_unmasked_multimodal_encoder
  1368. self.post_init()
  1369. def _resize_to_2d(self, x: torch.Tensor):
  1370. if x.dim() > 2:
  1371. x = x.view(x.size(0), -1)
  1372. return x
  1373. @auto_docstring
  1374. def forward(
  1375. self,
  1376. input_ids: Optional[torch.LongTensor] = None,
  1377. input_ids_masked: Optional[torch.LongTensor] = None,
  1378. pixel_values: Optional[torch.FloatTensor] = None,
  1379. codebook_pixel_values: Optional[torch.FloatTensor] = None,
  1380. attention_mask: Optional[torch.Tensor] = None,
  1381. token_type_ids: Optional[torch.Tensor] = None,
  1382. bool_masked_pos: Optional[torch.Tensor] = None,
  1383. position_ids: Optional[torch.LongTensor] = None,
  1384. image_attention_mask: Optional[torch.Tensor] = None,
  1385. skip_unmasked_multimodal_encoder: Optional[bool] = None,
  1386. mlm_labels: Optional[torch.Tensor] = None,
  1387. mim_labels: Optional[torch.Tensor] = None,
  1388. itm_labels: Optional[torch.Tensor] = None,
  1389. output_attentions: Optional[bool] = None,
  1390. output_hidden_states: bool = True,
  1391. return_dict: Optional[bool] = None,
  1392. return_loss: Optional[bool] = None,
  1393. ) -> Union[tuple[torch.Tensor], FlavaForPreTrainingOutput]:
  1394. r"""
  1395. input_ids (`torch.LongTensor` of shape `(batch_size, text_seq_len)`):
  1396. Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
  1397. [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
  1398. IDs?](../glossary#input-ids)
  1399. input_ids_masked (`torch.LongTensor` of shape `(batch_size, text_seq_len)`):
  1400. Indices of input sequence tokens in the vocabulary. These ones are the masked version of the original task
  1401. to be used with MLM. Indices can be obtained using [`AutoTokenizer`] along with
  1402. [`DataCollatorForMaskedLanguageModeling`]. See [`PreTrainedTokenizer.encode`] and
  1403. [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids)
  1404. codebook_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_image_patches, patch_size, patch_size, 3)`, *optional*):
  1405. Pixel values for image patches that are used to compute the image codebook labels for masked image modeling.
  1406. token_type_ids (`torch.LongTensor` of shape `(batch_size, text_seq_len)`, *optional*):
  1407. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1408. 1]`:
  1409. - 0 corresponds to a *sentence A* token,
  1410. - 1 corresponds to a *sentence B* token.
  1411. [What are token type IDs?](../glossary#token-type-ids)
  1412. bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, image_num_patches)`):
  1413. Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
  1414. image_attention_mask (`torch.FloatTensor` of shape `(batch_size, image_num_patches)`, *optional*):
  1415. Mask to avoid performing attention on padding token indices specifically for images. Mask values selected
  1416. in `[0, 1]`:
  1417. - 1 for tokens that are **not masked**,
  1418. - 0 for tokens that are **masked**.
  1419. [What are attention masks?](../glossary#attention-mask)
  1420. skip_unmasked_multimodal_encoder (*bool*, *optional*):
  1421. Skip any calculations for multimodal encoder for unmasked inputs. FLAVA pretraining doesn't need unmasked
  1422. multimodal embeddings or outputs as of now.
  1423. mlm_labels (`torch.LongTensor` of shape `(batch_size, text_seq_len)`, *optional*):
  1424. Labels for computing the left-to-right language and multimodal masked modeling loss (next word prediction).
  1425. Indices should be in `[-100, 0, ..., text_config.vocab_size - 1]` (see `input_ids` docstring). Tokens with
  1426. indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0,
  1427. ..., text_config.vocab_size - 1]`.
  1428. mim_labels (`torch.LongTensor` of shape `(batch_size, image_num_patches)`, *optional*):
  1429. Labels for computing the image and multimodal masked modeling loss. Indices should be in `[-100, 0, ...,
  1430. image_config.vocab_size - 1]`. Tokens with indices set to `-100` are ignored (masked), the loss is only
  1431. computed for the tokens with labels in `[0, ..., image_config.vocab_size - 1]`. If not passed, they are
  1432. generated automatically using the image codebook assigned to the model. By default, it uses
  1433. [`FlavaImageCodebook`]. See [`FlavaImageCodebook`] to understand how to generate mim_labels.
  1434. itm_labels (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*):
  1435. Labels for computing the image-text matching loss. 0 means the pairs don't match and 1 means they match.
  1436. The pairs with 0 will be skipped for calculation of MMM and global contrastive losses as well.
  1437. return_loss (`bool`, *optional*, default to None):
  1438. Whether to return calculated loss or not.
  1439. Examples:
  1440. ```python
  1441. >>> from PIL import Image
  1442. >>> import requests
  1443. >>> from transformers import FlavaForPreTraining, AutoProcessor
  1444. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1445. >>> image = Image.open(requests.get(url, stream=True).raw)
  1446. >>> model = FlavaForPreTraining.from_pretrained("facebook/flava-full")
  1447. >>> processor = AutoProcessor.from_pretrained("facebook/flava-full")
  1448. >>> text = ["a photo of a cat"]
  1449. >>> inputs = processor(
  1450. ... images=[image],
  1451. ... text=text,
  1452. ... return_masks=True,
  1453. ... return_codebook_pixels=True,
  1454. ... padding=True,
  1455. ... max_length=77,
  1456. ... return_tensors="pt",
  1457. ... )
  1458. >>> output = model(**inputs)
  1459. ```
  1460. """
  1461. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1462. return_loss = return_loss if return_loss is not None else self.config.return_loss
  1463. skip_unmasked_multimodal_encoder = (
  1464. skip_unmasked_multimodal_encoder
  1465. if skip_unmasked_multimodal_encoder is not None
  1466. else self.skip_unmasked_multimodal_encoder
  1467. )
  1468. if input_ids_masked is None and input_ids is not None:
  1469. logger.warning(
  1470. "`input_ids_masked` isn't passed which means MLM loss won't be calculated correctlySetting it to"
  1471. " `input_ids` so that model can work. Please pass it if this is unintentional. This is usually OKAY if"
  1472. " you are doing inference on unmasked text..."
  1473. )
  1474. input_ids_masked = input_ids
  1475. flava_output = self.flava(
  1476. input_ids=input_ids,
  1477. pixel_values=pixel_values,
  1478. attention_mask=attention_mask,
  1479. token_type_ids=token_type_ids,
  1480. position_ids=position_ids,
  1481. image_attention_mask=image_attention_mask,
  1482. # Don't need unmasked multimodal embedding for anything so skip it
  1483. # NOTE: ITM uses masked version
  1484. skip_multimodal_encoder=skip_unmasked_multimodal_encoder,
  1485. output_attentions=output_attentions,
  1486. output_hidden_states=output_hidden_states,
  1487. # Pass true to have deterministic outputs
  1488. return_dict=True,
  1489. )
  1490. flava_masked_output = self.flava(
  1491. input_ids=input_ids_masked,
  1492. pixel_values=pixel_values,
  1493. attention_mask=attention_mask,
  1494. token_type_ids=token_type_ids,
  1495. image_attention_mask=image_attention_mask,
  1496. bool_masked_pos=bool_masked_pos,
  1497. output_attentions=output_attentions,
  1498. output_hidden_states=output_hidden_states,
  1499. return_dict=True,
  1500. )
  1501. pos_mask = None
  1502. image_embeddings = flava_output.image_embeddings
  1503. text_embeddings = flava_output.text_embeddings
  1504. image_masked_embeddings = flava_masked_output.image_embeddings
  1505. text_masked_embeddings = flava_masked_output.text_embeddings
  1506. multimodal_masked_embeddings = flava_masked_output.multimodal_embeddings
  1507. total_loss = mim_loss = mlm_loss = mmm_text_loss = mmm_image_loss = gc_loss = itm_loss = None
  1508. mim_logits = mlm_logits = mmm_text_logits = mmm_image_logits = None
  1509. itm_logits = logits_per_image = logits_per_text = None
  1510. # Calculate mim_labels if necessary from the image_codebook
  1511. if image_masked_embeddings is not None or multimodal_masked_embeddings is not None:
  1512. if mim_labels is None and return_loss:
  1513. if self.image_codebook is None:
  1514. raise RuntimeError(
  1515. "`return_loss` is set to True but the image codebook is not initialized and no `mim_labels` "
  1516. " have been passed. Reinstantiate the model with `init_codebook` set to True or "
  1517. "pass in your custom `mim_labels`"
  1518. )
  1519. if codebook_pixel_values is None:
  1520. raise ValueError(
  1521. "`codebook_pixel_value` are required to generate `mim_labels` if loss is expected. "
  1522. "Call `AutoProcessor` with `return_codebook_pixels` set to True"
  1523. )
  1524. mim_labels = self.image_codebook.get_codebook_indices(codebook_pixel_values)
  1525. # Unimodal MIM Loss
  1526. # If multimodal embeddings are present, we will calculate MMM loss
  1527. if self.mim_weight > 0 and image_masked_embeddings is not None and multimodal_masked_embeddings is None:
  1528. sequence_for_image = image_masked_embeddings
  1529. if mim_labels is not None:
  1530. mim_labels = self._resize_to_2d(mim_labels)
  1531. bool_masked_pos = self._resize_to_2d(bool_masked_pos)
  1532. mim_labels[bool_masked_pos.ne(True)] = self.ce_ignore_index
  1533. sequence_for_image = sequence_for_image[:, -mim_labels.size(1) :, :]
  1534. masked_tokens = mim_labels.ne(self.ce_ignore_index)
  1535. mim_labels_filtered = mim_labels[masked_tokens]
  1536. sequence_for_image = sequence_for_image[masked_tokens, :]
  1537. mim_logits = self.mim_head(sequence_for_image)
  1538. if return_loss:
  1539. mim_loss = nn.functional.cross_entropy(
  1540. mim_logits.view(-1, self.image_vocab_size), mim_labels_filtered.view(-1)
  1541. )
  1542. mim_loss *= self.mim_weight
  1543. else:
  1544. mim_logits = self.mim_head(sequence_for_image)
  1545. # Unimodal MLM Loss
  1546. if self.mlm_weight > 0 and text_masked_embeddings is not None and multimodal_masked_embeddings is None:
  1547. sequence_for_text = text_masked_embeddings
  1548. if mlm_labels is not None:
  1549. mlm_labels = self._resize_to_2d(mlm_labels)
  1550. sequence_for_text = sequence_for_text[:, -mlm_labels.size(1) :, :]
  1551. masked_tokens = mlm_labels.ne(self.ce_ignore_index)
  1552. mlm_labels_filtered = mlm_labels[masked_tokens]
  1553. sequence_for_text = sequence_for_text[masked_tokens, :]
  1554. mlm_logits = self.mlm_head(sequence_for_text)
  1555. if return_loss:
  1556. mlm_loss = nn.functional.cross_entropy(
  1557. mlm_logits.view(-1, self.text_vocab_size), mlm_labels_filtered.view(-1)
  1558. )
  1559. mlm_loss *= self.mlm_weight
  1560. else:
  1561. mlm_logits = self.mlm_head(sequence_for_text)
  1562. # ITM Loss
  1563. if self.itm_weight > 0 and multimodal_masked_embeddings is not None:
  1564. itm_logits = self.itm_head(multimodal_masked_embeddings)
  1565. if itm_labels is not None:
  1566. pos_pairs = itm_labels.ne(0)
  1567. pos_mask = torch.where(pos_pairs.any(), pos_pairs, pos_pairs.new([True]))
  1568. if return_loss:
  1569. itm_loss = nn.functional.cross_entropy(itm_logits, itm_labels)
  1570. itm_loss *= self.itm_weight
  1571. if multimodal_masked_embeddings is not None:
  1572. multimodal_masked_embeddings = multimodal_masked_embeddings[pos_mask]
  1573. if mlm_labels is not None:
  1574. mlm_labels = mlm_labels[pos_mask]
  1575. if mim_labels is not None:
  1576. mim_labels = mim_labels[pos_mask]
  1577. bool_masked_pos = bool_masked_pos[pos_mask]
  1578. # MMM Image Loss
  1579. if multimodal_masked_embeddings is not None and self.mmm_image_weight > 0:
  1580. sequence_for_image = multimodal_masked_embeddings
  1581. end_index = image_masked_embeddings.size(1) - 1
  1582. sequence_for_image = sequence_for_image[:, 2 : 2 + end_index, :]
  1583. if mim_labels is not None:
  1584. mim_labels = self._resize_to_2d(mim_labels)
  1585. bool_masked_pos = self._resize_to_2d(bool_masked_pos)
  1586. mim_labels[bool_masked_pos.ne(True)] = self.ce_ignore_index
  1587. masked_tokens = mim_labels.ne(self.ce_ignore_index)
  1588. mim_labels_filtered = mim_labels[masked_tokens]
  1589. sequence_for_image = sequence_for_image[masked_tokens, :]
  1590. mmm_image_logits = self.mmm_image_head(sequence_for_image)
  1591. if return_loss:
  1592. mmm_image_loss = nn.functional.cross_entropy(
  1593. mmm_image_logits.view(-1, self.image_vocab_size), mim_labels_filtered.view(-1)
  1594. )
  1595. mmm_image_loss *= self.mmm_image_weight
  1596. else:
  1597. mmm_image_logits = self.mmm_image_head(sequence_for_image)
  1598. # MMM Text Loss
  1599. if multimodal_masked_embeddings is not None and self.mmm_text_weight > 0:
  1600. sequence_for_text = multimodal_masked_embeddings
  1601. sequence_for_text = sequence_for_text[:, -text_masked_embeddings.size(1) :, :]
  1602. if mlm_labels is not None:
  1603. mlm_labels = self._resize_to_2d(mlm_labels)
  1604. masked_tokens = mlm_labels.ne(self.ce_ignore_index)
  1605. mlm_labels_filtered = mlm_labels[masked_tokens]
  1606. sequence_for_text = sequence_for_text[masked_tokens, :]
  1607. mmm_text_logits = self.mmm_text_head(sequence_for_text)
  1608. if return_loss:
  1609. mmm_text_loss = nn.functional.cross_entropy(
  1610. mmm_text_logits.view(-1, self.text_vocab_size), mlm_labels_filtered.view(-1)
  1611. )
  1612. mmm_text_loss *= self.mmm_text_weight
  1613. else:
  1614. mmm_text_logits = self.mmm_text_head(sequence_for_text)
  1615. # Global Contrastive Loss
  1616. if image_embeddings is not None and text_embeddings is not None and self.global_contrastive_weight > 0:
  1617. text_embedding = self.flava.text_projection(text_embeddings[:, 0, :])
  1618. text_embedding = nn.functional.normalize(text_embedding, dim=-1)
  1619. image_embedding = self.flava.image_projection(image_embeddings[:, 0, :])
  1620. image_embedding = nn.functional.normalize(image_embedding, dim=-1)
  1621. self.flava.logit_scale.data.clamp_(LOGIT_SCALE_CLAMP_MIN, LOGIT_SCALE_CLAMP_MAX)
  1622. logits_per_image, logits_per_text, gc_labels = self.global_contrastive_head(
  1623. image_embedding, text_embedding, self.flava.logit_scale
  1624. )
  1625. # Apply ITM negative mask if any
  1626. if pos_mask is not None:
  1627. logits_per_image = logits_per_image[pos_mask]
  1628. logits_per_text = logits_per_text[pos_mask]
  1629. gc_labels = gc_labels[pos_mask]
  1630. if return_loss:
  1631. gc_loss_image = nn.functional.cross_entropy(logits_per_image, gc_labels)
  1632. gc_loss_text = nn.functional.cross_entropy(logits_per_text, gc_labels)
  1633. gc_loss = (gc_loss_image + gc_loss_text) / 2
  1634. gc_loss *= self.global_contrastive_weight
  1635. flava_losses = FlavaLosses(
  1636. mim=mim_loss,
  1637. mlm=mlm_loss,
  1638. itm=itm_loss,
  1639. global_contrastive=gc_loss,
  1640. mmm_image=mmm_image_loss,
  1641. mmm_text=mmm_text_loss,
  1642. )
  1643. if return_loss and not flava_losses.all_none():
  1644. total_loss = sum(loss if loss is not None else 0 for loss in flava_losses.values())
  1645. if not return_dict:
  1646. output = (
  1647. image_embeddings,
  1648. flava_output.image_output.to_tuple() if flava_output.image_output is not None else None,
  1649. text_embeddings,
  1650. flava_output.text_output.to_tuple() if flava_output.text_output is not None else None,
  1651. flava_output.multimodal_embeddings,
  1652. flava_output.multimodal_output.to_tuple() if flava_output.multimodal_output is not None else None,
  1653. image_masked_embeddings,
  1654. flava_masked_output.image_output.to_tuple() if flava_masked_output.image_output is not None else None,
  1655. text_masked_embeddings,
  1656. flava_masked_output.text_output.to_tuple() if flava_masked_output.text_output is not None else None,
  1657. multimodal_masked_embeddings,
  1658. flava_masked_output.multimodal_output.to_tuple()
  1659. if flava_masked_output.multimodal_output is not None
  1660. else None,
  1661. mim_logits,
  1662. mlm_logits,
  1663. itm_logits,
  1664. logits_per_image,
  1665. logits_per_image,
  1666. mmm_image_logits,
  1667. mmm_text_logits,
  1668. )
  1669. if return_loss and not flava_losses.all_none():
  1670. output = (
  1671. total_loss,
  1672. flava_losses,
  1673. ) + output
  1674. # Filter None as transformer by default won't handle it
  1675. return tuple(x for x in output if x is None)
  1676. return FlavaForPreTrainingOutput(
  1677. loss=total_loss,
  1678. loss_info=flava_losses,
  1679. image_embeddings=image_embeddings,
  1680. image_output=flava_output.image_output,
  1681. text_embeddings=text_embeddings,
  1682. text_output=flava_output.text_output,
  1683. multimodal_embeddings=flava_output.multimodal_embeddings,
  1684. multimodal_output=flava_output.multimodal_output,
  1685. image_masked_embeddings=image_masked_embeddings,
  1686. image_masked_output=flava_masked_output.image_output,
  1687. text_masked_embeddings=text_masked_embeddings,
  1688. text_masked_output=flava_masked_output.text_output,
  1689. multimodal_masked_embeddings=multimodal_masked_embeddings,
  1690. multimodal_masked_output=flava_masked_output.multimodal_output,
  1691. mim_logits=mim_logits,
  1692. mlm_logits=mlm_logits,
  1693. itm_logits=itm_logits,
  1694. contrastive_logits_per_image=logits_per_image,
  1695. contrastive_logits_per_text=logits_per_text,
  1696. mmm_image_logits=mmm_image_logits,
  1697. mmm_text_logits=mmm_text_logits,
  1698. )
  1699. __all__ = [
  1700. "FlavaForPreTraining",
  1701. "FlavaImageCodebook",
  1702. "FlavaImageModel",
  1703. "FlavaModel",
  1704. "FlavaMultimodalModel",
  1705. "FlavaPreTrainedModel",
  1706. "FlavaTextModel",
  1707. ]