util.py 7.4 KB

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