modeling_idefics.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  1. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  2. #
  3. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  4. # and OPT implementations in this library. It has been modified from its
  5. # original forms to accommodate minor architectural differences compared
  6. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. """PyTorch Idefics model."""
  20. from collections.abc import Callable
  21. from dataclasses import dataclass
  22. from typing import Any
  23. import torch
  24. import torch.nn.functional as F
  25. from torch import nn
  26. from ... import initialization as init
  27. from ...activations import ACT2FN
  28. from ...cache_utils import Cache, DynamicCache
  29. from ...generation import GenerationMixin
  30. from ...masking_utils import create_causal_mask
  31. from ...modeling_layers import GradientCheckpointingLayer
  32. from ...modeling_outputs import ModelOutput
  33. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedConfig, PreTrainedModel
  34. from ...processing_utils import Unpack
  35. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
  36. from ...utils.generic import merge_with_config_defaults
  37. from ...utils.output_capturing import OutputRecorder, capture_outputs
  38. from .configuration_idefics import IdeficsConfig
  39. from .perceiver import IdeficsPerceiverResampler
  40. from .vision import IdeficsVisionEmbeddings, IdeficsVisionTransformer
  41. logger = logging.get_logger(__name__)
  42. @dataclass
  43. @auto_docstring(
  44. custom_intro="""
  45. Base class for Idefics model's outputs that may also contain a past key/values (to speed up sequential decoding).
  46. """
  47. )
  48. class IdeficsBaseModelOutputWithPast(ModelOutput):
  49. r"""
  50. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  51. Sequence of hidden-states at the output of the last layer of the model.
  52. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  53. hidden_size)` is output.
  54. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  55. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  56. Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  57. `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
  58. input) to speed up sequential decoding.
  59. image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  60. Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
  61. sequence_length, hidden_size)`.
  62. image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
  63. """
  64. last_hidden_state: torch.FloatTensor | None = None
  65. past_key_values: Cache | None = None
  66. hidden_states: tuple[torch.FloatTensor] | None = None
  67. attentions: tuple[torch.FloatTensor] | None = None
  68. image_hidden_states: tuple[torch.FloatTensor] | None = None
  69. @dataclass
  70. @auto_docstring(
  71. custom_intro="""
  72. Base class for Idefics causal language model (or autoregressive) outputs.
  73. """
  74. )
  75. class IdeficsCausalLMOutputWithPast(ModelOutput):
  76. r"""
  77. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  78. Language modeling loss (for next-token prediction).
  79. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
  80. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  81. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  82. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  83. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  84. `past_key_values` input) to speed up sequential decoding.
  85. image_hidden_states (`tuple(torch.FloatTensor)`, *optional*):
  86. Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_images,
  87. sequence_length, hidden_size)`.
  88. image_hidden_states of the model produced by the vision encoder, and optionally by the perceiver
  89. """
  90. loss: torch.FloatTensor | None = None
  91. logits: torch.FloatTensor | None = None
  92. past_key_values: Cache | None = None
  93. hidden_states: tuple[torch.FloatTensor] | None = None
  94. attentions: tuple[torch.FloatTensor] | None = None
  95. image_hidden_states: tuple[torch.FloatTensor] | None = None
  96. def expand_inputs_for_generation(
  97. input_ids,
  98. expand_size=1,
  99. is_encoder_decoder=False,
  100. attention_mask=None,
  101. encoder_outputs=None,
  102. **model_kwargs,
  103. ):
  104. expanded_return_idx = (
  105. torch.arange(input_ids.shape[0]).view(-1, 1).repeat(1, expand_size).view(-1).to(input_ids.device)
  106. )
  107. input_ids = input_ids.index_select(0, expanded_return_idx)
  108. model_kwargs["pixel_values"] = model_kwargs.get("pixel_values")
  109. model_kwargs["image_encoder_embeddings"] = model_kwargs.get("image_encoder_embeddings")
  110. model_kwargs["perceiver_embeddings"] = model_kwargs.get("perceiver_embeddings")
  111. model_kwargs["image_attention_mask"] = model_kwargs.get("image_attention_mask")
  112. if "token_type_ids" in model_kwargs:
  113. token_type_ids = model_kwargs["token_type_ids"]
  114. model_kwargs["token_type_ids"] = token_type_ids.index_select(0, expanded_return_idx)
  115. if attention_mask is not None:
  116. model_kwargs["attention_mask"] = attention_mask.index_select(0, expanded_return_idx)
  117. if model_kwargs["image_attention_mask"] is not None:
  118. model_kwargs["image_attention_mask"] = model_kwargs["image_attention_mask"].index_select(
  119. 0, expanded_return_idx
  120. )
  121. if model_kwargs["pixel_values"] is not None:
  122. model_kwargs["pixel_values"] = model_kwargs["pixel_values"].index_select(0, expanded_return_idx)
  123. elif model_kwargs["image_encoder_embeddings"] is not None:
  124. model_kwargs["image_encoder_embeddings"] = model_kwargs["image_encoder_embeddings"].index_select(
  125. 0, expanded_return_idx
  126. )
  127. elif model_kwargs["perceiver_embeddings"] is not None:
  128. model_kwargs["perceiver_embeddings"] = model_kwargs["perceiver_embeddings"].index_select(
  129. 0, expanded_return_idx
  130. )
  131. return input_ids, model_kwargs
  132. def freeze_model(model, module_exceptions=()):
  133. mapping = {
  134. "LayerNorm": nn.LayerNorm,
  135. "Linear": nn.Linear,
  136. "Embedding": nn.Embedding,
  137. }
  138. module_exceptions_mapped = [mapping[m] for m in module_exceptions]
  139. for module in model.modules():
  140. if module_exceptions and any(isinstance(module, t) for t in module_exceptions_mapped):
  141. module.requires_grad_(True) # Explicitly setting it to true to avoid any mistakes
  142. else:
  143. module.requires_grad_(False)
  144. return model
  145. class IdeficsDecoupledEmbedding(nn.Embedding):
  146. # Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/sparse.html#Embedding
  147. """
  148. Implements a decoupling of parameters to allow freezing (or not) a subset of the embeddings. In practise, the
  149. regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `num_additional_embeddings` > 0,
  150. then it will create `num_additional_embeddings` additional parameters that are always trained. If
  151. `num_additional_embeddings=0`, then the module defaults back to the regular behavior of `nn.Embedding`.
  152. """
  153. def __init__(
  154. self,
  155. num_embeddings,
  156. num_additional_embeddings,
  157. embedding_dim,
  158. partially_freeze: bool | None = False,
  159. device=None,
  160. dtype=None,
  161. padding_idx=None,
  162. **kwargs,
  163. ) -> None:
  164. """
  165. Args:
  166. num_embeddings (`int`):
  167. Size of the dictionary of embeddings
  168. num_additional_embeddings (`int`):
  169. Number of additional embeddings. Only useful when you `partially_freeze=True`.
  170. embedding_dim (`int`):
  171. The size of each embedding vector
  172. partially_freeze: (`bool`, *optional*, defaults to `False`):
  173. If `True`, the regular `weight` will be frozen. `additional_weight` is never frozen.
  174. padding_idx (`int`, *optional*):
  175. The padding index (needs to be less than num_embeddings)
  176. Note: there are a lot of other parameters to initialize a standard `nn.Embedding` such as `padding_idx`,
  177. `max_norm` or `norm_type`. We are not supporting these.
  178. """
  179. if padding_idx is not None and padding_idx > num_embeddings:
  180. raise ValueError(f"padding_idx must be within num_embeddings. Got {padding_idx} and {num_embeddings}")
  181. super().__init__(
  182. num_embeddings=num_embeddings,
  183. embedding_dim=embedding_dim,
  184. device=device,
  185. dtype=dtype,
  186. padding_idx=padding_idx,
  187. **kwargs,
  188. )
  189. self.num_embeddings = num_embeddings
  190. self.padding_idx = padding_idx
  191. self.num_additional_embeddings = num_additional_embeddings
  192. self.partially_freeze = partially_freeze
  193. if partially_freeze:
  194. self.weight.requires_grad_(False)
  195. if self.num_additional_embeddings > 0:
  196. self.additional_embedding = nn.Embedding(
  197. num_embeddings=self.num_additional_embeddings,
  198. embedding_dim=embedding_dim,
  199. device=device,
  200. dtype=dtype,
  201. )
  202. def forward(self, input_ids):
  203. """
  204. we have 2 embeddings, with different indices - one pretrained self.weight and another
  205. self.additional_embedding.weight that is being trained.
  206. in order to make a lookup of the input ids, we:
  207. 1. find out the indices of the entries belonging to the 2nd embedding
  208. 2. extract those values while subtracting the size of the first embedding (num_embeddings), since the 2nd
  209. embedding starts from 0 and not num_embeddings
  210. 3. perform the 2nd embedding lookup
  211. 4. now we handle the 1st embedding, we overwrite indices belonging to the 2nd embedding with a padding index
  212. 5. perform the 1st embedding lookup
  213. 6. now we overwrite the values in the 1st embedding lookup with the values of the 2nd embedding lookup
  214. note: for the 1st embedding lookup we could have looked up only the low indices and not do the padding, but
  215. then we have to create a new tensor and populate it with 2 tensors that are spread out across various indices -
  216. i.e. not a simple concat - I haven't benchmarked the complex case if it's any faster, given that seqlens are
  217. usually relatively short it's probably not faster or if faster not by much - but might be a good idea to
  218. measure.
  219. """
  220. if self.num_additional_embeddings == 0:
  221. return F.embedding(input_ids, self.weight)
  222. # Clone so that we don't modify the original input_ids later on
  223. input_ids = input_ids.clone()
  224. additional_vocab_indices = torch.where(input_ids >= self.num_embeddings)
  225. input_ids_additional_vocab = input_ids[additional_vocab_indices]
  226. additional_embeddings = self.additional_embedding(input_ids_additional_vocab - self.num_embeddings)
  227. # for successful lookup replace input_ids with 0, the results of these will be discarded anyway
  228. input_ids[additional_vocab_indices] = 0
  229. full_vector = F.embedding(input_ids, self.weight)
  230. # overwrite the records with high indices
  231. full_vector[additional_vocab_indices] = additional_embeddings
  232. return full_vector
  233. def extra_repr(self) -> str:
  234. return f"num_embeddings={self.num_embeddings}, num_additional_embeddings={self.num_additional_embeddings}, embedding_dim={self.embedding_dim}, partially_freeze={self.partially_freeze}"
  235. class IdeficsDecoupledLinear(nn.Linear):
  236. # Derived from https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear
  237. """
  238. Implements a decoupling of parameters to allow freezing (or not) a subset of the parameters. In practise, the
  239. regular `weight` can be trained or frozen (i.e. `partially_freeze=True`), and if `out_additional_features` > 0,
  240. then it will create `out_additional_features * in_features` additional parameters that are always trained. If
  241. `out_additional_features=0`, then the module defaults back to the regular behavior of `nn.Linear`.
  242. """
  243. def __init__(
  244. self,
  245. in_features: int,
  246. out_features: int,
  247. out_additional_features: int = 0,
  248. bias: bool = True,
  249. partially_freeze: bool = True,
  250. device=None,
  251. dtype=None,
  252. ) -> None:
  253. """
  254. out_additional_features: int. Number of additional trainable dimensions. Only makes sense when
  255. `partially_freeze=True`. partially_freeze: bool. If True, the regular `weight` will be frozen and extra
  256. parameters (if any) will be trainable. If False, default to the regular behavior of nn.Linear.
  257. """
  258. super().__init__(in_features, out_features, bias, device, dtype)
  259. self.out_additional_features = out_additional_features
  260. self.partially_freeze = partially_freeze
  261. self.in_features = in_features
  262. self.out_features = out_features
  263. if partially_freeze:
  264. self.weight.requires_grad_(False)
  265. if bias:
  266. self.bias.requires_grad_(False)
  267. if out_additional_features > 0:
  268. self.additional_fc = nn.Linear(
  269. in_features=in_features,
  270. out_features=out_additional_features,
  271. bias=bias,
  272. device=device,
  273. dtype=dtype,
  274. )
  275. def forward(self, input: torch.Tensor) -> torch.Tensor:
  276. output = F.linear(input, self.weight, self.bias)
  277. if self.out_additional_features > 0:
  278. additional_features = self.additional_fc(input)
  279. output = torch.cat((output, additional_features), -1)
  280. return output
  281. def extra_repr(self) -> str:
  282. """Overwriting `nn.Linear.extra_repr` to include new parameters."""
  283. return f"in_features={self.in_features}, out_features={self.out_features}, out_additional_features={self.out_additional_features}, bias={self.bias is not None}, partially_freeze={self.partially_freeze}"
  284. # this was adapted from LlamaRMSNorm
  285. class IdeficsRMSNorm(nn.Module):
  286. def __init__(self, hidden_size, eps=1e-6):
  287. """
  288. IdeficsRMSNorm is equivalent to T5LayerNorm
  289. """
  290. super().__init__()
  291. self.weight = nn.Parameter(torch.ones(hidden_size))
  292. self.variance_epsilon = eps
  293. def forward(self, hidden_states):
  294. variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
  295. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  296. # convert into half-precision if necessary
  297. if self.weight.dtype in [torch.float16, torch.bfloat16]:
  298. hidden_states = hidden_states.to(self.weight.dtype)
  299. return self.weight * hidden_states
  300. def extra_repr(self):
  301. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  302. # this was adapted from LlamaRotaryEmbedding
  303. class IdeficsEmbedding(torch.nn.Module):
  304. def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
  305. super().__init__()
  306. self.dim = dim
  307. self.max_position_embeddings = max_position_embeddings
  308. self.base = base
  309. inv_freq = 1.0 / (
  310. self.base
  311. ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / self.dim)
  312. )
  313. self.register_buffer("inv_freq", inv_freq, persistent=False)
  314. # Build here to make `torch.jit.trace` work.
  315. self._set_cos_sin_cache(
  316. seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
  317. )
  318. def _set_cos_sin_cache(self, seq_len, device, dtype):
  319. self.max_seq_len_cached = seq_len
  320. t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
  321. freqs = torch.einsum("i,j->ij", t, self.inv_freq)
  322. # Different from paper, but it uses a different permutation in order to obtain the same calculation
  323. emb = torch.cat((freqs, freqs), dim=-1)
  324. self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
  325. self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
  326. def forward(self, x, seq_len=None):
  327. # x: [bs, num_attention_heads, seq_len, head_size]
  328. if seq_len > self.max_seq_len_cached:
  329. self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
  330. return (
  331. self.cos_cached[:seq_len].to(dtype=x.dtype),
  332. self.sin_cached[:seq_len].to(dtype=x.dtype),
  333. )
  334. def rotate_half(x):
  335. """Rotates half the hidden dims of the input."""
  336. x1 = x[..., : x.shape[-1] // 2]
  337. x2 = x[..., x.shape[-1] // 2 :]
  338. return torch.cat((-x2, x1), dim=-1)
  339. def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
  340. """Applies Rotary Position Embedding to the query and key tensors.
  341. Args:
  342. q (`torch.Tensor`): The query tensor.
  343. k (`torch.Tensor`): The key tensor.
  344. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  345. sin (`torch.Tensor`): The sine part of the rotary embedding.
  346. position_ids (`torch.Tensor`):
  347. The position indices of the tokens corresponding to the query and key tensors. For example, this can be
  348. used to pass offsetted position ids when working with a KV-cache.
  349. unsqueeze_dim (`int`, *optional*, defaults to 1):
  350. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  351. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  352. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  353. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  354. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  355. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  356. Returns:
  357. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  358. """
  359. cos = cos[position_ids].unsqueeze(unsqueeze_dim)
  360. sin = sin[position_ids].unsqueeze(unsqueeze_dim)
  361. q_embed = (q * cos) + (rotate_half(q) * sin)
  362. k_embed = (k * cos) + (rotate_half(k) * sin)
  363. return q_embed, k_embed
  364. # this was adapted from LlamaMLP
  365. class IdeficsMLP(nn.Module):
  366. def __init__(
  367. self,
  368. hidden_size: int,
  369. intermediate_size: int,
  370. hidden_act: str,
  371. ):
  372. super().__init__()
  373. self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
  374. self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
  375. self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
  376. self.act_fn = ACT2FN[hidden_act]
  377. def forward(self, x):
  378. return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  379. # Copied from transformers.models.siglip.modeling_siglip.eager_attention_forward
  380. def eager_attention_forward(
  381. module: nn.Module,
  382. query: torch.Tensor,
  383. key: torch.Tensor,
  384. value: torch.Tensor,
  385. attention_mask: torch.Tensor | None,
  386. scaling: float,
  387. dropout: float = 0.0,
  388. **kwargs,
  389. ):
  390. attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
  391. if attention_mask is not None:
  392. attn_weights = attn_weights + attention_mask
  393. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  394. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  395. attn_output = torch.matmul(attn_weights, value)
  396. attn_output = attn_output.transpose(1, 2).contiguous()
  397. return attn_output, attn_weights
  398. # this was adapted from LlamaAttention
  399. class IdeficsAttention(nn.Module):
  400. """Multi-headed attention from 'Attention Is All You Need' paper"""
  401. def __init__(
  402. self,
  403. hidden_size: int,
  404. num_heads: int,
  405. dropout: float = 0.0,
  406. is_cross_attention: bool = False,
  407. config: PreTrainedConfig | None = None,
  408. qk_layer_norms: bool = False,
  409. layer_idx: int | None = None,
  410. ):
  411. super().__init__()
  412. self.config = config
  413. self.hidden_size = hidden_size
  414. self.num_heads = num_heads
  415. self.head_dim = hidden_size // num_heads
  416. self.dropout = dropout
  417. self.is_causal = True
  418. self.scaling = self.head_dim**-0.5
  419. self.layer_idx = layer_idx
  420. if layer_idx is None:
  421. logger.warning_once(
  422. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  423. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  424. "when creating this class."
  425. )
  426. if (self.head_dim * num_heads) != self.hidden_size:
  427. raise ValueError(
  428. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  429. f" and `num_heads`: {num_heads})."
  430. )
  431. self.is_cross_attention = is_cross_attention
  432. if not hasattr(nn.functional, "scaled_dot_product_attention"):
  433. raise ValueError("this model requires pytorch 2.0 or higher")
  434. if self.is_cross_attention:
  435. kv_input_dim = (
  436. self.hidden_size if not hasattr(config.vision_config, "embed_dim") else config.vision_config.embed_dim
  437. )
  438. self.q_proj = nn.Linear(
  439. self.hidden_size,
  440. num_heads * self.head_dim,
  441. bias=False,
  442. )
  443. self.k_proj = nn.Linear(kv_input_dim, num_heads * self.head_dim, bias=False)
  444. self.v_proj = nn.Linear(
  445. kv_input_dim,
  446. num_heads * self.head_dim,
  447. bias=False,
  448. )
  449. else:
  450. self.q_proj = nn.Linear(
  451. self.hidden_size,
  452. num_heads * self.head_dim,
  453. bias=False,
  454. )
  455. self.k_proj = nn.Linear(
  456. self.hidden_size,
  457. num_heads * self.head_dim,
  458. bias=False,
  459. )
  460. self.v_proj = nn.Linear(
  461. self.hidden_size,
  462. num_heads * self.head_dim,
  463. bias=False,
  464. )
  465. self.o_proj = nn.Linear(
  466. num_heads * self.head_dim,
  467. hidden_size,
  468. bias=False,
  469. )
  470. self.rotary_emb = IdeficsEmbedding(self.head_dim)
  471. self.qk_layer_norms = qk_layer_norms
  472. if self.qk_layer_norms:
  473. self.q_layer_norm = IdeficsRMSNorm(self.head_dim, eps=config.rms_norm_eps)
  474. self.k_layer_norm = IdeficsRMSNorm(self.head_dim, eps=config.rms_norm_eps)
  475. def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
  476. return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
  477. def forward(
  478. self,
  479. hidden_states: torch.Tensor,
  480. key_value_states: torch.Tensor | None = None,
  481. attention_mask: torch.Tensor | None = None,
  482. position_ids: torch.LongTensor | None = None,
  483. past_key_values: Cache | None = None,
  484. **kwargs: Unpack[TransformersKwargs],
  485. ) -> tuple[torch.Tensor, torch.Tensor]:
  486. # if key_value_states are provided this layer is used as a cross-attention layer
  487. is_cross_attention = self.is_cross_attention or key_value_states is not None
  488. bsz, q_len, _ = hidden_states.size()
  489. query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  490. if not is_cross_attention:
  491. key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  492. value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  493. else:
  494. _, kv_len, _ = key_value_states.size() # Note that, in this case, `kv_len` == `kv_seq_len`
  495. key_states = self.k_proj(key_value_states).view(bsz, kv_len, self.num_heads, self.head_dim).transpose(1, 2)
  496. value_states = (
  497. self.v_proj(key_value_states).view(bsz, kv_len, self.num_heads, self.head_dim).transpose(1, 2)
  498. )
  499. kv_seq_len = key_states.shape[-2]
  500. if past_key_values is not None:
  501. kv_seq_len += past_key_values.get_seq_length()
  502. if not is_cross_attention:
  503. cos, sin = self.rotary_emb(value_states, seq_len=max(kv_seq_len, q_len))
  504. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
  505. # [bsz, nh, t, hd]
  506. if past_key_values is not None:
  507. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
  508. if self.qk_layer_norms:
  509. query_states = self.q_layer_norm(query_states)
  510. key_states = self.k_layer_norm(key_states)
  511. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  512. self.config._attn_implementation, eager_attention_forward
  513. )
  514. attn_output, attn_weights = attention_interface(
  515. self,
  516. query_states,
  517. key_states,
  518. value_states,
  519. attention_mask,
  520. dropout=0.0 if not self.training else self.dropout,
  521. scaling=self.scaling,
  522. **kwargs,
  523. )
  524. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  525. attn_output = self.o_proj(attn_output)
  526. return attn_output, attn_weights
  527. # this was adapted from LlamaDecoderLayer
  528. class IdeficsDecoderLayer(GradientCheckpointingLayer):
  529. def __init__(self, config: IdeficsConfig, layer_idx: int | None = None):
  530. super().__init__()
  531. self.hidden_size = config.hidden_size
  532. self.self_attn = IdeficsAttention(
  533. hidden_size=self.hidden_size,
  534. num_heads=config.num_attention_heads,
  535. dropout=config.dropout,
  536. config=config,
  537. layer_idx=layer_idx,
  538. )
  539. self.mlp = IdeficsMLP(
  540. hidden_size=self.hidden_size,
  541. intermediate_size=config.intermediate_size,
  542. hidden_act=config.hidden_act,
  543. )
  544. self.input_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  545. self.post_attention_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  546. self.dropout = config.dropout
  547. @auto_docstring
  548. def forward(
  549. self,
  550. hidden_states: torch.Tensor,
  551. attention_mask: torch.Tensor | None = None,
  552. position_ids: torch.LongTensor | None = None,
  553. past_key_values: Cache | None = None,
  554. **kwargs: Unpack[TransformersKwargs],
  555. ) -> torch.FloatTensor:
  556. residual = hidden_states
  557. hidden_states = self.input_layernorm(hidden_states)
  558. # Self Attention
  559. hidden_states, _ = self.self_attn(
  560. hidden_states=hidden_states,
  561. attention_mask=attention_mask,
  562. position_ids=position_ids,
  563. past_key_values=past_key_values,
  564. **kwargs,
  565. )
  566. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  567. hidden_states = residual + hidden_states
  568. # Fully Connected
  569. residual = hidden_states
  570. hidden_states = self.post_attention_layernorm(hidden_states)
  571. hidden_states = self.mlp(hidden_states)
  572. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  573. hidden_states = residual + hidden_states
  574. return hidden_states
  575. class IdeficsGatedCrossAttentionLayer(GradientCheckpointingLayer):
  576. def __init__(self, config: IdeficsConfig, layer_idx: int | None = None):
  577. super().__init__()
  578. self.hidden_size = config.hidden_size
  579. self.cross_attn = IdeficsAttention(
  580. hidden_size=self.hidden_size,
  581. num_heads=config.num_attention_heads,
  582. is_cross_attention=True,
  583. dropout=config.dropout,
  584. config=config,
  585. qk_layer_norms=config.qk_layer_norms,
  586. layer_idx=layer_idx,
  587. )
  588. self.mlp = IdeficsMLP(
  589. hidden_size=self.hidden_size,
  590. intermediate_size=config.intermediate_size,
  591. hidden_act=config.hidden_act,
  592. )
  593. self.input_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  594. self.post_attention_layernorm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  595. self.config = config.dropout
  596. self.act_cross_attn = nn.Tanh()
  597. self.act_dense = nn.Tanh()
  598. if config.alpha_initializer == "zeros":
  599. if config.alpha_type == "vector":
  600. self.alpha_cross_attn = nn.Parameter(torch.zeros(1, 1, self.hidden_size))
  601. self.alpha_dense = nn.Parameter(torch.zeros(1, 1, self.hidden_size))
  602. elif config.alpha_type == "float":
  603. self.alpha_cross_attn = nn.Parameter(torch.zeros(1))
  604. self.alpha_dense = nn.Parameter(torch.zeros(1))
  605. else:
  606. raise ValueError(f"Unknown value for `alpha_type` ({config.alpha_type})")
  607. elif config.alpha_initializer == "ones":
  608. if config.alpha_type == "vector":
  609. self.alpha_cross_attn = nn.Parameter(torch.ones(1, 1, self.hidden_size))
  610. self.alpha_dense = nn.Parameter(torch.ones(1, 1, self.hidden_size))
  611. elif config.alpha_type == "float":
  612. self.alpha_cross_attn = nn.Parameter(torch.ones(1))
  613. self.alpha_dense = nn.Parameter(torch.ones(1))
  614. else:
  615. raise ValueError(f"Unknown value for `alpha_type` ({config.alpha_type})")
  616. elif config.alpha_initializer in {"normal", "gaussian", "random"}:
  617. if config.alpha_type == "vector":
  618. self.alpha_cross_attn = nn.Parameter(
  619. torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1, 1, self.hidden_size))
  620. )
  621. self.alpha_dense = nn.Parameter(
  622. torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1, 1, self.hidden_size))
  623. )
  624. elif config.alpha_type == "float":
  625. self.alpha_cross_attn = nn.Parameter(
  626. torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1))
  627. )
  628. self.alpha_dense = nn.Parameter(torch.normal(mean=0.0, std=config.alphas_initializer_range, size=(1)))
  629. else:
  630. raise ValueError(f"Unknown value for `alpha_type` ({config.alpha_type})")
  631. else:
  632. raise NotImplementedError(f"Alpha initialization scheme {config.alpha_initializer} not yet implemented!")
  633. if not (hasattr(self, "alpha_cross_attn") and hasattr(self, "alpha_dense")):
  634. raise ValueError("Alpha parameters not initialized correctly!")
  635. @auto_docstring
  636. def forward(
  637. self,
  638. hidden_states: torch.Tensor,
  639. attention_mask: torch.Tensor | None = None,
  640. image_hidden_states: torch.Tensor | None = None,
  641. image_attention_mask: torch.Tensor | None = None,
  642. cross_attention_gate: torch.Tensor | None = None,
  643. past_key_values: Cache | None = None,
  644. **kwargs: Unpack[TransformersKwargs],
  645. ) -> torch.FloatTensor:
  646. r"""
  647. image_hidden_states (`torch.FloatTensor`):
  648. Input to the layer of shape `(batch, seq_len, embed_dim)`
  649. image_attention_mask (`torch.FloatTensor`, *optional*):
  650. image attention mask of size
  651. `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
  652. cross_attention_gate (`torch.FloatTensor`, *optional*):
  653. gate of size `(batch, seq_len)` used to zero-out cross-attention output for tokens attending no images.
  654. """
  655. if image_hidden_states is None:
  656. raise ValueError(
  657. "`image_hidden_states` is required for Idefics cross attention module which are visual features to be"
  658. " conditioned on."
  659. )
  660. if cross_attention_gate is None:
  661. raise ValueError(
  662. "`cross_attention_gate` is required for Idefics cross attention module to zero-out the cross-attention hidden_states attending to no images."
  663. )
  664. if past_key_values is not None:
  665. raise NotImplementedError("Past key value states are not implemented for Idefics cross attention module.")
  666. residual = hidden_states
  667. hidden_states = self.input_layernorm(hidden_states)
  668. # Self Attention
  669. hidden_states, _ = self.cross_attn(
  670. hidden_states=hidden_states,
  671. key_value_states=image_hidden_states,
  672. attention_mask=image_attention_mask,
  673. **kwargs,
  674. )
  675. hidden_states = nn.functional.dropout(hidden_states, p=self.config, training=self.training)
  676. # Fill in zeros for cross_attention hidden_states of tokens attending to no images
  677. hidden_states = hidden_states.masked_fill((cross_attention_gate == 0)[:, :, None], 0.0)
  678. hidden_states = residual + self.act_cross_attn(self.alpha_cross_attn) * hidden_states
  679. # Fully Connected
  680. residual = hidden_states
  681. hidden_states = self.post_attention_layernorm(hidden_states)
  682. hidden_states = self.mlp(hidden_states)
  683. hidden_states = nn.functional.dropout(hidden_states, p=self.config, training=self.training)
  684. hidden_states = residual + self.act_dense(self.alpha_dense) * hidden_states
  685. return hidden_states
  686. @auto_docstring
  687. class IdeficsPreTrainedModel(PreTrainedModel):
  688. config: IdeficsConfig
  689. base_model_prefix = "model"
  690. input_modalities = ("image", "text")
  691. supports_gradient_checkpointing = True
  692. _no_split_modules = ["IdeficsDecoderLayer", "IdeficsGatedCrossAttentionLayer"]
  693. _supports_sdpa = True
  694. _supports_flash_attn = False # only eager/sdpa creation is supported
  695. _can_compile_fullgraph = False # IDEFICS cannot compile due to dynamic control flow when checking inputs
  696. _supports_attention_backend = True
  697. _can_record_outputs = {
  698. "hidden_states": IdeficsDecoderLayer,
  699. "attentions": OutputRecorder(IdeficsAttention, index=1, layer_name="self_attn"),
  700. }
  701. @torch.no_grad()
  702. def _init_weights(self, module):
  703. # important: this ported version of Idefics isn't meant for training from scratch - only
  704. # inference and fine-tuning - so the proper init weights code has been removed - the m4 code
  705. # base should be used for training from scratch and it contains the correct code.
  706. super()._init_weights(module)
  707. if isinstance(module, IdeficsVisionEmbeddings):
  708. init.normal_(module.class_embedding)
  709. init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
  710. elif isinstance(module, IdeficsGatedCrossAttentionLayer):
  711. if self.config.alpha_initializer == "zeros":
  712. init.zeros_(module.alpha_cross_attn)
  713. init.zeros_(module.alpha_dense)
  714. elif self.config.alpha_initializer == "ones":
  715. init.ones_(module.alpha_cross_attn)
  716. init.ones_(module.alpha_dense)
  717. elif self.config.alpha_initializer in {"normal", "gaussian", "random"}:
  718. init.normal_(module.alpha_cross_attn, mean=0.0, std=self.config.alphas_initializer_range)
  719. init.normal_(module.alpha_dense, mean=0.0, std=self.config.alphas_initializer_range)
  720. elif isinstance(module, IdeficsPerceiverResampler):
  721. init.normal_(module.latents)
  722. elif isinstance(module, IdeficsEmbedding):
  723. inv_freq = 1.0 / (module.base ** (torch.arange(0, module.dim, 2) / module.dim))
  724. init.copy_(module.inv_freq, inv_freq)
  725. t = torch.arange(module.max_position_embeddings).type_as(inv_freq)
  726. freqs = torch.einsum("i,j->ij", t, inv_freq)
  727. # Different from paper, but it uses a different permutation in order to obtain the same calculation
  728. emb = torch.cat((freqs, freqs), dim=-1)
  729. init.copy_(module.cos_cached, emb.cos())
  730. init.copy_(module.sin_cached, emb.sin())
  731. @auto_docstring
  732. class IdeficsModel(IdeficsPreTrainedModel):
  733. """
  734. Transformer decoder consisting of `config.num_hidden_layers` layers. Each layer is a [`IdeficsDecoderLayer`]
  735. Args:
  736. config: IdeficsConfig
  737. """
  738. def __init__(self, config: IdeficsConfig):
  739. super().__init__(config)
  740. self.config = config
  741. self.padding_idx = config.pad_token_id
  742. self.vocab_size = config.vocab_size
  743. self.embed_tokens = IdeficsDecoupledEmbedding(
  744. num_embeddings=config.vocab_size,
  745. num_additional_embeddings=config.additional_vocab_size,
  746. embedding_dim=config.hidden_size,
  747. partially_freeze=config.freeze_text_layers,
  748. padding_idx=self.padding_idx,
  749. )
  750. self.image_size = config.vision_config.image_size
  751. self.vision_config = config.vision_config
  752. # The module using it is not a PreTrainedModel subclass so we need this
  753. self.vision_config._attn_implementation = config._attn_implementation
  754. self.vision_model = IdeficsVisionTransformer(config.vision_config)
  755. # Perceiver Resampler
  756. if config.use_resampler:
  757. perceiver_config = config.perceiver_config
  758. self.perceiver_resampler = IdeficsPerceiverResampler(
  759. config,
  760. config.vision_config.embed_dim,
  761. perceiver_config.resampler_depth,
  762. perceiver_config.resampler_n_heads,
  763. perceiver_config.resampler_head_dim,
  764. perceiver_config.resampler_n_latents,
  765. )
  766. self.layers = nn.ModuleList(
  767. [IdeficsDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
  768. )
  769. self.cross_layer_interval = config.cross_layer_interval
  770. num_cross_layers = config.num_hidden_layers // self.cross_layer_interval
  771. self.gated_cross_attn_layers = nn.ModuleList(
  772. [IdeficsGatedCrossAttentionLayer(config, layer_idx=i) for i in range(num_cross_layers)]
  773. )
  774. self.gradient_checkpointing = False
  775. self.norm = IdeficsRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  776. # Initialize weights and apply final processing
  777. self.post_init()
  778. self.freeze_relevant_params(config)
  779. def freeze_relevant_params(self, config=None):
  780. if config is None:
  781. config = self.config
  782. if config.freeze_text_layers:
  783. self.freeze_text_layers(config.freeze_text_module_exceptions)
  784. if config.freeze_vision_layers:
  785. freeze_model(self.vision_model, module_exceptions=config.freeze_vision_module_exceptions)
  786. def freeze_text_layers(self, module_exceptions=()):
  787. for module in [self.layers, self.norm]:
  788. freeze_model(module, module_exceptions=module_exceptions)
  789. def freeze_vision_layers(self, module_exceptions=()):
  790. freeze_model(self.vision_model, module_exceptions=module_exceptions)
  791. @merge_with_config_defaults
  792. @capture_outputs
  793. @auto_docstring
  794. def forward(
  795. self,
  796. input_ids: torch.LongTensor | None = None,
  797. attention_mask: torch.Tensor | None = None,
  798. position_ids: torch.LongTensor | None = None,
  799. past_key_values: Cache | None = None,
  800. inputs_embeds: torch.FloatTensor | None = None,
  801. pixel_values: torch.FloatTensor | None = None,
  802. image_encoder_embeddings: torch.FloatTensor | None = None,
  803. perceiver_embeddings: torch.FloatTensor | None = None,
  804. image_attention_mask: torch.Tensor | None = None,
  805. use_cache: bool | None = None,
  806. interpolate_pos_encoding: bool | None = False,
  807. **kwargs: Unpack[TransformersKwargs],
  808. ) -> tuple | IdeficsBaseModelOutputWithPast:
  809. r"""
  810. image_encoder_embeddings (`torch.FloatTensor`, *optional*):
  811. The output of the image encoder.
  812. perceiver_embeddings (`torch.FloatTensor`, *optional*):
  813. The output of the perceiver resampler.
  814. image_attention_mask (`torch.LongTensor`, *optional*):
  815. The attention mask for the image encoder.
  816. """
  817. device = input_ids.device if input_ids is not None else inputs_embeds.device
  818. if (input_ids is None) ^ (inputs_embeds is not None):
  819. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  820. if inputs_embeds is None:
  821. inputs_embeds = self.embed_tokens(input_ids)
  822. if use_cache and past_key_values is None:
  823. past_key_values = DynamicCache(config=self.config)
  824. seq_length = inputs_embeds.shape[1]
  825. past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
  826. seq_length_with_past = seq_length + past_key_values_length
  827. if attention_mask is not None and position_ids is None:
  828. # create position_ids on the fly for batch generation
  829. position_ids = attention_mask.long().cumsum(-1) - 1
  830. position_ids.masked_fill_(attention_mask == 0, 1)
  831. position_ids = position_ids[:, -seq_length:]
  832. elif position_ids is None:
  833. position_ids = torch.arange(seq_length, device=inputs_embeds.device) + past_key_values_length
  834. position_ids = position_ids.unsqueeze(0)
  835. if sum(x is None for x in [pixel_values, image_encoder_embeddings, perceiver_embeddings]) != 2:
  836. raise ValueError(
  837. "Exactly 1 of pixel_values, image_encoder_embeddings or perceiver_embeddings has to be not-None."
  838. )
  839. elif pixel_values is not None:
  840. pixel_values = pixel_values.to(dtype=self.dtype, device=device) # fp16 compatibility
  841. batch_size, num_images = pixel_values.shape[:2]
  842. pixel_values = pixel_values.contiguous().view(batch_size * num_images, *pixel_values.shape[2:])
  843. # Get sequence from the vision encoder
  844. image_hidden_states = self.vision_model(
  845. pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding
  846. ).last_hidden_state
  847. elif image_encoder_embeddings is not None:
  848. batch_size, num_images, image_seq_len, image_hidden_size = image_encoder_embeddings.size()
  849. image_hidden_states = image_encoder_embeddings.to(dtype=self.dtype, device=device)
  850. image_hidden_states = image_hidden_states.view(batch_size * num_images, image_seq_len, image_hidden_size)
  851. if self.config.use_resampler:
  852. if perceiver_embeddings is None:
  853. perceiver_embeddings = self.perceiver_resampler(image_hidden_states)
  854. image_seq_len, image_hidden_size = perceiver_embeddings.size(1), perceiver_embeddings.size(2)
  855. else:
  856. batch_size, num_images, image_seq_len, image_hidden_size = perceiver_embeddings.size()
  857. image_hidden_states = perceiver_embeddings
  858. elif perceiver_embeddings is None:
  859. image_seq_len, image_hidden_size = image_hidden_states.size(1), image_hidden_states.size(2)
  860. else:
  861. raise ValueError("If `perceiver_embeddings` are passed, use_resampler should be True")
  862. image_hidden_states = image_hidden_states.view(batch_size, num_images * image_seq_len, image_hidden_size)
  863. # # Hack to use the model in full language modeling mode
  864. # image_attention_mask = torch.zeros(batch_size, seq_length, 1, dtype=torch.long, device=image_hidden_states.device)
  865. # Make image_attention_mask compatible with hidden states
  866. text_seq_len = image_attention_mask.size(1)
  867. image_attention_mask = image_attention_mask.unsqueeze(-1)
  868. image_attention_mask = image_attention_mask.repeat(1, 1, 1, image_seq_len)
  869. image_attention_mask = image_attention_mask.view(batch_size, text_seq_len, num_images * image_seq_len)
  870. if image_hidden_states is not None:
  871. image_batch_size, image_sequence_length, _ = image_hidden_states.size()
  872. image_hidden_shape = (image_batch_size, image_sequence_length)
  873. if image_attention_mask is None:
  874. image_attention_mask = torch.ones(image_hidden_shape, device=device)
  875. image_attention_mask = self.invert_attention_mask(image_attention_mask)
  876. else:
  877. image_attention_mask = None
  878. # cross_attention_gate:
  879. # For any tokens attending to no images, the hidden_states coming out of the cross-attention should be zeroed-out.
  880. # `image_attention_mask` has shape [bsz, 1, num_images, hidden_size] with elements equal to either 0.0 or a very negative number.
  881. # If any of the elements are 0.0, then the token is attending to at least one image and the gate value is 1. Otherwise the gate value is 0.
  882. # `cross_attention_gate` has shape [bsz, seq_len] with elements equal to either 0.0 or 1.0.
  883. cross_attention_gate = ((((image_attention_mask == 0.0).any(dim=-1)).to(dtype=self.dtype)).squeeze(dim=1)).to(
  884. device
  885. )
  886. # embed positions
  887. if attention_mask is None:
  888. attention_mask = torch.ones(
  889. (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
  890. )
  891. causal_mask = create_causal_mask(
  892. config=self.config,
  893. inputs_embeds=inputs_embeds,
  894. attention_mask=attention_mask,
  895. past_key_values=past_key_values,
  896. position_ids=position_ids,
  897. )
  898. hidden_states = inputs_embeds
  899. for idx, decoder_layer in enumerate(self.layers):
  900. # TODO(ls): Add cross attention values to respective lists
  901. if idx % self.cross_layer_interval == 0:
  902. cross_attn_block = self.gated_cross_attn_layers[idx // self.cross_layer_interval]
  903. hidden_states = cross_attn_block(
  904. hidden_states,
  905. causal_mask,
  906. image_hidden_states,
  907. image_attention_mask=image_attention_mask,
  908. cross_attention_gate=cross_attention_gate,
  909. past_key_values=None, # not implemented
  910. **kwargs,
  911. )
  912. hidden_states = decoder_layer(
  913. hidden_states,
  914. attention_mask=causal_mask,
  915. position_ids=position_ids,
  916. past_key_values=past_key_values,
  917. **kwargs,
  918. )
  919. hidden_states = self.norm(hidden_states)
  920. image_hidden_states = image_hidden_states.view(batch_size, num_images, image_seq_len, image_hidden_size)
  921. return IdeficsBaseModelOutputWithPast(
  922. last_hidden_state=hidden_states,
  923. image_hidden_states=image_hidden_states,
  924. past_key_values=past_key_values,
  925. )
  926. class IdeficsForVisionText2Text(IdeficsPreTrainedModel, GenerationMixin):
  927. _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
  928. def __init__(self, config, vision_model=None):
  929. super().__init__(config)
  930. self.model = IdeficsModel(config)
  931. self.lm_head = IdeficsDecoupledLinear(
  932. in_features=config.hidden_size,
  933. out_features=config.vocab_size,
  934. out_additional_features=config.additional_vocab_size,
  935. bias=False,
  936. partially_freeze=config.freeze_lm_head,
  937. )
  938. if config.additional_vocab_size > 0:
  939. self._tied_weights_keys = {
  940. "lm_head.weight": "model.embed_tokens.weight",
  941. "lm_head.additional_fc.weight": "model.embed_tokens.additional_embedding.weight",
  942. }
  943. # Initialize weights and apply final processing
  944. self.post_init()
  945. @can_return_tuple
  946. @auto_docstring
  947. def forward(
  948. self,
  949. input_ids: torch.LongTensor | None = None,
  950. attention_mask: torch.Tensor | None = None,
  951. position_ids: torch.LongTensor | None = None,
  952. past_key_values: Cache | None = None,
  953. inputs_embeds: torch.FloatTensor | None = None,
  954. pixel_values: torch.FloatTensor | None = None,
  955. image_encoder_embeddings: torch.FloatTensor | None = None,
  956. perceiver_embeddings: torch.FloatTensor | None = None,
  957. image_attention_mask: torch.Tensor | None = None,
  958. labels: torch.LongTensor | None = None,
  959. use_cache: bool | None = None,
  960. interpolate_pos_encoding: bool | None = False,
  961. logits_to_keep: int | torch.Tensor = 0,
  962. **kwargs: Unpack[TransformersKwargs],
  963. ) -> tuple | IdeficsCausalLMOutputWithPast:
  964. r"""
  965. image_encoder_embeddings (`torch.FloatTensor`, *optional*):
  966. The output of the image encoder.
  967. perceiver_embeddings (`torch.FloatTensor`, *optional*):
  968. The output of the perceiver resampler.
  969. image_attention_mask (`torch.LongTensor`, *optional*):
  970. The attention mask for the image encoder.
  971. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  972. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  973. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  974. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  975. Example:
  976. ```python
  977. >>> from transformers import AutoProcessor, IdeficsForVisionText2Text
  978. >>> model = IdeficsForVisionText2Text.from_pretrained("HuggingFaceM4/idefics-9b")
  979. >>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics-9b")
  980. >>> dogs_image_url_1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image1.jpeg"
  981. >>> dogs_image_url_2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_nlvr2/raw/main/image2.jpeg"
  982. >>> prompts = [
  983. ... [
  984. ... "User:",
  985. ... dogs_image_url_1,
  986. ... "Describe this image.\nAssistant: An image of two dogs.\n",
  987. ... "User:",
  988. ... dogs_image_url_2,
  989. ... "Describe this image.\nAssistant:",
  990. ... ]
  991. ... ]
  992. >>> inputs = processor(prompts, return_tensors="pt")
  993. >>> generate_ids = model.generate(**inputs, max_new_tokens=6)
  994. >>> processor.batch_decode(generate_ids, skip_special_tokens=True)
  995. ```"""
  996. outputs: IdeficsBaseModelOutputWithPast = self.model(
  997. input_ids=input_ids,
  998. attention_mask=attention_mask,
  999. position_ids=position_ids,
  1000. past_key_values=past_key_values,
  1001. inputs_embeds=inputs_embeds,
  1002. pixel_values=pixel_values,
  1003. image_encoder_embeddings=image_encoder_embeddings,
  1004. perceiver_embeddings=perceiver_embeddings,
  1005. image_attention_mask=image_attention_mask,
  1006. use_cache=use_cache,
  1007. interpolate_pos_encoding=interpolate_pos_encoding,
  1008. return_dict=True,
  1009. **kwargs,
  1010. )
  1011. hidden_states = outputs.last_hidden_state
  1012. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1013. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1014. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1015. loss = None
  1016. if labels is not None:
  1017. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
  1018. return IdeficsCausalLMOutputWithPast(
  1019. loss=loss,
  1020. logits=logits,
  1021. past_key_values=outputs.past_key_values,
  1022. hidden_states=outputs.hidden_states,
  1023. attentions=outputs.attentions,
  1024. image_hidden_states=outputs.image_hidden_states,
  1025. )
  1026. def prepare_inputs_for_generation(
  1027. self,
  1028. input_ids,
  1029. attention_mask=None,
  1030. position_ids=None,
  1031. inputs_embeds=None,
  1032. past_key_values=None,
  1033. pixel_values=None,
  1034. image_hidden_states=None,
  1035. image_attention_mask=None,
  1036. use_cache=None,
  1037. **kwargs,
  1038. ):
  1039. # Overwritten -- custom processing based on `config.use_resampler`
  1040. images_kwargs = {}
  1041. if image_hidden_states is not None:
  1042. if self.config.use_resampler:
  1043. images_kwargs["perceiver_embeddings"] = image_hidden_states
  1044. else:
  1045. images_kwargs["image_encoder_embeddings"] = image_hidden_states
  1046. else:
  1047. images_kwargs["pixel_values"] = pixel_values
  1048. images_kwargs["interpolate_pos_encoding"] = kwargs.pop("interpolate_pos_encoding", False)
  1049. model_inputs = super().prepare_inputs_for_generation(
  1050. input_ids,
  1051. past_key_values=past_key_values,
  1052. attention_mask=attention_mask,
  1053. inputs_embeds=inputs_embeds,
  1054. position_ids=position_ids,
  1055. use_cache=use_cache,
  1056. image_attention_mask=image_attention_mask,
  1057. **images_kwargs,
  1058. **kwargs,
  1059. )
  1060. if image_attention_mask is not None and inputs_embeds is None:
  1061. seq_length = model_inputs["input_ids"].shape[1]
  1062. model_inputs["image_attention_mask"] = image_attention_mask[:, -seq_length:]
  1063. return model_inputs
  1064. def _update_model_kwargs_for_generation(
  1065. self,
  1066. outputs: ModelOutput,
  1067. model_kwargs: dict[str, Any],
  1068. is_encoder_decoder: bool = False,
  1069. **kwargs,
  1070. ) -> dict[str, Any]:
  1071. model_kwargs = super()._update_model_kwargs_for_generation(
  1072. outputs,
  1073. model_kwargs,
  1074. is_encoder_decoder,
  1075. **kwargs,
  1076. )
  1077. if "image_attention_mask" in model_kwargs:
  1078. image_attention_mask = model_kwargs["image_attention_mask"]
  1079. last_mask = image_attention_mask[:, -1, :].unsqueeze(1)
  1080. if model_kwargs.get("use_cache", True):
  1081. model_kwargs["image_attention_mask"] = last_mask
  1082. else:
  1083. model_kwargs["image_attention_mask"] = torch.cat([image_attention_mask, last_mask], dim=1)
  1084. # Get the precomputed image_hidden_states
  1085. model_kwargs["image_hidden_states"] = outputs.image_hidden_states
  1086. return model_kwargs
  1087. __all__ = ["IdeficsForVisionText2Text", "IdeficsModel", "IdeficsPreTrainedModel"]