model_runner.py 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. import dataclasses
  2. import gc
  3. import time
  4. import warnings
  5. from collections import defaultdict
  6. from typing import (TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Set,
  7. Tuple, Type, TypeVar, Union)
  8. import numpy as np
  9. import torch
  10. import torch.distributed
  11. import torch.nn as nn
  12. from loguru import logger
  13. try:
  14. from flashinfer import BatchDecodeWithPagedKVCacheWrapper
  15. from flashinfer.decode import CUDAGraphBatchDecodeWithPagedKVCacheWrapper
  16. from flashinfer.prefill import BatchPrefillWithPagedKVCacheWrapper
  17. FLASHINFER_WORKSPACE_BUFFER_SIZE = 128 * 1024 * 1024
  18. except ImportError:
  19. BatchDecodeWithPagedKVCacheWrapper = None
  20. CUDAGraphBatchDecodeWithPagedKVCacheWrapper = None
  21. BatchPrefillWithPagedKVCacheWrapper = None
  22. FLASHINFER_WORKSPACE_BUFFER_SIZE = 0
  23. from aphrodite.attention import AttentionMetadata, get_attn_backend
  24. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  25. LoRAConfig, ModelConfig, ParallelConfig,
  26. SchedulerConfig, VisionLanguageConfig)
  27. from aphrodite.common.sampling_params import SamplingParams
  28. from aphrodite.common.sequence import (IntermediateTensors, SamplerOutput,
  29. SequenceGroupMetadata)
  30. from aphrodite.common.utils import (CudaMemoryProfiler,
  31. get_kv_cache_torch_dtype, is_hip,
  32. is_pin_memory_available,
  33. make_tensor_with_pad)
  34. from aphrodite.distributed import get_pp_group
  35. from aphrodite.distributed.parallel_state import (
  36. get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size,
  37. graph_capture)
  38. from aphrodite.inputs import INPUT_REGISTRY
  39. from aphrodite.lora.layers import LoRAMapping
  40. from aphrodite.lora.request import LoRARequest
  41. from aphrodite.lora.worker_manager import LRUCacheWorkerLoRAManager
  42. from aphrodite.modeling import SamplingMetadata
  43. from aphrodite.modeling.model_loader import get_model
  44. from aphrodite.modeling.model_loader.tensorizer import TensorizerConfig
  45. from aphrodite.modeling.models.interfaces import supports_lora
  46. from aphrodite.multimodal import (MULTIMODAL_REGISTRY, BatchedTensors,
  47. MultiModalInputs)
  48. from aphrodite.task_handler.model_runner_base import (
  49. ModelRunnerBase, ModelRunnerInputBase,
  50. _add_attn_metadata_broadcastable_dict,
  51. _add_sampling_metadata_broadcastable_dict,
  52. _init_attn_metadata_from_tensor_dict,
  53. _init_sampling_metadata_from_tensor_dict)
  54. if TYPE_CHECKING:
  55. from aphrodite.attention.backends.abstract import AttentionBackend
  56. _PAD_SLOT_ID = -1
  57. LORA_WARMUP_RANK = 8
  58. _BATCH_SIZE_ALIGNMENT = 8
  59. # Capture graphs for token size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.
  60. # NOTE: _get_graph_batch_size needs to be updated if this list is changed.
  61. _BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [
  62. _BATCH_SIZE_ALIGNMENT * i for i in range(1, 33)
  63. ]
  64. _NUM_WARMUP_ITERS = 2
  65. TModelInputForGPU = TypeVar('TModelInputForGPU', bound="ModelInputForGPU")
  66. @dataclasses.dataclass(frozen=True)
  67. class ModelInputForGPU(ModelRunnerInputBase):
  68. """
  69. This base class contains metadata needed for the base model forward pass
  70. but not metadata for possible additional steps, e.g., sampling. Model
  71. runners that run additional steps should subclass this method to add
  72. additional fields.
  73. """
  74. input_tokens: Optional[torch.Tensor] = None
  75. input_positions: Optional[torch.Tensor] = None
  76. seq_lens: Optional[List[int]] = None
  77. query_lens: Optional[List[int]] = None
  78. lora_mapping: Optional["LoRAMapping"] = None
  79. lora_requests: Optional[Set[LoRARequest]] = None
  80. attn_metadata: Optional["AttentionMetadata"] = None
  81. multi_modal_kwargs: Optional[Mapping[str, BatchedTensors]] = None
  82. request_ids_to_seq_ids: Optional[Dict[str, List[int]]] = None
  83. finished_requests_ids: Optional[List[str]] = None
  84. virtual_engine: int = 0
  85. def as_broadcastable_tensor_dict(self) -> Dict[str, Any]:
  86. tensor_dict = {
  87. "input_tokens": self.input_tokens,
  88. "input_positions": self.input_positions,
  89. "lora_requests": self.lora_requests,
  90. "lora_mapping": self.lora_mapping,
  91. "multi_modal_kwargs": self.multi_modal_kwargs,
  92. "virtual_engine": self.virtual_engine,
  93. "request_ids_to_seq_ids": self.request_ids_to_seq_ids,
  94. "finished_requests_ids": self.finished_requests_ids,
  95. }
  96. _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
  97. return tensor_dict
  98. @classmethod
  99. def from_broadcasted_tensor_dict(
  100. cls: Type[TModelInputForGPU],
  101. tensor_dict: Dict[str, Any],
  102. attn_backend: Optional["AttentionBackend"] = None,
  103. ) -> TModelInputForGPU:
  104. if attn_backend is not None:
  105. tensor_dict = _init_attn_metadata_from_tensor_dict(
  106. attn_backend, tensor_dict)
  107. return cls(**tensor_dict)
  108. @dataclasses.dataclass(frozen=True)
  109. class ModelInputForGPUWithSamplingMetadata(ModelInputForGPU):
  110. """
  111. Used by the ModelRunner.
  112. """
  113. sampling_metadata: Optional["SamplingMetadata"] = None
  114. # Used for speculative decoding. We do not broadcast it because it is only
  115. # used by the driver worker.
  116. is_prompt: Optional[bool] = None
  117. def as_broadcastable_tensor_dict(self) -> Dict[str, Any]:
  118. tensor_dict = {
  119. "input_tokens": self.input_tokens,
  120. "input_positions": self.input_positions,
  121. "lora_requests": self.lora_requests,
  122. "lora_mapping": self.lora_mapping,
  123. "multi_modal_kwargs": self.multi_modal_kwargs,
  124. "virtual_engine": self.virtual_engine,
  125. "request_ids_to_seq_ids": self.request_ids_to_seq_ids,
  126. "finished_requests_ids": self.finished_requests_ids,
  127. }
  128. _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
  129. _add_sampling_metadata_broadcastable_dict(tensor_dict,
  130. self.sampling_metadata)
  131. return tensor_dict
  132. @classmethod
  133. def from_broadcasted_tensor_dict(
  134. cls,
  135. tensor_dict: Dict[str, Any],
  136. attn_backend: Optional["AttentionBackend"] = None,
  137. ) -> "ModelInputForGPUWithSamplingMetadata":
  138. tensor_dict = _init_sampling_metadata_from_tensor_dict(tensor_dict)
  139. if attn_backend is not None:
  140. tensor_dict = _init_attn_metadata_from_tensor_dict(
  141. attn_backend, tensor_dict)
  142. return cls(**tensor_dict)
  143. class GPUModelRunnerBase(ModelRunnerBase[TModelInputForGPU]):
  144. """
  145. Helper class for shared methods between GPU model runners.
  146. """
  147. _model_input_cls: Type[TModelInputForGPU]
  148. def __init__(
  149. self,
  150. model_config: ModelConfig,
  151. parallel_config: ParallelConfig,
  152. scheduler_config: SchedulerConfig,
  153. device_config: DeviceConfig,
  154. cache_config: CacheConfig,
  155. load_config: LoadConfig,
  156. lora_config: Optional[LoRAConfig],
  157. kv_cache_dtype: Optional[str] = "auto",
  158. is_driver_worker: bool = False,
  159. vision_language_config: Optional[VisionLanguageConfig] = None,
  160. return_hidden_states: bool = False,
  161. ):
  162. self.model_config = model_config
  163. self.parallel_config = parallel_config
  164. self.scheduler_config = scheduler_config
  165. self.device_config = device_config
  166. self.cache_config = cache_config
  167. self.lora_config = lora_config
  168. self.load_config = load_config
  169. self.is_driver_worker = is_driver_worker
  170. self.vision_language_config = vision_language_config
  171. self.return_hidden_states = return_hidden_states
  172. self.device = self.device_config.device
  173. self.pin_memory = is_pin_memory_available()
  174. self.kv_cache_dtype = kv_cache_dtype
  175. self.sliding_window = model_config.get_sliding_window()
  176. self.block_size = cache_config.block_size
  177. self.max_seq_len_to_capture = self.model_config.max_seq_len_to_capture
  178. self.graph_runners: List[Dict[int, CUDAGraphRunner]] = [
  179. {} for _ in range(self.parallel_config.pipeline_parallel_size)
  180. ]
  181. self.graph_memory_pool: Optional[Tuple[
  182. int, int]] = None # Set during graph capture.
  183. self.has_seqlen_agnostic = model_config.contains_seqlen_agnostic_layers(
  184. parallel_config)
  185. # When using CUDA graph, the input block tables must be padded to
  186. # max_seq_len_to_capture. However, creating the block table in
  187. # Python can be expensive. To optimize this, we cache the block table
  188. # in numpy and only copy the actual input content at every iteration.
  189. # The shape of the cached block table will be
  190. # (max batch size to capture, max context len to capture / block size).
  191. self.graph_block_tables = np.zeros(
  192. (max(_BATCH_SIZES_TO_CAPTURE), self.get_max_block_per_batch()),
  193. dtype=np.int32)
  194. num_attn_heads = self.model_config.get_num_attention_heads(
  195. self.parallel_config)
  196. self.attn_backend = get_attn_backend(
  197. num_attn_heads,
  198. self.model_config.get_head_size(),
  199. self.model_config.get_num_kv_heads(self.parallel_config),
  200. self.model_config.get_sliding_window(),
  201. self.model_config.dtype,
  202. self.kv_cache_dtype,
  203. self.block_size,
  204. ) if num_attn_heads else None
  205. # Multi-modal data support
  206. self.multi_modal_input_mapper = MULTIMODAL_REGISTRY \
  207. .create_input_mapper(self.model_config)
  208. # Lazy initialization
  209. self.model: nn.Module # Set after load_model
  210. # Set after load_model.
  211. self.lora_manager: Optional[LRUCacheWorkerLoRAManager] = None
  212. self.flashinfer_decode_workspace_buffer = None
  213. self.flashinfer_decode_wrapper = None
  214. self.flashinfer_prefill_workspace_buffer = None
  215. self.flashinfer_prefill_wrapper = None
  216. def load_model(self) -> None:
  217. with CudaMemoryProfiler() as m:
  218. # measure the time it takes to load the model
  219. start_time = time.time()
  220. self.model = get_model(
  221. model_config=self.model_config,
  222. device_config=self.device_config,
  223. load_config=self.load_config,
  224. lora_config=self.lora_config,
  225. vision_language_config=self.vision_language_config,
  226. parallel_config=self.parallel_config,
  227. scheduler_config=self.scheduler_config,
  228. cache_config=self.cache_config,
  229. )
  230. end_time = time.time()
  231. self.model_memory_usage = m.consumed_memory
  232. tp = get_tensor_model_parallel_world_size()
  233. rank = get_tensor_model_parallel_rank()
  234. total_time = end_time - start_time
  235. if tp > 1:
  236. logger.info(
  237. f"Rank {rank}: Model weights loaded in {total_time:.2f} secs.")
  238. if rank == 0:
  239. logger.info(
  240. "Memory usage: "
  241. f"{self.model_memory_usage / float(2**30):.2f} GiB x {tp} ="
  242. f" {self.model_memory_usage * tp / float(2**30):.2f} GiB")
  243. else:
  244. logger.info(f"Model weights loaded in {total_time:.2f} seconds.")
  245. logger.info("Memory usage: "
  246. f"{self.model_memory_usage / float(2**30):.2f} GiB")
  247. if self.lora_config:
  248. assert supports_lora(self.model), "Model does not support LoRA"
  249. self.lora_manager = LRUCacheWorkerLoRAManager(
  250. self.scheduler_config.max_num_seqs,
  251. self.scheduler_config.max_num_batched_tokens,
  252. self.vocab_size,
  253. self.lora_config,
  254. self.device,
  255. self.model.embedding_modules,
  256. self.model.embedding_padding_modules,
  257. max_position_embeddings=self.model.config.
  258. max_position_embeddings,
  259. )
  260. self.model = self.lora_manager.create_lora_manager(self.model)
  261. if self.kv_cache_dtype == "fp8" and is_hip():
  262. # Currently only ROCm accepts kv-cache scaling factors
  263. # via quantization_param_path and this will be deprecated
  264. # in the future.
  265. if self.model_config.quantization_param_path is not None:
  266. if callable(getattr(self.model, "load_kv_cache_scales", None)):
  267. warnings.warn(
  268. "Loading kv cache scaling factor from JSON is "
  269. "deprecated and will be removed. Please include "
  270. "kv cache scaling factors in the model checkpoint.",
  271. FutureWarning,
  272. stacklevel=2)
  273. self.model.load_kv_cache_scales(
  274. self.model_config.quantization_param_path)
  275. logger.info(
  276. "Loaded KV cache scaling factors from ",
  277. f"{self.model_config.quantization_param_path}")
  278. else:
  279. raise RuntimeError(
  280. "Using FP8 KV cache and scaling factors provided but "
  281. f"model {self.model.__class__} does not support loading"
  282. " scaling factors.", )
  283. else:
  284. logger.warning(
  285. "Using FP8 KV cache but no scaling factors "
  286. "provided. Defaulting to scaling factors of 1.0. "
  287. "This may lead to less accurate results!")
  288. def save_sharded_state(
  289. self,
  290. path: str,
  291. pattern: Optional[str] = None,
  292. max_size: Optional[int] = None,
  293. ) -> None:
  294. from aphrodite.modeling.model_loader.loader import ShardedStateLoader
  295. ShardedStateLoader.save_model(
  296. self.model,
  297. path,
  298. pattern=pattern,
  299. max_size=max_size,
  300. )
  301. def save_tensorized_model(
  302. self,
  303. tensorizer_config: TensorizerConfig,
  304. ) -> None:
  305. from aphrodite.modeling.model_loader.loader import TensorizerLoader
  306. TensorizerLoader.save_model(
  307. self.model,
  308. tensorizer_config=tensorizer_config,
  309. )
  310. def get_max_block_per_batch(self) -> int:
  311. block_size = self.block_size
  312. return (self.max_seq_len_to_capture + block_size - 1) // block_size
  313. def _prepare_model_input_tensors(
  314. self,
  315. seq_group_metadata_list: List[SequenceGroupMetadata],
  316. finished_requests_ids: Optional[List[str]] = None
  317. ) -> TModelInputForGPU:
  318. """Helper method to prepare the model input based on a given sequence
  319. group. Prepares metadata needed for the base model forward pass but not
  320. metadata for possible additional steps, e.g., sampling.
  321. The API assumes seq_group_metadata_list is sorted by prefill -> decode.
  322. The result tensors and data structure also batches input in prefill
  323. -> decode order. For example,
  324. - input_tokens[:num_prefill_tokens] contains prefill tokens.
  325. - input_tokens[num_prefill_tokens:] contains decode tokens.
  326. If cuda graph is required, this API automatically pads inputs.
  327. """
  328. input_tokens: List[int] = []
  329. input_positions: List[int] = []
  330. slot_mapping: List[int] = []
  331. lora_index_mapping: List[int] = []
  332. lora_prompt_mapping: List[int] = []
  333. lora_requests: Set[LoRARequest] = set()
  334. seq_lens: List[int] = []
  335. prefill_seq_lens: List[int] = []
  336. decode_seq_lens: List[int] = []
  337. context_lens: List[int] = []
  338. query_lens: List[int] = []
  339. block_tables: List[List[int]] = []
  340. multi_modal_inputs_list: List[MultiModalInputs] = []
  341. request_ids_to_seq_ids: Dict[str, List[int]] = defaultdict(list)
  342. decode_only = True
  343. num_prefills = 0
  344. num_prefill_tokens = 0
  345. num_decode_tokens = 0
  346. # The following fields are only for flashinfer
  347. # Please follow https://docs.flashinfer.ai/tutorials/kv_layout.html#page-layout
  348. # for the precise definition of the following fields.
  349. # An example:
  350. # request 1, page indices [0, 5, 8]
  351. # request 2, page indices [1, 6, 7]
  352. # request 3, page indices [3, 4]
  353. # paged_kv_indices is a concatenation of page indices of all requests:
  354. # [0, 5, 8, 1, 6, 7, 3, 4]
  355. # paged_kv_indptr is used to index into paged_kv_indices:
  356. # [0, 3, 6, 8]
  357. paged_kv_indices: List[int] = []
  358. # 0 at the beginning of paged_kv_indptr indicates the start of the
  359. # first request’s page indices in the paged_kv_indices list.
  360. paged_kv_indptr: List[int] = [0]
  361. # paged_kv_last_page_len is the length of the last page of each request
  362. paged_kv_last_page_len: List[int] = []
  363. if len(seq_group_metadata_list) == 0:
  364. return self._model_input_cls()
  365. if self.sliding_window is not None:
  366. sliding_window_blocks = (self.sliding_window + self.block_size -
  367. 1) // self.block_size
  368. block_aligned_sliding_window = \
  369. sliding_window_blocks * self.block_size
  370. for seq_group_metadata in seq_group_metadata_list:
  371. seq_ids = list(seq_group_metadata.seq_data.keys())
  372. is_prompt = seq_group_metadata.is_prompt
  373. for seq_id in seq_ids:
  374. computed_block_nums = seq_group_metadata.computed_block_nums
  375. if (self.scheduler_config is not None
  376. and self.scheduler_config.chunked_prefill_enabled
  377. and not (computed_block_nums is None
  378. or computed_block_nums == [])):
  379. raise RuntimeError(
  380. "chunked prefill cannot be used with prefix caching "
  381. "now.")
  382. seq_data = seq_group_metadata.seq_data[seq_id]
  383. if is_prompt:
  384. context_len = seq_data.get_num_computed_tokens()
  385. else:
  386. # get_num_computed_tokens is incorrect for spec decoding.
  387. # So, we should have a special logic here.
  388. # TODO: Fix it.
  389. context_len = seq_data.get_len() - 1
  390. seq_len = min(
  391. seq_data.get_len(),
  392. context_len + seq_group_metadata.token_chunk_size)
  393. if is_prompt:
  394. tokens = seq_data.get_token_ids()[context_len:seq_len]
  395. else:
  396. # Optimization. get_token_ids requires the entire copy of
  397. # tokens.
  398. tokens = [seq_data.get_last_token_id()]
  399. # Prefix cache was hit.
  400. # Prefix is not supported with sliding_window
  401. prefix_cache_hit = (computed_block_nums is not None
  402. and len(computed_block_nums) > 0
  403. and self.sliding_window is None
  404. and is_prompt)
  405. # These are seq_len/context_len capped to the sliding window.
  406. # They are passed to decode kernel.
  407. # We still need original seq_len/context_len to compute slot
  408. # mapping (and input position) below.
  409. curr_sliding_window_blocks = None
  410. sliding_seq_len = seq_len
  411. sliding_context_len = context_len
  412. # TODO: This is a hack to make sliding window work with
  413. # paged attn. We can remove it if we make paged attn kernel
  414. # to properly handle slinding window attn.
  415. if (self.sliding_window is not None and not is_prompt):
  416. curr_sliding_window_blocks = sliding_window_blocks
  417. if self.scheduler_config.use_v2_block_manager:
  418. # number of elements in last block
  419. suff_len = seq_len % self.block_size
  420. sliding_seq_len = min(
  421. seq_len, block_aligned_sliding_window + suff_len)
  422. if suff_len > 0:
  423. curr_sliding_window_blocks += 1
  424. else:
  425. sliding_seq_len = min(seq_len, self.sliding_window)
  426. sliding_context_len = sliding_seq_len - 1
  427. # TODO: Combine chunked prefill and prefix caching by
  428. # only allowing multiple of block_size chunk size.
  429. # NOTE: This only works for oooooooxxx style attention.
  430. if prefix_cache_hit:
  431. assert computed_block_nums is not None
  432. context_len = len(computed_block_nums) * self.block_size
  433. tokens = tokens[context_len:]
  434. # need to think what to set it to when we have both sliding
  435. # window and prefix caching...
  436. assert self.sliding_window is None, \
  437. "Prefix caching is not supported with sliding window"
  438. sliding_context_len = context_len
  439. if self.attn_backend.get_name() == "flash-attn":
  440. # NOTE: For flash-attn, the block table should
  441. # include the entries for the incoming prefill tokens.
  442. # TODO: This is a temporary fix. We should
  443. # provide a unified interface for different backends.
  444. block_table = seq_group_metadata.block_tables[seq_id]
  445. else:
  446. block_table = computed_block_nums
  447. elif (self.scheduler_config.chunked_prefill_enabled
  448. or not is_prompt):
  449. if seq_group_metadata.block_tables is not None:
  450. # chunked prefill or decode
  451. block_table = seq_group_metadata.block_tables[seq_id]
  452. if curr_sliding_window_blocks is not None:
  453. block_table = block_table[
  454. -curr_sliding_window_blocks:]
  455. else:
  456. # Only happens when memory profiling runs.
  457. block_table = []
  458. else:
  459. # Prefill without chunked prefill or memory profiling.
  460. block_table = []
  461. block_tables.append(block_table)
  462. seq_lens.append(sliding_seq_len)
  463. context_lens.append(sliding_context_len)
  464. query_len = sliding_seq_len - sliding_context_len
  465. query_lens.append(query_len)
  466. input_tokens.extend(tokens)
  467. input_positions.extend(list(range(context_len, seq_len)))
  468. lora_id = seq_group_metadata.lora_int_id
  469. if is_prompt:
  470. assert len(seq_ids) == 1
  471. num_prefills += 1
  472. num_prefill_tokens += len(tokens)
  473. decode_only = False
  474. prefill_seq_lens.append(seq_len)
  475. else:
  476. assert query_len == 1, (
  477. "seq_len: {}, context_len: {}, query_len: {}".format(
  478. seq_len, context_len, query_len))
  479. num_decode_tokens += query_len
  480. decode_seq_lens.append(sliding_seq_len)
  481. if lora_id > 0:
  482. lora_requests.add(seq_group_metadata.lora_request)
  483. lora_index_mapping += [lora_id] * query_len
  484. lora_prompt_mapping.extend(
  485. [lora_id] *
  486. (query_len if seq_group_metadata.sampling_params
  487. and seq_group_metadata.sampling_params.prompt_logprobs
  488. is not None else 1))
  489. mm_data = seq_group_metadata.multi_modal_data
  490. if mm_data:
  491. # Process multi-modal data
  492. mm_kwargs = self.multi_modal_input_mapper(mm_data)
  493. multi_modal_inputs_list.append(mm_kwargs)
  494. is_profile_run = _is_block_tables_empty(
  495. seq_group_metadata.block_tables)
  496. if is_profile_run:
  497. # During memory profiling, the block tables are not
  498. # initialized yet. In this case, we just use a dummy
  499. # slot mapping.
  500. # In embeddings, the block tables are {seq_id: None}.
  501. slot_mapping.extend([_PAD_SLOT_ID] * seq_len)
  502. continue
  503. # Compute the slot mapping.
  504. block_table = seq_group_metadata.block_tables[seq_id]
  505. # Mask the [0, start_idx) tokens of the prompt with
  506. # _PAD_SLOT_ID, where start_idx is max(0, seq_len -
  507. # sliding_window). For example, if the prompt len is 10,
  508. # sliding window is 8, and block size is 4, the first two
  509. # tokens are masked and the slot mapping will be
  510. # [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
  511. start_idx = 0
  512. if self.sliding_window is not None:
  513. if is_prompt:
  514. assert self.scheduler_config.use_v2_block_manager \
  515. or context_len == 0, (
  516. "Prefix caching is currently not supported with "
  517. "sliding window attention in V1 block manager")
  518. # It is an optimization. When it is decoding, it is always
  519. # 0. When prefill, we use it to not write slots to kv cache
  520. # to save memory.
  521. start_idx = max(0, query_len - self.sliding_window)
  522. for i in range(context_len, seq_len):
  523. if i < start_idx:
  524. slot_mapping.append(_PAD_SLOT_ID)
  525. continue
  526. block_number = block_table[i // self.block_size]
  527. block_offset = i % self.block_size
  528. slot = block_number * self.block_size + block_offset
  529. slot_mapping.append(slot)
  530. # Prepare input tensors for flashinfer
  531. if self.attn_backend.get_name() == "flashinfer":
  532. seq_len = seq_data.get_len()
  533. # Get the number of valid blocks based on sequence length.
  534. # If seq_len = 16, block_size = 16,
  535. # block_table_bound is 1 with 1 valid block.
  536. # If seq_len = 15, block_size = 16,
  537. # block_table_bound is 0 + 1 with 1 valid block.
  538. block_table_bound = seq_len // self.block_size + 1 \
  539. if seq_len % self.block_size != 0 \
  540. else seq_len // self.block_size
  541. paged_kv_indices.extend(block_table[:block_table_bound])
  542. paged_kv_indptr.append(paged_kv_indptr[-1] +
  543. block_table_bound)
  544. last_page_len = seq_len % self.block_size
  545. if last_page_len == 0:
  546. last_page_len = self.block_size
  547. paged_kv_last_page_len.append(last_page_len)
  548. batch_size = len(input_tokens)
  549. max_query_len = max(query_lens)
  550. max_prefill_seq_len = max(prefill_seq_lens, default=0)
  551. max_decode_seq_len = max(decode_seq_lens, default=0)
  552. # If cuda graph can be used, pad tensors accordingly.
  553. # See `capture_model` API for more details.
  554. # Aphrodite uses cuda graph only for decoding requests.
  555. use_captured_graph = (
  556. decode_only and not self.model_config.enforce_eager
  557. and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]
  558. and max_decode_seq_len <= self.max_seq_len_to_capture)
  559. if use_captured_graph:
  560. graph_batch_size = _get_graph_batch_size(batch_size)
  561. assert graph_batch_size >= batch_size
  562. for _ in range(graph_batch_size - batch_size):
  563. input_tokens.append(0)
  564. input_positions.append(0)
  565. slot_mapping.append(_PAD_SLOT_ID)
  566. seq_lens.append(1)
  567. block_tables.append([])
  568. lora_index_mapping.append(0)
  569. if self.attn_backend.get_name() == "flashinfer":
  570. last_paged_kv_indptr = paged_kv_indptr[-1]
  571. paged_kv_indptr.append(last_paged_kv_indptr)
  572. paged_kv_last_page_len.append(0)
  573. batch_size = graph_batch_size
  574. num_decode_tokens = batch_size
  575. if use_captured_graph:
  576. # The shape of graph_block_tables is
  577. # [max batch size, max context len // block size].
  578. input_block_tables = self.graph_block_tables[:batch_size]
  579. for i, block_table in enumerate(block_tables):
  580. if block_table:
  581. input_block_tables[i, :len(block_table)] = block_table
  582. block_tables = torch.tensor(input_block_tables, device=self.device)
  583. else:
  584. max_block_table_len = max(
  585. len(block_table) for block_table in block_tables)
  586. block_tables = make_tensor_with_pad(
  587. block_tables,
  588. max_len=max_block_table_len,
  589. pad=0,
  590. dtype=torch.int,
  591. device=self.device,
  592. )
  593. assert max_query_len > 0, ("query_lens: {}".format(query_lens))
  594. context_lens_tensor = torch.tensor(context_lens,
  595. dtype=torch.int,
  596. device=self.device)
  597. seq_lens_tensor = torch.tensor(seq_lens,
  598. dtype=torch.int,
  599. device=self.device)
  600. query_lens_tensor = torch.tensor(query_lens,
  601. dtype=torch.long,
  602. device=self.device)
  603. query_start_loc = torch.zeros(query_lens_tensor.shape[0] + 1,
  604. dtype=torch.int32,
  605. device=self.device)
  606. seq_start_loc = torch.zeros(seq_lens_tensor.shape[0] + 1,
  607. dtype=torch.int32,
  608. device=self.device)
  609. torch.cumsum(seq_lens_tensor,
  610. dim=0,
  611. dtype=seq_start_loc.dtype,
  612. out=seq_start_loc[1:])
  613. torch.cumsum(query_lens_tensor,
  614. dim=0,
  615. dtype=query_start_loc.dtype,
  616. out=query_start_loc[1:])
  617. input_tokens_tensor = torch.tensor(input_tokens,
  618. dtype=torch.long,
  619. device=self.device)
  620. input_positions_tensor = torch.tensor(input_positions,
  621. dtype=torch.long,
  622. device=self.device)
  623. slot_mapping_tensor = torch.tensor(slot_mapping,
  624. dtype=torch.long,
  625. device=self.device)
  626. if self.attn_backend.get_name() == "flashinfer":
  627. if len(paged_kv_indptr) > 0:
  628. paged_kv_indices_tensor = torch.tensor(paged_kv_indices,
  629. device='cpu',
  630. dtype=torch.int)
  631. paged_kv_indptr_tensor = torch.tensor(paged_kv_indptr,
  632. device='cpu',
  633. dtype=torch.int)
  634. paged_kv_last_page_len_tensor = torch.tensor(
  635. paged_kv_last_page_len, device='cpu', dtype=torch.int)
  636. else:
  637. paged_kv_indices_tensor = None
  638. paged_kv_indptr_tensor = None
  639. paged_kv_last_page_len_tensor = None
  640. kv_cache_dtype = get_kv_cache_torch_dtype(self.kv_cache_dtype,
  641. self.model_config.dtype)
  642. attn_metadata = self.attn_backend.make_metadata(
  643. num_prefills=num_prefills,
  644. slot_mapping=slot_mapping_tensor,
  645. num_prefill_tokens=num_prefill_tokens,
  646. num_decode_tokens=num_decode_tokens,
  647. max_prefill_seq_len=max_prefill_seq_len,
  648. block_tables=block_tables,
  649. paged_kv_indptr=paged_kv_indptr_tensor,
  650. paged_kv_indices=paged_kv_indices_tensor,
  651. paged_kv_last_page_len=paged_kv_last_page_len_tensor,
  652. num_qo_heads=self.model_config.get_num_attention_heads(
  653. self.parallel_config),
  654. num_kv_heads=self.model_config.get_num_kv_heads(
  655. self.parallel_config),
  656. head_dim=self.model_config.get_head_size(),
  657. page_size=self.block_size,
  658. seq_start_loc=seq_start_loc,
  659. query_start_loc=query_start_loc,
  660. device=self.device,
  661. data_type=kv_cache_dtype,
  662. use_cuda_graph=use_captured_graph)
  663. else:
  664. attn_metadata = self.attn_backend.make_metadata(
  665. num_prefills=num_prefills,
  666. slot_mapping=slot_mapping_tensor,
  667. num_prefill_tokens=num_prefill_tokens,
  668. num_decode_tokens=num_decode_tokens,
  669. seq_lens=seq_lens,
  670. seq_lens_tensor=seq_lens_tensor,
  671. max_query_len=max_query_len,
  672. max_prefill_seq_len=max_prefill_seq_len,
  673. max_decode_seq_len=max_decode_seq_len,
  674. query_start_loc=query_start_loc,
  675. seq_start_loc=seq_start_loc,
  676. context_lens_tensor=context_lens_tensor,
  677. block_tables=block_tables,
  678. use_cuda_graph=use_captured_graph,
  679. )
  680. if self.lora_config:
  681. lora_mapping = LoRAMapping(
  682. lora_index_mapping,
  683. lora_prompt_mapping,
  684. )
  685. else:
  686. lora_mapping = None
  687. multi_modal_kwargs = MultiModalInputs.batch(multi_modal_inputs_list,
  688. device=self.device)
  689. request_ids_to_seq_ids = {
  690. seq_group_metadata.request_id:
  691. list(seq_group_metadata.seq_data.keys())
  692. for seq_group_metadata in seq_group_metadata_list
  693. }
  694. return self._model_input_cls(
  695. input_tokens=input_tokens_tensor,
  696. input_positions=input_positions_tensor,
  697. attn_metadata=attn_metadata,
  698. seq_lens=seq_lens,
  699. query_lens=query_lens,
  700. lora_mapping=lora_mapping,
  701. lora_requests=lora_requests,
  702. multi_modal_kwargs=multi_modal_kwargs,
  703. request_ids_to_seq_ids=request_ids_to_seq_ids,
  704. finished_requests_ids=finished_requests_ids,
  705. )
  706. @torch.inference_mode()
  707. def profile_run(self) -> None:
  708. # Enable top-k sampling to reflect the accurate memory usage.
  709. sampling_params = SamplingParams(top_p=0.99, top_k=self.vocab_size - 1)
  710. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  711. max_num_seqs = self.scheduler_config.max_num_seqs
  712. # This represents the maximum number of different requests
  713. # that will have unique loras, an therefore the max amount of memory
  714. # consumption create dummy lora request copies from the lora request
  715. # passed in, which contains a lora from the lora warmup path.
  716. dummy_lora_requests: List[LoRARequest] = []
  717. dummy_lora_requests_per_seq: List[LoRARequest] = []
  718. if self.lora_config:
  719. assert self.lora_manager is not None
  720. with self.lora_manager.dummy_lora_cache():
  721. for idx in range(self.lora_config.max_loras):
  722. lora_id = idx + 1
  723. dummy_lora_request = LoRARequest(
  724. lora_name=f"warmup_{lora_id}",
  725. lora_int_id=lora_id,
  726. lora_local_path="/not/a/real/path",
  727. )
  728. self.lora_manager.add_dummy_lora(dummy_lora_request,
  729. rank=LORA_WARMUP_RANK)
  730. dummy_lora_requests.append(dummy_lora_request)
  731. dummy_lora_requests_per_seq = [
  732. dummy_lora_requests[idx % len(dummy_lora_requests)]
  733. for idx in range(max_num_seqs)
  734. ]
  735. # Profile memory usage with max_num_sequences sequences and the total
  736. # number of tokens equal to max_num_batched_tokens.
  737. seqs: List[SequenceGroupMetadata] = []
  738. # Additional GPU memory may be needed for vision encoding, which needs
  739. # to be accounted for when calculating the GPU blocks for
  740. # Aphrodite blocker manager.
  741. # To exercise the worst scenario for GPU memory consumption,
  742. # the number of seqs (batch_size) is chosen to maximize the number
  743. # of images processed.
  744. model_config = self.model_config
  745. vlm_config = self.vision_language_config
  746. if vlm_config:
  747. max_num_seqs = min(
  748. max_num_seqs,
  749. int(max_num_batched_tokens / vlm_config.image_feature_size))
  750. batch_size = 0
  751. for group_id in range(max_num_seqs):
  752. seq_len = (max_num_batched_tokens // max_num_seqs +
  753. (group_id < max_num_batched_tokens % max_num_seqs))
  754. batch_size += seq_len
  755. seq_data, dummy_multi_modal_data = INPUT_REGISTRY \
  756. .dummy_data_for_profiling(model_config, seq_len)
  757. # Having more tokens is over-conservative but otherwise fine
  758. assert len(seq_data.prompt_token_ids) >= seq_len, (
  759. f"Expected at least {seq_len} dummy tokens for profiling, "
  760. f"but got: {len(seq_data.prompt_token_ids)}")
  761. seq = SequenceGroupMetadata(
  762. request_id=str(group_id),
  763. is_prompt=True,
  764. seq_data={group_id: seq_data},
  765. sampling_params=sampling_params,
  766. block_tables=None,
  767. lora_request=dummy_lora_requests_per_seq[group_id]
  768. if dummy_lora_requests_per_seq else None,
  769. multi_modal_data=dummy_multi_modal_data,
  770. )
  771. seqs.append(seq)
  772. # Run the model with the dummy inputs.
  773. num_layers = self.model_config.get_num_layers(self.parallel_config)
  774. kv_caches = [None] * num_layers
  775. finished_requests_ids = [seq.request_id for seq in seqs]
  776. model_input = self.prepare_model_input(
  777. seqs, finished_requests_ids=finished_requests_ids)
  778. intermediate_tensors = None
  779. if not get_pp_group().is_first_rank:
  780. intermediate_tensors = self.model.make_empty_intermediate_tensors(
  781. batch_size=batch_size,
  782. dtype=self.model_config.dtype,
  783. device=self.device)
  784. self.execute_model(model_input, kv_caches, intermediate_tensors)
  785. torch.cuda.synchronize()
  786. return
  787. def remove_all_loras(self):
  788. if not self.lora_manager:
  789. raise RuntimeError("LoRA is not enabled.")
  790. self.lora_manager.remove_all_loras()
  791. def set_active_loras(self, lora_requests: Set[LoRARequest],
  792. lora_mapping: LoRAMapping) -> None:
  793. if not self.lora_manager:
  794. raise RuntimeError("LoRA is not enabled.")
  795. self.lora_manager.set_active_loras(lora_requests, lora_mapping)
  796. def add_lora(self, lora_request: LoRARequest) -> bool:
  797. if not self.lora_manager:
  798. raise RuntimeError("LoRA is not enabled.")
  799. return self.lora_manager.add_lora(lora_request)
  800. def remove_lora(self, lora_id: int) -> bool:
  801. if not self.lora_manager:
  802. raise RuntimeError("LoRA is not enabled.")
  803. return self.lora_manager.remove_lora(lora_id)
  804. def pin_lora(self, lora_id: int) -> bool:
  805. if not self.lora_manager:
  806. raise RuntimeError("LoRA is not enabled.")
  807. return self.lora_manager.pin_lora(lora_id)
  808. def list_loras(self) -> Set[int]:
  809. if not self.lora_manager:
  810. raise RuntimeError("LoRA is not enabled.")
  811. return self.lora_manager.list_loras()
  812. @torch.inference_mode()
  813. def capture_model(self, kv_caches: List[List[torch.Tensor]]) -> None:
  814. """Cuda graph capture a model.
  815. Note that CUDA graph's performance gain is negligible if number
  816. of batched tokens are larger than 200. And since CUDA graph
  817. requires fixed sized tensors, supporting large/variable batch
  818. size requires high GPU memory overhead. Thus, Aphrodite only captures
  819. decoding requests. Mixed batch (chunked prefill + decoding) or
  820. prefill requests are not captured.
  821. Since it is used for decoding-only, it assumes there's only 1 token
  822. per sequence in the batch.
  823. """
  824. assert not self.model_config.enforce_eager
  825. logger.info("Capturing the model for CUDA graphs. This may lead to "
  826. "unexpected consequences if the model is not static. To "
  827. "run the model in eager mode, set 'enforce_eager=True' or "
  828. "use '--enforce-eager' in the CLI.")
  829. logger.info("CUDA graphs can take additional 1~3 GiB memory per GPU. "
  830. "If you are running out of memory, consider decreasing "
  831. "`gpu_memory_utilization` or enforcing eager mode. "
  832. "You can also reduce the `max_num_seqs` as needed "
  833. "to decrease memory usage.")
  834. start_time = time.perf_counter()
  835. # Prepare dummy inputs. These will be reused for all batch sizes.
  836. max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)
  837. input_tokens = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  838. input_positions = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  839. slot_mapping = torch.empty(max_batch_size, dtype=torch.long).cuda()
  840. slot_mapping.fill_(_PAD_SLOT_ID)
  841. seq_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()
  842. block_tables = torch.from_numpy(self.graph_block_tables).cuda()
  843. intermediate_inputs = None
  844. if not get_pp_group().is_first_rank:
  845. intermediate_inputs = self.model.make_empty_intermediate_tensors(
  846. batch_size=max_batch_size,
  847. dtype=self.model_config.dtype,
  848. device=self.device)
  849. # Prepare buffer for outputs. These will be reused for all batch sizes.
  850. # It will be filled after the first graph capture.
  851. hidden_or_intermediate_states: List[Optional[torch.Tensor]] = [
  852. None
  853. ] * self.parallel_config.pipeline_parallel_size
  854. graph_batch_size = _get_graph_batch_size(
  855. self.scheduler_config.max_num_seqs)
  856. batch_size_capture_list = [
  857. bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size
  858. ]
  859. if self.attn_backend.get_name() == "flashinfer":
  860. # For flashinfer, different batch sizes will share the
  861. # same workspace buffer.
  862. decode_workspace_buffer = \
  863. torch.empty(FLASHINFER_WORKSPACE_BUFFER_SIZE,
  864. dtype=torch.uint8,
  865. device=self.device)
  866. indices_buffer = torch.empty(max_batch_size *
  867. self.cache_config.num_gpu_blocks,
  868. dtype=torch.int32,
  869. device=self.device)
  870. indptr_buffer = torch.empty(max_batch_size + 1,
  871. dtype=torch.int32,
  872. device=self.device)
  873. last_page_len_buffer = torch.empty(max_batch_size,
  874. dtype=torch.int32,
  875. device=self.device)
  876. with graph_capture() as graph_capture_context:
  877. # NOTE: Capturing the largest batch size first may help reduce the
  878. # memory usage of CUDA graph.
  879. for virtual_engine in range(
  880. self.parallel_config.pipeline_parallel_size):
  881. for batch_size in reversed(batch_size_capture_list):
  882. if self.attn_backend.get_name() == "flashinfer":
  883. indptr_buffer = indptr_buffer[:batch_size + 1]
  884. last_page_len_buffer = last_page_len_buffer[:
  885. batch_size]
  886. num_qo_heads = (
  887. self.model_config.get_num_attention_heads(
  888. self.parallel_config))
  889. num_kv_heads = self.model_config.get_num_kv_heads(
  890. self.parallel_config)
  891. if num_qo_heads // num_kv_heads >= 4:
  892. use_tensor_cores = True
  893. else:
  894. use_tensor_cores = False
  895. decode_wrapper = \
  896. CUDAGraphBatchDecodeWithPagedKVCacheWrapper(
  897. decode_workspace_buffer, indptr_buffer,
  898. indices_buffer, last_page_len_buffer, "NHD",
  899. use_tensor_cores)
  900. kv_cache_dtype = get_kv_cache_torch_dtype(
  901. self.kv_cache_dtype, self.model_config.dtype)
  902. paged_kv_indptr_tensor_host = torch.arange(
  903. 0, batch_size + 1, dtype=torch.int32)
  904. paged_kv_indices_tensor_host = torch.arange(
  905. 0, batch_size, dtype=torch.int32)
  906. paged_kv_last_page_len_tensor_host = torch.full(
  907. (batch_size, ), self.block_size, dtype=torch.int32)
  908. query_start_loc_host = torch.arange(0,
  909. batch_size + 1,
  910. dtype=torch.int32)
  911. attn_metadata = self.attn_backend.make_metadata(
  912. num_prefills=0,
  913. slot_mapping=slot_mapping[:batch_size],
  914. num_prefill_tokens=0,
  915. num_decode_tokens=batch_size,
  916. max_prefill_seq_len=0,
  917. block_tables=block_tables,
  918. paged_kv_indptr=paged_kv_indptr_tensor_host,
  919. paged_kv_indices=paged_kv_indices_tensor_host,
  920. paged_kv_last_page_len=
  921. paged_kv_last_page_len_tensor_host,
  922. num_qo_heads=num_qo_heads,
  923. num_kv_heads=num_kv_heads,
  924. head_dim=self.model_config.get_head_size(),
  925. page_size=self.block_size,
  926. seq_start_loc=None,
  927. query_start_loc=query_start_loc_host,
  928. device=self.device,
  929. data_type=kv_cache_dtype,
  930. use_cuda_graph=True,
  931. decode_wrapper=decode_wrapper,
  932. prefill_wrapper=None)
  933. attn_metadata.begin_forward()
  934. else:
  935. attn_metadata = self.attn_backend.make_metadata(
  936. num_prefills=0,
  937. num_prefill_tokens=0,
  938. num_decode_tokens=batch_size,
  939. slot_mapping=slot_mapping[:batch_size],
  940. seq_lens=None,
  941. seq_lens_tensor=seq_lens[:batch_size],
  942. max_query_len=None,
  943. max_prefill_seq_len=0,
  944. max_decode_seq_len=self.max_seq_len_to_capture,
  945. query_start_loc=None,
  946. seq_start_loc=None,
  947. context_lens_tensor=None,
  948. block_tables=block_tables[:batch_size],
  949. use_cuda_graph=True,
  950. )
  951. if self.lora_config:
  952. lora_mapping = LoRAMapping(
  953. [0] * batch_size,
  954. [0] * batch_size,
  955. )
  956. self.set_active_loras(set(), lora_mapping)
  957. graph_runner = CUDAGraphRunner(
  958. self.model, self.attn_backend.get_name())
  959. if self.attn_backend.get_name() == "flashinfer":
  960. graph_runner.flashinfer_indptr_buffer = indptr_buffer
  961. graph_runner.flashinfer_indices_buffer = indices_buffer
  962. graph_runner.flashinfer_last_page_len_buffer = \
  963. last_page_len_buffer
  964. graph_runner.flashinfer_decode_workspace_buffer = \
  965. decode_workspace_buffer
  966. graph_runner.flashinfer_decode_wrapper = \
  967. decode_wrapper
  968. capture_inputs = {
  969. "input_ids":
  970. input_tokens[:batch_size],
  971. "positions":
  972. input_positions[:batch_size],
  973. "hidden_or_intermediate_states":
  974. hidden_or_intermediate_states[
  975. virtual_engine] # type: ignore
  976. [:batch_size]
  977. if hidden_or_intermediate_states[virtual_engine]
  978. is not None else None,
  979. "intermediate_inputs":
  980. intermediate_inputs[:batch_size]
  981. if intermediate_inputs is not None else None,
  982. "kv_caches":
  983. kv_caches[virtual_engine],
  984. "attn_metadata":
  985. attn_metadata,
  986. "memory_pool":
  987. self.graph_memory_pool,
  988. "stream":
  989. graph_capture_context.stream
  990. }
  991. if self.has_seqlen_agnostic:
  992. # Only used by Mamba-based models CUDA graph atm (Jamba)
  993. capture_inputs.update({
  994. "seqlen_agnostic_capture_inputs":
  995. self.model.get_seqlen_agnostic_capture_inputs(
  996. batch_size)
  997. })
  998. graph_runner.capture(**capture_inputs)
  999. self.graph_memory_pool = graph_runner.graph.pool()
  1000. self.graph_runners[virtual_engine][batch_size] = (
  1001. graph_runner)
  1002. end_time = time.perf_counter()
  1003. elapsed_time = end_time - start_time
  1004. # This usually takes < 10 seconds.
  1005. logger.info(f"Graph capturing finished in {elapsed_time:2f} secs.")
  1006. @property
  1007. def vocab_size(self) -> int:
  1008. return self.model_config.get_vocab_size()
  1009. class ModelRunner(GPUModelRunnerBase[ModelInputForGPUWithSamplingMetadata]):
  1010. """
  1011. GPU model runner with sampling step.
  1012. """
  1013. _model_input_cls: Type[ModelInputForGPUWithSamplingMetadata] = (
  1014. ModelInputForGPUWithSamplingMetadata)
  1015. def make_model_input_from_broadcasted_tensor_dict(
  1016. self,
  1017. tensor_dict: Dict[str, Any],
  1018. ) -> ModelInputForGPUWithSamplingMetadata:
  1019. model_input = \
  1020. ModelInputForGPUWithSamplingMetadata.from_broadcasted_tensor_dict(
  1021. tensor_dict,
  1022. attn_backend=self.attn_backend,
  1023. )
  1024. return model_input
  1025. def prepare_model_input(
  1026. self,
  1027. seq_group_metadata_list: List[SequenceGroupMetadata],
  1028. virtual_engine: int = 0,
  1029. finished_requests_ids: Optional[List[str]] = None
  1030. ) -> ModelInputForGPUWithSamplingMetadata:
  1031. """Prepare the model input based on a given sequence group, including
  1032. metadata for the sampling step.
  1033. The API assumes seq_group_metadata_list is sorted by prefill -> decode.
  1034. The result tensors and data structure also batches input in prefill
  1035. -> decode order. For example,
  1036. - input_tokens[:num_prefill_tokens] contains prefill tokens.
  1037. - input_tokens[num_prefill_tokens:] contains decode tokens.
  1038. If cuda graph is required, this API automatically pads inputs.
  1039. """
  1040. model_input = self._prepare_model_input_tensors(
  1041. seq_group_metadata_list, finished_requests_ids)
  1042. sampling_metadata = SamplingMetadata.prepare(seq_group_metadata_list,
  1043. model_input.seq_lens,
  1044. model_input.query_lens,
  1045. self.device,
  1046. self.pin_memory)
  1047. is_prompt = (seq_group_metadata_list[0].is_prompt
  1048. if seq_group_metadata_list else None)
  1049. return dataclasses.replace(model_input,
  1050. sampling_metadata=sampling_metadata,
  1051. is_prompt=is_prompt,
  1052. virtual_engine=virtual_engine)
  1053. @torch.inference_mode()
  1054. def execute_model(
  1055. self,
  1056. model_input: ModelInputForGPUWithSamplingMetadata,
  1057. kv_caches: List[torch.Tensor],
  1058. intermediate_tensors: Optional[IntermediateTensors] = None,
  1059. num_steps: int = 1,
  1060. ) -> Optional[Union[List[SamplerOutput], IntermediateTensors]]:
  1061. if num_steps > 1:
  1062. raise ValueError("num_steps > 1 is not supported in ModelRunner")
  1063. if self.lora_config:
  1064. assert model_input.lora_requests is not None
  1065. assert model_input.lora_mapping is not None
  1066. self.set_active_loras(model_input.lora_requests,
  1067. model_input.lora_mapping)
  1068. if self.attn_backend.get_name() == "flashinfer":
  1069. assert model_input.attn_metadata is not None
  1070. assert model_input.input_tokens is not None
  1071. if self.flashinfer_decode_workspace_buffer is None:
  1072. self.flashinfer_decode_workspace_buffer = torch.empty(
  1073. FLASHINFER_WORKSPACE_BUFFER_SIZE,
  1074. dtype=torch.uint8,
  1075. device=self.device)
  1076. self.flashinfer_decode_wrapper = \
  1077. BatchDecodeWithPagedKVCacheWrapper(
  1078. self.flashinfer_decode_workspace_buffer, "NHD")
  1079. self.flashinfer_prefill_workspace_buffer = torch.empty(
  1080. FLASHINFER_WORKSPACE_BUFFER_SIZE,
  1081. dtype=torch.uint8,
  1082. device=self.device)
  1083. self.flashinfer_prefill_wrapper = \
  1084. BatchPrefillWithPagedKVCacheWrapper(
  1085. self.flashinfer_prefill_workspace_buffer, "NHD")
  1086. model_input.attn_metadata.prefill_wrapper = \
  1087. self.flashinfer_prefill_wrapper
  1088. if model_input.attn_metadata.use_cuda_graph:
  1089. batch_size = model_input.input_tokens.shape[0]
  1090. model_input.attn_metadata.decode_wrapper = self.graph_runners[
  1091. batch_size].flashinfer_decode_wrapper
  1092. else:
  1093. model_input.attn_metadata.decode_wrapper = \
  1094. self.flashinfer_decode_wrapper
  1095. model_input.attn_metadata.begin_forward()
  1096. # Currently cuda graph is only supported by the decode phase.
  1097. assert model_input.attn_metadata is not None
  1098. prefill_meta = model_input.attn_metadata.prefill_metadata
  1099. decode_meta = model_input.attn_metadata.decode_metadata
  1100. # TODO: We can remove this once all
  1101. # virtual engines share the same kv cache.
  1102. virtual_engine = model_input.virtual_engine
  1103. if prefill_meta is None and decode_meta.use_cuda_graph:
  1104. assert model_input.input_tokens is not None
  1105. graph_batch_size = model_input.input_tokens.shape[0]
  1106. model_executable = self.graph_runners[virtual_engine][
  1107. graph_batch_size]
  1108. else:
  1109. model_executable = self.model
  1110. multi_modal_kwargs = model_input.multi_modal_kwargs or {}
  1111. seqlen_agnostic_kwargs = {
  1112. "finished_requests_ids": model_input.finished_requests_ids,
  1113. "request_ids_to_seq_ids": model_input.request_ids_to_seq_ids,
  1114. } if self.has_seqlen_agnostic else {}
  1115. hidden_or_intermediate_states = model_executable(
  1116. input_ids=model_input.input_tokens,
  1117. positions=model_input.input_positions,
  1118. kv_caches=kv_caches,
  1119. attn_metadata=model_input.attn_metadata,
  1120. intermediate_tensors=intermediate_tensors,
  1121. **multi_modal_kwargs,
  1122. **seqlen_agnostic_kwargs,
  1123. )
  1124. # Compute the logits in the last pipeline stage.
  1125. if not get_pp_group().is_last_rank:
  1126. return hidden_or_intermediate_states
  1127. logits = self.model.compute_logits(hidden_or_intermediate_states,
  1128. model_input.sampling_metadata)
  1129. if not self.is_driver_worker:
  1130. return []
  1131. # Sample the next token.
  1132. output: SamplerOutput = self.model.sample(
  1133. logits=logits,
  1134. sampling_metadata=model_input.sampling_metadata,
  1135. )
  1136. if self.return_hidden_states:
  1137. # we only need to pass hidden states of most recent token
  1138. assert model_input.sampling_metadata is not None
  1139. indices = model_input.sampling_metadata.selected_token_indices
  1140. if model_input.is_prompt:
  1141. hidden_states = hidden_or_intermediate_states.index_select(
  1142. 0, indices)
  1143. elif decode_meta.use_cuda_graph:
  1144. hidden_states = hidden_or_intermediate_states[:len(indices)]
  1145. else:
  1146. hidden_states = hidden_or_intermediate_states
  1147. output.hidden_states = hidden_states
  1148. return [output]
  1149. class CUDAGraphRunner:
  1150. def __init__(self, model: nn.Module, backend_name: str):
  1151. self.model = model
  1152. self.backend_name = backend_name
  1153. self.input_buffers: Dict[str, torch.Tensor] = {}
  1154. self.output_buffers: Dict[str, torch.Tensor] = {}
  1155. self._graph: Optional[torch.cuda.CUDAGraph] = None
  1156. self.flashinfer_decode_workspace_buffer: Optional[torch.Tensor] = None
  1157. self.flashinfer_indptr_buffer: Optional[torch.Tensor] = None
  1158. self.flashinfer_indices_buffer: Optional[torch.Tensor] = None
  1159. self.flashinfer_last_page_len_buffer: Optional[torch.Tensor] = None
  1160. self.flashinfer_decode_wrapper: Optional[
  1161. CUDAGraphBatchDecodeWithPagedKVCacheWrapper] = None
  1162. @property
  1163. def graph(self):
  1164. assert self._graph is not None
  1165. return self._graph
  1166. def capture(
  1167. self,
  1168. input_ids: torch.Tensor,
  1169. positions: torch.Tensor,
  1170. hidden_or_intermediate_states: Optional[Union[IntermediateTensors,
  1171. torch.Tensor]],
  1172. intermediate_inputs: Optional[IntermediateTensors],
  1173. kv_caches: List[torch.Tensor],
  1174. attn_metadata: AttentionMetadata,
  1175. memory_pool: Optional[Tuple[int, int]],
  1176. stream: torch.cuda.Stream,
  1177. **kwargs,
  1178. ) -> Union[torch.Tensor, IntermediateTensors]:
  1179. assert self._graph is None
  1180. # Run the model a few times without capturing the graph.
  1181. # This is to make sure that the captured graph does not include the
  1182. # kernel launches for initial benchmarking (e.g., Triton autotune).
  1183. # Note one iteration is not enough for torch.jit.script
  1184. for _ in range(_NUM_WARMUP_ITERS):
  1185. self.model(
  1186. input_ids,
  1187. positions,
  1188. kv_caches,
  1189. attn_metadata,
  1190. intermediate_inputs,
  1191. **kwargs,
  1192. )
  1193. torch.cuda.synchronize()
  1194. # Capture the graph.
  1195. self._graph = torch.cuda.CUDAGraph()
  1196. with torch.cuda.graph(self._graph, pool=memory_pool, stream=stream):
  1197. output_hidden_or_intermediate_states = self.model(
  1198. input_ids,
  1199. positions,
  1200. kv_caches,
  1201. attn_metadata,
  1202. intermediate_inputs,
  1203. **kwargs,
  1204. )
  1205. if hidden_or_intermediate_states is not None:
  1206. if get_pp_group().is_last_rank:
  1207. hidden_or_intermediate_states.copy_(
  1208. output_hidden_or_intermediate_states)
  1209. else:
  1210. for key in hidden_or_intermediate_states.tensors:
  1211. hidden_or_intermediate_states[key].copy_(
  1212. output_hidden_or_intermediate_states[key])
  1213. else:
  1214. hidden_or_intermediate_states = (
  1215. output_hidden_or_intermediate_states)
  1216. del output_hidden_or_intermediate_states
  1217. # make sure `output_hidden_states` is deleted
  1218. # in the graph's memory pool
  1219. gc.collect()
  1220. torch.cuda.synchronize()
  1221. # Save the input and output buffers.
  1222. if self.backend_name == "flashinfer":
  1223. self.input_buffers = {
  1224. "input_ids": input_ids,
  1225. "positions": positions,
  1226. "kv_caches": kv_caches,
  1227. "slot_mapping": attn_metadata.slot_mapping,
  1228. **kwargs,
  1229. }
  1230. else:
  1231. self.input_buffers = {
  1232. "input_ids": input_ids,
  1233. "positions": positions,
  1234. "kv_caches": kv_caches,
  1235. "slot_mapping": attn_metadata.slot_mapping,
  1236. "seq_lens_tensor":
  1237. attn_metadata.decode_metadata.seq_lens_tensor,
  1238. "block_tables": attn_metadata.decode_metadata.block_tables,
  1239. **kwargs,
  1240. }
  1241. if intermediate_inputs is not None:
  1242. self.input_buffers.update(intermediate_inputs.tensors)
  1243. if get_pp_group().is_last_rank:
  1244. self.output_buffers = {
  1245. "hidden_states": hidden_or_intermediate_states
  1246. }
  1247. else:
  1248. self.output_buffers = hidden_or_intermediate_states
  1249. return hidden_or_intermediate_states
  1250. def forward(
  1251. self,
  1252. input_ids: torch.Tensor,
  1253. positions: torch.Tensor,
  1254. kv_caches: List[torch.Tensor],
  1255. attn_metadata: AttentionMetadata,
  1256. intermediate_tensors: Optional[IntermediateTensors],
  1257. **kwargs,
  1258. ) -> torch.Tensor:
  1259. # KV caches are fixed tensors, so we don't need to copy them.
  1260. del kv_caches
  1261. # Copy the input tensors to the input buffers.
  1262. self.input_buffers["input_ids"].copy_(input_ids, non_blocking=True)
  1263. self.input_buffers["positions"].copy_(positions, non_blocking=True)
  1264. self.input_buffers["slot_mapping"].copy_(attn_metadata.slot_mapping,
  1265. non_blocking=True)
  1266. if self.backend_name != "flashinfer":
  1267. self.input_buffers["seq_lens_tensor"].copy_(
  1268. attn_metadata.decode_metadata.seq_lens_tensor,
  1269. non_blocking=True)
  1270. self.input_buffers["block_tables"].copy_(
  1271. attn_metadata.decode_metadata.block_tables, non_blocking=True)
  1272. if "seqlen_agnostic_capture_inputs" in self.input_buffers:
  1273. self.model.copy_inputs_before_cuda_graphs(self.input_buffers,
  1274. **kwargs)
  1275. if intermediate_tensors is not None:
  1276. for key in intermediate_tensors.tensors:
  1277. self.input_buffers[key].copy_(intermediate_tensors[key],
  1278. non_blocking=True)
  1279. # Run the graph.
  1280. self.graph.replay()
  1281. if "seqlen_agnostic_capture_inputs" in self.input_buffers:
  1282. self.model.copy_outputs_after_cuda_graphs(self.input_buffers,
  1283. **kwargs)
  1284. # Return the output tensor.
  1285. if get_pp_group().is_last_rank:
  1286. return self.output_buffers["hidden_states"]
  1287. return self.output_buffers
  1288. def __call__(self, *args, **kwargs):
  1289. return self.forward(*args, **kwargs)
  1290. def _get_graph_batch_size(batch_size: int) -> int:
  1291. """Returns the padded batch size given actual batch size.
  1292. Batch sizes are 1, 2, 4, _BATCH_SIZE_ALIGNMENT,
  1293. 2*_BATCH_SIZE_ALIGNMENT, 3*_BATCH_SIZE_ALIGNMENT...
  1294. """
  1295. if batch_size <= 2:
  1296. return batch_size
  1297. elif batch_size <= 4:
  1298. return 4
  1299. else:
  1300. return ((batch_size + _BATCH_SIZE_ALIGNMENT - 1) //
  1301. _BATCH_SIZE_ALIGNMENT * _BATCH_SIZE_ALIGNMENT)
  1302. def _is_block_tables_empty(block_tables: Union[None, Dict]):
  1303. """
  1304. Check if block_tables is None or a dictionary with all None values.
  1305. """
  1306. if block_tables is None:
  1307. return True
  1308. if isinstance(block_tables, dict) and all(
  1309. value is None for value in block_tables.values()):
  1310. return True
  1311. return False