refactor(runtime): template-method adapter base + policy registry; rename CLI

Make the policy adapter architecturally clean and set up a single general
entry point for any language-conditioned policy.

Adapter architecture (Template Method):
- New lerobot/runtime/adapter.py: BaseLanguageAdapter owns the generic
  control loop (throttle → generate → gibberish/empty reject → subtask→memory
  cascade → diagnostics) and plan_from_text/handle_interjection. A policy
  supplies only select_action + generate_text + build_messages. The
  subtask→memory cascade is an overridable hook (_regenerate_context).
- GenerationConfig (typed, constructor-time) replaces config smuggled through
  RuntimeState.extra (temperature/top_p/min_new_tokens/chunks_per_regen).
- LanguageDiagnostics (typed, keyed by kind) replaces ~8 loose state.extra
  counter keys; the panel reads it via the adapter.
- looks_like_gibberish + split_plan_and_say move to runtime (generic).

Contract:
- LanguageConditionedPolicyAdapter protocol now states the true contract
  (select_action, update_language_state, handle_interjection); the runtime
  drops both getattr fallbacks.
- PI052PolicyAdapter shrinks to just its primitives (132 → ~half).

General entry point:
- lerobot/runtime/registry.py maps policy type → adapter (lazy import).
- run() resolves the adapter from the registry by policy type and defaults
  the panel label to it, so one CLI serves every policy.
- Rename lerobot-pi052-runtime → lerobot-language-runtime (general script);
  a new policy just registers its adapter, no new script.

