test_phi3v.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. import os
  2. import re
  3. from typing import List, Optional, Tuple, Type
  4. import pytest
  5. from PIL import Image
  6. from transformers import AutoTokenizer
  7. from aphrodite.common.sequence import SampleLogprobs
  8. from aphrodite.common.utils import is_cpu, is_hip
  9. from aphrodite.multimodal.utils import rescale_image_size
  10. from ..conftest import IMAGE_ASSETS, AphroditeRunner, HfRunner
  11. from .utils import check_logprobs_close
  12. pytestmark = pytest.mark.vlm
  13. HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
  14. "stop_sign":
  15. "<|user|>\n<|image_1|>\nWhat's the content of the image?<|end|>\n<|assistant|>\n", # noqa: E501
  16. "cherry_blossom":
  17. "<|user|>\n<|image_1|>\nWhat is the season?<|end|>\n<|assistant|>\n",
  18. })
  19. HF_MULTIIMAGE_IMAGE_PROMPT = "<|user|>\n<|image_1|>\n<|image_2|>\nDescribe these images.<|end|>\n<|assistant|>\n" # noqa: E501
  20. models = ["microsoft/Phi-3.5-vision-instruct"]
  21. def aphrodite_to_hf_output(
  22. aphrodite_output: Tuple[List[int], str, Optional[SampleLogprobs]],
  23. model: str,
  24. ):
  25. """Sanitize aphrodite output to be comparable with hf output."""
  26. _, output_str, out_logprobs = aphrodite_output
  27. output_str_without_image = re.sub(r"(<\|image_\d+\|>)+", "", output_str)
  28. assert output_str_without_image[0] == " "
  29. output_str_without_image = output_str_without_image[1:]
  30. hf_output_str = output_str_without_image + "<|end|><|endoftext|>"
  31. tokenizer = AutoTokenizer.from_pretrained(model)
  32. hf_output_ids = tokenizer.encode(output_str_without_image)
  33. assert hf_output_ids[0] == 1
  34. hf_output_ids = hf_output_ids[1:]
  35. return hf_output_ids, hf_output_str, out_logprobs
  36. target_dtype = "half"
  37. if is_cpu():
  38. target_dtype = "bfloat16"
  39. # ROCm Triton FA can run into shared memory issues with these models,
  40. # use other backends in the meantime
  41. # FIXME
  42. if is_hip():
  43. os.environ["APHRODITE_USE_TRITON_FLASH_ATTN"] = "0"
  44. def run_test(
  45. hf_runner: Type[HfRunner],
  46. aphrodite_runner: Type[AphroditeRunner],
  47. images: List[Image.Image],
  48. model: str,
  49. *,
  50. size_factors: List[float],
  51. dtype: str,
  52. max_tokens: int,
  53. num_logprobs: int,
  54. tensor_parallel_size: int,
  55. distributed_executor_backend: Optional[str] = None,
  56. ):
  57. """Inference result should be the same between hf and aphrodite.
  58. All the image fixtures for the test is under tests/images.
  59. For huggingface runner, we provide the PIL images as input.
  60. For aphrodite runner, we provide MultiModalDataDict objects
  61. and corresponding MultiModalConfig as input.
  62. Note, the text input is also adjusted to abide by aphrodite contract.
  63. The text output is sanitized to be able to compare with hf.
  64. """
  65. inputs_per_image = [
  66. (
  67. [prompt for _ in size_factors],
  68. [
  69. rescale_image_size(image, factor, transpose=idx)
  70. for idx, factor in enumerate(size_factors)
  71. ],
  72. )
  73. for image, prompt in zip(images, HF_IMAGE_PROMPTS)
  74. ]
  75. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  76. # Aphrodite needs a fresh new process without cuda initialization.
  77. # if we run HF first, the cuda initialization will be done and it
  78. # will hurt multiprocessing backend with fork method (the default method).
  79. # max_model_len should be greater than image_feature_size
  80. with aphrodite_runner(
  81. model,
  82. max_model_len=4096,
  83. max_num_seqs=1,
  84. dtype=dtype,
  85. tensor_parallel_size=tensor_parallel_size,
  86. distributed_executor_backend=distributed_executor_backend,
  87. enforce_eager=True,
  88. ) as aphrodite_model:
  89. aphrodite_outputs_per_image = [
  90. aphrodite_model.generate_greedy_logprobs(
  91. prompts, max_tokens, num_logprobs=num_logprobs, images=images
  92. )
  93. for prompts, images in inputs_per_image
  94. ]
  95. # use eager mode for hf runner, since phi3_v didn't work with flash_attn
  96. hf_model_kwargs = {"_attn_implementation": "eager"}
  97. with hf_runner(
  98. model, dtype=dtype, model_kwargs=hf_model_kwargs
  99. ) as hf_model:
  100. eos_token_id = hf_model.processor.eos_token_id
  101. hf_outputs_per_image = [
  102. hf_model.generate_greedy_logprobs_limit(
  103. prompts,
  104. max_tokens,
  105. num_logprobs=num_logprobs,
  106. images=images,
  107. eos_token_id=eos_token_id,
  108. )
  109. for prompts, images in inputs_per_image
  110. ]
  111. for hf_outputs, aphrodite_outputs in zip(
  112. hf_outputs_per_image, aphrodite_outputs_per_image
  113. ):
  114. check_logprobs_close(
  115. outputs_0_lst=hf_outputs,
  116. outputs_1_lst=[
  117. aphrodite_to_hf_output(aphrodite_output, model)
  118. for aphrodite_output in aphrodite_outputs
  119. ],
  120. name_0="hf",
  121. name_1="aphrodite",
  122. )
  123. # Since we use _attn_implementation="eager" for hf_runner, there is more
  124. # significant numerical difference. The basic `logprobs=5` fails to pass.
  125. @pytest.mark.parametrize("model", models)
  126. @pytest.mark.parametrize(
  127. "size_factors",
  128. [
  129. # No image
  130. [],
  131. # Single-scale
  132. [1.0],
  133. # Single-scale, batched
  134. [1.0, 1.0, 1.0],
  135. # Multi-scale
  136. [0.25, 0.5, 1.0],
  137. ],
  138. )
  139. @pytest.mark.parametrize("dtype", [target_dtype])
  140. @pytest.mark.parametrize("max_tokens", [128])
  141. @pytest.mark.parametrize("num_logprobs", [10])
  142. def test_models(
  143. hf_runner,
  144. aphrodite_runner,
  145. image_assets,
  146. model,
  147. size_factors,
  148. dtype: str,
  149. max_tokens: int,
  150. num_logprobs: int,
  151. ) -> None:
  152. run_test(
  153. hf_runner,
  154. aphrodite_runner,
  155. [asset.pil_image for asset in image_assets],
  156. model,
  157. size_factors=size_factors,
  158. dtype=dtype,
  159. max_tokens=max_tokens,
  160. num_logprobs=num_logprobs,
  161. tensor_parallel_size=1,
  162. )
  163. @pytest.mark.parametrize("model", models)
  164. @pytest.mark.parametrize("dtype", [target_dtype])
  165. def test_regression_7840(
  166. hf_runner, aphrodite_runner, image_assets, model, dtype
  167. ) -> None:
  168. run_test(
  169. hf_runner,
  170. aphrodite_runner,
  171. [image_assets[0].pil_image.resize((465, 226))],
  172. model,
  173. size_factors=[1.0],
  174. dtype=dtype,
  175. max_tokens=128,
  176. num_logprobs=10,
  177. tensor_parallel_size=1,
  178. )
  179. def run_multi_image_test(
  180. hf_runner: Type[HfRunner],
  181. aphrodite_runner: Type[AphroditeRunner],
  182. images: List[Image.Image],
  183. model: str,
  184. *,
  185. size_factors: List[float],
  186. dtype: str,
  187. max_tokens: int,
  188. num_logprobs: int,
  189. tensor_parallel_size: int,
  190. distributed_executor_backend: Optional[str] = None,
  191. ):
  192. """Inference result should be the same between hf and aphrodite.
  193. All the image fixtures for the test is under tests/images.
  194. For huggingface runner, we provide the PIL images as input.
  195. For aphrodite runner, we provide MultiModalDataDict objects
  196. and corresponding MultiModalConfig as input.
  197. Note, the text input is also adjusted to abide by aphrodite contract.
  198. The text output is sanitized to be able to compare with hf.
  199. """
  200. inputs_per_case = [
  201. (
  202. [HF_MULTIIMAGE_IMAGE_PROMPT for _ in size_factors],
  203. [
  204. [rescale_image_size(image, factor) for image in images]
  205. for factor in size_factors
  206. ],
  207. )
  208. ]
  209. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  210. # Aphrodite needs a fresh new process without cuda initialization.
  211. # if we run HF first, the cuda initialization will be done and it
  212. # will hurt multiprocessing backend with fork method (the default method).
  213. # max_model_len should be greater than image_feature_size
  214. with aphrodite_runner(
  215. model,
  216. max_model_len=4096,
  217. max_num_seqs=1,
  218. limit_mm_per_prompt={"image": len(images)},
  219. dtype=dtype,
  220. tensor_parallel_size=tensor_parallel_size,
  221. distributed_executor_backend=distributed_executor_backend,
  222. enforce_eager=True,
  223. ) as aphrodite_model:
  224. aphrodite_outputs_per_case = [
  225. aphrodite_model.generate_greedy_logprobs(
  226. prompts, max_tokens, num_logprobs=num_logprobs, images=images
  227. )
  228. for prompts, images in inputs_per_case
  229. ]
  230. hf_model_kwargs = {"_attn_implementation": "eager"}
  231. with hf_runner(
  232. model, dtype=dtype, model_kwargs=hf_model_kwargs
  233. ) as hf_model:
  234. eos_token_id = hf_model.processor.eos_token_id
  235. hf_outputs_per_case = [
  236. hf_model.generate_greedy_logprobs_limit(
  237. prompts,
  238. max_tokens,
  239. num_logprobs=num_logprobs,
  240. images=images,
  241. eos_token_id=eos_token_id,
  242. )
  243. for prompts, images in inputs_per_case
  244. ]
  245. for hf_outputs, aphrodite_outputs in zip(
  246. hf_outputs_per_case, aphrodite_outputs_per_case
  247. ):
  248. check_logprobs_close(
  249. outputs_0_lst=hf_outputs,
  250. outputs_1_lst=[
  251. aphrodite_to_hf_output(aphrodite_output, model)
  252. for aphrodite_output in aphrodite_outputs
  253. ],
  254. name_0="hf",
  255. name_1="aphrodite",
  256. )
  257. @pytest.mark.parametrize("model", models)
  258. @pytest.mark.parametrize(
  259. "size_factors",
  260. [
  261. # No image
  262. [],
  263. # Single-scale
  264. [1.0],
  265. # Single-scale, batched
  266. [1.0, 1.0, 1.0],
  267. # Multi-scale
  268. [0.25, 0.5, 1.0],
  269. ],
  270. )
  271. @pytest.mark.parametrize("dtype", [target_dtype])
  272. @pytest.mark.parametrize("max_tokens", [128])
  273. @pytest.mark.parametrize("num_logprobs", [5])
  274. def test_multi_images_models(
  275. hf_runner,
  276. aphrodite_runner,
  277. image_assets,
  278. model,
  279. size_factors,
  280. dtype: str,
  281. max_tokens: int,
  282. num_logprobs: int,
  283. ) -> None:
  284. run_multi_image_test(
  285. hf_runner,
  286. aphrodite_runner,
  287. [asset.pil_image for asset in image_assets],
  288. model,
  289. size_factors=size_factors,
  290. dtype=dtype,
  291. max_tokens=max_tokens,
  292. num_logprobs=num_logprobs,
  293. tensor_parallel_size=1,
  294. )