test_minicpmv.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. from typing import List, Optional, Tuple, Type
  2. import pytest
  3. import torch
  4. import torch.types
  5. from transformers import BatchEncoding
  6. from aphrodite.common.sequence import SampleLogprobs
  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. # 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. models = ["openbmb/MiniCPM-Llama3-V-2_5"]
  23. def _wrap_inputs(hf_inputs: BatchEncoding) -> BatchEncoding:
  24. return BatchEncoding({"model_inputs": hf_inputs})
  25. def trunc_hf_output(hf_output: Tuple[List[int], str,
  26. Optional[SampleLogprobs]]):
  27. output_ids, output_str, out_logprobs = hf_output
  28. if output_str.endswith("<|eot_id|>"):
  29. output_str = output_str.split("<|eot_id|>")[0]
  30. return output_ids, output_str, out_logprobs
  31. target_dtype = "half"
  32. def run_test(
  33. hf_runner: Type[HfRunner],
  34. aphrodite_runner: Type[AphroditeRunner],
  35. image_assets: _ImageAssets,
  36. model: str,
  37. *,
  38. size_factors: List[float],
  39. dtype: str,
  40. max_tokens: int,
  41. num_logprobs: int,
  42. tensor_parallel_size: int,
  43. distributed_executor_backend: Optional[str] = None,
  44. ):
  45. """Inference result should be the same between hf and aphrodite.
  46. All the image fixtures for the test is under tests/images.
  47. For huggingface runner, we provide the PIL images as input.
  48. For aphrodite runner, we provide MultiModalDataDict objects
  49. and corresponding MultiModalConfig as input.
  50. Note, the text input is also adjusted to abide by aphrodite contract.
  51. The text output is sanitized to be able to compare with hf.
  52. """
  53. images = [asset.pil_image for asset in image_assets]
  54. inputs_per_image = [(
  55. [prompt for _ in size_factors],
  56. [rescale_image_size(image, factor) for factor in size_factors],
  57. ) for image, prompt in zip(images, HF_IMAGE_PROMPTS)]
  58. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  59. # Aphrodite needs a fresh new process without cuda initialization.
  60. # if we run HF first, the cuda initialization will be done and it
  61. # will hurt multiprocessing backend with fork method (the default method).
  62. # max_model_len should be greater than image_feature_size
  63. with aphrodite_runner(model,
  64. max_model_len=4096,
  65. max_num_seqs=1,
  66. dtype=dtype,
  67. tensor_parallel_size=tensor_parallel_size,
  68. distributed_executor_backend=distributed_executor_backend,
  69. enforce_eager=True) as aphrodite_model:
  70. tokenizer = aphrodite_model.model.get_tokenizer()
  71. stop_token_ids = [tokenizer.eos_id, tokenizer.eot_id]
  72. aphrodite_outputs_per_image = [
  73. aphrodite_model.generate_greedy_logprobs(prompts,
  74. max_tokens,
  75. num_logprobs=num_logprobs,
  76. images=images,
  77. stop_token_ids=stop_token_ids)
  78. for prompts, images in inputs_per_image
  79. ]
  80. hf_model = hf_runner(model, dtype=dtype, postprocess_inputs=_wrap_inputs)
  81. with hf_model, torch.no_grad():
  82. hf_outputs_per_image = [
  83. hf_model.generate_greedy_logprobs_limit(prompts,
  84. max_tokens,
  85. num_logprobs=num_logprobs,
  86. images=images,
  87. tokenizer=tokenizer)
  88. for prompts, images in inputs_per_image
  89. ]
  90. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_image,
  91. aphrodite_outputs_per_image):
  92. check_logprobs_close(
  93. outputs_0_lst=[
  94. trunc_hf_output(hf_output) for hf_output in hf_outputs
  95. ],
  96. outputs_1_lst=aphrodite_outputs,
  97. name_0="hf",
  98. name_1="aphrodite",
  99. )
  100. @pytest.mark.parametrize("model", models)
  101. @pytest.mark.parametrize(
  102. "size_factors",
  103. [
  104. # No image
  105. [],
  106. # Single-scale
  107. [1.0],
  108. # Single-scale, batched
  109. [1.0, 1.0, 1.0],
  110. # Multi-scale
  111. [0.25, 0.5, 1.0],
  112. ],
  113. )
  114. @pytest.mark.parametrize("dtype", [target_dtype])
  115. @pytest.mark.parametrize("max_tokens", [128])
  116. @pytest.mark.parametrize("num_logprobs", [5])
  117. def test_models(hf_runner, aphrodite_runner, image_assets, model, size_factors,
  118. dtype: str, max_tokens: int, num_logprobs: int) -> None:
  119. run_test(
  120. hf_runner,
  121. aphrodite_runner,
  122. image_assets,
  123. model,
  124. size_factors=size_factors,
  125. dtype=dtype,
  126. max_tokens=max_tokens,
  127. num_logprobs=num_logprobs,
  128. tensor_parallel_size=1,
  129. )
  130. HF_MULTIIMAGE_IMAGE_PROMPT = \
  131. "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\n" \
  132. "(<image>./</image>)\n(<image>./</image>)\n" \
  133. "Describe these images.<|eot_id|>" \
  134. "<|start_header_id|>assistant<|end_header_id|>\n\n"
  135. def run_multi_image_test(
  136. hf_runner: Type[HfRunner],
  137. aphrodite_runner: Type[AphroditeRunner],
  138. image_assets: _ImageAssets,
  139. model: str,
  140. *,
  141. size_factors: List[float],
  142. dtype: str,
  143. max_tokens: int,
  144. num_logprobs: int,
  145. tensor_parallel_size: int,
  146. distributed_executor_backend: Optional[str] = None,
  147. ):
  148. """Inference result should be the same between hf and aphrodite.
  149. All the image fixtures for the test is under tests/images.
  150. For huggingface runner, we provide the PIL images as input.
  151. For aphrodite runner, we provide MultiModalDataDict objects
  152. and corresponding MultiModalConfig as input.
  153. Note, the text input is also adjusted to abide by aphrodite contract.
  154. The text output is sanitized to be able to compare with hf.
  155. """
  156. images = [asset.pil_image for asset in image_assets]
  157. inputs_per_case = [
  158. ([HF_MULTIIMAGE_IMAGE_PROMPT for _ in size_factors],
  159. [[rescale_image_size(image, factor) for image in images]
  160. for factor in size_factors])
  161. ]
  162. # NOTE: take care of the order. run Aphrodite first, and then run HF.
  163. # Aphrodite needs a fresh new process without cuda initialization.
  164. # if we run HF first, the cuda initialization will be done and it
  165. # will hurt multiprocessing backend with fork method (the default method).
  166. # max_model_len should be greater than image_feature_size
  167. with aphrodite_runner(model,
  168. max_model_len=4096,
  169. max_num_seqs=1,
  170. limit_mm_per_prompt={"image": len(images)},
  171. dtype=dtype,
  172. tensor_parallel_size=tensor_parallel_size,
  173. distributed_executor_backend=distributed_executor_backend,
  174. enforce_eager=True) as aphrodite_model:
  175. tokenizer = aphrodite_model.model.get_tokenizer()
  176. stop_token_ids = [tokenizer.eos_id, tokenizer.eot_id]
  177. aphrodite_outputs_per_case = [
  178. aphrodite_model.generate_greedy_logprobs(prompts,
  179. max_tokens,
  180. num_logprobs=num_logprobs,
  181. images=images,
  182. stop_token_ids=stop_token_ids)
  183. for prompts, images in inputs_per_case
  184. ]
  185. hf_model = hf_runner(model, dtype=dtype, postprocess_inputs=_wrap_inputs)
  186. with hf_model, torch.no_grad():
  187. hf_outputs_per_case = [
  188. hf_model.generate_greedy_logprobs_limit(prompts,
  189. max_tokens,
  190. num_logprobs=num_logprobs,
  191. images=images,
  192. tokenizer=tokenizer)
  193. for prompts, images in inputs_per_case
  194. ]
  195. for hf_outputs, aphrodite_outputs in zip(hf_outputs_per_case,
  196. aphrodite_outputs_per_case):
  197. check_logprobs_close(
  198. outputs_0_lst=[
  199. trunc_hf_output(hf_output) for hf_output in hf_outputs
  200. ],
  201. outputs_1_lst=aphrodite_outputs,
  202. name_0="hf",
  203. name_1="aphrodite",
  204. )
  205. @pytest.mark.parametrize("model", models)
  206. @pytest.mark.parametrize(
  207. "size_factors",
  208. [
  209. # No image
  210. [],
  211. # Single-scale
  212. [1.0],
  213. # Single-scale, batched
  214. [1.0, 1.0, 1.0],
  215. # Multi-scale
  216. [0.25, 0.5, 1.0],
  217. ],
  218. )
  219. @pytest.mark.parametrize("dtype", [target_dtype])
  220. @pytest.mark.parametrize("max_tokens", [128])
  221. @pytest.mark.parametrize("num_logprobs", [5])
  222. def test_multi_images_models(hf_runner, aphrodite_runner, image_assets, model,
  223. size_factors, dtype: str, max_tokens: int,
  224. num_logprobs: int) -> None:
  225. run_multi_image_test(
  226. hf_runner,
  227. aphrodite_runner,
  228. image_assets,
  229. model,
  230. size_factors=size_factors,
  231. dtype=dtype,
  232. max_tokens=max_tokens,
  233. num_logprobs=num_logprobs,
  234. tensor_parallel_size=1,
  235. )