aphrodite_engine.py 45 KB

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