aphrodite_engine.py 70 KB

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