test_llava_onevision.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. from typing import List, Optional, Tuple, Type, overload
  2. import pytest
  3. import transformers
  4. from transformers import (AutoConfig, AutoModelForVision2Seq, AutoTokenizer,
  5. BatchEncoding)
  6. from aphrodite.common.sequence import SampleLogprobs
  7. from aphrodite.common.utils import STR_DTYPE_TO_TORCH_DTYPE
  8. from aphrodite.multimodal.utils import (rescale_image_size, rescale_video_size,
  9. resize_video, sample_frames_from_video)
  10. from ....conftest import (VIDEO_ASSETS, AphroditeRunner, HfRunner,
  11. PromptImageInput, _VideoAssets)
  12. from ...utils import check_logprobs_close
  13. # Video test
  14. HF_VIDEO_PROMPTS = VIDEO_ASSETS.prompts(
  15. {
  16. "sample_demo_1": "<|im_start|>user <video>\nwhy is this video funny? \
  17. <|im_end|><|im_start|>assistant\n"
  18. }
  19. )
  20. models = ["llava-hf/llava-onevision-qwen2-7b-ov-hf"]
  21. def aphrodite_to_hf_output(
  22. aphrodite_output: Tuple[List[int], str, Optional[SampleLogprobs]], model: str
  23. ):
  24. """Sanitize aphrodite output to be comparable with hf output."""
  25. output_ids, output_str, out_logprobs = aphrodite_output
  26. config = AutoConfig.from_pretrained(model)
  27. video_token_id = config.video_token_index
  28. tokenizer = AutoTokenizer.from_pretrained(model)
  29. eos_token_id = tokenizer.eos_token_id
  30. hf_output_ids = [
  31. token_id
  32. for idx, token_id in enumerate(output_ids)
  33. if token_id != video_token_id or output_ids[idx - 1] != video_token_id
  34. ]
  35. hf_output_str = output_str
  36. if hf_output_ids[-1] == eos_token_id:
  37. hf_output_str = hf_output_str + tokenizer.decode(eos_token_id)
  38. return hf_output_ids, hf_output_str, out_logprobs
  39. @overload
  40. def run_video_test(
  41. hf_runner: Type[HfRunner],
  42. aphrodite_runner: Type[AphroditeRunner],
  43. video_assets: _VideoAssets,
  44. model: str,
  45. *,
  46. size_factors: List[float],
  47. dtype: str,
  48. max_tokens: int,
  49. num_logprobs: int,
  50. num_frames: int,
  51. tensor_parallel_size: int,
  52. distributed_executor_backend: Optional[str] = None,
  53. ):
  54. ...
  55. @overload
  56. def run_video_test(
  57. hf_runner: Type[HfRunner],
  58. aphrodite_runner: Type[AphroditeRunner],
  59. video_assets: _VideoAssets,
  60. model: str,
  61. *,
  62. sizes: List[Tuple[int, int]],
  63. dtype: str,
  64. max_tokens: int,
  65. num_logprobs: int,
  66. num_frames: int,
  67. tensor_parallel_size: int,
  68. distributed_executor_backend: Optional[str] = None,
  69. ):
  70. ...
  71. def run_video_test(
  72. hf_runner: Type[HfRunner],
  73. aphrodite_runner: Type[AphroditeRunner],
  74. video_assets: _VideoAssets,
  75. model: str,
  76. *,
  77. size_factors: Optional[List[float]] = None,
  78. sizes: Optional[List[Tuple[int, int]]] = None,
  79. dtype: str,
  80. max_tokens: int,
  81. num_logprobs: int,
  82. num_frames: int,
  83. tensor_parallel_size: int,
  84. distributed_executor_backend: Optional[str] = None,
  85. ):
  86. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
  87. videos = [
  88. sample_frames_from_video(asset.np_ndarrays, num_frames)
  89. for asset in video_assets
  90. ]
  91. if size_factors is not None:
  92. inputs_per_video = [
  93. (
  94. [prompt for _ in size_factors],
  95. [rescale_video_size(video, factor) for factor in size_factors],
  96. )
  97. for video, prompt in zip(videos, HF_VIDEO_PROMPTS)
  98. ]
  99. elif sizes is not None:
  100. inputs_per_video = [
  101. (
  102. [prompt for _ in sizes],
  103. [resize_video(video, size) for size in sizes],
  104. )
  105. for video, prompt in zip(videos, HF_VIDEO_PROMPTS)
  106. ]
  107. else:
  108. raise ValueError("You must provide either `size_factors` or `sizes`")
  109. # max_model_len should be greater than image_feature_size
  110. with aphrodite_runner(
  111. model,
  112. dtype=dtype,
  113. max_model_len=4096,
  114. tensor_parallel_size=tensor_parallel_size,
  115. distributed_executor_backend=distributed_executor_backend,
  116. enforce_eager=True,
  117. ) as aphrodite_model:
  118. aphrodite_outputs_per_video = [
  119. aphrodite_model.generate_greedy_logprobs(
  120. prompts, max_tokens, num_logprobs=num_logprobs, videos=videos
  121. )
  122. for prompts, videos in inputs_per_video
  123. ]
  124. def process(hf_inputs: BatchEncoding):
  125. hf_inputs["pixel_values_videos"] = hf_inputs["pixel_values_videos"].to(
  126. torch_dtype
  127. ) # type: ignore
  128. return hf_inputs
  129. with hf_runner(
  130. model,
  131. dtype=dtype,
  132. postprocess_inputs=process,
  133. auto_cls=AutoModelForVision2Seq,
  134. ) as hf_model:
  135. hf_outputs_per_video = [
  136. hf_model.generate_greedy_logprobs_limit(
  137. prompts, max_tokens, num_logprobs=num_logprobs, videos=videos
  138. )
  139. for prompts, videos in inputs_per_video
  140. ]
  141. for hf_outputs, aphrodite_outputs in zip(
  142. hf_outputs_per_video, aphrodite_outputs_per_video
  143. ):
  144. # TODO: Check whether using original CLIPVisionModel can improve
  145. # consistency against HF
  146. check_logprobs_close(
  147. outputs_0_lst=hf_outputs,
  148. outputs_1_lst=[
  149. aphrodite_to_hf_output(aphrodite_output, model)
  150. for aphrodite_output in aphrodite_outputs
  151. ],
  152. name_0="hf",
  153. name_1="aphrodite",
  154. )
  155. @pytest.mark.skipif(
  156. transformers.__version__ < "4.45",
  157. reason="Waiting for next transformers release",
  158. )
  159. @pytest.mark.parametrize("model", models)
  160. @pytest.mark.parametrize(
  161. "size_factors",
  162. [
  163. # No video
  164. [],
  165. # Single-scale
  166. [1.0],
  167. # Single-scale, batched
  168. [1.0, 1.0, 1.0],
  169. # Multi-scale
  170. [0.25, 0.5, 1.0],
  171. ],
  172. )
  173. @pytest.mark.parametrize("dtype", ["half"])
  174. @pytest.mark.parametrize("max_tokens", [128])
  175. @pytest.mark.parametrize("num_logprobs", [5])
  176. @pytest.mark.parametrize("num_frames", [16])
  177. def test_models(
  178. hf_runner,
  179. aphrodite_runner,
  180. video_assets,
  181. model,
  182. size_factors,
  183. dtype,
  184. max_tokens,
  185. num_logprobs,
  186. num_frames,
  187. ) -> None:
  188. """Inference result should be the same between hf and aphrodite.
  189. All the image fixtures for the test is under tests/videos.
  190. For huggingface runner, we provide the np.ndarray as input.
  191. For aphrodite runner, we provide MultiModalDataDict objects
  192. and corresponding MultiModalConfig as input.
  193. Note, the text input is also adjusted to abide by aphrodite contract.
  194. The text output is sanitized to be able to compare with hf.
  195. """
  196. run_video_test(
  197. hf_runner,
  198. aphrodite_runner,
  199. video_assets,
  200. model,
  201. size_factors=size_factors,
  202. dtype=dtype,
  203. max_tokens=max_tokens,
  204. num_logprobs=num_logprobs,
  205. num_frames=num_frames,
  206. tensor_parallel_size=1,
  207. )
  208. @pytest.mark.skipif(
  209. transformers.__version__ < "4.45",
  210. reason="Waiting for next transformers release",
  211. )
  212. @pytest.mark.parametrize("model", models)
  213. @pytest.mark.parametrize(
  214. "sizes",
  215. [[(1669, 2560), (2560, 1669), (183, 488), (488, 183)]],
  216. )
  217. @pytest.mark.parametrize("dtype", ["half"])
  218. @pytest.mark.parametrize("max_tokens", [128])
  219. @pytest.mark.parametrize("num_logprobs", [5])
  220. @pytest.mark.parametrize("num_frames", [16])
  221. def test_models_fixed_sizes(
  222. hf_runner,
  223. aphrodite_runner,
  224. video_assets,
  225. model,
  226. sizes,
  227. dtype,
  228. max_tokens,
  229. num_logprobs,
  230. num_frames,
  231. ) -> None:
  232. run_video_test(
  233. hf_runner,
  234. aphrodite_runner,
  235. video_assets,
  236. model,
  237. sizes=sizes,
  238. dtype=dtype,
  239. max_tokens=max_tokens,
  240. num_logprobs=num_logprobs,
  241. num_frames=num_frames,
  242. tensor_parallel_size=1,
  243. )
  244. # Image test
  245. _LIMIT_IMAGE_PER_PROMPT = 4
  246. def run_image_test(
  247. hf_runner: Type[HfRunner],
  248. aphrodite_runner: Type[AphroditeRunner],
  249. inputs: List[Tuple[List[str], PromptImageInput]],
  250. model: str,
  251. dtype: str,
  252. max_tokens: int,
  253. num_logprobs: int,
  254. tensor_parallel_size: int,
  255. distributed_executor_backend: Optional[str] = None,
  256. ):
  257. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
  258. # max_model_len should be greater than image_feature_size
  259. with aphrodite_runner(
  260. model,
  261. dtype=dtype,
  262. max_model_len=32768,
  263. tensor_parallel_size=tensor_parallel_size,
  264. distributed_executor_backend=distributed_executor_backend,
  265. enforce_eager=True,
  266. limit_mm_per_prompt={"image": _LIMIT_IMAGE_PER_PROMPT},
  267. ) as aphrodite_model:
  268. aphrodite_outputs_per_image = [
  269. aphrodite_model.generate_greedy_logprobs(
  270. prompts, max_tokens, num_logprobs=num_logprobs, images=images
  271. )
  272. for prompts, images in inputs
  273. ]
  274. def process(hf_inputs: BatchEncoding):
  275. hf_inputs["pixel_values"] = hf_inputs["pixel_values"].to(torch_dtype) # type: ignore
  276. return hf_inputs
  277. with hf_runner(
  278. model,
  279. dtype=dtype,
  280. postprocess_inputs=process,
  281. auto_cls=AutoModelForVision2Seq,
  282. ) as hf_model:
  283. hf_outputs_per_image = [
  284. hf_model.generate_greedy_logprobs_limit(
  285. prompts, max_tokens, num_logprobs=num_logprobs, images=images
  286. )
  287. for prompts, images in inputs
  288. ]
  289. for hf_outputs, aphrodite_outputs in zip(
  290. hf_outputs_per_image, aphrodite_outputs_per_image
  291. ):
  292. # TODO: Check whether using original CLIPVisionModel can improve
  293. # consistency against HF
  294. check_logprobs_close(
  295. outputs_0_lst=hf_outputs,
  296. outputs_1_lst=[
  297. aphrodite_to_hf_output(aphrodite_output, model)
  298. for aphrodite_output in aphrodite_outputs
  299. ],
  300. name_0="hf",
  301. name_1="aphrodite",
  302. )
  303. @pytest.mark.skipif(
  304. transformers.__version__ < "4.45",
  305. reason="Waiting for next transformers release",
  306. )
  307. @pytest.mark.parametrize("model", models)
  308. @pytest.mark.parametrize("dtype", ["half"])
  309. @pytest.mark.parametrize("max_tokens", [128])
  310. @pytest.mark.parametrize("num_logprobs", [5])
  311. def test_models_multiple_image_inputs(
  312. hf_runner, aphrodite_runner, image_assets, model, dtype, max_tokens, num_logprobs
  313. ) -> None:
  314. stop_sign = image_assets[0].pil_image
  315. cherry_blossom = image_assets[1].pil_image
  316. inputs = [
  317. (
  318. [
  319. "<|im_start|>user <image><image>\nDescribe 2 images. \
  320. <|im_end|><|im_start|>assistant\n",
  321. "<|im_start|>user <image><image>\nDescribe 2 images. \
  322. <|im_end|><|im_start|>assistant\n",
  323. "<|im_start|>user <image><image><image><image>\nDescribe 4 images. \
  324. <|im_end|><|im_start|>assistant\n",
  325. "<|im_start|>user <image>\nWhat is the season? \
  326. <|im_end|><|im_start|>assistant\n",
  327. ],
  328. [
  329. [stop_sign, cherry_blossom],
  330. # Images with different sizes and aspect-ratios
  331. [
  332. rescale_image_size(stop_sign, 0.1),
  333. stop_sign,
  334. ],
  335. [
  336. stop_sign,
  337. rescale_image_size(stop_sign, 0.25),
  338. cherry_blossom.resize((183, 488)),
  339. cherry_blossom.resize((488, 183)),
  340. ],
  341. cherry_blossom,
  342. ],
  343. )
  344. ]
  345. run_image_test(
  346. hf_runner,
  347. aphrodite_runner,
  348. inputs,
  349. model,
  350. dtype=dtype,
  351. max_tokens=max_tokens,
  352. num_logprobs=num_logprobs,
  353. tensor_parallel_size=1,
  354. )