Measuring and Optimizing Local LLM Generation Speed: A Reproducible Guide
Local LLM speed comparisons often mix prefill throughput, decode throughput, short-prompt peaks, and long-context steady-state performance into a single number. This article explains how to define comparable metrics, build a reproducible three-stage benchmark, identify hardware, model, and software bottlenecks, and optimize quantization, context management, KV cache, speculative decoding, and deployment choices without sacrificing quality.
Measuring and Optimizing Local LLM Generation Speed
When deploying large language models locally, tokens per second is often the first metric people compare. A common complaint in community discussions is that peak throughput looks high, but speed drops on long tasks. The cause is usually not a single misconfigured parameter. More often, prefill speed, decode speed, short-prompt peaks, and long-context steady state are all being mixed into one number. To make speed figures comparable and reproducible, define the measurement method first, then optimize each bottleneck in turn.
First, Clarify What You Are Measuring
A token is the basic unit a model processes. It is not equivalent to a Chinese character or an English word. The same Chinese text can produce different token counts under different tokenizers. When comparing models, fix the evaluation text and record token counts at the same time rather than looking only at character length.
Generation involves at least two phases:
- Prefill: The prompt and historical context are sent through the model at once. Computational cost grows roughly with context length and places more demand on compute and memory capacity.
- Decode: New tokens are produced one by one, or several at a time with speculative decoding. Each step must read a large number of weights and is often more constrained by memory bandwidth.
When reporting a single “tokens/s” figure, state whether it is prefill throughput before the first token or stable decode throughput, and whether it includes reasoning, tool-call waiting, and logging. Interactive experience is often determined by time to first token (TTFT). Batch jobs care more about sustained decode throughput and the number of tasks completed per unit of time.
Why the Same Model Can Show Very Different Speeds
On the hardware side, weights are read during every decode step. Larger parameter counts and higher precision increase bandwidth pressure. Replacing memory with a higher-capacity but lower-bandwidth specification can allow a larger context to fit while reducing decode speed. This is a classic capacity-versus-bandwidth tradeoff. “More memory” does not automatically mean “faster.”
On the model side, dense models and mixture-of-experts (MoE) models cannot be compared directly by total parameter count. An MoE model activates only a subset of experts at each step, so compute and memory access are closer to the active parameter count. This often makes MoE models faster for everyday agent tasks. However, expert routing, caching, and load imbalance can make long-task variance higher than with dense models.
Quantization changes precision, size, and bandwidth at the same time. Lower-bit weights substantially reduce the amount read during each decode step, so speed usually increases. Extreme quantization can still harm code, math, and long-document consistency. When comparing speed, always specify the quantization level, context limit, and whether speculative decoding is enabled. Speculative decoding uses a smaller model or draft mechanism to propose multiple tokens at once, which the target model then verifies. Decode throughput rises clearly when proposals are accepted. When the draft hit rate falls, the benefit shrinks. Instantaneous peaks in logs should not be treated as full-run averages.
On the software side, inference engine kernel implementations, cache layout, thread pinning, and whether the context cache is placed in a faster storage tier all change results. Asking a general-purpose coding assistant to “generate a startup script” can get a run working quickly, but if the script does not record context length, parallel threads, batch size, and sampling parameters, the result cannot be reproduced later.
A Reproducible Speed-Testing Method
Split testing into three stages: short prompt, medium context, and long task. Run each stage multiple times and discard the first run to exclude loading and compilation warm-up. Record the following: model size and architecture type, quantization method, maximum context, actual input tokens, output tokens, batch size, sampling temperature, hardware memory capacity and approximate bandwidth tier, and whether speculative decoding is enabled.
The timing logic below is illustrative. The key is to measure prefill and decode separately rather than printing only an average:
t0 = now()prefill(prompt)t1 = now()n = 0while n < target_new_tokens:step = decode_once() # if speculative decoding is enabled, step may be > 1n = n + accepted(step)t2 = now()prefill_tps = prompt_tokens / (t1 - t0)decode_tps = n / (t2 - t1)
For long tasks, generate continuously or run multiple conversation turns until the context approaches the target length, and observe whether speed falls from a high level to a plateau. The plateau is the appropriate figure for “stable speed.” At the same time, record GPU or system memory usage, whether swapping to disk occurs, and any frequency reduction caused by thermal limits. Once swapping occurs, token speed drops sharply. This is a capacity problem, not a sudden slowdown of the model.
When comparing configurations, keep the evaluation set unchanged: one short question-and-answer sample, one code-completion sample, and one summarization sample that requires long context. Code and strong reasoning tasks use different sampling and stopping conditions. If the thinking phase is counted as output, report “thinking speed” and “visible-answer speed” separately to avoid mixing them with ordinary chat throughput.
Which Optimization Levers to Pull First
1. Confirm the bottleneck. If throughput rises nearly linearly as batch size increases, the system is probably not yet saturating bandwidth or compute. If increasing batch size produces almost no gain and latency worsens noticeably, the system is close to its bandwidth or cache limit. In personal interactive use, batch size is usually 1. The optimization target should be single-stream decode and TTFT, not the machine’s maximum throughput.
2. Match quantization to the task. Everyday assistants and retrieval-based question answering can use more aggressive lower-bit weights to gain speed. Coding and tasks that require strict formatting should retain higher precision or use better-quality quantization, with fixed test cases for regression rather than speed alone.
3. Control context. Very long context amplifies prefill time and increases KV cache usage. If knowledge can be retrieved externally, there is no need to put all history into the window. KV cache layout and reuse have a major impact on speed for the second and later turns of multi-turn conversations.
4. Use speculative decoding carefully. It suits continuations with a high draft hit rate and stable style. For highly varied task distributions with many rejected samples, check the acceptance rate. If acceptance is low, disable speculative decoding or change the draft strategy; otherwise, extra computation can cancel out the benefit.
5. Avoid unrecorded script drift. Put startup parameters under version control: context length, thread count, batch size, quantization file checksum, and random seed. Before and after an inference engine upgrade, compare results with the same three-stage test. Keep only changes that improve speed or at least do not harm quality.
6. Separate local and cloud responsibilities. Local deployment suits low-latency, data-sensitive interactions where hardware limits are acceptable. Batch evaluation, elastic concurrency, and jobs that need more stable bandwidth are better suited to cloud environments with elastic compute, object storage, and monitoring and alerting. When using cloud resources such as Baidu AI Cloud, report results with the same prefill and decode definitions. Do not treat an instance peak as the business steady state.
How to Read Speed Numbers from Others
When you see “over forty” or “stable within a certain range,” ask five questions first: Is this peak or full-run average? How long is the prompt? How long is the output? Does it include speculative decoding? Does hardware bandwidth match the parameter scale? Short logs that spike and long tasks that fall back are normal. An MoE model may have a larger total parameter count but a smaller active parameter count, making it faster for everyday tasks. That does not mean it maintains the same ratio under very long context.
It is more useful to break requirements apart. Interactive use needs fast TTFT and stable single-stream decode. Offline batch processing needs total throughput under high concurrency. Coding tasks need acceptable speed while preserving format and correctness. The main model can switch by scenario: a faster model with a small active parameter count can handle everyday agent steps, while a larger or higher-precision model handles difficult reasoning. Do not use one speed number to decide all workloads.
The goal of speed optimization is not a leaderboard maximum. It is predictable long-task decode throughput under a fixed quality threshold, with a test method that can be reused. Split the metrics, document the configuration, and measure repeatedly with the same evaluation set. Only then does the question “what speed is everyone getting?” become meaningful.
