model_runner.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. import contextlib
  2. import time
  3. from typing import Dict, List, Optional, Tuple, Set, Union
  4. import numpy as np
  5. import torch
  6. import torch.nn as nn
  7. from rich.progress import Progress
  8. from aphrodite.common.config import (DeviceConfig, ModelConfig, LoRAConfig,
  9. ParallelConfig, SchedulerConfig)
  10. from aphrodite.common.logger import init_logger
  11. from aphrodite.modeling import get_model, InputMetadata, SamplingMetadata
  12. from aphrodite.modeling.megatron import cupy_utils
  13. from aphrodite.modeling.megatron.communication_op import (broadcast_tensor_dict
  14. )
  15. from aphrodite.modeling.megatron.parallel_state import (
  16. with_cupy_nccl_for_all_reduce)
  17. from aphrodite.modeling.megatron import custom_all_reduce
  18. from aphrodite.common.sampling_params import SamplingParams, SamplingType
  19. from aphrodite.common.sequence import (SamplerOutput, SequenceData,
  20. SequenceGroupMetadata)
  21. from aphrodite.modeling.sampling_metadata import PersistentMetadata
  22. from aphrodite.lora.worker_manager import LRUCacheWorkerLoRAManager
  23. from aphrodite.lora.layers import LoRAMapping
  24. from aphrodite.lora.request import LoRARequest
  25. from aphrodite.common.utils import in_wsl
  26. logger = init_logger(__name__)
  27. KVCache = Tuple[torch.Tensor, torch.Tensor]
  28. _PAD_SLOT_ID = -1
  29. LORA_WARMUP_RANK = 8
  30. # Capture graphs for batch size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.
  31. # NOTE: _get_graph_batch_size needs to be updated if this list is changed.
  32. _BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [8 * i for i in range(1, 33)]
  33. class ModelRunner:
  34. def __init__(
  35. self,
  36. model_config: ModelConfig,
  37. parallel_config: ParallelConfig,
  38. scheduler_config: SchedulerConfig,
  39. device_config: DeviceConfig,
  40. lora_config: Optional[LoRAConfig],
  41. kv_cache_dtype: Optional[str] = "auto",
  42. kv_quant_params_path: Optional[str] = None,
  43. is_driver_worker: bool = False,
  44. ):
  45. self.model_config = model_config
  46. self.parallel_config = parallel_config
  47. self.scheduler_config = scheduler_config
  48. self.lora_config = lora_config
  49. self.is_driver_worker = is_driver_worker
  50. # model_config can be None in tests/samplers/test_sampler.py.
  51. # FIXME: This is a hack to make the tests work. Refactor this.
  52. self.sliding_window = (model_config.get_sliding_window()
  53. if model_config is not None else None)
  54. self.device_config = (device_config
  55. if device_config is not None else DeviceConfig())
  56. self.device = self.device_config.device
  57. self.model = None
  58. self.block_size = None # Set after initial profiling.
  59. self.lora_manager = None
  60. self.graph_runners: Dict[int, CUDAGraphRunner] = {}
  61. self.graph_memory_pool = None # Set during graph capture.
  62. self.max_context_len_to_capture = (
  63. self.model_config.max_context_len_to_capture
  64. if self.model_config is not None else 0)
  65. # When using CUDA graph, the input block tables must be padded to
  66. # max_context_len_to_capture. However, creating the block table in
  67. # Python can be expensive. To optimize this, we cache the block table
  68. # in numpy and only copy the actual input content at every iteration.
  69. # The shape of the cached block table will be
  70. # (max batch size to capture, max context len to capture / block size).
  71. self.graph_block_tables = None # Set after initial profiling.
  72. # cache in_wsl result
  73. self.in_wsl = in_wsl()
  74. self.kv_cache_dtype = kv_cache_dtype
  75. self.kv_quant_params = self.load_kv_quant_params(
  76. model_config,
  77. kv_quant_params_path) if self.kv_cache_dtype == "int8" else None
  78. def load_kv_quant_params(self, model_config: ModelConfig,
  79. kv_quant_params_path: str) -> List[List[float]]:
  80. if model_config is None:
  81. return None
  82. # Remove it when all models support kv cache int8.
  83. architectures = model_config.hf_config.architectures
  84. for arch in architectures:
  85. if arch not in ["LlamaForCausalLM", "LLaMAForCausalLM"]:
  86. raise ValueError(
  87. f"KV CACHE INT8 is not supported for model architectures {arch} for now. "
  88. f"Supported architectures: LlamaForCausalLM and LLaMAForCausalLM."
  89. )
  90. num_layers = model_config.hf_config.num_hidden_layers
  91. kv_quant_params = []
  92. for i in range(num_layers):
  93. if kv_quant_params_path is not None:
  94. path = kv_quant_params_path + f"/layers.{i}.past_kv_scale.0.weight"
  95. kv_quant_param = list(np.fromfile(path, dtype=np.float32))
  96. kv_quant_params.append(kv_quant_param)
  97. return kv_quant_params
  98. def load_model(self) -> None:
  99. self.model = get_model(self.model_config, self.device_config,
  100. self.lora_config)
  101. vocab_size = self.model.config.vocab_size
  102. if self.lora_config:
  103. assert hasattr(
  104. self.model, "supported_lora_modules"
  105. ) and self.model.supported_lora_modules, "Model does not support LoRA"
  106. assert hasattr(
  107. self.model,
  108. "embedding_modules"), "Model does not have embedding_modules"
  109. assert hasattr(self.model, "embedding_padding_modules"
  110. ), "Model does not have embedding_padding_modules"
  111. self.lora_manager = LRUCacheWorkerLoRAManager(
  112. self.scheduler_config.max_num_seqs,
  113. self.scheduler_config.max_num_batched_tokens +
  114. self.scheduler_config.max_paddings, vocab_size,
  115. self.lora_config, self.device, self.model.embedding_modules,
  116. self.model.embedding_padding_modules)
  117. self.model = self.lora_manager.create_lora_manager(self.model)
  118. def set_block_size(self, block_size: int) -> None:
  119. self.block_size = block_size
  120. max_num_blocks = (self.max_context_len_to_capture + block_size -
  121. 1) // block_size
  122. self.graph_block_tables = np.zeros(
  123. (max(_BATCH_SIZES_TO_CAPTURE), max_num_blocks), dtype=np.int32)
  124. def _prepare_prompt(
  125. self,
  126. seq_group_metadata_list: List[SequenceGroupMetadata],
  127. ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, List[int], List[int],
  128. List[int], List[int], Set[LoRARequest]]:
  129. assert len(seq_group_metadata_list) > 0
  130. input_tokens: List[List[int]] = []
  131. input_positions: List[List[int]] = []
  132. slot_mapping: List[List[int]] = []
  133. lora_index_mapping: List[int] = []
  134. lora_prompt_mapping: List[int] = []
  135. lora_requests: Set[LoRARequest] = set()
  136. prompt_lens: List[int] = []
  137. context_lens: List[int] = []
  138. subquery_lens: List[int] = []
  139. prefix_block_tables: List[List[int]] = []
  140. for seq_group_metadata in seq_group_metadata_list:
  141. assert seq_group_metadata.is_prompt
  142. seq_ids = list(seq_group_metadata.seq_data.keys())
  143. assert len(seq_ids) == 1
  144. seq_id = seq_ids[0]
  145. seq_data = seq_group_metadata.seq_data[seq_id]
  146. prompt_tokens = seq_data.get_token_ids()
  147. prompt_len = len(prompt_tokens)
  148. prompt_lens.append(prompt_len)
  149. computed_len = 0
  150. # NOTE: This only works for oooooooxxx style attention.
  151. computed_block_nums = seq_group_metadata.computed_block_nums
  152. if computed_block_nums is not None and len(
  153. computed_block_nums) > 0 and self.sliding_window is None:
  154. # Prefix is not supported with sliding_window
  155. computed_len = len(computed_block_nums) * self.block_size
  156. prompt_tokens = prompt_tokens[computed_len:]
  157. prefix_block_tables.append(computed_block_nums)
  158. else:
  159. prefix_block_tables.append([])
  160. # actual prompt lens
  161. context_lens.append(computed_len)
  162. subquery_lens.append(prompt_len - computed_len)
  163. input_tokens.append(prompt_tokens)
  164. # NOTE: Here we assume that the first token in the prompt
  165. # is always the first token in the sequence.
  166. input_positions.append(
  167. list(range(computed_len, computed_len + len(prompt_tokens))))
  168. lora_id = seq_group_metadata.lora_int_id
  169. if lora_id > 0:
  170. lora_requests.add(seq_group_metadata.lora_request)
  171. lora_index_mapping.append([lora_id] * (prompt_len - computed_len))
  172. lora_prompt_mapping.extend(
  173. [lora_id] *
  174. (prompt_len - computed_len
  175. if seq_group_metadata.sampling_params.prompt_logprobs else 1))
  176. if seq_group_metadata.block_tables is None:
  177. # During memory profiling, the block tables are not initialized
  178. # yet. In this case, we just use a dummy slot mapping.
  179. slot_mapping.append([_PAD_SLOT_ID] * prompt_len)
  180. continue
  181. # Compute the slot mapping.
  182. slot_mapping.append([])
  183. block_table = seq_group_metadata.block_tables[seq_id]
  184. # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,
  185. # where start_idx is max(0, prompt_len - sliding_window).
  186. # For example, if the prompt len is 10, sliding window is 8, and
  187. # block size is 4, the first two tokens are masked and the slot
  188. # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
  189. start_idx = 0
  190. if self.sliding_window is not None:
  191. assert computed_len == 0, (
  192. "Prefix caching is currently not supported with "
  193. "sliding window attention")
  194. start_idx = max(0, prompt_len - self.sliding_window)
  195. for i in range(computed_len, prompt_len):
  196. if i < start_idx:
  197. slot_mapping[-1].append(_PAD_SLOT_ID)
  198. continue
  199. block_number = block_table[i // self.block_size]
  200. block_offset = i % self.block_size
  201. slot = block_number * self.block_size + block_offset
  202. slot_mapping[-1].append(slot)
  203. max_prompt_len = max(subquery_lens)
  204. input_tokens = _make_tensor_with_pad(input_tokens,
  205. max_prompt_len,
  206. pad=0,
  207. dtype=torch.long,
  208. device=self.device)
  209. input_positions = _make_tensor_with_pad(input_positions,
  210. max_prompt_len,
  211. pad=0,
  212. dtype=torch.long,
  213. device=self.device)
  214. slot_mapping = _make_tensor_with_pad(slot_mapping,
  215. max_prompt_len,
  216. pad=_PAD_SLOT_ID,
  217. dtype=torch.long,
  218. device=self.device)
  219. lora_index_mapping = [
  220. _pad_to_max(mapping, max_prompt_len, pad=0)
  221. for mapping in lora_index_mapping
  222. ]
  223. context_lens_tensor = torch.tensor(context_lens,
  224. dtype=torch.int,
  225. device=self.device)
  226. # Prepare prefix block tables
  227. max_prompt_block_table_len = max(len(t) for t in prefix_block_tables)
  228. block_tables = _make_tensor_with_pad(
  229. prefix_block_tables,
  230. max_len=max_prompt_block_table_len,
  231. pad=0,
  232. dtype=torch.int,
  233. device=self.device,
  234. )
  235. start_loc_tensor = torch.arange(0,
  236. len(prompt_lens) * max_prompt_len,
  237. max_prompt_len,
  238. dtype=torch.long,
  239. device=self.device)
  240. prompt_lens_tensor = torch.tensor(prompt_lens,
  241. dtype=torch.long,
  242. device=self.device)
  243. input_metadata = InputMetadata(
  244. is_prompt=True,
  245. slot_mapping=slot_mapping,
  246. prompt_lens=prompt_lens_tensor,
  247. max_seq_len=max_prompt_len,
  248. start_loc=start_loc_tensor,
  249. max_context_len=None,
  250. context_lens=context_lens_tensor,
  251. block_tables=block_tables,
  252. use_cuda_graph=False,
  253. kv_cache_dtype=self.kv_cache_dtype,
  254. kv_quant_params=self.kv_quant_params,
  255. )
  256. return (input_tokens, input_positions, input_metadata, prompt_lens,
  257. subquery_lens, lora_index_mapping, lora_prompt_mapping,
  258. lora_requests)
  259. def _prepare_decode(
  260. self,
  261. seq_group_metadata_list: List[SequenceGroupMetadata],
  262. ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, List[int], List[int],
  263. Set[LoRARequest]]:
  264. assert len(seq_group_metadata_list) > 0
  265. input_tokens: List[List[int]] = []
  266. input_positions: List[List[int]] = []
  267. slot_mapping: List[List[int]] = []
  268. context_lens: List[int] = []
  269. block_tables: List[List[int]] = []
  270. lora_index_mapping: List[int] = []
  271. lora_prompt_mapping: List[int] = []
  272. lora_requests: Set[LoRARequest] = set()
  273. for seq_group_metadata in seq_group_metadata_list:
  274. assert not seq_group_metadata.is_prompt
  275. seq_ids = list(seq_group_metadata.seq_data.keys())
  276. lora_id = seq_group_metadata.lora_int_id
  277. if lora_id > 0:
  278. lora_requests.add(seq_group_metadata.lora_request)
  279. for seq_id in seq_ids:
  280. seq_data = seq_group_metadata.seq_data[seq_id]
  281. generation_token = seq_data.get_last_token_id()
  282. input_tokens.append([generation_token])
  283. seq_len = seq_data.get_len()
  284. position = seq_len - 1
  285. input_positions.append([position])
  286. context_len = seq_len if self.sliding_window is None else min(
  287. seq_len, self.sliding_window)
  288. context_lens.append(context_len)
  289. block_table = seq_group_metadata.block_tables[seq_id]
  290. block_number = block_table[position // self.block_size]
  291. block_offset = position % self.block_size
  292. slot = block_number * self.block_size + block_offset
  293. slot_mapping.append([slot])
  294. lora_index_mapping.append([lora_id])
  295. lora_prompt_mapping.append(lora_id)
  296. if self.sliding_window is not None:
  297. sliding_window_blocks = (self.sliding_window //
  298. self.block_size)
  299. block_table = block_table[-sliding_window_blocks:]
  300. block_tables.append(block_table)
  301. batch_size = len(input_tokens)
  302. max_context_len = max(context_lens)
  303. use_captured_graph = (
  304. not self.model_config.enforce_eager
  305. and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]
  306. and max_context_len <= self.max_context_len_to_capture)
  307. if use_captured_graph:
  308. # Pad the input tokens, positions, and slot mapping to match the
  309. # batch size of the captured graph.
  310. graph_batch_size = _get_graph_batch_size(batch_size)
  311. assert graph_batch_size >= batch_size
  312. for _ in range(graph_batch_size - batch_size):
  313. input_tokens.append([])
  314. input_positions.append([])
  315. slot_mapping.append([])
  316. context_lens.append(1)
  317. block_tables.append([])
  318. batch_size = graph_batch_size
  319. input_tokens = _make_tensor_with_pad(input_tokens,
  320. max_len=1,
  321. pad=0,
  322. dtype=torch.long,
  323. device=self.device)
  324. input_positions = _make_tensor_with_pad(input_positions,
  325. max_len=1,
  326. pad=0,
  327. dtype=torch.long,
  328. device=self.device)
  329. slot_mapping = _make_tensor_with_pad(slot_mapping,
  330. max_len=1,
  331. pad=_PAD_SLOT_ID,
  332. dtype=torch.long,
  333. device=self.device)
  334. context_lens = torch.tensor(context_lens,
  335. dtype=torch.int,
  336. device=self.device)
  337. if use_captured_graph:
  338. # The shape of graph_block_tables is
  339. # [max batch size, max context len // block size].
  340. input_block_tables = self.graph_block_tables[:batch_size]
  341. for i, block_table in enumerate(block_tables):
  342. if block_table:
  343. input_block_tables[i, :len(block_table)] = block_table
  344. block_tables = torch.tensor(input_block_tables, device=self.device)
  345. else:
  346. max_block_table_len = max(
  347. len(block_table) for block_table in block_tables)
  348. block_tables = _make_tensor_with_pad(
  349. block_tables,
  350. max_len=max_block_table_len,
  351. pad=0,
  352. dtype=torch.int,
  353. device=self.device,
  354. )
  355. lora_index_mapping = [
  356. _pad_to_max(mapping, 1, pad=0) for mapping in lora_index_mapping
  357. ]
  358. input_metadata = InputMetadata(
  359. is_prompt=False,
  360. slot_mapping=slot_mapping,
  361. prompt_lens=None,
  362. max_seq_len=None,
  363. start_loc=None,
  364. max_context_len=max_context_len,
  365. context_lens=context_lens,
  366. block_tables=block_tables,
  367. use_cuda_graph=use_captured_graph,
  368. kv_cache_dtype=self.kv_cache_dtype,
  369. kv_quant_params=self.kv_quant_params,
  370. )
  371. return (input_tokens, input_positions, input_metadata,
  372. lora_index_mapping, lora_prompt_mapping, lora_requests)
  373. def _prepare_sample(
  374. self,
  375. seq_group_metadata_list: List[SequenceGroupMetadata],
  376. prompt_lens: List[int],
  377. subquery_lens: Optional[List[int]],
  378. ) -> SamplingMetadata:
  379. seq_groups: List[Tuple[List[int], SamplingParams]] = []
  380. selected_token_indices: List[int] = []
  381. generators: List[torch.Generator] = []
  382. selected_token_start_idx = 0
  383. categorized_sample_indices = {t: [] for t in SamplingType}
  384. categorized_sample_indices_start_idx = 0
  385. max_subquery_len = max(subquery_lens) if subquery_lens else 1
  386. for i, seq_group_metadata in enumerate(seq_group_metadata_list):
  387. seq_ids = list(seq_group_metadata.seq_data.keys())
  388. sampling_params = seq_group_metadata.sampling_params
  389. seq_groups.append((seq_ids, sampling_params))
  390. if seq_group_metadata.is_prompt:
  391. assert len(seq_ids) == 1
  392. assert subquery_lens is not None
  393. subquery_len = subquery_lens[i]
  394. if sampling_params.prompt_logprobs is not None:
  395. # NOTE: prompt token positions do not need sample, skip
  396. categorized_sample_indices_start_idx += subquery_len - 1
  397. categorized_sample_indices[
  398. sampling_params.sampling_type].append(
  399. categorized_sample_indices_start_idx)
  400. categorized_sample_indices_start_idx += 1
  401. if sampling_params.prompt_logprobs is not None:
  402. selected_token_indices.extend(
  403. range(selected_token_start_idx,
  404. selected_token_start_idx + subquery_len - 1))
  405. selected_token_indices.append(selected_token_start_idx +
  406. subquery_len - 1)
  407. selected_token_start_idx += max_subquery_len
  408. if sampling_params.seed is not None:
  409. seq_group_metadata.state.generator = torch.Generator(
  410. device="cuda").manual_seed(sampling_params.seed)
  411. else:
  412. num_seqs = len(seq_ids)
  413. selected_token_indices.extend(
  414. range(selected_token_start_idx,
  415. selected_token_start_idx + num_seqs))
  416. selected_token_start_idx += num_seqs
  417. categorized_sample_indices[
  418. sampling_params.sampling_type].extend(
  419. range(categorized_sample_indices_start_idx,
  420. categorized_sample_indices_start_idx + num_seqs))
  421. categorized_sample_indices_start_idx += num_seqs
  422. if sampling_params.seed is not None:
  423. generators.append(seq_group_metadata.state.generator)
  424. selected_token_indices = _async_h2d(selected_token_indices,
  425. dtype=torch.long,
  426. target_device=self.device,
  427. pin_memory=not self.in_wsl)
  428. categorized_sample_indices = {
  429. t: _async_h2d(seq_ids,
  430. dtype=torch.int,
  431. target_device=self.device,
  432. pin_memory=not self.in_wsl)
  433. for t, seq_ids in categorized_sample_indices.items()
  434. }
  435. seq_data: Dict[int, SequenceData] = {}
  436. for seq_group_metadata in seq_group_metadata_list:
  437. seq_data.update(seq_group_metadata.seq_data)
  438. seq_persistence_data: Dict[int, dict] = {}
  439. for grp in seq_group_metadata_list:
  440. seq_persistence_data.update(grp.persistent_data)
  441. sampling_metadata = SamplingMetadata(
  442. seq_groups=seq_groups,
  443. seq_data=seq_data,
  444. prompt_lens=prompt_lens,
  445. selected_token_indices=selected_token_indices,
  446. categorized_sample_indices=categorized_sample_indices,
  447. generators=generators,
  448. persistent_metadata=PersistentMetadata(seq_persistence_data),
  449. )
  450. return sampling_metadata
  451. def prepare_input_tensors(
  452. self,
  453. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],
  454. ) -> Tuple[torch.Tensor, torch.Tensor, InputMetadata, SamplingMetadata,
  455. Set[int], LoRAMapping]:
  456. if self.is_driver_worker:
  457. # NOTE: We assume that all sequences in the group are all prompts or
  458. # all decodes.
  459. is_prompt = seq_group_metadata_list[0].is_prompt
  460. # Prepare input tensors.
  461. if is_prompt:
  462. (input_tokens, input_positions, input_metadata, prompt_lens,
  463. subquery_lens, lora_index_mapping, lora_prompt_mapping,
  464. lora_requests) = self._prepare_prompt(seq_group_metadata_list)
  465. else:
  466. (input_tokens, input_positions, input_metadata,
  467. lora_index_mapping, lora_prompt_mapping,
  468. lora_requests) = self._prepare_decode(seq_group_metadata_list)
  469. prompt_lens = []
  470. subquery_lens = None
  471. sampling_metadata = self._prepare_sample(seq_group_metadata_list,
  472. prompt_lens,
  473. subquery_lens)
  474. if self.lora_config:
  475. flat_lora_index_mapping = [
  476. item for sublist in lora_index_mapping for item in sublist
  477. ]
  478. lora_mapping = LoRAMapping(
  479. flat_lora_index_mapping,
  480. lora_prompt_mapping,
  481. )
  482. else:
  483. lora_mapping = None
  484. # Broadcast the metadata.
  485. metadata_dict = {
  486. "input_tokens": input_tokens,
  487. "input_positions": input_positions,
  488. "is_prompt": input_metadata.is_prompt,
  489. "slot_mapping": input_metadata.slot_mapping,
  490. "prompt_lens": input_metadata.prompt_lens,
  491. "max_seq_len": input_metadata.max_seq_len,
  492. "start_loc": input_metadata.start_loc,
  493. "max_context_len": input_metadata.max_context_len,
  494. "context_lens": input_metadata.context_lens,
  495. "block_tables": input_metadata.block_tables,
  496. "use_cuda_graph": input_metadata.use_cuda_graph,
  497. "kv_cache_dtype": input_metadata.kv_cache_dtype,
  498. "kv_quant_params": input_metadata.kv_quant_params,
  499. "selected_token_indices":
  500. sampling_metadata.selected_token_indices,
  501. "lora_requests": lora_requests,
  502. "lora_mapping": lora_mapping,
  503. }
  504. broadcast_tensor_dict(metadata_dict, src=0)
  505. else:
  506. metadata_dict = broadcast_tensor_dict(src=0)
  507. input_tokens = metadata_dict["input_tokens"]
  508. input_positions = metadata_dict["input_positions"]
  509. lora_mapping = metadata_dict["lora_mapping"]
  510. lora_requests = metadata_dict["lora_requests"]
  511. input_metadata = InputMetadata(
  512. is_prompt=metadata_dict["is_prompt"],
  513. slot_mapping=metadata_dict["slot_mapping"],
  514. prompt_lens=metadata_dict["prompt_lens"],
  515. max_seq_len=metadata_dict["max_seq_len"],
  516. start_loc=metadata_dict["start_loc"],
  517. max_context_len=metadata_dict["max_context_len"],
  518. context_lens=metadata_dict["context_lens"],
  519. block_tables=metadata_dict["block_tables"],
  520. use_cuda_graph=metadata_dict["use_cuda_graph"],
  521. kv_cache_dtype=metadata_dict["kv_cache_dtype"],
  522. kv_quant_params=metadata_dict["kv_quant_params"],
  523. )
  524. sampling_metadata = SamplingMetadata(
  525. seq_groups=None,
  526. seq_data=None,
  527. prompt_lens=None,
  528. selected_token_indices=metadata_dict["selected_token_indices"],
  529. categorized_sample_indices=None,
  530. generators=None,
  531. perform_sampling=False,
  532. )
  533. return (input_tokens, input_positions, input_metadata,
  534. sampling_metadata, lora_requests, lora_mapping)
  535. @torch.inference_mode()
  536. def execute_model(
  537. self,
  538. seq_group_metadata_list: Optional[List[SequenceGroupMetadata]],
  539. kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],
  540. ) -> Optional[SamplerOutput]:
  541. (input_tokens, input_positions, input_metadata, sampling_metadata,
  542. lora_requests,
  543. lora_mapping) = (self.prepare_input_tensors(seq_group_metadata_list))
  544. if self.lora_config:
  545. self.set_active_loras(lora_requests, lora_mapping)
  546. # Execute the model.
  547. if input_metadata.use_cuda_graph:
  548. graph_batch_size = input_tokens.shape[0]
  549. model_executable = self.graph_runners[graph_batch_size]
  550. else:
  551. model_executable = self.model
  552. hidden_states = model_executable(
  553. input_ids=input_tokens,
  554. positions=input_positions,
  555. kv_caches=kv_caches,
  556. input_metadata=input_metadata,
  557. )
  558. # Sample the next token.
  559. output = self.model.sample(
  560. hidden_states=hidden_states,
  561. sampling_metadata=sampling_metadata,
  562. )
  563. return output
  564. @torch.inference_mode()
  565. def profile_run(self) -> None:
  566. # Enable top-k sampling to reflect the accurate memory usage.
  567. vocab_size = self.model_config.get_vocab_size()
  568. sampling_params = SamplingParams(top_p=0.99, top_k=vocab_size - 1)
  569. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  570. max_num_seqs = self.scheduler_config.max_num_seqs
  571. # This represents the maximum number of different requests
  572. # that will have unique loras, an therefore the max amount of memory
  573. # consumption create dummy lora request copies from the lora request
  574. # passed in, which contains a lora from the lora warmup path.
  575. dummy_lora_requests = []
  576. dummy_lora_requests_per_seq = []
  577. if self.lora_config:
  578. for idx in range(self.lora_config.max_loras):
  579. lora_id = idx + 1
  580. dummy_lora_request = LoRARequest(
  581. lora_name=f"warmup_{lora_id}",
  582. lora_int_id=lora_id,
  583. lora_local_path="/not/a/real/path",
  584. )
  585. self.lora_manager.add_dummy_lora(dummy_lora_request,
  586. rank=LORA_WARMUP_RANK)
  587. dummy_lora_requests.append(dummy_lora_request)
  588. dummy_lora_requests_per_seq = [
  589. dummy_lora_requests[idx % len(dummy_lora_requests)]
  590. for idx in range(max_num_seqs)
  591. ]
  592. # Profile memory usage with max_num_sequences sequences and the total
  593. # number of tokens equal to max_num_batched_tokens.
  594. seqs: List[SequenceGroupMetadata] = []
  595. for group_id in range(max_num_seqs):
  596. seq_len = (max_num_batched_tokens // max_num_seqs +
  597. (group_id < max_num_batched_tokens % max_num_seqs))
  598. seq_data = SequenceData([0] * seq_len)
  599. seq = SequenceGroupMetadata(
  600. request_id=str(group_id),
  601. is_prompt=True,
  602. seq_data={group_id: seq_data},
  603. sampling_params=sampling_params,
  604. block_tables=None,
  605. persistent_data={},
  606. lora_request=dummy_lora_requests_per_seq[group_id]
  607. if dummy_lora_requests_per_seq else None,
  608. )
  609. seqs.append(seq)
  610. # Run the model with the dummy inputs.
  611. num_layers = self.model_config.get_num_layers(self.parallel_config)
  612. kv_caches = [(None, None)] * num_layers
  613. self.execute_model(seqs, kv_caches)
  614. torch.cuda.synchronize()
  615. return
  616. def remove_all_loras(self) -> bool:
  617. if not self.lora_manager:
  618. raise RuntimeError("LoRA is not enabled.")
  619. return self.lora_manager.remove_all_loras()
  620. def set_active_loras(self, lora_requests: List[LoRARequest],
  621. lora_mapping: LoRAMapping) -> None:
  622. if not self.lora_manager:
  623. raise RuntimeError("LoRA is not enabled.")
  624. self.lora_manager.set_active_loras(lora_requests, lora_mapping)
  625. def add_lora(self, lora_request: LoRARequest) -> bool:
  626. if not self.lora_manager:
  627. raise RuntimeError("LoRA is not enabled.")
  628. return self.lora_manager.add_lora(lora_request)
  629. def remove_lora(self, lora_id: int) -> bool:
  630. if not self.lora_manager:
  631. raise RuntimeError("LoRA is not enabled.")
  632. return self.lora_manager.remove_lora(lora_id)
  633. def list_loras(self) -> Set[int]:
  634. if not self.lora_manager:
  635. raise RuntimeError("LoRA is not enabled.")
  636. return self.lora_manager.list_loras()
  637. @torch.inference_mode()
  638. def capture_model(self, kv_caches: List[KVCache]) -> None:
  639. # NOTE: This is a hack to ensure that the NCCL backend is never
  640. # deleted before the CUDA graph
  641. self.cupy_nccl_backend = cupy_utils.get_nccl_backend()
  642. assert not self.model_config.enforce_eager
  643. logger.info("Capturing the model for CUDA graphs. This may lead to "
  644. "unexpected consequences if the model is not static. To "
  645. "run the model in eager mode, set 'enforce_eager=True' or "
  646. "use '--enforce-eager' in the CLI.")
  647. logger.warning("CUDA graphs can take additional 1~3 GiB of memory "
  648. "per GPU. If you are running out of memory, consider "
  649. "decreasing `gpu_memory_utilization` or enforcing "
  650. "eager mode.")
  651. start_time = time.perf_counter()
  652. # Prepare dummy inputs. These will be reused for all batch sizes.
  653. max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)
  654. input_tokens = torch.zeros(max_batch_size, 1, dtype=torch.long).cuda()
  655. input_positions = torch.zeros(max_batch_size, 1,
  656. dtype=torch.long).cuda()
  657. slot_mapping = torch.empty(max_batch_size, 1, dtype=torch.long).cuda()
  658. slot_mapping.fill_(_PAD_SLOT_ID)
  659. context_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()
  660. block_tables = torch.from_numpy(self.graph_block_tables).cuda()
  661. graph_batch_size = _get_graph_batch_size(
  662. self.scheduler_config.max_num_seqs)
  663. batch_size_capture_list = [
  664. bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size
  665. ]
  666. # NOTE: Capturing the largest batch size first may help reduce the
  667. # memory usage of CUDA graph.
  668. # NOTE: There are 3 backends for all-reduce: custom all-reduce
  669. # kernel, CuPy NCCL, and PyTorch NCCL. When using CUDA graph, we use
  670. # either custom all-reduce kernel or CuPy NCCL. When not using CUDA
  671. # graph, we use either custom all-reduce kernel or PyTorch NCCL.
  672. # We always prioritize using custom all-reduce kernel but fall back
  673. # to PyTorch or CuPy NCCL if it is disabled or not supported.
  674. # Initialize a new progress bar
  675. progress = Progress()
  676. task = progress.add_task("[cyan]Capturing graph...",
  677. total=len(batch_size_capture_list))
  678. with progress:
  679. with custom_all_reduce.capture():
  680. for batch_size in reversed(batch_size_capture_list):
  681. if batch_size > self.scheduler_config.max_num_seqs:
  682. continue
  683. # Create dummy input_metadata.
  684. input_metadata = InputMetadata(
  685. is_prompt=False,
  686. slot_mapping=slot_mapping[:batch_size],
  687. prompt_lens=None,
  688. max_seq_len=None,
  689. start_loc=None,
  690. max_context_len=self.max_context_len_to_capture,
  691. context_lens=context_lens[:batch_size],
  692. block_tables=block_tables[:batch_size],
  693. use_cuda_graph=True,
  694. kv_cache_dtype=self.kv_cache_dtype,
  695. kv_quant_params=self.kv_quant_params,
  696. )
  697. if self.lora_config:
  698. lora_mapping = LoRAMapping(
  699. [0] * batch_size,
  700. [0] * batch_size,
  701. )
  702. self.set_active_loras(set(), lora_mapping)
  703. graph_runner = CUDAGraphRunner(self.model)
  704. graph_runner.capture(
  705. input_tokens[:batch_size],
  706. input_positions[:batch_size],
  707. kv_caches,
  708. input_metadata,
  709. memory_pool=self.graph_memory_pool,
  710. )
  711. self.graph_memory_pool = graph_runner.graph.pool()
  712. self.graph_runners[batch_size] = graph_runner
  713. # Update the progress bar
  714. progress.update(task, advance=1)
  715. end_time = time.perf_counter()
  716. elapsed_time = end_time - start_time
  717. # This usually takes < 10 seconds.
  718. logger.info(f"Graph capturing finished in {elapsed_time:.0f} secs.")
  719. def __del__(self) -> None:
  720. # Delete the CUDA graphs before deleting the CuPy NCCL communicator.
  721. # NOTE: This is necessary because otherwise deadlocks can
  722. # happen.
  723. # FIXME: This is a bit hacky. Find a more robust solution.
  724. self.graph_runners.clear()
  725. self.cupy_nccl_backend = None
  726. class CUDAGraphRunner:
  727. def __init__(self, model: nn.Module):
  728. self.model = model
  729. self.graph = None
  730. self.input_buffers: Dict[str, torch.Tensor] = {}
  731. self.output_buffers: Dict[str, torch.Tensor] = {}
  732. def capture(
  733. self,
  734. input_ids: torch.Tensor,
  735. positions: torch.Tensor,
  736. kv_caches: List[KVCache],
  737. input_metadata: InputMetadata,
  738. memory_pool,
  739. ) -> None:
  740. assert self.graph is None
  741. # Run the model once without capturing the graph.
  742. # This is to make sure that the captured graph does not include the
  743. # kernel launches for initial benchmarking (e.g., Triton autotune).
  744. with _maybe_cupy_nccl():
  745. self.model(
  746. input_ids,
  747. positions,
  748. kv_caches,
  749. input_metadata,
  750. )
  751. torch.cuda.synchronize()
  752. # Capture the graph.
  753. # NOTE: Python 3.8 does not support multi-line with statements.
  754. # https://stackoverflow.com/questions/31039022/python-multi-line-with-statement
  755. self.graph = torch.cuda.CUDAGraph()
  756. with torch.cuda.graph(self.graph, pool=memory_pool):
  757. with _maybe_cupy_nccl():
  758. hidden_states = self.model(
  759. input_ids,
  760. positions,
  761. kv_caches,
  762. input_metadata,
  763. )
  764. torch.cuda.synchronize()
  765. # Save the input and output buffers.
  766. self.input_buffers = {
  767. "input_ids": input_ids,
  768. "positions": positions,
  769. "kv_caches": kv_caches,
  770. "slot_mapping": input_metadata.slot_mapping,
  771. "context_lens": input_metadata.context_lens,
  772. "block_tables": input_metadata.block_tables,
  773. }
  774. self.output_buffers = {"hidden_states": hidden_states}
  775. return
  776. def forward(
  777. self,
  778. input_ids: torch.Tensor,
  779. positions: torch.Tensor,
  780. kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],
  781. input_metadata: InputMetadata,
  782. ) -> torch.Tensor:
  783. # KV caches are fixed tensors, so we don't need to copy them.
  784. del kv_caches
  785. # Copy the input tensors to the input buffers.
  786. self.input_buffers["input_ids"].copy_(input_ids, non_blocking=True)
  787. self.input_buffers["positions"].copy_(positions, non_blocking=True)
  788. self.input_buffers["slot_mapping"].copy_(input_metadata.slot_mapping,
  789. non_blocking=True)
  790. self.input_buffers["context_lens"].copy_(input_metadata.context_lens,
  791. non_blocking=True)
  792. self.input_buffers["block_tables"].copy_(input_metadata.block_tables,
  793. non_blocking=True)
  794. # Run the graph.
  795. self.graph.replay()
  796. # Return the output tensor.
  797. return self.output_buffers["hidden_states"]
  798. def __call__(self, *args, **kwargs):
  799. return self.forward(*args, **kwargs)
  800. @contextlib.contextmanager
  801. def _maybe_cupy_nccl():
  802. if cupy_utils.is_initialized() and not custom_all_reduce.is_initialized():
  803. with with_cupy_nccl_for_all_reduce():
  804. yield
  805. else:
  806. yield
  807. def _pad_to_max(x: List[int], max_len: int, pad: int) -> List[int]:
  808. assert len(x) <= max_len
  809. return x + [pad] * (max_len - len(x))
  810. def _make_tensor_with_pad(
  811. x: List[List[int]],
  812. max_len: int,
  813. pad: int,
  814. dtype: torch.dtype,
  815. device: Optional[Union[str, torch.device]],
  816. ) -> torch.Tensor:
  817. padded_x = [_pad_to_max(x_i, max_len, pad) for x_i in x]
  818. return torch.tensor(padded_x, dtype=dtype, device=device)
  819. def _get_graph_batch_size(batch_size: int) -> int:
  820. if batch_size <= 2:
  821. return batch_size
  822. elif batch_size <= 4:
  823. return 4
  824. else:
  825. return (batch_size + 7) // 8 * 8
  826. def _async_h2d(
  827. data: list,
  828. dtype: torch.dtype,
  829. target_device: Union[str, torch.device],
  830. pin_memory: bool,
  831. ) -> torch.Tensor:
  832. t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device="cpu")
  833. return t.to(device=target_device, non_blocking=True)