util.py 8.3 KB

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