test_phi3v.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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, _ImageAssets
  10. from .utils import check_logprobs_close
  11. pytestmark = pytest.mark.vlm
  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. models = ["microsoft/Phi-3-vision-128k-instruct"]
  19. def aphrodite_to_hf_output(aphrodite_output: Tuple[List[int], str,
  20. Optional[SampleLogprobs]],
  21. model: str):
  22. """Sanitize aphrodite output to be comparable with hf output."""
  23. _, output_str, out_logprobs = aphrodite_output
  24. output_str_without_image = re.sub(r"(<\|image_\d+\|>)+", "", output_str)
  25. assert output_str_without_image[0] == " "
  26. output_str_without_image = output_str_without_image[1:]
  27. hf_output_str = output_str_without_image + "<|end|><|endoftext|>"
  28. tokenizer = AutoTokenizer.from_pretrained(model)
  29. hf_output_ids = tokenizer.encode(output_str_without_image)
  30. assert hf_output_ids[0] == 1
  31. hf_output_ids = hf_output_ids[1:]
  32. return hf_output_ids, hf_output_str, out_logprobs
  33. target_dtype = "half"
  34. if is_cpu():
  35. target_dtype = "bfloat16"
  36. # ROCm Triton FA can run into shared memory issues with these models,
  37. # use other backends in the meantime
  38. # FIXME
  39. if is_hip():
  40. os.environ["APHRODITE_USE_TRITON_FLASH_ATTN"] = "0"
  41. def run_test(
  42. hf_runner: Type[HfRunner],
  43. aphrodite_runner: Type[AphroditeRunner],
  44. image_assets: _ImageAssets,
  45. model: str,
  46. *,
  47. size_factors: List[float],
  48. dtype: str,
  49. max_tokens: int,
  50. num_logprobs: int,
  51. tensor_parallel_size: int,
  52. distributed_executor_backend: Optional[str] = None,
  53. ):
  54. """Inference result should be the same between hf and aphrodite.
  55. All the image fixtures for the test is under tests/images.
  56. For huggingface runner, we provide the PIL images as input.
  57. For aphrodite runner, we provide MultiModalDataDict objects
  58. and corresponding MultiModalConfig as input.
  59. Note, the text input is also adjusted to abide by aphrodite contract.
  60. The text output is sanitized to be able to compare with hf.
  61. """
  62. images = [asset.pil_image for asset in image_assets]
  63. inputs_per_image = [(
  64. [prompt for _ in size_factors],
  65. [
  66. rescale_image_size(image, factor, transpose=idx)
  67. for idx, factor in enumerate(size_factors)
  68. ],
  69. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  70. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  71. # Aphrodite needs a fresh new process without cuda initialization.
  72. # if we run HF first, the cuda initialization will be done and it
  73. # will hurt multiprocessing backend with fork method (the default method).
  74. # max_model_len should be greater than image_feature_size
  75. with aphrodite_runner(model,
  76. max_model_len=4096,
  77. max_num_seqs=1,
  78. dtype=dtype,
  79. tensor_parallel_size=tensor_parallel_size,
  80. distributed_executor_backend=distributed_executor_backend,
  81. enforce_eager=True) as aphrodite_model:
  82. aphrodite_outputs_per_image = [
  83. aphrodite_model.generate_greedy_logprobs(prompts,
  84. max_tokens,
  85. num_logprobs=num_logprobs,
  86. images=images)
  87. for prompts, images in inputs_per_image
  88. ]
  89. # use eager mode for hf runner, since phi3_v didn't work with flash_attn
  90. hf_model_kwargs = {"_attn_implementation": "eager"}
  91. with hf_runner(model, dtype=dtype,
  92. model_kwargs=hf_model_kwargs) as hf_model:
  93. eos_token_id = hf_model.processor.tokenizer.eos_token_id
  94. hf_outputs_per_image = [
  95. hf_model.generate_greedy_logprobs_limit(prompts,
  96. max_tokens,
  97. num_logprobs=num_logprobs,
  98. images=images,
  99. eos_token_id=eos_token_id)
  100. for prompts, images in inputs_per_image
  101. ]
  102. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_image,
  103. aphrodite_outputs_per_image):
  104. check_logprobs_close(
  105. outputs_0_lst=hf_outputs,
  106. outputs_1_lst=[
  107. aphrodite_to_hf_output(aphrodite_output, model)
  108. for aphrodite_output in aphrodite_outputs
  109. ],
  110. name_0="hf",
  111. name_1="aphrodite",
  112. )
  113. # Since we use _attn_implementation="eager" for hf_runner, there is more
  114. # significant numerical difference. The basic `logprobs=5` fails to pass.
  115. @pytest.mark.parametrize("model", models)
  116. @pytest.mark.parametrize(
  117. "size_factors",
  118. [
  119. # No image
  120. [],
  121. # Single-scale
  122. [1.0],
  123. # Single-scale, batched
  124. [1.0, 1.0, 1.0],
  125. # Multi-scale
  126. [0.25, 0.5, 1.0],
  127. ],
  128. )
  129. @pytest.mark.parametrize("dtype", [target_dtype])
  130. @pytest.mark.parametrize("max_tokens", [128])
  131. @pytest.mark.parametrize("num_logprobs", [10])
  132. def test_models(hf_runner, aphrodite_runner, image_assets, model, size_factors,
  133. dtype: str, max_tokens: int, num_logprobs: int) -> None:
  134. run_test(
  135. hf_runner,
  136. aphrodite_runner,
  137. image_assets,
  138. model,
  139. size_factors=size_factors,
  140. dtype=dtype,
  141. max_tokens=max_tokens,
  142. num_logprobs=num_logprobs,
  143. tensor_parallel_size=1,
  144. )