aphrodite_engine.py 77 KB

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