Local LLM Inference Benchmarking: How to Measure Tokens/s Correctly

    This article explains how to benchmark local large language model inference on limited hardware and interpret tokens/s correctly. It covers prefill and decode, memory-bandwidth limits, older-platform trade-offs, dense versus MoE models, quantization, KV cache costs, speculative decoding, cold starts, agent task latency, reproducible measurement scripts, and a practical tuning checklist.

    Introduction: What a Real-World Sample on Older Hardware Shows

    One developer shared a local-deployment experience based entirely on personal testing. The numbers come from different models and different inference engines, placed side by side for comparison. After removing vendor marketing language, the sample reveals several common signals:

    • The hardware was not new: a used server motherboard, DDR3 memory, and entry-level discrete graphics are typical low-cost-platform choices.
    • The capability was not weak: under one configuration, the model supported contexts ranging from hundreds of thousands to millions of tokens and included visual-input capability; in long-text or similar-length tasks, generation speed stayed around 30 tokens/s.
    • Speed varied significantly: across several model forms used by the same developer, generation speed differed by 2 to 5 times. The difference comes from both model structure and how the inference framework handles long context and cold starts.
    • The selection logic is changing: a medium-sized dense model with a 256k context was “retired.” A mixture-of-experts model with about 35B total parameters and about 3B active parameters became the main choice, reaching 80–100 tokens/s. Falling prices for lightweight cloud models have further weakened the cost-effectiveness of running medium dense models locally.

    These numbers come from one user’s hardware and environment. They were not produced through a controlled experiment and should not be copied directly. But they raise a serious question: on budget-limited older hardware, what determines local inference speed, and how should it be measured and optimized? This article addresses that question.


    1. First, Understand That tokens/s Is Not a Single Metric

    1.1 Prefill and Decode: Two Very Different Physical Stages

    Processing one request in a large language model generally involves two stages:

    • Prefill: all input tokens are processed in parallel. This stage is compute-intensive and often achieves throughput of thousands of tokens per second.
    • Decode: only one token is generated at a time, and each step depends on the previous one. At every step, the system must read all active model weights and the cached historical state, so decode speed is heavily constrained by memory bandwidth.

    When people discuss “how fast a model runs,” they usually mean decode speed.

    1.2 The Upper Limit of Decode Speed Is a Simple Division

    A rough model helps explain the upper limit of decode speed:

    Theoretical upper limit (tokens/s) ≈ effective memory bandwidth ÷ bytes that must be read for each generated token

    Here is a simple estimation exercise. The conclusion is sensitive to the order of magnitude:

    Comparison ~3B dense model, 4-bit weights ~27B dense model, 4-bit weights
    Weight size About 1.5–1.8 GiB About 14–16 GiB
    Theoretical limit at 400 GB/s effective bandwidth About 220 tokens/s About 25 tokens/s
    Practical expectation Dozens to hundreds of tokens/s Dozens or less

    This table explains a common intuition trap: if parameter count differs by 9 times, theoretical speed can differ by a similar factor. In reality, routing overhead, sampling logic, and KV cache access reduce actual speed. But when weights no longer fit in VRAM and must be fetched from memory or even disk, bandwidth can drop by one or two orders of magnitude, and speed can fall sharply.

    The key takeaway is this: the first choice in local deployment is not “how large a model should I use?” but “how much data must be moved for each generated token?” The later discussions of MoE and quantization are essentially about reducing that denominator.

    The example calculations are simplified for clarity. Use your own measurements for real decisions.


    2. Hardware Ledger: Why Older Platforms Can Still Work

    The hardware path for local inference can be summarized as:

    • Where weights are stored: VRAM, system memory, or disk;
    • Data-transfer channels: internal GPU memory bus, PCIe, or the system memory bus;
    • Compute units: GPU cores.

    During decoding, if any portion of the weights is stored at a lower-bandwidth level, that portion becomes the bottleneck. For example, a common dual-channel DDR3-1600 setup has a theoretical bandwidth of about 25.6 GB/s. Entry-level discrete GPU memory bandwidth is often more than 10 times higher. If about 1 GB of weights must be read from system memory for each token, this alone can take about 40 ms, corresponding to a speed ceiling of about 25 tokens/s.

    In the shared case, the memory configuration changed from a platform with about 40 GB of DDR4 to one with about 128 GB of DDR3. This seemingly “downgraded” choice was based on three considerations:

    1. Capacity determines whether the model fits: KV cache growth from very long contexts is rapid, and if weights overflow VRAM, system memory must also serve as backup.
    2. More channels can compensate for lower per-channel bandwidth: server platforms often have more memory slots, and populating them can produce meaningful aggregate bandwidth.
    3. Cost efficiency: at the same budget, older platforms often offer a clear capacity advantage.

    In other words, “lower specification” does not necessarily mean “lower performance.” The right approach is to match hardware to the bottleneck, not blindly chase single-core performance or the latest components.

    2.2 Hidden Costs of Used Server Platforms

    • Power consumption: a multi-socket platform can draw several hundred watts under load. If electricity costs are factored in, a 300 W versus 600 W difference can create a meaningful annual cost difference.
    • Single-core performance: weaker single-core CPU performance can slow serial tasks such as tokenization and post-processing.
    • Stability: used hardware requires attention to capacitor aging, dust accumulation in cooling paths, and memory compatibility. A burn-in or stress test before production use is recommended.

    3. Model Form: Dense and Mixture-of-Experts Have Different Roles

    3.1 Two Parameters: Total Parameters and Active Parameters

    For a MoE model, two parameters matter most:

    • Total parameters: determine weight storage size, loading time, and whether the model fits in VRAM;
    • Active parameters: determine how many parameters are actually computed and read for each token, directly affecting decode speed.

    For a model with about 35B total parameters and about 3B active parameters:

    • At 4 bits, weights take about 18–20 GiB, which is still challenging for older platforms’ VRAM;
    • But each token only requires reading about 3B parameters, so decode speed can be comparable to that of a 3B-class small model.

    This is why the case-study user used it for daily agent tasks: storage cost is paid according to total parameters, while speed benefit comes from active parameters. This is the essential difference between dense models and MoE models.

    3.2 Selection Approach

    • High-frequency short tasks (instruction following, function calling, simple code generation): prefer MoE models with small active parameter counts and stable tool-calling behavior.
    • Deep reasoning tasks (complex code refactoring, long-document analysis): dense models or models with larger active parameter counts may provide more stable quality. These can be sent to cloud services or run locally at lower speed.
    • Long-context tasks (whole-repository code understanding, long-document Q&A): focus on KV cache implementation and long-context evaluation, not just the officially claimed context length.

    4. Quantization: Trading Precision for Speed and Capacity

    4.1 Common Quantization Granularity

    • Weight format: named by the average number of bits per parameter. Common formats include 8-bit, 4-bit, and grouped variants. Lower bit-width means smaller weights and faster reads, but also more noticeable precision loss.
    • Activation format: some implementations quantize the KV cache to reduce VRAM usage under long contexts.
    • Caution: the same “4-bit” label can produce noticeably different sizes and accuracy depending on the quantization scheme. When comparing speed, always state the specific quantization format.

    4.2 Rules of Thumb for Choosing Quantization

    1. VRAM capacity is the first gate: first filter candidates using “model size + estimated KV cache < VRAM capacity,” then compare quality.
    2. Prefer keeping weights fully resident in VRAM: in most cases, “4-bit and fully resident” is faster than “8-bit with partial offloading.”
    3. Keep sensitive modules at higher precision if needed: attention modules and embedding layers are more sensitive to precision loss. Some schemes allow preserving higher precision in these parts, trading a small amount of speed for quality.
    4. Validate with your real tasks: use your own code tasks and Q&A tasks for A/B comparisons instead of relying only on general leaderboards.

    5. Long Context: An Underrated Performance Killer

    5.1 KV Cache Size Can Be Calculated

    Use the following estimation formula:

    KV cache bytes ≈ 2 × number of layers × number of KV heads × head dimension × context length × bytes per element

    For a hypothetical model with “64 layers, 8 KV heads, and head dimension 128” (use the actual model configuration in practice):

    1. def kv_gib(layers, kv_heads, head_dim, ctx_len, bytes_per_elem):
    2. per_token = 2 * kv_heads * head_dim * bytes_per_elem # one K and one V per token
    3. return layers * per_token * ctx_len / 1024**3
    4. for ctx in [4096, 32768, 262144]:
    5. print(f"{ctx:>7} tokens | FP16: {kv_gib(64, 8, 128, ctx, 2):6.1f} GiB"
    6. f" | 4bit: {kv_gib(64, 8, 128, ctx, 0.5):5.1f} GiB")

    With typical parameters, the results are roughly:

    Context length FP16 KV cache 4-bit KV cache
    4k tokens About 0.5 GiB About 0.1 GiB
    32k tokens About 4 GiB About 1 GiB
    256k tokens About 32 GiB About 8 GiB

    That is, the capacity of long context is often not the problem, but its cost grows linearly.

    5.2 Why Context Length Slows Things Down

    1. Attention reads: for every generated token, the system must read all historical K and V data up to that point. For a 256k context at FP16, the KV cache is about 32 GiB. Even if VRAM can hold it, reading it at every step is a significant time cost.
    2. Cache overflow: KV cache can occupy VRAM that would otherwise be used for weights, forcing some weights to be evicted and causing cascading slowdown.
    3. Long-sequence attention implementation: some implementations change their computation pattern as sequence length grows, potentially reducing decode speed further.

    This may also explain an apparently contradictory observation from the case: “around 21 tokens/s in tens-of-thousands-token contexts, while long tasks can stay stable at around 30 tokens/s.” The short-context peak may occur when the KV cache is still small and the sequence length has not grown much. The long-task average is the result of combining multiple stages. A speed number without context length is essentially meaningless.

    5.3 Common Ways to Reduce Long-Context Cost

    • Quantize the KV cache, such as 8-bit or 4-bit;
    • Use more cache-efficient attention designs, such as grouped-query attention (GQA);
    • Chunk long documents and use retrieval-augmented generation (RAG), placing only relevant fragments in context;
    • Enable KV cache reuse so multi-turn conversations share the same prefix and avoid repeated prefill;
    • Disable the visual encoder when image input is not needed; do not load visual modules unnecessarily.

    6. Speculative Decoding: Speed Without Changing the Model

    6.1 Principle: Small Model Drafts, Large Model Verifies

    The basic speculative-decoding flow is:

    1. A lightweight “draft” source guesses multiple candidate tokens in sequence;
    2. The large model verifies these candidates in parallel with one forward pass;
    3. The accepted prefix is kept; rejected positions are resampled by the large model.

    Because the large model must read all weights at every step, verifying several extra candidate tokens adds almost no additional memory reads. The higher the acceptance rate, the more obvious the speedup. When the acceptance rate is high, the improvement can be substantial, and no retraining of the model is required.

    6.2 Costs and Risks

    • Extra overhead: the drafting stage requires additional compute or VRAM. Older platforms with limited VRAM should evaluate this carefully.
    • Hit rate depends on content: highly patterned scenarios such as code completion and structured output usually have higher hit rates. Open-ended writing may have lower hit rates and can even become slower because of drafting overhead.
    • Validation method: compare “enabled” and “disabled” versions on your real tasks, focusing on decode speed rather than time to first token.

    7. Inference Frameworks and Cold Start: An Overlooked Experience Variable

    7.1 What a Cold Start Includes

    A typical cold start includes:

    1. Reading weight files, affected by disk and file-system caching;
    2. Deserialization and memory allocation;
    3. Uploading to VRAM;
    4. Initialization work such as graph capture and warmup.

    7.2 Why Cold Starts Matter Especially for Agent Scenarios

    • Many single-turn tasks: for one-off small tasks, loading time can be a major part of total time;
    • Frequent service restarts: when switching models or restarting services often, loading time is paid repeatedly;
    • Interactive experience: users directly notice the wait from clicking to seeing the first token.

    The case-study user mentioned that one class of framework had cold-start speed around 3 times that of common inference frameworks. For frequently started and stopped scenarios, this can mean a difference of several seconds to tens of seconds per task.

    7.3 How to Measure and Optimize

    • Measure: time from process start to receiving the first token; run multiple trials and take the median.
    • Stay warm: keep the model resident in memory or leverage file-system caching to avoid cold loading every time.
    • Choose formats: prefer weight formats that support zero-copy or fast deserialization.
    • Fix resources: avoid competing with other high-load processes for memory and I/O bandwidth.

    8. Agent Scenarios: From tokens/s to Task Completion Time

    8.1 The Token Bill of an Agent Task

    A complete agent task usually includes multiple rounds of “model inference — tool call — result feedback.” Input tokens are often much larger than output tokens. Suppose:

    • Each turn has 8k input tokens, with a prefill throughput of 400 tokens/s;
    • Output is 500 tokens, with a decode speed of 15 tokens/s.

    Then the per-turn time is approximately: 8000 ÷ 400 + 500 ÷ 15 ≈ 20 + 33 = 53 seconds.

    Bottleneck improvement Per-turn time Relative improvement
    Current state About 53 s Baseline
    Decode speed 15 → 30 tokens/s About 37 s About 30%
    Also improve prefill throughput 400 → 1000 tokens/s About 25 s About 53%

    Conclusion: improving decode speed brings clear benefits, but improving prefill and reducing repeated context can also significantly shorten task time.

    8.2 Differences Between Thinking and Output Stages

    The case mentions that in programming tasks, the speed of the “thinking stage” and the “output stage” can differ, with the former usually being lower. Possible reasons include:

    • The thinking stage has a longer context and a larger KV cache;
    • Thinking text and final output have different content distributions, which may affect speculative-decoding acceptance rates.

    For this kind of phenomenon, the reasonable approach is to measure the speed of each stage separately rather than reporting a single “average tokens/s.”

    • Task success rate: whether the task can be completed within a limited number of rounds;
    • End-to-end time: wall-clock time from task submission to final result;
    • Interactive latency: time to first token plus perceived typing speed;
    • Resource usage: whether VRAM, memory, and CPU usage remain stable.

    9. A Reproducible Benchmarking Method

    9.1 What to Measure: Four Core Metrics

    Metric Meaning Typical use
    Time to first token (TTFT) Time from request to the first output token Interactive experience, cold start
    Prefill speed Number of input tokens processed per second Long documents, agent scenarios with large inputs
    Decode speed tokens/s during generation Daily conversation, code generation
    End-to-end time Total time for a complete task Overall judgment

    9.2 How to Test: A Variable-Control Checklist

    1. Fix hardware and driver versions; record CPU, GPU, and memory specifications.
    2. Fix the model quantization format and inference framework version.
    3. Fix sampling parameters such as temperature, top_p, and max_tokens.
    4. Fix context length and test different lengths separately, such as 4k, 32k, and 128k.
    5. Warm up 2–3 times per configuration, then run at least 5 formal measurements and take the median.
    6. Record VRAM/memory usage and temperature changes to check for throttling.

    9.3 Example Measurement Script

    The script below measures streaming responses, such as those using SSE, and times tokens individually. It relies only on the standard library and can work with most OpenAI-style local inference services:

    1. import time
    2. import json
    3. import statistics
    4. import urllib.request
    5. BASE_URL = "http://localhost:8000/v1" # Change to your local inference service address
    6. def measure_once(model, prompt, max_tokens=256):
    7. payload = {
    8. "model": model,
    9. "messages": [{"role": "user", "content": prompt}],
    10. "max_tokens": max_tokens,
    11. "temperature": 0.0,
    12. "stream": True,
    13. }
    14. req = urllib.request.Request(
    15. f"{BASE_URL}/chat/completions",
    16. data=json.dumps(payload).encode(),
    17. headers={"Content-Type": "application/json"},
    18. )
    19. start = time.perf_counter()
    20. first_token_at, last_token_at, n_tokens = None, None, 0
    21. with urllib.request.urlopen(req, timeout=300) as resp:
    22. for raw in resp:
    23. if not raw.startswith(b"data:"):
    24. continue
    25. chunk = raw[5:].strip()
    26. if chunk == b"[DONE]":
    27. break
    28. data = json.loads(chunk)
    29. delta = data["choices"][0].get("delta", {}).get("content", "")
    30. if not delta:
    31. continue
    32. now = time.perf_counter()
    33. if first_token_at is None:
    34. first_token_at = now
    35. last_token_at = now
    36. n_tokens += 1
    37. end = time.perf_counter()
    38. return {
    39. "ttft_ms": (first_token_at - start) * 1000,
    40. "decode_tps": (n_tokens - 1) / (end - first_token_at) if n_tokens > 1 else 0,
    41. "tokens": n_tokens,
    42. "total_s": end - start,
    43. }
    44. def benchmark(model, prompt, runs=5):
    45. warmup = measure_once(model, prompt, max_tokens=32)
    46. results = [measure_once(model, prompt) for _ in range(runs)]
    47. print(f"TTFT median: {statistics.median(r['ttft_ms'] for r in results):.0f} ms")
    48. print(f"Decode speed median: {statistics.median(r['decode_tps'] for r in results):.1f} tokens/s")
    49. print(f"Output token median: {statistics.median(r['tokens'] for r in results):.0f}")
    50. if __name__ == "__main__":
    51. benchmark(
    52. "local-model",
    53. "Please implement an HTTP request function with retry logic in Python, and briefly explain the approach."
    54. )

    Note: Some inference services send the first token together with control information such as the role field in a streaming response. In that case, TTFT measurement may need to be adjusted to match the service’s actual behavior. Output token count can also prefer the usage field at the end of the response.

    9.4 Preparation Before Testing

    • Use fixed-text prompts to avoid large differences in output length between runs.
    • For the same model, measure the “thinking stage” and “final output stage” separately if needed, and report stage-specific results.
    • If using a model with tool-calling capability, measure end-to-end time with real tool calls when testing cold start and long-task stability.

    10. Tuning Checklist: Getting the Most From Older Hardware

    Goal Method Explanation
    Improve decode speed Use 4-bit weights and keep them fully resident in VRAM Reduce bytes read per token
    Improve decode speed Enable speculative decoding Works well for code-like tasks
    Improve decode speed Reduce context length when appropriate Reduce KV reads and attention overhead
    Reduce VRAM pressure Quantize the KV cache Clear benefit in long-context scenarios
    Reduce VRAM pressure Use chunked prefill Reduce instantaneous peaks for long inputs
    Reduce VRAM pressure Disable unnecessary visual/multimodal modules Reduce resident VRAM
    Shorten startup time Keep processes resident and leverage file-system caching Avoid frequent cold loading
    Shorten startup time Choose weight formats that support fast deserialization Reduce loading time
    Improve task efficiency Reuse prefix caches Multi-turn conversations can share the same history
    Improve task efficiency Trim system prompts and history Directly reduce prefill tokens

    11. Cost and Positioning: From More Parameters to the Right Fit

    The case-study user noted that after lightweight cloud models became cheaper, the need to run medium dense models locally decreased. This reflects a broader trend:

    • Cloud services: billed by tokens, with no hardware-maintenance burden; suitable for low-frequency or high-difficulty tasks.
    • Local deployment: requires upfront hardware investment, but has low marginal cost and keeps data inside the private network; suitable for high-frequency short tasks, privacy-sensitive scenarios, and offline environments.
    • Hybrid mode: local models handle daily requests, while requests involving very long contexts or high difficulty fall back to cloud APIs. Cloud inference services can scale elastically on demand and complement local systems.

    For local users, a more realistic selection principle is:

    1. Start with the task: high frequency, short input, strong privacy → local; low frequency, long context, strong reasoning → cloud.
    2. Then look at hardware: make sure the model fits in VRAM, leave enough memory headroom, and prefer higher bandwidth.
    3. Finally choose the model: among candidates, prefer MoE models with small active parameter counts, strong tool-calling ability, and long-context support.

    Conclusion

    The numbers from the shared case can be reduced to explainable engineering facts:

    • Usable speed on older hardware comes from the combination of “small weights, few active parameters, and sufficient bandwidth,” not from the hardware being powerful.
    • Long-context capability is essentially a trade-off between KV cache and VRAM capacity.
    • Speed differences largely come from model structure and details in the inference framework.
    • Daily agent tasks were assigned to MoE models with very few active parameters, a typical trade-off of “paying full storage cost but receiving a speed discount.”

    For local deployment users, three questions matter more than “how many tokens/s did someone else achieve?”:

    1. Where is my bottleneck?
    2. How many tokens/s do my tasks actually need?
    3. How much more can I extract from my hardware?

    Using the measurement methods and tuning checklist in this article, you can quantify step by step, validate item by item, and turn older equipment into a stable, usable private inference platform.