aphrodite_engine.py 43 KB

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