aphrodite_engine.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import time
  2. from typing import Iterable, List, Optional, Type, Union
  3. from loguru import logger
  4. from transformers import GenerationConfig, PreTrainedTokenizer
  5. import aphrodite
  6. from aphrodite.common.config import (CacheConfig, DecodingConfig, DeviceConfig,
  7. LoRAConfig, ModelConfig, ParallelConfig,
  8. SchedulerConfig, SpeculativeConfig,
  9. VisionLanguageConfig)
  10. from aphrodite.common.logger import setup_logger
  11. from aphrodite.common.outputs import RequestOutput
  12. from aphrodite.common.sampling_params import SamplingParams
  13. from aphrodite.common.sequence import (MultiModalData, SamplerOutput, Sequence,
  14. SequenceGroup, SequenceStage)
  15. from aphrodite.common.utils import Counter
  16. from aphrodite.engine.args_tools import EngineArgs
  17. from aphrodite.engine.metrics import StatLogger, Stats
  18. from aphrodite.engine.output_processor.interfaces import \
  19. SequenceGroupOutputProcessor
  20. from aphrodite.engine.output_processor.stop_checker import StopChecker
  21. from aphrodite.engine.output_processor.util import \
  22. create_output_by_sequence_group
  23. from aphrodite.engine.ray_tools import initialize_ray_cluster
  24. from aphrodite.executor.executor_base import ExecutorBase
  25. from aphrodite.lora.request import LoRARequest
  26. from aphrodite.processing.scheduler import Scheduler, SchedulerOutputs
  27. from aphrodite.transformers_utils.detokenizer import Detokenizer
  28. from aphrodite.transformers_utils.tokenizer_group import (BaseTokenizerGroup,
  29. get_tokenizer_group)
  30. _LOCAL_LOGGING_INTERVAL_SEC = 5
  31. def _load_generation_config_dict(model_config: ModelConfig):
  32. try:
  33. return GenerationConfig.from_pretrained(
  34. model_config.model,
  35. revision=model_config.revision,
  36. ).to_diff_dict()
  37. except OSError:
  38. # Not found.
  39. return {}
  40. class AphroditeEngine:
  41. """An LLM engine that receives requests and generates texts.
  42. This is the main class for the Aphrodite engine. It receives requests
  43. from clients and generates texts from the LLM. It includes a tokenizer, a
  44. language model (possibly distributed across multiple GPUs), and GPU memory
  45. space allocated for intermediate states (aka KV cache). This class utilizes
  46. iteration-level scheduling and efficient memory management to maximize the
  47. serving throughput.
  48. The `LLM` class wraps this class for offline batched inference and the
  49. `AsyncAphrodite` class wraps this class for online serving.
  50. NOTE: The config arguments are derived from the `EngineArgs` class. For the
  51. comprehensive list of arguments, see `EngineArgs`.
  52. Args:
  53. model_config: The configuration related to the LLM model.
  54. cache_config: The configuration related to the KV cache memory
  55. management.
  56. parallel_config: The configuration related to distributed execution.
  57. scheduler_config: The configuration related to the request scheduler.
  58. device_config: The configuration related to the device.
  59. lora_config (Optional): The configuration related to serving multi-LoRA.
  60. vision_language_config (Optional): The configuration related to vision
  61. language models.
  62. speculative_config (Optional): The configuration related to speculative
  63. decoding.
  64. executor_class: The model executor class for managing distributed
  65. execution.
  66. log_stats: Whether to log statistics.
  67. """
  68. def __init__(
  69. self,
  70. model_config: ModelConfig,
  71. cache_config: CacheConfig,
  72. parallel_config: ParallelConfig,
  73. scheduler_config: SchedulerConfig,
  74. device_config: DeviceConfig,
  75. lora_config: Optional[LoRAConfig],
  76. vision_language_config: Optional[VisionLanguageConfig],
  77. speculative_config: Optional[SpeculativeConfig],
  78. decoding_config: Optional[DecodingConfig],
  79. executor_class: Type[ExecutorBase],
  80. log_stats: bool,
  81. ) -> None:
  82. logger.info(
  83. f"Initializing the Aphrodite Engine (v{aphrodite.__version__}) "
  84. "with the following config:\n"
  85. f"Model = {model_config.model!r}\n"
  86. f"Speculative Config = {speculative_config!r}\n"
  87. f"DataType = {model_config.dtype}\n"
  88. f"Model Load Format = {model_config.load_format}\n"
  89. f"Number of GPUs = {parallel_config.tensor_parallel_size}\n"
  90. f"Disable Custom All-Reduce = "
  91. f"{parallel_config.disable_custom_all_reduce}\n"
  92. f"Quantization Format = {model_config.quantization}\n"
  93. f"Context Length = {model_config.max_model_len}\n"
  94. f"Enforce Eager Mode = {model_config.enforce_eager}\n"
  95. f"KV Cache Data Type = {cache_config.cache_dtype}\n"
  96. f"KV Cache Params Path = {model_config.quantization_param_path}\n"
  97. f"Device = {device_config.device}\n"
  98. f"Guided Decoding Backend = {decoding_config!r}\n")
  99. # TODO: Print more configs in debug mode.
  100. self.model_config = model_config
  101. self.cache_config = cache_config
  102. self.lora_config = lora_config
  103. self.vision_language_config = vision_language_config
  104. self.parallel_config = parallel_config
  105. self.scheduler_config = scheduler_config
  106. self.device_config = device_config
  107. self.speculative_config = speculative_config
  108. self.decoding_config = decoding_config or DecodingConfig()
  109. self.log_stats = log_stats
  110. self._verify_args()
  111. self._init_tokenizer()
  112. self.detokenizer = Detokenizer(self.tokenizer)
  113. self.seq_counter = Counter()
  114. self.generation_config_fields = _load_generation_config_dict(
  115. model_config)
  116. self.model_executor = executor_class(
  117. model_config=model_config,
  118. cache_config=cache_config,
  119. parallel_config=parallel_config,
  120. scheduler_config=scheduler_config,
  121. device_config=device_config,
  122. lora_config=lora_config,
  123. vision_language_config=vision_language_config,
  124. speculative_config=speculative_config,
  125. )
  126. self._initialize_kv_caches()
  127. # Ping the tokenizer to ensure it is loaded if
  128. # it runs on a separate process.
  129. self.tokenizer.ping()
  130. # Create the scheduler.
  131. # NOTE: the cache_config here have been updated with the numbers of
  132. # GPU and CPU blocks, which are profiled in the distributed executor.
  133. self.scheduler = Scheduler(scheduler_config, cache_config, lora_config)
  134. # Metric Logging.
  135. if self.log_stats:
  136. self.stat_logger = StatLogger(
  137. local_interval=_LOCAL_LOGGING_INTERVAL_SEC,
  138. labels=dict(model_name=model_config.model),
  139. )
  140. self.stat_logger.info("cache_config", self.cache_config)
  141. # Create sequence output processor, e.g. for beam search or
  142. # speculative decoding.
  143. self.output_processor = (
  144. SequenceGroupOutputProcessor.create_output_processor(
  145. self.scheduler_config,
  146. self.detokenizer,
  147. self.scheduler,
  148. self.seq_counter,
  149. self.get_tokenizer_for_seq,
  150. stop_checker=StopChecker(
  151. self.scheduler_config.max_model_len,
  152. self.get_tokenizer_for_seq,
  153. ),
  154. ))
  155. def _initialize_kv_caches(self) -> None:
  156. """Initialize the KV cache in the worker(s).
  157. The workers will determine the number of blocks in both the GPU cache
  158. and the swap CPU cache.
  159. """
  160. num_gpu_blocks, num_cpu_blocks = (
  161. self.model_executor.determine_num_available_blocks())
  162. if self.cache_config.num_gpu_blocks_override is not None:
  163. num_gpu_blocks_override = self.cache_config.num_gpu_blocks_override
  164. logger.info(f"Overriding {num_gpu_blocks=} with "
  165. f"{num_gpu_blocks_override=}")
  166. num_gpu_blocks = num_gpu_blocks_override
  167. self.cache_config.num_gpu_blocks = num_gpu_blocks
  168. self.cache_config.num_cpu_blocks = num_cpu_blocks
  169. self.model_executor.initialize_cache(num_gpu_blocks, num_cpu_blocks)
  170. @classmethod
  171. def from_engine_args(cls, engine_args: EngineArgs) -> "AphroditeEngine":
  172. """Creates an LLM engine from the engine arguments."""
  173. # Create the engine configs.
  174. engine_config = engine_args.create_engine_config()
  175. # Initialize the cluster and specify the executor class.
  176. if engine_config.device_config.device_type == "neuron":
  177. from aphrodite.executor.neuron_executor import NeuronExecutor
  178. executor_class = NeuronExecutor
  179. elif engine_config.device_config.device_type == "cpu":
  180. from aphrodite.executor.cpu_executor import CPUExecutor
  181. executor_class = CPUExecutor
  182. elif engine_config.parallel_config.worker_use_ray:
  183. initialize_ray_cluster(engine_config.parallel_config)
  184. from aphrodite.executor.ray_gpu_executor import RayGPUExecutor
  185. executor_class = RayGPUExecutor
  186. else:
  187. assert engine_config.parallel_config.world_size == 1, (
  188. "Ray is required if parallel_config.world_size > 1.")
  189. from aphrodite.executor.gpu_executor import GPUExecutor
  190. executor_class = GPUExecutor
  191. # Create the LLM engine.
  192. engine = cls(**engine_config.to_dict(),
  193. executor_class=executor_class,
  194. log_stats=not engine_args.disable_log_stats)
  195. return engine
  196. def __reduce__(self):
  197. # This is to ensure that the AphroditeEngine is not referenced in
  198. # the closure used to initialize Ray worker actors
  199. raise RuntimeError("AphroditeEngine should not be pickled!")
  200. def get_tokenizer(self) -> "PreTrainedTokenizer":
  201. return self.tokenizer.get_lora_tokenizer(None)
  202. def get_tokenizer_for_seq(self,
  203. sequence: Sequence) -> "PreTrainedTokenizer":
  204. return self.tokenizer.get_lora_tokenizer(sequence.lora_request)
  205. def _init_tokenizer(self, **tokenizer_init_kwargs):
  206. init_kwargs = dict(
  207. tokenizer_id=self.model_config.tokenizer,
  208. enable_lora=bool(self.lora_config),
  209. max_num_seqs=self.scheduler_config.max_num_seqs,
  210. max_input_length=None,
  211. tokenizer_mode=self.model_config.tokenizer_mode,
  212. trust_remote_code=self.model_config.trust_remote_code,
  213. revision=self.model_config.revision)
  214. init_kwargs.update(tokenizer_init_kwargs)
  215. self.tokenizer: BaseTokenizerGroup = get_tokenizer_group(
  216. self.parallel_config.tokenizer_pool_config, **init_kwargs)
  217. if len(self.get_tokenizer()) != self.model_config.get_vocab_size():
  218. logger.warning(
  219. f"The tokenizer's vocabulary size {len(self.get_tokenizer())}"
  220. f" does not match the model's vocabulary size "
  221. f"{self.model_config.get_vocab_size()}.")
  222. self.model_config.hf_config.tokenizer_vocab_size = len(
  223. self.get_tokenizer())
  224. def _verify_args(self) -> None:
  225. self.model_config.verify_with_parallel_config(self.parallel_config)
  226. self.cache_config.verify_with_parallel_config(self.parallel_config)
  227. if self.lora_config:
  228. self.lora_config.verify_with_model_config(self.model_config)
  229. self.lora_config.verify_with_scheduler_config(
  230. self.scheduler_config)
  231. def encode_request(
  232. self,
  233. request_id: str,
  234. prompt: Optional[str],
  235. prompt_token_ids: Optional[List[int]] = None,
  236. lora_request: Optional[LoRARequest] = None,
  237. ):
  238. if prompt_token_ids is None:
  239. assert prompt is not None
  240. prompt_token_ids = self.tokenizer.encode(request_id=request_id,
  241. prompt=prompt,
  242. lora_request=lora_request)
  243. return prompt_token_ids
  244. def add_request(
  245. self,
  246. request_id: str,
  247. prompt: Optional[str],
  248. sampling_params: SamplingParams,
  249. prompt_token_ids: Optional[List[int]] = None,
  250. arrival_time: Optional[float] = None,
  251. lora_request: Optional[LoRARequest] = None,
  252. multi_modal_data: Optional[MultiModalData] = None,
  253. ) -> None:
  254. """Add a request to the engine's request pool.
  255. The request is added to the request pool and will be processed by the
  256. scheduler as `engine.step()` is called. The exact scheduling policy is
  257. determined by the scheduler.
  258. Args:
  259. request_id: The unique ID of the request.
  260. prompt: The prompt string. Can be None if prompt_token_ids is
  261. provided.
  262. sampling_params: The sampling parameters for text generation.
  263. prompt_token_ids: The token IDs of the prompt. If None, we
  264. use the tokenizer to convert the prompts to token IDs.
  265. arrival_time: The arrival time of the request. If None, we use
  266. the current monotonic time.
  267. multi_modal_data: The multimodal data for the request.
  268. Details:
  269. - Set arrival_time to the current time if it is None.
  270. - Set prompt_token_ids to the encoded prompt if it is None.
  271. - Create `best_of` number of :class:`~aphrodite.Sequence` objects.
  272. - Create a :class:`~aphrodite.SequenceGroup` object
  273. from the list of :class:`~aphrodite.Sequence`.
  274. - Add the :class:`~aphrodite.SequenceGroup` object to the scheduler.
  275. Example:
  276. >>> # initialize engine
  277. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  278. >>> # set request arguments
  279. >>> example_prompt = "Who is the president of the United States?"
  280. >>> sampling_params = SamplingParams(temperature=0.0)
  281. >>> request_id = 0
  282. >>>
  283. >>> # add the request to the engine
  284. >>> engine.add_request(
  285. >>> str(request_id),
  286. >>> example_prompt,
  287. >>> SamplingParams(temperature=0.0))
  288. >>> # continue the request processing
  289. >>> ...
  290. """
  291. if lora_request is not None and not self.lora_config:
  292. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  293. "not enabled!")
  294. max_log_probs = self.get_model_config().max_log_probs
  295. if (sampling_params.logprobs
  296. and sampling_params.logprobs > max_log_probs) or (
  297. sampling_params.prompt_logprobs
  298. and sampling_params.prompt_logprobs > max_log_probs):
  299. raise ValueError(f"Cannot request more than "
  300. f"{max_log_probs} logprobs. "
  301. "Please increase the max_log_probs.")
  302. if arrival_time is None:
  303. arrival_time = time.monotonic()
  304. prompt_token_ids = self.encode_request(
  305. request_id=request_id,
  306. prompt=prompt,
  307. prompt_token_ids=prompt_token_ids,
  308. lora_request=lora_request,
  309. )
  310. # Create the sequences.
  311. block_size = self.cache_config.block_size
  312. seq_id = next(self.seq_counter)
  313. eos_token_id = self.tokenizer.get_lora_tokenizer(
  314. lora_request).eos_token_id
  315. seq = Sequence(
  316. seq_id,
  317. prompt,
  318. prompt_token_ids,
  319. block_size,
  320. eos_token_id,
  321. lora_request,
  322. )
  323. # Defensive copy of SamplingParams, which are used by the sampler,
  324. # this doesn't deep-copy LogitsProcessor objects
  325. sampling_params = sampling_params.clone()
  326. # Inject the eos token id into the sampling_params to support min_tokens
  327. # processing
  328. sampling_params.eos_token_id = seq.eos_token_id
  329. sampling_params.update_from_generation_config(
  330. self.generation_config_fields)
  331. # Create the sequence group.
  332. seq_group = SequenceGroup(request_id, [seq], sampling_params,
  333. arrival_time, lora_request, multi_modal_data)
  334. # Add the sequence group to the scheduler.
  335. self.scheduler.add_seq_group(seq_group)
  336. def abort_request(self, request_id: Union[str, Iterable[str]]) -> None:
  337. """Aborts a request(s) with the given ID.
  338. Args:
  339. request_id: The ID(s) of the request to abort.
  340. Details:
  341. - Refer to the
  342. :meth:`~aphrodite.processing.scheduler.Scheduler.abort_seq_group`
  343. from class :class:`~aphrodite.processing.scheduler.Scheduler`.
  344. Example:
  345. >>> # initialize engine and add a request with request_id
  346. >>> request_id = str(0)
  347. >>> # abort the request
  348. >>> engine.abort_request(request_id)
  349. """
  350. self.scheduler.abort_seq_group(request_id)
  351. def get_model_config(self) -> ModelConfig:
  352. """Gets the model configuration."""
  353. return self.model_config
  354. def get_num_unfinished_requests(self) -> int:
  355. """Gets the number of unfinished requests."""
  356. return self.scheduler.get_num_unfinished_seq_groups()
  357. def has_unfinished_requests(self) -> bool:
  358. """Returns True if there are unfinished requests."""
  359. return self.scheduler.has_unfinished_seqs()
  360. def _process_model_outputs(
  361. self, output: List[SamplerOutput],
  362. scheduled_seq_groups: List[SequenceGroup],
  363. ignored_seq_groups: List[SequenceGroup]) -> List[RequestOutput]:
  364. """Apply the model output to the sequences in the scheduled seq groups.
  365. Returns RequestOutputs that can be returned to the client.
  366. """
  367. now = time.time()
  368. # Organize outputs by [sequence group][step] instead of
  369. # [step][sequence group].
  370. output_by_sequence_group = create_output_by_sequence_group(
  371. sampler_outputs=output, num_seq_groups=len(scheduled_seq_groups))
  372. # Update the scheduled sequence groups with the model outputs.
  373. for scheduled_seq_group, outputs in zip(scheduled_seq_groups,
  374. output_by_sequence_group):
  375. seq_group = scheduled_seq_group.seq_group
  376. seq_group.update_num_computed_tokens(
  377. scheduled_seq_group.token_chunk_size)
  378. # If all sequences in the sequence group are in DECODE, then we can
  379. # process the output tokens. Otherwise, they are (chunked) prefill
  380. # samples and should not be processed.
  381. stages = [seq.data._stage for seq in seq_group.seqs_dict.values()]
  382. if all(stage == SequenceStage.DECODE for stage in stages):
  383. self.output_processor.process_outputs(seq_group, outputs)
  384. # Free the finished sequence groups.
  385. self.scheduler.free_finished_seq_groups()
  386. # Create the outputs.
  387. request_outputs: List[RequestOutput] = []
  388. for scheduled_seq_group in scheduled_seq_groups:
  389. seq_group = scheduled_seq_group.seq_group
  390. seq_group.maybe_set_first_token_time(now)
  391. request_output = RequestOutput.from_seq_group(seq_group)
  392. request_outputs.append(request_output)
  393. for seq_group in ignored_seq_groups:
  394. request_output = RequestOutput.from_seq_group(seq_group)
  395. request_outputs.append(request_output)
  396. return request_outputs
  397. def step(self) -> List[RequestOutput]:
  398. """Performs one decoding iteration and returns newly generated results.
  399. .. figure:: https://i.imgur.com/sv2HssD.png
  400. :alt: Overview of the step function
  401. :align: center
  402. Overview of the step function.
  403. Details:
  404. - Step 1: Schedules the sequences to be executed in the next
  405. iteration and the token blocks to be swapped in/out/copy.
  406. - Depending on the scheduling policy,
  407. sequences may be `preempted/reordered`.
  408. - A Sequence Group (SG) refer to a group of sequences
  409. that are generated from the same prompt.
  410. - Step 2: Calls the distributed executor to execute the model.
  411. - Step 3: Processes the model output. This mainly includes:
  412. - Decodes the relevant outputs.
  413. - Updates the scheduled sequence groups with model outputs
  414. based on its `sampling parameters` (`use_beam_search` or not).
  415. - Frees the finished sequence groups.
  416. - Finally, it creates and returns the newly generated results.
  417. Example:
  418. >>> # Please see the example/ folder for more detailed examples.
  419. >>>
  420. >>> # initialize engine and request arguments
  421. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  422. >>> example_inputs = [(0, "What is LLM?",
  423. >>> SamplingParams(temperature=0.0))]
  424. >>>
  425. >>> # Start the engine with an event loop
  426. >>> while True:
  427. >>> if example_inputs:
  428. >>> req_id, prompt, sampling_params = example_inputs.pop(0)
  429. >>> engine.add_request(str(req_id), prompt, sampling_params)
  430. >>>
  431. >>> # continue the request processing
  432. >>> request_outputs = engine.step()
  433. >>> for request_output in request_outputs:
  434. >>> if request_output.finished:
  435. >>> # return or show the request output
  436. >>>
  437. >>> if not (engine.has_unfinished_requests() or example_inputs):
  438. >>> break
  439. """
  440. seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()
  441. if not scheduler_outputs.is_empty():
  442. output = self.model_executor.execute_model(
  443. seq_group_metadata_list=seq_group_metadata_list,
  444. blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in,
  445. blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out,
  446. blocks_to_copy=scheduler_outputs.blocks_to_copy,
  447. num_lookahead_slots=scheduler_outputs.num_lookahead_slots)
  448. else:
  449. output = []
  450. request_outputs = self._process_model_outputs(
  451. output, scheduler_outputs.scheduled_seq_groups,
  452. scheduler_outputs.ignored_seq_groups)
  453. # Log stats.
  454. if self.log_stats:
  455. self.stat_logger.log(
  456. self._get_stats(scheduler_outputs, model_output=output))
  457. return request_outputs
  458. def do_log_stats(self) -> None:
  459. """Forced log when no requests active."""
  460. if self.log_stats:
  461. self.stat_logger.log(self._get_stats(scheduler_outputs=None))
  462. def _get_stats(
  463. self,
  464. scheduler_outputs: Optional[SchedulerOutputs],
  465. model_output: Optional[List[SamplerOutput]] = None) -> Stats:
  466. """Get Stats to be Logged to Prometheus.
  467. Args:
  468. scheduler_outputs: Optional, used to populate metrics related to
  469. the scheduled batch,
  470. model_output: Optional, used to emit speculative decoding metrics
  471. which are created by the workers.
  472. """
  473. now = time.monotonic()
  474. # KV Cache Usage in %.
  475. num_total_gpu = self.cache_config.num_gpu_blocks
  476. num_free_gpu = self.scheduler.block_manager.get_num_free_gpu_blocks()
  477. gpu_cache_usage = 1.0 - (num_free_gpu / num_total_gpu)
  478. num_total_cpu = self.cache_config.num_cpu_blocks
  479. cpu_cache_usage = 0.0
  480. if num_total_cpu > 0:
  481. num_free_cpu = (
  482. self.scheduler.block_manager.get_num_free_cpu_blocks())
  483. cpu_cache_usage = 1.0 - (num_free_cpu / num_total_cpu)
  484. # Scheduler State
  485. num_running = len(self.scheduler.running)
  486. num_swapped = len(self.scheduler.swapped)
  487. num_waiting = len(self.scheduler.waiting)
  488. # Iteration stats if we have scheduler output.
  489. num_prompt_tokens = 0
  490. num_generation_tokens = 0
  491. time_to_first_tokens = []
  492. time_per_output_tokens = []
  493. time_e2e_requests = []
  494. if scheduler_outputs is not None:
  495. prompt_run = scheduler_outputs.num_prefill_groups > 0
  496. # Number of Tokens.
  497. if prompt_run:
  498. num_prompt_tokens = sum(
  499. len(scheduled_seq_group.seq_group.prompt_token_ids)
  500. for scheduled_seq_group in
  501. scheduler_outputs.scheduled_seq_groups)
  502. num_generation_tokens = sum(
  503. scheduled_seq_group.seq_group.num_seqs()
  504. for scheduled_seq_group in
  505. scheduler_outputs.scheduled_seq_groups)
  506. else:
  507. num_generation_tokens = scheduler_outputs.num_batched_tokens
  508. # Latency Timings.
  509. time_last_iters = []
  510. for scheduled_seq_group in scheduler_outputs.scheduled_seq_groups:
  511. seq_group = scheduled_seq_group.seq_group
  512. # Time since last token.
  513. # (n.b. updates seq_group.metrics.last_token_time)
  514. time_last_iters.append(seq_group.get_last_latency(now))
  515. # Time since arrival for all finished requests.
  516. if seq_group.is_finished():
  517. time_e2e_requests.append(now -
  518. seq_group.metrics.arrival_time)
  519. time_to_first_tokens = time_last_iters if prompt_run else []
  520. time_per_output_tokens = [] if prompt_run else time_last_iters
  521. # Spec decode, if enabled, emits specialized metrics from the worker in
  522. # sampler output.
  523. if model_output and (model_output[0].spec_decode_worker_metrics
  524. is not None):
  525. spec_decode_metrics = model_output[0].spec_decode_worker_metrics
  526. else:
  527. spec_decode_metrics = None
  528. return Stats(
  529. now=now,
  530. num_running=num_running,
  531. num_swapped=num_swapped,
  532. num_waiting=num_waiting,
  533. gpu_cache_usage=gpu_cache_usage,
  534. cpu_cache_usage=cpu_cache_usage,
  535. num_prompt_tokens=num_prompt_tokens,
  536. num_generation_tokens=num_generation_tokens,
  537. time_to_first_tokens=time_to_first_tokens,
  538. time_per_output_tokens=time_per_output_tokens,
  539. time_e2e_requests=time_e2e_requests,
  540. spec_decode_metrics=spec_decode_metrics,
  541. )
  542. def add_lora(self, lora_request: LoRARequest) -> bool:
  543. return self.model_executor.add_lora(lora_request)
  544. def remove_lora(self, lora_id: int) -> bool:
  545. return self.model_executor.remove_lora(lora_id)
  546. def list_loras(self) -> List[int]:
  547. return self.model_executor.list_loras()
  548. def check_health(self) -> None:
  549. self.model_executor.check_health()
  550. setup_logger()