test_phi3v.py 7.9 KB

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