sampling.py 3.78 KB
Newer Older
mshoeybi's avatar
mshoeybi committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

mshoeybi's avatar
mshoeybi committed
16
"""Sampling utilities.
mshoeybi's avatar
mshoeybi committed
17
18
19
20
Part of this code is inspired by:
 - https://github.com/ari-holtzman/degen/blob/master/gen.py
 - https://huggingface.co/transformers/_modules/transformers/generation_logits_process.html
"""
mshoeybi's avatar
mshoeybi committed
21
22
23
24
25


import torch


mshoeybi's avatar
mshoeybi committed
26
27
28

def modify_logits_for_top_k_filtering(logits, top_k):
    """Set the logits for none top-k values to -inf."""
mshoeybi's avatar
mshoeybi committed
29
30
31
32
33
34

    filter_ = logits < torch.topk(logits, top_k)[0][..., -1, None]
    logits.masked_fill_(filter_, float('-Inf'))



mshoeybi's avatar
mshoeybi committed
35
36
def modify_logits_for_top_p_filtering(logits, top_p):
    """Set the logits for none top-p values to -inf."""
mshoeybi's avatar
mshoeybi committed
37
38
39
40
41
42
43

    # First sort and calculate cumulative sum of probabilities.
    sorted_logits, sorted_indices = torch.sort(logits, descending=True)
    cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)

    # Filteration based on the cumulative sum.
    filter_ = cumulative_probs > top_p
mshoeybi's avatar
mshoeybi committed
44
45
46
47
48
    # This shift by 1 is weird and I cannot justify it. This existed
    # in the original implementation:
    #   https://github.com/ari-holtzman/degen/blob/master/gen.py
    # and I guess it is needed so keeping it for now.
    filter_[:, 1:] = filter_[:, :-1].clone()
mshoeybi's avatar
mshoeybi committed
49
50
51
52
53
54
55
56
    # Make sure we at least have one token to select from.
    filter_[..., 0] = 0

    # Fill in the filtered part
    filter_ = filter_.scatter(1, sorted_indices, filter_)
    logits.masked_fill_(filter_, float('-Inf'))


mshoeybi's avatar
mshoeybi committed
57

mshoeybi's avatar
mshoeybi committed
58
def sample(logits, top_k=0, top_p=0.0, temperature=1.0, vocab_size=None):
mshoeybi's avatar
mshoeybi committed
59
60
61
    """ Sample and generate a token.
    Note: logits has the dimension [b, v] where b is the batch size
          and v is the vocabulary size.
mshoeybi's avatar
mshoeybi committed
62
63
64
65
    If vocab_size is provided, we will make sure the sample that is
    generated is in [0, vocab-size). This will avoid out of vocabulary
    generations due to padding.
    """
mshoeybi's avatar
mshoeybi committed
66
67

    # Check logits for consistency.
mshoeybi's avatar
mshoeybi committed
68
    assert logits.ndim == 2, 'expected the logits to be of [b, v] shape.'
mshoeybi's avatar
mshoeybi committed
69
70
    assert logits.type() == 'torch.cuda.FloatTensor', \
        'input logits should be floats.'
mshoeybi's avatar
mshoeybi committed
71

mshoeybi's avatar
mshoeybi committed
72

mshoeybi's avatar
mshoeybi committed
73
    # Greedy is just simple argmax.
mshoeybi's avatar
mshoeybi committed
74
    if top_k == 1:
mshoeybi's avatar
mshoeybi committed
75
76
77
78
79
        assert top_p == 0.0, 'cannot set both greedy and top-p samplings.'
        samples = torch.argmax(logits, dim=-1)

    # Top-k or top-p sampling.
    else:
mshoeybi's avatar
mshoeybi committed
80
81
        # Clone so we do not modify the inputs,
        logits = logits.clone()
mshoeybi's avatar
mshoeybi committed
82
        # Apply temperature in place.
mshoeybi's avatar
mshoeybi committed
83
84
        if temperature != 1.0:
            logits.div_(temperature)
mshoeybi's avatar
mshoeybi committed
85

mshoeybi's avatar
mshoeybi committed
86
        if top_k > 1:
mshoeybi's avatar
mshoeybi committed
87
88
89
90
            assert top_p == 0.0, 'cannot set both top-k and top-p samplings.'
            assert top_k <= logits.size(1), 'top-k is larger than logit size.'
            if vocab_size:
                assert top_k < vocab_size, 'top-k is larger than vocab size.'
mshoeybi's avatar
mshoeybi committed
91
            modify_logits_for_top_k_filtering(logits, top_k)
mshoeybi's avatar
mshoeybi committed
92

mshoeybi's avatar
mshoeybi committed
93
94
95
        elif top_p > 0.0:
            assert top_p <= 1.0, 'top-p should be in (0, 1].'
            modify_logits_for_top_p_filtering(logits, top_p)
mshoeybi's avatar
mshoeybi committed
96
97

        # After filtering, we need to recalculate the distribution.
mshoeybi's avatar
mshoeybi committed
98
99
        probs = logits.softmax(dim=-1)
        samples = torch.multinomial(probs, num_samples=1).view(-1)
mshoeybi's avatar
mshoeybi committed
100
101
102
103
104
105

    # If vocab size is provided, make sure the samples are in
    # in the range [0, vocab-size).
    if vocab_size:
        samples = torch.clamp(samples, min=0, max=(vocab_size - 1))

mshoeybi's avatar
mshoeybi committed
106
    return samples