|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +"""Sampler layer implementing TPU supported operations.""" |
| 3 | + |
| 4 | +import torch |
| 5 | +import torch.nn as nn |
| 6 | + |
| 7 | +from vllm.v1.outputs import LogprobsTensors, SamplerOutput |
| 8 | +from vllm.v1.sample.ops.topk_topp_sampler import TopKTopPSampler |
| 9 | +from vllm.v1.sample.tpu.metadata import TPUSupportedSamplingMetadata |
| 10 | + |
| 11 | +_SAMPLING_EPS = 1e-5 |
| 12 | + |
| 13 | + |
| 14 | +class Sampler(nn.Module): |
| 15 | + |
| 16 | + def __init__(self): |
| 17 | + super().__init__() |
| 18 | + self.topk_topp_sampler = TopKTopPSampler() |
| 19 | + |
| 20 | + def forward( |
| 21 | + self, |
| 22 | + logits: torch.Tensor, |
| 23 | + sampling_metadata: TPUSupportedSamplingMetadata, |
| 24 | + ) -> SamplerOutput: |
| 25 | + # NOTE(woosuk): Use the original logits (before any penalties or |
| 26 | + # temperature scaling) for the top-k logprobs. |
| 27 | + # This is different from the V0 sampler, which uses the logits that |
| 28 | + # is used for sampling (after penalties and temperature scaling). |
| 29 | + |
| 30 | + # Use float32 for the logits. |
| 31 | + logits = logits.to(torch.float32) |
| 32 | + # Sample the next token. |
| 33 | + sampled = self.sample(logits, sampling_metadata) |
| 34 | + |
| 35 | + # Use int32 to reduce the tensor size. |
| 36 | + sampled = sampled.to(torch.int32) |
| 37 | + |
| 38 | + # These are GPU tensors. |
| 39 | + sampler_output = SamplerOutput( |
| 40 | + # The sampled tokens are expanded to 2D tensor with shape |
| 41 | + # [num_requests, 1], where each row represents one generated |
| 42 | + # token per request. |
| 43 | + sampled_token_ids=sampled.unsqueeze(-1), |
| 44 | + logprobs_tensors=None, |
| 45 | + ) |
| 46 | + return sampler_output |
| 47 | + |
| 48 | + def apply_temperature( |
| 49 | + self, |
| 50 | + logits: torch.Tensor, |
| 51 | + temp: torch.Tensor, |
| 52 | + ) -> torch.Tensor: |
| 53 | + # Use in-place division to avoid creating a new tensor. |
| 54 | + return logits.div_(temp.unsqueeze(dim=1)) |
| 55 | + |
| 56 | + def greedy_sample(self, logits: torch.Tensor) -> torch.Tensor: |
| 57 | + return logits.argmax(dim=-1).view(-1) |
| 58 | + |
| 59 | + def sample( |
| 60 | + self, |
| 61 | + logits: torch.Tensor, |
| 62 | + sampling_metadata: TPUSupportedSamplingMetadata, |
| 63 | + ) -> torch.Tensor: |
| 64 | + greedy_sampled = self.greedy_sample(logits) |
| 65 | + |
| 66 | + assert sampling_metadata.temperature is not None |
| 67 | + |
| 68 | + # Apply temperature. |
| 69 | + logits = self.apply_temperature(logits, sampling_metadata.temperature) |
| 70 | + |
| 71 | + # Apply min_p. |
| 72 | + if sampling_metadata.min_p is not None: |
| 73 | + logits = self.apply_min_p(logits, sampling_metadata.min_p) |
| 74 | + |
| 75 | + # Apply top_k and/or top_p. |
| 76 | + random_sampled = self.topk_topp_sampler( |
| 77 | + logits, |
| 78 | + sampling_metadata.generators, |
| 79 | + sampling_metadata.top_k, |
| 80 | + sampling_metadata.top_p, |
| 81 | + ) |
| 82 | + |
| 83 | + sampled = torch.where(sampling_metadata.temperature < _SAMPLING_EPS, |
| 84 | + greedy_sampled, random_sampled) |
| 85 | + return sampled |
| 86 | + |
| 87 | + def compute_logprobs(self, logits: torch.Tensor) -> torch.Tensor: |
| 88 | + return logits.log_softmax(dim=-1, dtype=torch.float32) |
| 89 | + |
| 90 | + def gather_logprobs( |
| 91 | + self, |
| 92 | + logprobs: torch.Tensor, |
| 93 | + num_logprobs: int, |
| 94 | + token_ids: torch.Tensor, |
| 95 | + ) -> LogprobsTensors: |
| 96 | + """ |
| 97 | + Gather logprobs for topk and sampled/prompt token. |
| 98 | +
|
| 99 | + Args: |
| 100 | + logits: (num tokens) x (vocab) tensor |
| 101 | + num_logprobs: minimum number of logprobs to |
| 102 | + retain per token |
| 103 | + token_ids: prompt tokens (if prompt logprobs) |
| 104 | + or sampled tokens (if sampled |
| 105 | + logprobs); 1D token ID tensor |
| 106 | + with (num tokens) elements |
| 107 | +
|
| 108 | + Returns: |
| 109 | + Top-k int indices tensor, (num tokens) x (num_logprobs + 1) |
| 110 | + Top-k float logprobs tensor, (num tokens) x (num_logprobs + 1) |
| 111 | + Sampled token rank tensor, (num tokens) |
| 112 | + """ |
| 113 | + # Find the topK values. |
| 114 | + topk_logprobs, topk_indices = torch.topk(logprobs, |
| 115 | + num_logprobs, |
| 116 | + dim=-1) |
| 117 | + |
| 118 | + # Get with the logprob of the prompt or sampled token. |
| 119 | + token_ids = token_ids.unsqueeze(-1) |
| 120 | + token_logprobs = logprobs.gather(-1, token_ids) |
| 121 | + |
| 122 | + # Compute the ranks of the actual token. |
| 123 | + token_ranks = (logprobs >= token_logprobs).sum(-1) |
| 124 | + |
| 125 | + # Concatenate together with the topk. |
| 126 | + indices = torch.cat((token_ids, topk_indices), dim=1) |
| 127 | + logprobs = torch.cat((token_logprobs, topk_logprobs), dim=1) |
| 128 | + |
| 129 | + # Use int32 to reduce the tensor size. |
| 130 | + indices = indices.to(torch.int32) |
| 131 | + |
| 132 | + return LogprobsTensors(indices, logprobs, token_ranks) |
| 133 | + |
| 134 | + def apply_min_p( |
| 135 | + self, |
| 136 | + logits: torch.Tensor, |
| 137 | + min_p: torch.Tensor, |
| 138 | + ) -> torch.Tensor: |
| 139 | + """ |
| 140 | + Filters logits using adaptive probability thresholding. |
| 141 | + """ |
| 142 | + # Convert logits to probability distribution |
| 143 | + probability_values = torch.nn.functional.softmax(logits, dim=-1) |
| 144 | + # Calculate maximum probabilities per sequence |
| 145 | + max_probabilities = torch.amax(probability_values, |
| 146 | + dim=-1, |
| 147 | + keepdim=True) |
| 148 | + # Reshape min_p for broadcasting |
| 149 | + adjusted_min_p = min_p.unsqueeze(1) * max_probabilities |
| 150 | + # Identify valid tokens using threshold comparison |
| 151 | + valid_token_mask = probability_values >= adjusted_min_p |
| 152 | + # Apply mask using boolean indexing (xla friendly) |
| 153 | + logits.masked_fill_(~valid_token_mask, -float("inf")) |
| 154 | + return logits |
0 commit comments