Renaissance Labs · Code
Code / Guide
Guide

How to improve any model at coding

The short version: measure, fix the data, teach the format, reward what passes, measure again.

You do not need a frontier lab to make a model better at code. You need a loop you can trust. This guide is the short version of what the published evidence and the open tooling support, with the caveats attached. Every dataset and tool named here is in the catalog with its license and limits. If you would rather answer a few questions and get a plan, use the recipe builder.

The loop1. Measure with an eval the model cannot have memorized. 2. Fix data quality. 3. Teach the format with SFT. 4. Reward what passes tests (RL with verifiable rewards). 5. Measure again with the same settings. Change one thing at a time.

0. Decide what “better” means

“Good at code” is at least five different skills: completing the next lines, writing a function from a description, fixing a bug in a repository, working in a terminal, and writing SQL. They need different data, different evals and different verifiers. Write down one sentence, such as “resolve more real GitHub issues in Python repositories”, and let it choose your eval. Everything below depends on that sentence.

1. Measure first

Before you change anything, score the model you have. This is the step people skip, and it is the one that makes every later decision honest.

  • Use at least one eval the model cannot have seen. Classic benchmarks such as HumanEval have been public for years and leak into training sets. LiveCodeBench collects new problems with release dates, so you can score only problems published after your model’s training cutoff. For repository tasks, SWE-bench-Live and SWE-rebench (nebius, v1) refresh over time. Be careful with the best-known repository benchmark: OpenAI reported in February 2026 that it had stopped reporting SWE-bench Verified after finding many problems with flawed tests or descriptions and signs of training exposure. Use it to compare with published numbers, not as your only gate.
  • Match the eval to your sentence. Function writing: EvalPlus-style tests. Repository work: SWE-bench-style tasks. Terminal work: Terminal-Bench 2.0.
  • Freeze the settings. Same prompt format, same sampling temperature, same number of samples, same harness version. Different harnesses give different numbers for the same model.
  • Report pass@1 from several samples, not one lucky run. The unbiased estimator is short:
Unbiased pass@k estimator
import numpy as np


def pass_at_k(n, c, k):
    """Unbiased pass@k estimator (Chen et al. 2021, Codex paper).

    n: samples generated per problem, c: samples that passed, k: budget.
    Computes 1 - C(n-c, k) / C(n, k) in a numerically stable product form.
    """
    if n - c < k:
        return 1.0
    return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))


if __name__ == "__main__":
    from math import comb
    # tiny check against the exact combinatorial definition
    for n, c, k in [(10, 3, 1), (10, 3, 5), (200, 37, 10), (20, 0, 5), (20, 20, 5), (5, 1, 5)]:
        exact = 1.0 - comb(n - c, k) / comb(n, k) if n - c >= k else 1.0
        assert abs(pass_at_k(n, c, k) - exact) < 1e-12, (n, c, k)
    assert abs(pass_at_k(10, 3, 1) - 0.3) < 1e-12  # pass@1 is c/n
    print("ok", round(pass_at_k(200, 37, 10), 6))

Verified: ran locally, version seen: Python 3.9.6, numpy. Ran locally on Python 3.9 with numpy: matches the exact 1 - C(n-c,k)/C(n,k) definition for six cases, pass@1 equals c/n, and the check prints ok. Average the result over problems. Needs n >= k. source

LiveCodeBench code generation with release version and date window
git clone https://github.com/LiveCodeBench/LiveCodeBench.git && cd LiveCodeBench
pip install -e .   # or: uv pip install -e .

# generate + evaluate on a fine-grained release (contamination control by release)
python -m lcb_runner.runner.main --model {model_name} --scenario codegeneration \
    --evaluate --release_version release_v6

# re-score only problems released after a cutoff date (YYYY-MM-DD)
python -m lcb_runner.evaluation.compute_scores --eval_all_file {saved_eval_all_file} --start_date 2023-09-01

Verified: matched official docs on 2026-11-24, version seen: LiveCodeBench main (pyproject 0.1.0, Python >=3.10). Flags per the README: --release_version (default release_latest; also v1, v2, v1_v3, v4_v5 style), --evaluate, and compute_scores --start_date/--end_date. {model_name} must be listed in lcb_runner/lm_styles.py; local models take --local_model_path. Uses vllm for open models. Not run locally. The README example uses release_v2 and start_date 2023-09-01 (for DeepSeek); pick a cutoff after your model's training cutoff. Code is executed on the host: run in a container. source

Keep one private eval. Fifty to two hundred tasks from your own domain, with tests, never published, never used for training. It is the only number you can fully trust.

Also read failures by hand. Some benchmark instances have flawed tests or ambiguous statements, so a small difference on a single benchmark is easy to over-read.

2. Fix data quality

