Unit 7 of 7 · about 3 hours · implement

Stopping rules and reproducible generation

Unbounded generation never terminates cleanly, and unseeded sampling cannot be debugged. Stopping, seeds and validation turn demos into experiments that can be rerun and compared.

You'll be able to

  • Implement EOS, stop-sequence, maximum-length and finished-batch handling in a generate loop.
  • Make sampling exactly reproducible from a recorded seed and validate the outputs.
  • Compare prompts and chat templates while holding decoding fixed, and state each choice in config.

Covers

EOS, stop sequences, maximum length and finished batchesSampling RNG, reproducibility and output validationPrompt and chat-template comparison
1

Read

In this order, only the parts listed

0 of 5 done

  1. Raschka gpt_generate.py: bounded generation with eos_idLLMs from Scratch companion - training and generation

    generate(): context-window slicing of the running sequence, the max_new_tokens loop, the eos_id early break and appending each sampled token

  2. Modern LLM Notebook 20-generation: complete pipeline and orderModern LLM Notebook - configuration, loss and generation

    Section 9 (complete generate with penalty, temperature, top- and top-, eos_id and seed) and the Summary execution order: penalty, temperature, top- and top-, sample, then eos

  3. PyTorch reproducibility notes: seeding for exact rerunsPyTorch saving, loading and reproducibility references

    Controlling sources of randomness (seed torch, Python and other libraries together); the Raschka scripts set torch.manual_seed(123) before generation

  4. Modern LLM Notebook 20-generation and 10-training-loss: templatesModern LLM Notebook - configuration, loss and generation

    Notebook 20 Section 8 (chat templates stitch turns into model text, wrong template degrades quality, apply_chat_template) with notebook 10 Section 2 (templates decide which tokens the loss sees)

  5. Hugging Face LLM Course: inference translationHugging Face LLM Course - library translation

    Chapter 1, Inference with LLMs (chapter1/8): map generation configuration and stopping behavior into library APIs

    Open only after the blank-file loop passes fixed-seed checks; the from-scratch tests stay the authority.

2

Focus on

  • Check EOS every step and cap length regardless. EOS is model-controlled and may never arrive.
  • Seed every RNG in the path and record the seeds with the output. One unseeded source breaks reruns.
  • Validation is cheap and explicit: EOS present, length within cap, template matching training, decoded text well-formed.
  • Hold decoding fixed when comparing prompts or templates, or policy differences will masquerade as prompt effects.
Common mistakes · 3
  • Stopping on EOS alone. A model that never emits EOS generates until the budget or the wallet runs out.
  • Seeding torch but not the Python RNG or sampler state. Multinomial draws still differ and the mismatch looks like a model bug.
  • Grading a chat model with the wrong template and blaming the weights. Format mismatch degrades answers without changing any parameter.
3

Try it yourself

Closed-book, before checking anything

Write a generate loop with max_new_tokens, eos_id, a stop-sequence check and seed control that returns identical tokens on every rerun.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why does the loop need both eos_id and max_new_tokens?Answer

    EOS is emitted by the model and may never come, so it cannot bound cost. The cap bounds tokens, latency and cost on every call no matter what the model does.

  2. 2.Same seed, different outputs on rerun. Name two suspects.Answer

    An unseeded RNG such as Python random or a sampler without generator control, and a nondeterministic kernel or op ordering. Both must be fixed before blaming the policy code.

  3. 3.What failure does apply_chat_template prevent?Answer

    Train and serve format mismatch. The template wraps turns exactly as training saw them; a hand-rolled prompt can silently use the wrong markers and degrade quality.

  4. 4.A run uses temperature 0.6, top_p 0.9, top_k 50 and repetition penalty 1.1. In what order do they apply?Answer

    Penalty first, then temperature, then top- and top- truncation, then sampling, then the EOS check, as the notebook summary lists. The order matters: temperature changes the probabilities, so applying it before or after top- changes which tokens the nucleus keeps. Record the order in the config.

5

Practice

  • Modern LLM Notebook 09-model-config Exercise 1: compare generation configs

    Exercise 1: open two model generation_config files, write three differences with explanations for temperature, top_p, top_k, max_new_tokens and stopping entries

    Then encode your own loop's stopping and sampling choices as one such config and demonstrate the EOS plus max-length stops with a fixed seed.

You're done when

Your loop stops on EOS and on the cap, reruns bit-identically from a recorded seed, and every stopping and template choice is stated in one config.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 2 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.

  • 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.

  • 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.

Also in this section

  • 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.

  • 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.