DeepGym
Build RL environments and record agent traces, with rewards that hold up against shortcut answers and infrastructure failures.
DeepGym is a Python library for teams that build gyms and trace datasets, and for researchers who train models on them.
Take the coin-change task in the quickstart below. The answer return -1 passes 3 of its
25 cases, so a verifier that pays partial credit gives it 0.12, and a policy trained on
that reward learns to collect it. A policy that can read the verifier's files has a
shorter route: print the expected output. Outages do damage too. When a sandbox dies
mid-run, the 0 it leaves lands in the group baseline and pushes the policy away from an
answer that may have been right.
DeepGym runs each answer in a sandbox, apart from the verifier wherever the task allows,
and gives a run no verdict when the infrastructure failed rather than the policy, so that
run stays out of training. Before you train, deepgym qa attacks each environment with
answers that should earn nothing (empty, stubbed or reward-hacking ones, depending on the
task) and fails it if any of them earns reward. The rewards
then go to verl, TRL, OpenRLHF, Axolotl or lm-evaluation-harness, and agent episodes are
recorded as traces with their provenance.
Quickstart
pip install deepgym
Score a correct and a wrong answer to a built-in task. It runs locally with no account or
API key. Linux needs bubblewrap installed:
from deepgym import DeepGym, load_environment
dg = DeepGym(mode='local')
env = load_environment('coin_change')
solution = '''
def coin_change(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
'''
wrong = 'def coin_change(coins, amount):\n return -1\n'
batch = dg.run_batch(env, [solution, wrong])
for r in batch.results:
print(r.score, r.passed, r.has_verdict, r.metrics)
# 1.0 True True {'pass_fraction': 1.0}
# 0.0 False True {'pass_fraction': 0.12}
Built-ins pay 1.0 only when every case passes, so the wrong answer scores 0. The share of
cases it passed stays in metrics, and each case's result is in r.cases.
mode='local' runs the answer under sandbox-exec (macOS) or bwrap (Linux) and is for
development. Without either, local runs refuse unless you set
DEEPGYM_ALLOW_UNSANDBOXED=1. On macOS the answer can still read the environment
variables of the shell that started DeepGym, and DeepGym warns, naming the ones that look
like keys.
Your own environment starts from a template that already passes every check:
deepgym new word_stats --kind function # or script, repo-patch, multi-turn
deepgym check word_stats # the reference passes, empty and stub answers fail
deepgym qa word_stats # determinism, reward-hack attacks, your controls
Or define one in code. The verifier reaches the answer only through the
deepgym_solution helpers:
from deepgym import Environment
env = Environment(
task='Write a function `add(a, b)` that returns the sum of two numbers.',
verifier_code=(
'from deepgym_solution import load_solution\n'
'sol = load_solution(solution_path)\n'
'return 1.0 if hasattr(sol, "add") and sol.add(2, 3) == 5 else 0.0\n'
),
)
result = dg.run(env, model_output='def add(a, b):\n return a + b\n')
print(result.score) # 1.0
Training
In training the answers come from a policy you don't trust, so they run in a sandbox provider: Docker, Apple container, Daytona, Modal or E2B. Not every task runs on every provider. Desktop tasks, OSWorld included, need Daytona, and SWE-bench Pro and Terminal-Bench 2.0 need a sandbox with network, such as Daytona. With TRL and Docker:
from datasets import Dataset
from trl import GRPOConfig, GRPOTrainer
from deepgym import DeepGym, load_environment
from deepgym.integrations.trl import make_trl_reward_fn
env = load_environment('coin_change')
reward_fn = make_trl_reward_fn(env, DeepGym(mode='docker')) # or daytona, modal, e2b
trainer = GRPOTrainer(
model='Qwen/Qwen2.5-0.5B-Instruct',
reward_funcs=[reward_fn],
args=GRPOConfig(output_dir='grpo-coin-change'),
train_dataset=Dataset.from_list([{'prompt': env.task}] * 64),
)
trainer.train()
The snippet repeats one task to show the wiring. MixedEnvironment puts SWE-bench Pro,
Terminal-Bench 2.0 and built-ins behind one reward function and sends each completion to
the environment its row's env_name names (TRL). A completion whose sandbox or
verifier failed gets None. TRL 1.6+ leaves a completion out of the group's baseline only
when every reward function returned None for it, so a format reward added beside this
one keeps it in.
verl loads the same scoring from its config, with each dataset row naming its environment
(verl_rows(['coin_change', 'two_sum']) writes them). Its v1 trainer drops a sample
without a verdict instead of scoring it:
reward:
custom_reward_function:
path: pkg://deepgym.integrations.verl
name: compute_score
reward_kwargs: {mode: daytona}
The examples cover OpenRLHF, lm-evaluation-harness, multi-turn sessions, computer-use agents, Claude Code and Codex in the sandbox, traces, and benchmark imports.
Why the rewards hold up
flowchart LR
task["Task"] --> policy["Model<br/>or agent"]
policy -- "answer" --> sandbox["Sandbox"]
sandbox --> verifier["Verifier"]
verifier -- "judged" --> reward["Reward<br/>0 to 1"]
verifier -- "infra failed" --> noverdict["No verdict,<br/>not trained on"]
reward --> trainer["Trainer"]
sandbox -. "each step" .-> trace["Trace"]
- A single-file answer never runs inside its verifier. Verifiers reach it through the
deepgym_solutionhelpers, which start it in a separate process with no network (as another Linux user in a sandbox provider, undersandbox-execorbwraplocally) and pass back only plain data, so it can't read the expected outputs, print a fake score or patch the verifier. - Repo-patch tasks (SWE-bench Pro, MiMo), Harbor tasks and BigCodeBench run the answer's code next to the tests. There the sandbox, the test-infrastructure guard and a fresh grading sandbox do the isolating, and the reward is only as strong as the tests (importers).
- Infrastructure failures are not scored. When the provider or network fails, or the
sandbox or verifier fails before the answer is in play,
dg.runraises, andrun_batch,evaland the trainer reward functions return the run without a verdict (has_verdictis false). The trainer integrations keep it out of training where the trainer allows. - Failures the policy causes are scored. Failing tests, a malformed patch, a patch that touches test infrastructure, an answer that crashes or hangs the verifier, and a sandbox the agent killed all score 0, and a score printed before a crash is never kept.
- Masking has a cost: a policy can learn to trigger failures that look like
infrastructure and escape the penalty.
RewardFunction, the TRL, Axolotl and DAPO reward functions, the OpenRLHF endpoint, the verl agent loops andRubricRewardwarn when more than 5 in 100 samples get no verdict. verl'scompute_scoreand the lm-eval tasks don't. deepgym qafails an environment whose reference doesn't score 1.0 on every rerun, or whose empty, stub or reward-hack answers earn anything above float noise. It also runs the controls you ship, mutants of the reference (--mutants) and a pass@k difficulty probe against your model (--model).deepgym qa --approvestores the report with a hash of every file, anddeepgym checkfails once the folder changes.- In a rubric for an LLM judge, an unmet
mustcheck or a metfatalcheck scores the answer 0 whatever else it got right. A judge reply that was refused, cut off or malformed gets no verdict.calibratemeasures the judge against expert labels (TPR, TNR, Cohen's kappa) before you rely on it. - DeepGym stops every process a CLI agent started before grading, and grades a Harbor task in a fresh sandbox from a copy of its work directory.
- Batch and eval totals still count a run without a verdict as a failed 0, so an outage can only lower a pass rate, and print the judged-only numbers beside them.
The rules are in the reward contract, the QA gate and rubric-judged rewards.
What ships
| Area | Included |
|---|---|
| Environments | 31 built-ins: 22 coding, 5 computer-use desktops with 8 seeded variants each, 2 tool-use, 2 cyber (list). Single-turn, multi-turn (one live sandbox per episode, from Python or over HTTP) and computer use (screenshots in, mouse and keyboard out, scored on the state the agent leaves) |
| Benchmarks | SWE-bench Pro, Terminal-Bench 2.0 and any other Harbor dataset, BigCodeBench, HumanEval, MBPP, EvalPlus, MiMo-V2.6-RL code tasks, CyberGym, and 16 OSWorld LibreOffice tasks (importers); MixedEnvironment puts several behind one reward function |
| Sandboxes | Docker, Apple container, Daytona (cloud or self-hosted), Modal and E2B; local for development. Desktop tasks need Daytona (sandboxes) |
| Agents | Claude Code and Codex CLI inside the sandbox, Anthropic and OpenAI computer-use and API tool agents, with turn, time and cost budgets (agents) |
| Training and eval | verl (reward function and agent loops), TRL, OpenRLHF, Axolotl, lm-evaluation-harness, RewardFunction for your own loop, and a Gymnasium-style reset/step API |
| Authoring | deepgym new, check and qa, controls, mutation testing and approvals (authoring, verifiers); Hugging Face Hub sharing |
| Traces | Recorded with provenance, token usage and cost; exported as JSONL, Parquet rows for verl and TRL, or ATIF (traces) |
| Analysis | Two runs compared task by task with pass@k, pass^k and an exact significance test; scanners for behaviour the verifier missed; versioned datasets with splits by prompt and a manifest hash (compare, scanners, datasets) |
| Review | Labels on runs, episodes, traces and single steps; review queues for expert reviewers, blind by default; judge calibration from stored labels (console) |
| Serving | deepgym serve, an HTTP API with jobs and live sessions (API server); deepgym console, a local web console for environments, runs, episode replay, sandboxes and QA reports (console) |
Agents and traces
An episode is one agent working through a multi-turn task in a sandbox. dg.trace()
records it while it runs, one event per line under ~/.deepgym/traces/ (or
$DEEPGYM_TRACES_DIR), so a crash or a killed process keeps the steps taken so far. Here
Claude Code works on a task inside the sandbox:
from deepgym import DeepGym
from deepgym.agents import Budget, ClaudeCodeAgent
from deepgym.traces import AgentMeta
dg = DeepGym(mode='daytona')
# allow_model_credentials: the CLI, and so the model, can read the provider API key
agent = ClaudeCodeAgent(model='claude-opus-5-5', allow_model_credentials=True)
# env: a MultiTurnEnvironment whose image has the Claude Code CLI, with 'cli' in
# allowed_actions and cli_provider_egress=True (see the examples)
with dg.trace(env, AgentMeta(name='claude-code', model='claude-opus-5-5')) as tr:
agent.run(tr, tr.start(), task=env.task,
budget=Budget(max_turns=None, max_seconds=4 * 3600)) # CLI runs need a deadline
tr.score()
print(tr.trace.has_verdict, tr.trace.usage, tr.trace.cost_usd)
The CLI runs headless as an unprivileged user, and its network reaches only the provider's
hostname on port 443. CodexAgent works the same way. The Anthropic and OpenAI
computer-use and API tool agents drive the sandbox from the host (agents). What
lands in the trace depends on the agent:
| Agent | Records |
|---|---|
| API tool agents | Each step's model messages, token usage and cost |
| Computer-use agents | Each step's token usage and cost, no messages |
| Claude Code, Codex | One step holding the CLI's own events (tool calls, edits, output), and the run's token usage and cost when it ends; no model messages |
| Your own loop | What you pass to tr.step(action, messages, usage=..., cost_usd=...) |
A trace holds:
- Provenance: SHA-256 hashes of the environment, task, verifiers and reference, the image digest the sandbox booted from, the deepgym version and git commit, and the agent, model and sampling config you passed.
- Every step: the action, the model messages behind it when the agent records them (with token ids and logprobs if you have them), token usage and USD cost, what came back, and the step reward.
- The verdict, with every earlier
score()result kept. Usage or cost that a provider never reported stays null, never 0, andusage_completesays whether any is missing.
Export them as training data:
deepgym traces export --format jsonl --out traces.jsonl # whole traces
deepgym traces export --format parquet --rows rl --out rl.parquet # verl / TRL rows
deepgym traces export --format atif --out atif/ --only-valid # ATIF documents
A trace without a verdict is exported with has_verdict: false and its RL row gets a null
reward; --only-valid leaves it out. --rows rl needs the model messages of every turn,
so it skips computer-use, Claude Code and Codex runs. Details are in traces.
Compare two runs
Base model against a checkpoint, or one agent against another, on the same tasks. Give
each run its own DEEPGYM_TRACES_DIR and load the folders:
from pathlib import Path
from deepgym.compare import attempts_from_traces, compare
from deepgym.traces import load_trace
base = [load_trace(p) for p in Path('runs/base').glob('*.jsonl')]
tuned = [load_trace(p) for p in Path('runs/step-400').glob('*.jsonl')]
report = compare(attempts_from_traces(base), attempts_from_traces(tuned))
print(report.flips) # task count per flip
print(report.significance) # exact test: p_value, b_better, a_better, ties
for task in report.tasks:
if task.flip == 'regressed':
print(task.key, task.a.solve_rate, task.b.solve_rate)
- Each task gets its solve rate (pass@1) and mean score on both sides, and a flip: improved, regressed, both solved, both failed, or mixed (a side solved only some of its attempts).
- Each side gets mean pass@k and pass^k (all k attempts pass), and a count of tasks the model never solves, always solves, or solves some of the time.
- The p-value comes from an exact permutation test stratified by task, so it stays valid when tasks have different attempt counts. With one attempt per task it equals exact McNemar.
- An attempt without a verdict counts in no rate. A task whose environment changed between
the runs (its verifier edited, say) is listed as
changedand left out, so a new checkpoint is never compared against an old verifier.
deepgym.passk has the estimators on their own: pass_at_k(n, c, k), pass_hat_k(n, c, k) and task_difficulty(n, c).
Find what the verifier missed
A verifier checks the state the agent leaves. It doesn't see an agent that edited the tests on the way there, or skipped the one that kept failing. Scanners read the trace for that:
from deepgym.scanners import PatternScanner, ProtectedPathScanner, group_findings, scan_traces
scanners = [
ProtectedPathScanner(name='protected', globs=('tests', 'conftest.py')),
PatternScanner(name='skips', patterns=[
{'regex': r'pytest\.skip|@unittest\.skip', 'message': 'Skips a test', 'severity': 'high'},
]),
]
report = scan_traces(traces, scanners) # traces: loaded with load_trace, as above
for group in group_findings(report.findings):
print(group.scanner, group.message, len(group.findings), group.traces)
deepgym traces scan --config scanners.json --out report.json --write-labels
- Each finding cites its trace and step, and quotes the text where the action has it; for file writes and CLI edits the message names the path instead.
ProtectedPathScannerreads shell commands, Python file writes and Claude Code and Codex edits without running anything. It only knows the write patterns listed in the docs, so diff the final workspace when you need every changed file.PatternScannermatches your regexes in actions, observations or messages. It doesn't see a CLI agent's own tool calls.LLMScanner(Python only) has a judge model read each trace with your instruction.- A scanner that fails on a trace is reported as an error for that trace, never as clean, and the CLI exits 3.
--write-labelsstores a label for every finding and every scan error, so a dataset build can drop flagged traces and the ones no scanner cleared.
Expert review and judge calibration
A label is one judgment about a run, episode or trace, or one step or quoted span of it. It comes from a verifier, an LLM judge or an expert, and an expert's label carries the reason. Labels are an append-only log, so a correction supersedes the old label instead of overwriting it.
Review queues hand items to experts. Each item gets overlap reviews from different
people, and reservations never hand it to more reviewers than that. In a blind queue (the
default) a reviewer sees no one else's label, the verifier's and judge's included, until
they submit. That covers only what the queue routes return. The local console has no
login, so anyone can review under another name or read grades from other routes; a shared
setup must put reviewers behind a login that reaches only the queue routes
(console).
from deepgym.console import record_episode
from deepgym.console.db import DEFAULT_DB_PATH
from deepgym.console.queue_store import QueueStore
from deepgym.labels import LabelTarget
from deepgym.review_queues import ItemCreate, QueueCreate, ReviewLabel
queues = QueueStore(DEFAULT_DB_PATH)
queue = queues.create(QueueCreate(
name='judge v3 calibration', instructions='Pass only if the config is fixed.',
label_names=('passed',), overlap=3, blind=True,
))
for t in traces:
record_episode(t) # stores the trace, so the queue can show it to reviewers
trace_ids = [t.trace_id for t in traces]
queues.add_items(queue.id, [ItemCreate(target=LabelTarget(kind='trace', id=t)) for t in trace_ids])
view = queues.next_item(queue.id, 'ana') # None once nothing is left for ana
content = queues.content(queue.id, view.item.id, 'ana') # task, answer and steps, no grades
queues.submit(queue.id, view.item.id, 'ana', [
ReviewLabel(name='passed', value=False, comment='Opens port 80 instead of fixing the config.'),
])
Before you train on an LLM judge's reward, run calibrate. It has the judge grade
expert-labeled answers several times and reports TPR, TNR, Cohen's kappa and the judge's
agreement with itself, beside the experts' agreement with each other. Pass the ids of the
answers you wrote the rubric from as built_from: if any is among the labeled answers, it
raises before calling the judge. report.meets(min_tpr=0.9, min_tnr=0.9) gives a pass or
fail you can put in CI. The console computes the same
numbers from stored labels, without calling the judge (rubric judge,
console).
Build a dataset
deepgym.dataset turns traces and their labels into a versioned dataset with train, val
and test splits:
from pathlib import Path
from deepgym.console.db import DEFAULT_DB_PATH
from deepgym.console.episode_store import read_trace_ids
from deepgym.console.label_store import read_labels
from deepgym.dataset import DatasetSpec, build_dataset, write_dataset
from deepgym.scanners import scanner_forbids
spec = DatasetSpec(
models=('Qwen/Qwen3-8B',),
bands=('learnable',), inside_band=True, # tasks solved 10 to 90% of the time
forbid_labels=scanner_forbids('protected', source='verifier'),
max_cost_usd=0.5,
)
dataset = build_dataset(traces, spec, read_labels(DEFAULT_DB_PATH), read_trace_ids(DEFAULT_DB_PATH))
print(dataset.counts) # kept, per split, dropped per reason
sha256 = write_dataset(dataset, Path('notes-v1'), name='notes', version='1.0.0',
formats=['jsonl', 'parquet'])
deepgym dataset build --spec spec.json --name notes --version 1.0.0 --out notes-v1 \
--format jsonl parquet
deepgym dataset verify notes-v1 --sha256 <the sha256 build printed>
- Copies of one trajectory ship once. Human
passedlabels on any copy are pooled and override the verifier. When humans disagree, every copy is dropped ascontested; when the verifier passed some copies and failed others and no human judged them, every copy is dropped asinconsistent. - Splits go by a hash of the prompt, so one prompt never lands in both train and test, and adding prompts later never moves an existing one.
- Every dropped trace is listed under the reason it was dropped. By default a trace without
a verdict is dropped as
no_verdict, never kept as a fail. manifest.jsonpins every file by SHA-256. Publish the manifest's own hash, anddeepgym dataset verifychecks a downloaded copy against it, file by file.
The console
deepgym console is a local web app over the same database: browse environments, score
solutions on any provider, replay episodes step by step with screenshots, and read QA
reports. Traces stored with record_episode(tr.trace), labels, review queues, scans,
datasets and judge agreement also have REST routes, so you can build your own review tool
or dashboard on top:
| Route | What it does |
|---|---|
/api/runs, /api/runs/compare |
Score solutions in the background; compare two run groups |
/api/traces |
List stored traces with their verdicts; read one with every step |
/api/labels |
Add, correct, retract and query labels |
/api/queues |
Review queues: next item, its content with grades hidden, submit, skip, progress |
/api/scans |
Run rule scanners over stored traces |
/api/datasets |
Build, list and verify datasets |
/api/calibration/agreement |
A judge's stored verdicts against the experts' |
pip install "deepgym[server]"
deepgym console --port 8080 # http://127.0.0.1:8080
It binds to 127.0.0.1 by default, and every API call needs the per-launch token the
console writes into its pages. --ui-dir serves your own UI build in place of the bundled
one (console).
Install
Python 3.10 or later. Optional extras:
| Extra | Adds |
|---|---|
deepgym[daytona], deepgym[modal], deepgym[e2b] |
Those sandbox providers |
deepgym[server] |
deepgym serve and deepgym console |
deepgym[hf] |
Hugging Face Hub sharing and dataset loaders |
deepgym[lm_eval] |
lm-evaluation-harness tasks |
deepgym[traces] |
Parquet trace export |
deepgym[anthropic], deepgym[openai] |
The built-in computer-use and API tool agents; [anthropic] also the Anthropic rubric judge |
deepgym[all] |
Everything above except lm_eval and the agent extras |
Documentation
- Core concepts: how a run moves through environment, sandbox, verifier and trainer
- Examples: every integration and workflow as code
- CLI reference: every
deepgymcommand and its main flags - Environments: built-ins, importers, sessions, computer use
- Authoring: new, check, qa, verifiers, the QA gate, approvals
- Training: the reward contract, rubric judge, verl, TRL, OpenRLHF, Axolotl, lm-eval
- Running: sandboxes, agents, console, API server
- Traces and data: record and export, compare, scanners, datasets
For teams and labs
DeepGym is free for personal, research and other noncommercial use. Commercial use, including inside a company or in a product you sell, needs a commercial license. We also build private environments and verifiers for your tasks, deploy DeepGym privately or self-hosted, and help set up and run RL training. For DeepGym Pro access or a custom RL environment, email contact@deepgym.io or visit deepgym.io.
Contributing
New environments, verifiers, benchmark importers and integrations are all welcome. Start with a good first issue and see CONTRIBUTING.md for setup, tests and releases.
License
PolyForm Noncommercial License 1.0.0. Commercial use needs a license: contact@deepgym.io.
Metadata
Release files for deepgym 0.6.11
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| deepgym-0.6.11.tar.gz | 2.4 MB | Without provenance | Details for deepgym-0.6.11.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| deepgym-0.6.11-py3-none-any.whl | Python 3 | none | any | Details for deepgym-0.6.11-py3-none-any.whl |
Total release size: 4.4 MB
Release files / deepgym-0.6.11.tar.gz
| Download URL | deepgym-0.6.11.tar.gz |
|---|---|
| Size | 2.4 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f94405153116ddfec375daa8eb641867de176c2238e35e8628461e41959badd9
|
|
BLAKE2b-256 checksum How to use checksums |
027d18386a5d0cc6d4582fe02c3da3d0db398698b6dc8cac4d52c88620e23bc5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Release files / deepgym-0.6.11-py3-none-any.whl
| Download URL | deepgym-0.6.11-py3-none-any.whl |
|---|---|
| Size | 2.0 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1a3cbca70e409bc24019a21554abdc45739816bb1a0ae4024fbaae588a912c9e
|
|
BLAKE2b-256 checksum How to use checksums |
ab44b0c7c64dc9213ee01f52a1d4253bbaffbc0a8ed891fd45ba1429f5e29d33
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.16
|
Security for deepgym 0.6.11
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.