model_runner.py 47 KB

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