PIXELBANKv9.1.0
Menu

Implement nucleus (top-P) sampling.

Top-P sampling selects the smallest set of tokens whose cumulative probability exceeds P:

  1. Convert logits to probabilities (softmax)
  2. Sort by probability descending
  3. Find the smallest set where cumulative probability >= P
  4. Zero out all other positions and renormalize

Input:

  • Line 1: P (nucleus threshold)
  • Line 2: space-separated logits

Output: The filtered probability distribution, rounded to 4 decimal places.

Example:

Input:
0.9
3.0 1.0 4.0 0.5
Output:
0.2583 0.0000 0.7417 0.0000
Reasoning:
  • First, we convert the logits to probabilities using the softmax function: pi=exi∑j=1nexjp_i = \frac{e^{x_i}}{\sum_{j=1}^{n} e^{x_j}}, resulting in probabilities for the given logits: p1=e3.0e3.0+e1.0+e4.0+e0.5p_1 = \frac{e^{3.0}}{e^{3.0} + e^{1.0} + e^{4.0} + e^{0.5}}, p2=e1.0e3.0+e1.0+e4.0+e0.5p_2 = \frac{e^{1.0}}{e^{3.0} + e^{1.0} + e^{4.0} + e^{0.5}}, p3=e4.0e3.0+e1.0+e4.0+e0.5p_3 = \frac{e^{4.0}}{e^{3.0} + e^{1.0} + e^{4.0} + e^{0.5}}, p4=e0.5e3.0+e1.0+e4.0+e0.5p_4 = \frac{e^{0.5}}{e^{3.0} + e^{1.0} + e^{4.0} + e^{0.5}}.
  • Then, we sort these probabilities in descending order and calculate their cumulative sum until it exceeds the given threshold P=0.9P = 0.9.
  • Next, we select the smallest set of tokens whose cumulative probability exceeds PP, which in this case are the first and third tokens (p1p_1 and p3p_3), and zero out the other positions (p2p_2 and p4p_4).
  • Finally, we renormalize the selected probabilities to ensure they sum up to 1, resulting in the filtered probability distribution: p1=0.25830.2583+0.7417=0.2583p_1 = \frac{0.2583}{0.2583 + 0.7417} = 0.2583, p2=0p_2 = 0, p3=0.74170.2583+0.7417=0.7417p_3 = \frac{0.7417}{0.2583 + 0.7417} = 0.7417, p4=0p_4 = 0.

Constraints:

  • 0 < P <= 1
  • Include the token that causes cumulative probability to exceed P
  • Renormalize selected probabilities to sum to 1
  • Round to 4 decimal places
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Nucleus (Top-P) Sampling - Medium | PixelBank