multi_step_worker.py 16 KB

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