Model Inference: Core Concepts, Key Metrics, and Performance Optimization Strategies

    This article provides a comprehensive introduction to AI model inference—the stage where trained models deliver real business value. It explains the difference between inference and training, breaks down the prefill and decode phases of LLM inference, defines the three core performance metrics (latency, throughput, and cost), and examines the key factors that constrain inference performance, including model size, memory bandwidth, KV cache, and request scheduling. It also covers mainstream optimization techniques at the model, system, and hardware levels—quantization, pruning, distillation, prefix caching, continuous batching, speculative decoding, and more—along with engineering practices for production deployment and cost analysis. Readers will gain a systematic framework for benchmarking, optimizing, and operating inference services.

    1. What Is Inference?

    Inference is the application stage of an AI model. Once training is complete and the model’s parameters are fixed, the system feeds new input data into the model, which performs computation, analysis, and prediction based on the patterns it learned during training, and then produces an output. The output can be a piece of text, a classification label, or a business decision.

    Inference is where a model’s capabilities translate into real value. Even if a model performs well on evaluation benchmarks, it cannot support production workloads if it responds slowly or costs too much to run. Training and inference therefore form the two ends of the AI workflow: training determines what a model can do, while inference determines how fast and how cheaply it can do it.

    In large language model (LLM) scenarios, each inference call typically involves two phases. The first is prefill, where the model processes the entire input prompt in one pass, computing and storing intermediate states. The second is decode, where the model generates output tokens one at a time, with each new token depending on the full preceding context. The decode phase is usually memory-bandwidth-bound, while the prefill phase is more compute-bound, so the two phases call for different optimization strategies.

    2. The Fundamental Differences Between Inference and Training

    Training and inference have different goals, and therefore different optimization priorities.

    The training phase focuses on model accuracy and generalization. Engineers use large-scale datasets, backpropagation, and many iterations to make the model perform reliably on unseen data. Training is typically an offline task that can run for days or even weeks, with costs concentrated in a one-time investment.

    The inference phase, given an acceptable level of accuracy, pursues low latency, high throughput, and low per-unit cost. Inference is usually an online service: requests arrive at any time, and users are highly sensitive to waiting time. Inference costs accumulate continuously with call volume—the larger the volume, the more that per-request cost optimization translates into meaningful overall savings.

    The two phases also make different trade-offs in numerical precision. Training typically uses higher-precision number formats to keep gradients stable, while inference can use lower-precision representations as long as errors stay within acceptable bounds. This is the foundation of the quantization techniques discussed later.

    3. Three Core Metrics for Measuring Inference Performance

    Evaluating an inference system requires looking at all three of the following metric categories together; focusing on just one easily leads to one-sided conclusions.

    1. Latency

    Latency is the time from when a request is sent to when the complete response is received. In streaming scenarios, you also need to track Time to First Token (TTFT) separately, since it determines how quickly users see the first character. Engineering practice typically focuses on percentiles such as P50, P95, and P99, because averages can hide long-tail problems.

    2. Throughput

    Throughput is the number of requests or generated tokens the system can complete per unit of time. Higher throughput means the same hardware can serve more users. Throughput and latency are usually in tension: larger batches increase throughput, but individual requests may wait longer.

    3. Cost

    Cost can be broken down into hardware cost and energy cost. For teams billed per call or running their own clusters, the per-request cost formula can be written as:

    Per-request cost = compute-resource time occupied per request × unit resource price

    The essence of cost optimization is reducing the resource time occupied by each request, or improving the utilization of each unit of resource, under the same latency and accuracy constraints.

    The following example shows how to measure latency percentiles of an inference endpoint using only the standard library, helping a team establish baseline data:

    1. import time
    2. import statistics
    3. def benchmark(infer_fn, requests, warmup=5):
    4. """Benchmark an inference function and return latency percentiles (in seconds)."""
    5. for req in requests[:warmup]: # Warm up to exclude first-load overhead
    6. infer_fn(req)
    7. latencies = []
    8. for req in requests[warmup:]:
    9. start = time.perf_counter()
    10. infer_fn(req)
    11. latencies.append(time.perf_counter() - start)
    12. latencies.sort()
    13. n = len(latencies)
    14. return {
    15. "p50": statistics.median(latencies),
    16. "p95": latencies[int(n * 0.95) - 1],
    17. "p99": latencies[int(n * 0.99) - 1],
    18. "mean": statistics.mean(latencies),
    19. }

    When testing, make sure the input distribution matches production traffic. Load-testing only with short texts will seriously underestimate latency in long-context scenarios.

    4. Key Factors Affecting Inference Performance

    Inference performance is mainly constrained by the following factors.

    1. Model size and parameter precision

    The more parameters, the higher the compute load and memory footprint. For a 7B-parameter model, the memory occupied by weights alone is roughly:

    Parameter precision Bytes per parameter Estimated weight memory
    FP16 2 ~14 GB
    INT8 1 ~7 GB
    INT4 0.5 ~3.5 GB

    Actual runtime also needs additional space for activations, the KV cache, and runtime overhead, so the table should be treated as a lower-bound reference.

    2. Memory bandwidth

    During the decode phase, the model weights must be read once for every generated token. Even with powerful compute units, insufficient memory bandwidth leaves the GPU frequently waiting for data. This is the bottleneck in many LLM inference scenarios.

    3. KV cache

    The Transformer architecture caches the key-value vectors of historical tokens during generation—the KV cache. Its footprint can be estimated as:

    KV cache bytes ≈ 2 × number of layers × number of attention heads × head dimension × sequence length × batch size × bytes per element

    This formula shows that long contexts and large batches significantly amplify memory pressure. Once memory is filled by the KV cache, the system can only reduce concurrency, and throughput drops accordingly.

    4. Request scheduling

    Static batching requires all requests in a batch to start and finish together, so short requests are slowed down by long ones. Continuous batching allows requests to dynamically join and leave during generation, significantly improving GPU utilization. The choice of scheduling strategy often delivers more direct gains than simply swapping hardware.

    5. Mainstream Optimization Techniques

    Common inference optimizations in the industry fall into three levels: model, system, and hardware.

    5.1 Model level: quantization, pruning, and distillation

    Quantization converts high-precision weights and activations into lower-precision representations, for example from FP16 to INT8 or INT4. Quantization reduces memory footprint and data movement. The key is evaluating accuracy loss: you typically need to compare pre- and post-quantization results on your business evaluation set and confirm the degradation is acceptable.

    Pruning removes weights or structures that have little impact on the output, reducing computation. Unstructured pruning requires specific hardware support to deliver real speedups, so it is used cautiously in engineering practice.

    Knowledge distillation uses a large model as a teacher to train a smaller model that mimics its outputs. The distilled small model has low inference cost, but requires additional training investment, and its capability ceiling is limited by the student model’s size.

    5.2 System level: caching, batching, and parallelism

    Prefix caching applies when many requests share the same system prompt. The system can reuse the already-computed prefix KV states, reducing redundant computation in the prefill phase.

    Dynamic batching and continuous batching, as mentioned earlier, are common means of improving throughput.

    Model parallelism and tensor parallelism are used when a model does not fit on a single GPU. Tensor parallelism introduces inter-GPU communication overhead, so the partitioning scheme should be chosen based on the network topology.

    Speculative decoding has a smaller draft model quickly generate several candidate tokens, which the large model then verifies in a single pass. When the draft quality is high, this reduces the number of step-by-step decode iterations the large model must perform.

    5.3 Hardware level: general-purpose accelerators and specialized chips

    General-purpose GPUs remain the dominant inference hardware today, with a mature ecosystem and broad model and framework support. As inference demand scales, custom inference chip (ASIC) projects are becoming more common. These chips are designed for specific computation patterns, aiming for better performance per watt and per dollar. Hardware selection needs to weigh operator support, software-stack maturity, procurement lead time, and long-term operational cost—not just peak compute on a spec sheet.

    Public reports have described cases where leading model teams significantly reduced inference costs. Those numbers are closely tied to specific models, traffic patterns, and engineering investment. When planning, teams should rely on their own benchmark results rather than directly applying others’ reported gains.

    6. Engineering Essentials for Production Deployment

    Delivering inference capability to the business requires a complete service architecture, not just loading a model into memory. A typical inference service includes the following components:

    • Access layer: handles authentication, rate limiting, request validation, and protocol conversion.
    • Scheduling layer: handles request queuing, batch assembly, and priority management.
    • Inference engine: handles model loading, operator execution, and memory management.
    • Auto-scaling: automatically adjusts instance count based on queue length and latency metrics.
    • Monitoring and alerting: continuously collects metrics such as latency, throughput, error rate, and memory utilization.

    When deploying in the cloud, you can use a container platform for instance orchestration, object storage for model weights, and log and monitoring services to observe production behavior. General-purpose infrastructure of this kind, offered by cloud platforms such as Baidu AI Cloud, reduces the work of building底层底层 components in-house.

    One thing to watch carefully with scaling is cold start. Loading a large model’s weights can take tens of seconds or longer. If your scaling policy only reacts to instantaneous traffic, new instances may come online after the peak has already passed. A more robust approach is to keep a pool of pre-warmed instances and perform predictive scaling based on historical traffic curves.

    7. A Practical Approach to Cost Analysis

    Before optimizing, build a cost model first. Below is a simplified estimation framework for comparing deployment options:

    1. def cost_per_1k_requests(gpu_hour_price, avg_latency_s, concurrency):
    2. """Estimate compute cost per 1,000 requests (assuming hourly GPU pricing and stable utilization)."""
    3. # Requests served per GPU-hour = 3600 / avg latency * concurrency
    4. requests_per_hour = 3600 / avg_latency_s * concurrency
    5. return gpu_hour_price / requests_per_hour * 1000
    6. # Option A: unoptimized, avg latency 2s, concurrency 4
    7. # Option B: quantization + continuous batching, avg latency 1.5s, concurrency 16
    8. price = 10.0 # Assumed hourly GPU price, for demonstration of the calculation only
    9. print(round(cost_per_1k_requests(price, 2.0, 4), 4))
    10. print(round(cost_per_1k_requests(price, 1.5, 16), 4))

    This model ignores idle periods, redundancy for fault tolerance, and network overhead, so actual costs will be higher. Its value lies in making it直观 clear that concurrency and latency usually affect unit cost far more than changes in hardware unit price.

    8. Practical Recommendations and Common Pitfalls

    Measure before optimizing. Without baseline data, teams easily focus effort on the wrong part of the system. First identify whether the bottleneck is in prefill, decode, scheduling, or network transfer.

    Define business constraints clearly. Conversational applications care more about TTFT, while batch offline jobs care more about throughput. Different optimization goals call for different technology choices.

    Be cautious about trading accuracy for speed. Quantization and distillation incur accuracy loss, which should be validated on business evaluation sets rather than judged by public leaderboards alone.

    Watch the long tail. Meeting the average latency target does not mean the user experience is acceptable; P99 metrics often better reflect real problems.

    Keep a rollback path. Before rolling out a new optimization, support gradual (canary) release and fast rollback, so a single configuration change cannot affect all users.

    Overall, inference optimization is a systems engineering effort. The model, scheduling, hardware, and operations must be designed together, and a weakness in any one of them limits overall results. After establishing a unified metrics system, teams can gradually introduce quantization, caching, and batching techniques, which typically deliver clear gains at well-controlled risk.