aphrodite_engine.py 65 KB

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