batch_expansion.py 18 KB

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