util.py 7.7 KB

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