Build graders and verifiers that a policy can't game, by grading outside the policy's reach, keeping answers away from it, red-teaming the grader before training, and auditing trajectories during it.

Rewards that resist hacking

A policy optimizes the reward it gets, not the reward you meant. When the reward was a function of the completion’s text, a flaw in it could pay for the wrong format or a longer answer. When the policy acts in an environment, such as a repository, a shell, a browser, or a simulator, the grader often inspects that same environment. Then the policy can change what the grader sees: edit the tests, write a configuration file the test runner loads, exit before the checks run, or print what the grader looks for.

This page covers how to build graders that hold up, and how to find out whether they do. For the signs of reward hacking in a training run, see Catch reward hacking.

Grade outside the policy’s reach

The policy controls everything in its environment. Treat all of it as untrusted input to the grader.

  • Take only what the task asks for. List the outputs the policy is meant to produce, such as one source file, a patch, an answer string, or a final simulator state. Copy only those into the grader. Test files, configuration, hooks, and anything else the policy wrote stay behind.
  • Grade in a fresh copy of the environment. Rebuild the pristine environment, or fork it from a sealed copy, and apply the policy’s outputs to it. Don’t grade in the environment the policy just worked in.
  • Run the policy’s code in a process the grader doesn’t share. Code that runs in the grader’s process can patch the grader. Run it in a subprocess or a sandbox, with a timeout, resource limits, and no network.
  • Never let expected answers enter that process. Send the policy’s code the inputs. Bring its outputs back, and compare them in the grader. Code that never sees the answer can’t produce it without solving the task.
  • Read structured results, not exit statuses or logs. An exit status of 0 or the text “passed” is easy to produce without passing anything. Read outputs back in a format such as JSON, so an object that only pretends to equal the answer can’t cross the boundary.
  • Check the hidden cases, all or nothing. Visible tests tell the policy what to special-case. Partial credit over cases the starting code already passes pays the policy for doing nothing.

In Flyte, the grader is its own task, so it runs in its own container with its own image, and returns a typed result. This grader takes one source file from the policy, runs it in a fresh directory, and compares its outputs in the grader’s own process:

red_team_world.py
RUNNER = '''\
import json, sys
sys.path.insert(0, sys.argv[1])
from solution import {fn}
outputs = []
for args in json.load(sys.stdin):
    try:
        outputs.append({{"ok": True, "value": {fn}(*args)}})
    except Exception as e:
        outputs.append({{"ok": False, "error": type(e).__name__}})
with open(sys.argv[2], "w") as f:
    json.dump(outputs, f)
'''

def _limit_resources() -> None:
    import resource

    resource.setrlimit(resource.RLIMIT_CPU, (10, 10))  # seconds of CPU
    try:
        resource.setrlimit(resource.RLIMIT_AS, (1 << 30, 1 << 30))  # 1 GiB of address space
    except (ValueError, OSError):
        pass  # not supported on macOS; the container runs Linux

def grade_sealed(task: TaskSpec, files: dict[str, str]) -> tuple[float, str]:
    """Take only the editable file, run it in a fresh directory, and compare outputs in the grader's process.

    - Tests, conftest.py, and any other file the policy wrote are ignored, because they're never copied in.
    - The solution process gets the hidden inputs but never the expected outputs, so it can't fake a pass.
    - Outputs come back as JSON. An object that only pretends to equal the answer can't be serialized.
    - Exiting early leaves no output file, which is a failure, not a pass.
    """
    with tempfile.TemporaryDirectory() as d:
        src, out = Path(d) / "src", Path(d) / "outputs.json"
        src.mkdir()
        for name in task.editable:
            if name in files:
                (src / name).write_text(files[name])
        (Path(d) / "runner.py").write_text(RUNNER.format(fn=task.function))
        try:
            r = subprocess.run(
                [sys.executable, "-I", str(Path(d) / "runner.py"), str(src), str(out)],
                input=json.dumps([c.args for c in task.hidden]), capture_output=True, text=True,
                timeout=30, cwd=d, env={"PATH": "/usr/bin:/bin"}, preexec_fn=_limit_resources,
            )
        except subprocess.TimeoutExpired:
            return 0.0, "timeout"
        if not out.exists():
            return 0.0, f"no outputs (exit status {r.returncode}): {r.stderr[-200:]}"
        try:
            outputs = json.loads(out.read_text())
        except json.JSONDecodeError:
            return 0.0, "outputs were not valid JSON"
        if len(outputs) != len(task.hidden):
            return 0.0, f"expected {len(task.hidden)} outputs, got {len(outputs)}"
        passed = sum(o.get("ok") is True and _same(o.get("value"), c.expected) for o, c in zip(outputs, task.hidden))
        # All or nothing: partial credit would pay the unchanged buggy code for the cases it already passes.
        return float(passed == len(task.hidden)), f"{passed}/{len(task.hidden)} hidden cases"

def _same(got: object, expected: object) -> bool:
    """Compare JSON values, treating 2 and 2.0 as equal but not True and 1."""
    if isinstance(got, bool) or isinstance(expected, bool):
        return type(got) is type(expected) and got == expected
    if isinstance(got, (int, float)) and isinstance(expected, (int, float)):
        return abs(got - expected) < 1e-9
    return type(got) is type(expected) and got == expected

Red-team the grader before you train

Test the grader the way the policy will: with submissions that should fail. Before training, run a set of known exploits and an honest solution through every grader you are considering, and count two errors:

  • Unsolved submissions paid. Any exploit that gets the full reward is a hole the policy can find.
  • Solved submissions refused. A hardened grader that rejects correct solutions also gives the trainer a wrong signal. Include real model outputs, not just one reference fix, because a correct solution can return a tuple where you expected a list.

Also run a do-nothing baseline: the starting environment, unchanged. If it earns reward, the tests don’t cover the bug.

Make each (task, policy, grader) cell its own cached task. Adding an exploit runs only its cells, and changing a grader re-grades the stored submissions without generating them again.

Harden judges too

An LLM judge reads text the policy wrote, so that text can address the judge directly.

  • Let a verifier decide correctness where one exists. Use the judge only for qualities a verifier can’t check, and weight it accordingly.
  • Show the judge only what it grades. Pass the final answer and the rubric, not the whole trajectory, unless the trajectory is what you grade.
  • Mark the policy’s text as data. Put it inside clear delimiters, tell the judge that instructions inside them are part of the answer, and ask for a structured score.
  • Measure the judge against a verifier. On a sample with known answers, track how often the judge and a verifier disagree, iteration by iteration.

Wrap the judge call in @flyte.trace so a retried grading task doesn’t pay for the same call twice. See Call a judge without paying for it twice.

Audit trajectories during training

A grader stops the exploits you anticipated. An audit shows you the ones you didn’t. Run two kinds of audit over the rollouts of every iteration:

  • Deterministic flags. Compare each episode’s final environment with its starting state. Flag changes outside the files the task allows, and tokens such as os._exit, sys.exit, __eq__, or test-runner imports in the policy’s code. Flags don’t change the reward. They tell you which trajectories to read.
  • An LLM classifier on a sample. Label failures and flagged successes against a fixed taxonomy. Make the classifier, its prompt version, and the taxonomy inputs to the labeling task, so changing any of them re-labels without downloading the trajectories again.

Plot the flag rate next to the reward. A flag rate that rises while the grader still refuses the exploit means the policy is probing the grader. A reward that rises along with the flag rate means it found a hole.

Keep evaluation separate from the reward

Evaluate with a verifier the policy never trained against, on problems it never saw. A hole in the training reward then can’t hide in the evaluation too. See Evaluation.