From 3894c8a658b8884274e2483eef517c01de4710ca Mon Sep 17 00:00:00 2001 From: iamziyuzhao Date: Sat, 28 Nov 2026 23:54:53 -0500 Subject: [PATCH 01/12] Add RATs: the rats template and Evolver, with a LIBERO example RATs (Playful Agentic Robot Learning, arXiv:2606.19419) learns a skill library by play and is evaluated with the library frozen. Hermit had no way to run it. Now RATs' own code runs every row, unchanged, at the pinned commit: - The rats template holds RATs' skill library (skills.json) and its play-time state (state/: failure memory, retry bank, proposer counts, curator history, loop counters, iteration digests). Its check screens a library's records and code and a state's files. - RatsActor runs RATs' scripts/run_rats.py on one row in RATs' Python 3.10 venv, through runner.py, inside a bubblewrap sandbox of its own: the checkout read-only, no network but the model endpoint and RATs' vision services, one GPU, the authors' learned libraries hidden, and in play the LIBERO-PRO test suites hidden. Every model call goes to a ChatEndpoint in the actor's process (Direct, Layer 1), which holds the key and meters tokens and cost; each request carries the configured reasoning effort (medium by default), and for a model without video input RATs' own _strip_videos_from_messages drops the videos. - A play row is one play iteration, resumed from the adapter with RATs' own --resume. An exec row is one LIBERO-PRO batch-driver job: one task, N trials in init states first_state + j, the library frozen, strict benchmark. - RatsEvolver applies what a play iteration hands back (skills.json and state/) after the template check, or leaves the adapter unchanged and says why. - examples/libero/rats/ has train (50 play iterations), val (the original LIBERO, init states 43-49), test (the paper's Table 1: six LIBERO-PRO suites, init states 0-9, 600 trials) and test_full (eight suites, 50 states) as configs of their own, plus rows.py, launch.sh (rows written once per argument set) and serve.sh (RATs' services). Tests: tests/methods/rats/ (29) on a stand-in of RATs' modules, including the Trainer and evaluate end to end in the sandbox. Docs: docs/methods/rats.md. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + docs/index.md | 1 + docs/methods/index.md | 2 + docs/methods/rats.md | 206 +++++ examples/libero/.gitignore | 3 + examples/libero/README.md | 1 + examples/libero/rats/README.md | 113 +++ .../env_configs/rats_libero_pro_graspnet.yaml | 45 + examples/libero/rats/judge.py | 39 + examples/libero/rats/launch.sh | 92 ++ examples/libero/rats/rows.py | 125 +++ examples/libero/rats/serve.sh | 63 ++ examples/libero/rats/smoke.yaml | 38 + examples/libero/rats/smoke_val.yaml | 36 + examples/libero/rats/task-info/README.md | 10 + examples/libero/rats/test.yaml | 40 + examples/libero/rats/test_full.yaml | 37 + examples/libero/rats/train.yaml | 40 + examples/libero/rats/val.yaml | 40 + .../adapter/templates/rats/.hermit/EVOLVER.md | 20 + .../templates/rats/.hermit/UPSTREAM.md | 8 + .../templates/rats/.hermit/UPSTREAM_LICENSE | 201 +++++ .../templates/rats/.hermit/adapter.yaml | 36 + .../adapter/templates/rats/.hermit/check.py | 185 ++++ hermit/adapter/templates/rats/ADAPTER.md | 5 + hermit/adapter/templates/rats/README.md | 14 + hermit/adapter/templates/rats/exports.yaml | 4 + hermit/adapter/templates/rats/skills.json | 226 +++++ hermit/agent/evolver/methods/rats/actor.py | 536 ++++++++++++ hermit/agent/evolver/methods/rats/evolver.py | 111 +++ .../agent/evolver/methods/rats/evolver.yaml | 12 + hermit/agent/evolver/methods/rats/runner.py | 269 ++++++ tests/README.md | 2 +- tests/core/test_selection.py | 5 +- tests/methods/rats/test_rats.py | 802 ++++++++++++++++++ tests/selection.py | 1 + 36 files changed, 3373 insertions(+), 3 deletions(-) create mode 100644 docs/methods/rats.md create mode 100644 examples/libero/rats/README.md create mode 100644 examples/libero/rats/env_configs/rats_libero_pro_graspnet.yaml create mode 100644 examples/libero/rats/judge.py create mode 100755 examples/libero/rats/launch.sh create mode 100644 examples/libero/rats/rows.py create mode 100755 examples/libero/rats/serve.sh create mode 100644 examples/libero/rats/smoke.yaml create mode 100644 examples/libero/rats/smoke_val.yaml create mode 100644 examples/libero/rats/task-info/README.md create mode 100644 examples/libero/rats/test.yaml create mode 100644 examples/libero/rats/test_full.yaml create mode 100644 examples/libero/rats/train.yaml create mode 100644 examples/libero/rats/val.yaml create mode 100644 hermit/adapter/templates/rats/.hermit/EVOLVER.md create mode 100644 hermit/adapter/templates/rats/.hermit/UPSTREAM.md create mode 100644 hermit/adapter/templates/rats/.hermit/UPSTREAM_LICENSE create mode 100644 hermit/adapter/templates/rats/.hermit/adapter.yaml create mode 100644 hermit/adapter/templates/rats/.hermit/check.py create mode 100644 hermit/adapter/templates/rats/ADAPTER.md create mode 100644 hermit/adapter/templates/rats/README.md create mode 100644 hermit/adapter/templates/rats/exports.yaml create mode 100644 hermit/adapter/templates/rats/skills.json create mode 100644 hermit/agent/evolver/methods/rats/actor.py create mode 100644 hermit/agent/evolver/methods/rats/evolver.py create mode 100644 hermit/agent/evolver/methods/rats/evolver.yaml create mode 100644 hermit/agent/evolver/methods/rats/runner.py create mode 100644 tests/methods/rats/test_rats.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 91e80f5f..2784056c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -152,6 +152,14 @@ 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 (init states 43-49), LIBERO-PRO as test (the + paper's Table 1, 600 trials; and all eight suites in all 50 init states), each split its own config, with + `launch.sh` and `serve.sh` for RATs' vision services ([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..23ff068b --- /dev/null +++ b/docs/methods/rats.md @@ -0,0 +1,206 @@ +# 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 (RATs' own default) + 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 three 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' 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, RATs' own `llm_reasoning_effort`, which RATs sends only in its OpenAI form). RATs' verifiers and + diagnoser attach the attempt's videos, which Gemini takes; for a model that takes none (`agent.params.video: + false`, the default) the runner drops them from every call with RATs' own `_strip_videos_from_messages`, as RATs + does when it falls back to a model without video, and the images and text stay. +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 (the curation and skill-proposal counters, the curator's rolling history, the failure memory's + distillation counter) is restored from `state/loop.json` before the iteration and saved after it; everything else + RATs carries already lives in its output directory, which its own `--resume` reads. + +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 RATs' vision services on their loopback ports (SAM3 8114, +Contact-GraspNet 8115, PyRoki 8116, GraspGen 5556, Molmo 8122), and sees one GPU. It hides what no row reads: the +checkout's git history, its `outputs/` and logs, 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'. + +## The step + +```mermaid +flowchart TD + A["adapter: skills.json (L) + state/ (M, retry bank,
proposer counts, curator history, loop.json, 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`, 40 | exec | the original LIBERO Spatial, Object, Goal and Long suites, 10 tasks each, init states 43-49 | 280 | +| `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, one validation trial, one test trial | 1 each | + +What play and the test share: play never reads a test suite's BDDL files or init states (the sandbox hides them), +and the actor refuses RATs' `--proposer-include-eval-task-context` (its optional task-aware play, which writes the +60 test tasks' descriptions into the proposer's prompt) in a play row. 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 changes the instruction and goal. 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. + +What play and validation share: validation is the original LIBERO, the setting the paper's play is grounded in. +RATs' play may rebind to the tasks of its scene's suite (`libero_spatial`'s ten: +`LifelongLoop._init_libero_validated_tasks`) and resets with the iteration's seed, so the `libero_spatial` +validation rows are not unseen by play; their 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. + +## 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 `RATS_VERIFIER_STRICT_BENCHMARK=1`, so that only LIBERO's native `task_completed` counts. +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"). 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. +`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; the strict-benchmark flag and RATs' verifiers are what keep a reported success +to LIBERO's own goal check. + +## 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`: the videos RATs attaches to its +vision calls are dropped; `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; a play row refuses +those that name its scene or output, or put the test tasks into play), `env` (more variables for RATs' process; a +secret-looking name is refused), `service_ports`, `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`, `trial_timeout_s`, `call_timeout_s`, `max_retries`. + +## 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 distillation counter | saved to and restored from `state/loop.json` around each iteration | 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 | medium (`llm_reasoning_effort`), sent in RATs' OpenAI form only | medium on every request (`effort`); a request of RATs' own that sets one keeps it | the first-evaluation row; RATs' own default | +| Videos in vision calls | the verifiers and the diagnoser attach the attempt's videos (Gemini takes them) | dropped with RATs' `_strip_videos_from_messages`, images and text kept (`video: true` keeps them) | GLM 5.3 Flash refuses video input (HTTP 400); RATs does the same for its fallback models; a deviation | +| 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 | +| Vision services | auto-launched from the env config | started once by `serve.sh` from RATs' own server modules, shared by the rows | concurrent rows share them; acceptable | +| Molmo (8122) | a vLLM-served pointing model, set up with the MolmoSpaces runtime; `docs/setup.md`: the LIBERO-PRO workflows do not require it | not started; the LIBERO API's Molmo pointing falls back to SAM3's text prompt | as RATs' LIBERO setup | +| 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 loopback services, one GPU, the authors' libraries and the test suites hidden in play | the framework's rules for a run's code | +| Not ported | MolmoSpaces, the real robot, the plug-in mode | — | scope | + +## What it is not + +The final library is what RATs' play produced; nothing selects it on held-out data. Validation and test scores are +RATs' own success flags. Play and validation share LIBERO's original scenes (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..4b6a1b59 --- /dev/null +++ b/examples/libero/rats/README.md @@ -0,0 +1,113 @@ +# 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 iterations (`splits/train.txt`), one 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 | +| `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 | 40 exec rows | `libero_spatial`, `libero_object`, `libero_goal`, `libero_10` (the original LIBERO) | 43-49 | 280 | `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 (the sandbox hides them), and a +play row refuses RATs' `--proposer-include-eval-task-context`, which would show the test tasks to the proposer. +Validation shares LIBERO's original scenes with play (play may rebind to `libero_spatial`'s tasks), 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. `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** (a vLLM-served pointing model on 8122) is not started: RATs' `docs/setup.md` lists it with the + MolmoSpaces runtime and says the LIBERO-PRO workflows do not require it; the LIBERO API then falls back to SAM3's + text prompt (its log shows the failed requests). +- **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. + +## Run + +From this folder, with the services up: + +```bash +export RATS_ROOT=/path/to/RATs FIREWORKS_API_KEY=... +RATS_SERVER_GPU=1 HF_HOME=/path/to/hf ./serve.sh # SAM3, Contact-GraspNet, PyRoki, GraspGen +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) +./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`, 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. 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/judge.py b/examples/libero/rats/judge.py new file mode 100644 index 00000000..3a6f3a73 --- /dev/null +++ b/examples/libero/rats/judge.py @@ -0,0 +1,39 @@ +"""The judge, on the host: what the RATs actor returned (hermit/agent/evolver/methods/rats/actor.py). + +- An exec row (validation, test) scores the share of its trials whose native LIBERO success check passed in RATs' + process (RATS_VERIFIER_STRICT_BENCHMARK=1: only `task_completed` counts, as RATs' LIBERO-PRO evaluation counts it); + a trial that never ran (RATs crashed, the row timed out) counts as failed. +- A play row scores 1 when RATs judged its self-proposed task solved, else 0: RATs' play success rate, a record of + play (the Evolver applies every iteration's update, as RATs does), not an objective. + +The flags come from RATs' own process, which also runs the generated programs: the trust of RATs' own evaluation +(docs/methods/rats.md, "Evaluation").""" +from __future__ import annotations + + +def score(task: dict, output) -> dict: + out = getattr(output, "output", output) + if not isinstance(out, dict): + return {"score": 0.0, "feedback": "the RATs actor returned no result"} + error = out.get("error") + note = f"; RATs: {str(error)[:300]}" if error else "" + if out.get("mode") == "play": + if out.get("iteration") is None: + return {"score": 0.0, "feedback": f"the play iteration did not run{note}"} + task_text = f" {out['task']!r}" if out.get("task") else "" + learned = out.get("skills_learned") or [] + return {"score": 1.0 if out.get("success") else 0.0, + "feedback": f"play iteration {out['iteration']}:{task_text} " + f"{'solved' if out.get('success') else 'not solved'}" + + (f"; skills learned: {', '.join(map(str, learned))}" if learned else "") + note, + "iteration": out["iteration"], "state": bool(out.get("state"))} + trials = int(out.get("trials") or task.get("trials") or 0) + if trials <= 0: + return {"score": 0.0, "feedback": f"no trials{note}"} + successes = int(out.get("successes") or 0) + ran = int(out.get("ran") or 0) + first = int(task.get("first_state", 0)) + return {"score": successes / trials, + "feedback": f"{successes}/{trials} trials in init states {first}-{first + trials - 1}" + + (f" ({trials - ran} did not run)" if ran < trials else "") + note, + "successes": successes, "trials": trials, "ran": ran} diff --git a/examples/libero/rats/launch.sh b/examples/libero/rats/launch.sh new file mode 100755 index 00000000..ef798b25 --- /dev/null +++ b/examples/libero/rats/launch.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# RATs on LIBERO (Playful-RATs/RATs, arXiv:2606.19419) through Hermit: train (play), validation and test, each with +# its own config and split. Run it on the host that serves RATs' vision services (./serve.sh). From this folder: +# +# RATS_ROOT=/path/to/RATs RATS_GPUS=1,3 ./launch.sh train # train.yaml: 50 play iterations +# ./launch.sh val --adapter final # val.yaml: the validation split +# ./launch.sh val --adapter rats-libero/ckpt-step-20 # a snapshot (train.yaml's save_freq) +# ./launch.sh test --adapter final # test.yaml: LIBERO-PRO, Table 1 (600 trials) +# ./launch.sh test --adapter none # no library: RATs' noseed condition +# ./launch.sh test_full --adapter final # test_full.yaml: 8 suites x 50 init states +# RATS_SMOKE=1 ./launch.sh train | test | val # smoke.yaml, smoke_val.yaml +# +# Variables: RATS_ROOT (RATs' checkout with its .venv, README.md), RATS_GPUS (the GPUs RATs renders LIBERO on), +# RATS_GRASP (graspgen, the default: RATs' LIBERO-PRO config; graspnet: env_configs/rats_libero_pro_graspnet.yaml), +# RATS_OUT (the runs, default runs/ here: the rows, the Trainer's records, the actor's logs and RATs' output +# directories), RATS_ROWS_ARGS (rows.py's options: --play, --tasks, --val-states, --test-states, --full-states), +# HERMIT_PYTHON (default python), FIREWORKS_API_KEY (the configs' model; it stays in Hermit's process). Any further +# argument goes to hermit: --adapter for an evaluation, or a config override (key=value). +set -euo pipefail +HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +cd "$HERE" +: "${RATS_ROOT:?set RATS_ROOT to a RATs checkout with its .venv (README.md)}" +RATS_ROOT="$(cd "$RATS_ROOT" && pwd)" +[[ -x "$RATS_ROOT/.venv/bin/python" && -f "$RATS_ROOT/scripts/run_rats.py" ]] \ + || { echo "$RATS_ROOT: not a RATs checkout with its .venv (README.md)" >&2; exit 1; } +: "${RATS_GPUS:?set RATS_GPUS to the GPUs RATs renders LIBERO on, e.g. 1,3}" +# The RATs commit this example was written against; another one is run, but named. +PINNED=1fd2ef56857cfde6d5d815fc49a9fe9b0a531beb +ACTUAL="$(git -C "$RATS_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)" +[[ "$ACTUAL" == "$PINNED" ]] || echo "note: RATS_ROOT is at $ACTUAL, not the pinned $PINNED" >&2 +HERMIT="${HERMIT_PYTHON:-python}" +[[ "$HERMIT" != */* || "$HERMIT" == /* ]] || HERMIT="$PWD/$HERMIT" + +MODE="${1:-train}" +[[ $# -eq 0 ]] || shift +case "$MODE" in + train|val|test|test_full) ;; + *) echo "usage: ./launch.sh train|val|test|test_full [--adapter A] [key=value ...]" >&2; exit 2 ;; +esac +if [[ -n "${RATS_SMOKE:-}" ]]; then + case "$MODE" in + train|test) CONFIG=smoke.yaml ;; + val) CONFIG=smoke_val.yaml ;; + *) echo "the smoke has train, test and val" >&2; exit 2 ;; + esac +else + CONFIG="$MODE.yaml" +fi +! grep -q "model: fireworks/" "$CONFIG" || : "${FIREWORKS_API_KEY:?set FIREWORKS_API_KEY}" +EXTRA=() +case "${RATS_GRASP:-graspgen}" in + graspgen) GRASP=5556 ;; + graspnet) GRASP=8115; EXTRA+=("agent.params.exec_config=env_configs/rats_libero_pro_graspnet.yaml") ;; + *) echo "RATS_GRASP is graspgen or graspnet" >&2; exit 2 ;; +esac + +# RATs' services on their loopback ports (serve.sh): SAM3 and PyRoki always; play's Contact-GraspNet, evaluation's +# grasp service +up() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } +if [[ "$MODE" == train ]]; then NEED=(8114 8115 8116); else NEED=(8114 8116 "$GRASP"); fi +for port in "${NEED[@]}"; do + up "$port" || { echo "RATs' service on 127.0.0.1:$port is not up (./serve.sh)" >&2; exit 1; } +done + +OUT="${RATS_OUT:-$HERE/runs}" +mkdir -p "$OUT" +OUT="$(cd "$OUT" && pwd)" +case "$(cd "$OUT" && pwd -P)/" in # the sandbox shows RATs' checkout: the runs stay out of it + "$(cd "$RATS_ROOT" && pwd -P)"/*) echo "RATS_OUT ($OUT) lies inside RATS_ROOT: keep the runs elsewhere" >&2; exit 2 ;; +esac + +# The rows and splits the configs read (rows.py here), one folder per RATS_ROWS_ARGS +# (e.g. "--play 20 --test-states 0-4"), written once and then only read: runs started side by side (training, a +# baseline's evaluation) share it, and none rewrites another's +KEY="$(printf '%s' "${RATS_ROWS_ARGS:-}" | sha1sum | cut -c1-12)" +ROWS="$OUT/rows/$KEY" +if [[ ! -f "$ROWS/done" ]]; then + TMP="$OUT/rows/.tmp-$$" + rm -rf -- "$TMP" + # shellcheck disable=SC2086 + "$HERMIT" "$HERE/rows.py" --out "$TMP" ${RATS_ROWS_ARGS:-} + printf '%s\n' "${RATS_ROWS_ARGS:-}" > "$TMP/done" + mv -T -- "$TMP" "$ROWS" 2>/dev/null || rm -rf -- "$TMP" # another launch wrote the same rows first +fi +split() { sed -n "s/^ $1: *splits\/\([^ #]*\).*/\1/p" "$CONFIG" | head -1; } +RUN="$(sed -n 's/^ run_name: *\([^ #]*\).*/\1/p' "$CONFIG" | head -1)" +# One tree per training run: the evaluations' --adapter final and ckpt tags name its adapters +if [[ "$MODE" == train ]]; then CMD=train; DIR="$OUT"; else CMD=eval; DIR="$OUT/$MODE"; fi +exec "$HERMIT" -m hermit.cli "$CMD" --config "$CONFIG" "data.tasks=$ROWS/tasks" \ + "data.train=$ROWS/splits/$(split train)" "data.test=$ROWS/splits/$(split test)" "agent.params.rats_root=$RATS_ROOT" \ + "agent.params.gpus=$RATS_GPUS" "agent.params.logs=$DIR/actor-logs" "agent.params.scratch=$DIR/rats" \ + "trainer.output_dir=$DIR" "trainer.tree_dir=$OUT/trees/$RUN" ${EXTRA[@]+"${EXTRA[@]}"} "$@" diff --git a/examples/libero/rats/rows.py b/examples/libero/rats/rows.py new file mode 100644 index 00000000..ee29e002 --- /dev/null +++ b/examples/libero/rats/rows.py @@ -0,0 +1,125 @@ +"""RATs' task rows on LIBERO and LIBERO-PRO, and the splits the example's configs read (examples/libero/rats/): task +directories in Harbor's format (hermit.task.directory), each row's fields under [metadata], read back by the +cap-harness view (examples/cap_harness/utils/agent/fields.py:task_row). launch.sh writes them (into its runs folder, +rows//, one folder per set of options); by hand, from this folder: + + python rows.py --out . + +The three splits share nothing: + +- train (`play-`): RATs' play iterations, `mode: play`. No benchmark task: RATs proposes its own tasks in LIBERO's + scenes (its LIBERO catalog of objects and fixtures; play bootstraps from libero_spatial task 0, as + env_configs/libero/rats_libero_play.yaml does). RATs plays N = 50 iterations (arXiv:2606.19419 §4.1). +- val (`val--t`): RATs Exec with the library frozen on the original LIBERO suites (Spatial, Object, Goal, + Long: 40 tasks) in init states 43-49, `mode: exec`. RATs has no validation step; these rows serve the choice of a + snapshot or a setting, outside the test suites. +- test (`test--t`): RATs Exec on LIBERO-PRO's six held-out suites (Object, Goal and Spatial under the + position swap and the task perturbation: 60 tasks), init states 0-9: the paper's Table 1 (600 trials). +- test_full (`full--t`): the eight LIBERO-PRO suites (with LIBERO-Long's two) in all 50 init states. +- smoke_train, smoke_val, smoke_test: one play iteration, one validation trial, one test trial. + +An exec row is one RATs job (scripts/run_rats_libero_pro_batch.py): one task, all of its trials in one RATs process, +trial j in init state `first_state` + j; its score is the share of trials whose native success check passed. +""" +from __future__ import annotations + +import argparse +from pathlib import Path +import re +import shutil + +from hermit.task.directory import write_task + +ORIGINAL = ("libero_spatial", "libero_object", "libero_goal", "libero_10") +PAPER_TEST = ("libero_object_swap", "libero_object_task", "libero_goal_swap", "libero_goal_task", + "libero_spatial_swap", "libero_spatial_task") +FULL_TEST = (*PAPER_TEST, "libero_10_swap", "libero_10_task") +TASKS_PER_SUITE = 10 +INIT_STATES = 50 + + +def states(value: str) -> tuple[int, int]: + """`a-b` (inclusive) as (first, count), within LIBERO's 50 init states.""" + m = re.fullmatch(r"\s*(\d+)\s*(?:-\s*(\d+))?\s*", str(value)) + if not m: + raise argparse.ArgumentTypeError(f"init states as a-b, not {value!r}") + first, last = int(m.group(1)), int(m.group(2) or m.group(1)) + if last < first or last >= INIT_STATES: + raise argparse.ArgumentTypeError(f"init states {value}: within 0-{INIT_STATES - 1}") + return first, last - first + 1 + + +def play_row(k: int) -> dict: + return {"id": f"play-{k:03d}", "mode": "play", "slot": k, "split": "train"} + + +def exec_row(prefix: str, split: str, suite: str, task_id: int, first: int, trials: int) -> dict: + return {"id": f"{prefix}-{suite}-t{task_id:02d}", "mode": "exec", "suite": suite, "task_id": task_id, + "first_state": first, "trials": trials, "split": split} + + +def instruction(row: dict) -> str: + if row["mode"] == "play": + return (f"Play iteration slot {row['slot']}: propose a task of your own in a LIBERO scene, attempt it, and " + "update the skill library and the failure memory.") + last = row["first_state"] + row["trials"] - 1 + return (f"Solve LIBERO suite `{row['suite']}`, task {row['task_id']}, in init states {row['first_state']}-{last} " + "with the skill library frozen.") + + +def task_ids(value: str) -> range: + """`a-b` (inclusive) as the task ids of each suite, within its ten.""" + m = re.fullmatch(r"\s*(\d+)\s*(?:-\s*(\d+))?\s*", str(value)) + first, last = (int(m.group(1)), int(m.group(2) or m.group(1))) if m else (1, 0) + if last < first or last >= TASKS_PER_SUITE: + raise argparse.ArgumentTypeError(f"task ids {value!r}: a-b within 0-{TASKS_PER_SUITE - 1}") + return range(first, last + 1) + + +def build(play: int, val_states: tuple[int, int], test_states: tuple[int, int], + full_states: tuple[int, int], tasks: range = range(TASKS_PER_SUITE)) -> dict[str, list[dict]]: + return { + "train": [play_row(k) for k in range(1, play + 1)], + "val": [exec_row("val", "val", s, t, *val_states) for s in ORIGINAL for t in tasks], + "test": [exec_row("test", "test", s, t, *test_states) for s in PAPER_TEST for t in tasks], + "test_full": [exec_row("full", "test_full", s, t, *full_states) for s in FULL_TEST for t in tasks], + "smoke_train": [play_row(1)], + "smoke_val": [exec_row("smoke-val", "smoke_val", ORIGINAL[0], 0, val_states[0], 1)], + "smoke_test": [exec_row("smoke-test", "smoke_test", PAPER_TEST[0], 0, test_states[0], 1)], + } + + +def write(out: Path, splits: dict[str, list[dict]]) -> None: + for name in ("tasks", "splits"): # this script's own output: rewritten whole + if (out / name).exists(): + shutil.rmtree(out / name) + (out / "splits").mkdir(parents=True) + written = set() + for split, rows in splits.items(): + for row in rows: + if row["id"] not in written: + write_task(out / "tasks" / row["id"], instruction(row), + metadata={k: v for k, v in row.items() if k != "id"}, + environment={"network_mode": "no-network"}) + written.add(row["id"]) + (out / "splits" / f"{split}.txt").write_text("".join(f"{r['id']}\n" for r in rows)) + print(", ".join(f"{k}: {len(v)}" for k, v in splits.items()) + f" -> {out / 'tasks'}") + + +def main(argv=None) -> None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--out", type=Path, required=True, help="where tasks/ and splits/ go") + ap.add_argument("--play", type=int, default=50, help="play iterations (RATs: 50)") + ap.add_argument("--val-states", type=states, default=states("43-49")) + ap.add_argument("--test-states", type=states, default=states("0-9"), help="the paper's: the first ten") + ap.add_argument("--full-states", type=states, default=states("0-49")) + ap.add_argument("--tasks", type=task_ids, default=task_ids("0-9"), + help="the task ids of each suite in val, test and test_full (all ten by default)") + a = ap.parse_args(argv) + if a.play < 1: + ap.error("--play: at least one iteration") + write(a.out, build(a.play, a.val_states, a.test_states, a.full_states, a.tasks)) + + +if __name__ == "__main__": + main() diff --git a/examples/libero/rats/serve.sh b/examples/libero/rats/serve.sh new file mode 100755 index 00000000..3f0c5fda --- /dev/null +++ b/examples/libero/rats/serve.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# RATs' vision services on their fixed loopback ports, each from RATs' own server module, as RATs' +# scripts/start_servers.sh starts them: SAM3 (8114) and PyRoki (8116) for play and evaluation, Contact-GraspNet (8115) +# for play (and RATS_GRASP=graspnet evaluations), GraspGen (5556) for evaluation. A port already listening is left as +# it is (another RATs run's services serve this one too). +# +# RATS_ROOT=/path/to/RATs RATS_SERVER_GPU=1 ./serve.sh # all four +# RATS_SERVICES="sam3 graspnet pyroki" ./serve.sh # some of them +# ./serve.sh stop # the ones this script started +# +# Variables: RATS_SERVER_GPU (the GPU their models load on; default 0), RATS_OUT (logs and pids under services/; +# default runs/ here), HF_HOME (where SAM3's checkpoint is: facebook/sam3 on Hugging Face, gated; accept its terms, +# then download it once with your token), GRASPGEN_ROOT, GRASPGEN_MODELS_DIR (NVlabs/GraspGen with its .venv, and its +# GraspGenModels: by default beside RATS_ROOT; README.md). +set -euo pipefail +HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +OUT="${RATS_OUT:-$HERE/runs}" +LOGS="$OUT/services" +mkdir -p "$LOGS" +up() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } + +if [[ "${1:-}" == stop ]]; then + # SIGTERM: GraspGen's launcher passes it on to the GraspGen server it started + for pid in "$LOGS"/*.pid; do + [[ -f "$pid" ]] || continue + kill "$(cat "$pid")" 2>/dev/null && echo "stopped $(basename "$pid" .pid)" || true + rm -f "$pid" + done + exit 0 +fi + +: "${RATS_ROOT:?set RATS_ROOT to a RATs checkout with its .venv (README.md)}" +RATS_ROOT="$(cd "$RATS_ROOT" && pwd)" +GPU="${RATS_SERVER_GPU:-0}" +GRASPGEN_ROOT="${GRASPGEN_ROOT:-$(dirname "$RATS_ROOT")/GraspGen}" +declare -A PORT=([sam3]=8114 [graspnet]=8115 [pyroki]=8116 [graspgen]=5556) +declare -A CODE=( + [sam3]="from rats.serving.launch_sam3_server import main; main(device='cuda', port=8114, host='127.0.0.1')" + [graspnet]="from rats.serving.launch_contact_graspnet_server import main; main(device='cuda', port=8115, host='127.0.0.1')" + [pyroki]="from rats.serving.launch_pyroki_server import main; main(robot='panda_description', target_link='panda_hand', port=8116, host='127.0.0.1')" + [graspgen]="from rats.serving.launch_graspgen_server import main; main(port=5556, host='127.0.0.1', graspgen_root='$GRASPGEN_ROOT')" +) +started=() +for name in ${RATS_SERVICES:-sam3 graspnet pyroki graspgen}; do + [[ -n "${PORT[$name]:-}" ]] || { echo "unknown service $name (sam3 graspnet pyroki graspgen)" >&2; exit 2; } + port="${PORT[$name]}" + if up "$port"; then echo "[$name] already listening on $port"; continue; fi + echo "[$name] starting on 127.0.0.1:$port (GPU $GPU), log $LOGS/$name.log" + # the subshell becomes the server (exec): its pid is the server's, and it holds none of this script's descriptors + (cd "$RATS_ROOT" && CUDA_VISIBLE_DEVICES="$GPU" PYTHONPATH="$RATS_ROOT" MUJOCO_GL=egl PYOPENGL_PLATFORM=egl \ + TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1 exec nohup .venv/bin/python -c "${CODE[$name]}" \ + < /dev/null > "$LOGS/$name.log" 2>&1) & + echo $! > "$LOGS/$name.pid" + started+=("$name") +done +for name in ${started[@]+"${started[@]}"}; do + for _ in $(seq 1 600); do + up "${PORT[$name]}" && break + kill -0 "$(cat "$LOGS/$name.pid")" 2>/dev/null || { echo "[$name] exited: $LOGS/$name.log" >&2; exit 1; } + sleep 1 + done + up "${PORT[$name]}" && echo "[$name] up on ${PORT[$name]}" || { echo "[$name] not up after 600 s: $LOGS/$name.log" >&2; exit 1; } +done diff --git a/examples/libero/rats/smoke.yaml b/examples/libero/rats/smoke.yaml new file mode 100644 index 00000000..2ce7be57 --- /dev/null +++ b/examples/libero/rats/smoke.yaml @@ -0,0 +1,38 @@ +# RATs on LIBERO, the smoke: one play iteration (train), then one test trial (LIBERO-PRO libero_object_swap task +# 0, init state 0) with the library it left. Started by launch.sh: RATS_SMOKE=1 ./launch.sh train; RATS_SMOKE=1 +# ./launch.sh test --adapter final; RATS_SMOKE=1 ./launch.sh val --adapter final +data: + tasks: tasks # written by launch.sh (rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it was written + train: splits/smoke_train.txt # play-001 + test: splits/smoke_test.txt # libero_object_swap task 0, init state 0 + step_size: 1 + shuffle: false +task_info: task-info +agent: + name: hermit.agent.evolver.methods.rats.actor:RatsActor + concurrency: 1 + params: + rats_root: $RATS_ROOT # RATs' checkout with its venv (README.md), at the commit launch.sh pins + model: fireworks/accounts/fireworks/models/glm-5p3-flash # every RATs role; it must take images + effort: medium # each request's reasoning_effort (RATs' own default) + gpus: $RATS_GPUS # the GPUs RATs renders LIBERO on (the N of /dev/nvidia) + per_gpu: 2 +judge: + path: judge.py # on the host: the trials' native success, from RATs' process +template: rats +evolver: + name: rats +environment: + runner: host # the actor renders on a GPU and confines RATs in a sandbox of its own +sandbox: + enabled: true + enforce: required +trainer: + run_name: smoke-rats-libero # the training run whose adapters this evaluates (--adapter final, ckpt tags) + epochs: 1 + call_timeout_min: 30 + save_freq: {steps: 1} + budget: {usd: 20, hours: 12} +eval: + repeats: 1 diff --git a/examples/libero/rats/smoke_val.yaml b/examples/libero/rats/smoke_val.yaml new file mode 100644 index 00000000..1652cc6d --- /dev/null +++ b/examples/libero/rats/smoke_val.yaml @@ -0,0 +1,36 @@ +# RATs on LIBERO, the smoke's validation: one validation trial (libero_spatial task 0, init state 43) with the +# smoke run's library. Started by launch.sh: RATS_SMOKE=1 ./launch.sh val --adapter final +data: + tasks: tasks # written by launch.sh (rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it was written + train: splits/smoke_train.txt # unused by eval + test: splits/smoke_val.txt # libero_spatial task 0, init state 43 + step_size: 1 + shuffle: false +task_info: task-info +agent: + name: hermit.agent.evolver.methods.rats.actor:RatsActor + concurrency: 1 + params: + rats_root: $RATS_ROOT # RATs' checkout with its venv (README.md), at the commit launch.sh pins + model: fireworks/accounts/fireworks/models/glm-5p3-flash # every RATs role; it must take images + effort: medium # each request's reasoning_effort (RATs' own default) + gpus: $RATS_GPUS # the GPUs RATs renders LIBERO on (the N of /dev/nvidia) + per_gpu: 2 +judge: + path: judge.py # on the host: the trials' native success, from RATs' process +template: rats +evolver: + name: rats +environment: + runner: host # the actor renders on a GPU and confines RATs in a sandbox of its own +sandbox: + enabled: true + enforce: required +trainer: + run_name: smoke-rats-libero # the training run whose adapters this evaluates (--adapter final, ckpt tags) + epochs: 1 + call_timeout_min: 30 + budget: {usd: 20, hours: 12} +eval: + repeats: 1 diff --git a/examples/libero/rats/task-info/README.md b/examples/libero/rats/task-info/README.md new file mode 100644 index 00000000..9dd4260b --- /dev/null +++ b/examples/libero/rats/task-info/README.md @@ -0,0 +1,10 @@ +# RATs on LIBERO + +Play (training): RATs proposes its own manipulation tasks in LIBERO's tabletop scenes, writes each one's BDDL, checks +that the environment instantiates, and has its execution team (planner, policy writer, verifiers, failure diagnoser) +solve it with a Franka arm through RATs' Code-as-Policy API (SAM3 segmentation, a grasp planner, PyRoki inverse +kinematics), up to six attempts (five retries). Its memory team turns each success into reusable skills and each +failure into lessons. No benchmark task is given during play. + +Evaluation: RATs Exec on LIBERO tasks with the learned skill library frozen; a trial succeeds when LIBERO's own goal +check passes. diff --git a/examples/libero/rats/test.yaml b/examples/libero/rats/test.yaml new file mode 100644 index 00000000..0829ada4 --- /dev/null +++ b/examples/libero/rats/test.yaml @@ -0,0 +1,40 @@ +# RATs on LIBERO, test: the paper's Table 1 (arXiv:2606.19419 §4.2). RATs Exec with a training run's library +# frozen on LIBERO-PRO's six held-out suites (Object, Goal, Spatial under the position swap and the task +# perturbation), 10 tasks each, init states 0-9 (splits/test.txt: 60 rows, 600 trials), as RATs' LIBERO-PRO batch +# driver runs them. Started by launch.sh: +# ./launch.sh test --adapter final # RATs +# ./launch.sh test --adapter none # no library: RATs' noseed condition (its reduced API's primitives) +data: + tasks: tasks # written by launch.sh (rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it was written + train: splits/train.txt # unused by eval (a config names its training split) + test: splits/test.txt # LIBERO-PRO Object/Goal/Spatial x swap/task, init states 0-9 + step_size: 1 + shuffle: false +task_info: task-info +agent: + name: hermit.agent.evolver.methods.rats.actor:RatsActor + concurrency: 4 # RATs jobs at once: GPUs x per_gpu + params: + rats_root: $RATS_ROOT # RATs' checkout with its venv (README.md), at the commit launch.sh pins + model: fireworks/accounts/fireworks/models/glm-5p3-flash # every RATs role; it must take images + effort: medium # each request's reasoning_effort (RATs' own default) + gpus: $RATS_GPUS # the GPUs RATs renders LIBERO on (the N of /dev/nvidia) + per_gpu: 2 +judge: + path: judge.py # on the host: the trials' native success, from RATs' process +template: rats +evolver: + name: rats +environment: + runner: host # the actor renders on a GPU and confines RATs in a sandbox of its own +sandbox: + enabled: true + enforce: required +trainer: + run_name: rats-libero # the training run whose adapters this evaluates (--adapter final, ckpt tags) + epochs: 1 + call_timeout_min: 30 + budget: {usd: 500, hours: 400} +eval: + repeats: 1 diff --git a/examples/libero/rats/test_full.yaml b/examples/libero/rats/test_full.yaml new file mode 100644 index 00000000..3db952b1 --- /dev/null +++ b/examples/libero/rats/test_full.yaml @@ -0,0 +1,37 @@ +# RATs on LIBERO, the full LIBERO-PRO test: all eight swap and task suites (with LIBERO-Long's two), 10 tasks +# each, all 50 init states (splits/test_full.txt: 80 rows, 4,000 trials), for a comparison on the whole benchmark +# beyond the paper's protocol (test.yaml). Started by launch.sh: ./launch.sh test_full --adapter final +data: + tasks: tasks # written by launch.sh (rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it was written + train: splits/train.txt # unused by eval (a config names its training split) + test: splits/test_full.txt # LIBERO-PRO's 8 suites x 10 tasks, init states 0-49 + step_size: 1 + shuffle: false +task_info: task-info +agent: + name: hermit.agent.evolver.methods.rats.actor:RatsActor + concurrency: 4 # RATs jobs at once: GPUs x per_gpu + params: + rats_root: $RATS_ROOT # RATs' checkout with its venv (README.md), at the commit launch.sh pins + model: fireworks/accounts/fireworks/models/glm-5p3-flash # every RATs role; it must take images + effort: medium # each request's reasoning_effort (RATs' own default) + gpus: $RATS_GPUS # the GPUs RATs renders LIBERO on (the N of /dev/nvidia) + per_gpu: 2 +judge: + path: judge.py # on the host: the trials' native success, from RATs' process +template: rats +evolver: + name: rats +environment: + runner: host # the actor renders on a GPU and confines RATs in a sandbox of its own +sandbox: + enabled: true + enforce: required +trainer: + run_name: rats-libero # the training run whose adapters this evaluates (--adapter final, ckpt tags) + epochs: 1 + call_timeout_min: 30 + budget: {usd: 3000, hours: 2000} +eval: + repeats: 1 diff --git a/examples/libero/rats/train.yaml b/examples/libero/rats/train.yaml new file mode 100644 index 00000000..d033bf7a --- /dev/null +++ b/examples/libero/rats/train.yaml @@ -0,0 +1,40 @@ +# RATs on LIBERO (arXiv:2606.19419), training: play. Fifty play iterations on LIBERO's scenes (splits/train.txt: +# play-001 ... play-050), one per step, each resumed from the last one's library and state; RATs proposes its own +# tasks. The test split is the paper's Table 1 (splits/test.txt; test.yaml runs it in parallel). No validation data +# reaches the Evolver: RATs has none (val.yaml evaluates snapshots on the validation split after training). +# Started by launch.sh: RATS_ROOT=/path/to/RATs RATS_GPUS=1,3 ./launch.sh train +data: + tasks: tasks # written by launch.sh (rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it was written + train: splits/train.txt # play-001 ... play-050: no benchmark task + test: splits/test.txt # LIBERO-PRO Object/Goal/Spatial x swap/task, 10 tasks each, init states 0-9 + step_size: 1 # one play iteration per step, from the last one's state + shuffle: false +task_info: task-info +agent: + name: hermit.agent.evolver.methods.rats.actor:RatsActor + concurrency: 1 # play runs one iteration at a time + params: + rats_root: $RATS_ROOT # RATs' checkout with its venv (README.md), at the commit launch.sh pins + model: fireworks/accounts/fireworks/models/glm-5p3-flash # every RATs role; it must take images + effort: medium # each request's reasoning_effort (RATs' own default) + gpus: $RATS_GPUS # the GPUs RATs renders LIBERO on (the N of /dev/nvidia) + per_gpu: 2 +judge: + path: judge.py # on the host: the trials' native success, from RATs' process +template: rats +evolver: + name: rats +environment: + runner: host # the actor renders on a GPU and confines RATs in a sandbox of its own +sandbox: + enabled: true + enforce: required +trainer: + run_name: rats-libero + epochs: 1 + call_timeout_min: 30 # the Evolver only checks and applies the handed-back state + save_freq: {steps: 10} # rats-libero/ckpt-step-10 ... -50: RATs' snapshots, for val.yaml + budget: {usd: 500, hours: 400} +eval: + repeats: 1 diff --git a/examples/libero/rats/val.yaml b/examples/libero/rats/val.yaml new file mode 100644 index 00000000..fe80481c --- /dev/null +++ b/examples/libero/rats/val.yaml @@ -0,0 +1,40 @@ +# RATs on LIBERO, validation: RATs Exec with a training run's library frozen on the validation split +# (splits/val.txt): LIBERO's original Spatial, Object, Goal and Long suites, 10 tasks each, init states 43-49 (seven +# trials a task, 280 in all). No validation row is a test suite's task: the test split is LIBERO-PRO's perturbations +# (test.yaml). RATs itself has no validation step; use these to compare snapshots or settings. Started by launch.sh: +# ./launch.sh val --adapter final +# ./launch.sh val --adapter rats-libero/ckpt-step-20 # a snapshot (train.yaml's save_freq) +data: + tasks: tasks # written by launch.sh (rows.py) + view: ../../cap_harness/utils/agent/fields.py:task_row # each task as the row it was written + train: splits/train.txt # unused by eval (a config names its training split) + test: splits/val.txt # original LIBERO x 10 tasks, init states 43-49 + step_size: 1 + shuffle: false +task_info: task-info +agent: + name: hermit.agent.evolver.methods.rats.actor:RatsActor + concurrency: 4 # RATs jobs at once: GPUs x per_gpu + params: + rats_root: $RATS_ROOT # RATs' checkout with its venv (README.md), at the commit launch.sh pins + model: fireworks/accounts/fireworks/models/glm-5p3-flash # every RATs role; it must take images + effort: medium # each request's reasoning_effort (RATs' own default) + gpus: $RATS_GPUS # the GPUs RATs renders LIBERO on (the N of /dev/nvidia) + per_gpu: 2 +judge: + path: judge.py # on the host: the trials' native success, from RATs' process +template: rats +evolver: + name: rats +environment: + runner: host # the actor renders on a GPU and confines RATs in a sandbox of its own +sandbox: + enabled: true + enforce: required +trainer: + run_name: rats-libero # the training run whose adapters this evaluates (--adapter final, ckpt tags) + epochs: 1 + call_timeout_min: 30 + budget: {usd: 300, hours: 400} +eval: + repeats: 1 diff --git a/hermit/adapter/templates/rats/.hermit/EVOLVER.md b/hermit/adapter/templates/rats/.hermit/EVOLVER.md new file mode 100644 index 00000000..6ce22978 --- /dev/null +++ b/hermit/adapter/templates/rats/.hermit/EVOLVER.md @@ -0,0 +1,20 @@ +# RATs adapter: structure + +The adapter is RATs' skill library and the play-time state its next play iteration resumes from (arXiv:2606.19419, +Algorithm 1: the library L and the failure memory M that PROPOSE_TASK, RUN_TASK and UPDATE_MEMORY carry from one +iteration to the next). + +| path | what it is | +|---|---| +| `skills.json` | the library L, RATs' SkillLibrary JSON: L0's primitives (documentation entries), then the learned skills, each with `code`, `description`, `api_primitives_used`, `preconditions`, `effects`, `dependent_skills`, `usage_count`, `success_count`, `tier` | +| `state/iteration_.json` | play iteration n's digest: its task proposal, outcome, attempts, skills learned and, after a success, its last program (what RATs' `resume_from` replays into the proposer) | +| `state/failure_memory/` | the failure memory M: `episodes.json`, `lessons.json` | +| `state/retry_bank/items.json` | failed tasks worth retrying | +| `state/candidate_state/object_skill_counts.json` | the (object, skill) attempt counts the novelty score reads | +| `state/memory/` | the memory curator's and the skill curator's histories | +| `state/loop.json` | the counters a continuous RATs run keeps in memory (curation and skill-proposal cadence, the curator's rolling history, the failure memory's distillation counter) | + +- A learned skill defines `def ` at its top level and reaches only its arguments, the API functions and the other + skills (`.hermit/check.py`); a primitive's `code` is comments only. +- `state/` is internal: an evaluation reads `skills.json` alone. +- Fixed: `.hermit/`, `ADAPTER.md`, `README.md`, `exports.yaml`. diff --git a/hermit/adapter/templates/rats/.hermit/UPSTREAM.md b/hermit/adapter/templates/rats/.hermit/UPSTREAM.md new file mode 100644 index 00000000..7be9a27f --- /dev/null +++ b/hermit/adapter/templates/rats/.hermit/UPSTREAM.md @@ -0,0 +1,8 @@ +`skills.json` is copied without modification from Playful-RATs/RATs: +https://github.com/Playful-RATs/RATs/blob/1fd2ef56857cfde6d5d815fc49a9fe9b0a531beb/skill_library/libero_skills.json + +It is the primitive library L0 that RATs' LIBERO play starts from (`scripts/run_rats.py` picks it for a LIBERO config +whose API is not a reduced one, as `env_configs/libero/rats_libero_play.yaml`'s `FrankaLiberoApi`): twelve +documentation entries of the robot API, no learned skill. + +Upstream is licensed under Apache-2.0; see UPSTREAM_LICENSE. diff --git a/hermit/adapter/templates/rats/.hermit/UPSTREAM_LICENSE b/hermit/adapter/templates/rats/.hermit/UPSTREAM_LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/hermit/adapter/templates/rats/.hermit/UPSTREAM_LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/hermit/adapter/templates/rats/.hermit/adapter.yaml b/hermit/adapter/templates/rats/.hermit/adapter.yaml new file mode 100644 index 00000000..eb0d371a --- /dev/null +++ b/hermit/adapter/templates/rats/.hermit/adapter.yaml @@ -0,0 +1,36 @@ +# The RATs adapter (Zhang et al., "Playful Agentic Robot Learning", arXiv:2606.19419; Playful-RATs/RATs): what play +# hands to the next task. The skill library L (skills.json, RATs' own SkillLibrary file: the primitive library L0 that +# play starts from, then every skill the memory team admitted, with its reliability counters and tier) is what an +# evaluation reads, frozen. What lies under state/ is the rest of RATs' play-time state, in the layout of RATs' own +# output directory: one digest per play iteration (the task proposer's history), the failure memory M, the retry bank, +# the proposer's object-skill counts, the curators' histories and the loop's counters. Only the next play iteration +# reads it (exports.yaml: internal). +template: + id: rats + version: "1.0" + contract: "2" + name: RATs skill library and play state +structure: + learnable: + - path: skills.json # the skill library L (RATs skill_library/library.py) + format: {text: true, max_bytes: 4000000} + - path: state/iteration_*.json # one digest per play iteration, as RATs' resume reads it + format: {text: true, max_bytes: 1000000, max_files: 2000} + - path: state/failure_memory/*.json # the failure memory M: episodes.json, lessons.json + format: {text: true, max_bytes: 16000000, max_files: 2} + - path: state/retry_bank/items.json # the retry bank (rats/loop/retry_bank.py) + format: {text: true, max_bytes: 1000000} + - path: state/candidate_state/object_skill_counts.json # the novelty counts (rats/agents/curiosity_scoring.py) + format: {text: true, max_bytes: 1000000} + - path: state/memory/*.json # the memory and skill curators' histories + format: {text: true, max_bytes: 4000000, max_files: 2} + - path: state/loop.json # the counters a continuous RATs run keeps in memory + format: {text: true, max_bytes: 1000000} + fixed: + - ADAPTER.md + - README.md + - exports.yaml +check: .hermit/check.py:check +# RATs' own loop reads the library (its planner ranks and renders it); a workspace or a plugin has nothing to read it, +# so `hermit deploy` and `hermit convert` refuse these adapters. +plugin-portable: false diff --git a/hermit/adapter/templates/rats/.hermit/check.py b/hermit/adapter/templates/rats/.hermit/check.py new file mode 100644 index 00000000..eb25e3ff --- /dev/null +++ b/hermit/adapter/templates/rats/.hermit/check.py @@ -0,0 +1,185 @@ +"""Template check for `rats` adapters: RATs' skill library and its play-time state, as RATs' own loop reads them. + +The surface: + skills.json a JSON list of skill records (RATs skill_library/library.py): each with a `name` + that is a Python identifier and unique, `code`, `is_primitive`, a `tier` of + experimental, verified or deprecated, and `usage_count` >= `success_count` >= 0. + A primitive documents the robot API: its code is comments only. A learned + skill's code parses and defines `def ` at its top level (the name RATs' + add_skill gives it), and reaches nothing but its arguments, the API functions and + the other skills: no simulator internals (`env.` and `low_level_env.`, RATs' own + forbidden patterns: rats/agents/policy_quality_checker.py), no private or dunder + attribute or name, no exec, eval, compile, open, __import__, globals, locals or + vars, getattr, setattr and delattr only on a plain constant name, and no import + of the interpreter, the file system, processes, the network or the simulator's + packages. This is a screen of what the library hands the next task, not the + boundary: RATs runs its programs in a sandbox (the actor's). + state/iteration_.json a play iteration's digest: a JSON object whose `iteration` is n + state/failure_memory/episodes.json, state/failure_memory/lessons.json JSON lists + state/retry_bank/items.json, state/candidate_state/object_skill_counts.json, + state/memory/curator_history.json, state/memory/skill_curator_history.json, state/loop.json JSON +Nothing else lies outside .hermit/, ADAPTER.md, README.md and exports.yaml. +""" +from __future__ import annotations + +import ast +import json +from pathlib import Path +import re + +OWN = frozenset({"ADAPTER.md", "README.md", "exports.yaml"}) +STATE_JSON = frozenset({"state/failure_memory/episodes.json", "state/failure_memory/lessons.json", + "state/retry_bank/items.json", "state/candidate_state/object_skill_counts.json", + "state/memory/curator_history.json", "state/memory/skill_curator_history.json", + "state/loop.json"}) +LISTS = frozenset({"state/failure_memory/episodes.json", "state/failure_memory/lessons.json"}) +ITERATION = re.compile(r"state/iteration_(\d+)\.json") +TIERS = frozenset({"experimental", "verified", "deprecated"}) +NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") +# The simulator behind the API: RATs refuses `env.` and `low_level_env.` in a program +PRIVILEGED_NAMES = frozenset({"env", "low_level_env"}) +PRIVILEGED_ATTRS = frozenset({"env", "low_level_env", "sim", "physics"}) +CALLS = frozenset({"exec", "eval", "compile", "open", "__import__", "globals", "locals", "vars", "breakpoint", + "input"}) +REFLECTION = frozenset({"getattr", "setattr", "delattr"}) +# Modules a skill never imports: the interpreter and its introspection, files, processes, the network, and the +# simulator and RATs itself (the scene behind the API) +MODULES = frozenset({ + "os", "sys", "subprocess", "socket", "shutil", "pathlib", "io", "builtins", "importlib", "ctypes", "pickle", + "marshal", "shelve", "dill", "requests", "urllib", "urllib3", "http", "httpx", "aiohttp", "inspect", "gc", + "threading", "multiprocessing", "concurrent", "asyncio", "signal", "glob", "fnmatch", "tempfile", "code", "codeop", + "runpy", "types", "weakref", "traceback", "select", "fcntl", "resource", "pty", "mmap", "zipimport", "pkgutil", + "site", "sysconfig", "platform", "getpass", "pwd", "zipfile", "tarfile", "sqlite3", "h5py", + "mujoco", "robosuite", "libero", "bddl", "rats", "skill_library", "scripts", "capx", "torch"}) + + +def code_problem(name: str, code: str) -> str | None: + """Why a learned skill's code is refused, or None.""" + try: + tree = ast.parse(code) + except SyntaxError as exc: + return f"its code does not parse: {exc.msg} (line {exc.lineno})" + if not any(isinstance(n, ast.FunctionDef) and n.name == name for n in tree.body): + return f"its code defines no top-level `def {name}`" + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + mods = [a.name for a in node.names] if isinstance(node, ast.Import) else [node.module or ""] + if isinstance(node, ast.ImportFrom) and node.level: + return "a relative import" + bad = [m for m in mods if m.split(".")[0] in MODULES] + if bad: + return f"it imports {bad[0]}" + elif isinstance(node, ast.Attribute): + if node.attr.startswith("_"): + return f"private or dunder attribute access (.{node.attr})" + if node.attr in PRIVILEGED_ATTRS or (isinstance(node.value, ast.Name) + and node.value.id in PRIVILEGED_NAMES): + return f"privileged simulator access (.{node.attr})" + elif isinstance(node, ast.Name) and node.id.startswith("__"): + return f"a dunder name ({node.id})" + elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + if node.func.id in CALLS: + return f"it calls {node.func.id}" + if node.func.id in REFLECTION: + attr = node.args[1] if len(node.args) > 1 else None + if not (isinstance(attr, ast.Constant) and isinstance(attr.value, str) + and not attr.value.startswith("_") and attr.value not in PRIVILEGED_ATTRS): + return f"{node.func.id} on a name that is not a plain constant" + return None + + +def comments_only(code: str) -> bool: + try: + return not ast.parse(code or "").body + except SyntaxError: + return False + + +def skills_problems(text: str) -> list[str]: + try: + skills = json.loads(text) + except ValueError as exc: + return [f"not JSON: {exc}"] + if not isinstance(skills, list): + return ["the library is a JSON list of skill records"] + out, seen = [], set() + for i, s in enumerate(skills): + if not isinstance(s, dict): + out.append(f"entry {i} is not an object") + continue + name = s.get("name") + where = f"skill {name!r}" if isinstance(name, str) else f"entry {i}" + if not isinstance(name, str) or not NAME.fullmatch(name): + out.append(f"{where}: `name` must be a Python identifier") + continue + if name in seen: + out.append(f"{where}: two entries have this name") + seen.add(name) + if not isinstance(s.get("code"), str): + out.append(f"{where}: `code` must be a string") + continue + if not isinstance(s.get("is_primitive", False), bool): + out.append(f"{where}: `is_primitive` must be true or false") + continue + if s.get("tier", "experimental") not in TIERS: + out.append(f"{where}: `tier` must be one of {', '.join(sorted(TIERS))}") + counts = [s.get(k, 0) for k in ("usage_count", "success_count")] + if not all(isinstance(c, int) and not isinstance(c, bool) and c >= 0 for c in counts): + out.append(f"{where}: `usage_count` and `success_count` must be counts") + elif counts[1] > counts[0]: + out.append(f"{where}: more successes ({counts[1]}) than uses ({counts[0]})") + if s.get("is_primitive", False): + if not comments_only(s["code"]): + out.append(f"{where}: a primitive documents the API: its code must be comments only") + continue + why = code_problem(name, s["code"]) + if why: + out.append(f"{where}: {why}") + return out + + +def state_problem(rel: str, text: str) -> str | None: + try: + value = json.loads(text) + except ValueError as exc: + return f"not JSON: {exc}" + m = ITERATION.fullmatch(rel) + if m: + if not isinstance(value, dict) or value.get("iteration") != int(m.group(1)): + return f"an iteration digest is a JSON object whose `iteration` is {int(m.group(1))}" + if not isinstance(value.get("task_proposal") or {}, dict): + return "`task_proposal` must be an object" + elif rel in LISTS and not isinstance(value, list): + return "a JSON list" + elif rel == "state/loop.json" and not isinstance(value, dict): + return "a JSON object" + return None + + +def check(adapter_path: str) -> list[dict]: + adapter = Path(adapter_path).resolve() + if not (adapter / "skills.json").is_file(): + # Never pass an adapter this check cannot see (under bubblewrap, /tmp is an empty tmpfs). + return [{"path": "skills.json", "problem": f"no rats adapter at {adapter} (skills.json missing or not " + "visible)"}] + issues = [] + for p in sorted(adapter.rglob("*")): + rel = p.relative_to(adapter).as_posix() + if "__pycache__" in p.parts or rel.startswith((".hermit/", ".git/")) or rel in OWN: + continue + if p.is_symlink() or not (p.is_dir() or p.is_file()): # a link (to a file or a folder), a pipe, a device + issues.append({"path": rel, "problem": "not a regular file or folder"}) + continue + if p.is_dir(): + continue + text = p.read_text(encoding="utf-8", errors="replace") + if rel == "skills.json": + issues += [{"path": rel, "problem": problem} for problem in skills_problems(text)] + elif rel in STATE_JSON or ITERATION.fullmatch(rel): + why = state_problem(rel, text) + if why: + issues.append({"path": rel, "problem": why}) + else: + issues.append({"path": rel, "problem": f"{rel} is off the adapter's surface (skills.json and RATs' play " + "state under state/)"}) + return issues diff --git a/hermit/adapter/templates/rats/ADAPTER.md b/hermit/adapter/templates/rats/ADAPTER.md new file mode 100644 index 00000000..3b969ce8 --- /dev/null +++ b/hermit/adapter/templates/rats/ADAPTER.md @@ -0,0 +1,5 @@ +This adapter is a RATs skill library (`skills.json`): Code-as-Policy helper functions that RATs learned in play, +each with its docstring, the primitives it calls, its preconditions and effects, and how reliably it has worked +(`usage_count`, `success_count`, `tier`). RATs' planner reads it before it plans a task; entries marked +`"is_primitive": true` document the robot API itself. Prefer `verified` skills, treat `experimental` ones as +evidence from other tasks, and never call a `deprecated` one. diff --git a/hermit/adapter/templates/rats/README.md b/hermit/adapter/templates/rats/README.md new file mode 100644 index 00000000..57ed7b40 --- /dev/null +++ b/hermit/adapter/templates/rats/README.md @@ -0,0 +1,14 @@ +# RATs skill library + +The adapter of RATs (Zhang et al., "Playful Agentic Robot Learning", arXiv:2606.19419; +https://github.com/Playful-RATs/RATs): the skill library L that play builds and evaluation reads, and the rest of the +play-time state the next play iteration resumes from. + +- `skills.json`: the library, in RATs' own SkillLibrary format (`skill_library/library.py`). It starts as RATs' LIBERO + primitive library L0 (`skill_library/libero_skills.json` at 1fd2ef5, the twelve primitives of `FrankaLiberoApi`; + see `.hermit/UPSTREAM.md`): play starts from no learned skill. +- `state/`: the failure memory M, the retry bank, the proposer's object-skill counts, one digest per play iteration + (the proposer's task history), the curators' histories and the loop's counters, laid out as RATs' own output + directory holds them. Internal: an evaluation never reads it. + +The `rats` Evolver writes it; the RATs actor runs RATs' own loop on it. See docs/methods/rats.md. diff --git a/hermit/adapter/templates/rats/exports.yaml b/hermit/adapter/templates/rats/exports.yaml new file mode 100644 index 00000000..c18815bb --- /dev/null +++ b/hermit/adapter/templates/rats/exports.yaml @@ -0,0 +1,4 @@ +# The RATs actor (hermit/agent/evolver/methods/rats/actor.py) hands skills.json to RATs' own loop, whose planner +# ranks and renders the library; another agent receives ADAPTER.md only. The play-time state is never deployed. +context: ADAPTER.md +internal: [state/] diff --git a/hermit/adapter/templates/rats/skills.json b/hermit/adapter/templates/rats/skills.json new file mode 100644 index 00000000..930b24a8 --- /dev/null +++ b/hermit/adapter/templates/rats/skills.json @@ -0,0 +1,226 @@ +[ + { + "skill_id": "primitive_get_observation", + "name": "get_observation", + "description": "Get current observation: RGB/depth images from agentview and wrist cameras, robot joint positions, and end-effector cartesian pose.", + "code": "# Built-in Franka LIBERO primitive: get_observation() -> dict\n# Keys: ['agentview']['images']['rgb'|'depth'], ['robot0_eye_in_hand']['images']['rgb'|'depth'],\n# ['robot_joint_pos'] (8,), ['robot_cartesian_pos'] (8,: xyz + wxyz + gripper)", + "api_primitives_used": [ + "get_observation" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_get_object_pose", + "name": "get_object_pose", + "description": "Get the 3D pose of a named object in the robot base frame. Returns (position (3,) XYZ meters, quaternion_wxyz (4,)).", + "code": "# Built-in Franka LIBERO primitive: get_object_pose(object_name: str) -> tuple[ndarray, ndarray]", + "api_primitives_used": [ + "get_object_pose" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_goto_pose", + "name": "goto_pose", + "description": "Move end-effector to target pose using IK. Optional z_approach for pre-grasp approach motion (higher z, then descend).", + "code": "# Built-in Franka LIBERO primitive: goto_pose(position: ndarray(3,), quaternion_wxyz: ndarray(4,), z_approach: float = 0.0) -> None", + "api_primitives_used": [ + "goto_pose" + ], + "preconditions": [], + "effects": [ + "robot_moved" + ], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_open_gripper", + "name": "open_gripper", + "description": "Open the Franka gripper fully.", + "code": "# Built-in Franka LIBERO primitive: open_gripper() -> None", + "api_primitives_used": [ + "open_gripper" + ], + "preconditions": [], + "effects": [ + "gripper_open" + ], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_close_gripper", + "name": "close_gripper", + "description": "Close the Franka gripper fully.", + "code": "# Built-in Franka LIBERO primitive: close_gripper() -> None", + "api_primitives_used": [ + "close_gripper" + ], + "preconditions": [], + "effects": [ + "gripper_closed" + ], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_goto_home_joint_position", + "name": "goto_home_joint_position", + "description": "Move the Franka arm to its home (rest) joint configuration. Useful before perception to get a clear agentview.", + "code": "# Built-in Franka LIBERO primitive: goto_home_joint_position() -> None", + "api_primitives_used": [ + "goto_home_joint_position" + ], + "preconditions": [], + "effects": [ + "robot_at_home" + ], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_sample_grasp_pose", + "name": "sample_grasp_pose", + "description": "Plan grasp poses for a named object using ContactGraspNet. Returns (positions, quaternions_wxyz, scores) arrays.", + "code": "# Built-in Franka LIBERO primitive: sample_grasp_pose(object_name: str, top_k: int = 5, use_multiview: bool = True) -> tuple[ndarray, ndarray, ndarray]", + "api_primitives_used": [ + "sample_grasp_pose" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_get_object_3d_points_and_masks_from_language", + "name": "get_object_3d_points_and_masks_from_language", + "description": "Get 3D point cloud and 2D masks for an object specified by name. Uses SAM3 + depth deprojection. Returns dict with 'points_3d', 'agentview_mask', 'wrist_mask'.", + "code": "# Built-in Franka LIBERO primitive: get_object_3d_points_and_masks_from_language(object_name: str, use_multiview: bool = True) -> dict", + "api_primitives_used": [ + "get_object_3d_points_and_masks_from_language" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_get_oriented_bounding_box_from_3d_points", + "name": "get_oriented_bounding_box_from_3d_points", + "description": "Compute oriented bounding box (OBB) from 3D points. Returns dict with 'center', 'extent', 'R' (rotation matrix).", + "code": "# Built-in Franka LIBERO primitive: get_oriented_bounding_box_from_3d_points(points: ndarray) -> dict", + "api_primitives_used": [ + "get_oriented_bounding_box_from_3d_points" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_segment_sam3_text_prompt", + "name": "segment_sam3_text_prompt", + "description": "Run SAM3 segmentation on an RGB image conditioned on a text prompt. Returns list of masks with bounding boxes and confidence scores.", + "code": "# Built-in Franka LIBERO primitive: segment_sam3_text_prompt(rgb: ndarray, text_prompt: str) -> list[dict]", + "api_primitives_used": [ + "segment_sam3_text_prompt" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_segment_sam3_point_prompt", + "name": "segment_sam3_point_prompt", + "description": "Run SAM3 segmentation with point prompt conditioning. Returns list of segmentation masks with scores.", + "code": "# Built-in Franka LIBERO primitive: segment_sam3_point_prompt(rgb: ndarray, point_coords: tuple) -> list[dict]", + "api_primitives_used": [ + "segment_sam3_point_prompt" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + }, + { + "skill_id": "primitive_point_prompt_molmo", + "name": "point_prompt_molmo", + "description": "Use Molmo VLM to locate objects in an image given a text description. Returns dict mapping object name to (x, y) pixel coordinates.", + "code": "# Built-in Franka LIBERO primitive: point_prompt_molmo(image: ndarray, text_prompt: str) -> dict[str, tuple]", + "api_primitives_used": [ + "point_prompt_molmo" + ], + "preconditions": [], + "effects": [], + "dependent_skills": [], + "success_rate": 1.0, + "source_task": "franka_libero_builtin", + "is_primitive": true, + "usage_count": 0, + "success_count": 0, + "tier": "verified" + } +] \ No newline at end of file diff --git a/hermit/agent/evolver/methods/rats/actor.py b/hermit/agent/evolver/methods/rats/actor.py new file mode 100644 index 00000000..48cb4770 --- /dev/null +++ b/hermit/agent/evolver/methods/rats/actor.py @@ -0,0 +1,536 @@ +"""The RATs actor: RATs' own loop (Playful-RATs/RATs, scripts/run_rats.py) on one task row, in RATs' venv, in a +bubblewrap sandbox of its own (runner.py inside). Its configs run it on the host (environment.runner: host): it +renders LIBERO on a GPU and reaches RATs' vision services, and confines RATs itself. + +A row is one of two modes (examples/libero/rats/rows.py writes them): + +- `play`: one play iteration (arXiv:2606.19419, Algorithm 1: PROPOSE_TASK, RUN_TASK and UPDATE_MEMORY; + `run_rats.py --explore` on LIBERO), resumed from the adapter: the skill library and the play-time state under + state/, laid out as RATs' output directory. RATs' memory team updates its copy as RATs does in each iteration + (skills extracted from a success, the reliability counters, failure records and lessons, and every + RATS_CURATE_EVERY iterations the curators and the skill proposer); the copy comes back in the log, under adapter/, + and the Evolver makes it the adapter. +- `exec`: RATs Exec on one LIBERO task with the library frozen (the LIBERO-PRO batch driver's job: + --fixed-task --no-skill-reuse --no-failure-memory), its `trials` trials in one process, trial j in the task's init + state `first_state` + j. The output is the number of trials whose native success check passed + (RATS_VERIFIER_STRICT_BENCHMARK=1). + +The sandbox shows RATs' checkout and venv read-only, less what no row may read (its git history, its runs, the skill +libraries the authors learned, and in play every LIBERO-PRO suite besides the original LIBERO ones), writes only the +row's RATs output directory, reaches no network but the model endpoint and RATs' vision services on their loopback +ports, and sees one GPU. Every model call of RATs goes to an endpoint of this process (hermit.agent.base.endpoint, over +one Direct call each, Layer 1) that sends it to the run's model with the provider's key, which the sandbox never holds, +and counts its tokens and cost. + +Log: result.json (what each iteration returned), RATs' records of the iteration(s) it ran (iteration_.json, +final_summary.json, report.md), runner.log, the handed-back adapter/ (play) and sandbox/ (the sandbox's records); +RATs' whole output directory (videos, generated BDDL, attempt artifacts) stays under `agent.params.scratch`. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import threading +import time + +from hermit.agent.acting import Agent +from hermit.common import RunOutput + +HERE = Path(__file__).resolve().parent +RUNNER = HERE / "runner.py" +# The authors' configs (Playful-RATs/RATs env_configs/libero/): play on LIBERO with the full API and Contact-GraspNet, +# RATs Exec on LIBERO-PRO with the reduced API and GraspGen (the batch driver's default) +PLAY_CONFIG = "env_configs/libero/rats_libero_play.yaml" +EXEC_CONFIG = "env_configs/libero/rats_libero_pro_nonpriv.yaml" +# RATs' vision services on their fixed loopback ports: SAM3, Contact-GraspNet, PyRoki, GraspGen, Molmo +SERVICE_PORTS = (8114, 8115, 8116, 5556, 8122) +# What of RATs' checkout no row reads: its git history (and the submodules' under it), its runs and their logs, the +# libraries its authors learned (capx-baseline's preserved ones; skill_library's learned files are found by content), +# LIBERO's demonstrations when downloaded +HIDDEN = (".git", "outputs", "logs", "rats-cache", "capx-baseline/skill_libraries", "capx-baseline/outputs", + "rats/third_party/LIBERO-PRO/libero/datasets") +LIBERO_FILES = "rats/third_party/LIBERO-PRO/libero/libero" +# The original LIBERO suites: play's bootstrap scene and the validation rows; play sees no other suite's BDDL or +# init states (LIBERO-PRO's perturbations, the test rows) +ORIGINAL_SUITES = ("libero_spatial", "libero_object", "libero_goal", "libero_10", "libero_90") +# RATs' per-role model variables: every role calls the run's one model +ROLE_MODELS = ("RATS_LLM_MODEL", "RATS_CURATOR_MODEL", "RATS_DIAGNOSER_MODEL", "RATS_FEEDBACK_GENERATOR_MODEL", + "RATS_PER_STEP_VERIFIER_MODEL", "RATS_PLANNER_VERIFIER_MODEL", "RATS_POLICY_WRITER_MODEL", + "RATS_VERIFIER_MODEL") +SECRET = re.compile(r"KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH", re.I) +# run_rats.py flags no play row takes: the first puts the 60 LIBERO-PRO test tasks' descriptions into the task +# proposer's prompt (RATs' optional task-aware play, off by default; the test suites' task names are in LIBERO-PRO's +# Python task map, which play imports, so hiding their files does not hide them); the others name the scene or the +# output, which the row's mode sets +PLAY_REFUSED = ("--proposer-include-eval-task-context", "--libero-suite", "--libero-task", "--output-dir", "--resume", + "--skill-library") +HANDED_BACK_MAX = 64 << 20 # bytes of state a play iteration may hand back +RECORD_MAX = 32 << 20 # bytes of one RATs record copied into the log +PLAY_TIMEOUT_S = 6 * 3600 # one play iteration: six attempts at most (run_rats.py --max-retries 5) +TRIAL_TIMEOUT_S = 3600 # one exec trial + + +class _Meter: + """The run's model as one rollout's RATs process calls it: every request sent to the configured model (RATs names + its own per role; the run has one), its usage kept.""" + + def __init__(self, client): + self.client = client + self.usage: list = [] + self._lock = threading.Lock() + + @property + def model(self) -> str: + return self.client.model + + def chat(self, messages: list, **kwargs): + kwargs.pop("model", None) + message, usage = self.client.chat(messages, **kwargs) + with self._lock: + self.usage.append(usage) + return message, usage + + def spent(self) -> dict: + with self._lock: + usage = list(self.usage) + tokens = sum(u.input_tokens + u.output_tokens for u in usage) + costs = [u.cost_usd for u in usage] + cost = None if any(c is None for c in costs) else sum(costs) + return {"calls": len(usage), "input_tokens": sum(u.input_tokens for u in usage), + "cached_input_tokens": sum(u.cached_input_tokens for u in usage), + "output_tokens": sum(u.output_tokens for u in usage), "tokens": tokens, "cost_usd": cost} + + +class _Gpus: + """The GPUs the rollouts render on, at most `per_gpu` rollouts on each, the least loaded first.""" + + def __init__(self, gpus: list[int], per_gpu: int): + self.load = {int(g): 0 for g in gpus} + self.per_gpu = max(1, int(per_gpu)) + self._cv = threading.Condition() + + def take(self) -> int | None: + if not self.load: + return None + with self._cv: + while min(self.load.values()) >= self.per_gpu: + self._cv.wait() + gpu = min(self.load, key=lambda g: (self.load[g], g)) + self.load[gpu] += 1 + return gpu + + def give(self, gpu: int | None) -> None: + if gpu is None: + return + with self._cv: + self.load[gpu] -= 1 + self._cv.notify_all() + + +def learned_libraries(root: Path) -> list[Path]: + """The skill libraries in RATs' skill_library/ that hold learned skills (what its authors' play produced); the + primitive-only ones stay, as RATs' defaults.""" + out = [] + for f in sorted((root / "skill_library").glob("*.json")): + try: + skills = json.loads(f.read_text()) + except (OSError, ValueError): + out.append(f) + continue + if not isinstance(skills, list) or any(isinstance(s, dict) and not s.get("is_primitive") for s in skills): + out.append(f) + return out + + +def held_out_suites(root: Path) -> list[Path]: + """Every LIBERO-PRO suite's BDDL files and init states but the original LIBERO suites': what play never reads.""" + out = [] + for kind in ("bddl_files", "init_files"): + d = root / LIBERO_FILES / kind + if d.is_dir(): + out += [p for p in sorted(d.iterdir()) if p.name not in ORIGINAL_SUITES] + return out + + +def copy_regular(src: Path, dst: Path, limit: int) -> int: + """The regular files under `src` (a directory a sandboxed process wrote) copied to `dst`: never through a link, + never a pipe or a device, at most `limit` bytes in all. The bytes copied.""" + total = 0 + if not src.is_dir() or src.is_symlink(): + return 0 + for entry in sorted(os.scandir(src), key=lambda e: e.name): + if entry.is_symlink(): + continue + target = dst / entry.name + if entry.is_dir(follow_symlinks=False): + total += copy_regular(Path(entry.path), target, limit - total) + elif entry.is_file(follow_symlinks=False): + data = _read_bytes(Path(entry.path), limit - total) + if data is None: + raise ValueError(f"{entry.path}: past {limit} bytes, or not a regular file") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + total += len(data) + return total + + +def _read_bytes(path: Path, limit: int) -> bytes | None: + try: + fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError: + return None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None + data = os.read(fd, limit + 1) if limit >= 0 else b"" + chunks = [data] + while data and sum(map(len, chunks)) <= limit: + data = os.read(fd, 1 << 20) + chunks.append(data) + out = b"".join(chunks) + return None if len(out) > limit else out + finally: + os.close(fd) + + +def _json(path: Path, limit: int = RECORD_MAX): + data = _read_bytes(path, limit) + if data is None: + return None + try: + return json.loads(data.decode("utf-8", errors="replace")) + except ValueError: + return None + + +class RatsActor(Agent): + supports = () # the adapter is RATs' own library file, read by RATs' loop + + def __init__(self, params=None, base=None): + super().__init__(params, base) + self._gpus: _Gpus | None = None + self._gpus_lock = threading.Lock() + + def gpus(self) -> _Gpus: + with self._gpus_lock: + if self._gpus is None: + gpus = self.params.get("gpus") + if isinstance(gpus, str): + gpus = os.path.expandvars(gpus) + if "$" in gpus: + raise ValueError(f"agent.params.gpus: {gpus} is not set (launch.sh passes RATS_GPUS)") + gpus = [int(g) for g in gpus.replace(",", " ").split()] + elif isinstance(gpus, int): + gpus = [gpus] + if not gpus: + raise ValueError("agent.params.gpus: the GPUs RATs renders LIBERO on (the N of /dev/nvidia)") + self._gpus = _Gpus([int(g) for g in gpus], int(self.params.get("per_gpu", 2))) + return self._gpus + + # ---- the model ---- + + def _model(self) -> dict: + """The run's model as a spec: a `/` reference, or a mapping (a spec with `base_url`, or + `model`/`ref` with its request fields), with `effort` as each request's `reasoning_effort` (default medium, + the framework's first-evaluation row; false sends none; a request of RATs' own that sets it keeps its own).""" + from hermit.agent.model.backends import registry, resolve + model = self.params.get("model") + if not model: + raise ValueError("agent.params.model: the model RATs' roles call (a `/` reference)") + if isinstance(model, dict) and model.get("base_url"): + spec = dict(model) + else: + rest = dict(model) if isinstance(model, dict) else {} + ref = model if not isinstance(model, dict) else (rest.pop("ref", None) or rest.pop("model", None)) + base = resolve(ref, registry()).spec() + spec = {**base, **rest, "extra_body": {**(base.get("extra_body") or {}), **(rest.get("extra_body") or {})}} + extra = dict(spec.get("extra_body") or {}) + own = spec.pop("effort", None) # {ref, effort}, as Layer 1 writes a model + effort = self.params.get("effort") + if effort is None: + effort = own if own is not None else extra.get("reasoning_effort") or "medium" + if effort: + extra["reasoning_effort"] = effort + else: + extra.pop("reasoning_effort", None) + spec["extra_body"] = extra + if self.params.get("price") is not None: + spec["price"] = self.params["price"] + return spec + + def _rats_model(self, spec: dict) -> tuple[str, str]: + """What RATs is told its model is, and which of its request forms it sends: an OpenAI model as + `openai/` in RATs' OpenAI form, any other as its id in RATs' generic form.""" + dialect = self.params.get("dialect") or ("openai" if spec.get("backend") == "openai" else "chat") + if dialect not in ("openai", "chat"): + raise ValueError("agent.params.dialect: openai or chat") + name = self.params.get("rats_model") or (f"openai/{spec['model']}" if dialect == "openai" else spec["model"]) + return str(name), dialect + + # ---- one row ---- + + def run(self, task: dict, adapter: Path | None, environment=None) -> RunOutput: + p = self.params + mode = task.get("mode") + if mode not in ("play", "exec"): + raise ValueError(f"{task.get('id')}: a RATs row is `mode: play` or `mode: exec`, not {mode!r}") + root = self.path(os.path.expandvars(str(p.get("rats_root") or os.environ.get("RATS_ROOT") or ""))) + python = self.path(os.path.expandvars(str(p.get("python") or (root / ".venv" / "bin" / "python")))) + if not (root / "scripts" / "run_rats.py").is_file() or not python.exists(): + raise FileNotFoundError(f"agent.params.rats_root: a RATs checkout with its venv ({root}; " + f"see examples/libero/rats/README.md)") + started = time.time() + stamp = time.strftime("%Y%m%d-%H%M%S") + f"-{os.getpid()}-{threading.get_ident() % 100000}" + name = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(task["id"])) + log = self.log_dir() / f"{name}-{stamp}" + scratch = self.path(p.get("scratch") or (self.log_dir() / "scratch")) / f"{name}-{stamp}" + for d in (log, scratch): + if d.resolve().is_relative_to(root.resolve()): + raise ValueError(f"{d} lies inside RATs' checkout {root}, which the sandbox shows: keep the logs " + "elsewhere") + out, home = scratch / "rats", scratch / "home" + for d in (log, out, home / "tmp"): + d.mkdir(parents=True, exist_ok=True) + args, shown = self._prepare(task, mode, adapter, root, out, scratch) + spec = self._model() + rats_model, dialect = self._rats_model(spec) + from hermit.agent.base.endpoint import ChatEndpoint + from hermit.agent.model.direct import Direct + from hermit.agent.model.llm import ChatClient + meter = _Meter(ChatClient.from_spec(spec, max_retries=int(p.get("max_retries", 4)), + retry_wait=float(p.get("retry_wait", 4.0)), retry_wait_max=60.0, + timeout=float(p.get("call_timeout_s", 900)))) + gpus = self.gpus() + gpu = gpus.take() + endpoint = held = None + try: + endpoint = ChatEndpoint(Direct({}, meter)).start() + env, cache = self._environment(mode, root, python, home, endpoint.url, rats_model, dialect) + command = [str(python), str(RUNNER), mode, "--rats-root", str(root), "--out", str(out), *args] + held, command, env = self._confine(command, mode=mode, root=root, python=python, env=env, + writable=[out, home], readable=[*shown, *cache], home=home, gpu=gpu, + port=endpoint.port, log=log) + timeout = float(task.get("timeout_s") or p.get("timeout_s") or + (PLAY_TIMEOUT_S if mode == "play" else + int(task.get("trials", 1)) * float(p.get("trial_timeout_s", TRIAL_TIMEOUT_S)))) + code, timed_out = self._call(command, env, root, log / "runner.log", timeout) + finally: + if endpoint is not None: + endpoint.close() + gpus.give(gpu) + if held is not None: + held.close() + shutil.rmtree(home, ignore_errors=True) + spent = meter.spent() + result = self._collect(task, mode, out, log) + result.update(exit_code=code, timed_out=timed_out, gpu=gpu, model=spec.get("ref") or spec.get("model"), + usage=spent, scratch=str(out)) + output = result["output"] + output["timed_out"] = timed_out + # A row that ended early says so: its finished trials count, the rest failed (the judge says how many) + failure = (f"the row timed out after {timeout:.0f} s" if timed_out else + None if (out / "hermit" / "result.json").is_file() else f"the runner left no result (exit {code})") + if failure and not output.get("error"): + output["error"] = result["error"] = failure + extra = {"rats": result} + if output.get("error") and (output.get("iteration") is None if mode == "play" else not output.get("ran")): + # Nothing of RATs' ran to an outcome: not the method's result but a failed run (an error in the records, + # its cost and log kept) + extra["session_failed"] = f"{output['error']} (see {log / 'runner.log'})" + (log / "result.json").write_text(json.dumps(result, indent=1, default=str)) + return RunOutput(output=output, log=log, cost_usd=spent["cost_usd"], tokens=spent["tokens"] or None, + wall_s=time.time() - started, extra=extra) + + def _prepare(self, task: dict, mode: str, adapter: Path | None, root: Path, out: Path, + scratch: Path) -> tuple[list[str], list[Path]]: + """(The runner's arguments, what the sandbox shows read-only besides RATs' checkout): play lays the adapter's + library and state out in `out` as RATs' output directory (RATs resumes in place), exec copies the library + beside it, shown read-only (frozen).""" + p = self.params + rats_args = [str(a) for a in (p.get("rats_args") or [])] + refused = [a for a in rats_args if a.split("=", 1)[0] in PLAY_REFUSED] + if mode == "play" and refused: + raise ValueError(f"agent.params.rats_args: {refused[0]} is not for a play row (the test tasks stay out of " + "play; the row sets its scene and its output)") + extra = [f"--rats-arg={a}" for a in rats_args] + if mode == "play": + if adapter is not None: + shutil.copy2(adapter / "skills.json", out / "skills.json") + if (adapter / "state").is_dir(): + shutil.copytree(adapter / "state", out, dirs_exist_ok=True) + else: # no adapter: RATs' own LIBERO primitive library L0 + shutil.copy2(root / "skill_library" / "libero_skills.json", out / "skills.json") + config, shown = self._rats_config(p.get("play_config"), PLAY_CONFIG, root) + return ["--config", config, *extra], shown + for key in ("suite", "task_id"): + if task.get(key) is None: + raise ValueError(f"{task.get('id')}: an exec row names its `suite` and `task_id`") + first, trials = int(task.get("first_state", 0)), int(task.get("trials", 1)) + if first < 0 or trials < 1 or first + trials > 50: + raise ValueError(f"{task.get('id')}: init states {first}..{first + trials - 1} are not among LIBERO's 50") + if adapter is not None: + library = scratch / "library" / "skills.json" + library.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(adapter / "skills.json", library) + else: + # No adapter: RATs' no-library condition, the default it picks for the reduced API (run_rats.py) + library = root / "skill_library" / "libero_nonpriv_skills.json" + config, shown = self._rats_config(p.get("exec_config"), EXEC_CONFIG, root) + return ["--config", config, "--skills", str(library), "--suite", str(task["suite"]), "--task", + str(int(task["task_id"])), "--first-state", str(first), "--trials", str(trials), *extra], \ + [*shown, *([library.parent] if adapter is not None else [])] + + def _rats_config(self, value, default: str, root: Path) -> tuple[str, list[Path]]: + """An env config of RATs' (its name as run_rats.py takes it; what the sandbox must show of it besides the + checkout): one of its checkout's (env_configs/..., relative to it), or a file of the run's own (relative to + the run config's folder).""" + name = str(value or default) + if not Path(name).is_absolute() and (root / name).is_file(): + return name, [] + own = self.path(name) + if not own.is_file(): + raise FileNotFoundError(f"RATs env config {name}: neither in {root} nor at {own}") + return str(own), [own] + + def _environment(self, mode: str, root: Path, python: Path, home: Path, url: str, rats_model: str, + dialect: str) -> tuple[dict, list[Path]]: + """RATs' runtime environment (its docs/setup.md and the batch driver's), and nothing of this process's: no + key, no token; and what the sandbox must show for it besides the checkout (a robot-description cache of the + run's own).""" + libero = root / LIBERO_FILES + (home / ".libero").mkdir(parents=True, exist_ok=True) + # LIBERO asks for its paths on stdin without this file (RATs' docs/setup.md) + (home / ".libero" / "config.yaml").write_text( + f"benchmark_root: {libero}\nbddl_files: {libero}/bddl_files\ninit_states: {libero}/init_files\n" + f"datasets: {libero.parent}/datasets\nassets: {libero}/assets\n") + env = {"PATH": f"{python.parent}:/usr/local/bin:/usr/bin:/bin", "HOME": str(home), "TMPDIR": str(home / "tmp"), + "LANG": os.environ.get("LANG", "C.UTF-8"), "PYTHONPATH": str(root), "PYTHONUNBUFFERED": "1", + "CAPX_ENV_STACK": "libero", "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl", + "TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD": "1", "HERMIT_RATS_URL": url, "HERMIT_RATS_DIALECT": dialect, + # RATs attaches videos to its vision calls (Gemini takes them); a model that takes none gets the + # images and text (agent.params.video: true keeps them) + "HERMIT_RATS_VIDEO": "1" if self.params.get("video") else "0"} + # The robot descriptions RATs' IK loads (robot_descriptions clones them on first use; the sandbox has no + # network): a cache fetched once on the host (README.md), read-only here + cache = self.path(os.path.expandvars(str(self.params.get("robot_descriptions") + or (root / ".cache" / "robot_descriptions")))) + env["ROBOT_DESCRIPTIONS_CACHE"] = str(cache) + if mode == "exec": + env["RATS_VERIFIER_STRICT_BENCHMARK"] = "1" # only the native task_completed counts (docs/evaluation.md) + for name in ROLE_MODELS: + env[name] = rats_model + for key, value in (self.params.get("env") or {}).items(): + if SECRET.search(str(key)): + raise ValueError(f"agent.params.env: {key} looks like a secret; RATs' process holds none (its model " + "calls go through the actor's endpoint)") + env[str(key)] = str(value) + return env, ([] if cache.is_relative_to(root) or not cache.exists() else [cache]) + + def _confine(self, command: list[str], *, mode: str, root: Path, python: Path, env: dict, writable: list[Path], + readable: list[Path], home: Path, gpu: int | None, port: int, log: Path): + """The runner in a bubblewrap sandbox of its own: (what to close after; its command; its environment).""" + from hermit.sandbox import Sandbox + venv = python.parent.parent + hide = [root / h for h in HIDDEN] + learned_libraries(root) + if mode == "play": + hide += held_out_suites(root) + ports = sorted({port, *(int(x) for x in (self.params.get("service_ports") or SERVICE_PORTS))}) + box = Sandbox(enabled=True, enforce="required", network="no-network", readable=[root, venv], + writable=list(writable), framework=False, gpu=[gpu] if gpu is not None else [], + forward=ports, record_dir=log / "sandbox", role="rats") + box.hide = [*box.hide, *(h for h in hide if os.path.lexists(h))] + # A venv's interpreter, by its own name; the shell runs it by that name (hermit.sandbox, #95) + args, env = box.wrap(["/bin/sh", "-c", 'exec "$0" "$@"', *command], env=env, chdir=root, env_ports=False, + readable=[RUNNER, *readable], writable=list(writable), home=home) + return box, args, env + + @staticmethod + def _call(command: list[str], env: dict, cwd: Path, log_path: Path, timeout: float) -> tuple[int | None, bool]: + with open(log_path, "ab") as stream: + proc = subprocess.Popen(command, env=env, cwd=str(cwd), stdout=stream, stderr=subprocess.STDOUT, + start_new_session=True) + try: + return proc.wait(timeout=timeout), False + except subprocess.TimeoutExpired: + _kill(proc) + return None, True + except BaseException: + _kill(proc) + raise + + def _collect(self, task: dict, mode: str, out: Path, log: Path) -> dict: + """What the row produced, read on the host from what the sandboxed process left: the runner's result, RATs' + records of the iterations it ran, and (play) the handed-back adapter.""" + result = _json(out / "hermit" / "result.json") or {} + iterations = [r for r in (result.get("iterations") or []) if isinstance(r, dict)] + ran = {int(r["iteration"]) for r in iterations if isinstance(r.get("iteration"), int)} + for f in sorted(out.glob("iteration_*.json")): + m = re.fullmatch(r"iteration_(\d+)\.json", f.name) + if m and int(m.group(1)) in ran and not f.is_symlink(): + data = _read_bytes(f, RECORD_MAX) + if data is not None: + (log / "rats").mkdir(exist_ok=True) + (log / "rats" / f.name).write_bytes(data) + for name in ("final_summary.json", "report.md"): + data = _read_bytes(out / name, RECORD_MAX) + if data is not None: + (log / "rats").mkdir(exist_ok=True) + (log / "rats" / name).write_bytes(data) + record = {"mode": mode, "iterations": iterations, "error": result.get("error"), + "argv": result.get("argv")} + if mode == "play": + last = iterations[-1] if iterations else {} + handed = 0 + if _plain_dir(out, "hermit/adapter"): + try: + handed = copy_regular(out / "hermit" / "adapter", log / "adapter", HANDED_BACK_MAX) + except ValueError as exc: + shutil.rmtree(log / "adapter", ignore_errors=True) + record["error"] = record["error"] or f"the handed-back state was refused: {exc}" + record.update(handed_back_bytes=handed, iteration=last.get("iteration"), + success=bool(last.get("success")), task=last.get("task")) + record["output"] = {"mode": "play", "iteration": last.get("iteration"), "success": bool(last.get("success")), + "task": (last.get("task") or {}).get("language"), + "skills_learned": last.get("skills_learned") or [], + "state": bool(handed), "error": record["error"]} + return record + first, n = int(task.get("first_state", 0)), int(task.get("trials", 1)) + by_iteration = {int(r["iteration"]): r for r in iterations if isinstance(r.get("iteration"), int)} + trials = [] + for j in range(n): + r = by_iteration.get(first + j + 1) # trial j: iteration first + j + 1, init state first + j + trials.append({"init_state": first + j, "iteration": first + j + 1, "ran": r is not None, + "success": bool(r and r.get("success")), "attempts": (r or {}).get("total_attempts"), + "error": (r or {}).get("error")}) + record["trials"] = trials + record["output"] = {"mode": "exec", "suite": task.get("suite"), "task_id": task.get("task_id"), + "successes": sum(t["success"] for t in trials), "trials": n, + "ran": sum(t["ran"] for t in trials), "error": record["error"]} + return record + + +def _plain_dir(base: Path, rel: str) -> bool: + """Whether base/rel is a directory reached through no link.""" + p = base + for part in Path(rel).parts: + p = p / part + try: + if not stat.S_ISDIR(os.lstat(p).st_mode): + return False + except OSError: + return False + return True + + +def _kill(proc: subprocess.Popen) -> None: + import signal + try: + os.killpg(proc.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + proc.wait() diff --git a/hermit/agent/evolver/methods/rats/evolver.py b/hermit/agent/evolver/methods/rats/evolver.py new file mode 100644 index 00000000..83f3531f --- /dev/null +++ b/hermit/agent/evolver/methods/rats/evolver.py @@ -0,0 +1,111 @@ +"""RatsEvolver: RATs' UPDATE_MEMORY as an Evolver on the `rats` template (Zhang et al., "Playful Agentic Robot +Learning", arXiv:2606.19419, Algorithm 1; github.com/Playful-RATs/RATs). + +In RATs one play iteration proposes a task, creates and verifies its environment, runs the execution team on it and +updates the memory (rats/loop/lifelong_loop.py `_run_one_iteration`): the feedback generator extracts at most two +skills from a success into the library L, every attempt's skill calls update the skills' reliability counters and +tiers, every failed attempt goes into the failure memory M, which distills lessons, and every RATS_CURATE_EVERY +iterations (5) the memory curator and the skill curator prune and merge M and L; the skill proposer writes helpers +from accumulated failures. These updates interleave with the iteration's own attempts (a lesson written after one +attempt is read by the next), so they run where RATs runs them: in the rollout's RATs process (the RATs actor, one +play iteration per training step), on its copy of the adapter. + +On the Trainer, one step is one play iteration. Its rollout hands back the updated library and play-time state (the +actor's log, adapter/); this Evolver checks it against the template (the library's records and code, the state's +files) and makes it the adapter: it replaces skills.json and state/ whole, as RATs' next iteration would find its +output directory. A rollout that handed back nothing (RATs crashed before it wrote its state) or a state that fails +the check leaves the adapter as it was, and the step says why. RATs has no validation step and selects no snapshot: +the final adapter is the library after the last play iteration. +""" +from __future__ import annotations + +import json +from pathlib import Path +import shutil + +from hermit.agent.evolver.base import Evolver, StepContext, StepResult +from hermit.agent.evolver.methods.rats.actor import HANDED_BACK_MAX, _plain_dir, _read_bytes, copy_regular +from hermit.sandbox import read_regular + +RECORD_MAX = 8 << 20 + + +class RatsEvolver(Evolver): + + def step(self, ctx: StepContext) -> StepResult: + current = ctx.workspace.learning_material / "current" + plays, failed = [], [] + for f in sorted((current / "tasks").glob("*.json")): + text = read_regular(f, RECORD_MAX) + try: + record = json.loads(text) if text is not None else None + except ValueError: + record = None + if not isinstance(record, dict): + continue + output = record.get("output") + if isinstance(output, dict) and output.get("mode") == "play": + plays.append(record) + elif (record.get("input") or {}).get("mode") == "play": + failed.append(record) # a play row whose run failed: nothing of RATs' came back + if len(plays) + len(failed) > 1: + return StepResult("failed", f"{len(plays) + len(failed)} play iterations in one step: RATs plays one " + "iteration at a time, each from the last one's state (data.step_size: 1, " + "agent.concurrency: 1)") + if failed: + why = str(failed[0].get("error") or "no record")[:300] + return StepResult("done", f"{failed[0].get('id')}: the play iteration did not run ({why}): the adapter " + "is unchanged", extra={"iteration": None, "applied": False}) + if not plays: + return StepResult("done", "no play iteration in this step: the adapter is unchanged") + record = plays[0] + output = record["output"] + what = (f"play iteration {output.get('iteration')} ({record.get('id')}): " + f"{'success' if output.get('success') else 'failure'}" + + (f", {output.get('task')!r}" if output.get("task") else "")) + traj = record.get("trajectory") + if not isinstance(traj, str) or not traj or Path(traj).is_absolute() or ".." in Path(traj).parts: + traj = None # the material's own relative path, nothing else + handed = (current / traj / "adapter") if traj else None + library = _read_bytes(handed / "skills.json", HANDED_BACK_MAX) \ + if handed is not None and _plain_dir(current, f"{traj}/adapter") else None + if library is None: + why = output.get("error") or record.get("error") or "no state came back" + return StepResult("done", f"{what}; it handed back no state ({str(why)[:300]}): the adapter is unchanged", + extra={"iteration": output.get("iteration"), "applied": False}) + adapter = ctx.workspace.adapter + candidate = ctx.workspace.scratch / "candidate" + if candidate.exists(): + shutil.rmtree(candidate) + shutil.copytree(adapter, candidate, ignore=lambda d, names: [n for n in names if Path(d) == adapter and + n in (".git", "state", "skills.json")]) + # What the iteration hands back is its library and its state, nothing else of the adapter + (candidate / "skills.json").write_bytes(library) + try: + if _plain_dir(handed, "state"): + copy_regular(handed / "state", candidate / "state", HANDED_BACK_MAX - len(library)) + except ValueError as exc: + return StepResult("done", f"{what}; its state was refused ({exc}): the adapter is unchanged", + extra={"iteration": output.get("iteration"), "applied": False}) + check = ctx.tools["check_spec"](path=str(candidate)) if "check_spec" in ctx.tools else {"passed": True} + if not check.get("passed"): + issues = "; ".join(f"{i.get('path')}: {i.get('problem')}" for i in (check.get("issues") or [])[:5]) + return StepResult("done", f"{what}; its state fails the template check ({issues}): the adapter is " + "unchanged", extra={"iteration": output.get("iteration"), "applied": False, + "check": check}) + if (adapter / "state").exists(): + shutil.rmtree(adapter / "state") + shutil.copy2(candidate / "skills.json", adapter / "skills.json") + if (candidate / "state").is_dir(): + shutil.copytree(candidate / "state", adapter / "state") + shutil.rmtree(candidate, ignore_errors=True) + skills = json.loads((adapter / "skills.json").read_text()) + learned = [s for s in skills if not s.get("is_primitive")] + tiers = {t: sum(1 for s in learned if s.get("tier", "experimental") == t) + for t in ("verified", "experimental", "deprecated")} + new = output.get("skills_learned") or [] + return StepResult("done", f"{what}; library: {len(learned)} learned skills " + f"({', '.join(f'{n} {t}' for t, n in tiers.items())})" + + (f", new: {', '.join(map(str, new))}" if new else ""), + extra={"iteration": output.get("iteration"), "applied": True, "learned": len(learned), + "tiers": tiers, "skills_learned": new}) diff --git a/hermit/agent/evolver/methods/rats/evolver.yaml b/hermit/agent/evolver/methods/rats/evolver.yaml new file mode 100644 index 00000000..6fdd0526 --- /dev/null +++ b/hermit/agent/evolver/methods/rats/evolver.yaml @@ -0,0 +1,12 @@ +description: >- + RATs (Playful Agentic Robot Learning, arXiv:2606.19419; Playful-RATs/RATs) on the `rats` template. One training step + is one play iteration of RATs' own loop, run by the RATs actor (hermit.agent.evolver.methods.rats.actor, class + RatsActor) on a copy of the adapter - the task proposer, the environment creator, the execution team and the memory + team's updates (skills extracted from a success, reliability tiers, the failure memory and its lessons, the curators + every five iterations, the skill proposer) as RATs interleaves them. This Evolver checks the library and play-time + state the iteration handed back and makes them the adapter; RATs has no validation step and no snapshot selection, + so the final adapter is the library after the last iteration. Evaluation runs RATs Exec with the library frozen + (exec rows). +class: evolver.py:RatsEvolver +needs: [] +params: {} diff --git a/hermit/agent/evolver/methods/rats/runner.py b/hermit/agent/evolver/methods/rats/runner.py new file mode 100644 index 00000000..d942b1ee --- /dev/null +++ b/hermit/agent/evolver/methods/rats/runner.py @@ -0,0 +1,269 @@ +"""RATs' own entry point, scripts/run_rats.py main() (Playful-RATs/RATs, the commit the examples' launcher pins), run in +RATs' venv inside the RATs actor's sandbox (actor.py), with three seams and nothing else of RATs changed. + + python runner.py play --rats-root R --out O --config C [--rats-arg=--flag ...] + one play iteration of `run_rats.py --env-type libero --explore`, resumed from O (the actor laid the adapter's + state out there as RATs' output directory: skills.json, failure_memory/, retry_bank/, candidate_state/, + memory/, iteration_.json); writes O/hermit/adapter/ (skills.json and state/) for the Evolver. + python runner.py exec --rats-root R --out O --skills K --suite S --task T --first-state F --trials N --config C + RATs Exec on one task with the library frozen, as RATs' LIBERO-PRO batch driver runs a job + (scripts/run_rats_libero_pro_batch.py: --fixed-task --no-skill-reuse --no-failure-memory, one process for + all of the task's trials); trial j runs in the task's init state F + j. + +The seams: +1. Every model call goes to HERMIT_RATS_URL, the actor's metered endpoint (the provider's key never enters the + sandbox): rats.agents.base_agent's `_get_api_config` names it, and Bedrock, Vertex and the Gemini proxy are off. + HERMIT_RATS_DIALECT=openai keeps RATs' OpenAI request form (reasoning_effort, max_completion_tokens), as RATs + builds it for an `openai/...` model; otherwise its generic one (temperature, max_tokens). HERMIT_RATS_VIDEO=0 (a + model that takes no video) drops the videos RATs attaches to its vision calls, with RATs' own + `_strip_videos_from_messages`. +2. In exec, LifelongLoop.run starts after iteration F (--first-state): RATs resets each iteration's env with seed = + the iteration's number, and its LIBERO env puts a task in init state (seed - 1) % 50 + (rats/envs/simulators/libero.py), so trial j (iteration F + j + 1) runs in init state F + j. +3. A play iteration is one process: what a continuous RATs run keeps in memory between iterations (the curation and + skill-proposal counters, the curator's rolling history, the failure memory's distillation counter) is restored + from state/loop.json before it and saved after it; everything else RATs carries already lives in its output + directory, which its own --resume reads. + +O/hermit/result.json holds what each iteration returned, as LifelongLoop._run_one_iteration returned it in this +process. This file runs under RATs' Python (3.10) and imports nothing of Hermit. +""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import shutil +import sys +import traceback + +LOOP_STATE = "loop.json" +# What of the loop a continuous run keeps in memory between iterations (rats/loop/lifelong_loop.py __init__) +LOOP_FIELDS = ("_iters_since_skill_proposal", "_iters_since_curate", "_iter_history_for_curator") +# What of a play iteration's record RATs' resume_from reads: the proposer's history (TaskProposer.record_task_outcome) +# and, after a success, the last program (the success-code cache) +PROPOSAL_KEYS = ("activity_name", "canonical_task_id", "language", "goal_conditions", "objects", "fixtures", "goal", + "play_mode", "play_verb", "play_target", "_playtime", "scene_type", "required_skills", + "candidate_type", "source_retry_id") +SCALAR_MAX = 4000 +STATE_FILES = ("failure_memory/episodes.json", "failure_memory/lessons.json", "retry_bank/items.json", + "candidate_state/object_skill_counts.json", "memory/curator_history.json", + "memory/skill_curator_history.json") +ITERATION = re.compile(r"iteration_(\d+)\.json$") + + +# ---------- seam 1: the model ---------- + +def route_models(url: str, dialect: str, video: bool = True) -> None: + """Every RATs model call to the Hermit endpoint at `url` (its chat completions are `url`/chat/completions); for a + model that takes no video, each call's videos dropped by RATs' own `_strip_videos_from_messages` (what RATs does + for a fallback model without video), its images and text kept.""" + import rats.agents.base_agent as base_agent + from rats.llm import genai_backend + target = url.rstrip("/") + "/chat/completions" + if dialect == "openai": + base_agent.OPENAI_API_URL = target # RATs' OpenAI request form, and its `openai/` prefix stripped + headers = {"Content-Type": "application/json"} # no key: the endpoint holds it + + def api_config(model=None): + return target, dict(headers) + + base_agent._get_api_config = api_config + base_agent.is_bedrock_model = lambda model: False + base_agent.should_use_gemini_proxy = lambda model: False + genai_backend.is_available = lambda: False + if not video: + query = base_agent.query_llm + + def query_llm(messages, *args, **kwargs): + return query(base_agent._strip_videos_from_messages(messages), *args, **kwargs) + base_agent.query_llm = query_llm + + +# ---------- seams 2 and 3: the loop ---------- + +def hook_loop(first_iteration: int | None, out: Path, results: list, flush=lambda: None) -> None: + """LifelongLoop.run starting after `first_iteration`, with the loop's in-memory counters restored from and saved + to out/loop.json; each iteration's returned record kept in `results`, and `flush` called after each one (a row + stopped at its timeout keeps the iterations it finished).""" + from rats.loop.lifelong_loop import LifelongLoop + run, one = LifelongLoop.run, LifelongLoop._run_one_iteration + + def run_hooked(self, num_iterations: int = 10): + if first_iteration is not None and self._iteration < first_iteration: + self._iteration = first_iteration + restore_loop(self, out / LOOP_STATE) + try: + return run(self, num_iterations) + finally: + save_loop(self, out / LOOP_STATE) + + def one_hooked(self): + try: + record = one(self) + except BaseException as exc: + results.append({"iteration": self._iteration, "success": False, "error": f"{type(exc).__name__}: {exc}"}) + flush() + raise + results.append(outcome(record)) + flush() + return record + + LifelongLoop.run, LifelongLoop._run_one_iteration = run_hooked, one_hooked + + +def restore_loop(loop, path: Path) -> None: + if not path.is_file(): + return + saved = json.loads(path.read_text()) + for name in LOOP_FIELDS: + if name in saved: + setattr(loop, name, saved[name]) + if "episodes_since_last_distill" in saved and getattr(loop, "failure_memory", None) is not None: + loop.failure_memory._episodes_since_last_distill = int(saved["episodes_since_last_distill"]) + + +def save_loop(loop, path: Path) -> None: + saved = {name: getattr(loop, name) for name in LOOP_FIELDS if hasattr(loop, name)} + fm = getattr(loop, "failure_memory", None) + if fm is not None and hasattr(fm, "_episodes_since_last_distill"): + saved["episodes_since_last_distill"] = int(fm._episodes_since_last_distill) + saved["iteration"] = int(getattr(loop, "_iteration", 0)) + path.write_text(json.dumps(jsonable(saved), indent=1)) + + +def jsonable(value): + return json.loads(json.dumps(value, default=str)) + + +def outcome(record: dict) -> dict: + """What the Trainer's records keep of an iteration: its number, task, outcome and skills.""" + keep = ("iteration", "success", "total_attempts", "skills_learned", "skills_added", "skills_reused", + "skills_failed", "failure_reason", "failure_category", "elapsed_seconds", "learned_skill_count", + "skill_library_size", "failure_memory_episodes", "_env_created", "_env_error", "error", "error_type") + out = {k: record.get(k) for k in keep if k in record} + proposal = record.get("task_proposal") or {} + out["task"] = {k: proposal.get(k) for k in ("activity_name", "language", "objects", "goal") if k in proposal} + return jsonable(out) + + +# ---------- the play state ---------- + +def digest(record: dict) -> dict: + """A play iteration's record as the next iteration's resume reads it: its scalar fields and lists of scalars, + the task proposal's history fields and, after a success, the last program.""" + out = {} + for key, value in record.items(): + if isinstance(value, (bool, int, float)) or value is None: + out[key] = value + elif isinstance(value, str) and not key.startswith("code_attempt_"): + out[key] = value[:SCALAR_MAX] # a failure reason, an env error: as the proposer reads them + elif isinstance(value, list) and all(isinstance(v, (str, int, float, bool)) for v in value): + out[key] = value + proposal = record.get("task_proposal") or {} + out["task_proposal"] = {k: proposal[k] for k in PROPOSAL_KEYS if k in proposal} + # resume_from's _latest_code_attempt: the highest-numbered non-empty program + attempts = sorted((int(m.group(1)), k) for k, v in record.items() + if (m := re.fullmatch(r"code_attempt_(\d+)", k)) and isinstance(v, str) and v.strip()) + if record.get("success") and attempts: + out[attempts[-1][1]] = record[attempts[-1][1]] + return jsonable(out) + + +def hand_back(out: Path) -> None: + """out/hermit/adapter/: skills.json and state/ (the stores, the loop's counters, a digest per iteration).""" + dest = out / "hermit" / "adapter" + if dest.exists(): + shutil.rmtree(dest) + (dest / "state").mkdir(parents=True) + shutil.copy2(out / "skills.json", dest / "skills.json") + for rel in (*STATE_FILES, LOOP_STATE): + if (out / rel).is_file(): + (dest / "state" / rel).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(out / rel, dest / "state" / rel) + for f in sorted(out.glob("iteration_*.json")): + m = ITERATION.search(f.name) + try: + record = json.loads(f.read_text()) + except ValueError: + continue # an iteration that never finished writing: resume skips it too + if isinstance(record, dict) and m and record.get("iteration") == int(m.group(1)): + (dest / "state" / f.name).write_text(json.dumps(digest(record), indent=1)) + + +def completed(out: Path) -> int: + """The last play iteration the state holds (RATs' resume continues after it).""" + return max((int(m.group(1)) for f in out.glob("iteration_*.json") if (m := ITERATION.search(f.name))), default=0) + + +# ---------- the commands ---------- + +def argv_play(a, out: Path) -> list[str]: + n = completed(out) + argv = ["--config", a.config, "--env-type", "libero", "--explore", "--iterations", str(n + 1), + "--output-dir", str(out), "--skill-library", str(out / "skills.json")] + if n: + argv += ["--resume", str(out)] # in place: RATs' own resume of a run's output directory + return argv + list(a.rats_arg or []) + + +def argv_exec(a, out: Path) -> list[str]: + # scripts/run_rats_libero_pro_batch.py build_argv, with the init states this row names + return ["--config", a.config, "--env-type", "libero", "--libero-suite", a.suite, "--libero-task", str(a.task), + "--iterations", str(a.first_state + a.trials), "--fixed-task", "--no-skill-reuse", "--no-failure-memory", + "--output-dir", str(out), "--skill-library", str(a.skills), *list(a.rats_arg or [])] + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("mode", choices=["play", "exec"]) + ap.add_argument("--rats-root", type=Path, required=True) + ap.add_argument("--out", type=Path, required=True) + ap.add_argument("--config", required=True, help="RATs' env config, relative to its checkout") + ap.add_argument("--skills", type=Path, help="exec: the library, frozen") + ap.add_argument("--suite") + ap.add_argument("--task", type=int) + ap.add_argument("--first-state", type=int, default=0) + ap.add_argument("--trials", type=int, default=1) + ap.add_argument("--rats-arg", action="append", help="one more argument for run_rats.py (as --rats-arg=--flag)") + a = ap.parse_args(argv) + root, out = a.rats_root.resolve(), a.out.resolve() + (out / "hermit").mkdir(parents=True, exist_ok=True) + os.chdir(root) # RATs' paths are relative to its checkout + sys.path.insert(0, str(root)) + route_models(os.environ["HERMIT_RATS_URL"], os.environ.get("HERMIT_RATS_DIALECT", "chat"), + video=os.environ.get("HERMIT_RATS_VIDEO", "1") != "0") + results: list = [] + if a.mode == "exec" and (a.skills is None or a.suite is None or a.task is None): + ap.error("exec needs --skills, --suite and --task") + rats_argv = argv_play(a, out) if a.mode == "play" else argv_exec(a, out) + + def write(error, running=False): + result = {"mode": a.mode, "argv": rats_argv, "iterations": results, "error": error} + if running: + result["running"] = True # RATs had not finished: the iterations so far + if a.mode == "exec": + result.update(suite=a.suite, task=a.task, first_state=a.first_state, trials=a.trials) + (out / "hermit" / "result.json").write_text(json.dumps(jsonable(result), indent=1)) + hook_loop(None if a.mode == "play" else a.first_state, out, results, lambda: write(None, running=True)) + from scripts import run_rats + error = None + sys.argv = [str(root / "scripts" / "run_rats.py"), *rats_argv] + try: + run_rats.main() + except SystemExit as exc: + if exc.code not in (0, None): + error = f"run_rats.py exited with {exc.code}" + except BaseException as exc: # noqa: BLE001 - what failed goes into the result + error = f"{type(exc).__name__}: {exc}" + traceback.print_exc() + if a.mode == "play" and (out / "skills.json").is_file(): + hand_back(out) + write(error) + return 0 if error is None else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/README.md b/tests/README.md index 4f45e3ba..bbc8b496 100644 --- a/tests/README.md +++ b/tests/README.md @@ -10,7 +10,7 @@ python -m pytest --integration ... # also the tests that run an agent CLI insta | Group | What it covers | |---|---| | `core/` | the framework: the Trainer, templates and `check_spec`, deployment and host exporters, the agent layers (Base Agents, CLI agents, model bindings), the sandbox and isolation, the generic AgentEvolvers | -| `methods//` | one method: its Evolver, its template and its examples (`ace`, `ahe`, `aspire`, `continual_harness`, `evosafe`, `harness2`, `meta_harness_adapter`, `mwm`, `opro`, `optimizers` for GEPA and SkillOpt, `reharness`, `rrsi_adapter`, `she`) | +| `methods//` | one method: its Evolver, its template and its examples (`ace`, `ahe`, `aspire`, `continual_harness`, `evosafe`, `harness2`, `meta_harness_adapter`, `mwm`, `opro`, `optimizers` for GEPA and SkillOpt, `rats`, `reharness`, `rrsi_adapter`, `she`) | `--changed` reads `selection.py`: `core/` runs for every change but documentation (its tests also read every method's template, manifest and packaging); a method's own files (its Evolver, its template, its examples, its tests) diff --git a/tests/core/test_selection.py b/tests/core/test_selection.py index c48640c1..0da761e1 100644 --- a/tests/core/test_selection.py +++ b/tests/core/test_selection.py @@ -62,8 +62,9 @@ def test_a_benchmarks_shared_files_run_the_methods_with_an_example_there(): "rrsi_adapter", "core"} assert groups_for("examples/servelearnbench/utils/x.py") == {"mwm", "core"} # an engine several benchmarks run on: the methods with an example under any of them - assert groups_for("examples/cap_harness/utils/agent/sim.py") == {"aspire", "core"} - assert groups_for("examples/libero/utils/agent/task.py") == {"aspire", "core"} + assert groups_for("examples/cap_harness/utils/agent/sim.py") == {"aspire", "rats", "core"} + assert groups_for("examples/libero/utils/agent/task.py") == {"aspire", "rats", "core"} + assert groups_for("examples/robosuite/utils/x.py") == {"aspire", "core"} # no RATs example there assert groups_for("examples/robosuite/aspire/run.yaml") == {"aspire", "core"} groups, why = select(["hermit/cli.py", "examples/officeqa/rrsi_adapter/README.md", "docs/index.md"]) assert groups == {"core", "rrsi_adapter"} and why == {"core": "hermit/cli.py", diff --git a/tests/methods/rats/test_rats.py b/tests/methods/rats/test_rats.py new file mode 100644 index 00000000..82c83bd1 --- /dev/null +++ b/tests/methods/rats/test_rats.py @@ -0,0 +1,802 @@ +"""RATs (hermit/agent/evolver/methods/rats/): the rats template (RATs' skill library and play state, and its check), +the task rows and splits (rows.py), the runner's seams into RATs' own entry point (runner.py), the actor that runs it +in a sandbox of its own behind a metered endpoint (actor.py), the Evolver that applies a play iteration's state +(evolver.py), and the example's judge and configs (examples/libero/rats/), through the Trainer and `evaluate`. + +RATs is a stand-in written here (FAKE_RATS): the modules the runner touches, with the code paths it relies on as RATs +has them at the commit the example pins (Playful-RATs/RATs 1fd2ef5): scripts/run_rats.py main (its flags), the +iteration loop of LifelongLoop.run (`for i in range(start, num_iterations): self._iteration = i + 1`, an exception +saved as the iteration's error record, each record saved as iteration_.json) and its resume after the last saved +iteration (rats/loop/lifelong_loop.py), query_llm's routing (rats/agents/base_agent.py: `_get_api_config`, the +`openai/` prefix stripped for OPENAI_API_URL, Bedrock and the Gemini proxy first) and genai_backend.is_available. The +LIBERO env's init state is (seed - 1) % 50 with seed the iteration's number (rats/envs/simulators/libero.py). The +provider is a local HTTP server answering as an OpenAI-compatible endpoint does. No simulator, no GPU (the sandbox's +GPU binding is the one stand-in at its edge), no network.""" +import importlib.util +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import sys +import textwrap +import threading + +import pytest +import yaml + +from claude_stand import bwrap_works +from hermit import sandbox as S +from hermit.agent.evolver.base import Access, Progress, StepContext, Workspace +from hermit.agent.evolver.methods.rats import actor as A +from hermit.agent.evolver.methods.rats import evolver as E +from hermit.agent.evolver.methods.rats import runner as R +from hermit.config import Config +from hermit.evaluate import evaluate +from hermit.spec import check_spec +from hermit.task import Benchmark +from hermit.trainer.trainer import Trainer + +ROOT = Path(__file__).resolve().parents[3] +TEMPLATE = ROOT / "hermit" / "adapter" / "templates" / "rats" +EXAMPLE = ROOT / "examples" / "libero" / "rats" + + +def _load(name: str, path: Path): + spec_ = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(module) + return module + + +CHECK = _load("rats_check", TEMPLATE / ".hermit" / "check.py") +JUDGE = _load("rats_judge", EXAMPLE / "judge.py") +Rw = _load("rats_rows", EXAMPLE / "rows.py") # the example's: agents never import the task layer +F = _load("cap_fakes", ROOT / "examples" / "cap_harness" / "utils" / "tests" / "cap_fakes.py") +tmp_path = F.tmp_path # a fixture: a directory outside /tmp, for the template check's sandbox +PRIMITIVES = json.loads((TEMPLATE / "skills.json").read_text()) + + +def learned(name: str, code: str | None = None, **fields) -> dict: + """A learned skill as RATs' SkillLibrary.add_skill records it.""" + return {"name": name, "description": f"{name}, learned in play", "is_primitive": False, "tier": "experimental", + "usage_count": 2, "success_count": 1, + "code": code or f"def {name}(obj):\n pose = get_object_pose(obj)\n return move_to(pose)\n", **fields} + + +FAKE_RATS = { + "rats/__init__.py": "", + "rats/agents/__init__.py": "", + "rats/llm/__init__.py": "", + "rats/loop/__init__.py": "", + # RATs' scripts/ is a namespace package; here a regular one, which wins over a `scripts` package the test's + # interpreter may have installed (RATs' venv has none) + "scripts/__init__.py": "", + "rats/llm/genai_backend.py": ''' + def is_available(): + return True # RATs would send every call to Vertex + ''', + "rats/agents/base_agent.py": ''' + import json, os, urllib.request + OPENAI_API_URL = "https://api.openai.com/v1/chat/completions" + SENT = [] + + def _get_api_config(model=None): + return "https://openrouter.invalid/api/v1/chat/completions", {"Authorization": "Bearer from-the-env"} + + def is_bedrock_model(model): + return True + + def should_use_gemini_proxy(model): + return True + + def _strip_videos_from_messages(messages): + stripped = [] + for msg in messages: + content = msg.get("content") + if not isinstance(content, list): + stripped.append(msg) + continue + blocks = [b for b in content if not (isinstance(b, dict) and b.get("type") == "image_url" and + str((b.get("image_url") or {}).get("url", "")).startswith("data:video"))] + stripped.append({**msg, "content": blocks}) + return stripped + + def query_llm(messages, *, model=None, max_tokens=64): + from rats.llm import genai_backend + model = model or os.environ["RATS_LLM_MODEL"] + if is_bedrock_model(model) or should_use_gemini_proxy(model) or genai_backend.is_available(): + raise RuntimeError("sent past the endpoint") + url, headers = _get_api_config(model) + if url == OPENAI_API_URL and model.startswith("openai/"): + payload = {"model": model.split("/", 1)[1], "messages": messages, "max_completion_tokens": max_tokens, + "reasoning_effort": "low"} + else: + payload = {"model": model, "messages": messages, "max_tokens": max_tokens, "temperature": 0.2} + request = urllib.request.Request(url, data=json.dumps(payload).encode(), method="POST", + headers={**headers, "Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=60) as response: + body = json.loads(response.read()) + SENT.append({"url": url, "headers": headers, "payload": payload}) + return {"content": body["choices"][0]["message"]["content"]} + ''', + "rats/loop/lifelong_loop.py": ''' + import json, os, socket, time + from pathlib import Path + from rats.agents import base_agent + + LIBERO = Path("rats/third_party/LIBERO-PRO/libero/libero") + + class FailureMemory: + def __init__(self): + self._episodes_since_last_distill = 0 + + def shown(path): + if path.is_dir(): + return sorted(p.name for p in path.iterdir()) + return path.stat().st_size if path.is_file() else None + + class LifelongLoop: + def __init__(self, args): + self.args, self.out = args, Path(args.output_dir) + self._iteration = 0 + self._iters_since_skill_proposal = self._iters_since_curate = 0 + self._iter_history_for_curator = [] + self.failure_memory = FailureMemory() + if args.resume: + done = [int(f.stem.split("_")[1]) for f in Path(args.resume).glob("iteration_*.json")] + self._iteration = max(done, default=0) + + def run(self, num_iterations=10): + for i in range(self._iteration, num_iterations): + self._iteration = i + 1 + try: + result = self._run_one_iteration() + except Exception as e: + result = {"iteration": self._iteration, "error": str(e), "error_type": type(e).__name__, + "success": False} + (self.out / f"iteration_{self._iteration:03d}.json").write_text(json.dumps(result)) + return {} + + def probe(self, n): + closed = int(os.environ.get("FAKE_RATS_CLOSED_PORT", "9")) + try: + socket.create_connection(("127.0.0.1", closed), timeout=2).close() + reached = True + except OSError: + reached = False + try: + Path("planted.txt").write_text("x") + wrote = True + except OSError: + wrote = False + try: + with open(self.args.skill_library, "a"): + frozen = False + except OSError: + frozen = True + info = {"git": shown(Path(".git")), "outputs": shown(Path("outputs")), + "authors_library": shown(Path("skill_library/learned_by_authors.json")), + "primitives": shown(Path("skill_library/libero_skills.json")), + "held_out": shown(LIBERO / "bddl_files/libero_object_swap"), + "original": shown(LIBERO / "bddl_files/libero_spatial"), + "reached_closed_port": reached, "wrote_rats_root": wrote, "library_frozen": frozen, + "env": dict(os.environ)} + (self.out / f"probe-{n}.json").write_text(json.dumps(info)) + + def _run_one_iteration(self): + n = self._iteration + if os.environ.get("FAKE_RATS_PROBE"): + self.probe(n) + if str(n) in os.environ.get("FAKE_RATS_FAIL", "").split(","): + raise RuntimeError("the env did not instantiate") + if str(n) in os.environ.get("FAKE_RATS_HANG", "").split(","): + time.sleep(600) + before = {"_iters_since_curate": self._iters_since_curate, + "_iters_since_skill_proposal": self._iters_since_skill_proposal, + "history": len(self._iter_history_for_curator), + "episodes_since_last_distill": self.failure_memory._episodes_since_last_distill} + reply = base_agent.query_llm([{"role": "user", "content": [ + {"type": "text", "text": f"propose a task for iteration {n}"}, + {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}, + {"type": "image_url", "image_url": {"url": "data:video/mp4;base64,BBBB"}}]}]) + library = json.loads(Path(self.args.skill_library).read_text()) + record = {"iteration": n, "success": True, "total_attempts": 2, "counters_before": before, + "sent": base_agent.SENT[-1], "init_state": (n - 1) % 50, + "library": [s["name"] for s in library if not s.get("is_primitive")]} + if not self.args.explore: + record.update(suite=self.args.libero_suite, task=self.args.libero_task) + return record + self._iters_since_curate += 1 + self._iters_since_skill_proposal += 1 + self._iter_history_for_curator.append({"iteration": n}) + self.failure_memory._episodes_since_last_distill += 1 + library.append({"name": f"place_on_{n}", "description": "place it", "is_primitive": False, + "tier": "experimental", "usage_count": 1, "success_count": 1, + "code": f"def place_on_{n}(obj):\\n return move_to(get_object_pose(obj))\\n"}) + (self.out / "skills.json").write_text(json.dumps(library)) + memory = self.out / "failure_memory" + memory.mkdir(exist_ok=True) + episodes = json.loads((memory / "episodes.json").read_text()) if (memory / "episodes.json").exists() else [] + (memory / "episodes.json").write_text(json.dumps(episodes + [{"iteration": n, "failure": "missed"}])) + record.update(task_proposal={"language": reply["content"], "activity_name": f"task_{n}", + "objects": ["bowl"], "_playtime": True, "_rendered_scene": {"rgb": [1]}}, + code_attempt_1="def first(): pass", code_attempt_2=f"def solution_{n}(): pass", + code_attempt_3=" ", + attempt_details=[{"nested": True}], skills_learned=[f"place_on_{n}"]) + return record + ''', + "scripts/run_rats.py": ''' + import argparse, json, sys + from pathlib import Path + from rats.loop.lifelong_loop import LifelongLoop + + def main(): + ap = argparse.ArgumentParser() + for flag in ("--config", "--env-type", "--iterations", "--output-dir", "--skill-library", "--resume", + "--libero-suite", "--libero-task"): + ap.add_argument(flag) + for flag in ("--explore", "--fixed-task", "--no-skill-reuse", "--no-failure-memory"): + ap.add_argument(flag, action="store_true") + args = ap.parse_args(sys.argv[1:]) + out = Path(args.output_dir) + out.mkdir(parents=True, exist_ok=True) + (out / "fake_argv.json").write_text(json.dumps(sys.argv[1:])) + LifelongLoop(args).run(int(args.iterations)) + ''', + "env_configs/libero/rats_libero_play.yaml": "env: {}\n", + "env_configs/libero/rats_libero_pro_nonpriv.yaml": "env: {}\n", + ".git/HEAD": "ref: refs/heads/main\n", + "outputs/authors_run/iteration_1.json": "{}\n", + "rats/third_party/LIBERO-PRO/libero/libero/bddl_files/libero_spatial/a.bddl": "(define (problem a))\n", + "rats/third_party/LIBERO-PRO/libero/libero/bddl_files/libero_object_swap/b.bddl": "(define (problem b))\n", + "rats/third_party/LIBERO-PRO/libero/libero/init_files/libero_object_swap/b.pruned_init": "states\n", +} + + +def fake_rats(root: Path) -> Path: + for rel, text in FAKE_RATS.items(): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_text(textwrap.dedent(text).lstrip("\n")) + (root / "skill_library").mkdir() + for name in ("libero_skills.json", "libero_nonpriv_skills.json"): # RATs' primitive-only libraries + (root / "skill_library" / name).write_text(json.dumps(PRIMITIVES)) + (root / "skill_library" / "learned_by_authors.json").write_text(json.dumps([*PRIMITIVES, learned("theirs")])) + (root / ".cache" / "robot_descriptions").mkdir(parents=True) + return root + + +@pytest.fixture +def chat(provider): + """Hermit's endpoint as the actor starts it (over Direct, Layer 1), to the provider below, with what each request + asked kept (`seen`).""" + from hermit.agent.base.endpoint import ChatEndpoint + from hermit.agent.model.direct import Direct + from hermit.agent.model.llm import ChatClient + endpoint = ChatEndpoint(Direct({}, ChatClient(provider.url, "m-1", max_retries=0))).start() + endpoint.seen, endpoint.media = provider.seen, provider.media + yield endpoint + endpoint.close() + + +@pytest.fixture +def provider(): + """An OpenAI-compatible provider on the loopback: each request's headers and body kept, a reply with usage.""" + requests, seen, media = [], [], [] + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + requests.append({"path": self.path, "headers": dict(self.headers), "body": body}) + content = body["messages"][-1]["content"] + if isinstance(content, list): + media.append([b["image_url"]["url"].split(";")[0] for b in content if b.get("type") == "image_url"]) + content = " ".join(b["text"] for b in content if b.get("type") == "text") + seen.append(content) + data = json.dumps({"id": "c1", "object": "chat.completion", "model": body.get("model"), + "choices": [{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": "put the bowl on the plate"}}], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *args): + pass + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + server.url, server.requests, server.seen = f"http://127.0.0.1:{server.server_address[1]}/v1", requests, seen + server.media = media + yield server + server.shutdown() + server.server_close() + + +def runner(root: Path, out: Path, args: list[str], url: str, *, model: str = "glm-x", dialect: str = "chat", + env: dict | None = None): + return subprocess.run([sys.executable, str(A.RUNNER), args[0], "--rats-root", str(root), "--out", str(out), + *args[1:]], + env={"PATH": os.environ["PATH"], "HOME": str(out.parent), "HERMIT_RATS_URL": url, + "HERMIT_RATS_DIALECT": dialect, "RATS_LLM_MODEL": model, **(env or {})}, + capture_output=True, text=True, timeout=120) + + +def adapter_of(tmp: Path, skills: list | str | None = None, files: dict | None = None) -> Path: + """The template's seed as an adapter (its metadata too), with its library or state files replaced.""" + adapter = tmp / "adapter" + shutil.copytree(TEMPLATE, adapter) + if skills is not None: + (adapter / "skills.json").write_text(skills if isinstance(skills, str) else json.dumps(skills)) + for rel, text in (files or {}).items(): + (adapter / rel).parent.mkdir(parents=True, exist_ok=True) + (adapter / rel).write_text(text if isinstance(text, str) else json.dumps(text)) + return adapter + + +def problems(adapter: Path) -> list[str]: + return [f"{i.path}: {i.problem}" for i in check_spec(adapter, TEMPLATE, deploy=False).issues] + + +# ---------- the template ---------- + +def test_the_seed_is_rats_primitive_library_and_passes_the_check(tmp_path): + assert check_spec(TEMPLATE, TEMPLATE, deploy=True).passed + assert len(PRIMITIVES) == 12 and all(s["is_primitive"] for s in PRIMITIVES) # L0: FrankaLiberoApi's twelve + adapter = adapter_of(tmp_path, [*PRIMITIVES, learned("place_bowl_on_plate"), + learned("stack", "def stack(a, b):\n place_bowl_on_plate(a)\n" + " return getattr(b, 'name')\n", tier="verified")], + {"state/iteration_3.json": {"iteration": 3, "success": True, "task_proposal": {"goal": "x"}}, + "state/failure_memory/episodes.json": [], "state/loop.json": {"iteration": 3}}) + assert problems(adapter) == [] + + +@pytest.mark.parametrize("skills, problem", [ + ("{", "not JSON"), + ([*PRIMITIVES, learned("peek", "def peek():\n return env.sim.data\n")], "privileged simulator access"), + ([*PRIMITIVES, learned("shell", "import os\ndef shell():\n os.system('ls')\n")], "it imports os"), + ([*PRIMITIVES, learned("klass", "def klass(x):\n return x.__class__\n")], "private or dunder attribute"), + ([*PRIMITIVES, learned("reflect", "def reflect(x, n):\n return getattr(x, n)\n")], "not a plain constant"), + ([*PRIMITIVES, learned("run", "def run(c):\n return eval(c)\n")], "it calls eval"), + ([*PRIMITIVES, learned("misnamed", "def other():\n pass\n")], "no top-level `def misnamed`"), + ([{**PRIMITIVES[0], "code": "import os"}, *PRIMITIVES[1:]], "comments only"), + ([*PRIMITIVES, learned("twice"), learned("twice")], "two entries have this name"), + ([*PRIMITIVES, learned("lucky", usage_count=1, success_count=2)], "more successes (2) than uses (1)"), + ([*PRIMITIVES, learned("tiered", tier="gold")], "`tier` must be one of"), +]) +def test_the_check_refuses_a_library_whose_skills_reach_past_the_api(tmp_path, skills, problem): + """What the library hands the next task's program: RATs' own forbidden patterns (no `env.`), nothing of the + interpreter, files or processes; a primitive only documents the API.""" + assert any(problem in p for p in problems(adapter_of(tmp_path, skills))), problems(adapter_of(tmp_path, skills)) + + +def test_the_check_refuses_state_rats_could_not_resume_from(tmp_path): + adapter = adapter_of(tmp_path, None, {"state/iteration_3.json": {"iteration": 4}, + "state/failure_memory/episodes.json": {}, + "state/loop.json": [], + "notes.md": "stray\n"}) + found = problems(adapter) + assert any("state/iteration_3.json: an iteration digest" in p for p in found) + assert any("episodes.json: a JSON list" in p for p in found) + assert any("state/loop.json: a JSON object" in p for p in found) + assert any("notes.md is off the adapter's surface" in p for p in found) + (adapter / "notes.md").unlink() + (adapter / "state" / "loop.json").unlink() + (adapter / "state" / "loop.json").symlink_to("/etc/hostname") # the check itself, unsanitized + assert {"path": "state/loop.json", "problem": "not a regular file or folder"} in CHECK.check(str(adapter)) + assert CHECK.check(str(tmp_path / "missing"))[0]["path"] == "skills.json" + + +# ---------- the rows and splits ---------- + +def test_the_splits_share_no_task_and_hold_the_papers_protocol(): + splits = Rw.build(50, Rw.states("43-49"), Rw.states("0-9"), Rw.states("0-49")) + assert {k: len(v) for k, v in splits.items()} == {"train": 50, "val": 40, "test": 60, "test_full": 80, + "smoke_train": 1, "smoke_val": 1, "smoke_test": 1} + ids = {k: {r["id"] for r in v} for k, v in splits.items() if not k.startswith("smoke")} + assert sum(map(len, ids.values())) == len(set().union(*ids.values())) # no row in two splits + assert all(r["mode"] == "play" for r in splits["train"]) # play has no benchmark task + suites = {k: {r["suite"] for r in splits[k]} for k in ("val", "test", "test_full")} + assert suites["val"] == {"libero_spatial", "libero_object", "libero_goal", "libero_10"} # the original LIBERO + assert suites["val"].isdisjoint(suites["test_full"]) and suites["test"] < suites["test_full"] + assert sum(r["trials"] for r in splits["test"]) == 600 # Table 1: 60 tasks x states 0-9 + assert {(r["first_state"], r["trials"]) for r in splits["test"]} == {(0, 10)} + assert {(r["first_state"], r["trials"]) for r in splits["val"]} == {(43, 7)} + assert sum(r["trials"] for r in splits["test_full"]) == 4000 + assert splits["smoke_test"][0]["suite"] == "libero_object_swap" and splits["smoke_val"][0]["first_state"] == 43 + for bad in ("0-50", "9-3", "x"): + with pytest.raises(Exception, match="init states"): + Rw.states(bad) + small = Rw.build(10, Rw.states("43-49"), Rw.states("0-1"), Rw.states("0-49"), Rw.task_ids("0-1")) + assert (len(small["test"]), sum(r["trials"] for r in small["test"])) == (12, 24) # a reduced Table 1 + assert {r["task_id"] for r in small["val"] + small["test"] + small["test_full"]} == {0, 1} + for bad in ("3-10", "5-2", "x"): + with pytest.raises(Exception, match="task ids"): + Rw.task_ids(bad) + + +def test_the_rows_are_written_as_task_directories_the_view_reads_back(tmp_path): + Rw.main(["--out", str(tmp_path), "--play", "3", "--test-states", "0-1"]) + fields = _load("rats_fields", ROOT / "examples" / "cap_harness" / "utils" / "agent" / "fields.py") + rows = fields.task_rows(tmp_path / "tasks") + assert rows["play-002"] == {"id": "play-002", "mode": "play", "slot": 2, "split": "train"} + assert rows["test-libero_goal_task-t04"] == {"id": "test-libero_goal_task-t04", "mode": "exec", + "suite": "libero_goal_task", "task_id": 4, "first_state": 0, + "trials": 2, "split": "test"} + assert (tmp_path / "splits" / "train.txt").read_text().split() == ["play-001", "play-002", "play-003"] + assert "network_mode" in (tmp_path / "tasks" / "play-001" / "task.toml").read_text() + + +# ---------- the runner: RATs' own entry point, three seams ---------- + +def test_the_runner_resumes_a_play_iteration_and_hands_back_its_state(tmp_path, chat): + root = fake_rats(tmp_path / "RATs") + out = tmp_path / "out" + out.mkdir() + shutil.copy(TEMPLATE / "skills.json", out / "skills.json") + (out / "iteration_001.json").write_text(json.dumps({"iteration": 1, "success": False, + "task_proposal": {"language": "earlier"}})) + (out / "loop.json").write_text(json.dumps({"_iters_since_curate": 4, "_iters_since_skill_proposal": 1, + "_iter_history_for_curator": [{"iteration": 1}], + "episodes_since_last_distill": 3, "iteration": 1})) + run = runner(root, out, ["play", "--config", A.PLAY_CONFIG], chat.url) + assert run.returncode == 0, run.stdout + run.stderr + argv = json.loads((out / "fake_argv.json").read_text()) + assert argv[argv.index("--iterations") + 1] == "2" and argv[argv.index("--resume") + 1] == str(out) + assert "--explore" in argv and argv[argv.index("--skill-library") + 1] == str(out / "skills.json") + record = json.loads((out / "iteration_002.json").read_text()) + # seam 3: the counters a continuous run keeps in memory, restored before the iteration and saved after it + assert record["counters_before"] == {"_iters_since_curate": 4, "_iters_since_skill_proposal": 1, "history": 1, + "episodes_since_last_distill": 3} + saved = json.loads((out / "loop.json").read_text()) + assert (saved["_iters_since_curate"], saved["episodes_since_last_distill"], saved["iteration"]) == (5, 4, 2) + # seam 1: the call went to the endpoint, in RATs' generic form, with no key of RATs' + assert record["sent"]["url"] == chat.url + "/chat/completions" and record["sent"]["headers"] == \ + {"Content-Type": "application/json"} + assert record["sent"]["payload"]["model"] == "glm-x" and "max_tokens" in record["sent"]["payload"] + assert chat.seen == ["propose a task for iteration 2"] + assert chat.media == [["data:image/png", "data:video/mp4"]] # the videos kept by default + back = out / "hermit" / "adapter" + assert [s["name"] for s in json.loads((back / "skills.json").read_text()) if not s["is_primitive"]] == \ + ["place_on_2"] + digest = json.loads((back / "state" / "iteration_002.json").read_text()) + assert digest["code_attempt_2"] == "def solution_2(): pass" # a success's last program, no other + assert not {"code_attempt_1", "code_attempt_3", "attempt_details", "sent"} & set(digest) + assert digest["task_proposal"] == {"language": "put the bowl on the plate", "activity_name": "task_2", + "objects": ["bowl"], "_playtime": True} + assert json.loads((back / "state" / "iteration_001.json").read_text())["iteration"] == 1 + assert json.loads((back / "state" / "failure_memory" / "episodes.json").read_text())[-1]["iteration"] == 2 + adapter = adapter_of(tmp_path) # what comes back passes the check + shutil.copy(back / "skills.json", adapter / "skills.json") + shutil.copytree(back / "state", adapter / "state") + assert problems(adapter) == [] + result = json.loads((out / "hermit" / "result.json").read_text()) + assert [(i["iteration"], i["success"], i["skills_learned"]) for i in result["iterations"]] == \ + [(2, True, ["place_on_2"])] and result["error"] is None + + +def test_the_runner_runs_an_exec_row_in_its_init_states_with_the_library_frozen(tmp_path, chat): + root = fake_rats(tmp_path / "RATs") + out, library = tmp_path / "out", tmp_path / "library.json" + library.write_text(json.dumps([*PRIMITIVES, learned("lift_bowl")])) + run = runner(root, out, ["exec", "--config", A.EXEC_CONFIG, "--skills", str(library), "--suite", + "libero_goal_task", "--task", "3", "--first-state", "7", "--trials", "3"], + chat.url, model="openai/gpt-x", dialect="openai", + env={"FAKE_RATS_FAIL": "9", "HERMIT_RATS_VIDEO": "0"}) + assert run.returncode == 0, run.stdout + run.stderr + argv = json.loads((out / "fake_argv.json").read_text()) + assert argv[argv.index("--iterations") + 1] == "10" and argv[argv.index("--libero-task") + 1] == "3" + assert {"--fixed-task", "--no-skill-reuse", "--no-failure-memory"} <= set(argv) + assert "--resume" not in argv and "--explore" not in argv + assert sorted(int(f.stem.split("_")[1]) for f in out.glob("iteration_*.json")) == [8, 9, 10] + records = {n: json.loads((out / f"iteration_{n:03d}.json").read_text()) for n in (8, 9, 10)} + assert (records[8]["init_state"], records[10]["init_state"]) == (7, 9) # trial j: init state 7 + j + assert records[8]["library"] == ["lift_bowl"] and records[8]["suite"] == "libero_goal_task" + assert records[9]["error_type"] == "RuntimeError" # RATs' own record of a failed trial + # RATs' OpenAI form for an openai/ model: the prefix stripped, as for OPENAI_API_URL + assert records[8]["sent"]["payload"]["model"] == "gpt-x" and "max_completion_tokens" in records[8]["sent"]["payload"] + # a model that takes no video: RATs' _strip_videos_from_messages on every call, the images kept + assert chat.media == [["data:image/png"], ["data:image/png"]] + result = json.loads((out / "hermit" / "result.json").read_text()) + assert [(i["iteration"], i["success"]) for i in result["iterations"]] == [(8, True), (9, False), (10, True)] + assert result["iterations"][1]["error"] == "RuntimeError: the env did not instantiate" + assert not (out / "hermit" / "adapter").exists() + + +def test_a_play_iteration_that_crashes_hands_back_what_rats_saved_and_says_why(tmp_path, chat): + root = fake_rats(tmp_path / "RATs") + out = tmp_path / "out" + out.mkdir() + shutil.copy(TEMPLATE / "skills.json", out / "skills.json") + (root / "scripts" / "run_rats.py").write_text("def main():\n raise SystemExit(3)\n") + run = runner(root, out, ["play", "--config", A.PLAY_CONFIG], chat.url) + assert run.returncode == 1 + result = json.loads((out / "hermit" / "result.json").read_text()) + assert result["error"] == "run_rats.py exited with 3" and result["iterations"] == [] + assert json.loads((out / "hermit" / "adapter" / "skills.json").read_text()) == PRIMITIVES + + +# ---------- the actor's rows, read on the host ---------- + +def test_an_exec_rows_trials_are_its_iterations_and_one_that_never_ran_fails(tmp_path): + out, log = tmp_path / "out", tmp_path / "log" + (out / "hermit").mkdir(parents=True) + log.mkdir() + (out / "hermit" / "result.json").write_text(json.dumps({"iterations": [ + {"iteration": 8, "success": True, "total_attempts": 1}, {"iteration": 10, "success": False}]})) + for n in (8, 10, 11): + (out / f"iteration_{n:03d}.json").write_text(json.dumps({"iteration": n})) + actor = A.RatsActor({}, tmp_path) + record = actor._collect({"suite": "libero_goal_task", "task_id": 3, "first_state": 7, "trials": 3}, "exec", out, + log) + assert [(t["init_state"], t["ran"], t["success"]) for t in record["trials"]] == \ + [(7, True, True), (8, False, False), (9, True, False)] + assert record["output"] == {"mode": "exec", "suite": "libero_goal_task", "task_id": 3, "successes": 1, "trials": 3, + "ran": 2, "error": None} + assert sorted(p.name for p in (log / "rats").iterdir()) == ["iteration_008.json", "iteration_010.json"] + assert JUDGE.score({"first_state": 7, "trials": 3}, record["output"])["feedback"] == \ + "1/3 trials in init states 7-9 (1 did not run)" + + +def test_the_actor_sends_the_rows_reasoning_effort_unless_told_otherwise(tmp_path, monkeypatch): + """RATs' generic request form carries no reasoning effort: the actor adds the first evaluation's (medium), or the + one given, to each request; false sends none.""" + monkeypatch.setenv("FIREWORKS_API_KEY", "x") + spec = {"base_url": "http://127.0.0.1:9/v1", "model": "m-1"} + def extra(params): + return A.RatsActor(params, tmp_path)._model().get("extra_body") + assert extra({"model": spec}) == {"reasoning_effort": "medium"} + assert extra({"model": spec, "effort": "high"}) == {"reasoning_effort": "high"} + assert extra({"model": spec, "effort": False}) == {} + assert extra({"model": {**spec, "extra_body": {"reasoning_effort": "low", "top_k": 5}}}) == \ + {"reasoning_effort": "low", "top_k": 5} + glm = "fireworks/accounts/fireworks/models/glm-5p3-flash" + resolved = A.RatsActor({"model": glm}, tmp_path)._model() + assert (resolved["model"], resolved["extra_body"]) == ("accounts/fireworks/models/glm-5p3-flash", + {"reasoning_effort": "medium"}) + layered = A.RatsActor({"model": {"ref": glm, "effort": "low"}}, tmp_path)._model() # Layer 1's form + assert layered["extra_body"] == {"reasoning_effort": "low"} and "effort" not in layered + + +def test_the_actor_refuses_a_row_or_a_setting_that_would_leak_or_misplace_a_run(tmp_path): + root = fake_rats(tmp_path / "RATs") + base = {"rats_root": str(root), "python": sys.executable, "logs": str(tmp_path / "logs"), + "model": {"base_url": "http://127.0.0.1:9/v1", "model": "m-1"}} + play, test = {"id": "play-001", "mode": "play"}, {"id": "t", "mode": "exec", "suite": "libero_object_swap", + "task_id": 0, "first_state": 45, "trials": 6} + for params, task, match in ( + ({"rats_args": ["--proposer-include-eval-task-context"]}, play, "not for a play row"), + ({"rats_args": ["--libero-suite=libero_object_swap"]}, play, "not for a play row"), + ({}, test, "not among LIBERO's 50"), + ({}, {"id": "x", "mode": "eval"}, "mode: play"), + ({"env": {"OPENAI_API_KEY": "x"}, "gpus": [0]}, play, "looks like a secret"), + ({}, play, "agent.params.gpus"), + ({"gpus": "$RATS_GPUS_UNSET"}, play, "is not set"), + ({"logs": str(root / "logs")}, play, "inside RATs' checkout")): + with pytest.raises(ValueError, match=match): + A.RatsActor({**base, **params}, tmp_path).run(task, None) + with pytest.raises(FileNotFoundError, match="neither in"): + A.RatsActor({**base, "exec_config": "missing.yaml", "gpus": [0]}, tmp_path).run( + {**test, "first_state": 0, "trials": 1}, None) + + +# ---------- the Evolver ---------- + +def material(tmp: Path, records: dict[str, dict], handed: dict[str, Path | None]) -> Path: + """One step's learning material: each record and, under its trajectory, the adapter it handed back.""" + step = tmp / "material" / "step_0001" + (step / "tasks").mkdir(parents=True) + for rid, record in records.items(): + traj = step / "trajectories" / rid + traj.mkdir(parents=True) + if handed.get(rid) is not None: + shutil.copytree(handed[rid], traj / "adapter", symlinks=True) + (step / "tasks" / f"{rid}.json").write_text(json.dumps({"id": rid, **record, + "trajectory": f"trajectories/{rid}"})) + (tmp / "material" / "current").symlink_to("step_0001") + return tmp / "material" + + +def context(tmp: Path, adapter: Path) -> StepContext: + ws = Workspace(adapter=adapter, learning_material=tmp / "material", task_info=tmp / "task-info", + history=tmp / "history", state=tmp / "state", scratch=tmp / "scratch", output=tmp / "output") + for d in (ws.state, ws.scratch, ws.output, ws.task_info): + d.mkdir(parents=True, exist_ok=True) + + def check_spec_tool(path: str) -> dict: + result = check_spec(Path(path), TEMPLATE, deploy=False) + return {"passed": result.passed, "issues": [i.__dict__ for i in result.issues]} + return StepContext(workspace=ws, access=Access(), tools={"check_spec": check_spec_tool}, params={}, + progress=Progress(1, 1, False)) + + +PLAY = {"output": {"mode": "play", "iteration": 4, "success": True, "task": "put the bowl on the plate", + "skills_learned": ["place_on_4"], "state": True, "error": None}} + + +def handed_back(tmp: Path, skills: list, state: dict) -> Path: + back = tmp / "handed" + (back / "state").mkdir(parents=True) + (back / "skills.json").write_text(json.dumps(skills)) + for rel, value in state.items(): + (back / "state" / rel).parent.mkdir(parents=True, exist_ok=True) + (back / "state" / rel).write_text(json.dumps(value)) + return back + + +def test_the_evolver_makes_a_play_iterations_library_and_state_the_adapter(tmp_path): + adapter = adapter_of(tmp_path, None, {"state/iteration_1.json": {"iteration": 1}}) + back = handed_back(tmp_path, [*PRIMITIVES, learned("place_on_4", tier="verified")], + {"iteration_004.json": {"iteration": 4, "task_proposal": {}}, "loop.json": {"iteration": 4}}) + material(tmp_path, {"play-004": PLAY}, {"play-004": back}) + result = E.RatsEvolver().step(context(tmp_path, adapter)) + assert result.status == "done" and result.extra["applied"] and result.extra["tiers"]["verified"] == 1 + assert "1 learned skills" in result.summary and "new: place_on_4" in result.summary + assert json.loads((adapter / "skills.json").read_text())[-1]["name"] == "place_on_4" + assert sorted(p.name for p in (adapter / "state").iterdir()) == ["iteration_004.json", "loop.json"] # replaced + assert (adapter / "ADAPTER.md").read_text() == (TEMPLATE / "ADAPTER.md").read_text() + + +def test_the_evolver_leaves_the_adapter_when_a_play_iteration_hands_back_nothing_it_can_apply(tmp_path): + adapter = adapter_of(tmp_path) + seed = (adapter / "skills.json").read_bytes() + bad = handed_back(tmp_path, [*PRIMITIVES, learned("peek", "def peek():\n return env.sim\n")], {}) + material(tmp_path, {"play-004": PLAY}, {"play-004": bad}) + result = E.RatsEvolver().step(context(tmp_path, adapter)) + assert result.status == "done" and not result.extra["applied"] and "fails the template check" in result.summary + assert (adapter / "skills.json").read_bytes() == seed + shutil.rmtree(tmp_path / "material") + crashed = {"output": {**PLAY["output"], "iteration": None, "error": "RuntimeError: EGL"}} + material(tmp_path, {"play-004": crashed}, {}) + result = E.RatsEvolver().step(context(tmp_path, adapter)) + assert "handed back no state (RuntimeError: EGL)" in result.summary and (adapter / "skills.json").read_bytes() == seed + shutil.rmtree(tmp_path / "material") + link = tmp_path / "link" + link.mkdir() + (link / "adapter").symlink_to(handed_back(tmp_path / "elsewhere", [*PRIMITIVES, learned("x")], {})) + material(tmp_path, {"play-004": PLAY}, {"play-004": link}) + step = tmp_path / "material" / "step_0001" / "trajectories" / "play-004" + shutil.rmtree(step) + shutil.copytree(link, step, symlinks=True) # the trajectory's adapter/ is a link + result = E.RatsEvolver().step(context(tmp_path, adapter)) + assert "handed back no state" in result.summary and (adapter / "skills.json").read_bytes() == seed + + +def test_the_evolver_says_why_when_a_play_row_failed_to_run(tmp_path): + adapter = adapter_of(tmp_path) + seed = (adapter / "skills.json").read_bytes() + material(tmp_path, {"play-004": {"input": {"id": "play-004", "mode": "play"}, "status": "error", "output": None, + "error": "the agent's session failed: the row timed out after 60 s"}}, {}) + result = E.RatsEvolver().step(context(tmp_path, adapter)) + assert result.status == "done" and not result.extra["applied"] + assert result.summary.startswith("play-004: the play iteration did not run (the agent's session failed: the row") + assert (adapter / "skills.json").read_bytes() == seed + + +def test_the_evolver_refuses_a_step_of_more_than_one_play_iteration(tmp_path): + material(tmp_path, {"play-001": PLAY, "play-002": PLAY}, {}) + result = E.RatsEvolver().step(context(tmp_path, adapter_of(tmp_path))) + assert result.status == "failed" and "data.step_size: 1" in result.summary + shutil.rmtree(tmp_path / "material") + material(tmp_path, {"val-x": {"output": {"mode": "exec"}}}, {}) + assert "no play iteration" in E.RatsEvolver().step(context(tmp_path, adapter_of(tmp_path / "b"))).summary + + +# ---------- the judge and the example's configs ---------- + +def test_the_judge_scores_an_exec_row_by_its_trials_and_a_play_row_by_its_own_task(): + assert JUDGE.score({"first_state": 0, "trials": 10}, + {"mode": "exec", "successes": 7, "trials": 10, "ran": 10})["score"] == 0.7 + assert JUDGE.score({}, {"mode": "play", "iteration": 3, "success": True, "task": "stack", + "skills_learned": ["s"]})["feedback"] == "play iteration 3: 'stack' solved; skills learned: s" + assert JUDGE.score({}, {"mode": "play", "iteration": None, "error": "boom"})["score"] == 0.0 + assert JUDGE.score({}, None)["score"] == 0.0 + + +def test_the_example_configs_name_their_splits_and_the_training_run_they_evaluate(tmp_path): + Rw.write(tmp_path, Rw.build(50, Rw.states("43-49"), Rw.states("0-9"), Rw.states("0-49"))) + expect = {"train.yaml": ("train", "test", "rats-libero"), "val.yaml": ("train", "val", "rats-libero"), + "test.yaml": ("train", "test", "rats-libero"), "test_full.yaml": ("train", "test_full", "rats-libero"), + "smoke.yaml": ("smoke_train", "smoke_test", "smoke-rats-libero"), + "smoke_val.yaml": ("smoke_train", "smoke_val", "smoke-rats-libero")} + assert sorted(p.name for p in EXAMPLE.glob("*.yaml")) == sorted(expect) + for name, (train, test, run) in expect.items(): + config = Config.load(EXAMPLE / name, [f"data.tasks={tmp_path / 'tasks'}", + f"data.train={tmp_path / 'splits' / f'{train}.txt'}", + f"data.test={tmp_path / 'splits' / f'{test}.txt'}"]) + raw = yaml.safe_load((EXAMPLE / name).read_text()) + assert (raw["data"]["train"], raw["data"]["test"]) == (f"splits/{train}.txt", f"splits/{test}.txt"), name + assert raw["agent"]["name"] == "hermit.agent.evolver.methods.rats.actor:RatsActor" and raw["template"] == "rats" + assert raw["evolver"]["name"] == "rats" and config.run_name() == run, name + bench = Benchmark.from_config(config) + assert bench.overlaps() == [], name + assert {t.given()["split"] for t in bench.split("test")} == {test}, name + assert (EXAMPLE / "env_configs" / "rats_libero_pro_graspnet.yaml").is_file() + + +# ---------- through the Trainer, in the actor's sandbox ---------- + +@pytest.mark.skipif(not bwrap_works(), reason="needs bubblewrap with unprivileged user namespaces (CONTRIBUTING.md)") +def test_a_run_plays_through_the_trainer_in_a_sandbox_and_evaluates_its_final_library(tmp_path, provider, + monkeypatch): + """The smoke config as launch.sh runs it, on the stand-in: one play iteration through the Trainer, the Evolver's + update, then the test row on the final library; RATs in the actor's sandbox, its model calls metered on the + host.""" + monkeypatch.setattr(S, "gpu_args", lambda gpus: []) # no GPU here: its binding is the edge + root = fake_rats(tmp_path / "RATs") + here = tmp_path / "rows" + Rw.write(here, Rw.build(1, Rw.states("43"), Rw.states("0"), Rw.states("0"))) + closed = socket.socket() + closed.bind(("127.0.0.1", 0)) + closed.listen() + monkeypatch.setenv("FAKE_PROVIDER_KEY", "sk-hermit-test-key") + config = Config.load(EXAMPLE / "smoke.yaml", [ + f"data.tasks={here / 'tasks'}", f"data.train={here / 'splits' / 'smoke_train.txt'}", + f"data.test={here / 'splits' / 'smoke_test.txt'}", f"trainer.output_dir={tmp_path / 'runs'}", + f"trainer.tree_dir={tmp_path / 'trees'}", f"agent.params.rats_root={root}", + f"agent.params.python={sys.executable}", "agent.params.gpus=0", f"agent.params.logs={tmp_path / 'logs'}", + f"agent.params.scratch={tmp_path / 'scratch'}", + f"agent.params.model={{base_url: '{provider.url}', model: m-1, api_key_env: FAKE_PROVIDER_KEY}}", + "agent.params.price={input: 1.0, cached_input: 0.5, output: 2.0}", + f"agent.params.env={{FAKE_RATS_PROBE: '1', FAKE_RATS_CLOSED_PORT: '{closed.getsockname()[1]}'}}"]) + try: + Trainer(config, log=lambda *_: None).train() + run = tmp_path / "runs" / "smoke-rats-libero" + [step] = [json.loads(l) for l in (run / "steps.jsonl").read_text().splitlines()] + assert step["status"] == "done" and "new: place_on_1" in step["evolver"]["summary"], step + final = run / "checkout" + assert [s["name"] for s in json.loads((final / "skills.json").read_text()) if not s["is_primitive"]] == \ + ["place_on_1"] + assert json.loads((final / "state" / "iteration_001.json").read_text())["task_proposal"]["_playtime"] is True + [probe] = (tmp_path / "scratch").glob("play-001-*/rats/probe-1.json") + seen = json.loads(probe.read_text()) + assert (seen["git"], seen["outputs"], seen["authors_library"]) == ([], [], 0) # hidden + assert seen["held_out"] == [] and seen["original"] == ["a.bddl"] # play sees no test suite + assert seen["primitives"] > 0 and not seen["reached_closed_port"] and not seen["wrote_rats_root"] + assert not seen["library_frozen"] # play updates its copy of L + assert "FAKE_PROVIDER_KEY" not in seen["env"] and "sk-hermit-test-key" not in json.dumps(seen["env"]) + assert {seen["env"][k] for k in A.ROLE_MODELS} == {"m-1"} + # every call went through the host's meter to the configured model, with the provider's key added there + assert provider.requests and {r["body"]["model"] for r in provider.requests} == {"m-1"} + assert {r["headers"]["Authorization"] for r in provider.requests} == {"Bearer sk-hermit-test-key"} + assert {r["body"].get("reasoning_effort") for r in provider.requests} == {"medium"} + assert provider.media and all(m == ["data:image/png"] for m in provider.media) # no video by default + calls = len(provider.requests) # 10 + 5 tokens each, priced + assert step["budget_after"]["tokens"]["rollout"] == 15 * calls + assert step["rollout"]["cost_usd"] == pytest.approx(calls * (10 * 1.0 + 5 * 2.0) / 1e6) + result = evaluate(config, "final", log=lambda *_: None) + assert result["mean_score"] == 1.0 + [probe] = (tmp_path / "scratch").glob("smoke-test-*/rats/probe-1.json") + seen = json.loads(probe.read_text()) + assert seen["held_out"] == ["b.bddl"] and seen["library_frozen"] # it reads the suite, not writes L + [trial] = (tmp_path / "logs").glob("smoke-test-*/rats/iteration_001.json") + assert json.loads(trial.read_text())["library"] == ["place_on_1"] # the final library, frozen + assert json.loads((final / "skills.json").read_text())[-1]["name"] == "place_on_1" + finally: + closed.close() + + +@pytest.mark.skipif(not bwrap_works(), reason="needs bubblewrap with unprivileged user namespaces (CONTRIBUTING.md)") +def test_a_row_that_times_out_or_crashes_keeps_what_finished_and_says_why(tmp_path, provider, monkeypatch): + """A row stopped at its timeout keeps the trials RATs finished (the runner writes them as they end); a row of + which nothing ran is a failed run (`session_failed`: an error in the records, its cost and log kept), not a + zero of the method's.""" + monkeypatch.setattr(S, "gpu_args", lambda gpus: []) + root = fake_rats(tmp_path / "RATs") + params = {"rats_root": str(root), "python": sys.executable, "gpus": [0], "logs": str(tmp_path / "logs"), + "scratch": str(tmp_path / "scratch"), "model": {"base_url": provider.url, "model": "m-1"}, + "env": {"FAKE_RATS_HANG": "2"}, "timeout_s": 8} + row = {"id": "test-libero_goal_swap-t01", "mode": "exec", "suite": "libero_goal_swap", "task_id": 1, + "first_state": 0, "trials": 3} + out = A.RatsActor(params, tmp_path).run(row, None) + assert out.output["timed_out"] and out.output["error"] == "the row timed out after 8 s" + assert (out.output["successes"], out.output["ran"], out.output["trials"]) == (1, 1, 3) + assert "session_failed" not in out.extra and out.tokens == 15 # the finished trial's call counted + assert JUDGE.score(row, out.output)["feedback"].startswith("1/3 trials in init states 0-2 (2 did not run)") + (root / "scripts" / "run_rats.py").write_text("def main():\n raise SystemExit(3)\n") + out = A.RatsActor({**params, "env": {}}, tmp_path).run(row, None) + assert out.output["ran"] == 0 and out.output["error"] == "run_rats.py exited with 3" + assert out.extra["session_failed"].startswith("run_rats.py exited with 3 (see ") diff --git a/tests/selection.py b/tests/selection.py index 37f93bde..e42aa3fd 100644 --- a/tests/selection.py +++ b/tests/selection.py @@ -48,6 +48,7 @@ def fnmatch(path: str, pattern: str) -> bool: "examples/*/reharness/*"], "rrsi_adapter": ["hermit/agent/evolver/methods/rrsi_adapter/*", "hermit/adapter/templates/rrsi_adapter/*", "examples/*/rrsi_adapter/*"], + "rats": ["hermit/agent/evolver/methods/rats/*", "hermit/adapter/templates/rats/*", "examples/*/rats/*"], } # group -> the other groups whose tests read its files (tests/core/test_selection.py finds a method's tests naming # another group's directory) From 797ac85e9fd835b0999357f6b2a4303863a8f226 Mon Sep 17 00:00:00 2001 From: iamziyuzhao Date: Sat, 28 Nov 2026 23:58:52 -0500 Subject: [PATCH 02/12] RATs tests: name the effort test by the behaviour it holds Co-Authored-By: Claude Opus 5.5 --- tests/methods/rats/test_rats.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/methods/rats/test_rats.py b/tests/methods/rats/test_rats.py index 82c83bd1..2317c5f6 100644 --- a/tests/methods/rats/test_rats.py +++ b/tests/methods/rats/test_rats.py @@ -541,7 +541,7 @@ def test_an_exec_rows_trials_are_its_iterations_and_one_that_never_ran_fails(tmp "1/3 trials in init states 7-9 (1 did not run)" -def test_the_actor_sends_the_rows_reasoning_effort_unless_told_otherwise(tmp_path, monkeypatch): +def test_the_actor_sends_the_first_evaluations_reasoning_effort_unless_told_otherwise(tmp_path, monkeypatch): """RATs' generic request form carries no reasoning effort: the actor adds the first evaluation's (medium), or the one given, to each request; false sends none.""" monkeypatch.setenv("FIREWORKS_API_KEY", "x") From 3a996c59075bf6fbbd4c24d14a4b42cdae80ca85 Mon Sep 17 00:00:00 2001 From: iamziyuzhao Date: Sun, 29 Nov 2026 00:26:33 -0500 Subject: [PATCH 03/12] RATs: render with Mesa on the CPU when the host's GPUs run CUDA work The first evaluation's rows stopped on RATs' get_real_depth_map assertion: on this host's H200s, other processes' CUDA work (here GraspGen's, and other users' jobs) silently invalidates a live NVIDIA EGL context's reads, so the depth maps RATs reads back are garbage. RATs' own setup renders with NVIDIA's EGL; the actor still does by default, and now also takes `render: cpu` (launch.sh: RATS_RENDER=cpu): - Mesa is the only EGL vendor (__EGL_VENDOR_LIBRARY_FILENAMES, the glvnd vendor file), RATs' process sees no CUDA device and binds no GPU, and llvmpipe's threads are bounded (render_threads, default 2). - Inside the sandbox the runner points MuJoCo's and robosuite's EGL backends at Mesa's software device as the sandbox lists it (MUJOCO_EGL_DEVICE_ID): the index differs from the host's. - Checked in the actor's real sandbox: a LIBERO scene renders with depth in [0, 1]. The method page also says what final against none compares: a play library carries play's primitive records (the full API's 12, three of which the reduced API lacks) and the no-library condition the reduced API's 26, as in RATs' own evaluation recipe. Tests: the render settings, and a cpu row in the sandbox that binds no GPU and sets the device (skipped without Mesa's EGL). Co-Authored-By: Claude Opus 5.5 --- docs/methods/rats.md | 19 +++++-- examples/libero/rats/README.md | 7 ++- examples/libero/rats/launch.sh | 12 +++-- hermit/agent/evolver/methods/rats/actor.py | 44 ++++++++++++---- hermit/agent/evolver/methods/rats/runner.py | 28 ++++++++++ tests/methods/rats/test_rats.py | 57 +++++++++++++++++++++ 6 files changed, 150 insertions(+), 17 deletions(-) diff --git a/docs/methods/rats.md b/docs/methods/rats.md index 23ff068b..4074ad6d 100644 --- a/docs/methods/rats.md +++ b/docs/methods/rats.md @@ -59,7 +59,8 @@ RATs at three seams only: 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 RATs' vision services on their loopback ports (SAM3 8114, -Contact-GraspNet 8115, PyRoki 8116, GraspGen 5556, Molmo 8122), and sees one GPU. It hides what no row reads: the +Contact-GraspNet 8115, PyRoki 8116, GraspGen 5556, Molmo 8122), and sees one GPU (none with `render: cpu`). It +hides what no row reads: the checkout's git history, its `outputs/` and logs, 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'. @@ -133,8 +134,14 @@ At the pinned commit `--no-skill-reuse` stops storing extracted skills and the s 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"). RATs' `docs/evaluation.md` -runs five trials a task; `RATS_ROWS_ARGS="--test-states 0-4"` writes that test split. +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 @@ -164,7 +171,10 @@ vision calls are dropped; `true` for a model that takes video), `price` (overrid 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; a play row refuses those that name its scene or output, or put the test tasks into play), `env` (more variables for RATs' process; a -secret-looking name is refused), `service_ports`, `robot_descriptions` (the cache of the robot descriptions RATs' +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), `mesa_egl_vendor` +(Mesa's glvnd vendor file), `service_ports`, `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`, `trial_timeout_s`, `call_timeout_s`, `max_retries`. @@ -185,6 +195,7 @@ attempt artifacts), `timeout_s`, `trial_timeout_s`, `call_timeout_s`, `max_retri | Videos in vision calls | the verifiers and the diagnoser attach the attempt's videos (Gemini takes them) | dropped with RATs' `_strip_videos_from_messages`, images and text kept (`video: true` keeps them) | GLM 5.3 Flash refuses video input (HTTP 400); RATs does the same for its fallback models; a deviation | | 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) | 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 | | Vision services | auto-launched from the env config | started once by `serve.sh` from RATs' own server modules, shared by the rows | concurrent rows share them; acceptable | | Molmo (8122) | a vLLM-served pointing model, set up with the MolmoSpaces runtime; `docs/setup.md`: the LIBERO-PRO workflows do not require it | not started; the LIBERO API's Molmo pointing falls back to SAM3's text prompt | as RATs' LIBERO setup | | 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 | diff --git a/examples/libero/rats/README.md b/examples/libero/rats/README.md index 4b6a1b59..4a14246d 100644 --- a/examples/libero/rats/README.md +++ b/examples/libero/rats/README.md @@ -79,7 +79,11 @@ uv sync --frozen --active --extra libero --extra contactgraspnet MolmoSpaces runtime and says the LIBERO-PRO workflows do not require it; the LIBERO API then falls back to SAM3's text prompt (its log shows the failed requests). - **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. + 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. ## Run @@ -94,6 +98,7 @@ 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 ``` diff --git a/examples/libero/rats/launch.sh b/examples/libero/rats/launch.sh index ef798b25..46454c93 100755 --- a/examples/libero/rats/launch.sh +++ b/examples/libero/rats/launch.sh @@ -11,7 +11,8 @@ # RATS_SMOKE=1 ./launch.sh train | test | val # smoke.yaml, smoke_val.yaml # # Variables: RATS_ROOT (RATs' checkout with its .venv, README.md), RATS_GPUS (the GPUs RATs renders LIBERO on), -# RATS_GRASP (graspgen, the default: RATs' LIBERO-PRO config; graspnet: env_configs/rats_libero_pro_graspnet.yaml), +# RATS_RENDER (gpu, the default: NVIDIA's EGL on those GPUs; cpu: Mesa's llvmpipe through EGL, no GPU, for a host +# whose GPUs run other processes' CUDA work, README.md), RATS_GRASP (graspgen, the default: RATs' LIBERO-PRO config; graspnet: env_configs/rats_libero_pro_graspnet.yaml), # RATS_OUT (the runs, default runs/ here: the rows, the Trainer's records, the actor's logs and RATs' output # directories), RATS_ROWS_ARGS (rows.py's options: --play, --tasks, --val-states, --test-states, --full-states), # HERMIT_PYTHON (default python), FIREWORKS_API_KEY (the configs' model; it stays in Hermit's process). Any further @@ -23,7 +24,6 @@ cd "$HERE" RATS_ROOT="$(cd "$RATS_ROOT" && pwd)" [[ -x "$RATS_ROOT/.venv/bin/python" && -f "$RATS_ROOT/scripts/run_rats.py" ]] \ || { echo "$RATS_ROOT: not a RATs checkout with its .venv (README.md)" >&2; exit 1; } -: "${RATS_GPUS:?set RATS_GPUS to the GPUs RATs renders LIBERO on, e.g. 1,3}" # The RATs commit this example was written against; another one is run, but named. PINNED=1fd2ef56857cfde6d5d815fc49a9fe9b0a531beb ACTUAL="$(git -C "$RATS_ROOT" rev-parse HEAD 2>/dev/null || echo unknown)" @@ -48,6 +48,12 @@ else fi ! grep -q "model: fireworks/" "$CONFIG" || : "${FIREWORKS_API_KEY:?set FIREWORKS_API_KEY}" EXTRA=() +case "${RATS_RENDER:-gpu}" in + gpu) : "${RATS_GPUS:?set RATS_GPUS to the GPUs RATs renders LIBERO on, e.g. 1,3 (or RATS_RENDER=cpu)}" + EXTRA+=("agent.params.gpus=$RATS_GPUS") ;; + cpu) EXTRA+=("agent.params.render=cpu") ;; + *) echo "RATS_RENDER is gpu or cpu" >&2; exit 2 ;; +esac case "${RATS_GRASP:-graspgen}" in graspgen) GRASP=5556 ;; graspnet) GRASP=8115; EXTRA+=("agent.params.exec_config=env_configs/rats_libero_pro_graspnet.yaml") ;; @@ -88,5 +94,5 @@ RUN="$(sed -n 's/^ run_name: *\([^ #]*\).*/\1/p' "$CONFIG" | head -1)" if [[ "$MODE" == train ]]; then CMD=train; DIR="$OUT"; else CMD=eval; DIR="$OUT/$MODE"; fi exec "$HERMIT" -m hermit.cli "$CMD" --config "$CONFIG" "data.tasks=$ROWS/tasks" \ "data.train=$ROWS/splits/$(split train)" "data.test=$ROWS/splits/$(split test)" "agent.params.rats_root=$RATS_ROOT" \ - "agent.params.gpus=$RATS_GPUS" "agent.params.logs=$DIR/actor-logs" "agent.params.scratch=$DIR/rats" \ + "agent.params.logs=$DIR/actor-logs" "agent.params.scratch=$DIR/rats" \ "trainer.output_dir=$DIR" "trainer.tree_dir=$OUT/trees/$RUN" ${EXTRA[@]+"${EXTRA[@]}"} "$@" diff --git a/hermit/agent/evolver/methods/rats/actor.py b/hermit/agent/evolver/methods/rats/actor.py index 48cb4770..e9e18326 100644 --- a/hermit/agent/evolver/methods/rats/actor.py +++ b/hermit/agent/evolver/methods/rats/actor.py @@ -18,7 +18,7 @@ The sandbox shows RATs' checkout and venv read-only, less what no row may read (its git history, its runs, the skill libraries the authors learned, and in play every LIBERO-PRO suite besides the original LIBERO ones), writes only the row's RATs output directory, reaches no network but the model endpoint and RATs' vision services on their loopback -ports, and sees one GPU. Every model call of RATs goes to an endpoint of this process (hermit.agent.base.endpoint, over +ports, and sees one GPU (none with `render: cpu`, which renders with Mesa's llvmpipe through EGL). Every model call of RATs goes to an endpoint of this process (hermit.agent.base.endpoint, over one Direct call each, Layer 1) that sends it to the run's model with the provider's key, which the sandbox never holds, and counts its tokens and cost. @@ -49,6 +49,8 @@ EXEC_CONFIG = "env_configs/libero/rats_libero_pro_nonpriv.yaml" # RATs' vision services on their fixed loopback ports: SAM3, Contact-GraspNet, PyRoki, GraspGen, Molmo SERVICE_PORTS = (8114, 8115, 8116, 5556, 8122) +# Mesa's EGL vendor file (glvnd): as the only EGL vendor, RATs' MuJoCo renders with Mesa's llvmpipe on the CPU +MESA_EGL_VENDOR = "/usr/share/glvnd/egl_vendor.d/50_mesa.json" # What of RATs' checkout no row reads: its git history (and the submodules' under it), its runs and their logs, the # libraries its authors learned (capx-baseline's preserved ones; skill_library's learned files are found by content), # LIBERO's demonstrations when downloaded @@ -272,6 +274,16 @@ def _rats_model(self, spec: dict) -> tuple[str, str]: name = self.params.get("rats_model") or (f"openai/{spec['model']}" if dialect == "openai" else spec["model"]) return str(name), dialect + def _render(self) -> str: + """Where RATs' MuJoCo renders: `gpu` (RATs' setup: NVIDIA's EGL on the row's GPU) or `cpu` (Mesa's llvmpipe + through EGL, 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 = str(self.params.get("render") or "gpu") + if render not in ("gpu", "cpu"): + raise ValueError(f"agent.params.render: gpu (NVIDIA's EGL on the row's GPU) or cpu (Mesa's llvmpipe " + f"through EGL), not {render!r}") + return render + # ---- one row ---- def run(self, task: dict, adapter: Path | None, environment=None) -> RunOutput: @@ -299,18 +311,19 @@ def run(self, task: dict, adapter: Path | None, environment=None) -> RunOutput: args, shown = self._prepare(task, mode, adapter, root, out, scratch) spec = self._model() rats_model, dialect = self._rats_model(spec) + render = self._render() from hermit.agent.base.endpoint import ChatEndpoint from hermit.agent.model.direct import Direct from hermit.agent.model.llm import ChatClient meter = _Meter(ChatClient.from_spec(spec, max_retries=int(p.get("max_retries", 4)), retry_wait=float(p.get("retry_wait", 4.0)), retry_wait_max=60.0, timeout=float(p.get("call_timeout_s", 900)))) - gpus = self.gpus() - gpu = gpus.take() + gpus = self.gpus() if render == "gpu" else None # cpu: no GPU, no GPU slot + gpu = gpus.take() if gpus is not None else None endpoint = held = None try: endpoint = ChatEndpoint(Direct({}, meter)).start() - env, cache = self._environment(mode, root, python, home, endpoint.url, rats_model, dialect) + env, cache = self._environment(mode, root, python, home, endpoint.url, rats_model, dialect, render) command = [str(python), str(RUNNER), mode, "--rats-root", str(root), "--out", str(out), *args] held, command, env = self._confine(command, mode=mode, root=root, python=python, env=env, writable=[out, home], readable=[*shown, *cache], home=home, gpu=gpu, @@ -322,7 +335,8 @@ def run(self, task: dict, adapter: Path | None, environment=None) -> RunOutput: finally: if endpoint is not None: endpoint.close() - gpus.give(gpu) + if gpus is not None: + gpus.give(gpu) if held is not None: held.close() shutil.rmtree(home, ignore_errors=True) @@ -398,10 +412,10 @@ def _rats_config(self, value, default: str, root: Path) -> tuple[str, list[Path] return str(own), [own] def _environment(self, mode: str, root: Path, python: Path, home: Path, url: str, rats_model: str, - dialect: str) -> tuple[dict, list[Path]]: + dialect: str, render: str = "gpu") -> tuple[dict, list[Path]]: """RATs' runtime environment (its docs/setup.md and the batch driver's), and nothing of this process's: no - key, no token; and what the sandbox must show for it besides the checkout (a robot-description cache of the - run's own).""" + key, no token; and what the sandbox must show for it besides the checkout (a robot-description cache or a + Mesa vendor file of the run's own).""" libero = root / LIBERO_FILES (home / ".libero").mkdir(parents=True, exist_ok=True) # LIBERO asks for its paths on stdin without this file (RATs' docs/setup.md) @@ -420,6 +434,18 @@ def _environment(self, mode: str, root: Path, python: Path, home: Path, url: str cache = self.path(os.path.expandvars(str(self.params.get("robot_descriptions") or (root / ".cache" / "robot_descriptions")))) env["ROBOT_DESCRIPTIONS_CACHE"] = str(cache) + shown = [] if cache.is_relative_to(root) or not cache.exists() else [cache] + if render == "cpu": + # Mesa the only EGL vendor; no CUDA device, so robosuite takes MUJOCO_EGL_DEVICE_ID, which the runner + # sets to Mesa's software device as the sandbox lists it; llvmpipe's threads bounded + vendor = self.path(os.path.expandvars(str(self.params.get("mesa_egl_vendor") or MESA_EGL_VENDOR))) + if not vendor.is_file(): + raise FileNotFoundError(f"agent.params.render: cpu renders with Mesa's EGL, whose vendor file {vendor} " + "is missing (install Mesa's EGL, or render on a GPU)") + env.update({"__EGL_VENDOR_LIBRARY_FILENAMES": str(vendor), "CUDA_VISIBLE_DEVICES": "", + "HERMIT_RATS_RENDER": "cpu", "LP_NUM_THREADS": str(int(self.params.get("render_threads", 2)))}) + if not vendor.is_relative_to("/usr"): # the sandbox shows /usr + shown.append(vendor) if mode == "exec": env["RATS_VERIFIER_STRICT_BENCHMARK"] = "1" # only the native task_completed counts (docs/evaluation.md) for name in ROLE_MODELS: @@ -429,7 +455,7 @@ def _environment(self, mode: str, root: Path, python: Path, home: Path, url: str raise ValueError(f"agent.params.env: {key} looks like a secret; RATs' process holds none (its model " "calls go through the actor's endpoint)") env[str(key)] = str(value) - return env, ([] if cache.is_relative_to(root) or not cache.exists() else [cache]) + return env, shown def _confine(self, command: list[str], *, mode: str, root: Path, python: Path, env: dict, writable: list[Path], readable: list[Path], home: Path, gpu: int | None, port: int, log: Path): diff --git a/hermit/agent/evolver/methods/rats/runner.py b/hermit/agent/evolver/methods/rats/runner.py index d942b1ee..9582d72a 100644 --- a/hermit/agent/evolver/methods/rats/runner.py +++ b/hermit/agent/evolver/methods/rats/runner.py @@ -25,6 +25,9 @@ from state/loop.json before it and saved after it; everything else RATs carries already lives in its output directory, which its own --resume reads. +HERMIT_RATS_RENDER=cpu (the actor's `render: cpu`, Mesa the only EGL vendor) points MuJoCo's EGL backend at Mesa's +software device as this sandbox lists it (MUJOCO_EGL_DEVICE_ID): where RATs renders, not what it does. + O/hermit/result.json holds what each iteration returned, as LifelongLoop._run_one_iteration returned it in this process. This file runs under RATs' Python (3.10) and imports nothing of Hermit. """ @@ -82,6 +85,29 @@ def query_llm(messages, *args, **kwargs): base_agent.query_llm = query_llm +def software_egl_device() -> int: + """The index of Mesa's software (llvmpipe) EGL device in EGL's device list (eglQueryDevicesEXT), the numbering + MuJoCo's and robosuite's EGL backends take from MUJOCO_EGL_DEVICE_ID.""" + import ctypes + egl = ctypes.CDLL("libEGL.so.1") + egl.eglGetProcAddress.argtypes = [ctypes.c_char_p] + egl.eglGetProcAddress.restype = ctypes.c_void_p + devices, string = egl.eglGetProcAddress(b"eglQueryDevicesEXT"), egl.eglGetProcAddress(b"eglQueryDeviceStringEXT") + if not devices or not string: + raise RuntimeError("render: cpu, but EGL has no device enumeration (EGL_EXT_device_enumeration)") + query_devices = ctypes.CFUNCTYPE(ctypes.c_uint, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p), + ctypes.POINTER(ctypes.c_int))(devices) + query_string = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_void_p, ctypes.c_int)(string) + count = ctypes.c_int() + query_devices(0, None, ctypes.byref(count)) + handles = (ctypes.c_void_p * max(count.value, 1))() + query_devices(count.value, handles, ctypes.byref(count)) + for index in range(count.value): + if b"EGL_MESA_device_software" in (query_string(handles[index], 0x3055) or b""): # EGL_EXTENSIONS + return index + raise RuntimeError("render: cpu, but EGL lists no Mesa software device (Mesa's EGL with llvmpipe)") + + # ---------- seams 2 and 3: the loop ---------- def hook_loop(first_iteration: int | None, out: Path, results: list, flush=lambda: None) -> None: @@ -233,6 +259,8 @@ def main(argv=None) -> int: (out / "hermit").mkdir(parents=True, exist_ok=True) os.chdir(root) # RATs' paths are relative to its checkout sys.path.insert(0, str(root)) + if os.environ.get("HERMIT_RATS_RENDER") == "cpu": + os.environ["MUJOCO_EGL_DEVICE_ID"] = str(software_egl_device()) route_models(os.environ["HERMIT_RATS_URL"], os.environ.get("HERMIT_RATS_DIALECT", "chat"), video=os.environ.get("HERMIT_RATS_VIDEO", "1") != "0") results: list = [] diff --git a/tests/methods/rats/test_rats.py b/tests/methods/rats/test_rats.py index 2317c5f6..9f3e642f 100644 --- a/tests/methods/rats/test_rats.py +++ b/tests/methods/rats/test_rats.py @@ -561,6 +561,31 @@ def extra(params): assert layered["extra_body"] == {"reasoning_effort": "low"} and "effort" not in layered +def test_the_actor_renders_with_mesa_on_the_cpu_only_when_told(tmp_path): + """`render: cpu` (a host whose GPUs run other processes' CUDA work, which on Hopper GPUs silently invalidates a + live EGL context's reads): Mesa the only EGL vendor, no CUDA device, llvmpipe's threads bounded; RATs' own + NVIDIA EGL otherwise.""" + root = fake_rats(tmp_path / "RATs") + home = tmp_path / "home" + vendor = tmp_path / "50_mesa.json" + vendor.write_text("{}") + + def env_of(params, render): + actor = A.RatsActor({"rats_root": str(root), **params}, tmp_path) + return actor._environment("exec", root, Path(sys.executable), home, "http://127.0.0.1:1/v1", "m", "chat", + actor._render() if render is None else render) + env, shown = env_of({"mesa_egl_vendor": str(vendor), "render": "cpu"}, None) + assert (env["__EGL_VENDOR_LIBRARY_FILENAMES"], env["CUDA_VISIBLE_DEVICES"], env["HERMIT_RATS_RENDER"], + env["LP_NUM_THREADS"]) == (str(vendor), "", "cpu", "2") + assert vendor in shown # a vendor file outside /usr: shown read-only + env, _ = env_of({}, None) + assert not {"__EGL_VENDOR_LIBRARY_FILENAMES", "CUDA_VISIBLE_DEVICES", "HERMIT_RATS_RENDER"} & set(env) + with pytest.raises(FileNotFoundError, match="Mesa's EGL"): + env_of({"mesa_egl_vendor": str(tmp_path / "missing.json")}, "cpu") + with pytest.raises(ValueError, match="agent.params.render"): + A.RatsActor({"render": "vulkan"}, tmp_path)._render() + + def test_the_actor_refuses_a_row_or_a_setting_that_would_leak_or_misplace_a_run(tmp_path): root = fake_rats(tmp_path / "RATs") base = {"rats_root": str(root), "python": sys.executable, "logs": str(tmp_path / "logs"), @@ -800,3 +825,35 @@ def test_a_row_that_times_out_or_crashes_keeps_what_finished_and_says_why(tmp_pa out = A.RatsActor({**params, "env": {}}, tmp_path).run(row, None) assert out.output["ran"] == 0 and out.output["error"] == "run_rats.py exited with 3" assert out.extra["session_failed"].startswith("run_rats.py exited with 3 (see ") + + +def _mesa_software_egl() -> bool: + """Whether this host's EGL lists Mesa's software device with Mesa the only vendor (the runner's lookup).""" + if not Path(A.MESA_EGL_VENDOR).is_file(): + return False + found = subprocess.run([sys.executable, "-c", "import runner; print(runner.software_egl_device())"], + cwd=str(A.RUNNER.parent), capture_output=True, text=True, timeout=60, + env={"PATH": os.environ["PATH"], "__EGL_VENDOR_LIBRARY_FILENAMES": A.MESA_EGL_VENDOR}) + return found.returncode == 0 and found.stdout.strip().isdigit() + + +@pytest.mark.skipif(not bwrap_works(), reason="needs bubblewrap with unprivileged user namespaces (CONTRIBUTING.md)") +@pytest.mark.skipif(not _mesa_software_egl(), reason="needs Mesa's EGL with its software (llvmpipe) device") +def test_a_cpu_rendered_row_binds_no_gpu_and_renders_on_mesas_software_device(tmp_path, provider, monkeypatch): + """With `render: cpu` the row needs no GPU and the sandbox binds none; inside it the runner points MuJoCo's EGL + backend at Mesa's software device as the sandbox lists it.""" + bound = [] + monkeypatch.setattr(S, "gpu_args", lambda gpus: bound.append(list(gpus)) or []) + root = fake_rats(tmp_path / "RATs") + params = {"rats_root": str(root), "python": sys.executable, "render": "cpu", "logs": str(tmp_path / "logs"), + "scratch": str(tmp_path / "scratch"), "model": {"base_url": provider.url, "model": "m-1"}, + "env": {"FAKE_RATS_PROBE": "1"}} + row = {"id": "test-libero_goal_swap-t01", "mode": "exec", "suite": "libero_goal_swap", "task_id": 1, + "first_state": 0, "trials": 1} + out = A.RatsActor(params, tmp_path).run(row, None) + assert out.output["ran"] == 1 and not out.output["error"] and out.extra["rats"]["gpu"] is None + assert all(g == [] for g in bound) + [probe] = (tmp_path / "scratch").glob("test-*/rats/probe-1.json") + env = json.loads(probe.read_text())["env"] + assert env["MUJOCO_EGL_DEVICE_ID"].isdigit() and env["CUDA_VISIBLE_DEVICES"] == "" + assert env["__EGL_VENDOR_LIBRARY_FILENAMES"] == A.MESA_EGL_VENDOR From f25700f7c9f5981c1adf8f2773ac6bd3627de748 Mon Sep 17 00:00:00 2001 From: iamziyuzhao Date: Sun, 29 Nov 2026 01:19:59 -0500 Subject: [PATCH 04/12] RATs: score test trials on LIBERO's own check, confine the services, carry the play scene The post-PR audit of 476a45a found two P1 and four P2 defects; this fixes them and its P3s. - Seam 4: in exec, 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 and visual verifiers' results as an uncounted `vote`. RATs' docs set RATS_VERIFIER_STRICT_BENCHMARK=1 for this, but no code at 1fd2ef5 reads it, so a VLM-only success counted. A trial now counts when RATs' verdict and its last verification's native check both say success. - The services: a row's sandbox reaches only the ports its RATs config names (api_servers: play 8114/8115/8116, test 8114/8116 and the grasp service; never Molmo's 8122). serve.sh starts every service with a clean environment (env -i and a short list, no key or token), and GraspGen through graspgen-python, whose graspgen_guard.py refuses the one request msgpack_numpy would unpickle (an object array). - Without video, every vision call is built from images as RATs builds it without a video (the visual verifier's sampled frames, the feedback generator's first and last frames, the per-step verifier's images, the diagnoser's filmstrip), instead of a text-only call after the strip. - RATs' parallel sub-agent workers, which it starts as processes of their own, start through `runner.py worker` and reach the endpoint. - The play scene the last iteration left (its generated BDDL and custom verifier) is saved in state/scene/ and rebuilt with RATs' EnvironmentCreator in the next process, with the bootstrap task's name in loop.json; the template takes state/scene/. Validation leaves out play's bootstrap task, libero_spatial task 0 (39 rows). - Provider key files (.env, .openrouterkey) are hidden; play also hides LIBERO-PRO's perturbation specs (libero_ood/, which repeat the test `_task` instructions). - RATs' own parser reads a row's arguments: rats_args that change the row in any spelling (abbreviations, --flag=value) refuse it before RATs runs. - The provider call is bounded like RATs' request (200 s); the effort comment names the first-evaluation row (RATs' default.yaml says low); the rows cache key includes rows.py; the docs say a run with failed play rows ends short of 50 iterations, that RATs' docs' auto-launch of the services is not what run_rats.py does, and how the per-row read-only library differs from the batch driver's shared file. - Tests: the stand-in now has RATs' Verifier vote and video choice, its worker processes, a generated scene behind RATs' wrappers and build_parser; new tests for each fix, the template's scene, GraspGen's guard and the services' clean environment. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- docs/methods/rats.md | 142 ++++-- examples/libero/rats/README.md | 48 +- examples/libero/rats/graspgen-python | 6 + examples/libero/rats/graspgen_guard.py | 45 ++ examples/libero/rats/judge.py | 8 +- examples/libero/rats/launch.sh | 8 +- examples/libero/rats/rows.py | 18 +- examples/libero/rats/serve.sh | 27 +- examples/libero/rats/smoke.yaml | 2 +- examples/libero/rats/smoke_val.yaml | 2 +- examples/libero/rats/test.yaml | 2 +- examples/libero/rats/test_full.yaml | 2 +- examples/libero/rats/train.yaml | 10 +- examples/libero/rats/val.yaml | 9 +- .../adapter/templates/rats/.hermit/EVOLVER.md | 3 +- .../templates/rats/.hermit/adapter.yaml | 6 +- .../adapter/templates/rats/.hermit/check.py | 42 +- hermit/agent/evolver/methods/rats/actor.py | 93 ++-- hermit/agent/evolver/methods/rats/runner.py | 309 +++++++++++- tests/methods/rats/test_rats.py | 467 ++++++++++++++++-- 21 files changed, 1063 insertions(+), 193 deletions(-) create mode 100755 examples/libero/rats/graspgen-python create mode 100644 examples/libero/rats/graspgen_guard.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2784056c..50318558 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -157,9 +157,10 @@ Changes are grouped by software version. Entries under Unreleased describe work (`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 (init states 43-49), LIBERO-PRO as test (the - paper's Table 1, 600 trials; and all eight suites in all 50 init states), each split its own config, with - `launch.sh` and `serve.sh` for RATs' vision services ([RATs](docs/methods/rats.md)). + 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/methods/rats.md b/docs/methods/rats.md index 4074ad6d..25ee3ff4 100644 --- a/docs/methods/rats.md +++ b/docs/methods/rats.md @@ -27,7 +27,7 @@ agent: 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 (RATs' own default) + 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} @@ -38,38 +38,62 @@ so it is a checkout beside Hermit, as ASPIRE's is, not a dependency group: the e (`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 three seams only: +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' 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, RATs' own `llm_reasoning_effort`, which RATs sends only in its OpenAI form). RATs' verifiers and - diagnoser attach the attempt's videos, which Gemini takes; for a model that takes none (`agent.params.video: - false`, the default) the runner drops them from every call with RATs' own `_strip_videos_from_messages`, as RATs - does when it falls back to a model without video, and the images and text stay. + `_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' + verifiers, feedback generator and diagnoser attach the attempt's videos, which Gemini takes; 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 eight sampled frames, the feedback generator's first and last + frames, 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 (the curation and skill-proposal counters, the curator's rolling history, the failure memory's - distillation counter) is restored from `state/loop.json` before the iteration and saved after it; everything else - RATs carries already lives in its output directory, which its own `--resume` reads. + 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, and a row whose +`rats_args` change what the row is (its scene, task, output, library, iterations or frozen flags; in play the test +tasks' descriptions), in any spelling the parser takes, is refused. 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 RATs' vision services on their loopback ports (SAM3 8114, -Contact-GraspNet 8115, PyRoki 8116, GraspGen 5556, Molmo 8122), and sees one GPU (none with `render: cpu`). It -hides what no row reads: the -checkout's git history, its `outputs/` and logs, 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'. +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 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`, with a clean environment (no key or +token of that shell's). A program in the sandbox reaches them through their request protocols: images and point +clouds in JSON and base64 for RATs' own three (NumPy arrays read without pickle), msgpack for GraspGen, whose NumPy +decoder unpickles an array of dtype object; the example's `graspgen_guard.py` refuses that request (RATs' client +sends arrays of floats), so no request runs code in a service. ## The step ```mermaid flowchart TD - A["adapter: skills.json (L) + state/ (M, retry bank,
proposer counts, curator history, loop.json, iteration digests)"] + 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)"] @@ -103,25 +127,32 @@ 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`, 40 | exec | the original LIBERO Spatial, Object, Goal and Long suites, 10 tasks each, init states 43-49 | 280 | +| `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, one validation trial, one test trial | 1 each | +| `smoke_*` | one each | play / exec | one play iteration, the first validation row's first trial, one test trial | 1 each | -What play and the test share: play never reads a test suite's BDDL files or init states (the sandbox hides them), -and the actor refuses RATs' `--proposer-include-eval-task-context` (its optional task-aware play, which writes the -60 test tasks' descriptions into the proposer's prompt) in a play row. The test suites are perturbations of the +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 changes the instruction and goal. 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. -What play and validation share: validation is the original LIBERO, the setting the paper's play is grounded in. -RATs' play may rebind to the tasks of its scene's suite (`libero_spatial`'s ten: -`LifelongLoop._init_libero_validated_tasks`) and resets with the iteration's seed, so the `libero_spatial` -validation rows are not unseen by play; their 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. +What play and validation share: validation is the original LIBERO, the setting the paper's play is grounded in. In +its default mode (novel tasks, RATs' `--catalog` off) play 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. The other +validation tasks' objects and fixtures are the ones play's scenes are built from, and their 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. ## Evaluation @@ -129,7 +160,9 @@ The protocol is train / test: the Evolver learns from the play iterations, and t 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 `RATS_VERIFIER_STRICT_BENCHMARK=1`, so that only LIBERO's native `task_completed` counts. +--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 @@ -154,8 +187,14 @@ servers RATs' `docs/evaluation.md` lists for this evaluation), for a machine wit 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; the strict-benchmark flag and RATs' verifiers are what keep a reported success -to LIBERO's own goal check. +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.) + +Each row gets its own read-only copy of the library. RATs' batch driver passes one library file to all of its +concurrent jobs, and RATs writes the skills' usage counts into it as they run (`--no-skill-reuse` stops storing new +skills, not that write), so a job there can see counts another job left; here RATs' write fails, and RATs carries on +(it treats a failed save as non-fatal), so every row reads the library the training run produced. ## Parameters @@ -165,18 +204,22 @@ to LIBERO's own goal check. 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`: the videos RATs attaches to its -vision calls are dropped; `true` for a model that takes video), `price` (overrides the backend'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; a play row refuses -those that name its scene or output, or put the test tasks into play), `env` (more variables for RATs' process; a +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), `mesa_egl_vendor` -(Mesa's glvnd vendor file), `service_ports`, `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`, `trial_timeout_s`, `call_timeout_s`, `max_retries`. +(Mesa's glvnd vendor file), `service_ports` (the vision services' ports the sandbox reaches; default those of the +row's RATs config's `api_servers`), `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`, `trial_timeout_s`, `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 authors' implementation against this one @@ -185,28 +228,31 @@ attempt artifacts), `timeout_s`, `trial_timeout_s`, `call_timeout_s`, `max_retri | 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 distillation counter | saved to and restored from `state/loop.json` around each iteration | one process per iteration; 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 | medium (`llm_reasoning_effort`), sent in RATs' OpenAI form only | medium on every request (`effort`); a request of RATs' own that sets one keeps it | the first-evaluation row; RATs' own default | -| Videos in vision calls | the verifiers and the diagnoser attach the attempt's videos (Gemini takes them) | dropped with RATs' `_strip_videos_from_messages`, images and text kept (`video: true` keeps them) | GLM 5.3 Flash refuses video input (HTTP 400); RATs does the same for its fallback models; a deviation | +| 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 verifiers, the feedback generator and the diagnoser attach the attempt's videos (Gemini takes them) | each built from images, as RATs builds it without a video (sampled frames, first and last frames, 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) | 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 | -| Vision services | auto-launched from the env config | started once by `serve.sh` from RATs' own server modules, shared by the rows | concurrent rows share them; acceptable | -| Molmo (8122) | a vLLM-served pointing model, set up with the MolmoSpaces runtime; `docs/setup.md`: the LIBERO-PRO workflows do not require it | not started; the LIBERO API's Molmo pointing falls back to SAM3's text prompt | as RATs' LIBERO setup | +| 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; GraspGen's object-array requests refused | concurrent rows share them; the services run outside the sandbox; acceptable | +| Molmo (8122) | a vLLM-served pointing model, set up with the MolmoSpaces runtime; `docs/setup.md`: the LIBERO-PRO workflows do not require it | not started, and no row reaches its port; the LIBERO API's Molmo pointing falls back to SAM3's text prompt | as RATs' LIBERO setup | +| The library at test | one file shared by the batch driver's concurrent jobs; RATs writes usage counts into it | a read-only copy per row; RATs' write fails as a non-fatal save | every row reads the trained library; a decision | | 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 loopback services, one GPU, the authors' libraries and the test suites hidden in play | the framework's rules for a run's code | +| 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 | ## What it is not The final library is what RATs' play produced; nothing selects it on held-out data. Validation and test scores are -RATs' own success flags. Play and validation share LIBERO's original scenes (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 +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'`). diff --git a/examples/libero/rats/README.md b/examples/libero/rats/README.md index 4a14246d..5bb78516 100644 --- a/examples/libero/rats/README.md +++ b/examples/libero/rats/README.md @@ -10,7 +10,7 @@ states, not with the cap-harness seeds. | File | What it is | |---|---| -| `train.yaml` | Training: 50 play iterations (`splits/train.txt`), one per step; snapshots every 10 steps | +| `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) | @@ -19,7 +19,8 @@ states, not with the cap-harness seeds. | `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 | +| `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 one request of its protocol that would run code refused ([Trust](#trust)) | | `task-info/` | What play and evaluation are, for the learner | ## Data splits @@ -27,15 +28,19 @@ states, not with the cap-harness seeds. | 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 | 40 exec rows | `libero_spatial`, `libero_object`, `libero_goal`, `libero_10` (the original LIBERO) | 43-49 | 280 | `val.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 (the sandbox hides them), and a -play row refuses RATs' `--proposer-include-eval-task-context`, which would show the test tasks to the proposer. -Validation shares LIBERO's original scenes with play (play may rebind to `libero_spatial`'s tasks), 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. `RATS_ROWS_ARGS` changes the sizes (`--play 20`, `--test-states 0-4` for the five trials +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), and a play row whose arguments turn on RATs' `--proposer-include-eval-task-context` +(in any spelling RATs' parser takes), which would show the test tasks to the proposer, is refused. 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 @@ -75,9 +80,9 @@ uv sync --frozen --active --extra libero --extra contactgraspnet ``` Without GraspGen, `RATS_GRASP=graspnet` evaluates on Contact-GraspNet (8115), a deviation from RATs' config. -- **Molmo** (a vLLM-served pointing model on 8122) is not started: RATs' `docs/setup.md` lists it with the - MolmoSpaces runtime and says the LIBERO-PRO workflows do not require it; the LIBERO API then falls back to SAM3's - text prompt (its log shows the failed requests). +- **Molmo** (a vLLM-served pointing model on 8122) is not started, and no row reaches its port: RATs' + `docs/setup.md` lists it with the MolmoSpaces runtime and says the LIBERO-PRO workflows do not require it; the + LIBERO API then falls back to SAM3's text prompt (its log shows the failed requests). - **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), @@ -85,13 +90,26 @@ uv sync --frozen --active --extra libero --extra contactgraspnet `/usr/share/glvnd/egl_vendor.d/50_mesa.json`): no GPU, the same physics, slower frames, images that differ by renderer noise. +## 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`). What a program can do there is what their request +protocols take: images and point clouds (JSON and base64 for RATs' own three, NumPy arrays without pickle), and for +GraspGen msgpack, whose NumPy decoder unpickles an array of dtype object; `graspgen_guard.py` refuses that one request +(RATs' client sends arrays of floats). `serve.sh` starts every service with a clean environment, so a service holds +no key or token of the shell that started it. + ## Run -From this folder, with the services up: +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 FIREWORKS_API_KEY=... +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 @@ -110,8 +128,8 @@ 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`, written once -and shared by the runs started with it), the Trainer's records, the actor's logs (`actor-logs/-/`: +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 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..e77c55c4 --- /dev/null +++ b/examples/libero/rats/graspgen_guard.py @@ -0,0 +1,45 @@ +"""GraspGen's ZMQ server (NVlabs/GraspGen client-server/graspgen_server.py) with its requests decoded without pickle. + +GraspGen's wire format is msgpack with msgpack_numpy, whose decoder unpickles an array of dtype object +(msgpack_numpy.decode: `kind == b'O'` -> pickle.loads). RATs' programs reach GraspGen's port from the RATs actor's +sandbox, and the server runs outside it: one such request would run its code there. RATs' own client sends point +clouds of floats, which decode as before; an object array is refused, as a request error (the server answers it with +{"error": ...} and 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 + + +def refuse_object_arrays() -> None: + """msgpack_numpy's decoder, refusing what it would unpickle (its unpack functions look `decode` up per call).""" + import msgpack_numpy + decode = msgpack_numpy.decode + + def guarded(obj, chain=None): + if isinstance(obj, dict) and obj.get(b"nd") is True and obj.get(b"kind") == b"O": + raise ValueError("an object array is refused: msgpack_numpy would unpickle it") + return decode(obj, chain) + + msgpack_numpy.decode = 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() + script = argv[0] + sys.argv = list(argv) + sys.path[0] = str(Path(script).resolve().parent) # as `python