Practices in Improving Code Models with Pure Reinforcement Learning

    This article explores how to use pure reinforcement learning (RL) to enhance large language models for real-world software engineering tasks. It covers defining executable success criteria, designing hack-resistant reward functions, managing training loops and resource control, conducting rigorous evaluations, and implementing deployment strategies for continuous improvement.

    For a code model to be useful in real engineering, it must do more than generate syntactically correct snippets. It must modify the correct files under constraints, pass tests, and avoid introducing regressions. The industry commonly uses Supervised Fine-Tuning (SFT) as a baseline and applies Reinforcement Learning (RL) based on verifiable signals to further align behaviors. “Pure RL” in this context does not mean abandoning existing knowledge; rather, it relies primarily on environmental feedback rather than manual, item-by-item rewrites to update a policy that already possesses foundational coding capabilities. It addresses the problem of “how to consistently solve more problems correctly,” rather than serving as a mere marketing slogan.

    How to Define the Task

    First, define success criteria as executable checks rather than vague “better code” metrics. Common checks include passing public or private tests, clean type and static checks, patches modifying only allowed paths, and no runtime timeouts or resource exhaustion. Task descriptions should include failure symptoms, relevant module boundaries, and acceptance criteria to prevent the model from guessing interfaces.

    Data should ideally be stratified by difficulty and failure type: single-function defects, cross-file dependencies, environment configuration errors, and missing boundary conditions. Each layer needs sufficient control samples; otherwise, the average score will be inflated by simple problems, masking whether difficult problems actually improved. Historical commits, minimal reproductions, and fixed dependency versions help reduce randomness. For tasks involving external networks or non-reproducible services, use offline fixtures; otherwise, reward noise will dominate training.

    Designing a Hack-Resistant Reward Function

    Passing tests is a strong signal, but not the only one. If the model is only rewarded for an “exit code of zero,” the policy might delete assertions, relax timeouts, hardcode expected outputs, or modify tests instead of implementations. A more robust approach is to split the reward: functional correctness makes up the primary portion, while penalties or invalidations are applied for tampering with tests, expanding the scope of changes, or introducing high-risk calls. Static checks, diff size, and touching forbidden paths are better suited as constraints rather than simply added to the correctness score, preventing the model from trading “fixing it properly” for “changing fewer lines.”

    Rewards must be reproducible and auditable. Under the same seed, image, and dependency lockfile, repeated runs should yield similar results. Random failures must be recorded separately from genuine errors, or the policy will chase noise. Be cautious with partial scores: too many intermediate rewards can lead the model to optimize process metrics rather than final correctness, while too few leave long-horizon tasks without learnable signals. In practice, it is common to use “final pass/fail” as the primary metric with a few process constraints, alongside manual spot-checks to detect reward hacking.

    A representative acceptance logic can be expressed in the following pseudocode, illustrating the judgment sequence rather than corresponding to any specific product API:

    1. result = run_in_sandbox(patch, tests, timeout, resource_limit)
    2. if result.touched_forbidden_paths or result.mutated_tests:
    3. return invalid
    4. if not result.tests_passed:
    5. return fail
    6. if result.static_checks_failed:
    7. return partial_or_fail
    8. return pass

    Training Loop and Resource Control

    A single training loop typically involves: sampling tasks, generating patches in an isolated environment, executing checks, aggregating rewards, updating the policy, and finally evaluating for regressions on a holdout set. Updates should be incremental and rollbackable, keeping the previous policy version as a baseline. Code environments are more compute-intensive than pure text scoring: dependency installation, compilation, and testing are often more expensive than generation itself. Therefore, cache images, limit concurrency, and implement fast circuit-breaking on failures to avoid exhausting the budget on repeated installations.

    Container platforms are suitable for fixed runtimes, object storage for storing patches, logs, and failed cases, and message queues for decoupling evaluation tasks from the training process. Logging and monitoring alerts are essential for detecting timeout spikes, sandbox escape attempts, and sudden shifts in reward distribution. These are general capability categories. If deployed in a cloud environment like Baidu AI Cloud, selection should be based solely on capacity, isolation, and auditing capabilities, rather than treating “able to run training” as some unverified specific capability.

    Exploration must have boundaries. Allow the model to try multiple repair paths, but default to prohibiting arbitrary outbound connections, privilege escalation, and unnecessary file deletions. Set upper limits for timeouts, memory, and process counts. Failed samples must be sanitized before entering the next round to avoid writing secrets or internal addresses into the training set.

    Evaluation Beyond a Single Metric

    A single total score is easily influenced by the test bank distribution, random seeds, and evaluation leakage. More valuable metrics include: pass rates by difficulty, the number of newly introduced failures after a fix, whether patches can be manually merged, latency under the same budget, and the variance across multiple runs. When comparing against a baseline, fix the prompts, decoding parameters, tool permissions, and test set versions. The baseline itself must be an equivalently configured setup, not an unfair comparison like “one with tools, one without.”

    Preventing data contamination is equally critical. If training and evaluation tasks share the same source, high scores only indicate memorization. Holdout sets should be split from the training set by time or repository and rotated regularly. For claims like “significant lead over the previous version,” report the sample size and specify which categories improved and which regressed. Without these, the multiplier lacks engineering significance.

    Human review remains indispensable. Automated tests cannot cover whether semantics meet requirements, whether comments align with implementations, or whether hidden compatibility issues are introduced. Spot-checks should cover the categories with the most failures and samples with abnormally high rewards, the latter often signaling reward hacking.

    Deployment and Continuous Improvement

    Before going live, use shadow traffic or a small canary release to compare new and old policies: accuracy, rollback rate, manual takeover rate, and cost per task. If widespread mis-fixes or security alerts occur, you should be able to immediately revert to the previous version. After deployment, re-sanitize, deduplicate, and stratify real failures to decide whether to add data, modify rewards, or tighten tool permissions, rather than blindly increasing training steps.

    Teams can follow this sequence for implementation: first standardize task and sandbox standards, then solidify reward and anti-cheating rules, followed by establishing repeatable comparative evaluations, and only then scale up RL. This ensures that improvements come from an explainable closed loop, not an unverifiable benchmark run.