Capability Fusion and Alignment Optimization Practices in Large Language Model Iterations

    This article explores practical strategies for integrating diverse capabilities into a single large language model during version iterations. It covers data mixed training, parameter merging, and sequential fine-tuning. Additionally, it delves into preference alignment techniques, post-training reinforcement for math, code, and roleplay domains, and the engineering design of online retrieval modules.

    I. Background: Why Capability Fusion is Core to Version Iteration

    Large Language Model (LLM) version iteration typically involves incremental optimization on an existing foundation and capabilities rather than training a new model from scratch. Teams usually have three primary demands. First, code generation and general conversational capabilities must be usable simultaneously. Second, model outputs must align more closely with human preferences, providing well-structured and instruction-compliant answers. Third, specific scenarios like mathematical reasoning and role-playing require specialized enhancements.

    Maintaining separate models for each capability type rapidly increases deployment, routing, and operational costs. Gateways must determine request types and distribute them to different models, version rhythms across models are inconsistent, and troubleshooting production issues becomes more complex. Therefore, converging multi-directional capabilities into a single version is a common goal during iteration.

    The benefits of capability fusion are twofold. First, it simplifies the service architecture; a single model handles various requests, eliminating the need for callers to maintain multiple interfaces and routing rules. Second, it enables capability transfer. For instance, structured reasoning training in code data can sometimes improve logical expression in general tasks. This transfer effect does not happen automatically and must be verified through evaluation, a point emphasized later in the release process.

    II. Three Technical Paths for Capability Fusion

    2.1 Data Mixed Training

    In the same training round, data from different domains is mixed in preset proportions. Capabilities are learned synchronously, maintaining relative balance within the training cycle. The challenge lies in ratio allocation. If the data volume or difficulty in one domain is too high, it can suppress performance in other domains. Therefore, domain-specific regression testing is necessary after each ratio adjustment.

    1. # Schematic: Sample a training batch from the data pool based on domain ratios
    2. DATA_MIX = {
    3. "general_chat": 0.35,
    4. "code_generation": 0.25,
    5. "math_reasoning": 0.15,
    6. "role_play": 0.10,
    7. "instruction_following": 0.15,
    8. }
    9. def sample_batch(pools: dict, batch_size: int, rng) -> list:
    10. """Extract samples based on ratios. Rounding errors are compensated by the last domain."""
    11. assert abs(sum(DATA_MIX.values()) - 1.0) < 1e-6, "The sum of ratios must be 1"
    12. batch, domains = [], list(DATA_MIX.keys())
    13. for domain in domains[:-1]:
    14. n = round(batch_size * DATA_MIX[domain])
    15. batch.extend(rng.sample(pools[domain], k=n))
    16. last = domains[-1]
    17. batch.extend(rng.sample(pools[last], k=batch_size - len(batch)))
    18. rng.shuffle(batch)
    19. return batch

    2.2 Parameter-Level Merging

    For multiple fine-tuned versions derived from the same base, parameter interpolation or task vector merging can be performed based on weights. This method is low-cost and requires no retraining, but it requires all versions to have identical structures. After merging, the model’s performance on each capability may shift, requiring item-by-item re-evaluation.

    1. def merge_state_dicts(state_dicts: list, weights: list) -> dict:
    2. """Perform weighted averaging on parameters of isomorphic models. Requires weights sum to 1 and identical parameter names and shapes."""
    3. assert abs(sum(weights) - 1.0) < 1e-6, "The sum of weights must be 1"
    4. keys = state_dicts[0].keys()
    5. for sd in state_dicts[1:]:
    6. if sd.keys() != keys:
    7. raise ValueError("Parameter structures are inconsistent and cannot be merged")
    8. return {
    9. k: sum(w * sd[k] for sd, w in zip(state_dicts, weights))
    10. for k in keys
    11. }

    2.3 Sequential Fine-tuning and Experience Replay

    Fine-tune in one domain first, then continue fine-tuning in others. To mitigate catastrophic forgetting, a small amount of old domain data is mixed in as replay samples at each stage. This approach is simple to implement and widely used in engineering. The trade-off is an increase in training phases, and the stage order affects the final result, necessitating experimental validation.

    III. Preference Alignment: Making Outputs Meet Human Expectations

    Preference alignment typically involves four stages:

    1. Instruction Data Construction: Collect diverse user instructions covering task types like Q&A, rewriting, summarization, and format constraints.
    2. Supervised Fine-tuning (SFT): Train the model with high-quality demonstration responses to teach basic instruction response formats.
    3. Preference Data Collection: Generate multiple candidate responses for the same prompt, ranked by annotators or a judge model.
    4. Preference Optimization: Use ranking data to train a reward model or directly optimize the policy using preference pairs, making the model favor high-scoring responses.

    In practice, three issues require attention. First is annotation consistency. Different annotators may have varying definitions of a “good response,” so regular consistency checks and clear annotation guidelines are necessary. Second is reward over-optimization. The model may learn to cater to the reward model’s preferences, such as generating lengthy but uninformative responses. Thus, an independent evaluation set must be maintained for monitoring. Third is length bias. Reward signals tend to favor longer responses, so length should be controlled during data construction and scoring, or response length distribution should be tracked separately during evaluation.

    IV. Post-Training Reinforcement: Math, Code, and Roleplay

    Data quality standards vary significantly across domains, requiring distinct strategies.

    4.1 Mathematical Reasoning

    Math problems have the advantage of verifiable answers. Multiple candidate solutions can be generated for each problem, retaining only those with correct final answers and complete derivation processes. This method, known as rejection sampling, expands high-quality training data without relying on manual annotation.

    4.2 Code Generation

    Code samples can be filtered using executable unit tests. For a given requirement, generated code must pass all test cases and satisfy static analysis rules to enter the training set. The coverage of test cases directly determines data quality; boundary conditions and anomalous inputs should be included in test design.

    1. def rejection_sample(prompts, generate, verify, k: int = 4) -> list:
    2. """Generate up to k candidates for each prompt, keeping the first response that passes verification."""
    3. kept = []
    4. for prompt in prompts:
    5. for _ in range(k):
    6. answer = generate(prompt)
    7. if verify(prompt, answer):
    8. kept.append({"prompt": prompt, "response": answer})
    9. break
    10. return kept

    4.3 Role-Playing

    Evaluating roleplay is difficult to fully automate. The focus should be on persona consistency and style stability. Training data must explicitly define persona descriptions, tone constraints, and prohibited behaviors, with sampling checks during evaluation to detect persona drift in long dialogue scenarios.

    V. Engineering Design for Online Retrieval Modules

    Online retrieval allows models to access the latest information beyond training data but introduces new risks. A reliable retrieval-augmented generation (RAG) process typically includes the following steps:

    1. Intent Judgment: Identify whether the question relies on time-sensitive information. Common sense questions can be answered directly by the model, reducing latency and cost.
    2. Query Rewriting: Convert colloquial user questions into keywords or phrases suitable for retrieval.
    3. Retrieval and Deduplication: Call the search service to get candidate results, deduplicate by content, and rank by relevance and source credibility.
    4. Snippet Extraction: Extract relevant snippets from the results while controlling context length.
    5. Citation Generation: Require the model to answer based on the snippets and annotate citation numbers for users to verify sources.
    1. def answer_with_search(question, llm, search, needs_fresh_info, rewrite_query,
    2. dedupe_and_rank, max_results: int = 5) -> str:
    3. """Schematic: Retrieval-augmented Q&A process. Auxiliary functions need to be implemented based on the actual system."""
    4. if not needs_fresh_info(question):
    5. return llm.generate(question)
    6. query = rewrite_query(question)
    7. hits = search(query, top_k=max_results)
    8. snippets = dedupe_and_rank(hits)[:3]
    9. context = "\n".join(
    10. f"[{i + 1}] {s.title}: {s.text}" for i, s in enumerate(snippets)
    11. )
    12. prompt = (
    13. "Please answer the question based only on the following materials, and annotate citation numbers after relevant conclusions. "
    14. "If the materials are insufficient to answer, please state clearly.\n"
    15. f"{context}\nQuestion: {question}"
    16. )
    17. return llm.generate(prompt)