modeling_idefics.py 57 KB

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