How Reinforcement Learning Enhances Coding and Security Auditing with a Fixed Base Model

    This article explores whether post-training and reinforcement learning can improve large language model (LLM) performance in coding and security auditing while keeping the pre-trained base model fixed. It also examines the application boundaries of million-token context windows and Mixture of Experts (MoE) architectures, and highlights the key risks enterprises should consider before deployment.

    This article answers three questions: With a fixed pre-trained base model, can post-training and reinforcement learning (RL) alone improve LLM performance in coding and security auditing? What are the application boundaries of million-token context windows and Mixture of Experts (MoE) architectures? What risks should enterprises consider before deployment?

    I. Fixed Base Model: Focusing Investment on Post-Training

    Expanding parameter scales does not always yield proportional returns. While training and inference costs grow with scale, many business scenarios only require the model to be more stable in a few specific capabilities. Fixing the base model and concentrating efforts on post-training is a more pragmatic approach.

    The Mixture of Experts (MoE) architecture is a common foundation for this route. It splits the feedforward network into multiple experts, with each token only activating a small fraction of them. Taking the DeepSeek-V3 technical report as an example, the model has a total of 671B parameters but only activates about 37B parameters per token (Source: DeepSeek-V3 Technical Report, 2024). This results in a large overall knowledge capacity, while the computation required per inference is significantly lower than that of a dense model with an equivalent total parameter count.

    However, the benefits of MoE come with trade-offs. The router must distribute tokens relatively evenly among experts; otherwise, some experts become overloaded while others sit idle. During multi-GPU training and inference, the communication overhead between experts increases, and router training itself can be unstable. Therefore, fewer activated parameters do not necessarily mean lower overall costs; evaluation must consider hardware topology and actual throughput.

    1. Reinforcement Learning Refines Verifiable Goals

    Supervised Fine-Tuning (SFT) trains the model to mimic labeled answers. While the model performs well on the training set, it tends to copy surface-level patterns when encountering unseen problems. RL, on the other hand, allows the model to generate multiple solutions itself, which are then evaluated by reward signals. In coding tasks, rewards can come from whether unit tests pass or compilation succeeds. In security tasks, rewards can be based on whether vulnerabilities are correctly located and whether tests still pass after the fix. The more verifiable the reward, the more reliable the training signal.

    Improper reward design can cause issues. If test cases have insufficient coverage, the model might learn to delete assertions to pass tests. If the reward model prefers lengthy answers, the output length will increase meaninglessly. During deployment, it is necessary to continuously monitor for such shortcut behaviors.

    2. Fixed Base Model Reduces Migration Costs

    An unchanged base model means that existing inference frameworks, quantization schemes, and monitoring metrics can continue to be used. The team only needs to validate the new version’s performance on business-specific data without re-adapting the model structure. This migration cost is often underestimated, especially when extensive customization has already been done internally for the previous version.

    II. Long Context is Usable, But Not Lossless

    Context windows with millions of tokens make it possible for models to ingest an entire code repository, technical documentation, or lengthy logs in a single pass. Cross-module issues that single-file completion cannot cover—such as circular dependencies or inconsistent interface contracts—can potentially be discovered using long context.

    However, being able to fit it in does not mean it will all be used effectively. Long context has several known limitations. First, attention dilutes as input lengthens, dispersing the weight of relevant information. Second, many models have a lower recall rate for information located in the middle of long texts compared to the beginning and end, a phenomenon described by Liu et al. (2023) in “Lost in the Middle.” Third, positions exceeding the training length require extrapolation, which may degrade performance. Therefore, claiming that long context is “lossless” is inaccurate. A more robust approach is to first filter files relevant to the task, place key snippets near the beginning or end of the prompt, and validate recall effectiveness using a test set.

    The following example is only for architecture review suggestions; the function only generates report text and does not modify any files.

    1. # Example: Using long context to generate architecture review suggestions (text only, no code modification)
    2. def build_review_prompt(files: dict[str, str], max_chars: int = 400_000) -> str:
    3. """Concatenates project files into a prompt. max_chars is the character limit, used as a rough token budget estimate."""
    4. parts = []
    5. total = 0
    6. for path, content in files.items():
    7. chunk = f"--- {path} ---\n{content}\n"
    8. if total + len(chunk) > max_chars:
    9. parts.append("[Note: Context exceeds the limit, subsequent files are omitted]\n")
    10. break
    11. parts.append(chunk)
    12. total += len(chunk)
    13. return (
    14. "Please analyze the module dependencies based on the following source code, point out potential circular dependencies, "
    15. "and provide splitting suggestions. Only provide analysis conclusions, do not output directly executable modifications.\n"
    16. + "".join(parts)
    17. )
    18. def analyze_project(llm_client, files: dict[str, str]) -> str:
    19. prompt = build_review_prompt(files)
    20. try:
    21. return llm_client.generate(
    22. prompt,
    23. max_tokens=2048, # Limit output length to control cost
    24. temperature=0.2, # Lower randomness for reproducible conclusions
    25. )
    26. except Exception as exc:
    27. # Log error and return empty string, caller decides whether to retry
    28. print(f"Architecture review call failed: {exc}")
    29. return ""

    Inference Cost Control

    Long context brings significant token costs and memory consumption. As context length grows, the KV cache expands, limiting the number of concurrent requests the same hardware can serve. In practice, teams can set context budgets based on task types, cache frequently occurring repository content, and use monitoring to record the input and output token counts for each task. Only in this way can one determine whether an optimization actually reduces costs.

    III. Coding and Agent Tasks: Training Methods and Execution Constraints

    The table below compares the two training methods in coding tasks.

    Dimension Supervised Fine-Tuning (SFT) Reinforcement Learning (RL)
    Training Signal Standard answers Reward function or reward model
    Strengths Format, style, known patterns Multi-step reasoning, exploring new solutions
    Typical Failure Mode Copying surface patterns from training data Exploiting rewards, e.g., deleting assertions
    Data Requirements High-quality annotations Automatically verifiable tasks and test environments
    Main Limitations High annotation cost Learning deviations when reward design is poor

    In Agent scenarios, the model needs to perform planning, tool invocation, result analysis, and self-correction. For example, when assigned a task to “fix a compilation error,” the model first reads the error message, then modifies the relevant file and recompiles. If compilation still fails, the model continues to adjust based on the new logs.

    Agents can execute terminal commands, meaning they can also modify files and install dependencies. Therefore, before execution, it is recommended to check the following items:

    • Context budget: Define the maximum input length; filter the excess with a retrieval module first.
    • Tool permissions: Only grant commands necessary to complete the task; do not access production environment credentials by default.
    • Sandbox environment: Run compilation and tests in isolated containers; code should not directly enter the production branch.
    • Rollback strategy: Create a snapshot before each modification to allow quick recovery in case of failure.
    • Loop limits: Restrict the number of retries; escalate to manual processing if exceeded.

    IV. Security Auditing: Finding Issues vs. Manual Fix Confirmation

    LLMs can identify common web security vulnerabilities, such as SQL injection, Cross-Site Scripting (XSS), and unsafe deserialization. Compared to Static Application Security Testing (SAST) tools that only report vulnerability locations, models can combine context to explain the cause of the vulnerability and draft repair code. This shortens the time from discovery to remediation.

    However, “discovery implies a fix” should not be interpreted as “discovery implies deployment.” When using models, the following limitations must be noted.

    1. False positives and false negatives: The model might misjudge secure code as a vulnerability or miss cross-file data flows. Teams should use known vulnerability sample sets to evaluate recall and precision rates rather than relying on empirical judgment.
    2. Prompt injection: Code comments, third-party documentation, or logs may contain text that induces the model to execute operations. The model should treat this content as data, not instructions.
    3. Fixes introducing new issues: Patches must pass existing tests and regression tests targeting the specific vulnerability.

    The recommended workflow is as follows: the model generates findings and repair suggestions; a security engineer reviews the vulnerability cause and the patch; the patch is tested in a sandbox or staging environment; after passing, it is merged into production by the person in charge. Audit logs should be retained throughout the process, recording inputs, outputs, and approvers.

    Regarding log analysis, LLMs are well-suited for summarizing anomaly patterns from large volumes of logs.