Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/getting_started/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ ROLLOUT_NNODES=32 MODEL=<model dir> EVAL_STEP=<step> RUN=$WORK_DIR/runs/eval bas

The records and the summary land in `$RUN/val_dumps/eval_<step>.jsonl` and `$RUN/val_dumps/eval_<step>_summary.json`.

## Model-controlled completion in LIBERO

Set `policy_finish: true` in the LIBERO entry of the recipe's tool config
(`actor_rollout_ref.rollout.multi_turn.tool_config_path`). The model can submit its usual action or a fenced JSON block
containing `{"finish": true}`. Reaching the goal still returns an observation while there is budget for another turn. When the model emits `finish`, LIBERO checks the
current state and the rollout receives 1 for success or 0 for failure. A rollout that exhausts the native step or token
budget without finishing receives 0. The episode records `finish` and `budget` as distinct end reasons.

## Next Steps

- [Robot-Use RL with Qwen3.8-27B](../../examples/models/qwen3_8_27b_pear/train/README.md): stages 2 and 3
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ tools:
config:
type: native
env_class: pear.envs.libero.env.LiberoEnv # the family: its facts and its simulator
policy_finish: false # true lets the model finish the episode
# its servers: one per slot the rollout machines offer as libero (scripts/start_ray_node.sh)
log_dir: ${oc.env:PEAR_LOG_DIR} # the servers' logs and the tool's call log (the recipe: $RUN/sim)
- class_name: pear.envs.tool.EnvironmentTool
Expand Down
7 changes: 7 additions & 0 deletions pear/agent_loop/agent_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ async def run(self, sampling_params: dict[str, Any], **kwargs) -> AgentLoopOutpu
# the episode's record for the val dumps and the evaluation's records, as a dict (verl ships extra_fields as
# JSON); written only now: verl takes an empty extra_fields as the mark of the first generation
output.extra_fields["episode"] = self.episode.record()
if getattr(self.tool, "policy_finish", False):
output.extra_fields["episode"]["end_reason"] = self.end_reason.value

# uid is the prompt's id, shared by the n trajectories of a group; global_steps is the training step (both from
# verl's batch)
Expand Down Expand Up @@ -167,6 +169,11 @@ async def _handle_processing_tools_state(self, agent_data: AgentData) -> AgentSt

if self.episode.done:
self.end_reason = EndReason.ENV
if getattr(self.tool, "policy_finish", False):
if result["outcome"] == "finish":
self.end_reason = EndReason.FINISH
elif result["outcome"] == "budget":
self.end_reason = EndReason.BUDGET
return AgentState.TERMINATED

return await self._resume_generating(agent_data, {"role": "user", "content": content})
Expand Down
7 changes: 5 additions & 2 deletions pear/agent_loop/episode.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ class EndReason(str, Enum):
"""How an episode ends, each by the text its EPISODE_END record names it with."""

ENV = "env" # the environment finished it
FINISH = "finish" # the model declared the task complete
PARSE = "parse" # an answer without a usable action
BUDGET = "budget" # its response tokens ran out
BUDGET = "budget" # its response tokens or native steps ran out


@dataclass(eq=False) # each episode is a run of its own: two are never the same by their contents
Expand Down Expand Up @@ -52,5 +53,7 @@ def record(self) -> dict[str, Any]:

@staticmethod
def is_success(result: dict[str, Any]) -> bool:
"""Returns whether ``result`` ends its episode with the task done: its action earned a reward."""
"""Returns whether the result ends the episode with the task complete."""
if "task_success" in result:
return bool(result["done"]) and result["task_success"]
return bool(result["done"]) and sum(float(reward) for reward in result["rewards"]) > 0.0
5 changes: 5 additions & 0 deletions pear/agent_loop/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ class JsonBlockProtocol:

JSON_BLOCK_PATTERN = re.compile(r"```json\s*(\{.*?\})\s*```", re.DOTALL) # a fenced json block and its object

@staticmethod
def is_finish(action: Any) -> bool:
"""Whether the output is the explicit finish action."""
return isinstance(action, dict) and action.keys() == {"finish"} and action["finish"] is True

