Chapter 3 of 8 · Free, no signup

Support Us

Generative AI & LLM Engineering · Chapter 3 · ~18 min · Interactive Lab

Temperature, Sampling & Context Windows

How do models turn raw numbers into creative text? Discover how Temperature, Top-P (Nucleus), and Top-K control randomness, how to budget context windows, and why facts get "lost in the middle."

  • Master Temperature, Top-P and Top-K live
  • Prevent loops with repetition penalties
  • Budget context windows (prompts vs outputs)
  • Avoid the 'lost in the middle' attention trap

1Inside the Logit-to-Probability engine

Before an LLM picks a token, its final neural layer outputs a raw numerical score for every single word in its vocabulary (all ~100,000 of them). These raw unnormalized scores are called logits.

To turn logits into clean percentages that add up to 100%, the model runs them through a mathematical formula called Softmax:

probability = exp(logit / temperature) / sum(exp(all_logits / temperature))
Logits can be negative, zero, or positive (e.g. +4.8 for "coffee", -1.8 for "oil"). Softmax guarantees every token gets a positive percentage, with higher logits getting exponentially more probability.

What does the Softmax function do to the model's raw logits?

2The Sampling Lab: Temperature, Top-P & Top-K

How should the model pick from those percentages? You have three primary dials to steer generation:

Temperature (T)

Controls sharpness. At T=0, it greedily picks #1 every time. High T flattens the distribution so unlikely tokens can win.

Top-P (Nucleus)

Dynamic threshold. Accumulates probabilities until reaching P (e.g. 0.90) and truncates the rest of the tail.

Top-K (Cap)

Hard count limit. Discards everything beyond the top K most likely tokens, preventing completely nonsensical picks.

Prompt: "Every morning before work, I drink a hot cup of [next token?]"
Temperature (T)0.70

Common starting range; tune for the task.

Top-P (Nucleus)0.95

Keeps the smallest pool whose cumulative prob exceeds P.

Top-K (Cap)6

Cuts off everything below the top 6 candidates.

Balanced Chat2 of 6 candidates eligible
"coffee"
78.3%
"tea"
21.7%
"water"
Cutoff
"juice"
Cutoff
"soup"
Cutoff
"oil"
Cutoff
Production Rule: Never tune both high Temperature and high Top-P at the same time. The recommended standard is to set Top-P to 0.9–0.95 and only adjust Temperature depending on your task.

Which sampling setting usually makes token selection least random for the same prompt and model?

3Stopping Infinite Loops (Frequency & Presence Penalties)

Have you ever seen an AI get stuck repeating: "In conclusion, furthermore, in conclusion, furthermore..."?

Because generating a word makes that word appear in its own history, language models can fall into positive feedback loops. LLM APIs provide two penalties to break this cycle:

Presence Penalty (0.0 to 2.0)

One-time penalty if a word has appeared at all in the text so far. Encourages the model to introduce fresh topics and vocabulary.

Frequency Penalty (0.0 to 2.0)

Grows larger the more times a specific token is repeated. Directly penalizes verbatim phrase repetitions.

A subtle frequency penalty (e.g. 0.2 to 0.5) makes prose sound less repetitive. Setting it too high (1.5+) will force the model into unnatural synonyms or broken grammar.

4Context Window Budgeting (Input vs Output)

A common mistake when calling LLM APIs is forgetting that the context window is a shared pool between your input prompt and the model's generated response.

If your model has a 32,000-token limit and your prompt is 30,000 tokens long, the model can generate at most 2,000 tokens before crashing into the wall. Test different configurations below:

System Prompt & Instructions:1,200 tok
Conversation Chat History:14,000 tok
Retrieved Documents / RAG chunks:10,000 tok
Reserved Max Output Tokens:4,000 tok
Window Utilization:29,200 / 32,000 tokens (91%)
System Prompt Chat History RAG / Docs Output Budget
Safe headroom remaining for output generation:6,800 tokens
Always reserve a safe margin for max_tokens (completion tokens). If a response cuts off mid-sentence, it almost always means it hit your configured max completion token ceiling!

Your prompt is 110,000 tokens in a 128,000-token context window model. What is the maximum length the answer can be?

5The 'Lost in the Middle' Trap

Even when a model technically supports 100K or 1M tokens, it doesn't pay equal attention to every position. Research demonstrates that LLMs exhibit a U-shaped attention curve:

The "Lost in the Middle" Phenomenon

Simulated attention weight across a long document prompt:

Start (System Prompt)Middle (Buried Documents)End (User Query)
Estimated Fact Retrieval Rate: 54%

Dramatically lower recall! The model often skips or confuses facts buried in the middle of 20+ pages.

💡 Engineering Rule: Put critical instructions and formatting constraints at the very top or very bottom of the prompt — never buried halfway through your text.

When building Retrieval-Augmented Generation (RAG) pipelines in Chapter 6, always sort your most relevant retrieved document chunks to the very top or bottom of your prompt.

6Chapter challenge

Sampling & Context Mastery

Answer all four questions correctly to complete Chapter 3.

0 / 4 correct
  1. 1Which temperature is best suited for extracting JSON fields from an invoice?

  2. 2How does Top-P (Nucleus Sampling) work?

  3. 3What causes a model's response to abruptly truncate mid-sentence?

  4. 4According to the 'Lost in the Middle' phenomenon, where should critical instructions be placed in a long prompt?

7Recap

  • Logits to Probabilities: Raw model outputs pass through Softmax to produce token odds.
  • Temperature dial: T=0 for code & extraction; T=0.7 for chat; T=1.2+ for creative writing.
  • Top-P & Top-K: Filter out the improbable tail of bizarre tokens.
  • Context Budgeting: Input tokens + Output tokens must fit within the model's max window.
  • Lost in the Middle: Keep your most critical facts and instructions at the start or end of long prompts.

Solve the challenge above to complete the chapter, or

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us