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'))
| 48 | |
| 49 | |
| 50 | def 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 | |
| 83 | def generate_samples_input_from_file(model): |
no test coverage detected