@staticmethod
def system_prompt(template: str, environment: str, instruction: str) -> str:
"""Returns ``template`` with the family's facts as its ENVIRONMENT section (no section without facts) and the
Expand Down
1 change: 1 addition & 0 deletions pear/envs/libero/configs/tool_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ tools:
config:
type: native
env_class: pear.envs.libero.env.LiberoEnv # the family: its facts and its simulator
policy_finish: false # true lets the model finish the episode
# its servers: one per slot the rollout machines offer as libero (scripts/start_ray_node.sh)
log_dir: ${oc.env:PEAR_LOG_DIR} # the servers' logs and the tool's call log (the recipe: $RUN/sim)
7 changes: 5 additions & 2 deletions pear/envs/libero/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ def __init__(self, scene: Any, observation: dict[str, np.ndarray], action: dict[
self.stall_step_n = self.slow_stall_step_n = 0
self.is_stopping = False

def move(self, budget: int) -> tuple[dict[str, np.ndarray], list[list[float]], list[float], bool, str]:
def move(
self, budget: int, *, stop_on_success: bool = True
) -> tuple[dict[str, np.ndarray], list[list[float]], list[float], bool, str]:
"""Native actions toward the targets until they are reached at rest, the robot stops short of them, the task
ends, or the episode's ``budget`` or the action's cap runs out: the last observation, the actions, their
rewards, whether the episode ended and the outcome (reached | stopped | done | budget | timeout)."""
Expand All @@ -97,7 +99,8 @@ def move(self, budget: int) -> tuple[dict[str, np.ndarray], list[list[float]], l
self.observation, reward, done, _ = self.scene.step(native_action)
actions.append(native_action.tolist())
rewards.append(float(reward))
if done:
# The pinned LIBERO sets done to its task success predicate.
if done and stop_on_success:
return self.observation, actions, rewards, True, "done"
outcome = self._step_outcome()
if outcome is not None:
Expand Down
28 changes: 21 additions & 7 deletions pear/envs/libero/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import torch
from PIL import Image

from pear.agent_loop.protocol import JsonBlockProtocol
from pear.envs.libero.controller import MotionController
from pear.sim.env import StatelessEnv
from pear.sim.process import SimulatorProcess
Expand Down Expand Up @@ -62,14 +63,18 @@ class LiberoEnv(StatelessEnv):
# the family's conversation (EnvironmentTool)
SCHEMA = MotionController.SCHEMA
CAMERAS = ("agentview", "wrist") # the frames of an observation, in this order
ENVIRONMENT_PROMPT = Path(__file__).with_name("environment_prompt.md").read_text().strip()
POLICY_FINISH_ENVIRONMENT_PROMPT = Path(__file__).with_name("environment_prompt.md").read_text().strip()
ENVIRONMENT_PROMPT = (
POLICY_FINISH_ENVIRONMENT_PROMPT
+ "\n- the episode ends by itself as soon as the task is done: while observations keep coming, the task is not done yet."
)
# beyond this the simulator process is hung, even in a replay of the longest episode (520 steps)
ROLLOUT_TIMEOUT_S = 180.0

# LIBERO benchmark object per suite (instruction, bddl file, init states), process-wide
_benchmark_by_suite: dict[str, Any] = {}

def __init__(self, suite: str, task_id: int, trial_id: int) -> None:
def __init__(self, suite: str, task_id: int, trial_id: int, policy_finish: bool = False) -> None:
if suite not in self.MAX_STEP_N_BY_SUITE:
raise ValueError(f"unknown suite {suite!r}; known: {sorted(self.MAX_STEP_N_BY_SUITE)}")
assert 0 <= int(trial_id) < self.TRIALS_PER_TASK, (
Expand All @@ -79,6 +84,7 @@ def __init__(self, suite: str, task_id: int, trial_id: int) -> None:
self.suite = suite
self.task_id = int(task_id)
self.trial_id = int(trial_id)
self.policy_finish = policy_finish

self.scene: Any = None # the OffScreenRenderEnv of the current call
self._render_cache: dict[tuple, Any] = {}
Expand Down Expand Up @@ -147,10 +153,16 @@ def rollout(self, history: list[list[float]], action: dict[str, Any] | None) ->
outcome = None
done = len(history) >= max_step_n # nothing left to execute: the budget is already spent
if action is not None and not done:
with self._no_render(): # the controller steps the scene and reads only proprioception
observation, actions, rewards, done, outcome = MotionController(
self.scene, observation, action
).move(max_step_n - len(history))
if self.policy_finish and JsonBlockProtocol.is_finish(action):
done, outcome = True, "finish"
else:
with self._no_render(): # the controller steps the scene and reads only proprioception
observation, actions, rewards, done, outcome = MotionController(
self.scene, observation, action
).move(max_step_n - len(history), stop_on_success=not self.policy_finish)

if self.policy_finish and len(history) + len(actions) >= max_step_n:
done, outcome = True, "budget"

result: EnvResult = {
"images": None, # the frames come below, while the episode goes on
Expand All @@ -159,13 +171,15 @@ def rollout(self, history: list[list[float]], action: dict[str, Any] | None) ->
"rewards": rewards,
"done": done,
"executed": len(actions),
"outcome": outcome, # reached | stopped | done | budget | timeout
"outcome": outcome, # reached | stopped | done | budget | timeout | finish
"instruction": re.sub(
r"\b(left|right)\b",
lambda match: self.MIRRORED_SIDE_BY_SIDE[match.group(1)],
str(self._benchmark().get_task(self.task_id).language),
),
}
if self.policy_finish and done:
result["task_success"] = outcome == "finish" and bool(self.scene.check_success())
if not done:
if len(history) or actions: # the reset rendered its last step, the replay and the action nothing
observation = self.scene.env._get_observations(force_update=True)
Expand Down
1 change: 0 additions & 1 deletion pear/envs/libero/environment_prompt.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
- agentview: a fixed camera; the robot's base is at the top of its image, +x points toward the bottom of the image and +y toward its left.
- wrist: a camera on the gripper; with the gripper pointing straight down at yaw 0, +x points toward the top of its image and +y toward its right.
- the episode ends by itself as soon as the task is done: while observations keep coming, the task is not done yet.
25 changes: 19 additions & 6 deletions pear/envs/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,18 @@ class EnvironmentTool(BaseTool):
SYSTEM_PROMPT_TEMPLATE = Path(__file__).with_name("system_prompt.md").read_text()
# repeated every turn: without it the model drops the json block
REMINDER = "The current camera frames follow. End your response with one json block containing the next action."
FINISH_INSTRUCTION = (
'End your response with one fenced json block containing the next action or {"finish": true} '
"if you have completed the task."
)

def __init__(self, config: dict, tool_schema: OpenAIFunctionToolSchema | None = None) -> None:
# one instance per agent-loop process (PEAR's trainer config keeps verl's dataset from building the tools on
# the driver); the loop's episodes run on its client
self.env_class: type[BaseEnv] = pkgutil.resolve_name(config["env_class"]) # the family's facts and simulator
self.policy_finish = config.get("policy_finish", False)
if self.policy_finish and self.env_class.POLICY_FINISH_ENVIRONMENT_PROMPT is None:
raise ValueError(f"policy_finish is not supported by {config['env_class']}")
self.client = pkgutil.resolve_name(self.env_class.CLIENT_CLASS_PATH)(self.env_class) # its kind's client
self.log_path = Path(str(config["log_dir"])) / f"actions_{os.getpid()}.jsonl"
self.log_path.parent.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -63,22 +70,25 @@ def get_openai_tool_schema(self) -> OpenAIFunctionToolSchema:
async def open(self, episode: Episode) -> tuple[list[dict[str, Any]] | None, EnvResult]:
"""Opens ``episode`` and returns the first user turn's content with the result of its initial observation."""
steps_before, start_time = len(episode.actions), time.monotonic()
result = await self.client.open(episode.uid, episode.env_args)
env_args = {**episode.env_args, "policy_finish": True} if self.policy_finish else episode.env_args
result = await self.client.open(episode.uid, env_args)
self._log_call(episode, steps_before, None, result, time.monotonic() - start_time)

