ngram_worker.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import weakref
  2. from typing import List, Optional, Tuple
  3. import torch
  4. from aphrodite.common.sequence import ExecuteModelRequest, SamplerOutput
  5. from aphrodite.spec_decode.interfaces import SpeculativeProposals
  6. from aphrodite.spec_decode.top1_proposer import Top1Proposer
  7. from aphrodite.task_handler.worker_base import LoraNotSupportedWorkerBase
  8. class NGramWorker(LoraNotSupportedWorkerBase):
  9. """NGramWorker provides a light drafter without need for model.
  10. Current NGramWorker only implement prompt lookup decoding,
  11. and in future we may also do RAG type drafter and other scenerios
  12. which don't rely on LLM model to give proposals.
  13. """
  14. def __init__(self, *args, **kwargs):
  15. # Get local_rank/vocab_size from kwargs attribute
  16. self.local_rank = kwargs["local_rank"]
  17. self.vocab_size = kwargs["model_config"].get_vocab_size()
  18. # Lazy initialization list.
  19. self._proposer: Top1Proposer
  20. def set_ngram_window_size(self, ngram_prompt_lookup_min: int,
  21. ngram_prompt_lookup_max: int):
  22. # Search valid candidate window between
  23. # ngram_prompt_lookup_min/ngram_prompt_lookup_max
  24. self.ngram_prompt_lookup_max = ngram_prompt_lookup_max
  25. self.ngram_prompt_lookup_min = ngram_prompt_lookup_min
  26. def init_device(self):
  27. self.device = torch.device(f"cuda:{self.local_rank}")
  28. self.load_model = lambda *args, **kwargs: None
  29. # Current only support Top1Proposer
  30. self._proposer = Top1Proposer(
  31. weakref.proxy(self),
  32. device=self.device,
  33. vocab_size=self.vocab_size,
  34. )
  35. def set_include_gpu_probs_tensor(self):
  36. # NGram don't need gpu sampler
  37. pass
  38. def execute_model(
  39. self,
  40. execute_model_req: Optional[ExecuteModelRequest] = None) -> None:
  41. """NGram doesn't depend on model execution, just pass this function"""
  42. pass
  43. def determine_num_available_blocks(self) -> None:
  44. """NGram doesn't depend on model execution, no need to check blocks"""
  45. pass
  46. def initialize_cache(self, num_gpu_blocks: int,
  47. num_cpu_blocks: int) -> None:
  48. """As there is no cache need to handle, just pass this function"""
  49. pass
  50. def get_cache_block_size_bytes(self):
  51. """Return the size of a cache block in bytes."""
  52. return 0
  53. def sampler_output(
  54. self,
  55. execute_model_req: ExecuteModelRequest,
  56. sample_len: int,
  57. ) -> Tuple[Optional[List[SamplerOutput]], bool]:
  58. """NGram match algo to pick proposal candidate. Returns the list of
  59. sampler output, one per SequenceGroupMetadata.
  60. For ngram worker, we already done needed transposed internal, so the
  61. indicator pass to sampler_output_to_torch shall be False.
  62. """
  63. self._raise_if_unsupported(execute_model_req)
  64. has_spec_out = False
  65. token_id_list = []
  66. token_prob_list = []
  67. for idx, seq_group_metadata in enumerate(
  68. execute_model_req.seq_group_metadata_list):
  69. seq_data = next(iter(seq_group_metadata.seq_data.values()))
  70. input_ids = torch.as_tensor(seq_data.get_token_ids(),
  71. dtype=torch.long,
  72. device=self.device)
  73. input_length = seq_data.get_len()
  74. for ngram_size in range(
  75. min(self.ngram_prompt_lookup_max, input_length - 1),
  76. self.ngram_prompt_lookup_min - 1,
  77. -1,
  78. ):
  79. ngram_tensor = input_ids[-ngram_size:]
  80. proposal_start_idx = None
  81. if ngram_size == 1:
  82. # Do not match itself and do not use unfold and all
  83. matches = (input_ids[:-1] == ngram_tensor)
  84. else:
  85. windows = input_ids.unfold(dimension=0,
  86. size=ngram_size,
  87. step=1)
  88. # Do not match itself
  89. matches = (windows[:-1] == ngram_tensor).all(dim=-1)
  90. # first_match includes "values" (bool), indicating whether
  91. # the match is found, and "indices", indicating the index
  92. # of the first match.
  93. # Note that "first_match.values.item()" triggers GPU-CPU
  94. # sync so it is a bit inefficient, but we have not found
  95. # a better way to do this.
  96. first_match = matches.max(dim=-1)
  97. if first_match.values.item():
  98. proposal_start_idx = first_match.indices.add_(ngram_size)
  99. spec_indices = (
  100. proposal_start_idx).repeat(sample_len) + torch.arange(
  101. sample_len, device=self.device)
  102. spec_indices.clamp_(max=input_ids.shape[-1] - 1)
  103. res = input_ids.gather(dim=-1, index=spec_indices)
  104. token_id_list.append(res)
  105. token_prob_list.append(
  106. torch.nn.functional.one_hot(
  107. res,
  108. num_classes=self.vocab_size).to(torch.float32))
  109. has_spec_out = True
  110. break
  111. else:
  112. token_id_list.append(None)
  113. token_prob_list.append(None)
  114. if not has_spec_out:
  115. return None, False
  116. outputs: List[Optional[SamplerOutput]] = []
  117. for idx in range(len(execute_model_req.seq_group_metadata_list)):
  118. if token_id_list[idx] is None:
  119. outputs.append(None)
  120. else:
  121. outputs.append(
  122. SamplerOutput(
  123. outputs=None,
  124. sampled_token_probs=token_prob_list[idx],
  125. logprobs=torch.zeros((sample_len, self.vocab_size),
  126. dtype=torch.float32,
  127. device=self.device),
  128. sampled_token_ids=token_id_list[idx],
  129. ))
  130. return outputs, False
  131. def get_spec_proposals(
  132. self,
  133. execute_model_req: ExecuteModelRequest,
  134. ) -> SpeculativeProposals:
  135. """Produce speculations given an input batch of sequences. The number of
  136. speculative tokens per sequence is determined by max_proposal_len.
  137. """
  138. return self._proposer.get_proposals(execute_model_req)
  139. def _raise_if_unsupported(
  140. self,
  141. execute_model_req: ExecuteModelRequest,
  142. ) -> None:
  143. """NGramWorker does not yet implement support for cache swap
  144. operations or beam search.
  145. """
  146. if any([
  147. execute_model_req.blocks_to_swap_in,
  148. execute_model_req.blocks_to_swap_out,
  149. execute_model_req.blocks_to_copy
  150. ]):
  151. raise NotImplementedError(
  152. "NGramWorker does not support cache operations")
  153. if any(
  154. len(seq_group_metadata.seq_data.keys()) != 1
  155. for seq_group_metadata in
  156. execute_model_req.seq_group_metadata_list):
  157. raise NotImplementedError(
  158. "NGramWorker does not support beam search.")