conftest.py 27 KB

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