1
0

conftest.py 30 KB

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