draft_model_runner.py 15 KB

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