If you only change the data, you can still move a model a long way. Three things come first.

  • Deduplicate. Near-duplicate files inflate scores and waste training tokens. datatrove implements MinHash deduplication that you can run locally.
  • Decontaminate. Remove anything that overlaps your eval sets. Plain n-gram matching misses rephrased copies (a 2023 study, arXiv 2311.04850, showed this), which is another reason to keep a private eval and a time-windowed one.
  • Mind licenses. Code corpora carry per-file licenses, and synthetic datasets inherit the terms of the model that wrote them. Keep the metadata.
datatrove MinHash dedup of code, local executor
from datatrove.executor import LocalPipelineExecutor
from datatrove.pipeline.dedup import MinhashDedupSignature
from datatrove.pipeline.dedup.minhash import (
    MinhashConfig, MinhashDedupBuckets, MinhashDedupCluster, MinhashDedupFilter,
)
from datatrove.pipeline.readers import JsonlReader
from datatrove.pipeline.writers.jsonl import JsonlWriter
from datatrove.utils.hashing import HashConfig

cfg = MinhashConfig(hash_config=HashConfig(precision=64), num_buckets=14, hashes_per_bucket=8)
BASE, LOGS, TASKS = "work/minhash", "work/logs", 8
reader = JsonlReader("data/raw_jsonl/", text_key="content")  # code field name in your files

s1 = LocalPipelineExecutor(
    pipeline=[reader, MinhashDedupSignature(output_folder=f"{BASE}/sigs", config=cfg)],
    tasks=TASKS, logging_dir=f"{LOGS}/s1")
s2 = LocalPipelineExecutor(
    pipeline=[MinhashDedupBuckets(input_folder=f"{BASE}/sigs", output_folder=f"{BASE}/buckets", config=cfg)],
    tasks=cfg.num_buckets, logging_dir=f"{LOGS}/s2", depends=s1)
s3 = LocalPipelineExecutor(
    pipeline=[MinhashDedupCluster(input_folder=f"{BASE}/buckets", output_folder=f"{BASE}/remove_ids", config=cfg)],
    tasks=1, logging_dir=f"{LOGS}/s3", depends=s2)
s4 = LocalPipelineExecutor(
    pipeline=[reader, MinhashDedupFilter(input_folder=f"{BASE}/remove_ids"),
              JsonlWriter(f"{BASE}/deduplicated")],
    tasks=TASKS, logging_dir=f"{LOGS}/s4", depends=s3)  # same TASKS and reader as stage 1
s4.run()

Verified: matched official docs on 2026-11-24 (source of example and classes); not executed, version seen: datatrove 0.10.1 (main). Adapted from datatrove examples/minhash_deduplication.py (which uses SlurmPipelineExecutor): same four stages and MinhashConfig values; swapped to LocalPipelineExecutor (signature confirmed in executor/local.py) and added text_key. Class names and args confirmed from source. Not run: datatrove needs Python >=3.11. MinhashDedupSignature has language=Languages.english by default, whose word tokenizer is tuned for prose, so for code consider a custom shingling or a different near-dedup tool and validate on a sample. Decontaminate against eval sets (HumanEval, MBPP, LiveCodeBench) separately. LICENSE: keep per-file license metadata and filter to permissive licenses (for example by SPDX id) before training; The Stack v2 does this by file license detection. PII: scrub emails, keys, and IPs (datatrove has PII/formatting filters; BigCode used StarPII) and honor opt-out lists. source source source

For pretraining-scale data, quality filtering has repeatedly beaten raw volume for smaller models. Stack-Edu and The Stack v3 (train) are the open starting points; OpenCoder repo is the most transparent end-to-end recipe. Most readers will not pretrain. They will use this stage to clean their own SFT and RL data.

3. Teach the format with SFT

Supervised fine-tuning is cheap and fast to iterate. It teaches the model to follow instructions, explain, edit and call tools. Start small, because published results suggest that a few tens of thousands of carefully seeded, checked examples compete with much larger sets: the Magicoder paper (arXiv 2312.02120) used 75K examples from Magicoder OSS-Instruct 75K, and SelfCodeAlign (arXiv 2410.24198) used 74K self-generated, execution-validated pairs.

SFT on a code instruction dataset with TRL SFTTrainer
from datasets import load_dataset
from trl import SFTConfig, SFTTrainer

# Magicoder OSS-Instruct has columns: lang, problem, solution (verified via the HF datasets server).
ds = load_dataset("ise-uiuc/Magicoder-OSS-Instruct-75K", split="train")
ds = ds.map(
    lambda ex: {"prompt": ex["problem"], "completion": ex["solution"]},
    remove_columns=ds.column_names,
)  # standard prompt-completion format, see TRL dataset_formats

trainer = SFTTrainer(
    model="Qwen/Qwen2.5-0.5B",
    args=SFTConfig(output_dir="out/sft-code", packing=False),
    train_dataset=ds,
)
trainer.train()

