test_llava_next.py 9.0 KB

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