llava_next.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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 PIL import Image
  7. from transformers import CLIPVisionConfig, LlavaNextConfig, SiglipVisionConfig
  8. from transformers.models.llava_next.modeling_llava_next import (
  9. get_anyres_image_grid_shape, unpad_image)
  10. from typing_extensions import NotRequired
  11. from aphrodite.attention import AttentionMetadata
  12. from aphrodite.common.config import CacheConfig, MultiModalConfig
  13. from aphrodite.common.sequence import IntermediateTensors
  14. from aphrodite.common.utils import is_list_of
  15. from aphrodite.inputs import INPUT_REGISTRY, InputContext, LLMInputs
  16. from aphrodite.modeling.layers.sampler import SamplerOutput
  17. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  18. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  19. from aphrodite.multimodal import MULTIMODAL_REGISTRY
  20. from aphrodite.quantization.base_config import QuantizationConfig
  21. from .clip import (CLIPVisionModel, dummy_image_for_clip,
  22. dummy_seq_data_for_clip, get_clip_image_feature_size,
  23. get_clip_patch_grid_length, input_processor_for_clip)
  24. from .interfaces import SupportsMultiModal
  25. from .llava import LlavaMultiModalProjector
  26. from .siglip import (SiglipVisionModel, dummy_image_for_siglip,
  27. dummy_seq_data_for_siglip, get_siglip_image_feature_size,
  28. get_siglip_patch_grid_length, input_processor_for_siglip)
  29. from .utils import (filter_weights, flatten_bn,
  30. init_aphrodite_registered_model,
  31. merge_multimodal_embeddings)
  32. _KEYS_TO_MODIFY_MAPPING = {
  33. "language_model.lm_head": "lm_head",
  34. "language_model.model": "language_model",
  35. }
  36. # Result in the max possible feature size (2x2 grid of 336x336px tiles)
  37. MAX_IMAGE_FEATURE_SIZE_HEIGHT = MAX_IMAGE_FEATURE_SIZE_WIDTH = 448
  38. class LlavaNextImagePixelInputs(TypedDict):
  39. type: Literal["pixel_values"]
  40. data: Union[torch.Tensor, List[torch.Tensor]]
  41. """
  42. Shape:
  43. `(batch_size * num_images, 1 + num_patches, num_channels, height, width)`
  44. Note that `num_patches` may be different per batch and image,
  45. in which case the data is passed as a list instead of a batched tensor.
  46. """
  47. image_sizes: NotRequired[torch.Tensor]
  48. """
  49. Shape: `(batch_size * num_images, 2)`
  50. This should be in `(height, width)` format.
  51. """
  52. class LlavaNextImageEmbeddingInputs(TypedDict):
  53. type: Literal["image_embeds"]
  54. data: torch.Tensor
  55. """Shape: `(batch_size * num_images, image_feature_size, hidden_size)`
  56. `hidden_size` must match the hidden size of language model backbone.
  57. """
  58. LlavaNextImageInputs = Union[LlavaNextImagePixelInputs,
  59. LlavaNextImageEmbeddingInputs]
  60. # Based on: https://github.com/huggingface/text-generation-inference/blob/v2.2.0/server/text_generation_server/models/vlm_causal_lm.py#L79
  61. def _get_llava_next_num_unpadded_features(
  62. original_height: int,
  63. original_width: int,
  64. npatches: int,
  65. num_patch_height: int,
  66. num_patch_width: int,
  67. ) -> Tuple[int, int]:
  68. current_height = npatches * num_patch_height
  69. current_width = npatches * num_patch_width
  70. aspect_ratio = original_width / original_height
  71. current_aspect_ratio = current_width / current_height
  72. if aspect_ratio > current_aspect_ratio:
  73. new_height = (original_height * current_width) // original_width
  74. padding = (current_height - new_height) // 2
  75. current_height -= padding * 2
  76. else:
  77. new_width = (original_width * current_height) // original_height
  78. padding = (current_width - new_width) // 2
  79. current_width -= padding * 2
  80. unpadded_features = current_height * current_width
  81. newline_features = current_height
  82. return (unpadded_features, newline_features)
  83. # Based on: https://github.com/huggingface/text-generation-inference/blob/v2.2.0/server/text_generation_server/models/vlm_causal_lm.py#L106
  84. def get_llava_next_image_feature_size(
  85. hf_config: LlavaNextConfig,
  86. *,
  87. input_height: int,
  88. input_width: int,
  89. ) -> int:
  90. vision_config = hf_config.vision_config
  91. if isinstance(vision_config, CLIPVisionConfig):
  92. num_patches = get_clip_patch_grid_length(
  93. image_size=vision_config.image_size,
  94. patch_size=vision_config.patch_size,
  95. )
  96. base_feature_size = get_clip_image_feature_size(vision_config)
  97. elif isinstance(vision_config, SiglipVisionConfig):
  98. num_patches = get_siglip_patch_grid_length(
  99. image_size=vision_config.image_size,
  100. patch_size=vision_config.patch_size,
  101. )
  102. base_feature_size = get_siglip_image_feature_size(vision_config)
  103. else:
  104. msg = f"Unsupported vision config: {type(vision_config)}"
  105. raise NotImplementedError(msg)
  106. strategy = hf_config.vision_feature_select_strategy
  107. if strategy == "default":
  108. base_feature_size -= 1
  109. elif strategy == "full":
  110. pass
  111. else:
  112. raise ValueError(f"Unexpected select feature strategy: {strategy}")
  113. num_patch_height, num_patch_width = get_anyres_image_grid_shape(
  114. image_size=(input_height, input_width),
  115. grid_pinpoints=hf_config.image_grid_pinpoints,
  116. patch_size=vision_config.image_size,
  117. )
  118. (
  119. unpadded_feature_size,
  120. newline_feature_size,
  121. ) = _get_llava_next_num_unpadded_features(input_height, input_width,
  122. num_patches, num_patch_height,
  123. num_patch_width)
  124. return unpadded_feature_size + newline_feature_size + base_feature_size
  125. def get_max_llava_next_image_tokens(ctx: InputContext):
  126. return get_llava_next_image_feature_size(
  127. ctx.get_hf_config(LlavaNextConfig),
  128. input_height=MAX_IMAGE_FEATURE_SIZE_HEIGHT,
  129. input_width=MAX_IMAGE_FEATURE_SIZE_WIDTH,
  130. )
  131. def dummy_data_for_llava_next(ctx: InputContext, seq_len: int,
  132. mm_counts: Mapping[str, int]):
  133. hf_config = ctx.get_hf_config(LlavaNextConfig)
  134. vision_config = hf_config.vision_config
  135. num_images = mm_counts["image"]
  136. image_feature_size = get_max_llava_next_image_tokens(ctx)
  137. if isinstance(vision_config, CLIPVisionConfig):
  138. seq_data = dummy_seq_data_for_clip(
  139. vision_config,
  140. seq_len,
  141. num_images,
  142. image_token_id=hf_config.image_token_index,
  143. image_feature_size_override=image_feature_size,
  144. )
  145. mm_data = dummy_image_for_clip(
  146. vision_config,
  147. num_images,
  148. image_width_override=MAX_IMAGE_FEATURE_SIZE_WIDTH,
  149. image_height_override=MAX_IMAGE_FEATURE_SIZE_HEIGHT,
  150. )
  151. return seq_data, mm_data
  152. elif isinstance(vision_config, SiglipVisionConfig):
  153. seq_data = dummy_seq_data_for_siglip(
  154. vision_config,
  155. seq_len,
  156. num_images,
  157. image_token_id=hf_config.image_token_index,
  158. image_feature_size_override=image_feature_size,
  159. )
  160. mm_data = dummy_image_for_siglip(
  161. vision_config,
  162. num_images,
  163. image_width_override=MAX_IMAGE_FEATURE_SIZE_WIDTH,
  164. image_height_override=MAX_IMAGE_FEATURE_SIZE_HEIGHT,
  165. )
  166. return seq_data, mm_data
  167. msg = f"Unsupported vision config: {type(vision_config)}"
  168. raise NotImplementedError(msg)
  169. def input_processor_for_llava_next(ctx: InputContext, llm_inputs: LLMInputs):
  170. multi_modal_data = llm_inputs.get("multi_modal_data")
  171. if multi_modal_data is None or "image" not in multi_modal_data:
  172. return llm_inputs
  173. model_config = ctx.model_config
  174. hf_config = ctx.get_hf_config(LlavaNextConfig)
  175. vision_config = hf_config.vision_config
  176. image_data = multi_modal_data["image"]
  177. if isinstance(image_data, Image.Image):
  178. width, height = image_data.size
  179. image_feature_size = get_llava_next_image_feature_size(
  180. hf_config,
  181. input_height=height,
  182. input_width=width,
  183. )
  184. elif is_list_of(image_data, Image.Image):
  185. image_feature_size = [
  186. get_llava_next_image_feature_size(hf_config,
  187. input_height=img.height,
  188. input_width=img.width)
  189. for img in image_data
  190. ]
  191. elif isinstance(image_data, torch.Tensor):
  192. num_images, image_feature_size, hidden_size = image_data.shape
  193. elif is_list_of(image_data, torch.Tensor):
  194. image_feature_size = [item.shape[1] for item in image_data]
  195. else:
  196. raise TypeError(f"Invalid image type: {type(image_data)}")
  197. vision_config = hf_config.vision_config
  198. if isinstance(vision_config, CLIPVisionConfig):
  199. return input_processor_for_clip(
  200. model_config,
  201. vision_config,
  202. llm_inputs,
  203. image_token_id=hf_config.image_token_index,
  204. image_feature_size_override=image_feature_size,
  205. )
  206. elif isinstance(vision_config, SiglipVisionConfig):
  207. return input_processor_for_siglip(
  208. model_config,
  209. vision_config,
  210. llm_inputs,
  211. image_token_id=hf_config.image_token_index,
  212. image_feature_size_override=image_feature_size,
  213. )
  214. msg = f"Unsupported vision config: {type(vision_config)}"
  215. raise NotImplementedError(msg)
  216. def _init_vision_tower(hf_config: LlavaNextConfig):
  217. vision_config = hf_config.vision_config
  218. # Initialize the vision tower only up to the required feature layer
  219. vision_feature_layer = hf_config.vision_feature_layer
  220. if vision_feature_layer < 0:
  221. num_hidden_layers = hf_config.vision_config.num_hidden_layers \
  222. + vision_feature_layer + 1
  223. else:
  224. num_hidden_layers = vision_feature_layer + 1
  225. if isinstance(vision_config, CLIPVisionConfig):
  226. return CLIPVisionModel(
  227. vision_config,
  228. num_hidden_layers_override=num_hidden_layers,
  229. )
  230. elif isinstance(vision_config, SiglipVisionConfig):
  231. return SiglipVisionModel(
  232. vision_config,
  233. num_hidden_layers_override=num_hidden_layers,
  234. )
  235. msg = f"Unsupported vision config: {type(vision_config)}"
  236. raise NotImplementedError(msg)
  237. @MULTIMODAL_REGISTRY.register_image_input_mapper()
  238. @MULTIMODAL_REGISTRY.register_max_image_tokens(get_max_llava_next_image_tokens)
  239. @INPUT_REGISTRY.register_dummy_data(dummy_data_for_llava_next)
  240. @INPUT_REGISTRY.register_input_processor(input_processor_for_llava_next)
  241. class LlavaNextForConditionalGeneration(nn.Module, SupportsMultiModal):
  242. def __init__(self,
  243. config: LlavaNextConfig,
  244. multimodal_config: MultiModalConfig,
  245. cache_config: Optional[CacheConfig] = None,
  246. quant_config: Optional[QuantizationConfig] = None) -> None:
  247. super().__init__()
  248. self.config = config
  249. self.multimodal_config = multimodal_config
  250. # TODO: Optionally initializes this for supporting embeddings.
  251. self.vision_tower = _init_vision_tower(config)
  252. self.multi_modal_projector = LlavaMultiModalProjector(
  253. vision_hidden_size=config.vision_config.hidden_size,
  254. text_hidden_size=config.text_config.hidden_size,
  255. projector_hidden_act=config.projector_hidden_act)
  256. self.language_model = init_aphrodite_registered_model(
  257. config.text_config, cache_config, quant_config)
  258. self.image_newline = nn.Parameter(
  259. torch.empty(config.text_config.hidden_size))
  260. def _validate_image_sizes(self, data: torch.Tensor) -> torch.Tensor:
  261. expected_dims = (2, )
  262. def _validate_shape(d: torch.Tensor):
  263. actual_dims = tuple(d.shape)
  264. if actual_dims != expected_dims:
  265. expected_expr = str(expected_dims)
  266. raise ValueError(
  267. f"The expected shape of image sizes per image per batch "
  268. f"is {expected_expr}. You supplied {tuple(d.shape)}.")
  269. for d in data:
  270. _validate_shape(d)
  271. return data
  272. def _validate_pixel_values(
  273. self, data: Union[torch.Tensor, List[torch.Tensor]]
  274. ) -> Union[torch.Tensor, List[torch.Tensor]]:
  275. h = w = self.config.vision_config.image_size
  276. expected_dims = (3, h, w)
  277. def _validate_shape(d: torch.Tensor):
  278. actual_dims = tuple(d.shape[1:])
  279. if actual_dims != expected_dims:
  280. expected_expr = ("num_patches", *map(str, expected_dims))
  281. raise ValueError(
  282. "The expected shape of pixel values per image per batch "
  283. f"is {expected_expr}. You supplied {tuple(d.shape)}.")
  284. for d in data:
  285. _validate_shape(d)
  286. return data
  287. def _parse_and_validate_image_input(
  288. self, **kwargs: object) -> Optional[LlavaNextImageInputs]:
  289. pixel_values = kwargs.pop("pixel_values", None)
  290. image_sizes = kwargs.pop("image_sizes", None)
  291. image_embeds = kwargs.pop("image_embeds", None)
  292. if pixel_values is None and image_embeds is None:
  293. return None
  294. if pixel_values is not None:
  295. if not isinstance(pixel_values, (torch.Tensor, list)):
  296. raise ValueError("Incorrect type of pixel values. "
  297. f"Got type: {type(pixel_values)}")
  298. if not isinstance(image_sizes, (torch.Tensor, list)):
  299. raise ValueError("Incorrect type of image sizes. "
  300. f"Got type: {type(image_sizes)}")
  301. return LlavaNextImagePixelInputs(
  302. type="pixel_values",
  303. data=self._validate_pixel_values(flatten_bn(pixel_values)),
  304. image_sizes=self._validate_image_sizes(
  305. flatten_bn(image_sizes, concat=True)),
  306. )
  307. if image_embeds is not None:
  308. if not isinstance(image_embeds, torch.Tensor):
  309. raise ValueError("Incorrect type of image embeds. "
  310. f"Got type: {type(image_embeds)}")
  311. return LlavaNextImageEmbeddingInputs(
  312. type="image_embeds",
  313. data=flatten_bn(image_embeds),
  314. )
  315. raise AssertionError("This line should be unreachable.")
  316. def _select_image_features(self, image_features: torch.Tensor, *,
  317. strategy: str) -> torch.Tensor:
  318. # Copied from https://github.com/huggingface/transformers/blob/39c3c0a72af6fbda5614dde02ff236069bb79827/src/transformers/models/llava/modeling_llava.py#L421 # noqa
  319. if strategy == "default":
  320. return image_features[:, 1:]
  321. elif strategy == "full":
  322. return image_features
  323. raise ValueError(f"Unexpected select feature strategy: {strategy}")
  324. def _image_pixels_to_features(
  325. self,
  326. vision_tower: Union[CLIPVisionModel, SiglipVisionModel],
  327. pixel_values: torch.Tensor,
  328. ) -> torch.Tensor:
  329. # NOTE: we skip the step to select the vision feature layer since
  330. # this is already done inside the vision tower
  331. image_features = vision_tower(pixel_values)
  332. return self._select_image_features(
  333. image_features,
  334. strategy=self.config.vision_feature_select_strategy,
  335. )
  336. # Based on: https://github.com/haotian-liu/LLaVA/blob/main/llava/model/llava_arch.py
  337. def _merge_image_patch_embeddings(self, image_size: torch.Tensor,
  338. patch_embeddings: torch.Tensor, *,
  339. strategy: str) -> torch.Tensor:
  340. if strategy == "flat":
  341. return patch_embeddings.flatten(0, 1)
  342. if strategy.startswith("spatial"):
  343. height = width = self.config.vision_config.image_size \
  344. // self.config.vision_config.patch_size
  345. base_patch_embeds = patch_embeddings[0]
  346. if height * width != base_patch_embeds.shape[0]:
  347. raise ValueError(
  348. "The number of patches is not consistent with the "
  349. "image size.")
  350. if patch_embeddings.shape[0] > 1:
  351. other_patch_embeds = patch_embeddings[1:]
  352. # Move to CPU to avoid floating-point errors
  353. orig_height, orig_width = image_size.tolist()
  354. # image_aspect_ratio == "anyres"
  355. num_patch_height, num_patch_width = get_anyres_image_grid_shape(
  356. (orig_height, orig_width),
  357. self.config.image_grid_pinpoints,
  358. self.config.vision_config.image_size,
  359. )
  360. num_patches = num_patch_height * num_patch_width
  361. # Image patches might be padded for batch processing
  362. other_patch_embeds = other_patch_embeds[:num_patches] \
  363. .view(num_patch_height, num_patch_width, height, width, -1)
  364. if "unpad" in strategy:
  365. other_patch_embeds = other_patch_embeds \
  366. .permute(4, 0, 2, 1, 3).contiguous() \
  367. .flatten(1, 2).flatten(2, 3)
  368. other_patch_embeds = unpad_image(other_patch_embeds,
  369. (orig_height, orig_width))
  370. other_patch_embeds = torch.cat((
  371. other_patch_embeds,
  372. self.image_newline[:, None, None] \
  373. .expand(*other_patch_embeds.shape[:-1], 1) \
  374. .to(other_patch_embeds.device),
  375. ), dim=-1)
  376. other_patch_embeds = other_patch_embeds \
  377. .flatten(1, 2).transpose(0, 1)
  378. else:
  379. other_patch_embeds = other_patch_embeds \
  380. .permute(0, 2, 1, 3, 4).contiguous() \
  381. .flatten(0, 3)
  382. merged_patch_embeddings = torch.cat(
  383. (base_patch_embeds, other_patch_embeds), dim=0)
  384. else:
  385. if "unpad" in strategy:
  386. merged_patch_embeddings = torch.cat(
  387. (base_patch_embeds,
  388. self.image_newline[None] \
  389. .to(base_patch_embeds.device)
  390. ), dim=0)
  391. else:
  392. merged_patch_embeddings = base_patch_embeds
  393. return merged_patch_embeddings
  394. raise ValueError(f"Unexpected patch merge strategy: {strategy}")
  395. def _process_image_pixels(
  396. self,
  397. inputs: LlavaNextImagePixelInputs,
  398. ) -> Union[torch.Tensor, List[torch.Tensor]]:
  399. assert self.vision_tower is not None
  400. pixel_values = inputs["data"]
  401. if isinstance(pixel_values, torch.Tensor):
  402. b, num_patches, c, h, w = pixel_values.shape
  403. stacked_pixel_values = pixel_values.view(b * num_patches, c, h, w)
  404. stacked_image_features = self._image_pixels_to_features(
  405. self.vision_tower, stacked_pixel_values)
  406. stacked_patch_embeddings = self.multi_modal_projector(
  407. stacked_image_features)
  408. return stacked_patch_embeddings.view(
  409. b, num_patches, *stacked_patch_embeddings.shape[1:])
  410. num_patches_per_batch = [v.shape[0] for v in pixel_values]
  411. stacked_pixel_values = torch.cat(pixel_values)
  412. stacked_image_features = self._image_pixels_to_features(
  413. self.vision_tower, stacked_pixel_values)
  414. return [
  415. self.multi_modal_projector(image_features) for image_features in
  416. torch.split(stacked_image_features, num_patches_per_batch)
  417. ]
  418. def _process_image_input(
  419. self,
  420. image_input: LlavaNextImageInputs,
  421. ) -> Union[torch.Tensor, List[torch.Tensor]]:
  422. if image_input["type"] == "image_embeds":
  423. return [image_input["data"]]
  424. patch_embeddings = self._process_image_pixels(image_input)
  425. image_sizes = image_input.get("image_sizes")
  426. if image_sizes is None:
  427. batch_size = len(image_input["data"])
  428. vision_config = self.config.vision_config
  429. default_height = default_width = vision_config.image_size
  430. image_sizes = torch.as_tensor([[default_height, default_width]
  431. for _ in range(batch_size)])
  432. return [
  433. self._merge_image_patch_embeddings(image_sizes[i],
  434. patch_features_batch,
  435. strategy="spatial_unpad")
  436. for i, patch_features_batch in enumerate(patch_embeddings)
  437. ]
  438. def forward(
  439. self,
  440. input_ids: torch.Tensor,
  441. positions: torch.Tensor,
  442. kv_caches: List[torch.Tensor],
  443. attn_metadata: AttentionMetadata,
  444. intermediate_tensors: Optional[IntermediateTensors] = None,
  445. **kwargs: object,
  446. ) -> SamplerOutput:
  447. """Run forward pass for LlaVA-NeXT.
  448. One key thing to understand is the `input_ids` already accounts for the
  449. positions of the to-be-inserted image embeddings.
  450. Concretely, consider a text prompt:
  451. `"A chat between a curious human and an artificial intelligence
  452. assistant. The assistant gives helpful, detailed, and polite answers to
  453. the human's questions.
  454. USER: <image>\\nWhat is shown in this image? ASSISTANT:"`.
  455. Tokenizer outputs:
  456. `[1, 319, 13563, 1546, 263, 12758, 5199, 322, 385, 23116, 21082, 20255,
  457. 29889, 450, 20255, 4076, 8444, 29892, 13173, 29892, 322, 1248, 568,
  458. 6089, 304, 278, 5199, 29915, 29879, 5155, 29889, 3148, 1001, 29901,
  459. 29871, 32000, 13, 5618, 338, 4318, 297, 445, 1967, 29973, 319, 1799,
  460. 9047, 13566, 29901]`.
  461. To reserve space in KV cache, we have to insert placeholder tokens
  462. before they are inputted to the model, so the input processor prepends
  463. additional image tokens (denoted as `32000`), resulting in:
  464. `[1, 319, 13563, 1546, 263, 12758, 5199, 322, 385, 23116, 21082, 20255,
  465. 29889, 450, 20255, 4076, 8444, 29892, 13173, 29892, 322, 1248, 568,
  466. 6089, 304, 278, 5199, 29915, 29879, 5155, 29889, 3148, 1001, 29901,
  467. 29871, 32000, ..., 32000, 13, 5618, 338, 4318, 297, 445, 1967, 29973,
  468. 319, 1799, 9047, 13566, 29901]`.
  469. Unlike in LLaVA-1.5, the number of image tokens inputted to the language
  470. model depends on the original size of the input image. Including the
  471. original image token in the input, the required number of image tokens
  472. is given by :func:`get_llava_next_image_feature_size`.
  473. This way, the `positions` and `attn_metadata` are consistent
  474. with the `input_ids`.
  475. Args:
  476. input_ids: Flattened (concatenated) input_ids corresponding to a
  477. batch.
  478. pixel_values: The pixels in each grid patch for each input image.
  479. image_sizes: The original `(height, width)` for each input image.
  480. See also:
  481. :class:`LlavaNextImageInputs`
  482. """
  483. image_input = self._parse_and_validate_image_input(**kwargs)
  484. if image_input is not None:
  485. vision_embeddings = self._process_image_input(image_input)
  486. inputs_embeds = self.language_model.model.get_input_embeddings(
  487. input_ids)
  488. inputs_embeds = merge_multimodal_embeddings(
  489. input_ids, inputs_embeds, vision_embeddings,
  490. self.config.image_token_index)
  491. input_ids = None
  492. else:
  493. inputs_embeds = None
  494. hidden_states = self.language_model.model(input_ids,
  495. positions,
  496. kv_caches,
  497. attn_metadata,
  498. None,
  499. inputs_embeds=inputs_embeds)
  500. return hidden_states
  501. def compute_logits(
  502. self,
  503. hidden_states: torch.Tensor,
  504. sampling_metadata: SamplingMetadata,
  505. ) -> Optional[torch.Tensor]:
  506. return self.language_model.compute_logits(hidden_states,
  507. sampling_metadata)
  508. def sample(
  509. self,
  510. logits: torch.Tensor,
  511. sampling_metadata: SamplingMetadata,
  512. ) -> Optional[SamplerOutput]:
  513. return self.language_model.sample(logits, sampling_metadata)
  514. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  515. # prepare weight iterators for components
  516. vit_weights, mlp_weights, newline_weights, llm_weights = itertools.tee(
  517. weights, 4)
  518. # load vision encoder
  519. vit_weights = filter_weights(vit_weights, "vision_tower")
  520. self.vision_tower.load_weights(vit_weights)
  521. # load mlp projector
  522. mlp_weights = filter_weights(mlp_weights, "multi_modal_projector")
  523. mlp_params_dict = dict(self.multi_modal_projector.named_parameters())
  524. for name, loaded_weight in mlp_weights:
  525. param = mlp_params_dict[name]
  526. weight_loader = getattr(param, "weight_loader",
  527. default_weight_loader)
  528. weight_loader(param, loaded_weight)
  529. # load newline
  530. newline_weights = filter_weights(newline_weights, "image_newline")
  531. for name, loaded_weight in newline_weights:
  532. assert name == ""
  533. param = self.image_newline
  534. weight_loader = getattr(param, "weight_loader",
  535. default_weight_loader)
  536. weight_loader(param, loaded_weight)
  537. # load llm backbone
  538. llm_weights = filter_weights(llm_weights, "language_model")
  539. self.language_model.load_weights(llm_weights)