multi_step_worker.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import copy
  2. import weakref
  3. from typing import List, Tuple
  4. import torch
  5. from aphrodite.common.sequence import (ExecuteModelRequest, SamplerOutput,
  6. SequenceGroupMetadata)
  7. from aphrodite.spec_decode.interfaces import SpeculativeProposals
  8. from aphrodite.spec_decode.top1_proposer import Top1Proposer
  9. from aphrodite.task_handler.worker import Worker
  10. class MultiStepWorker(Worker):
  11. """The MultiStepWorker is equivalent to a Worker except that it allows
  12. multiple forward passes in a single call, assuming the scheduler has
  13. allocated enough space to store the additional KV. This reduces overhead
  14. by invoking the scheduler less.
  15. The MultiStepWorker does not support cache swap operations, or beam search.
  16. Cache swap operations do not require large modifications. On the other hand,
  17. beam search requires memory allocations during sequence forks and thus
  18. requires more thought for MultiStepWorker support.
  19. """
  20. def __init__(self, *args, **kwargs):
  21. super().__init__(*args, **kwargs)
  22. # Lazy initialization list.
  23. self._proposer: Top1Proposer
  24. def init_device(self):
  25. super().init_device()
  26. self._proposer = Top1Proposer(
  27. weakref.proxy(self),
  28. self.device,
  29. self.vocab_size,
  30. max_proposal_len=self.max_model_len,
  31. )
  32. def set_include_gpu_probs_tensor(self):
  33. # Need include_gpu_probs_tensor for multi_step_worker
  34. self.model_runner.model.sampler.include_gpu_probs_tensor = True
  35. @torch.inference_mode()
  36. def sampler_output(
  37. self,
  38. execute_model_req: ExecuteModelRequest,
  39. sample_len: int,
  40. ) -> Tuple[List[SamplerOutput], bool]:
  41. """Run the model forward pass sample_len times. Returns the list of
  42. sampler output, one per model forward pass, along with indicator of
  43. whether torch tensor in sampler output need to be transposed in latter
  44. sampler_output_to_torch logic.
  45. For multi step worker, this indicator shall be True.
  46. """
  47. self._raise_if_unsupported(execute_model_req)
  48. # Shallow copy input data so modifications (such as appending tokens)
  49. # do not cause side-effects.
  50. copied_seq_group_metadata_list = self._shallow_copy_inputs(
  51. execute_model_req.seq_group_metadata_list)
  52. copied_execute_model_req = execute_model_req.clone(
  53. copied_seq_group_metadata_list)
  54. # Assert enough KV space for sample_len tokens per sequence.
  55. self._assert_enough_kv_space(execute_model_req.seq_group_metadata_list,
  56. sample_len)
  57. # Run model sample_len times.
  58. model_outputs = []
  59. for _ in range(sample_len):
  60. model_output = super().execute_model(
  61. execute_model_req=copied_execute_model_req)
  62. assert (len(model_output) == 1
  63. ), "composing multistep workers not supported"
  64. model_output = model_output[0]
  65. self._append_new_tokens(model_output,
  66. copied_seq_group_metadata_list)
  67. model_outputs.append(model_output)
  68. return model_outputs, True
  69. def get_spec_proposals(
  70. self,
  71. execute_model_req: ExecuteModelRequest,
  72. ) -> SpeculativeProposals:
  73. """Produce speculations given an input batch of sequences. The number of
  74. speculative tokens per sequence is determined by max_proposal_len.
  75. """
  76. return self._proposer.get_proposals(execute_model_req)
  77. def _append_new_tokens(
  78. self, model_output: SamplerOutput,
  79. seq_group_metadata_list: SequenceGroupMetadata) -> None:
  80. """Given model output from a single run, append the tokens to the
  81. sequences. This is normally done outside of the worker, but it is
  82. required if the worker is to perform multiple forward passes.
  83. """
  84. for seq_group_metadata, sequence_group_outputs in zip(
  85. seq_group_metadata_list, model_output):
  86. seq_group_metadata.is_prompt = False
  87. for seq_output in sequence_group_outputs.samples:
  88. # NOTE: Beam search is not supported, so we can assume that
  89. # parent_seq_id == seq_id.
  90. seq = seq_group_metadata.seq_data[seq_output.parent_seq_id]
  91. token_id = seq_output.output_token
  92. token_logprob = seq_output.logprobs[token_id]
  93. seq.append_token_id(token_id, token_logprob.logprob)
  94. seq.update_num_computed_tokens(1)
  95. def _shallow_copy_inputs(
  96. self, seq_group_metadata_list: List[SequenceGroupMetadata]
  97. ) -> List[SequenceGroupMetadata]:
  98. """Copy input data structures to remove side-effects when input data
  99. structures are shared with other modules.
  100. Helpful when the Aphrodite scheduler runs in the same process as the
  101. worker. The alternative is deep-copying (or other form of deep copy);
  102. this has performance downsides.
  103. """
  104. # Shallow-copy the list of SequenceGroupMetadata. This allows us to
  105. # append tokens and change is_prompt without external side-effects.
  106. new_seq_group_metadata_list = []
  107. for old_seq_group_metadata in seq_group_metadata_list:
  108. # We must shallow-copy seq_group_metadata as is_prompt could change.
  109. seq_group_metadata = copy.copy(old_seq_group_metadata)
  110. new_seq_group_metadata_list.append(seq_group_metadata)
  111. # We must shallow-copy seq_data as we will append token ids
  112. new_seq_data = {}
  113. for seq_id, old_seq_data in seq_group_metadata.seq_data.items():
  114. new_seq_data[seq_id] = copy.copy(old_seq_data)
  115. new_seq_data[
  116. seq_id].output_token_ids = old_seq_data.output_token_ids[:]
  117. seq_group_metadata.seq_data = new_seq_data
  118. return new_seq_group_metadata_list
  119. def _assert_enough_kv_space(
  120. self, seq_group_metadata_list: List[SequenceGroupMetadata],
  121. num_steps: int) -> None:
  122. """Assert there are enough physical blocks per sequence to store the
  123. current KV plus additional KV from num_steps tokens.
  124. """
  125. assert self.model_runner.block_size is not None
  126. for seq_group_metadata in seq_group_metadata_list:
  127. # Only one seq_id is guaranteed because there is no beam search.
  128. seq_id = list(seq_group_metadata.seq_data.keys())[0]
  129. seq = seq_group_metadata.seq_data[seq_id]
  130. # After num_steps, the seq len will be the current seq len
  131. # plus one token per step.
  132. final_seq_len = seq.get_len() + num_steps
  133. # We will have final_seq_len - 1 KV because Aphrodite saves KV for
  134. # a token in the iteration after the token was generated.
  135. required_num_kv_slots = final_seq_len - 1
  136. # The allocated number of kv slots is the number of allocated blocks
  137. # times the number of slots of block.
  138. number_physical_blocks = len(
  139. seq_group_metadata.block_tables[seq_id])
  140. allocated_kv_slots = (number_physical_blocks *
  141. self.model_runner.block_size)
  142. if required_num_kv_slots > allocated_kv_slots:
  143. request_id = seq_group_metadata.request_id
  144. raise ValueError(
  145. "The worker attempted to run "
  146. f"{num_steps} times but found insufficient KV space for "
  147. f"{request_id=} {seq_id=}. ({allocated_kv_slots=} "
  148. f"{required_num_kv_slots=}).")
  149. def _raise_if_unsupported(
  150. self,
  151. execute_model_req: ExecuteModelRequest,
  152. ) -> None:
  153. """MultiStepWorker does not yet implement support for cache swap
  154. operations or beam search.
  155. """
  156. if any([
  157. execute_model_req.blocks_to_swap_in,
  158. execute_model_req.blocks_to_swap_out,
  159. execute_model_req.blocks_to_copy
  160. ]):
  161. raise NotImplementedError(
  162. "MultiStepWorker does not support cache operations")
  163. if any(
  164. len(seq_group_metadata.seq_data.keys()) != 1
  165. for seq_group_metadata in
  166. execute_model_req.seq_group_metadata_list):
  167. raise NotImplementedError(
  168. "MultiStepWorker does not support beam search.")