batch_expansion.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. from itertools import chain, count
  2. from typing import Dict, Iterator, List, Optional, Tuple
  3. import torch
  4. from aphrodite.common.sequence import (SamplerOutput, SequenceData,
  5. SequenceGroupMetadata)
  6. from aphrodite.spec_decode.interfaces import (SpeculativeProposals,
  7. SpeculativeScorer,
  8. SpeculativeScores)
  9. from aphrodite.spec_decode.util import (get_all_seq_ids, nvtx_range,
  10. sampler_output_to_torch,
  11. split_batch_by_proposal_len)
  12. from aphrodite.task_handler.worker_base import WorkerBase
  13. SeqId = int
  14. TargetSeqId = int
  15. TokenId = int
  16. class BatchExpansionTop1Scorer(SpeculativeScorer):
  17. """Implements a speculative scorer that uses batch expansion to get
  18. probabilities of speculative tokens according to the scoring model.
  19. Batch expansion converts a list of sequences and multiple query positions
  20. to a new batch of sequences, each with a single query position. This allows
  21. for MQA-like scoring in speculative decoding without requiring an MQA
  22. kernel.
  23. It is strictly less efficient than MQA scoring.
  24. It only supports scoring the top1 proposal tokens of the proposer, instead
  25. of topk/tree.
  26. """
  27. def __init__(self, scorer_worker: WorkerBase, device: str,
  28. vocab_size: int):
  29. self._scorer_worker = scorer_worker
  30. self._device = device
  31. self._vocab_size = vocab_size
  32. @nvtx_range("BatchExpansionTop1Scorer.score_proposals")
  33. def score_proposals(
  34. self,
  35. seq_group_metadata_list: List[SequenceGroupMetadata],
  36. blocks_to_swap_in: Optional[Dict[int, int]],
  37. blocks_to_swap_out: Optional[Dict[int, int]],
  38. blocks_to_copy: Optional[Dict[int, List[int]]],
  39. k: int,
  40. proposals: SpeculativeProposals,
  41. ) -> SpeculativeScores:
  42. """Score the proposed tokens via the scorer model.
  43. This converts each input sequence to a set of k+1 target sequences. The
  44. target sequences have the unique continuations to be scored and a
  45. unique sequence ID that is different from all input sequence ids.
  46. If a speculative sequence length would exceed the max model length, then
  47. no speculation is produced for that sequence.
  48. Args:
  49. seq_group_metadata_list: The input sequence group metadata.
  50. blocks_to_swap_in: This is passed to the worker during scoring.
  51. blocks_to_swap_out: This is passed to the worker during scoring.
  52. blocks_to_copy: This is passed to the worker during scoring.
  53. k: The fixed proposal length.
  54. proposals: The speculative proposals to score.
  55. Returns:
  56. SpeculativeScores: The scores of each speculative token, along with
  57. which sequences were ignored during scoring.
  58. """
  59. # TODO: perform this on GPU to remove blocking call.
  60. proposal_lens_list = proposals.proposal_lens.tolist()
  61. proposal_token_ids_list = proposals.proposal_token_ids.tolist()
  62. # Filter the list to ignore -1 proposals.
  63. proposal_token_ids_list_without_skips = [
  64. proposals for proposals in proposal_token_ids_list
  65. if -1 not in proposals
  66. ]
  67. (spec_indices, non_spec_indices, target_seq_group_metadata_list,
  68. num_scoring_tokens) = self._expand_batch(
  69. seq_group_metadata_list=seq_group_metadata_list,
  70. proposal_token_ids_list=proposal_token_ids_list_without_skips,
  71. proposal_lens_list=proposal_lens_list,
  72. )
  73. target_sampler_output = self._scorer_worker.execute_model(
  74. seq_group_metadata_list=target_seq_group_metadata_list,
  75. blocks_to_swap_in=blocks_to_swap_in,
  76. blocks_to_swap_out=blocks_to_swap_out,
  77. blocks_to_copy=blocks_to_copy,
  78. )
  79. assert len(target_sampler_output) == 1, "expected single-step output"
  80. target_sampler_output = target_sampler_output[0]
  81. all_tokens, all_probs = self._contract_batch(
  82. contracted_bs=len(seq_group_metadata_list),
  83. target_sampler_output=target_sampler_output,
  84. proposals=proposals,
  85. num_scoring_tokens=num_scoring_tokens,
  86. non_spec_indices=non_spec_indices,
  87. spec_indices=spec_indices,
  88. k=k,
  89. )
  90. return SpeculativeScores(
  91. probs=all_probs,
  92. token_ids=all_tokens,
  93. )
  94. def _expand_batch(
  95. self,
  96. seq_group_metadata_list: List[SequenceGroupMetadata],
  97. proposal_token_ids_list: List[List[TokenId]],
  98. proposal_lens_list: List[int],
  99. ) -> Tuple[List[int], List[int], List[SequenceGroupMetadata], int]:
  100. """Given the input sequences and potentially multiple corresponding
  101. proposal tokens, create a new batch where each sequence has a single
  102. query token.
  103. """
  104. # Aphrodite currently only supports proposal lens equal to zero or the
  105. # batch proposal len. This adds some complexity (splitting the batch
  106. # into spec and non spec sequences) and should be removed in the
  107. # future. It can be done by supporting per-sequence proposal lens.
  108. spec_seqs, spec_indices = split_batch_by_proposal_len(
  109. seq_group_metadata_list,
  110. proposal_lens_list,
  111. select_proposal_len_zero=False)
  112. non_spec_seqs, non_spec_indices = split_batch_by_proposal_len(
  113. seq_group_metadata_list,
  114. proposal_lens_list,
  115. select_proposal_len_zero=True)
  116. target_seq_group_metadata_list = self._create_scoring_model_input(
  117. seq_group_metadata_list=spec_seqs,
  118. proposal_token_ids=proposal_token_ids_list,
  119. # NOTE: We determine the seq ids in the expanded batch using the
  120. # full seq_group_metadata_list, instead of only spec_seqs.
  121. target_seq_ids_iter=self._create_target_seq_id_iterator(
  122. seq_ids=get_all_seq_ids(seq_group_metadata_list)),
  123. )
  124. num_scoring_tokens = len(target_seq_group_metadata_list)
  125. target_seq_group_metadata_list.extend(non_spec_seqs)
  126. return (spec_indices, non_spec_indices, target_seq_group_metadata_list,
  127. num_scoring_tokens)
  128. def _contract_batch(self, contracted_bs: int,
  129. target_sampler_output: List[SamplerOutput],
  130. proposals: SpeculativeProposals,
  131. num_scoring_tokens: int, non_spec_indices: List[int],
  132. spec_indices: List[int],
  133. k: int) -> Tuple[torch.Tensor, torch.Tensor]:
  134. """Contract the expanded batch back into its original size.
  135. This maps the scores of speculative tokens back to their original
  136. sequences.
  137. contracted_bs is the original batch size, and the batch size that the
  138. target_sampler_output will be contracted to.
  139. """
  140. (target_token_ids, target_probs, non_spec_target_token_ids,
  141. non_spec_target_probs) = self._split_scoring_output(
  142. target_sampler_output, num_scoring_tokens)
  143. # Map distinct sequences used to score each token
  144. # of shape [batch_size * k + 1] back to [batch_size, k + 1].
  145. expanded_batch_size, k = proposals.proposal_token_ids.shape
  146. # The number of tokens in the expanded batch used for speculation is
  147. # equal to the total expanded batch size minus the number of samples for
  148. # non-speculative sequences.
  149. non_spec_expanded_bs, _ = non_spec_target_token_ids.shape
  150. spec_expanded_bs = expanded_batch_size - non_spec_expanded_bs
  151. target_token_ids = target_token_ids.squeeze().reshape(
  152. spec_expanded_bs, k + 1)
  153. target_probs = target_probs.squeeze().reshape(spec_expanded_bs, k + 1,
  154. self._vocab_size)
  155. all_tokens = torch.full(size=(contracted_bs, k + 1),
  156. fill_value=-1,
  157. device=self._device,
  158. dtype=torch.long)
  159. all_probs = torch.zeros(contracted_bs,
  160. k + 1,
  161. self._vocab_size,
  162. device=self._device,
  163. dtype=torch.float32)
  164. if non_spec_indices:
  165. all_tokens[non_spec_indices, :1] = non_spec_target_token_ids
  166. all_probs[non_spec_indices, :1, :] = non_spec_target_probs
  167. if spec_indices:
  168. all_tokens[spec_indices] = target_token_ids
  169. all_probs[spec_indices] = target_probs
  170. return all_tokens, all_probs
  171. def _create_scoring_model_input(
  172. self,
  173. seq_group_metadata_list: List[SequenceGroupMetadata],
  174. proposal_token_ids: List[List[TokenId]], # shape: [batch_size, k]
  175. target_seq_ids_iter: Iterator[TargetSeqId],
  176. ) -> List[SequenceGroupMetadata]:
  177. """Given the original input sequences and proposed tokens from the draft
  178. model, create a list of target sequences that can be used for scoring.
  179. target_seq_ids_iter provides sequence ids for the expanded batch,
  180. fulfilling the requirement that no seq id in the expanded batch is equal
  181. to the seq id in the original batch.
  182. """
  183. if not seq_group_metadata_list:
  184. return []
  185. target_seq_group_metadata = list(
  186. chain.from_iterable(
  187. self._create_target_seq_group_metadata(
  188. seq_group_metadata,
  189. proposal_token_ids,
  190. i,
  191. target_seq_ids_iter,
  192. ) for i, seq_group_metadata in enumerate(
  193. seq_group_metadata_list)))
  194. return target_seq_group_metadata
  195. def _create_target_seq_group_metadata(
  196. self,
  197. input_seq_group_metadata: SequenceGroupMetadata,
  198. proposal_token_ids: List[List[TokenId]], # shape: [batch_size, k]
  199. batch_index: int,
  200. target_seq_ids_iter: Iterator[TargetSeqId],
  201. ) -> List[SequenceGroupMetadata]:
  202. """Given an input sequence group metadata and a list of draft tokens,
  203. create a list of target SequenceGroupMetadata, one for each
  204. token id that needs to be scored.
  205. Naive speculative decoding requires K target model scores, one for each
  206. draft model token. However one can add a bonus token such that if each
  207. token is accepted, then a final token may be sampled from the model.
  208. This function creates K+1 target SequenceGroupMetadata to take
  209. advantage of the bonus token.
  210. """
  211. assert not input_seq_group_metadata.is_prompt, (
  212. "Speculating on "
  213. "prompts not yet supported")
  214. assert len(input_seq_group_metadata.seq_data) == 1, (
  215. "Beam search "
  216. "not supported in speculative decoding")
  217. input_seq_id = next(iter(input_seq_group_metadata.seq_data.keys()))
  218. token_ids_to_score = self._get_token_ids_to_score(
  219. proposal_token_ids[batch_index])
  220. target_seq_group_metadata_list: List[SequenceGroupMetadata] = []
  221. for token_ids in token_ids_to_score:
  222. target_seq_group_metadata_list.append(
  223. self._create_single_target_seq_group_metadata(
  224. input_seq_group_metadata,
  225. input_seq_id,
  226. next(target_seq_ids_iter),
  227. token_ids,
  228. ))
  229. return target_seq_group_metadata_list
  230. def _create_single_target_seq_group_metadata(
  231. self,
  232. seq_group_metadata: SequenceGroupMetadata,
  233. seq_id: SeqId,
  234. target_seq_id: TargetSeqId,
  235. token_ids: List[TokenId],
  236. ) -> SequenceGroupMetadata:
  237. """Create a single target SequenceGroupMetadata.
  238. Args:
  239. seq_group_metadata: The metadata for the input sequence.
  240. seq_id: The input sequence ID.
  241. target_seq_id: The corresponding target sequence ID.
  242. token_ids: The list of token ids that are to be appended to the
  243. input sequence.
  244. """
  245. seq_data = seq_group_metadata.seq_data[seq_id]
  246. prompt_token_ids = seq_data.get_prompt_token_ids()
  247. new_output_token_ids = [*seq_data.get_output_token_ids(), *token_ids]
  248. return SequenceGroupMetadata(
  249. request_id=seq_group_metadata.request_id,
  250. is_prompt=seq_group_metadata.is_prompt,
  251. seq_data={
  252. target_seq_id:
  253. SequenceData(
  254. prompt_token_ids=prompt_token_ids,
  255. output_token_ids=new_output_token_ids,
  256. ),
  257. },
  258. sampling_params=seq_group_metadata.sampling_params,
  259. block_tables={
  260. target_seq_id: seq_group_metadata.block_tables[seq_id],
  261. },
  262. lora_request=None,
  263. persistent_data={},
  264. )
  265. def _split_scoring_output(
  266. self, sampler_output: SamplerOutput, num_scoring_tokens: int
  267. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
  268. """Split the target model output into speculative and non-speculative
  269. output.
  270. """
  271. # Aphrodite currently only supports proposal lens equal to zero or the
  272. # batch proposal len. This adds some complexity (splitting the batch
  273. # into spec and non spec sequences) and should be removed in the
  274. # future. It can be done by supporting per-sequence proposal lens.
  275. # First samples are from speculative scoring, latter samples are non-
  276. # speculative samples.
  277. split_sizes = [
  278. num_scoring_tokens,
  279. sampler_output.sampled_token_ids.numel() - num_scoring_tokens
  280. ]
  281. (spec_probs, non_spec_probs
  282. ) = sampler_output.sampled_token_probs.split(split_sizes)
  283. (spec_sampled_tokens, non_spec_sampled_tokens
  284. ) = sampler_output.sampled_token_ids.flatten().split(split_sizes)
  285. # Convert scores to tensors.
  286. sampler_output.sampled_token_probs = spec_probs
  287. sampler_output.sampled_token_ids = spec_sampled_tokens
  288. target_token_ids, target_probs = sampler_output_to_torch(
  289. [sampler_output], True)
  290. # Convert non-speculative output tokens to tensors.
  291. sampler_output.sampled_token_probs = non_spec_probs
  292. sampler_output.sampled_token_ids = non_spec_sampled_tokens
  293. non_spec_target_token_ids, non_spec_target_probs = (
  294. sampler_output_to_torch([sampler_output], True))
  295. return (target_token_ids, target_probs, non_spec_target_token_ids,
  296. non_spec_target_probs)
  297. def _create_target_seq_id_iterator(
  298. self, seq_ids: List[SeqId]) -> Iterator[TargetSeqId]:
  299. """Create an iterator for creating target sequence ids.
  300. Target sequence ids are distinct from sequence ids because we create a
  301. distinct target sequence id for each proposal token to be scored.
  302. This implementation increments a counter starting at 1 + max of all
  303. provided input sequence ids.
  304. """
  305. return count(start=max(seq_ids) + 1)
  306. def _get_token_ids_to_score(
  307. self,
  308. full_spec_token_ids: List[TokenId] # shape: [k]
  309. ) -> List[List[TokenId]]:
  310. """Given an int tensor of proposal token ids, return a list of
  311. token ids that should be scored.
  312. Returns k+1 output lists. The additional one is used for generating the
  313. bonus token.
  314. Example:
  315. Input: [0, 1, 2, 3] (k=4)
  316. Output: (k+1 lists)
  317. []
  318. [0]
  319. [0, 1]
  320. [0, 1, 2]
  321. [0, 1, 2, 3]
  322. """
  323. empty_token_ids: List[TokenId] = []
  324. token_ids_to_score = [empty_token_ids]
  325. token_ids_to_score.extend([
  326. full_spec_token_ids[:i + 1]
  327. for i in range(len(full_spec_token_ids))
  328. ])
  329. return token_ids_to_score