enc_dec_model_runner.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import dataclasses
  2. from typing import Any, Dict, List, Optional, Tuple, Type, cast
  3. import torch
  4. import torch.distributed
  5. from loguru import logger
  6. from aphrodite.attention.backends.abstract import (AttentionBackend,
  7. AttentionMetadata)
  8. from aphrodite.attention.backends.utils import PAD_SLOT_ID
  9. from aphrodite.attention.selector import (_Backend,
  10. get_env_variable_attn_backend,
  11. get_global_forced_attn_backend,
  12. global_force_attn_backend)
  13. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  14. LoRAConfig, ModelConfig, ParallelConfig,
  15. PromptAdapterConfig, SchedulerConfig)
  16. from aphrodite.common.sampling_params import SamplingParams
  17. from aphrodite.common.sequence import (IntermediateTensors, PoolerOutput,
  18. SamplerOutput, SequenceGroupMetadata)
  19. from aphrodite.common.utils import (STR_NOT_IMPL_ENC_DEC_BACKEND,
  20. make_tensor_with_pad)
  21. from aphrodite.inputs import INPUT_REGISTRY, InputRegistry
  22. from aphrodite.modeling import SamplingMetadata
  23. from aphrodite.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
  24. from aphrodite.task_handler.model_runner import (
  25. GPUModelRunnerBase, ModelInputForGPUBuilder,
  26. ModelInputForGPUWithSamplingMetadata)
  27. from aphrodite.task_handler.model_runner_base import (
  28. _add_attn_metadata_broadcastable_dict,
  29. _add_sampling_metadata_broadcastable_dict)
  30. from aphrodite.task_handler.utils import assert_enc_dec_mr_supported_scenario
  31. @dataclasses.dataclass(frozen=True)
  32. class EncoderDecoderModelInput(ModelInputForGPUWithSamplingMetadata):
  33. """
  34. Used by the EncoderDecoderModelRunner.
  35. """
  36. encoder_input_tokens: Optional[torch.Tensor] = None
  37. encoder_input_positions: Optional[torch.Tensor] = None
  38. def as_broadcastable_tensor_dict(self) -> Dict[str, Any]:
  39. tensor_dict = {
  40. "input_tokens": self.input_tokens,
  41. "input_positions": self.input_positions,
  42. "encoder_input_tokens": self.encoder_input_tokens,
  43. "encoder_input_positions": self.encoder_input_positions,
  44. "virtual_engine": self.virtual_engine,
  45. "request_ids_to_seq_ids": self.request_ids_to_seq_ids,
  46. "finished_requests_ids": self.finished_requests_ids,
  47. }
  48. _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
  49. _add_sampling_metadata_broadcastable_dict(tensor_dict,
  50. self.sampling_metadata)
  51. return tensor_dict
  52. @classmethod
  53. def from_broadcasted_tensor_dict(
  54. cls,
  55. tensor_dict: Dict[str, Any],
  56. attn_backend: Optional["AttentionBackend"] = None,
  57. ) -> "EncoderDecoderModelInput":
  58. return cast(
  59. EncoderDecoderModelInput,
  60. super().from_broadcasted_tensor_dict(tensor_dict, attn_backend))
  61. class EncoderDecoderModelRunner(GPUModelRunnerBase[EncoderDecoderModelInput]):
  62. _model_input_cls: Type[EncoderDecoderModelInput] = (
  63. EncoderDecoderModelInput)
  64. _builder_cls: Type[ModelInputForGPUBuilder] = (ModelInputForGPUBuilder)
  65. def __init__(
  66. self,
  67. model_config: ModelConfig,
  68. parallel_config: ParallelConfig,
  69. scheduler_config: SchedulerConfig,
  70. device_config: DeviceConfig,
  71. cache_config: CacheConfig,
  72. load_config: LoadConfig,
  73. lora_config: Optional[LoRAConfig],
  74. kv_cache_dtype: Optional[str] = "auto",
  75. is_driver_worker: bool = False,
  76. prompt_adapter_config: Optional[PromptAdapterConfig] = None,
  77. input_registry: InputRegistry = INPUT_REGISTRY,
  78. mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
  79. **kwargs,
  80. ):
  81. '''
  82. EncoderDecoderModelRunner constructor.
  83. `lora_config` and `prompt_adapter_config` are
  84. unused (since these features are not yet supported for encoder/decoder
  85. models) but these arguments are present here for compatibility with
  86. the base-class constructor.
  87. '''
  88. self._maybe_force_supported_attention_backend()
  89. super().__init__(
  90. model_config,
  91. parallel_config,
  92. scheduler_config,
  93. device_config,
  94. cache_config,
  95. load_config,
  96. lora_config=None,
  97. kv_cache_dtype=kv_cache_dtype,
  98. is_driver_worker=is_driver_worker,
  99. **kwargs,
  100. )
  101. # Crash for unsupported encoder/scenarios
  102. assert_enc_dec_mr_supported_scenario(self)
  103. def _maybe_force_supported_attention_backend(self):
  104. '''
  105. Force Aphrodite to use the XFormers attention backend,
  106. which is currently the only supported option.
  107. '''
  108. def raise_backend_err():
  109. # The user has specified an attention backend override
  110. # which is invalid for encoder/decoder models
  111. raise NotImplementedError(STR_NOT_IMPL_ENC_DEC_BACKEND)
  112. maybe_env_var_forced_backend = get_env_variable_attn_backend()
  113. maybe_global_forced_backend = get_global_forced_attn_backend()
  114. is_forced_by_global = maybe_global_forced_backend is not None
  115. is_forced_by_env_var = maybe_env_var_forced_backend is not None
  116. if not (is_forced_by_global or is_forced_by_env_var):
  117. # The user has not already specified an attention backend
  118. # override
  119. logger.info("EncoderDecoderModelRunner requires "
  120. "XFormers backend; overriding backend "
  121. "auto-selection and forcing XFormers.")
  122. global_force_attn_backend(_Backend.XFORMERS)
  123. elif is_forced_by_global:
  124. # Backend override enforced by global variable takes
  125. # precedence over Aphrodite backend environment variable.
  126. if maybe_global_forced_backend != _Backend.XFORMERS:
  127. raise_backend_err()
  128. elif is_forced_by_env_var:
  129. # Backend override enforced by Aphrodite backend
  130. # environment variable
  131. if maybe_env_var_forced_backend != _Backend.XFORMERS:
  132. raise_backend_err()
  133. def _list_to_int32_tensor(
  134. self,
  135. _list: List[int],
  136. ) -> torch.Tensor:
  137. return torch.tensor(_list, dtype=torch.int32, device=self.device)
  138. def _list_to_long_tensor(
  139. self,
  140. _list: List[int],
  141. ) -> torch.Tensor:
  142. return torch.tensor(_list, dtype=torch.long, device=self.device)
  143. def _empty_int32_tensor(self) -> torch.Tensor:
  144. return self._list_to_int32_tensor([])
  145. def _empty_long_tensor(self) -> torch.Tensor:
  146. return self._list_to_long_tensor([])
  147. @torch.inference_mode()
  148. def execute_model(
  149. self,
  150. model_input: EncoderDecoderModelInput,
  151. kv_caches: List[torch.Tensor],
  152. intermediate_tensors: Optional[IntermediateTensors] = None,
  153. num_steps: int = 1,
  154. ) -> Optional[List[PoolerOutput]]:
  155. if num_steps > 1:
  156. raise ValueError("num_steps > 1 is not supported in "
  157. "EncoderDecoderModelRunner")
  158. model_executable = self.model
  159. seqlen_agnostic_kwargs = {
  160. "finished_requests_ids": model_input.finished_requests_ids,
  161. "request_ids_to_seq_ids": model_input.request_ids_to_seq_ids,
  162. } if self.has_seqlen_agnostic else {}
  163. hidden_or_intermediate_states = model_executable(
  164. input_ids=model_input.input_tokens,
  165. positions=model_input.input_positions,
  166. encoder_input_ids=model_input.encoder_input_tokens,
  167. encoder_positions=model_input.encoder_input_positions,
  168. kv_caches=kv_caches,
  169. attn_metadata=model_input.attn_metadata,
  170. intermediate_tensors=intermediate_tensors,
  171. **seqlen_agnostic_kwargs)
  172. logits = self.model.compute_logits(hidden_or_intermediate_states,
  173. model_input.sampling_metadata)
  174. if not self.is_driver_worker:
  175. return []
  176. # Sample the next token.
  177. output: SamplerOutput = self.model.sample(
  178. logits=logits,
  179. sampling_metadata=model_input.sampling_metadata,
  180. )
  181. return [output]
  182. def make_model_input_from_broadcasted_tensor_dict(
  183. self, tensor_dict: Dict[str, Any]) -> EncoderDecoderModelInput:
  184. return EncoderDecoderModelInput.from_broadcasted_tensor_dict(
  185. tensor_dict,
  186. attn_backend=self.attn_backend,
  187. )
  188. def prepare_model_input(
  189. self,
  190. seq_group_metadata_list: List[SequenceGroupMetadata],
  191. virtual_engine: int = 0,
  192. finished_requests_ids: Optional[List[str]] = None
  193. ) -> EncoderDecoderModelInput:
  194. """Prepare the model input based on a given sequence group, including
  195. metadata for the sampling step.
  196. Since chunked prefill is not supported for encoder/decoder models,
  197. `input_tokens` is assumed to be either entirely prefill tokens or
  198. entirely decode tokens.
  199. """
  200. model_input = self._prepare_model_input_tensors(
  201. seq_group_metadata_list, finished_requests_ids)
  202. (
  203. attn_metadata,
  204. encoder_input_tokens_tensor,
  205. encoder_input_positions_tensor,
  206. ) = (self._prepare_encoder_model_input_tensors(seq_group_metadata_list,
  207. model_input))
  208. # Inject attn_metadata encoder/cross-attention fields &
  209. # encoder input tokens/positions into model_input.
  210. # Frozen dataclass fields cannot be modified, so use
  211. # dataclasses.replace to construct a new model input
  212. # instance.
  213. model_input = dataclasses.replace(
  214. model_input,
  215. attn_metadata=attn_metadata,
  216. encoder_input_tokens=encoder_input_tokens_tensor,
  217. encoder_input_positions=encoder_input_positions_tensor,
  218. )
  219. sampling_metadata = SamplingMetadata.prepare(seq_group_metadata_list,
  220. model_input.seq_lens,
  221. model_input.query_lens,
  222. self.device,
  223. self.pin_memory)
  224. is_prompt = (seq_group_metadata_list[0].is_prompt
  225. if seq_group_metadata_list else None)
  226. return dataclasses.replace(model_input,
  227. sampling_metadata=sampling_metadata,
  228. is_prompt=is_prompt,
  229. virtual_engine=virtual_engine)
  230. @torch.inference_mode()
  231. def profile_run(self) -> None:
  232. # Enable top-k sampling to reflect the accurate memory usage.
  233. sampling_params = SamplingParams(top_p=0.99, top_k=self.vocab_size - 1)
  234. max_num_batched_tokens = self.scheduler_config.max_num_batched_tokens
  235. max_num_seqs = self.scheduler_config.max_num_seqs
  236. # Profile memory usage with max_num_sequences sequences and the total
  237. # number of tokens equal to max_num_batched_tokens.
  238. seqs: List[SequenceGroupMetadata] = []
  239. max_mm_tokens = self.mm_registry.get_max_multimodal_tokens(
  240. self.model_config)
  241. if max_mm_tokens > 0:
  242. raise NotImplementedError(
  243. "Multi-modal encoder-decoder models are not supported yet")
  244. batch_size = 0
  245. for group_id in range(max_num_seqs):
  246. seq_len = (max_num_batched_tokens // max_num_seqs +
  247. (group_id < max_num_batched_tokens % max_num_seqs))
  248. batch_size += seq_len
  249. seq_data, _ = self.input_registry \
  250. .dummy_data_for_profiling(self.model_config,
  251. seq_len,
  252. self.mm_registry)
  253. # Having more tokens is over-conservative but otherwise fine
  254. assert len(seq_data.prompt_token_ids) >= seq_len, (
  255. f"Expected at least {seq_len} dummy tokens for profiling, "
  256. f"but got: {len(seq_data.prompt_token_ids)}")
  257. seq = SequenceGroupMetadata(
  258. request_id=str(group_id),
  259. is_prompt=True,
  260. seq_data={group_id: seq_data},
  261. sampling_params=sampling_params,
  262. block_tables=None,
  263. encoder_seq_data=seq_data,
  264. cross_block_table=None,
  265. )
  266. seqs.append(seq)
  267. # Run the model with the dummy inputs.
  268. num_layers = self.model_config.get_num_layers(self.parallel_config)
  269. kv_caches = [None] * num_layers
  270. finished_requests_ids = [seq.request_id for seq in seqs]
  271. model_input = self.prepare_model_input(
  272. seqs, finished_requests_ids=finished_requests_ids)
  273. intermediate_tensors = None
  274. self.execute_model(model_input, kv_caches, intermediate_tensors)
  275. torch.cuda.synchronize()
  276. return
  277. def _prepare_encoder_model_input_tensors(
  278. self,
  279. seq_group_metadata_list: List[SequenceGroupMetadata],
  280. model_input: EncoderDecoderModelInput,
  281. ) -> Tuple[AttentionMetadata, Optional[torch.Tensor],
  282. Optional[torch.Tensor]]:
  283. """Helper method to prepare the encoder- and cross-attn-related
  284. model inputs based on a given sequence group. These additional inputs
  285. are used to augment an already-computed `EncoderDecoderModelInput`
  286. data structure which already has decoder-related model inputs
  287. populated.
  288. Sets the following attn_metadata fields:
  289. * `num_encoder_tokens`
  290. * `encoder_seq_lens`
  291. * `encoder_seq_lens_tensor`
  292. * `max_encoder_seq_len`
  293. * `cross_slot_mapping`
  294. * `cross_block_tables`
  295. Constructs a new model inputs data structure, based on
  296. (1) the existing fields in the `model_inputs` argument,
  297. and (2) the following additional fields which are
  298. computed (or in the case of `attn_metadata`, updated)
  299. by this function:
  300. * attn_metadata
  301. * encoder_input_tokens
  302. * encoder_input_positions
  303. Arguments:
  304. * seq_group_metadata_list: list of sequence groups for which to
  305. compute inputs
  306. * model_inputs: model inputs data structure with decoder-oriented
  307. fields already computed.
  308. Return:
  309. * Updated model inputs data structure
  310. """
  311. if len(seq_group_metadata_list) == 0:
  312. return (model_input.attn_metadata, None, None)
  313. # Since we are not supporting chunked prefill either the entire
  314. # batch is prefill or it is decode
  315. is_prompt = seq_group_metadata_list[0].is_prompt
  316. # Build encoder inputs
  317. encoder_seq_lens: List[int] = []
  318. if is_prompt:
  319. # Prefill phase.
  320. cross_block_tables = self._empty_int32_tensor().view(
  321. len(seq_group_metadata_list), -1)
  322. # Extract input tokens/positions, cross-attention slot-mapping,
  323. # & seq len from each sequence group metadata
  324. (
  325. encoder_input_tokens,
  326. encoder_input_positions,
  327. cross_slot_mapping,
  328. ) = (
  329. [],
  330. [],
  331. [],
  332. )
  333. for seq_group_metadata in seq_group_metadata_list:
  334. # Build seq lens
  335. seq_len = seq_group_metadata.encoder_seq_data.get_len()
  336. token_ids = seq_group_metadata.encoder_seq_data.get_token_ids()
  337. encoder_seq_lens.append(seq_len)
  338. # Build slot mapping
  339. is_profile_run = (seq_group_metadata.block_tables is None)
  340. if is_profile_run:
  341. # During memory profiling, the block tables are not
  342. # initialized yet. In this case, we just use a dummy
  343. # slot mapping.
  344. # In embeddings, the block tables are {seq_id: None}.
  345. cross_slot_mapping.extend([PAD_SLOT_ID] * seq_len)
  346. else:
  347. for i in range(0, seq_len):
  348. block_number = seq_group_metadata.cross_block_table[
  349. i // self.block_size]
  350. block_offset = i % self.block_size
  351. slot = block_number * self.block_size + block_offset
  352. cross_slot_mapping.append(slot)
  353. # Build encoder input tokens
  354. encoder_input_tokens.extend(token_ids)
  355. encoder_input_positions.extend(list(range(0, seq_len)))
  356. # Convert tokens/positions & cross-attention
  357. # slot-mapping to encoder input tensors
  358. encoder_input_tokens_tensor = self._list_to_long_tensor(
  359. encoder_input_tokens)
  360. encoder_input_positions_tensor = self._list_to_long_tensor(
  361. encoder_input_positions)
  362. cross_slot_mapping_tensor = self._list_to_long_tensor(
  363. cross_slot_mapping)
  364. else:
  365. # Decode phase.
  366. encoder_input_tokens_tensor = self._empty_long_tensor()
  367. encoder_input_positions_tensor = self._empty_long_tensor()
  368. cross_slot_mapping_tensor = self._empty_long_tensor()
  369. # Extract cross-attention block tables &
  370. # seq len from each sequence group metadata.
  371. # Cross-attention block tables are empty
  372. # during Aphrodite memory profiling.
  373. cross_block_tables = []
  374. for seq_group_metadata in seq_group_metadata_list:
  375. encoder_seq_lens.append(
  376. seq_group_metadata.encoder_seq_data.get_len())
  377. cross_block_table = seq_group_metadata.cross_block_table
  378. cross_block_tables.append([] if (
  379. cross_block_table is None) else cross_block_table)
  380. # Convert cross-attention block tables to encoder input tensor
  381. cross_block_tables = make_tensor_with_pad(
  382. cross_block_tables,
  383. max_len=max(
  384. len(block_table) for block_table in cross_block_tables),
  385. pad=0,
  386. dtype=torch.int32,
  387. device=self.device,
  388. )
  389. # Compute encoder sequence lengths & encoder
  390. # sequence starting offset tensors
  391. max_encoder_seq_len = max(encoder_seq_lens, default=0)
  392. encoder_seq_lens_tensor = self._list_to_int32_tensor(encoder_seq_lens)
  393. encoder_seq_start_loc = torch.zeros(encoder_seq_lens_tensor.shape[0] +
  394. 1,
  395. dtype=torch.int32,
  396. device=self.device)
  397. torch.cumsum(encoder_seq_lens_tensor,
  398. dim=0,
  399. dtype=encoder_seq_start_loc.dtype,
  400. out=encoder_seq_start_loc[1:])
  401. # Update attention metadata with encoder-oriented attributes
  402. attn_metadata = model_input.attn_metadata
  403. assert attn_metadata is not None
  404. (
  405. attn_metadata.num_encoder_tokens,
  406. attn_metadata.encoder_seq_lens,
  407. attn_metadata.encoder_seq_lens_tensor,
  408. attn_metadata.max_encoder_seq_len,
  409. attn_metadata.cross_slot_mapping,
  410. attn_metadata.cross_block_tables,
  411. ) = (
  412. sum(encoder_seq_lens),
  413. encoder_seq_lens,
  414. encoder_seq_lens_tensor,
  415. max_encoder_seq_len,
  416. cross_slot_mapping_tensor,
  417. cross_block_tables,
  418. )
  419. return (attn_metadata, encoder_input_tokens_tensor,
  420. encoder_input_positions_tensor)