Skip to content

← Decoding Strategies step 1 of 8

Easy Primitives

Greedy Decoding

Generate tokens one at a time by selecting the largest model score at each step. The supplied callback provides the scores; your function manages the sequence and the stopping rule.

Your task

Implement greedy_decode(logits_fn, prompt, max_tokens, eos_id).

  • prompt is a one-dimensional tensor of integer-valued token IDs.
  • logits_fn accepts the current sequence as a Python list of integers and returns a nonempty vector of finite logits, one score per vocabulary token. A token's ID is its position in that vector.
  • max_tokens is a nonnegative integer limiting newly generated tokens. Prompt tokens do not count toward this limit.
  • eos_id is the end-of-sequence ID. It may be outside the callback's vocabulary, in which case it cannot be generated.

Return a one-dimensional float32 tensor containing the prompt followed by all generated IDs. The float32 representation matches this exercise's runtime convention; the IDs passed to logits_fn must still be Python integers. Leave the prompt unchanged.

Generation loop

Start with an integer list copied from prompt. On each step:

  1. Call logits_fn with the full current sequence.
  2. Choose the index of the largest logit. If scores tie, choose the lowest index.
  3. Append that ID to the sequence.
  4. If the appended ID equals eos_id, stop. Keep that EOS token in the result.

For prompt [5], a callback that always favors token 2, max_tokens=3 and eos_id=99, return [5, 2, 2, 2].

If the callback favors token 7 while the sequence has fewer than three tokens, then favors EOS token 0, the same prompt grows as follows:

[5] -> [5, 7] -> [5, 7, 7] -> [5, 7, 7, 0]

With max_tokens=0, return the prompt without calling logits_fn. The stopping check applies to newly generated tokens; an EOS ID already in the prompt does not itself stop this loop.

What greedy selection does

Use torch.argmax or jnp.argmax. There is no random draw, and softmax is not needed to identify the largest finite logit. Fixed callback scores and the tie rule give a deterministic choice; the callback itself is responsible for any model randomness.

Greedy decoding chooses the best next token by score. It does not search for the highest-probability whole sequence, and it can repeat tokens. This exercise does not implement the language model, caching or beam search.

The diagram shows scores and their softmax probabilities. Changing positive temperature changes those probabilities but preserves the largest score's position, so greedy selection remains the same.

Loading visualization…