llava.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import itertools
  2. from typing import (Iterable, List, Literal, Mapping, Optional, Tuple,
  3. TypedDict, Union)
  4. import torch
  5. import torch.nn as nn
  6. from transformers import CLIPVisionConfig, LlavaConfig, SiglipVisionConfig
  7. from aphrodite.attention import AttentionMetadata
  8. from aphrodite.common.config import CacheConfig, MultiModalConfig
  9. from aphrodite.common.sequence import IntermediateTensors, SamplerOutput
  10. from aphrodite.inputs import INPUT_REGISTRY, InputContext, LLMInputs
  11. from aphrodite.modeling.layers.activation import get_act_fn
  12. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  13. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  14. from aphrodite.multimodal import MULTIMODAL_REGISTRY
  15. from aphrodite.quantization.base_config import QuantizationConfig
  16. from .clip import (CLIPVisionModel, dummy_image_for_clip,
  17. dummy_seq_data_for_clip, get_max_clip_image_tokens,
  18. input_processor_for_clip)
  19. from .interfaces import SupportsMultiModal
  20. from .siglip import (SiglipVisionModel, dummy_image_for_siglip,
  21. dummy_seq_data_for_siglip, get_max_siglip_image_tokens,
  22. input_processor_for_siglip)
  23. from .utils import (filter_weights, init_aphrodite_registered_model,
  24. merge_multimodal_embeddings)
  25. class LlavaImagePixelInputs(TypedDict):
  26. type: Literal["pixel_values"]
  27. data: torch.Tensor
  28. """Shape: `(batch_size, num_channels, height, width)`"""
  29. class LlavaImageEmbeddingInputs(TypedDict):
  30. type: Literal["image_embeds"]
  31. data: torch.Tensor
  32. """Shape: `(batch_size, image_feature_size, hidden_size)`
  33. `hidden_size` must match the hidden size of language model backbone.
  34. """
  35. LlavaImageInputs = Union[LlavaImagePixelInputs, LlavaImageEmbeddingInputs]
  36. # TODO: Run benchmark and decide if TP.
  37. class LlavaMultiModalProjector(nn.Module):
  38. def __init__(self, vision_hidden_size: int, text_hidden_size: int,
  39. projector_hidden_act: str):
  40. super().__init__()
  41. self.linear_1 = nn.Linear(vision_hidden_size,
  42. text_hidden_size,
  43. bias=True)
  44. self.act = get_act_fn(projector_hidden_act)
  45. self.linear_2 = nn.Linear(text_hidden_size,
  46. text_hidden_size,
  47. bias=True)
  48. def forward(self, image_features: torch.Tensor) -> torch.Tensor:
  49. hidden_states = self.linear_1(image_features)
  50. hidden_states = self.act(hidden_states)
  51. hidden_states = self.linear_2(hidden_states)
  52. return hidden_states
  53. def get_max_llava_image_tokens(ctx: InputContext):
  54. hf_config = ctx.get_hf_config(LlavaConfig)
  55. vision_config = hf_config.vision_config
  56. if isinstance(vision_config, CLIPVisionConfig):
  57. num_image_tokens = get_max_clip_image_tokens(vision_config)
  58. elif isinstance(vision_config, SiglipVisionConfig):
  59. num_image_tokens = get_max_siglip_image_tokens(vision_config)
  60. else:
  61. msg = f"Unsupported vision config: {type(vision_config)}"
  62. raise NotImplementedError(msg)
  63. strategy = hf_config.vision_feature_select_strategy
  64. if strategy == "default":
  65. return num_image_tokens - 1
  66. elif strategy == "full":
  67. return num_image_tokens
  68. else:
  69. raise ValueError(f"Unexpected select feature strategy: {strategy}")
  70. def dummy_data_for_llava(ctx: InputContext, seq_len: int,
  71. mm_counts: Mapping[str, int]):
  72. hf_config = ctx.get_hf_config(LlavaConfig)
  73. vision_config = hf_config.vision_config
  74. num_images = mm_counts["image"]
  75. image_feature_size = get_max_llava_image_tokens(ctx)
  76. if isinstance(vision_config, CLIPVisionConfig):
  77. seq_data = dummy_seq_data_for_clip(
  78. vision_config,
  79. seq_len,
  80. num_images,
  81. image_token_id=hf_config.image_token_index,
  82. image_feature_size_override=image_feature_size,
  83. )
  84. mm_data = dummy_image_for_clip(vision_config, num_images)
  85. return seq_data, mm_data
  86. elif isinstance(vision_config, SiglipVisionConfig):
  87. seq_data = dummy_seq_data_for_siglip(
  88. vision_config,
  89. seq_len,
  90. num_images,
  91. image_token_id=hf_config.image_token_index,
  92. image_feature_size_override=image_feature_size,
  93. )
  94. mm_data = dummy_image_for_siglip(vision_config, num_images)
  95. return seq_data, mm_data
  96. msg = f"Unsupported vision config: {type(vision_config)}"
  97. raise NotImplementedError(msg)
  98. def input_processor_for_llava(ctx: InputContext, llm_inputs: LLMInputs):
  99. multi_modal_data = llm_inputs.get("multi_modal_data")
  100. if multi_modal_data is None or "image" not in multi_modal_data:
  101. return llm_inputs
  102. model_config = ctx.model_config
  103. hf_config = ctx.get_hf_config(LlavaConfig)
  104. vision_config = hf_config.vision_config
  105. image_feature_size = get_max_llava_image_tokens(ctx)
  106. if isinstance(vision_config, CLIPVisionConfig):
  107. return input_processor_for_clip(
  108. model_config,
  109. vision_config,
  110. llm_inputs,
  111. image_token_id=hf_config.image_token_index,
  112. image_feature_size_override=image_feature_size,
  113. )
  114. elif isinstance(vision_config, SiglipVisionConfig):
  115. return input_processor_for_siglip(
  116. model_config,
  117. vision_config,
  118. llm_inputs,
  119. image_token_id=hf_config.image_token_index,
  120. image_feature_size_override=image_feature_size,
  121. )
  122. msg = f"Unsupported vision config: {type(vision_config)}"
  123. raise NotImplementedError(msg)
  124. def _init_vision_tower(hf_config: LlavaConfig):
  125. vision_config = hf_config.vision_config
  126. # Initialize the vision tower only up to the required feature layer
  127. vision_feature_layer = hf_config.vision_feature_layer
  128. if vision_feature_layer < 0:
  129. num_hidden_layers = hf_config.vision_config.num_hidden_layers \
  130. + vision_feature_layer + 1
  131. else:
  132. num_hidden_layers = vision_feature_layer + 1
  133. if isinstance(vision_config, CLIPVisionConfig):
  134. return CLIPVisionModel(
  135. vision_config,
  136. num_hidden_layers_override=num_hidden_layers,
  137. )
  138. elif isinstance(vision_config, SiglipVisionConfig):
  139. return SiglipVisionModel(
  140. vision_config,
  141. num_hidden_layers_override=num_hidden_layers,
  142. )
  143. msg = f"Unsupported vision config: {type(vision_config)}"
  144. raise NotImplementedError(msg)
  145. @MULTIMODAL_REGISTRY.register_image_input_mapper()
  146. @MULTIMODAL_REGISTRY.register_max_image_tokens(get_max_llava_image_tokens)
  147. @INPUT_REGISTRY.register_dummy_data(dummy_data_for_llava)
  148. @INPUT_REGISTRY.register_input_processor(input_processor_for_llava)
  149. class LlavaForConditionalGeneration(nn.Module, SupportsMultiModal):
  150. def __init__(self,
  151. config: LlavaConfig,
  152. multimodal_config: MultiModalConfig,
  153. cache_config: Optional[CacheConfig] = None,
  154. quant_config: Optional[QuantizationConfig] = None) -> None:
  155. super().__init__()
  156. self.config = config
  157. self.multimodal_config = multimodal_config
  158. # TODO: Optionally initializes this for supporting embeddings.
  159. self.vision_tower = _init_vision_tower(config)
  160. self.multi_modal_projector = LlavaMultiModalProjector(
  161. vision_hidden_size=config.vision_config.hidden_size,
  162. text_hidden_size=config.text_config.hidden_size,
  163. projector_hidden_act=config.projector_hidden_act)
  164. self.language_model = init_aphrodite_registered_model(
  165. config.text_config, cache_config, quant_config)
  166. def _validate_pixel_values(self, data: torch.Tensor) -> torch.Tensor:
  167. h = w = self.config.vision_config.image_size
  168. expected_dims = (3, h, w)
  169. actual_dims = tuple(data.shape[1:])
  170. if actual_dims != expected_dims:
  171. expected_expr = ("batch_size", *map(str, expected_dims))
  172. raise ValueError(
  173. f"The expected shape of pixel values is {expected_expr}. "
  174. f"You supplied {tuple(data.shape)}.")
  175. return data
  176. def _parse_and_validate_image_input(
  177. self, **kwargs: object) -> Optional[LlavaImageInputs]:
  178. pixel_values = kwargs.pop("pixel_values", None)
  179. image_embeds = kwargs.pop("image_embeds", None)
  180. if pixel_values is None and image_embeds is None:
  181. return None
  182. if pixel_values is not None:
  183. if not isinstance(pixel_values, torch.Tensor):
  184. raise ValueError("Incorrect type of pixel values. "
  185. f"Got type: {type(pixel_values)}")
  186. return LlavaImagePixelInputs(
  187. type="pixel_values",
  188. data=self._validate_pixel_values(pixel_values),
  189. )
  190. if image_embeds is not None:
  191. if not isinstance(image_embeds, torch.Tensor):
  192. raise ValueError("Incorrect type of image embeddings. "
  193. f"Got type: {type(image_embeds)}")
  194. return LlavaImageEmbeddingInputs(
  195. type="image_embeds",
  196. data=image_embeds,
  197. )
  198. raise AssertionError("This line should be unreachable.")
  199. def _select_image_features(self, image_features: torch.Tensor, *,
  200. strategy: str) -> torch.Tensor:
  201. # Copied from https://github.com/huggingface/transformers/blob/39c3c0a72af6fbda5614dde02ff236069bb79827/src/transformers/models/llava/modeling_llava.py#L421 # noqa
  202. if strategy == "default":
  203. return image_features[:, 1:]
  204. elif strategy == "full":
  205. return image_features
  206. raise ValueError(f"Unexpected select feature strategy: {strategy}")
  207. def _image_pixels_to_features(
  208. self,
  209. vision_tower: Union[CLIPVisionModel, SiglipVisionModel],
  210. pixel_values: torch.Tensor,
  211. ) -> torch.Tensor:
  212. # NOTE: we skip the step to select the vision feature layer since
  213. # this is already done inside the vision tower
  214. image_features = vision_tower(pixel_values)
  215. return self._select_image_features(
  216. image_features,
  217. strategy=self.config.vision_feature_select_strategy,
  218. )
  219. def _process_image_pixels(self,
  220. inputs: LlavaImagePixelInputs) -> torch.Tensor:
  221. assert self.vision_tower is not None
  222. pixel_values = inputs["data"]
  223. return self._image_pixels_to_features(self.vision_tower, pixel_values)
  224. def _process_image_input(self,
  225. image_input: LlavaImageInputs) -> torch.Tensor:
  226. if image_input["type"] == "image_embeds":
  227. return image_input["data"]
  228. assert self.vision_tower is not None
  229. image_features = self._process_image_pixels(image_input)
  230. return self.multi_modal_projector(image_features)
  231. def forward(
  232. self,
  233. input_ids: torch.Tensor,
  234. positions: torch.Tensor,
  235. kv_caches: List[torch.Tensor],
  236. attn_metadata: AttentionMetadata,
  237. intermediate_tensors: Optional[IntermediateTensors] = None,
  238. **kwargs: object,
  239. ) -> SamplerOutput:
  240. """Run forward pass for LLaVA-1.5.
  241. One key thing to understand is the `input_ids` already accounts for the
  242. positions of the to-be-inserted image embeddings.
  243. Concretely, consider a text prompt:
  244. `"USER: <image>\\nWhat's the content of the image?\\nASSISTANT:"`.
  245. Tokenizer outputs:
  246. `[1, 3148, 1001, 29901, 29871, 32000, 29871, 13, 5618, 29915, 29879,
  247. 278, 2793, 310, 278, 1967, 29973, 13, 22933, 9047, 13566, 29901]`.
  248. To reserve space in KV cache, we have to insert placeholder tokens
  249. before they are inputted to the model, so the input processor prepends
  250. additional image tokens (denoted as `32000`), resulting in:
  251. `[1, 3148, 1001, 29901, 29871, 32000, ..., 32000, 29871, 13, 5618,
  252. 29915, 29879, 278, 2793, 310, 278, 1967, 29973, 13, 22933, 9047, 13566,
  253. 29901]`.
  254. We insert 575 tokens so that including the original image token in the
  255. input, there are a total of 576 (24 * 24) image tokens, which
  256. corresponds to the number of image tokens inputted to the language
  257. model, i.e. the number of image tokens outputted by the visual encoder.
  258. This way, the `positions` and `attn_metadata` are consistent
  259. with the `input_ids`.
  260. Args:
  261. input_ids: Flattened (concatenated) input_ids corresponding to a
  262. batch.
  263. pixel_values: The pixels in each input image.
  264. See also:
  265. :class:`LlavaImageInputs`
  266. """
  267. image_input = self._parse_and_validate_image_input(**kwargs)
  268. if image_input is not None:
  269. vision_embeddings = self._process_image_input(image_input)
  270. inputs_embeds = self.language_model.model.get_input_embeddings(
  271. input_ids)
  272. inputs_embeds = merge_multimodal_embeddings(
  273. input_ids, inputs_embeds, vision_embeddings,
  274. self.config.image_token_index)
  275. input_ids = None
  276. else:
  277. inputs_embeds = None
  278. hidden_states = self.language_model.model(input_ids,
  279. positions,
  280. kv_caches,
  281. attn_metadata,
  282. None,
  283. inputs_embeds=inputs_embeds)
  284. return hidden_states
  285. def compute_logits(
  286. self,
  287. hidden_states: torch.Tensor,
  288. sampling_metadata: SamplingMetadata,
  289. ) -> Optional[torch.Tensor]:
  290. return self.language_model.compute_logits(hidden_states,
  291. sampling_metadata)
  292. def sample(
  293. self,
  294. logits: torch.Tensor,
  295. sampling_metadata: SamplingMetadata,
  296. ) -> Optional[SamplerOutput]:
  297. return self.language_model.sample(logits, sampling_metadata)
  298. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  299. # prepare weight iterators for components
  300. vit_weights, mlp_weights, llm_weights = itertools.tee(weights, 3)
  301. # load vision encoder
  302. vit_weights = filter_weights(vit_weights, "vision_tower")
  303. self.vision_tower.load_weights(vit_weights)
  304. # load mlp projector
  305. mlp_weights = filter_weights(mlp_weights, "multi_modal_projector")
  306. mlp_params_dict = dict(self.multi_modal_projector.named_parameters())
  307. for name, loaded_weight in mlp_weights:
  308. param = mlp_params_dict[name]
  309. weight_loader = getattr(param, "weight_loader",
  310. default_weight_loader)
  311. weight_loader(param, loaded_weight)
  312. # load llm backbone
  313. llm_weights = filter_weights(llm_weights, "language_model")
  314. self.language_model.load_weights(llm_weights)