draft_model_runner.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. from typing import List, Optional
  2. import torch
  3. from loguru import logger
  4. from aphrodite import _custom_ops as ops
  5. try:
  6. from aphrodite.attention.backends.flash_attn import FlashAttentionMetadata
  7. except ModuleNotFoundError:
  8. # aphrodite_flash_attn is not installed, use the identical ROCm FA metadata
  9. from aphrodite.attention.backends.rocm_flash_attn import (
  10. ROCmFlashAttentionMetadata as FlashAttentionMetadata)
  11. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  12. LoRAConfig, ModelConfig, ParallelConfig,
  13. PromptAdapterConfig, SchedulerConfig)
  14. from aphrodite.common.sequence import (ExecuteModelRequest,
  15. IntermediateTensors, SamplerOutput)
  16. from aphrodite.multimodal import MultiModalInputs
  17. from aphrodite.task_handler.model_runner import (
  18. ModelInputForGPUWithSamplingMetadata, ModelRunner)
  19. # A flag to enable debug prints for the updated input tensors
  20. # before each step.
  21. debug_advance_input = False
  22. # A flag to allow GPU advance step for draft model runner.
  23. # Set to False for debugging.
  24. allow_gpu_advance_step = True
  25. class TP1DraftModelRunner(ModelRunner):
  26. """Specialized model runner for speculative decoding draft model.
  27. Since the draft model always execute k forward passes consecutively to
  28. generate k speculative tokens in a single speculative decoding step,
  29. we could get rid of most CPU-GPU synchronization and data transfer
  30. overheads by keeping model input and output tensors on GPU all the time.
  31. TODOs:
  32. 1. Currently supports only flash-attn, add support for other attn_backends.
  33. 2. Support TP > 1 (this requires some designs because we do not expect
  34. any broadcasting inside execute_model).
  35. """
  36. def __init__(
  37. self,
  38. model_config: ModelConfig,
  39. parallel_config: ParallelConfig,
  40. scheduler_config: SchedulerConfig,
  41. device_config: DeviceConfig,
  42. cache_config: CacheConfig,
  43. load_config: LoadConfig,
  44. lora_config: Optional[LoRAConfig],
  45. kv_cache_dtype: Optional[str] = "auto",
  46. is_driver_worker: bool = False,
  47. prompt_adapter_config: Optional[PromptAdapterConfig] = None,
  48. return_hidden_states: bool = False,
  49. **kwargs, # for uneven TP
  50. ):
  51. if return_hidden_states:
  52. raise ValueError(
  53. "return_hidden_states is not supported for TP1DraftModelRunner."
  54. )
  55. super().__init__(
  56. model_config=model_config,
  57. parallel_config=parallel_config,
  58. scheduler_config=scheduler_config,
  59. device_config=device_config,
  60. cache_config=cache_config,
  61. load_config=load_config,
  62. lora_config=lora_config,
  63. kv_cache_dtype=kv_cache_dtype,
  64. is_driver_worker=is_driver_worker,
  65. prompt_adapter_config=prompt_adapter_config,
  66. return_hidden_states=return_hidden_states,
  67. **kwargs,
  68. )
  69. def _update_sampling_metadata(self, sampling_metadata, num_seqs,
  70. num_queries):
  71. assert sampling_metadata.num_prompts == 0
  72. assert len(sampling_metadata.seq_groups) == num_queries
  73. assert sampling_metadata.selected_token_indices.shape == (
  74. num_queries, )
  75. # assert sampling_metadata.categorized_sample_indices == TODO: Add if needed # noqa: E501
  76. # Verify that all sequences are decodes
  77. for i in range(num_queries):
  78. seq_group = sampling_metadata.seq_groups[i]
  79. assert seq_group.is_prompt is False # No prompt
  80. assert seq_group.prompt_logprob_indices == [] # No prompt
  81. assert seq_group.sample_indices == [i] # Simple
  82. assert seq_group.seq_len is None # Decode
  83. assert seq_group.query_len is None # Decode
  84. def _gpu_advance_step(
  85. self, model_input: ModelInputForGPUWithSamplingMetadata,
  86. last_output: SamplerOutput
  87. ) -> ModelInputForGPUWithSamplingMetadata:
  88. # Currently, we expect "decode mode" only
  89. assert not model_input.is_prompt
  90. # Get num_seqs
  91. num_seqs = len(model_input.seq_lens)
  92. num_queries = len(model_input.query_lens)
  93. # Get output tokens GPU tensor
  94. sampled_token_ids = last_output.sampled_token_ids
  95. assert sampled_token_ids is not None
  96. # Update attn_metadata
  97. attn_metadata = model_input.attn_metadata
  98. assert isinstance(attn_metadata, FlashAttentionMetadata)
  99. attn_metadata.advance_step(num_seqs, num_queries)
  100. # Update GPU tensors
  101. ops.advance_step(num_seqs=num_seqs,
  102. num_queries=num_queries,
  103. block_size=self.block_size,
  104. input_tokens=model_input.input_tokens,
  105. sampled_token_ids=sampled_token_ids,
  106. input_positions=model_input.input_positions,
  107. seq_lens=attn_metadata.seq_lens_tensor,
  108. slot_mapping=attn_metadata.slot_mapping,
  109. block_tables=attn_metadata.block_tables)
  110. # Update sampling_metadata
  111. sampling_metadata = model_input.sampling_metadata
  112. self._update_sampling_metadata(sampling_metadata, num_seqs,
  113. num_queries)
  114. # Create new input
  115. new_model_input = self._model_input_cls(
  116. input_tokens=model_input.input_tokens,
  117. input_positions=model_input.input_positions,
  118. attn_metadata=attn_metadata,
  119. seq_lens=attn_metadata.seq_lens,
  120. query_lens=model_input.query_lens,
  121. lora_mapping=model_input.lora_mapping,
  122. lora_requests=model_input.lora_requests,
  123. multi_modal_kwargs=model_input.multi_modal_kwargs,
  124. sampling_metadata=model_input.sampling_metadata,
  125. is_prompt=False,
  126. )
  127. # Ensure we skip CPU samples
  128. assert new_model_input.sampling_metadata.skip_sampler_cpu_output is True
  129. # We can reuse sampling tensors since every decode iteration is the same
  130. new_model_input.sampling_metadata.reuse_sampling_tensors = True
  131. if debug_advance_input:
  132. logger.debug("NEW INPUT: ")
  133. logger.debug(f" input_tokens = {new_model_input.input_tokens}")
  134. logger.debug(" input_positions = "
  135. f"{new_model_input.input_positions}")
  136. logger.debug(f" seq_lens = {new_model_input.seq_lens}")
  137. logger.debug(f" query_lens = {new_model_input.query_lens}")
  138. logger.debug(" attn_metadata:")
  139. logger.debug(" seq_lens_tensor: "
  140. f"{attn_metadata.seq_lens_tensor}")
  141. logger.debug(f" slot_mapping: {attn_metadata.slot_mapping}")
  142. logger.debug(f" block_tables: {attn_metadata.block_tables}")
  143. return new_model_input
  144. def supports_gpu_multi_step(self, execute_model_req: ExecuteModelRequest):
  145. """Determines if draft_model_runner GPU multi-step can be used.
  146. Currently required conditions are:
  147. 1. Only decodes
  148. 2. Only flash-attn
  149. 3. No LORA
  150. 4. No prompt_adapter_config
  151. """
  152. if not allow_gpu_advance_step:
  153. return False
  154. # We allow multi-step GPU only in decode mode
  155. for seq_group in execute_model_req.seq_group_metadata_list:
  156. if seq_group.is_prompt:
  157. return False
  158. # TODO: Add support for other attn backends
  159. if self.attn_backend.get_name() != "flash-attn":
  160. return False
  161. # TODO: Add support for LORA
  162. if self.lora_config:
  163. return False
  164. # TODO: Add soft-tuning prompt adapter support
  165. if self.prompt_adapter_config:
  166. return False
  167. return True
  168. @torch.inference_mode()
  169. def execute_model(
  170. self,
  171. model_input: ModelInputForGPUWithSamplingMetadata,
  172. kv_caches: List[torch.Tensor],
  173. previous_hidden_states: Optional[torch.Tensor] = None,
  174. intermediate_tensors: Optional[IntermediateTensors] = None,
  175. num_steps: int = 1,
  176. ) -> Optional[List[SamplerOutput]]:
  177. """Executes num_steps forward passes with advacement of input tensors
  178. on the GPU. Look at supports_gpu_multi_step(..) for pre-conditions.
  179. Optimizations used:
  180. 1. Input tensors are updated on the GPU directly
  181. 2. Skips GPU=>CPU serialization of sampler outputs (we don't need
  182. them since we do batch expansion later that uses GPU outputs)
  183. 3. Reuses sampling tensors (since we run only decodes and they have
  184. a repeating sampling logic)
  185. """
  186. # When num_steps == 1, we execute the fallback here for the GPU
  187. # advance_step, which runs prepare_inputs on CPU and for each spec
  188. # iteration invokes this function only once
  189. # (Look at multi-step-worker code)
  190. is_fallback = num_steps == 1
  191. if not is_fallback:
  192. # Since we do not broadcast data inside execute_model anymore,
  193. # we need to figure out the best way to support TP > 1 in this
  194. # case, because we will at least need to broadcast the sampled
  195. # tokens to all workers.
  196. if not self.is_driver_worker:
  197. raise ValueError("TP1DraftModelRunner only supports TP=1.")
  198. # Sanity
  199. if self.lora_config is not None:
  200. raise ValueError("TP1DraftModelRunner has no support for LORA")
  201. if self.prompt_adapter_config is not None:
  202. raise ValueError("TP1DraftModelRunner has no support for "
  203. "prompt_adapter_config")
  204. if model_input.multi_modal_kwargs:
  205. raise ValueError(
  206. "TP1DraftModelRunner has no support for multi_modal_kwargs"
  207. )
  208. else:
  209. if self.lora_config:
  210. assert model_input.lora_requests is not None
  211. assert model_input.lora_mapping is not None
  212. self.set_active_loras(model_input.lora_requests,
  213. model_input.lora_mapping)
  214. if self.prompt_adapter_config:
  215. assert model_input.prompt_adapter_requests is not None
  216. assert model_input.prompt_adapter_mapping is not None
  217. self.set_active_prompt_adapters(
  218. model_input.prompt_adapter_requests,
  219. model_input.prompt_adapter_mapping)
  220. self.attn_state.begin_forward(model_input)
  221. # Detect exec mode
  222. assert model_input.attn_metadata is not None
  223. use_cuda_graph = False
  224. if model_input.attn_metadata.num_prefills > 0:
  225. # In this case, execute_model(..) was called directly
  226. if num_steps > 1:
  227. raise ValueError(
  228. "execute_model(..) of draft_model_runner can be called "
  229. "directly only with a single-step prefill")
  230. else:
  231. # We can skip CPU samples for spec token generation.
  232. # (We do allow CPU samples for num_steps == 1 to support the
  233. # fallback case, where supports_gpu_multi_step(..) does not pass)
  234. model_input.sampling_metadata.skip_sampler_cpu_output = (
  235. not is_fallback)
  236. # Attn attr defines if we use cuda graphs
  237. use_cuda_graph = model_input.attn_metadata.use_cuda_graph
  238. # Get model
  239. if use_cuda_graph:
  240. graph_batch_size = model_input.input_tokens.shape[0]
  241. model_executable = (self.graph_runners[model_input.virtual_engine]
  242. [graph_batch_size])
  243. if previous_hidden_states is not None:
  244. hidden_states = torch.cat([
  245. previous_hidden_states,
  246. torch.empty([
  247. graph_batch_size - previous_hidden_states.shape[0],
  248. *previous_hidden_states.shape[1:]
  249. ],
  250. dtype=previous_hidden_states.dtype,
  251. device=previous_hidden_states.device)
  252. ])
  253. else:
  254. hidden_states = None
  255. else:
  256. model_executable = self.model
  257. hidden_states = previous_hidden_states
  258. outputs: List[SamplerOutput] = []
  259. for step in range(num_steps):
  260. multi_modal_kwargs = model_input.multi_modal_kwargs or {}
  261. kwargs = {"previous_hidden_states": hidden_states} \
  262. if previous_hidden_states is not None else {}
  263. # Run model
  264. hidden_states = model_executable(
  265. input_ids=model_input.input_tokens,
  266. positions=model_input.input_positions,
  267. kv_caches=kv_caches,
  268. attn_metadata=model_input.attn_metadata,
  269. intermediate_tensors=intermediate_tensors,
  270. **MultiModalInputs.as_kwargs(multi_modal_kwargs,
  271. device=self.device),
  272. **kwargs,
  273. )
  274. # Compute the logits.
  275. logits = self.model.compute_logits(hidden_states,
  276. model_input.sampling_metadata)
  277. # Sample the next token.
  278. outputs.append(
  279. self.model.sample(
  280. logits=logits,
  281. sampling_metadata=model_input.sampling_metadata,
  282. ))
  283. # Prepare inputs for the next step
  284. if step != num_steps - 1:
  285. model_input = self._gpu_advance_step(model_input, outputs[-1])
  286. return outputs