File size: 12,058 Bytes
d7b60cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/env python3
"""
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


# =============================================================================
# Configuration
# =============================================================================

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

# Tuned settings
USE_RTC = True
MAX_GUIDANCE_WEIGHT = 5.0  # Reduced from 10
SMOOTH_ALPHA = 0.85        # More responsive

# Robot
ROBOT_PORT = "/dev/ttyACM0"
TOP_CAMERA_INDEX = 6
WRIST_CAMERA_INDEX = 4

# Normalization
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()


# =============================================================================
# Classes
# =============================================================================

class RTCActionQueue:
    def __init__(self):
        self.actions = []
        self.prev_chunk_normalized = None
        self.lock = threading.Lock()
        self.last_chunk_stats = None  # For logging
    
    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:]
            
            # Compute chunk stats
            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),  # Peak-to-peak per joint
                }
            
            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])}


# =============================================================================
# Main
# =============================================================================

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")
    
    # Setup
    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")
    
    # Analyze initial state
    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()
    
    # Test inference and analyze
    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()
    
    # Show trajectory
    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...")
    
    # Shared state
    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()
                
                # Log with chunk stats
                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
    
    # Track executed actions for analysis
    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:
                    # Analyze recent execution
                    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...")
        
        # Final analysis
        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()