model_runner.py 78 KB

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