aphrodite_engine.py 43 KB

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