aphrodite_engine.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. import copy
  2. from collections import defaultdict
  3. import os
  4. import time
  5. from typing import (TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple,
  6. Union)
  7. from loguru import logger
  8. import aphrodite
  9. from aphrodite.lora.request import LoRARequest
  10. from aphrodite.common.config import (CacheConfig, ModelConfig, ParallelConfig,
  11. SchedulerConfig, LoRAConfig, DeviceConfig)
  12. from aphrodite.processing.scheduler import Scheduler, SchedulerOutputs
  13. from aphrodite.engine.args_tools import EngineArgs
  14. from aphrodite.engine.metrics import StatLogger, Stats
  15. from aphrodite.engine.ray_tools import (RayWorkerAphrodite, initialize_cluster,
  16. ray)
  17. from aphrodite.common.logger import setup_logger
  18. from aphrodite.common.outputs import RequestOutput
  19. from aphrodite.common.sampling_params import SamplingParams
  20. from aphrodite.common.sequence import (SamplerOutput, Sequence, SequenceGroup,
  21. SequenceGroupOutput, SequenceOutput,
  22. SequenceStatus, Logprob)
  23. from aphrodite.transformers_utils.tokenizer import (detokenize_incrementally,
  24. TokenizerGroup)
  25. from aphrodite.common.utils import (Counter, set_cuda_visible_devices, get_ip,
  26. get_open_port)
  27. if ray:
  28. from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
  29. if TYPE_CHECKING:
  30. from ray.util.placement_group import PlacementGroup
  31. _LOCAL_LOGGING_INTERVAL_SEC = 5
  32. class AphroditeEngine:
  33. """An LLM engine that receives requests and generates texts.
  34. This is the main class for the Aphrodite engine. It receives requests
  35. from clients and generates texts from the LLM. It includes a tokenizer, a
  36. language model (possibly distributed across multiple GPUs), and GPU memory
  37. space allocated for intermediate states (aka KV cache). This class utilizes
  38. iteration-level scheduling and efficient memory management to maximize the
  39. serving throughput.
  40. The `LLM` class wraps this class for offline batched inference and the
  41. `AsyncAphrodite` class wraps this class for online serving.
  42. NOTE: The config arguments are derived from the `EngineArgs` class. For the
  43. comprehensive list of arguments, see `EngineArgs`.
  44. Args:
  45. model_config: The configuration related to the LLM model.
  46. cache_config: The configuration related to the KV cache memory
  47. management.
  48. parallel_config: The configuration related to distributed execution.
  49. scheduler_config: The configuration related to the request scheduler.
  50. device_config: The configuration related to the device.
  51. lora_config: The configuration related to LoRA.
  52. placement_group: Ray placement group for distributed execution.
  53. Required for distributed execution.
  54. log_stats: Whether to log statistics.
  55. """
  56. def __init__(
  57. self,
  58. model_config: ModelConfig,
  59. cache_config: CacheConfig,
  60. parallel_config: ParallelConfig,
  61. scheduler_config: SchedulerConfig,
  62. device_config: DeviceConfig,
  63. lora_config: Optional[LoRAConfig],
  64. placement_group: Optional["PlacementGroup"],
  65. log_stats: bool,
  66. ) -> None:
  67. logger.info(
  68. f"Initializing the Aphrodite Engine (v{aphrodite.__version__}) "
  69. "with the following config:\n"
  70. f"Model = {model_config.model!r}\n"
  71. f"DataType = {model_config.dtype}\n"
  72. f"Model Load Format = {model_config.load_format}\n"
  73. f"Number of GPUs = {parallel_config.tensor_parallel_size}\n"
  74. f"Disable Custom All-Reduce = "
  75. f"{parallel_config.disable_custom_all_reduce}\n"
  76. f"Quantization Format = {model_config.quantization}\n"
  77. f"Context Length = {model_config.max_model_len}\n"
  78. f"Enforce Eager Mode = {model_config.enforce_eager}\n"
  79. f"KV Cache Data Type = {cache_config.cache_dtype}\n"
  80. f"KV Cache Params Path = {cache_config.cache_quant_params_path}\n"
  81. f"Device = {device_config.device}")
  82. # TODO: Print more configs in debug mode.
  83. self.model_config = model_config
  84. self.cache_config = cache_config
  85. self.lora_config = lora_config
  86. self.parallel_config = parallel_config
  87. self.scheduler_config = scheduler_config
  88. self.device_config = device_config
  89. self.log_stats = log_stats
  90. self._verify_args()
  91. self._init_tokenizer()
  92. self.seq_counter = Counter()
  93. # Create the parallel GPU workers.
  94. if self.parallel_config.worker_use_ray:
  95. # Disable Ray usage stats collection.
  96. ray_usage = os.environ.get("RAY_USAGE_STATS_ENABLED", "0")
  97. if ray_usage != "1":
  98. os.environ["RAY_USAGE_STATS_ENABLED"] = "0"
  99. self._init_workers_ray(placement_group)
  100. else:
  101. self._init_workers()
  102. # Profile the memory usage and initialize the cache.
  103. self._init_cache()
  104. # Create the scheduler.
  105. self.scheduler = Scheduler(scheduler_config, cache_config, lora_config)
  106. # Metric Logging.
  107. if self.log_stats:
  108. self.stat_logger = StatLogger(
  109. local_interval=_LOCAL_LOGGING_INTERVAL_SEC,
  110. labels=dict(model_name=model_config.model))
  111. self.is_encoder_decoder = getattr(self.model_config.hf_config,
  112. "is_encoder_decoder", False)
  113. def get_tokenizer_for_seq(self, sequence: Sequence):
  114. return self.tokenizer.get_lora_tokenizer(sequence.lora_request)
  115. def _init_workers(self):
  116. # Lazy import the Worker to avoid importing torch.cuda/xformers
  117. # before CUDA_VISIBLE_DEVICES is set in the Worker
  118. # pylint: disable=import-outside-toplevel
  119. from aphrodite.task_handler.worker import Worker
  120. assert self.parallel_config.world_size == 1, (
  121. "Ray is required if parallel_config.world_size > 1.")
  122. self.workers: List[Worker] = []
  123. distributed_init_method = f"tcp://{get_ip()}:{get_open_port()}"
  124. self.driver_worker = Worker(
  125. self.model_config,
  126. self.parallel_config,
  127. self.scheduler_config,
  128. self.device_config,
  129. local_rank=0,
  130. rank=0,
  131. distributed_init_method=distributed_init_method,
  132. lora_config=self.lora_config,
  133. kv_cache_dtype=self.cache_config.cache_dtype,
  134. kv_quant_params_path=(self.cache_config.cache_quant_params_path),
  135. is_driver_worker=True,
  136. )
  137. self._run_workers("init_model")
  138. self._run_workers("load_model")
  139. def _init_tokenizer(self, **tokenizer_init_kwargs):
  140. init_kwargs = dict(
  141. enable_lora=bool(self.lora_config),
  142. max_num_seqs=self.scheduler_config.max_num_seqs,
  143. max_input_length=None,
  144. tokenizer_mode=self.model_config.tokenizer_mode,
  145. trust_remote_code=self.model_config.trust_remote_code,
  146. revision=self.model_config.tokenizer_revision)
  147. init_kwargs.update(tokenizer_init_kwargs)
  148. self.tokenizer: TokenizerGroup = TokenizerGroup(
  149. self.model_config.tokenizer, **init_kwargs)
  150. def _init_workers_ray(self, placement_group: "PlacementGroup",
  151. **ray_remote_kwargs):
  152. if self.parallel_config.tensor_parallel_size == 1:
  153. num_gpus = self.cache_config.gpu_memory_utilization
  154. else:
  155. num_gpus = 1
  156. self.driver_dummy_worker: RayWorkerAphrodite = None
  157. self.workers: List[RayWorkerAphrodite] = []
  158. driver_ip = get_ip()
  159. for bundle_id, bundle in enumerate(placement_group.bundle_specs):
  160. if not bundle.get("GPU", 0):
  161. continue
  162. scheduling_strategy = PlacementGroupSchedulingStrategy(
  163. placement_group=placement_group,
  164. placement_group_capture_child_tasks=True,
  165. placement_group_bundle_index=bundle_id,
  166. )
  167. worker = ray.remote(
  168. num_cpus=0,
  169. num_gpus=num_gpus,
  170. scheduling_strategy=scheduling_strategy,
  171. **ray_remote_kwargs,
  172. )(RayWorkerAphrodite).remote(self.model_config.trust_remote_code)
  173. worker_ip = ray.get(worker.get_node_ip.remote())
  174. if worker_ip == driver_ip and self.driver_dummy_worker is None:
  175. # If the worker is on the same node as the driver, we use it
  176. # as the resource holder for the driver process.
  177. self.driver_dummy_worker = worker
  178. else:
  179. self.workers.append(worker)
  180. if self.driver_dummy_worker is None:
  181. raise ValueError(
  182. "Ray does not allocate any GPUs on the driver node. Consider "
  183. "adjusting the Ray placement group or running the driver on a "
  184. "GPU node.")
  185. driver_node_id, driver_gpu_ids = ray.get(
  186. self.driver_dummy_worker.get_node_and_gpu_ids.remote())
  187. worker_node_and_gpu_ids = ray.get(
  188. [worker.get_node_and_gpu_ids.remote() for worker in self.workers])
  189. node_workers = defaultdict(list)
  190. node_gpus = defaultdict(list)
  191. node_workers[driver_node_id].append(0)
  192. node_gpus[driver_node_id].extend(driver_gpu_ids)
  193. for i, (node_id, gpu_ids) in enumerate(worker_node_and_gpu_ids,
  194. start=1):
  195. node_workers[node_id].append(i)
  196. node_gpus[node_id].extend(gpu_ids)
  197. for node_id, gpu_ids in node_gpus.items():
  198. node_gpus[node_id] = sorted(gpu_ids)
  199. # Set CUDA_VISIBLE_DEVICES for the driver.
  200. set_cuda_visible_devices(node_gpus[driver_node_id])
  201. for worker, (node_id, _) in zip(self.workers, worker_node_and_gpu_ids):
  202. worker.set_cuda_visible_devices.remote(node_gpus[node_id])
  203. distributed_init_method = f"tcp://{driver_ip}:{get_open_port()}"
  204. # Lazy import the Worker to avoid importing torch.cuda/xformers
  205. # before CUDA_VISIBLE_DEVICES is set in the Worker
  206. # pylint: disable=import-outside-toplevel
  207. from aphrodite.task_handler.worker import Worker
  208. # Initialize torch distributed process group for the workers.
  209. model_config = copy.deepcopy(self.model_config)
  210. parallel_config = copy.deepcopy(self.parallel_config)
  211. scheduler_config = copy.deepcopy(self.scheduler_config)
  212. device_config = copy.deepcopy(self.device_config)
  213. for rank, (worker, (node_id,
  214. _)) in enumerate(zip(self.workers,
  215. worker_node_and_gpu_ids),
  216. start=1):
  217. local_rank = node_workers[node_id].index(rank)
  218. worker.init_worker.remote(
  219. lambda rank=rank, local_rank=local_rank: Worker(
  220. model_config,
  221. parallel_config,
  222. scheduler_config,
  223. device_config,
  224. local_rank,
  225. rank,
  226. distributed_init_method,
  227. lora_config=self.lora_config,
  228. kv_cache_dtype=self.cache_config.cache_dtype,
  229. kv_quant_params_path=
  230. (self.cache_config.cache_quant_params_path),
  231. ))
  232. driver_rank = 0
  233. driver_local_rank = node_workers[driver_node_id].index(driver_rank)
  234. self.driver_worker = Worker(
  235. model_config,
  236. parallel_config,
  237. scheduler_config,
  238. device_config,
  239. driver_local_rank,
  240. driver_rank,
  241. distributed_init_method,
  242. lora_config=self.lora_config,
  243. kv_cache_dtype=self.cache_config.cache_dtype,
  244. kv_quant_params_path=(self.cache_config.cache_quant_params_path),
  245. is_driver_worker=True,
  246. )
  247. self._run_workers("init_model", cupy_port=get_open_port())
  248. self._run_workers(
  249. "load_model",
  250. max_concurrent_workers=self.parallel_config.
  251. max_parallel_loading_workers,
  252. )
  253. def _verify_args(self) -> None:
  254. self.model_config.verify_with_parallel_config(self.parallel_config)
  255. self.cache_config.verify_with_parallel_config(self.parallel_config)
  256. if self.lora_config:
  257. self.lora_config.verify_with_model_config(self.model_config)
  258. self.lora_config.verify_with_scheduler_config(
  259. self.scheduler_config)
  260. def _init_cache(self) -> None:
  261. # ruff: noqa: E501
  262. """Profiles the memory usage and initializes the KV cache.
  263. The engine will first conduct a profiling of the existing memory usage.
  264. Then, it calculate the maximum possible number of GPU and CPU blocks
  265. that can be allocated with the remaining free memory.
  266. More details can be found in the
  267. # pylint: disable=line-too-long
  268. :meth:`~aphrodite.task_handler.worker.Worker.profile_num_available_blocks` method
  269. from class :class:`~aphrodite.task_handler.Worker`.
  270. Afterwards, as there may be multiple workers,
  271. we take the minimum number of blocks across all workers
  272. to ensure this can be applied to all of them.
  273. Finally, the engine will initialize the KV cache
  274. with the calculated number of blocks.
  275. .. tip::
  276. You may limit the usage of GPU memory
  277. by adjusting the `gpu_memory_utilization` parameters.
  278. """
  279. # Get the maximum number of blocks that can be allocated on GPU and CPU.
  280. num_blocks = self._run_workers(
  281. "profile_num_available_blocks",
  282. block_size=self.cache_config.block_size,
  283. gpu_memory_utilization=self.cache_config.gpu_memory_utilization,
  284. cpu_swap_space=self.cache_config.swap_space_bytes,
  285. cache_dtype=self.cache_config.cache_dtype,
  286. )
  287. # Since we use a shared centralized controller, we take the minimum
  288. # number of blocks across all workers to make sure all the memory
  289. # operators can be applied to all workers.
  290. num_gpu_blocks = min(b[0] for b in num_blocks)
  291. num_cpu_blocks = min(b[1] for b in num_blocks)
  292. # FIXME: Change to debug log.
  293. logger.info(f"# GPU blocks: {num_gpu_blocks}, "
  294. f"# CPU blocks: {num_cpu_blocks}")
  295. logger.info(
  296. f"Minimum concurrency: {num_gpu_blocks * self.cache_config.block_size / self.scheduler_config.max_model_len:.2f}x"
  297. )
  298. if num_gpu_blocks <= 0:
  299. raise ValueError("No available memory for the cache blocks. "
  300. "Try increasing `gpu_memory_utilization` when "
  301. "initializing the engine.")
  302. max_seq_len = self.cache_config.block_size * num_gpu_blocks
  303. logger.info(f"Maximum sequence length allowed in the cache: "
  304. f"{max_seq_len}")
  305. if self.model_config.max_model_len > max_seq_len:
  306. raise ValueError(
  307. f"The model's max seq len ({self.model_config.max_model_len}) "
  308. "is larger than the maximum number of tokens that can be "
  309. f"stored in KV cache ({max_seq_len}). Try increasing "
  310. "`gpu_memory_utilization` or decreasing `max_model_len` when "
  311. "initializing the engine.")
  312. self.cache_config.num_gpu_blocks = num_gpu_blocks
  313. self.cache_config.num_cpu_blocks = num_cpu_blocks
  314. # Initialize the cache.
  315. self._run_workers("init_cache_engine", cache_config=self.cache_config)
  316. # Warm up the model. This includes capturing the model into CUDA graph
  317. # if enforce_eager is False.
  318. self._run_workers("warm_up_model")
  319. @classmethod
  320. def from_engine_args(cls, engine_args: EngineArgs) -> "AphroditeEngine":
  321. """Creates an LLM engine from the engine arguments."""
  322. # Create the engine configs.
  323. engine_configs = engine_args.create_engine_configs()
  324. parallel_config = engine_configs[2]
  325. # Initialize the cluster.
  326. placement_group = initialize_cluster(parallel_config)
  327. # Create the LLM engine.
  328. engine = cls(*engine_configs,
  329. placement_group,
  330. log_stats=not engine_args.disable_log_stats)
  331. return engine
  332. def encode_request(
  333. self,
  334. request_id: str,
  335. prompt: Optional[str],
  336. prompt_token_ids: Optional[List[int]] = None,
  337. lora_request: Optional[LoRARequest] = None,
  338. ):
  339. if prompt_token_ids is None:
  340. assert prompt is not None
  341. prompt_token_ids = self.tokenizer.encode(request_id=request_id,
  342. prompt=prompt,
  343. lora_request=lora_request)
  344. return prompt_token_ids
  345. def add_request(
  346. self,
  347. request_id: str,
  348. prompt: Optional[str],
  349. sampling_params: SamplingParams,
  350. prompt_token_ids: Optional[List[int]] = None,
  351. arrival_time: Optional[float] = None,
  352. lora_request: Optional[LoRARequest] = None,
  353. ) -> None:
  354. """Add a request to the engine's request pool.
  355. The request is added to the request pool and will be processed by the
  356. scheduler as `engine.step()` is called. The exact scheduling policy is
  357. determined by the scheduler.
  358. Args:
  359. request_id: The unique ID of the request.
  360. prompt: The prompt string. Can be None if prompt_token_ids is
  361. provided.
  362. sampling_params: The sampling parameters for text generation.
  363. prompt_token_ids: The token IDs of the prompt. If None, we
  364. use the tokenizer to convert the prompts to token IDs.
  365. arrival_time: The arrival time of the request. If None, we use
  366. the current monotonic time.
  367. Details:
  368. - Set arrival_time to the current time if it is None.
  369. - Set prompt_token_ids to the encoded prompt if it is None.
  370. - Create `best_of` number of :class:`~aphrodite.Sequence` objects.
  371. - Create a :class:`~aphrodite.SequenceGroup` object
  372. from the list of :class:`~aphrodite.Sequence`.
  373. - Add the :class:`~aphrodite.SequenceGroup` object to the scheduler.
  374. Example:
  375. >>> # initialize engine
  376. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  377. >>> # set request arguments
  378. >>> example_prompt = "Who is the president of the United States?"
  379. >>> sampling_params = SamplingParams(temperature=0.0)
  380. >>> request_id = 0
  381. >>>
  382. >>> # add the request to the engine
  383. >>> engine.add_request(
  384. >>> str(request_id),
  385. >>> example_prompt,
  386. >>> SamplingParams(temperature=0.0))
  387. >>> # continue the request processing
  388. >>> ...
  389. """
  390. if lora_request is not None and not self.lora_config:
  391. raise ValueError(f"Got lora_request {lora_request} but LoRA is "
  392. "not enabled!")
  393. max_log_probs = self.get_model_config().max_log_probs
  394. if (sampling_params.logprobs
  395. and sampling_params.logprobs > max_log_probs) or (
  396. sampling_params.prompt_logprobs
  397. and sampling_params.prompt_logprobs > max_log_probs):
  398. raise ValueError(f"Cannot request more than "
  399. f"{max_log_probs} logprobs.")
  400. if arrival_time is None:
  401. arrival_time = time.monotonic()
  402. prompt_token_ids = self.encode_request(
  403. request_id=request_id,
  404. prompt=prompt,
  405. prompt_token_ids=prompt_token_ids,
  406. lora_request=lora_request)
  407. # Create the sequences.
  408. block_size = self.cache_config.block_size
  409. seq_id = next(self.seq_counter)
  410. seq = Sequence(seq_id, prompt, prompt_token_ids, block_size,
  411. self.is_encoder_decoder, lora_request)
  412. # Create the sequence group.
  413. seq_group = SequenceGroup(request_id, [seq], sampling_params,
  414. arrival_time, lora_request)
  415. # Add the sequence group to the scheduler.
  416. self.scheduler.add_seq_group(seq_group)
  417. def abort_request(self, request_id: Union[str, Iterable[str]]) -> None:
  418. """Aborts a request(s) with the given ID.
  419. Args:
  420. request_id: The ID(s) of the request to abort.
  421. Details:
  422. - Refer to the
  423. :meth:`~aphrodite.processing.scheduler.Scheduler.abort_seq_group`
  424. from class :class:`~aphrodite.processing.scheduler.Scheduler`.
  425. Example:
  426. >>> # initialize engine and add a request with request_id
  427. >>> request_id = str(0)
  428. >>> # abort the request
  429. >>> engine.abort_request(request_id)
  430. """
  431. self.scheduler.abort_seq_group(request_id)
  432. def get_model_config(self) -> ModelConfig:
  433. """Gets the model configuration."""
  434. return self.model_config
  435. def get_num_unfinished_requests(self) -> int:
  436. """Gets the number of unfinished requests."""
  437. return self.scheduler.get_num_unfinished_seq_groups()
  438. def has_unfinished_requests(self) -> bool:
  439. """Returns True if there are unfinished requests."""
  440. return self.scheduler.has_unfinished_seqs()
  441. def _check_beam_search_early_stopping(
  442. self,
  443. early_stopping: Union[bool, str],
  444. sampling_params: SamplingParams,
  445. best_running_seq: Sequence,
  446. current_worst_seq: Sequence,
  447. ) -> bool:
  448. assert sampling_params.use_beam_search
  449. length_penalty = sampling_params.length_penalty
  450. if early_stopping is True:
  451. return True
  452. current_worst_score = (current_worst_seq.get_beam_search_score(
  453. length_penalty=length_penalty,
  454. eos_token_id=self.get_tokenizer_for_seq(
  455. current_worst_seq).eos_token_id))
  456. if early_stopping is False:
  457. highest_attainable_score = (best_running_seq.get_beam_search_score(
  458. length_penalty=length_penalty,
  459. eos_token_id=self.get_tokenizer_for_seq(
  460. best_running_seq).eos_token_id))
  461. else:
  462. assert early_stopping == "never"
  463. if length_penalty > 0.0:
  464. # If length_penalty > 0.0, beam search will prefer longer
  465. # sequences. The highest attainable score calculation is
  466. # based on the longest possible sequence length in this case.
  467. max_possible_length = max(
  468. best_running_seq.get_prompt_len() +
  469. sampling_params.max_tokens,
  470. self.scheduler_config.max_model_len)
  471. highest_attainable_score = (
  472. best_running_seq.get_beam_search_score(
  473. length_penalty=length_penalty,
  474. eos_token_id=self.get_tokenizer_for_seq(
  475. best_running_seq).eos_token_id,
  476. seq_len=max_possible_length))
  477. else:
  478. # Otherwise, beam search will prefer shorter sequences. The
  479. # highest attainable score calculation is based on the current
  480. # sequence length.
  481. highest_attainable_score = (
  482. best_running_seq.get_beam_search_score(
  483. length_penalty=length_penalty,
  484. eos_token_id=self.get_tokenizer_for_seq(
  485. best_running_seq).eos_token_id))
  486. return current_worst_score >= highest_attainable_score
  487. def _process_sequence_group_outputs(self, seq_group: SequenceGroup,
  488. outputs: SequenceGroupOutput) -> None:
  489. # Process prompt logprobs
  490. prompt_logprobs = outputs.prompt_logprobs
  491. if prompt_logprobs is not None:
  492. seq_group.prompt_logprobs = prompt_logprobs
  493. # Process samples
  494. samples = outputs.samples
  495. parent_seqs = seq_group.get_seqs(status=SequenceStatus.RUNNING)
  496. existing_finished_seqs = seq_group.get_finished_seqs()
  497. parent_child_dict = {
  498. parent_seq.seq_id: []
  499. for parent_seq in parent_seqs
  500. }
  501. for sample in samples:
  502. parent_child_dict[sample.parent_seq_id].append(sample)
  503. # List of (child, parent)
  504. child_seqs: List[Tuple[Sequence, Sequence]] = []
  505. # Process the child samples for each parent sequence
  506. for parent in parent_seqs:
  507. child_samples: List[SequenceOutput] = parent_child_dict[
  508. parent.seq_id]
  509. if len(child_samples) == 0:
  510. # This parent sequence has no children samples. Remove
  511. # the parent sequence from the sequence group since it will
  512. # not be used in the future iterations.
  513. parent.status = SequenceStatus.FINISHED_ABORTED
  514. seq_group.remove(parent.seq_id)
  515. self.scheduler.free_seq(parent)
  516. continue
  517. # Fork the parent sequence if there are multiple child samples.
  518. for child_sample in child_samples[:-1]:
  519. new_child_seq_id = next(self.seq_counter)
  520. child = parent.fork(new_child_seq_id)
  521. child.append_token_id(child_sample.output_token,
  522. child_sample.logprobs)
  523. child.persistent_data = child_sample.persistent_data
  524. child_seqs.append((child, parent))
  525. # Continue the parent sequence for the last child sample.
  526. # We reuse the parent sequence here to reduce redundant memory
  527. # copies, especially when using non-beam search sampling methods.
  528. last_child_sample = child_samples[-1]
  529. parent.append_token_id(last_child_sample.output_token,
  530. last_child_sample.logprobs)
  531. parent.persistent_data = last_child_sample.persistent_data
  532. child_seqs.append((parent, parent))
  533. for seq, _ in child_seqs:
  534. self._decode_sequence(seq, seq_group.sampling_params)
  535. self._check_stop(seq, seq_group.sampling_params)
  536. # Non-beam search case
  537. if not seq_group.sampling_params.use_beam_search:
  538. # For newly created child sequences, add them to the sequence group
  539. # and fork them in block manager if they are not finished.
  540. for seq, parent in child_seqs:
  541. if seq is not parent:
  542. seq_group.add(seq)
  543. if not seq.is_finished():
  544. self.scheduler.fork_seq(parent, seq)
  545. # Free the finished and selected parent sequences' memory in block
  546. # manager. Keep them in the sequence group as candidate output.
  547. # NOTE: we need to fork the new sequences before freeing the
  548. # old sequences.
  549. for seq, parent in child_seqs:
  550. if seq is parent and seq.is_finished():
  551. self.scheduler.free_seq(seq)
  552. return
  553. # Beam search case
  554. # Select the child sequences to keep in the sequence group.
  555. selected_child_seqs = []
  556. unselected_child_seqs = []
  557. beam_width = seq_group.sampling_params.best_of
  558. length_penalty = seq_group.sampling_params.length_penalty
  559. # Select the newly finished sequences with the highest scores
  560. # to replace existing finished sequences.
  561. # Tuple of (seq, parent, is_new)
  562. existing_finished_seqs = [(seq, None, False)
  563. for seq in existing_finished_seqs]
  564. new_finished_seqs = [(seq, parent, True) for seq, parent in child_seqs
  565. if seq.is_finished()]
  566. all_finished_seqs = existing_finished_seqs + new_finished_seqs
  567. # Sort the finished sequences by their scores.
  568. all_finished_seqs.sort(key=lambda x: x[0].get_beam_search_score(
  569. length_penalty=length_penalty,
  570. eos_token_id=self.get_tokenizer_for_seq(x[0]).eos_token_id),
  571. reverse=True)
  572. for seq, parent, is_new in all_finished_seqs[:beam_width]:
  573. if is_new:
  574. # A newly generated child sequence finishes and has a high
  575. # score, so we will add it into the sequence group.
  576. selected_child_seqs.append((seq, parent))
  577. for seq, parent, is_new in all_finished_seqs[beam_width:]:
  578. if is_new:
  579. # A newly generated child sequence finishes but has a low
  580. # score, so we will not add it into the sequence group.
  581. # Additionally, if this sequence is a continuation of a
  582. # parent sequence, we will need remove the parent sequence
  583. # from the sequence group.
  584. unselected_child_seqs.append((seq, parent))
  585. else:
  586. # An existing finished sequence has a low score, so we will
  587. # remove it from the sequence group.
  588. seq_group.remove(seq.seq_id)
  589. # select the top beam_width sequences from the running
  590. # sequences for the next iteration to continue the beam
  591. # search.
  592. running_child_seqs = [(seq, parent) for seq, parent in child_seqs
  593. if not seq.is_finished()]
  594. # Sort the running sequences by their scores.
  595. running_child_seqs.sort(key=lambda x: x[0].get_beam_search_score(
  596. length_penalty=length_penalty,
  597. eos_token_id=self.get_tokenizer_for_seq(x[0]).eos_token_id),
  598. reverse=True)
  599. # Check if we can stop the beam search.
  600. if len(running_child_seqs) == 0:
  601. # No running sequences, stop the beam search.
  602. stop_beam_search = True
  603. elif len(all_finished_seqs) < beam_width:
  604. # Not enough finished sequences, continue the beam search.
  605. stop_beam_search = False
  606. else:
  607. # Check the early stopping criteria
  608. best_running_seq = running_child_seqs[0][0]
  609. current_worst_seq = all_finished_seqs[beam_width - 1][0]
  610. stop_beam_search = self._check_beam_search_early_stopping(
  611. seq_group.sampling_params.early_stopping,
  612. seq_group.sampling_params, best_running_seq, current_worst_seq)
  613. if stop_beam_search:
  614. # Stop the beam search and remove all the running sequences from
  615. # the sequence group.
  616. unselected_child_seqs.extend(running_child_seqs)
  617. else:
  618. # Continue the beam search and select the top beam_width sequences
  619. # to continue the beam search.
  620. selected_child_seqs.extend(running_child_seqs[:beam_width])
  621. # The remaining running sequences will not be used in the next
  622. # iteration. Again, if these sequences are continuations of
  623. # parent sequences, we will need to remove the parent sequences
  624. # from the sequence group.
  625. unselected_child_seqs.extend(running_child_seqs[beam_width:])
  626. # For newly created child sequences, add them to the sequence group
  627. # and fork them in block manager if they are not finished.
  628. for seq, parent in selected_child_seqs:
  629. if seq is not parent:
  630. seq_group.add(seq)
  631. if not seq.is_finished():
  632. self.scheduler.fork_seq(parent, seq)
  633. # Free the finished and selected parent sequences' memory in block
  634. # manager. Keep them in the sequence group as candidate output.
  635. for seq, parent in selected_child_seqs:
  636. if seq is parent and seq.is_finished():
  637. self.scheduler.free_seq(seq)
  638. # Remove the unselected parent sequences from the sequence group and
  639. # free their memory in block manager.
  640. for seq, parent in unselected_child_seqs:
  641. if seq is parent:
  642. # Remove the parent sequence if it is not selected for next
  643. # iteration
  644. seq_group.remove(seq.seq_id)
  645. self.scheduler.free_seq(seq)
  646. def _process_model_outputs(
  647. self, output: SamplerOutput,
  648. scheduler_outputs: SchedulerOutputs) -> List[RequestOutput]:
  649. # Update the scheduled sequence groups with the model outputs.
  650. scheduled_seq_groups = scheduler_outputs.scheduled_seq_groups
  651. # If prefix caching is enabled, mark all blocks in the sequence groups
  652. # as completed so that future requests don't attempt to recompute them
  653. if self.cache_config.context_shift:
  654. for seq_group in scheduled_seq_groups:
  655. self.scheduler.mark_blocks_as_computed(seq_group)
  656. for seq_group, outputs in zip(scheduled_seq_groups, output):
  657. self._process_sequence_group_outputs(seq_group, outputs)
  658. # Free the finished sequence groups.
  659. self.scheduler.free_finished_seq_groups()
  660. # Create the outputs.
  661. request_outputs: List[RequestOutput] = []
  662. for seq_group in scheduled_seq_groups:
  663. request_output = RequestOutput.from_seq_group(seq_group)
  664. request_outputs.append(request_output)
  665. for seq_group in scheduler_outputs.ignored_seq_groups:
  666. request_output = RequestOutput.from_seq_group(seq_group)
  667. request_outputs.append(request_output)
  668. # Log stats.
  669. if self.log_stats:
  670. self.stat_logger.log(self._get_stats(scheduler_outputs))
  671. return request_outputs
  672. def step(self) -> List[RequestOutput]:
  673. """Performs one decoding iteration and returns newly generated results.
  674. .. figure:: https://i.imgur.com/sv2HssD.png
  675. :alt: Overview of the step function
  676. :align: center
  677. Overview of the step function.
  678. Details:
  679. - Step 1: Schedules the sequences to be executed in the next
  680. iteration and the token blocks to be swapped in/out/copy.
  681. - Depending on the scheduling policy,
  682. sequences may be `preempted/reordered`.
  683. - A Sequence Group (SG) refer to a group of sequences
  684. that are generated from the same prompt.
  685. - Step 2: Calls the workers to execute the model.
  686. - Step 3: Processes the model output. This mainly includes:
  687. - Decodes the relevant outputs.
  688. - Updates the scheduled sequence groups with model outputs
  689. based on its `sampling parameters` (`use_beam_search` or not).
  690. - Frees the finished sequence groups.
  691. - Finally, it creates and returns the newly generated results.
  692. Example:
  693. >>> # Please see the example/ folder for more detailed examples.
  694. >>>
  695. >>> # initialize engine and request arguments
  696. >>> engine = AphroditeEngine.from_engine_args(engine_args)
  697. >>> example_inputs = [(0, "What is LLM?",
  698. >>> SamplingParams(temperature=0.0))]
  699. >>>
  700. >>> # Start the engine with an event loop
  701. >>> while True:
  702. >>> if example_inputs:
  703. >>> req_id, prompt, sampling_params = example_inputs.pop(0)
  704. >>> engine.add_request(str(req_id), prompt, sampling_params)
  705. >>>
  706. >>> # continue the request processing
  707. >>> request_outputs = engine.step()
  708. >>> for request_output in request_outputs:
  709. >>> if request_output.finished:
  710. >>> # return or show the request output
  711. >>>
  712. >>> if not (engine.has_unfinished_requests() or example_inputs):
  713. >>> break
  714. """
  715. seq_group_metadata_list, scheduler_outputs = self.scheduler.schedule()
  716. if not scheduler_outputs.is_empty():
  717. # Execute the model.
  718. all_outputs = self._run_workers(
  719. "execute_model",
  720. driver_kwargs={
  721. "seq_group_metadata_list": seq_group_metadata_list,
  722. "blocks_to_swap_in": scheduler_outputs.blocks_to_swap_in,
  723. "blocks_to_swap_out": scheduler_outputs.blocks_to_swap_out,
  724. "blocks_to_copy": scheduler_outputs.blocks_to_copy,
  725. })
  726. # Only the driver worker returns the sampling results.
  727. output = all_outputs[0]
  728. else:
  729. output = []
  730. return self._process_model_outputs(output, scheduler_outputs)
  731. def do_log_stats(self) -> None:
  732. """Forced log when no requests active."""
  733. if self.log_stats:
  734. self.stat_logger.log(self._get_stats(scheduler_outputs=None))
  735. def _get_stats(self,
  736. scheduler_outputs: Optional[SchedulerOutputs]) -> Stats:
  737. """Get Stats to be Logged to Prometheus."""
  738. now = time.monotonic()
  739. # KV Cache Usage in %.
  740. num_total_gpu = self.cache_config.num_gpu_blocks
  741. num_free_gpu = self.scheduler.block_manager.get_num_free_gpu_blocks()
  742. gpu_cache_usage = 1.0 - (num_free_gpu / num_total_gpu)
  743. num_total_cpu = self.cache_config.num_cpu_blocks
  744. cpu_cache_usage = 0.
  745. if num_total_cpu > 0:
  746. num_free_cpu = self.scheduler.block_manager.get_num_free_cpu_blocks(
  747. )
  748. cpu_cache_usage = 1.0 - (num_free_cpu / num_total_cpu)
  749. # Scheduler State
  750. num_running = len(self.scheduler.running)
  751. num_swapped = len(self.scheduler.swapped)
  752. num_waiting = len(self.scheduler.waiting)
  753. # Iteration stats if we have scheduler output.
  754. num_prompt_tokens = 0
  755. num_generation_tokens = 0
  756. time_to_first_tokens = []
  757. time_per_output_tokens = []
  758. time_e2e_requests = []
  759. if scheduler_outputs is not None:
  760. prompt_run = scheduler_outputs.prompt_run
  761. # Number of Tokens.
  762. if prompt_run:
  763. num_prompt_tokens = sum(
  764. len(seq_group.prompt_token_ids)
  765. for seq_group in scheduler_outputs.scheduled_seq_groups)
  766. num_generation_tokens = sum(
  767. seq_group.num_seqs()
  768. for seq_group in scheduler_outputs.scheduled_seq_groups)
  769. else:
  770. num_generation_tokens = scheduler_outputs.num_batched_tokens
  771. # Latency Timings.
  772. time_last_iters = []
  773. for seq_group in scheduler_outputs.scheduled_seq_groups:
  774. # Time since last token. (n.b. updates seq_group.metrics.last_token_time)
  775. time_last_iters.append(seq_group.get_last_latency(now))
  776. # Time since arrival for all finished requests.
  777. if seq_group.is_finished():
  778. time_e2e_requests.append(now -
  779. seq_group.metrics.arrival_time)
  780. time_to_first_tokens = time_last_iters if prompt_run else []
  781. time_per_output_tokens = [] if prompt_run else time_last_iters
  782. return Stats(
  783. now=now,
  784. num_running=num_running,
  785. num_swapped=num_swapped,
  786. num_waiting=num_waiting,
  787. gpu_cache_usage=gpu_cache_usage,
  788. cpu_cache_usage=cpu_cache_usage,
  789. num_prompt_tokens=num_prompt_tokens,
  790. num_generation_tokens=num_generation_tokens,
  791. time_to_first_tokens=time_to_first_tokens,
  792. time_per_output_tokens=time_per_output_tokens,
  793. time_e2e_requests=time_e2e_requests,
  794. )
  795. def _decode_logprobs(self, seq: Sequence, prms: SamplingParams,
  796. logprobs: Dict[int, Logprob],
  797. all_input_ids: List[int]) -> None:
  798. if not logprobs:
  799. return
  800. for token_id, sample_logprob in logprobs.items():
  801. if (sample_logprob.decoded_token is None and token_id != -1):
  802. all_input_ids_with_logprob = all_input_ids[:-1] + [token_id]
  803. # pylint: disable=unused-variable
  804. _, new_text, prefix_offset, read_offset = detokenize_incrementally(
  805. self.get_tokenizer_for_seq(seq),
  806. all_input_ids=all_input_ids_with_logprob,
  807. prev_tokens=seq.tokens,
  808. prefix_offset=seq.prefix_offset,
  809. read_offset=seq.read_offset,
  810. skip_special_tokens=prms.skip_special_tokens,
  811. spaces_between_special_tokens=prms.
  812. spaces_between_special_tokens,
  813. )
  814. sample_logprob.decoded_token = new_text
  815. def _decode_sequence(self, seq: Sequence, prms: SamplingParams) -> None:
  816. """Decodes the new token for a sequence."""
  817. all_input_ids = seq.get_token_ids()
  818. self._decode_logprobs(seq, prms, seq.output_logprobs[-1],
  819. all_input_ids)
  820. (new_tokens, new_output_text, prefix_offset,
  821. read_offset) = detokenize_incrementally(
  822. self.get_tokenizer_for_seq(seq),
  823. all_input_ids=all_input_ids,
  824. prev_tokens=seq.tokens,
  825. prefix_offset=seq.prefix_offset,
  826. read_offset=seq.read_offset,
  827. skip_special_tokens=prms.skip_special_tokens,
  828. spaces_between_special_tokens=prms.spaces_between_special_tokens,
  829. )
  830. if seq.tokens is None:
  831. seq.tokens = new_tokens
  832. else:
  833. seq.tokens.extend(new_tokens)
  834. seq.prefix_offset = prefix_offset
  835. seq.read_offset = read_offset
  836. seq.output_text += new_output_text
  837. def _check_stop(self, seq: Sequence,
  838. sampling_params: SamplingParams) -> None:
  839. """Stop the finished sequences."""
  840. for stop_str in sampling_params.stop:
  841. if seq.output_text.endswith(stop_str):
  842. self._finalize_sequence(seq, sampling_params, stop_str)
  843. seq.status = SequenceStatus.FINISHED_STOPPED
  844. return
  845. if seq.get_last_token_id() in sampling_params.stop_token_ids:
  846. stop_str = self.get_tokenizer_for_seq(seq).convert_ids_to_tokens(
  847. seq.get_last_token_id())
  848. self._finalize_sequence(seq, sampling_params, stop_str)
  849. seq.status = SequenceStatus.FINISHED_STOPPED
  850. return
  851. # Check if the sequence has reached max_model_len.
  852. if seq.get_len() > self.scheduler_config.max_model_len:
  853. seq.status = SequenceStatus.FINISHED_LENGTH_CAPPED
  854. return
  855. # Check if the sequence has reached max_tokens.
  856. if seq.get_output_len() == sampling_params.max_tokens:
  857. seq.status = SequenceStatus.FINISHED_LENGTH_CAPPED
  858. return
  859. # Check if the sequence has generated the EOS token.
  860. if ((not sampling_params.ignore_eos) and seq.get_last_token_id()
  861. == self.get_tokenizer_for_seq(seq).eos_token_id):
  862. seq.status = SequenceStatus.FINISHED_STOPPED
  863. return
  864. def _finalize_sequence(self, seq: Sequence,
  865. sampling_params: SamplingParams,
  866. stop_string: str) -> None:
  867. if not sampling_params.include_stop_str_in_output and stop_string:
  868. # Truncate the output text so that the stop string is
  869. # not included in the output.
  870. seq.output_text = seq.output_text[:-len(stop_string)]
  871. def add_lora(self, lora_request: LoRARequest) -> bool:
  872. assert lora_request.lora_int_id > 0, "lora_id must be greater than 0."
  873. return self._run_workers(
  874. "add_lora",
  875. lora_request=lora_request,
  876. )
  877. def remove_lora(self, lora_id: int) -> bool:
  878. assert lora_id > 0, "lora_id must be greater than 0."
  879. return self._run_workers(
  880. "remove_lora",
  881. lora_id=lora_id,
  882. )
  883. def list_loras(self) -> List[int]:
  884. return self._run_workers("list_loras")
  885. def _run_workers(
  886. self,
  887. method: str,
  888. *args,
  889. driver_args: Optional[List[Any]] = None,
  890. driver_kwargs: Optional[Dict[str, Any]] = None,
  891. max_concurrent_workers: Optional[int] = None,
  892. **kwargs,
  893. ) -> Any:
  894. """Runs the given method on all workers."""
  895. if max_concurrent_workers:
  896. raise NotImplementedError(
  897. "max_concurrent_workers is not supported yet.")
  898. # Start the ray workers first.
  899. ray_worker_outputs = [
  900. worker.execute_method.remote(method, *args, **kwargs)
  901. for worker in self.workers
  902. ]
  903. if driver_args is None:
  904. driver_args = args
  905. if driver_kwargs is None:
  906. driver_kwargs = kwargs
  907. # Start the driver worker after all the ray workers.
  908. driver_worker_output = getattr(self.driver_worker,
  909. method)(*driver_args, **driver_kwargs)
  910. # Get the results of the ray workers.
  911. if self.workers:
  912. ray_worker_outputs = ray.get(ray_worker_outputs)
  913. return [driver_worker_output] + ray_worker_outputs
  914. def check_health(self) -> None:
  915. """Raises an error if engine is unhealthy."""
  916. self._check_if_any_actor_is_dead()
  917. def _check_if_any_actor_is_dead(self):
  918. if not self.parallel_config.worker_use_ray:
  919. return
  920. if not self.workers:
  921. return
  922. dead_actors = []
  923. for actor in self.workers:
  924. actor_state = ray.state.actors(actor._ray_actor_id.hex())
  925. if actor_state["State"] == "DEAD":
  926. dead_actors.append(actor)
  927. if dead_actors:
  928. raise RuntimeError("At least one Worker is dead. "
  929. f"Dead workers: {dead_actors}")
  930. setup_logger()