xpu_model_runner.py 20 KB

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