Show me an implementation of nucleus sampling written in python
- User
Show me an implementation of nucleus sampling written in python
- Assistant
Nucleus sampling is a technique used in natural language processing to control the diversity of generated text. It works by filtering out all but the most likely tokens given a certain probability threshold, also known as the "nucleus". Here's an implementation of nucleus sampling in Python:
import numpy as np
def nucleus_sampling(logits, p=0.9): """ Implements nucleus sampling, a technique used in natural language processing to control the diversity of generated text.
Args: - logits: an array of predicted logits for the next token - p: the probability threshold, also known as the "nucleus", to use for filtering out unlikely tokens Returns: - the index of the most likely token, sampled from the filtered set of tokens """ sorted_logits = np.sort(logits) cumulative_probs = np.cumsum(np.exp(sorted_logits)) / np.sum(np.exp(sorted_logits)) threshold_index = np.searchsorted(cumulative_probs, p) threshold_logits = sorted_logits[threshold_index] filtered_logits = np.where(logits >= threshold_logits, logits, -1e32) filtered_probs = np.exp(filtered_logits) / np.sum(np.exp(filtered_logits)) return np.random.choice(np.arange(len(logits)), p=filtered_probs)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.