1
0

conftest.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. import contextlib
  2. import gc
  3. import json
  4. import os
  5. import sys
  6. import tempfile
  7. from collections import UserList
  8. from enum import Enum
  9. from typing import (Any, Callable, Dict, List, Optional, Tuple, TypedDict,
  10. TypeVar, Union)
  11. import numpy as np
  12. import pytest
  13. import torch
  14. import torch.nn as nn
  15. import torch.nn.functional as F
  16. from huggingface_hub import snapshot_download
  17. from loguru import logger
  18. from PIL import Image
  19. from transformers import (AutoModelForCausalLM, AutoTokenizer, BatchEncoding,
  20. BatchFeature)
  21. from aphrodite import LLM, SamplingParams
  22. from aphrodite.assets.image import ImageAsset
  23. from aphrodite.assets.video import VideoAsset
  24. from aphrodite.common.config import TokenizerPoolConfig
  25. from aphrodite.common.outputs import RequestOutput
  26. from aphrodite.common.sequence import SampleLogprobs
  27. from aphrodite.common.utils import (STR_DTYPE_TO_TORCH_DTYPE,
  28. cuda_device_count_stateless, identity,
  29. is_cpu)
  30. from aphrodite.connections import global_http_connection
  31. from aphrodite.distributed import (destroy_distributed_environment,
  32. destroy_model_parallel,
  33. init_distributed_environment,
  34. initialize_model_parallel)
  35. from aphrodite.inputs import (ExplicitEncoderDecoderPrompt, TextPrompt,
  36. to_enc_dec_tuple_list, zip_enc_dec_prompts)
  37. _TEST_DIR = os.path.dirname(__file__)
  38. _TEST_PROMPTS = [os.path.join(_TEST_DIR, "prompts", "example.txt")]
  39. _LONG_PROMPTS = [os.path.join(_TEST_DIR, "prompts", "summary.txt")]
  40. PromptImageInput = Union[List[Image.Image], List[List[Image.Image]]]
  41. PromptAudioInput = Union[List[Tuple[np.ndarray, int]],
  42. List[List[Tuple[np.ndarray, int]]]]
  43. PromptVideoInput = Union[List[np.ndarray], List[List[np.ndarray]]]
  44. def _read_prompts(filename: str) -> List[str]:
  45. with open(filename, "r") as f:
  46. prompts = f.readlines()
  47. return prompts
  48. class _ImageAssetPrompts(TypedDict):
  49. stop_sign: str
  50. cherry_blossom: str
  51. if sys.version_info < (3, 9):
  52. # UserList cannot be subscripted
  53. class _ImageAssetsBase(UserList):
  54. pass
  55. else:
  56. class _ImageAssetsBase(UserList[ImageAsset]):
  57. pass
  58. class _ImageAssets(_ImageAssetsBase):
  59. def __init__(self) -> None:
  60. super().__init__([
  61. ImageAsset("stop_sign"),
  62. ImageAsset("cherry_blossom"),
  63. ])
  64. def prompts(self, prompts: _ImageAssetPrompts) -> List[str]:
  65. """
  66. Convenience method to define the prompt for each test image.
  67. The order of the returned prompts matches the order of the
  68. assets when iterating through this object.
  69. """
  70. return [prompts["stop_sign"], prompts["cherry_blossom"]]
  71. class _VideoAssetPrompts(TypedDict):
  72. sample_demo_1: str
  73. if sys.version_info < (3, 9):
  74. # UserList cannot be subscripted
  75. class _VideoAssetsBase(UserList):
  76. pass
  77. else:
  78. class _VideoAssetsBase(UserList[VideoAsset]):
  79. pass
  80. class _VideoAssets(_VideoAssetsBase):
  81. def __init__(self) -> None:
  82. super().__init__([
  83. VideoAsset("sample_demo_1.mp4"),
  84. ])
  85. def prompts(self, prompts: _VideoAssetPrompts) -> List[str]:
  86. return [prompts["sample_demo_1"]]
  87. IMAGE_ASSETS = _ImageAssets()
  88. """Singleton instance of :class:`_ImageAssets`."""
  89. VIDEO_ASSETS = _VideoAssets()
  90. """Singleton instance of :class:`_VideoAssets`."""
  91. @pytest.fixture(autouse=True)
  92. def init_test_http_connection():
  93. # pytest_asyncio may use a different event loop per test
  94. # so we need to make sure the async client is created anew
  95. global_http_connection.reuse_client = False
  96. @pytest.fixture
  97. def dist_init():
  98. temp_file = tempfile.mkstemp()[1]
  99. init_distributed_environment(
  100. world_size=1,
  101. rank=0,
  102. distributed_init_method=f"file://{temp_file}",
  103. local_rank=0,
  104. backend="nccl",
  105. )
  106. initialize_model_parallel(1, 1)
  107. yield
  108. cleanup()
  109. def cleanup():
  110. destroy_model_parallel()
  111. destroy_distributed_environment()
  112. with contextlib.suppress(AssertionError):
  113. torch.distributed.destroy_process_group()
  114. gc.collect()
  115. if not is_cpu():
  116. torch.cuda.empty_cache()
  117. @pytest.fixture()
  118. def should_do_global_cleanup_after_test(request) -> bool:
  119. """Allow subdirectories to skip global cleanup by overriding this fixture.
  120. This can provide a ~10x speedup for non-GPU unit tests since they don't need
  121. to initialize torch.
  122. """
  123. if request.node.get_closest_marker("skip_global_cleanup"):
  124. return False
  125. return True
  126. @pytest.fixture(autouse=True)
  127. def cleanup_fixture(should_do_global_cleanup_after_test: bool):
  128. yield
  129. if should_do_global_cleanup_after_test:
  130. cleanup()
  131. @pytest.fixture
  132. def example_prompts() -> List[str]:
  133. prompts = []
  134. for filename in _TEST_PROMPTS:
  135. prompts += _read_prompts(filename)
  136. return prompts
  137. class DecoderPromptType(Enum):
  138. """For encoder/decoder models only."""
  139. CUSTOM = 1
  140. NONE = 2
  141. EMPTY_STR = 3
  142. @pytest.fixture
  143. def example_encoder_decoder_prompts(
  144. ) -> Dict[DecoderPromptType, List[ExplicitEncoderDecoderPrompt]]:
  145. '''
  146. Returns an encoder prompt list and a decoder prompt list, wherein each pair
  147. of same-index entries in both lists corresponds to an (encoder prompt,
  148. decoder prompt) tuple.
  149. Returns:
  150. * Encoder prompt list
  151. * Decoder prompt list (reverse of encoder prompt list)
  152. '''
  153. encoder_prompts = []
  154. for filename in _TEST_PROMPTS:
  155. encoder_prompts += _read_prompts(filename)
  156. custom_decoder_prompts = encoder_prompts[::-1]
  157. empty_str_decoder_prompts = [""] * len(encoder_prompts)
  158. none_decoder_prompts = [None] * len(encoder_prompts)
  159. # NONE decoder prompt type
  160. return {
  161. DecoderPromptType.NONE:
  162. zip_enc_dec_prompts(encoder_prompts, none_decoder_prompts),
  163. DecoderPromptType.EMPTY_STR:
  164. zip_enc_dec_prompts(encoder_prompts, empty_str_decoder_prompts),
  165. DecoderPromptType.CUSTOM:
  166. zip_enc_dec_prompts(encoder_prompts, custom_decoder_prompts),
  167. }
  168. @pytest.fixture
  169. def example_long_prompts() -> List[str]:
  170. prompts = []
  171. for filename in _LONG_PROMPTS:
  172. prompts += _read_prompts(filename)
  173. return prompts
  174. @pytest.fixture(scope="session")
  175. def image_assets() -> _ImageAssets:
  176. return IMAGE_ASSETS
  177. @pytest.fixture(scope="session")
  178. def video_assets() -> _VideoAssets:
  179. return VIDEO_ASSETS
  180. _T = TypeVar("_T", nn.Module, torch.Tensor, BatchEncoding, BatchFeature)
  181. class HfRunner:
  182. def wrap_device(self, input: _T) -> _T:
  183. if not is_cpu():
  184. # Check if the input is already on the GPU
  185. if hasattr(input, 'device') and input.device.type == "cuda":
  186. return input # Already on GPU, no need to move
  187. return input.to("cuda")
  188. else:
  189. # Check if the input is already on the CPU
  190. if hasattr(input, 'device') and input.device.type == "cpu":
  191. return input # Already on CPU, no need to move
  192. return input.to("cpu")
  193. def __init__(
  194. self,
  195. model_name: str,
  196. dtype: str = "half",
  197. *,
  198. model_kwargs: Optional[Dict[str, Any]] = None,
  199. is_embedding_model: bool = False,
  200. auto_cls=AutoModelForCausalLM,
  201. postprocess_inputs: Callable[[BatchEncoding],
  202. BatchEncoding] = identity,
  203. ) -> None:
  204. torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
  205. self.model_name = model_name
  206. if is_embedding_model:
  207. # Lazy init required for AMD CI
  208. from sentence_transformers import SentenceTransformer
  209. self.model = self.wrap_device(
  210. SentenceTransformer(
  211. model_name,
  212. device="cpu",
  213. ).to(dtype=torch_dtype))
  214. else:
  215. model_kwargs = model_kwargs if model_kwargs is not None else {}
  216. self.model = self.wrap_device(
  217. auto_cls.from_pretrained(
  218. model_name,
  219. torch_dtype=torch_dtype,
  220. trust_remote_code=True,
  221. **model_kwargs,
  222. ))
  223. self.tokenizer = AutoTokenizer.from_pretrained(
  224. model_name,
  225. torch_dtype=torch_dtype,
  226. trust_remote_code=True,
  227. )
  228. try:
  229. # don't put this import at the top level
  230. # it will call torch.cuda.device_count()
  231. from transformers import AutoProcessor # noqa: F401
  232. self.processor = AutoProcessor.from_pretrained(
  233. model_name,
  234. torch_dtype=torch_dtype,
  235. trust_remote_code=True,
  236. )
  237. except Exception as exc:
  238. logger.warning(
  239. f"Unable to auto-load HuggingFace processor for model "
  240. f"({model_name}). Using tokenizer instead. Reason: {exc}")
  241. self.processor = self.tokenizer
  242. self.postprocess_inputs = postprocess_inputs
  243. def generate(
  244. self,
  245. prompts: List[str],
  246. images: Optional[PromptImageInput] = None,
  247. videos: Optional[List[np.ndarray]] = None,
  248. **kwargs: Any,
  249. ) -> List[Tuple[List[List[int]], List[str]]]:
  250. if images:
  251. assert len(prompts) == len(images)
  252. outputs: List[Tuple[List[List[int]], List[str]]] = []
  253. for i, prompt in enumerate(prompts):
  254. processor_kwargs: Dict[str, Any] = {
  255. "text": prompt,
  256. "return_tensors": "pt",
  257. }
  258. if images is not None and images[i] is not None:
  259. processor_kwargs["images"] = images[i]
  260. if videos is not None and videos[i] is not None:
  261. processor_kwargs["videos"] = videos[i]
  262. inputs = self.processor(**processor_kwargs)
  263. inputs = self.postprocess_inputs(inputs)
  264. output_ids = self.model.generate(
  265. **self.wrap_device(inputs),
  266. use_cache=True,
  267. **kwargs,
  268. )
  269. output_str = self.processor.batch_decode(
  270. output_ids,
  271. skip_special_tokens=True,
  272. clean_up_tokenization_spaces=False,
  273. )
  274. output_ids = output_ids.cpu().tolist()
  275. outputs.append((output_ids, output_str))
  276. return outputs
  277. def generate_greedy(
  278. self,
  279. prompts: List[str],
  280. max_tokens: int,
  281. images: Optional[PromptImageInput] = None,
  282. **kwargs: Any,
  283. ) -> List[Tuple[List[int], str]]:
  284. outputs = self.generate(prompts,
  285. do_sample=False,
  286. max_new_tokens=max_tokens,
  287. images=images,
  288. **kwargs)
  289. return [(output_ids[0], output_str[0])
  290. for output_ids, output_str in outputs]
  291. def generate_beam_search(
  292. self,
  293. prompts: List[str],
  294. beam_width: int,
  295. max_tokens: int,
  296. ) -> List[Tuple[List[List[int]], List[str]]]:
  297. outputs = self.generate(prompts,
  298. do_sample=False,
  299. max_new_tokens=max_tokens,
  300. num_beams=beam_width,
  301. num_return_sequences=beam_width)
  302. for i in range(len(outputs)):
  303. output_ids, output_str = outputs[i]
  304. for j in range(len(output_ids)):
  305. output_ids[j] = [
  306. x for x in output_ids[j]
  307. if x != self.tokenizer.pad_token_id
  308. ]
  309. outputs[i] = (output_ids, output_str)
  310. return outputs
  311. def generate_greedy_logprobs(
  312. self,
  313. prompts: List[str],
  314. max_tokens: int,
  315. images: Optional[PromptImageInput] = None,
  316. videos: Optional[List[np.ndarray]] = None,
  317. **kwargs: Any,
  318. ) -> List[List[torch.Tensor]]:
  319. all_logprobs: List[List[torch.Tensor]] = []
  320. for i, prompt in enumerate(prompts):
  321. processor_kwargs: Dict[str, Any] = {
  322. "text": prompt,
  323. "return_tensors": "pt",
  324. }
  325. if images is not None and images[i] is not None:
  326. processor_kwargs["images"] = images[i]
  327. if videos is not None and videos[i] is not None:
  328. processor_kwargs["videos"] = videos[i]
  329. inputs = self.processor(**processor_kwargs)
  330. inputs = self.postprocess_inputs(inputs)
  331. output = self.model.generate(
  332. **self.wrap_device(inputs),
  333. use_cache=True,
  334. do_sample=False,
  335. max_new_tokens=max_tokens,
  336. output_hidden_states=True,
  337. return_dict_in_generate=True,
  338. **kwargs,
  339. )
  340. seq_logprobs: List[torch.Tensor] = []
  341. for hidden_states in output.hidden_states:
  342. last_hidden_states = hidden_states[-1][0]
  343. logits = torch.matmul(
  344. last_hidden_states,
  345. self.model.get_output_embeddings().weight.t(),
  346. )
  347. if self.model.get_output_embeddings().bias is not None:
  348. logits += self.model.get_output_embeddings(
  349. ).bias.unsqueeze(0)
  350. logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
  351. seq_logprobs.append(logprobs)
  352. all_logprobs.append(seq_logprobs)
  353. return all_logprobs
  354. def _hidden_states_to_logprobs(
  355. self,
  356. hidden_states,
  357. num_logprobs,
  358. ) -> Tuple[List[Dict[int, float]], int]:
  359. seq_logprobs: List[torch.Tensor] = []
  360. output_len = len(hidden_states)
  361. for _, hidden_state in enumerate(hidden_states):
  362. last_hidden_states = hidden_state[-1][0]
  363. logits = torch.matmul(
  364. last_hidden_states,
  365. self.model.get_output_embeddings().weight.t(),
  366. )
  367. if getattr(self.model.get_output_embeddings(), "bias",
  368. None) is not None:
  369. logits += self.model.get_output_embeddings().bias.unsqueeze(0)
  370. logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
  371. seq_logprobs.append(logprobs)
  372. # convert to dict
  373. seq_logprobs_lst: List[Dict[int, float]] = []
  374. for tok_idx, tok_logprobs in enumerate(seq_logprobs):
  375. # drop prompt logprobs
  376. if tok_idx == 0:
  377. tok_logprobs = tok_logprobs[-1, :].reshape(1, -1)
  378. topk = tok_logprobs.topk(num_logprobs)
  379. tok_logprobs_dct = {}
  380. for token_id, logprob in zip(topk.indices[0], topk.values[0]):
  381. tok_logprobs_dct[token_id.item()] = logprob.item()
  382. seq_logprobs_lst.append(tok_logprobs_dct)
  383. return (
  384. seq_logprobs_lst,
  385. output_len,
  386. )
  387. def generate_greedy_logprobs_limit(
  388. self,
  389. prompts: List[str],
  390. max_tokens: int,
  391. num_logprobs: int,
  392. images: Optional[PromptImageInput] = None,
  393. audios: Optional[PromptAudioInput] = None,
  394. videos: Optional[List[np.ndarray]] = None,
  395. **kwargs: Any,
  396. ) -> List[Tuple[List[int], str, List[Dict[int, float]]]]:
  397. all_logprobs: List[List[Dict[int, float]]] = []
  398. all_output_ids: List[List[int]] = []
  399. all_output_strs: List[str] = []
  400. for i, prompt in enumerate(prompts):
  401. processor_kwargs: Dict[str, Any] = {
  402. "text": prompt,
  403. "return_tensors": "pt",
  404. }
  405. if images is not None and images[i] is not None:
  406. processor_kwargs["images"] = images[i]
  407. if audios is not None:
  408. audio, sr = audios[i]
  409. processor_kwargs["audio"] = audio
  410. processor_kwargs["sampling_rate"] = sr
  411. if videos is not None:
  412. processor_kwargs["videos"] = videos[i]
  413. inputs = self.processor(**processor_kwargs)
  414. inputs = self.postprocess_inputs(inputs)
  415. output = self.model.generate(
  416. **self.wrap_device(inputs),
  417. use_cache=True,
  418. do_sample=False,
  419. max_new_tokens=max_tokens,
  420. output_hidden_states=True,
  421. return_dict_in_generate=True,
  422. **kwargs,
  423. )
  424. (
  425. seq_logprobs_lst,
  426. output_len,
  427. ) = self._hidden_states_to_logprobs(output.hidden_states,
  428. num_logprobs)
  429. all_logprobs.append(seq_logprobs_lst)
  430. seq_ids = output.sequences[0]
  431. output_len = len(seq_logprobs_lst)
  432. output_ids = seq_ids[-output_len:]
  433. all_output_ids.append(output_ids.tolist())
  434. all_output_strs.append(self.tokenizer.decode(output_ids))
  435. outputs = zip(all_output_ids, all_output_strs, all_logprobs)
  436. return [(output_ids, output_str, output_logprobs)
  437. for output_ids, output_str, output_logprobs in outputs]
  438. def generate_encoder_decoder_greedy_logprobs_limit(
  439. self,
  440. encoder_decoder_prompts: List[ExplicitEncoderDecoderPrompt[str, str]],
  441. max_tokens: int,
  442. num_logprobs: int,
  443. **kwargs: Any,
  444. ) -> List[Tuple[List[int], str, List[Dict[int, float]]]]:
  445. '''
  446. Greedy logprobs generation for Aphrodite encoder/decoder models
  447. '''
  448. all_logprobs: List[List[Dict[int, float]]] = []
  449. all_output_ids: List[List[int]] = []
  450. all_output_strs: List[str] = []
  451. for (encoder_prompt,
  452. decoder_prompt) in to_enc_dec_tuple_list(encoder_decoder_prompts):
  453. encoder_input_ids = self.wrap_device(
  454. self.tokenizer(encoder_prompt, return_tensors="pt").input_ids)
  455. decoder_input_ids = (
  456. None if decoder_prompt is None else self.wrap_device(
  457. self.tokenizer(decoder_prompt,
  458. return_tensors="pt").input_ids))
  459. output = self.model.generate(
  460. encoder_input_ids,
  461. decoder_input_ids=decoder_input_ids,
  462. use_cache=True,
  463. do_sample=False,
  464. max_new_tokens=max_tokens,
  465. output_hidden_states=True,
  466. return_dict_in_generate=True,
  467. **kwargs,
  468. )
  469. (
  470. seq_logprobs_lst,
  471. output_len,
  472. ) = self._hidden_states_to_logprobs(output.decoder_hidden_states,
  473. num_logprobs)
  474. all_logprobs.append(seq_logprobs_lst)
  475. seq_ids = output.sequences[0]
  476. output_ids = seq_ids[-output_len:]
  477. all_output_ids.append(output_ids.tolist())
  478. all_output_strs.append(self.tokenizer.decode(output_ids))
  479. outputs = zip(all_output_ids, all_output_strs, all_logprobs)
  480. return [(output_ids, output_str, output_logprobs)
  481. for output_ids, output_str, output_logprobs in outputs]
  482. def encode(self, prompts: List[str]) -> List[List[torch.Tensor]]:
  483. return self.model.encode(prompts)
  484. def __enter__(self):
  485. return self
  486. def __exit__(self, exc_type, exc_value, traceback):
  487. del self.model
  488. cleanup()
  489. @pytest.fixture(scope="session")
  490. def hf_runner():
  491. return HfRunner
  492. class AphroditeRunner:
  493. def __init__(
  494. self,
  495. model_name: str,
  496. tokenizer_name: Optional[str] = None,
  497. # Use smaller max model length, otherwise bigger model cannot run due
  498. # to kv cache size limit.
  499. max_model_len: int = 1024,
  500. dtype: str = "half",
  501. disable_log_stats: bool = True,
  502. tensor_parallel_size: int = 1,
  503. block_size: int = 16,
  504. enable_chunked_prefill: bool = False,
  505. swap_space: int = 4,
  506. enforce_eager: Optional[bool] = False,
  507. **kwargs,
  508. ) -> None:
  509. self.model = LLM(
  510. model=model_name,
  511. tokenizer=tokenizer_name,
  512. trust_remote_code=True,
  513. dtype=dtype,
  514. swap_space=swap_space,
  515. enforce_eager=enforce_eager,
  516. disable_log_stats=disable_log_stats,
  517. tensor_parallel_size=tensor_parallel_size,
  518. max_model_len=max_model_len,
  519. block_size=block_size,
  520. enable_chunked_prefill=enable_chunked_prefill,
  521. **kwargs,
  522. )
  523. def generate(
  524. self,
  525. prompts: List[str],
  526. sampling_params: SamplingParams,
  527. images: Optional[PromptImageInput] = None,
  528. ) -> List[Tuple[List[List[int]], List[str]]]:
  529. if images is not None:
  530. assert len(prompts) == len(images)
  531. inputs = [TextPrompt(prompt=prompt) for prompt in prompts]
  532. if images is not None:
  533. for i, image in enumerate(images):
  534. inputs[i]["multi_modal_data"] = {"image": image}
  535. req_outputs = self.model.generate(inputs,
  536. sampling_params=sampling_params)
  537. outputs: List[Tuple[List[List[int]], List[str]]] = []
  538. for req_output in req_outputs:
  539. prompt_str = req_output.prompt
  540. prompt_ids = req_output.prompt_token_ids
  541. req_sample_output_ids: List[List[int]] = []
  542. req_sample_output_strs: List[str] = []
  543. for sample in req_output.outputs:
  544. output_str = sample.text
  545. output_ids = list(sample.token_ids)
  546. req_sample_output_ids.append(prompt_ids + output_ids)
  547. req_sample_output_strs.append(prompt_str + output_str)
  548. outputs.append((req_sample_output_ids, req_sample_output_strs))
  549. return outputs
  550. @staticmethod
  551. def _final_steps_generate_w_logprobs(
  552. req_outputs: List[RequestOutput],
  553. ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
  554. outputs: List[Tuple[List[int], str, Optional[SampleLogprobs]]] = []
  555. for req_output in req_outputs:
  556. for sample in req_output.outputs:
  557. output_str = sample.text
  558. output_ids = list(sample.token_ids)
  559. output_logprobs = sample.logprobs
  560. outputs.append((output_ids, output_str, output_logprobs))
  561. return outputs
  562. def generate_w_logprobs(
  563. self,
  564. prompts: List[str],
  565. sampling_params: SamplingParams,
  566. images: Optional[PromptImageInput] = None,
  567. audios: Optional[PromptAudioInput] = None,
  568. videos: Optional[PromptVideoInput] = None,
  569. ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
  570. assert sampling_params.logprobs is not None
  571. if images is not None:
  572. assert len(prompts) == len(images)
  573. if videos is not None:
  574. assert len(prompts) == len(videos)
  575. inputs = [TextPrompt(prompt=prompt) for prompt in prompts]
  576. if images is not None:
  577. for i, image in enumerate(images):
  578. inputs[i]["multi_modal_data"] = {"image": image}
  579. if audios is not None:
  580. for i, audio in enumerate(audios):
  581. inputs[i]["multi_modal_data"] = {"audio": audio}
  582. if videos is not None:
  583. for i, video in enumerate(videos):
  584. inputs[i]["multi_modal_data"] = {"video": video}
  585. print(f"[INPUTS!!!!]: {inputs}, {sampling_params}")
  586. req_outputs = self.model.generate(inputs,
  587. sampling_params=sampling_params)
  588. return self._final_steps_generate_w_logprobs(req_outputs)
  589. def generate_encoder_decoder_w_logprobs(
  590. self,
  591. encoder_decoder_prompts: List[ExplicitEncoderDecoderPrompt[str, str]],
  592. sampling_params: SamplingParams,
  593. ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
  594. '''
  595. Logprobs generation for Aphrodite encoder/decoder models
  596. '''
  597. assert sampling_params.logprobs is not None
  598. req_outputs = self.model.generate(encoder_decoder_prompts,
  599. sampling_params=sampling_params)
  600. return self._final_steps_generate_w_logprobs(req_outputs)
  601. def generate_greedy(
  602. self,
  603. prompts: List[str],
  604. max_tokens: int,
  605. images: Optional[PromptImageInput] = None,
  606. ) -> List[Tuple[List[int], str]]:
  607. greedy_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
  608. outputs = self.generate(prompts, greedy_params, images=images)
  609. return [(output_ids[0], output_str[0])
  610. for output_ids, output_str in outputs]
  611. def generate_greedy_logprobs(
  612. self,
  613. prompts: List[str],
  614. max_tokens: int,
  615. num_logprobs: int,
  616. images: Optional[PromptImageInput] = None,
  617. audios: Optional[PromptAudioInput] = None,
  618. videos: Optional[PromptVideoInput] = None,
  619. stop_token_ids: Optional[List[int]] = None,
  620. ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
  621. greedy_logprobs_params = SamplingParams(temperature=0.0,
  622. max_tokens=max_tokens,
  623. logprobs=num_logprobs,
  624. stop_token_ids=stop_token_ids)
  625. outputs = self.generate_w_logprobs(prompts,
  626. greedy_logprobs_params,
  627. images=images,
  628. audios=audios,
  629. videos=videos)
  630. return [(output_ids, output_str, output_logprobs)
  631. for output_ids, output_str, output_logprobs in outputs]
  632. def generate_encoder_decoder_greedy_logprobs(
  633. self,
  634. encoder_decoder_prompts: List[ExplicitEncoderDecoderPrompt[str, str]],
  635. max_tokens: int,
  636. num_logprobs: int,
  637. ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
  638. greedy_logprobs_params = SamplingParams(temperature=0.0,
  639. use_beam_search=False,
  640. max_tokens=max_tokens,
  641. logprobs=num_logprobs)
  642. '''
  643. Greedy logprobs generation for Aphrodite encoder/decoder models
  644. '''
  645. outputs = self.generate_encoder_decoder_w_logprobs(
  646. encoder_decoder_prompts, greedy_logprobs_params)
  647. return [(output_ids, output_str, output_logprobs)
  648. for output_ids, output_str, output_logprobs in outputs]
  649. def generate_beam_search(
  650. self,
  651. prompts: List[str],
  652. beam_width: int,
  653. max_tokens: int,
  654. ) -> List[Tuple[List[List[int]], List[str]]]:
  655. beam_search_params = SamplingParams(n=beam_width,
  656. use_beam_search=True,
  657. temperature=0.0,
  658. max_tokens=max_tokens)
  659. outputs = self.generate(prompts, beam_search_params)
  660. return outputs
  661. def encode(self, prompts: List[str]) -> List[List[float]]:
  662. req_outputs = self.model.encode(prompts)
  663. outputs = []
  664. for req_output in req_outputs:
  665. embedding = req_output.outputs.embedding
  666. outputs.append(embedding)
  667. return outputs
  668. def __enter__(self):
  669. return self
  670. def __exit__(self, exc_type, exc_value, traceback):
  671. del self.model
  672. cleanup()
  673. @pytest.fixture(scope="session")
  674. def aphrodite_runner():
  675. return AphroditeRunner
  676. def get_tokenizer_pool_config(tokenizer_group_type):
  677. if tokenizer_group_type is None:
  678. return None
  679. if tokenizer_group_type == "ray":
  680. return TokenizerPoolConfig(pool_size=1,
  681. pool_type="ray",
  682. extra_config={})
  683. if isinstance(tokenizer_group_type, type):
  684. return TokenizerPoolConfig(pool_size=1,
  685. pool_type=tokenizer_group_type,
  686. extra_config={})
  687. raise ValueError(f"Unknown tokenizer_group_type: {tokenizer_group_type}")
  688. @pytest.fixture()
  689. def temporary_enable_log_propagate():
  690. import logging
  691. logger = logging.getLogger("aphrodite")
  692. logger.propagate = True
  693. yield
  694. logger.propagate = False
  695. @pytest.fixture()
  696. def caplog_aphrodite(temporary_enable_log_propagate, caplog):
  697. # To capture aphrodite log, we should enable propagate=True temporarily
  698. # because caplog depends on logs propagated to the root logger.
  699. yield caplog
  700. @pytest.fixture(scope="session")
  701. def num_gpus_available():
  702. """Get number of GPUs without initializing the CUDA context
  703. in current process."""
  704. return cuda_device_count_stateless()
  705. temp_dir = tempfile.gettempdir()
  706. _dummy_path = os.path.join(temp_dir, "dummy_opt")
  707. @pytest.fixture
  708. def dummy_opt_path():
  709. json_path = os.path.join(_dummy_path, "config.json")
  710. if not os.path.exists(_dummy_path):
  711. snapshot_download(repo_id="facebook/opt-125m",
  712. local_dir=_dummy_path,
  713. ignore_patterns=[
  714. "*.bin", "*.bin.index.json", "*.pt", "*.h5",
  715. "*.msgpack"
  716. ])
  717. assert os.path.exists(json_path)
  718. with open(json_path, "r") as f:
  719. config = json.load(f)
  720. config["architectures"] = ["MyOPTForCausalLM"]
  721. with open(json_path, "w") as f:
  722. json.dump(config, f)
  723. return _dummy_path