|
|
|
|
|
""" |
|
|
PI05 RTC Inference - With Action Logging |
|
|
""" |
|
|
|
|
|
import torch |
|
|
import time |
|
|
import numpy as np |
|
|
import threading |
|
|
import traceback |
|
|
|
|
|
torch._dynamo.config.suppress_errors = True |
|
|
torch._dynamo.config.disable = True |
|
|
|
|
|
from lerobot.policies.pi05.modeling_pi05 import PI05Policy |
|
|
from lerobot.configs.types import RTCAttentionSchedule |
|
|
from lerobot.policies.rtc.configuration_rtc import RTCConfig |
|
|
from lerobot.policies.rtc.modeling_rtc import RTCProcessor |
|
|
from trlc_dk1.follower import DK1Follower, DK1FollowerConfig |
|
|
from lerobot.cameras.opencv import OpenCVCameraConfig |
|
|
from transformers import AutoTokenizer |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
MODEL_PATH = "qualiaadmin/81df74e6-274f-4f02-aaa7-c1f83c549832" |
|
|
TOKENIZER_NAME = "google/paligemma-3b-pt-224" |
|
|
TASK = "clean the table" |
|
|
|
|
|
CONTROL_FREQ = 50 |
|
|
CHUNK_SIZE = 50 |
|
|
EXECUTION_HORIZON = 20 |
|
|
|
|
|
|
|
|
USE_RTC = True |
|
|
MAX_GUIDANCE_WEIGHT = 5.0 |
|
|
SMOOTH_ALPHA = 0.85 |
|
|
|
|
|
|
|
|
ROBOT_PORT = "/dev/ttyACM0" |
|
|
TOP_CAMERA_INDEX = 6 |
|
|
WRIST_CAMERA_INDEX = 4 |
|
|
|
|
|
|
|
|
STATE_MEAN = torch.tensor([0.1108, 0.8736, 0.7812, -0.3134, 0.0278, -0.0890, 0.2867]).cuda() |
|
|
STATE_STD = torch.tensor([0.2484, 0.6667, 0.5777, 0.3697, 0.0903, 0.1300, 0.4132]).cuda() |
|
|
ACTION_MEAN = torch.tensor([0.1110, 0.8739, 0.7815, -0.3132, 0.0280, -0.0888, 0.2853]).cuda() |
|
|
ACTION_STD = torch.tensor([0.2519, 0.6752, 0.5838, 0.3747, 0.0924, 0.1315, 0.4204]).cuda() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RTCActionQueue: |
|
|
def __init__(self): |
|
|
self.actions = [] |
|
|
self.prev_chunk_normalized = None |
|
|
self.lock = threading.Lock() |
|
|
self.last_chunk_stats = None |
|
|
|
|
|
def remaining(self) -> int: |
|
|
with self.lock: |
|
|
return len(self.actions) |
|
|
|
|
|
def get_left_over_for_rtc(self): |
|
|
with self.lock: |
|
|
if self.prev_chunk_normalized is None: |
|
|
return None |
|
|
return self.prev_chunk_normalized.clone() |
|
|
|
|
|
def set_new_chunk(self, actions_tensor: torch.Tensor, inference_delay: int): |
|
|
with self.lock: |
|
|
self.prev_chunk_normalized = actions_tensor[:, inference_delay:, :].detach().clone() |
|
|
actions = actions_tensor[0] if actions_tensor.dim() == 3 else actions_tensor |
|
|
actions = actions * ACTION_STD + ACTION_MEAN |
|
|
actions_np = actions.detach().cpu().numpy()[inference_delay:] |
|
|
|
|
|
|
|
|
if len(actions_np) > 1: |
|
|
deltas = np.diff(actions_np, axis=0) |
|
|
self.last_chunk_stats = { |
|
|
'mean_delta': np.mean(np.abs(deltas)), |
|
|
'max_delta': np.max(np.abs(deltas)), |
|
|
'range': np.ptp(actions_np, axis=0), |
|
|
} |
|
|
|
|
|
self.actions = list(actions_np) |
|
|
|
|
|
def get(self): |
|
|
with self.lock: |
|
|
return self.actions.pop(0) if self.actions else None |
|
|
|
|
|
def get_chunk_stats(self): |
|
|
with self.lock: |
|
|
return self.last_chunk_stats |
|
|
|
|
|
|
|
|
class ActionSmoother: |
|
|
def __init__(self, alpha: float): |
|
|
self.alpha = alpha |
|
|
self.prev = None |
|
|
|
|
|
def __call__(self, action: np.ndarray) -> np.ndarray: |
|
|
if self.alpha >= 1.0 or self.prev is None: |
|
|
self.prev = action.copy() |
|
|
return action |
|
|
smoothed = self.alpha * action + (1 - self.alpha) * self.prev |
|
|
self.prev = smoothed.copy() |
|
|
return smoothed |
|
|
|
|
|
|
|
|
def format_observation(raw_obs: dict, tokenizer) -> dict: |
|
|
state = torch.tensor([ |
|
|
raw_obs["joint_1.pos"], raw_obs["joint_2.pos"], raw_obs["joint_3.pos"], |
|
|
raw_obs["joint_4.pos"], raw_obs["joint_5.pos"], raw_obs["joint_6.pos"], |
|
|
raw_obs["gripper.pos"], |
|
|
], dtype=torch.float32).cuda() |
|
|
state = ((state - STATE_MEAN) / STATE_STD).unsqueeze(0) |
|
|
|
|
|
top = raw_obs["top"] |
|
|
wrist = raw_obs["wrist"] |
|
|
if not isinstance(top, torch.Tensor): |
|
|
top = torch.from_numpy(top).permute(2, 0, 1).float() / 255.0 |
|
|
wrist = torch.from_numpy(wrist).permute(2, 0, 1).float() / 255.0 |
|
|
|
|
|
tokens = tokenizer(TASK, return_tensors="pt", padding="max_length", max_length=48, truncation=True) |
|
|
|
|
|
return { |
|
|
"observation.images.top": top.unsqueeze(0).cuda(), |
|
|
"observation.images.wrist": wrist.unsqueeze(0).cuda(), |
|
|
"observation.state": state, |
|
|
"observation.language.tokens": tokens["input_ids"].cuda(), |
|
|
"observation.language.attention_mask": tokens["attention_mask"].bool().cuda(), |
|
|
} |
|
|
|
|
|
|
|
|
def action_to_dict(action: np.ndarray) -> dict: |
|
|
return {f"joint_{i}.pos": float(action[i-1]) for i in range(1, 7)} | {"gripper.pos": float(action[6])} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main(): |
|
|
print("=" * 60) |
|
|
print("PI05 RTC Inference - Action Analysis Mode") |
|
|
print("=" * 60) |
|
|
print(f"\nUSE_RTC={USE_RTC}, GUIDANCE={MAX_GUIDANCE_WEIGHT}, SMOOTH={SMOOTH_ALPHA}\n") |
|
|
|
|
|
|
|
|
rtc_config = RTCConfig( |
|
|
enabled=USE_RTC, |
|
|
execution_horizon=EXECUTION_HORIZON, |
|
|
max_guidance_weight=MAX_GUIDANCE_WEIGHT, |
|
|
prefix_attention_schedule=RTCAttentionSchedule.EXP, |
|
|
) |
|
|
|
|
|
print("Loading model...") |
|
|
policy = PI05Policy.from_pretrained(MODEL_PATH, device="cuda") |
|
|
policy.eval() |
|
|
|
|
|
if USE_RTC: |
|
|
policy.config.rtc_config = rtc_config |
|
|
rtc_processor = RTCProcessor(rtc_config) |
|
|
policy.rtc_processor = rtc_processor |
|
|
if hasattr(policy, 'model'): |
|
|
policy.model.config.rtc_config = rtc_config |
|
|
policy.model.rtc_processor = rtc_processor |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_NAME) |
|
|
|
|
|
print("Connecting to robot...") |
|
|
robot_config = DK1FollowerConfig( |
|
|
port=ROBOT_PORT, |
|
|
cameras={ |
|
|
"top": OpenCVCameraConfig(index_or_path=TOP_CAMERA_INDEX, width=640, height=360, fps=30), |
|
|
"wrist": OpenCVCameraConfig(index_or_path=WRIST_CAMERA_INDEX, width=640, height=360, fps=30), |
|
|
}, |
|
|
) |
|
|
robot = DK1Follower(robot_config) |
|
|
robot.connect() |
|
|
print("Ready!\n") |
|
|
|
|
|
|
|
|
raw_obs = robot.get_observation() |
|
|
current_pos = np.array([raw_obs[f"joint_{i}.pos"] for i in range(1, 7)] + [raw_obs["gripper.pos"]]) |
|
|
|
|
|
print("=" * 40) |
|
|
print("POSITION ANALYSIS") |
|
|
print("=" * 40) |
|
|
print(f"Current: {np.round(current_pos, 3)}") |
|
|
print(f"Mean: {np.round(STATE_MEAN.cpu().numpy(), 3)}") |
|
|
print(f"Delta: {np.round(current_pos - STATE_MEAN.cpu().numpy(), 3)}") |
|
|
print() |
|
|
|
|
|
|
|
|
obs = format_observation(raw_obs, tokenizer) |
|
|
with torch.enable_grad(): |
|
|
action_tensor = policy.predict_action_chunk(obs) |
|
|
|
|
|
actions_np = (action_tensor[0] * ACTION_STD + ACTION_MEAN).detach().cpu().numpy() |
|
|
|
|
|
print("=" * 40) |
|
|
print("ACTION CHUNK ANALYSIS") |
|
|
print("=" * 40) |
|
|
print(f"First action: {np.round(actions_np[0], 3)}") |
|
|
print(f"Last action: {np.round(actions_np[-1], 3)}") |
|
|
print(f"Chunk range: {np.round(np.ptp(actions_np, axis=0), 3)}") |
|
|
print(f"Mean step size: {np.round(np.mean(np.abs(np.diff(actions_np, axis=0)), axis=0), 4)}") |
|
|
print() |
|
|
|
|
|
|
|
|
print("Action trajectory (joint 1,2,3 at steps 0,10,20,30,40,49):") |
|
|
for i in [0, 10, 20, 30, 40, 49]: |
|
|
print(f" [{i:2d}] {np.round(actions_np[i, :3], 3)}") |
|
|
print() |
|
|
|
|
|
input("Press Enter to start execution...") |
|
|
|
|
|
|
|
|
action_queue = RTCActionQueue() |
|
|
smoother = ActionSmoother(SMOOTH_ALPHA) |
|
|
latest_obs = None |
|
|
obs_lock = threading.Lock() |
|
|
running = True |
|
|
first_chunk_ready = threading.Event() |
|
|
inference_times = [] |
|
|
|
|
|
def inference_loop(): |
|
|
nonlocal running |
|
|
|
|
|
while running: |
|
|
with obs_lock: |
|
|
obs = latest_obs |
|
|
if obs is None: |
|
|
time.sleep(0.01) |
|
|
continue |
|
|
|
|
|
try: |
|
|
formatted = format_observation(obs, tokenizer) |
|
|
prev_actions = action_queue.get_left_over_for_rtc() if USE_RTC else None |
|
|
|
|
|
if inference_times: |
|
|
delay = int(np.ceil(np.mean(inference_times[-10:]) * CONTROL_FREQ)) |
|
|
delay = max(1, min(delay, CHUNK_SIZE - EXECUTION_HORIZON - 1)) |
|
|
else: |
|
|
delay = 10 |
|
|
|
|
|
start = time.time() |
|
|
with torch.enable_grad(): |
|
|
actions = policy.predict_action_chunk( |
|
|
formatted, |
|
|
inference_delay=delay if USE_RTC else 0, |
|
|
prev_chunk_left_over=prev_actions, |
|
|
) |
|
|
elapsed = time.time() - start |
|
|
inference_times.append(elapsed) |
|
|
|
|
|
action_queue.set_new_chunk(actions, delay) |
|
|
first_chunk_ready.set() |
|
|
|
|
|
|
|
|
stats = action_queue.get_chunk_stats() |
|
|
if stats: |
|
|
print(f"Inference: {elapsed*1000:.0f}ms | queue: {action_queue.remaining()} | " |
|
|
f"mean_delta: {stats['mean_delta']:.4f} | max_delta: {stats['max_delta']:.4f}") |
|
|
|
|
|
while running and action_queue.remaining() > EXECUTION_HORIZON: |
|
|
time.sleep(0.005) |
|
|
|
|
|
except Exception as e: |
|
|
print(f"[ERROR] {e}") |
|
|
traceback.print_exc() |
|
|
time.sleep(1) |
|
|
|
|
|
threading.Thread(target=inference_loop, daemon=True).start() |
|
|
|
|
|
raw_obs = robot.get_observation() |
|
|
with obs_lock: |
|
|
latest_obs = raw_obs |
|
|
|
|
|
first_chunk_ready.wait(timeout=60) |
|
|
print("\nRunning!\n") |
|
|
|
|
|
step = 0 |
|
|
loop_period = 1.0 / CONTROL_FREQ |
|
|
|
|
|
|
|
|
executed_actions = [] |
|
|
|
|
|
try: |
|
|
while running: |
|
|
t0 = time.time() |
|
|
|
|
|
raw_obs = robot.get_observation() |
|
|
with obs_lock: |
|
|
latest_obs = raw_obs |
|
|
|
|
|
action = action_queue.get() |
|
|
if action is not None: |
|
|
action = smoother(action) |
|
|
robot.send_action(action_to_dict(action)) |
|
|
executed_actions.append(action.copy()) |
|
|
step += 1 |
|
|
|
|
|
if step % 200 == 0: |
|
|
|
|
|
recent = np.array(executed_actions[-200:]) |
|
|
total_movement = np.sum(np.abs(np.diff(recent, axis=0))) |
|
|
print(f"Step {step} | Total movement (last 200): {total_movement:.2f} rad") |
|
|
|
|
|
dt = time.time() - t0 |
|
|
if dt < loop_period: |
|
|
time.sleep(loop_period - dt) |
|
|
|
|
|
except KeyboardInterrupt: |
|
|
print("\n\nStopping...") |
|
|
|
|
|
|
|
|
if len(executed_actions) > 100: |
|
|
all_actions = np.array(executed_actions) |
|
|
print("\n" + "=" * 40) |
|
|
print("EXECUTION SUMMARY") |
|
|
print("=" * 40) |
|
|
print(f"Total steps: {len(executed_actions)}") |
|
|
print(f"Position range: {np.round(np.ptp(all_actions, axis=0), 3)}") |
|
|
print(f"Mean step size: {np.round(np.mean(np.abs(np.diff(all_actions, axis=0)), axis=0), 4)}") |
|
|
print(f"Total movement: {np.sum(np.abs(np.diff(all_actions, axis=0))):.2f} rad") |
|
|
finally: |
|
|
running = False |
|
|
robot.disconnect() |
|
|
print("Done!") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |