aphrodite_engine.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  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 Tuple, Type, TypeVar, Union
  7. from loguru import logger
  8. from transformers import PreTrainedTokenizer
  9. from typing_extensions import assert_never
  10. from aphrodite.common.config import (CacheConfig, DecodingConfig, DeviceConfig,
  11. EngineConfig, LoadConfig, LoRAConfig,
  12. ModelConfig, ParallelConfig,
  13. PromptAdapterConfig, SchedulerConfig,
  14. SpeculativeConfig)
  15. from aphrodite.common.logger import setup_logger
  16. from aphrodite.common.outputs import (EmbeddingRequestOutput, RequestOutput,
  17. RequestOutputFactory)
  18. from aphrodite.common.pooling_params import PoolingParams
  19. from aphrodite.common.sampling_params import SamplingParams
  20. from aphrodite.common.sequence import (EmbeddingSequenceGroupOutput,
  21. ExecuteModelRequest, PoolerOutput,
  22. SamplerOutput, Sequence, SequenceGroup,
  23. SequenceGroupMetadata, SequenceStatus)
  24. from aphrodite.common.utils import Counter, Device
  25. from aphrodite.engine.args_tools import EngineArgs
  26. from aphrodite.engine.metrics_types import 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, EncoderDecoderLLMInputs,
  35. InputRegistry, LLMInputs, PromptInputs,
  36. SingletonPromptInputs)
  37. from aphrodite.inputs.parse import is_explicit_encoder_decoder_prompt
  38. from aphrodite.lora.request import LoRARequest
  39. from aphrodite.multimodal import MultiModalDataDict
  40. from aphrodite.processing.scheduler import (ScheduledSequenceGroup, Scheduler,
  41. SchedulerOutputs)
  42. from aphrodite.prompt_adapter.request import PromptAdapterRequest
  43. from aphrodite.transformers_utils.config import try_get_generation_config
  44. from aphrodite.transformers_utils.detokenizer import Detokenizer
  45. from aphrodite.transformers_utils.tokenizer_group import (
  46. BaseTokenizerGroup, init_tokenizer_from_configs)
  47. from aphrodite.version import __version__ as APHRODITE_VERSION
  48. _LOCAL_LOGGING_INTERVAL_SEC = 5
  49. APHRODITE_USE_RAY_SPMD_WORKER = bool(
  50. os.getenv("APHRODITE_USE_RAY_SPMD_WORKER", 0))
  51. def _load_generation_config_dict(model_config: ModelConfig) -> Dict[str, Any]:
  52. config = try_get_generation_config(
  53. model_config.model,
  54. trust_remote_code=model_config.trust_remote_code,
  55. revision=model_config.revision,
  56. )
  57. if config is None:
  58. return {}
  59. return config.to_diff_dict()
  60. _O = TypeVar("_O", RequestOutput, EmbeddingRequestOutput)
  61. PromptComponents = Tuple[Optional[str], List[int],
  62. Optional[MultiModalDataDict],
  63. Optional[None], Optional[None]]
  64. DecoderPromptComponents = Tuple[Optional[str], Optional[List[int]],
  65. Optional[MultiModalDataDict],
  66. Optional[None], Optional[None]]
  67. class AphroditeEngine:
  68. """An LLM engine that receives requests and generates texts.
  69. This is the main class for the Aphrodite engine. It receives requests
  70. from clients and generates texts from the LLM. It includes a tokenizer, a
  71. language model (possibly distributed across multiple GPUs), and GPU memory
  72. space allocated for intermediate states (aka KV cache). This class utilizes
  73. iteration-level scheduling and efficient memory management to maximize the
  74. serving throughput.
  75. The `LLM` class wraps this class for offline batched inference and the
  76. `AsyncAphrodite` class wraps this class for online serving.
  77. NOTE: The config arguments are derived from the `EngineArgs` class. For the
  78. comprehensive list of arguments, see `EngineArgs`.
  79. Args:
  80. model_config: The configuration related to the LLM model.
  81. cache_config: The configuration related to the KV cache memory
  82. management.
  83. parallel_config: The configuration related to distributed execution.
  84. scheduler_config: The configuration related to the request scheduler.
  85. device_config: The configuration related to the device.
  86. lora_config (Optional): The configuration related to serving multi-LoRA.
  87. speculative_config (Optional): The configuration related to speculative
  88. decoding.
  89. executor_class: The model executor class for managing distributed
  90. execution.
  91. prompt_adapter_config (Optional): The configuration related to serving
  92. prompt adapters.
  93. log_stats: Whether to log statistics.
  94. """
  95. DO_VALIDATE_OUTPUT: ClassVar[bool] = False
  96. """A flag to toggle whether to validate the type of request output."""
  97. @classmethod
  98. @contextmanager
  99. def enable_output_validation(cls):
  100. cls.DO_VALIDATE_OUTPUT = True
  101. yield
  102. cls.DO_VALIDATE_OUTPUT = False
  103. @classmethod
  104. def validate_output(
  105. cls,
  106. output: object,
  107. output_type: Type[_O],
  108. ) -> _O:
  109. do_validate = cls.DO_VALIDATE_OUTPUT
  110. if ((TYPE_CHECKING or do_validate)
  111. and not isinstance(output, output_type)):
  112. raise TypeError(f"Expected output of type {output_type}, "
  113. f"but found type {type(output)}")
  114. return output
  115. @classmethod
  116. def validate_outputs(
  117. cls,
  118. outputs: GenericSequence[object],
  119. output_type: Type[_O],
  120. ) -> List[_O]:
  121. do_validate = cls.DO_VALIDATE_OUTPUT
  122. outputs_: List[_O]
  123. if TYPE_CHECKING or do_validate:
  124. outputs_ = []
  125. for output in outputs:
  126. if not isinstance(output, output_type):
  127. raise TypeError(f"Expected output of type {output_type}, "
  128. f"but found type {type(output)}")
  129. outputs_.append(output)
  130. else:
  131. outputs_ = outputs
  132. return outputs_
  133. tokenizer: Optional[BaseTokenizerGroup]
  134. def __init__(
  135. self,
  136. model_config: ModelConfig,
  137. cache_config: CacheConfig,
  138. parallel_config: ParallelConfig,
  139. scheduler_config: SchedulerConfig,
  140. device_config: DeviceConfig,
  141. load_config: LoadConfig,
  142. lora_config: Optional[LoRAConfig],
  143. speculative_config: Optional[SpeculativeConfig],
  144. decoding_config: Optional[DecodingConfig],
  145. prompt_adapter_config: Optional[PromptAdapterConfig],
  146. executor_class: Type[ExecutorBase],
  147. log_stats: bool,
  148. stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,
  149. input_registry: InputRegistry = INPUT_REGISTRY,
  150. ) -> None:
  151. try:
  152. import aphrodite.commit_id
  153. commit_id = True
  154. except ImportError:
  155. commit_id = False
  156. config_dict = {
  157. "Model": model_config.model,
  158. "Speculative Config": speculative_config,
  159. "DataType": model_config.dtype,
  160. "Model Load Format": load_config.load_format,
  161. "Tensor Parallel Size": parallel_config.tensor_parallel_size,
  162. "Pipeline Parallel Size": parallel_config.pipeline_parallel_size,
  163. "Disable Custom All-Reduce":
  164. parallel_config.disable_custom_all_reduce,
  165. "Quantization Format": model_config.quantization,
  166. "Context Length": model_config.max_model_len,
  167. "Enforce Eager Mode": model_config.enforce_eager,
  168. "Prefix Caching": cache_config.enable_prefix_caching,
  169. "KV Cache DataType": cache_config.cache_dtype,
  170. "Device": device_config.device,
  171. "Rope Scaling": model_config.rope_scaling,
  172. "Guided Decoding Backend": decoding_config
  173. }
  174. logger.info("-" * 85)
  175. if not commit_id:
  176. logger.info(
  177. f"Initializing Aphrodite Engine (v{APHRODITE_VERSION}) "
  178. "with the following config:")
  179. else:
  180. logger.info(f"Initializing Aphrodite Engine (v{APHRODITE_VERSION} "
  181. f"commit {aphrodite.__short_commit__}) with the "
  182. "following config:")
  183. for key, value in config_dict.items():
  184. if value is not None and not ((key == "Model Load Format" or key ==\
  185. "KV Cache DataType") and value == \
  186. "auto"):
  187. logger.info(f"{key} = {value!r}")
  188. logger.info("-" * 85)
  189. # TODO: Print more configs in debug mode.
  190. from aphrodite.plugins import load_general_plugins
  191. load_general_plugins()
  192. self.model_config = model_config
  193. self.cache_config = cache_config
  194. self.lora_config = lora_config
  195. self.parallel_config = parallel_config
  196. self.scheduler_config = scheduler_config
  197. self.device_config = device_config
  198. self.speculative_config = speculative_config
  199. self.load_config = load_config
  200. self.decoding_config = decoding_config or DecodingConfig()
  201. self.prompt_adapter_config = prompt_adapter_config
  202. self.log_stats = log_stats
  203. if not self.model_config.skip_tokenizer_init:
  204. self.tokenizer = self._init_tokenizer()
  205. self.detokenizer = Detokenizer(self.tokenizer)
  206. tokenizer_group = self.get_tokenizer_group()
  207. else:
  208. self.tokenizer = None
  209. self.detokenizer = None
  210. tokenizer_group = None
  211. # Ensure that the function doesn't contain a reference to self,
  212. # to avoid engine GC issues
  213. def get_tokenizer_for_seq(sequence: Sequence) -> PreTrainedTokenizer:
  214. assert tokenizer_group, ("tokenizer_group cannot be None, "
  215. "make sure skip_tokenizer_init is False")
  216. return tokenizer_group.get_lora_tokenizer(sequence.lora_request)
  217. self.seq_counter = Counter()
  218. self.generation_config_fields = _load_generation_config_dict(
  219. model_config)
  220. self.input_registry = input_registry
  221. self.input_processor = input_registry.create_input_processor(
  222. model_config)
  223. self.model_executor = executor_class(
  224. model_config=model_config,
  225. cache_config=cache_config,
  226. parallel_config=parallel_config,
  227. scheduler_config=scheduler_config,
  228. device_config=device_config,
  229. lora_config=lora_config,
  230. speculative_config=speculative_config,
  231. load_config=load_config,
  232. prompt_adapter_config=prompt_adapter_config,
  233. )
  234. if not self.model_config.embedding_mode:
  235. self._initialize_kv_caches()
  236. if self.tokenizer:
  237. # Ping the tokenizer to ensure liveness if it runs in a
  238. # different process.
  239. self.tokenizer.ping()
  240. # Create the scheduler.
  241. # NOTE: the cache_config here have been updated with the numbers of
  242. # GPU and CPU blocks, which are profiled in the distributed executor.
  243. self.scheduler = [
  244. Scheduler(scheduler_config, cache_config, lora_config,
  245. parallel_config.pipeline_parallel_size)
  246. for _ in range(parallel_config.pipeline_parallel_size)
  247. ]
  248. # Metric Logging.
  249. if self.log_stats:
  250. if stat_loggers is not None:
  251. self.stat_loggers = stat_loggers
  252. else:
  253. # Lazy import for prometheus multiprocessing.
  254. # We need to set PROMETHEUS_MULTIPROC_DIR environment variable
  255. # before prometheus_client is imported.
  256. # See https://prometheus.github.io/client_python/multiprocess/
  257. from aphrodite.engine.metrics import (LoggingStatLogger,
  258. PrometheusStatLogger)
  259. self.stat_loggers = {
  260. "logging":
  261. LoggingStatLogger(
  262. local_interval=_LOCAL_LOGGING_INTERVAL_SEC),
  263. "prometheus":
  264. PrometheusStatLogger(
  265. local_interval=_LOCAL_LOGGING_INTERVAL_SEC,
  266. labels=dict(model_name=model_config.served_model_name),
  267. max_model_len=self.model_config.max_model_len),
  268. }
  269. self.stat_loggers["prometheus"].info("cache_config",
  270. self.cache_config)
  271. # Create sequence output processor, e.g. for beam search or
  272. # speculative decoding.
  273. self.output_processor = (
  274. SequenceGroupOutputProcessor.create_output_processor(
  275. self.scheduler_config,
  276. self.detokenizer,
  277. self.scheduler,
  278. self.seq_counter,
  279. get_tokenizer_for_seq,
  280. stop_checker=StopChecker(
  281. self.scheduler_config.max_model_len,
  282. get_tokenizer_for_seq,
  283. ),
  284. ))
  285. def _initialize_kv_caches(self) -> None:
  286. """Initialize the KV cache in the worker(s).
  287. The workers will determine the number of blocks in both the GPU cache
  288. and the swap CPU cache.
  289. """
  290. num_gpu_blocks, num_cpu_blocks = (
  291. self.model_executor.determine_num_available_blocks())
  292. if self.cache_config.num_gpu_blocks_override is not None:
  293. num_gpu_blocks_override = self.cache_config.num_gpu_blocks_override
  294. logger.info(f"Overriding {num_gpu_blocks=} with "
  295. f"{num_gpu_blocks_override=}")
  296. num_gpu_blocks = num_gpu_blocks_override
  297. self.cache_config.num_gpu_blocks = num_gpu_blocks
  298. self.cache_config.num_cpu_blocks = num_cpu_blocks
  299. self.model_executor.initialize_cache(num_gpu_blocks, num_cpu_blocks)
  300. @classmethod
  301. def _get_executor_cls(cls,
  302. engine_config: EngineConfig) -> Type[ExecutorBase]:
  303. distributed_executor_backend = (
  304. engine_config.parallel_config.distributed_executor_backend)
  305. # Initialize the cluster and specify the executor class.
  306. if isinstance(distributed_executor_backend, type):
  307. if not issubclass(distributed_executor_backend, ExecutorBase):
  308. raise TypeError(
  309. "distributed_executor_backend must be a subclass of "
  310. f"ExecutorBase. Got {distributed_executor_backend}.")
  311. if distributed_executor_backend.uses_ray: # type: ignore
  312. initialize_ray_cluster(engine_config.parallel_config)
  313. executor_class = distributed_executor_backend
  314. elif engine_config.device_config.device_type == "neuron":
  315. from aphrodite.executor.neuron_executor import NeuronExecutor
  316. executor_class = NeuronExecutor
  317. elif engine_config.device_config.device_type == "tpu":
  318. if distributed_executor_backend == "ray":
  319. initialize_ray_cluster(engine_config.parallel_config)
  320. from aphrodite.executor.ray_tpu_executor import RayTPUExecutor
  321. executor_class = RayTPUExecutor
  322. else:
  323. assert distributed_executor_backend is None
  324. from aphrodite.executor.tpu_executor import TPUExecutor
  325. executor_class = TPUExecutor
  326. elif engine_config.device_config.device_type == "cpu":
  327. from aphrodite.executor.cpu_executor import CPUExecutor
  328. executor_class = CPUExecutor
  329. elif engine_config.device_config.device_type == "openvino":
  330. from aphrodite.executor.openvino_executor import OpenVINOExecutor
  331. executor_class = OpenVINOExecutor
  332. elif engine_config.device_config.device_type == "xpu":
  333. if distributed_executor_backend == "ray":
  334. initialize_ray_cluster(engine_config.parallel_config)
  335. from aphrodite.executor.ray_xpu_executor import RayXPUExecutor
  336. executor_class = RayXPUExecutor
  337. else:
  338. from aphrodite.executor.xpu_executor import XPUExecutor
  339. executor_class = XPUExecutor
  340. elif distributed_executor_backend == "ray":
  341. initialize_ray_cluster(engine_config.parallel_config)
  342. from aphrodite.executor.ray_gpu_executor import RayGPUExecutor
  343. executor_class = RayGPUExecutor
  344. elif distributed_executor_backend == "mp":
  345. from aphrodite.executor.multiproc_gpu_executor import (
  346. MultiprocessingGPUExecutor)
  347. assert not APHRODITE_USE_RAY_SPMD_WORKER, (
  348. "multiprocessing distributed executor backend does not "
  349. "support APHRODITE_USE_RAY_SPMD_WORKER=1")
  350. executor_class = MultiprocessingGPUExecutor
  351. else:
  352. from aphrodite.executor.gpu_executor import GPUExecutor
  353. executor_class = GPUExecutor
  354. return executor_class
  355. @classmethod
  356. def from_engine_args(
  357. cls,
  358. engine_args: EngineArgs,
  359. stat_loggers: Optional[Dict[str, StatLoggerBase]] = None,
  360. ) -> "AphroditeEngine":
  361. """Creates an LLM engine from the engine arguments."""
  362. # Create the engine configs.
  363. engine_config = engine_args.create_engine_config()
  364. executor_class = cls._get_executor_cls(engine_config)
  365. # Create the LLM engine.
  366. engine = cls(
  367. **engine_config.to_dict(),
  368. executor_class=executor_class,
  369. log_stats=not engine_args.disable_log_stats,
  370. stat_loggers=stat_loggers,
  371. )
  372. return engine
  373. def __reduce__(self):
  374. # This is to ensure that the AphroditeEngine is not referenced in
  375. # the closure used to initialize Ray worker actors
  376. raise RuntimeError("AphroditeEngine should not be pickled!")
  377. def __del__(self):
  378. # Shutdown the model executor when engine is garbage collected.
  379. # Use getattr since __init__ can fail before the field is set
  380. if model_executor := getattr(self, "model_executor", None):
  381. model_executor.shutdown()
  382. MISSING_TOKENIZER_GROUP_MSG = ("Unable to get tokenizer because "
  383. "skip_tokenizer_init is True")
  384. def get_tokenizer_group(
  385. self,
  386. fail_msg: str = MISSING_TOKENIZER_GROUP_MSG) -> BaseTokenizerGroup:
  387. if self.tokenizer is None:
  388. raise ValueError(fail_msg)
  389. return self.tokenizer
  390. def get_tokenizer(
  391. self,
  392. lora_request: Optional[LoRARequest] = None
  393. ) -> "PreTrainedTokenizer":
  394. return self.get_tokenizer_group().get_lora_tokenizer(lora_request)
  395. def _init_tokenizer(self) -> BaseTokenizerGroup:
  396. return init_tokenizer_from_configs(
  397. model_config=self.model_config,
  398. scheduler_config=self.scheduler_config,
  399. parallel_config=self.parallel_config,
  400. enable_lora=bool(self.lora_config))
  401. def _verify_args(self) -> None:
  402. self.model_config.verify_with_parallel_config(self.parallel_config)
  403. self.cache_config.verify_with_parallel_config(self.parallel_config)
  404. if self.lora_config:
  405. self.lora_config.verify_with_model_config(self.model_config)
  406. self.lora_config.verify_with_scheduler_config(
  407. self.scheduler_config)
  408. if self.prompt_adapter_config:
  409. self.prompt_adapter_config.verify_with_model_config(
  410. self.model_config)
  411. def _get_bos_token_id(self,
  412. lora_request: Optional[LoRARequest] = None
  413. ) -> Optional[int]:
  414. if self.tokenizer is None:
  415. logger.warning("Using None for BOS token id because tokenizer "
  416. "is not initialized")
  417. return None
  418. return self.tokenizer.get_lora_tokenizer(lora_request).bos_token_id
  419. def _get_eos_token_id(self,
  420. lora_request: Optional[LoRARequest] = None
  421. ) -> Optional[int]:
  422. if self.tokenizer is None:
  423. logger.warning("Using None for EOS token id because tokenizer "
  424. "is not initialized")
  425. return None
  426. return self.tokenizer.get_lora_tokenizer(lora_request).eos_token_id
  427. def _get_decoder_start_token_id(self) -> Optional[int]:
  428. '''
  429. Obtain the decoder start token id employed by an encoder/decoder
  430. model. Returns None for non-encoder/decoder models or if the
  431. model config is unavailable.
  432. '''
  433. if not self.is_encoder_decoder_model():
  434. logger.warning("Using None for decoder start token id because "
  435. "this is not an encoder/decoder model.")
  436. return None
  437. if (self.model_config is None or self.model_config.hf_config is None):
  438. logger.warning("Using None for decoder start token id because "
  439. "model config is not available.")
  440. return None
  441. dec_start_token_id = getattr(self.model_config.hf_config,
  442. 'decoder_start_token_id', None)
  443. if dec_start_token_id is None:
  444. logger.warning("Falling back on <BOS> for decoder start token id "
  445. "because decoder start token id is not available.")
  446. dec_start_token_id = self._get_bos_token_id()
  447. return dec_start_token_id
  448. def _add_processed_request(
  449. self,
  450. request_id: str,
  451. processed_inputs: Union[LLMInputs, EncoderDecoderLLMInputs],
  452. params: Union[SamplingParams, PoolingParams],
  453. arrival_time: float,
  454. lora_request: Optional[LoRARequest],
  455. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  456. ) -> None:
  457. # Create the sequences.
  458. block_size = self.cache_config.block_size
  459. seq_id = next(self.seq_counter)
  460. eos_token_id = self._get_eos_token_id(lora_request)
  461. seq = Sequence(seq_id, processed_inputs, block_size, eos_token_id,
  462. lora_request, prompt_adapter_request)
  463. negative_seq = None
  464. if processed_inputs["negative_prompt_token_ids"]:
  465. negative_seq = Sequence(seq_id,
  466. processed_inputs,
  467. block_size,
  468. eos_token_id,
  469. lora_request,
  470. prompt_adapter_request,
  471. from_negative_prompt=True)
  472. encoder_seq = None
  473. if 'encoder_prompt_token_ids' in processed_inputs:
  474. encoder_seq = Sequence(seq_id,
  475. processed_inputs,
  476. block_size,
  477. eos_token_id,
  478. lora_request,
  479. prompt_adapter_request,
  480. from_decoder_prompt=False)
  481. # Create a SequenceGroup based on SamplingParams or PoolingParams
  482. if isinstance(params, SamplingParams):
  483. seq_group = self._create_sequence_group_with_sampling(
  484. request_id,
  485. seq,
  486. params,
  487. arrival_time=arrival_time,
  488. lora_request=lora_request,
  489. prompt_adapter_request=prompt_adapter_request,
  490. encoder_seq=encoder_seq,
  491. negative_seq=negative_seq,
  492. )
  493. elif isinstance(params, PoolingParams):
  494. seq_group = self._create_sequence_group_with_pooling(
  495. request_id,
  496. seq,
  497. params,
  498. arrival_time=arrival_time,
  499. lora_request=lora_request,
  500. prompt_adapter_request=prompt_adapter_request,
  501. encoder_seq=encoder_seq,
  502. )
  503. else:
  504. raise ValueError(
  505. "Either SamplingParams or PoolingParams must be provided.")
  506. # Add the sequence group to the scheduler with least unfinished seqs.
  507. costs = [
  508. scheduler.get_num_unfinished_seq_groups()
  509. for scheduler in self.scheduler
  510. ]
  511. min_cost_scheduler = self.scheduler[costs.index(min(costs))]
  512. min_cost_scheduler.add_seq_group(seq_group)
  513. def stop_remote_worker_execution_loop(self) -> None:
  514. self.model_executor.stop_remote_worker_execution_loop()
  515. _LLMInputComponentsType = Tuple[str, List[int]]
  516. def _prepare_decoder_input_ids_for_generation(
  517. self,
  518. decoder_input_ids: Optional[List[int]],
  519. ) -> List[int]:
  520. """
  521. Prepares `decoder_input_ids` for generation with encoder-decoder models.
  522. Based on
  523. https://github.com/huggingface/transformers/blob/
  524. 4037a2b5b1278736e566aec12e169100275545ea/
  525. src/transformers/generation/utils.py
  526. specifically GenerationMixin._prepare_decoder_input_ids_for_generation()
  527. Arguments:
  528. * decoder_input_ids: input token ids to preprocess
  529. Returns:
  530. * Processed token list
  531. """
  532. decoder_start_token_id = self._get_decoder_start_token_id()
  533. assert decoder_start_token_id is not None
  534. if decoder_input_ids is None:
  535. # no decoder prompt input ->
  536. # use decoder_start_token_id as decoder_input_ids
  537. decoder_input_ids = self._get_default_enc_dec_decoder_prompt()
  538. if (len(decoder_input_ids) == 0
  539. or decoder_input_ids[0] != decoder_start_token_id):
  540. decoder_input_ids = [decoder_start_token_id] + decoder_input_ids
  541. return decoder_input_ids
  542. def _tokenize_prompt(
  543. self,
  544. prompt: str,
  545. request_id: str,
  546. lora_request: Optional[LoRARequest],
  547. ) -> List[int]:
  548. '''
  549. Wrapper around application of the model's tokenizer.
  550. Arguments:
  551. * prompt
  552. * request_id
  553. * lora_request
  554. Returns:
  555. * prompt token ids
  556. '''
  557. tokenizer = self.get_tokenizer_group("prompts must be None if "
  558. "skip_tokenizer_init is True")
  559. return tokenizer.encode(request_id=request_id,
  560. prompt=prompt,
  561. lora_request=lora_request)
  562. def _extract_prompt_components(
  563. self,
  564. inputs: SingletonPromptInputs,
  565. request_id: str,
  566. lora_request: Optional[LoRARequest] = None,
  567. ) -> PromptComponents:
  568. '''
  569. Extract the components of any single encoder or decoder input prompt.
  570. Arguments:
  571. * request_id
  572. * inputs: single encoder or decoder input prompt
  573. * lora_request: this is only valid for decoder prompts
  574. Returns:
  575. * prompt
  576. * prompt_token_ids
  577. * multi_modal_data
  578. '''
  579. if isinstance(inputs, str):
  580. prompt = inputs
  581. prompt_token_ids = self._tokenize_prompt(
  582. prompt,
  583. request_id=request_id,
  584. lora_request=lora_request,
  585. )
  586. multi_modal_data = None
  587. negative_prompt = negative_prompt_token_ids = None
  588. elif isinstance(inputs, dict):
  589. if "prompt_token_ids" in inputs:
  590. prompt = None
  591. prompt_token_ids = inputs["prompt_token_ids"]
  592. else:
  593. # NOTE: This extra assignment is required to pass mypy
  594. prompt = parsed_prompt = inputs["prompt"]
  595. prompt_token_ids = self._tokenize_prompt(
  596. parsed_prompt,
  597. request_id=request_id,
  598. lora_request=lora_request,
  599. )
  600. if "negative_prompt_token_ids" in inputs:
  601. negative_prompt = None
  602. negative_prompt_token_ids = inputs["negative_prompt_token_ids"]
  603. elif "negative_prompt" in inputs:
  604. negative_prompt = parsed_negative_prompt = inputs[
  605. "negative_prompt"]
  606. negative_prompt_token_ids = self._tokenize_prompt(
  607. parsed_negative_prompt,
  608. request_id=request_id,
  609. lora_request=lora_request,
  610. )
  611. else:
  612. negative_prompt = None
  613. negative_prompt_token_ids = None
  614. multi_modal_data = inputs.get("multi_modal_data")
  615. else:
  616. assert_never(inputs)
  617. return (prompt, prompt_token_ids, multi_modal_data,
  618. negative_prompt, negative_prompt_token_ids)
  619. def _apply_prompt_adapter(
  620. self,
  621. prompt_token_ids: List[int],
  622. prompt_adapter_request: Optional[PromptAdapterRequest],
  623. ) -> List[int]:
  624. if prompt_adapter_request:
  625. prompt_token_ids = (
  626. [0] * prompt_adapter_request.prompt_adapter_num_virtual_tokens
  627. + prompt_token_ids)
  628. return prompt_token_ids
  629. def _get_default_enc_dec_decoder_prompt(self) -> List[int]:
  630. '''
  631. Specifically for encoder/decoder models:
  632. generate a default decoder prompt for when
  633. the user specifies only the encoder prompt.
  634. Encoder/decoder models utilize the decoder
  635. prompt in different ways; as new models are
  636. added, it is intended that this function
  637. will be extended to produce differing
  638. default decoder prompts, depending on the
  639. model variety.
  640. Absent a special case, the default behavior
  641. of this method is to mirror the behavior of
  642. the HuggingFace (HF) GenerationMixin for a None
  643. decoder prompt, which is to employ a logit processor
  644. setting to force the first decoded token to be <BOS>.
  645. Here, this behavior is approximated by having the
  646. "default" decoder prompt be <BOS>.
  647. However, it is possible that in the future
  648. other models may have different or more
  649. complex logic for the default decoder prompt.
  650. This motivates having a special helper method
  651. for default decoder prompts.
  652. Returns:
  653. * prompt_token_ids
  654. '''
  655. bos_token_id = self._get_bos_token_id()
  656. assert bos_token_id is not None
  657. return [bos_token_id]
  658. def _build_enc_dec_llm_inputs(
  659. self,
  660. encoder_comps: PromptComponents,
  661. decoder_comps: DecoderPromptComponents,
  662. ) -> EncoderDecoderLLMInputs:
  663. encoder_prompt, encoder_prompt_ids, encoder_mm_data, \
  664. encoder_negative_prompt, encoder_negative_prompt_ids = encoder_comps
  665. decoder_prompt, decoder_prompt_ids, decoder_mm_data, \
  666. decoder_negative_prompt, decoder_negative_prompt_ids= decoder_comps
  667. if encoder_mm_data is not None or decoder_mm_data is not None:
  668. raise ValueError("Multi-modal encoder-decoder models are "
  669. "not supported yet")
  670. decoder_prompt_ids = (
  671. self._prepare_decoder_input_ids_for_generation(decoder_prompt_ids))
  672. decoder_negative_prompt_ids = (
  673. self._prepare_decoder_input_ids_for_generation(decoder_negative_prompt_ids))
  674. return EncoderDecoderLLMInputs(
  675. prompt_token_ids=decoder_prompt_ids,
  676. prompt=decoder_prompt,
  677. negative_prompt_token_ids=decoder_negative_prompt_ids,
  678. negative_prompt=decoder_negative_prompt,
  679. encoder_prompt_token_ids=encoder_prompt_ids,
  680. encoder_prompt=encoder_prompt,
  681. encoder_negative_prompt_token_ids=encoder_negative_prompt_ids,
  682. encoder_negative_prompt=encoder_negative_prompt,
  683. )
  684. def _process_encoder_decoder_prompt(
  685. self,
  686. inputs: PromptInputs,
  687. request_id: str,
  688. ) -> EncoderDecoderLLMInputs:
  689. '''
  690. For encoder/decoder models only:
  691. Process an input prompt into an
  692. :class:`EncoderDecoderLLMInputs` instance.
  693. There are two types of input prompts:
  694. singleton prompts which carry only the
  695. encoder prompt, and explicit encoder/decoder
  696. prompts which carry both the encoder and the
  697. decoder prompts as member variables.
  698. This function handles the following scenarios:
  699. * Singleton encoder prompt: extract encoder prompt
  700. token ids & infer default decoder prompt token ids
  701. * Explicit encoder/decoder prompt: extract encoder
  702. and decoder prompt token ids
  703. Note that for Explicit encoder/decoder prompts,
  704. each sub-prompt (encoder or decoder prompt) can
  705. have any possible singleton type; thus this
  706. method relies on helper functions to obtain
  707. token ids for the sub-prompts.
  708. Arguments:
  709. * inputs: an input prompt
  710. * request_id
  711. Returns:
  712. * :class:`EncoderDecoderLLMInputs` instance
  713. '''
  714. encoder_comps: PromptComponents
  715. decoder_comps: DecoderPromptComponents
  716. if is_explicit_encoder_decoder_prompt(inputs):
  717. encoder_comps = self._extract_prompt_components(
  718. inputs["encoder_prompt"],
  719. request_id=request_id,
  720. )
  721. if (decoder_input := inputs["decoder_prompt"]) is None:
  722. decoder_comps = None, None, None, None, None
  723. else:
  724. decoder_comps = self._extract_prompt_components(
  725. decoder_input,
  726. request_id=request_id,
  727. )
  728. else:
  729. encoder_comps = self._extract_prompt_components(
  730. inputs,
  731. request_id=request_id,
  732. )
  733. decoder_comps = None, None, None, None, None
  734. return self._build_enc_dec_llm_inputs(encoder_comps, decoder_comps)
  735. def _build_decoder_only_llm_inputs(
  736. self,
  737. prompt_comps: PromptComponents,
  738. prompt_adapter_request: Optional[PromptAdapterRequest],
  739. ) -> LLMInputs:
  740. prompt, prompt_token_ids, multi_modal_data, \
  741. negative_prompt, negative_prompt_token_ids = prompt_comps
  742. prompt_token_ids = self._apply_prompt_adapter(
  743. prompt_token_ids, prompt_adapter_request=prompt_adapter_request)
  744. return LLMInputs(prompt_token_ids=prompt_token_ids,
  745. prompt=prompt,
  746. multi_modal_data=multi_modal_data,
  747. negative_prompt_token_ids=negative_prompt_token_ids,
  748. negative_prompt=negative_prompt)
  749. def _process_decoder_only_prompt(
  750. self,
  751. inputs: SingletonPromptInputs,
  752. request_id: str,
  753. lora_request: Optional[LoRARequest] = None,
  754. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  755. ) -> LLMInputs:
  756. '''
  757. For decoder-only models:
  758. Process an input prompt into an :class:`LLMInputs` instance.
  759. Arguments:
  760. * inputs: input prompt
  761. * request_id
  762. * lora_request
  763. * prompt_adapter_request
  764. Returns:
  765. * :class:`LLMInputs` instance
  766. '''
  767. prompt_comps = self._extract_prompt_components(
  768. inputs,
  769. request_id=request_id,
  770. lora_request=lora_request,
  771. )
  772. return self._build_decoder_only_llm_inputs(
  773. prompt_comps,
  774. prompt_adapter_request=prompt_adapter_request,
  775. )
  776. def process_model_inputs(
  777. self,
  778. inputs: PromptInputs,
  779. request_id: str,
  780. lora_request: Optional[LoRARequest] = None,
  781. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  782. ) -> Union[LLMInputs, EncoderDecoderLLMInputs]:
  783. if self.is_encoder_decoder_model():
  784. # Encoder-decoder model requires special mapping of
  785. # input prompts to encoder & decoder
  786. model_inputs = self._process_encoder_decoder_prompt(
  787. inputs,
  788. request_id=request_id,
  789. )
  790. else:
  791. if is_explicit_encoder_decoder_prompt(inputs):
  792. raise ValueError("Cannot pass encoder-decoder prompt "
  793. "to decoder-only models")
  794. # Decoder-only operation
  795. model_inputs = self._process_decoder_only_prompt(
  796. inputs,
  797. request_id=request_id,
  798. lora_request=lora_request,
  799. prompt_adapter_request=prompt_adapter_request,
  800. )
  801. return self.input_processor(model_inputs)
  802. def add_request(
  803. self,
  804. request_id: str,
  805. inputs: PromptInputs,
  806. params: Union[SamplingParams, PoolingParams],
  807. arrival_time: Optional[float] = None,
  808. lora_request: Optional[LoRARequest] = None,
  809. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  810. ) -> None:
  811. """Add a request to the engine's request pool.
  812. The request is added to the request pool and will be processed by the
  813. scheduler as `engine.step()` is called. The exact scheduling policy is
  814. determined by the scheduler.
  815. Args:
  816. request_id: The unique ID of the request.
  817. prompt: The prompt string. Can be None if prompt_token_ids is
  818. provided.
  819. params: Parameters for sampling or pooling. SamplingParams
  820. for text generation. PoolingParams for pooling.
  821. prompt_token_ids: The token IDs of the prompt. If None, we
  822. use the tokenizer to convert the prompts to token IDs.
  823. arrival_time: The arrival time of the request. If None, we use
  824. the current monotonic time.
  825. multi_modal_data: Multi modal data per request.
  826. Details:
  827. - Set arrival_time to the current time if it is None.
  828. - Set prompt_token_ids to the encoded prompt if it is None.
  829. - Create `best_of` number of :class:`~aphrodite.common.sequence`
  830. objects.
  831. - Create a :class:`~aphrodite.common.sequenceGroup` object
  832. from the list of :class:`~aphrodite.common.sequence`.
  833. - Add the :class:`~aphrodite.common.sequenceGroup` object to the
  834. scheduler.
  835. Example:
  836. >>> # initialize engine
  837. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  838. >>> # set request arguments
  839. >>> example_prompt = "Who is the president of the United States?"
  840. >>> sampling_params = SamplingParams(temperature=0.0)
  841. >>> request_id = 0
  842. >>>
  843. >>> # add the request to the engine
  844. >>> engine.add_request(
  845. >>> str(request_id),
  846. >>> example_prompt,
  847. >>> SamplingParams(temperature=0.0))
  848. >>> # continue the request processing
  849. >>> ...
  850. """
  851. if lora_request is not None and not self.lora_config:
  852. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  853. "not enabled!")
  854. if arrival_time is None:
  855. arrival_time = time.time()
  856. processed_inputs = self.process_model_inputs(
  857. inputs,
  858. request_id=request_id,
  859. lora_request=lora_request,
  860. prompt_adapter_request=prompt_adapter_request,
  861. )
  862. self._add_processed_request(
  863. request_id=request_id,
  864. processed_inputs=processed_inputs,
  865. params=params,
  866. arrival_time=arrival_time,
  867. lora_request=lora_request,
  868. prompt_adapter_request=prompt_adapter_request,
  869. )
  870. def _create_sequence_group_with_sampling(
  871. self,
  872. request_id: str,
  873. seq: Sequence,
  874. sampling_params: SamplingParams,
  875. arrival_time: float,
  876. lora_request: Optional[LoRARequest],
  877. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  878. encoder_seq: Optional[Sequence] = None,
  879. negative_seq: Optional[Sequence] = None,
  880. ) -> SequenceGroup:
  881. """Creates a SequenceGroup with SamplingParams."""
  882. max_logprobs = self.get_model_config().max_logprobs
  883. if (sampling_params.logprobs
  884. and sampling_params.logprobs > max_logprobs) or (
  885. sampling_params.prompt_logprobs
  886. and sampling_params.prompt_logprobs > max_logprobs):
  887. raise ValueError(f"Cannot request more than "
  888. f"{max_logprobs} logprobs.")
  889. # Defensive copy of SamplingParams, which are used by the sampler,
  890. # this doesn't deep-copy LogitsProcessor objects
  891. sampling_params = sampling_params.clone()
  892. sampling_params.update_from_generation_config(
  893. self.generation_config_fields, seq.eos_token_id)
  894. # Create the sequence group.
  895. seq_group = SequenceGroup(
  896. request_id=request_id,
  897. seqs=[seq],
  898. arrival_time=arrival_time,
  899. sampling_params=sampling_params,
  900. lora_request=lora_request,
  901. prompt_adapter_request=prompt_adapter_request,
  902. encoder_seq=encoder_seq,
  903. negative_seqs=[negative_seq] if negative_seq else None)
  904. return seq_group
  905. def _create_sequence_group_with_pooling(
  906. self,
  907. request_id: str,
  908. seq: Sequence,
  909. pooling_params: PoolingParams,
  910. arrival_time: float,
  911. lora_request: Optional[LoRARequest],
  912. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  913. encoder_seq: Optional[Sequence] = None,
  914. ) -> SequenceGroup:
  915. """Creates a SequenceGroup with PoolingParams."""
  916. # Defensive copy of PoolingParams, which are used by the pooler
  917. pooling_params = pooling_params.clone()
  918. # Create the sequence group.
  919. seq_group = SequenceGroup(
  920. request_id=request_id,
  921. seqs=[seq],
  922. arrival_time=arrival_time,
  923. lora_request=lora_request,
  924. pooling_params=pooling_params,
  925. prompt_adapter_request=prompt_adapter_request,
  926. encoder_seq=encoder_seq)
  927. return seq_group
  928. def abort_request(self, request_id: Union[str, Iterable[str]]) -> None:
  929. """Aborts a request(s) with the given ID.
  930. Args:
  931. request_id: The ID(s) of the request to abort.
  932. Details:
  933. - Refer to the
  934. :meth:`~aphrodite.processing.scheduler.Scheduler.abort_seq_group`
  935. from class :class:`~aphrodite.processing.scheduler.Scheduler`.
  936. Example:
  937. >>> # initialize engine and add a request with request_id
  938. >>> request_id = str(0)
  939. >>> # abort the request
  940. >>> engine.abort_request(request_id)
  941. """
  942. for scheduler in self.scheduler:
  943. scheduler.abort_seq_group(request_id)
  944. def get_model_config(self) -> ModelConfig:
  945. """Gets the model configuration."""
  946. return self.model_config
  947. def get_parallel_config(self) -> ParallelConfig:
  948. """Gets the parallel configuration."""
  949. return self.parallel_config
  950. def get_decoding_config(self) -> DecodingConfig:
  951. """Gets the decoding configuration."""
  952. return self.decoding_config
  953. def get_scheduler_config(self) -> SchedulerConfig:
  954. """Gets the scheduler configuration."""
  955. return self.scheduler_config
  956. def get_lora_config(self) -> LoRAConfig:
  957. """Gets the LoRA configuration."""
  958. return self.lora_config
  959. def get_num_unfinished_requests(self) -> int:
  960. """Gets the number of unfinished requests."""
  961. return sum(scheduler.get_num_unfinished_seq_groups()
  962. for scheduler in self.scheduler)
  963. def has_unfinished_requests(self) -> bool:
  964. """Returns True if there are unfinished requests."""
  965. return any(scheduler.has_unfinished_seqs()
  966. for scheduler in self.scheduler)
  967. def has_unfinished_requests_for_virtual_engine(
  968. self, virtual_engine: int) -> bool:
  969. """
  970. Returns True if there are unfinished requests for the virtual engine.
  971. """
  972. return self.scheduler[virtual_engine].has_unfinished_seqs()
  973. def _process_sequence_group_outputs(
  974. self,
  975. seq_group: SequenceGroup,
  976. outputs: List[EmbeddingSequenceGroupOutput],
  977. ) -> None:
  978. seq_group.embeddings = outputs[0].embeddings
  979. for seq in seq_group.get_seqs():
  980. seq.status = SequenceStatus.FINISHED_STOPPED
  981. return
  982. def _process_model_outputs(
  983. self,
  984. output: GenericSequence[Union[SamplerOutput, PoolerOutput]],
  985. scheduled_seq_groups: List[ScheduledSequenceGroup],
  986. ignored_seq_groups: List[SequenceGroup],
  987. seq_group_metadata_list: List[SequenceGroupMetadata],
  988. ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  989. """Apply the model output to the sequences in the scheduled seq groups.
  990. Returns RequestOutputs that can be returned to the client.
  991. """
  992. now = time.time()
  993. # Organize outputs by [sequence group][step] instead of
  994. # [step][sequence group].
  995. output_by_sequence_group = create_output_by_sequence_group(
  996. output, num_seq_groups=len(scheduled_seq_groups))
  997. # Update the scheduled sequence groups with the model outputs.
  998. for scheduled_seq_group, outputs, seq_group_meta in zip(
  999. scheduled_seq_groups, output_by_sequence_group,
  1000. seq_group_metadata_list):
  1001. seq_group = scheduled_seq_group.seq_group
  1002. seq_group.update_num_computed_tokens(
  1003. scheduled_seq_group.token_chunk_size)
  1004. if seq_group.has_negative_seqs():
  1005. seq_group.update_negative_num_computed_tokens(
  1006. scheduled_seq_group.negative_token_chunk_size
  1007. )
  1008. if self.model_config.embedding_mode:
  1009. self._process_sequence_group_outputs(seq_group, outputs)
  1010. continue
  1011. self.output_processor.process_prompt_logprob(seq_group, outputs)
  1012. if seq_group_meta.do_sample:
  1013. self.output_processor.process_outputs(seq_group, outputs)
  1014. # Free the finished sequence groups.
  1015. for scheduler in self.scheduler:
  1016. scheduler.free_finished_seq_groups()
  1017. # Create the outputs.
  1018. request_outputs: List[Union[RequestOutput,
  1019. EmbeddingRequestOutput]] = []
  1020. for scheduled_seq_group in scheduled_seq_groups:
  1021. seq_group = scheduled_seq_group.seq_group
  1022. seq_group.maybe_set_first_token_time(now)
  1023. request_output = RequestOutputFactory.create(seq_group)
  1024. request_outputs.append(request_output)
  1025. for seq_group in ignored_seq_groups:
  1026. request_output = RequestOutputFactory.create(seq_group)
  1027. request_outputs.append(request_output)
  1028. return request_outputs
  1029. def step(self) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
  1030. """Performs one decoding iteration and returns newly generated results.
  1031. .. figure:: https://i.imgur.com/sv2HssD.png
  1032. :alt: Overview of the step function
  1033. :align: center
  1034. Overview of the step function.
  1035. Details:
  1036. - Step 1: Schedules the sequences to be executed in the next
  1037. iteration and the token blocks to be swapped in/out/copy.
  1038. - Depending on the scheduling policy,
  1039. sequences may be `preempted/reordered`.
  1040. - A Sequence Group (SG) refer to a group of sequences
  1041. that are generated from the same prompt.
  1042. - Step 2: Calls the distributed executor to execute the model.
  1043. - Step 3: Processes the model output. This mainly includes:
  1044. - Decodes the relevant outputs.
  1045. - Updates the scheduled sequence groups with model outputs
  1046. based on its `sampling parameters` (`use_beam_search` or not).
  1047. - Frees the finished sequence groups.
  1048. - Finally, it creates and returns the newly generated results.
  1049. Example:
  1050. >>> # Please see the example/ folder for more detailed examples.
  1051. >>>
  1052. >>> # initialize engine and request arguments
  1053. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  1054. >>> example_inputs = [(0, "What is LLM?",
  1055. >>> SamplingParams(temperature=0.0))]
  1056. >>>
  1057. >>> # Start the engine with an event loop
  1058. >>> while True:
  1059. >>> if example_inputs:
  1060. >>> req_id, prompt, sampling_params = example_inputs.pop(0)
  1061. >>> engine.add_request(str(req_id), prompt, sampling_params)
  1062. >>>
  1063. >>> # continue the request processing
  1064. >>> request_outputs = engine.step()
  1065. >>> for request_output in request_outputs:
  1066. >>> if request_output.finished:
  1067. >>> # return or show the request output
  1068. >>>
  1069. >>> if not (engine.has_unfinished_requests() or example_inputs):
  1070. >>> break
  1071. """
  1072. if self.parallel_config.pipeline_parallel_size > 1:
  1073. raise NotImplementedError(
  1074. "Pipeline parallelism is only supported through AsyncAphrodite "
  1075. "as performance will be severely degraded otherwise.")
  1076. seq_group_metadata_list, scheduler_outputs = self.scheduler[
  1077. 0].schedule()
  1078. if not scheduler_outputs.is_empty():
  1079. finished_requests_ids = self.scheduler[
  1080. 0].get_and_reset_finished_requests_ids()
  1081. execute_model_req = ExecuteModelRequest(
  1082. seq_group_metadata_list=seq_group_metadata_list,
  1083. blocks_to_swap_in=scheduler_outputs.blocks_to_swap_in,
  1084. blocks_to_swap_out=scheduler_outputs.blocks_to_swap_out,
  1085. blocks_to_copy=scheduler_outputs.blocks_to_copy,
  1086. num_lookahead_slots=scheduler_outputs.num_lookahead_slots,
  1087. running_queue_size=scheduler_outputs.running_queue_size,
  1088. finished_requests_ids=finished_requests_ids,
  1089. )
  1090. output = self.model_executor.execute_model(
  1091. execute_model_req=execute_model_req)
  1092. else:
  1093. output = []
  1094. request_outputs = self._process_model_outputs(
  1095. output, scheduler_outputs.scheduled_seq_groups,
  1096. scheduler_outputs.ignored_seq_groups, seq_group_metadata_list)
  1097. # Log stats.
  1098. self.do_log_stats(scheduler_outputs, output)
  1099. if not self.has_unfinished_requests():
  1100. # Stop the execute model loop in parallel workers until there are
  1101. # more requests to process. This avoids waiting indefinitely in
  1102. # torch.distributed ops which may otherwise timeout, and unblocks
  1103. # the RPC thread in the workers so that they can process any other
  1104. # queued control plane messages, such as add/remove lora adapters.
  1105. self.model_executor.stop_remote_worker_execution_loop()
  1106. return request_outputs
  1107. def add_logger(self, logger_name: str, logger: StatLoggerBase) -> None:
  1108. if logger_name in self.stat_loggers:
  1109. raise KeyError(f"Logger with name {logger_name} already exists.")
  1110. self.stat_loggers[logger_name] = logger
  1111. def remove_logger(self, logger_name: str) -> None:
  1112. if logger_name not in self.stat_loggers:
  1113. raise KeyError(f"Logger with name {logger_name} does not exist.")
  1114. del self.stat_loggers[logger_name]
  1115. def do_log_stats(
  1116. self,
  1117. scheduler_outputs: Optional[SchedulerOutputs] = None,
  1118. model_output: Optional[List[SamplerOutput]] = None) -> None:
  1119. """Forced log when no requests active."""
  1120. if self.log_stats:
  1121. stats = self._get_stats(scheduler_outputs, model_output)
  1122. for loggers in self.stat_loggers.values():
  1123. loggers.log(stats)
  1124. def _get_stats(
  1125. self,
  1126. scheduler_outputs: Optional[SchedulerOutputs],
  1127. model_output: Optional[List[SamplerOutput]] = None) -> Stats:
  1128. """Get Stats to be Logged to Prometheus.
  1129. Args:
  1130. scheduler_outputs: Optional, used to populate metrics related to
  1131. the scheduled batch,
  1132. model_output: Optional, used to emit speculative decoding metrics
  1133. which are created by the workers.
  1134. """
  1135. now = time.time()
  1136. # System State
  1137. # Scheduler State
  1138. num_running_sys = sum(
  1139. len(scheduler.running) for scheduler in self.scheduler)
  1140. num_swapped_sys = sum(
  1141. len(scheduler.swapped) for scheduler in self.scheduler)
  1142. num_waiting_sys = sum(
  1143. len(scheduler.waiting) for scheduler in self.scheduler)
  1144. # KV Cache Usage in %
  1145. num_total_gpu = self.cache_config.num_gpu_blocks
  1146. gpu_cache_usage_sys = 0.
  1147. if num_total_gpu is not None:
  1148. num_free_gpu = sum(
  1149. scheduler.block_manager.get_num_free_gpu_blocks()
  1150. for scheduler in self.scheduler)
  1151. if not self.model_config.is_attention_free():
  1152. gpu_cache_usage_sys = 1.0 - (num_free_gpu / num_total_gpu)
  1153. else:
  1154. gpu_cache_usage_sys = 0.0
  1155. num_total_cpu = self.cache_config.num_cpu_blocks
  1156. cpu_cache_usage_sys = 0.
  1157. if num_total_cpu is not None and num_total_cpu > 0:
  1158. num_free_cpu = sum(
  1159. scheduler.block_manager.get_num_free_cpu_blocks()
  1160. for scheduler in self.scheduler)
  1161. if not self.model_config.is_attention_free():
  1162. cpu_cache_usage_sys = 1.0 - (num_free_cpu / num_total_cpu)
  1163. else:
  1164. cpu_cache_usage_sys = 0.0
  1165. # Prefix Cache Hit Rate. Note that we always use
  1166. # the cache hit rate of the first virtual engine.
  1167. cpu_prefix_cache_hit_rate = self.scheduler[
  1168. 0].get_prefix_cache_hit_rate(Device.CPU)
  1169. gpu_prefix_cache_hit_rate = self.scheduler[
  1170. 0].get_prefix_cache_hit_rate(Device.GPU)
  1171. # Iteration stats
  1172. num_prompt_tokens_iter = 0
  1173. num_generation_tokens_iter = 0
  1174. time_to_first_tokens_iter: List[float] = []
  1175. time_per_output_tokens_iter: List[float] = []
  1176. num_preemption_iter = (0 if scheduler_outputs is None else
  1177. scheduler_outputs.preempted)
  1178. # Request stats
  1179. # Latency
  1180. time_e2e_requests: List[float] = []
  1181. # Metadata
  1182. num_prompt_tokens_requests: List[int] = []
  1183. num_generation_tokens_requests: List[int] = []
  1184. best_of_requests: List[int] = []
  1185. n_requests: List[int] = []
  1186. finished_reason_requests: List[str] = []
  1187. # NOTE: This loop assumes prefill seq_groups are before
  1188. # decode seq_groups in scheduled_seq_groups.
  1189. if scheduler_outputs is not None:
  1190. num_generation_tokens_from_prefill_groups = 0.
  1191. # NOTE: if scheduler_outputs.num_prefill_groups > 0 and
  1192. # the len of scheduler_outputs.scheduled_seq_groups is !=
  1193. # scheduler_outputs.num_prefill_groups, this means that
  1194. # chunked prefills have been detected.
  1195. for idx, scheduled_seq_group in enumerate(
  1196. scheduler_outputs.scheduled_seq_groups):
  1197. group_was_prefill = idx < scheduler_outputs.num_prefill_groups
  1198. seq_group = scheduled_seq_group.seq_group
  1199. # NOTE: a seq_group that completed all of its prefill tokens
  1200. # in the last iteration will have seq_group.is_prefill() = False
  1201. # with group_was_prefill = True
  1202. if group_was_prefill:
  1203. # Number of prompt tokens.
  1204. num_prompt_tokens_iter += (
  1205. scheduled_seq_group.token_chunk_size)
  1206. # If the seq_group just finished the prefill state
  1207. # get TTFT.
  1208. if not seq_group.is_prefill():
  1209. latency = seq_group.get_last_latency(now)
  1210. time_to_first_tokens_iter.append(latency)
  1211. # One generation token per finished prefill.
  1212. num_generation_tokens_from_prefill_groups += (
  1213. seq_group.num_seqs())
  1214. else:
  1215. # TPOTs.
  1216. latency = seq_group.get_last_latency(now)
  1217. time_per_output_tokens_iter.append(latency)
  1218. # Because of chunked prefill, we can have a single sequence
  1219. # group that does multiple prompt_runs. To prevent logging
  1220. # the same metadata more than once per request, we standardize
  1221. # on logging request level information for finished requests,
  1222. # which can only happen once.
  1223. if seq_group.is_finished():
  1224. # Latency timings
  1225. time_e2e_requests.append(now -
  1226. seq_group.metrics.arrival_time)
  1227. # Metadata
  1228. num_prompt_tokens_requests.append(
  1229. len(seq_group.prompt_token_ids))
  1230. num_generation_tokens_requests.extend([
  1231. seq.get_output_len()
  1232. for seq in seq_group.get_finished_seqs()
  1233. ])
  1234. if seq_group.sampling_params is not None:
  1235. best_of_requests.append(
  1236. seq_group.sampling_params.best_of)
  1237. n_requests.append(seq_group.sampling_params.n)
  1238. finished_reason_requests.extend([
  1239. SequenceStatus.get_finished_reason(seq.status)
  1240. for seq in seq_group.get_finished_seqs()
  1241. ])
  1242. # Number of generation tokens.
  1243. # num_batched_tokens equals the number of prompt_tokens plus the
  1244. # number of decode_tokens in a single iteration. So,
  1245. # num_generation_tokens = num_batched_tokens - num_prompt_tokens
  1246. # + num_generation_tokens_from_prefill_groups (since we generate
  1247. # one token on prefills on iters where the prefill finishes).
  1248. num_generation_tokens_iter = (
  1249. scheduler_outputs.num_batched_tokens - num_prompt_tokens_iter +
  1250. num_generation_tokens_from_prefill_groups)
  1251. # Spec decode, if enabled, emits specialized metrics from the worker in
  1252. # sampler output.
  1253. if model_output and (model_output[0].spec_decode_worker_metrics
  1254. is not None):
  1255. spec_decode_metrics = model_output[0].spec_decode_worker_metrics
  1256. else:
  1257. spec_decode_metrics = None
  1258. return Stats(
  1259. now=now,
  1260. # System stats
  1261. # Scheduler State
  1262. num_running_sys=num_running_sys,
  1263. num_swapped_sys=num_swapped_sys,
  1264. num_waiting_sys=num_waiting_sys,
  1265. # KV Cache Usage in %
  1266. gpu_cache_usage_sys=gpu_cache_usage_sys,
  1267. cpu_cache_usage_sys=cpu_cache_usage_sys,
  1268. # Prefix Cache Hit Rate
  1269. cpu_prefix_cache_hit_rate=cpu_prefix_cache_hit_rate,
  1270. gpu_prefix_cache_hit_rate=gpu_prefix_cache_hit_rate,
  1271. # Iteration stats
  1272. num_prompt_tokens_iter=num_prompt_tokens_iter,
  1273. num_generation_tokens_iter=num_generation_tokens_iter,
  1274. time_to_first_tokens_iter=time_to_first_tokens_iter,
  1275. time_per_output_tokens_iter=time_per_output_tokens_iter,
  1276. spec_decode_metrics=spec_decode_metrics,
  1277. num_preemption_iter=num_preemption_iter,
  1278. # Request stats
  1279. # Latency
  1280. time_e2e_requests=time_e2e_requests,
  1281. # Metadata
  1282. num_prompt_tokens_requests=num_prompt_tokens_requests,
  1283. num_generation_tokens_requests=num_generation_tokens_requests,
  1284. best_of_requests=best_of_requests,
  1285. n_requests=n_requests,
  1286. finished_reason_requests=finished_reason_requests,
  1287. )
  1288. def add_lora(self, lora_request: LoRARequest) -> bool:
  1289. return self.model_executor.add_lora(lora_request)
  1290. def remove_lora(self, lora_id: int) -> bool:
  1291. return self.model_executor.remove_lora(lora_id)
  1292. def list_loras(self) -> List[int]:
  1293. return self.model_executor.list_loras()
  1294. def pin_lora(self, lora_id: int) -> bool:
  1295. return self.model_executor.pin_lora(lora_id)
  1296. def add_prompt_adapter(
  1297. self, prompt_adapter_request: PromptAdapterRequest) -> bool:
  1298. return self.model_executor.add_prompt_adapter(prompt_adapter_request)
  1299. def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool:
  1300. return self.model_executor.remove_prompt_adapter(prompt_adapter_id)
  1301. def list_prompt_adapters(self) -> List[int]:
  1302. return self.model_executor.list_prompt_adapters()
  1303. def check_health(self) -> None:
  1304. if self.tokenizer:
  1305. self.tokenizer.check_health()
  1306. self.model_executor.check_health()
  1307. def is_encoder_decoder_model(self):
  1308. return self.model_config.is_encoder_decoder_model
  1309. def is_embedding_model(self):
  1310. return self.model_config.is_embedding_model
  1311. setup_logger()