MCPcopy Create free account
hub / github.com/AIS-SNU/Smart-Infinity / top_k_logits

Function top_k_logits

DeepSpeedExample/megatron/text_generation_utils.py:50–80  ·  view source on GitHub ↗

This function has been mostly taken from huggingface conversational ai code at https://medium.com/huggingface/how-to-build-a-state-of-the-art- conversational-ai-with-transfer-learning-2d818ac26313

(logits, top_k=0, top_p=0.0, filter_value=-float('Inf'))

Source from the content-addressed store, hash-verified

48
49
50def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
51 """ This function has been mostly taken from huggingface conversational
52 ai code at
53 https://medium.com/huggingface/how-to-build-a-state-of-the-art-
54 conversational-ai-with-transfer-learning-2d818ac26313 """
55
56 if top_k > 0:
57 # Remove all tokens with a probability less than the
58 # last token of the top-k
59 indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
60 logits[indices_to_remove] = filter_value
61
62 if top_p > 0.0:
63 # Cconvert to 1D
64 sorted_logits, sorted_indices = torch.sort(
65 logits, descending=True, dim=-1)
66 cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1),
67 dim=-1)
68
69 # Remove tokens with cumulative probability above the threshold
70 sorted_indices_to_remove = cumulative_probs > top_p
71 # Shift the indices to the right to keep also the first token
72 # above the threshold
73 sorted_indices_to_remove[..., 1:] \
74 = sorted_indices_to_remove[..., :-1].clone()
75 sorted_indices_to_remove[..., 0] = 0
76 for i in range(sorted_indices.size(0)):
77 indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
78 logits[i][indices_to_remove] = filter_value
79
80 return logits
81
82
83def generate_samples_input_from_file(model):

Callers 1

sample_sequence_batchFunction · 0.85

Calls 3

topkMethod · 0.80
cumsumMethod · 0.80
sizeMethod · 0.45

Tested by

no test coverage detected