xpu_model_runner.py 23 KB

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