return self._observation(result), result

def system_prompt(self, result: EnvResult) -> str:
"""Returns the episode's system prompt, from the result of its initial observation."""
return JsonBlockProtocol.system_prompt(
self.SYSTEM_PROMPT_TEMPLATE, self.env_class.environment_prompt(result), result["instruction"]
)
environment = self.env_class.environment_prompt(result)
if self.policy_finish:
environment = f"{self.env_class.POLICY_FINISH_ENVIRONMENT_PROMPT}\n- {self.FINISH_INSTRUCTION}"
return JsonBlockProtocol.system_prompt(self.SYSTEM_PROMPT_TEMPLATE, environment, result["instruction"])

async def step(self, episode: Episode, action: Any) -> tuple[list[dict[str, Any]] | None, EnvResult]:
"""Carries out the answer's ``action`` in ``episode`` and returns the next user turn's content (None once the
episode ended) with the result; raises InvalidAction for a json block that is no action."""
steps_before, start_time = len(episode.actions), time.monotonic()
JsonBlockProtocol.check_action(action, self.env_class.SCHEMA)
if not (self.policy_finish and JsonBlockProtocol.is_finish(action)):
JsonBlockProtocol.check_action(action, self.env_class.SCHEMA)
result = await self.client.step(episode.uid, action)
self._log_call(episode, steps_before, action, result, time.monotonic() - start_time)

Expand Down Expand Up @@ -117,7 +127,10 @@ def _observation(self, result: EnvResult) -> list[dict[str, Any]] | None:
if result["images"] is None:
return None

text = JsonBlockProtocol.turn_text(result["state"], self.REMINDER)
reminder = (
f"The current camera frames follow. {self.FINISH_INSTRUCTION}" if self.policy_finish else self.REMINDER
)
text = JsonBlockProtocol.turn_text(result["state"], reminder)
blocks: list[dict[str, Any]] = [{"type": "text", "text": text}]