Verified: matched official docs on 2026-11-24; dataset columns checked via datasets-server; not executed, version seen: TRL main (VERSION 1.19.0.dev0). SFTTrainer(model=<str>, train_dataset=...) and SFTConfig(packing=...) come from the TRL docs; prompt-completion datasets are supported. Not executed locally (TRL main requires Python >=3.11, local is 3.9, and training needs a GPU). The dataset is GPT-3.5 generated, so check OpenAI terms and license before commercial use. Swap model for your base model. source source

Check teacher termsMany synthetic sets were written by proprietary or open-weight teachers. Their cards name the teacher, and some are non-commercial. Look at the license and the caveats on each resource page before you train a model you plan to ship.

4. Preference data (optional)

Preference optimization is useful when SFT has plateaued and you want a cheap step before RL. Pairs derived from test results are far more reliable than pairs picked by another model. AceCoder (arXiv 2502.01718) built pairs from test cases and reports gains from both reward models and RL; its data is in AceCode-V2-122K (TIGER-Lab). If you can run tests, building on-policy pairs from your own model’s samples is often a better use of your time than a public set. Control for length, or the model learns that longer is better.

5. Reward what passes: RL with verifiable rewards

Code is one of the few domains where you can check the answer by running it. That is the idea behind RL with verifiable rewards: sample several solutions per task, run the tests, reward the ones that pass. Open recipes such as DeepCoder (14B model card) and Skywork-OR1 (arXiv 2505.22312) report gains this way. The hard part is not the algorithm. It is the verifier.

Pick the task source to match the verifier

Keep a middle band of difficulty

With group-relative methods such as GRPO, a task where every sampled solution gets the same reward teaches nothing. Tasks the model always solves or never solves are wasted compute. Slide the figure to see how fast the useful fraction collapses at the extremes.

50%
Bars: the chance that a group of 8 rollouts for one task is mixed (some pass, some fail), assuming each rollout passes independently with the pass rate on the x-axis. Groups where every rollout gets the same reward have zero advantage under group-relative methods such as GRPO, so they teach nothing. This is why RL task sets are filtered to a middle band of difficulty. Computed as 1 - p^8 - (1-p)^8.

In practice, sample your own model several times per task and keep tasks with mixed outcomes. Some datasets ship difficulty fields you can use as a first filter. DeepCoder’s card also describes filtering overlong and truncated samples.

Start from a model that already solves some tasks

The published open recipes start from strong distilled or instruct models (DeepCoder, AceReason and Skywork-OR1 all start from R1-distilled bases). From a weak start, most rollouts fail and the signal is thin. Do SFT first.

Build the verifier like an adversary is attacking it

One is. Models optimize whatever you reward. Documented cases include reading the future fix from git history, editing the tests, and fetching solutions from the web. See pitfalls. The minimum:

  • Run generated code in a container with no network, a read-only filesystem, and memory, CPU and process limits.
  • Put the tests in after the agent finishes, from outside the sandbox. Never leave them where the agent can read or edit them.
  • Strip future git history from repository tasks.
  • Check each task with a reference solution: it must pass, and the unfixed code must fail.
Hardened Docker run for untrusted generated code
docker run --rm \
  --network none \
  --read-only \
  --memory 256m --memory-swap 256m \
  --cpus 1 \
  --pids-limit 64 \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --user 65534:65534 \
  --tmpfs /tmp:rw,noexec,nosuid,size=16m \
  -v "$PWD/job:/work:ro" -w /work \
  python:3.12-slim timeout 10 python candidate.py

Verified: ran locally (Docker 29.1.3); flags checked in docker/cli source, version seen: Docker 29.1.3, python:3.12-slim. Every flag exists in docker/cli container opts source (network, read-only, memory, pids-limit, cap-drop, security-opt, user, tmpfs, cpus). A near-identical command was run on Docker 29.1.3 with python:3.12-slim: the script ran as uid 65534, outbound socket failed, writes to the read-only mount failed, and writes to /tmp worked. Kernel shared with host: for adversarial code add gVisor/Firecracker and seccomp. The timeout is the coreutils one inside the image (not separately tested); also enforce a wall-clock kill from the outside (docker kill). source source

Reward function: run code plus tests in a subprocess with limits
import os
import subprocess
import sys
import tempfile

try:
    import resource  # POSIX only
except ImportError:  # pragma: no cover
    resource = None


def _limits(cpu_seconds, mem_bytes):
    def apply():
        if resource is None:
            return
        os.setsid()
        resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds))
        resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20))
        resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
        if sys.platform.startswith("linux"):  # RLIMIT_AS is unreliable on macOS
            resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
            resource.setrlimit(resource.RLIMIT_NPROC, (64, 64))
    return apply


