Post-Training Optimization for LLMs: Model Selection and Cost Management

    This article explores how post-training optimization enhances Large Language Model (LLM) capabilities without merely relying on parameter expansion. It covers common post-training techniques such as instruction following, multi-step reasoning, and safety alignment, alongside parameter efficiency strategies like quantization and dynamic routing. Furthermore, it provides a practical framework for cost estimation, evaluation design, and engineering practices for autonomous Agent integration, helping developers and enterprises make informed model selection decisions while effectively managing risks.

    1. Why Post-Training Optimization Matters

    The focus of the LLM competition is shifting. In the past, capability improvements primarily relied on increasing parameter counts and training data volumes. Recently, cloud providers have released new generations of foundation model APIs targeting scenarios such as complex coding, defensive cybersecurity, and long-horizon tasks. These models use the same base model as their predecessors, with performance gains mainly coming from the post-training phase.

    This suggests that pre-trained weights may already possess sufficient knowledge capacity, and the gap lies more in how to elicit these capabilities. For developers and enterprises, the direct implication is that model selection should focus on actual performance on specific tasks rather than just parameter scale or leaderboard scores.

    It is important to note that any third-party evaluation rankings or comparisons with closed-source flagship models mentioned should be verified against the evaluation organization’s public versions, dates, and metrics. Until the original report is reviewed, treat these conclusions as leads rather than decision-making baselines.

    2. Three Common Approaches to Post-Training Optimization

    Post-training typically includes instruction fine-tuning, human feedback alignment, and reasoning path reinforcement. The following three approaches are common in public materials, though specific implementation details vary by vendor and cannot be directly confirmed externally.

    Can Instruction Following Be More Granular?

    In programming and security scenarios, the same prompt might correspond to entirely different intents. For example, “analyze the vulnerabilities in this code” could be for remediation or for an attack. If these differences are clearly labeled during training, the model is more likely to respond according to the authorized scope and intended use.

    Applicability: This optimization is most effective in scenarios with clear task instructions and standardized inputs. If user prompts are ambiguous or context is missing, the model may still misinterpret the intent.

    Can Multi-Step Reasoning Be Guided?

    Process supervision focuses on each step of the reasoning process, while outcome supervision only looks at the final answer. In long-horizon tasks, process supervision helps the model plan step-by-step, check intermediate states, and correct errors.

    Applicability: Process supervision has high annotation costs, and more steps mean higher latency and costs per request. For one-off Q&A tasks, this extra overhead is usually not cost-effective.

    How to Verify Safety Alignment?

    In cybersecurity scenarios, a common practice is using red and blue team adversarial exercises to generate test samples, checking whether the model can identify malicious inputs and reject unauthorized requests. Enterprises should treat these tests as acceptance criteria rather than assuming the model is inherently safe.

    Applicability: All safety tests must be conducted within authorized scopes, and test samples should not contain complete, executable exploit code.

    3. How to Implement Parameter Efficiency

    Parameter efficiency focuses on completing the same tasks with less computation. External materials usually describe the goals but rarely detail the specific architecture. Common implementation methods include:

    • Quantization and Pruning: Compressing weights to lower bit-widths to reduce memory usage and inference latency. After quantization, accuracy must be re-evaluated on your own dataset.
    • Dynamic Routing: Selecting different computational paths or models based on input complexity. The accuracy of routing rules directly determines the balance between cost and quality.
    • Multi-Model Division of Labor: Using small models to handle common requests and routing complex requests to large models. The effectiveness of this approach depends on traffic distribution.

    During selection, do not look solely at unit price. Under the same unit price, output length, context length, and retry counts will all affect the final cost.

    4. Cost Estimation and Control

    Basic Formula

    Monthly costs can be estimated using the following formula:

    Monthly Cost = Average Monthly Requests × Average Input & Output Tokens × Unit Price × Redundancy Factor

    The redundancy factor is used to cover peak traffic. It should not be a fixed value. A more reasonable approach is to calculate the peak-to-average ratio using historical monitoring data, then determine the factor based on business tolerance. For example, the peak difference between a promotional event and daily office work can be significant, requiring different factors.

    Scenario and Model Matching

    The table below outlines a common approach to model selection. The model tiers should be adjusted based on actual pricing and evaluation results.

    Scenario Recommended Model Tier Context Length Latency Requirement Cost Sensitivity Primary Risk
    Code completion, format validation Small model or lightweight version Short Low High Prone to errors in complex logic
    Unit test generation, security policy suggestions Medium model Medium Medium Medium Requires manual review of output
    Vulnerability chain analysis, full architecture design Flagship model Long High latency acceptable Low High per-request cost, results need verification

    Cost Reduction Conditions for Hybrid Routing

    The hybrid routing concept: simple requests are handled by small models, and only when the small model’s confidence is low or the task is complex is it escalated to a large model. Whether this approach reduces costs depends on three conditions:

    1. Simple requests account for a sufficiently high proportion of total traffic.
    2. The small model’s accuracy on these requests meets business standards.
    3. The cost and error rate of the escalation decision itself are controllable.

    It is recommended to test cost reduction magnitude using offline samples before deploying online. Do not directly quote percentage figures from external articles.

    5. How to Design an Evaluation Plan

    Select Three Core Task Types

    The evaluation can cover three types of tasks:

    • Code Logic Analysis: Input code snippets to check if the model can identify defects and provide executable fix suggestions.
    • Security Policy Generation: Input network topologies to check if the generated access control rules comply with the principle of least privilege.
    • Long-Horizon Planning: Input requirement documents to check if the model’s phased plan is complete and dependency relationships are correct.

    How to Build a Test Set?

    The test set should ideally come from real business data and be desensitized. Each task type can be divided into three difficulty layers: normal, boundary, and anomaly. Anomaly samples should include ambiguous instructions, missing context, and malicious inputs.

    There is no unified standard for the number of samples per layer. As a starting point, you can use no fewer than 200 samples per layer and ensure a reasonable ratio between layers. The sample size should be gradually adjusted based on the stability of evaluation results.

    Thresholds and Checklists

    Pass criteria (e.g., accuracy, P95 latency, hallucination rate, safety failure rate) should be determined before the evaluation. Thresholds are set by the team based on business risk.

    You can refer to the following checklist:

    • Have you recorded the model version, input/output length, concurrency, and cache hit rate?
    • Have you separately tracked accuracy and hallucination rates?
    • Have you covered malicious inputs and unauthorized requests?
    • Have you compared at least two candidate models under the same conditions?
    • Can the evaluation results be reproduced by others?

    6. Engineering Essentials for Agent Integration

    To build autonomous Agents, you need to handle the instability of model outputs. Below is a simplified example demonstrating JSON parsing, tool whitelisting, retry limits, and timeout control.

    1. import json
    2. ALLOWED_TOOLS = {"run_tests", "search_docs"}
    3. MAX_STEPS = 10
    4. MAX_RETRIES = 2
    5. def build_plan_prompt(task):
    6. return (
    7. "Decompose the task into steps, only output a JSON list, "
    8. "each item containing 'tool' and 'args' fields.\nTask: " + task
    9. )
    10. def parse_plan(raw_text):
    11. try:
    12. plan = json.loads(raw_text)
    13. except json.JSONDecodeError:
    14. raise ValueError("Model output is not valid JSON")
    15. if not isinstance(plan, list):
    16. raise ValueError("Plan must be a list of steps")
    17. return plan
    18. def run_step(step, sandbox):
    19. tool = step.get("tool")
    20. if tool not in ALLOWED_TOOLS:
    21. raise PermissionError(f"Tool not authorized: {tool}")
    22. return sandbox.call(tool, step.get("args", {}), timeout=30)
    23. def agent_loop(task, model, sandbox):
    24. plan = parse_plan(model.generate(prompt=build_plan_prompt(task)))
    25. if len(plan) > MAX_STEPS:
    26. raise ValueError("Number of steps exceeds the limit")
    27. results = []
    28. for step in plan:
    29. for attempt in range(MAX_RETRIES + 1):
    30. try:
    31. results.append(run_step(step, sandbox))
    32. break
    33. except PermissionError:
    34. raise # Do not retry on unauthorized access, stop immediately
    35. except TimeoutError:
    36. if attempt == MAX_RETRIES:
    37. raise
    38. return results

    This code still has areas that need expansion. model and sandbox must be provided by the caller, the sandbox should run in an isolated container without production credentials, and retry logic should be designed based on error types (e.g., network timeouts can be retried, while parameter errors should be returned to the model for correction).

    7. Risk and Compliance Reminders

    • Data Security: Data fed to the model should be desensitized. Private deployments can reduce data egress, but audit logs and access permissions are still required.
    • Open Source Licenses: When selecting open-source models, confirm whether the license permits commercial use, redistribution, and fine-tuning.
    • Tool Permissions: Agents should only have the minimum permissions necessary to complete tasks. Irreversible operations like deletion, sending, and deployment require human confirmation.
    • Injection Attacks: Retrieved web pages or documents may contain malicious instructions. The model should treat this content as data, not execute instructions within it.
    • Version Updates: Model version changes may alter output behavior. Re-run the evaluation set before upgrading.

    8. Conclusion

    Post-training optimization shows that enhancing model capabilities does not necessarily depend on parameter expansion. For developers and enterprises, the more practical questions are: Is the model reliable on your specific tasks? Is the unit cost acceptable? Can risks be controlled?

    During selection, match model tiers to scenarios, estimate costs using real data, and decide on deployment through standardized evaluation. If tasks are simple and traffic is concentrated, hybrid routing can yield significant cost savings; if tasks carry high risks, prioritize ensuring verifiable outputs.

    This article does not draw conclusions about specific products. Any evaluation results, pricing, and cost ratios mentioned should be verified against official or third-party public reports. Before making actual decisions, complete validation using your own data.