model_runner.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. import gc
  2. import time
  3. import warnings
  4. from collections import defaultdict
  5. from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union
  6. import numpy as np
  7. import torch
  8. import torch.nn as nn
  9. from loguru import logger
  10. from aphrodite.attention import AttentionMetadata, get_attn_backend
  11. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  12. LoRAConfig, ModelConfig, ParallelConfig,
  13. SchedulerConfig, VisionLanguageConfig)
  14. from aphrodite.common.sampling_params import SamplingParams
  15. from aphrodite.common.sequence import (SamplerOutput, SequenceData,
  16. SequenceGroupMetadata)
  17. from aphrodite.common.utils import (CudaMemoryProfiler,
  18. get_kv_cache_torch_dtype, is_hip,
  19. is_pin_memory_available,
  20. make_tensor_with_pad)
  21. from aphrodite.distributed import broadcast_tensor_dict
  22. from aphrodite.distributed.communication_op import graph_capture
  23. from aphrodite.distributed.parallel_state import (
  24. get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size)
  25. from aphrodite.lora.layers import LoRAMapping
  26. from aphrodite.lora.request import LoRARequest
  27. from aphrodite.lora.worker_manager import LRUCacheWorkerLoRAManager
  28. from aphrodite.modeling import SamplingMetadata
  29. from aphrodite.modeling.model_loader import get_model
  30. from aphrodite.multimodal import MULTIMODAL_REGISTRY
  31. _PAD_SLOT_ID = -1
  32. LORA_WARMUP_RANK = 8
  33. _BATCH_SIZE_ALIGNMENT = 8
  34. # Capture graphs for token size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.
  35. # NOTE: _get_graph_batch_size needs to be updated if this list is changed.
  36. _BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [
  37. _BATCH_SIZE_ALIGNMENT * i for i in range(1, 33)
  38. ]
  39. _NUM_WARMUP_ITERS = 2
  40. class ModelInput(NamedTuple):
  41. input_tokens: torch.Tensor
  42. input_positions: torch.Tensor
  43. attn_metadata: Optional[AttentionMetadata]
  44. seq_lens: List[int]
  45. query_lens: List[int]
  46. lora_mapping: Optional[LoRAMapping]
  47. lora_requests: Set[LoRARequest]
  48. multi_modal_kwargs: Dict[str, torch.Tensor]
  49. slot_mapping: torch.Tensor
  50. num_prefill_tokens: int
  51. num_decode_tokens: int
  52. num_prefills: int
  53. @classmethod
  54. def empty(cls, device):
  55. return ModelInput(
  56. input_tokens=torch.empty(0, device=device),
  57. input_positions=torch.empty(0, device=device),
  58. attn_metadata=None,
  59. seq_lens=[],
  60. query_lens=[],
  61. lora_mapping=None,
  62. lora_requests=set(),
  63. multi_modal_kwargs={},
  64. slot_mapping=torch.empty(0, device=device),
  65. num_prefill_tokens=0,
  66. num_decode_tokens=0,
  67. num_prefills=0,
  68. )
  69. class ModelRunner:
  70. def __init__(
  71. self,
  72. model_config: ModelConfig,
  73. parallel_config: ParallelConfig,
  74. scheduler_config: SchedulerConfig,
  75. device_config: DeviceConfig,
  76. cache_config: CacheConfig,
  77. load_config: LoadConfig,
  78. lora_config: Optional[LoRAConfig],
  79. kv_cache_dtype: Optional[str] = "auto",
  80. is_driver_worker: bool = False,
  81. vision_language_config: Optional[VisionLanguageConfig] = None,
  82. ):
  83. self.model_config = model_config
  84. self.parallel_config = parallel_config
  85. self.scheduler_config = scheduler_config
  86. self.device_config = device_config
  87. self.cache_config = cache_config
  88. self.lora_config = lora_config
  89. self.load_config = load_config
  90. self.is_driver_worker = is_driver_worker
  91. self.vision_language_config = vision_language_config
  92. self.device = self.device_config.device
  93. self.pin_memory = is_pin_memory_available()
  94. self.kv_cache_dtype = kv_cache_dtype
  95. self.sliding_window = model_config.get_sliding_window()
  96. self.block_size = cache_config.block_size
  97. self.max_seq_len_to_capture = self.model_config.max_seq_len_to_capture
  98. self.graph_runners: Dict[int, CUDAGraphRunner] = {}
  99. self.graph_memory_pool: Optional[Tuple[
  100. int, int]] = None # Set during graph capture.
  101. # When using CUDA graph, the input block tables must be padded to
  102. # max_seq_len_to_capture. However, creating the block table in
  103. # Python can be expensive. To optimize this, we cache the block table
  104. # in numpy and only copy the actual input content at every iteration.
  105. # The shape of the cached block table will be
  106. # (max batch size to capture, max context len to capture / block size).
  107. self.graph_block_tables = np.zeros(
  108. (max(_BATCH_SIZES_TO_CAPTURE), self.get_max_block_per_batch()),
  109. dtype=np.int32)
  110. self.attn_backend = get_attn_backend(
  111. self.model_config.get_num_attention_heads(self.parallel_config),
  112. self.model_config.get_head_size(),
  113. self.model_config.get_num_kv_heads(self.parallel_config),
  114. self.model_config.get_sliding_window(),
  115. self.model_config.dtype,
  116. self.kv_cache_dtype,
  117. self.block_size,
  118. )
  119. # Create processor for multi-modal data
  120. if self.vision_language_config is not None:
  121. self.multi_modal_input_processor = MULTIMODAL_REGISTRY \
  122. .create_input_processor(
  123. self.model_config,
  124. self.vision_language_config,
  125. )
  126. else:
  127. self.multi_modal_input_processor = None
  128. # Lazy initialization
  129. self.model: nn.Module # Set after load_model
  130. # Set if the backend is flashinfer.
  131. self.flashinfer_workspace_buffer: torch.Tensor
  132. # Set after load_model.
  133. self.lora_manager: Optional[LRUCacheWorkerLoRAManager] = None
  134. def load_model(self) -> None:
  135. with CudaMemoryProfiler() as m:
  136. # measure the time it takes to load the model
  137. start_time = time.time()
  138. self.model = get_model(
  139. model_config=self.model_config,
  140. device_config=self.device_config,
  141. load_config=self.load_config,
  142. lora_config=self.lora_config,
  143. vision_language_config=self.vision_language_config,
  144. parallel_config=self.parallel_config,
  145. scheduler_config=self.scheduler_config,
  146. cache_config=self.cache_config,
  147. )
  148. end_time = time.time()
  149. self.model_memory_usage = m.consumed_memory
  150. tp = get_tensor_model_parallel_world_size()
  151. rank = get_tensor_model_parallel_rank()
  152. total_time = end_time - start_time
  153. if tp > 1:
  154. logger.info(
  155. f"Rank {rank}: Model weights loaded in {total_time:.2f} secs.")
  156. if rank == 0:
  157. logger.info(
  158. "Memory usage: "
  159. f"{self.model_memory_usage / float(2**30):.2f} GiB x {tp} ="
  160. f" {self.model_memory_usage * tp / float(2**30):.2f} GiB")
  161. else:
  162. logger.info(f"Model weights loaded in {total_time:.2f} seconds.")
  163. logger.info("Memory usage: "
  164. f"{self.model_memory_usage / float(2**30):.2f} GiB")
  165. if self.lora_config:
  166. assert hasattr(self.model, "supported_lora_modules"
  167. ) and self.model.supported_lora_modules, (
  168. "Model does not support LoRA")
  169. assert hasattr(
  170. self.model,
  171. "embedding_modules"), "Model does not have embedding_modules"
  172. assert hasattr(self.model, "embedding_padding_modules"
  173. ), "Model does not have embedding_padding_modules"
  174. self.lora_manager = LRUCacheWorkerLoRAManager(
  175. self.scheduler_config.max_num_seqs,
  176. self.scheduler_config.max_num_batched_tokens,
  177. self.vocab_size,
  178. self.lora_config,
  179. self.device,
  180. self.model.embedding_modules,
  181. self.model.embedding_padding_modules,
  182. max_position_embeddings=self.model.config.
  183. max_position_embeddings,
  184. )
  185. self.model = self.lora_manager.create_lora_manager(self.model)
  186. if self.kv_cache_dtype == "fp8" and is_hip():
  187. # Currently only ROCm accepts kv-cache scaling factors
  188. # via quantization_param_path and this will be deprecated
  189. # in the future.
  190. if self.model_config.quantization_param_path is not None:
  191. if callable(getattr(self.model, "load_kv_cache_scales", None)):
  192. warnings.warn(
  193. "Loading kv cache scaling factor from JSON is "
  194. "deprecated and will be removed. Please include "
  195. "kv cache scaling factors in the model checkpoint.",
  196. FutureWarning,
  197. stacklevel=2)
  198. self.model.load_kv_cache_scales(
  199. self.model_config.quantization_param_path)
  200. logger.info(
  201. "Loaded KV cache scaling factors from ",
  202. f"{self.model_config.quantization_param_path}")
  203. else:
  204. raise RuntimeError(
  205. "Using FP8 KV cache and scaling factors provided but "
  206. f"model {self.model.__class__} does not support loading"
  207. " scaling factors.", )
  208. else:
  209. logger.warning(
  210. "Using FP8 KV cache but no scaling factors "
  211. "provided. Defaulting to scaling factors of 1.0. "
  212. "This may lead to less accurate results!")
  213. def save_sharded_state(
  214. self,
  215. path: str,
  216. pattern: Optional[str] = None,
  217. max_size: Optional[int] = None,
  218. ) -> None:
  219. from aphrodite.modeling.model_loader.loader import ShardedStateLoader
  220. ShardedStateLoader.save_model(
  221. self.model,
  222. path,
  223. pattern=pattern,
  224. max_size=max_size,
  225. )
  226. def get_max_block_per_batch(self) -> int:
  227. block_size = self.block_size
  228. return (self.max_seq_len_to_capture + block_size - 1) // block_size
  229. def _prepare_model_input(
  230. self,
  231. seq_group_metadata_list: List[SequenceGroupMetadata],
  232. ) -> ModelInput:
  233. """Prepare the model input based on a given sequence group.
  234. The API assumes seq_group_metadata_list is sorted by prefill -> decode.
  235. The result tensors and data structure also batches input in prefill
  236. -> decode order. For example,
  237. - input_tokens[:num_prefill_tokens] contains prefill tokens.
  238. - input_tokens[num_prefill_tokens:] contains decode tokens.
  239. If cuda graph is required, this API automatically pads inputs.
  240. """
  241. input_tokens: List[int] = []
  242. input_positions: List[int] = []
  243. slot_mapping: List[int] = []
  244. lora_index_mapping: List[int] = []
  245. lora_prompt_mapping: List[int] = []
  246. lora_requests: Set[LoRARequest] = set()
  247. seq_lens: List[int] = []
  248. prefill_seq_lens: List[int] = []
  249. decode_seq_lens: List[int] = []
  250. context_lens: List[int] = []
  251. query_lens: List[int] = []
  252. block_tables: List[List[int]] = []
  253. multi_modal_kwargs_list: Dict[str,
  254. List[torch.Tensor]] = defaultdict(list)
  255. decode_only = True
  256. num_prefills = 0
  257. num_prefill_tokens = 0
  258. num_decode_tokens = 0
  259. # The following fields are only for flashinfer
  260. # Please follow https://docs.flashinfer.ai/tutorials/kv_layout.html#page-layout
  261. # for the precise definition of the following fields.
  262. # An example:
  263. # request 1, page indices [0, 5, 8]
  264. # request 2, page indices [1, 6, 7]
  265. # request 3, page indices [3, 4]
  266. # paged_kv_indices is a concatenation of page indices of all requests:
  267. # [0, 5, 8, 1, 6, 7, 3, 4]
  268. # paged_kv_indptr is used to index into paged_kv_indices:
  269. # [0, 3, 6, 8]
  270. paged_kv_indices: List[int] = []
  271. # 0 at the beginning of paged_kv_indptr indicates the start of the
  272. # first request’s page indices in the paged_kv_indices list.
  273. paged_kv_indptr: List[int] = [0]
  274. # paged_kv_last_page_len is the length of the last page of each request
  275. paged_kv_last_page_len: List[int] = []
  276. if len(seq_group_metadata_list) == 0:
  277. return ModelInput.empty(self.device)
  278. if self.sliding_window is not None:
  279. sliding_window_blocks = (self.sliding_window + self.block_size -
  280. 1) // self.block_size
  281. block_aligned_sliding_window = \
  282. sliding_window_blocks * self.block_size
  283. for seq_group_metadata in seq_group_metadata_list:
  284. seq_ids = list(seq_group_metadata.seq_data.keys())
  285. is_prompt = seq_group_metadata.is_prompt
  286. for seq_id in seq_ids:
  287. computed_block_nums = seq_group_metadata.computed_block_nums
  288. if (self.scheduler_config is not None
  289. and self.scheduler_config.chunked_prefill_enabled
  290. and not (computed_block_nums is None
  291. or computed_block_nums == [])):
  292. raise RuntimeError(
  293. "chunked prefill cannot be used with prefix caching "
  294. "now.")
  295. seq_data = seq_group_metadata.seq_data[seq_id]
  296. if is_prompt:
  297. context_len = seq_data.get_num_computed_tokens()
  298. else:
  299. # get_num_computed_tokens is incorrect for spec decoding.
  300. # So, we should have a special logic here.
  301. # TODO: Fix it.
  302. context_len = seq_data.get_len() - 1
  303. seq_len = min(
  304. seq_data.get_len(),
  305. context_len + seq_group_metadata.token_chunk_size)
  306. if is_prompt:
  307. tokens = seq_data.get_token_ids()[context_len:seq_len]
  308. else:
  309. # Optimization. get_token_ids requires the entire copy of
  310. # tokens.
  311. tokens = [seq_data.get_last_token_id()]
  312. # Prefix cache was hit.
  313. # Prefix is not supported with sliding_window
  314. prefix_cache_hit = (computed_block_nums is not None
  315. and len(computed_block_nums) > 0
  316. and self.sliding_window is None
  317. and is_prompt)
  318. # These are seq_len/context_len capped to the sliding window.
  319. # They are passed to decode kernel.
  320. # We still need original seq_len/context_len to compute slot
  321. # mapping (and input position) below.
  322. curr_sliding_window_blocks = None
  323. sliding_seq_len = seq_len
  324. sliding_context_len = context_len
  325. # TODO: This is a hack to make sliding window work with
  326. # paged attn. We can remove it if we make paged attn kernel
  327. # to properly handle slinding window attn.
  328. if (self.sliding_window is not None and not is_prompt):
  329. curr_sliding_window_blocks = sliding_window_blocks
  330. if self.scheduler_config.use_v2_block_manager:
  331. # number of elements in last block
  332. suff_len = seq_len % self.block_size
  333. sliding_seq_len = min(
  334. seq_len, block_aligned_sliding_window + suff_len)
  335. if suff_len > 0:
  336. curr_sliding_window_blocks += 1
  337. else:
  338. sliding_seq_len = min(seq_len, self.sliding_window)
  339. sliding_context_len = sliding_seq_len - 1
  340. # TODO: Combine chunked prefill and prefix caching by
  341. # only allowing multiple of block_size chunk size.
  342. # NOTE: This only works for oooooooxxx style attention.
  343. if prefix_cache_hit:
  344. assert computed_block_nums is not None
  345. context_len = len(computed_block_nums) * self.block_size
  346. tokens = tokens[context_len:]
  347. # need to think what to set it to when we have both sliding
  348. # window and prefix caching...
  349. assert self.sliding_window is None, \
  350. "Prefix caching is not supported with sliding window"
  351. sliding_context_len = context_len
  352. if self.attn_backend.get_name() == "flash-attn":
  353. # NOTE: For flash-attn, the block table should
  354. # include the entries for the incoming prefill tokens.
  355. # TODO: This is a temporary fix. We should
  356. # provide a unified interface for different backends.
  357. block_table = seq_group_metadata.block_tables[seq_id]
  358. else:
  359. block_table = computed_block_nums
  360. elif (self.scheduler_config.chunked_prefill_enabled
  361. or not is_prompt):
  362. if seq_group_metadata.block_tables is not None:
  363. # chunked prefill or decode
  364. block_table = seq_group_metadata.block_tables[seq_id]
  365. if curr_sliding_window_blocks is not None:
  366. block_table = block_table[
  367. -curr_sliding_window_blocks:]
  368. if self.attn_backend.get_name() == "flashinfer":
  369. paged_kv_indices.extend(block_table)
  370. paged_kv_indptr.append(paged_kv_indptr[-1] +
  371. len(block_table))
  372. last_page_len = seq_data.get_len(
  373. ) % self.block_size
  374. if last_page_len == 0:
  375. last_page_len = self.block_size
  376. paged_kv_last_page_len.append(last_page_len)
  377. else:
  378. # Only happens when memory profiling runs.
  379. block_table = []
  380. else:
  381. # Prefill without chunked prefill or memory profiling.
  382. block_table = []
  383. block_tables.append(block_table)
  384. seq_lens.append(sliding_seq_len)
  385. context_lens.append(sliding_context_len)
  386. query_len = sliding_seq_len - sliding_context_len
  387. query_lens.append(query_len)
  388. input_tokens.extend(tokens)
  389. input_positions.extend(list(range(context_len, seq_len)))
  390. lora_id = seq_group_metadata.lora_int_id
  391. if is_prompt:
  392. assert len(seq_ids) == 1
  393. num_prefills += 1
  394. num_prefill_tokens += len(tokens)
  395. decode_only = False
  396. prefill_seq_lens.append(seq_len)
  397. else:
  398. assert query_len == 1, (
  399. "seq_len: {}, context_len: {}, query_len: {}".format(
  400. seq_len, context_len, query_len))
  401. num_decode_tokens += query_len
  402. decode_seq_lens.append(sliding_seq_len)
  403. if lora_id > 0:
  404. lora_requests.add(seq_group_metadata.lora_request)
  405. lora_index_mapping += [lora_id] * query_len
  406. lora_prompt_mapping.extend(
  407. [lora_id] *
  408. (query_len if seq_group_metadata.sampling_params
  409. and seq_group_metadata.sampling_params.prompt_logprobs
  410. is not None else 1))
  411. mm_data = seq_group_metadata.multi_modal_data
  412. if mm_data is not None:
  413. # Process multi-modal data
  414. if self.multi_modal_input_processor is None:
  415. raise ValueError(
  416. "Multi-modal inputs are only supported by "
  417. "vision language models.")
  418. mm_kwargs = self.multi_modal_input_processor(mm_data)
  419. for k, v in mm_kwargs.items():
  420. multi_modal_kwargs_list[k].append(v)
  421. if _is_block_tables_empty(seq_group_metadata.block_tables):
  422. # During memory profiling, the block tables are not
  423. # initialized yet. In this case, we just use a dummy
  424. # slot mapping.
  425. # In embeddings, the block tables are {seq_id: None}.
  426. slot_mapping.extend([_PAD_SLOT_ID] * seq_len)
  427. continue
  428. # Compute the slot mapping.
  429. block_table = seq_group_metadata.block_tables[seq_id]
  430. # Mask the [0, start_idx) tokens of the prompt with
  431. # _PAD_SLOT_ID, where start_idx is max(0, seq_len -
  432. # sliding_window). For example, if the prompt len is 10,
  433. # sliding window is 8, and block size is 4, the first two
  434. # tokens are masked and the slot mapping will be
  435. # [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
  436. start_idx = 0
  437. if self.sliding_window is not None:
  438. if is_prompt:
  439. assert self.scheduler_config.use_v2_block_manager \
  440. or context_len == 0, (
  441. "Prefix caching is currently not supported with "
  442. "sliding window attention in V1 block manager")
  443. # It is an optimization. When it is decoding, it is always
  444. # 0. When prefill, we use it to not write slots to kv cache
  445. # to save memory.
  446. start_idx = max(0, query_len - self.sliding_window)
  447. for i in range(context_len, seq_len):
  448. if i < start_idx:
  449. slot_mapping.append(_PAD_SLOT_ID)
  450. continue
  451. block_number = block_table[i // self.block_size]
  452. block_offset = i % self.block_size
  453. slot = block_number * self.block_size + block_offset
  454. slot_mapping.append(slot)
  455. batch_size = len(input_tokens)
  456. max_query_len = max(query_lens)
  457. max_prefill_seq_len = max(prefill_seq_lens, default=0)
  458. max_decode_seq_len = max(decode_seq_lens, default=0)
  459. # If cuda graph can be used, pad tensors accordingly.
  460. # See `capture_model` API for more details.
  461. # Aphrodite uses cuda graph only for decoding requests.
  462. use_captured_graph = (
  463. decode_only and not self.model_config.enforce_eager
  464. and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]
  465. and max_decode_seq_len <= self.max_seq_len_to_capture)
  466. if use_captured_graph:
  467. graph_batch_size = _get_graph_batch_size(batch_size)
  468. assert graph_batch_size >= batch_size
  469. for _ in range(graph_batch_size - batch_size):
  470. input_tokens.append(0)
  471. input_positions.append(0)
  472. slot_mapping.append(_PAD_SLOT_ID)
  473. seq_lens.append(1)
  474. block_tables.append([])
  475. lora_index_mapping.append(0)
  476. batch_size = graph_batch_size
  477. num_decode_tokens = batch_size
  478. if use_captured_graph:
  479. # The shape of graph_block_tables is
  480. # [max batch size, max context len // block size].
  481. input_block_tables = self.graph_block_tables[:batch_size]
  482. for i, block_table in enumerate(block_tables):
  483. if block_table:
  484. input_block_tables[i, :len(block_table)] = block_table
  485. block_tables = torch.tensor(input_block_tables, device=self.device)
  486. else:
  487. max_block_table_len = max(
  488. len(block_table) for block_table in block_tables)
  489. block_tables = make_tensor_with_pad(
  490. block_tables,
  491. max_len=max_block_table_len,
  492. pad=0,
  493. dtype=torch.int,
  494. device=self.device,
  495. )
  496. assert max_query_len > 0, ("query_lens: {}".format(query_lens))
  497. seq_lens_tensor = torch.tensor(seq_lens,
  498. dtype=torch.int,
  499. device=self.device)
  500. seq_start_loc = torch.zeros(seq_lens_tensor.shape[0] + 1,
  501. dtype=torch.int32,
  502. device=self.device)
  503. torch.cumsum(seq_lens_tensor,
  504. dim=0,
  505. dtype=seq_start_loc.dtype,
  506. out=seq_start_loc[1:])
  507. input_tokens_tensor = torch.tensor(input_tokens,
  508. dtype=torch.long,
  509. device=self.device)
  510. input_positions_tensor = torch.tensor(input_positions,
  511. dtype=torch.long,
  512. device=self.device)
  513. slot_mapping_tensor = torch.tensor(slot_mapping,
  514. dtype=torch.long,
  515. device=self.device)
  516. if self.attn_backend.get_name() == "flashinfer":
  517. if not hasattr(self, "flashinfer_workspace_buffer"):
  518. # Allocate 16MB workspace buffer
  519. # Follow the example of flashinfer: https://docs.flashinfer.ai/api/python/decode.html
  520. self.flashinfer_workspace_buffer = torch.empty(
  521. 16 * 1024 * 1024, dtype=torch.uint8, device=self.device)
  522. paged_kv_indptr_tensor = torch.tensor(paged_kv_indptr,
  523. dtype=torch.int,
  524. device=self.device)
  525. paged_kv_indices_tensor = torch.tensor(paged_kv_indices,
  526. dtype=torch.int,
  527. device=self.device)
  528. paged_kv_last_page_len_tensor = torch.tensor(
  529. paged_kv_last_page_len, dtype=torch.int, device=self.device)
  530. kv_cache_dtype = get_kv_cache_torch_dtype(self.kv_cache_dtype,
  531. self.model_config.dtype)
  532. attn_metadata = self.attn_backend.make_metadata(
  533. num_prefills=num_prefills,
  534. slot_mapping=slot_mapping_tensor,
  535. num_prefill_tokens=num_prefill_tokens,
  536. num_decode_tokens=num_decode_tokens,
  537. use_cuda_graph=False,
  538. max_prefill_seq_len=max_prefill_seq_len,
  539. block_tables=block_tables,
  540. workspace_buffer=self.flashinfer_workspace_buffer,
  541. paged_kv_indptr=paged_kv_indptr_tensor,
  542. paged_kv_indices=paged_kv_indices_tensor,
  543. paged_kv_last_page_len=paged_kv_last_page_len_tensor,
  544. num_qo_heads=self.model_config.get_num_attention_heads(
  545. self.parallel_config),
  546. num_kv_heads=self.model_config.get_num_kv_heads(
  547. self.parallel_config),
  548. head_dim=self.model_config.get_head_size(),
  549. page_size=16,
  550. seq_start_loc=seq_start_loc,
  551. data_type=kv_cache_dtype)
  552. else:
  553. context_lens_tensor = torch.tensor(context_lens,
  554. dtype=torch.int,
  555. device=self.device)
  556. query_lens_tensor = torch.tensor(query_lens,
  557. dtype=torch.long,
  558. device=self.device)
  559. query_start_loc = torch.zeros(query_lens_tensor.shape[0] + 1,
  560. dtype=torch.int32,
  561. device=self.device)
  562. torch.cumsum(query_lens_tensor,
  563. dim=0,
  564. dtype=query_start_loc.dtype,
  565. out=query_start_loc[1:])
  566. attn_metadata = self.attn_backend.make_metadata(
  567. num_prefills=num_prefills,
  568. slot_mapping=slot_mapping_tensor,
  569. num_prefill_tokens=num_prefill_tokens,
  570. num_decode_tokens=num_decode_tokens,
  571. seq_lens=seq_lens,
  572. seq_lens_tensor=seq_lens_tensor,
  573. max_query_len=max_query_len,
  574. max_prefill_seq_len=max_prefill_seq_len,
  575. max_decode_seq_len=max_decode_seq_len,
  576. query_start_loc=query_start_loc,
  577. seq_start_loc=seq_start_loc,
  578. context_lens_tensor=context_lens_tensor,
  579. block_tables=block_tables,
  580. use_cuda_graph=use_captured_graph,
  581. )
  582. if self.lora_config:
  583. lora_mapping = LoRAMapping(
  584. lora_index_mapping,
  585. lora_prompt_mapping,
  586. )
  587. else:
  588. lora_mapping = None
  589. multi_modal_kwargs = {
  590. k: torch.cat(v, dim=0).to(self.device)
  591. for k, v in multi_modal_kwargs_list.items()
  592. }
  593. return ModelInput(
  594. input_tokens=input_tokens_tensor,
  595. input_positions=input_positions_tensor,
  596. attn_metadata=attn_metadata,
  597. seq_lens=seq_lens,
  598. query_lens=query_lens,
  599. lora_mapping=lora_mapping,
  600. lora_requests=lora_requests,
  601. multi_modal_kwargs=multi_modal_kwargs,
  602. slot_mapping=slot_mapping_tensor,
  603. num_prefill_tokens=num_prefill_tokens,
  604. num_decode_tokens=num_decode_tokens,
  605. num_prefills=num_prefills,
  606. )
  607. def prepare_input_tensors(
  608. self,
  609. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],
  610. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, SamplingMetadata,
  611. Set[LoRARequest], LoRAMapping, Dict[str, torch.Tensor]]:
  612. if self.is_driver_worker:
  613. assert seq_group_metadata_list is not None
  614. # Prepare input tensors.
  615. (
  616. input_tokens,
  617. input_positions,
  618. attn_metadata,
  619. seq_lens,
  620. query_lens,
  621. lora_mapping,
  622. lora_requests,
  623. multi_modal_kwargs,
  624. slot_mapping,
  625. num_prefill_tokens,
  626. num_decode_tokens,
  627. num_prefills,
  628. ) = self._prepare_model_input(seq_group_metadata_list)
  629. sampling_metadata = SamplingMetadata.prepare(
  630. seq_group_metadata_list, seq_lens, query_lens, self.device,
  631. self.pin_memory)
  632. metadata_dict = {
  633. "input_tokens": input_tokens,
  634. "input_positions": input_positions,
  635. "selected_token_indices":
  636. sampling_metadata.selected_token_indices,
  637. "lora_requests": lora_requests,
  638. "lora_mapping": lora_mapping,
  639. "multi_modal_kwargs": multi_modal_kwargs,
  640. "num_prefill_tokens": num_prefill_tokens,
  641. "num_decode_tokens": num_decode_tokens,
  642. "slot_mapping": slot_mapping,
  643. "num_prefills": num_prefills,
  644. }
  645. if attn_metadata:
  646. metadata_dict.update(attn_metadata.asdict_zerocopy())
  647. broadcast_tensor_dict(metadata_dict, src=0)
  648. else:
  649. metadata_dict = broadcast_tensor_dict(src=0)
  650. input_tokens = metadata_dict.pop("input_tokens")
  651. input_positions = metadata_dict.pop("input_positions")
  652. selected_token_indices = metadata_dict.pop(
  653. "selected_token_indices")
  654. lora_mapping = metadata_dict.pop("lora_mapping")
  655. lora_requests = metadata_dict.pop("lora_requests")
  656. multi_modal_kwargs = metadata_dict.pop("multi_modal_kwargs")
  657. if metadata_dict:
  658. attn_metadata = self.attn_backend.make_metadata(
  659. **metadata_dict)
  660. else:
  661. attn_metadata = None
  662. sampling_metadata = SamplingMetadata(
  663. seq_groups=None,
  664. selected_token_indices=selected_token_indices,
  665. categorized_sample_indices=None,
  666. num_prompts=0,
  667. )
  668. return (input_tokens, input_positions, attn_metadata,
  669. sampling_metadata, lora_requests, lora_mapping,
  670. multi_modal_kwargs)
  671. @torch.inference_mode()
  672. def execute_model(
  673. self,
  674. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],
  675. kv_caches: List[torch.Tensor],
  676. ) -> Optional[SamplerOutput]:
  677. (input_tokens, input_positions, attn_metadata, sampling_metadata,
  678. lora_requests, lora_mapping, multi_modal_kwargs
  679. ) = self.prepare_input_tensors(seq_group_metadata_list)
  680. if self.lora_config:
  681. self.set_active_loras(lora_requests, lora_mapping)
  682. # Currently cuda graph is only supported by the decode phase.
  683. prefill_meta = attn_metadata.prefill_metadata
  684. decode_meta = attn_metadata.decode_metadata
  685. if prefill_meta is None and decode_meta.use_cuda_graph:
  686. graph_batch_size = input_tokens.shape[0]
  687. model_executable = self.graph_runners[graph_batch_size]
  688. else:
  689. model_executable = self.model
  690. hidden_states = model_executable(
  691. input_ids=input_tokens,
  692. positions=input_positions,
  693. kv_caches=kv_caches,
  694. attn_metadata=attn_metadata,
  695. **multi_modal_kwargs,
  696. )
  697. # Compute the logits.
  698. logits = self.model.compute_logits(hidden_states, sampling_metadata)
  699. # Only perform sampling in the driver worker.
  700. if not self.is_driver_worker:
  701. return None
  702. # Sample the next token.
  703. output = self.model.sample(
  704. logits=logits,
  705. sampling_metadata=sampling_metadata,
  706. )
  707. return output
  708. @torch.inference_mode()
  709. def profile_run(self) -> None:
  710. # Enable top-k sampling to reflect the accurate memory usage.
  711. sampling_params = SamplingParams(top_p=0.99, top_k=self.vocab_size - 1)
  712. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  713. max_num_seqs = self.scheduler_config.max_num_seqs
  714. # This represents the maximum number of different requests
  715. # that will have unique loras, an therefore the max amount of memory
  716. # consumption create dummy lora request copies from the lora request
  717. # passed in, which contains a lora from the lora warmup path.
  718. dummy_lora_requests = []
  719. dummy_lora_requests_per_seq = []
  720. if self.lora_config:
  721. assert self.lora_manager is not None
  722. with self.lora_manager.dummy_lora_cache():
  723. for idx in range(self.lora_config.max_loras):
  724. lora_id = idx + 1
  725. dummy_lora_request = LoRARequest(
  726. lora_name=f"warmup_{lora_id}",
  727. lora_int_id=lora_id,
  728. lora_local_path="/not/a/real/path",
  729. )
  730. self.lora_manager.add_dummy_lora(dummy_lora_request,
  731. rank=LORA_WARMUP_RANK)
  732. dummy_lora_requests.append(dummy_lora_request)
  733. dummy_lora_requests_per_seq = [
  734. dummy_lora_requests[idx % len(dummy_lora_requests)]
  735. for idx in range(max_num_seqs)
  736. ]
  737. # Profile memory usage with max_num_sequences sequences and the total
  738. # number of tokens equal to max_num_batched_tokens.
  739. seqs: List[SequenceGroupMetadata] = []
  740. # Additional GPU memory may be needed for vision encoding, which needs
  741. # to be accounted for when calculating the GPU blocks for
  742. # Aphrodite blocker manager.
  743. # To exercise the worst scenario for GPU memory consumption,
  744. # the number of seqs (batch_size) is chosen to maximize the number
  745. # of images processed.
  746. model_config = self.model_config
  747. vlm_config = self.vision_language_config
  748. if vlm_config:
  749. max_num_seqs = min(
  750. max_num_seqs,
  751. int(max_num_batched_tokens / vlm_config.image_feature_size))
  752. for group_id in range(max_num_seqs):
  753. seq_len = (max_num_batched_tokens // max_num_seqs +
  754. (group_id < max_num_batched_tokens % max_num_seqs))
  755. if vlm_config is None:
  756. seq_data = SequenceData([0] * seq_len)
  757. dummy_multi_modal_data = None
  758. else:
  759. seq_data, dummy_multi_modal_data = MULTIMODAL_REGISTRY \
  760. .dummy_data_for_profiling(seq_len, model_config, vlm_config)
  761. seq = SequenceGroupMetadata(
  762. request_id=str(group_id),
  763. is_prompt=True,
  764. seq_data={group_id: seq_data},
  765. sampling_params=sampling_params,
  766. block_tables=None,
  767. lora_request=dummy_lora_requests_per_seq[group_id]
  768. if dummy_lora_requests_per_seq else None,
  769. multi_modal_data=dummy_multi_modal_data,
  770. )
  771. seqs.append(seq)
  772. # Run the model with the dummy inputs.
  773. num_layers = self.model_config.get_num_layers(self.parallel_config)
  774. kv_caches = [None] * num_layers
  775. self.execute_model(seqs, kv_caches)
  776. torch.cuda.synchronize()
  777. return
  778. def remove_all_loras(self):
  779. if not self.lora_manager:
  780. raise RuntimeError("LoRA is not enabled.")
  781. self.lora_manager.remove_all_loras()
  782. def set_active_loras(self, lora_requests: Set[LoRARequest],
  783. lora_mapping: LoRAMapping) -> None:
  784. if not self.lora_manager:
  785. raise RuntimeError("LoRA is not enabled.")
  786. self.lora_manager.set_active_loras(lora_requests, lora_mapping)
  787. def add_lora(self, lora_request: LoRARequest) -> bool:
  788. if not self.lora_manager:
  789. raise RuntimeError("LoRA is not enabled.")
  790. return self.lora_manager.add_lora(lora_request)
  791. def remove_lora(self, lora_id: int) -> bool:
  792. if not self.lora_manager:
  793. raise RuntimeError("LoRA is not enabled.")
  794. return self.lora_manager.remove_lora(lora_id)
  795. def list_loras(self) -> Set[int]:
  796. if not self.lora_manager:
  797. raise RuntimeError("LoRA is not enabled.")
  798. return self.lora_manager.list_loras()
  799. @torch.inference_mode()
  800. def capture_model(self, kv_caches: List[torch.Tensor]) -> None:
  801. """Cuda graph capture a model.
  802. Note that CUDA graph's performance gain is negligible if number
  803. of batched tokens are larger than 200. And since CUDA graph
  804. requires fixed sized tensors, supporting large/variable batch
  805. size requires high GPU memory overhead. Thus, Aphrodite only captures
  806. decoding requests. Mixed batch (chunked prefill + decoding) or
  807. prefill requests are not captured.
  808. Since it is used for decoding-only, it assumes there's only 1 token
  809. per sequence in the batch.
  810. """
  811. assert not self.model_config.enforce_eager
  812. logger.info("Capturing the model for CUDA graphs. This may lead to "
  813. "unexpected consequences if the model is not static. To "
  814. "run the model in eager mode, set 'enforce_eager=True' or "
  815. "use '--enforce-eager' in the CLI.")
  816. logger.info("CUDA graphs can take additional 1~3 GiB memory per GPU. "
  817. "If you are running out of memory, consider decreasing "
  818. "`gpu_memory_utilization` or enforcing eager mode. "
  819. "You can also reduce the `max_num_seqs` as needed "
  820. "to decrease memory usage.")
  821. start_time = time.perf_counter()
  822. # Prepare dummy inputs. These will be reused for all batch sizes.
  823. max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)
  824. input_tokens = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  825. input_positions = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  826. slot_mapping = torch.empty(max_batch_size, dtype=torch.long).cuda()
  827. slot_mapping.fill_(_PAD_SLOT_ID)
  828. seq_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()
  829. block_tables = torch.from_numpy(self.graph_block_tables).cuda()
  830. # Prepare buffer for outputs. These will be reused for all batch sizes.
  831. # It will be filled after the first graph capture.
  832. hidden_states: Optional[torch.Tensor] = None
  833. graph_batch_size = _get_graph_batch_size(
  834. self.scheduler_config.max_num_seqs)
  835. batch_size_capture_list = [
  836. bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size
  837. ]
  838. with graph_capture() as graph_capture_context:
  839. # NOTE: Capturing the largest batch size first may help reduce the
  840. # memory usage of CUDA graph.
  841. for batch_size in reversed(batch_size_capture_list):
  842. # Create dummy attn_metadata.
  843. attn_metadata = self.attn_backend.make_metadata(
  844. num_prefills=0,
  845. num_prefill_tokens=0,
  846. num_decode_tokens=batch_size,
  847. slot_mapping=slot_mapping[:batch_size],
  848. seq_lens=None,
  849. seq_lens_tensor=seq_lens[:batch_size],
  850. max_query_len=None,
  851. max_prefill_seq_len=0,
  852. max_decode_seq_len=self.max_seq_len_to_capture,
  853. query_start_loc=None,
  854. seq_start_loc=None,
  855. context_lens_tensor=None,
  856. block_tables=block_tables[:batch_size],
  857. use_cuda_graph=True,
  858. )
  859. if self.lora_config:
  860. lora_mapping = LoRAMapping(
  861. [0] * batch_size,
  862. [0] * batch_size,
  863. )
  864. self.set_active_loras(set(), lora_mapping)
  865. graph_runner = CUDAGraphRunner(self.model)
  866. hidden_states = graph_runner.capture(
  867. input_tokens[:batch_size],
  868. input_positions[:batch_size],
  869. hidden_states[:batch_size]
  870. if hidden_states is not None else None,
  871. kv_caches,
  872. attn_metadata,
  873. memory_pool=self.graph_memory_pool,
  874. stream=graph_capture_context.stream,
  875. )
  876. self.graph_memory_pool = graph_runner.graph.pool()
  877. self.graph_runners[batch_size] = graph_runner
  878. end_time = time.perf_counter()
  879. elapsed_time = end_time - start_time
  880. # This usually takes < 10 seconds.
  881. logger.info(f"Graph capturing finished in {elapsed_time} secs.")
  882. @property
  883. def vocab_size(self) -> int:
  884. return self.model_config.get_vocab_size()
  885. class CUDAGraphRunner:
  886. def __init__(self, model: nn.Module):
  887. self.model = model
  888. self.input_buffers: Dict[str, torch.Tensor] = {}
  889. self.output_buffers: Dict[str, torch.Tensor] = {}
  890. self._graph: Optional[torch.cuda.CUDAGraph] = None
  891. @property
  892. def graph(self):
  893. assert self._graph is not None
  894. return self._graph
  895. def capture(
  896. self,
  897. input_ids: torch.Tensor,
  898. positions: torch.Tensor,
  899. hidden_states: Optional[torch.Tensor],
  900. kv_caches: List[torch.Tensor],
  901. attn_metadata: AttentionMetadata,
  902. memory_pool: Optional[Tuple[int, int]],
  903. stream: torch.cuda.Stream,
  904. **kwargs,
  905. ) -> torch.Tensor:
  906. assert self._graph is None
  907. # Run the model a few times without capturing the graph.
  908. # This is to make sure that the captured graph does not include the
  909. # kernel launches for initial benchmarking (e.g., Triton autotune).
  910. # Note one iteration is not enough for torch.jit.script
  911. for _ in range(_NUM_WARMUP_ITERS):
  912. self.model(
  913. input_ids,
  914. positions,
  915. kv_caches,
  916. attn_metadata,
  917. **kwargs,
  918. )
  919. torch.cuda.synchronize()
  920. # Capture the graph.
  921. self._graph = torch.cuda.CUDAGraph()
  922. with torch.cuda.graph(self._graph, pool=memory_pool, stream=stream):
  923. output_hidden_states = self.model(
  924. input_ids,
  925. positions,
  926. kv_caches,
  927. attn_metadata,
  928. **kwargs,
  929. )
  930. if hidden_states is not None:
  931. hidden_states.copy_(output_hidden_states)
  932. else:
  933. hidden_states = output_hidden_states
  934. del output_hidden_states
  935. # make sure `output_hidden_states` is deleted
  936. # in the graph's memory pool
  937. gc.collect()
  938. torch.cuda.synchronize()
  939. # Save the input and output buffers.
  940. self.input_buffers = {
  941. "input_ids": input_ids,
  942. "positions": positions,
  943. "kv_caches": kv_caches,
  944. "slot_mapping": attn_metadata.slot_mapping,
  945. "seq_lens_tensor": attn_metadata.decode_metadata.seq_lens_tensor,
  946. "block_tables": attn_metadata.decode_metadata.block_tables,
  947. }
  948. self.output_buffers = {"hidden_states": hidden_states}
  949. return hidden_states
  950. def forward(
  951. self,
  952. input_ids: torch.Tensor,
  953. positions: torch.Tensor,
  954. kv_caches: List[torch.Tensor],
  955. attn_metadata: AttentionMetadata,
  956. **kwargs,
  957. ) -> torch.Tensor:
  958. # KV caches are fixed tensors, so we don't need to copy them.
  959. del kv_caches
  960. # Copy the input tensors to the input buffers.
  961. self.input_buffers["input_ids"].copy_(input_ids, non_blocking=True)
  962. self.input_buffers["positions"].copy_(positions, non_blocking=True)
  963. self.input_buffers["slot_mapping"].copy_(attn_metadata.slot_mapping,
  964. non_blocking=True)
  965. self.input_buffers["seq_lens_tensor"].copy_(
  966. attn_metadata.decode_metadata.seq_lens_tensor, non_blocking=True)
  967. self.input_buffers["block_tables"].copy_(
  968. attn_metadata.decode_metadata.block_tables, non_blocking=True)
  969. # Run the graph.
  970. self.graph.replay()
  971. # Return the output tensor.
  972. return self.output_buffers["hidden_states"]
  973. def __call__(self, *args, **kwargs):
  974. return self.forward(*args, **kwargs)
  975. def _get_graph_batch_size(batch_size: int) -> int:
  976. """Returns the padded batch size given actual batch size.
  977. Batch sizes are 1, 2, 4, _BATCH_SIZE_ALIGNMENT,
  978. 2*_BATCH_SIZE_ALIGNMENT, 3*_BATCH_SIZE_ALIGNMENT...
  979. """
  980. if batch_size <= 2:
  981. return batch_size
  982. elif batch_size <= 4:
  983. return 4
  984. else:
  985. return ((batch_size + _BATCH_SIZE_ALIGNMENT - 1) //
  986. _BATCH_SIZE_ALIGNMENT * _BATCH_SIZE_ALIGNMENT)
  987. def _is_block_tables_empty(block_tables: Union[None, Dict]):
  988. """
  989. Check if block_tables is None or a dictionary with all None values.
  990. """
  991. if block_tables is None:
  992. return True
  993. if isinstance(block_tables, dict) and all(
  994. value is None for value in block_tables.values()):
  995. return True
  996. return False