aphrodite_engine.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. import time
  2. from typing import Iterable, List, Optional, Tuple, Type, Union
  3. from loguru import logger
  4. from transformers import PreTrainedTokenizer
  5. import aphrodite
  6. from aphrodite.lora.request import LoRARequest
  7. from aphrodite.common.config import (CacheConfig, DeviceConfig, ModelConfig,
  8. ParallelConfig, SchedulerConfig,
  9. LoRAConfig, VisionLanguageConfig,
  10. SpeculativeConfig)
  11. from aphrodite.processing.scheduler import Scheduler, SchedulerOutputs
  12. from aphrodite.engine.args_tools import EngineArgs
  13. from aphrodite.executor.executor_base import ExecutorBase
  14. from aphrodite.engine.metrics import StatLogger, Stats
  15. from aphrodite.engine.ray_tools import (initialize_ray_cluster)
  16. from aphrodite.common.outputs import RequestOutput
  17. from aphrodite.common.sampling_params import SamplingParams
  18. from aphrodite.common.sequence import (SamplerOutput, Sequence, SequenceGroup,
  19. SequenceGroupOutput, SequenceOutput,
  20. SequenceStatus, MultiModalData)
  21. from aphrodite.transformers_utils.tokenizer_group import (BaseTokenizerGroup,
  22. get_tokenizer_group)
  23. from aphrodite.transformers_utils.detokenizer import Detokenizer
  24. from aphrodite.common.utils import (
  25. Counter, )
  26. from aphrodite.common.logger import setup_logger
  27. _LOCAL_LOGGING_INTERVAL_SEC = 5
  28. class AphroditeEngine:
  29. """An LLM engine that receives requests and generates texts.
  30. This is the main class for the Aphrodite engine. It receives requests
  31. from clients and generates texts from the LLM. It includes a tokenizer, a
  32. language model (possibly distributed across multiple GPUs), and GPU memory
  33. space allocated for intermediate states (aka KV cache). This class utilizes
  34. iteration-level scheduling and efficient memory management to maximize the
  35. serving throughput.
  36. The `LLM` class wraps this class for offline batched inference and the
  37. `AsyncAphrodite` class wraps this class for online serving.
  38. NOTE: The config arguments are derived from the `EngineArgs` class. For the
  39. comprehensive list of arguments, see `EngineArgs`.
  40. Args:
  41. model_config: The configuration related to the LLM model.
  42. cache_config: The configuration related to the KV cache memory
  43. management.
  44. parallel_config: The configuration related to distributed execution.
  45. scheduler_config: The configuration related to the request scheduler.
  46. device_config: The configuration related to the device.
  47. lora_config (Optional): The configuration related to serving multi-LoRA.
  48. vision_language_config (Optional): The configuration related to vision
  49. language models.
  50. speculative_config (Optional): The configuration related to speculative
  51. decoding.
  52. executor_class: The model executor class for managing distributed
  53. execution.
  54. log_stats: Whether to log statistics.
  55. """
  56. def __init__(
  57. self,
  58. model_config: ModelConfig,
  59. cache_config: CacheConfig,
  60. parallel_config: ParallelConfig,
  61. scheduler_config: SchedulerConfig,
  62. device_config: DeviceConfig,
  63. lora_config: Optional[LoRAConfig],
  64. vision_language_config: Optional[VisionLanguageConfig],
  65. speculative_config: Optional[SpeculativeConfig],
  66. executor_class: Type[ExecutorBase],
  67. log_stats: bool,
  68. ) -> None:
  69. logger.info(
  70. f"Initializing the Aphrodite Engine (v{aphrodite.__version__}) "
  71. "with the following config:\n"
  72. f"Model = {model_config.model!r}\n"
  73. f"Speculative Config = {speculative_config!r}\n"
  74. f"DataType = {model_config.dtype}\n"
  75. f"Model Load Format = {model_config.load_format}\n"
  76. f"Number of GPUs = {parallel_config.tensor_parallel_size}\n"
  77. f"Disable Custom All-Reduce = "
  78. f"{parallel_config.disable_custom_all_reduce}\n"
  79. f"Quantization Format = {model_config.quantization}\n"
  80. f"Context Length = {model_config.max_model_len}\n"
  81. f"Enforce Eager Mode = {model_config.enforce_eager}\n"
  82. f"KV Cache Data Type = {cache_config.cache_dtype}\n"
  83. f"KV Cache Params Path = {model_config.quantization_param_path}\n"
  84. f"Device = {device_config.device}")
  85. # TODO: Print more configs in debug mode.
  86. self.model_config = model_config
  87. self.cache_config = cache_config
  88. self.lora_config = lora_config
  89. self.vision_language_config = vision_language_config
  90. self.parallel_config = parallel_config
  91. self.scheduler_config = scheduler_config
  92. self.device_config = device_config
  93. self.speculative_config = speculative_config
  94. self.log_stats = log_stats
  95. self._verify_args()
  96. self._init_tokenizer()
  97. self.detokenizer = Detokenizer(self.tokenizer)
  98. self.seq_counter = Counter()
  99. self.model_executor = executor_class(
  100. model_config=model_config,
  101. cache_config=cache_config,
  102. parallel_config=parallel_config,
  103. scheduler_config=scheduler_config,
  104. device_config=device_config,
  105. lora_config=lora_config,
  106. vision_language_config=vision_language_config,
  107. speculative_config=speculative_config,
  108. )
  109. self._initialize_kv_caches()
  110. # Ping the tokenizer to ensure it is loaded if
  111. # it runs on a separate process.
  112. self.tokenizer.ping()
  113. # Create the scheduler.
  114. # NOTE: the cache_config here have been updated with the numbers of
  115. # GPU and CPU blocks, which are profiled in the distributed executor.
  116. self.scheduler = Scheduler(scheduler_config, cache_config, lora_config)
  117. # Metric Logging.
  118. if self.log_stats:
  119. self.stat_logger = StatLogger(
  120. local_interval=_LOCAL_LOGGING_INTERVAL_SEC,
  121. labels=dict(model_name=model_config.model),
  122. )
  123. self.stat_logger.info("cache_config", self.cache_config)
  124. def _initialize_kv_caches(self) -> None:
  125. """Initialize the KV cache in the worker(s).
  126. The workers will determine the number of blocks in both the GPU cache
  127. and the swap CPU cache.
  128. """
  129. num_gpu_blocks, num_cpu_blocks = (
  130. self.model_executor.determine_num_available_blocks())
  131. if self.cache_config.num_gpu_blocks_override is not None:
  132. num_gpu_blocks_override = self.cache_config.num_gpu_blocks_override
  133. logger.info(f"Overriding {num_gpu_blocks=} with "
  134. f"{num_gpu_blocks_override=}")
  135. num_gpu_blocks = num_gpu_blocks_override
  136. self.cache_config.num_gpu_blocks = num_gpu_blocks
  137. self.cache_config.num_cpu_blocks = num_cpu_blocks
  138. self.model_executor.initialize_cache(num_gpu_blocks, num_cpu_blocks)
  139. @classmethod
  140. def from_engine_args(cls, engine_args: EngineArgs) -> "AphroditeEngine":
  141. """Creates an LLM engine from the engine arguments."""
  142. # Create the engine configs.
  143. engine_config = engine_args.create_engine_config()
  144. # Initialize the cluster and specify the executor class.
  145. if engine_config.device_config.device_type == "neuron":
  146. from aphrodite.executor.neuron_executor import NeuronExecutor
  147. executor_class = NeuronExecutor
  148. elif engine_config.device_config.device_type == "cpu":
  149. from aphrodite.executor.cpu_executor import CPUExecutor
  150. executor_class = CPUExecutor
  151. elif engine_config.parallel_config.worker_use_ray:
  152. initialize_ray_cluster(engine_config.parallel_config)
  153. from aphrodite.executor.ray_gpu_executor import RayGPUExecutor
  154. executor_class = RayGPUExecutor
  155. else:
  156. assert engine_config.parallel_config.world_size == 1, (
  157. "Ray is required if parallel_config.world_size > 1.")
  158. from aphrodite.executor.gpu_executor import GPUExecutor
  159. executor_class = GPUExecutor
  160. # Create the LLM engine.
  161. engine = cls(**engine_config.to_dict(),
  162. executor_class=executor_class,
  163. log_stats=not engine_args.disable_log_stats)
  164. return engine
  165. def __reduce__(self):
  166. # This is to ensure that the AphroditeEngine is not referenced in
  167. # the closure used to initialize Ray worker actors
  168. raise RuntimeError("AphroditeEngine should not be pickled!")
  169. def get_tokenizer(self) -> "PreTrainedTokenizer":
  170. return self.tokenizer.get_lora_tokenizer(None)
  171. def get_tokenizer_for_seq(self,
  172. sequence: Sequence) -> "PreTrainedTokenizer":
  173. return self.tokenizer.get_lora_tokenizer(sequence.lora_request)
  174. def _init_tokenizer(self, **tokenizer_init_kwargs):
  175. init_kwargs = dict(
  176. tokenizer_id=self.model_config.tokenizer,
  177. enable_lora=bool(self.lora_config),
  178. max_num_seqs=self.scheduler_config.max_num_seqs,
  179. max_input_length=None,
  180. tokenizer_mode=self.model_config.tokenizer_mode,
  181. trust_remote_code=self.model_config.trust_remote_code,
  182. revision=self.model_config.tokenizer_revision,
  183. )
  184. init_kwargs.update(tokenizer_init_kwargs)
  185. self.tokenizer: BaseTokenizerGroup = get_tokenizer_group(
  186. self.parallel_config.tokenizer_pool_config, **init_kwargs)
  187. if len(self.get_tokenizer()) != self.model_config.get_vocab_size():
  188. logger.warning(
  189. f"The tokenizer's vocabulary size {len(self.get_tokenizer())}"
  190. f" does not match the model's vocabulary size "
  191. f"{self.model_config.get_vocab_size()}. This might "
  192. f"cause an error in decoding. Please change config.json "
  193. "to match the tokenizer's vocabulary size.")
  194. def _verify_args(self) -> None:
  195. self.model_config.verify_with_parallel_config(self.parallel_config)
  196. self.cache_config.verify_with_parallel_config(self.parallel_config)
  197. if self.lora_config:
  198. self.lora_config.verify_with_model_config(self.model_config)
  199. self.lora_config.verify_with_scheduler_config(
  200. self.scheduler_config)
  201. def encode_request(
  202. self,
  203. request_id: str,
  204. prompt: Optional[str],
  205. prompt_token_ids: Optional[List[int]] = None,
  206. lora_request: Optional[LoRARequest] = None,
  207. ):
  208. if prompt_token_ids is None:
  209. assert prompt is not None
  210. prompt_token_ids = self.tokenizer.encode(request_id=request_id,
  211. prompt=prompt,
  212. lora_request=lora_request)
  213. return prompt_token_ids
  214. def add_request(
  215. self,
  216. request_id: str,
  217. prompt: Optional[str],
  218. sampling_params: SamplingParams,
  219. prompt_token_ids: Optional[List[int]] = None,
  220. arrival_time: Optional[float] = None,
  221. lora_request: Optional[LoRARequest] = None,
  222. multi_modal_data: Optional[MultiModalData] = None,
  223. ) -> None:
  224. """Add a request to the engine's request pool.
  225. The request is added to the request pool and will be processed by the
  226. scheduler as `engine.step()` is called. The exact scheduling policy is
  227. determined by the scheduler.
  228. Args:
  229. request_id: The unique ID of the request.
  230. prompt: The prompt string. Can be None if prompt_token_ids is
  231. provided.
  232. sampling_params: The sampling parameters for text generation.
  233. prompt_token_ids: The token IDs of the prompt. If None, we
  234. use the tokenizer to convert the prompts to token IDs.
  235. arrival_time: The arrival time of the request. If None, we use
  236. the current monotonic time.
  237. multi_modal_data: The multimodal data for the request.
  238. Details:
  239. - Set arrival_time to the current time if it is None.
  240. - Set prompt_token_ids to the encoded prompt if it is None.
  241. - Create `best_of` number of :class:`~aphrodite.Sequence` objects.
  242. - Create a :class:`~aphrodite.SequenceGroup` object
  243. from the list of :class:`~aphrodite.Sequence`.
  244. - Add the :class:`~aphrodite.SequenceGroup` object to the scheduler.
  245. Example:
  246. >>> # initialize engine
  247. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  248. >>> # set request arguments
  249. >>> example_prompt = "Who is the president of the United States?"
  250. >>> sampling_params = SamplingParams(temperature=0.0)
  251. >>> request_id = 0
  252. >>>
  253. >>> # add the request to the engine
  254. >>> engine.add_request(
  255. >>> str(request_id),
  256. >>> example_prompt,
  257. >>> SamplingParams(temperature=0.0))
  258. >>> # continue the request processing
  259. >>> ...
  260. """
  261. if lora_request is not None and not self.lora_config:
  262. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  263. "not enabled!")
  264. max_log_probs = self.get_model_config().max_log_probs
  265. if (sampling_params.logprobs
  266. and sampling_params.logprobs > max_log_probs) or (
  267. sampling_params.prompt_logprobs
  268. and sampling_params.prompt_logprobs > max_log_probs):
  269. raise ValueError(f"Cannot request more than "
  270. f"{max_log_probs} logprobs. "
  271. "Please increase the max_log_probs.")
  272. if arrival_time is None:
  273. arrival_time = time.monotonic()
  274. prompt_token_ids = self.encode_request(
  275. request_id=request_id,
  276. prompt=prompt,
  277. prompt_token_ids=prompt_token_ids,
  278. lora_request=lora_request,
  279. )
  280. # Create the sequences.
  281. block_size = self.cache_config.block_size
  282. seq_id = next(self.seq_counter)
  283. eos_token_id = self.tokenizer.get_lora_tokenizer(
  284. lora_request).eos_token_id
  285. seq = Sequence(
  286. seq_id,
  287. prompt,
  288. prompt_token_ids,
  289. block_size,
  290. eos_token_id,
  291. lora_request,
  292. )
  293. # Defensive copy of SamplingParams, which are used by the sampler,
  294. # this doesn't deep-copy LogitsProcessor objects
  295. sampling_params = sampling_params.clone()
  296. # Inject the eos token id into the sampling_params to support min_tokens
  297. # processing
  298. sampling_params.eos_token_id = seq.eos_token_id
  299. # Create the sequence group.
  300. seq_group = SequenceGroup(request_id, [seq], sampling_params,
  301. arrival_time, lora_request, multi_modal_data)
  302. # Add the sequence group to the scheduler.
  303. self.scheduler.add_seq_group(seq_group)
  304. def abort_request(self, request_id: Union[str, Iterable[str]]) -> None:
  305. """Aborts a request(s) with the given ID.
  306. Args:
  307. request_id: The ID(s) of the request to abort.
  308. Details:
  309. - Refer to the
  310. :meth:`~aphrodite.processing.scheduler.Scheduler.abort_seq_group`
  311. from class :class:`~aphrodite.processing.scheduler.Scheduler`.
  312. Example:
  313. >>> # initialize engine and add a request with request_id
  314. >>> request_id = str(0)
  315. >>> # abort the request
  316. >>> engine.abort_request(request_id)
  317. """
  318. self.scheduler.abort_seq_group(request_id)
  319. def get_model_config(self) -> ModelConfig:
  320. """Gets the model configuration."""
  321. return self.model_config
  322. def get_num_unfinished_requests(self) -> int:
  323. """Gets the number of unfinished requests."""
  324. return self.scheduler.get_num_unfinished_seq_groups()
  325. def has_unfinished_requests(self) -> bool:
  326. """Returns True if there are unfinished requests."""
  327. return self.scheduler.has_unfinished_seqs()
  328. def _check_beam_search_early_stopping(
  329. self,
  330. early_stopping: Union[bool, str],
  331. sampling_params: SamplingParams,
  332. best_running_seq: Sequence,
  333. current_worst_seq: Sequence,
  334. ) -> bool:
  335. assert sampling_params.use_beam_search
  336. length_penalty = sampling_params.length_penalty
  337. if early_stopping is True:
  338. return True
  339. current_worst_score = current_worst_seq.get_beam_search_score(
  340. length_penalty=length_penalty,
  341. eos_token_id=current_worst_seq.eos_token_id,
  342. )
  343. if early_stopping is False:
  344. highest_attainable_score = best_running_seq.get_beam_search_score(
  345. length_penalty=length_penalty,
  346. eos_token_id=best_running_seq.eos_token_id,
  347. )
  348. else:
  349. assert early_stopping == "never"
  350. if length_penalty > 0.0:
  351. # If length_penalty > 0.0, beam search will prefer longer
  352. # sequences. The highest attainable score calculation is
  353. # based on the longest possible sequence length in this case.
  354. max_possible_length = max(
  355. best_running_seq.get_prompt_len() +
  356. sampling_params.max_tokens,
  357. self.scheduler_config.max_model_len,
  358. )
  359. highest_attainable_score = (
  360. best_running_seq.get_beam_search_score(
  361. length_penalty=length_penalty,
  362. eos_token_id=best_running_seq.eos_token_id,
  363. seq_len=max_possible_length,
  364. ))
  365. else:
  366. # Otherwise, beam search will prefer shorter sequences. The
  367. # highest attainable score calculation is based on the current
  368. # sequence length.
  369. highest_attainable_score = (
  370. best_running_seq.get_beam_search_score(
  371. length_penalty=length_penalty,
  372. eos_token_id=best_running_seq.eos_token_id,
  373. ))
  374. return current_worst_score >= highest_attainable_score
  375. def _process_sequence_group_outputs(self, seq_group: SequenceGroup,
  376. outputs: SequenceGroupOutput) -> None:
  377. # Process prompt logprobs
  378. prompt_logprobs = outputs.prompt_logprobs
  379. if prompt_logprobs is not None and seq_group.sampling_params.detokenize:
  380. self.detokenizer.decode_prompt_logprobs_inplace(
  381. seq_group, prompt_logprobs)
  382. seq_group.prompt_logprobs = prompt_logprobs
  383. # Process samples
  384. samples = outputs.samples
  385. parent_seqs = seq_group.get_seqs(status=SequenceStatus.RUNNING)
  386. existing_finished_seqs = seq_group.get_finished_seqs()
  387. parent_child_dict = {
  388. parent_seq.seq_id: []
  389. for parent_seq in parent_seqs
  390. }
  391. for sample in samples:
  392. parent_child_dict[sample.parent_seq_id].append(sample)
  393. # List of (child, parent)
  394. child_seqs: List[Tuple[Sequence, Sequence]] = []
  395. # Process the child samples for each parent sequence
  396. for parent in parent_seqs:
  397. child_samples: List[SequenceOutput] = parent_child_dict[
  398. parent.seq_id]
  399. if len(child_samples) == 0:
  400. # This parent sequence has no children samples. Remove
  401. # the parent sequence from the sequence group since it will
  402. # not be used in the future iterations.
  403. parent.status = SequenceStatus.FINISHED_ABORTED
  404. seq_group.remove(parent.seq_id)
  405. self.scheduler.free_seq(parent)
  406. continue
  407. # Fork the parent sequence if there are multiple child samples.
  408. for child_sample in child_samples[:-1]:
  409. new_child_seq_id = next(self.seq_counter)
  410. child = parent.fork(new_child_seq_id)
  411. child.append_token_id(child_sample.output_token,
  412. child_sample.logprobs)
  413. child.persistent_data = child_sample.persistent_data
  414. child_seqs.append((child, parent))
  415. # Continue the parent sequence for the last child sample.
  416. # We reuse the parent sequence here to reduce redundant memory
  417. # copies, especially when using non-beam search sampling methods.
  418. last_child_sample = child_samples[-1]
  419. parent.append_token_id(last_child_sample.output_token,
  420. last_child_sample.logprobs)
  421. parent.persistent_data = last_child_sample.persistent_data
  422. child_seqs.append((parent, parent))
  423. for seq, _ in child_seqs:
  424. if seq_group.sampling_params.detokenize:
  425. new_char_count = self.detokenizer.decode_sequence_inplace(
  426. seq, seq_group.sampling_params)
  427. else:
  428. new_char_count = 0
  429. self._check_stop(seq, new_char_count, seq_group.sampling_params)
  430. # Non-beam search case
  431. if not seq_group.sampling_params.use_beam_search:
  432. # For newly created child sequences, add them to the sequence group
  433. # and fork them in block manager if they are not finished.
  434. for seq, parent in child_seqs:
  435. if seq is not parent:
  436. seq_group.add(seq)
  437. if not seq.is_finished():
  438. self.scheduler.fork_seq(parent, seq)
  439. # Free the finished and selected parent sequences' memory in block
  440. # manager. Keep them in the sequence group as candidate output.
  441. # NOTE: we need to fork the new sequences before freeing the
  442. # old sequences.
  443. for seq, parent in child_seqs:
  444. if seq is parent and seq.is_finished():
  445. self.scheduler.free_seq(seq)
  446. return
  447. # Beam search case
  448. # Select the child sequences to keep in the sequence group.
  449. selected_child_seqs = []
  450. unselected_child_seqs = []
  451. beam_width = seq_group.sampling_params.best_of
  452. length_penalty = seq_group.sampling_params.length_penalty
  453. # Select the newly finished sequences with the highest scores
  454. # to replace existing finished sequences.
  455. # Tuple of (seq, parent, is_new)
  456. existing_finished_seqs = [(seq, None, False)
  457. for seq in existing_finished_seqs]
  458. new_finished_seqs = [(seq, parent, True) for seq, parent in child_seqs
  459. if seq.is_finished()]
  460. all_finished_seqs = existing_finished_seqs + new_finished_seqs
  461. # Sort the finished sequences by their scores.
  462. all_finished_seqs.sort(
  463. key=lambda x: x[0].get_beam_search_score(
  464. length_penalty=length_penalty, eos_token_id=x[0].eos_token_id),
  465. reverse=True,
  466. )
  467. for seq, parent, is_new in all_finished_seqs[:beam_width]:
  468. if is_new:
  469. # A newly generated child sequence finishes and has a high
  470. # score, so we will add it into the sequence group.
  471. selected_child_seqs.append((seq, parent))
  472. for seq, parent, is_new in all_finished_seqs[beam_width:]:
  473. if is_new:
  474. # A newly generated child sequence finishes but has a low
  475. # score, so we will not add it into the sequence group.
  476. # Additionally, if this sequence is a continuation of a
  477. # parent sequence, we will need remove the parent sequence
  478. # from the sequence group.
  479. unselected_child_seqs.append((seq, parent))
  480. else:
  481. # An existing finished sequence has a low score, so we will
  482. # remove it from the sequence group.
  483. seq_group.remove(seq.seq_id)
  484. # select the top beam_width sequences from the running
  485. # sequences for the next iteration to continue the beam
  486. # search.
  487. running_child_seqs = [(seq, parent) for seq, parent in child_seqs
  488. if not seq.is_finished()]
  489. # Sort the running sequences by their scores.
  490. running_child_seqs.sort(
  491. key=lambda x: x[0].get_beam_search_score(
  492. length_penalty=length_penalty, eos_token_id=x[0].eos_token_id),
  493. reverse=True,
  494. )
  495. # Check if we can stop the beam search.
  496. if len(running_child_seqs) == 0:
  497. # No running sequences, stop the beam search.
  498. stop_beam_search = True
  499. elif len(all_finished_seqs) < beam_width:
  500. # Not enough finished sequences, continue the beam search.
  501. stop_beam_search = False
  502. else:
  503. # Check the early stopping criteria
  504. best_running_seq = running_child_seqs[0][0]
  505. current_worst_seq = all_finished_seqs[beam_width - 1][0]
  506. stop_beam_search = self._check_beam_search_early_stopping(
  507. seq_group.sampling_params.early_stopping,
  508. seq_group.sampling_params,
  509. best_running_seq,
  510. current_worst_seq,
  511. )
  512. if stop_beam_search:
  513. # Stop the beam search and remove all the running sequences from
  514. # the sequence group.
  515. unselected_child_seqs.extend(running_child_seqs)
  516. else:
  517. # Continue the beam search and select the top beam_width sequences
  518. # to continue the beam search.
  519. selected_child_seqs.extend(running_child_seqs[:beam_width])
  520. # The remaining running sequences will not be used in the next
  521. # iteration. Again, if these sequences are continuations of
  522. # parent sequences, we will need to remove the parent sequences
  523. # from the sequence group.
  524. unselected_child_seqs.extend(running_child_seqs[beam_width:])
  525. # For newly created child sequences, add them to the sequence group
  526. # and fork them in block manager if they are not finished.
  527. for seq, parent in selected_child_seqs:
  528. if seq is not parent:
  529. seq_group.add(seq)
  530. if not seq.is_finished():
  531. self.scheduler.fork_seq(parent, seq)
  532. # Free the finished and selected parent sequences' memory in block
  533. # manager. Keep them in the sequence group as candidate output.
  534. for seq, parent in selected_child_seqs:
  535. if seq is parent and seq.is_finished():
  536. self.scheduler.free_seq(seq)
  537. # Remove the unselected parent sequences from the sequence group and
  538. # free their memory in block manager.
  539. for seq, parent in unselected_child_seqs:
  540. if seq is parent:
  541. # Remove the parent sequence if it is not selected for next
  542. # iteration
  543. seq_group.remove(seq.seq_id)
  544. self.scheduler.free_seq(seq)
  545. def _process_model_outputs(
  546. self, output: SamplerOutput,
  547. scheduler_outputs: SchedulerOutputs) -> List[RequestOutput]:
  548. now = time.time()
  549. # Update the scheduled sequence groups with the model outputs.
  550. scheduled_seq_groups = scheduler_outputs.scheduled_seq_groups
  551. for scheduled_seq_group, outputs in zip(scheduled_seq_groups, output):
  552. seq_group = scheduled_seq_group.seq_group
  553. seq_group.update_num_computed_tokens(
  554. scheduled_seq_group.token_chunk_size)
  555. # If uncomputed tokens > 0, it means prefill is chunked.
  556. # We don't need to process outputs in that case.
  557. if seq_group.get_num_uncomputed_tokens() == 0:
  558. self._process_sequence_group_outputs(seq_group, outputs)
  559. # Free the finished sequence groups.
  560. self.scheduler.free_finished_seq_groups()
  561. # Create the outputs.
  562. request_outputs: List[RequestOutput] = []
  563. for scheduled_seq_group in scheduled_seq_groups:
  564. seq_group = scheduled_seq_group.seq_group
  565. seq_group.maybe_set_first_token_time(now)
  566. request_output = RequestOutput.from_seq_group(seq_group)
  567. request_outputs.append(request_output)
  568. for seq_group in scheduler_outputs.ignored_seq_groups:
  569. request_output = RequestOutput.from_seq_group(seq_group)
  570. request_outputs.append(request_output)
  571. # Log stats.
  572. if self.log_stats:
  573. self.stat_logger.log(self._get_stats(scheduler_outputs))
  574. return request_outputs
  575. def step(self) -> List[RequestOutput]:
  576. """Performs one decoding iteration and returns newly generated results.
  577. .. figure:: https://i.imgur.com/sv2HssD.png
  578. :alt: Overview of the step function
  579. :align: center
  580. Overview of the step function.
  581. Details:
  582. - Step 1: Schedules the sequences to be executed in the next
  583. iteration and the token blocks to be swapped in/out/copy.
  584. - Depending on the scheduling policy,
  585. sequences may be `preempted/reordered`.
  586. - A Sequence Group (SG) refer to a group of sequences
  587. that are generated from the same prompt.
  588. - Step 2: Calls the distributed executor to execute the model.
  589. - Step 3: Processes the model output. This mainly includes:
  590. - Decodes the relevant outputs.
  591. - Updates the scheduled sequence groups with model outputs
  592. based on its `sampling parameters` (`use_beam_search` or not).
  593. - Frees the finished sequence groups.
  594. - Finally, it creates and returns the newly generated results.
  595. Example:
  596. >>> # Please see the example/ folder for more detailed examples.
  597. >>>
  598. >>> # initialize engine and request arguments
  599. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  600. >>> example_inputs = [(0, "What is LLM?",
  601. >>> SamplingParams(temperature=0.0))]
  602. >>>
  603. >>> # Start the engine with an event loop
  604. >>> while True:
  605. >>> if example_inputs:
  606. >>> req_id, prompt, sampling_params = example_inputs.pop(0)
  607. >>> engine.add_request(str(req_id), prompt, sampling_params)
  608. >>>
  609. >>> # continue the request processing
  610. >>> request_outputs = engine.step()
  611. >>> for request_output in request_outputs:
  612. >>> if request_output.finished:
  613. >>> # return or show the request output
  614. >>>
  615. >>> if not (engine.has_unfinished_requests() or example_inputs):
  616. >>> break
  617. """
  618. seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()
  619. if not scheduler_outputs.is_empty():
  620. output = self.model_executor.execute_model(
  621. seq_group_metadata_list, scheduler_outputs.blocks_to_swap_in,
  622. scheduler_outputs.blocks_to_swap_out,
  623. scheduler_outputs.blocks_to_copy)
  624. else:
  625. output = []
  626. return self._process_model_outputs(output, scheduler_outputs)
  627. def do_log_stats(self) -> None:
  628. """Forced log when no requests active."""
  629. if self.log_stats:
  630. self.stat_logger.log(self._get_stats(scheduler_outputs=None))
  631. def _get_stats(self,
  632. scheduler_outputs: Optional[SchedulerOutputs]) -> Stats:
  633. """Get Stats to be Logged to Prometheus."""
  634. now = time.monotonic()
  635. # KV Cache Usage in %.
  636. num_total_gpu = self.cache_config.num_gpu_blocks
  637. num_free_gpu = self.scheduler.block_manager.get_num_free_gpu_blocks()
  638. gpu_cache_usage = 1.0 - (num_free_gpu / num_total_gpu)
  639. num_total_cpu = self.cache_config.num_cpu_blocks
  640. cpu_cache_usage = 0.0
  641. if num_total_cpu > 0:
  642. num_free_cpu = (
  643. self.scheduler.block_manager.get_num_free_cpu_blocks())
  644. cpu_cache_usage = 1.0 - (num_free_cpu / num_total_cpu)
  645. # Scheduler State
  646. num_running = len(self.scheduler.running)
  647. num_swapped = len(self.scheduler.swapped)
  648. num_waiting = len(self.scheduler.waiting)
  649. # Iteration stats if we have scheduler output.
  650. num_prompt_tokens = 0
  651. num_generation_tokens = 0
  652. time_to_first_tokens = []
  653. time_per_output_tokens = []
  654. time_e2e_requests = []
  655. if scheduler_outputs is not None:
  656. prompt_run = scheduler_outputs.num_prefill_groups > 0
  657. # Number of Tokens.
  658. if prompt_run:
  659. num_prompt_tokens = sum(
  660. len(scheduled_seq_group.seq_group.prompt_token_ids)
  661. for scheduled_seq_group in
  662. scheduler_outputs.scheduled_seq_groups)
  663. num_generation_tokens = sum(
  664. scheduled_seq_group.seq_group.num_seqs()
  665. for scheduled_seq_group in
  666. scheduler_outputs.scheduled_seq_groups)
  667. else:
  668. num_generation_tokens = scheduler_outputs.num_batched_tokens
  669. # Latency Timings.
  670. time_last_iters = []
  671. for scheduled_seq_group in scheduler_outputs.scheduled_seq_groups:
  672. seq_group = scheduled_seq_group.seq_group
  673. # Time since last token.
  674. # (n.b. updates seq_group.metrics.last_token_time)
  675. time_last_iters.append(seq_group.get_last_latency(now))
  676. # Time since arrival for all finished requests.
  677. if seq_group.is_finished():
  678. time_e2e_requests.append(now -
  679. seq_group.metrics.arrival_time)
  680. time_to_first_tokens = time_last_iters if prompt_run else []
  681. time_per_output_tokens = [] if prompt_run else time_last_iters
  682. return Stats(
  683. now=now,
  684. num_running=num_running,
  685. num_swapped=num_swapped,
  686. num_waiting=num_waiting,
  687. gpu_cache_usage=gpu_cache_usage,
  688. cpu_cache_usage=cpu_cache_usage,
  689. num_prompt_tokens=num_prompt_tokens,
  690. num_generation_tokens=num_generation_tokens,
  691. time_to_first_tokens=time_to_first_tokens,
  692. time_per_output_tokens=time_per_output_tokens,
  693. time_e2e_requests=time_e2e_requests,
  694. )
  695. def _check_stop(self, seq: Sequence, new_char_count: int,
  696. sampling_params: SamplingParams) -> None:
  697. """Stop the finished sequences.
  698. new_char_count is the number of chars added to the
  699. sequence's output text for the newly generated token
  700. """
  701. # Check if the minimum number of tokens has been generated yet;
  702. # skip the stop string/token checks if not
  703. if seq.get_output_len() < sampling_params.min_tokens:
  704. return
  705. # Check if the sequence has generated the EOS token.
  706. if ((not sampling_params.ignore_eos)
  707. and seq.get_last_token_id() == seq.eos_token_id):
  708. seq.status = SequenceStatus.FINISHED_STOPPED
  709. return
  710. # Check if a stop token was encountered.
  711. # This assumes a single token produced per step.
  712. last_token_id = seq.get_last_token_id()
  713. if last_token_id in sampling_params.stop_token_ids:
  714. if new_char_count and (
  715. not sampling_params.include_stop_str_in_output):
  716. # Remove last token
  717. seq.output_text = seq.output_text[:-new_char_count]
  718. seq.status = SequenceStatus.FINISHED_STOPPED
  719. seq.stop_reason = last_token_id
  720. return
  721. # Check if any stop strings are matched.
  722. stop_str = self._check_stop_strings(seq, new_char_count,
  723. sampling_params)
  724. if stop_str is not None:
  725. seq.status = SequenceStatus.FINISHED_STOPPED
  726. seq.stop_reason = stop_str
  727. return
  728. # Check if the sequence has reached max_model_len.
  729. if seq.get_len() > self.scheduler_config.max_model_len:
  730. seq.status = SequenceStatus.FINISHED_LENGTH_CAPPED
  731. return
  732. # Check if the sequence has reached max_tokens.
  733. if seq.get_output_len() == sampling_params.max_tokens:
  734. seq.status = SequenceStatus.FINISHED_LENGTH_CAPPED
  735. return
  736. @staticmethod
  737. def _check_stop_strings(seq: Sequence, new_char_count: int,
  738. sampling_params: SamplingParams) -> Optional[str]:
  739. """Check if any stop strings are matched and truncate sequence
  740. output text accordingly.
  741. Returns the stop string if matched or else None.
  742. """
  743. if not new_char_count:
  744. return None
  745. for stop_str in sampling_params.stop:
  746. stop_string_len = len(stop_str)
  747. # Avoid searching already-searched text.
  748. stop_index = seq.output_text.find(
  749. stop_str, -new_char_count - stop_string_len)
  750. if stop_index == -1:
  751. continue
  752. if sampling_params.include_stop_str_in_output:
  753. # Truncate to end of stop string.
  754. stop_index += stop_string_len
  755. if stop_index >= len(seq.output_text):
  756. # No truncation required.
  757. return stop_str
  758. # Truncate the output text to either the beginning
  759. # or end of the stop string.
  760. seq.output_text = seq.output_text[:stop_index]
  761. return stop_str
  762. return None
  763. def add_lora(self, lora_request: LoRARequest) -> bool:
  764. return self.model_executor.add_lora(lora_request)
  765. def remove_lora(self, lora_id: int) -> bool:
  766. return self.model_executor.remove_lora(lora_id)
  767. def list_loras(self) -> List[int]:
  768. return self.model_executor.list_loras()
  769. def check_health(self) -> None:
  770. self.model_executor.check_health()
  771. setup_logger()