xpu_model_runner.py 20 KB

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