aphrodite_engine.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. import os
  2. import time
  3. from contextlib import contextmanager
  4. from typing import TYPE_CHECKING, Any, ClassVar, Dict, Iterable, List, Optional
  5. from typing import Sequence as GenericSequence
  6. from typing import Type, TypeVar, Union
  7. from loguru import logger
  8. from transformers import PreTrainedTokenizer
  9. from aphrodite.common.config import (CacheConfig, DecodingConfig, DeviceConfig,
  10. EngineConfig, LoadConfig, LoRAConfig,
  11. ModelConfig, MultiModalConfig,
  12. ParallelConfig, PromptAdapterConfig,
  13. SchedulerConfig, SpeculativeConfig)
  14. from aphrodite.common.logger import setup_logger
  15. from aphrodite.common.outputs import (EmbeddingRequestOutput, RequestOutput,
  16. RequestOutputFactory)
  17. from aphrodite.common.pooling_params import PoolingParams
  18. from aphrodite.common.sampling_params import SamplingParams
  19. from aphrodite.common.sequence import (EmbeddingSequenceGroupOutput,
  20. ExecuteModelRequest, PoolerOutput,
  21. SamplerOutput, Sequence, SequenceGroup,
  22. SequenceGroupMetadata, SequenceStatus)
  23. from aphrodite.common.utils import Counter
  24. from aphrodite.engine.args_tools import EngineArgs
  25. from aphrodite.engine.metrics import (LoggingStatLogger, PrometheusStatLogger,
  26. StatLoggerBase, Stats)
  27. from aphrodite.engine.output_processor.interfaces import \
  28. SequenceGroupOutputProcessor
  29. from aphrodite.engine.output_processor.stop_checker import StopChecker
  30. from aphrodite.engine.output_processor.util import \
  31. create_output_by_sequence_group
  32. from aphrodite.executor.executor_base import ExecutorBase
  33. from aphrodite.executor.ray_utils import initialize_ray_cluster
  34. from aphrodite.inputs import INPUT_REGISTRY, LLMInputs, PromptInputs
  35. from aphrodite.lora.request import LoRARequest
  36. from aphrodite.processing.scheduler import (ScheduledSequenceGroup, Scheduler,
  37. SchedulerOutputs)
  38. from aphrodite.prompt_adapter.request import PromptAdapterRequest
  39. from aphrodite.transformers_utils.config import try_get_generation_config
  40. from aphrodite.transformers_utils.detokenizer import Detokenizer
  41. from aphrodite.transformers_utils.tokenizer_group import (BaseTokenizerGroup,
  42. get_tokenizer_group)
  43. from aphrodite.version import __version__ as APHRODITE_VERSION
  44. _LOCAL_LOGGING_INTERVAL_SEC = 5
  45. APHRODITE_USE_RAY_SPMD_WORKER = bool(
  46. os.getenv("APHRODITE_USE_RAY_SPMD_WORKER", 0))
  47. def _load_generation_config_dict(model_config: ModelConfig) -> Dict[str, Any]:
  48. config = try_get_generation_config(
  49. model_config.model,
  50. trust_remote_code=model_config.trust_remote_code,
  51. revision=model_config.revision,
  52. )
  53. if config is None:
  54. return {}
  55. return config.to_diff_dict()
  56. _O = TypeVar("_O", RequestOutput, EmbeddingRequestOutput)
  57. class AphroditeEngine:
  58. """An LLM engine that receives requests and generates texts.
  59. This is the main class for the Aphrodite engine. It receives requests
  60. from clients and generates texts from the LLM. It includes a tokenizer, a
  61. language model (possibly distributed across multiple GPUs), and GPU memory
  62. space allocated for intermediate states (aka KV cache). This class utilizes
  63. iteration-level scheduling and efficient memory management to maximize the
  64. serving throughput.
  65. The `LLM` class wraps this class for offline batched inference and the
  66. `AsyncAphrodite` class wraps this class for online serving.
  67. NOTE: The config arguments are derived from the `EngineArgs` class. For the
  68. comprehensive list of arguments, see `EngineArgs`.
  69. Args:
  70. model_config: The configuration related to the LLM model.
  71. cache_config: The configuration related to the KV cache memory
  72. management.
  73. parallel_config: The configuration related to distributed execution.
  74. scheduler_config: The configuration related to the request scheduler.
  75. device_config: The configuration related to the device.
  76. lora_config (Optional): The configuration related to serving multi-LoRA.
  77. multimodal_config (Optional): The configuration related to multimodal
  78. models.
  79. speculative_config (Optional): The configuration related to speculative
  80. decoding.
  81. executor_class: The model executor class for managing distributed
  82. execution.
  83. prompt_adapter_config (Optional): The configuration related to serving
  84. prompt adapters.
  85. log_stats: Whether to log statistics.
  86. """
  87. DO_VALIDATE_OUTPUT: ClassVar[bool] = False
  88. """A flag to toggle whether to validate the type of request output."""
  89. @classmethod
  90. @contextmanager
  91. def enable_output_validation(cls):
  92. cls.DO_VALIDATE_OUTPUT = True
  93. yield
  94. cls.DO_VALIDATE_OUTPUT = False
  95. @classmethod
  96. def validate_output(
  97. cls,
  98. output: object,
  99. output_type: Type[_O],
  100. ) -> _O:
  101. do_validate = cls.DO_VALIDATE_OUTPUT
  102. if ((TYPE_CHECKING or do_validate)
  103. and not isinstance(output, output_type)):
  104. raise TypeError(f"Expected output of type {output_type}, "
  105. f"but found type {type(output)}")
  106. return output
  107. @classmethod
  108. def validate_outputs(
  109. cls,
  110. outputs: GenericSequence[object],
  111. output_type: Type[_O],
  112. ) -> List[_O]:
  113. do_validate = cls.DO_VALIDATE_OUTPUT
  114. outputs_: List[_O]
  115. if TYPE_CHECKING or do_validate:
  116. outputs_ = []
  117. for output in outputs:
  118. if not isinstance(output, output_type):
  119. raise TypeError(f"Expected output of type {output_type}, "
  120. f"but found type {type(output)}")
  121. outputs_.append(output)
  122. else:
  123. outputs_ = outputs
  124. return outputs_
  125. tokenizer: Optional[BaseTokenizerGroup]
  126. def __init__(
  127. self,
  128. model_config: ModelConfig,
  129. cache_config: CacheConfig,
  130. parallel_config: ParallelConfig,
  131. scheduler_config: SchedulerConfig,
  132. device_config: DeviceConfig,
  133. load_config: LoadConfig,
  134. lora_config: Optional[LoRAConfig],
  135. multimodal_config: Optional[MultiModalConfig],
  136. speculative_config: Optional[SpeculativeConfig],
  137. decoding_config: Optional[DecodingConfig],
  138. prompt_adapter_config: Optional[PromptAdapterConfig],
  139. executor_class: Type[ExecutorBase],
  140. log_stats: bool,
  141. stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,
  142. ) -> None:
  143. try:
  144. import aphrodite.commit_id
  145. commit_id = True
  146. except ImportError:
  147. commit_id = False
  148. config_dict = {
  149. "Model": model_config.model,
  150. "Speculative Config": speculative_config,
  151. "DataType": model_config.dtype,
  152. "Model Load Format": load_config.load_format,
  153. "Tensor Parallel Size": parallel_config.tensor_parallel_size,
  154. "Pipeline Parallel Size": parallel_config.pipeline_parallel_size,
  155. "Disable Custom All-Reduce":
  156. parallel_config.disable_custom_all_reduce,
  157. "Quantization Format": model_config.quantization,
  158. "Context Length": model_config.max_model_len,
  159. "Enforce Eager Mode": model_config.enforce_eager,
  160. "Prefix Caching": cache_config.enable_prefix_caching,
  161. "KV Cache DataType": cache_config.cache_dtype,
  162. "Device": device_config.device,
  163. "Rope Scaling": model_config.rope_scaling,
  164. "Guided Decoding Backend": decoding_config
  165. }
  166. logger.info("-" * 85)
  167. if not commit_id:
  168. logger.info(
  169. f"Initializing Aphrodite Engine (v{APHRODITE_VERSION}) "
  170. "with the following config:")
  171. else:
  172. logger.info(f"Initializing Aphrodite Engine (v{APHRODITE_VERSION} "
  173. f"commit {aphrodite.__short_commit__}) with the "
  174. "following config:")
  175. for key, value in config_dict.items():
  176. if value is not None and not ((key == "Model Load Format" or key ==\
  177. "KV Cache DataType") and value == \
  178. "auto"):
  179. logger.info(f"{key} = {value!r}")
  180. logger.info("-" * 85)
  181. # TODO: Print more configs in debug mode.
  182. self.model_config = model_config
  183. self.cache_config = cache_config
  184. self.lora_config = lora_config
  185. self.multimodal_config = multimodal_config
  186. self.parallel_config = parallel_config
  187. self.scheduler_config = scheduler_config
  188. self.device_config = device_config
  189. self.speculative_config = speculative_config
  190. self.load_config = load_config
  191. self.decoding_config = decoding_config or DecodingConfig()
  192. self.prompt_adapter_config = prompt_adapter_config
  193. self.log_stats = log_stats
  194. if not self.model_config.skip_tokenizer_init:
  195. self.tokenizer = self._init_tokenizer()
  196. self.detokenizer = Detokenizer(self.tokenizer)
  197. else:
  198. self.tokenizer = None
  199. self.detokenizer = None
  200. self.seq_counter = Counter()
  201. self.generation_config_fields = _load_generation_config_dict(
  202. model_config)
  203. self.input_processor = INPUT_REGISTRY.create_input_processor(
  204. self.model_config)
  205. self.model_executor = executor_class(
  206. model_config=model_config,
  207. cache_config=cache_config,
  208. parallel_config=parallel_config,
  209. scheduler_config=scheduler_config,
  210. device_config=device_config,
  211. lora_config=lora_config,
  212. multimodal_config=multimodal_config,
  213. speculative_config=speculative_config,
  214. load_config=load_config,
  215. prompt_adapter_config=prompt_adapter_config,
  216. )
  217. if not self.model_config.embedding_mode:
  218. self._initialize_kv_caches()
  219. if self.tokenizer:
  220. # Ping the tokenizer to ensure liveness if it runs in a
  221. # different process.
  222. self.tokenizer.ping()
  223. # Create the scheduler.
  224. # NOTE: the cache_config here have been updated with the numbers of
  225. # GPU and CPU blocks, which are profiled in the distributed executor.
  226. self.scheduler = [
  227. Scheduler(scheduler_config, cache_config, lora_config,
  228. parallel_config.pipeline_parallel_size)
  229. for _ in range(parallel_config.pipeline_parallel_size)
  230. ]
  231. # Metric Logging.
  232. if self.log_stats:
  233. if stat_loggers is not None:
  234. self.stat_loggers = stat_loggers
  235. else:
  236. self.stat_loggers = {
  237. "logging":
  238. LoggingStatLogger(
  239. local_interval=_LOCAL_LOGGING_INTERVAL_SEC),
  240. "prometheus":
  241. PrometheusStatLogger(
  242. local_interval=_LOCAL_LOGGING_INTERVAL_SEC,
  243. labels=dict(model_name=model_config.served_model_name),
  244. max_model_len=self.model_config.max_model_len),
  245. }
  246. self.stat_loggers["prometheus"].info("cache_config",
  247. self.cache_config)
  248. # Create sequence output processor, e.g. for beam search or
  249. # speculative decoding.
  250. self.output_processor = (
  251. SequenceGroupOutputProcessor.create_output_processor(
  252. self.scheduler_config,
  253. self.detokenizer,
  254. self.scheduler,
  255. self.seq_counter,
  256. self.get_tokenizer_for_seq,
  257. stop_checker=StopChecker(
  258. self.scheduler_config.max_model_len,
  259. self.get_tokenizer_for_seq,
  260. ),
  261. ))
  262. def _initialize_kv_caches(self) -> None:
  263. """Initialize the KV cache in the worker(s).
  264. The workers will determine the number of blocks in both the GPU cache
  265. and the swap CPU cache.
  266. """
  267. num_gpu_blocks, num_cpu_blocks = (
  268. self.model_executor.determine_num_available_blocks())
  269. if self.cache_config.num_gpu_blocks_override is not None:
  270. num_gpu_blocks_override = self.cache_config.num_gpu_blocks_override
  271. logger.info(f"Overriding {num_gpu_blocks=} with "
  272. f"{num_gpu_blocks_override=}")
  273. num_gpu_blocks = num_gpu_blocks_override
  274. self.cache_config.num_gpu_blocks = num_gpu_blocks
  275. self.cache_config.num_cpu_blocks = num_cpu_blocks
  276. self.model_executor.initialize_cache(num_gpu_blocks, num_cpu_blocks)
  277. @classmethod
  278. def _get_executor_cls(cls,
  279. engine_config: EngineConfig) -> Type[ExecutorBase]:
  280. distributed_executor_backend = (
  281. engine_config.parallel_config.distributed_executor_backend)
  282. # Initialize the cluster and specify the executor class.
  283. if isinstance(distributed_executor_backend, type):
  284. if not issubclass(distributed_executor_backend, ExecutorBase):
  285. raise TypeError(
  286. "distributed_executor_backend must be a subclass of "
  287. f"ExecutorBase. Got {distributed_executor_backend}.")
  288. if distributed_executor_backend.uses_ray: # type: ignore
  289. initialize_ray_cluster(engine_config.parallel_config)
  290. executor_class = distributed_executor_backend
  291. elif engine_config.device_config.device_type == "neuron":
  292. from aphrodite.executor.neuron_executor import NeuronExecutor
  293. executor_class = NeuronExecutor
  294. elif engine_config.device_config.device_type == "tpu":
  295. from aphrodite.executor.tpu_executor import TPUExecutor
  296. executor_class = TPUExecutor
  297. elif engine_config.device_config.device_type == "cpu":
  298. from aphrodite.executor.cpu_executor import CPUExecutor
  299. executor_class = CPUExecutor
  300. elif engine_config.device_config.device_type == "openvino":
  301. from aphrodite.executor.openvino_executor import OpenVINOExecutor
  302. executor_class = OpenVINOExecutor
  303. elif engine_config.device_config.device_type == "xpu":
  304. if distributed_executor_backend == "ray":
  305. initialize_ray_cluster(engine_config.parallel_config)
  306. from aphrodite.executor.ray_xpu_executor import RayXPUExecutor
  307. executor_class = RayXPUExecutor
  308. else:
  309. from aphrodite.executor.xpu_executor import XPUExecutor
  310. executor_class = XPUExecutor
  311. elif distributed_executor_backend == "ray":
  312. initialize_ray_cluster(engine_config.parallel_config)
  313. from aphrodite.executor.ray_gpu_executor import RayGPUExecutor
  314. executor_class = RayGPUExecutor
  315. elif distributed_executor_backend == "mp":
  316. from aphrodite.executor.multiproc_gpu_executor import \
  317. MultiprocessingGPUExecutor
  318. assert not APHRODITE_USE_RAY_SPMD_WORKER, (
  319. "multiprocessing distributed executor backend does not "
  320. "support APHRODITE_USE_RAY_SPMD_WORKER=1")
  321. executor_class = MultiprocessingGPUExecutor
  322. else:
  323. from aphrodite.executor.gpu_executor import GPUExecutor
  324. executor_class = GPUExecutor
  325. return executor_class
  326. @classmethod
  327. def from_engine_args(
  328. cls,
  329. engine_args: EngineArgs,
  330. stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,
  331. ) -> "AphroditeEngine":
  332. """Creates an LLM engine from the engine arguments."""
  333. # Create the engine configs.
  334. engine_config = engine_args.create_engine_config()
  335. executor_class = cls._get_executor_cls(engine_config)
  336. # Create the LLM engine.
  337. engine = cls(
  338. **engine_config.to_dict(),
  339. executor_class=executor_class,
  340. log_stats=not engine_args.disable_log_stats,
  341. )
  342. return engine
  343. def __reduce__(self):
  344. # This is to ensure that the AphroditeEngine is not referenced in
  345. # the closure used to initialize Ray worker actors
  346. raise RuntimeError("AphroditeEngine should not be pickled!")
  347. def __del__(self):
  348. # Shutdown the model executor when engine is garbage collected.
  349. # Use getattr since __init__ can fail before the field is set
  350. if model_executor := getattr(self, "model_executor", None):
  351. model_executor.shutdown()
  352. MISSING_TOKENIZER_GROUP_MSG = ("Unable to get tokenizer because "
  353. "skip_tokenizer_init is True")
  354. def get_tokenizer_group(
  355. self,
  356. fail_msg: str = MISSING_TOKENIZER_GROUP_MSG) -> BaseTokenizerGroup:
  357. if self.tokenizer is None:
  358. raise ValueError(fail_msg)
  359. return self.tokenizer
  360. def get_tokenizer(
  361. self,
  362. lora_request: Optional[LoRARequest] = None
  363. ) -> "PreTrainedTokenizer":
  364. return self.get_tokenizer_group().get_lora_tokenizer(lora_request)
  365. def get_tokenizer_for_seq(self,
  366. sequence: Sequence) -> "PreTrainedTokenizer":
  367. return self.get_tokenizer_group().get_lora_tokenizer(
  368. sequence.lora_request)
  369. def _init_tokenizer(self, **tokenizer_init_kwargs) -> BaseTokenizerGroup:
  370. init_kwargs = dict(
  371. tokenizer_id=self.model_config.tokenizer,
  372. enable_lora=bool(self.lora_config),
  373. max_num_seqs=self.scheduler_config.max_num_seqs,
  374. max_input_length=None,
  375. tokenizer_mode=self.model_config.tokenizer_mode,
  376. trust_remote_code=self.model_config.trust_remote_code,
  377. revision=self.model_config.tokenizer_revision)
  378. init_kwargs.update(tokenizer_init_kwargs)
  379. return get_tokenizer_group(self.parallel_config.tokenizer_pool_config,
  380. **init_kwargs)
  381. def _verify_args(self) -> None:
  382. self.model_config.verify_with_parallel_config(self.parallel_config)
  383. self.cache_config.verify_with_parallel_config(self.parallel_config)
  384. if self.lora_config:
  385. self.lora_config.verify_with_model_config(self.model_config)
  386. self.lora_config.verify_with_scheduler_config(
  387. self.scheduler_config)
  388. if self.prompt_adapter_config:
  389. self.prompt_adapter_config.verify_with_model_config(
  390. self.model_config)
  391. def _get_eos_token_id(
  392. self, lora_request: Optional[LoRARequest]) -> Optional[int]:
  393. if self.tokenizer is None:
  394. logger.warning("Using None for EOS token id because tokenizer "
  395. "is not initialized")
  396. return None
  397. return self.tokenizer.get_lora_tokenizer(lora_request).eos_token_id
  398. def _add_processed_request(
  399. self,
  400. request_id: str,
  401. processed_inputs: LLMInputs,
  402. params: Union[SamplingParams, PoolingParams],
  403. arrival_time: float,
  404. lora_request: Optional[LoRARequest],
  405. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  406. ) -> None:
  407. # Create the sequences.
  408. block_size = self.cache_config.block_size
  409. seq_id = next(self.seq_counter)
  410. eos_token_id = self._get_eos_token_id(lora_request)
  411. seq = Sequence(seq_id, processed_inputs, block_size, eos_token_id,
  412. lora_request, prompt_adapter_request)
  413. # Create a SequenceGroup based on SamplingParams or PoolingParams
  414. if isinstance(params, SamplingParams):
  415. seq_group = self._create_sequence_group_with_sampling(
  416. request_id,
  417. seq,
  418. params,
  419. arrival_time=arrival_time,
  420. lora_request=lora_request,
  421. prompt_adapter_request=prompt_adapter_request,
  422. )
  423. elif isinstance(params, PoolingParams):
  424. seq_group = self._create_sequence_group_with_pooling(
  425. request_id,
  426. seq,
  427. params,
  428. arrival_time=arrival_time,
  429. lora_request=lora_request,
  430. prompt_adapter_request=prompt_adapter_request,
  431. )
  432. else:
  433. raise ValueError(
  434. "Either SamplingParams or PoolingParams must be provided.")
  435. # Add the sequence group to the scheduler with least unfinished seqs.
  436. costs = [
  437. scheduler.get_num_unfinished_seq_groups()
  438. for scheduler in self.scheduler
  439. ]
  440. min_cost_scheduler = self.scheduler[costs.index(min(costs))]
  441. min_cost_scheduler.add_seq_group(seq_group)
  442. def stop_remote_worker_execution_loop(self) -> None:
  443. self.model_executor.stop_remote_worker_execution_loop()
  444. def process_model_inputs(
  445. self,
  446. request_id: str,
  447. inputs: PromptInputs,
  448. lora_request: Optional[LoRARequest] = None,
  449. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  450. ) -> LLMInputs:
  451. if isinstance(inputs, str):
  452. inputs = {"prompt": inputs}
  453. if "prompt_token_ids" not in inputs:
  454. tokenizer = self.get_tokenizer_group("prompts must be None if "
  455. "skip_tokenizer_init is True")
  456. prompt_token_ids = tokenizer.encode(request_id=request_id,
  457. prompt=inputs["prompt"],
  458. lora_request=lora_request)
  459. else:
  460. prompt_token_ids = inputs["prompt_token_ids"]
  461. if prompt_adapter_request:
  462. prompt_token_ids = \
  463. [0] * prompt_adapter_request.prompt_adapter_num_virtual_tokens\
  464. + prompt_token_ids
  465. llm_inputs = LLMInputs(prompt_token_ids=prompt_token_ids,
  466. prompt=inputs.get("prompt"),
  467. multi_modal_data=inputs.get("multi_modal_data"))
  468. return self.input_processor(llm_inputs)
  469. def add_request(
  470. self,
  471. request_id: str,
  472. inputs: PromptInputs,
  473. params: Union[SamplingParams, PoolingParams],
  474. arrival_time: Optional[float] = None,
  475. lora_request: Optional[LoRARequest] = None,
  476. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  477. ) -> None:
  478. """Add a request to the engine's request pool.
  479. The request is added to the request pool and will be processed by the
  480. scheduler as `engine.step()` is called. The exact scheduling policy is
  481. determined by the scheduler.
  482. Args:
  483. request_id: The unique ID of the request.
  484. prompt: The prompt string. Can be None if prompt_token_ids is
  485. provided.
  486. params: Parameters for sampling or pooling. SamplingParams
  487. for text generation. PoolingParams for pooling.
  488. prompt_token_ids: The token IDs of the prompt. If None, we
  489. use the tokenizer to convert the prompts to token IDs.
  490. arrival_time: The arrival time of the request. If None, we use
  491. the current monotonic time.
  492. multi_modal_data: Multi modal data per request.
  493. Details:
  494. - Set arrival_time to the current time if it is None.
  495. - Set prompt_token_ids to the encoded prompt if it is None.
  496. - Create `best_of` number of :class:`~aphrodite.common.sequence`
  497. objects.
  498. - Create a :class:`~aphrodite.common.sequenceGroup` object
  499. from the list of :class:`~aphrodite.common.sequence`.
  500. - Add the :class:`~aphrodite.common.sequenceGroup` object to the
  501. scheduler.
  502. Example:
  503. >>> # initialize engine
  504. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  505. >>> # set request arguments
  506. >>> example_prompt = "Who is the president of the United States?"
  507. >>> sampling_params = SamplingParams(temperature=0.0)
  508. >>> request_id = 0
  509. >>>
  510. >>> # add the request to the engine
  511. >>> engine.add_request(
  512. >>> str(request_id),
  513. >>> example_prompt,
  514. >>> SamplingParams(temperature=0.0))
  515. >>> # continue the request processing
  516. >>> ...
  517. """
  518. if lora_request is not None and not self.lora_config:
  519. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  520. "not enabled!")
  521. if arrival_time is None:
  522. arrival_time = time.time()
  523. processed_inputs = self.process_model_inputs(
  524. request_id=request_id,
  525. inputs=inputs,
  526. lora_request=lora_request,
  527. prompt_adapter_request=prompt_adapter_request)
  528. self._add_processed_request(
  529. request_id=request_id,
  530. processed_inputs=processed_inputs,
  531. params=params,
  532. arrival_time=arrival_time,
  533. lora_request=lora_request,
  534. prompt_adapter_request=prompt_adapter_request,
  535. )
  536. def _create_sequence_group_with_sampling(
  537. self,
  538. request_id: str,
  539. seq: Sequence,
  540. sampling_params: SamplingParams,
  541. arrival_time: float,
  542. lora_request: Optional[LoRARequest],
  543. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  544. ) -> SequenceGroup:
  545. """Creates a SequenceGroup with SamplingParams."""
  546. max_logprobs = self.get_model_config().max_logprobs
  547. if (sampling_params.logprobs
  548. and sampling_params.logprobs > max_logprobs) or (
  549. sampling_params.prompt_logprobs
  550. and sampling_params.prompt_logprobs > max_logprobs):
  551. raise ValueError(f"Cannot request more than "
  552. f"{max_logprobs} logprobs.")
  553. # Defensive copy of SamplingParams, which are used by the sampler,
  554. # this doesn't deep-copy LogitsProcessor objects
  555. sampling_params = sampling_params.clone()
  556. sampling_params.update_from_generation_config(
  557. self.generation_config_fields, seq.eos_token_id)
  558. # Create the sequence group.
  559. seq_group = SequenceGroup(
  560. request_id=request_id,
  561. seqs=[seq],
  562. arrival_time=arrival_time,
  563. sampling_params=sampling_params,
  564. lora_request=lora_request,
  565. prompt_adapter_request=prompt_adapter_request)
  566. return seq_group
  567. def _create_sequence_group_with_pooling(
  568. self,
  569. request_id: str,
  570. seq: Sequence,
  571. pooling_params: PoolingParams,
  572. arrival_time: float,
  573. lora_request: Optional[LoRARequest],
  574. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  575. ) -> SequenceGroup:
  576. """Creates a SequenceGroup with PoolingParams."""
  577. # Defensive copy of PoolingParams, which are used by the pooler
  578. pooling_params = pooling_params.clone()
  579. # Create the sequence group.
  580. seq_group = SequenceGroup(
  581. request_id=request_id,
  582. seqs=[seq],
  583. arrival_time=arrival_time,
  584. lora_request=lora_request,
  585. pooling_params=pooling_params,
  586. prompt_adapter_request=prompt_adapter_request)
  587. return seq_group
  588. def abort_request(self, request_id: Union[str, Iterable[str]]) -> None:
  589. """Aborts a request(s) with the given ID.
  590. Args:
  591. request_id: The ID(s) of the request to abort.
  592. Details:
  593. - Refer to the
  594. :meth:`~aphrodite.processing.scheduler.Scheduler.abort_seq_group`
  595. from class :class:`~aphrodite.processing.scheduler.Scheduler`.
  596. Example:
  597. >>> # initialize engine and add a request with request_id
  598. >>> request_id = str(0)
  599. >>> # abort the request
  600. >>> engine.abort_request(request_id)
  601. """
  602. for scheduler in self.scheduler:
  603. scheduler.abort_seq_group(request_id)
  604. def get_model_config(self) -> ModelConfig:
  605. """Gets the model configuration."""
  606. return self.model_config
  607. def get_decoding_config(self) -> DecodingConfig:
  608. """Gets the decoding configuration."""
  609. return self.decoding_config
  610. def get_num_unfinished_requests(self) -> int:
  611. """Gets the number of unfinished requests."""
  612. return sum(scheduler.get_num_unfinished_seq_groups()
  613. for scheduler in self.scheduler)
  614. def has_unfinished_requests(self) -> bool:
  615. """Returns True if there are unfinished requests."""
  616. return any(scheduler.has_unfinished_seqs()
  617. for scheduler in self.scheduler)
  618. def has_unfinished_requests_for_virtual_engine(
  619. self, virtual_engine: int) -> bool:
  620. """
  621. Returns True if there are unfinished requests for the virtual engine.
  622. """
  623. return self.scheduler[virtual_engine].has_unfinished_seqs()
  624. def _process_sequence_group_outputs(
  625. self,
  626. seq_group: SequenceGroup,
  627. outputs: List[EmbeddingSequenceGroupOutput],
  628. ) -> None:
  629. seq_group.embeddings = outputs[0].embeddings
  630. for seq in seq_group.get_seqs():
  631. seq.status = SequenceStatus.FINISHED_STOPPED
  632. return
  633. def _process_model_outputs(
  634. self,
  635. output: GenericSequence[Union[SamplerOutput, PoolerOutput]],
  636. scheduled_seq_groups: List[ScheduledSequenceGroup],
  637. ignored_seq_groups: List[SequenceGroup],
  638. seq_group_metadata_list: List[SequenceGroupMetadata],
  639. ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  640. """Apply the model output to the sequences in the scheduled seq groups.
  641. Returns RequestOutputs that can be returned to the client.
  642. """
  643. now = time.time()
  644. # Organize outputs by [sequence group][step] instead of
  645. # [step][sequence group].
  646. output_by_sequence_group = create_output_by_sequence_group(
  647. output, num_seq_groups=len(scheduled_seq_groups))
  648. # Update the scheduled sequence groups with the model outputs.
  649. for scheduled_seq_group, outputs, seq_group_meta in zip(
  650. scheduled_seq_groups, output_by_sequence_group,
  651. seq_group_metadata_list):
  652. seq_group = scheduled_seq_group.seq_group
  653. seq_group.update_num_computed_tokens(
  654. scheduled_seq_group.token_chunk_size)
  655. if self.model_config.embedding_mode:
  656. self._process_sequence_group_outputs(seq_group, outputs)
  657. continue
  658. self.output_processor.process_prompt_logprob(seq_group, outputs)
  659. if seq_group_meta.do_sample:
  660. self.output_processor.process_outputs(seq_group, outputs)
  661. # Free the finished sequence groups.
  662. for scheduler in self.scheduler:
  663. scheduler.free_finished_seq_groups()
  664. # Create the outputs.
  665. request_outputs: List[Union[RequestOutput,
  666. EmbeddingRequestOutput]] = []
  667. for scheduled_seq_group in scheduled_seq_groups:
  668. seq_group = scheduled_seq_group.seq_group
  669. seq_group.maybe_set_first_token_time(now)
  670. request_output = RequestOutputFactory.create(seq_group)
  671. request_outputs.append(request_output)
  672. for seq_group in ignored_seq_groups:
  673. request_output = RequestOutputFactory.create(seq_group)
  674. request_outputs.append(request_output)
  675. return request_outputs
  676. def step(self) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  677. """Performs one decoding iteration and returns newly generated results.
  678. .. figure:: https://i.imgur.com/sv2HssD.png
  679. :alt: Overview of the step function
  680. :align: center
  681. Overview of the step function.
  682. Details:
  683. - Step 1: Schedules the sequences to be executed in the next
  684. iteration and the token blocks to be swapped in/out/copy.
  685. - Depending on the scheduling policy,
  686. sequences may be `preempted/reordered`.
  687. - A Sequence Group (SG) refer to a group of sequences
  688. that are generated from the same prompt.
  689. - Step 2: Calls the distributed executor to execute the model.
  690. - Step 3: Processes the model output. This mainly includes:
  691. - Decodes the relevant outputs.
  692. - Updates the scheduled sequence groups with model outputs
  693. based on its `sampling parameters` (`use_beam_search` or not).
  694. - Frees the finished sequence groups.
  695. - Finally, it creates and returns the newly generated results.
  696. Example:
  697. >>> # Please see the example/ folder for more detailed examples.
  698. >>>
  699. >>> # initialize engine and request arguments
  700. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  701. >>> example_inputs = [(0, "What is LLM?",
  702. >>> SamplingParams(temperature=0.0))]
  703. >>>
  704. >>> # Start the engine with an event loop
  705. >>> while True:
  706. >>> if example_inputs:
  707. >>> req_id, prompt, sampling_params = example_inputs.pop(0)
  708. >>> engine.add_request(str(req_id), prompt, sampling_params)
  709. >>>
  710. >>> # continue the request processing
  711. >>> request_outputs = engine.step()
  712. >>> for request_output in request_outputs:
  713. >>> if request_output.finished:
  714. >>> # return or show the request output
  715. >>>
  716. >>> if not (engine.has_unfinished_requests() or example_inputs):
  717. >>> break
  718. """
  719. if self.parallel_config.pipeline_parallel_size > 1:
  720. raise NotImplementedError(
  721. "Pipeline parallelism is only supported through AsyncAphrodite "
  722. "as performance will be severely degraded otherwise.")
  723. seq_group_metadata_list, scheduler_outputs = self.scheduler[
  724. 0].schedule()
  725. if not scheduler_outputs.is_empty():
  726. finished_requests_ids = self.scheduler[
  727. 0].get_and_reset_finished_requests_ids()
  728. execute_model_req = ExecuteModelRequest(
  729. seq_group_metadata_list=seq_group_metadata_list,
  730. blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in,
  731. blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out,
  732. blocks_to_copy=scheduler_outputs.blocks_to_copy,
  733. num_lookahead_slots=scheduler_outputs.num_lookahead_slots,
  734. running_queue_size=scheduler_outputs.running_queue_size,
  735. finished_requests_ids=finished_requests_ids,
  736. )
  737. output = self.model_executor.execute_model(
  738. execute_model_req=execute_model_req)
  739. else:
  740. output = []
  741. request_outputs = self._process_model_outputs(
  742. output, scheduler_outputs.scheduled_seq_groups,
  743. scheduler_outputs.ignored_seq_groups, seq_group_metadata_list)
  744. # Log stats.
  745. self.do_log_stats(scheduler_outputs, output)
  746. if not self.has_unfinished_requests():
  747. # Stop the execute model loop in parallel workers until there are
  748. # more requests to process. This avoids waiting indefinitely in
  749. # torch.distributed ops which may otherwise timeout, and unblocks
  750. # the RPC thread in the workers so that they can process any other
  751. # queued control plane messages, such as add/remove lora adapters.
  752. self.model_executor.stop_remote_worker_execution_loop()
  753. return request_outputs
  754. def add_logger(self, logger_name: str, logger: StatLoggerBase) -> None:
  755. if logger_name in self.stat_loggers:
  756. raise KeyError(f"Logger with name {logger_name} already exists.")
  757. self.stat_loggers[logger_name] = logger
  758. def remove_logger(self, logger_name: str) -> None:
  759. if logger_name not in self.stat_loggers:
  760. raise KeyError(f"Logger with name {logger_name} does not exist.")
  761. del self.stat_loggers[logger_name]
  762. def do_log_stats(
  763. self,
  764. scheduler_outputs: Optional[SchedulerOutputs] = None,
  765. model_output: Optional[List[SamplerOutput]] = None) -> None:
  766. """Forced log when no requests active."""
  767. if self.log_stats:
  768. for loggers in self.stat_loggers.values():
  769. loggers.log(self._get_stats(scheduler_outputs, model_output))
  770. def _get_stats(
  771. self,
  772. scheduler_outputs: Optional[SchedulerOutputs],
  773. model_output: Optional[List[SamplerOutput]] = None) -> Stats:
  774. """Get Stats to be Logged to Prometheus.
  775. Args:
  776. scheduler_outputs: Optional, used to populate metrics related to
  777. the scheduled batch,
  778. model_output: Optional, used to emit speculative decoding metrics
  779. which are created by the workers.
  780. """
  781. now = time.time()
  782. # System State
  783. # Scheduler State
  784. num_running_sys = sum(
  785. len(scheduler.running) for scheduler in self.scheduler)
  786. num_swapped_sys = sum(
  787. len(scheduler.swapped) for scheduler in self.scheduler)
  788. num_waiting_sys = sum(
  789. len(scheduler.waiting) for scheduler in self.scheduler)
  790. # KV Cache Usage in %
  791. num_total_gpu = self.cache_config.num_gpu_blocks
  792. gpu_cache_usage_sys = 0.
  793. if num_total_gpu is not None:
  794. num_free_gpu = sum(
  795. scheduler.block_manager.get_num_free_gpu_blocks()
  796. for scheduler in self.scheduler)
  797. gpu_cache_usage_sys = 1.0 - (num_free_gpu / num_total_gpu)
  798. num_total_cpu = self.cache_config.num_cpu_blocks
  799. cpu_cache_usage_sys = 0.
  800. if num_total_cpu is not None and num_total_cpu > 0:
  801. num_free_cpu = sum(
  802. scheduler.block_manager.get_num_free_cpu_blocks()
  803. for scheduler in self.scheduler)
  804. cpu_cache_usage_sys = 1.0 - (num_free_cpu / num_total_cpu)
  805. # Iteration stats
  806. num_prompt_tokens_iter = 0
  807. num_generation_tokens_iter = 0
  808. time_to_first_tokens_iter: List[float] = []
  809. time_per_output_tokens_iter: List[float] = []
  810. num_preemption_iter = (0 if scheduler_outputs is None else
  811. scheduler_outputs.preempted)
  812. # Request stats
  813. # Latency
  814. time_e2e_requests: List[float] = []
  815. # Metadata
  816. num_prompt_tokens_requests: List[int] = []
  817. num_generation_tokens_requests: List[int] = []
  818. best_of_requests: List[int] = []
  819. n_requests: List[int] = []
  820. finished_reason_requests: List[str] = []
  821. # NOTE: This loop assumes prefill seq_groups are before
  822. # decode seq_groups in scheduled_seq_groups.
  823. if scheduler_outputs is not None:
  824. num_generation_tokens_from_prefill_groups = 0.
  825. # NOTE: if scheduler_outputs.num_prefill_groups > 0 and
  826. # the len of scheduler_outputs.scheduled_seq_groups is !=
  827. # scheduler_outputs.num_prefill_groups, this means that
  828. # chunked prefills have been detected.
  829. for idx, scheduled_seq_group in enumerate(
  830. scheduler_outputs.scheduled_seq_groups):
  831. group_was_prefill = idx < scheduler_outputs.num_prefill_groups
  832. seq_group = scheduled_seq_group.seq_group
  833. # NOTE: a seq_group that completed all of its prefill tokens
  834. # in the last iteration will have seq_group.is_prefill() = False
  835. # with group_was_prefill = True
  836. if group_was_prefill:
  837. # Number of prompt tokens.
  838. num_prompt_tokens_iter += (
  839. scheduled_seq_group.token_chunk_size)
  840. # If the seq_group just finished the prefill state
  841. # get TTFT.
  842. if not seq_group.is_prefill():
  843. latency = seq_group.get_last_latency(now)
  844. time_to_first_tokens_iter.append(latency)
  845. # One generation token per finished prefill.
  846. num_generation_tokens_from_prefill_groups += (
  847. seq_group.num_seqs())
  848. else:
  849. # TPOTs.
  850. latency = seq_group.get_last_latency(now)
  851. time_per_output_tokens_iter.append(latency)
  852. # Because of chunked prefill, we can have a single sequence
  853. # group that does multiple prompt_runs. To prevent logging
  854. # the same metadata more than once per request, we standardize
  855. # on logging request level information for finished requests,
  856. # which can only happen once.
  857. if seq_group.is_finished():
  858. # Latency timings
  859. time_e2e_requests.append(now -
  860. seq_group.metrics.arrival_time)
  861. # Metadata
  862. num_prompt_tokens_requests.append(
  863. len(seq_group.prompt_token_ids))
  864. num_generation_tokens_requests.extend([
  865. seq.get_output_len()
  866. for seq in seq_group.get_finished_seqs()
  867. ])
  868. if seq_group.sampling_params is not None:
  869. best_of_requests.append(
  870. seq_group.sampling_params.best_of)
  871. n_requests.append(seq_group.sampling_params.n)
  872. finished_reason_requests.extend([
  873. SequenceStatus.get_finished_reason(seq.status)
  874. for seq in seq_group.get_finished_seqs()
  875. ])
  876. # Number of generation tokens.
  877. # num_batched_tokens equals the number of prompt_tokens plus the
  878. # number of decode_tokens in a single iteration. So,
  879. # num_generation_tokens = num_batched_tokens - num_prompt_tokens
  880. # + num_generation_tokens_from_prefill_groups (since we generate
  881. # one token on prefills on iters where the prefill finishes).
  882. num_generation_tokens_iter = (
  883. scheduler_outputs.num_batched_tokens - num_prompt_tokens_iter +
  884. num_generation_tokens_from_prefill_groups)
  885. # Spec decode, if enabled, emits specialized metrics from the worker in
  886. # sampler output.
  887. if model_output and (model_output[0].spec_decode_worker_metrics
  888. is not None):
  889. spec_decode_metrics = model_output[0].spec_decode_worker_metrics
  890. else:
  891. spec_decode_metrics = None
  892. return Stats(
  893. now=now,
  894. # System stats
  895. # Scheduler State
  896. num_running_sys=num_running_sys,
  897. num_swapped_sys=num_swapped_sys,
  898. num_waiting_sys=num_waiting_sys,
  899. # KV Cache Usage in %
  900. gpu_cache_usage_sys=gpu_cache_usage_sys,
  901. cpu_cache_usage_sys=cpu_cache_usage_sys,
  902. # Iteration stats
  903. num_prompt_tokens_iter=num_prompt_tokens_iter,
  904. num_generation_tokens_iter=num_generation_tokens_iter,
  905. time_to_first_tokens_iter=time_to_first_tokens_iter,
  906. time_per_output_tokens_iter=time_per_output_tokens_iter,
  907. spec_decode_metrics=spec_decode_metrics,
  908. num_preemption_iter=num_preemption_iter,
  909. # Request stats
  910. # Latency
  911. time_e2e_requests=time_e2e_requests,
  912. # Metadata
  913. num_prompt_tokens_requests=num_prompt_tokens_requests,
  914. num_generation_tokens_requests=num_generation_tokens_requests,
  915. best_of_requests=best_of_requests,
  916. n_requests=n_requests,
  917. finished_reason_requests=finished_reason_requests,
  918. )
  919. def add_lora(self, lora_request: LoRARequest) -> bool:
  920. return self.model_executor.add_lora(lora_request)
  921. def remove_lora(self, lora_id: int) -> bool:
  922. return self.model_executor.remove_lora(lora_id)
  923. def list_loras(self) -> List[int]:
  924. return self.model_executor.list_loras()
  925. def pin_lora(self, lora_id: int) -> bool:
  926. return self.model_executor.pin_lora(lora_id)
  927. def add_prompt_adapter(
  928. self, prompt_adapter_request: PromptAdapterRequest) -> bool:
  929. return self.model_executor.add_prompt_adapter(prompt_adapter_request)
  930. def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool:
  931. return self.model_executor.remove_prompt_adapter(prompt_adapter_id)
  932. def list_prompt_adapters(self) -> List[int]:
  933. return self.model_executor.list_prompt_adapters()
  934. def check_health(self) -> None:
  935. if self.tokenizer:
  936. self.tokenizer.check_health()
  937. self.model_executor.check_health()
  938. setup_logger()