Sub topic 8
Context window, temperature, and other parameters
This chapter assumes you can run a model with ollama run, send JSON to the local REST API, and read a Modelfile. It covers the settings that change how a model behaves: how much text it can hold in memory, and how it picks each next token. Setting these well often matters more than switching to a different model.
Two kinds of settings
A model's weights are fixed once you pull it. Ollama exposes two groups of settings that you can change without touching the weights.
- Runtime settings control resources. The main one is the context window,
num_ctx. - Sampling settings control how the next token is chosen from the model's probability distribution. These include
temperature,top_k,top_p, andseed.
A third group limits output, such as num_predict and stop. All of them are called options in Ollama.
The context window
The context window is the maximum number of tokens the model can consider at once. A token is a chunk of text, often a short word or part of a word. In English, one token is about four characters on average.
Everything shares this one budget:
- the system prompt
- the earlier messages in the conversation
- your new prompt
- the reply the model is writing
In Ollama this size is the num_ctx option.
The default is small
The default num_ctx has changed between Ollama versions. Older releases used 2048 tokens, and newer ones use a larger default. Do not assume a value. Check what your install does with ollama show llama3.2 and by testing a long prompt.
The default is often much smaller than what the model supports. The model's trained maximum, shown as context length in ollama show, may be 128000 or more. Ollama does not use that full length unless you ask for it.
What happens when you exceed it
When the total goes over num_ctx, Ollama drops the oldest tokens to make room. The model then behaves as if the dropped text never existed. Typical symptoms:
- It forgets instructions you gave at the start of a long chat.
- It ignores the beginning of a long document you pasted in.
- It contradicts something said earlier.
Because the system prompt sits at the start, it is a common casualty. If a model "stops following the rules" in a long conversation, suspect the context window before blaming the model.
The cost of a bigger window
Memory for the attention cache (the KV cache) grows with num_ctx. Doubling the window roughly doubles that cache. It adds to the memory used by the weights, as the previous chapter described. A larger window also makes each response slower to start, because the model must process more input.
If the model plus cache no longer fits in GPU memory, Ollama moves some layers to the CPU, and speed drops sharply. Raise num_ctx only as far as your task needs.
Sampling parameters
At each step the model produces a probability for every possible next token. Sampling parameters decide how one is picked.
| Option | What it does | Typical range |
|---|---|---|
| `temperature` | Scales randomness. Low values favor the most likely token. High values flatten the odds. | 0 to 1.5 |
| `top_k` | Considers only the K most likely tokens. | 10 to 100 |
| `top_p` | Considers the smallest set of tokens whose probabilities add up to P. | 0.5 to 1.0 |
| `seed` | Fixes the random number generator. | any integer |
| `repeat_penalty` | Discourages repeating recent tokens. | 1.0 to 1.3 |
| `num_predict` | Maximum tokens to generate. `-1` means no limit. | -1 or a number |
| `stop` | Strings that end generation when produced. | list of strings |
Choosing temperature
Use a low temperature (0 to 0.3) for tasks with one right answer, such as extraction, classification, code, and summaries. Use a moderate one (0.7 to 1.0) for brainstorming and creative writing. Very high values tend to produce incoherent text.
A temperature of 0 makes the model pick the most likely token every time. This is close to deterministic, but not a guarantee. Results can still differ across hardware, versions, or batch sizes.
Combining top_k, top_p, and temperature
These settings interact. Temperature reshapes the odds, and top_k and top_p cut off the unlikely tail. Change one at a time, and test with the same prompt. Adjusting all three at once makes it impossible to tell which one changed the result. The model's library page often lists recommended values, and a model's default parameters are visible in ollama show.
Reproducible output
To get repeatable output for a test, set seed to a fixed number and temperature to 0 (or at least keep both constant). Keep the model, prompt, and options identical too.
Setting parameters in three places
You can set the same options in three ways. They apply at different scopes.
- Interactively, for one chat session only.
- In a request's
optionsobject, for one API call. - In a Modelfile with
PARAMETER, as the saved default of a custom model.
In an interactive session
ollama run llama3.2
>>> /set parameter num_ctx 8192
>>> /set parameter temperature 0.2
>>> /show parametersThese changes last until you exit. /show parameters prints the current values.
In an API request
Put sampling and runtime options inside options. The example below sends a low-temperature, seeded request with a larger context window and a reply cap.
import requests
resp = requests.post(
"http://localhost:11434/api/chat",
json={
"model": "llama3.2",
"messages": [
{"role": "user", "content": "List three uses of a hash map."}
],
"stream": False,
"options": {
"temperature": 0.2,
"seed": 42,
"num_ctx": 8192,
"num_predict": 200,
"stop": ["\n\n\n"],
},
},
timeout=120,
)
resp.raise_for_status()
data = resp.json()
print(data["message"]["content"])
print("prompt tokens:", data["prompt_eval_count"])
print("reply tokens:", data["eval_count"])
print("stopped because:", data["done_reason"])The response reports token counts. prompt_eval_count is how many tokens of your input were processed. eval_count is how many the model generated. Compare prompt_eval_count with num_ctx to see how close you are to the limit.
done_reason tells you why generation ended. The value stop means the model finished naturally or hit a stop string. The value length means it reached num_predict or the context limit, and the answer may be cut off mid-sentence.
In a Modelfile
Use PARAMETER lines to make settings permanent for a custom model:
FROM llama3.2
PARAMETER temperature 0.2
PARAMETER num_ctx 8192
PARAMETER stop "<END>"You can repeat PARAMETER stop to add several stop strings. Request-level options override the Modelfile values for that call.
Common errors
- The model forgets early instructions. The conversation exceeded
num_ctx. Raise it, shorten the history, or restate key rules. - Answers end abruptly.
num_predictis too low, or the context filled up. Checkdone_reason. - Options seem ignored. In the REST API, options must be inside
options, not at the top level. A top-leveltemperaturehas no effect. - A misspelled option has no visible effect. Check the spelling against the Ollama API documentation.
- Slowdown after raising
num_ctx. Runollama ps. If the PROCESSOR column shows a CPU/GPU split, the larger cache pushed part of the model off the GPU. - Changing
num_ctxreloads the model. A different context size means the loaded instance no longer matches, so the next request pays a loading delay.
Exercise
A chat with llama3.2 works well for ten turns, then the model stops following the system prompt's rule to "always answer in French". Name the most likely cause, two ways to check it, and two ways to fix it.
Show answer
The most likely cause is that the conversation exceeded num_ctx, so the oldest tokens, including the system prompt, were dropped. To check, compare prompt_eval_count in the API response with num_ctx, and look at the context length and parameters shown by ollama show. To fix it, raise num_ctx (for example with /set parameter num_ctx 8192 or options.num_ctx), or shorten or summarize the chat history, or repeat the rule in the latest message. Raising num_ctx costs more memory, so watch ollama ps for a CPU/GPU split.
Exercise
You need an extraction script to return the same output on repeated runs, and replies must never exceed 100 tokens. Which options do you set in the request, and where do they go?
Show answer
Inside the options object of the request, set temperature to 0 (or a low value), seed to a fixed integer, and num_predict to 100. Keep the model, prompt, and other options identical between runs. Check done_reason: a value of length means the reply was cut off at the cap.