util.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. from contextlib import contextmanager
  2. from itertools import chain
  3. from typing import Dict, List, Tuple
  4. import torch
  5. from aphrodite.common.sequence import (CompletionSequenceGroupOutput, Logprob,
  6. SamplerOutput, SequenceGroupMetadata,
  7. SequenceGroupOutput, SequenceOutput)
  8. SeqId = int
  9. def get_all_seq_ids(
  10. seq_group_metadata_list: List[SequenceGroupMetadata]) -> List[SeqId]:
  11. """Given a list of SequenceGroupMetadata, create a list of all
  12. sequence ids.
  13. """
  14. return list(
  15. chain.from_iterable([
  16. seq_group_metadata.seq_data.keys()
  17. for seq_group_metadata in seq_group_metadata_list
  18. ]))
  19. def get_all_num_logprobs(
  20. seq_group_metadata_list: List[SequenceGroupMetadata]) -> List[int]:
  21. """Given a list of SequenceGroupMetadata, create a list of all num_logprobs.
  22. If the sampling params do not call for any logprobs, return 0 for that
  23. sequence.
  24. """
  25. all_num_logprobs = []
  26. for seq_group_metadata in seq_group_metadata_list:
  27. num_logprobs = seq_group_metadata.sampling_params.logprobs
  28. if seq_group_metadata.sampling_params.logprobs is None:
  29. num_logprobs = 0
  30. all_num_logprobs.append(num_logprobs)
  31. return all_num_logprobs
  32. def get_sampled_token_logprobs(
  33. # shape [num_steps, batch_size, vocab_size]
  34. logprob_tensor: torch.Tensor,
  35. sampled_token_ids: torch.Tensor, # shape [num_steps, batch_size]
  36. ) -> Tuple[torch.Tensor, torch.Tensor]:
  37. """Get the logprobs for the sampled tokens. Returns the ranks and logprobs.
  38. """
  39. num_steps, batch_size, vocab_size = logprob_tensor.shape
  40. selected_logprobs = logprob_tensor[torch.arange(num_steps).unsqueeze(1),
  41. torch.arange(batch_size),
  42. sampled_token_ids, ]
  43. expanded_selected_logprobs = selected_logprobs.unsqueeze(-1).expand(
  44. -1, -1, vocab_size)
  45. sampled_token_ids_ranks = (logprob_tensor >=
  46. expanded_selected_logprobs).sum(-1)
  47. return sampled_token_ids_ranks, selected_logprobs
  48. def create_sequence_group_output(
  49. token_id: int,
  50. token_id_logprob_rank: int,
  51. token_id_logprob: float,
  52. seq_id: SeqId,
  53. topk_token_ids: List[int],
  54. topk_logprobs: List[float],
  55. ) -> SequenceGroupOutput:
  56. """Create a SequenceGroupOutput given the sampling results.
  57. Args:
  58. token_id (int): The sampled token for the sequence.
  59. token_id_logprob_rank (int): The logprob rank of the sampled token.
  60. token_id_logprob (float): The logprob value of the sampled token.
  61. seq_id (int): The sequence id.
  62. topk_token_ids (List[int]): The list of top-k token ids.
  63. topk_logprobs (List[float]): The list of top-k logprobs.
  64. """
  65. # Aphrodite logprobs always include the sampled token. In addition, the
  66. # user may request topk-logprobs (where top-k varies per user up to
  67. # max_logprobs).
  68. logprobs: Dict[int, Logprob] = {
  69. token_id: Logprob(
  70. logprob=token_id_logprob,
  71. rank=token_id_logprob_rank,
  72. ),
  73. }
  74. logprobs.update({
  75. topk_token_ids[topk_logprob_index]: Logprob(
  76. logprob=topk_logprobs[topk_logprob_index],
  77. rank=topk_logprob_index + 1,
  78. )
  79. for topk_logprob_index, _ in enumerate(topk_token_ids)
  80. })
  81. return CompletionSequenceGroupOutput(
  82. samples=[
  83. SequenceOutput(parent_seq_id=seq_id,
  84. output_token=token_id,
  85. logprobs=logprobs)
  86. ],
  87. # TODO add prompt logprobs support.
  88. prompt_logprobs=None,
  89. )
  90. def split_batch_by_proposal_len(
  91. seq_group_metadata_list: List[SequenceGroupMetadata],
  92. proposal_lens: List[int], select_proposal_len_zero: bool
  93. ) -> Tuple[List[SequenceGroupMetadata], List[int]]:
  94. """Utility function that splits a batch based on whether the proposal len is
  95. zero or not. We should remove this once Aphrodite supports per-sequence
  96. proposal lens in a batch.
  97. """
  98. if select_proposal_len_zero:
  99. predicate = lambda proposal_len: proposal_len == 0
  100. else:
  101. predicate = lambda proposal_len: proposal_len != 0
  102. indices = [
  103. i for i, (_, proposal_len
  104. ) in enumerate(zip(seq_group_metadata_list, proposal_lens))
  105. if predicate(proposal_len)
  106. ]
  107. seq_groups = [
  108. seq_group for seq_group, proposal_len in zip(
  109. seq_group_metadata_list, proposal_lens) if predicate(proposal_len)
  110. ]
  111. return seq_groups, indices
  112. def sampler_output_to_torch(
  113. sampler_output_list: List[SamplerOutput], sampler_transposed: bool
  114. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  115. """Utility function which converts a list of SamplerOutput to tensors.
  116. sampler_transposed here is used as the indicator for whether
  117. we need do additional tensor transpose logic here.
  118. Returns:
  119. sampled_token_ids: torch.Tensor
  120. shape: [batch_size, len(sampler_output_list)]
  121. sampled_token_probs: torch.Tensor
  122. shape: [batch_size, len(sampler_output_list), vocab_size]
  123. """
  124. # shape: [batch_size, num_sampler_output, vocab_size]
  125. sampled_token_probs = torch.stack(
  126. [
  127. sampler_output.sampled_token_probs
  128. for sampler_output in sampler_output_list
  129. ],
  130. dim=0,
  131. )
  132. if sampler_transposed:
  133. sampled_token_probs = sampled_token_probs.transpose(0, 1)
  134. # shape: [batch_size, num_sampler_output, vocab_size]
  135. sampled_token_logprobs = torch.stack(
  136. [sampler_output.logprobs for sampler_output in sampler_output_list],
  137. dim=0,
  138. )
  139. if sampler_transposed:
  140. sampled_token_logprobs = sampled_token_logprobs.transpose(0, 1)
  141. # shape: [batch_size, num_sampler_output]
  142. sampled_token_ids = torch.stack(
  143. [
  144. sampler_output.sampled_token_ids.flatten()
  145. for sampler_output in sampler_output_list
  146. ],
  147. dim=0,
  148. )
  149. if sampler_transposed:
  150. sampled_token_ids = sampled_token_ids.transpose(0, 1)
  151. return sampled_token_ids, sampled_token_probs, sampled_token_logprobs
  152. def maybe_mock_device_tensors(sampler_output: SamplerOutput, batch_size: int,
  153. vocab_size: int, device: str) -> None:
  154. """Helper method which mocks out the GPU tensors in SamplerOutput with dummy
  155. values.
  156. """
  157. values = [
  158. sampler_output.sampled_token_probs, sampler_output.sampled_token_ids
  159. ]
  160. assert all(v is None for v in values) or not any(v is None for v in values)
  161. if not any(v is None for v in values):
  162. # Do nothing if the tensors are already created (usually in unit tests).
  163. return
  164. # Softmax to ensure valid probs.
  165. sampler_output.sampled_token_probs = torch.nn.functional.softmax(
  166. torch.rand(batch_size, vocab_size, dtype=torch.float32, device=device),
  167. dim=-1)
  168. sampler_output.sampled_token_ids = torch.randint(low=10,
  169. high=100,
  170. size=(batch_size, ),
  171. dtype=torch.long,
  172. device=device)
  173. @contextmanager
  174. def nvtx_range(msg, *args, **kwargs):
  175. """
  176. Context manager / decorator that pushes an NVTX range at the beginning
  177. of its scope, and pops it at the end. If extra arguments are given,
  178. they are passed as arguments to msg.format().
  179. If running with cuda graphs, you must enable nsys cuda graph profiling.
  180. Arguments:
  181. msg (string): message to associate with the range
  182. """
  183. torch.cuda.nvtx.range_push(msg.format(*args, **kwargs))
  184. try:
  185. yield
  186. finally:
  187. torch.cuda.nvtx.range_pop()