multi_step_worker.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import copy
  2. import weakref
  3. from typing import Dict, List, Set, Tuple
  4. import torch
  5. from aphrodite.common.sequence import (ExecuteModelRequest, SamplerOutput,
  6. SequenceData, SequenceGroupMetadata)
  7. from aphrodite.spec_decode.draft_model_runner import TP1DraftModelRunner
  8. from aphrodite.spec_decode.interfaces import (SpeculativeProposals,
  9. SpeculativeProposer)
  10. from aphrodite.spec_decode.proposer_worker_base import ProposerWorkerBase
  11. from aphrodite.spec_decode.top1_proposer import Top1Proposer
  12. from aphrodite.task_handler.worker import Worker
  13. class MultiStepWorker(Worker, ProposerWorkerBase):
  14. """The MultiStepWorker is equivalent to a Worker except that it allows
  15. multiple forward passes in a single call, assuming the scheduler has
  16. allocated enough space to store the additional KV. This reduces overhead
  17. by invoking the scheduler less.
  18. The MultiStepWorker does not support cache swap operations, or beam search.
  19. Cache swap operations do not require large modifications. On the other hand,
  20. beam search requires memory allocations during sequence forks and thus
  21. requires more thought for MultiStepWorker support.
  22. """
  23. def __init__(self, *args, **kwargs):
  24. super().__init__(*args, **kwargs)
  25. # Lazy initialization list.
  26. self._proposer: SpeculativeProposer
  27. def init_device(self) -> None:
  28. super().init_device()
  29. self._proposer = Top1Proposer(
  30. weakref.proxy(self), # type: ignore[arg-type]
  31. self.device,
  32. self.vocab_size,
  33. max_proposal_len=self.max_model_len,
  34. )
  35. def set_include_gpu_probs_tensor(self) -> None:
  36. # Need include_gpu_probs_tensor for MultiStepWorker
  37. self.model_runner.model.sampler.include_gpu_probs_tensor = True
  38. def set_should_modify_greedy_probs_inplace(self) -> None:
  39. self.model_runner.model.sampler.should_modify_greedy_probs_inplace = (
  40. True)
  41. @torch.inference_mode()
  42. def sampler_output(
  43. self,
  44. execute_model_req: ExecuteModelRequest,
  45. sample_len: int,
  46. seq_ids_with_bonus_token_in_last_step: Set[int],
  47. ) -> Tuple[List[SamplerOutput], bool]:
  48. """Run the model forward pass sample_len times. Returns the list of
  49. sampler output, one per model forward pass, along with indicator of
  50. whether torch tensor in sampler output need to be transposed in latter
  51. sampler_output_to_torch logic.
  52. For multi step worker, this indicator shall be True.
  53. """
  54. self._raise_if_unsupported(execute_model_req)
  55. # Expand the batch for sequences with a bonus token.
  56. # Perform a forward pass on the expanded batch and filter the
  57. # response to retain only the original sequences' responses.
  58. expanded_request, indices_of_seq_with_bonus_tokens =\
  59. self._expand_execute_model_request(
  60. execute_model_req, seq_ids_with_bonus_token_in_last_step)
  61. # Run model sample_len times.
  62. model_outputs: List[SamplerOutput] = []
  63. if isinstance(
  64. self.model_runner, TP1DraftModelRunner
  65. ) and self.model_runner.supports_gpu_multi_step(expanded_request):
  66. # Here we run the draft_model_runner with multi-step prepare
  67. # on the GPU directly
  68. expanded_request.num_steps = sample_len
  69. model_outputs = self.execute_model(
  70. execute_model_req=expanded_request)
  71. else:
  72. # Here we run multi-step directly, with every step prepared
  73. # on the CPU.
  74. # TODO: Remove this branch once DraftModelRunner supports TP>1
  75. # and other restrictions that are part of DraftModelRunner's
  76. # supports_gpu_multi_step(..)
  77. for _ in range(sample_len):
  78. model_output: List[SamplerOutput] = super().execute_model(
  79. execute_model_req=expanded_request)
  80. assert (len(model_output) == 1
  81. ), "composing multistep workers not supported"
  82. model_output = model_output[0]
  83. self._append_new_tokens(
  84. model_output, expanded_request.seq_group_metadata_list)
  85. model_outputs.append(model_output)
  86. filtered_model_outputs = self._filter_model_output(
  87. model_outputs, indices_of_seq_with_bonus_tokens)
  88. return filtered_model_outputs, True
  89. @staticmethod
  90. def _expand_execute_model_request(
  91. execute_model_req: ExecuteModelRequest,
  92. seq_with_bonus_token_in_last_step: set,
  93. ) -> Tuple[ExecuteModelRequest, List[int]]:
  94. """
  95. Expands the execute model request based on sequences with bonus
  96. tokens.
  97. For each sequence with a bonus token, this method creates a new
  98. sequence without the bonus token and adds it to the execute model
  99. request. The original sequence groups are also retained. The indices
  100. of the original sequence groups are returned for further processing.
  101. Args:
  102. execute_model_req (ExecuteModelRequest): The original execute
  103. model request.
  104. seq_with_bonus_token_in_last_step (set): Set of sequence IDs that
  105. contain bonus tokens.
  106. Returns:
  107. Tuple[ExecuteModelRequest, List[int]]: The updated execute model
  108. request with expanded sequences and a list of indices corresponding
  109. to the original sequence groups.
  110. """
  111. updated_seq_group_metadata_list: List[SequenceGroupMetadata] = []
  112. updated_execute_model_req = execute_model_req.clone(
  113. updated_seq_group_metadata_list)
  114. indices_of_original_sequence_groups = []
  115. for seq_group in execute_model_req.seq_group_metadata_list:
  116. seq_group_has_bonus_tokens = False
  117. for seq_id, _ in seq_group.seq_data.items():
  118. # Identify sequences with bonus tokens in the sequence group.
  119. if seq_id in seq_with_bonus_token_in_last_step:
  120. seq_group_has_bonus_tokens = True
  121. break
  122. if seq_group_has_bonus_tokens:
  123. #Create new sequences without the last bonus token. These new
  124. # sequence have the same sequence id as the original sequence.
  125. # We create a new sequence group and add them there.
  126. updated_seq_group_without_bonus_token = \
  127. MultiStepWorker._copy_seq_metadata_excluding_last_token(
  128. seq_group, seq_with_bonus_token_in_last_step)
  129. updated_seq_group_metadata_list.append(
  130. updated_seq_group_without_bonus_token)
  131. # Add the original sequence group.
  132. updated_seq_group_metadata_list.append(
  133. MultiStepWorker._shallow_copy_seq_group_metadata(seq_group))
  134. # Record the index of the original sequence group.
  135. indices_of_original_sequence_groups.append(
  136. len(updated_seq_group_metadata_list) - 1)
  137. updated_execute_model_req.seq_group_metadata_list =\
  138. updated_seq_group_metadata_list
  139. return updated_execute_model_req, indices_of_original_sequence_groups
  140. @staticmethod
  141. def _filter_model_output(
  142. expanded_batch_outputs: List[SamplerOutput],
  143. output_indices_to_retain: List[int]) -> List[SamplerOutput]:
  144. """
  145. Filters the model output to include only the specified sequence
  146. outputs. This method contracts the expanded batch output from the
  147. model to retain the outputs of only those sequences indicated by the
  148. provided indices.
  149. Args:
  150. expanded_batch_output (List[SamplerOutput]): The expanded output
  151. batch from the model.
  152. output_indices_to_retain (List[int]): Indices of the model outputs
  153. to retain.
  154. Returns:
  155. List[SamplerOutput]: A list containing the filtered model
  156. outputs for the specified indices.
  157. """
  158. return [
  159. SamplerOutput(
  160. outputs=[
  161. expanded_batch_output.outputs[i]
  162. for i in output_indices_to_retain
  163. ] if len(expanded_batch_output.outputs) > 0 else [],
  164. sampled_token_probs=(
  165. expanded_batch_output.
  166. sampled_token_probs[output_indices_to_retain]
  167. if expanded_batch_output.sampled_token_probs is not None
  168. else None),
  169. logprobs=(
  170. expanded_batch_output.logprobs[output_indices_to_retain]
  171. if expanded_batch_output.logprobs is not None else None),
  172. sampled_token_ids=(expanded_batch_output.
  173. sampled_token_ids[output_indices_to_retain]
  174. if expanded_batch_output.sampled_token_ids
  175. is not None else None))
  176. for expanded_batch_output in expanded_batch_outputs
  177. ]
  178. def get_spec_proposals(
  179. self,
  180. execute_model_req: ExecuteModelRequest,
  181. seq_ids_with_bonus_token_in_last_step: set,
  182. ) -> SpeculativeProposals:
  183. """Produce speculations given an input batch of sequences. The number of
  184. speculative tokens per sequence is determined by max_proposal_len.
  185. """
  186. return self._proposer.get_spec_proposals(
  187. execute_model_req, seq_ids_with_bonus_token_in_last_step)
  188. @staticmethod
  189. def _append_new_tokens(
  190. model_output: List[SamplerOutput],
  191. seq_group_metadata_list: List[SequenceGroupMetadata]) -> None:
  192. """Given model output from a single run, append the tokens to the
  193. sequences. This is normally done outside of the worker, but it is
  194. required if the worker is to perform multiple forward passes.
  195. """
  196. for seq_group_metadata, sequence_group_outputs in zip(
  197. seq_group_metadata_list, model_output):
  198. seq_group_metadata.is_prompt = False
  199. for seq_output in sequence_group_outputs.samples:
  200. # NOTE: Beam search is not supported, so we can assume that
  201. # parent_seq_id == seq_id.
  202. seq = seq_group_metadata.seq_data[seq_output.parent_seq_id]
  203. token_id = seq_output.output_token
  204. token_logprob = seq_output.logprobs[token_id]
  205. seq.append_token_id(token_id, token_logprob.logprob)
  206. seq.update_num_computed_tokens(1)
  207. @staticmethod
  208. def _shallow_copy_seq_group_metadata(
  209. seq_group_metadata: SequenceGroupMetadata, ) -> SequenceGroupMetadata:
  210. """Copy input data structures to remove side-effects when input data
  211. structures are shared with other modules.
  212. Helpful when the Aphrodite scheduler runs in the same process as
  213. the worker. The alternative is deep-copying (or other form of deep
  214. copy); this has performance downsides.
  215. """
  216. # Shallow-copy the SequenceGroupMetadata. This allows us to
  217. # append tokens and change is_prompt without external side-effects.
  218. # We must shallow-copy seq_group_metadata as is_prompt could change.
  219. new_seq_group_metadata = copy.copy(seq_group_metadata)
  220. # We must shallow-copy seq_data as we will append token ids
  221. new_seq_data: Dict[int, SequenceData] = {}
  222. for seq_id, old_seq_data in seq_group_metadata.seq_data.items():
  223. new_seq_data[seq_id] = copy.copy(old_seq_data)
  224. new_seq_data[seq_id].output_token_ids =\
  225. old_seq_data.output_token_ids[:]
  226. new_seq_group_metadata.seq_data = new_seq_data
  227. return new_seq_group_metadata
  228. @staticmethod
  229. def _copy_seq_metadata_excluding_last_token(
  230. seq_group_metadata: SequenceGroupMetadata,
  231. seq_ids_to_copy: Set[int],
  232. ) -> SequenceGroupMetadata:
  233. """
  234. Creates a shallow copy of the given SequenceGroupMetadata, retaining
  235. only the sequence IDs specified in seq_ids_to_copy. For each of these
  236. sequence IDs, all output_token_ids except the last one are copied.
  237. Sequence IDs not in seq_ids_to_copy are excluded from the copy.
  238. Parameters:
  239. seq_group_metadata (SequenceGroupMetadata): The original sequence
  240. group metadata.
  241. seq_ids_to_copy (Set[int]): The set of sequence IDs to include in the
  242. copy.
  243. Returns:
  244. SequenceGroupMetadata: A shallow copy of the sequence group metadata
  245. with the specified modifications.
  246. """
  247. # Shallow-copy the SequenceGroupMetadata.
  248. new_seq_group_metadata = copy.copy(seq_group_metadata)
  249. # Shallow-copy seq_data and modify the output_token_ids.
  250. new_seq_data: Dict[int, SequenceData] = {}
  251. for seq_id, old_seq_data in seq_group_metadata.seq_data.items():
  252. if (seq_id in seq_ids_to_copy):
  253. new_seq_data[seq_id] = copy.copy(old_seq_data)
  254. # Copy all the output token ids except the last.
  255. # Also reduce num_computed_tokens by 1 since we are not
  256. # including the last output token.
  257. # NOTE: num_computed_tokens is not directly used by the
  258. # speculative decoding workers, as it is only relevant for
  259. # chunked prefill, which is disabled for speculative decoding.
  260. # However, to maintain consistency in num_computed_tokens,
  261. # we update it here.
  262. new_seq_data[seq_id].output_token_ids =\
  263. old_seq_data.output_token_ids[:-1]
  264. new_seq_data[seq_id].update_num_computed_tokens(-1)
  265. new_seq_group_metadata.seq_data = new_seq_data
  266. return new_seq_group_metadata
  267. def _assert_enough_kv_space(
  268. self, seq_group_metadata_list: List[SequenceGroupMetadata],
  269. num_steps: int) -> None:
  270. """Assert there are enough physical blocks per sequence to store the
  271. current KV plus additional KV from num_steps tokens.
  272. """
  273. assert self.model_runner.block_size is not None
  274. for seq_group_metadata in seq_group_metadata_list:
  275. # Only one seq_id is guaranteed because there is no beam search.
  276. seq_id = list(seq_group_metadata.seq_data.keys())[0]
  277. seq = seq_group_metadata.seq_data[seq_id]
  278. # After num_steps, the seq len will be the current seq len
  279. # plus one token per step.
  280. final_seq_len = seq.get_len() + num_steps
  281. # We will have final_seq_len - 1 KV because Aphrodite saves KV for
  282. # a token in the iteration after the token was generated.
  283. required_num_kv_slots = final_seq_len - 1
  284. # The allocated number of kv slots is the number of allocated blocks
  285. # times the number of slots of block.
  286. number_physical_blocks = len(
  287. seq_group_metadata.block_tables[seq_id])
  288. allocated_kv_slots = (number_physical_blocks *
  289. self.model_runner.block_size)
  290. if required_num_kv_slots > allocated_kv_slots:
  291. request_id = seq_group_metadata.request_id
  292. raise ValueError(
  293. "The worker attempted to run "
  294. f"{num_steps} times but found insufficient KV space for "
  295. f"{request_id=} {seq_id=}. ({allocated_kv_slots=} "
  296. f"{required_num_kv_slots=}).")
  297. def _raise_if_unsupported(
  298. self,
  299. execute_model_req: ExecuteModelRequest,
  300. ) -> None:
  301. """MultiStepWorker does not yet implement support for cache swap
  302. operations or beam search.
  303. """
  304. if any([
  305. execute_model_req.blocks_to_swap_in,
  306. execute_model_req.blocks_to_swap_out,
  307. execute_model_req.blocks_to_copy
  308. ]):
  309. raise NotImplementedError(
  310. "MultiStepWorker does not support cache operations")
  311. if any(
  312. len(seq_group_metadata.seq_data.keys()) != 1
  313. for seq_group_metadata in
  314. execute_model_req.seq_group_metadata_list):
  315. raise NotImplementedError(
  316. "MultiStepWorker does not support beam search.")