Python API¶
The command line is a thin layer over this API. Everything below is importable from the package named in each heading; anything not listed here, or starting with an underscore, is internal and may change between releases.
Tasks¶
TaskBuilder(root, config, *, overwrite=False)
¶
Writes one task directory step by step; finish validates it.
capture(capture, media_dir, *, visibility=None)
¶
Write the method-visible part of capture and only the media it still references.
With visibility, fields it does not expose are withheld, and what was withheld is
recorded in hidden/visibility_audit.json.
visible_doc(name, *, text=None, source=None)
¶
Add a reference document under visible/docs/.
visible_tool(name, source)
¶
Add a tool (file or directory) under visible/tools/.
reference(source=None, *, tracks=None)
¶
Store the true output of the recorded event, from a directory or tracks.
repeat(index, source=None, *, tracks=None)
¶
Store another recording of the same event, used for the noise floor.
generator(twin_dir)
¶
Store a twin package that generates the truth (synthetic tasks).
hidden_file(relative, *, text=None, source=None)
¶
Store any other file scoring needs under hidden/.
instruction(text)
¶
Replace the generated task statement with text ({workspace} is substituted).
finish(*, validate=True)
¶
Write task.toml (which marks the directory as a task from then on, instead of
:data:BUILD_MARKER); validate the directory unless validate is false.
load_task(root)
¶
Load the task at root; SpecError if task.toml is missing or invalid.
validate_task(root, *, check_references=True)
¶
Check the task directory at root and return every issue found.
find_tasks(root)
¶
Every task directory at or below root (directories holding task.toml).
Task(root, config, toml_digest=None)
dataclass
¶
A task directory with its parsed task.toml.
toml_digest = field(default=None, compare=False)
class-attribute
instance-attribute
¶
The SHA-256 of the task.toml bytes config was parsed from (:func:load_task):
whether the file changed since is told by its bytes (a parsed nan, in a free-form
table, is never equal to itself).
generator_dir
property
¶
The truth generator (a twin package), when the task has one.
capture()
¶
The visible capture.
reference_dir()
¶
The true output of the recorded event, in the task's output format.
repeat_dirs()
¶
Other recordings of the same event, for the noise floor; may be empty.
content_hash()
¶
SHA-256 of the whole task directory: the cache key of everything built from it.
changed_since(task_hash)
¶
Whether the directory is no longer the version task_hash names, or its
task.toml is no longer what config was parsed from (an edit after it was
loaded): told by its bytes when they were kept (toml_digest), else by what the file
says now.
describe()
¶
A JSON-compatible summary for r2s task show (no hidden values).
TaskConfig
¶
Bases: StrictModel
The content of task.toml.
license = Field(min_length=1)
class-attribute
instance-attribute
¶
SPDX identifier or a short statement, e.g. CC-BY-NC-4.0 or none (fetched at run
time).
redistributable
instance-attribute
¶
Whether the task directory may be shared; data that is not must be fetched, not copied.
visibility = None
class-attribute
instance-attribute
¶
Name of the visibility tier the visible directory was made with, e.g. calibrated.
split = Split.EVAL
class-attribute
instance-attribute
¶
eval (the default) or train. Training data is exported only from train tasks
unless asked otherwise, so evaluation tasks stay out of training sets.
metadata = Field(default_factory=dict)
class-attribute
instance-attribute
¶
Free-form data for the benchmark adapter; never shown to methods.
Captures¶
Capture
¶
Bases: StrictModel
A complete observation record of one physical event.
extensions = Field(default_factory=dict)
class-attribute
instance-attribute
¶
Rare, method-specific inputs (e.g. joint torques, LiDAR) kept out of the core schema.
media_paths()
¶
Relative paths of every media file the capture references.
object_names(role='dynamic')
¶
Names of the scene objects with role (None: every object).
restricted(field_paths)
¶
A copy that keeps only field_paths (plus the always-visible fields).
windowed(start, end)
¶
A copy whose views all expose only visible frames [start, end).
load_capture(capture_dir, *, check_media=True)
¶
Load and validate <capture_dir>/capture.json.
With check_media, every referenced media file must exist, and per-frame extrinsics
must have the right shape and be rigid. Videos are not decoded. Raises SpecError
listing every problem.
Twins¶
TwinManifest
¶
Bases: StrictModel
The content of twin.json. Written by the Lab or a method adapter, never by an agent.
load_twin(root, *, rules=None)
¶
Read and validate a twin directory. Raises InvalidTwinError listing every problem.
rules are the task's program rules (defaults apply when None).
fingerprint
¶
Content fingerprints that make frozen programs and directories verifiable.
OS_LITTER = frozenset({'.DS_Store', 'Thumbs.db', 'desktop.ini'})
module-attribute
¶
Files a file manager leaves in a directory it opened (macOS Finder, Windows Explorer).
EXECUTABLE = 1 << 63
module-attribute
¶
Set in a file's size field for a file someone may execute: a program that runs a helper
(./helper.sh) behaves differently without the bit, so it is content. Files without it
fingerprint as before.
SymbolicLinkError
¶
Bases: ValueError
What :func:fingerprint raises for a symbolic link in the directory: a ValueError
of its own, so a caller that reports links later (once it has copied the directory, say)
never takes another error for one.
is_os_litter(name)
¶
Whether a file named name is a file manager's, not anyone's content (.DS_Store,
macOS's ._ companions, Thumbs.db): content checks of what the Lab wrote skip it.
sha256_file(path)
¶
SHA-256 of a file's bytes.
fingerprint(directory, *, exclude=())
¶
SHA-256 over every file's relative path, executable bit and bytes, in sorted path order.
Directories contribute only through the files they hold, so an empty directory does not
change the fingerprint, nor does a file manager's litter (:func:is_os_litter): looking
at a run directory in Finder does not make its programs "changed". exclude lists
top-level names to skip. Raises :class:SymbolicLinkError (a ValueError) on a symbolic
link.
A path counts as the bytes the file system holds for it (:func:os.fsencode): the same as
its UTF-8 encoding for every name that is UTF-8, and a name that is not (a file unpacked
from an archive made on Windows, its name in another encoding) still has a fingerprint.
text_digest(*parts)
¶
SHA-256 of strings joined unambiguously; used for cache keys.
run_twin(twin, run_dir, *, backend, label='run', seed=0, limits=None, requirements=None, attempt=1)
¶
Run twin once and record the outcome in run_dir, which must not exist.
Caller errors raise before run_dir is created: a modified twin, an unavailable image,
an out-of-range seed, an existing run_dir. The program's own failures are recorded in
the result instead.
Experiments¶
parse_experiment(data, origin='<config>')
¶
Build a config from its TOML form; method tables may hold options inline.
load_experiment(path)
¶
Read an experiment file; return it and the directory relative paths start from.
Relative task paths and method options that name files (PATH_OPTIONS) start from the
file's directory.
run_experiment(config, out_dir, *, base_dir=None, backend=None, resume=True, log=None, report=True)
¶
Run config into out_dir, resuming a previous run there unless resume is false.
Results
¶
Bases: StrictModel
An experiment's aggregate over tasks, seeds and trials.
Training¶
score_solution(task, solution, *, backend='docker', work_dir=None, seed=0, session_output=None, method=SOLUTION, statement_root='/workspace')
¶
Score the solution in solution on task (a task or its directory).
solution holds what a method delivers for the task's convention (run.py and its
files), or is a twin package whose program/ holds it; either is taken as it is, never
through a symbolic link in its place (that scores 0, as a solution that cannot be
delivered). session_output, when given, is the output the solution's author saw,
compared with the frozen run's (session_consistent); one the Lab may not read as it is
(a symbolic link, a pipe, a file it cannot read) is not compared, and one that does not
read as its kind does not match. The run's files are kept in work_dir (a temporary
directory otherwise); a work directory used before is cleared first, so a scoring can be
retried in the same place. Raises :class:RewardUnavailable when the run
failed for a reason outside the solution.
reward_of(result)
¶
A task result as a reward in [0, 1]: the reproduction skill under the reproduction protocol; under the native protocol, the headline metric scaled by its range (reversed when lower is better). 0 when nothing could be scored (no delivery, a failed run).
Scored(reward, result)
dataclass
¶
A solution's reward and the full task result it comes from.
export_dataset(out, *, tasks=(), runs=(), against=(), allow_eval_tasks=False, min_reward=None, include_undelivered=False, skip_unmatched=False, overwrite=False, command=None, cache=None)
¶
Export the tasks under tasks and the counted results of the runs in runs (run
directories) to out, leaving out those that overlap a task under against; see the
module docstring for the layout and the rules. Video thumbnails are kept in cache
(default: the Lab's cache).
ExportSummary(out, tasks=0, runs=0, programs=0, skipped=(lambda: [])(), checked_against=None, overlapping=(lambda: [])())
dataclass
¶
tasks = 0
class-attribute
instance-attribute
¶
Rows of tasks.jsonl.
runs = 0
class-attribute
instance-attribute
¶
Rows of runs.jsonl.
programs = 0
class-attribute
instance-attribute
¶
Rows of runs.jsonl with a delivered program.
skipped = field(default_factory=lambda: [])
class-attribute
instance-attribute
¶
What was left out, and why.
checked_against = None
class-attribute
instance-attribute
¶
Evaluation tasks the training tasks were compared with; None: not checked.
overlapping = field(default_factory=lambda: [])
class-attribute
instance-attribute
¶
Tasks left out because they overlap an evaluation task.
fit_method(method, dataset, out, *, seed=0, overwrite=False, log=print)
¶
Train method on the exported dataset and write its checkpoint to out.
RewardUnavailable(message, result, fix=None)
¶
Bases: InfrastructureError
The solution could not be scored for a reason outside it (infra_error).
TrainContext(dataset, checkpoint_dir, seed=0, log=lambda message: None)
dataclass
¶
TrainingRecord
¶
Bases: StrictModel
What a checkpoint was learned from (training.json).
method
instance-attribute
¶
The registered method name.
options = Field(default_factory=dict)
class-attribute
instance-attribute
¶
The method's options while training.
dataset
instance-attribute
¶
The dataset directory, as given.
dataset_digest
instance-attribute
¶
SHA-256 of the dataset's tasks.jsonl and runs.jsonl.
task_ids = ()
class-attribute
instance-attribute
¶
The training tasks (of tasks.jsonl and of the runs).
prints = PRINTS_FILE
class-attribute
instance-attribute
¶
The overlap prints of the training tasks (training-prints.npz, in the checkpoint):
an evaluation with the checkpoint skips every task they overlap.
content_digest = None
class-attribute
instance-attribute
¶
SHA-256 of the checkpoint's files as training wrote them (every file but this record,
:func:content_digest): a checkpoint changed since is refused, not used. r2s train fit
always writes it: a checkpoint without it (its record edited, or written by a pre-release
build of the Lab) is refused too.
same_recording(a, b)
¶
How a and b show the same recording, or None: either is (nearly) contained
in the other, at one time offset (see the module docstring).
OverlapIndex(prints=())
¶
Prints of a set of tasks, to find which of them another task overlaps.
find(item)
¶
The first task of the index that item overlaps, and why; None if none.
save(path)
¶
Write the index to path (one .npz file).
load(path, *, fix='export the dataset again')
classmethod
¶
The index saved at path; SetupError with fix if it is missing, damaged or
written by another version of the overlap check.
digest()
¶
A digest of the tasks and files indexed.
Extending¶
BenchmarkAdapter
¶
Bases: ABC
Builds task directories for one benchmark.
training_terms = None
class-attribute
¶
The benchmark's own terms, quoted, when they forbid training on its data: its tasks are
then never exported as training data, whatever the user asks (r2s train export).
splits = ('eval',)
class-attribute
¶
The splits the adapter builds: eval, and train when the benchmark releases
training data that its terms allow training on. build then takes split="train"
and writes tasks with split = "train", which r2s train export accepts.
source_files()
¶
Every file that can shape this adapter's tasks: all of its top-level package (code, data, pins) and the Lab's own code and data, except the CLI and the report.
source_digest()
¶
A digest of :meth:source_files. Experiments rebuild the tasks they cached when it
changes, even if the Lab's version string does not; a task whose content does not
change keeps its hash, so its finished builds are still reused.
task_names()
abstractmethod
¶
The tasks (or task groups) this adapter can build.
build(out_dir, *, select=None, **options)
abstractmethod
¶
Write task directories under out_dir; return their paths.
options_taken(*read)
¶
The options build takes, for the error that refuses one it does not
(UnknownOptionError.from_names): its parameters but those a command sets itself
(NOT_OPTIONS), and read, those it reads from its **options.
training_refusal(task)
¶
Why task, one of this benchmark's, may never be training data, or None.
By default the benchmark's training_terms. Override it when only some tasks are
restricted, e.g. clips taken from another benchmark whose terms forbid training.
build_split(out_dir, split, /, *, select=None, **options)
¶
Build the tasks of split (r2s bench build --split). Refuses a split the
adapter does not declare, and checks that every task it wrote is marked with it.
Method(**options)
¶
Bases: ABC
A way of building twins from a task's visible data.
kind = 'method'
class-attribute
¶
agent, baseline or method.
method_version = '1'
class-attribute
¶
Bump when a method's behaviour changes, so cached builds are redone.
trainable = False
class-attribute
¶
Whether the method learns from data (train); its Options then derive from
TrainedOptions.
checkpoint
property
¶
The checkpoint the method was given (checkpoint=DIR), if any.
checkpoint_digest()
¶
The content fingerprint of the checkpoint (read once per method), if any.
config_digest()
¶
A digest of the method and its options, part of every cache key of its builds, and of its checkpoint's content: training again redoes the builds.
problems(backend)
¶
What prevents this method from running with backend; empty when ready.
applicable(task)
¶
Why this method cannot deliver for task at all, or None if it can.
Only for methods that make one kind of delivery whatever the task (a baseline that
writes run.py programs, a pipeline with one output format): a task they cannot
deliver for is reported as not applicable instead of scoring zero. A method that could
deliver and fails to is a result, not this. Agents adapt to every task.
held_out(task)
¶
Why task is not held out from this method's training data, or None.
A method given a checkpoint must not be evaluated on a task that overlaps one of the
tasks it learned from (the same recording: :mod:real2simlab.task.overlap).
train(context)
¶
Learn from the dataset in context and write what was learned in its
checkpoint_dir. Only for trainable methods.
build(context)
abstractmethod
¶
Build a twin for the task in context.
package_twin(context, program_dir, *, method, entrypoint=None, agent=None, model=None, privileged=False, notes=None)
¶
Freeze program_dir as the build's twin, with twin.json written by the Lab.
environment, output_format and origin come from the task and the method,
never from the program's author. Raises InvalidTwinError if the program breaks the
task's rules.
AgentMethod(**options)
¶
Bases: Method
A coding agent that builds a twin in a sandboxed workspace.
agent_image = None
class-attribute
¶
The agent's environment; None runs it in the task's runtime image.
version_command = None
class-attribute
¶
The CLI's version command, e.g. ("codex", "--version").
reports_cost = None
class-attribute
¶
Whether its runs can say what they cost (the record's cost_usd); None: whether
the agent implements :meth:cost. See :meth:cost_reported.
command(context, workspace)
abstractmethod
¶
The agent CLI's argv inside the sandbox; its stdin is the task statement.
credentials(context)
¶
Credentials to inject; raise SetupError if they are missing.
credential_status()
¶
Whether credentials are configured, without fetching them (no commands run, no
secret read). None: this agent cannot tell without fetching them.
version(backend, image)
¶
The agent CLI's version, recorded with every run and in its twin's origin:
version_command run offline in the image the agent runs in, by Docker or by the
backend itself (bwrap); on the host only for a backend that does not isolate (the agent
is the host's). None when it cannot be told there, never the host's CLI of that
name for an agent that runs in an image.
cost(trajectory)
¶
The run's cost in US dollars, when the agent reports it.
cost_reported()
classmethod
¶
Whether this agent's runs can say what they cost: :attr:reports_cost, or by
default whether it implements :meth:cost. A cost budget (max_cost_usd) limits
agents by what their runs say they cost: an experiment with one refuses an agent whose
runs never say it.
harness_starts(agent_dir)
staticmethod
¶
Say that a harness on the host started for the agent (:data:HARNESS_STARTED), as
soon as its process exists (run_captured(started=...)): a build that then fails on
this machine before the harness wrote its logs is one whose agent ran (its cost
unknown), never given back and run again; one whose harness never started is.
copy_after()
¶
In-sandbox files to keep (redacted) after the run: source path → log file name.
reasoning_effort()
¶
The reasoning effort the agent's CLI is given, for its record: the
reasoning_effort option, or None for an agent that passes none to its CLI.
image(context)
¶
The image option; otherwise the agent's image for the task's runtime
(:func:real2simlab.envs.agent_environment), so one agent runs on every benchmark.
collect(context, workspace, status)
¶
:meth:_collect, with a failure of this machine (not the agent's) as the third
value instead of an exception: the build is then not a result, and is retried.
collect_clean(context, workspace, status, values, outside=None)
¶
:meth:collect, once the injected values are out of the files the agent wrote
itself under the build's work directory (:func:scrub_injected), and what that did.
Nothing is delivered while a file may still hold one, nor when the run failed outside
the agent (outside says why: its sandbox, Harbor, the harness): that reason is then
the failure and the infrastructure error, with what the cleaning could not do.
Metric
¶
Bases: ABC
A comparison of a prediction with a reference. Lower values are better.
formats = frozenset({'tracks'})
class-attribute
¶
Output formats the metric reads. tracks also covers formats convertible to tracks.
compute(prediction, reference, *, frames=None, options=None)
abstractmethod
¶
Compare over reference frames [start, end) (default: all).
option_problems(options)
¶
What is wrong with options (the task's scoring.metric_options for this
metric): a name the metric does not take, or a value it cannot use. Empty when they
are usable. Task validation reports them, so a misspelt option is a broken task, not
a score of 0. This default accepts anything; a metric that reads options overrides it
(see :func:option_problems).
OutputFormat
¶
Bases: ABC
A named output format: its rules, its documentation and its conversion to tracks.
provides_tracks = False
class-attribute
¶
Whether to_tracks converts outputs of this format, so tracks metrics apply.
content = None
class-attribute
¶
Glob patterns, relative to an output's root, of the files that make up an output of
this format: what is compared when two outputs are checked for agreement (a session
output and its frozen re-run, or two re-runs). None: every file.
validate(root, requirements=None)
abstractmethod
¶
Every violation of the format in root; an empty list means it is valid.
to_tracks(root)
¶
The output as per-object tracks, or None if the format has none.
documentation()
¶
The format's specification in Markdown, as given to methods.
check(root, requirements=None)
¶
Raise InvalidOutputError listing every problem of root.
NativeScorer
¶
Bases: ABC
task_options = None
class-attribute
¶
The names a task's scoring.native.options may hold for this scorer (besides the
Lab's LAB_OPTIONS): task validation reports any other name (a typo). None (the
default): not declared, not checked.
required_task_options = ()
class-attribute
¶
Those of task_options every task must give (validation reports a missing one).
score(task, *, delivery_dir, output_dir, work_dir, options)
abstractmethod
¶
Official scores of one delivery. output_dir is the method's own output.
problems()
¶
What prevents this scorer from running here (e.g. missing GPU or weights).
failure(report)
¶
Why the scorer itself failed to produce report, or None when the report is a
score (including a score of a delivery that failed). A failed scorer says nothing about
the delivery: the result is left out of every statistic and reward, and redone when
the experiment runs again. By default: a report whose status is scorer_failed,
with its detail, exit_code and log when present.
cache_identity()
¶
What a score depends on beyond the delivery, the task, the options and this Lab (e.g. the content of a scorer image, the checkpoints present): an earlier score is reused only while this is unchanged. Nothing by default.
headline(report)
¶
The benchmark's headline metric in one of this scorer's reports (value is
None when the delivery could not be scored); None if the benchmark has none.
aggregate(reports)
classmethod
¶
The headline over several tasks the way the benchmark combines them, with the same
for each reference point ({"value": ..., "<reference>": ...}). None means the
mean of the tasks' headlines, which is what most benchmarks report.
Backend
¶
Bases: ABC
Runs sandboxed commands.
problems()
abstractmethod
¶
What prevents this backend from running on this machine; empty when ready.
ensure_ready()
¶
Raise SetupError with a fix if the backend cannot run here.
setup_problem(log)
¶
Why the sandbox of a probe the Lab ran (nothing of a program) could not be set up on
this machine, as this backend's own messages in the probe's log say; None when
they do not say so (it was set up, or this backend cannot tell). Never asked about a
program's log, which the program writes.
resolve_image(reference)
abstractmethod
¶
Check that reference is available; raise SetupError with a fix otherwise.
run(spec, log_path)
abstractmethod
¶
Run spec with stdout and stderr written to log_path.
info()
¶
Facts recorded with every run, e.g. the backend's version.
gpu_problems()
¶
What prevents GPU runs; empty when GPUs work.
session(spec)
¶
A sandbox that stays up while many commands run in it (spec.argv is ignored).
Each command runs as [*session.prefix, "<shell command>"] with session.env as
its whole environment and session.cwd as its working directory.