Robotics
LeRobot
Safetensors
act
so101
imitation-learning
mujoco
so101_act35_real_sim_v1 / deployment /async_chunk_controller.py
ddduk's picture
Upload selected ACT35 067000 checkpoint and validated portable rollout
2eeb9b8 verified
Raw History Blame Contribute Delete
11.4 kB
#!/usr/bin/env python3
"""Latency-aware action-chunk buffering for smooth real-time robot control.
The controller is policy- and robot-agnostic. A policy worker predicts a full
chunk from a timestamped observation while the control loop continues consuming
the previous plan. On arrival, stale actions are discarded and the overlapping
future is re-anchored and blended before per-tick slew limits are applied.
"""
from __future__ import annotations
import queue
import threading
import time
from dataclasses import dataclass
from typing import Any, Callable
import numpy as np
class TrackingError(RuntimeError):
"""Raised when measured joints are too far from the most recent command."""
@dataclass(frozen=True)
class ChunkPrediction:
actions: np.ndarray
observation_step: int
inference_seconds: float
@dataclass(frozen=True)
class ControllerConfig:
fps: float = 30.0
replan_every: int = 8
blend_steps: int = 6
anchor_steps: int = 6
max_step_delta: tuple[float, ...] = (2.5, 3.5, 3.5, 2.0, 2.7, 6.5)
max_acceleration: tuple[float, ...] | None = None
max_tracking_error: tuple[float, ...] = (12.0, 12.0, 12.0, 12.0, 15.0, 25.0)
def __post_init__(self) -> None:
if self.fps <= 0:
raise ValueError("fps must be positive")
if self.replan_every <= 0:
raise ValueError("replan_every must be positive")
if self.blend_steps < 0 or self.anchor_steps < 0:
raise ValueError("blend_steps and anchor_steps must be non-negative")
if self.max_acceleration is not None and any(value <= 0 for value in self.max_acceleration):
raise ValueError("max_acceleration values must be positive")
class RecedingHorizonController:
"""Maintain an absolute-time plan and emit one rate-limited action per tick."""
def __init__(self, config: ControllerConfig, action_dim: int = 6) -> None:
self.config = config
self.action_dim = action_dim
self.step = 0
self._plan_start = 0
self._plan: np.ndarray | None = None
self._last_command: np.ndarray | None = None
self._last_desired: np.ndarray | None = None
self._last_velocity = np.zeros(action_dim, dtype=np.float64)
self._last_state: np.ndarray | None = None
self._last_snapshot_step = -config.replan_every
self.underruns = 0
self.accepted_chunks = 0
self.discarded_stale_actions = 0
self._max_step_delta = self._as_vector(config.max_step_delta, "max_step_delta")
self._max_acceleration = (
self._as_vector(config.max_acceleration, "max_acceleration")
if config.max_acceleration is not None
else None
)
self._max_tracking_error = self._as_vector(config.max_tracking_error, "max_tracking_error")
def _as_vector(self, values: tuple[float, ...], name: str) -> np.ndarray:
vector = np.asarray(values, dtype=np.float64)
if vector.shape != (self.action_dim,) or np.any(vector <= 0):
raise ValueError(f"{name} must have {self.action_dim} positive values")
return vector
@property
def last_command(self) -> np.ndarray | None:
return None if self._last_command is None else self._last_command.copy()
@property
def last_desired(self) -> np.ndarray | None:
"""Return the current plan target before slew/acceleration limiting."""
return None if self._last_desired is None else self._last_desired.copy()
@property
def last_velocity(self) -> np.ndarray:
"""Return the most recent commanded per-tick joint displacement."""
return self._last_velocity.copy()
@property
def snapshot_due(self) -> bool:
return self.step - self._last_snapshot_step >= self.config.replan_every
def mark_snapshot(self, measured_state: np.ndarray) -> None:
state = np.asarray(measured_state, dtype=np.float64)
if state.shape != (self.action_dim,):
raise ValueError(f"measured_state must have shape ({self.action_dim},)")
self._last_state = state.copy()
self._last_snapshot_step = self.step
if self._last_command is not None:
error = np.abs(self._last_command - state)
if np.any(error > self._max_tracking_error):
joints = np.flatnonzero(error > self._max_tracking_error).tolist()
raise TrackingError(
f"tracking error exceeds guard on joints {joints}: "
f"error={error.round(3).tolist()}"
)
def _planned_action(self, absolute_step: int) -> np.ndarray | None:
if self._plan is None:
return None
index = absolute_step - self._plan_start
if index < 0 or index >= len(self._plan):
return None
return self._plan[index].copy()
def accept_prediction(self, prediction: ChunkPrediction) -> bool:
chunk = np.asarray(prediction.actions, dtype=np.float64)
if chunk.ndim != 2 or chunk.shape[1] != self.action_dim or not np.isfinite(chunk).all():
raise ValueError(f"actions must be finite with shape (T, {self.action_dim})")
# The observation was captured at observation_step. By the time inference
# finishes, actions before the current absolute step refer to the past.
# Align in *executed control ticks*, not wall-clock inference time. At
# startup the control loop intentionally waits for the first plan, so
# no action is stale even if inference took 80 ms. During motion,
# `self.step - observation_step` is exactly how many old-plan commands
# were sent while the worker was running.
elapsed_steps = max(0, self.step - prediction.observation_step)
if elapsed_steps >= len(chunk):
self.discarded_stale_actions += len(chunk)
return False
self.discarded_stale_actions += elapsed_steps
new_plan = chunk[elapsed_steps:].copy()
old_future = [self._planned_action(self.step + i) for i in range(len(new_plan))]
# Re-anchor the head to the command already being executed (or the latest
# measured state during startup), then smoothly release that offset.
reference = old_future[0]
if reference is None:
reference = self._last_command if self._last_command is not None else self._last_state
if reference is not None and self.config.anchor_steps > 0:
offset = np.asarray(reference) - new_plan[0]
n_anchor = min(self.config.anchor_steps, len(new_plan))
weights = 1.0 - np.arange(n_anchor, dtype=np.float64) / max(1, n_anchor)
new_plan[:n_anchor] += weights[:, None] * offset[None, :]
# Blend the overlapping head with the old future. Old-plan weight decays
# to zero, avoiding the discontinuity caused by replacing a whole queue.
n_blend = min(self.config.blend_steps, len(new_plan))
for i in range(n_blend):
if old_future[i] is None:
continue
new_weight = (i + 1) / (n_blend + 1)
new_plan[i] = (1.0 - new_weight) * old_future[i] + new_weight * new_plan[i]
self._plan_start = self.step
self._plan = new_plan
self.accepted_chunks += 1
return True
def next_action(self) -> np.ndarray:
desired = self._planned_action(self.step)
if desired is None:
self.underruns += 1
if self._last_command is not None:
desired = self._last_command.copy()
elif self._last_state is not None:
desired = self._last_state.copy()
else:
raise RuntimeError("no plan, previous command, or measured state is available")
self._last_desired = desired.copy()
if self._last_command is not None:
requested_delta = np.clip(
desired - self._last_command,
-self._max_step_delta,
self._max_step_delta,
)
if self._max_acceleration is not None:
delta = np.clip(
requested_delta,
self._last_velocity - self._max_acceleration,
self._last_velocity + self._max_acceleration,
)
# Do not cross a target that is already reachable this tick.
same_direction = np.sign(delta) == np.sign(requested_delta)
would_overshoot = same_direction & (np.abs(delta) > np.abs(requested_delta))
delta[would_overshoot] = requested_delta[would_overshoot]
else:
delta = requested_delta
desired = self._last_command + delta
self._last_velocity = delta.copy()
else:
self._last_velocity.fill(0.0)
self._last_command = desired.copy()
self.step += 1
return desired
class LatestObservationWorker:
"""Run chunk inference in a thread while retaining only the newest request."""
def __init__(self, predict: Callable[[Any], np.ndarray]) -> None:
self._predict = predict
self._requests: queue.Queue[tuple[int, Any] | None] = queue.Queue(maxsize=1)
self._results: queue.SimpleQueue[ChunkPrediction | BaseException] = queue.SimpleQueue()
self._thread = threading.Thread(target=self._run, name="act-policy-worker", daemon=True)
self._started = False
def start(self) -> None:
if not self._started:
self._thread.start()
self._started = True
def submit(self, observation_step: int, observation: Any) -> None:
if not self._started:
raise RuntimeError("worker has not been started")
try:
self._requests.put_nowait((observation_step, observation))
except queue.Full:
try:
self._requests.get_nowait()
except queue.Empty:
pass
self._requests.put_nowait((observation_step, observation))
def poll(self) -> ChunkPrediction | None:
try:
result = self._results.get_nowait()
except queue.Empty:
return None
if isinstance(result, BaseException):
raise RuntimeError("policy worker failed") from result
return result
def stop(self, timeout: float = 2.0) -> None:
if not self._started:
return
try:
self._requests.put_nowait(None)
except queue.Full:
try:
self._requests.get_nowait()
except queue.Empty:
pass
self._requests.put_nowait(None)
self._thread.join(timeout=timeout)
def _run(self) -> None:
while True:
request = self._requests.get()
if request is None:
return
observation_step, observation = request
started = time.perf_counter()
try:
actions = np.asarray(self._predict(observation), dtype=np.float64)
elapsed = time.perf_counter() - started
self._results.put(ChunkPrediction(actions, observation_step, elapsed))
except BaseException as exc: # propagate the original exception to the control thread
self._results.put(exc)