vllm.model_executor.layers.sampler
A layer that samples the next tokens from the model's outputs.
MaybeDeferredSampleResultType
module-attribute
¶
MaybeDeferredSampleResultType = Union[
SampleResultType, SampleResultArgsType
]
SampleMetadataType
module-attribute
¶
SampleMetadataType = dict[
SamplingType,
tuple[list[int], list[SequenceGroupToSample]],
]
SampleResultsDictType
module-attribute
¶
SampleReturnType
module-attribute
¶
SampleReturnType = tuple[
MaybeDeferredSampleResultType, Optional[Tensor]
]
SampleResultArgsType
dataclass
¶
Source code in vllm/model_executor/layers/sampler.py
__init__
¶
__init__(
sample_metadata: SampleMetadataType,
multinomial_samples: MultinomialSamplesType,
sample_results_dict: SampleResultsDictType,
sampling_metadata: SamplingMetadata,
greedy_samples: Optional[Tensor],
) -> None
Sampler
¶
Bases: Module
Samples the next tokens from the model's outputs.
This layer does the following: 1. Discard the hidden states that are not used for sampling (i.e., all tokens except the final one in each prompt). 2. Compute the logits for the next tokens. 3. Apply presence, frequency and repetition penalties. 4. Apply temperature scaling. 5. Apply top-p and top-k truncation. 6. Sample the next tokens. Here, each sequence group within the batch can have different sampling parameters (e.g., sampling method, temperature, top-p, top-k, etc.).
The structure of the logits tensor is coupled with the seq_groups in sampling_metadata. Typically, each sequence in each seq_group has one row in logits for the next token to be sampled; however, for a seq_group with a prompt request with the prompt_logprobs sampling parameter, there are rows in logits for each token in the input prompt.
Source code in vllm/model_executor/layers/sampler.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
|
_should_modify_greedy_probs_inplace
property
¶
_should_modify_greedy_probs_inplace: bool
Whether or not the sampler should modify the probability distribution of greedily-sampled tokens such that multinomial sampling would sample the greedily-sampled token.
In other words, if True then we set the probability of the greedily- sampled token to 1.
This is used by speculative decoding, which requires that the sampling method be encoded into the probability distribution.
__init__
¶
Source code in vllm/model_executor/layers/sampler.py
_init_sampling_tensors
¶
_init_sampling_tensors(
logits: Tensor, sampling_metadata: SamplingMetadata
)
The goal here is to reuse sampling tensors between similar decode runs. This is possible because sampling logic does not change between decodes of the same sequences.
Source code in vllm/model_executor/layers/sampler.py
forward
¶
forward(
logits: Tensor, sampling_metadata: SamplingMetadata
) -> Optional[SamplerOutput]
Single-step scheduling
- Perform GPU-side sampling computation & compute GPU-side logprobs tensor
- Pythonize sampling result & logprobs tensor
Multi-step scheduling
- Perform GPU-side sampling computation & compute GPU-side logprobs tensor
- Defer Pythonization of sampling result & logprobs tensor
- Encapsulate arguments required for deferred Pythonization
in the
SamplerOutput
structure
Parameters:
Name | Type | Description | Default |
---|---|---|---|
logits
|
Tensor
|
(num_tokens, vocab_size). |
required |
sampling_metadata
|
SamplingMetadata
|
Metadata for sampling. |
required |
Source code in vllm/model_executor/layers/sampler.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
|
SamplerOutput
¶
Bases: Struct
For each sequence group, we generate a list of SequenceOutput object, each of which contains one possible candidate for the next token.
This data structure implements methods, so it can be used like a list, but also has optional fields for device tensors.
Source code in vllm/model_executor/layers/sampler.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
|
deferred_sample_results_args
class-attribute
instance-attribute
¶
deferred_sample_results_args: Optional[
SampleResultArgsType
] = None
prefill_hidden_states
class-attribute
instance-attribute
¶
sampled_token_embeds
class-attribute
instance-attribute
¶
sampled_token_ids_cpu
class-attribute
instance-attribute
¶
sampled_token_probs
class-attribute
instance-attribute
¶
spec_decode_worker_metrics
class-attribute
instance-attribute
¶
spec_decode_worker_metrics: Optional[
SpecDecodeWorkerMetrics
] = None
__getitem__
¶
__getitem__(idx: int) -> CompletionSequenceGroupOutput
__iter__
¶
__iter__() -> Iterator[CompletionSequenceGroupOutput]
__len__
¶
__repr__
¶
__repr__() -> str
Show the shape of a tensor instead of its values to reduce noise.
Source code in vllm/model_executor/layers/sampler.py
_apply_min_p
¶
Adapted from https://github.com/oobabooga/text-generation-webui/blob/3146124ec01f02c8fb1650a6517cf1b60b537aaf/modules/sampler_hijack.py#L16C17-L16C17
Source code in vllm/model_executor/layers/sampler.py
_apply_min_tokens_penalty
¶
_apply_min_tokens_penalty(
logits: Tensor, sampling_metadata: SamplingMetadata
) -> Tensor
Apply min_tokens penalty which sets stop tokens to -inf if min_tokens have not been generated yet
Source code in vllm/model_executor/layers/sampler.py
_apply_top_k_top_p
¶
Source code in vllm/model_executor/layers/sampler.py
_build_sampler_output
¶
_build_sampler_output(
maybe_deferred_sample_results: MaybeDeferredSampleResultType,
sampling_metadata: SamplingMetadata,
prompt_logprobs: Optional[
list[Optional[PromptLogprobs]]
],
sample_logprobs: Optional[list[SampleLogprobs]],
on_device_tensors: Optional[
tuple[Tensor, Tensor, Tensor]
],
skip_sampler_cpu_output: bool = False,
) -> SamplerOutput
Construct Python objects with the output of sampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
on_device_tensors
|
Optional[tuple[Tensor, Tensor, Tensor]]
|
Tuple containing on-device tensors with the probabilities used in sampling and the sampled token ids. This allows post-processing without copies to CPU/serialization, e.g. in speculative decoding rejection sampling. |
required |
Source code in vllm/model_executor/layers/sampler.py
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 |
|
_get_next_prompt_tokens
¶
_get_next_prompt_tokens(
seq_group: SequenceGroupToSample,
) -> tuple[int, ...]
Get a list of next prompt tokens to compute logprob from a given sequence group.
It is used to compute prompt logprob. Imagine you have logprob for each query token. Query token needs to know the next prompt token id to compute prompt logprob. This is a helper to obtain next prompt token ids.
This API has to be used only when the caller knows seq_group is in prefill stage.
Returns:
Type | Description |
---|---|
tuple[int, ...]
|
A list of next prompt tokens to compute logprob. |
Source code in vllm/model_executor/layers/sampler.py
_get_prompt_logprob_if_needed
¶
_get_prompt_logprob_if_needed(
seq_group: SequenceGroupToSample,
selected_logprobs: Tensor,
ranks: Tensor,
top_token_ids: Tensor,
top_logprobs: Tensor,
selected_logprobs_idx: int,
top_logprob_idx: int,
)
Compute the prompt logprob from a sequence group if needed.
Source code in vllm/model_executor/layers/sampler.py
_get_ranks
¶
This function calculates the ranks of the chosen tokens in a logprob tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
2D logprob tensor of shape (N, M) where N is the no. of tokens and M is the vocab dim. |
required |
indices
|
Tensor
|
List of chosen token indices. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: 1D tensor of shape (N,) where N is the no. of tokens. Each element in the returned tensor represents the rank of the chosen token in the input logprob tensor. |
Source code in vllm/model_executor/layers/sampler.py
_get_sampled_logprob_if_needed
¶
_get_sampled_logprob_if_needed(
seq_group: SequenceGroupToSample,
sample_result: tuple[list[int], list[int]],
selected_logprobs: Tensor,
ranks: Tensor,
top_token_ids: Tensor,
top_logprobs: Tensor,
selected_logprobs_idx: int,
top_logprob_idx: int,
)
Compute the sample logprob if needed.
Source code in vllm/model_executor/layers/sampler.py
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 |
|
_greedy_sample
¶
_greedy_sample(
selected_seq_groups: list[SequenceGroupToSample],
samples: Tensor,
) -> SampleResultType
Run greedy sampling on a given samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
selected_seq_groups
|
list[SequenceGroupToSample]
|
A list of sequence groups batched. |
required |
samples
|
Tensor
|
(num_selected_samples,) A tensor of samples. The length of samples could be smaller than selected_seq_groups if seq_group.do_sample is False. |
required |
Returns: Tuple of (next_token_ids, parent_ids). The length of returned list is same as the length of selected_seq_groups. If the corresponding seq_group has do_sample=False, tuple contains ([], [])
Source code in vllm/model_executor/layers/sampler.py
_modify_greedy_probs_inplace
¶
_modify_greedy_probs_inplace(
logprobs: Tensor,
probs: Tensor,
sample_indices: Tensor,
greedy_samples: Tensor,
) -> None
Modify the probability distributions of the greedily-sampled tokens such that each sampled token has a "probability" of 1.0. This is required by speculative decoding, which depends on the sampling method being encoded within the probability distribution for correctness.
Why do we only need to do this for greedy sampling?¶
vLLM's sampler performs the following steps for greedy or multinomial
(random) sampling:
1. Get logits from model.
2. Modify logits according to per-sequence sampling parameters.
- Multiply by temperature, top-k and top-p masking, penalize tokens
according to their frequency, etc.
3. Sample a token.
- Random sampling simply samples from the modified probability
distribution.
- Greedy sampling performs argmax
to obtain the token with the
highest likelihood.
Ignoring greedy sampling for a moment, we find that the computed probability distribution has the following property: we can sample from it independently and find that the token sampled by the Sampler has a frequency corresponding to how often we see it in our sampling. In other words, for tokens sampled with vLLM's random SamplingType, the computed probability distribution encodes the sampling methodology completely.
Greedy sampling does not normally have this property. vLLM modifies logits
according to sampling params, then performs argmax
, then returns the
sampled token and the computed probability distribution. If we sample from
the distribution, we'll find the likelihood of the greedily-sampled token
is not always 1.0.
Since lossless speculative decoding requires that the sampling methodology be encoded within the probability distribution, we are motivated to modify the probability distribution such that the sampled token has probability 1 when speculative decoding is used.
NOTE: Alternatively, we could use an extremely low temperature to achieve greedy sampling using multinomial computation and unite the codepaths. This has implications on the overall design of the sampler, e.g. how to record accurate logprobs for the user, so this improvement is deferred to later.
Source code in vllm/model_executor/layers/sampler.py
_multinomial
¶
_multinomial(
probs: Tensor,
num_samples: int,
seq_groups: Optional[
list[SequenceGroupToSample]
] = None,
) -> Tensor
Source code in vllm/model_executor/layers/sampler.py
_random_sample
¶
_random_sample(
selected_seq_groups: list[SequenceGroupToSample],
random_samples: Tensor,
) -> SampleResultType
Run random sampling on a given samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
selected_seq_groups
|
list[SequenceGroupToSample]
|
A list of sequence groups batched. |
required |
random_samples
|
Tensor
|
(num_selected_samples,) A tensor of samples. The length of samples could be smaller than selected_seq_groups if seq_group.do_sample is False. |
required |
Returns: Tuple of (next_token_ids, parent_ids). The length of returned list is same as the length of selected_seq_groups. If the corresponding seq_group has do_sample=False, tuple contains ([], [])
Source code in vllm/model_executor/layers/sampler.py
_sample
¶
_sample(
probs: Tensor,
logprobs: Tensor,
sampling_metadata: SamplingMetadata,
sampling_tensors: SamplingTensors,
include_gpu_probs_tensor: bool,
modify_greedy_probs: bool,
) -> SampleReturnType
Parameters:
Name | Type | Description | Default |
---|---|---|---|
probs
|
Tensor
|
(num_query_tokens_in_batch, num_vocab) |
required |
logprobs
|
Tensor
|
(num_query_tokens_in_batch, num_vocab) |
required |
sampling_metadata
|
SamplingMetadata
|
The metadata for a batch for sampling. |
required |
sampling_tensors
|
SamplingTensors
|
Tensors that include sampling related metadata. |
required |
Returns:
Name | Type | Description |
---|---|---|
SampleReturnType
|
(next_token_ids, parent_seq_ids) for each seq group in a batch. If sampling is skipped, it returns ([], []) |
|
sampled_token_ids_tensor |
SampleReturnType
|
A tensor of sampled token ids. |
Source code in vllm/model_executor/layers/sampler.py
_sample_with_torch
¶
_sample_with_torch(
probs: Tensor,
logprobs: Tensor,
sampling_metadata: SamplingMetadata,
sampling_tensors: SamplingTensors,
include_gpu_probs_tensor: bool,
modify_greedy_probs: bool,
) -> SampleReturnType
Torch-oriented _sample() implementation.
Single-step scheduling: * Perform GPU-side sampling computation * Immediately Pythonize sampling result
Multi-step scheduling: * Perform GPU-side sampling computation * Defer Pythonization & preserve GPU-side tensors required for Pythonization
Source code in vllm/model_executor/layers/sampler.py
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 |
|
_top_k_top_p_multinomial_with_flashinfer
¶
_top_k_top_p_multinomial_with_flashinfer(
probs: Tensor,
top_ks: Tensor,
top_ps: Tensor,
num_samples: int,
seq_groups: Optional[list[SequenceGroupToSample]],
)
Source code in vllm/model_executor/layers/sampler.py
get_logprobs
¶
get_logprobs(
logprobs: Tensor,
sampling_metadata: SamplingMetadata,
sample_results: SampleResultType,
) -> tuple[
list[Optional[PromptLogprobs]], list[SampleLogprobs]
]
Return sample logprobs and prompt logprobs.
The logic consists of 3 parts. - Select indices to compute logprob from, ranks of token ids, and the top k token ids from logprobs. - Compute prompt logprobs if required. - Compute sample logprobs if required.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
logprobs
|
Tensor
|
(num_query_tokens_across_batch, num_vocab). Each query token's logprob per vocab. Sequence groups' query tokens are batched in a single flattened tensor. For example, assuming there are N seq groups, it is sorted by prefill tokens for seq_group_1 (if prompt logprob is enabled), decode tokens for seq_group_1 (if sampling is required), prefill tokens for seq_group_2, ... |
required |
sampling_metadata
|
SamplingMetadata
|
The sampling metadata. |
required |
sample_results
|
SampleResultType
|
(num_seq_groups) The tuple of (next_token_ids, parent_ids) for each sequence group. When beam search is enabled, sample_results can contain different number of seq_ids from sampling_metadata.seq_groups. It is because beam search creates 2 * BEAM_WIDTH number of samples (whereas there are only up to BEAM_WIDTH number of seq_ids). |
required |
Returns:
Type | Description |
---|---|
tuple[list[Optional[PromptLogprobs]], list[SampleLogprobs]]
|
A tuple of prompt and sample logprobs per sequence group in a batch. |
Source code in vllm/model_executor/layers/sampler.py
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 |
|
get_pythonized_sample_results
¶
get_pythonized_sample_results(
sample_result_args: SampleResultArgsType,
) -> SampleResultType
This function consumes GPU-side sampler results and computes Pythonized CPU-side sampler results (GPU -> CPU sync.)
Single-step scheduling: this function is invoked at sampling-time for immediate Pythonization.
Multi-step scheduling: Pythonization is deferred until after multiple GPU-side steps have been completed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_result_args
|
SampleResultArgsType
|
GPU-side inputs to the Pythonization process |
required |
Returns:
Type | Description |
---|---|
SampleResultType
|
Pythonized sampler results |