test_phi3v.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import os
  2. import re
  3. from typing import List, Optional, Tuple, Type
  4. import pytest
  5. from transformers import AutoTokenizer
  6. from aphrodite.common.sequence import SampleLogprobs
  7. from aphrodite.common.utils import is_cpu, is_hip
  8. from aphrodite.multimodal.utils import rescale_image_size
  9. from ....conftest import (IMAGE_ASSETS, AphroditeRunner, HfRunner,
  10. PromptImageInput)
  11. from ...utils import check_logprobs_close
  12. HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
  13. "stop_sign":
  14. "<|user|>\n<|image_1|>\nWhat's the content of the image?<|end|>\n<|assistant|>\n", # noqa: E501
  15. "cherry_blossom":
  16. "<|user|>\n<|image_1|>\nWhat is the season?<|end|>\n<|assistant|>\n",
  17. })
  18. HF_MULTIIMAGE_IMAGE_PROMPT = "<|user|>\n<|image_1|>\n<|image_2|>\nDescribe these images.<|end|>\n<|assistant|>\n" # noqa: E501
  19. models = ["microsoft/Phi-3.5-vision-instruct"]
  20. def aphrodite_to_hf_output(aphrodite_output: Tuple[List[int], str,
  21. Optional[SampleLogprobs]],
  22. model: str):
  23. """Sanitize aphrodite output to be comparable with hf output."""
  24. _, output_str, out_logprobs = aphrodite_output
  25. output_str_without_image = re.sub(r"(<\|image_\d+\|>)+", "", output_str)
  26. assert output_str_without_image[0] == " "
  27. output_str_without_image = output_str_without_image[1:]
  28. hf_output_str = output_str_without_image + "<|end|><|endoftext|>"
  29. tokenizer = AutoTokenizer.from_pretrained(model)
  30. hf_output_ids = tokenizer.encode(output_str_without_image)
  31. assert hf_output_ids[0] == 1
  32. hf_output_ids = hf_output_ids[1:]
  33. return hf_output_ids, hf_output_str, out_logprobs
  34. target_dtype = "half"
  35. if is_cpu():
  36. target_dtype = "bfloat16"
  37. # ROCm Triton FA can run into shared memory issues with these models,
  38. # use other backends in the meantime
  39. # FIXME (mattwong, gshtrasb, hongxiayan)
  40. if is_hip():
  41. os.environ["APHRODITE_USE_TRITON_FLASH_ATTN"] = "0"
  42. def run_test(
  43. hf_runner: Type[HfRunner],
  44. aphrodite_runner: Type[AphroditeRunner],
  45. inputs: List[Tuple[List[str], PromptImageInput]],
  46. model: str,
  47. *,
  48. dtype: str,
  49. max_tokens: int,
  50. num_logprobs: int,
  51. mm_limit: int,
  52. tensor_parallel_size: int,
  53. distributed_executor_backend: Optional[str] = None,
  54. ):
  55. """Inference result should be the same between hf and aphrodite.
  56. All the image fixtures for the test are from IMAGE_ASSETS.
  57. For huggingface runner, we provide the PIL images as input.
  58. For aphrodite runner, we provide MultiModalDataDict objects
  59. and corresponding MultiModalConfig as input.
  60. Note, the text input is also adjusted to abide by aphrodite contract.
  61. The text output is sanitized to be able to compare with hf.
  62. """
  63. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  64. # Aphrodite needs a fresh new process without cuda initialization.
  65. # if we run HF first, the cuda initialization will be done and it
  66. # will hurt multiprocessing backend with fork method (the default method).
  67. # max_model_len should be greater than image_feature_size
  68. with aphrodite_runner(model,
  69. max_model_len=4096,
  70. max_num_seqs=1,
  71. dtype=dtype,
  72. limit_mm_per_prompt={"image": mm_limit},
  73. tensor_parallel_size=tensor_parallel_size,
  74. distributed_executor_backend=distributed_executor_backend,
  75. enforce_eager=True) as aphrodite_model:
  76. aphrodite_outputs_per_case = [
  77. aphrodite_model.generate_greedy_logprobs(prompts,
  78. max_tokens,
  79. num_logprobs=num_logprobs,
  80. images=images)
  81. for prompts, images in inputs
  82. ]
  83. # use eager mode for hf runner, since phi3_v didn't work with flash_attn
  84. hf_model_kwargs = {"_attn_implementation": "eager"}
  85. with hf_runner(model, dtype=dtype,
  86. model_kwargs=hf_model_kwargs) as hf_model:
  87. eos_token_id = hf_model.processor.tokenizer.eos_token_id
  88. hf_outputs_per_case = [
  89. hf_model.generate_greedy_logprobs_limit(prompts,
  90. max_tokens,
  91. num_logprobs=num_logprobs,
  92. images=images,
  93. eos_token_id=eos_token_id)
  94. for prompts, images in inputs
  95. ]
  96. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_case,
  97. aphrodite_outputs_per_case):
  98. check_logprobs_close(
  99. outputs_0_lst=hf_outputs,
  100. outputs_1_lst=[
  101. aphrodite_to_hf_output(aphrodite_output, model)
  102. for aphrodite_output in aphrodite_outputs
  103. ],
  104. name_0="hf",
  105. name_1="aphrodite",
  106. )
  107. # Since we use _attn_implementation="eager" for hf_runner, there is more
  108. # significant numerical difference. The basic `logprobs=5` fails to pass.
  109. @pytest.mark.parametrize("model", models)
  110. @pytest.mark.parametrize(
  111. "size_factors",
  112. [
  113. # No image
  114. [],
  115. # Single-scale
  116. [1.0],
  117. # Single-scale, batched
  118. [1.0, 1.0, 1.0],
  119. # Multi-scale
  120. [0.25, 0.5, 1.0],
  121. ],
  122. )
  123. @pytest.mark.parametrize("dtype", [target_dtype])
  124. @pytest.mark.parametrize("max_tokens", [128])
  125. @pytest.mark.parametrize("num_logprobs", [10])
  126. def test_models(hf_runner, aphrodite_runner, image_assets, model, size_factors,
  127. dtype: str, max_tokens: int, num_logprobs: int) -> None:
  128. images = [asset.pil_image for asset in image_assets]
  129. inputs_per_image = [(
  130. [prompt for _ in size_factors],
  131. [rescale_image_size(image, factor) for factor in size_factors],
  132. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  133. run_test(
  134. hf_runner,
  135. aphrodite_runner,
  136. inputs_per_image,
  137. model,
  138. dtype=dtype,
  139. max_tokens=max_tokens,
  140. num_logprobs=num_logprobs,
  141. mm_limit=1,
  142. tensor_parallel_size=1,
  143. )
  144. @pytest.mark.parametrize("model", models)
  145. @pytest.mark.parametrize("dtype", [target_dtype])
  146. def test_regression_7840(hf_runner, aphrodite_runner, image_assets, model,
  147. dtype) -> None:
  148. images = [asset.pil_image for asset in image_assets]
  149. inputs_regresion_7840 = [
  150. ([prompt], [image]) for image, prompt in zip(images, HF_IMAGE_PROMPTS)
  151. ]
  152. # Regression test for #7840.
  153. run_test(
  154. hf_runner,
  155. aphrodite_runner,
  156. inputs_regresion_7840,
  157. model,
  158. dtype=dtype,
  159. max_tokens=128,
  160. num_logprobs=10,
  161. mm_limit=1,
  162. tensor_parallel_size=1,
  163. )
  164. @pytest.mark.parametrize("model", models)
  165. @pytest.mark.parametrize(
  166. "size_factors",
  167. [
  168. # No image
  169. [],
  170. # Single-scale
  171. [1.0],
  172. # Single-scale, batched
  173. [1.0, 1.0, 1.0],
  174. # Multi-scale
  175. [0.25, 0.5, 1.0],
  176. ],
  177. )
  178. @pytest.mark.parametrize("dtype", [target_dtype])
  179. @pytest.mark.parametrize("max_tokens", [128])
  180. @pytest.mark.parametrize("num_logprobs", [10])
  181. def test_multi_images_models(hf_runner, aphrodite_runner, image_assets, model,
  182. size_factors, dtype: str, max_tokens: int,
  183. num_logprobs: int) -> None:
  184. images = [asset.pil_image for asset in image_assets]
  185. inputs_per_case = [
  186. ([HF_MULTIIMAGE_IMAGE_PROMPT for _ in size_factors],
  187. [[rescale_image_size(image, factor) for image in images]
  188. for factor in size_factors])
  189. ]
  190. run_test(
  191. hf_runner,
  192. aphrodite_runner,
  193. inputs_per_case,
  194. model,
  195. dtype=dtype,
  196. max_tokens=max_tokens,
  197. num_logprobs=num_logprobs,
  198. mm_limit=2,
  199. tensor_parallel_size=1,
  200. )