batch_expansion.py 17 KB

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