diff --git a/CHANGELOG.md b/CHANGELOG.md index 91e80f5f..50318558 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -152,6 +152,15 @@ Changes are grouped by software version. Entries under Unreleased describe work cohort into a run whose learner never reads a persona. AHE-Beta's own demand and delivery Evolver (Gitea, OpenAgents) is in `delivery/`: its controller and worker run in the run's sandbox; run end to end once (a U4 round on the paper's models, its delivery bound for the next round), not evaluated. +- RATs ([Playful Agentic Robot Learning, arXiv:2606.19419](https://arxiv.org/abs/2606.19419)): the `rats` template + (RATs' skill library and its play state, with a check of the library's records and code), the RATs actor + (`hermit.agent.evolver.methods.rats.actor:RatsActor`), which runs RATs' own `scripts/run_rats.py` on one row in + RATs' Python environment, in a bubblewrap sandbox of its own, its model calls metered on the host, and the `rats` + Evolver, which checks and applies the library and state a play iteration hands back. `examples/libero/rats/`: + play as training (50 iterations), the original LIBERO as validation (less play's bootstrap task, init states + 43-49), LIBERO-PRO as test (the paper's Table 1, 600 trials, scored on LIBERO's own check; and all eight suites in + all 50 init states), each split its own config, with `launch.sh` and `serve.sh` for RATs' vision services (started + with no key; GraspGen's requests that would unpickle refused) ([RATs](docs/methods/rats.md)). - `examples/officeqa_harbor/`: OfficeQA as Harbor's task set (harbor-datasets' `datasets/officeqa`, pinned) in the OfficeQA paper's evaluation: each question in its own Harbor environment, the paper's agent prompt, the final message's `` scored by the paper's `reward.py` (the OfficeQA repository's at its commit) at a 0.0% diff --git a/docs/index.md b/docs/index.md index e3069cb8..6b437e89 100644 --- a/docs/index.md +++ b/docs/index.md @@ -76,6 +76,7 @@ methods/harness2 methods/continual_harness methods/reharness methods/aspire +methods/rats methods/meta_harness_adapter methods/ace methods/ahe_adapter diff --git a/docs/methods/index.md b/docs/methods/index.md index 16cc817f..5c63ee5f 100644 --- a/docs/methods/index.md +++ b/docs/methods/index.md @@ -24,6 +24,7 @@ template–method combinations meaningful. | Evolve whole adapters round by round under regularizers against overfitting the evolve set: an annealed edit budget, the edit history, exploration when stalled, a pre-evaluation leakage critic, a noise-adjusted floor and a cost rule | [RRSI Adapter](rrsi_adapter.md) | `rrsi-adapter` | A training split (the evolve set, k rows per task), a proposer CLI (Codex, Claude Code or Pi), the `rrsi` dependency group, a domain module with the benchmark's texts | | Learn the framework contract offline | [Quick Start](../get-started/quickstart.md) | Prompt-only with a teaching learner | Included toy tasks | | Grow a library of verified skill entries from robot tasks, each proposal re-solved by a fresh actor before it is admitted, with the coordinator choosing the next task | [ASPIRE](aspire.md) | `aspire` | A coordinator CLI (Codex, Claude Code or Pi), verifier task rows in `data.val`, an acting agent that delivers the adapter | +| Learn a library of robot skills by play: the method's own agent teams propose their own tasks, solve them and turn successes into skills and failures into lessons, the library then frozen for the benchmark | [RATs](rats.md) | `rats` | RATs' checkout and its vision services, a GPU, a model that takes images; `data.step_size: 1`, `agent.concurrency: 1` | A learner model endpoint above can be your Claude subscription, and a learner CLI can run on it, with no API key: [Claude subscription](../guides/claude-subscription.md) says which roles go which way. @@ -50,6 +51,7 @@ task-specific service overhead. Call counts vary with evidence, candidates, and | ReHarness | Per instance, one reflection call, one revision call per retrieved reflection (up to k) and one embedding call; no candidate rollouts or validation | Reflection bank in the adapter; source trajectories and per-instance retrieval and revision records in `state/` | Current adapter: the bank after the last instance | | Meta-Harness Adapter | One proposer session per round writing k candidates; each candidate is a full rollout of the search set, one step per candidate | Every candidate's files, hypothesis, base and per-task scores in `state/` | Best mean on the search set | | ASPIRE | Per task, one coordinator session and, when it proposes entries, a verifier rollout (a fresh actor on the task's verifier row) | The coordinator's curriculum and changelog notes in `state/` | Current adapter: the library after the last task | +| RATs | None beyond the rollout: one play iteration of RATs' own loop per step (its proposer, environment creator, execution and memory teams, many model calls), the update made inside it; the Evolver checks and applies the handed-back state | RATs' play state in `state/`: the failure memory and lessons, the retry bank, the proposer's counts, the curators' history, the loop's counters, a digest per iteration | Current adapter: the library after the last play iteration | | RRSI Adapter | Per round: the analyst with a digester per rendered trace (a session per turn), m proposer sessions with the critic's review and repairs, a smoke on the domain's smoke tasks per screened candidate; each candidate is a full rollout of the evolve set (k rows per task), one step per candidate | Every candidate's files and digest, the edit history, the attribution and the frontier in `state/` (upstream's files under `state/rrsi/`) | The incumbent H_T, admitted above the noise floor and within the cost rule | `use_gate: false` in SkillOpt removes the ordinary improvement requirement, **not** the validation calls. diff --git a/docs/methods/rats.md b/docs/methods/rats.md new file mode 100644 index 00000000..1e95462a --- /dev/null +++ b/docs/methods/rats.md @@ -0,0 +1,336 @@ +# RATs + +RATs ([Playful Agentic Robot Learning, arXiv:2606.19419](https://arxiv.org/abs/2606.19419), +[project](https://playful-rats.github.io/), [code](https://github.com/Playful-RATs/RATs)) learns robot skills by +play. With no benchmark task given, a task proposer picks a manipulation task of its own in a simulator scene, an +environment creator writes the task's BDDL and checks that it instantiates, and an execution team (planner, policy +writer, verifiers, failure diagnoser) solves it with a Code-as-Policy program over a Franka arm's API, up to six +attempts. A memory team then turns each success into reusable skills in a skill library L (Python functions over the +API, each with a reliability tier: experimental, verified or deprecated), each failure into a failure memory M with +distilled lessons, and every five iterations curates both and proposes helpers. At test time the library is frozen +and RATs' execution team solves the benchmark's tasks with it (RATs Exec). Here RATs' own code does all of that, in +its own Python environment, unchanged: Hermit runs one play iteration per training step, keeps L and RATs' play +state as the adapter, and evaluates the frozen library with RATs Exec on LIBERO-PRO. What differs from the paper: +the memory team's update runs in the rollout's RATs process (where RATs interleaves it with the attempts) and the +Evolver checks and applies what came back; every RATs role calls the run's one model (the paper plays with +Gemini 3.1 Pro); the plug-in evaluation mode (the library inside CaP-Agent0) is not ported. + +## Setup + +```yaml +template: rats # skills.json (RATs' library L) and RATs' play state under state/ +data: # rows.py writes tasks/ and splits/ (launch.sh) + {tasks: tasks, train: splits/train.txt, test: splits/test.txt, step_size: 1, shuffle: false} +agent: + name: hermit.agent.evolver.methods.rats.actor:RatsActor # RATs' run_rats.py on one row, in a sandbox of its own + concurrency: 1 # play: one iteration at a time, each from the last one's state + params: + rats_root: $RATS_ROOT # RATs' checkout with its .venv, at the pinned commit + model: fireworks/accounts/fireworks/models/glm-5p3-flash # every RATs role; it must take images + effort: medium # each request's reasoning_effort: the first-evaluation row's + gpus: $RATS_GPUS # where RATs renders LIBERO; per_gpu rollouts on each +environment: {runner: host} # the actor confines RATs itself +evolver: {name: rats} +``` + +RATs needs Python 3.10, its own submodules (LIBERO-PRO, robosuite, Contact-GraspNet, SAM3) and its vision services, +so it is a checkout beside Hermit, as ASPIRE's is, not a dependency group: the example's `launch.sh` pins its commit +(`1fd2ef5`) and names a different one, and [`examples/libero/rats/README.md`](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/libero/rats) +sets it up. Hermit calls RATs' own entry point (`scripts/run_rats.py main()`) through +`hermit/agent/evolver/methods/rats/runner.py`, which runs under RATs' Python, imports nothing of Hermit, and changes +RATs at four seams only: + +1. **The model.** Every model call goes to an endpoint of the actor's process (`hermit.agent.base.endpoint`, over one + Direct call each), which sends it to the run's model with the provider's key and counts its tokens and cost: RATs' + `_get_api_config` names that endpoint, and Bedrock, Vertex and the Gemini proxy are off. RATs' parallel sub-agent + workers, which it starts as processes of their own (`scripts/run_subagent_worker.py`), start through the runner + (`runner.py worker`) and route alike. RATs' per-role model variables (`RATS_LLM_MODEL`, `RATS_POLICY_WRITER_MODEL`, + ...) all name the run's model. RATs' generic request form (temperature, max_tokens) carries no reasoning effort; + the endpoint's model adds `agent.params.effort` (default medium, the first-evaluation row's; RATs' own + `llm_reasoning_effort` in `rats/config/default.yaml` is low, and RATs sends it only in its OpenAI form). RATs' + visual and per-step verifiers and its diagnoser attach the attempt's videos, which Gemini takes (its feedback + generator does too, on MolmoSpaces only); for a model that takes none (`agent.params.video: false`, the default) + the runner builds each of those calls from images, as RATs builds it where it has no video: the visual verifier's + sampled frames (up to eight), the per-step verifier's images and the diagnoser's filmstrip (RATs' + `RATS_DIAGNOSER_VISUAL_INPUT=frames`); RATs' own `_strip_videos_from_messages` drops any video left. +2. **The init states.** An exec row's trial j runs in the task's init state `first_state + j`: RATs resets each + iteration's environment with seed = the iteration's number, and its LIBERO environment takes init state + `(seed - 1) % 50`, so the loop starts after iteration `first_state`. +3. **The loop's memory.** A play iteration is one process. What a continuous RATs run keeps in memory between + iterations is restored before the iteration and saved after it: the curation and skill-proposal counters, the + curator's rolling history, the bootstrap task's name and the failure memory's distillation counter + (`state/loop.json`), and the scene the last iteration left (`state/scene/`: the BDDL RATs generated for it and its + custom verifier), which RATs' next iteration falls back to when its own scene cannot be created; the runner rebuilds + it with RATs' `EnvironmentCreator`. Everything else RATs carries lives in its output directory, which its own + `--resume` reads. +4. **The verdict at test.** An exec trial succeeds on LIBERO's own check: RATs' Verifier counts its native vote alone + (`task_completed`, or reward >= 0.99, behind RATs' gate that the program ran), and keeps the structured custom + verifier's and the visual verifier's results in its evidence without counting them, so a trial that the VLM judges + solved and LIBERO does not goes on to its next attempt. RATs' docs set `RATS_VERIFIER_STRICT_BENCHMARK=1` for this + ("counts only the native `task_completed` as success", `docs/evaluation.md`); no code at the pinned commit reads it, + so its Verifier there counts any of the three votes. + +Before RATs runs, its own parser (`run_rats.py build_parser`) reads the arguments the runner gives it, with what +`run_rats.py` then fills in from the env config's top-level `rats:` block (`_apply_rats_runtime_defaults`). A row is +refused whose `rats_args`, in any spelling the parser takes, or whose config's `rats:` block change what the row is: +its scene, task, output, library, iterations or frozen flags, a scaled execution timeout, RATs' mock environment +(`--mock`, which reports `task_completed` at random), the library merged with others or filtered by tier, memory +carried in from other runs, and in play its novel-task mode and the test tasks' descriptions. RATs' own method +switches pass (`--no-skill-reuse`, `--no-failure-memory`, `--random-order`), as do its budget switches (`--max-retries`, +`--attempts-per-iteration`, `--turns-per-attempt`, `--multiturn-reset`, `--ensemble`, and the env config's +`attempts_per_iteration`, `turns_per_attempt`, `multi_turn_decision`): in play, a run that sets one is that RATs +ablation, and an exec row holds its frozen flags whatever they say; a run that changes a budget evaluates another +protocol than RATs' default, which the rows' guards also assume. + +The sandbox (`hermit.sandbox`, bubblewrap) shows RATs' checkout and venv read-only, writes only the row's RATs output +directory, reaches no network but the model endpoint and the loopback ports of the vision services the row's RATs config +names in its `api_servers` (play: SAM3 8114, Contact-GraspNet 8115, PyRoki 8116; test: SAM3, PyRoki and GraspGen 5556) +and of the servers RATs' policy quality checker probes but Molmo's (8114, 8115 and 8116, so a test row reaches 8115 too: +below), and sees one GPU (none with `render: cpu`). It hides what no row reads: the checkout's git history, its +`outputs/` and logs, provider key files (`.env`, `.openrouterkey`, which RATs loads when present), the skill libraries +the authors learned (`skill_library/*.json` holding any learned skill, `capx-baseline/skill_libraries/`), and in play +every LIBERO-PRO suite's BDDL files and init states but the original LIBERO suites', and LIBERO-PRO's perturbation specs +(`libero_ood/`, which repeat the test `_task` suites' instructions). + +The vision services run outside the sandbox, as the user who starts `serve.sh`, each with a clean environment (no +key or token of that shell's in it; a service reads what that user can read). A program in the sandbox reaches them +through their request protocols, which the example's guards limit to what RATs' clients send: +- SAM3 takes base64 images, which its decoder opens in any format Pillow knows, and Pillow runs Ghostscript on an EPS + image; `sam3_guard.py` decodes PNG only (RATs' clients send PNG), of a camera's size. +- Contact-GraspNet reads NumPy arrays with `np.load`, which refuses pickled ones, and PyRoki takes numbers. +- GraspGen takes msgpack, whose NumPy decoder unpickles an array of kind object and builds one of an object type over + the request's bytes (its elements then pointers the request chose); `graspgen_guard.py` refuses every array whose + type holds Python objects (RATs' client sends arrays of floats). GraspGen's server stops on a request of more than + one ZMQ frame, which the guard answers as an error. + +Each guard answers what it refuses as its service answers a request it cannot handle, and the service serves on. The +guards hold for the services `serve.sh` started (it leaves a port that already answers alone). They limit what a +request may hold, not how much work it asks for: a program that sent a shared service large sampling parameters, which +RATs' API never sets, could hold it busy for the other rows. + +The actor checks that the row's services (its config's and the ones the quality checker probes) take a connection before +it starts RATs and after the row. A row whose services do not before it is not run; after it, an exec row whose trials +all succeeded on LIBERO's own check keeps its result (the outage noted, `services_down`), and any other row, play +included, is a failed run, as a trial or a play iteration's attempt may have failed for want of the service (and play's +hand-back would carry that failure into RATs' memory). Hermit scores a failed run (`session_failed`) 0 within +`mean_score` and counts it in `errors`; its trials are in the actor log's `result.json`, and such a row is to be run +again. The check finds a service that has stopped; one that listens but hangs, or fails every request, is not found. A +row whose runner was stopped before RATs' run ended (its timeout, a signal, the OOM killer) keeps the exec trials that +finished, the rest counted as failed, with the reason in its output and the judge's feedback; a play row's hand-back, +which may then be cut short, is not taken (a failed run). + +## The step + +```mermaid +flowchart TD + A["adapter: skills.json (L) + state/ (M, retry bank,
proposer counts, curator history, loop.json, scene, iteration digests)"] + P["play row: the actor lays the adapter out as RATs' output directory
and runs run_rats.py --explore --resume for one iteration"] + I["RATs, in the sandbox: PROPOSE_TASK, create + verify the env,
RUN_TASK (up to 6 attempts), UPDATE_MEMORY
(skills, tiers, failures, lessons; every 5: curators, skill proposer)"] + H["handed back: skills.json + state/ (digests of the iterations)"] + C{"template check
(the library's records and code, the state's files)"} + U["the Evolver replaces skills.json and state/"] + K["the adapter as it was; the step says why"] + F["final adapter: the library after the last iteration"] + E["test: RATs Exec per task, the library frozen
(--fixed-task --no-skill-reuse --no-failure-memory)"] + A --> P --> I --> H --> C + C -- passes --> U --> A + C -- fails, or nothing came back --> K --> A + A -. after the last step .-> F --> E +``` + +RATs has no validation step and selects no snapshot, so neither does the Evolver; the run tags a snapshot every ten +steps (`trainer.save_freq`) for the validation split to compare after training. + +What a play iteration hands back is checked before it becomes the adapter (`.hermit/check.py`): the library is RATs' +JSON list of skill records with valid names, counts and tiers; a primitive's code is comments only (it documents the +API); a learned skill's code parses, defines its own function, and reaches only its arguments, the API and the other +skills (no `env.` or `low_level_env.`, RATs' own forbidden patterns, no private or dunder attribute, no `exec`, +`eval`, `open` or `__import__`, no import of the interpreter, files, processes, the network or the simulator). This +is a screen of what the library hands the next program, not the boundary: RATs runs every program in the actor's +sandbox. + +## Data splits + +`rows.py` writes every row as a task directory in Harbor's format; the three splits share no row, and LIBERO-PRO's +test suites stay out of training. + +| Split | Rows | Mode | What it is | Trials | +|---|---|---|---|---| +| `train` | `play-001` ... `play-050` | play | RATs' 50 play iterations (§4.1), each one step; no benchmark task: RATs proposes its own in LIBERO's scenes, starting from `libero_spatial` task 0 as RATs' play config does | 50 iterations | +| `val` | `val--t`, 39 | exec | the original LIBERO Spatial, Object, Goal and Long suites' 40 tasks less play's bootstrap task (`libero_spatial` task 0), init states 43-49 | 273 | +| `test` | `test--t`, 60 | exec | LIBERO-PRO's six suites of Table 1 (Object, Goal, Spatial under the position swap and the task perturbation), 10 tasks each, init states 0-9 | 600 | +| `test_full` | `full--t`, 80 | exec | all eight LIBERO-PRO swap and task suites (with LIBERO-Long's), all 50 init states | 4,000 | +| `smoke_*` | one each | play / exec | one play iteration, the first validation row's first trial, one test trial | 1 each | + +A play row whose iteration hands nothing back (RATs crashed, or its state failed the template's check) leaves the +adapter as it was, and the next row runs that iteration again: a run with such rows ends short of 50 iterations, and +the Evolver's step records say which. + +What play and the test share: play never reads a test suite's BDDL files or init states, nor LIBERO-PRO's perturbation +specs (the sandbox hides them), and a play row is refused whose arguments turn on RATs' +`--proposer-include-eval-task-context` (its optional task-aware play, which writes the 60 test tasks' descriptions into +the proposer's prompt). The test suites are perturbations of the original suites: a `_swap` task is an original task +with its objects' positions exchanged, so it shares its instruction and scene with the original task; a `_task` task +gives its original's scene another instruction and goal, which in Object is another original task's (all ten: +`libero_object_task` task 0, "pick the cream cheese and place it in the basket", is `libero_object` task 1's) and in +Spatial for four tasks another one's instruction. LIBERO-PRO's Python task map names every suite's tasks, so play's +process could import those names; RATs' proposer reads them only with the refused flag. Play's bootstrap task, +`libero_spatial` task 0, is the original of `libero_spatial_swap`'s and `libero_spatial_task`'s task 0, so those two +test tasks are built on the scene play starts in (as with RATs' own play config and Table 1). + +What play and validation share: validation is the original LIBERO, the setting the paper's play is grounded in. +Play runs in RATs' default mode, novel tasks: a play row whose arguments turn on RATs' `--catalog` is refused, since in +that mode play rebinds to the bootstrap suite's own tasks, `libero_spatial`'s, which are validation rows. It works in +scenes it generates, from its catalog of LIBERO's objects and fixtures, and never rebinds to a LIBERO task, but it +starts in its bootstrap task, `libero_spatial` task 0, and falls back to it when an iteration's scene cannot be +created before any was (later, to the scene the last iteration left: seam 3), in the init state of the iteration's +seed; so validation leaves that task out. Play's scenes use LIBERO's objects and fixtures, as the validation tasks +do, and the validation init states 43-49 are distinct from the test's 0-9. Validation measures the library on the +original tasks (retention and in-distribution skill), for the choice of a snapshot or a setting; it is not a held-out +estimate of the test, whose `_swap` suites hold 29 of the 39 validation tasks with their objects' positions exchanged +(the same instruction and goal), and whose `_task` suites give 14 of their 20 Object and Spatial tasks a validation +task's instruction (the ten Object ones with its goal too) in another task's scene. + +## Evaluation + +The protocol is train / test: the Evolver learns from the play iterations, and the final library is evaluated frozen +on the test split (`test.yaml`, the paper's Table 1: 60 tasks under 10 initializations, 600 trials). An exec row +is one RATs LIBERO-PRO batch-driver job (`scripts/run_rats_libero_pro_batch.py`): one task, all of its trials in one +RATs process (RATs keeps a task's successful program across its trials), with `--fixed-task --no-skill-reuse +--no-failure-memory`, and with RATs' Verifier counting LIBERO's native check alone (seam 4); a trial counts when RATs' +verdict and its last verification's native check both say success, and the row's record keeps both, with each +trial's native `task_completed` and reward. +At the pinned commit `--no-skill-reuse` stops storing extracted skills and the skill proposer, and keeps the +planner's retrieval from the frozen library (`rats/loop/lifelong_loop.py`; the flag's help text in `run_rats.py` +says otherwise, the batch driver's comment agrees with the code). The row's score is the share of its trials that +succeeded; a trial that never ran counts as failed. `--adapter none` is RATs' no-library condition (the reduced +API's primitives, `skill_library/libero_nonpriv_skills.json`: the paper's "No Play"). The two conditions differ in +more than the learned skills: a play library carries play's primitive records (`libero_skills.json`, the full API's +12, three of which the reduced API lacks: `get_object_pose`, `sample_grasp_pose`, +`get_object_3d_points_and_masks_from_language`), the no-library condition the reduced API's own 26, and RATs' +planner reads the primitives from the library file. RATs' own evaluation does the same (its `docs/evaluation.md` +seeds the batch driver with the play snapshot's `skills.json` as it is), so final against none is RATs' comparison +of a play library with none, not of learned skills on equal primitives. RATs' `docs/evaluation.md` runs five trials +a task; `RATS_ROWS_ARGS="--test-states 0-4"` writes that test split. + +The test's environment config is RATs' own for LIBERO-PRO: `env_configs/libero/rats_libero_pro_nonpriv.yaml`, the +reduced skill-library API on GraspGen (port 5556), as the batch driver defaults to; play's is `rats_libero_play.yaml`, +the full API on Contact-GraspNet (8115). The two are RATs' own combination: the reduced API lacks some of play's +primitives, so a learned skill calling one fails at test time as it does in RATs. RATs' policy quality checker probes +SAM3's, Contact-GraspNet's and PyRoki's ports (and Molmo's) when its loop starts, and rejects a policy that names a +primitive of a server that does not answer, unless the API registers it, a rejection that uses up an attempt; RATs' +evaluation runs SAM3, Contact-GraspNet and PyRoki whatever the config names (`docs/evaluation.md`), so every row reaches +the probed ports but Molmo's (no LIBERO config of RATs' starts Molmo) and needs them to answer, and the checker reads a +policy that names play's `sample_grasp_pose` at test as it does there: it passes, and RATs' self-check finds the missing +primitive. `examples/libero/rats/env_configs/rats_libero_pro_graspnet.yaml` is the same test config on Contact-GraspNet +(the servers RATs' `docs/evaluation.md` lists for this evaluation), for a machine without GraspGen +(`RATS_GRASP=graspnet`): a deviation, recorded as one. + +The success flag comes from RATs' own process, which also runs the generated programs: the trust of RATs' own +evaluation. RATs' program checker refuses `env.` and `low_level_env.` in a program, and the sandbox keeps the +process to its row's directory, but a program could still reach the simulator's state through Python +introspection inside that process, or overwrite the runner's result file; LIBERO's own check (seam 4) is what a +reported success rests on, read in that process. (ASPIRE's judge instead re-runs a program on the host; RATs Exec's +trials keep state across attempts within one process, which a re-run would not reproduce.) + +The library at test, as RATs handles it: each run copies the library it is given into its own output directory and +works on that copy (`LifelongLoop.__init__`), and each of the batch driver's jobs has its own output directory, so +jobs share nothing. Within a job, RATs records the skills' use on its copy as the trials run (`record_usage`: usage +counts and tiers; a skill can be deprecated, and the planner then leaves it out), so a later trial of a task reads +the library as the earlier trials left it; `--no-skill-reuse` stops new skills, not that. A row here is one such job: +RATs copies the trained library (shown read-only) into the row's output directory and does the same, and the +trained library itself is never written. + +## Parameters + +```{literalinclude} ../../hermit/agent/evolver/methods/rats/evolver.yaml +:language: yaml +``` + +The actor's settings (`agent.params`): `rats_root` (RATs' checkout), `python` (default its `.venv/bin/python`), +`model` (a `/` reference, or a mapping with `base_url`), `effort` (each request's +`reasoning_effort`, default medium; `false` sends none), `video` (default `false`: RATs' vision calls are built from +images, as seam 1 says; `true` for a model that takes video), `price` (overrides the backend's), +`rats_model` and `dialect` (what RATs is told its model is, and its request form: `openai` for an OpenAI model, +which RATs names `openai/`, else `chat`), `gpus` and `per_gpu` (default 2), `play_config` and `exec_config` (an +env config of RATs' checkout or of the run's folder), `rats_args` (more `run_rats.py` flags; RATs' parser reads them +with the row's, and a row is refused whose flags change what it is or, in play, put the test tasks into play), `env` +(more variables for RATs' process; a +secret-looking name is refused), `render` (`gpu`, the default: NVIDIA's EGL on the row's GPU, as RATs runs; `cpu`: +Mesa's llvmpipe through EGL and no GPU, for a host whose GPUs run other processes' CUDA work, which on Hopper GPUs +silently invalidates a live EGL context's reads), `render_threads` (llvmpipe's, default 2), +`execution_timeout_scale` (RATs' policy execution timeout, 180 s in `rats/config/default.yaml`, times this factor, +passed as `run_rats.py --timeout`: RATs' policy self-check, its execution and its sub-agent workers run under it; +default 1 with `render: gpu` and 11 with `render: cpu`, as Mesa renders a LIBERO step about 11 times slower on the +examples' host with two llvmpipe threads; a row whose `rats_args` set another `--timeout` is then refused), +`mesa_egl_vendor` (Mesa's glvnd vendor file), `service_ports` (the vision services' ports the sandbox reaches and the +actor checks answer before and after the row; default those of the row's RATs config's `api_servers`; the sandbox also +reaches, and the actor also checks, those RATs' quality checker probes, but Molmo's), `robot_descriptions` (the cache of +the robot descriptions RATs' IK loads: the sandbox has no network to fetch them), `scratch` (RATs' output directories: +videos, generated BDDL, attempt artifacts), `timeout_s` (a row's whole limit; a play row's default is 6 h), +`trial_timeout_s` (an exec row's limit per trial, default 2 h; a scaled execution timeout grows both defaults by what it +can add to a trial's 24 program runs: six attempts, each a self-check, up to two self-repairs' self-checks and the +execution), `call_timeout_s` (the provider's call behind each request, default 200 s: RATs gives a request up after 200 +s, and the endpoint gives the call up with it; a call given up leaves no usage in the row's meter, though the provider +may bill it), `max_retries` (the endpoint's own retries of a provider's 408, 409, 429 and 5xx, default 4: RATs' client +retries a 404, 500, 502, 503 or 504 three times, and a 429 not at all for a model without one of its fallback chains, +which only Gemini 3.1 Pro has; RATs gives the request up after its 200 s all the same). + +## The authors' implementation against this one + +| Dimension | RATs (Playful-RATs/RATs) | This port | Why | +|---|---|---|---| +| Play loop | `run_rats.py --explore`, 50 iterations in one process | the same entry point, one iteration per process and per training step, resumed with RATs' `--resume` | the Trainer's step; acceptable | +| What one iteration does | PROPOSE_TASK, environment creation and verification, RUN_TASK (up to six attempts), UPDATE_MEMORY | RATs' own code, unchanged | — | +| When the memory updates | inside the iteration, interleaved with the attempts (a lesson after one attempt reaches the next) | the same, in the rollout's RATs process; the Evolver checks and applies what it hands back | the update cannot leave the iteration without changing RATs; acceptable | +| In-memory loop state | kept in the process: curation and skill-proposal counters, the curator's rolling history, the bootstrap task's name, the distillation counter, the current scene and its custom verifier | saved to and restored from `state/loop.json` and `state/scene/` around each iteration; the scene rebuilt from its BDDL with RATs' `EnvironmentCreator` | one process per iteration; acceptable | +| Curation, skill proposal | every five iterations, by the iteration number | the same: the iteration numbers continue across steps | — | +| The update's check | `add_skill`'s validation and semantic dedup, RATs' program checker | the same, plus the template check on what an iteration hands back | a decision: what reaches the adapter is screened | +| Selection | none: the library after the last iteration | the same | — | +| Models | gemini-3.1-pro-preview in play; per-role variables | one model in every role (GLM 5.3 Flash in the examples, which takes images) | the first-evaluation row; a decision | +| Model access | provider keys in RATs' environment, OpenRouter / Vertex / Bedrock routes | the actor's metered endpoint; no key in RATs' process | the framework's metering and isolation | +| Reasoning effort | low (`llm_reasoning_effort` in `rats/config/default.yaml`), sent in RATs' OpenAI form only; some calls set their own | medium on every request (`effort`); a request of RATs' own that sets one keeps it | the first-evaluation row (GLM 5.3 Flash, medium); a deviation | +| Videos in vision calls | the visual and per-step verifiers and the diagnoser attach the attempt's videos (Gemini takes them; the feedback generator too, on MolmoSpaces only) | each built from images, as RATs builds it without a video (sampled frames, step images, the filmstrip; `video: true` keeps the videos) | GLM 5.3 Flash refuses video input (HTTP 400); a deviation | +| Parallel sub-agents | worker processes, one per approach the diagnoser proposes, the first success kills the rest | the same processes, started through the runner so that their calls reach the endpoint | — | +| Success at test | `docs/evaluation.md`: `RATS_VERIFIER_STRICT_BENCHMARK=1`, only the native `task_completed`; at the pinned commit no code reads it, and the Verifier counts the native, the structured custom and the VLM votes alike | the native vote alone (seam 4): a trial the VLM alone judges solved goes on to its next attempt | RATs' documented protocol; LIBERO's own success | +| Evaluation | RATs Exec (batch driver) and plug-in into CaP-Agent0 | RATs Exec, one row per batch-driver job | the plug-in mode runs a second code base (`capx-baseline/`); not ported | +| Test trials | 10 per task in the paper (600); 5 in `docs/evaluation.md` | 10 (`test.yaml`); 5 with `--test-states 0-4`; all 50 in `test_full.yaml` | the paper's Table 1 | +| Rendering | MuJoCo through NVIDIA's EGL (`MUJOCO_GL=egl`) | the same by default; `render: cpu` renders through Mesa's EGL (llvmpipe), and RATs' execution timeout is scaled by 11 (`execution_timeout_scale`): Mesa takes 0.18 s per LIBERO step of RATs' play env against NVIDIA's 0.016 s on the H200 host, two llvmpipe threads | a host decision: other processes' CUDA work breaks EGL reads on Hopper GPUs; the same physics, images differ by renderer noise; recorded with the run. The scale bounds a program's whole wall clock, of which its model calls, vision services and IK do not slow down: a CPU row is more lenient than RATs' 180 s on a GPU (a deviation toward higher scores, alike for every condition) | +| Budgets | six attempts per iteration or trial; a policy execution timeout of 180 s (`rats/config/default.yaml`); no wall-clock cap on a job | the same attempts and execution timeout (scaled with `render: cpu`); a guard of 6 h per play row and 2 h per exec trial, which a scaled timeout grows by what it can add to the 24 program runs of six attempts (by 12 h with `render: cpu`: 18 h a play row, 14 h a trial) | a hung row ends; acceptable | +| Vision services | `docs/evaluation.md` says they auto-launch from the env config; `run_rats.py` at the pinned commit starts none (`scripts/start_servers.sh` does) | started once by `serve.sh` from RATs' own server modules, in a clean environment, shared by the rows; SAM3's images limited to PNG, GraspGen's object arrays and multi-frame requests refused; a row whose services take no connection before it is not run, and after it is a failed run unless its trials all succeeded; every row reaches, and needs, the ports RATs' quality checker probes but Molmo's, as RATs' evaluation runs them | concurrent rows share them; the services run outside the sandbox; acceptable | +| Molmo (8122) | Molmo2-8B served by vLLM: `scripts/start_servers.sh` starts it, and `docs/setup.md` lists 8122 among the release configs' ports, but its LIBERO-PRO install leaves out the `molmo` extra (vLLM), no LIBERO config starts it, and the LIBERO-PRO config calls it optional | not started, and no row reaches its port. The LIBERO API's object localization (`get_object_3d_points_and_masks_from_language`) asks Molmo three times, sleeping 1 s and then 2 s, before SAM3's text prompt, and prints each failed request into the program's output, which RATs' diagnoser reads: in the first evaluation, GLM 5.3 Flash's diagnoses often blamed a perception outage on 8122 | as RATs' LIBERO-PRO install; a deviation from `start_servers.sh` | +| The library at test | each job copies it into its own output directory and records the skills' use there (usage counts, tiers) as its trials run | the same per row; the trained library shown read-only | — | +| Grasp service at test | GraspGen (NVlabs/GraspGen, which RATs does not install) | GraspGen, set up beside RATs (README); Contact-GraspNet as a recorded deviation | RATs ships no GraspGen setup | +| Isolation | none: RATs runs in its checkout with the network | the actor's sandbox: read-only checkout, no network but the endpoint and the row's services, one GPU, no key, the authors' libraries and key files hidden, the test suites and LIBERO-PRO's perturbation specs hidden in play | the framework's rules for a run's code | +| Not ported | MolmoSpaces, the real robot, the plug-in mode | — | scope | + +## Result + +The first evaluation is on LIBERO with GLM 5.3 Flash in every RATs role, reduced in size: 10 play iterations, then +one trial of tasks 0-4 of each of Table 1's six suites (30 trials) for the final library and for the no-library +condition ([record](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/libero/rats#first-evaluation)): + +| Evaluation | `none` | `final` | Final − none (paired) | +|---|---|---|---| +| LIBERO-PRO, Table 1's suites, tasks 0-4, init state 0, LIBERO's own check (2026-11-29 and 30) | 0.167 | 0.133 | −3.3 points, SE 7.6 | + +The final library does not act at test: nine of its ten skills call a primitive of play's full API that the test's +reduced API lacks, so they raise a `NameError` or return a failure (RATs' own pairing of its play and LIBERO-PRO +configs, see Evaluation), and RATs' quality checker rejected more programs (34 against 14), most of them calling the +library's verifying skills. Molmo, which no LIBERO config of RATs' starts, shaped the library: RATs' diagnoser read its +failed requests as a perception outage in 22 of 28 play diagnoses, and two of the skills guard against that outage. No +experiment of the paper's size has run (50 play iterations, 600 trials, its model). + +## What it is not + +The final library is what RATs' play produced; nothing selects it on held-out data. Validation and test scores are +LIBERO's own check as RATs' process reports it. Play and validation share LIBERO's objects and fixtures (see Data +splits), so a validation score is not a held-out estimate. One model plays every role here, so results are not the paper's numbers; the first +evaluation is on the framework's row (GLM 5.3 Flash). That model sees images but no video, and it thinks before it +answers: RATs caps some replies at 1,600 tokens (the per-step verifier's `max_tokens`), which its thinking can use +up, and RATs then reads an empty reply (its log: `empty content with finish_reason='length'`). + +## Example + +[`examples/libero/rats/`](https://github.com/Infini-AI-Lab/hermit/tree/main/examples/libero/rats): `train.yaml` +(play), `val.yaml`, `test.yaml`, `test_full.yaml`, the smoke configs, `launch.sh` and `serve.sh`. diff --git a/examples/libero/.gitignore b/examples/libero/.gitignore index 62859799..cb50a345 100644 --- a/examples/libero/.gitignore +++ b/examples/libero/.gitignore @@ -2,3 +2,6 @@ runs/ # ASPIRE's tasks and splits, written by aspire/tasks.sh at launch aspire/tasks/ aspire/splits/ +# RATs' tasks and splits when rats/rows.py writes them here by hand (rats/launch.sh writes them under runs/rows/) +rats/tasks/ +rats/splits/ diff --git a/examples/libero/README.md b/examples/libero/README.md index 64f8f7dd..34ae7389 100644 --- a/examples/libero/README.md +++ b/examples/libero/README.md @@ -16,6 +16,7 @@ on held-out seeds by the task's own success check. | `utils/benchmark/task-info/` | What a task and its record are, for the learner | | `utils/launch.sh` | Starts a method folder's run: the simulator service and hermit | | [`aspire/`](aspire/) | The ASPIRE method (its session's task functions, verifier and coordinator are ASPIRE's own; `tasks.sh` adds its verifiers to the tasks). `run.yaml` (Object, Spatial, Goal, Long: 40 tasks), `run_90.yaml` (LIBERO-90), `run_pro.yaml` (LIBERO-Pro: 80), `run_pro_long.yaml` (LIBERO-Long-Pro), `run_luna.yaml` (`run.yaml` on Luna), `run_sample_luna.yaml` (six of the forty on Luna, for a run of a day or two), `smoke*.yaml`, `launch.sh` | +| [`rats/`](rats/) | The RATs method on its own engine (RATs' code, its LIBERO-PRO checkout and LIBERO's fixed init states): play as training, the original LIBERO as validation, LIBERO-PRO as test. `train.yaml`, `val.yaml`, `test.yaml`, `test_full.yaml`, `smoke.yaml`, `smoke_val.yaml`, `launch.sh`, `serve.sh` | | [`prompt_only/`](prompt_only/) | The prompt-only template: one `ADAPTER.md` the built-in Codex Evolver revises after each task, with the method-neutral prompt. `run.yaml`, `run_pro.yaml`, `smoke.yaml`, `smoke_luna.yaml`, `launch.sh` | The `*_luna.yaml` configs run GPT-5.6-Luna on the machine's ChatGPT login; the others GLM 5.3 Flash on Fireworks. diff --git a/examples/libero/rats/README.md b/examples/libero/rats/README.md new file mode 100644 index 00000000..08e05844 --- /dev/null +++ b/examples/libero/rats/README.md @@ -0,0 +1,212 @@ +# RATs on LIBERO + +[RATs](../../../docs/methods/rats.md) ([arXiv:2606.19419](https://arxiv.org/abs/2606.19419), +[code](https://github.com/Playful-RATs/RATs)) learns a skill library by play in LIBERO's scenes and is evaluated +with the library frozen on LIBERO-PRO, as the paper's Table 1 does. RATs' own code runs every row, in its own Python +environment, inside a sandbox the actor starts (`hermit/agent/evolver/methods/rats/`). It is a different engine from +the [cap-harness](../../cap_harness/) one the other LIBERO folders use: RATs' API, RATs' LIBERO-PRO checkout and +LIBERO's 50 fixed init states per task (its own protocol), so its numbers compare with results reported on those +states, not with the cap-harness seeds. + +| File | What it is | +|---|---| +| `train.yaml` | Training: 50 play rows (`splits/train.txt`), one play iteration per step; snapshots every 10 steps | +| `val.yaml` | Validation: a training run's library on the original LIBERO suites (`splits/val.txt`) | +| `test.yaml` | Test: LIBERO-PRO's six suites of Table 1, init states 0-9 (`splits/test.txt`, 600 trials) | +| `test_full.yaml` | The eight LIBERO-PRO swap and task suites in all 50 init states (`splits/test_full.txt`, 4,000 trials) | +| `smoke.yaml`, `smoke_val.yaml` | One play iteration, then one test and one validation trial on its library | +| `env_configs/rats_libero_pro_graspnet.yaml` | RATs' LIBERO-PRO config on Contact-GraspNet instead of GraspGen (`RATS_GRASP=graspnet`): a deviation | +| `rows.py` | The rows and splits below, as task directories (`launch.sh` runs it; `--help` for the sizes) | +| `judge.py` | An exec row's share of successful trials (LIBERO's own check, in RATs' process); a play row's own outcome | +| `launch.sh` | Writes the rows (`rows.py`), checks the services, starts `hermit train` or `hermit eval` | +| `serve.sh` | RATs' vision services on their loopback ports, from RATs' own server modules, with no key in their environment | +| `graspgen_guard.py`, `graspgen-python` | GraspGen's server as `serve.sh` starts it: the requests of its protocol that would run code in it or stop it refused ([Trust](#trust)) | +| `sam3_guard.py` | RATs' SAM3 server as `serve.sh` starts it: PNG images only ([Trust](#trust)) | +| `task-info/` | What play and evaluation are, for the learner | + +## Data splits + +| Split | Rows | Suites | Init states | Trials | Config | +|---|---|---|---|---|---| +| train | `play-001` ... `play-050` | none given: RATs proposes its own tasks in LIBERO's scenes (from `libero_spatial` task 0) | each iteration's seed | 50 iterations | `train.yaml` | +| val | 39 exec rows | `libero_spatial`, `libero_object`, `libero_goal`, `libero_10` (the original LIBERO), less `libero_spatial` task 0 | 43-49 | 273 | `val.yaml` | +| test | 60 exec rows | `libero_{object,goal,spatial}_{swap,task}` (LIBERO-PRO) | 0-9 | 600 | `test.yaml` | +| test_full | 80 exec rows | the six above, `libero_10_swap`, `libero_10_task` | 0-49 | 4,000 | `test_full.yaml` | + +No row is in two splits. Play never reads a test suite's BDDL files or init states, nor LIBERO-PRO's perturbation +specs (the sandbox hides them). A play row whose arguments turn on RATs' `--proposer-include-eval-task-context`, +which would show the test tasks to the proposer, or `--catalog`, which would play `libero_spatial`'s own tasks (the +validation rows), is refused, in any spelling RATs' parser takes. Play starts in its +bootstrap task, `libero_spatial` task 0, and falls back to it when an iteration's scene cannot be created before any +was (as in RATs' own runs), so validation leaves that task out. Validation still shares LIBERO's objects and fixtures +with the scenes play generates (RATs' catalog), so it serves the choice of a snapshot or a setting, not a held-out +estimate; [the method page](../../../docs/methods/rats.md#data-splits) says what each split shares. A play row whose +iteration hands nothing back (RATs crashed, or the state failed the template's check) leaves the state as it was, and +the next row runs that iteration again, so a run with such rows ends short of 50 iterations. `RATS_ROWS_ARGS` changes the sizes (`--play 20`, `--test-states 0-4` for the five trials +of RATs' `docs/evaluation.md`). + +## Setup + +RATs at the pinned commit, as its `docs/setup.md` ("LIBERO-PRO runtime") sets it up (about 100 GB with the caches; +put them on a large local disk): + +```bash +git clone https://github.com/Playful-RATs/RATs && cd RATs +git checkout 1fd2ef56857cfde6d5d815fc49a9fe9b0a531beb +git submodule update --init --depth 1 rats/third_party/LIBERO-PRO rats/third_party/libero_dependencies/robosuite \ + rats/third_party/robosuite rats/third_party/contact_graspnet_pytorch rats/third_party/curobo rats/third_party/sam3 +uv venv .venv --python 3.10 && source .venv/bin/activate +uv sync --frozen --active --extra libero --extra contactgraspnet +``` + +- **SAM3's checkpoint** (`facebook/sam3` on Hugging Face, gated): accept its terms, then download it once with your + token into the `HF_HOME` that `serve.sh` is started with + (`python -c "from huggingface_hub import snapshot_download; snapshot_download('facebook/sam3')"`). +- **The robot descriptions** RATs' IK loads (`robot_descriptions` clones them on first use; the sandbox has no + network): fetch them once into RATs' checkout, where the actor shows them read-only: + `ROBOT_DESCRIPTIONS_CACHE=$PWD/.cache/robot_descriptions .venv/bin/python -c "from robot_descriptions.loaders.yourdfpy import load_robot_description as l; l('panda_description')"` + (`agent.params.robot_descriptions` names another place). +- **GraspGen**, the grasp service of RATs' LIBERO-PRO config (port 5556), which RATs does not install. Its launcher + (`rats/serving/launch_graspgen_server.py`) looks for `NVlabs/GraspGen` with its `.venv` beside RATs and the + `GraspGenModels` checkpoints beside that. GraspGen pins `torch==2.1.0` (CUDA 12.1) and builds `pointnet2_ops`, so the + build needs a CUDA 12.1 toolkit (`conda create -p cuda121 -c nvidia/label/cuda-12.1.1 cuda-toolkit`; set + `TORCH_CUDA_ARCH_LIST` to the GPUs' architecture, e.g. `9.0` for H100 / H200): + + ```bash + git clone https://github.com/NVlabs/GraspGen ../GraspGen && cd ../GraspGen # tested at 2dd8852 + uv venv --python 3.10 .venv && source .venv/bin/activate && uv pip install -e . + CUDA_HOME=/path/to/cuda121 PATH=/path/to/cuda121/bin:$PATH TORCH_CUDA_ARCH_LIST=9.0 \ + uv pip install --no-build-isolation ./pointnet2_ops + uv pip install pyzmq msgpack msgpack-numpy + python -c "from huggingface_hub import snapshot_download as d; d('adithyamurali/GraspGenModels', local_dir='../GraspGenModels', allow_patterns=['checkpoints/graspgen_franka_panda*'])" + ``` + + Without GraspGen, `RATS_GRASP=graspnet` evaluates on Contact-GraspNet (8115), a deviation from RATs' config. +- **Molmo** (Molmo2-8B, a vLLM-served pointing model on 8122) is not started, and no row reaches its port, as in + RATs' LIBERO-PRO install (no `molmo` extra) and LIBERO configs. RATs' `scripts/start_servers.sh` does start it: a + deviation from that script. Without it, each object localization of the LIBERO API asks Molmo three times (3 s) + before SAM3's text prompt, and the failed requests it prints reach RATs' diagnoser, which may blame a perception + outage (`docs/methods/rats.md`, the Molmo row). +- **Rendering**: an NVIDIA GPU with EGL. The actor shows RATs one GPU (`RATS_GPUS`, the N of `/dev/nvidia`), at + most `per_gpu` rows on each. On a host whose GPUs run other processes' CUDA work (on H200s that work silently + invalidates a live EGL context's reads, and RATs stops on `get_real_depth_map`'s depth assertion), + `RATS_RENDER=cpu` renders with Mesa's llvmpipe through EGL instead (`agent.params.render: cpu`; Mesa's EGL, + `/usr/share/glvnd/egl_vendor.d/50_mesa.json`): no GPU, the same physics, slower frames, images that differ by + renderer noise. Mesa renders a step of RATs' LIBERO env about 11 times slower (0.18 s against 0.016 s on an H200, + with two llvmpipe threads; eight threads bring it to 0.10 s, at four times the CPU), so the actor scales RATs' + policy execution timeout by 11 (`agent.params.execution_timeout_scale`; measure your host's ratio and set it) and + grows the rows' guards by what that can add. The scale bounds a program's whole wall clock, of which its model + calls, vision services and IK run no slower: a CPU row is somewhat more lenient than RATs' 180 s on a GPU. + +## Trust + +RATs runs its generated programs in its own process, which the actor confines: no network, read-only checkout, the row's +output directory the only place it writes, no key. The vision services run outside that sandbox, as the user who starts +`serve.sh`, and a row reaches the loopback ports of the ones its RATs config names (its `api_servers`): in play SAM3, +Contact-GraspNet and PyRoki (8114, 8115, 8116), in evaluation SAM3, PyRoki and the grasp service (GraspGen's 5556, or +Contact-GraspNet's 8115 with `RATS_GRASP=graspnet`). Every row also reaches, and needs, 8114, 8115 and 8116, which RATs' +policy quality checker probes (RATs' evaluation runs the three); none reaches Molmo's 8122. + +What a program can do there is what their request protocols take, which `serve.sh` limits to what RATs' clients send: +- SAM3 (base64 images): its decoder opens any format Pillow knows, and Pillow runs Ghostscript on an EPS image. + `serve.sh` starts it through `sam3_guard.py`, which decodes PNG only, of at most 4096 x 4096 pixels (RATs' clients + send PNG camera images). +- Contact-GraspNet reads NumPy arrays with `np.load`, which refuses pickled ones; PyRoki takes numbers. +- GraspGen (msgpack): its NumPy decoder unpickles an array of kind object, and builds one of an object type over the + request's bytes, whose elements GraspGen then reads as pointers; its server stops on a request of more than one + ZMQ frame. `serve.sh` starts it through `graspgen_guard.py`, which refuses every array whose type holds Python + objects (RATs' client sends arrays of floats) and answers a request in more than one frame as an error. + +`serve.sh` starts every service with a clean environment: no key or token of the shell that started it is in a service's +environment (a service still reads what its user can read, which the guards keep requests from reaching). The guards and +the clean environment hold for the services `serve.sh` started: it leaves a port that already answers alone, and +`launch.sh` checks only that each port answers, so stop a service started any other way first. The actor checks that a +row's services (its config's and the checker's) take a connection before it starts RATs and after the row. A row whose +services do not before it is not run; after it, an exec row whose trials all succeeded keeps its result (`services_down` +in its output), and any other row is a failed run, as a trial may have failed for want of the service. Hermit scores a +failed run 0 within `mean_score` and counts it in `errors` (its trials are in the actor log's `result.json`): run such a +row again. The check finds a service that has stopped, not one that listens but hangs or fails its requests. + +## Run + +From this folder, with the services up (started without the key: `serve.sh` passes them none either way): + +```bash +export RATS_ROOT=/path/to/RATs +RATS_SERVER_GPU=1 HF_HOME=/path/to/hf ./serve.sh # SAM3, Contact-GraspNet, PyRoki, GraspGen +export FIREWORKS_API_KEY=... # for launch.sh: it stays in Hermit's process +RATS_SMOKE=1 RATS_GPUS=3 ./launch.sh train # the smoke: one play iteration +RATS_SMOKE=1 RATS_GPUS=3 ./launch.sh test --adapter final # one test trial on its library +RATS_GPUS=1,3 ./launch.sh train # 50 play iterations +RATS_GPUS=1,3 ./launch.sh val --adapter rats-libero/ckpt-step-20 # a snapshot on the validation split +RATS_GPUS=1,3 ./launch.sh test --adapter final # Table 1 on the final library +RATS_GPUS=1,3 ./launch.sh test --adapter none # the no-library baseline (the paper's No Play) +RATS_RENDER=cpu ./launch.sh test --adapter final # rendered with Mesa on the CPU: no GPU +./serve.sh stop +``` + +To check a config's settings by hand, write the rows into this folder (`tasks/` and `splits/`, which git ignores) +and run the check without its probe, which would run the first training row: a whole play iteration (the smoke): + +```bash +python rows.py --out . +hermit check --no-probe --config train.yaml agent.params.rats_root=$RATS_ROOT agent.params.gpus=3 +``` + +The runs go to `runs/` here (`RATS_OUT`): the rows (`rows//`, one folder per `RATS_ROWS_ARGS` and version +of `rows.py`, written once and shared by the runs started with it), the Trainer's records, the actor's logs (`actor-logs/-/`: +`result.json`, RATs' `iteration_.json`, `runner.log`, the sandbox's records) and RATs' whole output +directories (`rats/`: videos, generated BDDL, attempt artifacts). Each row calls the model many times (RATs' roles: +proposer, environment creator, planner, policy writer, verifiers, diagnoser, feedback generator, curators); its +tokens and cost are in its record. + +## First evaluation + +2026-11-29 and 30, the [reproduction guide](../../../docs/developer/reproducing-a-method.md)'s first-evaluation row: +GLM 5.3 Flash (`fireworks/accounts/fireworks/models/glm-5p3-flash`) in every RATs role at effort medium (RATs' own is +low), reduced in size with `RATS_ROWS_ARGS="--play 10 --tasks 0-4 --test-states 0-0"`: 10 play iterations +(`train.yaml`, concurrency 1), then one trial of tasks 0-4 of each of Table 1's six suites in init state 0 (30 +trials, `test.yaml`, concurrency 4) for the final library and for `--adapter none`. RATs at `1fd2ef5` (with its +LIBERO and LIBERO-PRO), rendering on the CPU (`RATS_RENDER=cpu`), no Molmo. Play and `none` ran at this branch's +"scale RATs' execution timeout" (`ddad5a1`), `final` at "correct the docs on Molmo" (`a43afa7`), which the rebase onto +`main`'s `84afde7` made `50f84c2` and `45dcc6e` with no change to this example; both evaluations ran on the same rows +(diffed). The four services ran as `serve.sh` started them at "score test trials on LIBERO's own check" (`ab4c26d`), +before the SAM3 guard and the GraspGen guard's extension, neither of which changes what RATs' own requests get. + +| Condition | Success | Errors | Spending | Time | +|---|---|---|---|---| +| `none`: the reduced API's primitives, no learned skill (the paper's No Play) | 0.167 (5 of 30), SE 0.068 | 0 | $3.59, 17.4 M tokens | 10.3 h | +| `final`: the library after 10 play iterations | 0.133 (4 of 30), SE 0.062 | 0 | $3.33, 16.6 M tokens | 7.5 h | + +Paired per trial, final − none: −3.3 points, SE 7.6; final better on 2 trials, none on 3, 25 tied (exact sign test +p = 1.0). By suite (none, final): `goal_swap` 1, 1; `goal_task` 0, 1; `object_swap` 0, 1; `object_task` 3, 1; +`spatial_swap` 0, 0; `spatial_task` 1, 0. Training: $1.23, 6.0 M tokens, 15.1 h. These are not the paper's numbers +(another model, 10 of 50 play iterations, 30 of 600 trials), and at 30 trials a difference under about 15 points (two +standard errors) is not told from noise. + +- **The final library does not act at test.** Nine of its ten skills call, directly or through + `localize_with_health_gate`, a primitive of play's full API that the test's reduced API lacks (`get_object_pose`, + `sample_grasp_pose`, `get_object_3d_points_and_masks_from_language`): RATs' own pairing of its play and LIBERO-PRO + configs ([the method page](../../../docs/methods/rats.md#evaluation)). RATs' planner chose learned skills in 25 of + the 30 final rows. In 16, a program raised a `NameError` on `get_object_pose` (in + `place_held_object_and_verify_seated` or `grasp_bar_handle_and_pull`); `grasp_lift_and_verify` and + `localize_with_health_gate` catch the error and return a failure without moving the arm. One of the four successes + calls a learned skill (`grasp_lift_and_verify`), and its program grasped through its own fallback, the reduced API's + `plan_grasp`. +- **More programs were rejected.** RATs' quality checker rejected 34 programs in the final rows, and every attempt of + 3 rows: 29 for a release gated on a post-grasp check, 25 of which call the library's `verify_object_on_surface` + (23 also `grasp_lift_and_verify`). In the `none` rows it rejected 14 (3 for that gate), and no row lost every attempt. +- **Play.** 1 of 10 iterations succeeded (iteration 9, the milk carton on the plate). The checker rejected all six + attempts of iterations 1, 5 and 10 (a release gated on a VLM check, `while True`). The library holds ten + experimental skills: nine written by RATs' skill proposer from failures, and `verify_object_on_surface`, extracted + from iteration 9's success. +- **Molmo's absence shaped the library.** Without Molmo, each localization of the LIBERO API prints Molmo's failed + requests before SAM3's text prompt, and RATs' diagnoser read them as a perception outage in 22 of 28 play diagnoses + (11 of 129 in the final rows, 18 of 150 in `none`'s). The skill proposer wrote `localize_with_health_gate` for that + outage, and `perception_guarded`, which probes Molmo's port before the call it wraps and returns `None` when the port + is closed: without Molmo, every call it wraps fails. SAM3, Contact-GraspNet and PyRoki answered every request; + GraspGen failed 12 (10 in `none`'s rows, 2 in final's), in its own outlier removal and inference on point clouds of + too few points, and kept serving. +- **No row was cut.** No program reached RATs' execution timeout (1,980 s on the CPU; the longest self-check or + execution took 1,407 s), and no row reached the actor's guard (12 h per play row and 4 h per test trial at + `ddad5a1`, 14 h at `a43afa7`; the longest play row took 3.4 h, the longest test row 3.1 h). diff --git a/examples/libero/rats/env_configs/rats_libero_pro_graspnet.yaml b/examples/libero/rats/env_configs/rats_libero_pro_graspnet.yaml new file mode 100644 index 00000000..78c99d89 --- /dev/null +++ b/examples/libero/rats/env_configs/rats_libero_pro_graspnet.yaml @@ -0,0 +1,45 @@ +# RATs Exec on LIBERO-PRO with Contact-GraspNet in place of GraspGen: Playful-RATs/RATs +# env_configs/libero/rats_libero_pro_nonpriv.yaml at 1fd2ef5 with two changes, its API +# FrankaLiberoGraspGenApiReducedSkillLibrary -> FrankaLiberoApiReducedSkillLibrary (the same reduced skill-library +# API, registered by RATs with its default grasp backend, Contact-GraspNet: rats/integrations/__init__.py) and its +# GraspGen server -> Contact-GraspNet's (port 8115), the servers RATs' docs/evaluation.md lists for this evaluation. +# For a machine without GraspGen (NVlabs/GraspGen, which RATs does not install): agent.params.exec_config. +# Upstream is licensed under Apache-2.0 (hermit/adapter/templates/rats/.hermit/UPSTREAM_LICENSE). +env: + _target_: rats.envs.tasks.franka.franka_libero_env.FrankaLiberoCodeEnv + cfg: + _target_: rats.envs.tasks.base.CodeExecEnvConfig + low_level: + _target_: rats.envs.simulators.libero.FrankaLiberoEnv + suite_name: libero_object_swap + task_id: 0 + max_steps: 8000 + control_freq: 20 + privileged: false + apis: + - FrankaLiberoApiReducedSkillLibrary + prompt: | + You are controlling a Franka Emika robot with API described below. + Goal: pick up the alphabet soup and place it in the basket + You may write python code comments for reasoning but ONLY write the executable Python code and do not write it in code fences. + After this code executes, you will be able to get a new observation of the environment and write new code to complete the task if needed. + The functions (APIs) below are already imported to the environment. If you want to use numpy, you need to import it explicitly. + +api_servers: + - _target_: rats.serving.launch_pyroki_server.main + port: 8116 + host: 127.0.0.1 + robot: panda_description + target_link: panda_hand + + - _target_: rats.serving.launch_contact_graspnet_server.main + port: 8115 + host: 127.0.0.1 + + - _target_: rats.serving.launch_sam3_server.main + device: cuda + port: 8114 + host: 127.0.0.1 + +record_video: true +output_dir: ./outputs/rats_libero_pro_nonpriv diff --git a/examples/libero/rats/graspgen-python b/examples/libero/rats/graspgen-python new file mode 100755 index 00000000..c2876ed7 --- /dev/null +++ b/examples/libero/rats/graspgen-python @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# GraspGen's interpreter as RATs' GraspGen launcher calls it (serve.sh passes python=): GraspGen's venv +# Python running the server script through graspgen_guard.py, which refuses the requests msgpack_numpy would unpickle. +set -euo pipefail +exec "${HERMIT_GRASPGEN_PYTHON:?set HERMIT_GRASPGEN_PYTHON to the GraspGen venv Python (serve.sh does)}" \ + "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/graspgen_guard.py" "$@" diff --git a/examples/libero/rats/graspgen_guard.py b/examples/libero/rats/graspgen_guard.py new file mode 100644 index 00000000..314e551e --- /dev/null +++ b/examples/libero/rats/graspgen_guard.py @@ -0,0 +1,98 @@ +"""GraspGen's ZMQ server (NVlabs/GraspGen client-server/graspgen_server.py) with the requests refused that would run +code in it or stop it. + +RATs' programs reach GraspGen's port from the RATs actor's sandbox, and the server runs outside it, as the user who +started serve.sh. GraspGen's wire format is msgpack with msgpack_numpy, and GraspGen's server loop has two openings: + +- msgpack_numpy's decoder builds an array of Python objects from a request: it unpickles one of kind O + (`pickle.loads`), and builds one of an object type under any other kind, or of a structured type with an object + field, over the request's own bytes (`np.ndarray(buffer=...)`), whose elements are then pointers the request chose + and GraspGen reads (`np.asarray(point_cloud, dtype=np.float32)`). Every array whose type holds Python objects is + refused before it is built. +- The server reads one ZMQ frame of a request and then replies, which ZMQ refuses while the request's other frames are + unread: the error leaves the server's loop, and GraspGen stops, for every row. A request of more than one frame is + read whole and answered as an error. + +RATs' own client sends point clouds of floats in one frame, which decode and are answered as before; a refused +request is answered with {"error": ...}, as any request GraspGen cannot handle, and the server serves on. Nothing else +of GraspGen changes. + +serve.sh starts GraspGen through RATs' own launcher (rats.serving.launch_graspgen_server) with `graspgen-python` as +its interpreter, which runs this file under GraspGen's venv: + + HERMIT_GRASPGEN_PYTHON=/.venv/bin/python graspgen-python [its arguments] +""" +from __future__ import annotations + +from pathlib import Path +import runpy +import sys + +# What the server answers a request of more than one frame (its action is unknown to GraspGen: an error reply) +FRAMES_REFUSED = "refused: a request in more than one ZMQ frame" + + +def refuse_object_arrays() -> None: + """msgpack_numpy's decoder, refusing every array whose type holds Python objects before it is built (its unpack + functions look `decode` up per call).""" + import msgpack_numpy + import numpy as np + decode = msgpack_numpy.decode + + def refusal(obj: dict) -> str | None: + """Why the array msgpack_numpy would decode from `obj` is refused (its type read as msgpack_numpy reads it), + or None.""" + if obj.get(b"kind") == b"O": + return "an array of Python objects is refused (msgpack_numpy would unpickle it)" + try: + descr = obj[b"type"] + if obj.get(b"kind") == b"V": + descr = [tuple(msgpack_numpy.tostr(t) if type(t) is bytes else t for t in d) for d in descr] + dtype = np.dtype(msgpack_numpy._unpack_dtype(descr)) + except Exception as exc: # noqa: BLE001 - no type numpy reads: nothing to build + return f"an array of no type numpy reads is refused ({type(exc).__name__})" + if dtype.hasobject: + return "an array of Python objects is refused (msgpack_numpy would build it over the request's bytes)" + return None + + def guarded(obj, chain=None): + why = refusal(obj) if isinstance(obj, dict) and b"nd" in obj else None + if why: + raise ValueError(why) + return decode(obj, chain) + + msgpack_numpy.decode = guarded + + +def one_frame_requests() -> None: + """A reply socket's recv reading a request of more than one frame whole, and handing the server one it answers + with an error (GraspGen's loop reads one frame with socket.recv, then sends).""" + import msgpack + import zmq + recv = zmq.Socket.recv + refused = msgpack.packb({"action": FRAMES_REFUSED}, use_bin_type=True) + + def guarded(self, flags=0, copy=True, track=False): + frame = recv(self, flags, copy=copy, track=track) + if self.getsockopt(zmq.TYPE) == zmq.REP and self.getsockopt(zmq.RCVMORE): + while self.getsockopt(zmq.RCVMORE): + recv(self, flags) + return refused + return frame + + zmq.Socket.recv = guarded + + +def main(argv: list[str]) -> None: + if not argv: + sys.exit("graspgen_guard.py: GraspGen's server script and its arguments") + refuse_object_arrays() + one_frame_requests() + script = argv[0] + sys.argv = list(argv) + sys.path[0] = str(Path(script).resolve().parent) # as `python