model_runner.py 71 KB

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