ngram_worker.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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.proposer_worker_base import NonLLMProposerWorkerBase
  7. from aphrodite.spec_decode.top1_proposer import Top1Proposer
  8. class NGramWorker(NonLLMProposerWorkerBase):
  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 sampler_output(
  36. self,
  37. execute_model_req: ExecuteModelRequest,
  38. sample_len: int,
  39. ) -> Tuple[Optional[List[SamplerOutput]], bool]:
  40. """NGram match algo to pick proposal candidate. Returns the list of
  41. sampler output, one per SequenceGroupMetadata.
  42. For ngram worker, we already done needed transposed internal, so the
  43. indicator pass to sampler_output_to_torch shall be False.
  44. """
  45. self._raise_if_unsupported(execute_model_req)
  46. has_spec_out = False
  47. token_id_list = []
  48. token_prob_list = []
  49. for idx, seq_group_metadata in enumerate(
  50. execute_model_req.seq_group_metadata_list):
  51. seq_data = next(iter(seq_group_metadata.seq_data.values()))
  52. input_ids = torch.as_tensor(seq_data.get_token_ids(),
  53. dtype=torch.long,
  54. device=self.device)
  55. input_length = seq_data.get_len()
  56. for ngram_size in range(
  57. min(self.ngram_prompt_lookup_max, input_length - 1),
  58. self.ngram_prompt_lookup_min - 1,
  59. -1,
  60. ):
  61. ngram_tensor = input_ids[-ngram_size:]
  62. if ngram_size == 1:
  63. # Do not match itself and do not use unfold and all
  64. matches = (input_ids[:-1] == ngram_tensor)
  65. else:
  66. windows = input_ids.unfold(dimension=0,
  67. size=ngram_size,
  68. step=1)
  69. # Do not match itself
  70. matches = (windows[:-1] == ngram_tensor).all(dim=-1)
  71. # first_match includes "values" (bool), indicating whether
  72. # the match is found, and "indices", indicating the index
  73. # of the first match.
  74. # Note that "first_match.values.item()" triggers GPU-CPU
  75. # sync so it is a bit inefficient, but we have not found
  76. # a better way to do this.
  77. first_match = matches.max(dim=-1)
  78. if first_match.values.item():
  79. proposal_start_idx = first_match.indices.add_(ngram_size)
  80. spec_indices = (
  81. proposal_start_idx).repeat(sample_len) + torch.arange(
  82. sample_len, device=self.device)
  83. spec_indices.clamp_(max=input_ids.shape[-1] - 1)
  84. res = input_ids.gather(dim=-1, index=spec_indices)
  85. token_id_list.append(res)
  86. token_prob_list.append(
  87. torch.nn.functional.one_hot(
  88. res,
  89. num_classes=self.vocab_size).to(torch.float32))
  90. has_spec_out = True
  91. break
  92. else:
  93. token_id_list.append(None)
  94. token_prob_list.append(None)
  95. if not has_spec_out:
  96. return None, False
  97. outputs: List[Optional[SamplerOutput]] = []
  98. for idx in range(len(execute_model_req.seq_group_metadata_list)):
  99. if token_id_list[idx] is None:
  100. outputs.append(None)
  101. else:
  102. outputs.append(
  103. SamplerOutput(
  104. outputs=None,
  105. sampled_token_probs=token_prob_list[idx],
  106. logprobs=torch.zeros((sample_len, self.vocab_size),
  107. dtype=torch.float32,
  108. device=self.device),
  109. sampled_token_ids=token_id_list[idx],
  110. ))
  111. return outputs, False
  112. def get_spec_proposals(
  113. self,
  114. execute_model_req: ExecuteModelRequest,
  115. ) -> SpeculativeProposals:
  116. """Produce speculations given an input batch of sequences. The number of
  117. speculative tokens per sequence is determined by max_proposal_len.
  118. """
  119. return self._proposer.get_spec_proposals(execute_model_req)
  120. def _raise_if_unsupported(
  121. self,
  122. execute_model_req: ExecuteModelRequest,
  123. ) -> None:
  124. """NGramWorker does not yet implement support for cache swap
  125. operations or beam search.
  126. """
  127. if any([
  128. execute_model_req.blocks_to_swap_in,
  129. execute_model_req.blocks_to_swap_out,
  130. execute_model_req.blocks_to_copy
  131. ]):
  132. raise NotImplementedError(
  133. "NGramWorker does not support cache operations")
  134. if any(
  135. len(seq_group_metadata.seq_data.keys()) != 1
  136. for seq_group_metadata in
  137. execute_model_req.seq_group_metadata_list):
  138. raise NotImplementedError(
  139. "NGramWorker does not support beam search.")