spec_decode_worker.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. from functools import cached_property
  2. from typing import List, Optional, Tuple
  3. import torch
  4. from loguru import logger
  5. from aphrodite.common.sequence import (ExecuteModelRequest, SamplerOutput,
  6. SequenceGroupMetadata)
  7. from aphrodite.modeling.layers.rejection import RejectionSampler
  8. from aphrodite.spec_decode.batch_expansion import BatchExpansionTop1Scorer
  9. from aphrodite.spec_decode.interfaces import (SpeculativeProposals,
  10. SpeculativeScorer,
  11. SpeculativeScores)
  12. from aphrodite.spec_decode.metrics import AsyncMetricsCollector
  13. from aphrodite.spec_decode.multi_step_worker import MultiStepWorker
  14. from aphrodite.spec_decode.ngram_worker import NGramWorker
  15. from aphrodite.spec_decode.util import (create_sequence_group_output,
  16. get_all_num_logprobs, get_all_seq_ids,
  17. get_sampled_token_logprobs, nvtx_range,
  18. split_batch_by_proposal_len)
  19. from aphrodite.task_handler.worker_base import (LoraNotSupportedWorkerBase,
  20. WorkerBase)
  21. class SpecDecodeWorker(LoraNotSupportedWorkerBase):
  22. """Worker which implements speculative decoding.
  23. Speculative decoding reduces decoding per-token latency by using a proposal
  24. method, such as a small draft model, to speculate ahead of a larger LLM. The
  25. probabilities of the speculative tokens are then determined by the larger
  26. LLM, after which some verification routine determines which (if any) of the
  27. speculative tokens are accepted by the larger LLM.
  28. The current implementation has the following limitations:
  29. * Only draft-model proposal is implemented (contributions for more forms are
  30. welcome!).
  31. * Only top-1 proposal and scoring are implemented. Tree-attention is left as
  32. future work.
  33. * Only lossless rejection sampling is supported. Contributions adding lossy
  34. verification routines are welcome (e.g. Medusa's typical acceptance).
  35. * All sequences in a batch must have the same proposal length, or zero. This
  36. can be improved by having per-sequence speculation in the future.
  37. * The scoring forward pass is done without an MQA kernel, which is
  38. suboptimal especially as the batch size, proposal length, and sequence
  39. lengths grow. Contributions to add a MQA scoring are welcome once
  40. correctness tests pass.
  41. """
  42. @classmethod
  43. def create_worker(
  44. cls,
  45. scorer_worker: WorkerBase,
  46. draft_worker_kwargs,
  47. ) -> "SpecDecodeWorker":
  48. ngram_prompt_lookup_max = (
  49. draft_worker_kwargs.pop("ngram_prompt_lookup_max"))
  50. ngram_prompt_lookup_min = (
  51. draft_worker_kwargs.pop("ngram_prompt_lookup_min"))
  52. if ngram_prompt_lookup_max > 0:
  53. proposer_worker = NGramWorker(**draft_worker_kwargs)
  54. proposer_worker.set_ngram_window_size(ngram_prompt_lookup_min,
  55. ngram_prompt_lookup_max)
  56. else:
  57. proposer_worker = MultiStepWorker(**draft_worker_kwargs)
  58. logger.info("Configuring SpecDecodeWorker with "
  59. f"proposer={type(proposer_worker)}")
  60. return SpecDecodeWorker(
  61. proposer_worker,
  62. scorer_worker,
  63. # TODO: disable strict mode for speedup.
  64. rejection_sampler=RejectionSampler(strict_mode=True),
  65. )
  66. def __init__(
  67. self,
  68. proposer_worker: WorkerBase,
  69. scorer_worker: WorkerBase,
  70. rejection_sampler: RejectionSampler,
  71. metrics_collector: Optional[AsyncMetricsCollector] = None,
  72. ):
  73. """
  74. Create a SpecDecodeWorker.
  75. Args:
  76. proposer_worker: A worker that can produce speculative tokens for
  77. sequences.
  78. scorer_worker: A worker that produces probabilities of speculative
  79. tokens according to some base model. Typically a vanilla
  80. Aphrodite Worker.
  81. rejection_sampler: A Torch module used to perform modified rejection
  82. sampling for speculative decoding.
  83. metrics_collector: Helper class for collecting metrics; can be set
  84. for testing purposes.
  85. """
  86. self.proposer_worker = proposer_worker
  87. self.scorer_worker = scorer_worker
  88. self.rejection_sampler = rejection_sampler
  89. self._metrics = AsyncMetricsCollector(
  90. rejection_sampler
  91. ) if metrics_collector is None else metrics_collector
  92. self.probs_dtype = self.rejection_sampler.probs_dtype
  93. self.token_id_dtype = self.rejection_sampler.token_id_dtype
  94. # Lazy initiazliation.
  95. self.scorer: SpeculativeScorer
  96. def init_device(self) -> None:
  97. """Initialize both scorer and proposer models.
  98. """
  99. # The scorer worker model is initialized first in case the proposer
  100. # model has a smaller TP degree than the target worker.
  101. self.scorer_worker.init_device()
  102. self.proposer_worker.init_device()
  103. # NOTE: load_model is not part of the WorkerBase interface.
  104. self.scorer_worker.load_model()
  105. self.proposer_worker.load_model()
  106. self._metrics.init_gpu_tensors(self.rank)
  107. self.rejection_sampler.init_gpu_tensors(self.rank)
  108. self.scorer = BatchExpansionTop1Scorer(
  109. scorer_worker=self.scorer_worker,
  110. device=self.device,
  111. vocab_size=self._vocab_size)
  112. self._configure_model_sampler_for_spec_decode()
  113. def _configure_model_sampler_for_spec_decode(self):
  114. """Configure model sampler to emit GPU tensors. This allows spec decode
  115. to keep data on device without transferring to CPU and serializing,
  116. which significantly reduces overhead of rejection sampling.
  117. NOTE: This breaks abstraction boundaries pretty badly. The better
  118. design is to have the "move to CPU and serialize" sampling decision be
  119. done outside of the model/sampler; this way the "last-mile" worker
  120. object which interfaces with the scheduler can serialize and incur the
  121. performance hit as necessary. This allows us to run the worker several
  122. iterations in a row without incurring the "move to CPU and serialize"
  123. performance penalty.
  124. Since this requires a large change to vLLM, we defer it to later and
  125. temporarily accept this broken abstraction boundary.
  126. NOTE: This will require a special check if the proposer worker
  127. does not have a sampler (e.g. ngram speculation).
  128. """
  129. (self.scorer_worker.model_runner.model.sampler.include_gpu_probs_tensor
  130. ) = True
  131. self.proposer_worker.set_include_gpu_probs_tensor()
  132. def determine_num_available_blocks(self) -> Tuple[int, int]:
  133. """Determine the number of cache blocks to use.
  134. This is done by profiling the scorer model (which is typically the
  135. larger of the two). Then the total memory which would be used by the
  136. scorer cache is divided evenly between the proposer and scorer model KV,
  137. such that the number of blocks is equal in both KV caches.
  138. """
  139. num_gpu_blocks, num_cpu_blocks = (
  140. self.scorer_worker.determine_num_available_blocks())
  141. scorer_cache_block_size_bytes = (
  142. self.scorer_worker.get_cache_block_size_bytes())
  143. proposer_cache_block_size_bytes = (
  144. self.proposer_worker.get_cache_block_size_bytes())
  145. new_num_gpu_blocks = split_num_cache_blocks_evenly(
  146. scorer_cache_block_size_bytes, proposer_cache_block_size_bytes,
  147. num_gpu_blocks)
  148. return new_num_gpu_blocks, num_cpu_blocks
  149. def initialize_cache(self, num_gpu_blocks: int,
  150. num_cpu_blocks: int) -> None:
  151. """Initialize the cache engine of the scorer and proposer workers.
  152. """
  153. self.scorer_worker.initialize_cache(num_gpu_blocks=num_gpu_blocks,
  154. num_cpu_blocks=num_cpu_blocks)
  155. self.proposer_worker.initialize_cache(num_gpu_blocks=num_gpu_blocks,
  156. num_cpu_blocks=num_cpu_blocks)
  157. @torch.inference_mode()
  158. def execute_model(
  159. self,
  160. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  161. """Perform speculative decoding on the input batch.
  162. """
  163. assert execute_model_req.seq_group_metadata_list is not None, (
  164. "speculative decoding "
  165. "requires non-None seq_group_metadata_list")
  166. # If no spec tokens, call the proposer and scorer workers normally.
  167. # Used for prefill.
  168. if execute_model_req.num_lookahead_slots == 0 or len(
  169. execute_model_req.seq_group_metadata_list) == 0:
  170. return self._run_no_spec(execute_model_req)
  171. return self._run_speculative_decoding_step(execute_model_req)
  172. @nvtx_range("spec_decode_worker._run_no_spec")
  173. def _run_no_spec(
  174. self,
  175. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  176. """Run a prefill step, without any speculation. The input is sent to the
  177. proposer and scorer model so that the KV cache is consistent between the
  178. two.
  179. """
  180. #logger.info("run proposer worker no spec")
  181. self.proposer_worker.execute_model(execute_model_req)
  182. #logger.info("run target worker no spec")
  183. sampler_output = self.scorer_worker.execute_model(execute_model_req)
  184. assert len(sampler_output) == 1
  185. sampler_output = sampler_output[0]
  186. # Clear device tensors from sampler output. This reduces communication
  187. # overhead when the engine runs in a different process than the workers.
  188. sampler_output.probs = None
  189. sampler_output.sampled_tokens = None
  190. sampler_output.logprobs = None
  191. return [sampler_output]
  192. @nvtx_range("spec_decode_worker._run_speculative_decoding_step")
  193. def _run_speculative_decoding_step(
  194. self,
  195. execute_model_req: ExecuteModelRequest) -> List[SamplerOutput]:
  196. """Execute a single step of speculative decoding.
  197. This invokes the proposer worker to get k speculative tokens for each
  198. sequence, then scores each speculative token using the scoring worker.
  199. Returns a list of SamplerOutput, each containing a single token per
  200. sequence.
  201. """
  202. #logger.info("get spec proposals")
  203. # Generate proposals using draft worker.
  204. proposals = self.proposer_worker.get_spec_proposals(execute_model_req)
  205. #logger.info("score proposals")
  206. proposal_scores = self.scorer.score_proposals(
  207. execute_model_req,
  208. proposals,
  209. )
  210. #logger.info("verify proposals")
  211. accepted_token_ids, target_logprobs = self._verify_tokens(
  212. execute_model_req.seq_group_metadata_list, proposal_scores,
  213. proposals, execute_model_req.num_lookahead_slots)
  214. #logger.info("create output list")
  215. return self._create_output_sampler_list(
  216. execute_model_req.seq_group_metadata_list,
  217. accepted_token_ids,
  218. target_logprobs=target_logprobs,
  219. k=execute_model_req.num_lookahead_slots)
  220. @nvtx_range("spec_decode_worker._verify_tokens")
  221. def _verify_tokens(
  222. self,
  223. seq_group_metadata_list: List[SequenceGroupMetadata],
  224. proposal_scores: SpeculativeScores,
  225. proposals: SpeculativeProposals,
  226. max_proposal_len: int,
  227. ) -> Tuple[torch.Tensor, torch.Tensor]:
  228. """Determine which speculative tokens are accepted using the
  229. probabilities of each token according to the proposer and scorer models.
  230. Returns a tuple of Tensors, one for the accepted token ids and one for
  231. the logprobs according to the scoring model.
  232. """
  233. proposal_lens_list = proposals.proposal_lens.tolist()
  234. # Aphrodite currently only supports proposal lens equal to zero or the
  235. # batch proposal len. This adds some complexity (splitting the batch
  236. # into spec and non spec sequences) and should be removed in the
  237. # future. It can be done by supporting per-sequence proposal lens.
  238. _, spec_indices = split_batch_by_proposal_len(
  239. seq_group_metadata_list,
  240. proposal_lens_list,
  241. select_proposal_len_zero=False)
  242. _, non_spec_indices = split_batch_by_proposal_len(
  243. seq_group_metadata_list,
  244. proposal_lens_list,
  245. select_proposal_len_zero=True)
  246. original_indices = spec_indices + non_spec_indices
  247. # Get probabilities of target model, excluding bonus token.
  248. proposal_verifier_probs = proposal_scores.probs[spec_indices, :-1]
  249. # Get non-speculative sampled tokens from target model.
  250. non_spec_token_ids = proposal_scores.token_ids[non_spec_indices]
  251. # Get bonus tokens from target model.
  252. bonus_token_ids = proposal_scores.token_ids[spec_indices, -1:]
  253. # Get probabilities according to proposal method.
  254. proposal_probs = proposals.proposal_probs[spec_indices]
  255. # Get proposed tokens.
  256. proposal_token_ids = proposals.proposal_token_ids[spec_indices]
  257. accepted_token_ids = self.rejection_sampler(
  258. target_probs=proposal_verifier_probs,
  259. bonus_token_ids=bonus_token_ids,
  260. draft_probs=proposal_probs,
  261. draft_token_ids=proposal_token_ids,
  262. )
  263. # Append output tokens from non-speculative sequences to
  264. # the accepted token ids tensor.
  265. non_spec_token_ids = non_spec_token_ids.expand(-1, max_proposal_len +
  266. 1).clone()
  267. non_spec_token_ids[:, 1:] = -1
  268. accepted_token_ids = torch.cat(
  269. [accepted_token_ids, non_spec_token_ids])
  270. logprobs = proposal_scores.logprobs
  271. # Rearrange so that results are in the order of the original seq group
  272. # metadata.
  273. accepted_token_ids[original_indices] = accepted_token_ids.clone()
  274. return accepted_token_ids, logprobs
  275. def _create_output_sampler_list(
  276. self,
  277. seq_group_metadata_list: List[SequenceGroupMetadata],
  278. accepted_token_ids: torch.Tensor, # shape: [batch_size, k+1]
  279. target_logprobs: torch.Tensor, # shape: [batch_size, k+1, vocab_size]
  280. k: int,
  281. ) -> List[SamplerOutput]:
  282. """Given the accepted token ids, create a list of SamplerOutput.
  283. The output is padded with -1 tokens such that each sequence has
  284. the same number of outputs.
  285. """
  286. batch_size, num_steps = accepted_token_ids.shape
  287. # Organize input tensors by step instead of by sequence.
  288. target_logprobs_by_step = target_logprobs.transpose(0, 1)
  289. accepted_token_ids_by_step = accepted_token_ids.transpose(0, 1)
  290. # Get the logprobs/rank of the accepted tokens.
  291. (accepted_token_id_ranks_by_step,
  292. accepted_token_id_logprobs_by_step) = get_sampled_token_logprobs(
  293. logprob_tensor=target_logprobs_by_step,
  294. sampled_token_ids=accepted_token_ids_by_step,
  295. )
  296. # Get the top-k logprobs (which may or may not include the logprob of
  297. # the accepted token).
  298. (topk_logprobs_by_step,
  299. topk_indices_by_step) = target_logprobs_by_step.topk(
  300. k=self.scorer_worker.model_config.max_logprobs,
  301. dim=-1,
  302. )
  303. # Get the sequence ids and num_logprobs (sampling parameter) in the
  304. # batch.
  305. seq_ids = get_all_seq_ids(seq_group_metadata_list)
  306. num_logprobs_per_seq = get_all_num_logprobs(seq_group_metadata_list)
  307. # Serialize all tensors to CPU Python lists.
  308. accepted_token_ids_by_step = accepted_token_ids_by_step.tolist()
  309. accepted_token_id_ranks_by_step = (
  310. accepted_token_id_ranks_by_step.tolist())
  311. accepted_token_id_logprobs_by_step = (
  312. accepted_token_id_logprobs_by_step.tolist())
  313. topk_logprobs_by_step = topk_logprobs_by_step.tolist()
  314. topk_indices_by_step = topk_indices_by_step.tolist()
  315. # Construct the output on a per-step, per-sequence basis.
  316. sampler_output_list = []
  317. for step_index in range(num_steps):
  318. if all(token_id == -1
  319. for token_id in accepted_token_ids_by_step[step_index]):
  320. break
  321. step_output_token_ids = []
  322. for sequence_index in range(batch_size):
  323. # Each sequence may have a different num_logprobs; retrieve it.
  324. num_logprobs = num_logprobs_per_seq[sequence_index]
  325. step_output_token_ids.append(
  326. create_sequence_group_output(
  327. token_id=accepted_token_ids_by_step[step_index]
  328. [sequence_index],
  329. token_id_logprob_rank=accepted_token_id_ranks_by_step[
  330. step_index][sequence_index],
  331. token_id_logprob=accepted_token_id_logprobs_by_step[
  332. step_index][sequence_index],
  333. seq_id=seq_ids[sequence_index],
  334. topk_token_ids=topk_indices_by_step[step_index]
  335. [sequence_index][:num_logprobs],
  336. topk_logprobs=topk_logprobs_by_step[step_index]
  337. [sequence_index][:num_logprobs],
  338. ))
  339. sampler_output_list.append(
  340. SamplerOutput(outputs=step_output_token_ids))
  341. maybe_rejsample_metrics = (
  342. self._metrics.maybe_collect_rejsample_metrics(k))
  343. if maybe_rejsample_metrics is not None:
  344. sampler_output_list[
  345. 0].spec_decode_worker_metrics = maybe_rejsample_metrics
  346. return sampler_output_list
  347. @cached_property
  348. def _vocab_size(self) -> int:
  349. """Get the vocab size of the model and make sure it's consistent between
  350. draft and target workers.
  351. """
  352. vocab_sizes = [
  353. worker.vocab_size
  354. for worker in [self.proposer_worker, self.scorer_worker]
  355. ]
  356. assert all(vocab_sizes[0] == vocab_size for vocab_size in vocab_sizes)
  357. return vocab_sizes[0]
  358. @property
  359. def rank(self):
  360. return self.scorer_worker.rank
  361. @property
  362. def device(self):
  363. return self.scorer_worker.device
  364. def get_cache_block_size_bytes(self):
  365. """Return the size of a cache block in bytes.
  366. This function is only used to compose workers within a SpecDecodeWorker.
  367. We leave composing a SpecDecodeWorker within a SpecDecodeWorker
  368. undefined for now, although it could be implemented in the future.
  369. See https://arxiv.org/abs/2308.04623.
  370. """
  371. raise NotImplementedError
  372. def split_num_cache_blocks_evenly(scorer_cache_block_size_bytes: int,
  373. proposer_cache_block_size_bytes: int,
  374. total_num_gpu_blocks: int) -> int:
  375. """Given total_num_gpu_blocks, the number of GPU blocks that could be
  376. allocate to the target model, this function calculates how many blocks
  377. should be given to the draft and target model.
  378. Note that usually the block size, in bytes, of each model is different,
  379. as it's a function of number of KV/layer, number of heads, and hidden
  380. dimension size.
  381. Since the target and draft models allocate the same number of blocks, we
  382. simply calculate the number of blocks where if allocated by both models,
  383. the total memory usage from KV cache is no larger than the number of
  384. blocks allocatable by the target model alone.
  385. """
  386. new_num_gpu_blocks = int(
  387. total_num_gpu_blocks * scorer_cache_block_size_bytes /
  388. (proposer_cache_block_size_bytes + scorer_cache_block_size_bytes))
  389. return new_num_gpu_blocks