modeling_fuyu.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. # coding=utf-8
  2. # Copyright 2023 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 Fuyu model."""
  16. from typing import Optional, Union
  17. import torch
  18. from torch import nn
  19. from ...cache_utils import Cache
  20. from ...generation import GenerationMixin
  21. from ...modeling_outputs import CausalLMOutputWithPast
  22. from ...modeling_utils import PreTrainedModel
  23. from ...models.auto.modeling_auto import AutoModel
  24. from ...utils import auto_docstring, can_return_tuple, logging
  25. from .configuration_fuyu import FuyuConfig
  26. logger = logging.get_logger(__name__)
  27. @auto_docstring
  28. class FuyuPreTrainedModel(PreTrainedModel):
  29. config: FuyuConfig
  30. base_model_prefix = "fuyu"
  31. supports_gradient_checkpointing = True
  32. _supports_attention_backend = True
  33. _supports_flash_attn = True
  34. _supports_sdpa = True
  35. _supports_flex_attn = True
  36. _no_split_modules = []
  37. _skip_keys_device_placement = "past_key_values"
  38. def _init_weights(self, module):
  39. std = self.config.initializer_range
  40. if isinstance(module, nn.Linear):
  41. module.weight.data.normal_(mean=0.0, std=std)
  42. if module.bias is not None:
  43. module.bias.data.zero_()
  44. elif isinstance(module, nn.Embedding):
  45. module.weight.data.normal_(mean=0.0, std=std)
  46. if module.padding_idx is not None:
  47. module.weight.data[module.padding_idx].zero_()
  48. @auto_docstring(
  49. custom_intro="""
  50. The Fuyu model which consists of a vision backbone and a language model, without a language modeling head.
  51. """
  52. )
  53. class FuyuModel(FuyuPreTrainedModel):
  54. _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
  55. def __init__(self, config: FuyuConfig):
  56. super().__init__(config)
  57. self.padding_idx = config.pad_token_id
  58. self.vocab_size = config.text_config.vocab_size
  59. self.language_model = AutoModel.from_config(config.text_config)
  60. self.vision_embed_tokens = nn.Linear(
  61. config.patch_size * config.patch_size * config.num_channels, config.hidden_size
  62. )
  63. self.gradient_checkpointing = False
  64. # Initialize weights and apply final processing
  65. self.post_init()
  66. def get_input_embeddings(self):
  67. return self.language_model.get_input_embeddings()
  68. def set_input_embeddings(self, value):
  69. self.language_model.set_input_embeddings(value)
  70. def set_decoder(self, decoder):
  71. self.language_model = decoder
  72. def get_decoder(self):
  73. return self.language_model
  74. def gather_continuous_embeddings(
  75. self,
  76. word_embeddings: torch.Tensor,
  77. continuous_embeddings: list[torch.Tensor],
  78. image_patch_input_indices: torch.Tensor,
  79. ) -> torch.Tensor:
  80. """This function places the continuous_embeddings into the word_embeddings at the locations
  81. indicated by image_patch_input_indices. Different batch elements can have different numbers of continuous
  82. embeddings.
  83. Args:
  84. word_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  85. Tensor of word embeddings.
  86. continuous_embeddings (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`):
  87. Tensor of continuous embeddings. The length of the list is the batch size. Each entry is shape
  88. [num_image_embeddings, hidden], and num_image_embeddings needs to match the number of non-negative
  89. indices in image_patch_input_indices for that batch element.
  90. image_patch_input_indices (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  91. Tensor of indices of the image patches in the input_ids tensor.
  92. """
  93. if not (word_embeddings.shape[0] == len(continuous_embeddings)):
  94. raise ValueError(
  95. f"Batch sizes must match! Got {len(continuous_embeddings)=} and {word_embeddings.shape[0]=}"
  96. )
  97. output_embeddings = word_embeddings.clone()
  98. for batch_idx in range(word_embeddings.shape[0]):
  99. # First, find the positions of all the non-negative values in image_patch_input_indices, those are the
  100. # positions in word_embeddings that we want to replace with content from continuous_embeddings.
  101. dst_indices = torch.nonzero(image_patch_input_indices[batch_idx] >= 0, as_tuple=True)[0]
  102. # Next look up those indices in image_patch_input_indices to find the indices in continuous_embeddings that we
  103. # want to use to replace the values in word_embeddings.
  104. src_indices = image_patch_input_indices[batch_idx][dst_indices]
  105. # Check if we have more indices than embeddings. Note that we could have fewer indices if images got truncated.
  106. if src_indices.shape[0] > continuous_embeddings[batch_idx].shape[0]:
  107. raise ValueError(
  108. f"Number of continuous embeddings {continuous_embeddings[batch_idx].shape=} does not match "
  109. f"number of continuous token ids {src_indices.shape=} in batch element {batch_idx}."
  110. )
  111. output_embeddings[batch_idx, dst_indices] = continuous_embeddings[batch_idx][src_indices].to(
  112. output_embeddings.device
  113. )
  114. return output_embeddings
  115. def get_image_features(self, pixel_values: torch.FloatTensor, **kwargs):
  116. """
  117. Encodes images into continuous embeddings that can be forwarded to the language model.
  118. Args:
  119. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  120. The tensors corresponding to the input images.
  121. """
  122. patch_embeddings = [
  123. self.vision_embed_tokens(patch.to(self.vision_embed_tokens.weight.dtype)).squeeze(0)
  124. for patch in pixel_values
  125. ]
  126. return patch_embeddings
  127. def get_placeholder_mask(
  128. self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
  129. ):
  130. """
  131. Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
  132. equal to the length of multimodal features. If the lengths are different, an error is raised.
  133. """
  134. if input_ids is None:
  135. special_image_mask = inputs_embeds == self.get_input_embeddings()(
  136. torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  137. )
  138. special_image_mask = special_image_mask.all(-1)
  139. else:
  140. special_image_mask = input_ids == self.config.image_token_id
  141. n_image_tokens = special_image_mask.sum()
  142. special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  143. n_image_features = image_features.shape[0] * image_features.shape[1]
  144. if inputs_embeds[special_image_mask].numel() != image_features.numel():
  145. raise ValueError(
  146. f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
  147. )
  148. return special_image_mask
  149. @auto_docstring
  150. def forward(
  151. self,
  152. input_ids: Optional[torch.LongTensor] = None,
  153. # [batch_size, num_total_patches, patch_size_ x patch_size x num_channels ]
  154. image_patches: Optional[torch.Tensor] = None,
  155. image_patches_indices: Optional[torch.Tensor] = None,
  156. attention_mask: Optional[torch.Tensor] = None,
  157. position_ids: Optional[torch.LongTensor] = None,
  158. past_key_values: Optional[Cache] = None,
  159. inputs_embeds: Optional[torch.FloatTensor] = None,
  160. use_cache: Optional[bool] = None,
  161. output_attentions: Optional[bool] = None,
  162. output_hidden_states: Optional[bool] = None,
  163. return_dict: Optional[bool] = None,
  164. **kwargs,
  165. ) -> Union[tuple, CausalLMOutputWithPast]:
  166. r"""
  167. image_patches (`torch.FloatTensor` of shape `(batch_size, num_total_patches, patch_size_ x patch_size x num_channels)`, *optional*):
  168. Image patches to be used as continuous embeddings. The patches are flattened and then projected to the
  169. hidden size of the model.
  170. image_patches_indices (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  171. Tensor of indices of the image patches in the input_ids tensor.
  172. """
  173. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  174. output_hidden_states = (
  175. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  176. )
  177. use_cache = use_cache if use_cache is not None else self.config.use_cache
  178. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  179. if input_ids is not None and inputs_embeds is not None:
  180. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  181. elif input_ids is not None:
  182. batch_size, seq_length = input_ids.shape
  183. elif inputs_embeds is not None:
  184. batch_size, seq_length, _ = inputs_embeds.shape
  185. else:
  186. raise ValueError("You have to specify either input_is or inputs_embeds")
  187. if position_ids is None:
  188. device = input_ids.device if input_ids is not None else inputs_embeds.device
  189. past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
  190. position_ids = torch.arange(
  191. past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
  192. )
  193. position_ids = position_ids.unsqueeze(0)
  194. if inputs_embeds is None:
  195. inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
  196. if image_patches is not None:
  197. patch_embeddings = self.get_image_features(image_patches)
  198. patch_embeddings = torch.cat(patch_embeddings, dim=0).to(inputs_embeds.device, inputs_embeds.dtype)
  199. special_image_mask = self.get_placeholder_mask(
  200. input_ids, inputs_embeds=inputs_embeds, image_features=patch_embeddings
  201. )
  202. inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, patch_embeddings)
  203. outputs = self.language_model(
  204. inputs_embeds=inputs_embeds,
  205. attention_mask=attention_mask,
  206. position_ids=position_ids,
  207. past_key_values=past_key_values,
  208. output_attentions=output_attentions,
  209. output_hidden_states=output_hidden_states,
  210. use_cache=use_cache,
  211. return_dict=return_dict,
  212. **kwargs,
  213. )
  214. return outputs
  215. @auto_docstring(
  216. custom_intro="""
  217. Fuyu Model with a language modeling head on top for causal language model conditioned on image patches and text.
  218. """
  219. )
  220. class FuyuForCausalLM(FuyuPreTrainedModel, GenerationMixin):
  221. _checkpoint_conversion_mapping = {
  222. "^language_model.model": "model.language_model",
  223. "^vision_embed_tokens": "model.vision_embed_tokens",
  224. "^language_model.lm_head": "lm_head",
  225. }
  226. _tied_weights_keys = ["lm_head.weight"]
  227. def __init__(self, config: FuyuConfig):
  228. super().__init__(config)
  229. self.model = FuyuModel(config)
  230. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  231. self.post_init()
  232. def get_input_embeddings(self):
  233. return self.model.get_input_embeddings()
  234. def set_input_embeddings(self, value):
  235. self.model.set_input_embeddings(value)
  236. def set_decoder(self, decoder):
  237. self.model.set_decoder(decoder)
  238. def get_decoder(self):
  239. return self.model.get_decoder()
  240. @can_return_tuple
  241. @auto_docstring
  242. def forward(
  243. self,
  244. input_ids: Optional[torch.LongTensor] = None,
  245. # [batch_size, num_total_patches, patch_size_ x patch_size x num_channels ]
  246. image_patches: Optional[torch.Tensor] = None,
  247. image_patches_indices: Optional[torch.Tensor] = None,
  248. attention_mask: Optional[torch.Tensor] = None,
  249. position_ids: Optional[torch.LongTensor] = None,
  250. past_key_values: Optional[Cache] = None,
  251. inputs_embeds: Optional[torch.FloatTensor] = None,
  252. use_cache: Optional[bool] = None,
  253. labels: Optional[torch.Tensor] = None,
  254. output_attentions: Optional[bool] = None,
  255. output_hidden_states: Optional[bool] = None,
  256. return_dict: Optional[bool] = None,
  257. logits_to_keep: Optional[int] = 0,
  258. **kwargs,
  259. ) -> Union[tuple, CausalLMOutputWithPast]:
  260. r"""
  261. image_patches (`torch.FloatTensor` of shape `(batch_size, num_total_patches, patch_size_ x patch_size x num_channels)`, *optional*):
  262. Image patches to be used as continuous embeddings. The patches are flattened and then projected to the
  263. hidden size of the model.
  264. image_patches_indices (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  265. Tensor of indices of the image patches in the input_ids tensor.
  266. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  267. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  268. config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  269. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
  270. Examples:
  271. ```python
  272. >>> from transformers import FuyuProcessor, FuyuForCausalLM
  273. >>> from PIL import Image
  274. >>> import requests
  275. >>> processor = FuyuProcessor.from_pretrained("adept/fuyu-8b")
  276. >>> model = FuyuForCausalLM.from_pretrained("adept/fuyu-8b")
  277. >>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png"
  278. >>> image = Image.open(requests.get(url, stream=True).raw)
  279. >>> prompt = "Generate a coco-style caption.\n"
  280. >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
  281. >>> outputs = model(**inputs)
  282. >>> generated_ids = model.generate(**inputs, max_new_tokens=7)
  283. >>> generation_text = processor.batch_decode(generated_ids[:, -7:], skip_special_tokens=True)
  284. >>> print(generation_text[0])
  285. A blue bus parked on the side of a road.
  286. ```"""
  287. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  288. output_hidden_states = (
  289. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  290. )
  291. use_cache = use_cache if use_cache is not None else self.config.use_cache
  292. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  293. outputs = self.model(
  294. input_ids=input_ids,
  295. image_patches=image_patches,
  296. image_patches_indices=image_patches_indices,
  297. inputs_embeds=inputs_embeds,
  298. attention_mask=attention_mask,
  299. position_ids=position_ids,
  300. past_key_values=past_key_values,
  301. output_attentions=output_attentions,
  302. output_hidden_states=output_hidden_states,
  303. use_cache=use_cache,
  304. return_dict=True,
  305. # don't pass kwargs because Persimmon-backbone doesn't accept FA2 kwargs yet, TODO: raushan
  306. )
  307. hidden_states = outputs[0]
  308. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  309. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  310. logits = self.lm_head(hidden_states[:, slice_indices, :])
  311. loss = None
  312. if labels is not None:
  313. loss = self.loss_function(
  314. logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
  315. )
  316. return CausalLMOutputWithPast(
  317. loss=loss,
  318. logits=logits,
  319. past_key_values=outputs.past_key_values,
  320. hidden_states=outputs.hidden_states,
  321. attentions=outputs.attentions,
  322. )
  323. def prepare_inputs_for_generation(
  324. self,
  325. input_ids,
  326. past_key_values=None,
  327. attention_mask=None,
  328. inputs_embeds=None,
  329. image_patches=None,
  330. image_patches_indices=None,
  331. cache_position=None,
  332. **kwargs,
  333. ):
  334. # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
  335. model_inputs = super().prepare_inputs_for_generation(
  336. input_ids,
  337. past_key_values=past_key_values,
  338. attention_mask=attention_mask,
  339. inputs_embeds=inputs_embeds,
  340. image_patches=image_patches,
  341. image_patches_indices=image_patches_indices,
  342. cache_position=cache_position,
  343. **kwargs,
  344. )
  345. if cache_position[0] != 0:
  346. # set image_patches and image_patches_indices to `None` for decoding stage
  347. model_inputs["image_patches_indices"] = None
  348. model_inputs["image_patches"] = None
  349. return model_inputs
  350. __all__ = ["FuyuForCausalLM", "FuyuPreTrainedModel", "FuyuModel"]