liveBook · Manning

Greedy algorithm

As explained in Build a Reasoning Model (From Scratch)

A decoding strategy that always selects the highest-probability next token instead of sampling randomly.

Greedy decoding selects the single highest-scoring next token at each inference step, turning an LLM’s final-position scores into deterministic text generation. section 2.6

Apply the method inside the autoregressive generation loop:

  • Run the model on the prompt and previously generated tokens. section 2.6
  • Keep the score vector from the final input position, because it predicts the next token. section 2.6
  • Use torch.argmax(..., keepdim=True) to return the index of the largest score while preserving a concatenation-friendly shape. section 2.6
  • Decode the resulting token ID and feed it back into the next generation iteration. section 2.6

Selecting the next token

Given the final score vector, torch.argmax(last_token, dim=-1, keepdim=True) returns token ID 20286; decoding that ID produces “Large.” section 2.6

Figure 2.10 Sequential (autoregressive) text generation in LLMs. At each iteration, the model generates the next token based on the input and previously generated tokens, which are cumulatively fed back into the model to produce coherent output.

Trace how each selected token is appended to the context and reused to produce the next prediction. section 2.6

How Build a Reasoning Model (From Scratch) covers it

How deep it goes
Explains score extraction, argmax indexing, shape preservation, decoding, and iterative reuse, while deferring alternative decoding strategies.
Examples
Demonstrates torch.argmax on score vectors and decodes token ID 20286 into “Large.”
What it assumes
Assumes a pretrained LLM, tokenizer, inference output tensor, and basic familiarity with tensor indexing and dimensions.
What you can do after
Apply greedy decoding with PyTorch to select and decode each next token in an autoregressive generation loop.
How it connects
Links autoregressive text generation, next-token prediction, token IDs, tokenization, and tensor shapes.

Also explained in

Compare how 12 books explain greedy algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Reasoning Model (From Scratch). The section links point to the parts of the book it draws on.