xpu_model_runner.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. # Lazy initialization.
  116. self.model: nn.Module # Set after init_Model
  117. def load_model(self) -> None:
  118. with CudaMemoryProfiler() as m:
  119. self.model = get_model(
  120. model_config=self.model_config,
  121. device_config=self.device_config,
  122. load_config=self.load_config,
  123. lora_config=self.lora_config,
  124. multimodal_config=self.multimodal_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. model_config = self.model_config
  151. mm_config = self.multimodal_config
  152. input_registry = self.input_registry
  153. mm_registry = self.mm_registry
  154. mm_registry.init_mm_limits_per_prompt(model_config, mm_config)
  155. max_mm_tokens = mm_registry.get_max_multimodal_tokens(model_config)
  156. if max_mm_tokens > 0:
  157. max_num_seqs_orig = max_num_seqs
  158. max_num_seqs = min(max_num_seqs,
  159. max_num_batched_tokens // max_mm_tokens)
  160. if max_num_seqs < 1:
  161. expr = (f"min({max_num_seqs_orig}, "
  162. f"{max_num_batched_tokens} // {max_mm_tokens})")
  163. logger.warning(
  164. f"Computed max_num_seqs ({expr}) to be less than 1. "
  165. "Setting it to the minimum value of 1.")
  166. max_num_seqs = 1
  167. for group_id in range(max_num_seqs):
  168. seq_len = (max_num_batched_tokens // max_num_seqs +
  169. (group_id < max_num_batched_tokens % max_num_seqs))
  170. seq_data, dummy_multi_modal_data = input_registry \
  171. .dummy_data_for_profiling(model_config, seq_len, mm_registry)
  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. generators=self.get_generators(finished_requests_ids))
  225. # Broadcast the metadata.
  226. metadata_dict = {
  227. "input_tokens": input_tokens,
  228. "input_positions": input_positions,
  229. "selected_token_indices":
  230. sampling_metadata.selected_token_indices,
  231. "multi_modal_kwargs": multi_modal_kwargs,
  232. }
  233. metadata_dict.update(attn_metadata.asdict_zerocopy())
  234. broadcast_tensor_dict(metadata_dict, src=0)
  235. else:
  236. metadata_dict = broadcast_tensor_dict(src=0)
  237. input_tokens = metadata_dict.pop("input_tokens")
  238. input_positions = metadata_dict.pop("input_positions")
  239. selected_token_indices = metadata_dict.pop(
  240. "selected_token_indices")
  241. multi_modal_kwargs = metadata_dict.pop("multi_modal_kwargs")
  242. attn_metadata = self.attn_backend.make_metadata(**metadata_dict)
  243. sampling_metadata = SamplingMetadata(
  244. seq_groups=None,
  245. selected_token_indices=selected_token_indices,
  246. categorized_sample_indices=None,
  247. num_prompts=0,
  248. )
  249. return ModelInputForXPU(input_tokens=input_tokens,
  250. input_positions=input_positions,
  251. attn_metadata=attn_metadata,
  252. sampling_metadata=sampling_metadata,
  253. multi_modal_kwargs=multi_modal_kwargs)
  254. def _prepare_decode(
  255. self,
  256. seq_group_metadata_list: List[SequenceGroupMetadata],
  257. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata]:
  258. assert len(seq_group_metadata_list) > 0
  259. input_tokens: List[int] = []
  260. input_positions: List[int] = []
  261. slot_mapping: List[int] = []
  262. seq_lens: List[int] = []
  263. block_tables: List[List[int]] = []
  264. for seq_group_metadata in seq_group_metadata_list:
  265. assert not seq_group_metadata.is_prompt
  266. assert seq_group_metadata.token_chunk_size == 1
  267. seq_ids = list(seq_group_metadata.seq_data.keys())
  268. for seq_id in seq_ids:
  269. seq_data = seq_group_metadata.seq_data[seq_id]
  270. generation_token = seq_data.get_last_token_id()
  271. input_tokens.append(generation_token)
  272. seq_len = seq_data.get_len()
  273. position = seq_len - 1
  274. input_positions.append(position)
  275. seq_len = seq_len if self.sliding_window is None else min(
  276. seq_len, self.sliding_window)
  277. seq_lens.append(seq_len)
  278. block_table = seq_group_metadata.block_tables[seq_id]
  279. block_number = block_table[position // self.block_size]
  280. block_offset = position % self.block_size
  281. slot = block_number * self.block_size + block_offset
  282. slot_mapping.append(slot)
  283. if self.sliding_window is not None:
  284. sliding_window_blocks = (self.sliding_window //
  285. self.block_size)
  286. block_table = block_table[-sliding_window_blocks:]
  287. block_tables.append(block_table)
  288. max_decode_seq_len = max(seq_lens)
  289. input_tokens = torch.tensor(input_tokens,
  290. dtype=torch.long,
  291. device=self.device)
  292. input_positions = torch.tensor(input_positions,
  293. dtype=torch.long,
  294. device=self.device)
  295. slot_mapping = torch.tensor(slot_mapping,
  296. dtype=torch.long,
  297. device=self.device)
  298. seq_lens_tensor = torch.tensor(seq_lens,
  299. dtype=torch.int,
  300. device=self.device)
  301. block_tables = make_tensor_with_pad(
  302. block_tables,
  303. pad=0,
  304. dtype=torch.int,
  305. device=self.device,
  306. )
  307. attn_metadata = self.attn_backend.make_metadata(
  308. is_prompt=False,
  309. slot_mapping=slot_mapping,
  310. seq_lens=seq_lens,
  311. seqlen_q=None,
  312. max_seqlen=None,
  313. seq_lens_tensor=seq_lens_tensor,
  314. max_decode_seq_len=max_decode_seq_len,
  315. num_prefill_tokens=0,
  316. num_decode_tokens=len(input_tokens),
  317. num_prefills=0,
  318. block_tables=block_tables,
  319. )
  320. return (
  321. input_tokens,
  322. input_positions,
  323. attn_metadata,
  324. )
  325. @torch.inference_mode()
  326. def execute_model(
  327. self,
  328. model_input: ModelInputForXPU,
  329. kv_caches: List[torch.Tensor],
  330. intermediate_tensors: Optional[IntermediateTensors] = None,
  331. num_steps: int = 1,
  332. ) -> Optional[List[SamplerOutput]]:
  333. if num_steps > 1:
  334. raise ValueError(
  335. "XPUModelRunner does not support multi-step execution.")
  336. model_executable = self.model
  337. execute_model_kwargs = {
  338. "input_ids":
  339. model_input.input_tokens,
  340. "positions":
  341. model_input.input_positions,
  342. "kv_caches":
  343. kv_caches,
  344. "attn_metadata":
  345. model_input.attn_metadata,
  346. **MultiModalInputs.as_kwargs(model_input.multi_modal_kwargs or {},
  347. device=self.device),
  348. }
  349. hidden_states = model_executable(**execute_model_kwargs)
  350. # Compute the logits.
  351. logits = self.model.compute_logits(hidden_states,
  352. model_input.sampling_metadata)
  353. # Only perform sampling in the driver worker.
  354. if not self.is_driver_worker:
  355. return []
  356. # Sample the next token.
  357. output = self.model.sample(
  358. logits=logits,
  359. sampling_metadata=model_input.sampling_metadata,
  360. )
  361. return [output]
  362. def _prepare_prompt(
  363. self,
  364. seq_group_metadata_list: List[SequenceGroupMetadata],
  365. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, List[int],
  366. BatchedTensorInputs]:
  367. assert len(seq_group_metadata_list) > 0
  368. input_tokens: List[int] = []
  369. input_positions: List[int] = []
  370. slot_mapping: List[int] = []
  371. seq_lens: List[int] = []
  372. multi_modal_inputs_list: List[MultiModalInputs] = []
  373. for seq_group_metadata in seq_group_metadata_list:
  374. assert seq_group_metadata.is_prompt
  375. seq_ids = list(seq_group_metadata.seq_data.keys())
  376. assert len(seq_ids) == 1
  377. seq_id = seq_ids[0]
  378. seq_data = seq_group_metadata.seq_data[seq_id]
  379. prompt_tokens = seq_data.get_token_ids()
  380. computed_len = seq_data.get_num_computed_tokens()
  381. seq_len = len(prompt_tokens)
  382. seq_lens.append(seq_len) # Prompt token num
  383. input_tokens.extend(prompt_tokens) # Token ids
  384. # Token position ids
  385. # NOTE: Here we assume that the first token in the prompt
  386. # is always the first token in the sequence.
  387. input_positions.extend(list(range(computed_len, seq_len)))
  388. mm_data = seq_group_metadata.multi_modal_data
  389. if mm_data:
  390. mm_kwargs = self.multi_modal_input_mapper(mm_data)
  391. multi_modal_inputs_list.append(mm_kwargs)
  392. if seq_group_metadata.block_tables is None:
  393. # During memory profiling, the block tables are not initialized
  394. # yet. In this case, we just use a dummy slot mapping.
  395. slot_mapping.extend([_PAD_SLOT_ID] * seq_len)
  396. continue
  397. # Compute the slot mapping.
  398. block_table = seq_group_metadata.block_tables[seq_id]
  399. # Mask the [0, start_idx) tokens of the prompt with _PAD_SLOT_ID,
  400. # where start_idx is max(0, seq_len - sliding_window).
  401. # For example, if the prompt len is 10, sliding window is 8, and
  402. # block size is 4, the first two tokens are masked and the slot
  403. # mapping will be [-1, -1, 2, 3, 4, 5, 6, 7, 0, 1].
  404. start_idx = 0
  405. if self.sliding_window is not None:
  406. start_idx = max(0, seq_len - self.sliding_window)
  407. for i in range(computed_len, seq_len):
  408. if i < start_idx:
  409. slot_mapping.append(_PAD_SLOT_ID)
  410. continue
  411. block_number = block_table[i //
  412. self.block_size] # type: ignore
  413. block_offset = i % self.block_size # type: ignore
  414. slot = block_number * self.block_size + block_offset
  415. slot_mapping.append(slot)
  416. num_prompt_tokens = len(input_tokens)
  417. input_tokens = torch.tensor(input_tokens,
  418. dtype=torch.long,
  419. device=self.device) # type: ignore
  420. input_positions = torch.tensor(input_positions,
  421. dtype=torch.long,
  422. device=self.device) # type: ignore
  423. slot_mapping = torch.tensor(slot_mapping,
  424. dtype=torch.long,
  425. device=self.device) # type: ignore
  426. max_seqlen = max(seq_lens)
  427. tmp = [0]
  428. tmp.extend(seq_lens)
  429. seqlen = torch.tensor(tmp)
  430. seqlen_q = torch.cumsum(seqlen, dim=0).to(device=self.device)
  431. attn_metadata = self.attn_backend.make_metadata(
  432. is_prompt=True,
  433. slot_mapping=slot_mapping,
  434. seq_lens=seq_lens,
  435. seqlen_q=seqlen_q,
  436. max_seqlen=max_seqlen,
  437. seq_lens_tensor=None,
  438. max_decode_seq_len=None,
  439. num_prefills=len(seq_lens),
  440. num_prefill_tokens=num_prompt_tokens,
  441. num_decode_tokens=0,
  442. block_tables=torch.tensor([], device=self.device, dtype=torch.int),
  443. )
  444. multi_modal_kwargs = MultiModalInputs.batch(multi_modal_inputs_list)
  445. return (input_tokens, input_positions, attn_metadata, seq_lens,
  446. multi_modal_kwargs)