Build gyms, record traces, learn from them
A Python library for building RL environments and trace datasets. QA attacks every environment with answers that should earn nothing, and a crashed sandbox gets no verdict instead of a 0.
Loading...
Build environments
Start from a working environment, check it, and gate it before it reaches a trainer. Or bring the tasks you already have.
deepgym newScaffolds a working environment: task, verifier, reference and seeded variants, for function, script, repo-patch or multi-turn tasks.
deepgym checkValidates the files, metadata and protocol output, then runs the reference, empty and stub solutions.
deepgym qa --mutantsAdds reward-hack attacks and mutation testing. With --approve, it writes a read-only approval tied to the hash of every file.
deepgym harbor import | exportRuns Harbor tasks with grading in a fresh sandbox, and exports your environments as Harbor tasks. Importers cover Terminal-Bench 2.0, SWE-bench Pro, HumanEval, MBPP, BigCodeBench, EvalPlus and 2,698 MiMo-V2.6-RL code tasks.
$ deepgym new churn_window --kind function Created churn_window: controls/must_fail/equal_neighbors.py controls/must_pass/run_lengths.py metadata.json reference_solution.py task.md variants.py verifier.py $ deepgym check churn_window ok files task, verifier, reference and metadata ok reference_passes score 1.00 (46/46 cases passed) ok empty_fails score 0.00 (solution does not define a function named longest_run) ok stub_fails score 0.00 (0/46 cases passed) ok protocol 46 cases per run; every failed case says why result: PASS $ deepgym harbor import harborframework/terminal-bench-2.0 --limit 3 ok adaptive-rejection-sampler image=alexgshaw/adaptive-rejection-sampler:20251031 solution=yes ok bn-fit-modify image=alexgshaw/bn-fit-modify:20251031 solution=yes ok break-filter-js-from-html image=alexgshaw/break-filter-js-from-html:20251031 solution=yes 3 of 3 tasks valid
QA that never passes without evidence
Before you train, deepgym qa runs the reference, agents that do nothing, reward-hack attacks and mutants of your reference. A check that can't reach a verdict is inconclusive, and so is the environment. Once QA passes, an approval pins a hash of every file, so an edit fails the check instead of reaching a trainer unreviewed.
passThe check ran and the evidence holds.
failIt ran and found a problem. The command exits 1.
inconclusiveIt could not reach a verdict, so it is not a pass. Exit 2.
skipIt does not apply to this environment, and the report lists it.
$ deepgym qa churn_window --mutants --model Qwen/Qwen3-8B --allow-local-execrunningreference_passesscore 1.00 (46/46 cases passed)deterministic4 runs all scored 1.00empty_failsscore 0.00stub_failsscore 0.00 (0/46 cases passed)hack_resistant5 attacks, max score 0.07 (an exploit is 0.50)mutants_killedmutation score 23/23 (100%) of 23 mutantsdifficulty8/8 samples never came back from the model endpoint after 5 retries
$ deepgym qa fix_runsrunningempty_failsquits at once: score 0.00 (0/13 failing cases fixed)busy_failsuses every action in turn: score 0.00 (0/13 failing cases fixed)random_failsacts at random: score 0.00 (0/13 failing cases fixed)
$ deepgym qa churn_window --mode local --approve --by "$USER" Approved: churn_window/approval.json $ deepgym check churn_window ok approval approved by reviewer-1 on 2026-11-20 with deepgym 0.6.11; all 10 file hashes match result: PASS $ $EDITOR churn_window/verifier.py $ deepgym check churn_window FAIL approval approval.json no longer matches the files (changed: verifier.py); re-run QA, delete approval.json and approve again result: FAIL
approval.json
Written by deepgym qa --approve --by NAME once QA passes. Read-only, with the QA report, who approved it, the deepgym version and a hash of every file.
deepgym check
Fails as soon as a file is changed, added or removed, and names it.
Rewards you can trust
Infrastructure failures are masked, never trained as 0. Anything the policy did is scored, so it can't escape a 0 by breaking things.
The policy acted
Everything that follows from its code or actions is scored.
The infrastructure failed
Failures that aren't the policy's doing get no verdict.
verlDrops the sample, or masks it on the legacy trainer.
TRLGets None, so the group baseline leaves it out.
OpenRLHFGets NaN with infra_failure_score='nan', which dynamic filtering drops.
MaskedRateverl and OpenRLHF warn when more than 5% of a batch has no verdict.
Inspect every trace
Every episode is recorded while it runs: each action, what came back, the reward, and the code and image that produced them.
click (407, 179)
3/3 changes made
Replay
Step through actions and screenshots in deepgym console. Each step is written as it happens, so a crash keeps the steps so far.
Provenance
Hashes of the environment, task, verifiers and reference, the image digest, the deepgym version, and the model and sampling config you ran.
Export
deepgym traces export writes JSONL, Parquet rows for verl and TRL, or ATIF. Traces without a verdict are flagged or left out.
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.
scan.py
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
for group in group_findings(report.findings):
print(group.scanner, group.message, len(group.findings), group.traces)or from the CLI
deepgym traces scan --config scanners.json --out report.json --write-labels
Cited findings
Each finding cites its trace and step, and quotes the text where the action has it. For file writes and CLI edits it names the path.
Protected paths
ProtectedPathScanner reads shell commands, Python file writes and Claude Code and Codex edits without running anything. It knows the write patterns listed in the docs, so diff the final workspace when you need every changed file.
Patterns and judges
PatternScanner matches your regexes in actions, observations or messages, but not a CLI agent's own tool calls. LLMScanner (Python only) has a judge model read each trace with your instruction.
An error is not a clean trace
A scanner that fails on a trace is reported as an error for that trace, never as clean, and the CLI exits 3.
Findings become labels
--write-labels stores 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
Review queues send traces to experts, and their labels are what you measure an LLM judge against before you train on its reward.
Review queues
Each item goes to overlap different reviewers, no more. 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, so a shared setup needs a login that reaches only the queue routes.
Labels
One judgment about a run, episode or trace, or one step or quoted span of it, from a verifier, a judge or an expert. The log is append-only, so a correction supersedes a label instead of overwriting it.
Judge calibration
calibrate has the judge grade expert-labeled answers several times and reports TPR, TNR, Cohen's kappa and its agreement with itself, beside the experts' agreement with each other. report.meets(min_tpr=0.9, min_tnr=0.9) gives a pass or fail for CI.
review_queue.py
from pathlib import Path
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
from deepgym.traces import load_trace
traces = [load_trace(p) for p in Path('runs/base').glob('*.jsonl')]
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, 'reviewer-1') # None once nothing is left for reviewer-1
content = queues.content(queue.id, view.item.id, 'reviewer-1') # task, answer and steps, no grades
queues.submit(queue.id, view.item.id, 'reviewer-1', [
ReviewLabel(name='passed', value=False, comment='Opens port 80 instead of fixing the config.'),
])Datasets a buyer can verify
Turn traces and their labels into a versioned dataset with train, val and test splits, filtered by model, task band, labels and cost.
Splits by prompt hash
One prompt never lands in both train and test, and adding prompts later never moves an existing one.
Verdicts pooled across copies
Copies of one trajectory ship once. Human passed labels on any copy are pooled and override the verifier. When humans disagree, every copy is dropped as contested.
Every drop has a reason
Each 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.
A manifest you publish
manifest.json pins every file by SHA-256. Publish the manifest's own hash, and deepgym dataset verify checks a downloaded copy against it, file by file.
build and verify
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>Train with your stack
Reward functions for verl, TRL, OpenRLHF and Axolotl, tasks for lm-eval, and five sandbox providers behind one switch.
- verl
path: pkg://deepgym.integrations.verl - TRL
make_trl_reward_fn(env) - OpenRLHF
create_openrlhf_router(env, dg, ...) - Axolotl
make_axolotl_reward_fn(env) - lm-eval
make_lm_eval_task(env, name)
- Docker
DeepGym(mode='docker') - Apple container
DeepGym(mode='apple') - Daytona
DeepGym(mode='daytona') - Modal
DeepGym(mode='modal') - E2B
DeepGym(mode='e2b')
make_dataset.py
import pandas as pd
from deepgym.integrations.verl import verl_rows
pd.DataFrame(verl_rows(['coin_change', 'two_sum']) * 64).to_parquet('train.parquet')verl config
reward:
custom_reward_function:
path: pkg://deepgym.integrations.verl
name: compute_score
reward_kwargs: {mode: docker} # or daytona, modal, e2b, apple, auto, localCompare two runs task by task
Base model against a checkpoint, or one agent against another, on the same tasks. Give each run its own traces folder and load both.
- Each task gets its solve rate and mean score on both sides, and a flip: improved, regressed, both solved, both failed, or mixed.
- Each side gets mean pass@k and pass^k (all k attempts pass), and a count of tasks it never, always or sometimes solves.
- The p-value comes from an exact permutation test that compares each task only with itself, so it stays valid when tasks have different numbers of attempts.
- An attempt without a verdict counts in no rate. A task whose environment changed between the runs, such as an edited verifier, is listed as
changedand left out.
compare.py
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)Build your own tools on the console
deepgym console is a local web app for environments, runs, episode replay and QA reports. Its REST routes cover traces, labels, review queues, scans, datasets and judge agreement, so a review tool or dashboard of your own can sit on top.
/api/runs, /api/runs/compareScore solutions in the background; compare two run groups/api/tracesList stored traces with their verdicts; read one with every step/api/labelsAdd, correct, retract and query labels/api/queuesReview queues: next item, its content with grades hidden, submit, skip, progress/api/scansRun rule scanners over stored traces/api/datasetsBuild, list and verify datasets/api/calibration/agreementA judge's stored verdicts against the experts'
terminal
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.