model_runner.py 68 KB

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