spec_decode_worker.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. from functools import cached_property
  2. from typing import Dict, List, Optional, Tuple
  3. import torch
  4. from aphrodite.common.sequence import (
  5. SamplerOutput,
  6. SequenceGroupMetadata,
  7. SequenceGroupOutput,
  8. SequenceOutput,
  9. )
  10. from aphrodite.modeling.layers.rejection import RejectionSampler
  11. from aphrodite.spec_decode.batch_expansion import BatchExpansionTop1Scorer
  12. from aphrodite.spec_decode.interfaces import (
  13. SpeculativeProposals,
  14. SpeculativeScorer,
  15. SpeculativeScores,
  16. )
  17. from aphrodite.spec_decode.metrics import AsyncMetricsCollector
  18. from aphrodite.spec_decode.multi_step_worker import MultiStepWorker
  19. from aphrodite.spec_decode.util import (
  20. get_all_seq_ids,
  21. nvtx_range,
  22. split_batch_by_proposal_len,
  23. )
  24. from aphrodite.task_handler.worker import Worker
  25. from aphrodite.task_handler.worker_base import LoraNotSupportedWorkerBase
  26. class SpecDecodeWorker(LoraNotSupportedWorkerBase):
  27. """Worker which implements speculative decoding.
  28. Speculative decoding reduces decoding per-token latency by using a proposal
  29. method, such as a small draft model, to speculate ahead of a larger LLM. The
  30. probabilities of the speculative tokens are then determined by the larger
  31. LLM, after which some verification routine determines which (if any) of the
  32. speculative tokens are accepted by the larger LLM.
  33. The current implementation has the following limitations:
  34. * Only draft-model proposal is implemented (contributions for more forms are
  35. welcome!).
  36. * Only top-1 proposal and scoring are implemented. Tree-attention is left as
  37. future work.
  38. * Only lossless rejection sampling is supported. Contributions adding lossy
  39. verification routines are welcome (e.g. Medusa's typical acceptance).
  40. * All sequences in a batch must have the same proposal length, or zero. This
  41. can be improved by having per-sequence speculation in the future.
  42. * The scoring forward pass is done without an MQA kernel, which is
  43. suboptimal especially as the batch size, proposal length, and sequence
  44. lengths grow. Contributions to add a MQA scoring are welcome once
  45. correctness tests pass.
  46. """
  47. def __init__(
  48. self,
  49. proposer_worker: MultiStepWorker,
  50. scorer_worker: Worker,
  51. rejection_sampler: RejectionSampler,
  52. metrics_collector: Optional[AsyncMetricsCollector] = None,
  53. ):
  54. """
  55. Create a SpecDecodeWorker.
  56. Args:
  57. proposer_worker: A worker that can produce speculative tokens for
  58. sequences.
  59. scorer_worker: A worker that produces probabilities of speculative
  60. tokens according to some base model. Typically a vanilla
  61. Aphrodite Worker.
  62. rejection_sampler: A Torch module used to perform modified rejection
  63. sampling for speculative decoding.
  64. metrics_collector: Helper class for collecting metrics; can be set
  65. for testing purposes.
  66. """
  67. self.proposer_worker = proposer_worker
  68. self.scorer_worker = scorer_worker
  69. self.rejection_sampler = rejection_sampler
  70. self._metrics = (AsyncMetricsCollector(rejection_sampler)
  71. if metrics_collector is None else metrics_collector)
  72. self.probs_dtype = self.rejection_sampler.probs_dtype
  73. self.token_id_dtype = self.rejection_sampler.token_id_dtype
  74. self.scorer: SpeculativeScorer = None
  75. def init_device(self) -> None:
  76. """Initialize both scorer and proposer models."""
  77. # The scorer worker model is initialized first in case the proposer
  78. # model has a smaller TP degree than the target worker.
  79. self.scorer_worker.init_device()
  80. self.proposer_worker.init_device()
  81. self._metrics.init_gpu_tensors(self.rank)
  82. self.rejection_sampler.init_gpu_tensors(self.rank)
  83. self.scorer = BatchExpansionTop1Scorer(
  84. scorer_worker=self.scorer_worker,
  85. device=self.device,
  86. vocab_size=self._vocab_size,
  87. )
  88. def determine_num_available_blocks(self) -> Tuple[int, int]:
  89. """Determine the number of cache blocks to use.
  90. This is done by profiling the scorer model (which is typically the
  91. larger of the two). Then the total memory which would be used by the
  92. scorer cache is divided evenly between the proposer and scorer model KV,
  93. such that the number of blocks is equal in both KV caches.
  94. """
  95. num_gpu_blocks, num_cpu_blocks = (
  96. self.scorer_worker.determine_num_available_blocks())
  97. scorer_cache_block_size_bytes = (
  98. self.scorer_worker.get_cache_block_size_bytes())
  99. proposer_cache_block_size_bytes = (
  100. self.proposer_worker.get_cache_block_size_bytes())
  101. new_num_gpu_blocks = split_num_cache_blocks_evenly(
  102. scorer_cache_block_size_bytes,
  103. proposer_cache_block_size_bytes,
  104. num_gpu_blocks,
  105. )
  106. return new_num_gpu_blocks, num_cpu_blocks
  107. def initialize_cache(self, num_gpu_blocks: int,
  108. num_cpu_blocks: int) -> None:
  109. """Initialize the cache engine of the scorer and proposer workers.
  110. """
  111. self.scorer_worker.initialize_cache(num_gpu_blocks=num_gpu_blocks,
  112. num_cpu_blocks=num_cpu_blocks)
  113. self.proposer_worker.initialize_cache(num_gpu_blocks=num_gpu_blocks,
  114. num_cpu_blocks=num_cpu_blocks)
  115. @torch.inference_mode()
  116. def execute_model(
  117. self,
  118. seq_group_metadata_list: List[SequenceGroupMetadata],
  119. blocks_to_swap_in: Optional[Dict[int, int]],
  120. blocks_to_swap_out: Optional[Dict[int, int]],
  121. blocks_to_copy: Optional[Dict[int, List[int]]],
  122. num_spec_tokens: int,
  123. ) -> List[SamplerOutput]:
  124. """Perform speculative decoding on the input batch."""
  125. assert seq_group_metadata_list is not None, (
  126. "speculative decoding "
  127. "requires non-None seq_group_metadata_list")
  128. # If no spec tokens, call the proposer and scorer workers normally.
  129. # Used for prefill.
  130. if num_spec_tokens == 0 or len(seq_group_metadata_list) == 0:
  131. return self._run_no_spec(
  132. seq_group_metadata_list=seq_group_metadata_list,
  133. blocks_to_swap_in=blocks_to_swap_in,
  134. blocks_to_swap_out=blocks_to_swap_out,
  135. blocks_to_copy=blocks_to_copy,
  136. )
  137. return self._run_speculative_decoding_step(
  138. seq_group_metadata_list=seq_group_metadata_list,
  139. blocks_to_swap_in=blocks_to_swap_in,
  140. blocks_to_swap_out=blocks_to_swap_out,
  141. blocks_to_copy=blocks_to_copy,
  142. k=num_spec_tokens,
  143. )
  144. @nvtx_range("spec_decode_worker._run_no_spec")
  145. def _run_no_spec(
  146. self,
  147. seq_group_metadata_list: List[SequenceGroupMetadata],
  148. blocks_to_swap_in: Optional[Dict[int, int]],
  149. blocks_to_swap_out: Optional[Dict[int, int]],
  150. blocks_to_copy: Optional[Dict[int, List[int]]],
  151. ) -> List[SamplerOutput]:
  152. """Run a prefill step, without any speculation. The input is sent to the
  153. proposer and scorer model so that the KV cache is consistent between the
  154. two.
  155. """
  156. self.proposer_worker.execute_model(
  157. seq_group_metadata_list=seq_group_metadata_list,
  158. blocks_to_swap_in=blocks_to_swap_in,
  159. blocks_to_swap_out=blocks_to_swap_out,
  160. blocks_to_copy=blocks_to_copy,
  161. return_python_output=False,
  162. )
  163. sampler_output = self.scorer_worker.execute_model(
  164. seq_group_metadata_list=seq_group_metadata_list,
  165. blocks_to_swap_in=blocks_to_swap_in,
  166. blocks_to_swap_out=blocks_to_swap_out,
  167. blocks_to_copy=blocks_to_copy,
  168. )
  169. # Clear device tensors from sampler output. This reduces communication
  170. # overhead when the engine runs in a different process than the workers.
  171. sampler_output.probs = None
  172. sampler_output.sampled_tokens = None
  173. return [sampler_output]
  174. @nvtx_range("spec_decode_worker._run_speculative_decoding_step")
  175. def _run_speculative_decoding_step(
  176. self,
  177. seq_group_metadata_list: List[SequenceGroupMetadata],
  178. blocks_to_swap_in: Optional[Dict[int, int]],
  179. blocks_to_swap_out: Optional[Dict[int, int]],
  180. blocks_to_copy: Optional[Dict[int, List[int]]],
  181. k: int,
  182. ) -> List[SamplerOutput]:
  183. """Execute a single step of speculative decoding.
  184. This invokes the proposer worker to get k speculative tokens for each
  185. sequence, then scores each speculative token using the scoring worker.
  186. Returns a list of SamplerOutput, each containing a single token per
  187. sequence.
  188. """
  189. # Generate proposals using draft worker.
  190. proposals = self.proposer_worker.get_spec_proposals(
  191. seq_group_metadata_list,
  192. blocks_to_swap_in,
  193. blocks_to_swap_out,
  194. blocks_to_copy,
  195. k,
  196. )
  197. proposal_scores = self.scorer.score_proposals(
  198. seq_group_metadata_list,
  199. blocks_to_swap_in,
  200. blocks_to_swap_out,
  201. blocks_to_copy,
  202. k,
  203. proposals,
  204. )
  205. accepted_token_ids = self._verify_tokens(seq_group_metadata_list,
  206. proposal_scores, proposals, k)
  207. return self._create_output_sampler_list(seq_group_metadata_list,
  208. accepted_token_ids, k)
  209. @nvtx_range("spec_decode_worker._verify_tokens")
  210. def _verify_tokens(
  211. self,
  212. seq_group_metadata_list: List[SequenceGroupMetadata],
  213. proposal_scores: SpeculativeScores,
  214. proposals: SpeculativeProposals,
  215. max_proposal_len: int,
  216. ) -> torch.Tensor:
  217. """Determine which speculative tokens are accepted using the
  218. probabilities of each token according to the proposer and scorer models.
  219. """
  220. proposal_lens_list = proposals.proposal_lens.tolist()
  221. # Aphrodite currently only supports proposal lens equal to zero or the
  222. # batch proposal len. This adds some complexity (splitting the batch
  223. # into spec and non spec sequences) and should be removed in the
  224. # future. It can be done by supporting per-sequence proposal lens.
  225. _, spec_indices = split_batch_by_proposal_len(
  226. seq_group_metadata_list,
  227. proposal_lens_list,
  228. select_proposal_len_zero=False,
  229. )
  230. _, non_spec_indices = split_batch_by_proposal_len(
  231. seq_group_metadata_list,
  232. proposal_lens_list,
  233. select_proposal_len_zero=True,
  234. )
  235. original_indices = spec_indices + non_spec_indices
  236. proposal_probs = proposal_scores.probs[spec_indices, :-1]
  237. bonus_token_ids = proposal_scores.token_ids[spec_indices, -1:]
  238. non_spec_token_ids = proposal_scores.token_ids[non_spec_indices]
  239. accepted_token_ids = self.rejection_sampler(
  240. proposal_probs,
  241. bonus_token_ids,
  242. proposals.proposal_probs,
  243. proposals.proposal_token_ids,
  244. )
  245. # Append output tokens from non-speculative sequences to
  246. # the accepted token ids tensor.
  247. non_spec_token_ids = non_spec_token_ids.expand(-1, max_proposal_len +
  248. 1).clone()
  249. non_spec_token_ids[:, 1:] = -1
  250. accepted_token_ids = torch.cat(
  251. [accepted_token_ids, non_spec_token_ids])
  252. # Rearrange so that results are in the order of the original seq group
  253. # metadata.
  254. accepted_token_ids[original_indices] = accepted_token_ids.clone()
  255. return accepted_token_ids
  256. def _create_output_sampler_list(
  257. self,
  258. seq_group_metadata_list: List[SequenceGroupMetadata],
  259. accepted_token_ids: torch.Tensor, # shape: [batch_size, k+1]
  260. k: int,
  261. ) -> List[SamplerOutput]:
  262. """Given the accepted token ids, create a list of SamplerOutput.
  263. The output is padded with -1 tokens such that each sequence has
  264. the same number of outputs.
  265. """
  266. seq_ids = get_all_seq_ids(seq_group_metadata_list)
  267. # shape: [k+1, batch_size]
  268. accepted_token_ids_by_step = accepted_token_ids.transpose(0,
  269. 1).tolist()
  270. sampler_output_list = []
  271. for token_ids_by_step in accepted_token_ids_by_step:
  272. if all(token_id == -1 for token_id in token_ids_by_step):
  273. break
  274. step_output_token_ids = []
  275. for token_id, seq_id in zip(token_ids_by_step, seq_ids):
  276. step_output_token_ids.append(
  277. SequenceGroupOutput(
  278. samples=[
  279. SequenceOutput(
  280. parent_seq_id=seq_id,
  281. output_token=token_id,
  282. # TODO Add verifier logprobs.
  283. logprobs={token_id: 0.0},
  284. persistent_data={},
  285. )
  286. ],
  287. prompt_logprobs=None,
  288. ))
  289. sampler_output_list.append(
  290. SamplerOutput(outputs=step_output_token_ids))
  291. maybe_rejsample_metrics = self._metrics.maybe_collect_rejsample_metrics(
  292. k)
  293. if maybe_rejsample_metrics is not None:
  294. sampler_output_list[
  295. 0].spec_decode_worker_metrics = maybe_rejsample_metrics
  296. return sampler_output_list
  297. @cached_property
  298. def _vocab_size(self) -> int:
  299. """Get the vocab size of the model and make sure it's consistent between
  300. draft and target workers.
  301. """
  302. vocab_sizes = [
  303. worker.vocab_size
  304. for worker in [self.proposer_worker, self.scorer_worker]
  305. ]
  306. assert all(vocab_sizes[0] == vocab_size for vocab_size in vocab_sizes)
  307. return vocab_sizes[0]
  308. @property
  309. def rank(self):
  310. return self.scorer_worker.rank
  311. @property
  312. def device(self):
  313. return self.scorer_worker.device
  314. def get_cache_block_size_bytes(self):
  315. """Return the size of a cache block in bytes.
  316. This function is only used to compose workers within a SpecDecodeWorker.
  317. We leave composing a SpecDecodeWorker within a SpecDecodeWorker
  318. undefined for now, although it could be implemented in the future.
  319. See https://arxiv.org/abs/2308.04623.
  320. """
  321. raise NotImplementedError
  322. def split_num_cache_blocks_evenly(
  323. scorer_cache_block_size_bytes: int,
  324. proposer_cache_block_size_bytes: int,
  325. total_num_gpu_blocks: int,
  326. ) -> int:
  327. """Given total_num_gpu_blocks, the number of GPU blocks that could be
  328. allocate to the target model, this function calculates how many blocks
  329. should be given to the draft and target model.
  330. Note that usually the block size, in bytes, of each model is different,
  331. as it's a function of number of KV/layer, number of heads, and hidden
  332. dimension size.
  333. Since the target and draft models allocate the same number of blocks, we
  334. simply calculate the number of blocks where if allocated by both models,
  335. the total memory usage from KV cache is no larger than the number of
  336. blocks allocatable by the target model alone.
  337. """
  338. new_num_gpu_blocks = int(
  339. total_num_gpu_blocks * scorer_cache_block_size_bytes /
  340. (proposer_cache_block_size_bytes + scorer_cache_block_size_bytes))
  341. return new_num_gpu_blocks