모든 챌린지
보통 0명 해결 정답률 0%

Temperature and Top-K Sampling

Choose the next token like a language model does: keep the top k logits, apply temperature, and sample.

배우게 될 내용

  • Keep the top k candidate tokens
  • Control randomness with temperature
  • Sample from a probability distribution

문제

번역본 보기

Language models pick the next token from a probability distribution. Two settings shape it:

  • Top-k: keep only the k tokens with the highest logits (if logits tie, the lower index ranks higher).
  • Temperature T: divide the kept logits by T before softmax. Low T makes the choice more predictable; high T makes it more random.

To make sampling testable, the random number is given:

  1. Keep the top k tokens, then list them by their original index (ascending).
  2. Compute softmax(logit / T) over the kept tokens (subtract the largest before taking e^x).
  3. Walk through the list adding probabilities; return the index of the first token where the running total becomes greater than random_value. If none does (rounding), return the last kept token.

With k = 1 this is greedy decoding: always the most likely token.

Implement sample_token(logits, temperature, k, random_value).

Input

logits: One score per token in the vocabulary.

temperature: T, greater than 0.

k: How many top tokens to keep.

random_value: A random number in [0, 1).

Output

Return the index of the chosen token.

제약 조건

1 ≤ k ≤ number of logits ≤ 1,000

0 < temperature ≤ 100, 0 ≤ random_value < 1

-100 ≤ each logit ≤ 100

예시

예시 1
입력:
k = 1
logits = [1.0, 3.0, 2.0, 0.5]
temperature = 1.0
random_value = 0.99

예상 출력:
expected = 1
입력:
long long k = 1;
std::vector<double> logits = {1.0, 3.0, 2.0, 0.5};
double temperature = 1.0;
double random_value = 0.99;

예상 출력:
long long expected = 1;
입력:
long k = 1;
double[] logits = new double[] {1.0, 3.0, 2.0, 0.5};
double temperature = 1.0;
double random_value = 0.99;

예상 출력:
long expected = 1;

설명

k = 1 keeps only the highest logit, 3.0 at index 1. Its probability is 1, so it is chosen whatever the random value: greedy decoding.

예시 2
입력:
k = 2
logits = [2.0, 1.0, 0.0]
temperature = 1.0
random_value = 0.8

예상 출력:
expected = 1
입력:
long long k = 2;
std::vector<double> logits = {2.0, 1.0, 0.0};
double temperature = 1.0;
double random_value = 0.8;

예상 출력:
long long expected = 1;
입력:
long k = 2;
double[] logits = new double[] {2.0, 1.0, 0.0};
double temperature = 1.0;
double random_value = 0.8;

예상 출력:
long expected = 1;

설명

Top-2 keeps indices 0 and 1 (logits 2 and 1). softmax gives about 0.731 and 0.269. The running total is 0.731 after index 0 (not above 0.8) and 1 after index 1, so index 1 is chosen.

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.