test_minicpmv.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. from typing import List, Optional, Tuple, Type, Union
  2. import pytest
  3. import torch
  4. import torch.types
  5. from PIL import Image
  6. from transformers import BatchEncoding
  7. from aphrodite.common.sequence import SampleLogprobs
  8. from aphrodite.multimodal.utils import rescale_image_size
  9. from ....conftest import IMAGE_ASSETS, AphroditeRunner, HfRunner
  10. from ...utils import check_logprobs_close
  11. # The image token is placed before "user" on purpose so that the test can pass
  12. HF_IMAGE_PROMPTS = IMAGE_ASSETS.prompts({
  13. "stop_sign":
  14. "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" \
  15. "(<image>./</image>)\nWhat's the content of the image?<|eot_id|>" \
  16. "<|start_header_id|>assistant<|end_header_id|>\n\n", # noqa: E501
  17. "cherry_blossom":
  18. "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" \
  19. "(<image>./</image>)\nWhat is the season?<|eot_id|>" \
  20. "<|start_header_id|>assistant<|end_header_id|>\n\n",
  21. })
  22. HF_MULTIIMAGE_IMAGE_PROMPT = \
  23. "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" \
  24. "(<image>./</image>)\n(<image>./</image>)\n" \
  25. "Describe these images.<|eot_id|>" \
  26. "<|start_header_id|>assistant<|end_header_id|>\n\n"
  27. models = ["openbmb/MiniCPM-Llama3-V-2_5"]
  28. def _wrap_inputs(hf_inputs: BatchEncoding) -> BatchEncoding:
  29. return BatchEncoding({"model_inputs": hf_inputs})
  30. def trunc_hf_output(hf_output: Tuple[List[int], str,
  31. Optional[SampleLogprobs]]):
  32. output_ids, output_str, out_logprobs = hf_output
  33. if output_str.endswith("<|eot_id|>"):
  34. output_str = output_str.split("<|eot_id|>")[0]
  35. return output_ids, output_str, out_logprobs
  36. target_dtype = "half"
  37. def run_test(
  38. hf_runner: Type[HfRunner],
  39. aphrodite_runner: Type[AphroditeRunner],
  40. inputs: List[Tuple[List[str], Union[List[Image.Image],
  41. List[List[Image.Image]]]]],
  42. model: str,
  43. *,
  44. dtype: str,
  45. max_tokens: int,
  46. num_logprobs: int,
  47. mm_limit: int,
  48. tensor_parallel_size: int,
  49. distributed_executor_backend: Optional[str] = None,
  50. ):
  51. """Inference result should be the same between hf and aphrodite.
  52. All the image fixtures for the test are from IMAGE_ASSETS.
  53. For huggingface runner, we provide the PIL images as input.
  54. For aphrodite runner, we provide MultiModalDataDict objects
  55. and corresponding MultiModalConfig as input.
  56. Note, the text input is also adjusted to abide by aphrodite contract.
  57. The text output is sanitized to be able to compare with hf.
  58. """
  59. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  60. # Aphrodite needs a fresh new process without cuda initialization.
  61. # if we run HF first, the cuda initialization will be done and it
  62. # will hurt multiprocessing backend with fork method (the default method).
  63. # max_model_len should be greater than image_feature_size
  64. with aphrodite_runner(model,
  65. max_model_len=4096,
  66. max_num_seqs=1,
  67. dtype=dtype,
  68. limit_mm_per_prompt={"image": mm_limit},
  69. tensor_parallel_size=tensor_parallel_size,
  70. distributed_executor_backend=distributed_executor_backend,
  71. enforce_eager=True) as aphrodite_model:
  72. tokenizer = aphrodite_model.model.get_tokenizer()
  73. stop_token_ids = [tokenizer.eos_id, tokenizer.eot_id]
  74. aphrodite_outputs_per_image = [
  75. aphrodite_model.generate_greedy_logprobs(prompts,
  76. max_tokens,
  77. num_logprobs=num_logprobs,
  78. images=images,
  79. stop_token_ids=stop_token_ids)
  80. for prompts, images in inputs
  81. ]
  82. hf_model = hf_runner(model, dtype=dtype, postprocess_inputs=_wrap_inputs)
  83. with hf_model, torch.no_grad():
  84. hf_outputs_per_image = [
  85. hf_model.generate_greedy_logprobs_limit(prompts,
  86. max_tokens,
  87. num_logprobs=num_logprobs,
  88. images=images,
  89. tokenizer=tokenizer)
  90. for prompts, images in inputs
  91. ]
  92. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_image,
  93. aphrodite_outputs_per_image):
  94. check_logprobs_close(
  95. outputs_0_lst=[
  96. trunc_hf_output(hf_output) for hf_output in hf_outputs
  97. ],
  98. outputs_1_lst=aphrodite_outputs,
  99. name_0="hf",
  100. name_1="aphrodite",
  101. )
  102. @pytest.mark.parametrize("model", models)
  103. @pytest.mark.parametrize(
  104. "size_factors",
  105. [
  106. # No image
  107. [],
  108. # Single-scale
  109. [1.0],
  110. # Single-scale, batched
  111. [1.0, 1.0, 1.0],
  112. # Multi-scale
  113. [0.25, 0.5, 1.0],
  114. ],
  115. )
  116. @pytest.mark.parametrize("dtype", [target_dtype])
  117. @pytest.mark.parametrize("max_tokens", [128])
  118. @pytest.mark.parametrize("num_logprobs", [5])
  119. def test_models(hf_runner, aphrodite_runner, image_assets, model, size_factors,
  120. dtype: str, max_tokens: int, num_logprobs: int) -> None:
  121. images = [asset.pil_image for asset in image_assets]
  122. inputs_per_image = [(
  123. [prompt for _ in size_factors],
  124. [rescale_image_size(image, factor) for factor in size_factors],
  125. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  126. run_test(
  127. hf_runner,
  128. aphrodite_runner,
  129. inputs_per_image,
  130. model,
  131. dtype=dtype,
  132. max_tokens=max_tokens,
  133. num_logprobs=num_logprobs,
  134. mm_limit=1,
  135. tensor_parallel_size=1,
  136. )
  137. @pytest.mark.parametrize("model", models)
  138. @pytest.mark.parametrize(
  139. "size_factors",
  140. [
  141. # No image
  142. [],
  143. # Single-scale
  144. [1.0],
  145. # Single-scale, batched
  146. [1.0, 1.0, 1.0],
  147. # Multi-scale
  148. [0.25, 0.5, 1.0],
  149. ],
  150. )
  151. @pytest.mark.parametrize("dtype", [target_dtype])
  152. @pytest.mark.parametrize("max_tokens", [128])
  153. @pytest.mark.parametrize("num_logprobs", [5])
  154. def test_multi_images_models(hf_runner, aphrodite_runner, image_assets, model,
  155. size_factors, dtype: str, max_tokens: int,
  156. num_logprobs: int) -> None:
  157. images = [asset.pil_image for asset in image_assets]
  158. inputs_per_case = [
  159. ([HF_MULTIIMAGE_IMAGE_PROMPT for _ in size_factors],
  160. [[rescale_image_size(image, factor) for image in images]
  161. for factor in size_factors])
  162. ]
  163. run_test(
  164. hf_runner,
  165. aphrodite_runner,
  166. inputs_per_case,
  167. model,
  168. dtype=dtype,
  169. max_tokens=max_tokens,
  170. num_logprobs=num_logprobs,
  171. mm_limit=2,
  172. tensor_parallel_size=1,
  173. )