What Is a Context Window in an LLM?
A context window is the maximum number of token positions an LLM can use at once. For a typical decoder-only model, the prompt and generated continuation share that window, while temperature, top-k and top-p control how the model selects each next token. An output token cap separately limits how much the model can generate.

When a chat application sends a request to a large language model, the input can contain system instructions, earlier messages, the latest question, tool results and retrieved documents. The application serialises these items into a sequence. The tokenizer converts that sequence into token IDs, including any role markers and other special tokens required by the chat format. A token can be a word fragment, punctuation mark or other unit. Use the model's tokenizer or the provider's counting interface rather than estimating from word count. Marathi prose, an English translation and a Python listing of similar visible length can have different token counts.
In a decoder-only transformer with full causal attention, each position can attend to positions up to and including itself. The model uses the representation at the final position to compute scores for the next token. It appends the selected token and repeats the process. A key-value cache can reuse attention keys and values from earlier positions to avoid recomputing them at each step. It uses memory while the sequence is being processed and provides no access to text omitted from the request. Architectures with local or sliding attention can restrict which earlier positions a given layer attends to.
A larger window gives an application room to include more conversation or more source material. It does not ensure that the model will extract the right fact from every position. An earlier message is available only if the serving system includes it in the current context, possibly in summarised form. If a chat application drops a message about the user's preferred units, increasing temperature or changing the output cap cannot restore that information. Store important state separately and insert the relevant parts when building the next request.
How Do Context Window and Max Tokens Limits Work?
For a service that documents a shared sequence limit, plan with input_tokens + requested_output_budget <= context_window. Check separate input and output limits as well. The effective output allowance cannot exceed either the model's output limit or the space left after the prompt. A serving endpoint can have tighter limits than the underlying model, so use the specifications for the model ID and endpoint you actually call.
Suppose a service offers a shared window of 8,192 tokens and has a separate maximum output of 2,048 tokens. Your formatted prompt uses 7,400 tokens, including chat markers. The remaining space is 8,192 - 7,400 = 792 tokens. To reserve 1,000 output tokens, reduce the input to 7,192 tokens or fewer, which means removing at least 208 tokens. Count the formatted prompt again after editing it. A service may reject a request that exceeds its limits, reduce the available output, or apply truncation if configured to do so. Find out which behaviour your endpoint provides before deploying.
Hugging Face Transformers uses max_new_tokens to cap the generated continuation. In that library, max_length can instead refer to the combined sequence length for decoder-only generation. Hosted APIs use names such as max_output_tokens or max_completion_tokens, depending on the endpoint. Some APIs count internal reasoning tokens against the completion budget, so a request capped at 500 tokens can produce fewer than 500 visible tokens. A cap of 50 or 500 is an upper bound. The model can stop earlier when it emits an end token or meets another stopping condition.
For a document assistant, reserve space for the answer before filling the prompt with evidence. Keep required instructions and the current question, then fit the most relevant passages into the remaining budget. Retrieval-augmented generation gives you a way to select those passages when the entire corpus cannot fit. Leave room for source IDs and delimiters, and test what happens when the retrieved material contains no answer. If the output hits the cap during JSON generation, a closing bracket may be missing. Check the termination reason and validate the response before passing it to another service.
What Does Temperature in an LLM Do?
At each decoding step, the model produces a vector of logits z, one score per vocabulary token. With temperature T > 0, a sampler can convert those scores to probabilities using P(i) = exp(z_i / T) / sum_j exp(z_j / T). In code, subtract the largest scaled logit before exponentiating to avoid overflow. The subtraction does not change the resulting probabilities because the same factor cancels from the numerator and denominator.
At T = 1, temperature scaling leaves the logits unchanged. Below one, it widens the gaps between scaled scores and concentrates probability on higher ranked tokens. Above one, it narrows those gaps and spreads probability across more candidates. For any positive temperature, this step preserves token rank. The equation is defined for any positive temperature, although each API can impose its own permitted range. A value of zero is usually an API convention for greedy decoding, since dividing logits by zero is undefined. For greedy decoding in Transformers, set do_sample=False and num_beams=1.
Try a low setting such as 0.2 when comparing variants of a short answer, and try a setting such as 0.8 when you want more variation across drafts. These are experiment settings rather than accuracy targets. If an incorrect token has the highest logit, lowering temperature increases the chance of selecting it. Greedy decoding can also differ across deployments if numerical precision, tie handling or model revisions change a token decision. One changed token alters the prefix, so later tokens can diverge even when early outputs look nearly identical.
How Does Top-k Sampling Work?
Top-k sampling keeps the k highest ranked next-token candidates, excludes the others, and samples from the retained set after renormalising its probabilities. You can implement the exclusion by setting the removed logits to negative infinity before softmax. With k = 1 and a unique highest logit, only one token can be selected. With k = 50, as many as 50 candidates survive that filter, although many can still have a negligible chance of being drawn. Some implementations keep extra tokens when scores tie at the cutoff.
A fixed rank cutoff has different effects at different positions. After New in a passage about India's capital, the model might assign most probability to one continuation. At the start of a story it may spread probability across dozens. With the same k, the first step might retain several nearly irrelevant candidates, while the second discards many plausible ones. Inspect the total probability mass retained before renormalisation to understand how much the filter has changed a distribution. Also check whether the serving API exposes top-k. When it does not, top-p can limit candidates by probability mass, but it cannot enforce a fixed rank cutoff.
What Is Top-p Sampling in LLMs?
Top-p sampling, also called nucleus sampling, sorts the candidates by descending probability and keeps the shortest prefix whose cumulative mass is at least p. The token that first reaches or exceeds the threshold stays in the set. The sampler renormalises the selected probabilities so they sum to one, then draws a token. For example, if the highest probability is 0.94 and p = 0.90, the nucleus consists of one token. With ten equally probable candidates, the same threshold keeps nine in exact arithmetic.

