File size: 11,518 Bytes
ef2a612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""L2 simulated closed-loop check: ActionQueue + SmolVLA RTC.

Does **not** need a real robot. Simulates control ticks and a fixed inference
delay (in action steps). Compares RTC vs non-RTC queue behavior.

Success criteria
----------------
1. ActionQueue: after consuming K steps, ``get_left_over()`` length == remaining.
2. RTC merge: queue size after merge == chunk_size - delay.
3. Closed loop (RTC): zero underruns over ``control_steps`` when requesting the
   next chunk early enough (qsize <= delay + margin).
4. Continuity: mean |Δaction| at chunk-handoff steps is lower with RTC than
   without (or RTC underruns == 0 and handoff MAE to planned leftover is small).

Usage (inside rm65_dev2)::

    cd /home/sdznkj/zkx_ws/sendlerobot
    PYTHONPATH=. python3 scripts/l2_rtc_action_queue_check.py --device cuda
"""

from __future__ import annotations

import argparse
import json
import sys
from dataclasses import dataclass

import torch


def _build_batch(policy, device: torch.device, seed: int) -> dict:
    g = torch.Generator(device="cpu").manual_seed(seed)
    state_dim = policy.config.robot_state_feature.shape[0]
    img = torch.rand(1, 3, 240, 320, generator=g)
    state = torch.randn(1, state_dim, generator=g)
    batch = {
        "observation.state": state.to(device),
        "task": "Grasp a lego block and put it in the bin.",
    }
    for key in policy.config.image_features:
        batch[key] = img.clone().to(device)
    return batch


def _set_rtc(policy, *, enabled: bool, execution_horizon: int, max_guidance_weight: float = 10.0) -> None:
    from lerobot.common.policies.rtc.configuration_rtc import RTCConfig
    from lerobot.configs.types import RTCAttentionSchedule

    policy.config.rtc_config = RTCConfig(
        enabled=enabled,
        mode="guided",
        prefix_attention_schedule=RTCAttentionSchedule.LINEAR,
        max_guidance_weight=max_guidance_weight,
        execution_horizon=execution_horizon,
        debug=False,
    )
    policy.init_rtc_processor()


@dataclass
class LoopStats:
    underruns: int = 0
    merges: int = 0
    executed: int = 0
    handoff_deltas: list[float] | None = None
    leftover_maes: list[float] | None = None

    def __post_init__(self):
        if self.handoff_deltas is None:
            self.handoff_deltas = []
        if self.leftover_maes is None:
            self.leftover_maes = []


@torch.no_grad()
def _predict_chunk(policy, batch, noise, *, leftover, delay, horizon):
    kwargs = {}
    if policy.config.rtc_config is not None and policy.config.rtc_config.enabled:
        kwargs = {
            "prev_chunk_left_over": leftover,
            "inference_delay": delay,
            "execution_horizon": horizon,
        }
    actions = policy.predict_action_chunk(batch, noise=noise, **kwargs)
    # (1, T, A) -> (T, A)
    return actions.squeeze(0).cpu()


def _check_queue_unit(delay: int, chunk: int, action_dim: int) -> dict:
    """Pure ActionQueue mechanics (no policy)."""
    from lerobot.common.policies.rtc.action_queue import ActionQueue
    from lerobot.common.policies.rtc.configuration_rtc import RTCConfig

    cfg = RTCConfig(enabled=True, execution_horizon=10)
    q = ActionQueue(cfg)
    actions = torch.arange(chunk * action_dim, dtype=torch.float32).reshape(chunk, action_dim)

    q.merge(actions, actions, real_delay=0)
    assert q.qsize() == chunk

    for _ in range(delay):
        assert q.get() is not None
    left = q.get_left_over()
    assert left is not None and left.shape[0] == chunk - delay

    # New chunk arrives after simulated inference of `delay` steps
    new_actions = actions + 1000
    q.merge(new_actions, new_actions, real_delay=delay)
    ok_size = q.qsize() == chunk - delay
    # First queued action should be new_actions[delay]
    first = q.get()
    ok_first = first is not None and torch.allclose(first, new_actions[delay])

    return {
        "leftover_len_ok": left.shape[0] == chunk - delay,
        "merge_size_ok": ok_size,
        "merge_skip_ok": bool(ok_first),
        "pass": bool(left.shape[0] == chunk - delay and ok_size and ok_first),
    }


@torch.no_grad()
def _run_loop(
    policy,
    *,
    device: torch.device,
    rtc: bool,
    delay: int,
    horizon: int,
    control_steps: int,
    seed: int,
    request_margin: int,
) -> LoopStats:
    from lerobot.common.policies.rtc.action_queue import ActionQueue
    from lerobot.common.policies.rtc.configuration_rtc import RTCConfig

    # Policy RTC on/off; queue always uses replace+delay semantics (RTC queue mode).
    _set_rtc(policy, enabled=rtc, execution_horizon=horizon)
    q = ActionQueue(RTCConfig(enabled=True, execution_horizon=horizon))
    stats = LoopStats()
    chunk = policy.config.chunk_size
    noise_shape = (1, chunk, policy.config.max_action_dim)

    prev_action = None
    bootstrapped = False

    t = 0
    while t < control_steps:
        need = (not bootstrapped) or (q.qsize() <= delay + request_margin)
        if need:
            if not bootstrapped:
                batch = _build_batch(policy, device, seed=seed)
                noise = torch.randn(noise_shape, device=device)
                actions = _predict_chunk(
                    policy, batch, noise, leftover=None, delay=delay, horizon=horizon
                )
                q.merge(actions, actions, real_delay=0)
                stats.merges += 1
                bootstrapped = True
                continue

            idx_before = q.get_action_index()
            leftover = q.get_left_over()

            # Consume exactly `delay` actions while "inferring"
            for _ in range(delay):
                if t >= control_steps:
                    break
                a = q.get()
                if a is None:
                    stats.underruns += 1
                    a = torch.zeros(policy.config.action_feature.shape[0])
                else:
                    stats.executed += 1
                if prev_action is not None:
                    stats.handoff_deltas.append(float((a - prev_action).abs().mean()))
                prev_action = a
                t += 1

            batch = _build_batch(policy, device, seed=seed + stats.merges)
            noise = torch.randn(noise_shape, device=device)
            actions = _predict_chunk(
                policy,
                batch,
                noise,
                leftover=leftover if rtc else None,
                delay=delay,
                horizon=horizon,
            )
            q.merge(
                actions,
                actions,
                real_delay=delay,
                action_index_before_inference=idx_before,
            )
            stats.merges += 1

            # New head should track leftover[delay] (post-inference continuity)
            if leftover is not None and leftover.shape[0] > delay and q.queue is not None:
                ref = leftover[delay]
                head = q.queue[0]
                stats.leftover_maes.append(float((head - ref).abs().mean()))
            continue

        a = q.get()
        if a is None:
            stats.underruns += 1
            a = torch.zeros(policy.config.action_feature.shape[0])
        else:
            stats.executed += 1
        if prev_action is not None:
            stats.handoff_deltas.append(float((a - prev_action).abs().mean()))
        prev_action = a
        t += 1

    return stats


def main() -> int:
    parser = argparse.ArgumentParser(description="L2 RTC ActionQueue closed-loop check")
    parser.add_argument(
        "--policy_path",
        type=str,
        default="/home/sdznkj/zkx_ws/sendlerobot/outputs/test/060000/pretrained_model",
    )
    parser.add_argument("--device", type=str, default="cuda")
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--inference_delay", type=int, default=4)
    parser.add_argument("--execution_horizon", type=int, default=10)
    parser.add_argument("--control_steps", type=int, default=120)
    parser.add_argument("--request_margin", type=int, default=2)
    args = parser.parse_args()

    device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu")
    delay = args.inference_delay
    horizon = args.execution_horizon

    # --- Part A: queue unit ---
    unit = _check_queue_unit(delay=delay, chunk=50, action_dim=6)
    print("queue_unit:", json.dumps(unit, ensure_ascii=False))
    if not unit["pass"]:
        print("FAIL: ActionQueue unit checks", file=sys.stderr)
        return 2

    from lerobot.common.policies.smolvla.modeling_smolvla import SmolVLAPolicy

    print(f"Loading policy from {args.policy_path} on {device} ...")
    policy = SmolVLAPolicy.from_pretrained(args.policy_path)
    policy.to(device)
    policy.eval()

    # --- Part B: closed loops ---
    stats_rtc = _run_loop(
        policy,
        device=device,
        rtc=True,
        delay=delay,
        horizon=horizon,
        control_steps=args.control_steps,
        seed=args.seed,
        request_margin=args.request_margin,
    )
    stats_nortc = _run_loop(
        policy,
        device=device,
        rtc=False,
        delay=delay,
        horizon=horizon,
        control_steps=args.control_steps,
        seed=args.seed,
        request_margin=args.request_margin,
    )

    def _mean(xs: list[float]) -> float:
        return float(sum(xs) / len(xs)) if xs else float("nan")

    report = {
        "inference_delay": delay,
        "execution_horizon": horizon,
        "control_steps": args.control_steps,
        "rtc": {
            "underruns": stats_rtc.underruns,
            "merges": stats_rtc.merges,
            "executed": stats_rtc.executed,
            "mean_leftover_head_mae": round(_mean(stats_rtc.leftover_maes), 6),
            "mean_step_delta": round(_mean(stats_rtc.handoff_deltas), 6),
            "n_leftover_cmp": len(stats_rtc.leftover_maes),
        },
        "no_rtc": {
            "underruns": stats_nortc.underruns,
            "merges": stats_nortc.merges,
            "executed": stats_nortc.executed,
            "mean_leftover_head_mae": round(_mean(stats_nortc.leftover_maes), 6),
            "mean_step_delta": round(_mean(stats_nortc.handoff_deltas), 6),
            "n_leftover_cmp": len(stats_nortc.leftover_maes),
        },
    }

    # Pass rules:
    # 1) unit already passed
    # 2) RTC loop has zero underruns
    # 3) RTC leftover-head MAE is finite and strictly below no-RTC (when both have samples)
    rtc_mae = _mean(stats_rtc.leftover_maes)
    nortc_mae = _mean(stats_nortc.leftover_maes)
    continuity_ok = (
        len(stats_rtc.leftover_maes) > 0
        and len(stats_nortc.leftover_maes) > 0
        and rtc_mae < nortc_mae
    )
    passed = stats_rtc.underruns == 0 and continuity_ok
    report["pass"] = passed
    report["pass_reasons"] = {
        "rtc_zero_underruns": stats_rtc.underruns == 0,
        "rtc_leftover_closer_than_nortc": continuity_ok,
        "rtc_mae": None if rtc_mae != rtc_mae else round(rtc_mae, 6),
        "nortc_mae": None if nortc_mae != nortc_mae else round(nortc_mae, 6),
    }

    print(json.dumps(report, indent=2, ensure_ascii=False))
    if passed:
        print(
            f"PASS: L2 RTC queue loop ok "
            f"(underruns=0, leftover_head_mae rtc={rtc_mae:.4f} < no_rtc={nortc_mae:.4f})"
        )
        return 0

    print("FAIL: L2 criteria not met", file=sys.stderr)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())