On-Device LLM Inference: A Practical Guide to Local Testing and Benchmarking

    This guide explains how to run large language model inference locally on edge devices, covering why teams move inference off centralized cloud infrastructure, how to choose an inference framework and runtime, how to organize model files for reproducible experiments, and how to benchmark three common configurations: a baseline dense model, a dense model with speculative decoding, and a model from another family with multi-token prediction. It defines shared metrics such as time to first token, decode throughput, prefill throughput, peak memory, and acceptance rate, then outlines where acceleration gains actually hold, common pitfalls, and how on-device and cloud capabilities divide the work.

    1. Why Move LLM Inference to the Device

    One of the clearest technical shifts of the past two years is that large language model deployment is spreading outward from centralized data centers to end devices. Three forces are driving this.

    Data compliance and privacy. When inputs contain code snippets, internal documents, or personal user data, keeping that data on the local machine shortens the trust chain and makes internal audits easier to pass.

    Cost structure. Cloud inference is billed per call, so bills become hard to predict when load fluctuates. On-device inference has a marginal cost close to zero, with the hardware investment paid once.

    Latency predictability. Local inference skips the round trip over the public internet, so jitter in time to first token and decode rate comes mainly from local load and is easier to control.

    To be clear, on-device inference is not a universal answer. Unified memory architectures typically offer less available bandwidth than a discrete GPU, and bandwidth quickly becomes the bottleneck with long contexts. Devices also cannot host models with extremely large parameter counts. On-device inference therefore suits medium-sized, quantized models built for one or a few tasks.

    2. How to Choose an Inference Framework and Runtime

    Before writing any code, settle the dimensions that matter for framework selection rather than copying someone else’s recommendation list.

    • Model format compatibility: whether the framework natively supports your model’s architecture, especially how attention variants are implemented.
    • Quantization format support: whether common integer quantization formats are supported and can be loaded directly without conversion.
    • Memory-mapped loading: whether weights can be read through memory mapping, so first load time benefits from the operating system page cache.
    • Backend portability: whether the backend can switch across accelerators from different vendors, integrated GPUs, and plain CPUs.
    • Observability: whether the framework reports tokens per second, time to first token, and peak memory, which makes side-by-side comparison possible.

    The tests in this article all use a lightweight inference framework in the same class: multi-backend, with memory-mapped weight loading. Model files were downloaded to local disk ahead of time so that network fluctuations would not add noise to the measurements.

    3. Preparing Model Files and Directory Layout

    The first step toward a reproducible experiment is pinning down the environment and the materials. A suggested layout:

    1. local-llm/
    2. ├── models/
    3. │ ├── config-a/ # Config A: medium-sized dense model
    4. │ ├── config-b/ # Config B: same-size model + decode acceleration module
    5. │ └── config-c/ # Config C: another model family + multi-token prediction head
    6. ├── prompts/ # Fixed evaluation prompt set
    7. ├── results/ # Raw outputs and metrics
    8. └── env/ # Runtime version records

    Checklist for preparing materials:

    1. Record the model source and checksum so every run loads the same weights.
    2. Pin the tokenizer and chat template versions; template differences directly change output style and token counts.
    3. Fix the sampling parameters, including temperature, top-p threshold, repetition penalty, and maximum generation length.
    4. Record the runtime version and quantization format, since operator implementations differ between versions and affect performance.

    4. Test Design for Three Configurations

    The three combinations in the source material can be generalized into a baseline dense model, a dense model with decode acceleration, and another model family with multi-token prediction. Here is a shared test protocol.

    Config A: a medium-sized dense model with token-by-token autoregressive decoding, serving as the performance baseline.

    Config B: the same model with speculative decoding. A lightweight draft source first proposes several candidate tokens in a row, then the main model verifies them all in parallel in a single pass, and the accepted prefix length becomes the output for that round. It does not change the output distribution, assuming the verification strategy is correct; it only changes the generation path.

    Config C: another model family with a multi-token prediction head enabled, so the model predicts several upcoming positions in one forward pass. The auxiliary objective introduced during training is used at inference time to reduce the number of serial steps.

    Shared metric definitions:

    • Time to first token: time from request submission to the first returned token.
    • Decode rate: tokens per second during generation, excluding prefill.
    • Prefill rate: tokens per second while processing the input prompt.
    • Peak memory: peak resident memory for the process plus GPU (or unified) memory usage.
    • Acceptance rate: the share of candidate tokens accepted per round in speculative decoding, the core variable for measuring speedup.

    Illustrative test driver logic:

    1. def run_case(model, prompt, gen_cfg, rounds=3):
    2. metrics = []
    3. for _ in range(rounds):
    4. t0 = now()
    5. first = None
    6. tokens = 0
    7. for tok in stream(model.generate(prompt, **gen_cfg)):
    8. if first is None:
    9. first = now() - t0 # time to first token
    10. tokens += 1
    11. total = now() - t0
    12. metrics.append({
    13. "ttft": first,
    14. "decode_tps": tokens / (total - first),
    15. "peak_mem": peak_memory(),
    16. "accepted": getattr(model, "accepted_ratio", None),
    17. })
    18. return summarize(metrics) # take the median to reduce jitter

    5. Reading the Results: Where Acceleration Actually Pays Off

    Without citing specific product data, it is still possible to state patterns commonly observed in the industry, as a reference for interpreting your own measurements.

    First, the gains from speculative decoding depend heavily on task entropy. Tasks with high predictability, such as code completion, structured output, and fixed-template extraction, usually see high acceptance rates and clear end-to-end speedups. High-entropy tasks such as open-ended writing and multi-turn debate see more candidates rejected, so the gains narrow, and in extreme cases the extra verification overhead makes things slightly slower.

    Second, the gains from a multi-token prediction head depend on consistency between training and inference. If the number of heads used at inference does not match the training configuration, acceptance rates drop significantly.

    Third, the bottleneck moves. Once decoding is accelerated, prefill and memory bandwidth often become the new constraints, which is especially visible with long prompts. This is why an evaluation must report prefill rate as well, or it risks drawing a one-sided conclusion.

    Fourth, quantization improves capacity efficiency but may hurt the stability of long reasoning chains. Run the same prompt set before and after quantization and compare output consistency, not just speed.

    6. Common Pitfalls and a Troubleshooting Checklist

    • Slow first load: usually disk reads and weight dequantization overhead; memory mapping and a warm-up request can help.
    • Large rate jitter: check for background sync, log writes to disk, or thermal throttling.
    • Repetitive output: adjust the repetition penalty and sampling parameters first rather than blindly enlarging the context.
    • Out of memory: reduce context length or switch to a lower-bit quantization, and check whether unnecessary cache reuse is enabled.
    • Non-reproducible results: fix the random seed, runtime version, and thread count, and keep the raw outputs.

    7. Dividing Work Between Device and Cloud

    On-device and cloud are not substitutes; the more sensible shape is a division of labor. Model repositories and version hosting, structured archiving of evaluation results, and batch replay of long tasks can be handled by object storage and container platforms. Observability for online services can rely on logging services and monitoring and alerting systems. Compute-heavy work such as model training and fine-tuning belongs on elastic compute, after which the quantized artifacts are pushed down to devices. In scenarios like these, Baidu AI Cloud typically supplies general capabilities such as model hosting, elastic compute, and data governance.

    8. Conclusion

    Getting a medium-sized model running locally is not hard. What is hard is building an evaluation method that is reproducible, comparable, and explainable. Pin down the materials, define the metrics clearly, and keep the shifting-bottleneck effect in view, and only then does a claim like “this configuration is faster” carry real engineering value.