A low threshold such as 0.1 can produce a single candidate at many steps. A value such as 0.9 generally permits a larger candidate set than 0.1 on the same distribution. The size can change with every generated token, even though the requested p stays fixed. This allows a tight cutoff when the model strongly favours one continuation and a wider cutoff when it assigns similar scores to many. Evaluate whether that behaviour helps your task. A rare but correct spelling or identifier can still end up outside the nucleus.
| Control | What it changes | What it cannot tell you |
|---|---|---|
| Temperature | Scales logit gaps before sampling | Whether a high-scoring token is factually correct |
| Top-k | Filters by rank at each step | How much probability mass the retained ranks contain |
| Top-p | Filters by cumulative probability at each step | How many candidates will survive at the next step |
| Output token cap | Limits the length of the generated continuation | Whether the answer will finish within the limit |
Worked Example: Temperature, Top-k and Top-p in Python
Assume five candidate tokens A to E have probabilities [0.40, 0.25, 0.15, 0.12, 0.08] at temperature one. With top-k set to two, the retained mass is 0.40 + 0.25 = 0.65. The sampling probabilities become 0.40 / 0.65 = 0.6154 and 0.25 / 0.65 = 0.3846. With top-p set to 0.75 instead, the first two are insufficient. Adding C brings the mass to 0.80, so the nucleus samples from A, B, C with probabilities [0.50, 0.3125, 0.1875].
Now apply temperature 0.5 before top-p. Since the original probabilities are the softmax of the original logits, we can use their logarithms as equivalent logits. Dividing those logarithms by 0.5 and exponentiating is the same as squaring the original probabilities. The squared weights sum to 0.2658. The rescaled probabilities of A and B sum to (0.16 + 0.0625) / 0.2658 = 0.8371 to four decimal places. Now the 0.75 nucleus needs only two tokens. Temperature changed the cumulative mass without changing the rank.
Filter order matters when you combine controls. At temperature one, apply top-k with k = 3 first, then normalise over those three candidates. The first two now account for 0.65 / 0.80 = 0.8125, so a subsequent top-p filter at 0.75 keeps two tokens. Applying top-p first would keep three, and a subsequent top-k of three would remove none. This NumPy implementation makes its chosen order explicit: temperature, then top-k, then top-p, then sampling.
import numpy as np
labels = np.array(["A", "B", "C", "D", "E"])
logits = np.log([0.40, 0.25, 0.15, 0.12, 0.08])
def distribution(logits, temperature=1.0, k=None, p=1.0):
order = np.argsort(-logits, kind="stable")
if k is not None:
order = order[:k]
scores = logits[order]
weights = np.exp((scores - scores.max()) / temperature)
probs = weights / weights.sum()
if p < 1.0:
cumulative = np.cumsum(probs)
keep = np.searchsorted(cumulative, p, side="left") + 1
order, probs = order[:keep], probs[:keep]
probs = probs / probs.sum()
return order, probs
for settings in ({"p": 0.75}, {"temperature": 0.5, "p": 0.75},
{"k": 3, "p": 0.75}):
ids, probs = distribution(logits, **settings)
print(labels[ids], probs.round(4))
rng = np.random.default_rng(7)
print("Sample:", labels[rng.choice(ids, p=probs)])
The sampler expects a non-empty vector of finite logits, positive temperature, a positive k if supplied, and 0 < p <= 1. Ranking before temperature scaling is equivalent here because positive scaling preserves the ordering. The last line draws from the final case; it does not always choose the most probable token. Once selected, that token becomes part of the prefix and a real model computes a new distribution for the next step. Do not assume a hosted service combines filters in the same order as this example unless its documentation says so.
How Do You Set LLM Generation Parameters in Practice?
Start with the constraint that can make the response unusable. For document questions, verify that the evidence reaches the model. For an API that expects JSON, prefer schema-constrained generation where available and validate the returned object. For a writing assistant, decide how much variation the interface should offer. Hold the model, prompt and output cap fixed while changing one sampling parameter at a time. Otherwise, you cannot tell which change affected diversity, task accuracy or termination.
This example uses Transformers with PyTorch and a small base model. It uses a plain continuation prompt because the model is not chat tuned. Install torch and transformers; the first run downloads model files. In Transformers, top_k=0 disables the top-k filter so this run can isolate the effect of temperature at a fixed top-p.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "distilgpt2"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name).eval()
inputs = tokenizer("The library opened at dawn because", return_tensors="pt")
prompt_length = inputs["input_ids"].shape[-1]
budget = 32
if prompt_length + budget > model.config.max_position_embeddings:
raise ValueError("Prompt and continuation exceed the context window")
for temperature in (0.3, 0.9):
torch.manual_seed(7)
with torch.inference_mode():
ids = model.generate(
**inputs,
do_sample=True,
temperature=temperature,
top_k=0,
top_p=0.9,
max_new_tokens=budget,
pad_token_id=tokenizer.eos_token_id,
)
continuation = ids[0, prompt_length:]
print(temperature, repr(tokenizer.decode(
continuation, skip_special_tokens=True
)))
The seed makes the comparison easier to repeat in the same environment. It does not establish that the settings consistently behave differently across inputs. Use several prompts and seeds, record the model revision and library versions, and score a task-specific outcome. For extraction, measure field-level correctness and parse failures. For document answers, check whether the cited text supports each factual claim. Record whether responses ended naturally or hit the token cap so truncation does not get mistaken for a sampling problem. See LLM evaluation and hallucination for ways to design these checks.
Some hosted APIs expose presence and frequency penalties. In a common formulation, a positive presence penalty subtracts a fixed amount from a token's logit once the token has appeared, whereas a positive frequency penalty subtracts an amount proportional to its count. These controls operate on tokens, so they can also suppress valid repetition such as a person's name or a JSON field value. Stop sequences end generation when a configured string is matched. Check whether the API returns the matched string, and test that it cannot appear inside valid content where it would terminate the answer early.
Key Takeaways
- Count tokens after chat formatting and reserve room for the continuation before adding history or evidence.
- A longer context window gives the model access to more text in a request. It does not provide persistent memory.
- Temperature changes logit gaps, which changes sampling probabilities without changing rank.
- Top-k keeps candidates by rank. Top-p keeps candidates by cumulative probability mass.
- When filters are combined, processing order and renormalisation can change which tokens survive.
- Check why generation stopped and validate structured outputs before using them downstream.
Frequently Asked Questions
Is a context window the same as conversational memory?
A context window is a limit on the sequence available during inference. Conversational memory is an application feature that stores or reconstructs state between requests. A stored preference can influence the next answer when the application sends it back as text or otherwise makes it available to the model.
Does temperature zero prevent hallucinations?
No. When a temperature of zero selects greedy decoding, it favours the highest-scoring token at each step. That token can still lead to an unsupported claim. To reduce factual errors, provide relevant evidence, check that the answer follows from it, and give the model a way to state when the evidence is insufficient.
Should I tune temperature and top-p together?
Start by changing one setting and holding the other fixed. Raising temperature often spreads probability across more candidates, while lowering top-p often removes candidates. Changing both at once can make the result hard to interpret. Use a joint parameter sweep only after you have a baseline and a metric you can compare across settings.
Why did the model generate fewer tokens than my maximum?
The maximum is a cap. The model can finish earlier by emitting an end token, and a stop sequence or serving rule can also terminate generation. On some endpoints, internal reasoning tokens share the budget with visible output. Check the termination reason and token usage rather than inferring the cause from the visible answer length.
How can I handle a document larger than the context window?
Split the document into passages, retain section and page identifiers, and retrieve passages relevant to the current question. For a whole-document summary, process sections separately and combine their summaries, checking the combined result against the sources. Increasing the generation cap cannot expose document text that was never included in the input.