test_llava_next.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. from typing import List, Optional, Tuple, Type, overload
  2. import pytest
  3. from transformers import AutoConfig, 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, _ImageAssets
  7. from .utils import check_logprobs_close
  8. pytestmark = pytest.mark.vlm
  9. _PREFACE = (
  10. "A chat between a curious human and an artificial intelligence assistant. "
  11. "The assistant gives helpful, detailed, and polite answers to the human's "
  12. "questions.")
  13. HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
  14. "stop_sign":
  15. f"{_PREFACE} USER: <image>\nWhat's the content of the image? ASSISTANT:",
  16. "cherry_blossom":
  17. f"{_PREFACE} USER: <image>\nWhat is the season? ASSISTANT:",
  18. })
  19. models = ["llava-hf/llava-v1.6-vicuna-7b-hf"]
  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_ids, output_str, out_logprobs = aphrodite_output
  25. config = AutoConfig.from_pretrained(model)
  26. image_token_id = config.image_token_index
  27. tokenizer = AutoTokenizer.from_pretrained(model)
  28. eos_token_id = tokenizer.eos_token_id
  29. hf_output_ids = [
  30. token_id for idx, token_id in enumerate(output_ids)
  31. if token_id != image_token_id or output_ids[idx - 1] != image_token_id
  32. ]
  33. assert output_str[0] == " "
  34. hf_output_str = output_str[1:]
  35. if hf_output_ids[-1] == eos_token_id:
  36. hf_output_str = hf_output_str + tokenizer.decode(eos_token_id)
  37. return hf_output_ids, hf_output_str, out_logprobs
  38. @overload
  39. def run_test(
  40. hf_runner: Type[HfRunner],
  41. aphrodite_runner: Type[AphroditeRunner],
  42. image_assets: _ImageAssets,
  43. model: str,
  44. *,
  45. size_factors: List[float],
  46. dtype: str,
  47. max_tokens: int,
  48. num_logprobs: int,
  49. tensor_parallel_size: int,
  50. distributed_executor_backend: Optional[str] = None,
  51. ):
  52. ...
  53. @overload
  54. def run_test(
  55. hf_runner: Type[HfRunner],
  56. aphrodite_runner: Type[AphroditeRunner],
  57. image_assets: _ImageAssets,
  58. model: str,
  59. *,
  60. sizes: List[Tuple[int, int]],
  61. dtype: str,
  62. max_tokens: int,
  63. num_logprobs: int,
  64. tensor_parallel_size: int,
  65. distributed_executor_backend: Optional[str] = None,
  66. ):
  67. ...
  68. def run_test(
  69. hf_runner: Type[HfRunner],
  70. aphrodite_runner: Type[AphroditeRunner],
  71. image_assets: _ImageAssets,
  72. model: str,
  73. *,
  74. size_factors: Optional[List[float]] = None,
  75. sizes: Optional[List[Tuple[int, int]]] = None,
  76. dtype: str,
  77. max_tokens: int,
  78. num_logprobs: int,
  79. tensor_parallel_size: int,
  80. distributed_executor_backend: Optional[str] = None,
  81. ):
  82. images = [asset.pil_image for asset in image_assets]
  83. if size_factors is not None:
  84. inputs_per_image = [(
  85. [prompt for _ in size_factors],
  86. [rescale_image_size(image, factor) for factor in size_factors],
  87. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  88. elif sizes is not None:
  89. inputs_per_image = [(
  90. [prompt for _ in sizes],
  91. [image.resize(size) for size in sizes],
  92. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  93. else:
  94. raise ValueError("You must provide either `size_factors` or `sizes`")
  95. # max_model_len should be greater than image_feature_size
  96. with aphrodite_runner(model,
  97. dtype=dtype,
  98. max_model_len=4096,
  99. tensor_parallel_size=tensor_parallel_size,
  100. distributed_executor_backend=distributed_executor_backend,
  101. enforce_eager=True) as aphrodite_model:
  102. aphrodite_outputs_per_image = [
  103. aphrodite_model.generate_greedy_logprobs(prompts,
  104. max_tokens,
  105. num_logprobs=num_logprobs,
  106. images=images)
  107. for prompts, images in inputs_per_image
  108. ]
  109. with hf_runner(model, dtype=dtype, is_vision_model=True) as hf_model:
  110. hf_outputs_per_image = [
  111. hf_model.generate_greedy_logprobs_limit(prompts,
  112. max_tokens,
  113. num_logprobs=num_logprobs,
  114. images=images)
  115. for prompts, images in inputs_per_image
  116. ]
  117. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_image,
  118. aphrodite_outputs_per_image):
  119. # TODO: Check whether using original CLIPVisionModel can improve
  120. # consistency against HF
  121. check_logprobs_close(
  122. outputs_0_lst=hf_outputs,
  123. outputs_1_lst=[
  124. aphrodite_to_hf_output(aphrodite_output, model)
  125. for aphrodite_output in aphrodite_outputs
  126. ],
  127. name_0="hf",
  128. name_1="aphrodite",
  129. )
  130. @pytest.mark.parametrize("model", models)
  131. @pytest.mark.parametrize(
  132. "size_factors",
  133. [
  134. # No image
  135. [],
  136. # Single-scale
  137. [1.0],
  138. # Single-scale, batched
  139. [1.0, 1.0, 1.0],
  140. # Multi-scale
  141. [0.25, 0.5, 1.0],
  142. ],
  143. )
  144. @pytest.mark.parametrize("dtype", ["half"])
  145. @pytest.mark.parametrize("max_tokens", [128])
  146. @pytest.mark.parametrize("num_logprobs", [5])
  147. def test_models(hf_runner, aphrodite_runner, image_assets, model, size_factors,
  148. dtype, max_tokens, num_logprobs) -> None:
  149. """Inference result should be the same between hf and aphrodite.
  150. All the image fixtures for the test is under tests/images.
  151. For huggingface runner, we provide the PIL images as input.
  152. For aphrodite runner, we provide MultiModalDataDict objects
  153. and corresponding MultiModalConfig as input.
  154. Note, the text input is also adjusted to abide by aphrodite contract.
  155. The text output is sanitized to be able to compare with hf.
  156. """
  157. run_test(
  158. hf_runner,
  159. aphrodite_runner,
  160. image_assets,
  161. model,
  162. size_factors=size_factors,
  163. dtype=dtype,
  164. max_tokens=max_tokens,
  165. num_logprobs=num_logprobs,
  166. tensor_parallel_size=1,
  167. )
  168. @pytest.mark.parametrize("model", models)
  169. @pytest.mark.parametrize(
  170. "sizes",
  171. [[(1669, 2560), (2560, 1669), (183, 488), (488, 183)]],
  172. )
  173. @pytest.mark.parametrize("dtype", ["half"])
  174. @pytest.mark.parametrize("max_tokens", [128])
  175. @pytest.mark.parametrize("num_logprobs", [5])
  176. def test_models_fixed_sizes(hf_runner, aphrodite_runner, image_assets, model,
  177. sizes, dtype, max_tokens, num_logprobs) -> None:
  178. run_test(
  179. hf_runner,
  180. aphrodite_runner,
  181. image_assets,
  182. model,
  183. sizes=sizes,
  184. dtype=dtype,
  185. max_tokens=max_tokens,
  186. num_logprobs=num_logprobs,
  187. tensor_parallel_size=1,
  188. )