model_runner.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  1. import dataclasses
  2. import gc
  3. import itertools
  4. import os
  5. import time
  6. import warnings
  7. import weakref
  8. from dataclasses import dataclass
  9. from typing import (TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Type,
  10. TypeVar, Union)
  11. import numpy as np
  12. import torch
  13. import torch.distributed
  14. import torch.nn as nn
  15. from loguru import logger
  16. try:
  17. from flashinfer import BatchDecodeWithPagedKVCacheWrapper
  18. from flashinfer.decode import CUDAGraphBatchDecodeWithPagedKVCacheWrapper
  19. from flashinfer.prefill import BatchPrefillWithPagedKVCacheWrapper
  20. FLASHINFER_WORKSPACE_BUFFER_SIZE = 256 * 1024 * 1024
  21. except ImportError:
  22. BatchDecodeWithPagedKVCacheWrapper = None
  23. CUDAGraphBatchDecodeWithPagedKVCacheWrapper = None
  24. BatchPrefillWithPagedKVCacheWrapper = None
  25. FLASHINFER_WORKSPACE_BUFFER_SIZE = 0
  26. from aphrodite.attention import AttentionMetadata, get_attn_backend
  27. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  28. LoRAConfig, ModelConfig, ParallelConfig,
  29. PromptAdapterConfig, SchedulerConfig)
  30. from aphrodite.common.sampling_params import SamplingParams
  31. from aphrodite.common.sequence import (IntermediateTensors, SamplerOutput,
  32. SequenceGroupMetadata)
  33. from aphrodite.common.utils import (CudaMemoryProfiler, PyObjectCache,
  34. async_tensor_h2d, flatten_2d_lists,
  35. get_kv_cache_torch_dtype, is_hip,
  36. is_pin_memory_available)
  37. from aphrodite.distributed import get_pp_group
  38. from aphrodite.distributed.parallel_state import (
  39. get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size,
  40. graph_capture)
  41. from aphrodite.inputs import INPUT_REGISTRY, InputRegistry
  42. from aphrodite.lora.layers import LoRAMapping
  43. from aphrodite.lora.request import LoRARequest
  44. from aphrodite.lora.worker_manager import LRUCacheWorkerLoRAManager
  45. from aphrodite.modeling import SamplingMetadata, SamplingMetadataCache
  46. from aphrodite.modeling.model_loader import get_model
  47. from aphrodite.modeling.model_loader.tensorizer import TensorizerConfig
  48. from aphrodite.modeling.models.interfaces import (supports_lora,
  49. supports_multimodal)
  50. from aphrodite.modeling.models.utils import set_cpu_offload_max_bytes
  51. from aphrodite.multimodal import (MULTIMODAL_REGISTRY, BatchedTensorInputs,
  52. MultiModalInputs, MultiModalRegistry)
  53. from aphrodite.prompt_adapter.layers import PromptAdapterMapping
  54. from aphrodite.prompt_adapter.request import PromptAdapterRequest
  55. from aphrodite.prompt_adapter.worker_manager import (
  56. LRUCacheWorkerPromptAdapterManager)
  57. from aphrodite.task_handler.model_runner_base import (
  58. ModelRunnerBase, ModelRunnerInputBase, ModelRunnerInputBuilderBase,
  59. _add_attn_metadata_broadcastable_dict,
  60. _add_sampling_metadata_broadcastable_dict,
  61. _init_attn_metadata_from_tensor_dict,
  62. _init_sampling_metadata_from_tensor_dict)
  63. if TYPE_CHECKING:
  64. from aphrodite.attention.backends.abstract import AttentionBackend
  65. _PAD_SLOT_ID = -1
  66. LORA_WARMUP_RANK = 8
  67. _BATCH_SIZE_ALIGNMENT = 8
  68. # Capture graphs for token size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.
  69. # NOTE: _get_graph_batch_size needs to be updated if this list is changed.
  70. _BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [
  71. _BATCH_SIZE_ALIGNMENT * i for i in range(1, 33)
  72. ]
  73. _NUM_WARMUP_ITERS = 2
  74. APHRODITE_TEST_DYNAMO_GRAPH_CAPTURE = int(
  75. os.environ.get("APHRODITE_TEST_DYNAMO_GRAPH_CAPTURE", "0"))
  76. TModelInputForGPU = TypeVar('TModelInputForGPU', bound="ModelInputForGPU")
  77. @dataclass(frozen=True)
  78. class ModelInputForGPU(ModelRunnerInputBase):
  79. """
  80. This base class contains metadata needed for the base model forward pass
  81. but not metadata for possible additional steps, e.g., sampling. Model
  82. runners that run additional steps should subclass this method to add
  83. additional fields.
  84. """
  85. input_tokens: Optional[torch.Tensor] = None
  86. input_positions: Optional[torch.Tensor] = None
  87. seq_lens: Optional[List[int]] = None
  88. query_lens: Optional[List[int]] = None
  89. lora_mapping: Optional["LoRAMapping"] = None
  90. lora_requests: Optional[Set[LoRARequest]] = None
  91. attn_metadata: Optional["AttentionMetadata"] = None
  92. prompt_adapter_mapping: Optional[PromptAdapterMapping] = None
  93. prompt_adapter_requests: Optional[Set[PromptAdapterRequest]] = None
  94. multi_modal_kwargs: Optional[BatchedTensorInputs] = None
  95. request_ids_to_seq_ids: Optional[Dict[str, List[int]]] = None
  96. finished_requests_ids: Optional[List[str]] = None
  97. virtual_engine: int = 0
  98. def as_broadcastable_tensor_dict(self) -> Dict[str, Any]:
  99. tensor_dict = {
  100. "input_tokens": self.input_tokens,
  101. "input_positions": self.input_positions,
  102. "lora_requests": self.lora_requests,
  103. "lora_mapping": self.lora_mapping,
  104. "multi_modal_kwargs": self.multi_modal_kwargs,
  105. "prompt_adapter_mapping": self.prompt_adapter_mapping,
  106. "prompt_adapter_requests": self.prompt_adapter_requests,
  107. "virtual_engine": self.virtual_engine,
  108. "request_ids_to_seq_ids": self.request_ids_to_seq_ids,
  109. "finished_requests_ids": self.finished_requests_ids,
  110. }
  111. _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
  112. return tensor_dict
  113. @classmethod
  114. def from_broadcasted_tensor_dict(
  115. cls: Type[TModelInputForGPU],
  116. tensor_dict: Dict[str, Any],
  117. attn_backend: Optional["AttentionBackend"] = None,
  118. ) -> TModelInputForGPU:
  119. if attn_backend is not None:
  120. tensor_dict = _init_attn_metadata_from_tensor_dict(
  121. attn_backend, tensor_dict)
  122. return cls(**tensor_dict)
  123. @dataclass(frozen=True)
  124. class ModelInputForGPUWithSamplingMetadata(ModelInputForGPU):
  125. """
  126. Used by the ModelRunner.
  127. """
  128. sampling_metadata: Optional["SamplingMetadata"] = None
  129. # Used for speculative decoding. We do not broadcast it because it is only
  130. # used by the driver worker.
  131. is_prompt: Optional[bool] = None
  132. def as_broadcastable_tensor_dict(self) -> Dict[str, Any]:
  133. tensor_dict = {
  134. "input_tokens": self.input_tokens,
  135. "input_positions": self.input_positions,
  136. "lora_requests": self.lora_requests,
  137. "lora_mapping": self.lora_mapping,
  138. "multi_modal_kwargs": self.multi_modal_kwargs,
  139. "prompt_adapter_mapping": self.prompt_adapter_mapping,
  140. "prompt_adapter_requests": self.prompt_adapter_requests,
  141. "virtual_engine": self.virtual_engine,
  142. "request_ids_to_seq_ids": self.request_ids_to_seq_ids,
  143. "finished_requests_ids": self.finished_requests_ids,
  144. }
  145. _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
  146. _add_sampling_metadata_broadcastable_dict(tensor_dict,
  147. self.sampling_metadata)
  148. return tensor_dict
  149. @classmethod
  150. def from_broadcasted_tensor_dict(
  151. cls,
  152. tensor_dict: Dict[str, Any],
  153. attn_backend: Optional["AttentionBackend"] = None,
  154. ) -> "ModelInputForGPUWithSamplingMetadata":
  155. tensor_dict = _init_sampling_metadata_from_tensor_dict(tensor_dict)
  156. if attn_backend is not None:
  157. tensor_dict = _init_attn_metadata_from_tensor_dict(
  158. attn_backend, tensor_dict)
  159. return cls(**tensor_dict)
  160. class ModelInputForGPUBuilder(ModelRunnerInputBuilderBase[ModelInputForGPU]):
  161. """Build ModelInputForGPU from SequenceGroupMetadata."""
  162. # NOTE: ideally, we dould be using a dataclass(kw_only=True)
  163. # here, so that this can be subclassed easily, but kw_only
  164. # is not supported in python<3.10.
  165. class InterDataForSeqGroup:
  166. """Intermediate data for the current sequence group."""
  167. def simple_reinit(self):
  168. self.input_tokens[0].clear() # type: ignore
  169. self.input_positions[0].clear() # type: ignore
  170. self.seq_lens[0] = 0 # type: ignore
  171. self.orig_seq_lens[0] = 0 # type: ignore
  172. self.query_lens[0] = 0 # type: ignore
  173. self.context_lens[0] = 0 # type: ignore
  174. self.curr_sliding_window_blocks[0] = 0 # type: ignore
  175. self.lora_index_mapping.clear() # type: ignore
  176. self.lora_prompt_mapping.clear() # type: ignore
  177. self.lora_requests.clear() # type: ignore
  178. self.prompt_adapter_index_mapping.clear() # type: ignore
  179. self.prompt_adapter_prompt_mapping.clear() # type: ignore
  180. def __init__(
  181. self,
  182. *,
  183. # From sequence group metadata.
  184. request_id: str,
  185. seq_ids: List[int],
  186. is_prompt: bool,
  187. block_tables: Optional[Dict[int, List[int]]],
  188. computed_block_nums: List[int],
  189. n_seqs: int = 0,
  190. # Input tokens and positions.
  191. input_tokens: Optional[List[List[int]]] = None,
  192. input_positions: Optional[List[List[int]]] = None,
  193. # The sequence length (may be capped to the sliding window).
  194. seq_lens: Optional[List[int]] = None,
  195. # The original sequence length (before applying sliding window).
  196. # This is used to compute slot mapping.
  197. orig_seq_lens: Optional[List[int]] = None,
  198. # The query length.
  199. query_lens: Optional[List[int]] = None,
  200. # The number of tokens that are already computed.
  201. context_lens: Optional[List[int]] = None,
  202. # The current sliding window block.
  203. curr_sliding_window_blocks: Optional[List[int]] = None,
  204. # LoRA inputs.
  205. lora_index_mapping: Optional[List[List[int]]] = None,
  206. lora_prompt_mapping: Optional[List[List[int]]] = None,
  207. lora_requests: Optional[Set[LoRARequest]] = None,
  208. # Prompt adapter inputs.
  209. prompt_adapter_index_mapping: Optional[List[int]] = None,
  210. prompt_adapter_prompt_mapping: Optional[List[int]] = None,
  211. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  212. # Multi-modal inputs.
  213. multi_modal_inputs: Optional[MultiModalInputs] = None,
  214. # Whether the prefix cache is hit (prefill only).
  215. prefix_cache_hit: bool = False,
  216. reinit: bool = False,
  217. reinit_use_defaults: bool = False,
  218. ):
  219. if reinit:
  220. assert len(self.seq_ids) == len(seq_ids) # type: ignore
  221. for i, seq_id in enumerate(seq_ids):
  222. self.seq_ids[i] = seq_id # type: ignore
  223. else:
  224. self.seq_ids = seq_ids
  225. self.request_id = request_id
  226. self.is_prompt = is_prompt
  227. self.block_tables = block_tables
  228. self.computed_block_nums = computed_block_nums
  229. self.n_seqs = n_seqs
  230. if reinit:
  231. if len(self.seq_ids) == 1 and reinit_use_defaults:
  232. self.simple_reinit()
  233. else:
  234. if input_tokens:
  235. self.input_tokens = input_tokens
  236. else:
  237. for seq_id in range(len(self.seq_ids)):
  238. self.input_tokens[seq_id].clear()
  239. if input_positions:
  240. self.input_positions = input_positions
  241. else:
  242. for seq_id in range(len(self.seq_ids)):
  243. self.input_positions[seq_id].clear()
  244. if seq_lens:
  245. self.seq_lens = seq_lens
  246. else:
  247. for seq_id in range(len(self.seq_ids)):
  248. self.seq_lens[seq_id] = 0
  249. if orig_seq_lens:
  250. self.orig_seq_lens = orig_seq_lens
  251. else:
  252. for seq_id in range(len(self.seq_ids)):
  253. self.orig_seq_lens[seq_id] = 0
  254. if query_lens:
  255. self.query_lens = query_lens
  256. else:
  257. for seq_id in range(len(self.seq_ids)):
  258. self.query_lens[seq_id] = 0
  259. if context_lens:
  260. self.context_lens = context_lens
  261. else:
  262. for seq_id in range(len(self.seq_ids)):
  263. self.context_lens[seq_id] = 0
  264. if curr_sliding_window_blocks:
  265. self.curr_sliding_window_blocks = \
  266. curr_sliding_window_blocks
  267. else:
  268. for seq_id in range(len(self.seq_ids)):
  269. self.curr_sliding_window_blocks[seq_id] = 0
  270. if lora_index_mapping:
  271. self.lora_index_mapping = lora_index_mapping
  272. else:
  273. self.lora_index_mapping.clear()
  274. if lora_prompt_mapping:
  275. self.lora_prompt_mapping = lora_prompt_mapping
  276. else:
  277. self.lora_prompt_mapping.clear()
  278. if lora_requests:
  279. self.lora_requests = lora_requests
  280. else:
  281. self.lora_requests.clear()
  282. if prompt_adapter_index_mapping:
  283. self.prompt_adapter_index_mapping = \
  284. prompt_adapter_index_mapping
  285. else:
  286. self.prompt_adapter_index_mapping.clear()
  287. if prompt_adapter_prompt_mapping:
  288. self.prompt_adapter_prompt_mapping = \
  289. prompt_adapter_prompt_mapping
  290. else:
  291. self.prompt_adapter_prompt_mapping.clear()
  292. else:
  293. self.input_tokens = input_tokens or []
  294. self.input_positions = input_positions or []
  295. self.seq_lens = seq_lens or []
  296. self.orig_seq_lens = orig_seq_lens or []
  297. self.query_lens = query_lens or []
  298. self.context_lens = context_lens or []
  299. self.curr_sliding_window_blocks = \
  300. curr_sliding_window_blocks or []
  301. self.lora_index_mapping = lora_index_mapping or []
  302. self.lora_prompt_mapping = lora_prompt_mapping or []
  303. self.lora_requests = lora_requests or set()
  304. self.prompt_adapter_index_mapping = (
  305. prompt_adapter_index_mapping or [])
  306. self.prompt_adapter_prompt_mapping = (
  307. prompt_adapter_prompt_mapping or [])
  308. self.prompt_adapter_request = prompt_adapter_request
  309. self.multi_modal_inputs = multi_modal_inputs
  310. self.prefix_cache_hit = prefix_cache_hit
  311. self.n_seqs = len(self.seq_ids)
  312. if not reinit:
  313. self.__post_init__()
  314. def __post_init__(self):
  315. self.n_seqs = len(self.seq_ids)
  316. self.input_tokens = [[] for _ in range(self.n_seqs)]
  317. self.input_positions = [[] for _ in range(self.n_seqs)]
  318. self.seq_lens = [0] * self.n_seqs
  319. self.orig_seq_lens = [0] * self.n_seqs
  320. self.query_lens = [0] * self.n_seqs
  321. self.context_lens = [0] * self.n_seqs
  322. self.curr_sliding_window_blocks = [0] * self.n_seqs
  323. self.lora_index_mapping = []
  324. self.lora_prompt_mapping = []
  325. def gen_inter_data_builder(self, num_seqs: int):
  326. return lambda: ModelInputForGPUBuilder.InterDataForSeqGroup(
  327. request_id="",
  328. seq_ids=[0] * num_seqs,
  329. is_prompt=True,
  330. block_tables=None,
  331. computed_block_nums=[])
  332. def init_cached_inter_data(self, *args, **kwargs):
  333. assert len(args) == 0
  334. assert "seq_ids" in kwargs
  335. seq_ids = kwargs["seq_ids"]
  336. num_seqs = len(seq_ids)
  337. # The inter-data cache is per model_runner
  338. inter_data_cache = self.runner.inter_data_cache
  339. if num_seqs not in inter_data_cache:
  340. inter_data_cache[num_seqs] = PyObjectCache(
  341. self.gen_inter_data_builder(num_seqs))
  342. obj = inter_data_cache[num_seqs].get_object()
  343. obj.__init__(*args, **kwargs)
  344. return obj
  345. def reset_cached_inter_data(self):
  346. for cache in self.runner.inter_data_cache.values():
  347. cache.reset()
  348. def __init__(self,
  349. runner: "GPUModelRunnerBase",
  350. finished_requests_ids: Optional[List[str]] = None):
  351. super().__init__()
  352. # Compute functions for each sequence in a sequence group.
  353. # WARNING: The order of the functions matters!
  354. self.per_seq_compute_fns = [
  355. self._compute_lens,
  356. self._compute_for_prefix_cache_hit,
  357. self._compute_for_sliding_window,
  358. self._compute_lora_input,
  359. ]
  360. # Compute functions for each sequence group.
  361. # WARNING: The order of the functions matters!
  362. self.per_seq_group_compute_fns = [
  363. self._compute_prompt_adapter_input,
  364. self._compute_multi_modal_input,
  365. ]
  366. self.runner = runner
  367. self.model_input_cls = self.runner._model_input_cls
  368. self.attn_backend = self.runner.attn_backend
  369. self.scheduler_config = self.runner.scheduler_config
  370. self.sliding_window = self.runner.sliding_window
  371. self.block_size = self.runner.block_size
  372. self.enable_lora = self.runner.lora_config is not None
  373. self.enable_prompt_adapter = (self.runner.prompt_adapter_config
  374. is not None)
  375. self.multi_modal_input_mapper = self.runner.multi_modal_input_mapper
  376. self.finished_requests_ids = finished_requests_ids
  377. self.decode_only = True
  378. # Intermediate data (data in CPU before going to GPU) for
  379. # the current sequence group.
  380. self.inter_data_list: List[
  381. ModelInputForGPUBuilder.InterDataForSeqGroup] = []
  382. # Attention metadata inputs.
  383. self.attn_metadata_builder = self.attn_backend.make_metadata_builder(
  384. weakref.proxy(self))
  385. # Engine/Model configurations.
  386. self.chunked_prefill_enabled = (
  387. self.scheduler_config is not None
  388. and self.scheduler_config.chunked_prefill_enabled)
  389. if self.sliding_window is not None:
  390. self.sliding_window_blocks = (
  391. self.sliding_window + self.block_size - 1) // self.block_size
  392. self.block_aligned_sliding_window = \
  393. self.sliding_window_blocks * self.block_size
  394. def _compute_lens(self, inter_data: InterDataForSeqGroup, seq_idx: int,
  395. seq_group_metadata: SequenceGroupMetadata):
  396. """Compute context length, sequence length and tokens
  397. for the given sequence data.
  398. """
  399. seq_data = seq_group_metadata.seq_data[inter_data.seq_ids[seq_idx]]
  400. token_chunk_size = seq_group_metadata.token_chunk_size
  401. # Compute context length (the number of tokens that are
  402. # already computed) and sequence length (total number of tokens).
  403. seq_len = seq_data.get_len()
  404. if inter_data.is_prompt:
  405. context_len = seq_data.get_num_computed_tokens()
  406. else:
  407. # get_num_computed_tokens is incorrect for spec decoding.
  408. # So, we should have a special logic here.
  409. # TODO: Fix it.
  410. context_len = seq_len - 1
  411. seq_len = min(seq_len, context_len + token_chunk_size)
  412. # Compute tokens.
  413. if inter_data.is_prompt:
  414. tokens = seq_data.get_token_ids()
  415. if context_len != 0 or seq_len < len(tokens):
  416. tokens = tokens[context_len:seq_len]
  417. else:
  418. # Optimization. get_token_ids requires the entire copy of
  419. # tokens.
  420. tokens = seq_data.get_last_token_id()
  421. inter_data.seq_lens[seq_idx] = seq_len
  422. inter_data.orig_seq_lens[seq_idx] = seq_len
  423. inter_data.context_lens[seq_idx] = context_len
  424. if isinstance(tokens, list):
  425. inter_data.input_tokens[seq_idx].extend(tokens)
  426. else:
  427. inter_data.input_tokens[seq_idx].append(tokens)
  428. if (seq_len - context_len) == 1:
  429. inter_data.input_positions[seq_idx].append(seq_len - 1)
  430. else:
  431. inter_data.input_positions[seq_idx].extend(
  432. range(context_len, seq_len))
  433. inter_data.query_lens[
  434. seq_idx] = seq_len - context_len if inter_data.is_prompt else 1
  435. def _compute_for_prefix_cache_hit(
  436. self, inter_data: InterDataForSeqGroup, seq_idx: int,
  437. seq_group_metadata: SequenceGroupMetadata):
  438. """Check if hit prefix cache (i.e., some blocks are already computed).
  439. If hit, update input tokens and positions to only compute the
  440. remaining blocks.
  441. """
  442. computed_block_nums = inter_data.computed_block_nums
  443. # Note that prefix caching does not support sliding window.
  444. prefix_cache_hit = (computed_block_nums is not None
  445. and len(computed_block_nums) > 0
  446. and self.sliding_window is None
  447. and inter_data.is_prompt)
  448. inter_data.prefix_cache_hit = prefix_cache_hit
  449. if self.chunked_prefill_enabled and prefix_cache_hit:
  450. raise RuntimeError(
  451. "chunked prefill cannot be used with prefix caching now.")
  452. # If prefix cache is hit, advance context length to bypass
  453. # hit blocks. Accordingly, input tokens, position and query length
  454. # have to be updated.
  455. if prefix_cache_hit:
  456. assert computed_block_nums is not None
  457. context_len = len(computed_block_nums) * self.block_size
  458. inter_data.input_tokens[seq_idx] = inter_data.input_tokens[
  459. seq_idx][context_len:]
  460. inter_data.input_positions[seq_idx] = inter_data.input_positions[
  461. seq_idx][context_len:]
  462. inter_data.context_lens[seq_idx] = context_len
  463. inter_data.query_lens[
  464. seq_idx] = inter_data.seq_lens[seq_idx] - context_len
  465. def _compute_for_sliding_window(self, inter_data: InterDataForSeqGroup,
  466. seq_idx: int,
  467. seq_group_metadata: SequenceGroupMetadata):
  468. """Update seq_len and curr_sliding_window_block for the given
  469. sequence data (only required by decoding) if sliding window is enabled.
  470. """
  471. curr_sliding_window_block = 0
  472. sliding_seq_len = inter_data.seq_lens[seq_idx]
  473. if not inter_data.is_prompt and self.sliding_window is not None:
  474. # TODO: This is a hack to make sliding window work with
  475. # paged attn. We can remove it if we make paged attn kernel
  476. # to properly handle slinding window attn.
  477. curr_sliding_window_block = self.sliding_window_blocks
  478. if self.scheduler_config.use_v2_block_manager:
  479. # number of elements in last block
  480. suff_len = inter_data.seq_lens[seq_idx] % self.block_size
  481. sliding_seq_len = min(
  482. inter_data.seq_lens[seq_idx],
  483. self.block_aligned_sliding_window + suff_len)
  484. if suff_len > 0:
  485. curr_sliding_window_block += 1
  486. else:
  487. sliding_seq_len = min(inter_data.seq_lens[seq_idx],
  488. self.sliding_window)
  489. inter_data.curr_sliding_window_blocks[
  490. seq_idx] = curr_sliding_window_block
  491. inter_data.seq_lens[seq_idx] = sliding_seq_len
  492. def _compute_lora_input(self, inter_data: InterDataForSeqGroup,
  493. seq_idx: int,
  494. seq_group_metadata: SequenceGroupMetadata):
  495. """If LoRA is enabled, compute LoRA index and prompt mapping."""
  496. if not self.enable_lora:
  497. return
  498. lora_id = seq_group_metadata.lora_int_id
  499. if lora_id > 0:
  500. inter_data.lora_requests.add(seq_group_metadata.lora_request)
  501. query_len = inter_data.query_lens[seq_idx]
  502. inter_data.lora_index_mapping.append([lora_id] * query_len)
  503. inter_data.lora_prompt_mapping.append(
  504. [lora_id] *
  505. (query_len if seq_group_metadata.sampling_params
  506. and seq_group_metadata.sampling_params.prompt_logprobs is not None
  507. else 1))
  508. def _compute_prompt_adapter_input(
  509. self, inter_data: InterDataForSeqGroup,
  510. seq_group_metadata: SequenceGroupMetadata):
  511. """If prompt adapter is enabled, compute index and prompt mapping.
  512. """
  513. # Note that when is_prompt=True, we expect only one sequence
  514. # in the group.
  515. if not self.enable_prompt_adapter:
  516. return
  517. prompt_adapter_id = seq_group_metadata.prompt_adapter_id
  518. if prompt_adapter_id <= 0 or not inter_data.is_prompt:
  519. return
  520. # We expect only one sequence in the group when is_prompt=True.
  521. assert inter_data.n_seqs == 1
  522. query_len = inter_data.query_lens[0]
  523. inter_data.prompt_adapter_request = (
  524. seq_group_metadata.prompt_adapter_request)
  525. num_tokens = seq_group_metadata.prompt_adapter_num_virtual_tokens
  526. inter_data.prompt_adapter_index_mapping = [
  527. prompt_adapter_id
  528. ] * num_tokens + [0] * (query_len - num_tokens)
  529. inter_data.prompt_adapter_prompt_mapping = [prompt_adapter_id] * (
  530. query_len if seq_group_metadata.sampling_params
  531. and seq_group_metadata.sampling_params.prompt_logprobs else 1)
  532. def _compute_multi_modal_input(self, inter_data: InterDataForSeqGroup,
  533. seq_group_metadata: SequenceGroupMetadata):
  534. """If multi-modal data is given, add it to the input."""
  535. mm_data = seq_group_metadata.multi_modal_data
  536. if not mm_data:
  537. return
  538. mm_kwargs = self.multi_modal_input_mapper(mm_data)
  539. inter_data.multi_modal_inputs = mm_kwargs
  540. def add_seq_group(self, seq_group_metadata: SequenceGroupMetadata):
  541. """Add a sequence group to the builder."""
  542. seq_ids = seq_group_metadata.seq_data.keys()
  543. n_seqs = len(seq_ids)
  544. is_prompt = seq_group_metadata.is_prompt
  545. if is_prompt:
  546. assert n_seqs == 1
  547. self.decode_only = False
  548. inter_data = self.init_cached_inter_data(
  549. request_id=seq_group_metadata.request_id,
  550. seq_ids=seq_ids,
  551. is_prompt=is_prompt,
  552. block_tables=seq_group_metadata.block_tables,
  553. computed_block_nums=seq_group_metadata.computed_block_nums,
  554. reinit=True,
  555. reinit_use_defaults=True)
  556. self.inter_data_list.append(inter_data)
  557. for seq_idx in range(n_seqs):
  558. for per_seq_fn in self.per_seq_compute_fns:
  559. per_seq_fn(inter_data, seq_idx, seq_group_metadata)
  560. for per_seq_group_fn in self.per_seq_group_compute_fns:
  561. per_seq_group_fn(inter_data, seq_group_metadata)
  562. def _use_captured_graph(self, batch_size: int,
  563. max_decode_seq_len: int) -> bool:
  564. return (self.decode_only and not self.runner.model_config.enforce_eager
  565. and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]
  566. and max_decode_seq_len <= self.runner.max_seq_len_to_capture)
  567. def build(self) -> ModelInputForGPU:
  568. """Finalize the builder intermediate data and
  569. create on-device tensors.
  570. """
  571. # Combine and flatten intermediate data.
  572. input_tokens = []
  573. for inter_data in self.inter_data_list:
  574. for cur_input_tokens in inter_data.input_tokens:
  575. input_tokens.extend(cur_input_tokens)
  576. if not input_tokens:
  577. # This may happen when all prefill requests hit
  578. # prefix caching and there is no decode request.
  579. return self.model_input_cls()
  580. input_positions = []
  581. for inter_data in self.inter_data_list:
  582. for cur_input_positions in inter_data.input_positions:
  583. input_positions.extend(cur_input_positions)
  584. seq_lens = []
  585. max_decode_seq_len = 0
  586. for inter_data in self.inter_data_list:
  587. seq_lens.extend(inter_data.seq_lens)
  588. if not inter_data.is_prompt:
  589. max_decode_seq_len = max(max_decode_seq_len,
  590. max(inter_data.seq_lens))
  591. query_lens = []
  592. for inter_data in self.inter_data_list:
  593. query_lens.extend(inter_data.query_lens)
  594. # Mapping from request IDs to sequence IDs. Used for Jamba models
  595. # that manages the cache by itself.
  596. request_ids_to_seq_ids = {
  597. data.request_id: data.seq_ids
  598. for data in self.inter_data_list
  599. }
  600. batch_size = len(input_tokens)
  601. use_captured_graph = self._use_captured_graph(batch_size,
  602. max_decode_seq_len)
  603. # If cuda graph can be used, pad tensors accordingly.
  604. # See `capture_model` API for more details.
  605. # Aphrodite uses cuda graph only for decoding requests.
  606. cuda_graph_pad_size = -1
  607. if use_captured_graph:
  608. graph_batch_size = _get_graph_batch_size(batch_size)
  609. assert graph_batch_size >= batch_size
  610. cuda_graph_pad_size = graph_batch_size - batch_size
  611. batch_size = graph_batch_size
  612. # Tokens and positions.
  613. if cuda_graph_pad_size:
  614. input_tokens.extend(itertools.repeat(0, cuda_graph_pad_size))
  615. input_positions.extend(itertools.repeat(0, cuda_graph_pad_size))
  616. assert self.runner.device is not None
  617. input_tokens_tensor = async_tensor_h2d(input_tokens, torch.long,
  618. self.runner.device,
  619. self.runner.pin_memory)
  620. input_positions_tensor = async_tensor_h2d(input_positions, torch.long,
  621. self.runner.device,
  622. self.runner.pin_memory)
  623. # Sequence and query lengths.
  624. if cuda_graph_pad_size:
  625. seq_lens.extend(itertools.repeat(1, cuda_graph_pad_size))
  626. # Attention metadata.
  627. attn_metadata = self.attn_metadata_builder.build(
  628. seq_lens, query_lens, cuda_graph_pad_size, batch_size)
  629. # LoRA data.
  630. lora_requests = set()
  631. lora_mapping = None
  632. if self.enable_lora:
  633. lora_requests = set(r for data in self.inter_data_list
  634. for r in data.lora_requests)
  635. lora_index_mapping = flatten_2d_lists([
  636. flatten_2d_lists(inter_data.lora_index_mapping)
  637. for inter_data in self.inter_data_list
  638. ])
  639. if cuda_graph_pad_size:
  640. lora_index_mapping.extend(
  641. itertools.repeat(0, cuda_graph_pad_size))
  642. lora_prompt_mapping = flatten_2d_lists([
  643. flatten_2d_lists(inter_data.lora_prompt_mapping)
  644. for inter_data in self.inter_data_list
  645. ])
  646. lora_mapping = LoRAMapping(
  647. **dict(index_mapping=lora_index_mapping,
  648. prompt_mapping=lora_prompt_mapping,
  649. is_prefill=not self.decode_only))
  650. # Prompt adapter data.
  651. prompt_adapter_requests: Set[PromptAdapterRequest] = set()
  652. prompt_adapter_mapping = None
  653. if self.enable_prompt_adapter:
  654. prompt_adapter_requests = set(
  655. data.prompt_adapter_request for data in self.inter_data_list
  656. if data.prompt_adapter_request is not None)
  657. prompt_adapter_index_mapping = flatten_2d_lists([
  658. inter_data.prompt_adapter_index_mapping
  659. for inter_data in self.inter_data_list
  660. ])
  661. if cuda_graph_pad_size:
  662. prompt_adapter_index_mapping.extend(
  663. itertools.repeat(0, cuda_graph_pad_size))
  664. prompt_adapter_prompt_mapping = flatten_2d_lists([
  665. inter_data.prompt_adapter_prompt_mapping
  666. for inter_data in self.inter_data_list
  667. ])
  668. prompt_adapter_mapping = PromptAdapterMapping(
  669. prompt_adapter_index_mapping,
  670. prompt_adapter_prompt_mapping,
  671. )
  672. # Multi-modal data.
  673. multi_modal_inputs_list = [
  674. data.multi_modal_inputs for data in self.inter_data_list
  675. if data.multi_modal_inputs is not None
  676. ]
  677. multi_modal_kwargs = MultiModalInputs.batch(multi_modal_inputs_list)
  678. return self.model_input_cls(
  679. input_tokens=input_tokens_tensor,
  680. input_positions=input_positions_tensor,
  681. attn_metadata=attn_metadata,
  682. seq_lens=seq_lens,
  683. query_lens=query_lens,
  684. lora_mapping=lora_mapping,
  685. lora_requests=lora_requests,
  686. multi_modal_kwargs=multi_modal_kwargs,
  687. request_ids_to_seq_ids=request_ids_to_seq_ids,
  688. finished_requests_ids=self.finished_requests_ids,
  689. prompt_adapter_mapping=prompt_adapter_mapping,
  690. prompt_adapter_requests=prompt_adapter_requests)
  691. class GPUModelRunnerBase(ModelRunnerBase[TModelInputForGPU]):
  692. """
  693. Helper class for shared methods between GPU model runners.
  694. """
  695. _model_input_cls: Type[TModelInputForGPU]
  696. _builder_cls: Type[ModelInputForGPUBuilder]
  697. def __init__(
  698. self,
  699. model_config: ModelConfig,
  700. parallel_config: ParallelConfig,
  701. scheduler_config: SchedulerConfig,
  702. device_config: DeviceConfig,
  703. cache_config: CacheConfig,
  704. load_config: LoadConfig,
  705. lora_config: Optional[LoRAConfig],
  706. kv_cache_dtype: Optional[str] = "auto",
  707. is_driver_worker: bool = False,
  708. prompt_adapter_config: Optional[PromptAdapterConfig] = None,
  709. return_hidden_states: bool = False,
  710. input_registry: InputRegistry = INPUT_REGISTRY,
  711. mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
  712. tp_rank: int = 0,
  713. ):
  714. self.model_config = model_config
  715. self.parallel_config = parallel_config
  716. self.scheduler_config = scheduler_config
  717. self.device_config = device_config
  718. self.cache_config = cache_config
  719. self.lora_config = lora_config
  720. self.load_config = load_config
  721. self.is_driver_worker = is_driver_worker
  722. self.prompt_adapter_config = prompt_adapter_config
  723. self.return_hidden_states = return_hidden_states
  724. self.device = self.device_config.device
  725. self.pin_memory = is_pin_memory_available()
  726. self.tp_rank = tp_rank
  727. self.kv_cache_dtype = kv_cache_dtype
  728. self.sliding_window = model_config.get_sliding_window()
  729. self.block_size = cache_config.block_size
  730. self.max_seq_len_to_capture = self.model_config.max_seq_len_to_capture
  731. self.graph_runners: List[Dict[int, CUDAGraphRunner]] = [
  732. {} for _ in range(self.parallel_config.pipeline_parallel_size)
  733. ]
  734. self.graph_memory_pool: Optional[Tuple[
  735. int, int]] = None # Set during graph capture.
  736. self.has_seqlen_agnostic = model_config.contains_seqlen_agnostic_layers(
  737. parallel_config)
  738. # When using CUDA graph, the input block tables must be padded to
  739. # max_seq_len_to_capture. However, creating the block table in
  740. # Python can be expensive. To optimize this, we cache the block table
  741. # in numpy and only copy the actual input content at every iteration.
  742. # The shape of the cached block table will be
  743. # (max batch size to capture, max context len to capture / block size).
  744. self.graph_block_tables = np.zeros(
  745. (max(_BATCH_SIZES_TO_CAPTURE), self.get_max_block_per_batch()),
  746. dtype=np.int32)
  747. self.attn_backend = get_attn_backend(
  748. self.model_config.get_head_size(),
  749. self.model_config.get_sliding_window(),
  750. self.model_config.dtype,
  751. self.kv_cache_dtype,
  752. self.block_size,
  753. self.model_config.is_attention_free(),
  754. )
  755. # Multi-modal data support
  756. self.input_registry = input_registry
  757. self.mm_registry = mm_registry
  758. self.multi_modal_input_mapper = mm_registry \
  759. .create_input_mapper(model_config)
  760. self.mm_registry.init_mm_limits_per_prompt(self.model_config)
  761. # Lazy initialization
  762. self.model: nn.Module # Set after load_model
  763. # Set after load_model.
  764. self.lora_manager: Optional[LRUCacheWorkerLoRAManager] = None
  765. self.prompt_adapter_manager: LRUCacheWorkerPromptAdapterManager = None
  766. self.flashinfer_decode_workspace_buffer = None
  767. self.flashinfer_decode_wrapper = None
  768. self.flashinfer_prefill_workspace_buffer = None
  769. self.flashinfer_prefill_wrapper = None
  770. set_cpu_offload_max_bytes(
  771. int(self.cache_config.cpu_offload_gb * 1024**3))
  772. # Used to cache python objects
  773. self.inter_data_cache: Dict[int, PyObjectCache] = {}
  774. self.sampling_metadata_cache: SamplingMetadataCache = \
  775. SamplingMetadataCache()
  776. def load_model(self) -> None:
  777. tp = get_tensor_model_parallel_world_size()
  778. rank = get_tensor_model_parallel_rank()
  779. if rank == 0:
  780. logger.info(f"Loading model {self.model_config.model}...")
  781. with CudaMemoryProfiler() as m:
  782. # measure the time it takes to load the model
  783. start_time = time.time()
  784. self.model = get_model(model_config=self.model_config,
  785. device_config=self.device_config,
  786. load_config=self.load_config,
  787. lora_config=self.lora_config,
  788. parallel_config=self.parallel_config,
  789. scheduler_config=self.scheduler_config,
  790. cache_config=self.cache_config)
  791. end_time = time.time()
  792. self.model_memory_usage = m.consumed_memory
  793. total_time = end_time - start_time
  794. if tp > 1:
  795. if rank == 0:
  796. logger.info(f"Model loaded in {total_time:.2f} seconds.")
  797. logger.info(
  798. "Weights memory usage: "
  799. f"{self.model_memory_usage / float(2**30):.2f} GiB x {tp} ="
  800. f" {self.model_memory_usage * tp / float(2**30):.2f} GiB")
  801. else:
  802. logger.info(f"Model weights loaded in {total_time:.2f} seconds.")
  803. logger.info("Weights memory usage: "
  804. f"{self.model_memory_usage / float(2**30):.2f} GiB")
  805. if self.lora_config:
  806. assert supports_lora(self.model), "Model does not support LoRA"
  807. assert not supports_multimodal(
  808. self.model
  809. ), "To be tested: multimodal language model with LoRA settings."
  810. self.lora_manager = LRUCacheWorkerLoRAManager(
  811. self.scheduler_config.max_num_seqs,
  812. self.scheduler_config.max_num_batched_tokens,
  813. self.vocab_size,
  814. self.lora_config,
  815. self.device,
  816. self.model.embedding_modules,
  817. self.model.embedding_padding_modules,
  818. max_position_embeddings=self.model.config.
  819. max_position_embeddings,
  820. )
  821. self.model = self.lora_manager.create_lora_manager(self.model)
  822. if self.prompt_adapter_config:
  823. self.prompt_adapter_manager = LRUCacheWorkerPromptAdapterManager(
  824. self.scheduler_config.max_num_seqs,
  825. self.scheduler_config.max_num_batched_tokens, self.device,
  826. self.prompt_adapter_config)
  827. self.model = (
  828. self.prompt_adapter_manager.create_prompt_adapter_manager(
  829. self.model))
  830. if self.kv_cache_dtype == "fp8" and is_hip():
  831. # Currently only ROCm accepts kv-cache scaling factors
  832. # via quantization_param_path and this will be deprecated
  833. # in the future.
  834. if self.model_config.quantization_param_path is not None:
  835. if callable(getattr(self.model, "load_kv_cache_scales", None)):
  836. warnings.warn(
  837. "Loading kv cache scaling factor from JSON is "
  838. "deprecated and will be removed. Please include "
  839. "kv cache scaling factors in the model checkpoint.",
  840. FutureWarning,
  841. stacklevel=2)
  842. self.model.load_kv_cache_scales(
  843. self.model_config.quantization_param_path)
  844. logger.info(
  845. "Loaded KV cache scaling factors from ",
  846. f"{self.model_config.quantization_param_path}")
  847. else:
  848. raise RuntimeError(
  849. "Using FP8 KV cache and scaling factors provided but "
  850. f"model {self.model.__class__} does not support loading"
  851. " scaling factors.", )
  852. else:
  853. logger.warning(
  854. "Using FP8 KV cache but no scaling factors "
  855. "provided. Defaulting to scaling factors of 1.0. "
  856. "This may lead to less accurate results!")
  857. if APHRODITE_TEST_DYNAMO_GRAPH_CAPTURE:
  858. logger.info("Compiling the model using torch.compile...")
  859. start_time = time.time()
  860. self.model = torch.compile(self.model,
  861. fullgraph=True,
  862. backend="eager")
  863. end_time = time.time()
  864. logger.info(
  865. f"Model compiled in {end_time - start_time:.2f} seconds.")
  866. def get_model_memory_usage(self):
  867. return self.model_memory_usage
  868. def save_sharded_state(
  869. self,
  870. path: str,
  871. pattern: Optional[str] = None,
  872. max_size: Optional[int] = None,
  873. ) -> None:
  874. from aphrodite.modeling.model_loader.loader import ShardedStateLoader
  875. ShardedStateLoader.save_model(
  876. self.model,
  877. path,
  878. pattern=pattern,
  879. max_size=max_size,
  880. )
  881. def save_tensorized_model(
  882. self,
  883. tensorizer_config: TensorizerConfig,
  884. ) -> None:
  885. from aphrodite.modeling.model_loader.loader import TensorizerLoader
  886. TensorizerLoader.save_model(
  887. self.model,
  888. tensorizer_config=tensorizer_config,
  889. )
  890. def get_max_block_per_batch(self) -> int:
  891. block_size = self.block_size
  892. return (self.max_seq_len_to_capture + block_size - 1) // block_size
  893. def _prepare_model_input_tensors(
  894. self,
  895. seq_group_metadata_list: List[SequenceGroupMetadata],
  896. finished_requests_ids: Optional[List[str]] = None
  897. ) -> TModelInputForGPU:
  898. """Helper method to prepare the model input based on a given sequence
  899. group. Prepares metadata needed for the base model forward pass but not
  900. metadata for possible additional steps, e.g., sampling.
  901. The API assumes seq_group_metadata_list is sorted by prefill -> decode.
  902. The result tensors and data structure also batches input in prefill
  903. -> decode order. For example,
  904. - input_tokens[:num_prefill_tokens] contains prefill tokens.
  905. - input_tokens[num_prefill_tokens:] contains decode tokens.
  906. If cuda graph is required, this API automatically pads inputs.
  907. """
  908. builder = self._builder_cls(weakref.proxy(self), finished_requests_ids)
  909. for seq_group_metadata in seq_group_metadata_list:
  910. builder.add_seq_group(seq_group_metadata)
  911. builder.reset_cached_inter_data()
  912. return builder.build() # type: ignore
  913. @torch.inference_mode()
  914. def profile_run(self) -> None:
  915. rank = get_tensor_model_parallel_rank()
  916. if rank == 0:
  917. logger.info("Profiling peak memory usage...")
  918. # Enable top-k sampling to reflect the accurate memory usage.
  919. sampling_params = SamplingParams(top_p=0.99, top_k=self.vocab_size - 1)
  920. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  921. max_num_seqs = self.scheduler_config.max_num_seqs
  922. # This represents the maximum number of different requests
  923. # that will have unique loras, an therefore the max amount of memory
  924. # consumption create dummy lora request copies from the lora request
  925. # passed in, which contains a lora from the lora warmup path.
  926. dummy_lora_requests: List[LoRARequest] = []
  927. dummy_lora_requests_per_seq: List[LoRARequest] = []
  928. if self.lora_config:
  929. assert self.lora_manager is not None
  930. with self.lora_manager.dummy_lora_cache():
  931. for idx in range(self.lora_config.max_loras):
  932. lora_id = idx + 1
  933. dummy_lora_request = LoRARequest(
  934. lora_name=f"warmup_{lora_id}",
  935. lora_int_id=lora_id,
  936. lora_local_path="/not/a/real/path",
  937. )
  938. self.lora_manager.add_dummy_lora(dummy_lora_request,
  939. rank=LORA_WARMUP_RANK)
  940. dummy_lora_requests.append(dummy_lora_request)
  941. dummy_lora_requests_per_seq = [
  942. dummy_lora_requests[idx % len(dummy_lora_requests)]
  943. for idx in range(max_num_seqs)
  944. ]
  945. # Profile memory usage with max_num_sequences sequences and the total
  946. # number of tokens equal to max_num_batched_tokens.
  947. seqs: List[SequenceGroupMetadata] = []
  948. # Additional GPU memory may be needed for multi-modal encoding, which
  949. # needs to be accounted for when calculating the GPU blocks for
  950. # Aphrodite blocker manager.
  951. # To exercise the worst scenario for GPU memory consumption,
  952. # the number of seqs (batch_size) is chosen to maximize the number
  953. # of images processed.
  954. max_mm_tokens = self.mm_registry.get_max_multimodal_tokens(
  955. self.model_config)
  956. if max_mm_tokens > 0:
  957. max_num_seqs_orig = max_num_seqs
  958. max_num_seqs = min(max_num_seqs,
  959. max_num_batched_tokens // max_mm_tokens)
  960. if max_num_seqs < 1:
  961. expr = (f"min({max_num_seqs_orig}, "
  962. f"{max_num_batched_tokens} // {max_mm_tokens})")
  963. logger.warning(
  964. f"Computed max_num_seqs ({expr}) to be less than 1. "
  965. "Setting it to the minimum value of 1.")
  966. max_num_seqs = 1
  967. batch_size = 0
  968. for group_id in range(max_num_seqs):
  969. seq_len = (max_num_batched_tokens // max_num_seqs +
  970. (group_id < max_num_batched_tokens % max_num_seqs))
  971. batch_size += seq_len
  972. seq_data, dummy_multi_modal_data = self.input_registry \
  973. .dummy_data_for_profiling(self.model_config,
  974. seq_len,
  975. self.mm_registry)
  976. seq = SequenceGroupMetadata(
  977. request_id=str(group_id),
  978. is_prompt=True,
  979. seq_data={group_id: seq_data},
  980. sampling_params=sampling_params,
  981. block_tables=None,
  982. lora_request=dummy_lora_requests_per_seq[group_id]
  983. if dummy_lora_requests_per_seq else None,
  984. multi_modal_data=dummy_multi_modal_data,
  985. )
  986. seqs.append(seq)
  987. # Run the model with the dummy inputs.
  988. num_layers = self.model_config.get_num_layers(self.parallel_config)
  989. kv_caches = [None] * num_layers
  990. finished_requests_ids = [seq.request_id for seq in seqs]
  991. model_input = self.prepare_model_input(
  992. seqs, finished_requests_ids=finished_requests_ids)
  993. intermediate_tensors = None
  994. if not get_pp_group().is_first_rank:
  995. intermediate_tensors = self.model.make_empty_intermediate_tensors(
  996. batch_size=batch_size,
  997. dtype=self.model_config.dtype,
  998. device=self.device)
  999. self.execute_model(model_input, kv_caches, intermediate_tensors)
  1000. torch.cuda.synchronize()
  1001. return
  1002. def remove_all_loras(self):
  1003. if not self.lora_manager:
  1004. raise RuntimeError("LoRA is not enabled.")
  1005. self.lora_manager.remove_all_adapters()
  1006. def set_active_loras(self, lora_requests: Set[LoRARequest],
  1007. lora_mapping: LoRAMapping) -> None:
  1008. if not self.lora_manager:
  1009. raise RuntimeError("LoRA is not enabled.")
  1010. self.lora_manager.set_active_adapters(lora_requests, lora_mapping)
  1011. def add_lora(self, lora_request: LoRARequest) -> bool:
  1012. if not self.lora_manager:
  1013. raise RuntimeError("LoRA is not enabled.")
  1014. return self.lora_manager.add_adapter(lora_request)
  1015. def remove_lora(self, lora_id: int) -> bool:
  1016. if not self.lora_manager:
  1017. raise RuntimeError("LoRA is not enabled.")
  1018. return self.lora_manager.remove_adapter(lora_id)
  1019. def pin_lora(self, lora_id: int) -> bool:
  1020. if not self.lora_manager:
  1021. raise RuntimeError("LoRA is not enabled.")
  1022. return self.lora_manager.pin_adapter(lora_id)
  1023. def list_loras(self) -> Set[int]:
  1024. if not self.lora_manager:
  1025. raise RuntimeError("LoRA is not enabled.")
  1026. return self.lora_manager.list_adapters()
  1027. def remove_all_prompt_adapters(self):
  1028. if not self.prompt_adapter_manager:
  1029. raise RuntimeError("PromptAdapter is not enabled.")
  1030. self.prompt_adapter_manager.remove_all_adapters()
  1031. def set_active_prompt_adapters(
  1032. self, prompt_adapter_requests: Set[PromptAdapterRequest],
  1033. prompt_adapter_mapping: PromptAdapterMapping) -> None:
  1034. if not self.prompt_adapter_manager:
  1035. raise RuntimeError("PromptAdapter is not enabled.")
  1036. self.prompt_adapter_manager.set_active_adapters(
  1037. prompt_adapter_requests, prompt_adapter_mapping)
  1038. def add_prompt_adapter(
  1039. self, prompt_adapter_request: PromptAdapterRequest) -> bool:
  1040. if not self.prompt_adapter_manager:
  1041. raise RuntimeError("PromptAdapter is not enabled.")
  1042. return self.prompt_adapter_manager.add_adapter(prompt_adapter_request)
  1043. def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool:
  1044. if not self.prompt_adapter_manager:
  1045. raise RuntimeError("PromptAdapter is not enabled.")
  1046. return self.prompt_adapter_manager.remove_adapter(prompt_adapter_id)
  1047. def pin_prompt_adapter(self, prompt_adapter_id: int) -> bool:
  1048. if not self.prompt_adapter_manager:
  1049. raise RuntimeError("PromptAdapter is not enabled.")
  1050. return self.prompt_adapter_manager.pin_adapter(prompt_adapter_id)
  1051. def list_prompt_adapters(self) -> Set[int]:
  1052. if not self.prompt_adapter_manager:
  1053. raise RuntimeError("PromptAdapter is not enabled.")
  1054. return self.prompt_adapter_manager.list_adapters()
  1055. @torch.inference_mode()
  1056. def capture_model(self, kv_caches: List[List[torch.Tensor]]) -> None:
  1057. """Cuda graph capture a model.
  1058. Note that CUDA graph's performance gain is negligible if number
  1059. of batched tokens are larger than 200. And since CUDA graph
  1060. requires fixed sized tensors, supporting large/variable batch
  1061. size requires high GPU memory overhead. Thus, Aphrodite only captures
  1062. decoding requests. Mixed batch (chunked prefill + decoding) or
  1063. prefill requests are not captured.
  1064. Since it is used for decoding-only, it assumes there's only 1 token
  1065. per sequence in the batch.
  1066. """
  1067. tp_rank = get_tensor_model_parallel_rank()
  1068. assert not self.model_config.enforce_eager
  1069. if tp_rank == 0:
  1070. logger.info(
  1071. "Capturing the model for CUDA graphs. This may lead to "
  1072. "unexpected consequences if the model is not static. To "
  1073. "run the model in eager mode, set 'enforce_eager=True' or "
  1074. "use '--enforce-eager' in the CLI.")
  1075. logger.info(
  1076. "CUDA graphs can take additional 1~3 GiB memory per GPU. "
  1077. "If you are running out of memory, consider decreasing "
  1078. "`gpu_memory_utilization` or enforcing eager mode. "
  1079. "You can also reduce the `max_num_seqs` as needed "
  1080. "to decrease memory usage.")
  1081. start_time = time.perf_counter()
  1082. # Prepare dummy inputs. These will be reused for all batch sizes.
  1083. max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)
  1084. input_tokens = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  1085. input_positions = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  1086. slot_mapping = torch.empty(max_batch_size, dtype=torch.long).cuda()
  1087. slot_mapping.fill_(_PAD_SLOT_ID)
  1088. seq_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()
  1089. block_tables = torch.from_numpy(self.graph_block_tables).cuda()
  1090. intermediate_inputs = None
  1091. if not get_pp_group().is_first_rank:
  1092. intermediate_inputs = self.model.make_empty_intermediate_tensors(
  1093. batch_size=max_batch_size,
  1094. dtype=self.model_config.dtype,
  1095. device=self.device)
  1096. # Prepare buffer for outputs. These will be reused for all batch sizes.
  1097. # It will be filled after the first graph capture.
  1098. hidden_or_intermediate_states: List[Optional[torch.Tensor]] = [
  1099. None
  1100. ] * self.parallel_config.pipeline_parallel_size
  1101. graph_batch_size = _get_graph_batch_size(
  1102. self.scheduler_config.max_num_seqs)
  1103. batch_size_capture_list = [
  1104. bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size
  1105. ]
  1106. if self.attn_backend.get_name() == "flashinfer":
  1107. # For flashinfer, different batch sizes will share the
  1108. # same workspace buffer.
  1109. decode_workspace_buffer = \
  1110. torch.empty(FLASHINFER_WORKSPACE_BUFFER_SIZE,
  1111. dtype=torch.uint8,
  1112. device=self.device)
  1113. indices_buffer = torch.empty(max_batch_size *
  1114. self.cache_config.num_gpu_blocks,
  1115. dtype=torch.int32,
  1116. device=self.device)
  1117. indptr_buffer = torch.empty(max_batch_size + 1,
  1118. dtype=torch.int32,
  1119. device=self.device)
  1120. last_page_len_buffer = torch.empty(max_batch_size,
  1121. dtype=torch.int32,
  1122. device=self.device)
  1123. with graph_capture() as graph_capture_context:
  1124. # NOTE: Capturing the largest batch size first may help reduce the
  1125. # memory usage of CUDA graph.
  1126. for virtual_engine in range(
  1127. self.parallel_config.pipeline_parallel_size):
  1128. for batch_size in reversed(batch_size_capture_list):
  1129. if self.attn_backend.get_name() == "flashinfer":
  1130. _indptr_buffer = indptr_buffer[:batch_size + 1]
  1131. _last_page_len_buffer = last_page_len_buffer[:
  1132. batch_size]
  1133. num_qo_heads = (
  1134. self.model_config.get_num_attention_heads(
  1135. self.parallel_config, self.tp_rank))
  1136. num_kv_heads = self.model_config.get_num_kv_heads(
  1137. self.parallel_config, self.tp_rank)
  1138. if num_qo_heads // num_kv_heads >= 4:
  1139. use_tensor_cores = True
  1140. else:
  1141. use_tensor_cores = False
  1142. decode_wrapper = \
  1143. CUDAGraphBatchDecodeWithPagedKVCacheWrapper(
  1144. decode_workspace_buffer, _indptr_buffer,
  1145. indices_buffer, _last_page_len_buffer, "NHD",
  1146. use_tensor_cores)
  1147. kv_cache_dtype = get_kv_cache_torch_dtype(
  1148. self.kv_cache_dtype, self.model_config.dtype)
  1149. paged_kv_indptr_tensor_host = torch.arange(
  1150. 0, batch_size + 1, dtype=torch.int32)
  1151. paged_kv_indices_tensor_host = torch.arange(
  1152. 0, batch_size, dtype=torch.int32)
  1153. paged_kv_last_page_len_tensor_host = torch.full(
  1154. (batch_size, ), self.block_size, dtype=torch.int32)
  1155. query_start_loc_host = torch.arange(0,
  1156. batch_size + 1,
  1157. dtype=torch.int32)
  1158. attn_metadata = self.attn_backend.make_metadata(
  1159. num_prefills=0,
  1160. slot_mapping=slot_mapping[:batch_size],
  1161. num_prefill_tokens=0,
  1162. num_decode_tokens=batch_size,
  1163. max_prefill_seq_len=0,
  1164. block_tables=block_tables,
  1165. paged_kv_indptr=paged_kv_indptr_tensor_host,
  1166. paged_kv_indices=paged_kv_indices_tensor_host,
  1167. paged_kv_last_page_len=
  1168. paged_kv_last_page_len_tensor_host,
  1169. num_qo_heads=num_qo_heads,
  1170. num_kv_heads=num_kv_heads,
  1171. head_dim=self.model_config.get_head_size(),
  1172. page_size=self.block_size,
  1173. seq_start_loc=None,
  1174. query_start_loc=query_start_loc_host,
  1175. device=self.device,
  1176. data_type=kv_cache_dtype,
  1177. use_cuda_graph=True,
  1178. decode_wrapper=decode_wrapper,
  1179. prefill_wrapper=None)
  1180. attn_metadata.begin_forward()
  1181. else:
  1182. attn_metadata = self.attn_backend.make_metadata(
  1183. num_prefills=0,
  1184. num_prefill_tokens=0,
  1185. num_decode_tokens=batch_size,
  1186. slot_mapping=slot_mapping[:batch_size],
  1187. seq_lens=None,
  1188. seq_lens_tensor=seq_lens[:batch_size],
  1189. max_query_len=None,
  1190. max_prefill_seq_len=0,
  1191. max_decode_seq_len=self.max_seq_len_to_capture,
  1192. query_start_loc=None,
  1193. seq_start_loc=None,
  1194. context_lens_tensor=None,
  1195. block_tables=block_tables[:batch_size],
  1196. use_cuda_graph=True,
  1197. )
  1198. if self.lora_config:
  1199. lora_mapping = LoRAMapping(
  1200. **dict(index_mapping=[0] * batch_size,
  1201. prompt_mapping=[0] * batch_size,
  1202. is_prefill=False))
  1203. self.set_active_loras(set(), lora_mapping)
  1204. if self.prompt_adapter_config:
  1205. prompt_adapter_mapping = PromptAdapterMapping(
  1206. [-1] * batch_size,
  1207. [-1] * batch_size,
  1208. )
  1209. self.set_active_prompt_adapters(
  1210. set(), prompt_adapter_mapping)
  1211. graph_runner = CUDAGraphRunner(
  1212. self.model, self.attn_backend.get_name())
  1213. if self.attn_backend.get_name() == "flashinfer":
  1214. graph_runner.flashinfer_indptr_buffer = _indptr_buffer
  1215. graph_runner.flashinfer_indices_buffer = indices_buffer
  1216. graph_runner.flashinfer_last_page_len_buffer = \
  1217. _last_page_len_buffer
  1218. graph_runner.flashinfer_decode_workspace_buffer = \
  1219. decode_workspace_buffer
  1220. graph_runner.flashinfer_decode_wrapper = \
  1221. decode_wrapper
  1222. capture_inputs = {
  1223. "input_ids":
  1224. input_tokens[:batch_size],
  1225. "positions":
  1226. input_positions[:batch_size],
  1227. "hidden_or_intermediate_states":
  1228. hidden_or_intermediate_states[
  1229. virtual_engine] # type: ignore
  1230. [:batch_size]
  1231. if hidden_or_intermediate_states[virtual_engine]
  1232. is not None else None,
  1233. "intermediate_inputs":
  1234. intermediate_inputs[:batch_size]
  1235. if intermediate_inputs is not None else None,
  1236. "kv_caches":
  1237. kv_caches[virtual_engine],
  1238. "attn_metadata":
  1239. attn_metadata,
  1240. "memory_pool":
  1241. self.graph_memory_pool,
  1242. "stream":
  1243. graph_capture_context.stream
  1244. }
  1245. if self.has_seqlen_agnostic:
  1246. # Only used by Mamba-based models CUDA graph atm (Jamba)
  1247. capture_inputs.update({
  1248. "seqlen_agnostic_capture_inputs":
  1249. self.model.get_seqlen_agnostic_capture_inputs(
  1250. batch_size)
  1251. })
  1252. graph_runner.capture(**capture_inputs)
  1253. self.graph_memory_pool = graph_runner.graph.pool()
  1254. self.graph_runners[virtual_engine][batch_size] = (
  1255. graph_runner)
  1256. end_time = time.perf_counter()
  1257. elapsed_time = end_time - start_time
  1258. # This usually takes < 10 seconds.
  1259. if tp_rank == 0:
  1260. logger.info(f"Graph capturing finished in {elapsed_time:.2f} secs")
  1261. @property
  1262. def vocab_size(self) -> int:
  1263. return self.model_config.get_vocab_size()
  1264. class ModelRunner(GPUModelRunnerBase[ModelInputForGPUWithSamplingMetadata]):
  1265. """
  1266. GPU model runner with sampling step.
  1267. """
  1268. _model_input_cls: Type[ModelInputForGPUWithSamplingMetadata] = (
  1269. ModelInputForGPUWithSamplingMetadata)
  1270. _builder_cls: Type[ModelInputForGPUBuilder] = ModelInputForGPUBuilder
  1271. def make_model_input_from_broadcasted_tensor_dict(
  1272. self,
  1273. tensor_dict: Dict[str, Any],
  1274. ) -> ModelInputForGPUWithSamplingMetadata:
  1275. model_input = \
  1276. ModelInputForGPUWithSamplingMetadata.from_broadcasted_tensor_dict(
  1277. tensor_dict,
  1278. attn_backend=self.attn_backend,
  1279. )
  1280. return model_input
  1281. def prepare_model_input(
  1282. self,
  1283. seq_group_metadata_list: List[SequenceGroupMetadata],
  1284. virtual_engine: int = 0,
  1285. finished_requests_ids: Optional[List[str]] = None
  1286. ) -> ModelInputForGPUWithSamplingMetadata:
  1287. """Prepare the model input based on a given sequence group, including
  1288. metadata for the sampling step.
  1289. The API assumes seq_group_metadata_list is sorted by prefill -> decode.
  1290. The result tensors and data structure also batches input in prefill
  1291. -> decode order. For example,
  1292. - input_tokens[:num_prefill_tokens] contains prefill tokens.
  1293. - input_tokens[num_prefill_tokens:] contains decode tokens.
  1294. If cuda graph is required, this API automatically pads inputs.
  1295. """
  1296. model_input = self._prepare_model_input_tensors(
  1297. seq_group_metadata_list, finished_requests_ids)
  1298. if get_pp_group().is_last_rank:
  1299. # Sampling metadata is only required for the final pp group
  1300. generators = self.get_generators(finished_requests_ids)
  1301. sampling_metadata = SamplingMetadata.prepare(
  1302. seq_group_metadata_list, model_input.seq_lens,
  1303. model_input.query_lens, self.device, self.pin_memory,
  1304. generators, self.sampling_metadata_cache)
  1305. else:
  1306. sampling_metadata = None
  1307. is_prompt = (seq_group_metadata_list[0].is_prompt
  1308. if seq_group_metadata_list else None)
  1309. return dataclasses.replace(model_input,
  1310. sampling_metadata=sampling_metadata,
  1311. is_prompt=is_prompt,
  1312. virtual_engine=virtual_engine)
  1313. @torch.inference_mode()
  1314. def execute_model(
  1315. self,
  1316. model_input: ModelInputForGPUWithSamplingMetadata,
  1317. kv_caches: List[torch.Tensor],
  1318. intermediate_tensors: Optional[IntermediateTensors] = None,
  1319. num_steps: int = 1,
  1320. ) -> Optional[Union[List[SamplerOutput], IntermediateTensors]]:
  1321. if num_steps > 1:
  1322. raise ValueError("num_steps > 1 is not supported in ModelRunner")
  1323. if self.lora_config:
  1324. assert model_input.lora_requests is not None
  1325. assert model_input.lora_mapping is not None
  1326. self.set_active_loras(model_input.lora_requests,
  1327. model_input.lora_mapping)
  1328. if self.prompt_adapter_config:
  1329. assert model_input.prompt_adapter_requests is not None
  1330. assert model_input.prompt_adapter_mapping is not None
  1331. self.set_active_prompt_adapters(
  1332. model_input.prompt_adapter_requests,
  1333. model_input.prompt_adapter_mapping)
  1334. if self.attn_backend.get_name() == "flashinfer":
  1335. assert model_input.attn_metadata is not None
  1336. assert model_input.input_tokens is not None
  1337. if self.flashinfer_decode_workspace_buffer is None:
  1338. self.flashinfer_decode_workspace_buffer = torch.empty(
  1339. FLASHINFER_WORKSPACE_BUFFER_SIZE,
  1340. dtype=torch.uint8,
  1341. device=self.device)
  1342. self.flashinfer_decode_wrapper = \
  1343. BatchDecodeWithPagedKVCacheWrapper(
  1344. self.flashinfer_decode_workspace_buffer, "NHD")
  1345. self.flashinfer_prefill_workspace_buffer = torch.empty(
  1346. FLASHINFER_WORKSPACE_BUFFER_SIZE,
  1347. dtype=torch.uint8,
  1348. device=self.device)
  1349. self.flashinfer_prefill_wrapper = \
  1350. BatchPrefillWithPagedKVCacheWrapper(
  1351. self.flashinfer_prefill_workspace_buffer, "NHD")
  1352. model_input.attn_metadata.prefill_wrapper = \
  1353. self.flashinfer_prefill_wrapper
  1354. if model_input.attn_metadata.use_cuda_graph:
  1355. batch_size = model_input.input_tokens.shape[0]
  1356. model_input.attn_metadata.decode_wrapper = self.graph_runners[
  1357. model_input.
  1358. virtual_engine][batch_size].flashinfer_decode_wrapper
  1359. else:
  1360. model_input.attn_metadata.decode_wrapper = \
  1361. self.flashinfer_decode_wrapper
  1362. model_input.attn_metadata.begin_forward()
  1363. # Currently cuda graph is only supported by the decode phase.
  1364. assert model_input.attn_metadata is not None
  1365. prefill_meta = model_input.attn_metadata.prefill_metadata
  1366. decode_meta = model_input.attn_metadata.decode_metadata
  1367. # TODO: We can remove this once all
  1368. # virtual engines share the same kv cache.
  1369. virtual_engine = model_input.virtual_engine
  1370. if prefill_meta is None and decode_meta.use_cuda_graph:
  1371. assert model_input.input_tokens is not None
  1372. graph_batch_size = model_input.input_tokens.shape[0]
  1373. model_executable = self.graph_runners[virtual_engine][
  1374. graph_batch_size]
  1375. else:
  1376. model_executable = self.model
  1377. multi_modal_kwargs = model_input.multi_modal_kwargs or {}
  1378. seqlen_agnostic_kwargs = {
  1379. "finished_requests_ids": model_input.finished_requests_ids,
  1380. "request_ids_to_seq_ids": model_input.request_ids_to_seq_ids,
  1381. } if self.has_seqlen_agnostic else {}
  1382. hidden_or_intermediate_states = model_executable(
  1383. input_ids=model_input.input_tokens,
  1384. positions=model_input.input_positions,
  1385. kv_caches=kv_caches,
  1386. attn_metadata=model_input.attn_metadata,
  1387. intermediate_tensors=intermediate_tensors,
  1388. **MultiModalInputs.as_kwargs(multi_modal_kwargs,
  1389. device=self.device),
  1390. **seqlen_agnostic_kwargs,
  1391. )
  1392. # Compute the logits in the last pipeline stage.
  1393. if not get_pp_group().is_last_rank:
  1394. return hidden_or_intermediate_states
  1395. logits = self.model.compute_logits(hidden_or_intermediate_states,
  1396. model_input.sampling_metadata)
  1397. if not self.is_driver_worker:
  1398. return []
  1399. # Sample the next token.
  1400. output: SamplerOutput = self.model.sample(
  1401. logits=logits,
  1402. sampling_metadata=model_input.sampling_metadata,
  1403. )
  1404. if self.return_hidden_states:
  1405. # we only need to pass hidden states of most recent token
  1406. assert model_input.sampling_metadata is not None
  1407. indices = model_input.sampling_metadata.selected_token_indices
  1408. if model_input.is_prompt:
  1409. hidden_states = hidden_or_intermediate_states.index_select(
  1410. 0, indices)
  1411. elif decode_meta.use_cuda_graph:
  1412. hidden_states = hidden_or_intermediate_states[:len(indices)]
  1413. else:
  1414. hidden_states = hidden_or_intermediate_states
  1415. output.hidden_states = hidden_states
  1416. return [output]
  1417. class CUDAGraphRunner:
  1418. def __init__(self, model: nn.Module, backend_name: str):
  1419. self.model = model
  1420. self.backend_name = backend_name
  1421. self.input_buffers: Dict[str, torch.Tensor] = {}
  1422. self.output_buffers: Dict[str, torch.Tensor] = {}
  1423. self._graph: Optional[torch.cuda.CUDAGraph] = None
  1424. self.flashinfer_decode_workspace_buffer: Optional[torch.Tensor] = None
  1425. self.flashinfer_indptr_buffer: Optional[torch.Tensor] = None
  1426. self.flashinfer_indices_buffer: Optional[torch.Tensor] = None
  1427. self.flashinfer_last_page_len_buffer: Optional[torch.Tensor] = None
  1428. self.flashinfer_decode_wrapper: Optional[
  1429. CUDAGraphBatchDecodeWithPagedKVCacheWrapper] = None
  1430. @property
  1431. def graph(self):
  1432. assert self._graph is not None
  1433. return self._graph
  1434. def capture(
  1435. self,
  1436. input_ids: torch.Tensor,
  1437. positions: torch.Tensor,
  1438. hidden_or_intermediate_states: Optional[Union[IntermediateTensors,
  1439. torch.Tensor]],
  1440. intermediate_inputs: Optional[IntermediateTensors],
  1441. kv_caches: List[torch.Tensor],
  1442. attn_metadata: AttentionMetadata,
  1443. memory_pool: Optional[Tuple[int, int]],
  1444. stream: torch.cuda.Stream,
  1445. **kwargs,
  1446. ) -> Union[torch.Tensor, IntermediateTensors]:
  1447. assert self._graph is None
  1448. # Run the model a few times without capturing the graph.
  1449. # This is to make sure that the captured graph does not include the
  1450. # kernel launches for initial benchmarking (e.g., Triton autotune).
  1451. # Note one iteration is not enough for torch.jit.script
  1452. for _ in range(_NUM_WARMUP_ITERS):
  1453. self.model(
  1454. input_ids,
  1455. positions,
  1456. kv_caches,
  1457. attn_metadata,
  1458. intermediate_inputs,
  1459. **kwargs,
  1460. )
  1461. torch.cuda.synchronize()
  1462. # Capture the graph.
  1463. self._graph = torch.cuda.CUDAGraph()
  1464. with torch.cuda.graph(self._graph, pool=memory_pool, stream=stream):
  1465. output_hidden_or_intermediate_states = self.model(
  1466. input_ids,
  1467. positions,
  1468. kv_caches,
  1469. attn_metadata,
  1470. intermediate_inputs,
  1471. **kwargs,
  1472. )
  1473. if hidden_or_intermediate_states is not None:
  1474. if get_pp_group().is_last_rank:
  1475. hidden_or_intermediate_states.copy_(
  1476. output_hidden_or_intermediate_states)
  1477. else:
  1478. for key in hidden_or_intermediate_states.tensors:
  1479. hidden_or_intermediate_states[key].copy_(
  1480. output_hidden_or_intermediate_states[key])
  1481. else:
  1482. hidden_or_intermediate_states = (
  1483. output_hidden_or_intermediate_states)
  1484. del output_hidden_or_intermediate_states
  1485. # make sure `output_hidden_states` is deleted
  1486. # in the graph's memory pool
  1487. gc.collect()
  1488. torch.cuda.synchronize()
  1489. # Save the input and output buffers.
  1490. if self.backend_name == "flashinfer":
  1491. self.input_buffers = {
  1492. "input_ids": input_ids,
  1493. "positions": positions,
  1494. "kv_caches": kv_caches,
  1495. "slot_mapping": attn_metadata.slot_mapping,
  1496. **kwargs,
  1497. }
  1498. else:
  1499. self.input_buffers = {
  1500. "input_ids": input_ids,
  1501. "positions": positions,
  1502. "kv_caches": kv_caches,
  1503. "slot_mapping": attn_metadata.slot_mapping,
  1504. "seq_lens_tensor":
  1505. attn_metadata.decode_metadata.seq_lens_tensor,
  1506. "block_tables": attn_metadata.decode_metadata.block_tables,
  1507. **kwargs,
  1508. }
  1509. if intermediate_inputs is not None:
  1510. self.input_buffers.update(intermediate_inputs.tensors)
  1511. if get_pp_group().is_last_rank:
  1512. self.output_buffers = {
  1513. "hidden_states": hidden_or_intermediate_states
  1514. }
  1515. else:
  1516. self.output_buffers = hidden_or_intermediate_states
  1517. return hidden_or_intermediate_states
  1518. def forward(
  1519. self,
  1520. input_ids: torch.Tensor,
  1521. positions: torch.Tensor,
  1522. kv_caches: List[torch.Tensor],
  1523. attn_metadata: AttentionMetadata,
  1524. intermediate_tensors: Optional[IntermediateTensors],
  1525. **kwargs,
  1526. ) -> torch.Tensor:
  1527. # KV caches are fixed tensors, so we don't need to copy them.
  1528. del kv_caches
  1529. # Copy the input tensors to the input buffers.
  1530. self.input_buffers["input_ids"].copy_(input_ids, non_blocking=True)
  1531. self.input_buffers["positions"].copy_(positions, non_blocking=True)
  1532. if self.backend_name != "No attention":
  1533. self.input_buffers["slot_mapping"].copy_(
  1534. attn_metadata.slot_mapping, non_blocking=True)
  1535. if self.backend_name != "flashinfer":
  1536. self.input_buffers["seq_lens_tensor"].copy_(
  1537. attn_metadata.decode_metadata.seq_lens_tensor,
  1538. non_blocking=True)
  1539. self.input_buffers["block_tables"].copy_(
  1540. attn_metadata.decode_metadata.block_tables, non_blocking=True)
  1541. if "seqlen_agnostic_capture_inputs" in self.input_buffers:
  1542. self.model.copy_inputs_before_cuda_graphs(self.input_buffers,
  1543. **kwargs)
  1544. if intermediate_tensors is not None:
  1545. for key in intermediate_tensors.tensors:
  1546. self.input_buffers[key].copy_(intermediate_tensors[key],
  1547. non_blocking=True)
  1548. # Run the graph.
  1549. self.graph.replay()
  1550. # Return the output tensor.
  1551. if get_pp_group().is_last_rank:
  1552. return self.output_buffers["hidden_states"]
  1553. return self.output_buffers
  1554. def __call__(self, *args, **kwargs):
  1555. return self.forward(*args, **kwargs)
  1556. def _get_graph_batch_size(batch_size: int) -> int:
  1557. """Returns the padded batch size given actual batch size.
  1558. Batch sizes are 1, 2, 4, _BATCH_SIZE_ALIGNMENT,
  1559. 2*_BATCH_SIZE_ALIGNMENT, 3*_BATCH_SIZE_ALIGNMENT...
  1560. """
  1561. if batch_size <= 2:
  1562. return batch_size
  1563. elif batch_size <= 4:
  1564. return 4
  1565. else:
  1566. return ((batch_size + _BATCH_SIZE_ALIGNMENT - 1) //
  1567. _BATCH_SIZE_ALIGNMENT * _BATCH_SIZE_ALIGNMENT)