test_llava.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. from typing import List, Optional, Tuple, Type, overload
  2. import pytest
  3. from transformers import (AutoConfig, AutoModelForVision2Seq, AutoTokenizer,
  4. BatchEncoding)
  5. from aphrodite.common.sequence import SampleLogprobs
  6. from aphrodite.common.utils import STR_DTYPE_TO_TORCH_DTYPE
  7. from aphrodite.multimodal.utils import rescale_image_size
  8. from ....conftest import (IMAGE_ASSETS, AphroditeRunner, HfRunner,
  9. PromptImageInput, _ImageAssets)
  10. from ...utils import check_logprobs_close
  11. _LIMIT_IMAGE_PER_PROMPT = 4
  12. HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
  13. "stop_sign":
  14. "USER: <image>\nWhat's the content of the image?\nASSISTANT:",
  15. "cherry_blossom":
  16. "USER: <image>\nWhat is the season?\nASSISTANT:",
  17. })
  18. models = [
  19. "llava-hf/llava-1.5-7b-hf",
  20. # TODO: Get this model to produce meaningful output in Aphrodite
  21. # "TIGER-Lab/Mantis-8B-siglip-llama3",
  22. ]
  23. def aphrodite_to_hf_output(aphrodite_output: Tuple[List[int], str,
  24. Optional[SampleLogprobs]],
  25. model: str):
  26. """Sanitize aphrodite output to be comparable with hf output."""
  27. output_ids, output_str, out_logprobs = aphrodite_output
  28. config = AutoConfig.from_pretrained(model)
  29. image_token_id = config.image_token_index
  30. tokenizer = AutoTokenizer.from_pretrained(model)
  31. eos_token_id = tokenizer.eos_token_id
  32. hf_output_ids = [
  33. token_id for idx, token_id in enumerate(output_ids)
  34. if token_id != image_token_id or output_ids[idx - 1] != image_token_id
  35. ]
  36. assert output_str[0] == " "
  37. hf_output_str = output_str[1:]
  38. if hf_output_ids[-1] == eos_token_id:
  39. hf_output_str = hf_output_str + tokenizer.decode(eos_token_id)
  40. return hf_output_ids, hf_output_str, out_logprobs
  41. @overload
  42. def run_test(
  43. hf_runner: Type[HfRunner],
  44. aphrodite_runner: Type[AphroditeRunner],
  45. image_assets: _ImageAssets,
  46. model: str,
  47. *,
  48. size_factors: List[float],
  49. dtype: str,
  50. max_tokens: int,
  51. num_logprobs: int,
  52. tensor_parallel_size: int,
  53. distributed_executor_backend: Optional[str] = None,
  54. ):
  55. ...
  56. @overload
  57. def run_test(
  58. hf_runner: Type[HfRunner],
  59. aphrodite_runner: Type[AphroditeRunner],
  60. image_assets: _ImageAssets,
  61. model: str,
  62. *,
  63. sizes: List[Tuple[int, int]],
  64. dtype: str,
  65. max_tokens: int,
  66. num_logprobs: int,
  67. tensor_parallel_size: int,
  68. distributed_executor_backend: Optional[str] = None,
  69. ):
  70. ...
  71. def run_test(
  72. hf_runner: Type[HfRunner],
  73. aphrodite_runner: Type[AphroditeRunner],
  74. image_assets: _ImageAssets,
  75. model: str,
  76. *,
  77. size_factors: Optional[List[float]] = None,
  78. sizes: Optional[List[Tuple[int, int]]] = None,
  79. dtype: str,
  80. max_tokens: int,
  81. num_logprobs: int,
  82. tensor_parallel_size: int,
  83. distributed_executor_backend: Optional[str] = None,
  84. ):
  85. images = [asset.pil_image for asset in image_assets]
  86. if size_factors is not None:
  87. inputs_per_image = [(
  88. [prompt for _ in size_factors],
  89. [rescale_image_size(image, factor) for factor in size_factors],
  90. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  91. elif sizes is not None:
  92. inputs_per_image = [(
  93. [prompt for _ in sizes],
  94. [image.resize(size) for size in sizes],
  95. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  96. else:
  97. raise ValueError("You must provide either `size_factors` or `sizes`")
  98. _run_test(hf_runner,
  99. aphrodite_runner,
  100. inputs_per_image,
  101. model,
  102. dtype=dtype,
  103. max_tokens=max_tokens,
  104. num_logprobs=num_logprobs,
  105. tensor_parallel_size=tensor_parallel_size,
  106. distributed_executor_backend=distributed_executor_backend)
  107. def _run_test(
  108. hf_runner: Type[HfRunner],
  109. aphrodite_runner: Type[AphroditeRunner],
  110. inputs: List[Tuple[List[str], PromptImageInput]],
  111. model: str,
  112. *,
  113. dtype: str,
  114. max_tokens: int,
  115. num_logprobs: int,
  116. tensor_parallel_size: int,
  117. distributed_executor_backend: Optional[str] = None,
  118. ):
  119. """Inference result should be the same between hf and aphrodite.
  120. All the image fixtures for the test are from IMAGE_ASSETS.
  121. For huggingface runner, we provide the PIL images as input.
  122. For aphrodite runner, we provide MultiModalDataDict objects
  123. and corresponding MultiModalConfig as input.
  124. Note, the text input is also adjusted to abide by aphrodite contract.
  125. The text output is sanitized to be able to compare with hf.
  126. """
  127. # NOTE: For local use; this isn't tested in CI yet (see TODO above)
  128. if model.startswith("TIGER-Lab/Mantis"):
  129. from mantis.models.mllava import MLlavaProcessor
  130. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
  131. mantis_processor = MLlavaProcessor.from_pretrained(
  132. model, torch_dtype=torch_dtype)
  133. assert isinstance(mantis_processor, MLlavaProcessor)
  134. else:
  135. mantis_processor = None
  136. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  137. # Aphrodite needs a fresh new process without cuda initialization.
  138. # if we run HF first, the cuda initialization will be done and it
  139. # will hurt multiprocessing backend with fork method (the default method).
  140. # max_model_len should be greater than image_feature_size
  141. with aphrodite_runner(model,
  142. dtype=dtype,
  143. max_model_len=4096,
  144. tensor_parallel_size=tensor_parallel_size,
  145. distributed_executor_backend=distributed_executor_backend,
  146. enforce_eager=True,
  147. limit_mm_per_prompt={"image": _LIMIT_IMAGE_PER_PROMPT
  148. }) as aphrodite_model:
  149. aphrodite_outputs_per_image = [
  150. aphrodite_model.generate_greedy_logprobs(prompts,
  151. max_tokens,
  152. num_logprobs=num_logprobs,
  153. images=images)
  154. for prompts, images in inputs
  155. ]
  156. if mantis_processor is not None:
  157. def process(hf_inputs: BatchEncoding):
  158. hf_inputs["pixel_values"] = hf_inputs["pixel_values"] \
  159. .to(torch_dtype) # type: ignore
  160. return hf_inputs
  161. else:
  162. def process(hf_inputs: BatchEncoding):
  163. return hf_inputs
  164. with hf_runner(model,
  165. dtype=dtype,
  166. postprocess_inputs=process,
  167. auto_cls=AutoModelForVision2Seq) as hf_model:
  168. hf_outputs_per_image = [
  169. hf_model.generate_greedy_logprobs_limit(prompts,
  170. max_tokens,
  171. num_logprobs=num_logprobs,
  172. images=images)
  173. for prompts, images in inputs
  174. ]
  175. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_image,
  176. aphrodite_outputs_per_image):
  177. # TODO: Check whether using original CLIPVisionModel can improve
  178. # consistency against HF
  179. check_logprobs_close(
  180. outputs_0_lst=hf_outputs,
  181. outputs_1_lst=[
  182. aphrodite_to_hf_output(aphrodite_output, model)
  183. for aphrodite_output in aphrodite_outputs
  184. ],
  185. name_0="hf",
  186. name_1="aphrodite",
  187. )
  188. @pytest.mark.parametrize("model", models)
  189. @pytest.mark.parametrize(
  190. "size_factors",
  191. [
  192. # No image
  193. [],
  194. # Single-scale
  195. [1.0],
  196. # Single-scale, batched
  197. [1.0, 1.0, 1.0],
  198. # Multi-scale
  199. [0.25, 0.5, 1.0],
  200. ],
  201. )
  202. @pytest.mark.parametrize("dtype", ["half"])
  203. @pytest.mark.parametrize("max_tokens", [128])
  204. @pytest.mark.parametrize("num_logprobs", [5])
  205. def test_models(hf_runner, aphrodite_runner, image_assets, model, size_factors,
  206. dtype, max_tokens, num_logprobs) -> None:
  207. run_test(
  208. hf_runner,
  209. aphrodite_runner,
  210. image_assets,
  211. model,
  212. size_factors=size_factors,
  213. dtype=dtype,
  214. max_tokens=max_tokens,
  215. num_logprobs=num_logprobs,
  216. tensor_parallel_size=1,
  217. )
  218. @pytest.mark.parametrize("model", models)
  219. @pytest.mark.parametrize("dtype", ["half"])
  220. @pytest.mark.parametrize("max_tokens", [128])
  221. @pytest.mark.parametrize("num_logprobs", [5])
  222. def test_models_multiple_image_inputs(hf_runner, aphrodite_runner, image_assets,
  223. model, dtype, max_tokens,
  224. num_logprobs) -> None:
  225. stop_sign = image_assets[0].pil_image
  226. cherry_blossom = image_assets[1].pil_image
  227. inputs = [(
  228. [
  229. "USER: <image><image>\nDescribe 2 images.\nASSISTANT:",
  230. "USER: <image><image>\nDescribe 2 images.\nASSISTANT:",
  231. "USER: <image><image><image><image>\nDescribe 4 images.\nASSISTANT:", # noqa: E501
  232. "USER: <image>\nWhat is the season?\nASSISTANT:",
  233. ],
  234. [
  235. [stop_sign, cherry_blossom],
  236. # Images with different sizes and aspect-ratios
  237. [
  238. rescale_image_size(stop_sign, 0.1),
  239. stop_sign,
  240. ],
  241. [
  242. stop_sign,
  243. rescale_image_size(stop_sign, 0.25),
  244. cherry_blossom.resize((183, 488)),
  245. cherry_blossom.resize((488, 183))
  246. ],
  247. cherry_blossom,
  248. ])]
  249. _run_test(
  250. hf_runner,
  251. aphrodite_runner,
  252. inputs,
  253. model,
  254. dtype=dtype,
  255. max_tokens=max_tokens,
  256. num_logprobs=num_logprobs,
  257. tensor_parallel_size=1,
  258. )
  259. @pytest.mark.parametrize("model", models)
  260. def test_context_length_too_short(aphrodite_runner, image_assets, model):
  261. images = [asset.pil_image for asset in image_assets]
  262. with pytest.raises(ValueError, match="too long to fit into the model"):
  263. aphrodite_model = aphrodite_runner(
  264. model,
  265. max_model_len=128, # LLaVA has a feature size of 576
  266. enforce_eager=True,
  267. )
  268. with aphrodite_model:
  269. aphrodite_model.generate_greedy([HF_IMAGE_PROMPTS[0]],
  270. max_tokens=1,
  271. images=[images[0]])