aphrodite_engine.py 27 KB

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