LLM Batching: What It Is, How Ollama Does It, and Why It Changes Outputs
An inference server handling several requests does not compute each one on its own: it packs them into the same GPU pass. That is batching, and it is why a self-hosted LLM can serve more than one user. It has a little-known side effect: the batch size slightly changes the numbers the model produces. This article explains what batching is, how Ollama handles it with OLLAMA_NUM_PARALLEL, when it breaks reproducibility, and when the real cause is something else.
It comes from a real problem in OpenArtemis, the open source autonomous penetration testing platform I develop, where an open-weight model served by Ollama acts as the planner for several parallel agents. With identical input, goal decomposition sometimes produced 16-17 sub-goals and sometimes 2. Parallel requests were the first suspect. They turned out to be innocent, but batch shape still played a part, in a less obvious place.
Who it's for: developers and ML engineers serving open-weight models with Ollama, llama.cpp or vLLM who need comparable outputs across runs: benchmarks, regression tests, agents, extraction pipelines.
Companion article: sampling and seeds are covered in LLM seeds: why a fixed seed doesn't make outputs reproducible.
Contents
- What batching is
- Static vs continuous batching
- Prefill and decode: two different computations
- How Ollama does it: OLLAMA_NUM_PARALLEL
- Why the batch changes the numbers
- How much it matters
- The OpenArtemis case: it wasn't num_parallel
- How to test your own server
- Solutions and trade-offs
What batching is
An LLM generates text one token at a time. For each token it has to read every model weight from GPU memory: for a 30-billion-parameter model quantized to 4 bits, that is about 18 GB. The actual arithmetic for a single token is small. The bottleneck is memory bandwidth, not compute.
Batching exploits that imbalance. If two requests both need their next token, the server reads the weights once and applies them to both. Cost per token goes down, total tokens per second go up. It is what lets a single GPU serve several users, or several agents, at the same time.
Static vs continuous batching
With static batching the server collects N requests, processes them together and returns the answers when all of them are done. Fine for offline jobs, wasteful for chat: one long answer holds back the short ones.
With continuous batching, used by vLLM, SGLang, llama.cpp and therefore Ollama, the batch changes at every step. A finished request leaves, a new one joins as soon as a slot is free. At each token the batch can hold one, two or more sequences, each possibly in a different phase.
The consequence that matters here: the shape of the computation depends on what the server happens to be doing, that is, on the load, which you don't control.
Prefill and decode: two different computations
- Prefill: the model reads the whole prompt, hundreds or thousands of tokens, in chunks (in llama.cpp the chunk size is
ubatch) and fills the KV cache. It is a wide matrix computation. - Decode: the model generates one token at a time. Each step is a narrow matrix computation, as wide as the number of sequences in the batch.
With continuous batching, the prefill of a new request can land in the same pass as another request's decode. Prompt caching also changes which tokens go through prefill: if the start of the prompt is cached, only the new part is computed, in differently shaped chunks.
How Ollama does it: OLLAMA_NUM_PARALLEL
OLLAMA_NUM_PARALLEL sets how many sequences a loaded model serves at once. Since version 0.30 Ollama starts llama.cpp's llama-server with -np equal to OLLAMA_NUM_PARALLEL and a total context of num_ctx times the number of slots. The official FAQ says so: a 2K context with 4 parallel requests results in an 8K context.
Each slot has its own KV cache. In OpenArtemis, with Qwen3-Coder-30B-A3B (48 layers, 4 KV heads thanks to GQA, head dimension 64) and num_ctx 32768:
KV per slot = 2 (K and V) x 48 layers x 4 kv_heads x 64 head_dim x 32768 tokens x 2 bytes (f16)
= about 1.5 GB
On a 32 GB RTX 5090 with about 19 GB of Q4_K_M weights, two slots fit comfortably and four are tight. Memory is not the real limit, though: bandwidth is shared, so with more slots each sequence slows down while the total rises. The practical rule: OLLAMA_NUM_PARALLEL must be at least the number of workers sending requests in parallel, otherwise the extra ones queue and the parallelism is fake.
# /etc/systemd/system/ollama.service.d/parallel.conf
[Service]
Environment="OLLAMA_NUM_PARALLEL=2"
Why the batch changes the numbers
Floating-point addition is not associative. The result depends on the order of the terms:
>>> (0.1 + 1e20) - 1e20
0.0
>>> 0.1 + (1e20 - 1e20)
0.1
An LLM forward pass performs billions of additions: matrix-vector products, normalizations, attention softmax. Libraries choose how to split those sums across GPU cores based on the input shape, and the shape depends on how many sequences are in the batch. Different order, different rounding, logits that differ in the last digit.
This is documented behaviour, not theory:
- Georgi Gerganov, author of llama.cpp, on a report of differing results: "This is expected, we use different kernels for different batch sizes" (issue #23335).
- The
llama-serverREADME, undercache_prompt, warns that logits are not guaranteed to be bit-for-bit identical across batch sizes (prompt processing vs token generation), so prompt caching can cause nondeterministic results. - On CUDA, maintainers explained in detail (issue #25618) that the quantized matrix-vector product uses a different number of warps for 1 token and for 8 tokens, and that flash attention switches from an f32-query kernel to an f16-query kernel as the batch grows. In the same thread a user shows that changing only
-ubchanges greedy output on CUDA, Vulkan, Metal, SYCL and CPU.
It is not a GPU-only issue: batched matrix multiplication on CPU is not batch-invariant either.
How much it matters
A last-digit difference in a logit only changes the answer when two candidate tokens are nearly tied. Over hundreds of generated tokens that eventually happens, and from then on the two answers diverge, because every token depends on the previous ones.
The reference here is "Defeating Nondeterminism in LLM Inference" by Horace He (Thinking Machines, September 2025):
- With Qwen3-235B at temperature 0, 1000 identical requests produced 80 distinct completions, first diverging at token 103. With batch-invariant kernels, 1000 identical ones.
- The main cause is not GPU parallelism as such: a repeated forward pass with the same batch is deterministic. The cause is that load, and therefore batch size, varies between requests.
The cost of batch invariance in the same study is speed: on Qwen3-8B, from 26 to 42 seconds for the same workload with the optimized version.
The OpenArtemis case: it wasn't num_parallel
In OpenArtemis the suspicion was natural: OLLAMA_NUM_PARALLEL=2 to serve two workers, unstable goal decomposition, and a config note promising "seed 42 and temperature 0.3 for reproducible runs" that reality contradicted. Two identical HTTP requests to /v1/chat/completions returned 1676 and 2714 characters, both complete.
Reading the code, the theory didn't fully hold. Since 0.30 Ollama does not use a KV cache unified across slots: a single request on an idle server should run the same computation with one or two slots. Batching changes the numbers when two requests overlap in time, not when only one arrives.
The decisive test was to separate the two variables. Idle model, sequential requests, num_parallel kept at 2:
| Configuration | Result on identical requests |
|---|---|
| temperature 0.3, seed 42 | different outputs |
| temperature 0 (greedy) | byte-identical outputs |
Identical greedy output at num_parallel=2 clears parallel requests. But be careful about what it does not prove: it does not prove the logits are identical. Greedy always picks the most likely token, and that choice survives tiny differences. Sampling at temperature 0.3 amplifies them, because the random draw only has to land near the boundary between two tokens.
And indeed, in the Ollama 0.33.2 and llama.cpp source the seed does reach the sampler, which restarts from 42 on every request. The difference has to come from upstream, and the most likely place is the prompt cache: on the second identical request llama-server finds the prompt already cached and recomputes only the last token, on its own, in a batch of 1 rather than inside the large prefill chunk. Different kernel, logits that differ in the last digit. Still a batch-shape effect, but within a single request rather than across parallel ones. Details in the seed article.
The general lesson: greedy on an idle server separates the problems, but read it correctly. If it diverges, the numbers change even without load. If it doesn't but sampling does, the logits can still differ slightly: check the prompt cache and the parameters the server actually applies.
How to test your own server
A request file and a hash of the answer are enough. First sequentially, on an idle server:
cat > req.json <<'EOF'
{"model": "qwen3-coder", "temperature": 0,
"messages": [{"role": "user", "content": "List 20 security checks for a REST API"}]}
EOF
for i in 1 2 3; do
curl -s http://127.0.0.1:11434/v1/chat/completions \
-H 'Content-Type: application/json' -d @req.json \
| jq -r '.choices[0].message.content' | sha256sum
done
Then with two concurrent requests, which is when batching really comes into play:
for i in 1 2; do
curl -s http://127.0.0.1:11434/v1/chat/completions \
-H 'Content-Type: application/json' -d @req.json \
| jq -r '.choices[0].message.content' | sha256sum &
done; wait
Repeat both with temperature 0.3 and a fixed seed. The four combinations tell you where the problem is. If the server is shared, be careful: changing OLLAMA_NUM_PARALLEL requires restarting the service and interrupts whoever is using it.
Solutions and trade-offs
| Solution | What it fixes | Cost |
|---|---|---|
| Temperature 0 for structured tasks | Removes sampling randomness. In OpenArtemis it made decomposition identical across runs | No variety; under concurrent load a near-tie between two tokens can still flip |
Dedicated instance with num_parallel=1 | Removes request overlap for jobs that must be repeatable | Memory for a second loaded model; prompt caching remains and the first answer can differ from later ones |
Global num_parallel=1 | Same, for everyone | Worse throughput and latency for all users |
vLLM with VLLM_BATCH_INVARIANT=1 | The only documented option that holds under concurrent requests | Beta, limited GPU support, slower, Hugging Face format rather than GGUF |
SGLang with --enable-deterministic-inference | The SGLang equivalent | Restricted to some attention backends |
In llama.cpp a --batch-invariant option exists only as a draft proposal so far (PR #32081, November 2026). Worth following, but today Ollama offers no determinism guarantee under load.
OpenArtemis went with the first option: greedy decomposition, because it is a one-shot structured task where you always want the same complete answer, while the worker loop keeps the profile's temperature, where some variety helps exploration. The two-slot parallelism stayed.
Key takeaways
- Batching gets more tokens per second out of the same GPU and is on in every modern server.
- Batch size changes the order of additions and therefore, very slightly, the logits. Under variable load two identical requests can diverge even greedy.
- A single request on an idle server is not affected by parallel requests, but it can be affected by the prompt cache, which changes the batch shape between the first request and the following ones.
- Identical greedy output does not prove identical logits: it only proves the most likely token didn't change.
Related articles
- LLM seeds: why a fixed seed doesn't make outputs reproducible
- Machine learning and AI development for companies: private on-premise LLMs, AI agents and RAG
- Questo articolo in italiano
Need a private LLM you can rely on?
I install and configure open-weight models on company servers, with agents and RAG, and measure answer quality before going to production.