Unit 6 of 7 · about 4 hours · derive, implement

Decoding policies: from greedy to nucleus sampling

The model outputs probabilities; the policy decides the text. The same logits can produce a memo or gibberish depending on truncation, so the policy must be owned separately from the weights.

You'll be able to

  • Derive the renormalized distribution after temperature, top- and top- with their edge cases.
  • Implement greedy, temperature, top- and top- sampling with deterministic seeds.
  • Compare decoding policies on matched logits with fixed output budgets, including beam search and repetition control.

Covers

Logits, greedy decoding and deterministic argmaxTemperature and distribution renormalizationTop-k and nucleus top-p truncationBeam-search objective and cost vocabularyRepetition and length penalties
1

Read

In this order, only the parts listed

0 of 4 done

  1. CS336 Assignment 1 handout: decoding with temperature and top-Stanford CS336 Assignment 1 - training and decoding contract

    Section 6, Generating text (pp. 37 to 38): equations 21 and 22 for last-position sampling, temperature scaling in equation 23 with the limit, and nucleus sampling in equation 24 as the smallest set with cumulative probability at least

  2. LLMs from Scratch ch05: temperature, top- and the generate functionLLMs from Scratch companion - training and generation

    Sections 5.3.1 (multinomial versus , temperature 0.1 and 5.0 behavior), 5.3.2 (top- masking with negative infinity) and 5.3.3 (the generate function combining temperature, top- and eos_id)

  3. Modern LLM Notebook 20-generation: truncation arithmeticModern LLM Notebook - configuration, loss and generation

    Sections 3 (greedy as ), 4 (temperature table), 5.1 (top- with the 0.71 and 0.29 renormalization), 5.2 (top- nucleus with 0.9) and 5.3 (industry default of top- plus top-)

  4. Modern LLM Notebook 20-generation: beam search and repetitionModern LLM Notebook - configuration, loss and generation

    Sections 6 (beam search keeps paths, fits translation and summarization, bores creative writing) and 7 (repetition penalty divides positive logits and multiplies negative ones)

    Read for objective and cost vocabulary only; full beam and penalty tuning belong to later tracks.

2

Focus on

  • Temperature approaching zero recovers , and top- with 1 is greedy by another name.
  • Truncation zeroes the tail first, then renormalizes, then samples. Sampling before renormalizing draws from the wrong distribution.
  • Top- adapts the candidate count to the distribution shape, which is why a fixed fails on both sharp and flat distributions.
  • Beam search optimizes sequence score over paths; it is not a sampling method and it trades diversity for safety.
Common mistakes · 3
  • Applying top- to raw logits. Cumulative probability needs probabilities, so softmax must come before sorting and accumulation.
  • Forgetting renormalization after masking. The kept tokens must sum to one before multinomial sees them.
  • Expecting diversity from beam search. Wider beams concentrate on safe sequences; temperature and nucleus control diversity instead.
3

Try it yourself

Closed-book, before checking anything

Implement top- and top- filters from sorted probabilities with renormalization, plus the temperature zero and one edge cases, all under a fixed seed.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Logits [2.0, 1.0, 0.5] with temperature 0.5. What are the scaled logits?Answer

    [4.0, 2.0, 1.0]. Temperature divides the logits, which sharpens the distribution toward the .

  2. 2.Logits [0.1, 2.0, 0.5, 3.0, 0.01] with top_k 2. Which positions survive?Answer

    Positions 3 (value 3.0) and 1 (value 2.0). Everything else is set to negative infinity before softmax.

  3. 3.Probabilities [0.4, 0.3, 0.15, 0.1, 0.05] with 0.8. Which tokens stay?Answer

    The first three. Sorted accumulation gives 0.4, then 0.7, then 0.85, which first reaches 0.8 at the third token.

  4. 4.The distribution is sharp and is 40. What goes wrong, and what fixes it?Answer

    Top- drags 39 implausible tail tokens into the candidate set. Top- fixes it by stopping accumulation once the nucleus reaches , keeping only the concentrated head.

5

Practice

  • Modern LLM Notebook 20-generation Exercises 1 to 3: temperature, top-, top-

    Exercises section: Exercise 1 (scaled logits assert), Exercise 2 (top- positions assert) and Exercise 3 (top- accumulation); each cell asserts the exact answer

    Solve each by hand first, then confirm with the cell. Afterwards reproduce fixed-seed greedy, temperature, top- and top- outputs from your own sampler on matched logits.

You're done when

Your filters pass all three exercise asserts, and your sampler reproduces fixed-seed outputs for each policy on matched logits within a fixed budget.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 3 more in the section
  • LLMs from Scratch companion - training and generationSebastian Raschka · primary

    Use the ch05 training and generation code for the small pretraining loop. Add full checkpoint state, explicit loss masks and resume-equivalence tests that the base example does not supply.

  • Stanford CS336 Assignment 1 - training and decoding contractStanford University · required

    Use cross_entropy, adamw, adamw_accounting, learning_rate_schedule, gradient_clipping, data_loading, checkpointing, training_together and decoding specifications plus public tests. Debug on CPU and implement independently in your own repository.

  • Modern LLM Notebook - configuration, loss and generationWalking Labs · support

    Use English notebooks 09-model-config, 10-training-loss and 20-generation to visualize configuration ownership, shifted loss and decoding policies. Change edge cases and cross-check probability calculations against your own implementation.

Also in this section

  • PyTorch saving, loading and reproducibility referencesPyTorch · support

    Use the state-dict and reproducibility notes to enumerate all state needed for the supported resume guarantee. Test model, optimizer, schedule, scaler, data order and RNG state across an interruption.

  • Hugging Face LLM Course - library translationHugging Face · optional

    Only after the blank-file loop passes, map tokenization, model configuration, data collation, generation configuration and stopping behavior into Transformers APIs. Keep the from-scratch tests as the authority.

  • PyTorch Automatic Mixed Precision recipePyTorch · support

    Use the autocast, GradScaler, unscale-before-clip, scaler checkpointing and inf-NaN troubleshooting sections to add mixed precision to the blank-file loop. Keep the CS336 clipping contract as the authority for the clipping rule.