batch_expansion.py 17 KB

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