for name, image in zip(self.env_class.CAMERAS, result["images"]):
Expand Down
1 change: 1 addition & 0 deletions pear/sim/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class BaseEnv(ABC):
CAMERAS: tuple[str, ...] # the frames' names, in the order of a result's images
ENVIRONMENT_PROMPT: str # the facts the protocol leaves out, in the family's words; empty: no ENVIRONMENT section
LOG_KEYS: tuple[str, ...] = () # the keys of its results the call log records besides the protocol's
POLICY_FINISH_ENVIRONMENT_PROMPT: str | None = None

@classmethod
def server_n(cls, config: dict[str, Any], cluster_resources: dict[str, float]) -> int:
Expand Down
6 changes: 5 additions & 1 deletion pear/sim/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ class ServerContext:
log: Callable[[str], None] # appends a message to the server's log


class EnvResult(TypedDict):
class _TerminalResult(TypedDict, total=False):
task_success: bool # explicit verdict for a terminal result in policy finish mode


class EnvResult(_TerminalResult):
"""What one call of an env returns: the protocol's keys, in this order, before the keys of the family's own."""

images: list[Any] | None # the cameras' frames in CAMERAS order; None once the episode ended
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
ZERO = {"arm": {"x": 0.0, "y": 0.0, "z": 0.0, "roll": 0.0, "pitch": 0.0, "yaw": 0.0}, "gripper": {"width": 0.0}}
# json blocks that are no action of LIBERO's schema, each with the tool's reason
INVALID_ACTIONS = [
({"finish": True}, "the json block must map exactly the parts arm, gripper to their quantities"),
([ZERO], "the json block must map exactly the parts arm, gripper to their quantities"),
({"arm": ZERO["arm"]}, "the json block must map exactly the parts arm, gripper to their quantities"),
({**ZERO, "gripper": {}}, "'gripper' must give exactly its quantities width"),
Expand Down
77 changes: 77 additions & 0 deletions tests/agent_loop/test_policy_finish_on_cpu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import asyncio
import json
from types import SimpleNamespace

import pytest
from PIL import Image

from pear.agent_loop.agent_loop import PearAgentLoop
from pear.agent_loop.episode import EndReason, Episode
from pear.agent_loop.protocol import InvalidAction
from pear.envs.libero.env import LiberoEnv
from pear.envs.tool import EnvironmentTool
from verl.experimental.agent_loop.tool_agent_loop import AgentState


class Client:
def __init__(self, env_class):
pass

async def open(self, uid, env_args):
assert env_args["policy_finish"] is True
return {
"images": [Image.new("RGB", (1, 1)) for _ in LiberoEnv.CAMERAS],
"state": {},
"actions": [],
"rewards": [],
"done": False,
"executed": 0,
"outcome": None,
"instruction": "Place the bowl on the plate.",
}

async def step(self, uid, action):
assert action == {"finish": True}
return {
"images": None,
"state": {},
"actions": [],
"rewards": [],
"done": True,
"executed": 0,
"outcome": "finish",
"instruction": "Place the bowl on the plate.",
"task_success": True,
}


def test_a_policy_finish_reaches_libero_and_terminates_the_agent_loop(tmp_path, monkeypatch):
monkeypatch.setattr(LiberoEnv, "CLIENT_CLASS_PATH", f"{__name__}.{Client.__qualname__}")
loop = object.__new__(PearAgentLoop)
loop.tool = EnvironmentTool(
{"env_class": "pear.envs.libero.env.LiberoEnv", "log_dir": str(tmp_path), "policy_finish": True}
)
loop.episode = Episode({"suite": "libero_goal", "task_id": 3, "trial_id": 0})
loop.end_reason = None
agent_data = SimpleNamespace(metrics={}, tool_calls=[SimpleNamespace(arguments=json.dumps({"finish": True}))])
observation, initial = asyncio.run(loop.tool.open(loop.episode))
prompt = loop.tool.system_prompt(initial)
assert '{"finish": true}' in prompt
assert '{"finish": true}' in observation[0]["text"]
assert "the episode ends by itself" not in prompt

state = asyncio.run(loop._handle_processing_tools_state(agent_data))

assert (state, loop.end_reason) == (AgentState.TERMINATED, EndReason.FINISH)
assert (loop.episode.done, loop.episode.success, loop.episode.actions) == (True, True, [])


@pytest.mark.parametrize("action", [{"finish": 1}, {"finish": True, "arm": {}}])
def test_malformed_finish_stays_an_invalid_action(tmp_path, monkeypatch, action):
monkeypatch.setattr(LiberoEnv, "CLIENT_CLASS_PATH", f"{__name__}.{Client.__qualname__}")
tool = EnvironmentTool(
{"env_class": "pear.envs.libero.env.LiberoEnv", "log_dir": str(tmp_path), "policy_finish": True}
)

with pytest.raises(InvalidAction):
asyncio.run(tool.step(Episode({}), action))
Loading
Loading