modeling_altclip.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. # Copyright 2022 The BAAI Teams Authors and The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """PyTorch AltCLIP model."""
  15. import math
  16. from collections.abc import Callable
  17. from dataclasses import dataclass
  18. from typing import Any
  19. import torch
  20. import torch.nn as nn
  21. from ... import initialization as init
  22. from ...activations import ACT2FN
  23. from ...modeling_layers import GradientCheckpointingLayer
  24. from ...modeling_outputs import (
  25. BaseModelOutput,
  26. BaseModelOutputWithPooling,
  27. BaseModelOutputWithPoolingAndProjection,
  28. )
  29. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  30. from ...processing_utils import Unpack
  31. from ...pytorch_utils import apply_chunking_to_forward
  32. from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_int
  33. from ...utils.generic import merge_with_config_defaults
  34. from ...utils.output_capturing import capture_outputs
  35. from .configuration_altclip import AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig
  36. logger = logging.get_logger(__name__)
  37. # contrastive loss function, adapted from
  38. # https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
  39. def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
  40. return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
  41. def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
  42. caption_loss = contrastive_loss(similarity)
  43. image_loss = contrastive_loss(similarity.t())
  44. return (caption_loss + image_loss) / 2.0
  45. @dataclass
  46. @auto_docstring
  47. # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP
  48. class AltCLIPOutput(ModelOutput):
  49. r"""
  50. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
  51. Contrastive loss for image-text similarity.
  52. logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
  53. The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
  54. similarity scores.
  55. logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
  56. The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
  57. similarity scores.
  58. text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
  59. The text embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPTextModel`].
  60. image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
  61. The image embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPVisionModel`].
  62. text_model_output (`BaseModelOutputWithPooling`):
  63. The output of the [`AltCLIPTextModel`].
  64. vision_model_output (`BaseModelOutputWithPooling`):
  65. The output of the [`AltCLIPVisionModel`].
  66. """
  67. loss: torch.FloatTensor | None = None
  68. logits_per_image: torch.FloatTensor | None = None
  69. logits_per_text: torch.FloatTensor | None = None
  70. text_embeds: torch.FloatTensor | None = None
  71. image_embeds: torch.FloatTensor | None = None
  72. text_model_output: BaseModelOutputWithPooling = None
  73. vision_model_output: BaseModelOutputWithPooling = None
  74. def to_tuple(self) -> tuple[Any]:
  75. return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values())
  76. # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->AltRoberta
  77. class AltRobertaEmbeddings(nn.Module):
  78. """Construct the embeddings from word, position and token_type embeddings."""
  79. def __init__(self, config):
  80. super().__init__()
  81. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  82. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  83. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  84. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  85. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  86. self.register_buffer(
  87. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  88. )
  89. self.register_buffer(
  90. "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
  91. )
  92. self.padding_idx = config.pad_token_id
  93. self.position_embeddings = nn.Embedding(
  94. config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
  95. )
  96. def forward(
  97. self,
  98. input_ids: torch.LongTensor | None = None,
  99. token_type_ids: torch.LongTensor | None = None,
  100. position_ids: torch.LongTensor | None = None,
  101. inputs_embeds: torch.FloatTensor | None = None,
  102. past_key_values_length: int = 0,
  103. ) -> torch.Tensor:
  104. if position_ids is None:
  105. if input_ids is not None:
  106. # Create the position ids from the input token ids. Any padded tokens remain padded.
  107. position_ids = self.create_position_ids_from_input_ids(
  108. input_ids, self.padding_idx, past_key_values_length
  109. )
  110. else:
  111. position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
  112. if input_ids is not None:
  113. input_shape = input_ids.size()
  114. else:
  115. input_shape = inputs_embeds.size()[:-1]
  116. batch_size, seq_length = input_shape
  117. # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
  118. # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
  119. # issue #5664
  120. if token_type_ids is None:
  121. if hasattr(self, "token_type_ids"):
  122. # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
  123. buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
  124. buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
  125. token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
  126. else:
  127. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  128. if inputs_embeds is None:
  129. inputs_embeds = self.word_embeddings(input_ids)
  130. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  131. embeddings = inputs_embeds + token_type_embeddings
  132. position_embeddings = self.position_embeddings(position_ids)
  133. embeddings = embeddings + position_embeddings
  134. embeddings = self.LayerNorm(embeddings)
  135. embeddings = self.dropout(embeddings)
  136. return embeddings
  137. @staticmethod
  138. def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
  139. """
  140. We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
  141. Args:
  142. inputs_embeds: torch.Tensor
  143. Returns: torch.Tensor
  144. """
  145. input_shape = inputs_embeds.size()[:-1]
  146. sequence_length = input_shape[1]
  147. position_ids = torch.arange(
  148. padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
  149. )
  150. return position_ids.unsqueeze(0).expand(input_shape)
  151. @staticmethod
  152. def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
  153. """
  154. Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
  155. are ignored. This is modified from fairseq's `utils.make_positions`.
  156. Args:
  157. x: torch.Tensor x:
  158. Returns: torch.Tensor
  159. """
  160. # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
  161. mask = input_ids.ne(padding_idx).int()
  162. incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
  163. return incremental_indices.long() + padding_idx
  164. class AltRobertaSelfAttention(nn.Module):
  165. def __init__(self, config):
  166. super().__init__()
  167. self.config = config
  168. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  169. raise ValueError(
  170. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  171. f"heads ({config.num_attention_heads})"
  172. )
  173. self.num_attention_heads = config.num_attention_heads
  174. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  175. self.all_head_size = self.num_attention_heads * self.attention_head_size
  176. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  177. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  178. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  179. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  180. def forward(
  181. self,
  182. hidden_states: torch.Tensor,
  183. attention_mask: torch.FloatTensor | None = None,
  184. **kwargs: Unpack[TransformersKwargs],
  185. ) -> tuple[torch.Tensor]:
  186. input_shape = hidden_states.shape[:-1]
  187. hidden_shape = (*input_shape, -1, self.attention_head_size)
  188. query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
  189. key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
  190. value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
  191. # Take the dot product between "query" and "key" to get the raw attention scores.
  192. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  193. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  194. if attention_mask is not None:
  195. # Apply the attention mask is (precomputed for all layers in AltRobertaModel forward() function)
  196. attention_scores = attention_scores + attention_mask
  197. # Normalize the attention scores to probabilities.
  198. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  199. # This is actually dropping out entire tokens to attend to, which might
  200. # seem a bit unusual, but is taken from the original Transformer paper.
  201. attention_probs = self.dropout(attention_probs)
  202. context_layer = torch.matmul(attention_probs, value_layer)
  203. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  204. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  205. context_layer = context_layer.view(new_context_layer_shape)
  206. return context_layer, attention_probs
  207. # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput
  208. class AltRobertaSelfOutput(nn.Module):
  209. def __init__(self, config):
  210. super().__init__()
  211. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  212. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  213. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  214. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  215. hidden_states = self.dense(hidden_states)
  216. hidden_states = self.dropout(hidden_states)
  217. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  218. return hidden_states
  219. ALT_ROBERTA_SELF_ATTENTION_CLASSES = {
  220. "eager": AltRobertaSelfAttention,
  221. }
  222. class AltRobertaAttention(nn.Module):
  223. def __init__(self, config):
  224. super().__init__()
  225. self.self = ALT_ROBERTA_SELF_ATTENTION_CLASSES[config._attn_implementation](config)
  226. self.output = AltRobertaSelfOutput(config)
  227. def forward(
  228. self,
  229. hidden_states: torch.Tensor,
  230. attention_mask: torch.FloatTensor | None = None,
  231. **kwargs: Unpack[TransformersKwargs],
  232. ) -> torch.Tensor:
  233. attention_output, _ = self.self(
  234. hidden_states,
  235. attention_mask=attention_mask,
  236. **kwargs,
  237. )
  238. attention_output = self.output(attention_output, hidden_states)
  239. return attention_output
  240. # Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate with Roberta->AltRoberta
  241. class AltRobertaIntermediate(nn.Module):
  242. def __init__(self, config):
  243. super().__init__()
  244. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  245. if isinstance(config.hidden_act, str):
  246. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  247. else:
  248. self.intermediate_act_fn = config.hidden_act
  249. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  250. hidden_states = self.dense(hidden_states)
  251. hidden_states = self.intermediate_act_fn(hidden_states)
  252. return hidden_states
  253. # Copied from transformers.models.roberta.modeling_roberta.RobertaOutput
  254. class AltRobertaOutput(nn.Module):
  255. def __init__(self, config):
  256. super().__init__()
  257. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  258. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  259. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  260. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  261. hidden_states = self.dense(hidden_states)
  262. hidden_states = self.dropout(hidden_states)
  263. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  264. return hidden_states
  265. # Copied from transformers.models.align.modeling_align.AlignTextLayer with AlignText->AltRoberta
  266. class AltRobertaLayer(GradientCheckpointingLayer):
  267. def __init__(self, config):
  268. super().__init__()
  269. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  270. self.seq_len_dim = 1
  271. self.attention = AltRobertaAttention(config)
  272. self.intermediate = AltRobertaIntermediate(config)
  273. self.output = AltRobertaOutput(config)
  274. def forward(
  275. self,
  276. hidden_states: torch.Tensor,
  277. attention_mask: torch.FloatTensor | None = None,
  278. **kwargs: Unpack[TransformersKwargs],
  279. ) -> torch.Tensor:
  280. hidden_states = self.attention(
  281. hidden_states,
  282. attention_mask=attention_mask,
  283. **kwargs,
  284. )
  285. hidden_states = apply_chunking_to_forward(
  286. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, hidden_states
  287. )
  288. return hidden_states
  289. def feed_forward_chunk(self, attention_output):
  290. intermediate_output = self.intermediate(attention_output)
  291. layer_output = self.output(intermediate_output, attention_output)
  292. return layer_output
  293. # Copied from transformers.models.align.modeling_align.AlignTextEncoder with AlignText->AltRoberta
  294. class AltRobertaEncoder(nn.Module):
  295. def __init__(self, config):
  296. super().__init__()
  297. self.config = config
  298. self.layer = nn.ModuleList([AltRobertaLayer(config) for i in range(config.num_hidden_layers)])
  299. self.gradient_checkpointing = False
  300. def forward(
  301. self,
  302. hidden_states: torch.Tensor,
  303. attention_mask: torch.FloatTensor | None = None,
  304. **kwargs: Unpack[TransformersKwargs],
  305. ) -> BaseModelOutput:
  306. for layer_module in self.layer:
  307. hidden_states = layer_module(
  308. hidden_states,
  309. attention_mask,
  310. **kwargs,
  311. )
  312. return BaseModelOutput(
  313. last_hidden_state=hidden_states,
  314. )
  315. # Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
  316. class AltRobertaPooler(nn.Module):
  317. def __init__(self, config):
  318. super().__init__()
  319. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  320. self.activation = nn.Tanh()
  321. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  322. # We "pool" the model by simply taking the hidden state corresponding
  323. # to the first token.
  324. first_token_tensor = hidden_states[:, 0]
  325. pooled_output = self.dense(first_token_tensor)
  326. pooled_output = self.activation(pooled_output)
  327. return pooled_output
  328. # Copied from transformers.models.siglip.modeling_siglip.eager_attention_forward
  329. def eager_attention_forward(
  330. module: nn.Module,
  331. query: torch.Tensor,
  332. key: torch.Tensor,
  333. value: torch.Tensor,
  334. attention_mask: torch.Tensor | None,
  335. scaling: float,
  336. dropout: float = 0.0,
  337. **kwargs,
  338. ):
  339. attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
  340. if attention_mask is not None:
  341. attn_weights = attn_weights + attention_mask
  342. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  343. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  344. attn_output = torch.matmul(attn_weights, value)
  345. attn_output = attn_output.transpose(1, 2).contiguous()
  346. return attn_output, attn_weights
  347. class AltCLIPAttention(nn.Module):
  348. """Multi-headed attention from 'Attention Is All You Need' paper"""
  349. def __init__(self, config):
  350. super().__init__()
  351. self.config = config
  352. self.embed_dim = config.hidden_size
  353. self.num_heads = config.num_attention_heads
  354. self.head_dim = self.embed_dim // self.num_heads
  355. if self.head_dim * self.num_heads != self.embed_dim:
  356. raise ValueError(
  357. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
  358. f" {self.num_heads})."
  359. )
  360. self.scale = self.head_dim**-0.5
  361. self.dropout = config.attention_dropout
  362. self.is_causal = False
  363. self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
  364. self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
  365. self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
  366. self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
  367. def forward(
  368. self,
  369. hidden_states: torch.Tensor,
  370. attention_mask: torch.Tensor | None = None,
  371. **kwargs: Unpack[TransformersKwargs],
  372. ) -> tuple[torch.Tensor, torch.Tensor | None]:
  373. """Input shape: Batch x Time x Channel"""
  374. input_shape = hidden_states.shape[:-1]
  375. hidden_shape = (*input_shape, -1, self.head_dim)
  376. queries = self.q_proj(hidden_states)
  377. keys = self.k_proj(hidden_states)
  378. values = self.v_proj(hidden_states)
  379. queries = queries.view(hidden_shape).transpose(1, 2)
  380. keys = keys.view(hidden_shape).transpose(1, 2)
  381. values = values.view(hidden_shape).transpose(1, 2)
  382. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  383. self.config._attn_implementation, eager_attention_forward
  384. )
  385. attn_output, attn_weights = attention_interface(
  386. self,
  387. queries,
  388. keys,
  389. values,
  390. attention_mask,
  391. scaling=self.scale,
  392. dropout=0.0 if not self.training else self.dropout,
  393. **kwargs,
  394. )
  395. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  396. attn_output = self.out_proj(attn_output)
  397. return attn_output, attn_weights
  398. # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->AltCLIP
  399. class AltCLIPMLP(nn.Module):
  400. def __init__(self, config):
  401. super().__init__()
  402. self.config = config
  403. self.activation_fn = ACT2FN[config.hidden_act]
  404. self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
  405. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
  406. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  407. hidden_states = self.fc1(hidden_states)
  408. hidden_states = self.activation_fn(hidden_states)
  409. hidden_states = self.fc2(hidden_states)
  410. return hidden_states
  411. class AltCLIPEncoderLayer(GradientCheckpointingLayer):
  412. def __init__(self, config: AltCLIPConfig):
  413. super().__init__()
  414. self.embed_dim = config.hidden_size
  415. self.self_attn = AltCLIPAttention(config)
  416. self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
  417. self.mlp = AltCLIPMLP(config)
  418. self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
  419. def forward(
  420. self,
  421. hidden_states: torch.Tensor,
  422. attention_mask: torch.Tensor,
  423. **kwargs: Unpack[TransformersKwargs],
  424. ) -> tuple[torch.FloatTensor, torch.Tensor | None]:
  425. residual = hidden_states
  426. hidden_states = self.layer_norm1(hidden_states)
  427. hidden_states, _ = self.self_attn(
  428. hidden_states=hidden_states,
  429. attention_mask=attention_mask,
  430. **kwargs,
  431. )
  432. hidden_states = residual + hidden_states
  433. residual = hidden_states
  434. hidden_states = self.layer_norm2(hidden_states)
  435. hidden_states = self.mlp(hidden_states)
  436. hidden_states = residual + hidden_states
  437. return hidden_states
  438. class AltCLIPEncoder(nn.Module):
  439. """
  440. Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
  441. [`AltCLIPEncoderLayer`].
  442. Args:
  443. config: AltCLIPConfig
  444. """
  445. def __init__(self, config: AltCLIPConfig):
  446. super().__init__()
  447. self.config = config
  448. self.layers = nn.ModuleList([AltCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
  449. self.gradient_checkpointing = False
  450. def forward(
  451. self,
  452. inputs_embeds,
  453. attention_mask: torch.Tensor | None = None,
  454. **kwargs: Unpack[TransformersKwargs],
  455. ) -> tuple | BaseModelOutput:
  456. r"""
  457. Args:
  458. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  459. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
  460. This is useful if you want more control over how to convert `input_ids` indices into associated vectors
  461. than the model's internal embedding lookup matrix.
  462. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  463. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  464. - 1 for tokens that are **not masked**,
  465. - 0 for tokens that are **masked**.
  466. [What are attention masks?](../glossary#attention-mask)
  467. """
  468. hidden_states = inputs_embeds
  469. for encoder_layer in self.layers:
  470. hidden_states = encoder_layer(
  471. hidden_states,
  472. attention_mask,
  473. **kwargs,
  474. )
  475. return BaseModelOutput(
  476. last_hidden_state=hidden_states,
  477. )
  478. # Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->AltCLIP
  479. class AltCLIPVisionEmbeddings(nn.Module):
  480. def __init__(self, config: AltCLIPVisionConfig):
  481. super().__init__()
  482. self.config = config
  483. self.embed_dim = config.hidden_size
  484. self.image_size = config.image_size
  485. self.patch_size = config.patch_size
  486. self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
  487. self.patch_embedding = nn.Conv2d(
  488. in_channels=config.num_channels,
  489. out_channels=self.embed_dim,
  490. kernel_size=self.patch_size,
  491. stride=self.patch_size,
  492. bias=False,
  493. )
  494. self.num_patches = (self.image_size // self.patch_size) ** 2
  495. self.num_positions = self.num_patches + 1
  496. self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
  497. self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
  498. def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
  499. """
  500. This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
  501. images. This method is also adapted to support torch.jit tracing.
  502. Adapted from:
  503. - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
  504. - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
  505. """
  506. num_patches = embeddings.shape[1] - 1
  507. position_embedding = self.position_embedding.weight.unsqueeze(0)
  508. num_positions = position_embedding.shape[1] - 1
  509. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  510. if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
  511. return self.position_embedding(self.position_ids)
  512. class_pos_embed = position_embedding[:, :1]
  513. patch_pos_embed = position_embedding[:, 1:]
  514. dim = embeddings.shape[-1]
  515. new_height = height // self.patch_size
  516. new_width = width // self.patch_size
  517. sqrt_num_positions = torch_int(num_positions**0.5)
  518. patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
  519. patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
  520. patch_pos_embed = nn.functional.interpolate(
  521. patch_pos_embed,
  522. size=(new_height, new_width),
  523. mode="bicubic",
  524. align_corners=False,
  525. )
  526. patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
  527. return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
  528. def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
  529. batch_size, _, height, width = pixel_values.shape
  530. if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
  531. raise ValueError(
  532. f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
  533. )
  534. target_dtype = self.patch_embedding.weight.dtype
  535. patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
  536. patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
  537. class_embeds = self.class_embedding.expand(batch_size, 1, -1)
  538. embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
  539. if interpolate_pos_encoding:
  540. embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
  541. else:
  542. embeddings = embeddings + self.position_embedding(self.position_ids)
  543. return embeddings
  544. @auto_docstring
  545. class AltCLIPPreTrainedModel(PreTrainedModel):
  546. config: AltCLIPConfig
  547. base_model_prefix = "altclip"
  548. input_modalities = ("image", "text")
  549. supports_gradient_checkpointing = True
  550. _no_split_module = []
  551. @torch.no_grad()
  552. def _init_weights(self, module):
  553. """Initialize the weights"""
  554. factor = self.config.initializer_factor
  555. if isinstance(module, AltCLIPVisionEmbeddings):
  556. factor = self.config.initializer_factor
  557. init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
  558. init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
  559. init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
  560. init.copy_(module.position_ids, torch.arange(module.num_positions).expand((1, -1)))
  561. elif isinstance(module, AltCLIPAttention):
  562. factor = self.config.initializer_factor
  563. in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
  564. out_proj_std = (module.embed_dim**-0.5) * factor
  565. init.normal_(module.q_proj.weight, std=in_proj_std)
  566. init.normal_(module.k_proj.weight, std=in_proj_std)
  567. init.normal_(module.v_proj.weight, std=in_proj_std)
  568. init.normal_(module.out_proj.weight, std=out_proj_std)
  569. elif isinstance(module, AltCLIPMLP):
  570. factor = self.config.initializer_factor
  571. in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
  572. fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
  573. init.normal_(module.fc1.weight, std=fc_std)
  574. init.normal_(module.fc2.weight, std=in_proj_std)
  575. elif isinstance(module, AltCLIPModel):
  576. init.normal_(
  577. module.text_projection.weight,
  578. std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
  579. )
  580. init.normal_(
  581. module.visual_projection.weight,
  582. std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
  583. )
  584. elif isinstance(module, nn.LayerNorm):
  585. init.zeros_(module.bias)
  586. init.ones_(module.weight)
  587. elif isinstance(module, nn.Linear):
  588. init.normal_(module.weight, mean=0.0, std=self.config.initializer_factor)
  589. if module.bias is not None:
  590. init.zeros_(module.bias)
  591. elif isinstance(module, nn.Embedding):
  592. init.normal_(module.weight, mean=0.0, std=self.config.initializer_factor)
  593. # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
  594. if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
  595. init.zeros_(module.weight[module.padding_idx])
  596. elif isinstance(module, AltRobertaEmbeddings):
  597. init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
  598. init.zeros_(module.token_type_ids)
  599. class AltCLIPVisionTransformer(nn.Module):
  600. def __init__(self, config: AltCLIPVisionConfig):
  601. super().__init__()
  602. self.config = config
  603. embed_dim = config.hidden_size
  604. self.embeddings = AltCLIPVisionEmbeddings(config)
  605. self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
  606. self.encoder = AltCLIPEncoder(config)
  607. self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
  608. @auto_docstring
  609. def forward(
  610. self,
  611. pixel_values: torch.FloatTensor | None = None,
  612. interpolate_pos_encoding: bool | None = False,
  613. **kwargs: Unpack[TransformersKwargs],
  614. ) -> tuple | BaseModelOutputWithPooling:
  615. if pixel_values is None:
  616. raise ValueError("You have to specify pixel_values")
  617. hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
  618. hidden_states = self.pre_layrnorm(hidden_states)
  619. encoder_outputs = self.encoder(
  620. inputs_embeds=hidden_states,
  621. **kwargs,
  622. )
  623. last_hidden_state = encoder_outputs[0]
  624. pooled_output = last_hidden_state[:, 0, :]
  625. pooled_output = self.post_layernorm(pooled_output)
  626. return BaseModelOutputWithPooling(
  627. last_hidden_state=last_hidden_state,
  628. pooler_output=pooled_output,
  629. )
  630. class AltCLIPVisionModel(AltCLIPPreTrainedModel):
  631. config: AltCLIPVisionConfig
  632. main_input_name = "pixel_values"
  633. input_modalities = ("image",)
  634. _can_record_outputs = {
  635. "hidden_states": AltCLIPEncoderLayer,
  636. "attentions": AltCLIPAttention,
  637. }
  638. def __init__(self, config: AltCLIPVisionConfig):
  639. super().__init__(config)
  640. self.vision_model = AltCLIPVisionTransformer(config)
  641. # Initialize weights and apply final processing
  642. self.post_init()
  643. def get_input_embeddings(self) -> nn.Module:
  644. return self.vision_model.embeddings.patch_embedding
  645. @merge_with_config_defaults
  646. @capture_outputs(tie_last_hidden_states=False)
  647. @auto_docstring
  648. def forward(
  649. self,
  650. pixel_values: torch.FloatTensor | None = None,
  651. interpolate_pos_encoding: bool = False,
  652. **kwargs: Unpack[TransformersKwargs],
  653. ) -> BaseModelOutputWithPooling:
  654. r"""
  655. Examples:
  656. ```python
  657. >>> from PIL import Image
  658. >>> import httpx
  659. >>> from io import BytesIO
  660. >>> from transformers import AutoProcessor, AltCLIPVisionModel
  661. >>> model = AltCLIPVisionModel.from_pretrained("BAAI/AltCLIP")
  662. >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
  663. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  664. >>> with httpx.stream("GET", url) as response:
  665. ... image = Image.open(BytesIO(response.read()))
  666. >>> inputs = processor(images=image, return_tensors="pt")
  667. >>> outputs = model(**inputs)
  668. >>> last_hidden_state = outputs.last_hidden_state
  669. >>> pooled_output = outputs.pooler_output # pooled CLS states
  670. ```"""
  671. return self.vision_model(
  672. pixel_values=pixel_values,
  673. interpolate_pos_encoding=interpolate_pos_encoding,
  674. **kwargs,
  675. )
  676. @auto_docstring(
  677. custom_intro="""
  678. The model behaves as an encoder following the architecture described in *Attention is
  679. all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
  680. Kaiser and Illia Polosukhin.
  681. .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
  682. """
  683. )
  684. class AltRobertaModel(AltCLIPPreTrainedModel):
  685. config: AltCLIPTextConfig
  686. _can_record_outputs = {
  687. "hidden_states": AltRobertaLayer,
  688. "attentions": AltRobertaSelfAttention,
  689. }
  690. # Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->AltRoberta
  691. def __init__(self, config, add_pooling_layer=True):
  692. r"""
  693. add_pooling_layer (bool, *optional*, defaults to `True`):
  694. Whether to add a pooling layer
  695. """
  696. super().__init__(config)
  697. self.config = config
  698. self.embeddings = AltRobertaEmbeddings(config)
  699. self.encoder = AltRobertaEncoder(config)
  700. self.pooler = AltRobertaPooler(config) if add_pooling_layer else None
  701. # Initialize weights and apply final processing
  702. self.post_init()
  703. def get_input_embeddings(self):
  704. return self.embeddings.word_embeddings
  705. def set_input_embeddings(self, value):
  706. self.embeddings.word_embeddings = value
  707. @merge_with_config_defaults
  708. @capture_outputs
  709. @auto_docstring
  710. # Copied from transformers.models.clap.modeling_clap.ClapTextModel.forward
  711. def forward(
  712. self,
  713. input_ids: torch.Tensor | None = None,
  714. attention_mask: torch.Tensor | None = None,
  715. token_type_ids: torch.Tensor | None = None,
  716. position_ids: torch.Tensor | None = None,
  717. inputs_embeds: torch.Tensor | None = None,
  718. **kwargs: Unpack[TransformersKwargs],
  719. ) -> BaseModelOutputWithPooling:
  720. if input_ids is not None and inputs_embeds is not None:
  721. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  722. elif input_ids is not None:
  723. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  724. input_shape = input_ids.size()
  725. elif inputs_embeds is not None:
  726. input_shape = inputs_embeds.size()[:-1]
  727. else:
  728. raise ValueError("You have to specify either input_ids or inputs_embeds")
  729. batch_size, seq_length = input_shape
  730. device = input_ids.device if input_ids is not None else inputs_embeds.device
  731. if attention_mask is None:
  732. attention_mask = torch.ones(((batch_size, seq_length)), device=device)
  733. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  734. # ourselves in which case we just need to make it broadcastable to all heads.
  735. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
  736. embedding_output = self.embeddings(
  737. input_ids=input_ids,
  738. position_ids=position_ids,
  739. token_type_ids=token_type_ids,
  740. inputs_embeds=inputs_embeds,
  741. )
  742. encoder_outputs = self.encoder(
  743. embedding_output,
  744. attention_mask=extended_attention_mask,
  745. **kwargs,
  746. )
  747. sequence_output = encoder_outputs[0]
  748. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  749. return BaseModelOutputWithPooling(
  750. last_hidden_state=sequence_output,
  751. pooler_output=pooled_output,
  752. )
  753. class AltCLIPTextModel(AltCLIPPreTrainedModel):
  754. config: AltCLIPTextConfig
  755. input_modalities = ("text",)
  756. def __init__(self, config):
  757. super().__init__(config)
  758. self.roberta = AltRobertaModel(config, add_pooling_layer=False)
  759. self.transformation = nn.Linear(config.hidden_size, config.project_dim)
  760. self.pre_LN = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  761. self.post_init()
  762. def get_input_embeddings(self) -> nn.Module:
  763. return self.roberta.embeddings.word_embeddings
  764. def set_input_embeddings(self, value: nn.Embedding) -> None:
  765. self.roberta.embeddings.word_embeddings = value
  766. def resize_token_embeddings(self, new_num_tokens: int | None = None) -> nn.Embedding:
  767. return super().resize_token_embeddings(new_num_tokens)
  768. @can_return_tuple
  769. @auto_docstring
  770. def forward(
  771. self,
  772. input_ids: torch.Tensor | None = None,
  773. attention_mask: torch.Tensor | None = None,
  774. token_type_ids: torch.Tensor | None = None,
  775. position_ids: torch.Tensor | None = None,
  776. inputs_embeds: torch.Tensor | None = None,
  777. **kwargs: Unpack[TransformersKwargs],
  778. ) -> tuple | BaseModelOutputWithPoolingAndProjection:
  779. r"""
  780. Examples:
  781. ```python
  782. >>> from transformers import AutoProcessor, AltCLIPTextModel
  783. >>> model = AltCLIPTextModel.from_pretrained("BAAI/AltCLIP")
  784. >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
  785. >>> texts = ["it's a cat", "it's a dog"]
  786. >>> inputs = processor(text=texts, padding=True, return_tensors="pt")
  787. >>> outputs = model(**inputs)
  788. >>> last_hidden_state = outputs.last_hidden_state
  789. >>> pooled_output = outputs.pooler_output # pooled CLS states
  790. ```"""
  791. outputs = self.roberta(
  792. input_ids=input_ids,
  793. attention_mask=attention_mask,
  794. token_type_ids=token_type_ids,
  795. position_ids=position_ids,
  796. inputs_embeds=inputs_embeds,
  797. **kwargs,
  798. )
  799. # last module outputs
  800. sequence_output = outputs[0]
  801. # project every module
  802. sequence_output = self.pre_LN(sequence_output)
  803. # pooler
  804. projection_state = self.transformation(sequence_output)
  805. pooler_output = projection_state[:, 0]
  806. return BaseModelOutputWithPoolingAndProjection(
  807. last_hidden_state=projection_state,
  808. pooler_output=pooler_output,
  809. hidden_states=outputs.hidden_states,
  810. attentions=outputs.attentions,
  811. )
  812. class AltCLIPModel(AltCLIPPreTrainedModel):
  813. config: AltCLIPConfig
  814. _can_record_outputs = {
  815. "hidden_states": AltCLIPEncoderLayer,
  816. "attentions": AltCLIPAttention,
  817. }
  818. def __init__(self, config: AltCLIPConfig):
  819. super().__init__(config)
  820. if not isinstance(config.vision_config, AltCLIPVisionConfig):
  821. raise TypeError(
  822. "config.vision_config is expected to be of type AltCLIPVisionConfig but is of type"
  823. f" {type(config.vision_config)}."
  824. )
  825. if not isinstance(config.text_config, AltCLIPTextConfig):
  826. raise TypeError(
  827. "config.text_config is expected to be of type AltCLIPTextConfig but is of type"
  828. f" {type(config.text_config)}."
  829. )
  830. text_config = config.text_config
  831. vision_config = config.vision_config
  832. # The module using it is not a PreTrainedModel subclass so we need this
  833. vision_config._attn_implementation = config._attn_implementation
  834. self.projection_dim = config.projection_dim
  835. self.text_embed_dim = text_config.project_dim
  836. self.vision_embed_dim = vision_config.hidden_size
  837. self.text_model = AltCLIPTextModel(text_config)
  838. self.vision_model = AltCLIPVisionTransformer(vision_config)
  839. self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
  840. self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
  841. self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
  842. # Initialize weights and apply final processing
  843. self.post_init()
  844. @can_return_tuple
  845. @auto_docstring
  846. def get_text_features(
  847. self,
  848. input_ids: torch.Tensor,
  849. attention_mask: torch.Tensor | None = None,
  850. position_ids: torch.Tensor | None = None,
  851. token_type_ids: torch.Tensor | None = None,
  852. **kwargs: Unpack[TransformersKwargs],
  853. ) -> tuple | BaseModelOutputWithPooling:
  854. r"""
  855. Examples:
  856. ```python
  857. >>> import torch
  858. >>> from transformers import AutoProcessor, AltCLIPModel
  859. >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
  860. >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
  861. >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
  862. >>> with torch.inference_mode():
  863. ... text_features = model.get_text_features(**inputs)
  864. ```"""
  865. text_outputs: BaseModelOutputWithPoolingAndProjection = self.text_model(
  866. input_ids=input_ids,
  867. attention_mask=attention_mask,
  868. position_ids=position_ids,
  869. token_type_ids=token_type_ids,
  870. **kwargs,
  871. )
  872. pooled_output = text_outputs.pooler_output
  873. text_outputs.pooler_output = self.text_projection(pooled_output)
  874. return text_outputs
  875. @merge_with_config_defaults
  876. @capture_outputs(tie_last_hidden_states=False)
  877. @auto_docstring
  878. def get_image_features(
  879. self,
  880. pixel_values: torch.FloatTensor,
  881. interpolate_pos_encoding: bool = False,
  882. **kwargs: Unpack[TransformersKwargs],
  883. ) -> tuple | BaseModelOutputWithPooling:
  884. r"""
  885. Examples:
  886. ```python
  887. >>> import torch
  888. >>> from transformers import AutoProcessor, AltCLIPModel
  889. >>> from transformers.image_utils import load_image
  890. >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
  891. >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
  892. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  893. >>> image = load_image(url)
  894. >>> inputs = processor(images=image, return_tensors="pt")
  895. >>> with torch.inference_mode():
  896. ... image_features = model.get_image_features(**inputs)
  897. ```"""
  898. vision_outputs = self.vision_model(
  899. pixel_values=pixel_values,
  900. interpolate_pos_encoding=interpolate_pos_encoding,
  901. **kwargs,
  902. )
  903. pooled_output = vision_outputs.pooler_output
  904. vision_outputs.pooler_output = self.visual_projection(pooled_output)
  905. return vision_outputs
  906. @can_return_tuple
  907. @auto_docstring
  908. def forward(
  909. self,
  910. input_ids: torch.LongTensor | None = None,
  911. pixel_values: torch.FloatTensor | None = None,
  912. attention_mask: torch.Tensor | None = None,
  913. position_ids: torch.LongTensor | None = None,
  914. token_type_ids: torch.Tensor | None = None,
  915. return_loss: bool | None = None,
  916. interpolate_pos_encoding: bool = False,
  917. **kwargs: Unpack[TransformersKwargs],
  918. ) -> tuple | AltCLIPOutput:
  919. r"""
  920. return_loss (`bool`, *optional*):
  921. Whether or not to return the contrastive loss.
  922. Examples:
  923. ```python
  924. >>> from PIL import Image
  925. >>> import httpx
  926. >>> from io import BytesIO
  927. >>> from transformers import AutoProcessor, AltCLIPModel
  928. >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
  929. >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
  930. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  931. >>> with httpx.stream("GET", url) as response:
  932. ... image = Image.open(BytesIO(response.read()))
  933. >>> inputs = processor(
  934. ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
  935. ... )
  936. >>> outputs = model(**inputs)
  937. >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
  938. >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
  939. ```"""
  940. text_outputs = self.text_model(
  941. input_ids=input_ids,
  942. attention_mask=attention_mask,
  943. token_type_ids=token_type_ids,
  944. position_ids=position_ids,
  945. **kwargs,
  946. )
  947. vision_outputs = self.vision_model(
  948. pixel_values=pixel_values,
  949. interpolate_pos_encoding=interpolate_pos_encoding,
  950. **kwargs,
  951. )
  952. image_embeds = vision_outputs[1]
  953. image_embeds = self.visual_projection(image_embeds)
  954. text_embeds = text_outputs[1]
  955. text_embeds = self.text_projection(text_embeds)
  956. # normalized features
  957. image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
  958. text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
  959. # cosine similarity as logits
  960. logit_scale = self.logit_scale.exp()
  961. logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
  962. logits_per_image = logits_per_text.T
  963. loss = None
  964. if return_loss:
  965. loss = clip_loss(logits_per_text)
  966. return AltCLIPOutput(
  967. loss=loss,
  968. logits_per_image=logits_per_image,
  969. logits_per_text=logits_per_text,
  970. text_embeds=text_embeds,
  971. image_embeds=image_embeds,
  972. text_model_output=text_outputs,
  973. vision_model_output=vision_outputs,
  974. )
  975. __all__ = ["AltCLIPPreTrainedModel", "AltCLIPVisionModel", "AltCLIPTextModel", "AltCLIPModel"]