Tests: new tests/runtime/test_adapter.py covers throttle/reject/cascade/
interjection; adapter + runtime + CLI-smoke tests updated for the new shape.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Pepijn
2026-07-02 15:34:41 +02:00
parent 171e06c6ba
commit edc3a5eb4f
14 changed files with 438 additions and 222 deletions
@@ -1,7 +1,8 @@
from types import SimpleNamespace
from lerobot.policies.pi052.inference.pi052_adapter import PI052PolicyAdapter, split_plan_and_say
from lerobot.policies.pi052.inference.pi052_adapter import PI052PolicyAdapter
from lerobot.runtime import RuntimeState
from lerobot.runtime.adapter import split_plan_and_say
def test_pi052_adapter_builds_recipe_prompts_from_runtime_state():
@@ -12,13 +13,13 @@ def test_pi052_adapter_builds_recipe_prompts_from_runtime_state():
extra={"prior_subtask": "pick the cup"},
)
assert adapter.messages_for("subtask", state) == [{"role": "user", "content": "clean the kitchen"}]
assert adapter.messages_for("memory", state) == [
assert adapter.build_messages("subtask", state) == [{"role": "user", "content": "clean the kitchen"}]
assert adapter.build_messages("memory", state) == [
{"role": "user", "content": "clean the kitchen"},
{"role": "assistant", "content": "Previous memory: cup moved"},
{"role": "user", "content": "Completed subtask: pick the cup"},
]
assert adapter.messages_for("interjection", state, user_text="wait") == [
assert adapter.build_messages("interjection", state, user_text="wait") == [
{"role": "user", "content": "clean the kitchen"},
{"role": "assistant", "content": "Previous plan:\npick then place"},
{"role": "user", "content": "wait"},
@@ -33,12 +34,12 @@ def test_pi052_adapter_strips_say_markers_from_plan_text():
assert adapter.plan_from_text(text) == "Move to the sink."
def test_pi052_runtime_cli_smoke_does_not_load_model(monkeypatch):
"""The pi052 entry wires its adapter into the generic runtime CLI."""
def test_language_runtime_cli_smoke_does_not_load_model(monkeypatch):
"""The general entry resolves the pi052 adapter from the registry by policy type."""
from lerobot.runtime import cli
from lerobot.scripts import lerobot_pi052_runtime
from lerobot.scripts import lerobot_language_runtime
fake_policy = SimpleNamespace(config=SimpleNamespace(device="cpu"))
fake_policy = SimpleNamespace(config=SimpleNamespace(device="cpu", type="pi052"))
monkeypatch.setattr(
cli,
@@ -48,5 +49,6 @@ def test_pi052_runtime_cli_smoke_does_not_load_model(monkeypatch):
monkeypatch.setattr(cli, "_run_repl", lambda runtime, **kwargs: 0)
assert (
lerobot_pi052_runtime.main(["--policy.path=fake", "--no_robot", "--task=clean", "--max_ticks=0"]) == 0
lerobot_language_runtime.main(["--policy.path=fake", "--no_robot", "--task=clean", "--max_ticks=0"])
== 0
)
+74
View File
@@ -0,0 +1,74 @@
from lerobot.runtime import RuntimeState
from lerobot.runtime.adapter import BaseLanguageAdapter, GenerationConfig, looks_like_gibberish
class ScriptedAdapter(BaseLanguageAdapter):
"""Base adapter whose text generation returns queued strings per kind."""
def __init__(self, scripts, gen=None):
super().__init__(policy=object(), gen=gen)
self.scripts = {k: list(v) for k, v in scripts.items()}
self.calls = []
def select_action(self, observation, state):
return None
def generate_text(self, kind, observation, state, user_text=None):
self.calls.append(kind)
queue = self.scripts.get(kind, [])
return queue.pop(0) if queue else ""
def test_cascade_sets_subtask_then_memory():
adapter = ScriptedAdapter({"subtask": ["pick the red cup"], "memory": ["the cup is grasped"]})
state = RuntimeState(task="clean")
adapter.update_language_state(None, state)
assert state.language_context["subtask"] == "pick the red cup"
assert state.language_context["memory"] == "the cup is grasped"
assert adapter.calls == ["subtask", "memory"]
def test_gibberish_subtask_is_rejected_and_counted():
adapter = ScriptedAdapter({"subtask": [":::: ::"], "memory": ["should not run"]})
state = RuntimeState(task="clean")
adapter.update_language_state(None, state)
assert "subtask" not in state.language_context
assert adapter.diag.gibberish.get("subtask") == 1
assert adapter.calls == ["subtask"] # memory never generated when subtask is rejected
def test_throttle_regenerates_every_n_chunks():
adapter = ScriptedAdapter(
{
"subtask": ["pick the first cup", "pick the second cup"],
"memory": ["memory one two three", "memory four five six"],
},
gen=GenerationConfig(chunks_per_regen=2),
)
state = RuntimeState(task="clean")
adapter.update_language_state(None, state) # generates
assert state.language_context["subtask"] == "pick the first cup"
adapter.update_language_state(None, state) # throttled — no generation
assert state.language_context["subtask"] == "pick the first cup"
adapter.update_language_state(None, state) # generates again
assert state.language_context["subtask"] == "pick the second cup"
def test_handle_interjection_sets_plan_and_strips_say():
adapter = ScriptedAdapter({"interjection": ["turn to the left now <say>heading left</say>"]})
state = RuntimeState(task="clean")
adapter.handle_interjection("turn", None, state)
assert state.language_context["plan"] == "turn to the left now"
def test_looks_like_gibberish_basic():
assert looks_like_gibberish("")
assert looks_like_gibberish(":::: ::")
assert not looks_like_gibberish("pick up the red cube")
+6 -6
View File
@@ -7,21 +7,21 @@ from lerobot.runtime import (
class FakeAdapter:
def __init__(self):
self.updated = False
self.text_calls = []
self.interjections = []
def select_action(self, observation, state):
assert observation == {"observation.state": 1}
assert state.task == "clean"
return ["a0", "a1"]
def select_text(self, kind, observation, state, user_text=None):
self.text_calls.append((kind, user_text))
return "new plan"
def update_language_state(self, observation, state):
self.updated = True
state.set_context("subtask", "pick cup", label="subtask")
def handle_interjection(self, user_text, observation, state):
self.interjections.append(user_text)
state.set_context("plan", "new plan", label="plan")
def test_runtime_tick_updates_language_enqueues_and_dispatches_action():
adapter = FakeAdapter()
@@ -54,7 +54,7 @@ def test_runtime_handles_user_interjection():
runtime.step_once()
assert ("interjection", "please say ok") in adapter.text_calls
assert "please say ok" in adapter.interjections
assert runtime.state.language_context["plan"] == "new plan"