test_llava.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. from typing import List, Optional, Tuple, Type
  2. import pytest
  3. from transformers import (AutoConfig, AutoModelForVision2Seq, AutoTokenizer,
  4. BatchEncoding)
  5. from aphrodite.common.sequence import SampleLogprobs
  6. from aphrodite.common.utils import STR_DTYPE_TO_TORCH_DTYPE
  7. from aphrodite.multimodal.utils import rescale_image_size
  8. from ..conftest import IMAGE_ASSETS, AphroditeRunner, HfRunner, _ImageAssets
  9. from .utils import check_logprobs_close
  10. pytestmark = pytest.mark.vlm
  11. HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
  12. "stop_sign":
  13. "USER: <image>\nWhat's the content of the image?\nASSISTANT:",
  14. "cherry_blossom":
  15. "USER: <image>\nWhat is the season?\nASSISTANT:",
  16. })
  17. models = [
  18. "llava-hf/llava-1.5-7b-hf",
  19. # TODO: Get this model to produce meaningful output in Aphrodite
  20. # "TIGER-Lab/Mantis-8B-siglip-llama3",
  21. ]
  22. def aphrodite_to_hf_output(aphrodite_output: Tuple[List[int], str,
  23. Optional[SampleLogprobs]],
  24. model: str):
  25. """Sanitize aphrodite output to be comparable with hf output."""
  26. output_ids, output_str, out_logprobs = aphrodite_output
  27. config = AutoConfig.from_pretrained(model)
  28. image_token_id = config.image_token_index
  29. tokenizer = AutoTokenizer.from_pretrained(model)
  30. eos_token_id = tokenizer.eos_token_id
  31. hf_output_ids = [
  32. token_id for idx, token_id in enumerate(output_ids)
  33. if token_id != image_token_id or output_ids[idx - 1] != image_token_id
  34. ]
  35. assert output_str[0] == " "
  36. hf_output_str = output_str[1:]
  37. if hf_output_ids[-1] == eos_token_id:
  38. hf_output_str = hf_output_str + tokenizer.decode(eos_token_id)
  39. return hf_output_ids, hf_output_str, out_logprobs
  40. def run_test(
  41. hf_runner: Type[HfRunner],
  42. aphrodite_runner: Type[AphroditeRunner],
  43. image_assets: _ImageAssets,
  44. model: str,
  45. *,
  46. size_factors: List[float],
  47. dtype: str,
  48. max_tokens: int,
  49. num_logprobs: int,
  50. tensor_parallel_size: int,
  51. distributed_executor_backend: Optional[str] = None,
  52. ):
  53. """Inference result should be the same between hf and aphrodite.
  54. All the image fixtures for the test is under tests/images.
  55. For huggingface runner, we provide the PIL images as input.
  56. For aphrodite runner, we provide MultiModalDataDict objects
  57. and corresponding MultiModalConfig as input.
  58. Note, the text input is also adjusted to abide by aphrodite contract.
  59. The text output is sanitized to be able to compare with hf.
  60. """
  61. # NOTE: For local use; this isn't tested in CI yet (see TODO above)
  62. if model.startswith("TIGER-Lab/Mantis"):
  63. from mantis.models.mllava import MLlavaProcessor
  64. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
  65. mantis_processor = MLlavaProcessor.from_pretrained(
  66. model, torch_dtype=torch_dtype)
  67. assert isinstance(mantis_processor, MLlavaProcessor)
  68. else:
  69. mantis_processor = None
  70. images = [asset.pil_image for asset in image_assets]
  71. inputs_per_image = [(
  72. [prompt for _ in size_factors],
  73. [rescale_image_size(image, factor) for factor in size_factors],
  74. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  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(model,
  81. dtype=dtype,
  82. tensor_parallel_size=tensor_parallel_size,
  83. distributed_executor_backend=distributed_executor_backend,
  84. enforce_eager=True) as aphrodite_model:
  85. aphrodite_outputs_per_image = [
  86. aphrodite_model.generate_greedy_logprobs(prompts,
  87. max_tokens,
  88. num_logprobs=num_logprobs,
  89. images=images)
  90. for prompts, images in inputs_per_image
  91. ]
  92. if mantis_processor is not None:
  93. def process(hf_inputs: BatchEncoding):
  94. hf_inputs["pixel_values"] = hf_inputs["pixel_values"] \
  95. .to(torch_dtype) # type: ignore
  96. return hf_inputs
  97. else:
  98. def process(hf_inputs: BatchEncoding):
  99. return hf_inputs
  100. with hf_runner(model,
  101. dtype=dtype,
  102. postprocess_inputs=process,
  103. auto_cls=AutoModelForVision2Seq) as hf_model:
  104. hf_outputs_per_image = [
  105. hf_model.generate_greedy_logprobs_limit(prompts,
  106. max_tokens,
  107. num_logprobs=num_logprobs,
  108. images=images)
  109. for prompts, images in inputs_per_image
  110. ]
  111. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_image,
  112. aphrodite_outputs_per_image):
  113. # TODO: Check whether using original CLIPVisionModel can improve
  114. # consistency against HF
  115. check_logprobs_close(
  116. outputs_0_lst=hf_outputs,
  117. outputs_1_lst=[
  118. aphrodite_to_hf_output(aphrodite_output, model)
  119. for aphrodite_output in aphrodite_outputs
  120. ],
  121. name_0="hf",
  122. name_1="aphrodite",
  123. )
  124. @pytest.mark.parametrize("model", models)
  125. @pytest.mark.parametrize(
  126. "size_factors",
  127. [
  128. # No image
  129. [],
  130. # Single-scale
  131. [1.0],
  132. # Single-scale, batched
  133. [1.0, 1.0, 1.0],
  134. # Multi-scale
  135. [0.25, 0.5, 1.0],
  136. ],
  137. )
  138. @pytest.mark.parametrize("dtype", ["half"])
  139. @pytest.mark.parametrize("max_tokens", [128])
  140. @pytest.mark.parametrize("num_logprobs", [5])
  141. def test_models(hf_runner, aphrodite_runner, image_assets, model, size_factors,
  142. dtype: str, max_tokens: int, num_logprobs: int) -> None:
  143. run_test(
  144. hf_runner,
  145. aphrodite_runner,
  146. image_assets,
  147. model,
  148. size_factors=size_factors,
  149. dtype=dtype,
  150. max_tokens=max_tokens,
  151. num_logprobs=num_logprobs,
  152. tensor_parallel_size=1,
  153. )