model_runner.py 74 KB

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