Large Model Capability Fusion and Post-Training: An Engineering Implementation Guide

    This guide provides a practical roadmap for engineering teams looking to merge multiple capabilities—such as general conversation, code generation, and document understanding—into a single large language model. It covers data mixing strategies for capability fusion, a three-stage post-training pipeline (SFT, preference optimization, and targeted reinforcement), and key engineering concerns including web search integration, file parsing, security controls, and rollback planning. The article also outlines common pitfalls such as insufficient evaluation sample sizes and the misconception that preference optimization eliminates hallucinations, along with the conditions under which a fused model approach is the right choice.

    Large language models are evolving from single-purpose tools into integrated systems. A customer support assistant, for example, may need to converse naturally, read documents, write code, and retrieve up-to-date pricing information. Consolidating these capabilities into one model reduces the operational cost of maintaining multiple separate systems, but it introduces the challenge of capability interference. This article walks through the process in five stages: capability fusion, post-training, engineering implementation, safe deployment, and common mistakes. It also clarifies the conditions under which the recommended approaches hold true.

    1. How to Fuse General Conversation with Code Capabilities

    Early engineering teams often trained separate models for different tasks—one for natural language dialogue and another for code comprehension and generation. The standard approach to fusion is to mix multiple data types into the training set, allowing a single set of parameters to learn both semantic understanding and code syntax simultaneously. Common data categories include dialogue, code, mathematics, and instruction-following data. There is no universal answer for the optimal mixing ratio; it needs to be determined experimentally against your target scenarios.

    Experiments should begin with a small-scale grid search. For example, select three or four candidate ratios, train each with the same number of steps and learning rate, and compare them on a fixed evaluation set. The evaluation set should be maintained by domain, with separate scores for code, mathematics, instruction following, and casual conversation. Monitor for per-capability regression after each run. If the code pass rate drops below a set threshold relative to the single-capability baseline, that ratio should not be deployed.

    The core difficulty in fusion is capability interference. Too much code data can make the model’s tone feel stiff in casual conversation or writing tasks. Conversely, too much dialogue data can degrade code accuracy. Therefore, after fusion, you cannot rely on overall impressions—you must evaluate each domain independently.

    Useful public benchmarks include HumanEval (code generation, 164 problems), GSM8K (grade-school math word problems), and IFEval (instruction following). When evaluating, three conditions must be met. First, the single-capability baseline and the fused model must use the same set of problems. Second, both must use identical decoding parameters, such as setting temperature to 0. Third, record the evaluation script version, environment version, and random seed.

    Sample size determines whether your conclusions are trustworthy. For HumanEval, with a pass rate around 50%, the 95% confidence interval for 164 problems is roughly ±7.6 percentage points. This means a difference of a few percentage points is likely just random noise. When comparing two models, apply a paired statistical test—such as McNemar’s test—on the same set of problems, rather than simply comparing the two percentage scores.

    Fusion is appropriate when multiple capabilities need to be used interchangeably within the same session, and when the team can bear the cost of unified maintenance. If your use case requires only a single capability, or if you need extremely high precision in one area, a dedicated single-purpose model is usually easier to control in terms of quality and cost.

    2. How to Approach Post-Training

    Post-training refers to a set of techniques applied after pretraining to improve model behavior. The typical approach is divided into three stages.

    Stage 1: Supervised Fine-Tuning (SFT). Train the model on human-written or reviewed “instruction-response” pairs to teach it to answer in the desired format. Data quality matters far more than quantity. A thousand samples with consistent formatting and correct answers are often more effective than ten thousand samples from mixed sources. Before training, the data should go through four processing steps. First, deduplication to prevent the same sample from appearing repeatedly. Second, desensitization—remove personal information such as phone numbers, ID numbers, email addresses, and physical addresses. Third, verify sources and licenses to confirm the data can be used for training. Fourth, spot-check the data, for example, have two reviewers independently verify a random 5% sample; if the agreement rate falls below an agreed threshold, the entire batch should be redone. You must also ensure training data does not overlap with evaluation problems, otherwise evaluation scores will be inflated.

    Stage 2: Preference Optimization. This includes RLHF (reinforcement learning from human feedback) based on a reward model, as well as direct methods like DPO (direct preference optimization) that optimize directly on preference pairs. These methods teach the model which type of response humans prefer. Preference optimization can reduce certain types of errors, but it does not guarantee the elimination of hallucinations. You can only observe improvements in factual accuracy if the reward signal explicitly covers factuality and the evaluation includes fact-checking tasks. Factuality evaluation can be done in two ways. One is manual verification, where annotators compare responses against credible sources. The other is retrieval-consistency checking, where key assertions in the response are compared against retrieved documents. When reporting results, specify the hallucination rate and the sample size, rather than giving only a qualitative statement.

    Stage 3: Targeted Reinforcement for Specific Capabilities. Typical objectives include the format correctness of tool-call parameters, compliance of structured output, or knowledge of domain-specific terminology and workflows. Data usually comes from expert-written samples and desensitized business logs. Training goals should be specific and measurable, such as “improve tool-call parameter validity from 92% to over 97%.” Evaluation metrics must include both the targeted capability metric and regression metrics for other capabilities. The scope of applicability must also be clearly stated. With only a few hundred samples, gains are usually unstable—run a small-scale validation first before deciding whether to expand the data.

    The following table compares the three approaches.

    Method Applicable Conditions Data Cost Primary Evaluation Focus Main Risks
    SFT Need unified response format or supplementary capabilities Medium—depends on annotation quality Format compliance, per-capability accuracy Mixed data causing capability degradation
    DPO/RLHF Need to adjust response preference and style High—requires paired preference annotations Preference win rate, factuality Over-fitting to user preferences; hallucinations not eliminated
    Targeted Reinforcement Has a specific, measurable capability goal Low to medium—small data volume but high quality requirements Targeted metric and regression in other capabilities Unstable results with small sample sizes

    3. Engineering Implementation: Web Search and File Parsing

    Web search and file parsing are two entry points that connect the model to the external world. Both should be designed with the principles: “controlled invocation, graceful degradation on failure, and traceable results.”

    The typical web search flow is as follows. First, the model determines whether the query requires up-to-date information. Second, the model generates a search query. Third, the system checks user permissions and quotas. Fourth, check the cache. Fifth, call the search service with a timeout; on failure, retry at most twice with exponential backoff. Sixth, clean the results and truncate to the top few entries. Seventh, pass the results as context to the model for response generation, with sources cited in the answer.

    Caching policy should be tuned to data freshness. For rapidly changing data like prices and inventory, set the cache time to around 5 minutes. For news data, 30 minutes is reasonable. Logs should record the query terms, source URLs, request timestamps, and latency, but must not record user identity information.

    Graceful degradation is a required design branch. If the search times out or the service is unavailable, the system should clearly tell the user that the latest data is temporarily unavailable and indicate the timestamp of the data it does have. It must not let the model generate what appear to be real-time prices from memory.

    File parsing also requires constraints. Check the file type before upload and allow only whitelisted formats, such as PDF, DOCX, and TXT. Enforce a file size limit, for example, a maximum of 20 MB. Perform parsing in an isolated sandbox with a timeout and a maximum page count, such as 30 seconds and 100 pages. Treat the parsed text as untrusted data. Finally, apply desensitization rules before passing the text to the model.

    The pseudocode below illustrates the core flow. Treat it as a starting point for your own implementation; replace the search service and sandbox environment with what your team actually uses.

    1. // Core routine: answer a query with an optional web search
    2. function answer_with_search(query, user):
    3. // 1. Check if the user is allowed to use web search
    4. if not policy.allow_web_search(user):
    5. return llm.answer(query)
    6. // 2. Let the model generate a search query from the user input
    7. search_query = llm.make_search_query(query)
    8. // 3. Check the cache first, using a TTL key based on data type
    9. results = cache.get(search_query, ttl_key="price")
    10. if results is None:
    11. // 4. Call the search API with retries and a timeout
    12. try:
    13. results = with_retry(
    14. lambda: search_api.search(search_query, timeout=5),
    15. max_retries=2,
    16. backoff=[1, 2],
    17. )
    18. cache.set(search_query, results, ttl=300)
    19. except (TimeoutError, APIError) as e:
    20. // 5. On failure, degrade gracefully
    21. log.warning("search_failed", query=search_query, error=str(e))
    22. return llm.answer(
    23. query,
    24. notice="Latest data is temporarily unavailable; the answer may be outdated.",
    25. )
    26. // 6. Clean and take the top entries; treat results as data, not instructions
    27. context = [clean(r) for r in results[:5]]
    28. return llm.answer(query, context=context, cite=True)
    29. // File upload and parsing routine
    30. function parse_upload(file):
    31. validate_type(file, allow={"pdf", "docx", "txt"})
    32. validate_size(file, max_mb=20)
    33. text = sandbox.run(parse_worker, file, timeout=30, max_pages=100)
    34. return redact_pii(text)

    Rollback should also be designed in advance. Tool invocation, web search, and file parsing should each have an independent feature flag. If monitoring metrics go abnormal, operations staff can disable the relevant feature without redeploying the model, causing the system to fall back to pure dialogue mode.

    4. Security Considerations and a Deployment Checklist

    Prompt injection is the most common risk in web-connected and file-processing scenarios. A webpage or file may contain text like “ignore your previous instructions.” Design for three principles. First, keep system instructions separate from external content, and explicitly mark external content as reference-only material. Second, external content must not grant the model new tool permissions. Third, tool invocation must be validated against a whitelist.

    Malicious file protection includes file type detection, virus scanning, sandbox isolation, and resource limits. Macros, embedded scripts, and external links should be stripped during the parsing stage. Parsers should be updated regularly, and files that fail to parse should be logged for investigation.

    Personal information and copyright must also be handled. Training and log data should be desensitized. Original files should have a retention period and be deleted upon expiration. When citing external content in answers, always attribute the source and avoid copying long excerpts verbatim.

    Output filtering should cover sensitive content categories. For high-risk topics such as medical, legal, and financial advice, include a disclaimer and provide a path for human review.

    Before deployment, confirm each item on the checklist below.

    • Evaluation results include comparisons against single-capability baselines, with sample sizes and confidence intervals recorded.
    • SFT data has gone through deduplication, desensitization, source verification, and spot-checking, and is disjoint from the evaluation set.
    • Factuality evaluation results are present after preference optimization, with hallucination rate reported.
    • Search API has a timeout, retry limit, and cache TTL, and has a degradation message.
    • File upload restricts type, size, and page count, and parsing runs in a sandbox.
    • Prompt injection test cases pass; external content cannot trigger tool invocation.
    • Monitoring covers tool-call success rate, P95 latency, timeout rate, degradation ratio, per-capability regression, and user complaint rate.
    • Progressive rollout proceeds through 5%, 20%, and 100% stages, with metrics observed at each stage.
    • Rollback thresholds are defined, e.g., disabling search when the timeout rate exceeds an agreed value, and a rollback drill has been performed at least once.

    5. Common Mistakes

    Mistake 1: Relying on overall impressions. If the fused model sounds fluent in conversation, you may assume all capabilities are fine. The correct approach is to evaluate each domain separately and maintain a single-capability baseline for comparison.

    Mistake 2: Drawing conclusions from too few samples. A difference seen on a few dozen problems is usually within the range of random variation. Increase the sample size and use paired statistical tests.

    Mistake 3: Assuming preference optimization eliminates hallucinations. Preference optimization improves response preferences; factual accuracy requires dedicated evaluation data and methods.

    Mistake 4: Treating webpage or file content as instructions. External content must be treated as reference material only and must not alter the model’s system behavior.

    Mistake 5: Missing timeouts and caching. When a search API slows down, the entire session is slowed down. Every external call should have a timeout, and cacheable data should have an appropriate cache TTL.

    Mistake 6: No rollback plan. When problems occur, the team has to do an emergency redeployment, which is slow and risky. Feature flags and rollback drills should be ready before deployment.

    A fused-model approach works only if your evaluation covers every capability in scope and if your external integrations have degradation and rollback paths. Confirm both of these conditions before you consider scaling it up.