test_llava_next.py 9.0 KB

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