Programming LLM Output Speed: Inference Optimization and Engineering Practices
This article examines how to improve output speed for programming LLMs from an engineering perspective. It defines Time To First Token (TTFT), output throughput, and end-to-end latency; reviews model size and architecture, quantization and numerical precision, inference engine scheduling and caching, and serving deployment factors; discusses the latency and cost implications of thinking mode; provides a streaming measurement example and testing guidelines; and recommends speed strategies by task tier.
Introduction: Why Output Speed Is a Key Metric in Coding Scenarios
In coding assistance scenarios, every token the model outputs directly affects developer waiting time. Tasks such as code completion, unit test generation, error log explanation, and refactoring suggestions usually need usable results within seconds. When output speed cannot keep up with the developer’s thought rhythm, attention is interrupted and the workflow breaks. Even when the generated code quality is high, the overall experience can still decline.
Therefore, when evaluating programming models, accuracy or benchmark scores alone are not enough. Response time also needs to be included in the same set of metrics. This article breaks down the components of output speed from an engineering perspective, explains which optimization approaches can be taken, and provides concrete methods for measurement and model selection.
1. Basic Speed Metrics
Generation speed is usually measured with three metrics.
- Time To First Token (TTFT): the time from sending a request to receiving the first output token. It is mainly affected by input length, queueing time, and the amount of computation in the prefill phase.
- Output throughput (Tokens Per Second, TPS): the number of tokens output per second during the decoding phase. It mainly depends on compute capability and memory bandwidth.
- End-to-end latency: the total time required for the full response to finish.
The relationship among the three can be written as:
End-to-end latency ≈ TTFT + number of output tokens / output throughput
This relationship shows that in short-answer scenarios, TTFT accounts for a higher proportion, while in long code generation scenarios, throughput dominates. The two types of scenarios have different optimization directions and cannot be summarized with a single number.
2. Four Layers That Affect Output Speed
1. Model Layer: Scale and Architecture
The larger the number of model parameters, the more weights need to be read and written at each decoding step, and the longer each step takes. On the same hardware, smaller models are usually faster, but their ability on complex code reasoning may decline. A mixture-of-experts architecture can reduce the number of parameters actually activated per step while keeping the total parameter count large. This is a common trade-off at the architecture level.
2. Quantization and Numerical Precision
Reducing weight precision, for example from 16-bit floating point to 8-bit or 4-bit integers, can reduce memory usage and memory bandwidth pressure, thereby improving decoding speed. The cost is that precision may decline, especially in long-chain reasoning and generation that requires precise syntax. In engineering practice, compare the pass rate before and after quantization on your own task set rather than relying on a single example.
3. Inference Engine Layer: Scheduling and Caching
Optimizations in the inference engine usually include the following categories.
- Continuous batching: dynamically merge decoding steps from different requests to improve accelerator utilization.
- KV cache management: reuse already computed attention keys and values to avoid repeated computation. In long-context scenarios, paged cache management can significantly reduce memory fragmentation.
- Speculative decoding: a small model drafts multiple tokens first, and a large model verifies them in batches. Accepted portions can be output at once. The acceptance rate depends on how well the draft model matches the target model.
- Operator fusion and kernel optimization: reduce kernel launch overhead and the reading and writing of intermediate results.
The effectiveness of these methods depends heavily on the workload shape. For example, speculative decoding has a higher acceptance rate on code snippets whose output is more predictable, while its benefit is limited on open-ended text.
4. Serving Deployment Layer: Replicas and Routing
On the serving side, multi-replica deployment, request-length bucketing, nearby access, and connection reuse can reduce queueing and network overhead. Under burst traffic, autoscaling and rate limiting need to be used together. Otherwise, queueing time during peak periods can offset the gains from inference acceleration.
3. How Thinking Mode Affects Latency and Cost
Some reasoning models support thinking mode, which generates internal reasoning content before producing the final answer. The thinking process can improve correctness on complex problems, but it increases the number of output tokens, thereby lengthening end-to-end latency and increasing usage consumption.
The following points should be noted during integration.
- Thinking mode usually needs to be configured according to the service provider’s requirements. Some models perform noticeably worse when thinking is disabled, while some services require it to remain enabled. Before integration, read the relevant documentation and confirm the recommended configuration.
- Whether thinking content is billed and whether it is returned to the caller vary by service. When calculating costs, use the official billing documentation as the basis.
- For the same batch of tasks, record pass rate, latency, and usage separately with thinking mode enabled and disabled. Use data to decide the configuration rather than relying on intuition.
4. How to Measure Your Real Output Speed
Speed numbers given in service documentation or promotional materials usually come from specific input lengths, concurrency levels, and hardware conditions. Teams should measure on their own workloads. The following example is unrelated to any specific service, and the generator is implemented by the caller according to the actual client.
import timedef measure_stream(stream_fn, prompt, max_tokens=512):"""stream_fn: generator function that returns incremental tokens, implemented by callerprompt: input promptReturns: time to first token (seconds), number of output tokens, decode throughput (tokens/s)"""start = time.perf_counter()first_token_time = Nonecount = 0for _token in stream_fn(prompt, max_tokens=max_tokens):now = time.perf_counter()if first_token_time is None:first_token_time = now - startcount += 1total = time.perf_counter() - startdecode_time = total - (first_token_time or 0.0)tps = count / decode_time if decode_time > 0 else 0.0return first_token_time, count, tps
The following issues should be noted during measurement.
- Repeat each test group at least dozens of times, and report the median and percentiles to avoid misjudgment caused by single-run fluctuation.
- Measure short context and long context separately, because their throughput usually differs significantly.
- Record the concurrency level. As concurrency rises, per-request throughput usually declines, so report data under different concurrency levels separately.
- Keep the test client in the same region as the service deployment when possible to exclude the impact of network jitter.
- When comparing different configurations, keep prompts, maximum output length, and sampling parameters consistent.
5. Selecting Speed Strategies by Task Tier
No single configuration fits all tasks. A practical approach is to divide tasks into three tiers.
- Low-latency tier: code completion, short explanations, and format conversion. These tasks are sensitive to TTFT, so prefer smaller models or high-throughput configurations and disable unnecessary reasoning steps.
- Balanced tier: single-function implementation, test case generation, and common defect localization. The standard configuration is sufficient to balance speed and quality.
- Deep tier: cross-file refactoring, complex architecture design, and difficult defect analysis. These tasks should be allowed longer response times.
