PIXELBANKv9.1.0
Menu

Implement top-K sampling for text generation.

Top-K sampling restricts the next token to the K most likely tokens:

  1. Sort logits descending
  2. Keep only the top K
  3. Set the rest to -infinity
  4. Apply softmax to the remaining logits

Input:

  • Line 1: K
  • Line 2: space-separated logits

Output: The filtered probability distribution (all positions), rounded to 4 decimal places. Non-top-K positions should be 0.0000.

Example:

Input:
2
3.0 1.0 4.0 2.0
Output:
0.2689 0.0000 0.7311 0.0000
Reasoning:
  • First, we sort the logits in descending order: 4.0,3.0,2.0,1.04.0, 3.0, 2.0, 1.0
  • Then, we keep only the top K (K=2K=2) logits and set the rest to −∞-\infty: 4.0,3.0,−∞,−∞4.0, 3.0, -\infty, -\infty
  • Next, we apply the softmax function to the remaining logits: P(i)=elogiti∑j=1KelogitjP(i) = \frac{e^{logit_i}}{\sum_{j=1}^{K} e^{logit_j}}, resulting in e4.0e4.0+e3.0\frac{e^{4.0}}{e^{4.0} + e^{3.0}} and e3.0e4.0+e3.0\frac{e^{3.0}}{e^{4.0} + e^{3.0}}
  • The final output is the filtered probability distribution, with non-top-K positions set to 0.00000.0000: 0.2689,0.0000,0.7311,0.00000.2689, 0.0000, 0.7311, 0.0000

Constraints:

  • 1 <= K <= vocab size
  • Positions not in top-K get probability 0
  • 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.
Top-K Sampling - Easy | PixelBank