model_runner.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. import contextlib
  2. import time
  3. from enum import IntEnum
  4. from typing import Dict, List, NamedTuple, Optional, Set, Tuple
  5. import numpy as np
  6. import torch
  7. import torch.nn as nn
  8. from loguru import logger
  9. from aphrodite.attention import (AttentionMetadata, AttentionMetadataPerStage,
  10. get_attn_backend)
  11. from aphrodite.common.config import (DeviceConfig, LoRAConfig, ModelConfig,
  12. ParallelConfig, SchedulerConfig,
  13. VisionLanguageConfig)
  14. from aphrodite.common.logger import get_loading_progress_bar
  15. from aphrodite.common.sampling_params import SamplingParams, SamplingType
  16. from aphrodite.common.sequence import (MultiModalData, SamplerOutput,
  17. SequenceData, SequenceGroupMetadata)
  18. from aphrodite.common.utils import (CudaMemoryProfiler, async_tensor_h2d,
  19. is_hip, is_pin_memory_available,
  20. make_tensor_with_pad, maybe_expand_dim)
  21. from aphrodite.distributed import (broadcast_tensor_dict,
  22. get_tensor_model_parallel_world_size,
  23. with_pynccl_for_all_reduce)
  24. from aphrodite.distributed.device_communicators import (custom_all_reduce,
  25. pynccl_utils)
  26. from aphrodite.lora.layers import LoRAMapping
  27. from aphrodite.lora.request import LoRARequest
  28. from aphrodite.lora.worker_manager import LRUCacheWorkerLoRAManager
  29. from aphrodite.modeling import SamplingMetadata
  30. from aphrodite.modeling.layers.mamba import RequestInfo
  31. from aphrodite.modeling.loader import get_model
  32. from aphrodite.modeling.sampling_metadata import PersistentMetadata
  33. _PAD_SLOT_ID = -1
  34. LORA_WARMUP_RANK = 8
  35. _BATCH_SIZE_ALIGNMENT = 8
  36. # Capture graphs for token size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.
  37. # NOTE: _get_graph_batch_size needs to be updated if this list is changed.
  38. _BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [
  39. _BATCH_SIZE_ALIGNMENT * i for i in range(1, 33)
  40. ]
  41. class PreparePromptMetadata(NamedTuple):
  42. input_tokens: List[int]
  43. input_positions: List[int]
  44. attn_metadata: Optional[AttentionMetadataPerStage]
  45. prompt_lens: List[int]
  46. subquery_lens: List[int]
  47. lora_index_mapping: List[int]
  48. lora_prompt_mapping: List[int]
  49. lora_requests: Set[LoRARequest]
  50. multi_modal_input: Optional[torch.Tensor]
  51. slot_mapping: List[int]
  52. @classmethod
  53. def empty(cls):
  54. return PreparePromptMetadata(
  55. input_tokens=[],
  56. input_positions=[],
  57. attn_metadata=None,
  58. prompt_lens=[],
  59. subquery_lens=[],
  60. lora_index_mapping=[],
  61. lora_prompt_mapping=[],
  62. lora_requests=set(),
  63. multi_modal_input=None,
  64. slot_mapping=[],
  65. )
  66. class PrepareDecodeMetadata(NamedTuple):
  67. input_tokens: List[int]
  68. input_positions: List[int]
  69. attn_metadata: Optional[AttentionMetadata]
  70. lora_index_mapping: List[int]
  71. lora_prompt_mapping: List[int]
  72. lora_requests: Set[LoRARequest]
  73. slot_mapping: List[int]
  74. @classmethod
  75. def empty(cls):
  76. return PrepareDecodeMetadata(
  77. input_tokens=[],
  78. input_positions=[],
  79. attn_metadata=None,
  80. lora_index_mapping=[],
  81. lora_prompt_mapping=[],
  82. lora_requests=set(),
  83. slot_mapping=[],
  84. )
  85. # How batches are constructed.
  86. class BatchType(IntEnum):
  87. # Every batch is prefill.
  88. PREFILL = 0
  89. # Every batch is decode.
  90. DECODE = 1
  91. # Batch is a mixture of prefill and decode.
  92. MIXED = 2
  93. class ModelRunner:
  94. def __init__(
  95. self,
  96. model_config: ModelConfig,
  97. parallel_config: ParallelConfig,
  98. scheduler_config: SchedulerConfig,
  99. device_config: DeviceConfig,
  100. lora_config: Optional[LoRAConfig],
  101. kv_cache_dtype: Optional[str] = "auto",
  102. is_driver_worker: bool = False,
  103. vision_language_config: Optional[VisionLanguageConfig] = None,
  104. ):
  105. self.model_config = model_config
  106. self.parallel_config = parallel_config
  107. self.scheduler_config = scheduler_config
  108. self.lora_config = lora_config
  109. self.is_driver_worker = is_driver_worker
  110. # model_config can be None in tests/samplers/test_sampler.py.
  111. # FIXME: This is a hack to make the tests work. Refactor this.
  112. self.sliding_window = (model_config.get_sliding_window()
  113. if model_config is not None else None)
  114. self.device_config = (device_config
  115. if device_config is not None else DeviceConfig())
  116. self.device = self.device_config.device
  117. self.model = None
  118. self.block_size = None # Set after initial profiling.
  119. self.lora_manager = None
  120. self.graph_runners: Dict[int, CUDAGraphRunner] = {}
  121. self.graph_memory_pool = None # Set during graph capture.
  122. self.max_context_len_to_capture = (
  123. self.model_config.max_context_len_to_capture
  124. if self.model_config is not None else 0)
  125. # When using CUDA graph, the input block tables must be padded to
  126. # max_context_len_to_capture. However, creating the block table in
  127. # Python can be expensive. To optimize this, we cache the block table
  128. # in numpy and only copy the actual input content at every iteration.
  129. # The shape of the cached block table will be
  130. # (max batch size to capture, max context len to capture / block size).
  131. self.graph_block_tables = None # Set after initial profiling.
  132. self.pin_memory = is_pin_memory_available()
  133. self.kv_cache_dtype = kv_cache_dtype
  134. self.vision_language_config = vision_language_config
  135. # cache in_wsl result
  136. self.is_mamba = self.model_config.hf_config.model_type == "jamba"
  137. self.mamba_cache = None
  138. self.mamba_cache4gc = None
  139. self.request2i: Dict[str, Dict[int, int]] = {}
  140. self.attn_backend = get_attn_backend(
  141. self.model_config.dtype if model_config is not None else None)
  142. @torch.inference_mode()
  143. def prepare_contiguous_mamba_cache(self, dtype):
  144. is_mamba = self.model_config.hf_config.model_type == "jamba"
  145. if not is_mamba or self.mamba_cache is not None:
  146. return
  147. hf_config = self.model_config.hf_config
  148. num_layers = hf_config.num_hidden_layers
  149. max_batch_size = _BATCH_SIZES_TO_CAPTURE[-1]
  150. world_size = get_tensor_model_parallel_world_size()
  151. conv_state_shape = (
  152. num_layers,
  153. max_batch_size,
  154. hf_config.mamba_expand * hf_config.hidden_size // world_size,
  155. hf_config.mamba_d_conv,
  156. )
  157. ssm_state_shape = (
  158. num_layers,
  159. max_batch_size,
  160. hf_config.mamba_expand * hf_config.hidden_size // world_size,
  161. hf_config.mamba_d_state,
  162. )
  163. if self.mamba_cache is None:
  164. self.mamba_cache = {}
  165. self.mamba_cache = (torch.empty(size=conv_state_shape,
  166. dtype=dtype,
  167. device="cuda"),
  168. torch.empty(size=ssm_state_shape,
  169. dtype=dtype,
  170. device="cuda"))
  171. self.mamba_cache4gc = (torch.empty(size=conv_state_shape,
  172. dtype=dtype,
  173. device="cuda"),
  174. torch.empty(size=ssm_state_shape,
  175. dtype=dtype,
  176. device="cuda"))
  177. def load_model(self) -> None:
  178. with CudaMemoryProfiler() as m:
  179. self.model = get_model(
  180. self.model_config,
  181. self.device_config,
  182. lora_config=self.lora_config,
  183. vision_language_config=self.vision_language_config,
  184. parallel_config=self.parallel_config,
  185. scheduler_config=self.scheduler_config)
  186. self.model_memory_usage = m.consumed_memory
  187. tp = get_tensor_model_parallel_world_size()
  188. logger.info(
  189. "Model weights loaded. Memory usage: "
  190. f"{self.model_memory_usage / float(2**30):.2f} GiB x {tp} = "
  191. f"{self.model_memory_usage * tp / float(2**30):.2f} GiB")
  192. if self.lora_config:
  193. assert hasattr(self.model, "supported_lora_modules"
  194. ) and self.model.supported_lora_modules, (
  195. "Model does not support LoRA")
  196. assert hasattr(
  197. self.model,
  198. "embedding_modules"), "Model does not have embedding_modules"
  199. assert hasattr(self.model, "embedding_padding_modules"
  200. ), "Model does not have embedding_padding_modules"
  201. self.lora_manager = LRUCacheWorkerLoRAManager(
  202. self.scheduler_config.max_num_seqs,
  203. self.scheduler_config.max_num_batched_tokens, self.vocab_size,
  204. self.lora_config, self.device, self.model.embedding_modules,
  205. self.model.embedding_padding_modules)
  206. self.model = self.lora_manager.create_lora_manager(self.model)
  207. if self.kv_cache_dtype == "fp8" and is_hip():
  208. # Currently scaled KV cache is only enabled on ROCm
  209. if self.model_config.quantization_param_path is not None:
  210. if callable(getattr(self.model, "load_kv_cache_scales", None)):
  211. self.model.load_kv_cache_scales(
  212. self.model_config.quantization_param_path)
  213. else:
  214. raise RuntimeError("Using FP8 KV cache and scaling "
  215. "factors provided but model "
  216. f"{self.model.__class__} does not "
  217. "support loading scaling factors.")
  218. else:
  219. logger.warning(
  220. "Using FP8 KV cache but no scaling factors "
  221. "provided. Defaulting to scaling factors of 1.0. "
  222. "This may lead to less accurate results!")
  223. elif self.model_config.quantization_param_path is not None:
  224. logger.warning("KV cache scaling factors provided, "
  225. "but the KV cache data type is not FP8. "
  226. "KV cache scaling factors will not be used.")
  227. def set_block_size(self, block_size: int) -> None:
  228. self.block_size = block_size
  229. self.graph_block_tables = np.zeros(
  230. (max(_BATCH_SIZES_TO_CAPTURE), self.get_max_block_per_batch()),
  231. dtype=np.int32)
  232. def get_max_block_per_batch(self) -> int:
  233. block_size = self.block_size
  234. return (self.max_context_len_to_capture + block_size - 1) // block_size
  235. def _prepare_prompt(
  236. self,
  237. seq_group_metadata_list: List[SequenceGroupMetadata],
  238. ) -> PreparePromptMetadata:
  239. input_tokens: List[int] = []
  240. input_positions: List[int] = []
  241. slot_mapping: List[int] = []
  242. lora_index_mapping: List[int] = []
  243. lora_prompt_mapping: List[int] = []
  244. lora_requests: Set[LoRARequest] = set()
  245. prompt_lens: List[int] = []
  246. context_lens: List[int] = []
  247. subquery_lens: List[int] = []
  248. prefix_block_tables: List[List[int]] = []
  249. multi_modal_input_list: List[torch.Tensor] = []
  250. if len(seq_group_metadata_list) == 0:
  251. return PreparePromptMetadata.empty()
  252. for seq_group_metadata in seq_group_metadata_list:
  253. assert seq_group_metadata.is_prompt
  254. seq_ids = list(seq_group_metadata.seq_data.keys())
  255. assert len(seq_ids) == 1
  256. seq_id = seq_ids[0]
  257. computed_block_nums = seq_group_metadata.computed_block_nums
  258. if (self.scheduler_config is not None
  259. and self.scheduler_config.chunked_prefill_enabled
  260. and not (computed_block_nums is None
  261. or computed_block_nums == [])):
  262. raise RuntimeError(
  263. "chunked prefill cannot be used with prefix caching "
  264. "now.")
  265. token_chunk_size = seq_group_metadata.token_chunk_size
  266. seq_data = seq_group_metadata.seq_data[seq_id]
  267. computed_len = seq_data.get_num_computed_tokens()
  268. # We should use get_len here because in case of preemption
  269. # it contains output tokens.
  270. prefill_end = min(seq_data.get_len(),
  271. computed_len + token_chunk_size)
  272. prompt_tokens = seq_data.get_token_ids()[computed_len:prefill_end]
  273. prompt_len = prefill_end
  274. prompt_lens.append(prompt_len)
  275. # NOTE: This only works for oooooooxxx style attention.
  276. if computed_block_nums is not None and len(
  277. computed_block_nums) > 0 and self.sliding_window is None:
  278. # Prefix is not supported with sliding_window
  279. computed_len = len(computed_block_nums) * self.block_size
  280. prompt_tokens = prompt_tokens[computed_len:]
  281. prefix_block_tables.append(computed_block_nums)
  282. elif self.scheduler_config.chunked_prefill_enabled:
  283. if seq_group_metadata.block_tables is not None:
  284. # Prefill has chunked before.
  285. block_table = seq_group_metadata.block_tables[seq_id]
  286. prefix_block_tables.append(block_table)
  287. else:
  288. # The first prefill.
  289. prefix_block_tables.append([])
  290. else:
  291. prefix_block_tables.append([])
  292. # Right now, prefill start is always 0. However, this
  293. # assumption can be changed once chunked prefill is introduced.
  294. assert computed_len == 0
  295. # actual prompt lens
  296. context_lens.append(computed_len)
  297. subquery_lens.append(prompt_len - computed_len)
  298. input_tokens.extend(prompt_tokens)
  299. # NOTE: Here we assume that the first token in the prompt
  300. # is always the first token in the sequence.
  301. input_positions.extend(list(range(computed_len, prefill_end)))
  302. lora_id = seq_group_metadata.lora_int_id
  303. if lora_id > 0:
  304. lora_requests.add(seq_group_metadata.lora_request)
  305. lora_index_mapping += [lora_id] * (prompt_len - computed_len)
  306. lora_prompt_mapping.extend(
  307. [lora_id] *
  308. (prompt_len - computed_len
  309. if seq_group_metadata.sampling_params.prompt_logprobs else 1))
  310. if seq_group_metadata.multi_modal_data:
  311. multi_modal_input_list.append(
  312. seq_group_metadata.multi_modal_data.data)
  313. if seq_group_metadata.block_tables is None:
  314. # During memory profiling, the block tables are not initialized
  315. # yet. In this case, we just use a dummy slot mapping.
  316. slot_mapping.extend([_PAD_SLOT_ID] * prompt_len)
  317. continue
  318. # Compute the slot mapping.
  319. block_table = seq_group_metadata.block_tables[seq_id]
  320. # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,
  321. # where start_idx is max(0, prompt_len - sliding_window).
  322. # For example, if the prompt len is 10, sliding window is 8, and
  323. # block size is 4, the first two tokens are masked and the slot
  324. # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
  325. start_idx = 0
  326. if self.sliding_window is not None:
  327. assert computed_len == 0, (
  328. "Prefix caching is currently not supported with "
  329. "sliding window attention")
  330. start_idx = max(0, prompt_len - self.sliding_window)
  331. for i in range(computed_len, prefill_end):
  332. if i < start_idx:
  333. slot_mapping.append(_PAD_SLOT_ID)
  334. continue
  335. block_number = block_table[i // self.block_size]
  336. block_offset = i % self.block_size
  337. slot = block_number * self.block_size + block_offset
  338. slot_mapping.append(slot)
  339. max_subquery_len = max(subquery_lens)
  340. max_prompt_len = max(prompt_lens)
  341. assert max_subquery_len > 0
  342. context_lens_tensor = torch.tensor(context_lens,
  343. dtype=torch.int,
  344. device=self.device)
  345. if multi_modal_input_list:
  346. assert self.vision_language_config, (
  347. "Multi-modal inputs are only supported by "
  348. "vision language models.")
  349. multi_modal_input = torch.cat(multi_modal_input_list,
  350. dim=0).to(self.device)
  351. else:
  352. multi_modal_input = None
  353. # Prepare prefix block tables
  354. max_prompt_block_table_len = max(len(t) for t in prefix_block_tables)
  355. block_tables = make_tensor_with_pad(
  356. prefix_block_tables,
  357. max_len=max_prompt_block_table_len,
  358. pad=0,
  359. dtype=torch.int,
  360. device=self.device,
  361. )
  362. # Query length can be shorter than key (i.e., prompt) when prefill
  363. # is chunked or prefix cached.
  364. subquery_lens_tensor = torch.tensor(subquery_lens,
  365. dtype=torch.long,
  366. device=self.device)
  367. subquery_start_loc = torch.zeros(subquery_lens_tensor.shape[0] + 1,
  368. dtype=torch.int32,
  369. device=self.device)
  370. prompt_lens_tensor = torch.tensor(prompt_lens,
  371. dtype=torch.long,
  372. device=self.device)
  373. seq_start_loc = torch.zeros(prompt_lens_tensor.shape[0] + 1,
  374. dtype=torch.int32,
  375. device=self.device)
  376. torch.cumsum(subquery_lens_tensor,
  377. dim=0,
  378. dtype=subquery_start_loc.dtype,
  379. out=subquery_start_loc[1:])
  380. torch.cumsum(prompt_lens_tensor,
  381. dim=0,
  382. dtype=seq_start_loc.dtype,
  383. out=seq_start_loc[1:])
  384. attn_metadata = self.attn_backend.make_metadata(
  385. is_prompt=True,
  386. prompt_lens=prompt_lens,
  387. prompt_lens_tensor=prompt_lens_tensor,
  388. max_subquery_len=max_subquery_len,
  389. max_context_len=None,
  390. max_prompt_len=max_prompt_len,
  391. subquery_start_loc=subquery_start_loc,
  392. seq_start_loc=seq_start_loc,
  393. context_lens=context_lens_tensor,
  394. block_tables=block_tables,
  395. use_cuda_graph=False,
  396. )
  397. return PreparePromptMetadata(
  398. input_tokens=input_tokens,
  399. input_positions=input_positions,
  400. attn_metadata=attn_metadata,
  401. prompt_lens=prompt_lens,
  402. subquery_lens=subquery_lens,
  403. lora_index_mapping=lora_index_mapping,
  404. lora_prompt_mapping=lora_prompt_mapping,
  405. lora_requests=lora_requests,
  406. multi_modal_input=multi_modal_input,
  407. slot_mapping=slot_mapping,
  408. )
  409. def _prepare_decode(
  410. self,
  411. seq_group_metadata_list: List[SequenceGroupMetadata],
  412. ) -> PrepareDecodeMetadata:
  413. input_tokens: List[int] = []
  414. input_positions: List[int] = []
  415. slot_mapping: List[int] = []
  416. context_lens: List[int] = []
  417. block_tables: List[List[int]] = []
  418. lora_index_mapping: List[int] = []
  419. lora_prompt_mapping: List[int] = []
  420. lora_requests: Set[LoRARequest] = set()
  421. if len(seq_group_metadata_list) == 0:
  422. return PrepareDecodeMetadata.empty()
  423. for seq_group_metadata in seq_group_metadata_list:
  424. assert not seq_group_metadata.is_prompt
  425. assert seq_group_metadata.token_chunk_size == 1
  426. seq_ids = list(seq_group_metadata.seq_data.keys())
  427. lora_id = seq_group_metadata.lora_int_id
  428. if lora_id > 0:
  429. lora_requests.add(seq_group_metadata.lora_request)
  430. for seq_id in seq_ids:
  431. seq_data = seq_group_metadata.seq_data[seq_id]
  432. generation_token = seq_data.get_last_token_id()
  433. input_tokens.append(generation_token)
  434. seq_len = seq_data.get_len()
  435. position = seq_len - 1
  436. input_positions.append(position)
  437. context_len = seq_len if self.sliding_window is None else min(
  438. seq_len, self.sliding_window)
  439. context_lens.append(context_len)
  440. block_table = seq_group_metadata.block_tables[seq_id]
  441. block_number = block_table[position // self.block_size]
  442. block_offset = position % self.block_size
  443. slot = block_number * self.block_size + block_offset
  444. slot_mapping.append(slot)
  445. lora_index_mapping.append(lora_id)
  446. lora_prompt_mapping.append(lora_id)
  447. if self.sliding_window is not None:
  448. sliding_window_blocks = (self.sliding_window //
  449. self.block_size)
  450. block_table = block_table[-sliding_window_blocks:]
  451. block_tables.append(block_table)
  452. # Aphrodite uses CUDA graph only for decoding requests.
  453. # See `capture_model` API for more details.
  454. # For decoding requests, batch_size == input_tokens.
  455. batch_size = len(input_tokens)
  456. max_context_len = max(context_lens)
  457. use_captured_graph = (
  458. not self.model_config.enforce_eager
  459. and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]
  460. and max_context_len <= self.max_context_len_to_capture)
  461. if use_captured_graph:
  462. graph_batch_size = _get_graph_batch_size(batch_size)
  463. assert graph_batch_size >= batch_size
  464. for _ in range(graph_batch_size - batch_size):
  465. input_tokens.append(0)
  466. input_positions.append(0)
  467. slot_mapping.append(_PAD_SLOT_ID)
  468. context_lens.append(1)
  469. block_tables.append([])
  470. lora_index_mapping.append(0)
  471. batch_size = graph_batch_size
  472. context_lens = torch.tensor(context_lens,
  473. dtype=torch.int,
  474. device=self.device)
  475. if use_captured_graph:
  476. # When using cuda-graph all these tensors should be
  477. # padded.
  478. assert context_lens.shape[0] == len(input_tokens)
  479. assert context_lens.shape[0] == len(input_positions)
  480. assert context_lens.shape[0] == len(slot_mapping)
  481. # The shape of graph_block_tables is
  482. # [max batch size, max context len // block size].
  483. input_block_tables = self.graph_block_tables[:batch_size]
  484. for i, block_table in enumerate(block_tables):
  485. if block_table:
  486. input_block_tables[i, :len(block_table)] = block_table
  487. block_tables = torch.tensor(input_block_tables, device=self.device)
  488. else:
  489. max_block_table_len = max(
  490. len(block_table) for block_table in block_tables)
  491. block_tables = make_tensor_with_pad(
  492. block_tables,
  493. max_len=max_block_table_len,
  494. pad=0,
  495. dtype=torch.int,
  496. device=self.device,
  497. )
  498. attn_metadata = self.attn_backend.make_metadata(
  499. is_prompt=False,
  500. prompt_lens=None,
  501. prompt_lens_tensor=None,
  502. max_subquery_len=None,
  503. max_context_len=max_context_len,
  504. max_prompt_len=None,
  505. subquery_start_loc=None,
  506. seq_start_loc=None,
  507. context_lens=context_lens,
  508. block_tables=block_tables,
  509. use_cuda_graph=use_captured_graph,
  510. )
  511. return PrepareDecodeMetadata(
  512. input_tokens=input_tokens,
  513. input_positions=input_positions,
  514. attn_metadata=attn_metadata,
  515. lora_index_mapping=lora_index_mapping,
  516. lora_prompt_mapping=lora_prompt_mapping,
  517. lora_requests=lora_requests,
  518. slot_mapping=slot_mapping,
  519. )
  520. def _prepare_sample(
  521. self,
  522. seq_group_metadata_list: List[SequenceGroupMetadata],
  523. prompt_lens: List[int],
  524. subquery_lens: Optional[List[int]],
  525. ) -> SamplingMetadata:
  526. seq_groups: List[Tuple[List[int], SamplingParams]] = []
  527. selected_token_indices: List[int] = []
  528. generators: List[torch.Generator] = []
  529. selected_token_start_idx = 0
  530. categorized_sample_indices = {t: [] for t in SamplingType}
  531. categorized_sample_indices_start_idx = 0
  532. categorized_sampled_token_indices_start_idx = 0
  533. for i, seq_group_metadata in enumerate(seq_group_metadata_list):
  534. seq_ids = list(seq_group_metadata.seq_data.keys())
  535. sampling_params = seq_group_metadata.sampling_params
  536. seq_groups.append((seq_ids, sampling_params))
  537. if seq_group_metadata.is_prompt:
  538. assert len(seq_ids) == 1
  539. assert subquery_lens is not None
  540. subquery_len = subquery_lens[i]
  541. if sampling_params.prompt_logprobs is not None:
  542. # NOTE: prompt token positions do not need sample, skip
  543. categorized_sample_indices_start_idx += subquery_len - 1
  544. categorized_sample_indices[
  545. sampling_params.sampling_type].append([
  546. categorized_sample_indices_start_idx,
  547. categorized_sampled_token_indices_start_idx
  548. ])
  549. categorized_sample_indices_start_idx += 1
  550. categorized_sampled_token_indices_start_idx += 1
  551. if sampling_params.prompt_logprobs is not None:
  552. selected_token_indices.extend(
  553. range(selected_token_start_idx,
  554. selected_token_start_idx + subquery_len - 1))
  555. selected_token_indices.append(selected_token_start_idx +
  556. subquery_len - 1)
  557. selected_token_start_idx += subquery_len
  558. if sampling_params.seed is not None:
  559. seq_group_metadata.state.generator = torch.Generator(
  560. device=self.device).manual_seed(sampling_params.seed)
  561. else:
  562. num_seqs = len(seq_ids)
  563. selected_token_indices.extend(
  564. range(selected_token_start_idx,
  565. selected_token_start_idx + num_seqs))
  566. selected_token_start_idx += num_seqs
  567. categorized_sample_indices[
  568. sampling_params.sampling_type].extend(
  569. zip(
  570. range(
  571. categorized_sample_indices_start_idx,
  572. categorized_sample_indices_start_idx +
  573. num_seqs),
  574. range(
  575. categorized_sampled_token_indices_start_idx,
  576. categorized_sampled_token_indices_start_idx +
  577. num_seqs)))
  578. categorized_sample_indices_start_idx += num_seqs
  579. categorized_sampled_token_indices_start_idx += num_seqs
  580. if sampling_params.seed is not None:
  581. generators.append(seq_group_metadata.state.generator)
  582. selected_token_indices = async_tensor_h2d(selected_token_indices,
  583. dtype=torch.long,
  584. target_device=self.device,
  585. pin_memory=self.pin_memory)
  586. categorized_sample_indices = {
  587. t: maybe_expand_dim(
  588. async_tensor_h2d(seq_ids,
  589. dtype=torch.int,
  590. target_device=self.device,
  591. pin_memory=self.pin_memory), 2, 2)
  592. for t, seq_ids in categorized_sample_indices.items()
  593. }
  594. seq_data: Dict[int, SequenceData] = {}
  595. for seq_group_metadata in seq_group_metadata_list:
  596. seq_data.update(seq_group_metadata.seq_data)
  597. seq_persistence_data: Dict[int, dict] = {}
  598. for grp in seq_group_metadata_list:
  599. seq_persistence_data.update(grp.persistent_data)
  600. sampling_metadata = SamplingMetadata(
  601. seq_groups=seq_groups,
  602. seq_data=seq_data,
  603. prompt_lens=prompt_lens,
  604. selected_token_indices=selected_token_indices,
  605. categorized_sample_indices=categorized_sample_indices,
  606. generators=generators,
  607. persistent_metadata=PersistentMetadata(seq_persistence_data),
  608. )
  609. return sampling_metadata
  610. def prepare_input_tensors(
  611. self,
  612. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],
  613. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, SamplingMetadata,
  614. Set[int], LoRAMapping, torch.Tensor]:
  615. if self.is_driver_worker:
  616. prefill_reqs = []
  617. decode_reqs = []
  618. for seq_group_meta in seq_group_metadata_list:
  619. if seq_group_meta.is_prompt:
  620. prefill_reqs.append(seq_group_meta)
  621. else:
  622. decode_reqs.append(seq_group_meta)
  623. # Prepare input tensors.
  624. (
  625. input_tokens,
  626. input_positions,
  627. prefill_attn_metadata,
  628. prompt_lens,
  629. subquery_lens,
  630. lora_index_mapping,
  631. lora_prompt_mapping,
  632. lora_requests,
  633. multi_modal_input,
  634. slot_mapping,
  635. ) = self._prepare_prompt(prefill_reqs)
  636. (
  637. decode_input_tokens,
  638. decode_input_positions,
  639. decode_attn_metadata,
  640. decode_lora_index_mapping,
  641. decode_lora_prompt_mapping,
  642. decode_lora_requests,
  643. decode_slot_mapping,
  644. ) = self._prepare_decode(decode_reqs)
  645. sampling_metadata = self._prepare_sample(seq_group_metadata_list,
  646. prompt_lens,
  647. subquery_lens)
  648. if not self.scheduler_config.chunked_prefill_enabled:
  649. assert (len(prefill_reqs) and len(decode_reqs)) == 0
  650. num_prefills = len(prompt_lens)
  651. num_prefill_tokens = len(input_tokens)
  652. num_decode_tokens = len(decode_input_tokens)
  653. # Coalesce tensors. Note that attn_metadata is currently not
  654. # coalesced for simplicity.
  655. input_tokens.extend(decode_input_tokens)
  656. input_positions.extend(decode_input_positions)
  657. slot_mapping.extend(decode_slot_mapping)
  658. lora_index_mapping.extend(decode_lora_index_mapping)
  659. lora_prompt_mapping.extend(decode_lora_prompt_mapping)
  660. lora_requests.update(decode_lora_requests)
  661. input_tokens = torch.tensor(input_tokens,
  662. dtype=torch.long,
  663. device=self.device)
  664. input_positions = torch.tensor(input_positions,
  665. dtype=torch.long,
  666. device=self.device)
  667. slot_mapping = torch.tensor(slot_mapping,
  668. dtype=torch.long,
  669. device=self.device)
  670. if self.lora_config:
  671. lora_mapping = LoRAMapping(
  672. lora_index_mapping,
  673. lora_prompt_mapping,
  674. )
  675. else:
  676. lora_mapping = None
  677. # Broadcast the metadata.
  678. # If batch contains both prefill and decode, it sends 2 broadcasts.
  679. # If it only contains 1 type, it triggers a single broadcast.
  680. if (prefill_attn_metadata is not None
  681. and decode_attn_metadata is not None):
  682. batch_type = BatchType.MIXED
  683. elif prefill_attn_metadata is not None:
  684. batch_type = BatchType.PREFILL
  685. else:
  686. batch_type = BatchType.DECODE
  687. requests_info = [
  688. RequestInfo(request_id=req.request_id,
  689. seqs_id=list(req.seq_data.keys()))
  690. for req in seq_group_metadata_list
  691. ]
  692. metadata_dict = {
  693. "input_tokens": input_tokens,
  694. "input_positions": input_positions,
  695. "selected_token_indices":
  696. sampling_metadata.selected_token_indices,
  697. "lora_requests": lora_requests,
  698. "lora_mapping": lora_mapping,
  699. "multi_modal_input": multi_modal_input,
  700. "num_prefill_tokens": num_prefill_tokens,
  701. "num_decode_tokens": num_decode_tokens,
  702. "slot_mapping": slot_mapping,
  703. "num_prefills": num_prefills,
  704. "batch_type": batch_type,
  705. "requests_info": requests_info,
  706. }
  707. if prefill_attn_metadata is not None:
  708. metadata_dict.update(prefill_attn_metadata.asdict_zerocopy())
  709. else:
  710. metadata_dict.update(decode_attn_metadata.asdict_zerocopy())
  711. broadcast_tensor_dict(metadata_dict, src=0)
  712. # Broadcast decode attn metadata for mixed batch type.
  713. # The additional broadcast costs 300us overhead on 4 A10 GPUs.
  714. # We can potentially reduce the overhead by coelescing tensors.
  715. if batch_type == BatchType.MIXED:
  716. assert decode_attn_metadata is not None
  717. metadata_dict = decode_attn_metadata.asdict_zerocopy()
  718. broadcast_tensor_dict(metadata_dict, src=0)
  719. else:
  720. metadata_dict = broadcast_tensor_dict(src=0)
  721. input_tokens = metadata_dict.pop("input_tokens")
  722. input_positions = metadata_dict.pop("input_positions")
  723. slot_mapping = metadata_dict.pop("slot_mapping")
  724. num_prefills = metadata_dict.pop("num_prefills")
  725. selected_token_indices = metadata_dict.pop(
  726. "selected_token_indices")
  727. lora_mapping = metadata_dict.pop("lora_mapping")
  728. lora_requests = metadata_dict.pop("lora_requests")
  729. multi_modal_input = metadata_dict.pop("multi_modal_input")
  730. num_prefill_tokens = metadata_dict.pop("num_prefill_tokens")
  731. num_decode_tokens = metadata_dict.pop("num_decode_tokens")
  732. batch_type = metadata_dict.pop("batch_type")
  733. requests_info = metadata_dict.pop("requests_info")
  734. # Create an attention metadata.
  735. prefill_attn_metadata = None
  736. decode_attn_metadata = None
  737. if batch_type == BatchType.PREFILL or batch_type == BatchType.MIXED:
  738. prefill_attn_metadata = self.attn_backend.make_metadata(
  739. **metadata_dict)
  740. else:
  741. decode_attn_metadata = self.attn_backend.make_metadata(
  742. **metadata_dict)
  743. sampling_metadata = SamplingMetadata(
  744. seq_groups=None,
  745. seq_data=None,
  746. prompt_lens=None,
  747. selected_token_indices=selected_token_indices,
  748. categorized_sample_indices=None,
  749. generators=None,
  750. perform_sampling=False,
  751. )
  752. # if it is a mixed batch, decode attn_metadata is broadcasted
  753. # separately.
  754. if batch_type == BatchType.MIXED:
  755. metadata_dict = broadcast_tensor_dict(src=0)
  756. decode_attn_metadata = self.attn_backend.make_metadata(
  757. **metadata_dict)
  758. attn_metadata = AttentionMetadata(
  759. num_prefills=num_prefills,
  760. slot_mapping=slot_mapping,
  761. num_prefill_tokens=num_prefill_tokens,
  762. num_decode_tokens=num_decode_tokens,
  763. prefill_metadata=prefill_attn_metadata,
  764. decode_metadata=decode_attn_metadata,
  765. kv_cache_dtype=self.kv_cache_dtype,
  766. )
  767. return (input_tokens, input_positions, attn_metadata,
  768. sampling_metadata, lora_requests, lora_mapping,
  769. multi_modal_input, requests_info)
  770. def release_mamba_cache(self, finished_seq_groups_req_ids: List[str]):
  771. for req_id in finished_seq_groups_req_ids:
  772. if req_id in self.request2i:
  773. indices = self.request2i.pop(req_id)
  774. logger.debug(
  775. f"Deleted { req_id } from mamba_cache with indices = "
  776. f"{indices}")
  777. @torch.inference_mode()
  778. def execute_model(
  779. self,
  780. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],
  781. kv_caches: List[torch.Tensor],
  782. ) -> Optional[SamplerOutput]:
  783. (input_tokens, input_positions, attn_metadata, sampling_metadata,
  784. lora_requests, lora_mapping, multi_modal_input,
  785. requests_info) = self.prepare_input_tensors(seq_group_metadata_list)
  786. if self.lora_config:
  787. self.set_active_loras(lora_requests, lora_mapping)
  788. # Currently cuda graph is only supported by the decode phase.
  789. prefill_meta = attn_metadata.prefill_metadata
  790. decode_meta = attn_metadata.decode_metadata
  791. if prefill_meta is None and decode_meta.use_cuda_graph:
  792. graph_batch_size = input_tokens.shape[0]
  793. model_executable = self.graph_runners[graph_batch_size]
  794. else:
  795. model_executable = self.model
  796. indices = []
  797. execute_model_kwargs = {
  798. "input_ids": input_tokens,
  799. "positions": input_positions,
  800. "kv_caches": kv_caches,
  801. "attn_metadata": attn_metadata,
  802. }
  803. if self.vision_language_config:
  804. execute_model_kwargs.update({"image_input": multi_modal_input})
  805. if self.is_mamba:
  806. if self.mamba_cache is None:
  807. self.prepare_contiguous_mamba_cache(self.model_config.dtype)
  808. conv_state, ssm_state, indices = self._prepare_request_mamba_cache(
  809. requests_info, input_tokens.shape[0] if
  810. attn_metadata.prefill_metadata is None else len(requests_info))
  811. execute_model_kwargs = {
  812. **execute_model_kwargs,
  813. "conv_state": conv_state,
  814. "ssm_state": ssm_state,
  815. }
  816. hidden_states = model_executable(**execute_model_kwargs)
  817. # Compute the logits.
  818. logits = self.model.compute_logits(hidden_states, sampling_metadata)
  819. # Only perform sampling in the driver worker.
  820. if not sampling_metadata.perform_sampling:
  821. return None
  822. if self.is_mamba:
  823. for i, offset in enumerate(indices):
  824. self.mamba_cache[0][:, offset].copy_(conv_state[:, i])
  825. self.mamba_cache[1][:, offset].copy_(ssm_state[:, i])
  826. # Sample the next token.
  827. output = self.model.sample(
  828. logits=logits,
  829. sampling_metadata=sampling_metadata,
  830. )
  831. return output
  832. def _get_first_free_mamba_cache_index(self):
  833. max_possible_bs = self.mamba_cache[0].shape[1]
  834. occupied = [
  835. id for seq_ids in self.request2i.values()
  836. for id in seq_ids.values()
  837. ]
  838. first_free_index = [i not in occupied
  839. for i in range(max_possible_bs)].index(True)
  840. return first_free_index
  841. def _prepare_request_mamba_cache(self, requests_info: List[RequestInfo],
  842. batch_size: int):
  843. indices = []
  844. max_possible_bs = self.mamba_cache[0].shape[1]
  845. for request_info in requests_info:
  846. cur_rid = request_info.request_id
  847. if cur_rid not in self.request2i:
  848. self.request2i[cur_rid] = {}
  849. for seq_id in request_info.seqs_id:
  850. f_free_index = self._get_first_free_mamba_cache_index()
  851. self.request2i[cur_rid][seq_id] = f_free_index
  852. indices.append(f_free_index)
  853. else:
  854. for seq_id in request_info.seqs_id:
  855. if seq_id not in self.request2i[cur_rid]:
  856. f_free_index = self._get_first_free_mamba_cache_index()
  857. ## case of decoding n>1
  858. i_exist = list(self.request2i[cur_rid].values())[0]
  859. self.mamba_cache[0][:, f_free_index].copy_(
  860. self.mamba_cache[0][:, i_exist])
  861. self.mamba_cache[1][:, f_free_index].copy_(
  862. self.mamba_cache[1][:, i_exist])
  863. self.request2i[cur_rid][seq_id] = f_free_index
  864. indices.append(self.request2i[cur_rid][seq_id])
  865. ## Pad the batch in case of running batch that was not captured via CG
  866. padded_indices = indices
  867. for _ in range(batch_size - len(indices)):
  868. occu = [
  869. i for s_ids in self.request2i.values() for i in s_ids.values()
  870. ]
  871. padded_indices += [[
  872. i not in set(occu).union(padded_indices)
  873. for i in range(max_possible_bs)
  874. ].index(True)]
  875. conv_state = self.mamba_cache[0][:, padded_indices]
  876. ssm_state = self.mamba_cache[1][:, padded_indices]
  877. return conv_state, ssm_state, indices
  878. @torch.inference_mode()
  879. def profile_run(self) -> None:
  880. # Enable top-k sampling to reflect the accurate memory usage.
  881. sampling_params = SamplingParams(top_p=0.99, top_k=self.vocab_size - 1)
  882. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  883. max_num_seqs = self.scheduler_config.max_num_seqs
  884. # This represents the maximum number of different requests
  885. # that will have unique loras, an therefore the max amount of memory
  886. # consumption create dummy lora request copies from the lora request
  887. # passed in, which contains a lora from the lora warmup path.
  888. dummy_lora_requests = []
  889. dummy_lora_requests_per_seq = []
  890. if self.lora_config:
  891. for idx in range(self.lora_config.max_loras):
  892. lora_id = idx + 1
  893. dummy_lora_request = LoRARequest(
  894. lora_name=f"warmup_{lora_id}",
  895. lora_int_id=lora_id,
  896. lora_local_path="/not/a/real/path",
  897. )
  898. self.lora_manager.add_dummy_lora(dummy_lora_request,
  899. rank=LORA_WARMUP_RANK)
  900. dummy_lora_requests.append(dummy_lora_request)
  901. dummy_lora_requests_per_seq = [
  902. dummy_lora_requests[idx % len(dummy_lora_requests)]
  903. for idx in range(max_num_seqs)
  904. ]
  905. # Profile memory usage with max_num_sequences sequences and the total
  906. # number of tokens equal to max_num_batched_tokens.
  907. seqs: List[SequenceGroupMetadata] = []
  908. # Additional GPU memory may be needed for vision encoding, which needs
  909. # to be accounted for when calculating the GPU blocks for
  910. # Aphrodite blocker manager.
  911. # To exercise the worst scenario for GPU memory consumption,
  912. # the number of seqs (batch_size) is chosen to maximize the number
  913. # of images processed.
  914. if self.vision_language_config:
  915. max_num_seqs = min(
  916. max_num_seqs,
  917. int(max_num_batched_tokens /
  918. self.vision_language_config.image_feature_size))
  919. for group_id in range(max_num_seqs):
  920. seq_len = (max_num_batched_tokens // max_num_seqs +
  921. (group_id < max_num_batched_tokens % max_num_seqs))
  922. seq_data, fake_multi_modal_input = _prepare_fake_inputs(
  923. seq_len, self.vision_language_config)
  924. seq = SequenceGroupMetadata(
  925. request_id=str(group_id),
  926. is_prompt=True,
  927. seq_data={group_id: seq_data},
  928. sampling_params=sampling_params,
  929. block_tables=None,
  930. persistent_data={},
  931. lora_request=dummy_lora_requests_per_seq[group_id]
  932. if dummy_lora_requests_per_seq else None,
  933. multi_modal_data=fake_multi_modal_input,
  934. )
  935. seqs.append(seq)
  936. # Run the model with the dummy inputs.
  937. num_layers = self.model_config.get_num_layers(self.parallel_config)
  938. kv_caches = [None] * num_layers
  939. self.execute_model(seqs, kv_caches)
  940. torch.cuda.synchronize()
  941. self.request2i = {}
  942. return
  943. def remove_all_loras(self) -> bool:
  944. if not self.lora_manager:
  945. raise RuntimeError("LoRA is not enabled.")
  946. return self.lora_manager.remove_all_loras()
  947. def set_active_loras(self, lora_requests: List[LoRARequest],
  948. lora_mapping: LoRAMapping) -> None:
  949. if not self.lora_manager:
  950. raise RuntimeError("LoRA is not enabled.")
  951. self.lora_manager.set_active_loras(lora_requests, lora_mapping)
  952. def add_lora(self, lora_request: LoRARequest) -> bool:
  953. if not self.lora_manager:
  954. raise RuntimeError("LoRA is not enabled.")
  955. return self.lora_manager.add_lora(lora_request)
  956. def remove_lora(self, lora_id: int) -> bool:
  957. if not self.lora_manager:
  958. raise RuntimeError("LoRA is not enabled.")
  959. return self.lora_manager.remove_lora(lora_id)
  960. def list_loras(self) -> Set[int]:
  961. if not self.lora_manager:
  962. raise RuntimeError("LoRA is not enabled.")
  963. return self.lora_manager.list_loras()
  964. @torch.inference_mode()
  965. def capture_model(self, kv_caches: List[torch.Tensor]) -> None:
  966. """Cuda graph capture a model.
  967. Note that CUDA graph's performance gain is negligible if number
  968. of batched tokens are larger than 200. And since CUDA graph
  969. requires fixed sized tensors, supporting large/variable batch
  970. size requires high GPU memory overhead. Thus, Aphrodite only captures
  971. decoding requests. Mixed batch (chunked prefill + decoding) or
  972. prefill requests are not captured.
  973. Since it is used for decoding-only, it assumes there's only 1 token
  974. per sequence in the batch.
  975. """
  976. # NOTE: This is a hack to ensure that the NCCL backend is never
  977. # deleted before the CUDA graphs.
  978. self.pynccl_backend = pynccl_utils.get_nccl_backend()
  979. assert not self.model_config.enforce_eager
  980. logger.info("Capturing the model for CUDA graphs. This may lead to "
  981. "unexpected consequences if the model is not static. To "
  982. "run the model in eager mode, set 'enforce_eager=True' or "
  983. "use '--enforce-eager' in the CLI.")
  984. logger.warning("CUDA graphs can take additional 1~3 GiB of memory "
  985. "per GPU. If you are running out of memory, consider "
  986. "decreasing `gpu_memory_utilization` or enforcing "
  987. "eager mode.")
  988. start_time = time.perf_counter()
  989. # Prepare dummy inputs. These will be reused for all batch sizes.
  990. max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)
  991. input_tokens = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  992. input_positions = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  993. slot_mapping = torch.empty(max_batch_size, dtype=torch.long).cuda()
  994. slot_mapping.fill_(_PAD_SLOT_ID)
  995. context_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()
  996. block_tables = torch.from_numpy(self.graph_block_tables).cuda()
  997. graph_batch_size = _get_graph_batch_size(
  998. self.scheduler_config.max_num_seqs)
  999. batch_size_capture_list = [
  1000. bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size
  1001. ]
  1002. # NOTE: There are 3 backends for all-reduce: custom all-reduce
  1003. # kernel, PyNCCL, and PyTorch NCCL. When using CUDA graph, we use
  1004. # either custom all-reduce kernel or PyNCCL. When not using CUDA
  1005. # graph, we use either custom all-reduce kernel or PyTorch NCCL.
  1006. # We always prioritize using custom all-reduce kernel but fall back
  1007. # to PyTorch or PyNCCL if it is disabled or not supported.
  1008. # Initialize a new progress bar
  1009. progress = get_loading_progress_bar()
  1010. task = progress.add_task("[cyan]Capturing graph...",
  1011. total=len(batch_size_capture_list))
  1012. with progress, custom_all_reduce.capture():
  1013. for batch_size in reversed(batch_size_capture_list):
  1014. # Create dummy attn_metadata.
  1015. decode_metadata = self.attn_backend.make_metadata(
  1016. is_prompt=False,
  1017. prompt_lens=None,
  1018. prompt_lens_tensor=None,
  1019. max_subquery_len=None,
  1020. max_context_len=self.max_context_len_to_capture,
  1021. max_prompt_len=None,
  1022. subquery_start_loc=None,
  1023. seq_start_loc=None,
  1024. context_lens=context_lens[:batch_size],
  1025. block_tables=block_tables[:batch_size],
  1026. use_cuda_graph=True,
  1027. )
  1028. attn_metadata = AttentionMetadata(
  1029. num_prefills=0,
  1030. num_prefill_tokens=0,
  1031. num_decode_tokens=batch_size,
  1032. slot_mapping=slot_mapping[:batch_size],
  1033. prefill_metadata=None,
  1034. decode_metadata=decode_metadata,
  1035. kv_cache_dtype=self.kv_cache_dtype,
  1036. )
  1037. if self.lora_config:
  1038. lora_mapping = LoRAMapping(
  1039. [0] * batch_size,
  1040. [0] * batch_size,
  1041. )
  1042. self.set_active_loras(set(), lora_mapping)
  1043. graph_runner = CUDAGraphRunner(self.model, self.is_mamba)
  1044. capture_inputs = {
  1045. "input_ids": input_tokens[:batch_size],
  1046. "positions": input_positions[:batch_size],
  1047. "kv_caches": kv_caches,
  1048. "attn_metadata": attn_metadata,
  1049. "memory_pool": self.graph_memory_pool,
  1050. }
  1051. if self.is_mamba:
  1052. capture_inputs["conv_state"] = self.mamba_cache4gc[
  1053. 0][:, :batch_size]
  1054. capture_inputs["ssm_state"] = self.mamba_cache4gc[
  1055. 1][:, :batch_size]
  1056. graph_runner.capture(**capture_inputs)
  1057. self.graph_memory_pool = graph_runner.graph.pool()
  1058. self.graph_runners[batch_size] = graph_runner
  1059. # Update the progress bar
  1060. progress.update(task, advance=1)
  1061. end_time = time.perf_counter()
  1062. elapsed_time = end_time - start_time
  1063. # This usually takes < 10 seconds.
  1064. logger.info(f"Graph capturing finished in {elapsed_time:.0f} secs.")
  1065. def __del__(self) -> None:
  1066. # Delete the CUDA graphs before deleting the pynccl communicator.
  1067. # NOTE: This is necessary because otherwise deadlocks can
  1068. # happen.
  1069. # FIXME: This is a bit hacky. Find a more robust solution.
  1070. # TODO: when we get enough user feedback that pynccl is
  1071. # more stable than cupy, we can remove this
  1072. self.graph_runners.clear()
  1073. self.pynccl_backend = None
  1074. @property
  1075. def vocab_size(self) -> int:
  1076. return self.model_config.get_vocab_size()
  1077. class CUDAGraphRunner:
  1078. def __init__(self, model: nn.Module, is_mamba: bool):
  1079. self.model = model
  1080. self.graph = None
  1081. self.input_buffers: Dict[str, torch.Tensor] = {}
  1082. self.output_buffers: Dict[str, torch.Tensor] = {}
  1083. self.is_mamba = is_mamba
  1084. def capture(
  1085. self,
  1086. input_ids: torch.Tensor,
  1087. positions: torch.Tensor,
  1088. kv_caches: List[torch.Tensor],
  1089. attn_metadata: AttentionMetadata,
  1090. memory_pool,
  1091. conv_state: Optional[torch.Tensor] = None,
  1092. ssm_state: Optional[torch.Tensor] = None,
  1093. **kwargs,
  1094. ) -> None:
  1095. assert self.graph is None
  1096. # Run the model once without capturing the graph.
  1097. # This is to make sure that the captured graph does not include the
  1098. # kernel launches for initial benchmarking (e.g., Triton autotune).
  1099. model_inputs = {
  1100. "input_ids": input_ids,
  1101. "positions": positions,
  1102. "kv_caches": kv_caches,
  1103. "attn_metadata": attn_metadata,
  1104. **kwargs
  1105. }
  1106. if self.is_mamba:
  1107. model_inputs = {
  1108. **model_inputs,
  1109. "conv_state": conv_state,
  1110. "ssm_state": ssm_state,
  1111. }
  1112. with _maybe_pynccl():
  1113. self.model(**model_inputs)
  1114. torch.cuda.synchronize()
  1115. # Capture the graph.
  1116. # NOTE: Python 3.8 does not support multi-line with statements.
  1117. # https://stackoverflow.com/questions/31039022/python-multi-line-with-statement
  1118. self.graph = torch.cuda.CUDAGraph()
  1119. with torch.cuda.graph(self.graph, pool=memory_pool): # noqa: SIM117
  1120. with _maybe_pynccl():
  1121. hidden_states = self.model(**model_inputs)
  1122. torch.cuda.synchronize()
  1123. # Save the input and output buffers.
  1124. self.input_buffers = {
  1125. "input_ids": input_ids,
  1126. "positions": positions,
  1127. "kv_caches": kv_caches,
  1128. "slot_mapping": attn_metadata.slot_mapping,
  1129. "context_lens": attn_metadata.decode_metadata.context_lens,
  1130. "block_tables": attn_metadata.decode_metadata.block_tables,
  1131. "conv_state": conv_state,
  1132. "ssm_state": ssm_state
  1133. }
  1134. if self.is_mamba:
  1135. self.input_buffers = {
  1136. **self.input_buffers,
  1137. "conv_state": conv_state,
  1138. "ssm_state": ssm_state,
  1139. }
  1140. self.output_buffers = {"hidden_states": hidden_states}
  1141. return
  1142. def forward(
  1143. self,
  1144. input_ids: torch.Tensor,
  1145. positions: torch.Tensor,
  1146. kv_caches: List[torch.Tensor],
  1147. attn_metadata: AttentionMetadata,
  1148. conv_state: Optional[torch.Tensor] = None,
  1149. ssm_state: Optional[torch.Tensor] = None,
  1150. **kwargs,
  1151. ) -> torch.Tensor:
  1152. # KV caches are fixed tensors, so we don't need to copy them.
  1153. del kv_caches
  1154. # Copy the input tensors to the input buffers.
  1155. self.input_buffers["input_ids"].copy_(input_ids, non_blocking=True)
  1156. self.input_buffers["positions"].copy_(positions, non_blocking=True)
  1157. self.input_buffers["slot_mapping"].copy_(attn_metadata.slot_mapping,
  1158. non_blocking=True)
  1159. self.input_buffers["context_lens"].copy_(
  1160. attn_metadata.decode_metadata.context_lens, non_blocking=True)
  1161. self.input_buffers["block_tables"].copy_(
  1162. attn_metadata.decode_metadata.block_tables, non_blocking=True)
  1163. if self.is_mamba:
  1164. self.input_buffers["conv_state"].copy_(conv_state,
  1165. non_blocking=True)
  1166. self.input_buffers["ssm_state"].copy_(ssm_state, non_blocking=True)
  1167. # Run the graph.
  1168. self.graph.replay()
  1169. # in-place edit of the mamba cache states as in the KV cache
  1170. if self.is_mamba:
  1171. ssm_state.copy_(self.input_buffers["ssm_state"])
  1172. conv_state.copy_(self.input_buffers["conv_state"])
  1173. # Return the output tensor.
  1174. return self.output_buffers["hidden_states"]
  1175. def __call__(self, *args, **kwargs):
  1176. return self.forward(*args, **kwargs)
  1177. @contextlib.contextmanager
  1178. def _maybe_pynccl():
  1179. if pynccl_utils.is_initialized(
  1180. ) and not custom_all_reduce.is_initialized():
  1181. with with_pynccl_for_all_reduce():
  1182. yield
  1183. else:
  1184. yield
  1185. def _get_graph_batch_size(batch_size: int) -> int:
  1186. """Returns the padded batch size given actual batch size.
  1187. Batch sizes are 1, 2, 4, _BATCH_SIZE_ALIGNMENT,
  1188. 2*_BATCH_SIZE_ALIGNMENT, 3*_BATCH_SIZE_ALIGNMENT...
  1189. """
  1190. if batch_size <= 2:
  1191. return batch_size
  1192. elif batch_size <= 4:
  1193. return 4
  1194. else:
  1195. return ((batch_size + _BATCH_SIZE_ALIGNMENT - 1) //
  1196. _BATCH_SIZE_ALIGNMENT * _BATCH_SIZE_ALIGNMENT)
  1197. def _prepare_fake_inputs(
  1198. seq_len: int, vision_language_config: Optional[VisionLanguageConfig]):
  1199. """Prepare fake inputs for profile run."""
  1200. if vision_language_config:
  1201. prompt_tokens = [
  1202. vision_language_config.image_token_id
  1203. ] * vision_language_config.image_feature_size + [0] * (
  1204. seq_len - vision_language_config.image_feature_size)
  1205. fake_image_input = MultiModalData(
  1206. type=MultiModalData.Type.IMAGE,
  1207. data=torch.zeros(vision_language_config.image_input_shape,
  1208. dtype=torch.float16))
  1209. else:
  1210. prompt_tokens = [0] * seq_len
  1211. fake_image_input = None
  1212. return SequenceData(prompt_tokens), fake_image_input