Reducing LLM Inference Costs: Thinking Token Compression and Self-Distillation Practices
As large language model capabilities continue to advance, inference costs and response latency have become primary bottlenecks in practical deployment, especially in multi-turn scenarios like coding agents. This article explores the cost model of MoE architectures, the importance of post-training data quality, and practical techniques for reducing inference costs through self-distillation and model compression. It also provides engineering practices for estimating and controlling token usage in coding agents, offering a comprehensive guide to evaluating and optimizing model deployment.
1. Background: Inference Costs Becoming the Core Constraint in Deployment
As the capabilities of large language models (LLMs) continue to advance, inference costs and response latency have become the primary challenges encountered by enterprises during actual deployment. In conversational applications, the length of a single response is relatively controllable. Coding agents, however, present a different scenario. Take fixing a complex, cross-module bug as an example: the model typically needs to read multiple files, reason about the root cause, modify the code, run tests, and continue refining based on failure information. Each round of invocation generates new output tokens while feeding the previous context back into the model. The more task rounds there are, the faster token consumption accumulates.
Therefore, evaluating whether a model is suitable for agent scenarios cannot rely solely on the quality of a single response. It is essential to evaluate the total token consumption, time spent, and success rate for completing an entire task.
Rumors frequently circulate within the industry regarding the planning of next-generation models, with most specific numbers unconfirmed. This article does not discuss these rumors; it focuses solely on verifiable technical principles and engineering practices.
2. Parameter Scale vs. Activated Parameters: Understanding the MoE Cost Model
Mixture of Experts (MoE) is a common scaling architecture. The model contains numerous expert sub-networks, and a routing module selects a small subset of experts to participate in the computation for each token. Consequently, the model’s scale metrics must be broken down into two numbers:
- Total parameters: Determines the model’s capacity, i.e., the range of knowledge and patterns it can store.
- Activated parameters: Determines the actual computation involved per token, directly impacting the compute overhead and latency of a single inference step.
A large total parameter count does not necessarily mean high inference costs. A model with a massive total parameter count but a low activation ratio might have a lower per-token computation requirement than a smaller dense model. However, the total parameter count still affects memory (VRAM) usage, deployment scale, and parallelization strategies. Therefore, both numbers should be examined together during evaluation and measured against the actual deployment environment.
The single-step computation can be roughly approximated as directly proportional to the number of activated parameters. This is a common order-of-magnitude estimation rather than a precise formula; actual latency is also influenced by memory bandwidth, batching methods, and communication overhead.
3. Post-Training Data Expansion: Quality Concerns Beyond Scale
Pre-training determines the model’s foundational language and knowledge capabilities. Post-training—which includes supervised fine-tuning (SFT), preference optimization, and reinforcement learning—determines the model’s performance in instruction following, coding, and long-horizon tasks. In recent years, a clear trend has emerged toward increasing post-training investments and covering more downstream domains.
However, growth in data scale does not equate to a linear improvement in capabilities. Three issues require close attention:
- Deduplication and quality filtering: Large volumes of duplicate samples will cause the model to memorize fixed templates, reducing its generalization ability.
- Task distribution: Whether the training data covers real-world engineering workflows, such as reading code, modifying files, and analyzing test error logs.
- Evaluation closed-loop: After each training round, the model’s effectiveness should be validated on benchmarks closely aligned with the business context, rather than solely relying on general leaderboard scores.
4. Thinking Token Compression: Self-Distillation and Model Compression
Enabling a model to accomplish the same task using fewer thinking tokens is the most direct approach to reducing inference costs. Common practices are divided into self-distillation and model compression.
4.1 Self-Distillation
Self-distillation refers to scenarios where the teacher and student models originate from the same base or architecture. A typical workflow is as follows:
- Have the model generate multiple reasoning trajectories for the same problem.
- Filter the results using correctness validation, retaining only the samples with correct answers.
- Among the retained samples, select those with shorter reasoning paths as the training targets.
- Use these samples to fine-tune the model, enabling it to output fewer thinking tokens at the same accuracy rate.
Self-distillation carries clear risks. Over-compression may eliminate necessary intermediate verification steps, leading to a decline in accuracy on complex tasks. Therefore, length rewards must be constrained alongside correctness rewards. The following example illustrates this principle:
def length_aware_reward(is_correct: bool, think_tokens: int,budget: int = 2048, penalty: float = 0.1) -> float:"""Prioritize correctness, deducting points proportionally for exceeding the length budget."""if not is_correct:return 0.0overflow = max(0, think_tokens - budget)reward = 1.0 - penalty * (overflow / budget)return max(0.0, reward)
This function only provides a reward when the answer is correct, and the reward decreases as the length exceeds the budget. It serves merely as an illustration of the training signal; actual systems need to adjust the budget and penalty coefficients based on the task type.
4.2 Model Compression
The goal of model compression is to reduce memory usage and computational overhead during deployment. Common methods include the following three:
- Quantization: Reduces weight precision (e.g., from 16-bit to 8-bit or 4-bit), decreasing memory and bandwidth usage. Precision loss needs to be independently verified on the target task.
- Pruning: Removes redundant structures or parameters and requires fine-tuning to recover performance.
- Knowledge Distillation: Uses the outputs of a large model to train a smaller model, enabling the smaller model to learn behaviors closer to the large one.
Compression typically sacrifices long-tail capabilities, such as rare languages, complex numerical reasoning, and the use of niche libraries. Therefore, evaluations should be conducted per task rather than just looking at average scores.
5. Estimating and Controlling Token Usage in Coding Agents
In engineering, you can break down each task into several steps, record the input and output tokens for each step, estimate costs, and set a budget cap. The following example demonstrates a simple recording method:
from dataclasses import dataclass, field@dataclassclass TaskBudget:max_tokens: intused: int = 0steps: list = field(default_factory=list)def record(self, name: str, input_tokens: int, output_tokens: int) -> None:step_total = input_tokens + output_tokensif self.used + step_total > self.max_tokens:raise RuntimeError(f"Step {name} exceeds task budget, already used {self.used}")self.used += step_totalself.steps.append((name, step_total))def estimate_cost(total_tokens: int, price_per_million: float) -> float:"""Estimate cost based on price per million tokens, referencing the pricing documentation of the service used."""return total_tokens / 1_000_000 * price_per_million
Actual billing rules vary by service method. For instance, whether input tokens distinguish cache hits, or whether input and output pricing differ, will affect the final cost. You should check the relevant pricing documentation before estimating.
In multi-turn agent loops, the input context often occupies the majority of tokens. Compressing thinking tokens is just one part of cost reduction; context management must be handled simultaneously. Common practices include:
- Reading only the file fragments relevant to the current problem, avoiding repeatedly sending entire files.
- Compressing completed steps into brief summaries to replace the full conversation history.
- Placing stable system instructions and tool descriptions at the beginning of the prompt prefix to facilitate cache reuse.
6. Engineering Practice Recommendations
- Hierarchical Routing: Assign simple steps like formatting, renaming, and file reading to lightweight models; delegate complex reasoning to more capable models.
- Dual-Metric Evaluation: Record both task success rate and token consumption per task. Reducing tokens while the success rate drops is a failed cost reduction.
- Budget and Circuit Breaking: Set token and round limits for each task. When limits are exceeded, halt automatic execution and transfer to human intervention.
- Monitoring and Alerting: Set up alerts for abnormal token growth in a single task. Common causes include recursive call failures, context bloat, and excessively long tool outputs.
- Regression Testing: After every model change or compression strategy adjustment, re-run evaluations on a fixed set of tasks to compare changes in success rate, latency, and cost.
