xpu_model_runner.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. from dataclasses import dataclass
  2. from typing import (TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Tuple,
  3. Type, Union)
  4. import torch
  5. import torch.nn as nn
  6. from loguru import logger
  7. from aphrodite.attention import get_attn_backend
  8. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  9. LoRAConfig, ModelConfig, MultiModalConfig,
  10. ParallelConfig, PromptAdapterConfig,
  11. SchedulerConfig)
  12. from aphrodite.common.sampling_params import SamplingParams
  13. from aphrodite.common.sequence import (IntermediateTensors, SamplerOutput,
  14. SequenceGroupMetadata)
  15. from aphrodite.common.utils import CudaMemoryProfiler, make_tensor_with_pad
  16. from aphrodite.distributed import broadcast_tensor_dict
  17. from aphrodite.inputs import INPUT_REGISTRY
  18. from aphrodite.modeling.model_loader import get_model
  19. from aphrodite.modeling.models.interfaces import supports_vision
  20. from aphrodite.multimodal import (MULTIMODAL_REGISTRY, BatchedTensors,
  21. MultiModalInputs)
  22. from aphrodite.task_handler.model_runner import (AttentionMetadata,
  23. SamplingMetadata)
  24. from aphrodite.task_handler.model_runner_base import (
  25. ModelRunnerBase, ModelRunnerInputBase,
  26. _add_attn_metadata_broadcastable_dict,
  27. _add_sampling_metadata_broadcastable_dict,
  28. _init_attn_metadata_from_tensor_dict,
  29. _init_sampling_metadata_from_tensor_dict)
  30. if TYPE_CHECKING:
  31. from aphrodite.attention.backends.abstract import AttentionBackend
  32. _PAD_SLOT_ID = -1
  33. _BATCH_SIZE_ALIGNMENT = 8
  34. _BATCH_SIZES_TO_CAPTURE = [1, 2, 4] + [
  35. _BATCH_SIZE_ALIGNMENT * i for i in range(1, 33)
  36. ]
  37. @dataclass(frozen=True)
  38. class ModelInputForXPU(ModelRunnerInputBase):
  39. """
  40. Used by the NeuronModelRunner.
  41. """
  42. input_tokens: Optional[torch.Tensor] = None
  43. input_positions: Optional[torch.Tensor] = None
  44. attn_metadata: Optional["AttentionMetadata"] = None
  45. sampling_metadata: Optional["SamplingMetadata"] = None
  46. multi_modal_kwargs: Optional[Mapping[str, BatchedTensors]] = None
  47. def as_broadcastable_tensor_dict(
  48. self) -> Dict[str, Union[int, torch.Tensor]]:
  49. tensor_dict = {
  50. "input_tokens": self.input_tokens,
  51. "input_positions": self.input_positions,
  52. }
  53. _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
  54. _add_sampling_metadata_broadcastable_dict(tensor_dict,
  55. self.sampling_metadata)
  56. return tensor_dict
  57. @classmethod
  58. def from_broadcasted_tensor_dict(
  59. cls: Type["ModelInputForXPU"],
  60. tensor_dict: Dict[str, Any],
  61. attn_backend: Optional["AttentionBackend"] = None,
  62. ) -> "ModelInputForXPU":
  63. tensor_dict = _init_sampling_metadata_from_tensor_dict(tensor_dict)
  64. if attn_backend is not None:
  65. tensor_dict = _init_attn_metadata_from_tensor_dict(
  66. attn_backend, tensor_dict)
  67. return cls(**tensor_dict)
  68. class XPUModelRunner(ModelRunnerBase[ModelInputForXPU]):
  69. def __init__(
  70. self,
  71. model_config: ModelConfig,
  72. parallel_config: ParallelConfig,
  73. scheduler_config: SchedulerConfig,
  74. device_config: DeviceConfig,
  75. cache_config: CacheConfig,
  76. load_config: LoadConfig,
  77. lora_config: Optional[LoRAConfig],
  78. multimodal_config: Optional[MultiModalConfig],
  79. kv_cache_dtype: Optional[str] = "auto",
  80. prompt_adapter_config: Optional[PromptAdapterConfig] = None,
  81. is_driver_worker: bool = False,
  82. *args,
  83. **kwargs,
  84. ):
  85. self.model_config = model_config
  86. self.parallel_config = parallel_config
  87. self.scheduler_config = scheduler_config
  88. self.lora_config = lora_config
  89. self.load_config = load_config
  90. self.cache_config = cache_config
  91. self.prompt_adapter_config = prompt_adapter_config
  92. self.multimodal_config = multimodal_config
  93. self.is_driver_worker = is_driver_worker
  94. self.sliding_window = model_config.get_sliding_window()
  95. self.device_config = device_config
  96. self.device = self.device_config.device
  97. self.kv_cache_dtype = kv_cache_dtype
  98. self.block_size = cache_config.block_size
  99. self.max_context_len_to_capture = (
  100. self.model_config.max_context_len_to_capture
  101. if self.model_config is not None else 0)
  102. self.attn_backend = get_attn_backend(
  103. self.model_config.get_num_attention_heads(self.parallel_config),
  104. self.model_config.get_head_size(),
  105. self.model_config.get_num_kv_heads(self.parallel_config),
  106. self.model_config.get_sliding_window(),
  107. self.model_config.dtype,
  108. self.kv_cache_dtype,
  109. self.block_size,
  110. )
  111. # Multi-modal data support
  112. self.multi_modal_input_mapper = MULTIMODAL_REGISTRY \
  113. .create_input_mapper(self.model_config)
  114. # Lazy initialization.
  115. self.model: nn.Module # Set after init_Model
  116. def load_model(self) -> None:
  117. with CudaMemoryProfiler() as m:
  118. self.model = get_model(
  119. model_config=self.model_config,
  120. device_config=self.device_config,
  121. load_config=self.load_config,
  122. lora_config=self.lora_config,
  123. multimodal_config=self.multimodal_config,
  124. parallel_config=self.parallel_config,
  125. scheduler_config=self.scheduler_config,
  126. cache_config=self.cache_config,
  127. )
  128. self.model_memory_usage = m.consumed_memory
  129. logger.info("Loading model weights took "
  130. f"{self.model_memory_usage / float(2**30):.4f} GB")
  131. @property
  132. def vocab_size(self) -> int:
  133. return self.model_config.get_vocab_size()
  134. @torch.inference_mode()
  135. def profile_run(self) -> None:
  136. # Enable top-k sampling to reflect the accurate memory usage.
  137. sampling_params = SamplingParams(top_p=0.99, top_k=self.vocab_size - 1)
  138. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  139. max_num_seqs = self.scheduler_config.max_num_seqs
  140. # Profile memory usage with max_num_sequences sequences and the total
  141. # number of tokens equal to max_num_batched_tokens.
  142. seqs: List[SequenceGroupMetadata] = []
  143. # Additional GPU memory may be needed for vision encoding, which needs
  144. # to be accounted for when calculating the GPU blocks for
  145. # Aphrodite blocker manager.
  146. # To exercise the worst scenario for GPU memory consumption,
  147. # the number of seqs (batch_size) is chosen to maximize the number
  148. # of images processed.
  149. model_config = self.model_config
  150. if supports_vision(self.model):
  151. max_mm_tokens = MULTIMODAL_REGISTRY \
  152. .get_max_multimodal_tokens(model_config)
  153. max_num_seqs_orig = max_num_seqs
  154. max_num_seqs = min(max_num_seqs,
  155. max_num_batched_tokens // max_mm_tokens)
  156. if max_num_seqs < 1:
  157. expr = (f"min({max_num_seqs_orig}, "
  158. f"{max_num_batched_tokens} // {max_mm_tokens})")
  159. logger.warning(
  160. f"Computed max_num_seqs ({expr}) to be less than 1. "
  161. "Setting it to the minimum value of 1.")
  162. max_num_seqs = 1
  163. for group_id in range(max_num_seqs):
  164. seq_len = (max_num_batched_tokens // max_num_seqs +
  165. (group_id < max_num_batched_tokens % max_num_seqs))
  166. seq_data, dummy_multi_modal_data = INPUT_REGISTRY \
  167. .dummy_data_for_profiling(model_config, seq_len)
  168. # Having more tokens is over-conservative but otherwise fine
  169. assert len(seq_data.prompt_token_ids) >= seq_len, (
  170. f"Expected at least {seq_len} dummy tokens for profiling, "
  171. f"but got: {len(seq_data.prompt_token_ids)}")
  172. seq = SequenceGroupMetadata(
  173. request_id=str(group_id),
  174. is_prompt=True,
  175. seq_data={group_id: seq_data},
  176. sampling_params=sampling_params,
  177. block_tables=None,
  178. lora_request=None,
  179. multi_modal_data=dummy_multi_modal_data,
  180. )
  181. seqs.append(seq)
  182. # Run the model with the dummy inputs.
  183. num_layers = self.model_config.get_num_layers(self.parallel_config)
  184. kv_caches = [None] * num_layers
  185. model_input = self.prepare_model_input(seqs)
  186. self.execute_model(model_input, kv_caches)
  187. torch.xpu.synchronize()
  188. return
  189. def make_model_input_from_broadcasted_tensor_dict(
  190. self, tensor_dict: Dict[str, Any]) -> ModelInputForXPU:
  191. return (ModelInputForXPU.from_broadcasted_tensor_dict(
  192. tensor_dict,
  193. attn_backend=self.attn_backend,
  194. ))
  195. def prepare_model_input(
  196. self,
  197. seq_group_metadata_list: List[SequenceGroupMetadata],
  198. virtual_engine: int = 0,
  199. finished_requests_ids: Optional[List[str]] = None
  200. ) -> ModelInputForXPU:
  201. multi_modal_kwargs = None
  202. if self.is_driver_worker:
  203. # NOTE: We assume that all sequences in the group are all prompts or
  204. # all decodes.
  205. is_prompt = seq_group_metadata_list[0].is_prompt
  206. # Prepare input tensors.
  207. if is_prompt:
  208. (input_tokens, input_positions, attn_metadata, seq_lens,
  209. multi_modal_kwargs
  210. ) = self._prepare_prompt(seq_group_metadata_list)
  211. else:
  212. (input_tokens, input_positions,
  213. attn_metadata) = self._prepare_decode(seq_group_metadata_list)
  214. seq_lens = []
  215. sampling_metadata = SamplingMetadata.prepare(
  216. seq_group_metadata_list,
  217. seq_lens,
  218. # subquery_lens is not needed if chunked prefill is not
  219. # supported. Since CPU worker doesn't support chunked prefill
  220. # just use seq_lens instead.
  221. seq_lens,
  222. self.device,
  223. pin_memory=False)
  224. # Broadcast the metadata.
  225. metadata_dict = {
  226. "input_tokens": input_tokens,
  227. "input_positions": input_positions,
  228. "selected_token_indices":
  229. sampling_metadata.selected_token_indices,
  230. "multi_modal_kwargs": multi_modal_kwargs,
  231. }
  232. metadata_dict.update(attn_metadata.asdict_zerocopy())
  233. broadcast_tensor_dict(metadata_dict, src=0)
  234. else:
  235. metadata_dict = broadcast_tensor_dict(src=0)
  236. input_tokens = metadata_dict.pop("input_tokens")
  237. input_positions = metadata_dict.pop("input_positions")
  238. selected_token_indices = metadata_dict.pop(
  239. "selected_token_indices")
  240. multi_modal_kwargs = metadata_dict.pop("multi_modal_kwargs")
  241. attn_metadata = self.attn_backend.make_metadata(**metadata_dict)
  242. sampling_metadata = SamplingMetadata(
  243. seq_groups=None,
  244. selected_token_indices=selected_token_indices,
  245. categorized_sample_indices=None,
  246. num_prompts=0,
  247. )
  248. return ModelInputForXPU(input_tokens=input_tokens,
  249. input_positions=input_positions,
  250. attn_metadata=attn_metadata,
  251. sampling_metadata=sampling_metadata,
  252. multi_modal_kwargs=multi_modal_kwargs)
  253. def _prepare_decode(
  254. self,
  255. seq_group_metadata_list: List[SequenceGroupMetadata],
  256. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata]:
  257. assert len(seq_group_metadata_list) > 0
  258. input_tokens: List[int] = []
  259. input_positions: List[int] = []
  260. slot_mapping: List[int] = []
  261. seq_lens: List[int] = []
  262. block_tables: List[List[int]] = []
  263. for seq_group_metadata in seq_group_metadata_list:
  264. assert not seq_group_metadata.is_prompt
  265. assert seq_group_metadata.token_chunk_size == 1
  266. seq_ids = list(seq_group_metadata.seq_data.keys())
  267. for seq_id in seq_ids:
  268. seq_data = seq_group_metadata.seq_data[seq_id]
  269. generation_token = seq_data.get_last_token_id()
  270. input_tokens.append(generation_token)
  271. seq_len = seq_data.get_len()
  272. position = seq_len - 1
  273. input_positions.append(position)
  274. seq_len = seq_len if self.sliding_window is None else min(
  275. seq_len, self.sliding_window)
  276. seq_lens.append(seq_len)
  277. block_table = seq_group_metadata.block_tables[seq_id]
  278. block_number = block_table[position // self.block_size]
  279. block_offset = position % self.block_size
  280. slot = block_number * self.block_size + block_offset
  281. slot_mapping.append(slot)
  282. if self.sliding_window is not None:
  283. sliding_window_blocks = (self.sliding_window //
  284. self.block_size)
  285. block_table = block_table[-sliding_window_blocks:]
  286. block_tables.append(block_table)
  287. max_decode_seq_len = max(seq_lens)
  288. input_tokens = torch.tensor(input_tokens,
  289. dtype=torch.long,
  290. device=self.device)
  291. input_positions = torch.tensor(input_positions,
  292. dtype=torch.long,
  293. device=self.device)
  294. slot_mapping = torch.tensor(slot_mapping,
  295. dtype=torch.long,
  296. device=self.device)
  297. seq_lens_tensor = torch.tensor(seq_lens,
  298. dtype=torch.int,
  299. device=self.device)
  300. max_block_table_len = max(
  301. len(block_table) for block_table in block_tables)
  302. block_tables = make_tensor_with_pad(
  303. block_tables,
  304. max_len=max_block_table_len,
  305. pad=0,
  306. dtype=torch.int,
  307. device=self.device,
  308. )
  309. attn_metadata = self.attn_backend.make_metadata(
  310. is_prompt=False,
  311. slot_mapping=slot_mapping,
  312. seq_lens=seq_lens,
  313. seqlen_q=None,
  314. max_seqlen=None,
  315. seq_lens_tensor=seq_lens_tensor,
  316. max_decode_seq_len=max_decode_seq_len,
  317. num_prefill_tokens=0,
  318. num_decode_tokens=len(input_tokens),
  319. num_prefills=0,
  320. block_tables=block_tables,
  321. )
  322. return (
  323. input_tokens,
  324. input_positions,
  325. attn_metadata,
  326. )
  327. @torch.inference_mode()
  328. def execute_model(
  329. self,
  330. model_input: ModelInputForXPU,
  331. kv_caches: List[torch.Tensor],
  332. intermediate_tensors: Optional[IntermediateTensors] = None,
  333. num_steps: int = 1,
  334. ) -> Optional[List[SamplerOutput]]:
  335. if num_steps > 1:
  336. raise ValueError(
  337. "XPUModelRunner does not support multi-step execution.")
  338. model_executable = self.model
  339. execute_model_kwargs = {
  340. "input_ids": model_input.input_tokens,
  341. "positions": model_input.input_positions,
  342. "kv_caches": kv_caches,
  343. "attn_metadata": model_input.attn_metadata,
  344. **(model_input.multi_modal_kwargs or {}),
  345. }
  346. hidden_states = model_executable(**execute_model_kwargs)
  347. # Compute the logits.
  348. logits = self.model.compute_logits(hidden_states,
  349. model_input.sampling_metadata)
  350. # Only perform sampling in the driver worker.
  351. if not self.is_driver_worker:
  352. return []
  353. # Sample the next token.
  354. output = self.model.sample(
  355. logits=logits,
  356. sampling_metadata=model_input.sampling_metadata,
  357. )
  358. return [output]
  359. def _prepare_prompt(
  360. self,
  361. seq_group_metadata_list: List[SequenceGroupMetadata],
  362. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, List[int],
  363. Mapping[str, BatchedTensors]]:
  364. assert len(seq_group_metadata_list) > 0
  365. input_tokens: List[int] = []
  366. input_positions: List[int] = []
  367. slot_mapping: List[int] = []
  368. seq_lens: List[int] = []
  369. multi_modal_inputs_list: List[MultiModalInputs] = []
  370. for seq_group_metadata in seq_group_metadata_list:
  371. assert seq_group_metadata.is_prompt
  372. seq_ids = list(seq_group_metadata.seq_data.keys())
  373. assert len(seq_ids) == 1
  374. seq_id = seq_ids[0]
  375. seq_data = seq_group_metadata.seq_data[seq_id]
  376. prompt_tokens = seq_data.get_token_ids()
  377. computed_len = seq_data.get_num_computed_tokens()
  378. seq_len = len(prompt_tokens)
  379. seq_lens.append(seq_len) # Prompt token num
  380. input_tokens.extend(prompt_tokens) # Token ids
  381. # Token position ids
  382. # NOTE: Here we assume that the first token in the prompt
  383. # is always the first token in the sequence.
  384. input_positions.extend(list(range(computed_len, seq_len)))
  385. mm_data = seq_group_metadata.multi_modal_data
  386. if mm_data:
  387. mm_kwargs = self.multi_modal_input_mapper(mm_data)
  388. multi_modal_inputs_list.append(mm_kwargs)
  389. if seq_group_metadata.block_tables is None:
  390. # During memory profiling, the block tables are not initialized
  391. # yet. In this case, we just use a dummy slot mapping.
  392. slot_mapping.extend([_PAD_SLOT_ID] * seq_len)
  393. continue
  394. # Compute the slot mapping.
  395. block_table = seq_group_metadata.block_tables[seq_id]
  396. # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,
  397. # where start_idx is max(0, seq_len - sliding_window).
  398. # For example, if the prompt len is 10, sliding window is 8, and
  399. # block size is 4, the first two tokens are masked and the slot
  400. # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
  401. start_idx = 0
  402. if self.sliding_window is not None:
  403. start_idx = max(0, seq_len - self.sliding_window)
  404. for i in range(computed_len, seq_len):
  405. if i < start_idx:
  406. slot_mapping.append(_PAD_SLOT_ID)
  407. continue
  408. block_number = block_table[i //
  409. self.block_size] # type: ignore
  410. block_offset = i % self.block_size # type: ignore
  411. slot = block_number * self.block_size + block_offset
  412. slot_mapping.append(slot)
  413. num_prompt_tokens = len(input_tokens)
  414. input_tokens = torch.tensor(input_tokens,
  415. dtype=torch.long,
  416. device=self.device) # type: ignore
  417. input_positions = torch.tensor(input_positions,
  418. dtype=torch.long,
  419. device=self.device) # type: ignore
  420. slot_mapping = torch.tensor(slot_mapping,
  421. dtype=torch.long,
  422. device=self.device) # type: ignore
  423. max_seqlen = max(seq_lens)
  424. tmp = [0]
  425. tmp.extend(seq_lens)
  426. seqlen = torch.tensor(tmp)
  427. seqlen_q = torch.cumsum(seqlen, dim=0).to(device=self.device)
  428. attn_metadata = self.attn_backend.make_metadata(
  429. is_prompt=True,
  430. slot_mapping=slot_mapping,
  431. seq_lens=seq_lens,
  432. seqlen_q=seqlen_q,
  433. max_seqlen=max_seqlen,
  434. seq_lens_tensor=None,
  435. max_decode_seq_len=None,
  436. num_prefills=len(seq_lens),
  437. num_prefill_tokens=num_prompt_tokens,
  438. num_decode_tokens=0,
  439. block_tables=torch.tensor([], device=self.device, dtype=torch.int),
  440. )
  441. multi_modal_kwargs = MultiModalInputs.batch(multi_modal_inputs_list,
  442. device=self.device)
  443. return (input_tokens, input_positions, attn_metadata, seq_lens,
  444. multi_modal_kwargs)