def run_tests(code, tests, timeout=5.0, mem_mb=512):
    """Return 1.0 if `code` followed by `tests` exits 0 within `timeout` seconds, else 0.0.

    NOT a security sandbox: no network or filesystem isolation. Use Docker/gVisor for untrusted code.
    """
    program = code + "\n\n" + tests + "\n"
    with tempfile.TemporaryDirectory() as tmp:
        path = os.path.join(tmp, "main.py")
        with open(path, "w") as f:
            f.write(program)
        try:
            proc = subprocess.run(
                [sys.executable, "-I", path], cwd=tmp, stdin=subprocess.DEVNULL,
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout,
                env={"PATH": os.environ.get("PATH", ""), "PYTHONHASHSEED": "0"},
                preexec_fn=_limits(int(timeout) + 1, mem_mb << 20),
            )
        except subprocess.TimeoutExpired:
            return 0.0
        return 1.0 if proc.returncode == 0 else 0.0


if __name__ == "__main__":
    tests = "assert add(2, 3) == 5"
    assert run_tests("def add(a, b):\n    return a + b", tests) == 1.0
    assert run_tests("def add(a, b):\n    return a * b", tests) == 0.0
    assert run_tests("while True:\n    pass", tests, timeout=1.0) == 0.0
    assert run_tests("def add(a, b:\n", tests) == 0.0  # syntax error
    print("ok: pass=1.0 fail=0.0 timeout=0.0 syntax-error=0.0")

Verified: ran locally, version seen: Python 3.9.6. Ran locally on Python 3.9 (macOS): passing example returns 1.0, failing 0.0, infinite loop 0.0 (timeout), syntax error 0.0. NOT a security sandbox: no network or filesystem isolation, and memory/process rlimits are applied only on Linux. Use inside a container (see docker-hardened-sandbox) for untrusted code.

GRPO with a unit-test execution reward (MBPP) in TRL
import re
from datasets import load_dataset
from trl import GRPOConfig, GRPOTrainer
from reward import run_tests  # from the subprocess reward snippet (code-reward-subprocess)

ds = load_dataset("google-research-datasets/mbpp", "full", split="train")
ds = ds.map(lambda ex: {"prompt": ex["text"] + "\nReturn only a Python code block."})


def extract_code(text):
    m = re.search(r"```(?:python)?\n(.*?)```", text, re.S)
    return m.group(1) if m else text


def unit_test_reward(completions, test_list, test_setup_code, **kwargs):
    """Called by GRPOTrainer with prompts, completions, completion_ids, trainer_state
    plus every dataset column except prompt (here test_list, test_setup_code).
    Must return one float per completion."""
    rewards = []
    for completion, tests, setup in zip(completions, test_list, test_setup_code):
        code = (setup or "") + "\n" + extract_code(completion)
        rewards.append(run_tests(code, "\n".join(tests), timeout=5.0))
    return rewards


trainer = GRPOTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",
    reward_funcs=unit_test_reward,
    args=GRPOConfig(output_dir="out/grpo-mbpp", num_generations=8, max_completion_length=512),
    train_dataset=ds,
)
trainer.train()

Verified: matched official docs on 2026-11-24; reward helper ran locally; trainer not executed, version seen: TRL main (VERSION 1.19.0.dev0). Reward signature (completions plus **kwargs carrying dataset columns, returns list of floats) is per the TRL GRPO docs; MBPP columns (text, code, test_list, test_setup_code) were checked on the HF datasets server. GRPOTrainer itself was not run locally (needs Python >=3.11 and a GPU); the run_tests helper was run locally. run_tests is not a sandbox, so run training workers inside a container with no network (see docker-hardened-sandbox). Reward hacking is possible: tests are visible in the dataset, so for real runs hold out tests the model never sees. source source

For larger runs, use a framework built for rollouts, such as verl. TRL is fine for small experiments.

6. Re-measure, and keep what helped

Run the same evals with the same settings. Look at three things: the target score, a general-coding regression check (RL on competitive problems can hurt other behavior), and a handful of outputs read by eye. If something got worse, undo the last change before adding another.

What we know, and what we do not

  • Well supported: contamination inflates classic benchmarks; deduplication and quality filtering help; small checked SFT sets are competitive; test-verified RL moves reasoning and repository scores for models that start strong; verifiers get hacked.
  • Contested: whether large-scale RL beats distillation for small models. The OpenCodeReasoning paper (arXiv 2504.01943) reports strong SFT-only results, while AceReason (arXiv 2505.16400) argues large RL can go further. Run both at your scale if it matters.
  • Not known to us: the right data mixture for your base model and language mix. No page can tell you that. Your private eval can.

Numbers quoted on resource pages come from the cited source on the check date. Benchmarks and leaderboards move fast, so confirm any score at its source.