logits_processor.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """A layer that compute logits from hidden_stats."""
  2. from typing import Optional
  3. import torch
  4. import torch.nn as nn
  5. from aphrodite.distributed import tensor_model_parallel_gather
  6. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  7. class LogitsProcessor(nn.Module):
  8. """Process logits and apply logits processors from sampling metadata.
  9. This layer does the following:
  10. 1. Gather logits from model hidden_states.
  11. 2. Scale logits if needed.
  12. 3. Apply logits processors (if any).
  13. """
  14. def __init__(self,
  15. vocab_size: int,
  16. org_vocab_size: Optional[int] = None,
  17. scale: Optional[float] = 1.0,
  18. logits_as_input: bool = False) -> None:
  19. """
  20. Args:
  21. scale: A scaling factor to apply to the logits.
  22. """
  23. super().__init__()
  24. self.scale = scale
  25. self.vocab_size = vocab_size
  26. # Whether the input is logits (default is hidden states).
  27. self.logits_as_input = logits_as_input
  28. # original vocabulary size (without LoRA).
  29. self.org_vocab_size = org_vocab_size or vocab_size
  30. def forward(
  31. self,
  32. embedding: torch.Tensor,
  33. hidden_states: torch.Tensor,
  34. sampling_metadata: SamplingMetadata,
  35. embedding_bias: Optional[torch.Tensor] = None,
  36. ) -> torch.Tensor:
  37. if self.logits_as_input:
  38. logits = hidden_states
  39. else:
  40. hidden_states = _prune_hidden_states(hidden_states,
  41. sampling_metadata)
  42. # Get the logits for the next tokens.
  43. logits = self._get_logits(hidden_states, embedding, embedding_bias)
  44. if logits is not None:
  45. logits *= self.scale
  46. # Apply logits processors (if any).
  47. logits = _apply_logits_processors(logits, sampling_metadata)
  48. return logits
  49. def _get_logits(self, hidden_states: torch.Tensor, embedding: torch.Tensor,
  50. embedding_bias: Optional[torch.Tensor]) -> torch.Tensor:
  51. # Get the logits for the next tokens.
  52. logits = torch.matmul(hidden_states, embedding.t())
  53. if embedding_bias is not None:
  54. logits += embedding_bias
  55. logits = tensor_model_parallel_gather(logits)
  56. # Remove paddings in vocab (if any).
  57. if logits is not None:
  58. logits = logits[:, :self.org_vocab_size]
  59. return logits
  60. def _prune_hidden_states(
  61. hidden_states: torch.Tensor,
  62. sampling_metadata: SamplingMetadata,
  63. ) -> torch.Tensor:
  64. return hidden_states.index_select(0,
  65. sampling_metadata.selected_token_indices)
  66. def _apply_logits_processors(
  67. logits: torch.Tensor,
  68. sampling_metadata: SamplingMetadata,
  69. ) -> torch.Tensor:
  70. found_logits_processors = False
  71. logits_processed = 0
  72. for seq_group in sampling_metadata.seq_groups:
  73. seq_ids = seq_group.seq_ids
  74. sampling_params = seq_group.sampling_params
  75. logits_processors = sampling_params.logits_processors
  76. if logits_processors:
  77. found_logits_processors = True
  78. for seq_id, logits_row_idx in zip(seq_ids,
  79. seq_group.sample_indices):
  80. logits_row = logits[logits_row_idx]
  81. token_ids = seq_group.seq_data[seq_id].output_token_ids
  82. for logits_processor in logits_processors:
  83. logits_row = logits_processor(token_ids, logits_row)
  84. logits[logits_row_idx] = logits_row
  85. logits_processed += len(seq_group.sample_indices) + len(
  86. seq_group.prompt_logprob_indices)
  87. if found_logits_processors:
  88. # verifies that no rows in logits were missed unexpectedly
  89. assert logits_processed == logits.shape[0]
  90. return logits