model_runner.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. import contextlib
  2. import time
  3. from enum import IntEnum
  4. from typing import Dict, List, NamedTuple, Optional, Set, Tuple
  5. import numpy as np
  6. import torch
  7. import torch.nn as nn
  8. from loguru import logger
  9. from aphrodite.attention import (AttentionMetadata, AttentionMetadataPerStage,
  10. get_attn_backend)
  11. from aphrodite.common.config import (DeviceConfig, LoadConfig, LoRAConfig,
  12. ModelConfig, ParallelConfig,
  13. SchedulerConfig, VisionLanguageConfig)
  14. from aphrodite.common.sampling_params import SamplingParams
  15. from aphrodite.common.sequence import (MultiModalData, SamplerOutput,
  16. SequenceData, SequenceGroupMetadata)
  17. from aphrodite.common.utils import (CudaMemoryProfiler,
  18. get_kv_cache_torch_dtype, is_hip,
  19. is_pin_memory_available,
  20. make_tensor_with_pad)
  21. from aphrodite.distributed import (broadcast_tensor_dict,
  22. get_tensor_model_parallel_world_size,
  23. with_pynccl_for_all_reduce)
  24. from aphrodite.distributed.device_communicators import (custom_all_reduce,
  25. pynccl_utils)
  26. from aphrodite.lora.layers import LoRAMapping
  27. from aphrodite.lora.request import LoRARequest
  28. from aphrodite.lora.worker_manager import LRUCacheWorkerLoRAManager
  29. from aphrodite.modeling import SamplingMetadata
  30. from aphrodite.modeling.model_loader import get_model
  31. _PAD_SLOT_ID = -1
  32. LORA_WARMUP_RANK = 8
  33. _BATCH_SIZE_ALIGNMENT = 8
  34. # Capture graphs for token size 1, 2, 4, 8, 16, 24, 32, 40, ..., 256.
  35. # NOTE: _get_graph_batch_size needs to be updated if this list is changed.
  36. _BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [
  37. _BATCH_SIZE_ALIGNMENT * i for i in range(1, 33)
  38. ]
  39. class PreparePromptMetadata(NamedTuple):
  40. input_tokens: List[int]
  41. input_positions: List[int]
  42. attn_metadata: Optional[AttentionMetadataPerStage]
  43. seq_lens: List[int]
  44. query_lens: List[int]
  45. lora_index_mapping: List[int]
  46. lora_prompt_mapping: List[int]
  47. lora_requests: Set[LoRARequest]
  48. multi_modal_input: Optional[torch.Tensor]
  49. slot_mapping: List[int]
  50. @classmethod
  51. def empty(cls):
  52. return PreparePromptMetadata(
  53. input_tokens=[],
  54. input_positions=[],
  55. attn_metadata=None,
  56. seq_lens=[],
  57. query_lens=[],
  58. lora_index_mapping=[],
  59. lora_prompt_mapping=[],
  60. lora_requests=set(),
  61. multi_modal_input=None,
  62. slot_mapping=[],
  63. )
  64. class PrepareDecodeMetadata(NamedTuple):
  65. input_tokens: List[int]
  66. input_positions: List[int]
  67. attn_metadata: Optional[AttentionMetadata]
  68. lora_index_mapping: List[int]
  69. lora_prompt_mapping: List[int]
  70. lora_requests: Set[LoRARequest]
  71. slot_mapping: List[int]
  72. @classmethod
  73. def empty(cls):
  74. return PrepareDecodeMetadata(
  75. input_tokens=[],
  76. input_positions=[],
  77. attn_metadata=None,
  78. lora_index_mapping=[],
  79. lora_prompt_mapping=[],
  80. lora_requests=set(),
  81. slot_mapping=[],
  82. )
  83. # How batches are constructed.
  84. class BatchType(IntEnum):
  85. # Every batch is prefill.
  86. PREFILL = 0
  87. # Every batch is decode.
  88. DECODE = 1
  89. # Batch is a mixture of prefill and decode.
  90. MIXED = 2
  91. class ModelRunner:
  92. def __init__(
  93. self,
  94. model_config: ModelConfig,
  95. parallel_config: ParallelConfig,
  96. scheduler_config: SchedulerConfig,
  97. device_config: DeviceConfig,
  98. load_config: LoadConfig,
  99. lora_config: Optional[LoRAConfig],
  100. kv_cache_dtype: Optional[str] = "auto",
  101. is_driver_worker: bool = False,
  102. vision_language_config: Optional[VisionLanguageConfig] = None,
  103. ):
  104. self.model_config = model_config
  105. self.parallel_config = parallel_config
  106. self.scheduler_config = scheduler_config
  107. self.lora_config = lora_config
  108. self.load_config = load_config
  109. self.is_driver_worker = is_driver_worker
  110. # model_config can be None in tests/samplers/test_sampler.py.
  111. # FIXME: This is a hack to make the tests work. Refactor this.
  112. self.sliding_window = (model_config.get_sliding_window()
  113. if model_config is not None else None)
  114. self.device_config = (device_config
  115. if device_config is not None else DeviceConfig())
  116. self.device = self.device_config.device
  117. # Set after load_model.
  118. self.lora_manager: LRUCacheWorkerLoRAManager = None
  119. self.graph_runners: Dict[int, CUDAGraphRunner] = {}
  120. self.graph_memory_pool: Optional[Tuple[
  121. int, int]] = None # Set during graph capture.
  122. self.max_seq_len_to_capture = (self.model_config.max_seq_len_to_capture
  123. if self.model_config is not None else 0)
  124. self.pin_memory = is_pin_memory_available()
  125. self.kv_cache_dtype = kv_cache_dtype
  126. self.vision_language_config = vision_language_config
  127. self.attn_backend = get_attn_backend(
  128. self.model_config.dtype if model_config is not None else None)
  129. # Lazy initialization
  130. self.model: torch.nn.Module # Set after load_model
  131. self.block_size: int # Set after initial profiling.
  132. # When using CUDA graph, the input block tables must be padded to
  133. # max_seq_len_to_capture. However, creating the block table in
  134. # Python can be expensive. To optimize this, we cache the block table
  135. # in numpy and only copy the actual input content at every iteration.
  136. # The shape of the cached block table will be
  137. # (max batch size to capture, max context len to capture / block size).
  138. self.graph_block_tables: torch.Tensor # Set after initial profiling.
  139. # Set if the backend is flashinfer.
  140. self.flashinfer_workspace_buffer: torch.Tensor
  141. def load_model(self) -> None:
  142. with CudaMemoryProfiler() as m:
  143. self.model = get_model(
  144. model_config=self.model_config,
  145. device_config=self.device_config,
  146. load_config=self.load_config,
  147. lora_config=self.lora_config,
  148. vision_language_config=self.vision_language_config,
  149. parallel_config=self.parallel_config,
  150. scheduler_config=self.scheduler_config,
  151. )
  152. self.model_memory_usage = m.consumed_memory
  153. tp = get_tensor_model_parallel_world_size()
  154. logger.info(
  155. "Model weights loaded. Memory usage: "
  156. f"{self.model_memory_usage / float(2**30):.2f} GiB x {tp} = "
  157. f"{self.model_memory_usage * tp / float(2**30):.2f} GiB")
  158. if self.lora_config:
  159. assert hasattr(self.model, "supported_lora_modules"
  160. ) and self.model.supported_lora_modules, (
  161. "Model does not support LoRA")
  162. assert hasattr(
  163. self.model,
  164. "embedding_modules"), "Model does not have embedding_modules"
  165. assert hasattr(self.model, "embedding_padding_modules"
  166. ), "Model does not have embedding_padding_modules"
  167. self.lora_manager = LRUCacheWorkerLoRAManager(
  168. self.scheduler_config.max_num_seqs,
  169. self.scheduler_config.max_num_batched_tokens, self.vocab_size,
  170. self.lora_config, self.device, self.model.embedding_modules,
  171. self.model.embedding_padding_modules)
  172. self.model = self.lora_manager.create_lora_manager(self.model)
  173. if self.kv_cache_dtype == "fp8" and is_hip():
  174. # Currently scaled KV cache is only enabled on ROCm
  175. if self.model_config.quantization_param_path is not None:
  176. if callable(getattr(self.model, "load_kv_cache_scales", None)):
  177. self.model.load_kv_cache_scales(
  178. self.model_config.quantization_param_path)
  179. else:
  180. raise RuntimeError(
  181. "Using FP8 KV cache and scaling factors provided but "
  182. "model %s does not support loading scaling factors.",
  183. self.model.__class__)
  184. else:
  185. logger.warning(
  186. "Using FP8 KV cache but no scaling factors "
  187. "provided. Defaulting to scaling factors of 1.0. "
  188. "This may lead to less accurate results!")
  189. elif self.model_config.quantization_param_path is not None:
  190. logger.warning("KV cache scaling factors provided, "
  191. "but the KV cache data type is not FP8. "
  192. "KV cache scaling factors will not be used.")
  193. def set_block_size(self, block_size: int) -> None:
  194. self.block_size = block_size
  195. self.graph_block_tables = np.zeros(
  196. (max(_BATCH_SIZES_TO_CAPTURE), self.get_max_block_per_batch()),
  197. dtype=np.int32)
  198. def get_max_block_per_batch(self) -> int:
  199. block_size = self.block_size
  200. return (self.max_seq_len_to_capture + block_size - 1) // block_size
  201. def _prepare_prompt(
  202. self,
  203. seq_group_metadata_list: List[SequenceGroupMetadata],
  204. ) -> PreparePromptMetadata:
  205. input_tokens: List[int] = []
  206. input_positions: List[int] = []
  207. slot_mapping: List[int] = []
  208. lora_index_mapping: List[int] = []
  209. lora_prompt_mapping: List[int] = []
  210. lora_requests: Set[LoRARequest] = set()
  211. seq_lens: List[int] = []
  212. context_lens: List[int] = []
  213. query_lens: List[int] = []
  214. prefix_block_tables: List[List[int]] = []
  215. multi_modal_input_list: List[torch.Tensor] = []
  216. if len(seq_group_metadata_list) == 0:
  217. return PreparePromptMetadata.empty()
  218. for seq_group_metadata in seq_group_metadata_list:
  219. assert seq_group_metadata.is_prompt
  220. seq_ids = list(seq_group_metadata.seq_data.keys())
  221. assert len(seq_ids) == 1
  222. seq_id = seq_ids[0]
  223. computed_block_nums = seq_group_metadata.computed_block_nums
  224. if (self.scheduler_config is not None
  225. and self.scheduler_config.chunked_prefill_enabled
  226. and not (computed_block_nums is None
  227. or computed_block_nums == [])):
  228. raise RuntimeError(
  229. "chunked prefill cannot be used with prefix caching "
  230. "now.")
  231. token_chunk_size = seq_group_metadata.token_chunk_size
  232. seq_data = seq_group_metadata.seq_data[seq_id]
  233. context_len = seq_data.get_num_computed_tokens()
  234. # We should use get_len here because in case of preemption
  235. # it contains output tokens.
  236. seq_len = min(seq_data.get_len(), context_len + token_chunk_size)
  237. prompt_tokens = seq_data.get_token_ids()[context_len:seq_len]
  238. seq_lens.append(seq_len)
  239. # NOTE: This only works for oooooooxxx style attention.
  240. if computed_block_nums is not None and len(
  241. computed_block_nums) > 0 and self.sliding_window is None:
  242. # Prefix is not supported with sliding_window
  243. context_len = len(computed_block_nums) * self.block_size
  244. prompt_tokens = prompt_tokens[context_len:]
  245. prefix_block_tables.append(computed_block_nums)
  246. elif self.scheduler_config.chunked_prefill_enabled:
  247. if seq_group_metadata.block_tables is not None:
  248. # Prefill has chunked before.
  249. block_table = seq_group_metadata.block_tables[seq_id]
  250. prefix_block_tables.append(block_table)
  251. else:
  252. # The first prefill.
  253. prefix_block_tables.append([])
  254. else:
  255. prefix_block_tables.append([])
  256. # Right now, prefill start is always 0. However, this
  257. # assumption can be changed once chunked prefill is introduced.
  258. assert context_len == 0
  259. # actual prompt lens
  260. context_lens.append(context_len)
  261. query_lens.append(seq_len - context_len)
  262. input_tokens.extend(prompt_tokens)
  263. # NOTE: Here we assume that the first token in the prompt
  264. # is always the first token in the sequence.
  265. input_positions.extend(list(range(context_len, seq_len)))
  266. lora_id = seq_group_metadata.lora_int_id
  267. if lora_id > 0:
  268. lora_requests.add(seq_group_metadata.lora_request)
  269. lora_index_mapping += [lora_id] * (seq_len - context_len)
  270. lora_prompt_mapping.extend(
  271. [lora_id] *
  272. (seq_len - context_len
  273. if seq_group_metadata.sampling_params.prompt_logprobs else 1))
  274. if seq_group_metadata.multi_modal_data:
  275. multi_modal_input_list.append(
  276. seq_group_metadata.multi_modal_data.data)
  277. if seq_group_metadata.block_tables is None:
  278. # During memory profiling, the block tables are not initialized
  279. # yet. In this case, we just use a dummy slot mapping.
  280. slot_mapping.extend([_PAD_SLOT_ID] * seq_len)
  281. continue
  282. # Compute the slot mapping.
  283. block_table = seq_group_metadata.block_tables[seq_id]
  284. # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,
  285. # where start_idx is max(0, seq_len - sliding_window).
  286. # For example, if the prompt len is 10, sliding window is 8, and
  287. # block size is 4, the first two tokens are masked and the slot
  288. # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
  289. start_idx = 0
  290. if self.sliding_window is not None:
  291. assert context_len == 0, (
  292. "Prefix caching is currently not supported with "
  293. "sliding window attention")
  294. start_idx = max(0, seq_len - self.sliding_window)
  295. for i in range(context_len, seq_len):
  296. if i < start_idx:
  297. slot_mapping.append(_PAD_SLOT_ID)
  298. continue
  299. block_number = block_table[i // self.block_size]
  300. block_offset = i % self.block_size
  301. slot = block_number * self.block_size + block_offset
  302. slot_mapping.append(slot)
  303. max_query_len = max(query_lens)
  304. max_seq_len = max(seq_lens)
  305. assert max_query_len > 0
  306. context_lens_tensor = torch.tensor(context_lens,
  307. dtype=torch.int,
  308. device=self.device)
  309. if multi_modal_input_list:
  310. assert self.vision_language_config, (
  311. "Multi-modal inputs are only supported by "
  312. "vision language models.")
  313. multi_modal_input = torch.cat(multi_modal_input_list,
  314. dim=0).to(self.device)
  315. else:
  316. multi_modal_input = None
  317. # Prepare prefix block tables
  318. max_prompt_block_table_len = max(len(t) for t in prefix_block_tables)
  319. block_tables = make_tensor_with_pad(
  320. prefix_block_tables,
  321. max_len=max_prompt_block_table_len,
  322. pad=0,
  323. dtype=torch.int,
  324. device=self.device,
  325. )
  326. # Query length can be shorter than key (i.e., prompt) when prefill
  327. # is chunked or prefix cached.
  328. query_lens_tensor = torch.tensor(query_lens,
  329. dtype=torch.long,
  330. device=self.device)
  331. subquery_start_loc = torch.zeros(query_lens_tensor.shape[0] + 1,
  332. dtype=torch.int32,
  333. device=self.device)
  334. seq_lens_tensor = torch.tensor(seq_lens,
  335. dtype=torch.int,
  336. device=self.device)
  337. seq_start_loc = torch.zeros(seq_lens_tensor.shape[0] + 1,
  338. dtype=torch.int32,
  339. device=self.device)
  340. torch.cumsum(query_lens_tensor,
  341. dim=0,
  342. dtype=subquery_start_loc.dtype,
  343. out=subquery_start_loc[1:])
  344. torch.cumsum(seq_lens_tensor,
  345. dim=0,
  346. dtype=seq_start_loc.dtype,
  347. out=seq_start_loc[1:])
  348. if self.attn_backend.get_name() == "flashinfer":
  349. attn_metadata = self.attn_backend.make_metadata(
  350. is_prompt=True,
  351. use_cuda_graph=False,
  352. seq_start_loc=seq_start_loc,
  353. max_seq_len=max_seq_len,
  354. block_tables=block_tables)
  355. else:
  356. attn_metadata = self.attn_backend.make_metadata(
  357. is_prompt=True,
  358. seq_lens=seq_lens,
  359. seq_lens_tensor=seq_lens_tensor,
  360. max_query_len=max_query_len,
  361. max_seq_len=max_seq_len,
  362. subquery_start_loc=subquery_start_loc,
  363. seq_start_loc=seq_start_loc,
  364. context_lens_tensor=context_lens_tensor,
  365. block_tables=block_tables,
  366. use_cuda_graph=False,
  367. )
  368. return PreparePromptMetadata(
  369. input_tokens=input_tokens,
  370. input_positions=input_positions,
  371. attn_metadata=attn_metadata,
  372. seq_lens=seq_lens,
  373. query_lens=query_lens,
  374. lora_index_mapping=lora_index_mapping,
  375. lora_prompt_mapping=lora_prompt_mapping,
  376. lora_requests=lora_requests,
  377. multi_modal_input=multi_modal_input,
  378. slot_mapping=slot_mapping,
  379. )
  380. def _prepare_decode(
  381. self,
  382. seq_group_metadata_list: List[SequenceGroupMetadata],
  383. ) -> PrepareDecodeMetadata:
  384. input_tokens: List[int] = []
  385. input_positions: List[int] = []
  386. slot_mapping: List[int] = []
  387. seq_lens: List[int] = []
  388. block_tables: List[List[int]] = []
  389. lora_index_mapping: List[int] = []
  390. lora_prompt_mapping: List[int] = []
  391. lora_requests: Set[LoRARequest] = set()
  392. # The following fields are only for flashinfer
  393. # Please follow https://docs.flashinfer.ai/tutorials/kv_layout.html#page-layout
  394. # for the precise definition of the following fields.
  395. # An example:
  396. # request 1, page indices [0, 5, 8]
  397. # request 2, page indices [1, 6, 7]
  398. # request 3, page indices [3, 4]
  399. # paged_kv_indices is a concatenation of page indices of all requests:
  400. # [0, 5, 8, 1, 6, 7, 3, 4]
  401. # paged_kv_indptr is used to index into paged_kv_indices:
  402. # [0, 3, 6, 8]
  403. paged_kv_indices: List[int] = []
  404. # 0 at the beginning of paged_kv_indptr indicates the start of the
  405. # first request’s page indices in the paged_kv_indices list.
  406. paged_kv_indptr: List[int] = [0]
  407. # paged_kv_last_page_len is the length of the last page of each request
  408. paged_kv_last_page_len: List[int] = []
  409. if len(seq_group_metadata_list) == 0:
  410. return PrepareDecodeMetadata.empty()
  411. for seq_group_metadata in seq_group_metadata_list:
  412. assert not seq_group_metadata.is_prompt
  413. assert seq_group_metadata.token_chunk_size == 1
  414. seq_ids = list(seq_group_metadata.seq_data.keys())
  415. lora_id = seq_group_metadata.lora_int_id
  416. if lora_id > 0:
  417. lora_requests.add(seq_group_metadata.lora_request)
  418. for seq_id in seq_ids:
  419. seq_data = seq_group_metadata.seq_data[seq_id]
  420. generation_token = seq_data.get_last_token_id()
  421. input_tokens.append(generation_token)
  422. seq_len = seq_data.get_len()
  423. position = seq_len - 1
  424. input_positions.append(position)
  425. seq_len = seq_len if self.sliding_window is None else min(
  426. seq_len, self.sliding_window)
  427. seq_lens.append(seq_len)
  428. block_table = seq_group_metadata.block_tables[seq_id]
  429. block_number = block_table[position // self.block_size]
  430. block_offset = position % self.block_size
  431. slot = block_number * self.block_size + block_offset
  432. slot_mapping.append(slot)
  433. lora_index_mapping.append(lora_id)
  434. lora_prompt_mapping.append(lora_id)
  435. if self.sliding_window is not None:
  436. sliding_window_blocks = (self.sliding_window //
  437. self.block_size)
  438. block_table = block_table[-sliding_window_blocks:]
  439. block_tables.append(block_table)
  440. paged_kv_indices.extend(block_table)
  441. paged_kv_indptr.append(paged_kv_indptr[-1] + len(block_table))
  442. last_page_len = seq_data.get_len() % self.block_size
  443. if last_page_len == 0:
  444. last_page_len = self.block_size
  445. paged_kv_last_page_len.append(last_page_len)
  446. # Aphrodite uses cuda graph only for decoding requests.
  447. # See `capture_model` API for more details.
  448. # For decoding requests, batch_size == input_tokens.
  449. batch_size = len(input_tokens)
  450. max_seq_len = max(seq_lens)
  451. use_captured_graph = (not self.model_config.enforce_eager
  452. and batch_size <= _BATCH_SIZES_TO_CAPTURE[-1]
  453. and max_seq_len <= self.max_seq_len_to_capture)
  454. if use_captured_graph:
  455. graph_batch_size = _get_graph_batch_size(batch_size)
  456. assert graph_batch_size >= batch_size
  457. for _ in range(graph_batch_size - batch_size):
  458. input_tokens.append(0)
  459. input_positions.append(0)
  460. slot_mapping.append(_PAD_SLOT_ID)
  461. seq_lens.append(1)
  462. block_tables.append([])
  463. lora_index_mapping.append(0)
  464. batch_size = graph_batch_size
  465. seq_lens_tensor = torch.tensor(seq_lens,
  466. dtype=torch.int,
  467. device=self.device)
  468. if use_captured_graph:
  469. # When using cuda-graph all these tensors should be
  470. # padded.
  471. assert seq_lens_tensor.shape[0] == len(input_tokens)
  472. assert seq_lens_tensor.shape[0] == len(input_positions)
  473. assert seq_lens_tensor.shape[0] == len(slot_mapping)
  474. # The shape of graph_block_tables is
  475. # [max batch size, max context len // block size].
  476. input_block_tables = self.graph_block_tables[:batch_size]
  477. for i, block_table in enumerate(block_tables):
  478. if block_table:
  479. input_block_tables[i, :len(block_table)] = block_table
  480. block_tables = torch.tensor(input_block_tables, device=self.device)
  481. else:
  482. max_block_table_len = max(
  483. len(block_table) for block_table in block_tables)
  484. block_tables = make_tensor_with_pad(
  485. block_tables,
  486. max_len=max_block_table_len,
  487. pad=0,
  488. dtype=torch.int,
  489. device=self.device,
  490. )
  491. if self.attn_backend.get_name() == "flashinfer":
  492. if not hasattr(self, "flashinfer_workspace_buffer"):
  493. # Allocate 16MB workspace buffer
  494. # Follow the example of flashinfer: https://docs.flashinfer.ai/api/python/decode.html
  495. self.flashinfer_workspace_buffer = torch.empty(
  496. 16 * 1024 * 1024, dtype=torch.uint8, device=self.device)
  497. paged_kv_indptr = torch.tensor(paged_kv_indptr,
  498. dtype=torch.int,
  499. device=self.device)
  500. paged_kv_indices = torch.tensor(paged_kv_indices,
  501. dtype=torch.int,
  502. device=self.device)
  503. paged_kv_last_page_len = torch.tensor(paged_kv_last_page_len,
  504. dtype=torch.int,
  505. device=self.device)
  506. kv_cache_dtype = get_kv_cache_torch_dtype(self.kv_cache_dtype,
  507. self.model_config.dtype)
  508. attn_metadata = self.attn_backend.make_metadata(
  509. is_prompt=False,
  510. use_cuda_graph=False,
  511. workspace_buffer=self.flashinfer_workspace_buffer,
  512. paged_kv_indptr=paged_kv_indptr,
  513. paged_kv_indices=paged_kv_indices,
  514. paged_kv_last_page_len=paged_kv_last_page_len,
  515. num_qo_heads=self.model_config.get_num_attention_heads(
  516. self.parallel_config),
  517. num_kv_heads=self.model_config.get_num_kv_heads(
  518. self.parallel_config),
  519. head_dim=self.model_config.get_head_size(),
  520. page_size=self.block_size,
  521. data_type=kv_cache_dtype)
  522. else:
  523. attn_metadata = self.attn_backend.make_metadata(
  524. is_prompt=False,
  525. seq_lens=None,
  526. seq_lens_tensor=seq_lens_tensor,
  527. max_query_len=None,
  528. max_seq_len=max_seq_len,
  529. subquery_start_loc=None,
  530. seq_start_loc=None,
  531. context_lens_tensor=None,
  532. block_tables=block_tables,
  533. use_cuda_graph=use_captured_graph,
  534. )
  535. return PrepareDecodeMetadata(
  536. input_tokens=input_tokens,
  537. input_positions=input_positions,
  538. attn_metadata=attn_metadata,
  539. lora_index_mapping=lora_index_mapping,
  540. lora_prompt_mapping=lora_prompt_mapping,
  541. lora_requests=lora_requests,
  542. slot_mapping=slot_mapping,
  543. )
  544. def prepare_input_tensors(
  545. self,
  546. seq_group_metadata_list: List[SequenceGroupMetadata],
  547. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, SamplingMetadata,
  548. Set[LoRARequest], LoRAMapping, torch.Tensor]:
  549. if self.is_driver_worker:
  550. prefill_reqs = []
  551. decode_reqs = []
  552. for seq_group_meta in seq_group_metadata_list:
  553. if seq_group_meta.is_prompt:
  554. prefill_reqs.append(seq_group_meta)
  555. else:
  556. decode_reqs.append(seq_group_meta)
  557. # Prepare input tensors.
  558. (
  559. input_tokens,
  560. input_positions,
  561. prefill_attn_metadata,
  562. seq_lens,
  563. query_lens,
  564. lora_index_mapping,
  565. lora_prompt_mapping,
  566. lora_requests,
  567. multi_modal_input,
  568. slot_mapping,
  569. ) = self._prepare_prompt(prefill_reqs)
  570. (
  571. decode_input_tokens,
  572. decode_input_positions,
  573. decode_attn_metadata,
  574. decode_lora_index_mapping,
  575. decode_lora_prompt_mapping,
  576. decode_lora_requests,
  577. decode_slot_mapping,
  578. ) = self._prepare_decode(decode_reqs)
  579. sampling_metadata = SamplingMetadata.prepare(
  580. seq_group_metadata_list, seq_lens, query_lens, self.device,
  581. self.pin_memory)
  582. if not self.scheduler_config.chunked_prefill_enabled:
  583. assert (len(prefill_reqs) and len(decode_reqs)) == 0
  584. num_prefills = len(seq_lens)
  585. num_prefill_tokens = len(input_tokens)
  586. num_decode_tokens = len(decode_input_tokens)
  587. # Coalesce tensors. Note that attn_metadata is currently not
  588. # coalesced for simplicity.
  589. input_tokens.extend(decode_input_tokens)
  590. input_positions.extend(decode_input_positions)
  591. slot_mapping.extend(decode_slot_mapping)
  592. lora_index_mapping.extend(decode_lora_index_mapping)
  593. lora_prompt_mapping.extend(decode_lora_prompt_mapping)
  594. lora_requests.update(decode_lora_requests)
  595. input_tokens = torch.tensor(input_tokens,
  596. dtype=torch.long,
  597. device=self.device)
  598. input_positions = torch.tensor(input_positions,
  599. dtype=torch.long,
  600. device=self.device)
  601. slot_mapping = torch.tensor(slot_mapping,
  602. dtype=torch.long,
  603. device=self.device)
  604. if self.lora_config:
  605. lora_mapping = LoRAMapping(
  606. lora_index_mapping,
  607. lora_prompt_mapping,
  608. )
  609. else:
  610. lora_mapping = None
  611. # Broadcast the metadata.
  612. # If batch contains both prefill and decode, it sends 2 broadcasts.
  613. # If it only contains 1 type, it triggers a single broadcast.
  614. if (prefill_attn_metadata is not None
  615. and decode_attn_metadata is not None):
  616. batch_type = BatchType.MIXED
  617. elif prefill_attn_metadata is not None:
  618. batch_type = BatchType.PREFILL
  619. else:
  620. batch_type = BatchType.DECODE
  621. metadata_dict = {
  622. "input_tokens": input_tokens,
  623. "input_positions": input_positions,
  624. "selected_token_indices":
  625. sampling_metadata.selected_token_indices,
  626. "lora_requests": lora_requests,
  627. "lora_mapping": lora_mapping,
  628. "multi_modal_input": multi_modal_input,
  629. "num_prefill_tokens": num_prefill_tokens,
  630. "num_decode_tokens": num_decode_tokens,
  631. "slot_mapping": slot_mapping,
  632. "num_prefills": num_prefills,
  633. "batch_type": batch_type,
  634. }
  635. if prefill_attn_metadata is not None:
  636. metadata_dict.update(prefill_attn_metadata.asdict_zerocopy())
  637. else:
  638. assert decode_attn_metadata is not None
  639. metadata_dict.update(decode_attn_metadata.asdict_zerocopy())
  640. broadcast_tensor_dict(metadata_dict, src=0)
  641. # Broadcast decode attn metadata for mixed batch type.
  642. # The additional broadcast costs 300us overhead on 4 A10 GPUs.
  643. # We can potentially reduce the overhead by coelescing tensors.
  644. if batch_type == BatchType.MIXED:
  645. assert decode_attn_metadata is not None
  646. metadata_dict = decode_attn_metadata.asdict_zerocopy()
  647. broadcast_tensor_dict(metadata_dict, src=0)
  648. else:
  649. metadata_dict = broadcast_tensor_dict(src=0)
  650. input_tokens = metadata_dict.pop("input_tokens")
  651. input_positions = metadata_dict.pop("input_positions")
  652. slot_mapping = metadata_dict.pop("slot_mapping")
  653. num_prefills = metadata_dict.pop("num_prefills")
  654. selected_token_indices = metadata_dict.pop(
  655. "selected_token_indices")
  656. lora_mapping = metadata_dict.pop("lora_mapping")
  657. lora_requests = metadata_dict.pop("lora_requests")
  658. multi_modal_input = metadata_dict.pop("multi_modal_input")
  659. num_prefill_tokens = metadata_dict.pop("num_prefill_tokens")
  660. num_decode_tokens = metadata_dict.pop("num_decode_tokens")
  661. batch_type = metadata_dict.pop("batch_type")
  662. # Create an attention metadata.
  663. prefill_attn_metadata = None
  664. decode_attn_metadata = None
  665. if batch_type == BatchType.PREFILL or batch_type == BatchType.MIXED:
  666. prefill_attn_metadata = self.attn_backend.make_metadata(
  667. **metadata_dict)
  668. else:
  669. decode_attn_metadata = self.attn_backend.make_metadata(
  670. **metadata_dict)
  671. sampling_metadata = SamplingMetadata(
  672. seq_groups=None,
  673. selected_token_indices=selected_token_indices,
  674. categorized_sample_indices=None,
  675. num_prompts=0,
  676. )
  677. # if it is a mixed batch, decode attn_metadata is broadcasted
  678. # separately.
  679. if batch_type == BatchType.MIXED:
  680. metadata_dict = broadcast_tensor_dict(src=0)
  681. decode_attn_metadata = self.attn_backend.make_metadata(
  682. **metadata_dict)
  683. attn_metadata = AttentionMetadata(
  684. num_prefills=num_prefills,
  685. slot_mapping=slot_mapping,
  686. num_prefill_tokens=num_prefill_tokens,
  687. num_decode_tokens=num_decode_tokens,
  688. prefill_metadata=prefill_attn_metadata,
  689. decode_metadata=decode_attn_metadata,
  690. kv_cache_dtype=self.kv_cache_dtype,
  691. )
  692. return (input_tokens, input_positions, attn_metadata,
  693. sampling_metadata, lora_requests, lora_mapping,
  694. multi_modal_input)
  695. @torch.inference_mode()
  696. def execute_model(
  697. self,
  698. seq_group_metadata_list: List[SequenceGroupMetadata],
  699. kv_caches: List[torch.Tensor],
  700. ) -> Optional[SamplerOutput]:
  701. (input_tokens, input_positions, attn_metadata, sampling_metadata,
  702. lora_requests, lora_mapping, multi_modal_input
  703. ) = self.prepare_input_tensors(seq_group_metadata_list)
  704. if self.lora_config:
  705. self.set_active_loras(lora_requests, lora_mapping)
  706. # Currently cuda graph is only supported by the decode phase.
  707. prefill_meta = attn_metadata.prefill_metadata
  708. decode_meta = attn_metadata.decode_metadata
  709. if prefill_meta is None and decode_meta.use_cuda_graph:
  710. graph_batch_size = input_tokens.shape[0]
  711. model_executable = self.graph_runners[graph_batch_size]
  712. else:
  713. model_executable = self.model
  714. execute_model_kwargs = {
  715. "input_ids": input_tokens,
  716. "positions": input_positions,
  717. "kv_caches": kv_caches,
  718. "attn_metadata": attn_metadata,
  719. }
  720. if self.vision_language_config:
  721. execute_model_kwargs.update({"image_input": multi_modal_input})
  722. hidden_states = model_executable(**execute_model_kwargs)
  723. # Compute the logits.
  724. logits = self.model.compute_logits(hidden_states, sampling_metadata)
  725. # Only perform sampling in the driver worker.
  726. if not self.is_driver_worker:
  727. return None
  728. # Sample the next token.
  729. output = self.model.sample(
  730. logits=logits,
  731. sampling_metadata=sampling_metadata,
  732. )
  733. return output
  734. @torch.inference_mode()
  735. def profile_run(self) -> None:
  736. # Enable top-k sampling to reflect the accurate memory usage.
  737. sampling_params = SamplingParams(top_p=0.99, top_k=self.vocab_size - 1)
  738. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  739. max_num_seqs = self.scheduler_config.max_num_seqs
  740. # This represents the maximum number of different requests
  741. # that will have unique loras, an therefore the max amount of memory
  742. # consumption create dummy lora request copies from the lora request
  743. # passed in, which contains a lora from the lora warmup path.
  744. dummy_lora_requests = []
  745. dummy_lora_requests_per_seq = []
  746. if self.lora_config:
  747. with self.lora_manager.dummy_lora_cache():
  748. for idx in range(self.lora_config.max_loras):
  749. lora_id = idx + 1
  750. dummy_lora_request = LoRARequest(
  751. lora_name=f"warmup_{lora_id}",
  752. lora_int_id=lora_id,
  753. lora_local_path="/not/a/real/path",
  754. )
  755. self.lora_manager.add_dummy_lora(dummy_lora_request,
  756. rank=LORA_WARMUP_RANK)
  757. dummy_lora_requests.append(dummy_lora_request)
  758. dummy_lora_requests_per_seq = [
  759. dummy_lora_requests[idx % len(dummy_lora_requests)]
  760. for idx in range(max_num_seqs)
  761. ]
  762. # Profile memory usage with max_num_sequences sequences and the total
  763. # number of tokens equal to max_num_batched_tokens.
  764. seqs: List[SequenceGroupMetadata] = []
  765. # Additional GPU memory may be needed for vision encoding, which needs
  766. # to be accounted for when calculating the GPU blocks for
  767. # Aphrodite blocker manager.
  768. # To exercise the worst scenario for GPU memory consumption,
  769. # the number of seqs (batch_size) is chosen to maximize the number
  770. # of images processed.
  771. if self.vision_language_config:
  772. max_num_seqs = min(
  773. max_num_seqs,
  774. int(max_num_batched_tokens /
  775. self.vision_language_config.image_feature_size))
  776. for group_id in range(max_num_seqs):
  777. seq_len = (max_num_batched_tokens // max_num_seqs +
  778. (group_id < max_num_batched_tokens % max_num_seqs))
  779. seq_data, fake_multi_modal_input = _prepare_fake_inputs(
  780. seq_len, self.vision_language_config)
  781. seq = SequenceGroupMetadata(
  782. request_id=str(group_id),
  783. is_prompt=True,
  784. seq_data={group_id: seq_data},
  785. sampling_params=sampling_params,
  786. block_tables=None,
  787. lora_request=dummy_lora_requests_per_seq[group_id]
  788. if dummy_lora_requests_per_seq else None,
  789. multi_modal_data=fake_multi_modal_input,
  790. )
  791. seqs.append(seq)
  792. # Run the model with the dummy inputs.
  793. num_layers = self.model_config.get_num_layers(self.parallel_config)
  794. kv_caches = [None] * num_layers
  795. self.execute_model(seqs, kv_caches)
  796. torch.cuda.synchronize()
  797. return
  798. def remove_all_loras(self):
  799. if not self.lora_manager:
  800. raise RuntimeError("LoRA is not enabled.")
  801. self.lora_manager.remove_all_loras()
  802. def set_active_loras(self, lora_requests: Set[LoRARequest],
  803. lora_mapping: LoRAMapping) -> None:
  804. if not self.lora_manager:
  805. raise RuntimeError("LoRA is not enabled.")
  806. self.lora_manager.set_active_loras(lora_requests, lora_mapping)
  807. def add_lora(self, lora_request: LoRARequest) -> bool:
  808. if not self.lora_manager:
  809. raise RuntimeError("LoRA is not enabled.")
  810. return self.lora_manager.add_lora(lora_request)
  811. def remove_lora(self, lora_id: int) -> bool:
  812. if not self.lora_manager:
  813. raise RuntimeError("LoRA is not enabled.")
  814. return self.lora_manager.remove_lora(lora_id)
  815. def list_loras(self) -> Set[int]:
  816. if not self.lora_manager:
  817. raise RuntimeError("LoRA is not enabled.")
  818. return self.lora_manager.list_loras()
  819. @torch.inference_mode()
  820. def capture_model(self, kv_caches: List[torch.Tensor]) -> None:
  821. """Cuda graph capture a model.
  822. Note that CUDA graph's performance gain is negligible if number
  823. of batched tokens are larger than 200. And since CUDA graph
  824. requires fixed sized tensors, supporting large/variable batch
  825. size requires high GPU memory overhead. Thus, vLLM only captures
  826. decoding requests. Mixed batch (chunked prefill + decoding) or
  827. prefill requests are not captured.
  828. Since it is used for decoding-only, it assumes there's only 1 token
  829. per sequence in the batch.
  830. """
  831. # NOTE: This is a hack to ensure that the NCCL backend is never
  832. # deleted before the CUDA graphs.
  833. self.pynccl_backend = pynccl_utils.get_nccl_backend()
  834. assert not self.model_config.enforce_eager
  835. logger.info("Capturing the model for CUDA graphs. This may lead to "
  836. "unexpected consequences if the model is not static. To "
  837. "run the model in eager mode, set 'enforce_eager=True' or "
  838. "use '--enforce-eager' in the CLI.")
  839. logger.info("CUDA graphs can take additional 1~3 GiB memory per GPU. "
  840. "If you are running out of memory, consider decreasing "
  841. "`gpu_memory_utilization` or enforcing eager mode. "
  842. "You can also reduce the `max_num_seqs` as needed "
  843. "to decrease memory usage.")
  844. start_time = time.perf_counter()
  845. # Prepare dummy inputs. These will be reused for all batch sizes.
  846. max_batch_size = max(_BATCH_SIZES_TO_CAPTURE)
  847. input_tokens = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  848. input_positions = torch.zeros(max_batch_size, dtype=torch.long).cuda()
  849. slot_mapping = torch.empty(max_batch_size, dtype=torch.long).cuda()
  850. slot_mapping.fill_(_PAD_SLOT_ID)
  851. seq_lens = torch.ones(max_batch_size, dtype=torch.int32).cuda()
  852. block_tables = torch.from_numpy(self.graph_block_tables).cuda()
  853. graph_batch_size = _get_graph_batch_size(
  854. self.scheduler_config.max_num_seqs)
  855. batch_size_capture_list = [
  856. bs for bs in _BATCH_SIZES_TO_CAPTURE if bs <= graph_batch_size
  857. ]
  858. # NOTE: There are 3 backends for all-reduce: custom all-reduce
  859. # kernel, pynccl, and PyTorch NCCL. When using CUDA graph, we use
  860. # either custom all-reduce kernel or pynccl. When not using CUDA
  861. # graph, we use either custom all-reduce kernel or PyTorch NCCL.
  862. # We always prioritize using custom all-reduce kernel but fall back
  863. # to PyTorch or pynccl if it is disabled or not supported.
  864. with custom_all_reduce.capture():
  865. # NOTE: Capturing the largest batch size first may help reduce the
  866. # memory usage of CUDA graph.
  867. for batch_size in reversed(batch_size_capture_list):
  868. # Create dummy attn_metadata.
  869. decode_metadata = self.attn_backend.make_metadata(
  870. is_prompt=False,
  871. seq_lens=None,
  872. seq_lens_tensor=seq_lens[:batch_size],
  873. max_query_len=None,
  874. max_seq_len=self.max_seq_len_to_capture,
  875. subquery_start_loc=None,
  876. seq_start_loc=None,
  877. context_lens_tensor=None,
  878. block_tables=block_tables[:batch_size],
  879. use_cuda_graph=True,
  880. )
  881. attn_metadata = AttentionMetadata(
  882. num_prefills=0,
  883. num_prefill_tokens=0,
  884. num_decode_tokens=batch_size,
  885. slot_mapping=slot_mapping[:batch_size],
  886. prefill_metadata=None,
  887. decode_metadata=decode_metadata,
  888. kv_cache_dtype=self.kv_cache_dtype,
  889. )
  890. if self.lora_config:
  891. lora_mapping = LoRAMapping(
  892. [0] * batch_size,
  893. [0] * batch_size,
  894. )
  895. self.set_active_loras(set(), lora_mapping)
  896. graph_runner = CUDAGraphRunner(self.model)
  897. graph_runner.capture(
  898. input_tokens[:batch_size],
  899. input_positions[:batch_size],
  900. kv_caches,
  901. attn_metadata,
  902. memory_pool=self.graph_memory_pool,
  903. )
  904. self.graph_memory_pool = graph_runner.graph.pool()
  905. self.graph_runners[batch_size] = graph_runner
  906. end_time = time.perf_counter()
  907. elapsed_time = end_time - start_time
  908. # This usually takes < 10 seconds.
  909. logger.info("Graph capturing finished in %.0f secs.", elapsed_time)
  910. def __del__(self) -> None:
  911. # Delete the CUDA graphs before deleting the pynccl communicator.
  912. # NOTE: This is necessary because otherwise deadlocks can
  913. # happen.
  914. # FIXME: This is a bit hacky. Find a more robust solution.
  915. # TODO: when we get enough user feedback that pynccl is
  916. # more stable than cupy, we can remove this, e.g. in v0.4.1.
  917. self.graph_runners.clear()
  918. self.pynccl_backend = None
  919. @property
  920. def vocab_size(self) -> int:
  921. return self.model_config.get_vocab_size()
  922. class CUDAGraphRunner:
  923. def __init__(self, model: nn.Module):
  924. self.model = model
  925. self.input_buffers: Dict[str, torch.Tensor] = {}
  926. self.output_buffers: Dict[str, torch.Tensor] = {}
  927. self._graph: Optional[torch.cuda.CUDAGraph] = None
  928. @property
  929. def graph(self):
  930. assert self._graph is not None
  931. return self._graph
  932. def capture(
  933. self,
  934. input_ids: torch.Tensor,
  935. positions: torch.Tensor,
  936. kv_caches: List[torch.Tensor],
  937. attn_metadata: AttentionMetadata,
  938. memory_pool,
  939. **kwargs,
  940. ) -> None:
  941. assert self._graph is None
  942. # Run the model once without capturing the graph.
  943. # This is to make sure that the captured graph does not include the
  944. # kernel launches for initial benchmarking (e.g., Triton autotune).
  945. with _maybe_pynccl():
  946. self.model(
  947. input_ids,
  948. positions,
  949. kv_caches,
  950. attn_metadata,
  951. **kwargs,
  952. )
  953. torch.cuda.synchronize()
  954. # Capture the graph.
  955. # NOTE: Python 3.8 does not support multi-line with statements.
  956. # https://stackoverflow.com/questions/31039022/python-multi-line-with-statement
  957. self._graph = torch.cuda.CUDAGraph()
  958. with torch.cuda.graph(self._graph, pool=memory_pool): # noqa: SIM117
  959. with _maybe_pynccl():
  960. hidden_states = self.model(
  961. input_ids,
  962. positions,
  963. kv_caches,
  964. attn_metadata,
  965. **kwargs,
  966. )
  967. torch.cuda.synchronize()
  968. # Save the input and output buffers.
  969. self.input_buffers = {
  970. "input_ids": input_ids,
  971. "positions": positions,
  972. "kv_caches": kv_caches,
  973. "slot_mapping": attn_metadata.slot_mapping,
  974. "seq_lens_tensor": attn_metadata.decode_metadata.seq_lens_tensor,
  975. "block_tables": attn_metadata.decode_metadata.block_tables,
  976. }
  977. self.output_buffers = {"hidden_states": hidden_states}
  978. return
  979. def forward(
  980. self,
  981. input_ids: torch.Tensor,
  982. positions: torch.Tensor,
  983. kv_caches: List[torch.Tensor],
  984. attn_metadata: AttentionMetadata,
  985. **kwargs,
  986. ) -> torch.Tensor:
  987. # KV caches are fixed tensors, so we don't need to copy them.
  988. del kv_caches
  989. # Copy the input tensors to the input buffers.
  990. self.input_buffers["input_ids"].copy_(input_ids, non_blocking=True)
  991. self.input_buffers["positions"].copy_(positions, non_blocking=True)
  992. self.input_buffers["slot_mapping"].copy_(attn_metadata.slot_mapping,
  993. non_blocking=True)
  994. self.input_buffers["seq_lens_tensor"].copy_(
  995. attn_metadata.decode_metadata.seq_lens_tensor, non_blocking=True)
  996. self.input_buffers["block_tables"].copy_(
  997. attn_metadata.decode_metadata.block_tables, non_blocking=True)
  998. # Run the graph.
  999. self.graph.replay()
  1000. # Return the output tensor.
  1001. return self.output_buffers["hidden_states"]
  1002. def __call__(self, *args, **kwargs):
  1003. return self.forward(*args, **kwargs)
  1004. @contextlib.contextmanager
  1005. def _maybe_pynccl():
  1006. if pynccl_utils.is_initialized(
  1007. ) and not custom_all_reduce.is_initialized():
  1008. with with_pynccl_for_all_reduce():
  1009. yield
  1010. else:
  1011. yield
  1012. def _get_graph_batch_size(batch_size: int) -> int:
  1013. """Returns the padded batch size given actual batch size.
  1014. Batch sizes are 1, 2, 4, _BATCH_SIZE_ALIGNMENT,
  1015. 2*_BATCH_SIZE_ALIGNMENT, 3*_BATCH_SIZE_ALIGNMENT...
  1016. """
  1017. if batch_size <= 2:
  1018. return batch_size
  1019. elif batch_size <= 4:
  1020. return 4
  1021. else:
  1022. return ((batch_size + _BATCH_SIZE_ALIGNMENT - 1) //
  1023. _BATCH_SIZE_ALIGNMENT * _BATCH_SIZE_ALIGNMENT)
  1024. def _prepare_fake_inputs(
  1025. seq_len: int, vision_language_config: Optional[VisionLanguageConfig]):
  1026. """Prepare fake inputs for profile run."""
  1027. if vision_language_config:
  1028. prompt_tokens = [
  1029. vision_language_config.image_token_id
  1030. ] * vision_language_config.image_feature_size + [0] * (
  1031. seq_len - vision_language_config.image_feature_size)
  1032. fake_image_input = MultiModalData(
  1033. type=MultiModalData.Type.IMAGE,
  1034. data=torch.zeros(vision_language_config.image_input_shape,
  1035. dtype=torch.float16))
  1036. else:
  1037. prompt_tokens = [0] * seq_len
  1038. fake_image_input = None
  1039. return SequenceData(prompt_tokens), fake_image_input