modeling_paligemma.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. # coding=utf-8
  2. # Copyright 2024 the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch PaliGemmamodel."""
  16. from dataclasses import dataclass
  17. from typing import Optional, Union
  18. import torch
  19. from torch import nn
  20. from ...cache_utils import Cache, StaticCache
  21. from ...generation import GenerationMixin
  22. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  23. from ...modeling_outputs import BaseModelOutputWithPast
  24. from ...modeling_utils import PreTrainedModel
  25. from ...processing_utils import Unpack
  26. from ...utils import (
  27. ModelOutput,
  28. TransformersKwargs,
  29. auto_docstring,
  30. can_return_tuple,
  31. logging,
  32. )
  33. from ..auto import AutoModel
  34. from .configuration_paligemma import PaliGemmaConfig
  35. logger = logging.get_logger(__name__)
  36. @dataclass
  37. @auto_docstring(
  38. custom_intro="""
  39. Base class for Paligemma outputs, with hidden states and attentions.
  40. """
  41. )
  42. class PaligemmaModelOutputWithPast(BaseModelOutputWithPast):
  43. r"""
  44. image_hidden_states (`torch.FloatTensor`, *optional*):
  45. A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
  46. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
  47. """
  48. image_hidden_states: Optional[torch.FloatTensor] = None
  49. @dataclass
  50. @auto_docstring(
  51. custom_intro="""
  52. Base class for PaliGemma causal language model (or autoregressive) outputs.
  53. """
  54. )
  55. class PaliGemmaCausalLMOutputWithPast(ModelOutput):
  56. r"""
  57. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  58. Language modeling loss (for next-token prediction).
  59. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
  60. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  61. past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  62. It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
  63. Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  64. `past_key_values` input) to speed up sequential decoding.
  65. image_hidden_states (`torch.FloatTensor`, *optional*):
  66. A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
  67. image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
  68. """
  69. loss: Optional[torch.FloatTensor] = None
  70. logits: Optional[torch.FloatTensor] = None
  71. past_key_values: Optional[Cache] = None
  72. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  73. attentions: Optional[tuple[torch.FloatTensor]] = None
  74. image_hidden_states: Optional[torch.FloatTensor] = None
  75. class PaliGemmaMultiModalProjector(nn.Module):
  76. def __init__(self, config: PaliGemmaConfig):
  77. super().__init__()
  78. self.linear = nn.Linear(config.vision_config.hidden_size, config.vision_config.projection_dim, bias=True)
  79. def forward(self, image_features):
  80. hidden_states = self.linear(image_features)
  81. return hidden_states
  82. @auto_docstring
  83. class PaliGemmaPreTrainedModel(PreTrainedModel):
  84. config: PaliGemmaConfig
  85. base_model_prefix = ""
  86. supports_gradient_checkpointing = True
  87. _no_split_modules = ["PaliGemmaMultiModalProjector"]
  88. _skip_keys_device_placement = "past_key_values"
  89. _can_compile_fullgraph = False
  90. _supports_flash_attn = True
  91. _supports_sdpa = True
  92. _supports_flex_attn = True
  93. _supports_attention_backend = True
  94. def _init_weights(self, module):
  95. # important: this ported version of PaliGemmaisn't meant for training from scratch - only
  96. # inference and fine-tuning
  97. std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
  98. if isinstance(module, nn.Linear):
  99. module.weight.data.normal_(mean=0.0, std=std)
  100. if module.bias is not None:
  101. module.bias.data.zero_()
  102. @auto_docstring(
  103. custom_intro="""
  104. The Base Paligemma model which consists of a vision backbone and a language model without language modeling head.,
  105. """
  106. )
  107. class PaliGemmaModel(PaliGemmaPreTrainedModel):
  108. _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
  109. # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
  110. accepts_loss_kwargs = False
  111. def __init__(self, config: PaliGemmaConfig):
  112. super().__init__(config)
  113. self.vision_tower = AutoModel.from_config(config=config.vision_config)
  114. self.multi_modal_projector = PaliGemmaMultiModalProjector(config)
  115. self.vocab_size = config.text_config.vocab_size
  116. language_model = AutoModel.from_config(config=config.text_config)
  117. self.language_model = language_model
  118. self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
  119. self.text_config_dtype = self.config.get_text_config().dtype or self.dtype
  120. self.post_init()
  121. # Copied from transformers.models.llava.modeling_llava.LlavaModel.get_input_embeddings with Llava->PaliGemma
  122. def get_input_embeddings(self):
  123. return self.language_model.get_input_embeddings()
  124. # Copied from transformers.models.llava.modeling_llava.LlavaModel.set_input_embeddings with Llava->PaliGemma
  125. def set_input_embeddings(self, value):
  126. self.language_model.set_input_embeddings(value)
  127. def set_decoder(self, decoder):
  128. self.language_model = decoder
  129. def get_decoder(self):
  130. return self.language_model
  131. def _update_causal_mask(
  132. self,
  133. attention_mask,
  134. token_type_ids=None,
  135. past_key_values=None,
  136. cache_position=None,
  137. input_tensor=None,
  138. is_training: Optional[bool] = None,
  139. ):
  140. if self.config.text_config._attn_implementation == "flash_attention_2":
  141. if attention_mask is not None and 0.0 in attention_mask:
  142. return attention_mask
  143. return None
  144. is_training = is_training if is_training is not None else self.training
  145. using_static_cache = isinstance(past_key_values, StaticCache)
  146. min_dtype = torch.finfo(self.text_config_dtype).min
  147. if input_tensor is None:
  148. input_tensor = attention_mask
  149. inputs_lead_dim, sequence_length = input_tensor.shape[:2]
  150. if using_static_cache:
  151. target_length = past_key_values.get_max_cache_shape()
  152. else:
  153. target_length = (
  154. attention_mask.shape[-1]
  155. if isinstance(attention_mask, torch.Tensor)
  156. else cache_position[0] + sequence_length + 1
  157. )
  158. if attention_mask is not None and attention_mask.dim() == 4:
  159. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  160. return attention_mask
  161. causal_mask = torch.full(
  162. (sequence_length, target_length),
  163. fill_value=min_dtype,
  164. dtype=self.text_config_dtype,
  165. device=cache_position.device,
  166. )
  167. # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
  168. if sequence_length != 1:
  169. if is_training:
  170. causal_mask = torch.triu(causal_mask, diagonal=1)
  171. else:
  172. causal_mask[:, :sequence_length] = 0.0
  173. causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
  174. causal_mask = causal_mask[None, None, :, :].expand(inputs_lead_dim, 1, -1, -1)
  175. if attention_mask is not None:
  176. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  177. mask_length = attention_mask.shape[-1]
  178. # First unmask prefix tokens during training
  179. if is_training:
  180. if token_type_ids is None:
  181. raise ValueError("Token type ids must be provided during training")
  182. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  183. token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
  184. )
  185. # Then apply padding mask (will mask pad tokens)
  186. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)
  187. padding_mask = padding_mask == 0
  188. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  189. padding_mask, min_dtype
  190. )
  191. return causal_mask
  192. def get_image_features(self, pixel_values: torch.FloatTensor):
  193. """
  194. Obtains image last hidden states from the vision tower and apply multimodal projection.
  195. Args:
  196. pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
  197. The tensors corresponding to the input images.
  198. Returns:
  199. image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
  200. """
  201. image_outputs = self.vision_tower(pixel_values)
  202. selected_image_feature = image_outputs.last_hidden_state
  203. image_features = self.multi_modal_projector(selected_image_feature)
  204. image_features = image_features / (self.config.text_config.hidden_size**0.5)
  205. return image_features
  206. def get_placeholder_mask(
  207. self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
  208. ):
  209. """
  210. Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
  211. equal to the length of multimodal features. If the lengths are different, an error is raised.
  212. """
  213. if input_ids is None:
  214. special_image_mask = inputs_embeds == self.get_input_embeddings()(
  215. torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  216. )
  217. special_image_mask = special_image_mask.all(-1)
  218. else:
  219. special_image_mask = input_ids == self.config.image_token_id
  220. n_image_tokens = special_image_mask.sum()
  221. special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  222. n_image_features = image_features.shape[0] * image_features.shape[1]
  223. if inputs_embeds[special_image_mask].numel() != image_features.numel():
  224. raise ValueError(
  225. f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
  226. )
  227. return special_image_mask
  228. @can_return_tuple
  229. @auto_docstring
  230. def forward(
  231. self,
  232. input_ids: Optional[torch.LongTensor] = None,
  233. pixel_values: Optional[torch.FloatTensor] = None,
  234. attention_mask: Optional[torch.Tensor] = None,
  235. position_ids: Optional[torch.LongTensor] = None,
  236. past_key_values: Optional[Cache] = None,
  237. token_type_ids: Optional[torch.LongTensor] = None,
  238. cache_position: Optional[torch.LongTensor] = None,
  239. inputs_embeds: Optional[torch.FloatTensor] = None,
  240. labels: Optional[torch.LongTensor] = None,
  241. use_cache: Optional[bool] = None,
  242. output_attentions: Optional[bool] = None,
  243. output_hidden_states: Optional[bool] = None,
  244. return_dict: Optional[bool] = None,
  245. **kwargs: Unpack[FlashAttentionKwargs],
  246. ) -> Union[tuple, PaligemmaModelOutputWithPast]:
  247. r"""
  248. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  249. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  250. config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  251. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
  252. Example:
  253. ```python
  254. >>> from PIL import Image
  255. >>> import requests
  256. >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
  257. >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
  258. >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")
  259. >>> prompt = "Where is the cat standing?"
  260. >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
  261. >>> image = Image.open(requests.get(url, stream=True).raw)
  262. >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
  263. >>> # Generate
  264. >>> generate_ids = model.generate(**inputs,)
  265. >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  266. "Where is the cat standing?\nsnow"
  267. ```"""
  268. if (input_ids is None) ^ (inputs_embeds is not None):
  269. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  270. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  271. output_hidden_states = (
  272. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  273. )
  274. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  275. is_training = token_type_ids is not None and labels is not None
  276. # Replace image id with PAD if the image token if OOV, to avoid index-errors
  277. if input_ids is not None and self.config.image_token_id >= self.vocab_size:
  278. special_image_mask = input_ids == self.config.image_token_id
  279. llm_input_ids = input_ids.clone()
  280. llm_input_ids[special_image_mask] = 0
  281. else:
  282. llm_input_ids = input_ids
  283. if inputs_embeds is None:
  284. inputs_embeds = self.get_input_embeddings()(llm_input_ids)
  285. if cache_position is None:
  286. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  287. cache_position = torch.arange(
  288. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  289. )
  290. if position_ids is None:
  291. position_ids = cache_position.unsqueeze(0) + 1 # Paligemma positions are 1-indexed
  292. # Merge text and images
  293. if pixel_values is not None:
  294. image_features = self.get_image_features(pixel_values)
  295. image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
  296. special_image_mask = self.get_placeholder_mask(
  297. input_ids, inputs_embeds=inputs_embeds, image_features=image_features
  298. )
  299. inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
  300. causal_mask = self._update_causal_mask(
  301. attention_mask, token_type_ids, past_key_values, cache_position, inputs_embeds, is_training
  302. )
  303. outputs = self.language_model(
  304. attention_mask=causal_mask,
  305. position_ids=position_ids,
  306. past_key_values=past_key_values,
  307. inputs_embeds=inputs_embeds,
  308. use_cache=use_cache,
  309. output_attentions=output_attentions,
  310. output_hidden_states=output_hidden_states,
  311. return_dict=True,
  312. cache_position=cache_position,
  313. **kwargs,
  314. )
  315. return PaligemmaModelOutputWithPast(
  316. last_hidden_state=outputs.last_hidden_state,
  317. past_key_values=outputs.past_key_values,
  318. hidden_states=outputs.hidden_states,
  319. attentions=outputs.attentions,
  320. image_hidden_states=image_features if pixel_values is not None else None,
  321. )
  322. @auto_docstring(
  323. custom_intro="""
  324. The Base Paligemma model which consists of a vision backbone and a language model without language modeling head.,
  325. """
  326. )
  327. class PaliGemmaForConditionalGeneration(PaliGemmaPreTrainedModel, GenerationMixin):
  328. _checkpoint_conversion_mapping = {
  329. "^language_model.model": "model.language_model",
  330. "^vision_tower": "model.vision_tower",
  331. "^multi_modal_projector": "model.multi_modal_projector",
  332. "^language_model.lm_head": "lm_head",
  333. }
  334. _tied_weights_keys = ["lm_head.weight"]
  335. def __init__(self, config: PaliGemmaConfig):
  336. super().__init__(config)
  337. self.model = PaliGemmaModel(config)
  338. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  339. self.post_init()
  340. def get_input_embeddings(self):
  341. return self.model.get_input_embeddings()
  342. def set_input_embeddings(self, value):
  343. self.model.set_input_embeddings(value)
  344. def set_decoder(self, decoder):
  345. self.model.set_decoder(decoder)
  346. def get_decoder(self):
  347. return self.model.get_decoder()
  348. def get_image_features(self, pixel_values):
  349. return self.model.get_image_features(pixel_values)
  350. # Make modules available through conditional class for BC
  351. @property
  352. def language_model(self):
  353. return self.model.language_model
  354. @property
  355. def vision_tower(self):
  356. return self.model.vision_tower
  357. @property
  358. def multi_modal_projector(self):
  359. return self.model.multi_modal_projector
  360. @can_return_tuple
  361. @auto_docstring
  362. def forward(
  363. self,
  364. input_ids: Optional[torch.LongTensor] = None,
  365. pixel_values: Optional[torch.FloatTensor] = None,
  366. attention_mask: Optional[torch.Tensor] = None,
  367. position_ids: Optional[torch.LongTensor] = None,
  368. past_key_values: Optional[Cache] = None,
  369. token_type_ids: Optional[torch.LongTensor] = None,
  370. cache_position: Optional[torch.LongTensor] = None,
  371. inputs_embeds: Optional[torch.FloatTensor] = None,
  372. labels: Optional[torch.LongTensor] = None,
  373. use_cache: Optional[bool] = None,
  374. output_attentions: Optional[bool] = None,
  375. output_hidden_states: Optional[bool] = None,
  376. return_dict: Optional[bool] = None,
  377. logits_to_keep: Union[int, torch.Tensor] = 0,
  378. **kwargs: Unpack[TransformersKwargs],
  379. ) -> Union[tuple, PaliGemmaCausalLMOutputWithPast]:
  380. r"""
  381. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  382. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  383. config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  384. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
  385. Example:
  386. ```python
  387. >>> from PIL import Image
  388. >>> import requests
  389. >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
  390. >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
  391. >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")
  392. >>> prompt = "Where is the cat standing?"
  393. >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
  394. >>> image = Image.open(requests.get(url, stream=True).raw)
  395. >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
  396. >>> # Generate
  397. >>> generate_ids = model.generate(**inputs,)
  398. >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  399. "Where is the cat standing?\nsnow"
  400. ```"""
  401. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  402. output_hidden_states = (
  403. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  404. )
  405. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  406. outputs = self.model(
  407. input_ids=input_ids,
  408. pixel_values=pixel_values,
  409. token_type_ids=token_type_ids,
  410. attention_mask=attention_mask,
  411. position_ids=position_ids,
  412. past_key_values=past_key_values,
  413. inputs_embeds=inputs_embeds,
  414. use_cache=use_cache,
  415. labels=labels,
  416. output_attentions=output_attentions,
  417. output_hidden_states=output_hidden_states,
  418. return_dict=True,
  419. cache_position=cache_position,
  420. **kwargs,
  421. )
  422. hidden_states = outputs[0]
  423. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  424. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  425. logits = self.lm_head(hidden_states[:, slice_indices, :])
  426. loss = None
  427. if labels is not None:
  428. loss = self.loss_function(
  429. logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
  430. )
  431. return PaliGemmaCausalLMOutputWithPast(
  432. loss=loss,
  433. logits=logits,
  434. past_key_values=outputs.past_key_values,
  435. hidden_states=outputs.hidden_states,
  436. attentions=outputs.attentions,
  437. image_hidden_states=outputs.image_hidden_states,
  438. )
  439. def prepare_inputs_for_generation(
  440. self,
  441. input_ids,
  442. past_key_values=None,
  443. inputs_embeds=None,
  444. cache_position=None,
  445. position_ids=None,
  446. pixel_values=None,
  447. attention_mask=None,
  448. token_type_ids=None,
  449. use_cache=True,
  450. logits_to_keep=None,
  451. labels=None,
  452. **kwargs,
  453. ):
  454. # Overwritten -- custom `position_ids` and `pixel_values` handling
  455. model_inputs = super().prepare_inputs_for_generation(
  456. input_ids,
  457. past_key_values=past_key_values,
  458. inputs_embeds=inputs_embeds,
  459. attention_mask=attention_mask,
  460. position_ids=position_ids,
  461. cache_position=cache_position,
  462. use_cache=use_cache,
  463. logits_to_keep=logits_to_keep,
  464. token_type_ids=token_type_ids,
  465. **kwargs,
  466. )
  467. # position_ids in Paligemma are 1-indexed
  468. if model_inputs.get("position_ids") is not None:
  469. model_inputs["position_ids"] += 1
  470. # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
  471. # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
  472. if cache_position[0] == 0:
  473. model_inputs["pixel_values"] = pixel_values
  474. is_training = token_type_ids is not None and labels is not None
  475. is_static_hybrid_cache = isinstance(past_key_values, StaticCache) and any(past_key_values.is_sliding)
  476. if cache_position[0] == 0 and is_static_hybrid_cache:
  477. input_tensor = inputs_embeds if inputs_embeds is not None else input_ids
  478. causal_mask = self.model._update_causal_mask(
  479. attention_mask, token_type_ids, past_key_values, cache_position, input_tensor, is_training
  480. )
  481. model_inputs["attention_mask"] = causal_mask
  482. return model_inputs
  483. @staticmethod
  484. # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
  485. def _prepare_4d_causal_attention_mask_with_cache_position(
  486. attention_mask: torch.Tensor,
  487. sequence_length: int,
  488. target_length: int,
  489. dtype: torch.dtype,
  490. cache_position: torch.Tensor,
  491. batch_size: int,
  492. **kwargs,
  493. ):
  494. """
  495. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  496. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  497. Args:
  498. attention_mask (`torch.Tensor`):
  499. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
  500. `(batch_size, 1, query_length, key_value_length)`.
  501. sequence_length (`int`):
  502. The sequence length being processed.
  503. target_length (`int`):
  504. The target length: when generating with static cache, the mask should be as long as the static cache,
  505. to account for the 0 padding, the part of the cache that is not filled yet.
  506. dtype (`torch.dtype`):
  507. The dtype to use for the 4D attention mask.
  508. cache_position (`torch.Tensor`):
  509. Indices depicting the position of the input sequence tokens in the sequence.
  510. batch_size (`torch.Tensor`):
  511. Batch size.
  512. """
  513. if attention_mask is not None and attention_mask.dim() == 4:
  514. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  515. causal_mask = attention_mask
  516. else:
  517. min_dtype = torch.finfo(dtype).min
  518. causal_mask = torch.full(
  519. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
  520. )
  521. if sequence_length != 1:
  522. causal_mask = torch.triu(causal_mask, diagonal=1)
  523. causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
  524. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  525. if attention_mask is not None:
  526. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  527. mask_length = attention_mask.shape[-1]
  528. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
  529. causal_mask.device
  530. )
  531. padding_mask = padding_mask == 0
  532. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  533. padding_mask, min_dtype
  534. )
  535. return causal_mask
  536. __all__ = ["PaliGemmaForConditionalGeneration", "PaliGemmaPreTrainedModel", "PaliGemmaModel"]