Chương 29 — Robotics: Diffusion vs. Flow Matching, Generalist VLAs & Kiểm chứng Sim-to-Real Có Đối chứng
Chuyên đề #12–#14: PyTorch CPU trên bài toán đa phương thức né vật cản (MSE 0.0% / 100.0% va chạm vs CFM NFE=4 đạt 97.5% tại 3,894 Hz — nhanh hơn 17.23x DDIM-50 87.5% @ 226 Hz), Modular Semantic VLA đa hình thái (k=8: 84.4%, +75.0pp vs Naive -21.9pp) và chẩn đoán Sim-to-Real 4 trục (no_adaptation 0.0% -> DR+History+SysID 92.5%).
Học phần:
T1-P7-U02· Lộ trình: Part 7 — Frontier World Models & Robotics · Chương trước: Chương 28 — World ModelsBài viết chuyên sâu tích hợp: Bài #12 (Diffusion vs. Flow Matching for Robot Action Sequences), Bài #13 (What Transfers Across Robots?), Bài #14 (Diagnosing the Sim-to-Real Gap) · Đề cương SOTA 2026 (
Chương 29)Thực hành đồng hành: Lab 17 — Flow Matching vs. Diffusion Action Policy, VLAs & Sim-to-Real · Artifact:
labs/lab-17-flow-matching-vs-diffusion-action-policy/artifacts/ch29_lab17_results.json· Dossier:_research/ch-29/04-curated-blueprint.md
Mục tiêu Chương#
Sau khi hoàn tất Chương 29 và Lab 17, bạn sẽ nắm vững toàn bộ chuỗi toán học, kiến trúc hệ thống và kỹ thuật triển khai điều khiển robot hiện đại năm 2025–2026:
- Chứng minh được vì sao hồi quy bình phương tối thiểu (MSE) đơn mốt sụp đổ thảm khốc trên phân phối hành động đa mốt (Bài #12), và thiết lập chặt chẽ bài toán sinh chuỗi hành động theo đường chân trời lùi (Action Chunking, \(H_a = 8\), chân trời thực thi \(H_e \in \{1, 4, 8\}\)).
- Phân biệt được bản chất toán học và hiệu năng thực thi giữa VP-SDE Diffusion (\(v\)-prediction DDIM) có quỹ đạo cong và Conditional Flow Matching / Rectified Flow (CFM) với đường nội suy Optimal Transport thẳng, lý giải vì sao CFM giải chính xác ở
NFE = 4–8và mở khóa tần số điều khiển cao cho VLA. - Giải phẫu được nguyên lý chuyển giao đa hình thái (Cross-Embodiment Generalist VLAs, Bài #13) từ biểu diễn ngữ nghĩa bất biến không gian làm việc (End-Effector Workspace) đến đầu ra động học riêng từng robot thông qua bộ chuyển đổi có cấu trúc Jacobian, đồng thời chỉ rõ cơ chế gây chuyển giao âm (negative transfer) khi ghép padding ngây thơ.
- Thiết kế được quy trình chẩn đoán khoảng cách thực tại (Sim-to-Real Gap, Bài #14) theo 4 trục cô lập (thị giác, động lực học ma sát/khối lượng, độ trễ kích hoạt, tổng hợp), kết hợp nhận dạng hệ thống (System Identification — SysID) với Domain Randomization (DR) và lịch sử hành động-quan sát.
Trụ cột 1 — Động lực, Bản chất Toán học & Phân tích Đa thức Hành động#
Ở Chương 28, ta đã khảo sát cách World Models dự đoán sự tiến hóa trạng thái tiềm ẩn \(z_{t+k}\) nhằm phục vụ hoạch định. Tuy nhiên, khi chuyển từ hoạch định trừu tượng sang phát tín hiệu điều khiển vật lý trực tiếp cho cánh tay robot hoặc robot hình người (visuomotor control), mô hình chính sách \(\pi_\theta(A_t \mid o_t)\) đối mặt với ba rào cản cốt lõi mà học có giám sát thông thường không thể vượt qua: tính đa mốt (multimodality) của quỹ đạo hợp lệ, áp lực độ trễ vòng kín (Hz budget) khi thực thi chuỗi hành động, và sự bất đồng nhất hình thái học (embodiment mismatch) cùng khoảng cách Sim-to-Real.
Bảng Ký hiệu Toán học Thống nhất#
| Ký hiệu | Miền giá trị / Kích thước | Ý nghĩa trong Chương 29 |
|---|---|---|
| \(o_t\) | \(\mathbb{R}^{d_o}\) | Quan sát tại bước \(t\) (tư thế vật lý, cảm biến hình ảnh, hoặc biểu diễn ngữ nghĩa) |
| \(A_t = (a_t, \dots, a_{t+H_a-1})\) | \(\mathbb{R}^{H_a \times d_a}\) | Chuỗi hành động (action chunk) độ dài \(H_a\), mỗi bước có chiều \(d_a\) |
| \(H_a, H_e\) | \(\mathbb{N}_+\) | Chân trời dự đoán (\(H_a = 8\)) và chân trời thực thi trước khi tái lập kế hoạch (\(H_e \le H_a\)) |
| \(x_0 \sim \mathcal{N}(0, I)\) | \(\mathbb{R}^{H_a d_a}\) | Nhiễu Gaussian khởi đầu trong không gian chuỗi hành động làm phẳng |
| \(x_1 = A_t\) | \(\mathbb{R}^{H_a d_a}\) | Chuỗi hành động mục tiêu từ tập trình diễn chuyên gia |
| \(\text{NFE}\) | \(\mathbb{N}_+\) | Số lần gọi mạng nơ-ron (Number of Function Evaluations) để sinh một chunk |
| \(f_{\text{ctrl}} = \frac{1000 \cdot H_e}{T_{\text{chunk}}}\) | \(\text{Hz}\) | Tần số cập nhật vòng kín hữu hiệu khi chi phí suy luận mỗi chunk là \(T_{\text{chunk}}\text{ ms}\) |
| \(q_t, \dot{q}_t\) | \(\mathbb{R}^{d_e}\) | Góc khớp và vận tốc khớp trên robot hình thái \(e\) có \(d_e\) bậc tự do (DoF) |
| \(J_e(q_t), J_e^+(q_t)\) | \(\mathbb{R}^{2 \times d_e}, \mathbb{R}^{d_e \times 2}\) | Ma trận Jacobian hình học và nghịch đảo giả tắt dần (DLS pseudoinverse) |
| \(m, b, \tau_{\text{lag}}\) | \(\mathbb{R}_+, \mathbb{R}_+, \mathbb{N}\) | Khối lượng hiệu dụng, hệ số cản nhớt (damping), và độ trễ điều khiển (số bước) |
1.1. Nghịch lý Trung bình hóa Mốt (Mode-Averaging Collapse) & Action Chunking (Bài #12)#
Xét một robot di chuyển trên mặt phẳng từ vị trí \(p_0 = (-0.80, 0)\) hướng về đích \(g = (0.95, 0)\) khi chính giữa đường đi tồn tại một vật cản hình tròn tâm \((0, 0)\) bán kính \(R = 0.34\). Tập dữ liệu chuyên gia \(\mathcal{D}\) chứa hai họ quỹ đạo đối xứng hoàn toàn hợp lệ: vòng qua hành lang trên (\(y > +0.34\), nhãn chế độ \(M_+\)) hoặc vòng qua hành lang dưới (\(y < -0.34\), nhãn chế độ \(M_-\)), mỗi chế độ chiếm xác suất \(0.5\).
Nếu ta huấn luyện một chính sách tất định \(\mu_\theta(o_t)\) tối thiểu hóa sai số bình phương trung bình (MSE Behavioral Cloning):
thì nghiệm tối ưu theo nghĩa \(L_2\) luôn là kỳ vọng có điều kiện:
Giá trị trung bình này nằm chính xác trên đường thẳng \(y = 0\), lao thẳng vào tâm vật cản với tỷ lệ va chạm thực nghiệm chạm ngưỡng 100.0% dù hàm mất mát MSE hội tụ thấp. Vấn đề còn trầm trọng hơn khi tái lập kế hoạch từng bước (\(H_e = 1\)): tại bước \(t\), chính sách chọn nhánh trên; sang bước \(t+1\), nhiễu cảm biến khiến nó nhảy sang nhánh dưới, tạo ra dao động tần số cao (chattering / high jerk).
Kỹ thuật Action Chunking khắc phục dao động bằng cách dự đoán đồng thời một khối \(A_t \in \mathbb{R}^{H_a \times d_a}\) nhất quán về mặt thời gian trong không gian đa biến, và thực thi \(H_e\) hành động đầu tiên trước khi quan sát lại trạng thái mới (Receding Horizon Control). Độ giật hành động (Action Jerk) được định lượng bằng sai phân bậc nhất giữa các lệnh nối tiếp:
Tăng \(H_e\) từ \(1\) lên \(4\) hoặc \(8\) giúp giảm số lần gọi mạng trong một chu kỳ điều khiển đi \(H_e\) lần, nâng tần số \(f_{\text{ctrl}}\) lên gấp bội và hạ \(\text{Jerk}\), nhưng đồng thời đòi hỏi phản ứng môi trường không thay đổi quá nhanh trong suốt cửa sổ mở \(H_e \cdot \Delta t\).
Biểu diễn Xoay 6D Liên tục (\(\text{SO}(3)\)) & Temporal Ensembling (ACT):
- 6D Continuous Rotation (\(\mathbb{R}^6 \to \text{SO}(3)\)): Góc Euler vướng điểm kỳ dị gimbal lock, còn quaternion vướng tính đồng nhất đối cực (\(q \equiv -q\)) gây nhảy bước khi nội suy. Theo Zhou et al., các Action Chunk dự đoán hướng kẹp robot bằng cặp vector thô \((r_1, r_2) \in \mathbb{R}^6\), rồi khôi phục ma trận trực chuẩn \(R = [b_1, b_2, b_3] \in \text{SO}(3)\) trơn mọi nơi qua trực giao hóa Gram–Schmidt:
- Temporal Ensembling (ACT): Khi mô hình sinh chunk ở mỗi bước thay vì đợi hết \(H_e\), các dự đoán chồng lấp tại thời điểm \(t\) được trộn theo trọng số suy giảm mũ \(w_k = \exp(-m\, k)\) (ưu tiên quan sát mới nhất \(k = 0\)) để triệt tiêu độ giật tại ranh giới chunk:
1.2. VP-SDE Diffusion (\(v\)-Prediction DDIM) vs. Conditional Flow Matching (OT Rectified Flow)#
Để mô hình hóa phân phối có điều kiện đa mốt \(p(A_t \mid o_t)\) thay vì kỳ vọng \(\mathbb{E}[A_t \mid o_t]\), hai họ mô hình sinh liên tục thống trị robotics hiện đại là Diffusion Models và Flow Matching:
1. DDPM / DDIM Diffusion (VP-SDE với lịch cosine):
Quá trình thuận khuếch tán chuỗi hành động sạch \(x_1\) theo lịch giảm phương sai \(\bar{\alpha}_k \in (0, 1]\) qua \(K\) bước:
Nếu tham số hóa mạng để dự đoán trực tiếp \(\epsilon_\theta\), việc suy ngược về \(x_1\) tại đầu nhiễu cao (\(\bar{\alpha}_k \to 10^{-4}\)) gặp bất ổn nghiêm trọng vì \(\hat{x}_1 = \frac{x^{(k)} - \sqrt{1 - \bar{\alpha}_k}\epsilon_\theta}{\sqrt{\bar{\alpha}_k}}\) khuếch đại sai số ước lượng lên hệ số \(\frac{1}{\sqrt{\bar{\alpha}_k}} \approx 100\times\). Do đó, các hệ thống ổn định chuyển sang dự đoán vận tốc khuếch tán (\(v\)-prediction):
Tuy vậy, quỹ đạo xác suất dòng (probability flow ODE) của VP-SDE vẫn cong theo hệ số lượng giác \(\sqrt{\bar{\alpha}_k}\) và \(\sqrt{1 - \bar{\alpha}_k}\). Khi cắt giảm số bước tích phân xuống \(\text{NFE} \in \{2, 4\}\), sai số rời rạc hóa Euler/DDIM trên quỹ đạo cong làm méo phân phối đầu ra, kéo tỷ lệ va chạm tăng vọt.
2. Conditional Flow Matching (CFM / Rectified Flow) trên đường thẳng Optimal Transport:
CFM định nghĩa phép nội suy tuyến tính thẳng (straight OT conditional path) từ nhiễu \(x_0 \sim \mathcal{N}(0, I)\) ở \(t = 0\) đến chuỗi hành động thật \(x_1 = A_t\) ở \(t = 1\):
Mạng trường vector \(v_\theta(x_t, t, o)\) được huấn luyện bằng hồi quy vận tốc thẳng trên \(t \sim \mathcal{U}(0, 1)\):
Vì trường vận tốc dọc theo đường thẳng gần như không đổi chiều theo \(t\), phương pháp tích phân ODE bậc hai Heun hoặc bậc nhất Euler hội tụ chính xác ngay tại NFE = 4 (2 bước Heun) hoặc NFE = 8:
Mỗi phép cập nhật Heun tiêu tốn \(2\) NFE nhưng triệt tiêu sai số bậc \(\mathcal{O}(\Delta t^2)\), cho phép CFM giữ nguyên entropy hai mốt (\(\approx 0.99\text{–}1.00\text{ bit}\)) với tốc độ khung hình gấp hàng chục lần DDIM NFE = 50.
Phương trình Liên tục & Probability Flow ODE:
Theo cơ học dòng xác suất, khi các mẫu \(x_t = \psi_t(x_0)\) trôi dọc theo trường vận tốc tất định \(\frac{dx_t}{dt} = v_t(x_t)\), bảo toàn khối lượng mật độ \(p_t(x)\) bị ràng buộc chặt bởi Phương trình Liên tục (Continuity Equation):
Định lý Flow Matching chứng minh rằng dù tối thiểu hóa \(\mathcal{L}_{\text{CFM}}\) chỉ hồi quy trên vận tốc có điều kiện \((x_1 - x_0)\) cho từng cặp mẫu ngẫu nhiên \((x_0, x_1)\), nghiệm tối ưu biên \(v^\star(x_t, t, o) = \mathbb{E}[x_1 - x_0 \mid x_t, o]\) thỏa mãn chính xác phương trình liên tục biên, biến phân phối nhiễu \(\mathcal{N}(0, I)\) thành đúng phân phối hành động đa mốt \(p_1(A_t \mid o_t)\) mà không cần mô phỏng chuỗi Markov thuận nhiều bước.
1.3. Cơ chế Chuyển giao Đa hình thái & Generalist VLAs (Bài #13)#
Khi mở rộng chính sách từ một cánh tay \(2\)-DoF sang tay máy \(3\)-DoF có chiều dài khâu \(L^{(e)}\) khác nhau và chiều xoay khớp đảo dấu (\(\text{sign} = +1\) so với \(-1\)), câu hỏi cốt lõi của Generalist Vision-Language-Action (VLA) là: thành phần nào thực sự chuyển giao được giữa các robot, và thành phần nào gây phá hủy?
Phân tách chuỗi điều khiển qua phép biến đổi vi phân động học thuận \(x_{\text{ee}} = \text{FK}_e(q)\):
Quan sát then chốt là đại lượng ý định không gian làm việc \((x_{\text{ee}}, g, g - x_{\text{ee}}, v_{\text{ee}}) \in \mathbb{R}^2\) bất biến theo hình thái robot, trong khi ánh xạ nghịch \(v_{\text{ee}} \mapsto \dot{q} \in \mathbb{R}^{d_e}\) phụ thuộc chặt chẽ vào số bậc tự do \(d_e\), giới hạn khớp và chiều dấu Jacobian \(J_e(q)\).
- Lỗi của Naive Shared-Head Zero-Padding: Khi nối trực tiếp \((o_{\text{sem}}, q_{\text{pad}})\) vào một đầu ra chung kích thước \(\max_e d_e\) và huấn luyện gộp, cùng một cấu hình khớp \((q_1, q_2)\) ở robot nguồn (\(\text{sign} = +1\)) và robot đích (\(\text{sign} = -1\)) đòi hỏi \(\dot{q}\) trái dấu nhau, tạo ra xung đột gradient và chuyển giao âm (negative transfer) trên robot đích ngay cả khi thêm dữ liệu fine-tune.
- Modular VLA với Bộ chuyển đổi Có cấu trúc Jacobian: Đóng băng bộ mã hóa ngữ nghĩa dùng chung \(\phi_{\text{sem}}(o_{\text{sem}}) \to \hat{v}_{\text{ee}}\), và chỉ học một phần dư ma trận theo cấu trúc Jacobian cho robot đích:
Nhờ tính chất nhân tính với \(\hat{v}_{\text{ee}}\), mọi điểm cân bằng tại đích (\(\hat{v}_{\text{ee}} = 0\)) luôn đảm bảo \(\dot{q}_e = 0\) tuyệt đối không trôi dạt (zero steady-state drift), cho phép zero-shot ngay khi chưa có demo đích và positive transfer áp đảo chỉ với \(k = 8\) trình diễn.
1.4. Phân rã Sim-to-Real Có đối chứng theo 4 Trục & Nhận dạng Hệ thống (Bài #14)#
Trong triển khai thực tế, việc tinh chỉnh ngẫu nhiên toàn bộ hệ thống khi robot thất bại ngoài đời thực che khuất nguyên nhân gốc. Phương pháp chẩn đoán có đối chứng tách khoảng cách mô phỏng – thực tại thành 4 trục trực giao:
- Thị giác & Nhiễu cảm biến (\(\Delta_{\text{vis}}\)): Suy giảm tương phản hình ảnh (\(s_v < 1\)), nhiễu định vị \(\sigma_v\), và các đặc trưng gây nhiễu nền (visual distractors) không liên quan đến nhiệm vụ.
- Động lực học vật lý (\(\Delta_{\text{dyn}}\)): Sai lệch khối lượng hiệu dụng \(m_{\text{real}} \neq m_{\text{sim}}\) và hệ số ma sát cản \(b_{\text{real}} \neq b_{\text{sim}}\) trong phương trình \(\dot{v} = (u_{\text{eff}} - b v) / m\).
- Độ trễ đường ống kích hoạt (\(\Delta_{\text{lat}}\)): Độ trễ rời rạc \(\tau_{\text{lag}}\) bước giữa thời điểm chính sách phát lệnh \(a_t\) và thời điểm cơ cấu chấp hành thực thi \(u_{\text{eff}}(t) = a_{t - \tau_{\text{lag}}}\).
- Kịch bản Thực tế Tổng hợp (\(\Delta_{\text{all}}\)): Tác động phi tuyến đồng thời của cả ba trục trên, khiến mô hình chỉ thích nghi đơn trục (
SysID onlyhoặcDR only) đều thất bại gần như hoàn toàn.
Để giải quyết có hệ thống, ta kết hợp System Identification (SysID) — ước lượng độ trễ \(\hat{\tau}_{\text{lag}} = \arg\max_{\ell} \mathbb{E}[u_t \cdot \dot{v}_{t+\ell}]\) bằng tương quan chéo phản ứng bước, rồi hồi quy Ridge tìm \((\hat{m}, \hat{b})\) trên các cặp đã căn hàng độ trễ — cùng Domain Randomization (DR) có phạt \(L_1\) lên kênh nhiễu thị giác và bộ đệm lịch sử \([o_t, o_{t-1}, a_{t-1}, a_{t-2}]\) để dự báo bù trễ kín vòng.
Trụ cột 2 — Kiến trúc SOTA 2025–2026: Diffusion Policy, Flow VLAs (\(\pi_0\), GR00T N1) & Cross-Embodiment#
Trong giai đoạn 2024–2026, sự hội tụ giữa mô hình nền tảng thị giác-ngôn ngữ (VLMs) và điều khiển sinh chuỗi hành động đã định hình chuẩn công nghiệp Dual-System VLA (nhanh–chậm tách rời), thay thế hoàn toàn bộ phân tách rời rạc hóa token hành động tự hồi quy chậm chạp của thế hệ OpenVLA nguyên thủy.
Bảng So sánh Các Kiến trúc Robot Nền tảng SOTA (2025–2026)#
| Hệ thống / Nền tảng | Tổ chức & Mốc | Kiến trúc Sinh Hành động | Cỡ Mô hình & Tần số Thực thi | Cơ chế Cross-Embodiment & Sim-to-Real |
|---|---|---|---|---|
| Diffusion Policy | Columbia / TRI (Chi et al.) | DDPM / DDIM (10–100 bước khử nhiễu, U-Net 1D hoặc DiT) | ~65M–250M; 10–15 Hz (giới hạn bởi NFE cao) | Action Chunking \(H_a=8\text{–}16\), điều khiển đa mốt trên từng tác vụ đơn lẻ |
| \(\pi_0\) & \(\pi_{0.5}\) | Physical Intelligence (2024–CoRL 2025) | Conditional Flow Matching (OT paths, NFE ~ 10 bước ODE) + Knowledge Insulation |
Backbone PaliGemma 3B + Action Expert 300M @ 50 Hz |
Chặn gradient Action Expert (stop-grad) bảo toàn tiên nghiệm VLM; \(\pi_{0.5}\) khái quát sang ngôi nhà lạ |
| \(\pi_0\)-FAST | Physical Intelligence (RSS 2025) | Token hóa Action Chunk liên tục bằng DCT (Discrete Cosine Transform) + BPE | Backbone 3B tự hồi quy trên chuỗi token nén tần số |
Nén độ dài token ~10x và hội tụ nhanh hơn ~5x so với rời rạc từng bước trên tác vụ tinh vi |
| OpenVLA & OpenVLA-OFT | Stanford / UC Berkeley (2024–2025) | OpenVLA gốc dùng token rời rạc 256-bin (~4–5 Hz); OFT chuyển sang hồi quy \(L_1\) liên tục / giải mã chunk song song | Backbone 7B Llama-2 + Prismatic Vision; tăng tốc 25–50x, đạt >100 Hz |
Huấn luyện trên OXE (~970k quỹ đạo, 22 hình thái), fine-tune LoRA nhanh |
| Isaac GR00T N1 | NVIDIA (2025, arXiv:2503.14734) |
Kiến trúc 2 hệ thống: System 2 Eagle-2 VLM (~1.34B) + System 1 Flow-Matching Action DiT (~860M) |
~2.20B tham số tổng (phân biệt rõ với SmolVLA ~450M); 120 Hz toàn thân |
Đồng huấn luyện video người, teleop và dữ liệu mô phỏng Isaac Lab đa hình thái humanoid |
| LeRobot & SmolVLA | Hugging Face (2025) | VLM gọn nhẹ + Flow-Matching Expert chạy trên vòng lặp suy luận bất đồng bộ (async inference loop) | ~450M tham số tổng (nhẹ chạy edge GPU, tách trễ VLM khỏi vòng khớp) |
Mã nguồn mở chuẩn hóa dữ liệu LeRobotDataset + thích nghi độ trễ truyền thông |
| Hệ sinh thái Dữ liệu & Sim | OXE / DROID / NVIDIA Isaac Lab | Thu thập thực tế đa cảnh + GPU-accelerated Physics Randomization | OXE: 1M+ quỹ đạo, 22 robot; DROID: 76k quỹ đạo, 564 cảnh | Isaac Lab chạy hàng nghìn môi trường song song trên GPU cho DR + SysID tự động |
Phân tích Đánh đổi Sản xuất (Production Trade-offs)#
- Tần số Vòng kín vs. Dung lượng Suy luận VLM & VLA Knowledge Insulation: Các VLM kích thước
1.34B–7Bmất khoảng60–150 mscho mỗi lần mã hóa ảnh-ngôn ngữ (System 2). Bằng cách giữ lại KV-cache ngữ nghĩa ở tần số5–10 Hz, áp dụng Knowledge Insulation (\(\pi_{0.5}\), ngắt gradient điều khiển thấp tầng quay ngược làm hỏng biểu diễn VLM), và giao cho Action Expert Flow Matching (300M–860M,NFE = 4–10) sinh chunk hành động ở 50–120 Hz (System 1), robot vừa hiểu chỉ dẫn ngữ nghĩa mở vừa phản xạ trơn tru khi tiếp xúc vật cứng. - Tại sao Flow Matching & \(\pi_0\)-FAST thắng thế DDIM và Auto-Regressive Tokenization: Với ngân sách chu kỳ cứng (
20 mscho 50 Hz hoặc8.3 mscho 120 Hz), việc ép DDIM vềNFE <= 4trên VP-SDE cong gây sai số rời rạc hóa lớn. OT Flow Matching có vận tốc gần như hằng dọc đường nối \(x_0 \to x_1\) (NFE = 4–8), còn \(\pi_0\)-FAST (DCT + BPE) nén phổ tần số của cả Action Chunk nên tránh hoàn toàn hiện tượng copy-last-action của tokenization thô từng bước. - Bẫy Cross-Embodiment & Suy luận Bất đồng bộ Biên: Nếu không căn chỉnh khung tọa độ không gian làm việc hoặc không dùng bộ chuyển đổi riêng cho từng hình thái (morphology adapter), việc gộp hàng trăm nghìn quỹ đạo từ các tay máy có trục khớp trái dấu sẽ gây triệt tiêu gradient. Với robot giới hạn phần cứng biên (
SmolVLA ~450M), mô hình tách luồng quan sát-tác vụ bất đồng bộ trongLeRobotgiúp giữ độ mượt khớp ngay cả khi VLM cập nhật chậm hơn.
Playbook Quyết định Kiến trúc Robotics Sản xuất (Production Decision Playbook)#
| Kịch bản Triển khai Thực tế | Kiến trúc Khuyến nghị | Lý do Kỹ thuật & Tần số Đạt được |
|---|---|---|
| Tác vụ đơn lẻ độ chính xác cao tại chỗ (gấp, lắp ráp cố định) | ACT (Temporal Ensembling) hoặc Diffusion Policy (1D U-Net) |
Ít tham số (~65M–80M), huấn luyện nhanh từ 50–200 demo, khử giật hiệu quả |
| Tổng quát đa nhiệm vụ / Chỉ dẫn ngôn ngữ mở (manipulation & humanoid) | \(\pi_0\) / \(\pi_{0.5}\) (OT Flow + Knowledge Insulation) hoặc GR00T N1 (~2.20B) |
Kết hợp suy luận VLM System 2 (1.34B–3B) + Flow Matching System 1 đạt 50–120 Hz |
| Tác vụ dexterous chu kỳ dài cần token rời rạc nhanh | \(\pi_0\)-FAST (DCT + BPE) hoặc OpenVLA-OFT |
Nén phổ tần số chunk giúp hội tụ nhanh ~5x hoặc giải mã song song >100 Hz |
| Phần cứng biên / Chi phí thấp / Mã nguồn mở (Jetson / SO-100) | LeRobot + SmolVLA (~450M) + Async Loop |
Dấu chân bộ nhớ nhỏ, tách độ trễ VLM bất đồng bộ khỏi vòng điều khiển khớp |
| Chuyển giao từ Mô phỏng sang Robot Thực tế | DR (L1 triệt distractor) + Lag History + SysID Ridge |
Cô lập 4 trục lỗi thực tại, bù trễ chấp hành \(2\text{–}3\) bước và lệch khối lượng/ma sát |
Khám phá Tương tác #1 — Đấu trường NFE & Tần số Vòng kín (Diffusion vs. Flow Matching)#
Sử dụng mô phỏng tương tác bên dưới (dữ liệu đối chứng từ Lab 17) để thay đổi NFE, loại chính sách (CFM vs. DDIM vs. MSE) và chân trời thực thi \(H_e\), quan sát trực tiếp sự sụp đổ vào vật cản của MSE so với biên Pareto Thành công–Hz của Conditional Flow Matching:
Khám phá Tương tác #2 — Ma trận Chuyển giao Đa hình thái Generalist VLA#
Chuyển đổi số mẫu trình diễn đích (\(k \in \{0, 8, 24\}\)) và chiến lược chia sẻ kiến thức từ tay máy \(2\)-DoF sang \(3\)-DoF để kiểm chứng nguyên nhân negative transfer của Zero-Padding và mức lợi ích positive transfer (+75.0 pp tại \(k=8\)) của Modular VLA Adapter:
Trụ cột 3 — Hiện thực hóa Engineering, PyTorch Thực thi Độc lập & Độ trễ Kín vòng#
Một trong những nguyên nhân lớn nhất khiến bài toán robotics gặp lỗi âm thầm ở cấp độ kỹ thuật phần mềm là việc trộn lẫn đơn vị khung hình, rò rỉ nhiễu lịch sử khi chuẩn hóa vector trạng thái, hoặc không cô lập bộ sinh số ngẫu nhiên khi đo tần số suy luận.
Trong gói thư viện robotics_action_policy_lab (labs/lab-17-flow-matching-vs-diffusion-action-policy/src/robotics_action_policy_lab/__init__.py) của Lab 17:
- Strict PyTorch Typing & Deterministic Generators: Toàn bộ mạng (
TypedMLP,DDIMDiffusionActionPolicy,ConditionalFlowMatchingPolicy,ModularSemanticVLA,Sim2RealHistoryPolicy) dùngF.linearvàF.silutuân thủmypy --strictvới0# type: ignore, sử dụngtorch.Generatorđộc lập để bảo đảm tái lập hoàn toàn vớiseed=42. - An toàn Không gian Hành động (Jacobian Residual Guarantee): Trong
src/robotics_action_policy_lab/vla_and_sim2real.py, bộ chuyển đổi hình thái dự đoán ma trận phần dư \(\Delta K_\psi(q) \in \mathbb{R}^{d_e \times 2}\) rồi nhân với \(\hat{v}_{\text{ee}}\), bảo đảm tuyệt đối \(\hat{v}_{\text{ee}} = 0 \implies \Delta\dot{q} = 0\) để tay máy không rung lắc tại đích. - Quan trắc OpenTelemetry Không rò rỉ Bộ nhớ: Bộ xuất
BoundedInMemorySpanExporter(src/robotics_action_policy_lab/diffusion_vs_flow.py) sử dụngcollections.deque(maxlen=max_spans)khóa an toàn luồng (thread-safe) ghi nhận đủ 4 phase (policy.train_eval,nfe.pareto_sweep,vla.cross_embodiment,sim2real.ablation_diagnostic) mà không làm phình bộ nhớ vòng lặp robot.
Mã nguồn PyTorch Chạy Độc lập (Tự chứng minh Đa thức CFM + Độ trễ Sim-to-Real)#
Đoạn mã dưới đây chạy trực tiếp chỉ với torch tiêu chuẩn (không phụ thuộc tệp ngoài), minh họa định lượng cả hai nguyên lý nền tảng: (1) MSE sụp đổ vào vật cản trong khi CFM Heun NFE=4 bảo toàn phân phối hai nhánh đối xứng, và (2) độ trễ kích hoạt 2 bước phá vỡ bộ điều khiển danh định nhưng được bù hoàn toàn nhờ bộ đệm dự báo lịch sử trạng thái.
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
class ActionChunkMLP(nn.Module):
def __init__(self, in_dim: int, out_dim: int, hidden: int = 192) -> None:
super().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, hidden),
nn.SiLU(),
nn.Linear(hidden, hidden),
nn.SiLU(),
nn.Linear(hidden, hidden),
nn.SiLU(),
nn.Linear(hidden, out_dim),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
def make_bimodal_chunks(n_eps: int = 240, horizon: int = 8, seed: int = 42) -> tuple[torch.Tensor, torch.Tensor]:
"""Tạo dữ liệu đa mốt đối xứng bằng rollout kín vòng né vật cản R=0.34."""
g = torch.Generator().manual_seed(seed)
pos = torch.stack(
[torch.empty(n_eps).uniform_(-0.85, -0.70, generator=g), torch.empty(n_eps).uniform_(-0.04, 0.04, generator=g)],
dim=-1,
)
vel = torch.zeros((n_eps, 2))
branch = torch.where(torch.arange(n_eps) % 2 == 0, 1.0, -1.0)
obs_seq, act_seq = [], []
for _ in range(32):
obs_seq.append(torch.cat([pos, vel, torch.tensor([[0.95, 0.0]]).expand(n_eps, 2) - pos], dim=-1))
need_clear = pos[:, 0] < 0.25
tx = torch.where(need_clear, torch.clamp(pos[:, 0] + 0.42, max=0.28), torch.full_like(pos[:, 0], 0.95))
ty = torch.where(need_clear, branch * 0.58, torch.zeros_like(pos[:, 0]))
a = torch.clamp((torch.stack([tx, ty], dim=-1) - pos) * 1.9 - 0.3 * vel, -1.4, 1.4)
act_seq.append(a)
vel = 0.55 * vel + 0.70 * a + torch.randn(vel.shape, generator=g) * 0.02
pos = pos + 0.14 * vel
obs_t = torch.stack(obs_seq, dim=1) # (N, 32, 6)
act_t = torch.stack(act_seq, dim=1) # (N, 32, 2)
chunks_list = [act_t[:, t : t + horizon, :].reshape(n_eps, horizon * 2) for t in range(24)]
obs_flat = torch.cat([obs_t[:, t, :] for t in range(24)], dim=0)
return obs_flat, torch.cat(chunks_list, dim=0)
def rollout_bimodal(policy_fn, trials: int = 40, horizon: int = 8, exec_h: int = 4) -> tuple[float, float, float]:
g = torch.Generator().manual_seed(77)
pos = torch.stack(
[torch.empty(trials).uniform_(-0.82, -0.72, generator=g), torch.empty(trials).uniform_(-0.04, 0.04, generator=g)],
dim=-1,
)
vel = torch.zeros((trials, 2))
collided = torch.zeros(trials, dtype=torch.bool)
reached = torch.zeros(trials, dtype=torch.bool)
upper_cnt, lower_cnt = 0, 0
for step in range(0, 32, exec_h):
obs = torch.cat([pos, vel, torch.tensor([[0.95, 0.0]]).expand(trials, 2) - pos], dim=-1)
chunk = policy_fn(obs).reshape(trials, horizon, 2)
if step == 0:
upper_cnt = int((chunk[:, 0, 1] > 0.15).sum().item())
lower_cnt = int((chunk[:, 0, 1] < -0.15).sum().item())
for h in range(exec_h):
active = (~collided) & (~reached)
vel = torch.where(active.unsqueeze(-1), 0.55 * vel + 0.70 * chunk[:, h, :], vel)
pos = torch.where(active.unsqueeze(-1), pos + 0.14 * vel, pos)
collided = collided | (active & (torch.linalg.norm(pos, dim=-1) < 0.34))
reached = reached | (active & (~collided) & (torch.linalg.norm(pos - torch.tensor([[0.95, 0.0]]), dim=-1) < 0.25))
total_m = max(1, upper_cnt + lower_cnt)
p = upper_cnt / total_m
ent = 0.0 if p in (0.0, 1.0) else float(-(p * torch.log2(torch.tensor(p)) + (1 - p) * torch.log2(torch.tensor(1 - p))).item())
return float(reached.float().mean()), float(collided.float().mean()), ent
def run_standalone_demo() -> None:
torch.manual_seed(42)
obs, chunks = make_bimodal_chunks(240)
obs_mean = obs.mean(0, keepdim=True)
obs_std = obs.std(0, keepdim=True).clamp(min=1e-4)
obs_n = (obs - obs_mean) / obs_std
act_scale = chunks.std().clamp(min=1e-4)
chunks_n = chunks / act_scale
def time_feat(t: torch.Tensor) -> torch.Tensor:
return torch.cat(
[
t,
torch.sin(2 * torch.pi * t),
torch.cos(2 * torch.pi * t),
torch.sin(4 * torch.pi * t),
torch.cos(4 * torch.pi * t),
torch.sin(8 * torch.pi * t),
torch.cos(8 * torch.pi * t),
torch.sin(16 * torch.pi * t),
torch.cos(16 * torch.pi * t),
],
dim=-1,
)
mse_net = ActionChunkMLP(6, 16, hidden=64)
cfm_net = ActionChunkMLP(16 + 6 + 9, 16, hidden=192)
opt_m = torch.optim.AdamW(mse_net.parameters(), lr=4e-3)
opt_c = torch.optim.AdamW(cfm_net.parameters(), lr=3e-3, weight_decay=1e-4)
sched_c = torch.optim.lr_scheduler.CosineAnnealingLR(opt_c, T_max=1500, eta_min=1e-4)
for _ in range(1500):
perm = torch.randperm(obs.shape[0])[:512]
loss_m = F.mse_loss(mse_net(obs[perm]), chunks[perm])
opt_m.zero_grad(); loss_m.backward(); opt_m.step()
ob_b, ch_b = obs_n[perm], chunks_n[perm]
t = torch.rand((512, 1))
x0 = torch.randn_like(ch_b)
xt = (1.0 - t) * x0 + t * ch_b
loss_c = F.mse_loss(cfm_net(torch.cat([xt, ob_b, time_feat(t)], dim=-1)), ch_b - x0)
opt_c.zero_grad(); loss_c.backward(); opt_c.step()
sched_c.step()
@torch.no_grad()
def sample_cfm_heun4(o: torch.Tensor) -> torch.Tensor:
o_n = (o - obs_mean) / obs_std
x = torch.randn((o.shape[0], 16))
for s in range(2): # 2 buoc Heun = 4 NFE
t0 = torch.full((o.shape[0], 1), s * 0.5)
t1 = torch.full((o.shape[0], 1), (s + 1) * 0.5)
v1 = cfm_net(torch.cat([x, o_n, time_feat(t0)], dim=-1))
v2 = cfm_net(torch.cat([x + 0.5 * v1, o_n, time_feat(t1)], dim=-1))
x = x + 0.25 * (v1 + v2)
return torch.clamp(x * act_scale, -1.45, 1.45)
trials = 40
with torch.no_grad():
succ_m, col_m, ent_m = rollout_bimodal(mse_net, trials=trials)
t_a = time.perf_counter()
succ_c, col_c, ent_c = rollout_bimodal(sample_cfm_heun4, trials=trials)
ms_c = (time.perf_counter() - t_a) * 1000.0
print(f"[Bimodal MSE ] success={succ_m:.1%} collision={col_m:.1%} entropy={ent_m:.2f} bits")
print(f"[CFM NFE=4 ] success={succ_c:.1%} collision={col_c:.1%} entropy={ent_c:.2f} bits ({trials}-rollout time={ms_c:.1f} ms)")
# Minh hoa Sim-to-Real: Do tre 2 buoc tren khoi luong thuc m=2.45 vs du bao lich su buf[-2], buf[-1]
def sim_latency(compensate: bool) -> float:
p, v = torch.tensor([-0.75, 0.16]), torch.zeros(2)
buf = [torch.zeros(2), torch.zeros(2)]
obs_c, goal = torch.tensor([0.0, 0.24]), torch.tensor([0.85, 0.0])
for _ in range(36):
p_pred, v_pred = p.clone(), v.clone()
if compensate:
for uq in buf[-2:]:
v_pred = v_pred + 0.22 * (uq - 0.25 * v_pred) / 2.45
p_pred = p_pred + 0.22 * v_pred
wp = torch.tensor([min(p_pred[0].item() + 0.4, 0.25), 0.72]) if p_pred[0] < 0.20 else goal
u = torch.clamp(0.25 * v_pred + (2.45 / 0.22) * 0.65 * (torch.clamp((wp - p_pred) * 2.8, -1.75, 1.75) - v_pred), -2.1, 2.1)
buf.append(u)
v = v + 0.22 * (buf[-3] - 0.25 * v) / 2.45
p = p + 0.22 * v
if torch.linalg.norm(p - obs_c) < 0.36:
return -1.0 # Va cham vat can do tre
return float(torch.linalg.norm(p - goal).item())
print(f"[Sim2Real Latency=2] No-History outcome={sim_latency(False):.3f} (-1=COLLISION) | Lag-Compensated goal_dist={sim_latency(True):.3f}")
if __name__ == "__main__":
run_standalone_demo()
Trụ cột 4 — Đánh giá Định lượng Lab 17 & Điều tra Failure Modes Sim-to-Real#
Toàn bộ kết quả thực nghiệm dưới đây được trích xuất từ chạy đối chứng chuẩn hóa seed=42, quick=false trong labs/lab-17-flow-matching-vs-diffusion-action-policy/artifacts/ch29_lab17_results.json (đo trực tiếp trên PyTorch CPU, kèm kiểm thử OpenTelemetry 4 spans).
4.1. Thí nghiệm 1 — Diffusion (\(v\)-DDIM) vs. Flow Matching (OT CFM) & Chân trời Thực thi#
| Chính sách & Số NFE (\(H_e=4\)) | Tỷ lệ Thành công / Va chạm | Entropy Mốt / Action Jerk | Độ trễ (ms/chunk) & Tần số (Hz) |
Nhận định Kỹ thuật |
|---|---|---|---|---|
Deterministic MSE (NFE=1) |
0.0% / 100.0% |
0.00 bits / 0.294 |
0.29 ms (13,962 Hz) |
Nhanh nhất nhưng trung bình hóa hai nhánh \(\implies\) đâm thẳng tâm vật cản |
DDIM (NFE=1) |
0.0% / 100.0% |
0.00 bits / 0.333 |
0.49 ms (8,210 Hz) |
1 bước không đủ khử nhiễu trên đường cong VP-SDE |
Flow Matching CFM (NFE=1) |
2.5% / 97.5% |
0.00 bits / 0.398 |
0.45 ms (8,963 Hz) |
Vẫn cần tối thiểu 2–4 bước giải đường cong hỗn hợp ở biên hai mốt |
DDIM (NFE=2) |
0.0% / 100.0% |
0.00 bits / 0.323 |
0.73 ms (5,504 Hz) |
Hai bước DDIM vẫn sụp đổ vào vật cản do độ cong lịch cosine |
Flow Matching CFM (NFE=2) |
35.0% / 27.5% |
0.59 bits / 1.446 |
0.57 ms (7,062 Hz) |
1 bước Heun đã bắt đầu tách được hai nhánh hành lang |
DDIM (NFE=4) |
82.5% / 17.5% |
1.00 bits / 0.340 |
1.20 ms (3,329 Hz) |
Sai số rời rạc hóa quỹ đạo cong vẫn làm hỏng 17.5% số lượt |
Flow Matching CFM (NFE=4) |
97.5% / 2.5% |
0.99 bits / 0.607 |
1.03 ms (3,894 Hz) |
Vượt DDIM-50 cả độ chính xác lẫn tốc độ (17.23x nhanh hơn DDIM-50) |
DDIM (NFE=8) |
87.5% / 12.5% |
1.00 bits / 0.337 |
3.36 ms (1,192 Hz) |
Tỷ lệ thành công tiệm cận ngưỡng trần của DDIM trên lưới bước này |
Flow Matching CFM (NFE=8) |
100.0% / 0.0% |
1.00 bits / 0.382 |
1.71 ms (2,341 Hz) |
Thành công tuyệt đối 100.0% & entropy 1.00 bit ở hơn 2,300 Hz |
DDIM (NFE=20) |
87.5% / 12.5% |
1.00 bits / 0.357 |
5.21 ms (768 Hz) |
Tỷ lệ thành công bão hòa tại 87.5%, thua CFM-8 đến 12.5 pp |
Flow Matching CFM (NFE=20) |
100.0% / 0.0% |
1.00 bits / 0.291 |
3.51 ms (1,141 Hz) |
Thành công 100.0%, độ mượt cao (jerk=0.291) & MSE=0.0067 |
DDIM (NFE=50) |
87.5% / 12.5% |
1.00 bits / 0.366 |
17.70 ms (226 Hz) |
Tốn chi phí tính toán cao và chậm gấp 17.23x so với CFM-4 |
Flow Matching CFM (NFE=50) |
100.0% / 0.0% |
1.00 bits / 0.275 |
10.21 ms (392 Hz) |
Độ giật thấp nhất (0.275) và đường cong hội tụ mịn hoàn hảo |
Phân tích Chân trời Thực thi (exec_horizon_ablation, \(H_e \in \{1, 4, 8\}\)):
- Với
CFM-8, tăng \(H_e = 1 \to 4 \to 8\) nâng tỷ lệ thành công từ47.5% -> 92.5% -> 97.5%, giảm mạnh độ giậtmean_action_jerktừ0.784 -> 0.415 -> 0.358, và đẩy tần số điều khiển hữu hiệu từ396 Hz -> 2,047 Hz -> 4,909 Hz. - Với
DDIM-20, tăng \(H_e = 1 \to 4 \to 8\) cũng cải thiện từ37.5% -> 75.0% -> 90.0%, giảm jerk từ0.760 -> 0.381 -> 0.285, và tăng tần số từ185 Hz -> 528 Hz -> 1,078 Hz, nhưng vẫn chậm hơnCFM-8trên4.5xtại cùng \(H_e = 8\).
4.2. Thí nghiệm 2 — Kết quả Cross-Embodiment Generalist VLA (2-DoF Source -> 3-DoF Target)#
| Chiến lược Chuyển giao | Zero-Shot (k=0) MSE / Succ / EE Err |
Few-Shot (k=8) MSE / Succ / EE Err |
Few-Shot (k=24) MSE / Succ / EE Err |
|---|---|---|---|
Target-Only Scratch |
0.755 / 15.6% / 0.327 |
1.063 / 9.4% / 0.928 |
0.201 / 53.1% / 0.724 |
Naive Shared Head (Zero-Pad) |
0.601 / 3.1% / 1.526 |
0.389 / 9.4% / 0.863 |
0.263 / 31.2% / 0.557 (-21.9 pp Negative Transfer) |
Modular VLA (Semantic + Adapter) |
0.623 / 65.6% / 0.183 |
0.380 / 84.4% / 0.155 (+75.0 pp) |
0.191 / 84.4% / 0.0566 (+31.3 pp) |
Phát hiện Thực nghiệm (Bài #13):
- Khi hai robot có dấu khớp ngược nhau (\(\text{sign} = +1\) vs. \(-1\)), việc ghép chung đầu ra zero-padding kéo tỷ lệ chạm đích tại \(k = 24\) xuống
31.2%— tệ hơn tới21.9 điểm phần trămso với huấn luyện lại từ đầu (53.1%), chứng minh hiện tượng chuyển giao âm. - Bộ mã hóa ngữ nghĩa bất biến kết hợp Jacobian residual adapter \(\Delta K_\psi(q)\,\hat{v}_{\text{ee}}\) đạt ngay
65.6%zero-shot (k=0), nhảy lên84.4%chỉ với8demo đích (vượtTarget Scratch75.0 pp) và siết sai số vị trí cuối xuống0.0566ởk=24.
4.3. Thí nghiệm 3 — Chẩn đoán 4 Trục Sim-to-Real & Phục hồi Kết hợp (Bài #14)#
Bộ nhận dạng hệ thống SysID trên chuỗi kích thích ngẫu nhiên khôi phục chính xác các tham số thực bị che khuất: khối lượng \(\hat{m} = 2.4548\) (thực \(2.45\)), độ cản \(\hat{b} = 0.2556\) (thực \(0.25\)), và độ trễ pipeline lag = 2 bước (chính xác tuyệt đối).
| Chiến lược Thích nghi | Nominal Sim | Visual Shift (\(\Delta_{\text{vis}}\)) | Dynamics Shift (\(\Delta_{\text{dyn}}\)) | Latency 2-step (\(\Delta_{\text{lat}}\)) | Combined Real-World (\(\Delta_{\text{all}}\)) |
|---|---|---|---|---|---|
no_adaptation |
100.0% (0.064) |
15.0% (col 85.0%) |
0.0% (dist 0.274) |
0.0% (col 100.0%) |
0.0% (col 85.0%, dist 1.180) |
sysid_only |
2.5% (col 97.5%) |
65.0% (col 27.5%) |
100.0% (0.149) |
100.0% (0.088) |
35.0% (col 5.0%, dist 0.811) |
dr_only |
100.0% (0.064) |
100.0% (0.080) |
0.0% (dist 0.675) |
0.0% (dist 0.412) |
0.0% (col 0.0%, dist 1.098) |
dr_history_sysid |
100.0% (0.083) |
100.0% (0.078) |
100.0% (0.136) |
100.0% (0.110) |
92.5% (col 0.0%, dist 0.144) |
Bảng chẩn đoán Failure Modes theo Ma trận Đối chứng:
- Trục đơn lẻ nào cũng đủ đánh sập chính sách danh định
no_adaptation(giảm từ100.0%xuống15.0%trước nhiễu thị giác, và về0.0%trước sai lệch khối lượng hoặc độ trễ2bước). sysid_onlychữa dứt điểm sai lệch khối lượng/ma sát (100.0%trêndynamics_friction_mass_shift) nhưng sụp đổ ngay trênnominal_sim(2.5%) và thất bại trên kịch bản tổng hợp có nhiễu thị giác/tương phản (35.0%combined).dr_onlyđạt miễn nhiễm tuyệt đối với nhiễu nền và suy giảm tương phản thị giác (100.0%trênvisual_noise_shift), nhưng thiếu nhận diện động lực học thực và bộ nhớ trễ nên kẹt hoàn toàn trước sai lệch khối lượng hoặc lag (0.0%combined).- Chỉ khi hợp nhất SysID + Action/Obs History (
28-dim buffer:[obs_t, o_{t-1}, o_{t-2}, a_{t-1..t-3}]) + Visual DR (tỉa \(L_1\)) phủ toàn bộ dải[nominal, real], hệ thống mới tổng quát mượt trên cả 5 chế độ (100% / 100% / 100% / 100% / 92.5%) với0.0%va chạm!
Khám phá Tương tác #3 — Bảng Chẩn đoán 4 Trục Sim-to-Real & Phục hồi Thực tế#
Chọn bất kỳ chế độ môi trường và chiến lược thích nghi nào bên dưới để quan sát phân rã tỷ lệ thành công, mức va chạm và khoảng cách tới đích trên cả 20 ô của ma trận đối chứng trong Lab 17:
Trụ cột 5 — Tài liệu Đọc, Kiểm tra Nhanh, Thực hành Lab 17 & Tiêu chuẩn Chấm điểm#
5.1. Tài liệu Đọc Kinh điển & Frontier SOTA (2023–2026)#
- Diffusion Policy (
Chi et al., RSS 2023): Khai sinh mô hình khuếch tán có điều kiện kết hợp Action Chunking và Receding Horizon Control để giải quyết đa mốt điều khiển visuomotor. - ACT / ALOHA (
Zhao et al., RSS 2023): Đề xuất Action Chunking với CVAE Transformer và kỹ thuật Temporal Ensembling trọng số mũ \(w_k = \exp(-m\, k)\) triệt tiêu sai số ghép bước. - Flow Matching & Rectified Flow (
Lipman et al., ICLR 2023;Liu et al., ICLR 2023): Chứng minh đường nội suy Optimal Transport thẳng cho phép tích phân ODE ít bước (NFE = 4–8) mà vẫn bảo toàn phương trình liên tục biên. - \(\pi_0\), \(\pi_0\)-FAST & \(\pi_{0.5}\) (
Black et al., Physical Intelligence 2024–CoRL 2025): Kết hợp VLM PaliGemma3B+ Flow-Matching Action Expert300M(50 Hz), nén phổ action chunk bằng DCT + BPE (~5xhội tụ nhanh hơn) và Knowledge Insulation ngăn gradient điều khiển làm thoái hóa VLM. - OpenVLA & OpenVLA-OFT (
Kim et al., CoRL 2024–2025): Khám phá970kquỹ đạoOXE, đồng thời chứng minh giải mã song song + hồi quy liên tụcOFTtăng tốc gấp25–50xso với token rời rạc tự hồi quy. - Isaac GR00T N1 (
NVIDIA, 2025,arXiv:2503.14734): Kiến trúc dual-system cho robot hình người gồm System 2 Eagle-2 VLM (~1.34B) và System 1 Flow-Matching Action DiT (~860M) đạt 120 Hz toàn thân trên nguồn hợp nhất video người + Isaac Lab. - LeRobot & SmolVLA (
Cadene / Shukor et al., Hugging Face 2025): Bộ khung chuẩn mở vớiSmolVLA (~450M)sử dụng vòng lặp suy luận bất đồng bộ tách độ trễ VLM khỏi điều khiển biên. - RMA & Controlled Sim-to-Real Ablation (
Kumar et al., RSS 2021+Bài #14): Tách biệt chuẩn đoán 4 trục (thị giác, động lực học, độ trễ chấp hành, tổng hợp) và phối hợp lịch sử quan sát-hành động cùng nhận dạng hệ thống.
5.2. Tám Câu hỏi Trắc nghiệm Kiểm tra Nhanh (T1-P7-U02, Q1–Q8)#
- Q1 — Nghịch lý MSE Behavioral Cloning: Vì sao tối thiểu hóa \(\mathbb{E}[\lVert \mu_\theta(o) - A \rVert_2^2]\) trên hai đường né vật cản đối xứng dẫn tới
100.0%va chạm (0.00 bitsentropy)? (Gợi ý: Nghiệm \(L_2\) luôn hội tụ về kỳ vọng \(\frac{1}{2}A_+ + \frac{1}{2}A_- \approx 0\) đâm xuyên tâm vật cản). - Q2 — Lợi thế Pareto của Conditional Flow Matching ở NFE Thấp: Tại sao CFM Heun
NFE = 4(97.5%,1.03 ms,17.23xnhanh hơn DDIM-50) thắng áp đảo VP-SDE DDIM ở vùngNFE <= 4? (Gợi ý: Đường OT \(x_t = (1-t)x_0 + t x_1\) có vận tốc thẳng không đổi hướng, không vướng sai số rời rạc hóa đường cong lượng giác). - Q3 — Bất ổn Số học của \(\epsilon\)-prediction vs. \(v\)-prediction: Ở vùng nhiễu nặng \(\bar{\alpha}_k = 10^{-4}\), vì sao
v-predictiontránh nổ sai số khi phục hồi \(\hat{x}_1\)? (Gợi ý: Công thức \(\frac{x - \sqrt{1-\bar{\alpha}}\epsilon_\theta}{\sqrt{\bar{\alpha}}}\) nhân sai số thêm \(\approx 100\times\), trong khi \(\hat{x}_1 = \sqrt{\bar{\alpha}}x - \sqrt{1-\bar{\alpha}}v_\theta\) bị chặn biên hữu hạn). - Q4 — Đánh đổi Chân trời Thực thi Action Chunking (\(H_e\)): Khi tăng \(H_e\) từ \(1 \to 4 \to 8\) trên
CFM-8(Lab 17), các chỉ số jerk, \(f_{\text{ctrl}}\), và rủi ro vòng hở thay đổi thế nào? (Gợi ý: Jerk giảm0.784 -> 0.358, \(f_{\text{ctrl}}\) tăng396 -> 4,909 Hz, nhưng cửa sổ hở quá dài dễ lỡ phản ứng khi mục tiêu dịch chuyển nhanh). - Q5 — Kiến trúc Dual-System VLA (
π0&GR00T N1): Vai trò tách tần số giữa System 2 (PaliGemma 3B/Eagle-2 ~1.34B,5–10 Hz) và System 1 (Action Expert 300M/Action DiT ~860M,50–120 Hz) là gì? (Gợi ý: Tái dùng KV-cache ngữ nghĩa tốn kém ở tần thấp để System 1 giải Flow Matching phản xạ cao tần). - Q6 — Cơ chế Gây Negative Transfer Đa Hình thái (
2-DoF -> 3-DoF): Vì saoNaive Shared Head (Zero-Pad)làmreach_successtụt-21.9 ppso vớiTarget Scratchở \(k = 24\)? (Gợi ý: Khác biệt số chiều DoF và dấu Jacobian đảo ngược giữa hai tay máy gây xung đột gradient trực tiếp ở đầu ra chung). - Q7 — Đảm bảo Zero Steady-State Drift ở Modular VLA: Cấu trúc \(\dot{q}_e = (\hat{J}_e^+(q) + \Delta K_\psi(q))\,\hat{v}_{\text{ee}}\) triệt tiêu trôi dạt tĩnh bằng cách nào? (Gợi ý: Tính nhân tính tuyến tính theo \(\hat{v}_{\text{ee}}\) ép \(\Delta \dot{q}_e = 0\) mỗi khi ý định không gian làm việc đạt \(\hat{v}_{\text{ee}} = 0\)).
- Q8 — Triage & Phục hồi Sim-to-Real 4 Trục: Vì sao cả
sysid_onlylẫndr_onlyđều thất bại trướccombined_real_worldtrong khidr_history_sysidđạt92.5%? (Gợi ý: Chỉ hợp nhất DR phủ dải[nominal, real]+ tỉaL1distractor + buffer lịch sử[o_t, o_{t-1}, o_{t-2}, a_{t-1..t-3}]+ SysID mới đồng thời triệt cả ba nguồn nhiễu thị giác, khối lượng/ma sát và trễ 2 bước).
5.3. Thực hành Lab 17 & 6 Bài tập Chuyên sâu#
Hướng dẫn Chạy Nhanh Lab 17#
Thực hiện toàn bộ thí nghiệm đối chứng, kiểm định kiểu tĩnh nghiêm ngặt và xuất artifact tại Lab 17 README:
Set-Location D:\FSDS-SOTA-Curriculum\02-track-1-data-science-and-ai\part-07-frontier-world-models-robotics\labs\lab-17-flow-matching-vs-diffusion-action-policy
uv lock --check
uv run --no-sync python scripts/run_lab_demo.py --seed 42
uv run --no-sync pytest -p no:cacheprovider -v
6 Bài tập Chuyên sâu (Tự luận & Mở rộng Mã nguồn)#
- Bài tập 1 — Phân tích Định lý Mode Collapse & Chính tắc hóa Entropy Hai nhánh: Chứng minh bằng giải tích vì sao tối thiểu hóa \(\mathbb{E}[\lVert \mu(o) - A \rVert_2^2]\) trên hỗn hợp đối xứng \(\frac{1}{2}\delta(A - A_+) + \frac{1}{2}\delta(A - A_-)\) luôn cho nghiệm \(\mu^\star = \frac{1}{2}(A_+ + A_-)\), và giải thích vì sao
Deterministic MSEtrong Lab 17 đạt entropy0.00 bitsvà100.0%va chạm. Đề xuất bổ sung một biến nhiễu đầu vào hoặc bộ chọn mode có giám sát rồi kiểm tra xem có thể đạt đa mốt mà không cần mô hình sinh liên tục hay không. - Bài tập 2 — So sánh Quỹ đạo Cong \(v\)-DDIM vs. Straight-Path Rectified Flow ở
NFE=2..8: Mởsrc/robotics_action_policy_lab/diffusion_vs_flow.pytrong Lab 17, chứng minh vì sao \(\epsilon\)-prediction bất ổn khi \(\bar{\alpha}_T = 10^{-4}\) so với \(v\)-prediction, và cài đặt thêm một bước Reflow (1-Rectified Flow distillation) nối các cặp \((x_0, x_1)\) sinh ra từ chính CFM đã huấn luyện để kiểm tra xemNFE = 1–2có vượt ngưỡng97.5%ởNFE = 4hay không. - Bài tập 3 — Quy hoạch Chân trời Thực thi \(H_e\) & Ngân sách Tần số Robot Công nghiệp: Dựa vào bảng kết quả \(H_e \in \{1, 4, 8\}\) trong Lab 17 (
CFM-8đạt396 -> 2,047 -> 4,909 Hzvà giảm jerk0.784 -> 0.358), viết hàm tính băng thông tối đa cho phép nếu một hệ thống phần cứng 50 Hz có backbone VLM tốn18 msvà mạng Action Expert tốn1.03 ms/chunk(NFE=4). Chỉ ra giá trị \(H_e\) tối thiểu bảo toàn thời gian thực và phân tích rủi ro khi vật thể mục tiêu dịch chuyển trong pha vòng hở. - Bài tập 4 — Khắc phục Negative Transfer bằng Kiến trúc Modular VLA Adapter: Kiểm tra hàm
forward_target_adaptertrongsrc/robotics_action_policy_lab/vla_and_sim2real.py. Chứng minh đại số vì sao phân tích tách \(\dot{q}_e = (\hat{J}_e^+(q) + \Delta K_\psi(q))\,\hat{v}_{\text{ee}}\) triệt tiêu hoàn toàn sai số trôi tĩnh tại \(\hat{v}_{\text{ee}} = 0\), và thử nghiệm mở rộng thêm một tay máy đích \(4\)-DoF có giới hạn góc khớp chặt để đo đường cong sample efficiency tại \(k \in \{0, 8, 24\}\). - Bài tập 5 — Nhận dạng Độ trễ Pipeline & Tham số Vật lý (SysID Lag Alignment): Trong
Sim2RealPhysicsEnv.identify_system_parameters(src/robotics_action_policy_lab/vla_and_sim2real.py), kiểm chứng điều gì xảy ra với ước lượng Ridge \((\hat{m}, \hat{b})\) nếu bạn cố ý bỏ qua bước căn hàng tương quan chéo (giả sử sai \(\ell = 0\) trong khi \(\tau_{\text{lag}} = 2\)). Lượng hóa độ lệch tỷ lệ sai số của \(\hat{m}\) khi hồi quy trên cặp chưa căn pha. - Bài tập 6 — Thiết kế Pipeline Triage Cho Kịch bản Thực tế Tổng hợp: Giả sử robot thực đạt
100.0%trong Nominal Sim nhưng chỉ đạt15.0%ngoài xưởng sản xuất, bạn chỉ có ngân sách cho 2 lần chạy thử nghiệm đối chứng trước khi tái huấn luyện. Sử dụng cây chẩn đoán 4 trục của Trụ cột 4, xây dựng quy trình 2 bước tối thiểu hóa chi phí phần cứng để định danh tỷ trọng đóng góp giữa \(\Delta_{\text{vis}}\), \(\Delta_{\text{dyn}}\), và \(\Delta_{\text{lat}}\), rồi chứng minh vì saodr_history_sysidphục hồicombined_real_worldtừ0.0%lên92.5%.
Tiêu chuẩn Chấm điểm Tổng hợp (T1-P7-U02)#
| Tiêu chuẩn | Yêu cầu Bắt buộc để Đạt Điểm Tối đa (100%) |
|---|---|
| Chất lượng Toán học & Chứng minh | Dẫn xuất chính xác nghiệm \(L_2\) của đa mốt, công thức \(v\)-prediction vs. OT velocity \(x_1 - x_0\), 6D Gram-Schmidt \(\text{SO}(3)\), Temporal Ensembling, Continuity Equation, Jacobian pseudoinverse DLS và hồi quy Ridge SysID. |
| Mã nguồn & Kiểm thử Tự động | Toàn bộ 22 test cases (pytest), ruff, mypy --strict (0 # type: ignore), uv.lock --check, và OpenTelemetry 4 spans đều thông qua sạch sẽ. |
| Khớp Số liệu & Điều tra Lỗi | Mọi báo cáo và biểu đồ phân tích đối chiếu đúng với artifacts/ch29_lab17_results.json (CFM-4 97.5%, 17.23x, Modular VLA 84.4%, Full Stack Sim-to-Real 92.5%). |
Bimodal Success Rate (%) Across NFE: Conditional Flow Matching vs DDIM Diffusion
Closed-Loop Control Frequency (Hz) at H_e=4 Across Policies & NFEs
3-DoF Target Reaching Success (%) Across Transfer Strategies (k=0, 8, 24)
Controlled Sim-to-Real Success (%): Single-Factor Attribution & Combined Recovery
Experiment 1: Deterministic MSE vs DDIM Diffusion vs Conditional Flow Matching
| Policy & NFE (H_e=4) | Success / Collision | Mode Entropy / Jerk | Latency (ms) & Control Hz |
|---|---|---|---|
| Deterministic MSE (NFE=1) | 0.0% / 100.0% | 0.00 bits / jerk=0.294 | 0.29 ms (13962 Hz) |
| DDIM NFE=1 | 0.0% / 100.0% | 0.00 bits / jerk=0.333 | 0.49 ms (8210 Hz) |
| Flow (CFM) NFE=1 | 2.5% / 97.5% | 0.00 bits / jerk=0.398 | 0.45 ms (8963 Hz) |
| DDIM NFE=4 | 82.5% / 17.5% | 1.00 bits / jerk=0.340 | 1.20 ms (3329 Hz) |
| Flow (CFM) NFE=4 | 97.5% / 2.5% | 0.99 bits / jerk=0.607 | 1.03 ms (3894 Hz) |
| DDIM NFE=8 | 87.5% / 12.5% | 1.00 bits / jerk=0.337 | 3.36 ms (1192 Hz) |
| Flow (CFM) NFE=8 | 100.0% / 0.0% | 1.00 bits / jerk=0.382 | 1.71 ms (2341 Hz) |
| DDIM NFE=20 | 87.5% / 12.5% | 1.00 bits / jerk=0.357 | 5.21 ms (768 Hz) |
| Flow (CFM) NFE=20 | 100.0% / 0.0% | 1.00 bits / jerk=0.290 | 3.51 ms (1141 Hz) |
| DDIM NFE=50 | 87.5% / 12.5% | 1.00 bits / jerk=0.366 | 17.70 ms (226 Hz) |
| Flow (CFM) NFE=50 | 100.0% / 0.0% | 1.00 bits / jerk=0.275 | 10.21 ms (392 Hz) |
Experiment 1B: Action-Chunking Execution Horizon Replanning (H_e in {1, 4, 8})
| Policy & Execution Horizon | Success / Collision | Action Jerk | Effective Control Hz |
|---|---|---|---|
| DDIM-20 (H_e=1) | 37.5% / 62.5% | 0.759 | 185 Hz |
| CFM-8 (H_e=1) | 47.5% / 52.5% | 0.784 | 396 Hz |
| DDIM-20 (H_e=4) | 75.0% / 22.5% | 0.381 | 528 Hz |
| CFM-8 (H_e=4) | 92.5% / 7.5% | 0.415 | 2047 Hz |
| DDIM-20 (H_e=8) | 90.0% / 10.0% | 0.285 | 1078 Hz |
| CFM-8 (H_e=8) | 97.5% / 2.5% | 0.357 | 4909 Hz |
Experiment 2: Cross-Embodiment Transfer (2-DoF Source -> 3-DoF Target Arm)
| Transfer Strategy | Zero-Shot (k=0) MSE / Succ | Few-Shot (k=8) MSE / Succ | Few-Shot (k=24) MSE / Succ |
|---|---|---|---|
| Target-Only Scratch | 0.755 / 15.6% | 1.063 / 9.4% | 0.201 / 53.1% |
| Naive Shared Head (Zero-Pad) | 0.601 / 3.1% | 0.389 / 9.4% | 0.263 / 31.2% |
| Modular VLA (Semantic + Adapter) | 0.623 / 65.6% | 0.380 / 84.4% | 0.191 / 84.4% |
Experiment 3: Controlled 4-Axis Sim-to-Real Gap Diagnostic Matrix (Success %)
| Adaptation Strategy | Nominal / Visual Shift | Dynamics Shift / 2-Step Latency | Combined Real-World Shift |
|---|---|---|---|
| no_adaptation | 100.0% / 15.0% | 0.0% / 0.0% | 0.0% (coll=85.0%) |
| sysid_only | 2.5% / 65.0% | 100.0% / 100.0% | 35.0% (coll=5.0%) |
| dr_only | 100.0% / 100.0% | 0.0% / 0.0% | 0.0% (coll=0.0%) |
| dr_history_sysid | 100.0% / 100.0% | 100.0% / 100.0% | 92.5% (coll=0.0%) |
02-track-1-data-science-and-ai/part-07-frontier-world-models-robotics/labs/lab-17-flow-matching-vs-diffusion-action-policy
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "robotics-action-policy-lab"
version = "0.1.0"
description = "Lab 17: Diffusion vs Conditional Flow Matching Action Policies, Cross-Embodiment Generalist VLAs, and Controlled 4-Axis Sim-to-Real Gap Ablations for T1-P7-U02."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_ignores = true
ignore_missing_imports = true
"""Lab 17: Diffusion vs Conditional Flow Matching, Cross-Embodiment VLAs, and Sim-to-Real Ablations."""
from robotics_action_policy_lab.diffusion_vs_flow import (
BimodalObstacleNavEnv,
BoundedInMemorySpanExporter,
ConditionalFlowMatchingPolicy,
DDIMDiffusionActionPolicy,
DeterministicMSEChunkPolicy,
Exp1DiffusionVsFlowReport,
NavEnvSpec,
PolicyEvalMetrics,
TypedMLP,
create_in_memory_otel_tracer,
evaluate_policy_closed_loop,
run_diffusion_vs_flow_benchmark,
)
from robotics_action_policy_lab.vla_and_sim2real import (
CrossEmbodimentPoint,
EmbodimentSpec,
Exp2CrossEmbodimentReport,
Exp3Sim2RealReport,
FullRoboticsBenchmarkReport,
ModularSemanticVLA,
NaiveJointPolicy,
OtelSummary,
PlanarArmKinematics,
Sim2RealHistoryPolicy,
Sim2RealPhysicsEnv,
Sim2RealRegimePoint,
run_cross_embodiment_vla_study,
run_full_robotics_benchmark,
run_sim2real_ablation_diagnostic,
)
__all__ = [
"BimodalObstacleNavEnv",
"BoundedInMemorySpanExporter",
"ConditionalFlowMatchingPolicy",
"CrossEmbodimentPoint",
"DDIMDiffusionActionPolicy",
"DeterministicMSEChunkPolicy",
"EmbodimentSpec",
"Exp1DiffusionVsFlowReport",
"Exp2CrossEmbodimentReport",
"Exp3Sim2RealReport",
"FullRoboticsBenchmarkReport",
"ModularSemanticVLA",
"NaiveJointPolicy",
"NavEnvSpec",
"OtelSummary",
"PlanarArmKinematics",
"PolicyEvalMetrics",
"Sim2RealHistoryPolicy",
"Sim2RealPhysicsEnv",
"Sim2RealRegimePoint",
"TypedMLP",
"create_in_memory_otel_tracer",
"evaluate_policy_closed_loop",
"run_cross_embodiment_vla_study",
"run_diffusion_vs_flow_benchmark",
"run_full_robotics_benchmark",
"run_sim2real_ablation_diagnostic",
]
"""Experiment 1 (Article #12): Diffusion vs Conditional Flow Matching on Multimodal Action Chunks."""
from __future__ import annotations
import math
import threading
import time
from collections import deque
from collections.abc import Sequence
from typing import Literal, cast
import torch
import torch.nn as nn
import torch.nn.functional as F
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from opentelemetry.trace import Tracer
from pydantic import BaseModel, ConfigDict, Field
# ---------------------------------------------------------------------------
# Thread-Safe Bounded OpenTelemetry Exporter (Zero Global State Leaks)
# ---------------------------------------------------------------------------
class BoundedInMemorySpanExporter(SpanExporter):
"""Thread-safe bounded in-memory OpenTelemetry span exporter using a fixed-capacity deque."""
def __init__(self, max_spans: int = 512) -> None:
if max_spans < 1:
raise ValueError("max_spans must be >= 1")
self._max_spans = max_spans
self._spans: deque[ReadableSpan] = deque(maxlen=max_spans)
self._lock = threading.Lock()
self._stopped = False
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
if self._stopped:
return SpanExportResult.FAILURE
with self._lock:
self._spans.extend(spans)
return SpanExportResult.SUCCESS
def get_finished_spans(self) -> tuple[ReadableSpan, ...]:
with self._lock:
return tuple(self._spans)
def clear(self) -> None:
with self._lock:
self._spans.clear()
def shutdown(self) -> None:
self._stopped = True
def force_flush(self, timeout_millis: int = 30000) -> bool:
_ = timeout_millis
return True
def create_in_memory_otel_tracer(
instrumentation_name: str = "robotics_action_policy_lab",
max_spans: int = 512,
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, Tracer]:
"""Create an isolated TracerProvider + BoundedInMemorySpanExporter for deterministic tests."""
exporter = BoundedInMemorySpanExporter(max_spans=max_spans)
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer(instrumentation_name)
return provider, exporter, tracer
# ---------------------------------------------------------------------------
# Strictly-Typed Neural Building Blocks (mypy --strict compatible)
# ---------------------------------------------------------------------------
class TypedMLP(nn.Module):
"""Multi-layer perceptron using F.linear and F.silu for full mypy --strict compatibility."""
def __init__(self, dims: Sequence[int]) -> None:
super().__init__()
if len(dims) < 2:
raise ValueError("TypedMLP requires at least input and output dimensions")
linears = [nn.Linear(dims[i], dims[i + 1]) for i in range(len(dims) - 1)]
self.net = nn.ModuleList(linears)
self._linears: tuple[nn.Linear, ...] = tuple(linears)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = x
last_idx = len(self._linears) - 1
for idx, layer in enumerate(self._linears):
out = F.linear(out, layer.weight, layer.bias)
if idx < last_idx:
out = F.silu(out)
return out
def sinusoidal_time_embedding(t: torch.Tensor, dim: int = 16) -> torch.Tensor:
"""Create sinusoidal Fourier embeddings for scalar diffusion/flow time t in [0, 1]."""
half = dim // 2
freqs = torch.exp(
-math.log(1000.0) * torch.arange(0, half, dtype=t.dtype, device=t.device) / max(1, half)
)
args = t.view(-1, 1) * freqs.view(1, -1) * (2.0 * math.pi)
emb = torch.cat([torch.sin(args), torch.cos(args)], dim=-1)
if emb.shape[-1] < dim:
emb = F.pad(emb, (0, dim - emb.shape[-1]))
return emb
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Schemas (ConfigDict(extra="forbid"))
# ---------------------------------------------------------------------------
class NavEnvSpec(BaseModel):
"""Specification for the 2D Bimodal Obstacle-Avoidance Action-Chunking Benchmark."""
model_config = ConfigDict(extra="forbid")
obs_dim: int = Field(default=6, ge=4, le=32)
action_horizon: int = Field(default=8, ge=2, le=32)
action_dim: int = Field(default=2, ge=2, le=8)
obstacle_center_x: float = Field(default=0.0)
obstacle_center_y: float = Field(default=0.0)
obstacle_radius: float = Field(default=0.34, gt=0.05, le=0.8)
goal_x: float = Field(default=0.95)
goal_y: float = Field(default=0.0)
goal_tolerance: float = Field(default=0.22, gt=0.05, le=0.6)
dt: float = Field(default=0.14, gt=0.02, le=0.5)
vel_damping: float = Field(default=0.45, gt=0.0, le=1.0)
accel_gain: float = Field(default=0.70, gt=0.1, le=2.0)
max_steps: int = Field(default=28, ge=10, le=100)
class PolicyEvalMetrics(BaseModel):
"""Closed-loop success, collision, multimodality, smoothness, and latency/Hz metrics."""
model_config = ConfigDict(extra="forbid")
policy_name: Literal["deterministic_mse", "ddim_diffusion", "conditional_flow_matching"]
nfe: int = Field(..., ge=1)
exec_horizon: int = Field(..., ge=1)
success_rate: float = Field(..., ge=0.0, le=1.0)
collision_rate: float = Field(..., ge=0.0, le=1.0)
mode_entropy_bits: float = Field(..., ge=0.0, le=1.01)
upper_mode_fraction: float = Field(..., ge=0.0, le=1.0)
lower_mode_fraction: float = Field(..., ge=0.0, le=1.0)
mean_action_jerk: float = Field(..., ge=0.0)
chunk_mse_to_nearest_mode: float = Field(..., ge=0.0)
inference_ms_per_chunk: float = Field(..., gt=0.0)
control_hz: float = Field(..., gt=0.0)
class Exp1DiffusionVsFlowReport(BaseModel):
"""Complete Experiment 1 report comparing MSE, DDIM Diffusion, and Flow Matching."""
model_config = ConfigDict(extra="forbid")
env_spec: NavEnvSpec
mse_baseline: PolicyEvalMetrics
nfe_pareto_sweep: list[PolicyEvalMetrics]
exec_horizon_ablation: list[PolicyEvalMetrics]
cfm_vs_ddim_speedup_at_equal_or_higher_success: float = Field(..., ge=1.0)
ot_interpolant_max_endpoint_error: float = Field(..., ge=0.0)
# ---------------------------------------------------------------------------
# 2D Bimodal Obstacle-Avoidance Environment & Expert Dataset
# ---------------------------------------------------------------------------
class BimodalObstacleNavEnv:
"""2D planar robot navigation around a central obstacle inducing symmetric bimodal actions."""
def __init__(self, spec: NavEnvSpec | None = None) -> None:
self.spec = spec or NavEnvSpec()
def build_observation(self, pos: torch.Tensor, vel: torch.Tensor) -> torch.Tensor:
"""Construct observation [px, py, vx, vy, dx_goal, dy_goal] of shape (B, 6)."""
goal = torch.tensor(
[self.spec.goal_x, self.spec.goal_y], dtype=pos.dtype, device=pos.device
).unsqueeze(0)
delta_g = goal - pos
return torch.cat([pos, vel, delta_g], dim=-1)
def step_dynamics(
self,
pos: torch.Tensor,
vel: torch.Tensor,
action: torch.Tensor,
process_noise: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Advance 2D damped velocity dynamics: v' = damping*v + gain*u, p' = p + dt*v'."""
u = torch.clamp(action, -1.2, 1.2)
if process_noise is not None:
u = u + process_noise
vel_next = torch.clamp(self.spec.vel_damping * vel + self.spec.accel_gain * u, -1.4, 1.4)
pos_next = torch.clamp(pos + self.spec.dt * vel_next, -1.6, 1.6)
return pos_next, vel_next
def check_collision(self, pos: torch.Tensor) -> torch.Tensor:
"""Return boolean mask (B,) where trajectory intersects the central circular obstacle."""
cx = self.spec.obstacle_center_x
cy = self.spec.obstacle_center_y
dist = torch.sqrt((pos[:, 0] - cx) ** 2 + (pos[:, 1] - cy) ** 2)
return dist < self.spec.obstacle_radius
def check_goal_reached(self, pos: torch.Tensor) -> torch.Tensor:
"""Return boolean mask (B,) where robot reaches within goal_tolerance."""
dist = torch.sqrt((pos[:, 0] - self.spec.goal_x) ** 2 + (pos[:, 1] - self.spec.goal_y) ** 2)
return dist <= self.spec.goal_tolerance
def expert_velocity_command(
self,
pos: torch.Tensor,
vel: torch.Tensor,
mode: torch.Tensor,
) -> torch.Tensor:
"""Compute smooth mode-conditioned PD action guiding around obstacle (+1 upper, -1 lower)."""
px = pos[:, 0]
py = pos[:, 1]
pass_mask = px < 0.25
subgoal_x = torch.where(
pass_mask, torch.clamp(px + 0.50, max=0.28), torch.full_like(px, self.spec.goal_x)
)
lat_clear = (self.spec.obstacle_radius + 0.28) * mode
subgoal_y = torch.where(pass_mask, lat_clear, torch.full_like(py, self.spec.goal_y))
target = torch.stack([subgoal_x, subgoal_y], dim=-1)
desired_vel = torch.clamp((target - pos) * 2.2, -1.25, 1.25)
u_cmd = (desired_vel - self.spec.vel_damping * vel) / self.spec.accel_gain
return torch.clamp(u_cmd, -1.15, 1.15)
def sample_expert_chunks(
self,
num_samples: int,
seed: int = 42,
) -> dict[str, torch.Tensor]:
"""Sample balanced bimodal expert (obs, action_chunk) pairs across full workspace."""
gen = torch.Generator().manual_seed(seed)
n_start = int(num_samples * 0.45)
n_mid = int(num_samples * 0.35)
n_exit = num_samples - n_start - n_mid
px_start = torch.empty(n_start).uniform_(-1.12, -0.45, generator=gen)
py_start = torch.empty(n_start).uniform_(-0.14, 0.14, generator=gen)
px_mid = torch.empty(n_mid).uniform_(-0.45, 0.45, generator=gen)
side_mid = torch.where(
torch.arange(n_mid) % 2 == 0,
torch.ones(n_mid),
-torch.ones(n_mid),
)
py_mid = side_mid * torch.empty(n_mid).uniform_(0.42, 0.85, generator=gen)
px_exit = torch.empty(n_exit).uniform_(0.35, 0.92, generator=gen)
py_exit = torch.empty(n_exit).uniform_(-0.45, 0.45, generator=gen)
pos = torch.stack(
[
torch.cat([px_start, px_mid, px_exit], dim=0),
torch.cat([py_start, py_mid, py_exit], dim=0),
],
dim=-1,
)
vel = torch.empty((num_samples, 2)).uniform_(-0.35, 0.35, generator=gen)
vel[:, 0] = torch.clamp(vel[:, 0] + 0.45, -0.3, 1.1)
rand_modes = torch.where(
torch.rand(num_samples, generator=gen) >= 0.5,
torch.ones(num_samples),
-torch.ones(num_samples),
)
committed_side = torch.where(pos[:, 1] >= 0.0, torch.ones(num_samples), -torch.ones(num_samples))
ambiguous = (pos[:, 0] < 0.15) & (torch.abs(pos[:, 1]) < 0.25)
modes = torch.where(ambiguous, rand_modes, committed_side)
obs = self.build_observation(pos, vel)
chunks: list[torch.Tensor] = []
p_cur = pos.clone()
v_cur = vel.clone()
for _step in range(self.spec.action_horizon):
u_t = self.expert_velocity_command(p_cur, v_cur, modes)
chunks.append(u_t)
p_cur, v_cur = self.step_dynamics(p_cur, v_cur, u_t)
action_chunks = torch.stack(chunks, dim=1)
return {
"obs": obs,
"action_chunks": action_chunks,
"modes": modes,
}
# ---------------------------------------------------------------------------
# Policies: MSE Chunk BC vs DDIM Diffusion vs Conditional Flow Matching
# ---------------------------------------------------------------------------
class DeterministicMSEChunkPolicy(nn.Module):
"""Unimodal MSE action-chunk regression baseline (mode-averages symmetric arcs)."""
def __init__(self, obs_dim: int = 6, chunk_dim: int = 16, hidden: int = 96) -> None:
super().__init__()
self.net = TypedMLP((obs_dim, hidden, hidden, chunk_dim))
def forward(self, obs: torch.Tensor) -> torch.Tensor:
return cast(torch.Tensor, self.net(obs))
@torch.no_grad()
def sample_chunk(
self,
obs: torch.Tensor,
nfe: int = 1,
generator: torch.Generator | None = None,
) -> torch.Tensor:
_ = nfe
_ = generator
return self.forward(obs)
class DDIMDiffusionActionPolicy(nn.Module):
"""VP-SDE Diffusion Policy over action chunks with cosine schedule & DDIM sampler."""
def __init__(
self,
obs_dim: int = 6,
chunk_dim: int = 16,
hidden: int = 112,
num_train_steps: int = 100,
) -> None:
super().__init__()
self.chunk_dim = chunk_dim
self.num_train_steps = num_train_steps
self.time_dim = 16
self.net = TypedMLP((chunk_dim + obs_dim + self.time_dim, hidden, hidden, hidden, chunk_dim))
# Cosine variance-preserving schedule reaching zero-terminal SNR (1e-4) at step T
steps = torch.arange(num_train_steps + 1, dtype=torch.float32) / float(num_train_steps)
s = 0.008
alphas_cumprod = torch.cos(((steps + s) / (1.0 + s)) * (math.pi / 2.0)) ** 2
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
alphas_cumprod = torch.clamp(alphas_cumprod[1:], min=1e-4, max=0.9999)
self.register_buffer("alphas_cumprod", alphas_cumprod)
self.alphas_cumprod: torch.Tensor
def forward(self, noisy_chunk: torch.Tensor, t_norm: torch.Tensor, obs: torch.Tensor) -> torch.Tensor:
t_emb = sinusoidal_time_embedding(t_norm, self.time_dim)
inp = torch.cat([noisy_chunk, obs, t_emb], dim=-1)
return cast(torch.Tensor, self.net(inp))
def training_loss(
self,
obs: torch.Tensor,
target_chunk: torch.Tensor,
generator: torch.Generator,
) -> torch.Tensor:
"""Train with velocity (v-prediction) objective for zero-division DDIM stability."""
bsz = obs.shape[0]
k = torch.randint(0, self.num_train_steps, (bsz,), generator=generator)
alpha_bar = self.alphas_cumprod[k].unsqueeze(-1)
sqrt_a = torch.sqrt(alpha_bar)
sqrt_one_minus_a = torch.sqrt(1.0 - alpha_bar)
eps = torch.randn(target_chunk.shape, generator=generator, dtype=target_chunk.dtype)
noisy = sqrt_a * target_chunk + sqrt_one_minus_a * eps
v_target = sqrt_a * eps - sqrt_one_minus_a * target_chunk
t_norm = (k.float() + 1.0) / float(self.num_train_steps)
pred_v = self.forward(noisy, t_norm, obs)
return F.mse_loss(pred_v, v_target)
@torch.no_grad()
def sample_chunk(
self,
obs: torch.Tensor,
nfe: int = 20,
generator: torch.Generator | None = None,
) -> torch.Tensor:
bsz = obs.shape[0]
x = torch.randn((bsz, self.chunk_dim), generator=generator, dtype=obs.dtype)
idx_grid = torch.linspace(self.num_train_steps - 1, 0, steps=nfe).round().long()
for step_i in range(nfe):
k_cur = int(idx_grid[step_i].item())
alpha_cur = self.alphas_cumprod[k_cur]
sqrt_a = torch.sqrt(alpha_cur)
sqrt_one_minus_a = torch.sqrt(1.0 - alpha_cur)
t_norm = torch.full((bsz,), float(k_cur + 1) / float(self.num_train_steps), dtype=obs.dtype)
pred_v = self.forward(x, t_norm, obs)
x0_pred = sqrt_a * x - sqrt_one_minus_a * pred_v
eps_pred = sqrt_one_minus_a * x + sqrt_a * pred_v
if step_i == nfe - 1:
x = torch.clamp(x0_pred, -1.6, 1.6)
else:
k_prev = int(idx_grid[step_i + 1].item())
alpha_prev = self.alphas_cumprod[k_prev]
x = torch.sqrt(alpha_prev) * x0_pred + torch.sqrt(1.0 - alpha_prev) * eps_pred
return x
class ConditionalFlowMatchingPolicy(nn.Module):
"""Rectified Flow / Conditional Flow Matching ODE policy with OT straight paths."""
def __init__(self, obs_dim: int = 6, chunk_dim: int = 16, hidden: int = 112) -> None:
super().__init__()
self.chunk_dim = chunk_dim
self.time_dim = 16
self.net = TypedMLP((chunk_dim + obs_dim + self.time_dim, hidden, hidden, hidden, chunk_dim))
def forward(self, x_t: torch.Tensor, t: torch.Tensor, obs: torch.Tensor) -> torch.Tensor:
t_emb = sinusoidal_time_embedding(t, self.time_dim)
inp = torch.cat([x_t, obs, t_emb], dim=-1)
return cast(torch.Tensor, self.net(inp))
@staticmethod
def ot_interpolant(
x0: torch.Tensor,
x1: torch.Tensor,
t: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Compute straight OT path x_t = (1-t)*x0 + t*x1 and target velocity (x1 - x0)."""
t_col = t.view(-1, 1)
x_t = (1.0 - t_col) * x0 + t_col * x1
target_vel = x1 - x0
return x_t, target_vel
def training_loss(
self,
obs: torch.Tensor,
target_chunk: torch.Tensor,
generator: torch.Generator,
) -> torch.Tensor:
bsz = obs.shape[0]
t = torch.rand(bsz, generator=generator, dtype=target_chunk.dtype)
x0 = torch.randn(target_chunk.shape, generator=generator, dtype=target_chunk.dtype)
x_t, target_vel = self.ot_interpolant(x0, target_chunk, t)
pred_vel = self.forward(x_t, t, obs)
return F.mse_loss(pred_vel, target_vel)
@torch.no_grad()
def sample_chunk(
self,
obs: torch.Tensor,
nfe: int = 8,
generator: torch.Generator | None = None,
) -> torch.Tensor:
"""Integrate straight OT velocity ODE from t=0 to t=1 using uniform Heun (NFE >= 2)."""
bsz = obs.shape[0]
x = torch.randn((bsz, self.chunk_dim), generator=generator, dtype=obs.dtype)
if nfe <= 1:
t0 = torch.zeros(bsz, dtype=obs.dtype)
return torch.clamp(x + self.forward(x, t0, obs), -1.6, 1.6)
n_heun_steps = nfe // 2
has_tail_euler = (nfe % 2) == 1
total_segments = n_heun_steps + (1 if has_tail_euler else 0)
dt = 1.0 / float(total_segments)
for step_i in range(n_heun_steps):
t_cur = torch.full((bsz,), float(step_i) * dt, dtype=obs.dtype)
t_nxt = torch.full((bsz,), float(step_i + 1) * dt, dtype=obs.dtype)
v1 = self.forward(x, t_cur, obs)
x_mid = x + dt * v1
v2 = self.forward(x_mid, t_nxt, obs)
x = x + 0.5 * dt * (v1 + v2)
if has_tail_euler:
t_last = torch.full((bsz,), float(n_heun_steps) * dt, dtype=obs.dtype)
x = x + dt * self.forward(x, t_last, obs)
return torch.clamp(x, -1.6, 1.6)
# ---------------------------------------------------------------------------
# Training & Closed-Loop Evaluation
# ---------------------------------------------------------------------------
def _train_policies(
env: BimodalObstacleNavEnv,
seed: int,
quick: bool,
) -> tuple[
DeterministicMSEChunkPolicy,
DDIMDiffusionActionPolicy,
ConditionalFlowMatchingPolicy,
dict[str, torch.Tensor],
]:
n_train = 1536 if quick else 1664
train_data = env.sample_expert_chunks(num_samples=n_train, seed=seed)
obs = train_data["obs"]
chunks = train_data["action_chunks"].reshape(n_train, -1)
chunk_dim = chunks.shape[1]
torch.manual_seed(seed)
mse_pol = DeterministicMSEChunkPolicy(env.spec.obs_dim, chunk_dim, hidden=96)
ddim_pol = DDIMDiffusionActionPolicy(env.spec.obs_dim, chunk_dim, hidden=120)
cfm_pol = ConditionalFlowMatchingPolicy(env.spec.obs_dim, chunk_dim, hidden=160)
batch_sz = 256
# 1. Train MSE Baseline
opt_mse = torch.optim.AdamW(mse_pol.parameters(), lr=4e-3, weight_decay=1e-4)
gen_mse = torch.Generator().manual_seed(seed + 10)
epochs_mse = 50 if quick else 65
for _ in range(epochs_mse):
perm = torch.randperm(n_train, generator=gen_mse)
for start in range(0, n_train, batch_sz):
idx = perm[start : start + batch_sz]
loss = F.mse_loss(mse_pol(obs[idx]), chunks[idx])
opt_mse.zero_grad()
torch.autograd.backward(loss)
opt_mse.step()
# 2. Train DDIM Diffusion Policy with CosineAnnealingLR
epochs_ddim = 150 if quick else 190
opt_ddim = torch.optim.AdamW(ddim_pol.parameters(), lr=3.5e-3, weight_decay=1e-4)
sched_ddim = torch.optim.lr_scheduler.CosineAnnealingLR(opt_ddim, T_max=epochs_ddim, eta_min=2e-4)
gen_ddim = torch.Generator().manual_seed(seed + 20)
for _ in range(epochs_ddim):
perm = torch.randperm(n_train, generator=gen_ddim)
for start in range(0, n_train, batch_sz):
idx = perm[start : start + batch_sz]
loss = ddim_pol.training_loss(obs[idx], chunks[idx], gen_ddim)
opt_ddim.zero_grad()
torch.autograd.backward(loss)
opt_ddim.step()
sched_ddim.step()
# 3. Train Conditional Flow Matching Policy with CosineAnnealingLR
epochs_cfm = 270
batch_sz_cfm = 128
opt_cfm = torch.optim.AdamW(cfm_pol.parameters(), lr=3e-3, weight_decay=1e-4)
sched_cfm = torch.optim.lr_scheduler.CosineAnnealingLR(opt_cfm, T_max=epochs_cfm, eta_min=1e-4)
gen_cfm = torch.Generator().manual_seed(seed + 30)
for _ in range(epochs_cfm):
perm = torch.randperm(n_train, generator=gen_cfm)
for start in range(0, n_train, batch_sz_cfm):
idx = perm[start : start + batch_sz_cfm]
loss = cfm_pol.training_loss(obs[idx], chunks[idx], gen_cfm)
opt_cfm.zero_grad()
torch.autograd.backward(loss)
opt_cfm.step()
sched_cfm.step()
mse_pol.eval()
ddim_pol.eval()
cfm_pol.eval()
return mse_pol, ddim_pol, cfm_pol, train_data
def _measure_wall_latency_ms(
policy: DeterministicMSEChunkPolicy | DDIMDiffusionActionPolicy | ConditionalFlowMatchingPolicy,
sample_obs: torch.Tensor,
nfe: int,
seed: int,
) -> float:
"""Measure genuine PyTorch CPU wall-clock inference latency per chunk in milliseconds."""
gen = torch.Generator().manual_seed(seed + 777)
_ = policy.sample_chunk(sample_obs, nfe=nfe, generator=gen)
repeats = 14
t0 = time.perf_counter()
for _ in range(repeats):
_ = policy.sample_chunk(sample_obs, nfe=nfe, generator=gen)
elapsed_ms = (time.perf_counter() - t0) * 1000.0 / float(repeats)
return max(0.02, round(elapsed_ms, 4))
def evaluate_policy_closed_loop(
env: BimodalObstacleNavEnv,
policy: DeterministicMSEChunkPolicy | DDIMDiffusionActionPolicy | ConditionalFlowMatchingPolicy,
policy_name: Literal["deterministic_mse", "ddim_diffusion", "conditional_flow_matching"],
nfe: int,
exec_horizon: int,
seed: int,
num_episodes: int = 36,
perturbation_std: float = 0.04,
) -> PolicyEvalMetrics:
"""Evaluate closed-loop obstacle avoidance, multimodality, jerk, and control frequency."""
gen = torch.Generator().manual_seed(seed + 1000 + exec_horizon)
pos = torch.stack(
[
torch.empty(num_episodes).uniform_(-1.02, -0.88, generator=gen),
torch.empty(num_episodes).uniform_(-0.04, 0.04, generator=gen),
],
dim=-1,
)
vel = torch.zeros((num_episodes, 2), dtype=pos.dtype)
collided = torch.zeros(num_episodes, dtype=torch.bool)
reached = torch.zeros(num_episodes, dtype=torch.bool)
max_y = torch.zeros(num_episodes, dtype=pos.dtype)
min_y = torch.zeros(num_episodes, dtype=pos.dtype)
action_history: list[torch.Tensor] = []
step = 0
while step < env.spec.max_steps:
obs = env.build_observation(pos, vel)
chunk_flat = policy.sample_chunk(obs, nfe=nfe, generator=gen)
chunk = chunk_flat.reshape(num_episodes, env.spec.action_horizon, env.spec.action_dim)
for k in range(exec_horizon):
if step >= env.spec.max_steps:
break
act = chunk[:, k, :]
action_history.append(act)
active = (~collided) & (~reached)
p_noise = torch.randn(act.shape, generator=gen, dtype=act.dtype) * perturbation_std
pos_next, vel_next = env.step_dynamics(pos, vel, act, process_noise=p_noise)
pos = torch.where(active.unsqueeze(-1), pos_next, pos)
vel = torch.where(active.unsqueeze(-1), vel_next, vel)
max_y = torch.maximum(max_y, pos[:, 1])
min_y = torch.minimum(min_y, pos[:, 1])
collided = collided | (active & env.check_collision(pos))
reached = reached | (active & (~collided) & env.check_goal_reached(pos))
step += 1
acts = torch.stack(action_history, dim=1)
action_diffs = torch.linalg.norm(acts[:, 1:, :] - acts[:, :-1, :], dim=-1)
mean_jerk = float(action_diffs.mean().item())
upper_mask = max_y >= torch.abs(min_y)
valid_success = reached & (~collided)
n_succ = int(valid_success.sum().item())
if n_succ > 0:
u_cnt = int((valid_success & upper_mask).sum().item())
l_cnt = n_succ - u_cnt
p_u = float(u_cnt) / float(n_succ)
p_l = float(l_cnt) / float(n_succ)
entropy_bits = 0.0
for p in (p_u, p_l):
if p > 1e-9:
entropy_bits -= p * math.log2(p)
else:
p_u = float(upper_mask.float().mean().item())
p_l = 1.0 - p_u
entropy_bits = 0.0
probe_pos = torch.tensor([[-0.95, 0.0]] * 24, dtype=torch.float32)
probe_vel = torch.zeros((24, 2), dtype=torch.float32)
probe_obs = env.build_observation(probe_pos, probe_vel)
def _expert_chunk(mode_val: float) -> torch.Tensor:
pc = probe_pos[:1].clone()
vc = probe_vel[:1].clone()
mv = torch.tensor([mode_val], dtype=torch.float32)
seq: list[torch.Tensor] = []
for _ in range(env.spec.action_horizon):
ut = env.expert_velocity_command(pc, vc, mv)
seq.append(ut)
pc, vc = env.step_dynamics(pc, vc, ut)
return torch.stack(seq, dim=1).reshape(1, -1)
c_up = _expert_chunk(1.0)
c_dn = _expert_chunk(-1.0)
pred_probe = policy.sample_chunk(probe_obs, nfe=nfe, generator=gen)
d_up = ((pred_probe - c_up) ** 2).mean(dim=-1)
d_dn = ((pred_probe - c_dn) ** 2).mean(dim=-1)
nearest_mse = float(torch.minimum(d_up, d_dn).mean().item())
obs_single = probe_obs[:1]
raw_head_ms = _measure_wall_latency_ms(policy, obs_single, nfe=nfe, seed=seed)
total_chunk_ms = round(0.25 + raw_head_ms, 4)
control_hz = round(1000.0 * float(exec_horizon) / total_chunk_ms, 2)
return PolicyEvalMetrics(
policy_name=policy_name,
nfe=nfe,
exec_horizon=exec_horizon,
success_rate=round(float(valid_success.float().mean().item()), 4),
collision_rate=round(float(collided.float().mean().item()), 4),
mode_entropy_bits=round(entropy_bits, 4),
upper_mode_fraction=round(p_u, 4),
lower_mode_fraction=round(p_l, 4),
mean_action_jerk=round(mean_jerk, 4),
chunk_mse_to_nearest_mode=round(nearest_mse, 4),
inference_ms_per_chunk=total_chunk_ms,
control_hz=control_hz,
)
def run_diffusion_vs_flow_benchmark(
seed: int = 42,
quick: bool = False,
tracer: Tracer | None = None,
) -> Exp1DiffusionVsFlowReport:
"""Run Experiment 1: MSE vs DDIM Diffusion vs Conditional Flow Matching across NFE & H_e."""
if torch.get_num_threads() > 1:
torch.set_num_threads(1)
env = BimodalObstacleNavEnv(NavEnvSpec())
def _exec() -> Exp1DiffusionVsFlowReport:
mse_pol, ddim_pol, cfm_pol, _ = _train_policies(env, seed=seed, quick=quick)
n_eps = 28 if quick else 40
mse_metrics = evaluate_policy_closed_loop(
env,
mse_pol,
"deterministic_mse",
nfe=1,
exec_horizon=4,
seed=seed,
num_episodes=n_eps,
)
nfe_grid = (1, 2, 4, 8, 20, 50)
pareto_sweep: list[PolicyEvalMetrics] = []
for nfe in nfe_grid:
pareto_sweep.append(
evaluate_policy_closed_loop(
env,
ddim_pol,
"ddim_diffusion",
nfe=nfe,
exec_horizon=4,
seed=seed,
num_episodes=n_eps,
)
)
pareto_sweep.append(
evaluate_policy_closed_loop(
env,
cfm_pol,
"conditional_flow_matching",
nfe=nfe,
exec_horizon=4,
seed=seed,
num_episodes=n_eps,
)
)
# Execution-horizon ablation (H_e in {1, 4, 8}) under mild execution disturbances
exec_ablation: list[PolicyEvalMetrics] = []
for he in (1, 4, 8):
exec_ablation.append(
evaluate_policy_closed_loop(
env,
ddim_pol,
"ddim_diffusion",
nfe=20,
exec_horizon=he,
seed=seed + 50,
num_episodes=n_eps,
perturbation_std=0.22,
)
)
exec_ablation.append(
evaluate_policy_closed_loop(
env,
cfm_pol,
"conditional_flow_matching",
nfe=8,
exec_horizon=he,
seed=seed + 50,
num_episodes=n_eps,
perturbation_std=0.22,
)
)
ddim_50 = next(
p for p in pareto_sweep if p.policy_name == "ddim_diffusion" and p.nfe == 50
)
cfm_low = next(
p for p in pareto_sweep if p.policy_name == "conditional_flow_matching" and p.nfe == 4
)
speedup = round(cfm_low.control_hz / max(1e-6, ddim_50.control_hz), 2)
x0 = torch.randn(16, 16)
x1 = torch.randn(16, 16)
xt0, _ = ConditionalFlowMatchingPolicy.ot_interpolant(x0, x1, torch.zeros(16))
xt1, _ = ConditionalFlowMatchingPolicy.ot_interpolant(x0, x1, torch.ones(16))
ep_err = float(max((xt0 - x0).abs().max().item(), (xt1 - x1).abs().max().item()))
return Exp1DiffusionVsFlowReport(
env_spec=env.spec,
mse_baseline=mse_metrics,
nfe_pareto_sweep=pareto_sweep,
exec_horizon_ablation=exec_ablation,
cfm_vs_ddim_speedup_at_equal_or_higher_success=max(1.0, speedup),
ot_interpolant_max_endpoint_error=round(ep_err, 8),
)
if tracer is not None:
with tracer.start_as_current_span("policy.train_eval") as sp1:
report = _exec()
sp1.set_attribute("mse.success_rate", report.mse_baseline.success_rate)
sp1.set_attribute("speedup_x", report.cfm_vs_ddim_speedup_at_equal_or_higher_success)
with tracer.start_as_current_span("nfe.pareto_sweep") as sp2:
sp2.set_attribute("nfe.grid_count", len(report.nfe_pareto_sweep))
sp2.set_attribute("exec_ablation_count", len(report.exec_horizon_ablation))
return report
return _exec()
"""Experiments 2 & 3 (Articles #13 & #14): Cross-Embodiment VLAs & Controlled Sim-to-Real Ablations."""
from __future__ import annotations
from typing import Literal, cast
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from opentelemetry.trace import Tracer
from pydantic import BaseModel, ConfigDict, Field
from robotics_action_policy_lab.diffusion_vs_flow import (
Exp1DiffusionVsFlowReport,
TypedMLP,
create_in_memory_otel_tracer,
run_diffusion_vs_flow_benchmark,
)
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Schemas (ConfigDict(extra="forbid"))
# ---------------------------------------------------------------------------
class EmbodimentSpec(BaseModel):
"""Kinematic specification for a 2D planar robot arm embodiment."""
model_config = ConfigDict(extra="forbid")
name: Literal["arm_2dof_source", "arm_3dof_target"]
dof: int = Field(..., ge=2, le=6)
link_lengths: tuple[float, ...]
joint_sign: float = Field(default=1.0)
class CrossEmbodimentPoint(BaseModel):
"""Evaluation point for a cross-embodiment transfer strategy at k target demos."""
model_config = ConfigDict(extra="forbid")
strategy: Literal["target_only_scratch", "naive_shared_head_padded", "modular_vla_adapter"]
target_demos_k: int = Field(..., ge=0)
target_action_mse: float = Field(..., ge=0.0)
reach_success_rate: float = Field(..., ge=0.0, le=1.0)
mean_final_ee_error: float = Field(..., ge=0.0)
class Exp2CrossEmbodimentReport(BaseModel):
"""Complete Experiment 2 report comparing positive vs negative cross-embodiment transfer."""
model_config = ConfigDict(extra="forbid")
source_embodiment: EmbodimentSpec
target_embodiment: EmbodimentSpec
k_values: list[int]
points: list[CrossEmbodimentPoint]
zero_shot_modular_success: float = Field(..., ge=0.0, le=1.0)
few_shot_k8_positive_transfer_gain: float
few_shot_k24_positive_transfer_gain: float
naive_k24_negative_transfer_delta: float
class Sim2RealRegimePoint(BaseModel):
"""Evaluation of an adaptation strategy on one isolated or combined reality-gap regime."""
model_config = ConfigDict(extra="forbid")
strategy: Literal["no_adaptation", "sysid_only", "dr_only", "dr_history_sysid"]
regime: Literal[
"nominal_sim",
"visual_noise_shift",
"dynamics_friction_mass_shift",
"actuation_latency_2steps",
"combined_real_world",
]
success_rate: float = Field(..., ge=0.0, le=1.0)
collision_rate: float = Field(..., ge=0.0, le=1.0)
mean_final_goal_dist: float = Field(..., ge=0.0)
class Exp3Sim2RealReport(BaseModel):
"""Complete Experiment 3 report isolating 4 reality-gap axes and adaptation recovery."""
model_config = ConfigDict(extra="forbid")
true_mass: float = Field(..., gt=0.0)
true_damping: float = Field(..., gt=0.0)
true_latency_steps: int = Field(..., ge=0)
identified_mass: float = Field(..., gt=0.0)
identified_damping: float = Field(..., gt=0.0)
identified_latency_steps: int = Field(..., ge=0)
regimes: list[str]
strategies: list[str]
points: list[Sim2RealRegimePoint]
no_adapt_nominal_success: float = Field(..., ge=0.0, le=1.0)
no_adapt_combined_success: float = Field(..., ge=0.0, le=1.0)
sysid_only_combined_success: float = Field(..., ge=0.0, le=1.0)
dr_only_combined_success: float = Field(..., ge=0.0, le=1.0)
full_stack_combined_success: float = Field(..., ge=0.0, le=1.0)
dominant_single_axis_drop: str
class OtelSummary(BaseModel):
"""Summary of OpenTelemetry spans recorded during the full Lab 17 benchmark."""
model_config = ConfigDict(extra="forbid")
total_spans_recorded: int = Field(..., ge=1)
distinct_span_names: list[str]
class FullRoboticsBenchmarkReport(BaseModel):
"""Top-level Lab 17 result schema uniting Articles #12, #13, #14 and OTel telemetry."""
model_config = ConfigDict(extra="forbid")
config: dict[str, int | bool]
exp1_diffusion_vs_flow: Exp1DiffusionVsFlowReport
exp2_cross_embodiment_vla: Exp2CrossEmbodimentReport
exp3_sim2real_diagnostic: Exp3Sim2RealReport
otel_telemetry: OtelSummary
# ---------------------------------------------------------------------------
# Experiment 2: Planar 2-DoF vs 3-DoF Kinematics & Generalist VLA Transfer
# ---------------------------------------------------------------------------
class PlanarArmKinematics:
"""Analytical forward kinematics and damped-least-squares Jacobian for n-DoF planar arms."""
def __init__(self, spec: EmbodimentSpec) -> None:
self.spec = spec
self.lengths = torch.tensor(spec.link_lengths, dtype=torch.float32)
def forward_kinematics(self, q: torch.Tensor) -> torch.Tensor:
"""Compute end-effector (x, y) in workspace from joint angles q of shape (B, dof)."""
angles = torch.cumsum(q * self.spec.joint_sign, dim=-1)
x = (torch.cos(angles) * self.lengths.unsqueeze(0)).sum(dim=-1)
y = (torch.sin(angles) * self.lengths.unsqueeze(0)).sum(dim=-1)
return torch.stack([x, y], dim=-1)
def jacobian(self, q: torch.Tensor) -> torch.Tensor:
"""Compute analytical geometric Jacobian J(q) of shape (B, 2, dof)."""
bsz = q.shape[0]
dof = self.spec.dof
angles = torch.cumsum(q * self.spec.joint_sign, dim=-1)
cos_l = torch.cos(angles) * self.lengths.unsqueeze(0)
sin_l = torch.sin(angles) * self.lengths.unsqueeze(0)
j_mat = torch.zeros((bsz, 2, dof), dtype=q.dtype)
for col in range(dof):
j_mat[:, 0, col] = -self.spec.joint_sign * sin_l[:, col:].sum(dim=-1)
j_mat[:, 1, col] = self.spec.joint_sign * cos_l[:, col:].sum(dim=-1)
return j_mat
def ik_velocity(self, q: torch.Tensor, v_ee: torch.Tensor, damping: float = 0.06) -> torch.Tensor:
"""Damped-least-squares pseudoinverse mapping workspace velocity v_ee to joint velocity dq."""
j_mat = self.jacobian(q)
jjt = torch.bmm(j_mat, j_mat.transpose(1, 2))
eye2 = torch.eye(2, dtype=q.dtype).unsqueeze(0) * (damping**2)
inv_term = torch.linalg.solve(jjt + eye2, v_ee.unsqueeze(-1))
dq = torch.bmm(j_mat.transpose(1, 2), inv_term).squeeze(-1)
return torch.clamp(dq, -1.6, 1.6)
def _sample_arm_demos(
arm: PlanarArmKinematics,
num_samples: int,
seed: int,
) -> dict[str, torch.Tensor]:
"""Generate expert workspace + joint velocity trajectories for a planar arm."""
gen = torch.Generator().manual_seed(seed)
if arm.spec.dof == 2:
q1 = torch.empty(num_samples).uniform_(-0.85, 0.85, generator=gen)
q2 = torch.empty(num_samples).uniform_(0.35, 1.35, generator=gen)
q = torch.stack([q1, q2], dim=-1)
else:
# Overlapping (q1, q2) box with reversed joint sign causes destructive naive pooling
q1 = torch.empty(num_samples).uniform_(-0.85, 0.85, generator=gen)
q2 = torch.empty(num_samples).uniform_(0.35, 1.35, generator=gen)
q3 = torch.empty(num_samples).uniform_(-0.65, 0.65, generator=gen)
q = torch.stack([q1, q2, q3], dim=-1)
ee = arm.forward_kinematics(q)
offset = torch.empty((num_samples, 2)).uniform_(-0.46, 0.46, generator=gen)
goal = torch.clamp(ee + offset, -1.05, 1.05)
delta = goal - ee
dist = torch.linalg.norm(delta, dim=-1, keepdim=True).clamp(min=1e-4)
v_ee = torch.clamp(delta * 1.9, -0.85, 0.85)
dq = arm.ik_velocity(q, v_ee)
sem_obs = torch.cat([ee, goal, delta, delta / dist], dim=-1)
return {
"sem_obs": sem_obs,
"q": q,
"v_ee": v_ee,
"dq": dq,
"ee": ee,
"goal": goal,
}
class NaiveJointPolicy(nn.Module):
"""Single shared-head joint-space MLP taking padded (sem_obs, q_pad) -> dq_pad."""
def __init__(self, sem_dim: int = 8, max_dof: int = 3, hidden: int = 80) -> None:
super().__init__()
self.net = TypedMLP((sem_dim + max_dof, hidden, hidden, max_dof))
def forward(self, sem_obs: torch.Tensor, q_pad: torch.Tensor) -> torch.Tensor:
return cast(torch.Tensor, self.net(torch.cat([sem_obs, q_pad], dim=-1)))
class ModularSemanticVLA(nn.Module):
"""Shared Semantic Encoder (workspace v_ee) + Jacobian-Structured Morphology Adapter."""
def __init__(self, sem_dim: int = 8, sem_latent: int = 16, target_dof: int = 3) -> None:
super().__init__()
self.target_dof = target_dof
self.semantic_encoder = TypedMLP((sem_dim, 64, sem_latent))
self.workspace_head = TypedMLP((sem_latent, 32, 2))
# Predicts a target_dof x 2 residual pseudoinverse matrix delta_J_pinv(q)
# Guaranteed dq == 0 whenever v_ee_hat == 0 (zero steady-state drift at goal).
self.morphology_head = TypedMLP((target_dof, 24, target_dof * 2))
last_layer = self.morphology_head.net[-1]
if isinstance(last_layer, nn.Linear):
nn.init.zeros_(last_layer.weight)
nn.init.zeros_(last_layer.bias)
def encode_semantic(self, sem_obs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
z_sem = F.silu(self.semantic_encoder(sem_obs))
v_ee_hat = self.workspace_head(z_sem)
return z_sem, v_ee_hat
def forward_target_adapter(self, v_ee_hat: torch.Tensor, q_target: torch.Tensor) -> torch.Tensor:
delta_k = self.morphology_head(q_target).reshape(-1, self.target_dof, 2)
return torch.bmm(delta_k, v_ee_hat.unsqueeze(-1)).squeeze(-1)
def _evaluate_arm_reaching(
arm: PlanarArmKinematics,
predict_dq_fn: object,
test_data: dict[str, torch.Tensor],
num_episodes: int = 32,
) -> tuple[float, float, float]:
"""Compute held-out action MSE and closed-loop 3-DoF target reaching success."""
sem_test = test_data["sem_obs"]
q_test = test_data["q"]
dq_true = test_data["dq"]
with torch.no_grad():
if not callable(predict_dq_fn):
raise TypeError("predict_dq_fn must be callable")
pred_test: torch.Tensor = predict_dq_fn(sem_test, q_test)
action_mse = float(F.mse_loss(pred_test, dq_true).item())
q_cur = q_test[:num_episodes].clone()
goal = test_data["goal"][:num_episodes]
dt = 0.14
for _ in range(24):
ee_cur = arm.forward_kinematics(q_cur)
delta = goal - ee_cur
dist = torch.linalg.norm(delta, dim=-1, keepdim=True).clamp(min=1e-4)
sem_cur = torch.cat([ee_cur, goal, delta, delta / dist], dim=-1)
dq_cmd: torch.Tensor = predict_dq_fn(sem_cur, q_cur)
dq_cmd = torch.clamp(dq_cmd, -1.6, 1.6)
q_cur = q_cur + dt * dq_cmd
final_ee = arm.forward_kinematics(q_cur)
final_err = torch.linalg.norm(goal - final_ee, dim=-1)
succ_rate = float((final_err <= 0.12).float().mean().item())
mean_err = float(final_err.mean().item())
return round(action_mse, 4), round(succ_rate, 4), round(mean_err, 4)
def run_cross_embodiment_vla_study(
seed: int = 42,
quick: bool = False,
tracer: Tracer | None = None,
) -> Exp2CrossEmbodimentReport:
"""Run Experiment 2: Cross-Embodiment Generalist VLA Transfer (2-DoF -> 3-DoF Arm)."""
src_spec = EmbodimentSpec(name="arm_2dof_source", dof=2, link_lengths=(0.70, 0.58), joint_sign=1.0)
tgt_spec = EmbodimentSpec(
name="arm_3dof_target", dof=3, link_lengths=(0.48, 0.44, 0.36), joint_sign=-1.0
)
src_arm = PlanarArmKinematics(src_spec)
tgt_arm = PlanarArmKinematics(tgt_spec)
def _exec() -> Exp2CrossEmbodimentReport:
n_src = 360 if quick else 520
n_test = 160
src_data = _sample_arm_demos(src_arm, n_src, seed=seed + 100)
tgt_pool = _sample_arm_demos(tgt_arm, 80, seed=seed + 200)
tgt_test = _sample_arm_demos(tgt_arm, n_test, seed=seed + 300)
# Pretrain Shared Semantic Encoder of Modular VLA on 2-DoF Source Fleet
torch.manual_seed(seed + 400)
vla_base = ModularSemanticVLA(sem_dim=8, sem_latent=16, target_dof=3)
opt_sem = torch.optim.AdamW(
list(vla_base.semantic_encoder.parameters()) + list(vla_base.workspace_head.parameters()),
lr=5e-3,
)
epochs_pre = 90 if quick else 120
for _ in range(epochs_pre):
_, v_hat = vla_base.encode_semantic(src_data["sem_obs"])
loss = F.mse_loss(v_hat, src_data["v_ee"])
opt_sem.zero_grad()
torch.autograd.backward(loss)
opt_sem.step()
# Pretrain Naive Shared Padded Policy on 2-DoF Source Fleet (zero-padded to 3-DoF)
torch.manual_seed(seed + 500)
naive_base = NaiveJointPolicy(sem_dim=8, max_dof=3, hidden=80)
opt_naive_src = torch.optim.AdamW(naive_base.parameters(), lr=4e-3)
q_src_pad = F.pad(src_data["q"], (0, 1), value=0.0)
dq_src_pad = F.pad(src_data["dq"], (0, 1), value=0.0)
for _ in range(epochs_pre):
pred = naive_base(src_data["sem_obs"], q_src_pad)
loss = F.mse_loss(pred, dq_src_pad)
opt_naive_src.zero_grad()
torch.autograd.backward(loss)
opt_naive_src.step()
# Off-center nominal Jacobian prior (creates realistic k=0 vs k=8 vs k=24 refinement)
q_nom_3 = torch.tensor([[-0.30, 0.45, -0.25]], dtype=torch.float32)
j_nom = tgt_arm.jacobian(q_nom_3).squeeze(0)
jjt = j_nom @ j_nom.T + (0.28**2) * torch.eye(2)
pinv_nom = j_nom.T @ torch.linalg.inv(jjt)
points: list[CrossEmbodimentPoint] = []
k_list = [0, 8, 24]
n_eval_eps = 32
for k_demos in k_list:
# 1. Target-only scratch baseline
torch.manual_seed(seed + 600 + k_demos)
scratch = NaiveJointPolicy(sem_dim=8, max_dof=3, hidden=80)
if k_demos > 0:
opt_sc = torch.optim.AdamW(scratch.parameters(), lr=4e-3, weight_decay=2e-3)
epochs_ft = 90 if quick else 120
sem_k = tgt_pool["sem_obs"][:k_demos]
q_k = tgt_pool["q"][:k_demos]
dq_k = tgt_pool["dq"][:k_demos]
for _ in range(epochs_ft):
loss = F.mse_loss(scratch(sem_k, q_k), dq_k)
opt_sc.zero_grad()
torch.autograd.backward(loss)
opt_sc.step()
scratch.eval()
mse_sc, succ_sc, err_sc = _evaluate_arm_reaching(tgt_arm, scratch, tgt_test, n_eval_eps)
points.append(
CrossEmbodimentPoint(
strategy="target_only_scratch",
target_demos_k=k_demos,
target_action_mse=mse_sc,
reach_success_rate=succ_sc,
mean_final_ee_error=err_sc,
)
)
# 2. Naive shared-head padded transfer (heavy OXE-style 2-DoF replay causes interference)
torch.manual_seed(seed + 700 + k_demos)
naive_ft = NaiveJointPolicy(sem_dim=8, max_dof=3, hidden=80)
naive_ft.load_state_dict(naive_base.state_dict())
if k_demos > 0:
opt_nv = torch.optim.AdamW(naive_ft.parameters(), lr=2.5e-3, weight_decay=1e-3)
epochs_ft = 90 if quick else 120
sem_k = tgt_pool["sem_obs"][:k_demos]
q_k = tgt_pool["q"][:k_demos]
dq_k = tgt_pool["dq"][:k_demos]
for _ in range(epochs_ft):
loss_tgt = F.mse_loss(naive_ft(sem_k, q_k), dq_k)
loss_src = F.mse_loss(
naive_ft(src_data["sem_obs"][:200], q_src_pad[:200]), dq_src_pad[:200]
)
loss = 0.25 * loss_tgt + 0.75 * loss_src
opt_nv.zero_grad()
torch.autograd.backward(loss)
opt_nv.step()
naive_ft.eval()
mse_nv, succ_nv, err_nv = _evaluate_arm_reaching(tgt_arm, naive_ft, tgt_test, n_eval_eps)
points.append(
CrossEmbodimentPoint(
strategy="naive_shared_head_padded",
target_demos_k=k_demos,
target_action_mse=mse_nv,
reach_success_rate=succ_nv,
mean_final_ee_error=err_nv,
)
)
# 3. Modular VLA: frozen shared semantic encoder + Jacobian-structured morphology adapter
torch.manual_seed(seed + 800 + k_demos)
vla_ft = ModularSemanticVLA(sem_dim=8, sem_latent=16, target_dof=3)
vla_ft.load_state_dict(vla_base.state_dict())
if k_demos > 0:
for p in vla_ft.semantic_encoder.parameters():
p.requires_grad_(False)
for p in vla_ft.workspace_head.parameters():
p.requires_grad_(False)
opt_mod = torch.optim.AdamW(
vla_ft.morphology_head.parameters(), lr=5e-3, weight_decay=1e-2
)
epochs_ft = 80 if quick else 110
sem_k = tgt_pool["sem_obs"][:k_demos]
q_k = tgt_pool["q"][:k_demos]
dq_k = tgt_pool["dq"][:k_demos]
with torch.no_grad():
_, v_ee_k = vla_ft.encode_semantic(sem_k)
dq_prior_k = v_ee_k @ pinv_nom.T
for _ in range(epochs_ft):
dq_res = vla_ft.forward_target_adapter(v_ee_k, q_k)
loss = F.mse_loss(dq_prior_k + dq_res, dq_k) + 0.02 * (dq_res**2).mean()
opt_mod.zero_grad()
torch.autograd.backward(loss)
opt_mod.step()
def _adapted_vla(
sem_obs: torch.Tensor,
q_t: torch.Tensor,
model: ModularSemanticVLA = vla_ft,
) -> torch.Tensor:
_, v_ee_hat = model.encode_semantic(sem_obs)
dq_prior = v_ee_hat @ pinv_nom.T
dq_res = model.forward_target_adapter(v_ee_hat, q_t)
return torch.clamp(dq_prior + dq_res, -1.6, 1.6)
mse_mod, succ_mod, err_mod = _evaluate_arm_reaching(
tgt_arm, _adapted_vla, tgt_test, n_eval_eps
)
points.append(
CrossEmbodimentPoint(
strategy="modular_vla_adapter",
target_demos_k=k_demos,
target_action_mse=mse_mod,
reach_success_rate=succ_mod,
mean_final_ee_error=err_mod,
)
)
def _get(strat: str, k_val: int) -> CrossEmbodimentPoint:
return next(p for p in points if p.strategy == strat and p.target_demos_k == k_val)
mod0 = _get("modular_vla_adapter", 0)
sc8, mod8 = _get("target_only_scratch", 8), _get("modular_vla_adapter", 8)
sc24, nv24, mod24 = (
_get("target_only_scratch", 24),
_get("naive_shared_head_padded", 24),
_get("modular_vla_adapter", 24),
)
return Exp2CrossEmbodimentReport(
source_embodiment=src_spec,
target_embodiment=tgt_spec,
k_values=k_list,
points=points,
zero_shot_modular_success=mod0.reach_success_rate,
few_shot_k8_positive_transfer_gain=round(mod8.reach_success_rate - sc8.reach_success_rate, 4),
few_shot_k24_positive_transfer_gain=round(mod24.reach_success_rate - sc24.reach_success_rate, 4),
naive_k24_negative_transfer_delta=round(nv24.reach_success_rate - sc24.reach_success_rate, 4),
)
if tracer is not None:
with tracer.start_as_current_span("vla.cross_embodiment") as sp:
rep = _exec()
sp.set_attribute("zero_shot_modular_success", rep.zero_shot_modular_success)
sp.set_attribute("k8_positive_gain", rep.few_shot_k8_positive_transfer_gain)
sp.set_attribute("naive_k24_negative_delta", rep.naive_k24_negative_transfer_delta)
return rep
return _exec()
# ---------------------------------------------------------------------------
# Experiment 3: Controlled 4-Axis Sim-to-Real Gap Diagnostic & Recovery
# ---------------------------------------------------------------------------
class Sim2RealPhysicsEnv:
"""Unimodal upper-corridor obstacle-avoidance simulator isolating visual, dynamics, & latency."""
def __init__(self) -> None:
self.dt = 0.22
self.obstacle_center = torch.tensor([0.0, 0.24], dtype=torch.float32)
self.obstacle_r = 0.36
self.goal = torch.tensor([0.85, 0.0], dtype=torch.float32)
def step(
self,
pos: torch.Tensor,
vel: torch.Tensor,
u_eff: torch.Tensor,
mass: float | torch.Tensor,
damping: float | torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Integrate second-order linear drag dynamics: dv/dt = (u - b*v)/m."""
u_clamp = torch.clamp(u_eff, -2.2, 2.2)
accel = (u_clamp - damping * vel) / mass
vel_next = torch.clamp(vel + self.dt * accel, -2.2, 2.2)
pos_next = torch.clamp(pos + self.dt * vel_next, -1.5, 1.5)
return pos_next, vel_next
def identify_system_parameters(self, seed: int = 42) -> tuple[float, float, int]:
"""Identify real-world (mass, damping, latency_steps) from excitation rollouts."""
gen = torch.Generator().manual_seed(seed + 911)
true_mass = 2.45
true_damp = 0.25
true_lat = 2
# 1. Step-response lag correlation to detect discrete pipeline latency (0..4 steps)
u_seq = torch.randn((40, 12, 2), generator=gen)
p_l = torch.zeros((40, 2))
v_l = torch.zeros((40, 2))
dv_seq: list[torch.Tensor] = []
buf = [torch.zeros((40, 2)) for _ in range(4)]
for t in range(12):
buf.append(u_seq[:, t, :])
u_eff = buf[-1 - true_lat]
p_l, v_nxt = self.step(p_l, v_l, u_eff, mass=true_mass, damping=true_damp)
dv_seq.append((v_nxt - v_l) / self.dt)
v_l = v_nxt
dv_ten = torch.stack(dv_seq, dim=1) # (40, 12, 2)
best_lag = 0
best_corr = -1.0
for lag in range(5):
if lag == 0:
corr = float((u_seq * dv_ten).mean().item())
else:
corr = float((u_seq[:, :-lag, :] * dv_ten[:, lag:, :]).mean().item())
if corr > best_corr:
best_corr = corr
best_lag = lag
# 2. Ridge regression on lag-aligned pairs for (mass, damping)
n_traj = 120
pos = torch.zeros((n_traj, 2))
vel = torch.empty((n_traj, 2)).uniform_(-1.0, 1.0, generator=gen)
u_cmd = torch.empty((n_traj, 2)).uniform_(-1.6, 1.6, generator=gen)
_, vel_next = self.step(pos, vel, u_cmd, mass=true_mass, damping=true_damp)
dv_dt = (vel_next - vel) / self.dt + torch.randn(vel.shape, generator=gen) * 0.02
x_mat = torch.stack([u_cmd.reshape(-1), -vel.reshape(-1)], dim=-1)
y_vec = dv_dt.reshape(-1, 1)
reg = 1e-3 * torch.eye(2)
coef = torch.linalg.solve(x_mat.T @ x_mat + reg, x_mat.T @ y_vec).squeeze(-1)
est_mass = float(torch.clamp(1.0 / torch.clamp(coef[0], min=0.1), 0.5, 4.0).item())
est_damp = float(torch.clamp(coef[1] * est_mass, 0.1, 4.0).item())
return round(est_mass, 4), round(est_damp, 4), best_lag
class Sim2RealHistoryPolicy(nn.Module):
"""Closed-loop policy consuming [obs_t(10), o_{t-1}(6), o_{t-2}(6), a_{t-1..t-3}(6)] = 28-dim."""
def __init__(self, hidden: int = 112) -> None:
super().__init__()
self.net = TypedMLP((28, hidden, hidden, 2))
def forward(self, feat: torch.Tensor) -> torch.Tensor:
return cast(torch.Tensor, self.net(feat))
def _corrupt_observation(
pos: torch.Tensor,
vel: torch.Tensor,
goal: torch.Tensor,
v_scale: torch.Tensor | float,
dist_std: torch.Tensor | float,
v_noise: float,
gen: torch.Generator,
) -> torch.Tensor:
"""Render 10-dim observation: 6 contrast-scaled/jittered kinematics + 4 visual distractors."""
pos_noisy = pos * v_scale + torch.randn(pos.shape, generator=gen) * v_noise
vel_noisy = vel * v_scale + torch.randn(vel.shape, generator=gen) * (0.5 * v_noise)
delta_noisy = (goal.unsqueeze(0) - pos) * v_scale + torch.randn(pos.shape, generator=gen) * v_noise
distractors = torch.randn((pos.shape[0], 4), generator=gen) * dist_std
return torch.cat([pos_noisy, vel_noisy, delta_noisy, distractors], dim=-1)
def _collect_sim2real_rollouts(
env: Sim2RealPhysicsEnv,
mass_range: tuple[float, float],
damp_range: tuple[float, float],
lat_choices: tuple[int, ...],
vis_scale_range: tuple[float, float],
dist_std_range: tuple[float, float],
vis_noise_std: float,
use_history: bool,
num_episodes: int,
seed: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Collect unimodal upper-corridor rollouts with delay compensation & action-obs history."""
gen = torch.Generator().manual_seed(seed)
feats_list: list[torch.Tensor] = []
targets_list: list[torch.Tensor] = []
for lat in lat_choices:
ep_n = max(24, num_episodes // len(lat_choices))
masses = torch.empty(ep_n).uniform_(mass_range[0], mass_range[1], generator=gen).unsqueeze(-1)
damps = torch.empty(ep_n).uniform_(damp_range[0], damp_range[1], generator=gen).unsqueeze(-1)
v_scale = torch.empty((ep_n, 1)).uniform_(vis_scale_range[0], vis_scale_range[1], generator=gen)
dist_std = torch.empty((ep_n, 1)).uniform_(dist_std_range[0], dist_std_range[1], generator=gen)
pos = torch.stack(
[
torch.empty(ep_n).uniform_(-0.85, -0.68, generator=gen),
torch.empty(ep_n).uniform_(0.12, 0.24, generator=gen),
],
dim=-1,
)
vel = torch.zeros((ep_n, 2), dtype=torch.float32)
buf: list[torch.Tensor] = [torch.zeros((ep_n, 2)) for _ in range(4)]
prev_obs_1 = _corrupt_observation(
pos, vel, env.goal, v_scale, dist_std, vis_noise_std, gen
)
prev_obs_2 = prev_obs_1.clone()
n_rollout_steps = 32
for _step in range(n_rollout_steps):
obs_cur = _corrupt_observation(pos, vel, env.goal, v_scale, dist_std, vis_noise_std, gen)
if use_history:
feat = torch.cat(
[obs_cur, prev_obs_1[:, :6], prev_obs_2[:, :6], buf[-1], buf[-2], buf[-3]],
dim=-1,
)
else:
feat = torch.cat(
[obs_cur, torch.zeros((ep_n, 18), dtype=obs_cur.dtype)], dim=-1
)
p_lead, v_lead = pos.clone(), vel.clone()
for q_idx in range(lat):
u_queued = buf[-lat + q_idx]
p_lead, v_lead = env.step(p_lead, v_lead, u_queued, mass=masses, damping=damps)
px = p_lead[:, 0]
clear_w = torch.sigmoid((0.20 - px) * 7.5)
sub_x = clear_w * torch.clamp(px + 0.42, max=0.28) + (1.0 - clear_w) * 0.85
sub_y = clear_w * 0.72
target_p = torch.stack([sub_x, sub_y], dim=-1)
desired_v = torch.clamp((target_p - p_lead) * 2.8, -1.75, 1.75)
u_opt = damps * v_lead + (masses / env.dt) * 0.65 * (desired_v - v_lead)
u_opt = torch.clamp(u_opt, -2.1, 2.1)
feats_list.append(feat)
targets_list.append(u_opt)
a_exec = torch.clamp(u_opt + torch.randn(u_opt.shape, generator=gen) * 0.10, -2.1, 2.1)
buf.append(a_exec)
u_eff = buf[-1 - lat]
pos, vel = env.step(pos, vel, u_eff, mass=masses, damping=damps)
prev_obs_2 = prev_obs_1
prev_obs_1 = obs_cur
return torch.cat(feats_list, dim=0), torch.cat(targets_list, dim=0)
def _train_sim2real_policy(
env: Sim2RealPhysicsEnv,
strategy: Literal["no_adaptation", "sysid_only", "dr_only", "dr_history_sysid"],
id_mass: float,
id_damp: float,
id_lat: int,
seed: int,
quick: bool,
) -> Sim2RealHistoryPolicy:
"""Train Sim-to-Real policy via real PyTorch backprop over strategy-matched rollouts."""
torch.manual_seed(seed)
hidden_w = 192 if strategy == "dr_history_sysid" else 112
pol = Sim2RealHistoryPolicy(hidden=hidden_w)
wd = 1e-4 if strategy in ("no_adaptation", "sysid_only", "dr_history_sysid") else 2e-3
lr_init = 4e-3 if strategy == "dr_history_sysid" else 3.5e-3
opt = torch.optim.AdamW(pol.parameters(), lr=lr_init, weight_decay=wd)
n_eps = 44 if quick else 60
if strategy == "no_adaptation":
feats, targets = _collect_sim2real_rollouts(
env, (0.72, 0.78), (0.75, 0.85), (0,), (1.0, 1.0), (0.0, 0.0), 0.0, False, n_eps, seed
)
elif strategy == "sysid_only":
feats, targets = _collect_sim2real_rollouts(
env,
(id_mass * 0.96, id_mass * 1.04),
(id_damp * 0.90, id_damp * 1.10),
(0,),
(1.0, 1.0),
(0.0, 0.0),
0.0,
False,
n_eps,
seed,
)
elif strategy == "dr_only":
feats, targets = _collect_sim2real_rollouts(
env, (0.68, 0.95), (0.65, 0.95), (0,), (0.52, 1.05), (0.0, 2.8), 0.045, False, n_eps, seed
)
else: # dr_history_sysid
n_env_eps = 64 if quick else 92
n_sys_eps = 72 if quick else 88
n_nom_eps = 40 if quick else 56
f_env, t_env = _collect_sim2real_rollouts(
env,
(0.68, 2.70),
(0.20, 0.92),
(0, id_lat),
(0.50, 1.05),
(0.0, 2.9),
0.045,
True,
n_env_eps,
seed,
)
f_sys_comb, t_sys_comb = _collect_sim2real_rollouts(
env,
(id_mass * 0.92, id_mass * 1.08),
(max(0.15, id_damp * 0.80), id_damp * 1.25),
(id_lat,),
(0.48, 0.84),
(1.0, 2.9),
0.05,
True,
n_sys_eps,
seed + 100,
)
f_sys_dyn, t_sys_dyn = _collect_sim2real_rollouts(
env,
(id_mass * 0.92, id_mass * 1.08),
(max(0.15, id_damp * 0.80), id_damp * 1.25),
(0,),
(0.85, 1.02),
(0.0, 0.4),
0.015,
True,
n_nom_eps,
seed + 150,
)
f_nom, t_nom = _collect_sim2real_rollouts(
env,
(0.70, 0.85),
(0.68, 0.90),
(0,),
(0.50, 1.02),
(0.0, 2.9),
0.035,
True,
n_nom_eps,
seed + 200,
)
f_nom_lat, t_nom_lat = _collect_sim2real_rollouts(
env,
(0.70, 0.85),
(0.68, 0.90),
(id_lat,),
(0.80, 1.02),
(0.0, 0.6),
0.015,
True,
n_nom_eps,
seed + 250,
)
feats = torch.cat([f_env, f_sys_comb, f_sys_dyn, f_nom, f_nom_lat], dim=0)
targets = torch.cat([t_env, t_sys_comb, t_sys_dyn, t_nom, t_nom_lat], dim=0)
n_samples = feats.shape[0]
batch_sz = (128 if quick else 192) if strategy == "dr_history_sysid" else 256
epochs = (220 if quick else 235) if strategy == "dr_history_sysid" else (165 if quick else 195)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs, eta_min=1e-4)
gen = torch.Generator().manual_seed(seed + 77)
first_linear = pol.net.net[0]
for _ in range(epochs):
perm = torch.randperm(n_samples, generator=gen)
for start in range(0, n_samples, batch_sz):
idx = perm[start : start + batch_sz]
loss = F.mse_loss(pol(feats[idx]), targets[idx])
if strategy in ("dr_only", "dr_history_sysid") and isinstance(first_linear, nn.Linear):
loss = loss + 3.5e-3 * first_linear.weight[:, 6:10].abs().sum()
opt.zero_grad()
torch.autograd.backward(loss)
opt.step()
sched.step()
pol.eval()
return pol
def _evaluate_sim2real_regime(
env: Sim2RealPhysicsEnv,
policy: Sim2RealHistoryPolicy,
strategy: Literal["no_adaptation", "sysid_only", "dr_only", "dr_history_sysid"],
regime: Literal[
"nominal_sim",
"visual_noise_shift",
"dynamics_friction_mass_shift",
"actuation_latency_2steps",
"combined_real_world",
],
seed: int,
num_episodes: int = 40,
) -> Sim2RealRegimePoint:
"""Roll out closed-loop policy under an isolated or combined Sim-to-Real perturbation."""
regime_cfg: dict[str, tuple[float, float, int, float, float, float]] = {
"nominal_sim": (0.75, 0.80, 0, 1.0, 0.0, 0.0),
"visual_noise_shift": (0.75, 0.80, 0, 0.55, 2.8, 0.05),
"dynamics_friction_mass_shift": (2.45, 0.25, 0, 1.0, 0.0, 0.0),
"actuation_latency_2steps": (0.75, 0.80, 2, 1.0, 0.0, 0.0),
"combined_real_world": (2.45, 0.25, 2, 0.55, 2.8, 0.05),
}
mass, damp, lat, v_scale, dist_std, v_noise = regime_cfg[regime]
gen = torch.Generator().manual_seed(seed + 1200 + len(regime))
pos = torch.stack(
[
torch.empty(num_episodes).uniform_(-0.85, -0.68, generator=gen),
torch.empty(num_episodes).uniform_(0.12, 0.24, generator=gen),
],
dim=-1,
)
vel = torch.zeros((num_episodes, 2), dtype=torch.float32)
collided = torch.zeros(num_episodes, dtype=torch.bool)
reached = torch.zeros(num_episodes, dtype=torch.bool)
buf: list[torch.Tensor] = [torch.zeros((num_episodes, 2)) for _ in range(4)]
prev_obs_1 = _corrupt_observation(pos, vel, env.goal, v_scale, dist_std, v_noise, gen)
prev_obs_2 = prev_obs_1.clone()
with torch.no_grad():
for _step in range(32):
obs_cur = _corrupt_observation(pos, vel, env.goal, v_scale, dist_std, v_noise, gen)
if strategy == "dr_history_sysid":
feat = torch.cat(
[obs_cur, prev_obs_1[:, :6], prev_obs_2[:, :6], buf[-1], buf[-2], buf[-3]],
dim=-1,
)
else:
feat = torch.cat(
[obs_cur, torch.zeros((num_episodes, 18), dtype=obs_cur.dtype)], dim=-1
)
a_new = torch.clamp(policy(feat), -2.1, 2.1)
buf.append(a_new)
u_eff = buf[-1 - lat]
active = (~collided) & (~reached)
p_nxt, v_nxt = env.step(pos, vel, u_eff, mass=mass, damping=damp)
pos = torch.where(active.unsqueeze(-1), p_nxt, pos)
vel = torch.where(active.unsqueeze(-1), v_nxt, vel)
prev_obs_2 = prev_obs_1
prev_obs_1 = obs_cur
obs_dist = torch.linalg.norm(pos - env.obstacle_center.unsqueeze(0), dim=-1)
goal_dist = torch.linalg.norm(pos - env.goal.unsqueeze(0), dim=-1)
collided = collided | (active & (obs_dist < env.obstacle_r))
reached = reached | (active & (~collided) & (goal_dist <= 0.16))
final_dist = torch.linalg.norm(pos - env.goal.unsqueeze(0), dim=-1)
succ = reached & (~collided)
return Sim2RealRegimePoint(
strategy=strategy,
regime=regime,
success_rate=round(float(succ.float().mean().item()), 4),
collision_rate=round(float(collided.float().mean().item()), 4),
mean_final_goal_dist=round(float(final_dist.mean().item()), 4),
)
def run_sim2real_ablation_diagnostic(
seed: int = 42,
quick: bool = False,
tracer: Tracer | None = None,
) -> Exp3Sim2RealReport:
"""Run Experiment 3: Controlled 4-Axis Sim-to-Real Gap Isolation & Recovery."""
env = Sim2RealPhysicsEnv()
def _exec() -> Exp3Sim2RealReport:
id_mass, id_damp, id_lat = env.identify_system_parameters(seed=seed)
strategies: tuple[Literal["no_adaptation", "sysid_only", "dr_only", "dr_history_sysid"], ...] = (
"no_adaptation",
"sysid_only",
"dr_only",
"dr_history_sysid",
)
regimes: tuple[
Literal[
"nominal_sim",
"visual_noise_shift",
"dynamics_friction_mass_shift",
"actuation_latency_2steps",
"combined_real_world",
],
...,
] = (
"nominal_sim",
"visual_noise_shift",
"dynamics_friction_mass_shift",
"actuation_latency_2steps",
"combined_real_world",
)
n_eps = 28 if quick else 40
points: list[Sim2RealRegimePoint] = []
for idx, strat in enumerate(strategies):
pol = _train_sim2real_policy(
env,
strategy=strat,
id_mass=id_mass,
id_damp=id_damp,
id_lat=id_lat,
seed=seed + 1500 + idx * 31,
quick=quick,
)
for reg in regimes:
points.append(
_evaluate_sim2real_regime(
env,
pol,
strategy=strat,
regime=reg,
seed=seed,
num_episodes=n_eps,
)
)
def _find(s: str, r: str) -> Sim2RealRegimePoint:
return next(p for p in points if p.strategy == s and p.regime == r)
nom = _find("no_adaptation", "nominal_sim")
comb_no = _find("no_adaptation", "combined_real_world")
comb_sysid = _find("sysid_only", "combined_real_world")
comb_dr = _find("dr_only", "combined_real_world")
comb_full = _find("dr_history_sysid", "combined_real_world")
single_axes = (
"visual_noise_shift",
"dynamics_friction_mass_shift",
"actuation_latency_2steps",
)
dominant_axis = min(single_axes, key=lambda r: _find("no_adaptation", r).success_rate)
return Exp3Sim2RealReport(
true_mass=2.45,
true_damping=0.25,
true_latency_steps=2,
identified_mass=id_mass,
identified_damping=id_damp,
identified_latency_steps=id_lat,
regimes=list(regimes),
strategies=list(strategies),
points=points,
no_adapt_nominal_success=nom.success_rate,
no_adapt_combined_success=comb_no.success_rate,
sysid_only_combined_success=comb_sysid.success_rate,
dr_only_combined_success=comb_dr.success_rate,
full_stack_combined_success=comb_full.success_rate,
dominant_single_axis_drop=dominant_axis,
)
if tracer is not None:
with tracer.start_as_current_span("sim2real.ablation_diagnostic") as sp:
rep = _exec()
sp.set_attribute("identified_mass", rep.identified_mass)
sp.set_attribute("identified_latency_steps", rep.identified_latency_steps)
sp.set_attribute("no_adapt_combined", rep.no_adapt_combined_success)
sp.set_attribute("full_stack_combined", rep.full_stack_combined_success)
return rep
return _exec()
def run_full_robotics_benchmark(seed: int = 42, quick: bool = False) -> FullRoboticsBenchmarkReport:
"""Orchestrate Lab 17 across Diffusion vs Flow, Cross-Embodiment VLA & Sim-to-Real with OTel."""
np.random.seed(seed)
torch.manual_seed(seed)
provider, exporter, tracer = create_in_memory_otel_tracer("robotics_action_policy_lab", max_spans=64)
exp1 = run_diffusion_vs_flow_benchmark(seed=seed, quick=quick, tracer=tracer)
exp2 = run_cross_embodiment_vla_study(seed=seed, quick=quick, tracer=tracer)
exp3 = run_sim2real_ablation_diagnostic(seed=seed, quick=quick, tracer=tracer)
spans = exporter.get_finished_spans()
distinct_names = sorted({s.name for s in spans})
provider.shutdown()
return FullRoboticsBenchmarkReport(
config={"seed": seed, "quick": quick},
exp1_diffusion_vs_flow=exp1,
exp2_cross_embodiment_vla=exp2,
exp3_sim2real_diagnostic=exp3,
otel_telemetry=OtelSummary(
total_spans_recorded=len(spans),
distinct_span_names=distinct_names,
),
)
"""CLI Benchmark & Artifact Generator for Lab 17 (T1-P7-U02: Robotics Policies, VLAs & Sim-to-Real)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
_LAB_ROOT = Path(__file__).resolve().parents[1]
_SRC_DIR = str(_LAB_ROOT / "src")
if _SRC_DIR not in sys.path:
sys.path.insert(0, _SRC_DIR)
from robotics_action_policy_lab.vla_and_sim2real import ( # noqa: E402
run_full_robotics_benchmark,
)
def run_lab17_benchmark(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute Lab 17 benchmark and assemble 6 KPIs, 4 bar charts, and 4 workbench tables."""
bench_model = run_full_robotics_benchmark(seed=seed, quick=quick)
bench = bench_model.model_dump()
exp1 = bench["exp1_diffusion_vs_flow"]
exp2 = bench["exp2_cross_embodiment_vla"]
exp3 = bench["exp3_sim2real_diagnostic"]
otel = bench["otel_telemetry"]
mse_p = exp1["mse_baseline"]
nfe_pts = exp1["nfe_pareto_sweep"]
ddim_4 = next(p for p in nfe_pts if p["policy_name"] == "ddim_diffusion" and p["nfe"] == 4)
ddim_20 = next(p for p in nfe_pts if p["policy_name"] == "ddim_diffusion" and p["nfe"] == 20)
ddim_50 = next(p for p in nfe_pts if p["policy_name"] == "ddim_diffusion" and p["nfe"] == 50)
cfm_4 = next(
p for p in nfe_pts if p["policy_name"] == "conditional_flow_matching" and p["nfe"] == 4
)
cfm_8 = next(
p for p in nfe_pts if p["policy_name"] == "conditional_flow_matching" and p["nfe"] == 8
)
vla_pts = exp2["points"]
def _vla(strat: str, k: int) -> dict[str, Any]:
return next(
p for p in vla_pts if p["strategy"] == strat and p["target_demos_k"] == k
)
sc_0 = _vla("target_only_scratch", 0)
nv_0 = _vla("naive_shared_head_padded", 0)
mod_0 = _vla("modular_vla_adapter", 0)
sc_8 = _vla("target_only_scratch", 8)
nv_8 = _vla("naive_shared_head_padded", 8)
mod_8 = _vla("modular_vla_adapter", 8)
sc_24 = _vla("target_only_scratch", 24)
nv_24 = _vla("naive_shared_head_padded", 24)
mod_24 = _vla("modular_vla_adapter", 24)
s2r_pts = exp3["points"]
def _s2r(strat: str, reg: str) -> dict[str, Any]:
return next(p for p in s2r_pts if p["strategy"] == strat and p["regime"] == reg)
def _pct(val: float) -> str:
return f"{val * 100:.1f}%"
def _vla_cell(row: dict[str, Any]) -> str:
return f"{row['target_action_mse']:.3f} / {_pct(row['reach_success_rate'])}"
def _s2r_row(strat: str) -> list[str]:
s_nom = _pct(_s2r(strat, "nominal_sim")["success_rate"])
s_vis = _pct(_s2r(strat, "visual_noise_shift")["success_rate"])
s_dyn = _pct(_s2r(strat, "dynamics_friction_mass_shift")["success_rate"])
s_lat = _pct(_s2r(strat, "actuation_latency_2steps")["success_rate"])
comb = _s2r(strat, "combined_real_world")
return [
strat,
f"{s_nom} / {s_vis}",
f"{s_dyn} / {s_lat}",
f"{_pct(comb['success_rate'])} (coll={_pct(comb['collision_rate'])})",
]
no_nom = _s2r("no_adaptation", "nominal_sim")
no_vis = _s2r("no_adaptation", "visual_noise_shift")
no_dyn = _s2r("no_adaptation", "dynamics_friction_mass_shift")
no_lat = _s2r("no_adaptation", "actuation_latency_2steps")
no_comb = _s2r("no_adaptation", "combined_real_world")
sysid_comb = _s2r("sysid_only", "combined_real_world")
dr_comb = _s2r("dr_only", "combined_real_world")
full_comb = _s2r("dr_history_sysid", "combined_real_world")
speedup_cfm4 = exp1["cfm_vs_ddim_speedup_at_equal_or_higher_success"]
pos_gain_k8 = exp2["few_shot_k8_positive_transfer_gain"] * 100
workbench_panels: dict[str, Any] = {
"kpis": [
{
"id": "kpi_mse_bimodal_collision",
"label": "MSE Mode-Averaging Collision Rate",
"value": _pct(mse_p["collision_rate"]),
"unit": (
f"(Success {_pct(mse_p['success_rate'])} vs "
f"CFM-8 {_pct(cfm_8['success_rate'])})"
),
"status": "warn",
"detail": (
"Deterministic MSE averages upper & lower arcs "
f"(entropy={mse_p['mode_entropy_bits']:.2f} bits, "
f"collision={_pct(mse_p['collision_rate'])}); CFM-8 preserves "
f"bimodality ({cfm_8['mode_entropy_bits']:.2f} bits)."
),
},
{
"id": "kpi_cfm_low_nfe_success",
"label": "Flow Matching Success @ NFE=4 / 8",
"value": f"{_pct(cfm_4['success_rate'])} / {_pct(cfm_8['success_rate'])}",
"unit": (
f"(vs DDIM-4 {_pct(ddim_4['success_rate'])}, "
f"DDIM-50 {_pct(ddim_50['success_rate'])})"
),
"status": "ok",
"detail": (
f"OT straight paths solve accurately in 4-8 NFE "
f"(CFM-4 Hz={cfm_4['control_hz']:.0f}, "
f"DDIM-50 Hz={ddim_50['control_hz']:.0f})."
),
},
{
"id": "kpi_cfm_hz_speedup",
"label": "CFM-4 vs DDIM-50 Control Speedup",
"value": f"{speedup_cfm4:.2f}x",
"unit": f"({cfm_4['control_hz']:.0f} Hz vs {ddim_50['control_hz']:.0f} Hz)",
"status": "ok",
"detail": (
f"CFM-4 takes {cfm_4['inference_ms_per_chunk']:.2f} ms/chunk vs "
f"DDIM-50 {ddim_50['inference_ms_per_chunk']:.2f} ms/chunk at H_e=4."
),
},
{
"id": "kpi_vla_cross_embodiment",
"label": "Modular VLA 3-DoF Transfer (k=0 / k=24)",
"value": (
f"{_pct(mod_0['reach_success_rate'])} / "
f"{_pct(mod_24['reach_success_rate'])}"
),
"unit": (
f"(Naive k=24: {_pct(nv_24['reach_success_rate'])} | "
f"Scratch: {_pct(sc_24['reach_success_rate'])})"
),
"status": "ok",
"detail": (
"Shared semantic encoder + morphology adapter gives positive transfer "
f"(+{pos_gain_k8:.1f}pp @ k=8) vs naive padding negative transfer."
),
},
{
"id": "kpi_sim2real_recovery",
"label": "Combined Real-World Success Recovery",
"value": _pct(full_comb["success_rate"]),
"unit": (
f"(No-Adapt {_pct(no_comb['success_rate'])} vs "
f"Nominal {_pct(no_nom['success_rate'])})"
),
"status": "ok",
"detail": (
f"SysID estimated mass={exp3['identified_mass']:.2f} "
f"(true {exp3['true_mass']:.2f}), "
f"lag={exp3['identified_latency_steps']} steps; "
"DR + History + SysID recovers combined gap from "
f"{_pct(no_comb['success_rate'])}."
),
},
{
"id": "kpi_otel_telemetry_spans",
"label": "OpenTelemetry Bounded Spans",
"value": f"{otel['total_spans_recorded']} spans",
"unit": f"({len(otel['distinct_span_names'])} distinct phases)",
"status": "ok",
"detail": (
"BoundedInMemorySpanExporter captured "
+ ", ".join(otel["distinct_span_names"])
+ "."
),
},
],
"bars": [
{
"id": "bar_nfe_success_comparison",
"title": (
"Bimodal Success Rate (%) Across NFE: "
"Conditional Flow Matching vs DDIM Diffusion"
),
"metric_label": "Success Rate (%)",
"items": [
{
"label": f"ddim_nfe_{p['nfe']}",
"value": round(p["success_rate"] * 100.0, 2),
"display": (
f"DDIM NFE={p['nfe']}: {_pct(p['success_rate'])} "
f"({p['control_hz']:.0f} Hz)"
),
"css_class": "is-mid" if p["success_rate"] >= 0.75 else "is-slow",
}
for p in nfe_pts
if p["policy_name"] == "ddim_diffusion" and p["nfe"] in (1, 4, 8, 50)
]
+ [
{
"label": f"cfm_nfe_{p['nfe']}",
"value": round(p["success_rate"] * 100.0, 2),
"display": (
f"CFM NFE={p['nfe']}: {_pct(p['success_rate'])} "
f"({p['control_hz']:.0f} Hz)"
),
"css_class": "is-fast" if p["success_rate"] >= 0.80 else "is-slow",
}
for p in nfe_pts
if p["policy_name"] == "conditional_flow_matching" and p["nfe"] in (1, 4, 8, 50)
],
},
{
"id": "bar_control_hz_pareto",
"title": "Closed-Loop Control Frequency (Hz) at H_e=4 Across Policies & NFEs",
"metric_label": "Control Frequency (Hz)",
"items": [
{
"label": "ddim_50",
"value": round(ddim_50["control_hz"], 1),
"display": (
f"DDIM NFE=50: {ddim_50['control_hz']:.0f} Hz "
f"(Succ {_pct(ddim_50['success_rate'])})"
),
"css_class": "is-slow",
},
{
"label": "ddim_20",
"value": round(ddim_20["control_hz"], 1),
"display": (
f"DDIM NFE=20: {ddim_20['control_hz']:.0f} Hz "
f"(Succ {_pct(ddim_20['success_rate'])})"
),
"css_class": "is-mid",
},
{
"label": "cfm_8",
"value": round(cfm_8["control_hz"], 1),
"display": (
f"CFM NFE=8: {cfm_8['control_hz']:.0f} Hz "
f"(Succ {_pct(cfm_8['success_rate'])})"
),
"css_class": "is-fast",
},
{
"label": "cfm_4",
"value": round(cfm_4["control_hz"], 1),
"display": (
f"CFM NFE=4: {cfm_4['control_hz']:.0f} Hz "
f"(Succ {_pct(cfm_4['success_rate'])})"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_vla_cross_embodiment_k24",
"title": "3-DoF Target Reaching Success (%) Across Transfer Strategies (k=0, 8, 24)",
"metric_label": "Reaching Success (%)",
"items": [
{
"label": "naive_k8",
"value": round(nv_8["reach_success_rate"] * 100.0, 2),
"display": f"Naive Padded (k=8): {_pct(nv_8['reach_success_rate'])}",
"css_class": "is-slow",
},
{
"label": "scratch_k8",
"value": round(sc_8["reach_success_rate"] * 100.0, 2),
"display": f"Target Scratch (k=8): {_pct(sc_8['reach_success_rate'])}",
"css_class": "is-mid",
},
{
"label": "modular_k8",
"value": round(mod_8["reach_success_rate"] * 100.0, 2),
"display": f"Modular VLA (k=8): {_pct(mod_8['reach_success_rate'])}",
"css_class": "is-fast",
},
{
"label": "naive_k24",
"value": round(nv_24["reach_success_rate"] * 100.0, 2),
"display": f"Naive Padded (k=24): {_pct(nv_24['reach_success_rate'])}",
"css_class": "is-slow",
},
{
"label": "scratch_k24",
"value": round(sc_24["reach_success_rate"] * 100.0, 2),
"display": f"Target Scratch (k=24): {_pct(sc_24['reach_success_rate'])}",
"css_class": "is-mid",
},
{
"label": "modular_k24",
"value": round(mod_24["reach_success_rate"] * 100.0, 2),
"display": f"Modular VLA (k=24): {_pct(mod_24['reach_success_rate'])}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_sim2real_gap_diagnosis",
"title": (
"Controlled Sim-to-Real Success (%): "
"Single-Factor Attribution & Combined Recovery"
),
"metric_label": "Success Rate (%)",
"items": [
{
"label": "no_adapt_nominal",
"value": round(no_nom["success_rate"] * 100.0, 2),
"display": f"Nominal Sim (No Adapt): {_pct(no_nom['success_rate'])}",
"css_class": "is-fast",
},
{
"label": "no_adapt_visual",
"value": round(no_vis["success_rate"] * 100.0, 2),
"display": f"Visual Noise Shift: {_pct(no_vis['success_rate'])}",
"css_class": "is-mid" if no_vis["success_rate"] >= 0.4 else "is-slow",
},
{
"label": "no_adapt_dynamics",
"value": round(no_dyn["success_rate"] * 100.0, 2),
"display": f"Dynamics Mass/Friction Shift: {_pct(no_dyn['success_rate'])}",
"css_class": "is-slow",
},
{
"label": "no_adapt_latency",
"value": round(no_lat["success_rate"] * 100.0, 2),
"display": f"Actuation Latency (2-step): {_pct(no_lat['success_rate'])}",
"css_class": "is-slow",
},
{
"label": "no_adapt_combined",
"value": round(no_comb["success_rate"] * 100.0, 2),
"display": f"Combined Real (No Adapt): {_pct(no_comb['success_rate'])}",
"css_class": "is-slow",
},
{
"label": "sysid_combined",
"value": round(sysid_comb["success_rate"] * 100.0, 2),
"display": f"Combined Real (SysID Only): {_pct(sysid_comb['success_rate'])}",
"css_class": "is-mid",
},
{
"label": "dr_combined",
"value": round(dr_comb["success_rate"] * 100.0, 2),
"display": f"Combined Real (DR Only): {_pct(dr_comb['success_rate'])}",
"css_class": "is-mid",
},
{
"label": "full_stack_combined",
"value": round(full_comb["success_rate"] * 100.0, 2),
"display": (
f"Combined Real (DR+History+SysID): {_pct(full_comb['success_rate'])}"
),
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "tbl_exp1_diffusion_vs_flow",
"title": (
"Experiment 1: Deterministic MSE vs DDIM Diffusion vs Conditional Flow Matching"
),
"columns": [
"Policy & NFE (H_e=4)",
"Success / Collision",
"Mode Entropy / Jerk",
"Latency (ms) & Control Hz",
],
"rows": [
[
"Deterministic MSE (NFE=1)",
f"{_pct(mse_p['success_rate'])} / {_pct(mse_p['collision_rate'])}",
f"{mse_p['mode_entropy_bits']:.2f} bits / jerk={mse_p['mean_action_jerk']:.3f}",
f"{mse_p['inference_ms_per_chunk']:.2f} ms ({mse_p['control_hz']:.0f} Hz)",
]
]
+ [
[
(
f"{'DDIM' if p['policy_name'] == 'ddim_diffusion' else 'Flow (CFM)'}"
f" NFE={p['nfe']}"
),
f"{_pct(p['success_rate'])} / {_pct(p['collision_rate'])}",
f"{p['mode_entropy_bits']:.2f} bits / jerk={p['mean_action_jerk']:.3f}",
f"{p['inference_ms_per_chunk']:.2f} ms ({p['control_hz']:.0f} Hz)",
]
for p in nfe_pts
if p["nfe"] in (1, 4, 8, 20, 50)
],
},
{
"id": "tbl_exp1_exec_horizon",
"title": "Experiment 1B: Action-Chunking Execution Horizon Replanning (H_e in {1, 4, 8})",
"columns": [
"Policy & Execution Horizon",
"Success / Collision",
"Action Jerk",
"Effective Control Hz",
],
"rows": [
[
(
f"{'DDIM-20' if p['policy_name'] == 'ddim_diffusion' else 'CFM-8'}"
f" (H_e={p['exec_horizon']})"
),
f"{_pct(p['success_rate'])} / {_pct(p['collision_rate'])}",
f"{p['mean_action_jerk']:.3f}",
f"{p['control_hz']:.0f} Hz",
]
for p in exp1["exec_horizon_ablation"]
],
},
{
"id": "tbl_exp2_vla_transfer",
"title": "Experiment 2: Cross-Embodiment Transfer (2-DoF Source -> 3-DoF Target Arm)",
"columns": [
"Transfer Strategy",
"Zero-Shot (k=0) MSE / Succ",
"Few-Shot (k=8) MSE / Succ",
"Few-Shot (k=24) MSE / Succ",
],
"rows": [
[
"Target-Only Scratch",
_vla_cell(sc_0),
_vla_cell(sc_8),
_vla_cell(sc_24),
],
[
"Naive Shared Head (Zero-Pad)",
_vla_cell(nv_0),
_vla_cell(nv_8),
_vla_cell(nv_24),
],
[
"Modular VLA (Semantic + Adapter)",
_vla_cell(mod_0),
_vla_cell(mod_8),
_vla_cell(mod_24),
],
],
},
{
"id": "tbl_exp3_sim2real_matrix",
"title": "Experiment 3: Controlled 4-Axis Sim-to-Real Gap Diagnostic Matrix (Success %)",
"columns": [
"Adaptation Strategy",
"Nominal / Visual Shift",
"Dynamics Shift / 2-Step Latency",
"Combined Real-World Shift",
],
"rows": [_s2r_row(strat) for strat in exp3["strategies"]],
},
],
}
return {**bench, "workbench_panels": workbench_panels}
def main() -> None:
parser = argparse.ArgumentParser(
description="Run Lab 17 Robotics Flow Matching vs Diffusion, VLA Transfer & Sim-to-Real benchmark."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true")
parser.add_argument(
"--output",
type=Path,
default=_LAB_ROOT / "artifacts" / "ch29_lab17_results.json",
)
args = parser.parse_args()
result = run_lab17_benchmark(seed=args.seed, quick=args.quick)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2), encoding="utf-8")
print(f"Wrote Lab 17 artifact to {args.output}")
if __name__ == "__main__":
main()
"""Strict verification test suite for Lab 17 (Diffusion vs Flow Matching, VLAs & Sim-to-Real)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
from typing import Any
import pytest
import torch
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from robotics_action_policy_lab import (
BimodalObstacleNavEnv,
BoundedInMemorySpanExporter,
ConditionalFlowMatchingPolicy,
CrossEmbodimentPoint,
DDIMDiffusionActionPolicy,
EmbodimentSpec,
FullRoboticsBenchmarkReport,
ModularSemanticVLA,
NavEnvSpec,
OtelSummary,
PlanarArmKinematics,
PolicyEvalMetrics,
Sim2RealPhysicsEnv,
Sim2RealRegimePoint,
TypedMLP,
create_in_memory_otel_tracer,
run_cross_embodiment_vla_study,
run_diffusion_vs_flow_benchmark,
run_full_robotics_benchmark,
run_sim2real_ablation_diagnostic,
)
from robotics_action_policy_lab.diffusion_vs_flow import sinusoidal_time_embedding
LAB_ROOT = Path(__file__).resolve().parents[1]
ARTIFACT_PATH = LAB_ROOT / "artifacts" / "ch29_lab17_results.json"
@pytest.fixture(scope="module")
def quick_benchmark() -> FullRoboticsBenchmarkReport:
"""Run the full Lab 17 benchmark once in quick mode for shared assertions."""
return run_full_robotics_benchmark(seed=42, quick=True)
def test_ast_security_gate_and_zero_type_ignore() -> None:
"""Verify AST safety across src, scripts, and tests (zero unsafe serializers/eval/ignore)."""
banned_modules = frozenset({"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"})
banned_calls = frozenset({"eval", "exec"})
ignore_marker = "# type:" + " ignore"
py_files = [
*sorted((LAB_ROOT / "src").rglob("*.py")),
*sorted((LAB_ROOT / "scripts").rglob("*.py")),
*sorted((LAB_ROOT / "tests").rglob("*.py")),
]
assert len(py_files) >= 5
for py_file in py_files:
text = py_file.read_text(encoding="utf-8")
assert ignore_marker not in text, f"Found forbidden type-ignore in {py_file}"
tree = ast.parse(text, filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
assert alias.name.split(".")[0] not in banned_modules
elif isinstance(node, ast.ImportFrom) and node.module is not None:
assert node.module.split(".")[0] not in banned_modules
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in banned_calls
def test_pydantic_models_forbid_extra_fields(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""Strict ConfigDict(extra='forbid') must reject unknown fields on every public schema."""
with pytest.raises(ValidationError):
NavEnvSpec.model_validate({"obs_dim": 6, "unexpected_field": 123})
with pytest.raises(ValidationError):
EmbodimentSpec.model_validate(
{"name": "x", "dof": 2, "link_lengths": [0.5, 0.5], "extra_bad": True}
)
sample_m = quick_benchmark.exp1_diffusion_vs_flow.mse_baseline.model_dump()
with pytest.raises(ValidationError):
PolicyEvalMetrics.model_validate({**sample_m, "bonus": 1.0})
sample_x = quick_benchmark.exp2_cross_embodiment_vla.points[0].model_dump()
with pytest.raises(ValidationError):
CrossEmbodimentPoint.model_validate({**sample_x, "bogus": "nope"})
sample_s = quick_benchmark.exp3_sim2real_diagnostic.points[0].model_dump()
with pytest.raises(ValidationError):
Sim2RealRegimePoint.model_validate({**sample_s, "extra_flag": False})
with pytest.raises(ValidationError):
OtelSummary.model_validate(
{"total_spans_recorded": 4, "distinct_span_names": ["a"], "leak": 0}
)
def test_ot_interpolant_endpoints_and_velocity_linearity() -> None:
"""Check straight-line OT interpolant x_0 at t=0, x_1 at t=1, and velocity x_1 - x_0."""
x0 = torch.randn((8, 16))
x1 = torch.randn((8, 16))
xt0, v0 = ConditionalFlowMatchingPolicy.ot_interpolant(x0, x1, torch.zeros(8))
xt1, v1 = ConditionalFlowMatchingPolicy.ot_interpolant(x0, x1, torch.ones(8))
assert torch.allclose(xt0, x0, atol=1e-6)
assert torch.allclose(xt1, x1, atol=1e-6)
assert torch.allclose(v0, x1 - x0, atol=1e-6)
assert torch.allclose(v1, x1 - x0, atol=1e-6)
def test_sinusoidal_time_embedding_and_typed_mlp() -> None:
"""Verify sinusoidal Fourier embedding dimensions and TypedMLP validation."""
t = torch.linspace(0.0, 1.0, 5)
emb_even = sinusoidal_time_embedding(t, dim=16)
emb_odd = sinusoidal_time_embedding(t, dim=15)
assert emb_even.shape == (5, 16)
assert emb_odd.shape == (5, 15)
assert torch.all((emb_even >= -1.0) & (emb_even <= 1.0))
with pytest.raises(ValueError, match="at least input and output"):
TypedMLP((6,))
mlp = TypedMLP((6, 16, 4))
assert mlp(torch.zeros((3, 6))).shape == (3, 4)
def test_bounded_otel_exporter_fifo_capacity_and_reset() -> None:
"""Verify BoundedInMemorySpanExporter respects max_spans FIFO capacity and clears cleanly."""
with pytest.raises(ValueError, match="max_spans"):
BoundedInMemorySpanExporter(max_spans=0)
provider, exporter, tracer = create_in_memory_otel_tracer("test_lab17", max_spans=3)
try:
for idx in range(5):
with tracer.start_as_current_span(f"span_{idx}"):
pass
spans = exporter.get_finished_spans()
assert len(spans) == 3
assert [s.name for s in spans] == ["span_2", "span_3", "span_4"]
exporter.clear()
assert len(exporter.get_finished_spans()) == 0
finally:
provider.shutdown()
def test_bimodal_env_builds_observations_and_symmetric_ddim_sampling() -> None:
"""Check BimodalObstacleNavEnv observations and DDIM/CFM chunk shapes."""
env = BimodalObstacleNavEnv()
obs = env.build_observation(torch.zeros((4, 2)), torch.zeros((4, 2)))
assert obs.shape == (4, 6)
assert torch.allclose(obs[:, 4:], torch.tensor([[0.95, 0.0]]).expand(4, 2))
ddim = DDIMDiffusionActionPolicy(obs_dim=6, chunk_dim=16)
cfm = ConditionalFlowMatchingPolicy(obs_dim=6, chunk_dim=16)
gen = torch.Generator().manual_seed(7)
assert ddim.sample_chunk(obs, nfe=4, generator=gen).shape == (4, 16)
assert cfm.sample_chunk(obs, nfe=4, generator=gen).shape == (4, 16)
def test_planar_arm_jacobian_matches_finite_difference() -> None:
"""Verify analytical geometric Jacobian against central finite differences on 2-DoF & 3-DoF."""
specs = [
EmbodimentSpec(name="arm_2dof_source", dof=2, link_lengths=(0.7, 0.58), joint_sign=1.0),
EmbodimentSpec(
name="arm_3dof_target", dof=3, link_lengths=(0.48, 0.44, 0.36), joint_sign=-1.0
),
]
eps = 1e-3
for spec in specs:
arm = PlanarArmKinematics(spec)
q = torch.full((3, spec.dof), 0.35)
j_ana = arm.jacobian(q)
j_num = torch.zeros_like(j_ana)
for col in range(spec.dof):
dq = torch.zeros_like(q)
dq[:, col] = eps
j_num[:, :, col] = (arm.forward_kinematics(q + dq) - arm.forward_kinematics(q - dq)) / (
2.0 * eps
)
assert torch.allclose(j_ana, j_num, atol=5e-4)
def test_modular_vla_zero_velocity_yields_zero_joint_residual() -> None:
"""Verify Jacobian-structured adapter emits exact zero joint delta when v_ee_hat == 0."""
vla = ModularSemanticVLA(sem_dim=8, sem_latent=16, target_dof=3)
q = torch.randn((10, 3))
v_zero = torch.zeros((10, 2))
dq_res = vla.forward_target_adapter(v_zero, q)
assert dq_res.shape == (10, 3)
assert torch.allclose(dq_res, torch.zeros_like(dq_res), atol=1e-7)
def test_sysid_identifies_real_mass_damping_and_lag() -> None:
"""Verify Sim2RealPhysicsEnv System Identification estimates physical mass, damping & lag."""
env = Sim2RealPhysicsEnv()
est_mass, est_damp, est_lag = env.identify_system_parameters(seed=42)
assert abs(est_mass - 2.45) < 0.15
assert abs(est_damp - 0.25) < 0.08
assert est_lag == 2
def test_exp1_mse_mode_averaging_collides_into_obstacle(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""Deterministic MSE baseline must exhibit mode collapse into central obstacle."""
mse = quick_benchmark.exp1_diffusion_vs_flow.mse_baseline
assert mse.policy_name == "deterministic_mse"
assert mse.collision_rate >= 0.85
assert mse.success_rate <= 0.15
assert mse.mode_entropy_bits < 0.1
def test_exp1_cfm_preserves_bimodality_and_pareto_dominates_ddim(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""CFM preserves bimodal entropy and Pareto-dominates DDIM via NFE forward-pass ratio."""
from robotics_action_policy_lab.diffusion_vs_flow import (
ConditionalFlowMatchingPolicy,
DDIMDiffusionActionPolicy,
)
exp1 = quick_benchmark.exp1_diffusion_vs_flow
assert exp1.ot_interpolant_max_endpoint_error < 1e-5
assert exp1.cfm_vs_ddim_speedup_at_equal_or_higher_success >= 3.0
def _pt(name: str, nfe: int) -> PolicyEvalMetrics:
return next(
p for p in exp1.nfe_pareto_sweep if p.policy_name == name and p.nfe == nfe
)
ddim4, cfm4 = _pt("ddim_diffusion", 4), _pt("conditional_flow_matching", 4)
cfm2, cfm8, cfm20, cfm50 = (
_pt("conditional_flow_matching", 2),
_pt("conditional_flow_matching", 8),
_pt("conditional_flow_matching", 20),
_pt("conditional_flow_matching", 50),
)
ddim50 = _pt("ddim_diffusion", 50)
assert cfm4.success_rate > ddim4.success_rate
assert cfm4.success_rate >= ddim50.success_rate
# Deterministic structural forward-pass budget invariant (avoids CPU-load wall-clock flakiness)
assert ddim50.nfe >= 3 * cfm4.nfe
obs_probe = torch.zeros((2, 6), dtype=torch.float32)
cfm_pol = ConditionalFlowMatchingPolicy(obs_dim=6, chunk_dim=16, hidden=32)
ddim_pol = DDIMDiffusionActionPolicy(obs_dim=6, chunk_dim=16, hidden=32)
cfm_calls = 0
ddim_calls = 0
def _count_cfm(_m: torch.nn.Module, _inp: tuple[object, ...], _out: object) -> None:
nonlocal cfm_calls
cfm_calls += 1
def _count_ddim(_m: torch.nn.Module, _inp: tuple[object, ...], _out: object) -> None:
nonlocal ddim_calls
ddim_calls += 1
h1 = cfm_pol.net.register_forward_hook(_count_cfm)
h2 = ddim_pol.net.register_forward_hook(_count_ddim)
_ = cfm_pol.sample_chunk(obs_probe, nfe=4, generator=torch.Generator().manual_seed(0))
_ = ddim_pol.sample_chunk(obs_probe, nfe=50, generator=torch.Generator().manual_seed(0))
h1.remove()
h2.remove()
assert cfm_calls == 4
assert ddim_calls == 50
assert cfm2.success_rate <= cfm4.success_rate <= cfm8.success_rate <= cfm20.success_rate
assert cfm50.success_rate >= cfm4.success_rate
assert cfm4.mode_entropy_bits >= 0.70
def test_exp1_execution_horizon_smoothness_and_effective_hz(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""Multi-step execution horizons (H_e=4/8) cut action jerk and boost effective control Hz."""
horizons = quick_benchmark.exp1_diffusion_vs_flow.exec_horizon_ablation
cfm_h1 = next(
p for p in horizons if p.policy_name == "conditional_flow_matching" and p.exec_horizon == 1
)
cfm_h8 = next(
p for p in horizons if p.policy_name == "conditional_flow_matching" and p.exec_horizon == 8
)
ddim_h1 = next(
p for p in horizons if p.policy_name == "ddim_diffusion" and p.exec_horizon == 1
)
ddim_h8 = next(
p for p in horizons if p.policy_name == "ddim_diffusion" and p.exec_horizon == 8
)
assert cfm_h8.mean_action_jerk < cfm_h1.mean_action_jerk
assert ddim_h8.mean_action_jerk < ddim_h1.mean_action_jerk
assert cfm_h8.control_hz > cfm_h1.control_hz
assert ddim_h8.control_hz > ddim_h1.control_hz
def test_exp2_cross_embodiment_positive_vs_negative_transfer(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""Modular VLA beats scratch with positive transfer while naive zero-padding hurts target."""
exp2 = quick_benchmark.exp2_cross_embodiment_vla
assert exp2.zero_shot_modular_success >= 0.50
assert exp2.few_shot_k8_positive_transfer_gain >= 0.30
assert exp2.few_shot_k24_positive_transfer_gain > 0.0
assert exp2.naive_k24_negative_transfer_delta < 0.0
def test_exp3_isolated_axes_degrade_no_adaptation(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""Each isolated shift degrades nominal no_adaptation policy cleanly."""
exp3 = quick_benchmark.exp3_sim2real_diagnostic
assert exp3.no_adapt_nominal_success >= 0.90
assert exp3.no_adapt_combined_success <= 0.05
def _no_adapt(regime: str) -> Sim2RealRegimePoint:
return next(
p for p in exp3.points if p.strategy == "no_adaptation" and p.regime == regime
)
assert _no_adapt("visual_noise_shift").success_rate <= 0.50
assert _no_adapt("dynamics_friction_mass_shift").success_rate <= 0.25
assert _no_adapt("actuation_latency_2steps").success_rate <= 0.50
def test_exp3_single_axis_vs_full_stack_recovery(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""Single-axis adaptations fail combined real shift; DR+History+SysID recovers >= 85%."""
exp3 = quick_benchmark.exp3_sim2real_diagnostic
assert exp3.sysid_only_combined_success <= 0.15
assert exp3.dr_only_combined_success <= 0.15
assert exp3.full_stack_combined_success >= 0.85
sysid_dyn = next(
p
for p in exp3.points
if p.strategy == "sysid_only" and p.regime == "dynamics_friction_mass_shift"
)
dr_vis = next(
p for p in exp3.points if p.strategy == "dr_only" and p.regime == "visual_noise_shift"
)
assert sysid_dyn.success_rate >= 0.90
assert dr_vis.success_rate >= 0.70
def test_determinism_same_seed_reproducibility() -> None:
"""Repeating seeded runs reproduces neural/physics outcomes deterministically."""
vla_a = run_cross_embodiment_vla_study(seed=42, quick=True)
vla_b = run_cross_embodiment_vla_study(seed=42, quick=True)
assert vla_a.model_dump() == vla_b.model_dump()
s2r_a = run_sim2real_ablation_diagnostic(seed=42, quick=True)
s2r_b = run_sim2real_ablation_diagnostic(seed=42, quick=True)
assert s2r_a.model_dump() == s2r_b.model_dump()
e1_a = run_diffusion_vs_flow_benchmark(seed=42, quick=True)
e1_b = run_diffusion_vs_flow_benchmark(seed=42, quick=True)
assert e1_a.mse_baseline.success_rate == e1_b.mse_baseline.success_rate
assert e1_a.mse_baseline.collision_rate == e1_b.mse_baseline.collision_rate
for p_a, p_b in zip(e1_a.nfe_pareto_sweep, e1_b.nfe_pareto_sweep, strict=True):
assert p_a.success_rate == p_b.success_rate
assert p_a.collision_rate == p_b.collision_rate
assert p_a.mode_entropy_bits == p_b.mode_entropy_bits
assert p_a.mean_action_jerk == p_b.mean_action_jerk
assert p_a.inference_ms_per_chunk > 0.0
assert p_a.control_hz > 0.0
def test_otel_records_exactly_four_distinct_spans(
quick_benchmark: FullRoboticsBenchmarkReport,
) -> None:
"""Verify full pipeline records 4 OTel spans via BoundedInMemorySpanExporter."""
otel = quick_benchmark.otel_telemetry
assert otel.total_spans_recorded == 4
assert set(otel.distinct_span_names) == {
"policy.train_eval",
"nfe.pareto_sweep",
"vla.cross_embodiment",
"sim2real.ablation_diagnostic",
}
def _assert_workbench_panels_contract(payload: dict[str, Any]) -> None:
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
for bar in panels["bars"]:
assert len(bar["items"]) >= 4
for table in panels["tables"]:
assert len(table["columns"]) == 4
assert len(table["rows"]) >= 3
def test_committed_artifact_workbench_panels_contract() -> None:
"""Committed artifacts/ch29_lab17_results.json satisfies full schema and 6/4/4 panels."""
assert ARTIFACT_PATH.is_file(), f"Missing artifact: {ARTIFACT_PATH}"
data: dict[str, Any] = json.loads(ARTIFACT_PATH.read_text(encoding="utf-8"))
FullRoboticsBenchmarkReport.model_validate(
{k: v for k, v in data.items() if k != "workbench_panels"}
)
_assert_workbench_panels_contract(data)
assert data["config"] == {"seed": 42, "quick": False}
def test_cli_quick_subprocess_produces_valid_workbench_artifact(
tmp_path_factory: pytest.TempPathFactory,
) -> None:
"""CLI scripts/run_lab_demo.py --quick writes valid JSON to an isolated temp path."""
out_file = tmp_path_factory.mktemp("lab17_cli") / "quick_demo.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_file),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "Wrote Lab 17 artifact" in proc.stdout
data: dict[str, Any] = json.loads(out_file.read_text(encoding="utf-8"))
assert data["config"] == {"seed": 42, "quick": True}
_assert_workbench_panels_contract(data)
@settings(max_examples=25, database=None)
@given(
t_val=st.floats(min_value=0.0, max_value=1.0, allow_nan=False, allow_infinity=False),
x0_val=st.floats(min_value=-3.0, max_value=3.0, allow_nan=False, allow_infinity=False),
x1_val=st.floats(min_value=-3.0, max_value=3.0, allow_nan=False, allow_infinity=False),
)
def test_hypothesis_ot_interpolant_linear_property(
t_val: float,
x0_val: float,
x1_val: float,
) -> None:
"""Hypothesis property: OT interpolant x_t is exact convex combination and constant speed."""
x0 = torch.full((2, 4), x0_val, dtype=torch.float32)
x1 = torch.full((2, 4), x1_val, dtype=torch.float32)
t = torch.full((2,), t_val, dtype=torch.float32)
x_t, vel = ConditionalFlowMatchingPolicy.ot_interpolant(x0, x1, t)
expected = (1.0 - t_val) * x0_val + t_val * x1_val
assert torch.allclose(x_t, torch.full_like(x_t, expected), atol=1e-5)
assert torch.allclose(vel, torch.full_like(vel, x1_val - x0_val), atol=1e-5)
@settings(max_examples=25, database=None)
@given(
q1=st.floats(min_value=-3.14, max_value=3.14, allow_nan=False, allow_infinity=False),
q2=st.floats(min_value=-3.14, max_value=3.14, allow_nan=False, allow_infinity=False),
q3=st.floats(min_value=-3.14, max_value=3.14, allow_nan=False, allow_infinity=False),
sign=st.sampled_from([-1.0, 1.0]),
)
def test_hypothesis_planar_arm_reach_within_link_sum_property(
q1: float,
q2: float,
q3: float,
sign: float,
) -> None:
"""Hypothesis property: planar arm EE radius never exceeds total link length L1+L2+L3."""
links = (0.48, 0.44, 0.36)
arm = PlanarArmKinematics(
EmbodimentSpec(name="arm_3dof_target", dof=3, link_lengths=links, joint_sign=sign)
)
q = torch.tensor([[q1, q2, q3]], dtype=torch.float32)
ee = arm.forward_kinematics(q)
jac = arm.jacobian(q)
assert ee.shape == (1, 2)
assert jac.shape == (1, 2, 3)
assert torch.isfinite(ee).all()
assert torch.isfinite(jac).all()
assert float(torch.linalg.norm(ee).item()) <= sum(links) + 1e-5
@settings(max_examples=25, database=None)
@given(
exec_h=st.integers(min_value=1, max_value=8),
ms_chunk=st.floats(min_value=0.05, max_value=100.0, allow_nan=False, allow_infinity=False),
)
def test_hypothesis_policy_metrics_control_hz_invariant(exec_h: int, ms_chunk: float) -> None:
"""Hypothesis property: PolicyEvalMetrics validates non-negative bounds and Hz positivity."""
hz = 1000.0 * float(exec_h) / ms_chunk
m = PolicyEvalMetrics(
policy_name="conditional_flow_matching",
nfe=4,
exec_horizon=exec_h,
success_rate=0.8,
collision_rate=0.2,
mode_entropy_bits=0.95,
upper_mode_fraction=0.5,
lower_mode_fraction=0.5,
mean_action_jerk=0.3,
chunk_mse_to_nearest_mode=0.05,
inference_ms_per_chunk=ms_chunk,
control_hz=hz,
)
assert m.control_hz > 0.0
assert m.inference_ms_per_chunk == pytest.approx(ms_chunk)
50/50), vì sao chính sách hồi quy MSE lại đạt tỷ lệ va chạm 100.0% trong Lab 17?Conditional Flow Matching (CFM / Rectified Flow) trong Lab 17 đạt tỷ lệ thành công 97.5% (chỉ 2.5% va chạm) ở NFE=4 (tốc độ 3,894 Hz, nhanh gấp 17.23x so với DDIM-50)?SNR rất nhỏ (\(\bar{\alpha}_{\min} = 10^{-4}\)) ở bước nhiễu lớn, vì sao DDIM thực tế chuyển từ dự đoán nhiễu \(\epsilon\) sang dự đoán vận tốc \(v\) (v-prediction)?Lab 17 với CFM-8 khi tăng chân trời thực thi \(H_e\) từ 1 lên 4 rồi 8, cặp hệ quả nào xảy ra đồng thời trên vòng điều khiển kín?VLA năm 2025–2026 như Pi0 hay NVIDIA GR00T N1, cơ chế nào cho phép tận dụng sức mạnh suy luận của VLM hàng tỷ tham số mà vẫn đạt tần số điều khiển 50–120 Hz?Lab 17 (chuyển giao từ tay máy nguồn 2-DoF sang tay máy đích 3-DoF đảo chiều khớp), vì sao Naive Shared Head (zero-padding) đạt 31.2% ở k=24, thấp hơn tới 21.9pp so với Target Scratch (53.1%)?ModularSemanticVLA của Lab 17, bộ chuyển đổi hình thái được thiết kế để dự đoán ma trận phần dư \(\Delta K_\psi(q)\) rồi nhân với vận tốc đích ước lượng \(\hat{v}_{\text{ee}}\) thay vì dự đoán trực tiếp vector cộng thêm \(\Delta q(q, \hat{v}_{\text{ee}})\)?20 ô trong Experiment 3 của Lab 17, nhận định nào mô tả chính xác nhất vai trò của từng kỹ thuật thích nghi Sim-to-Real?dr_history_sysid) mới đạt 100.0% cả 4 chế độ đơn/danh định lẫn 92.5% (0.0% va chạm) trong combined_real_world.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Phân tích Định lý Mode Collapse và Chính tắc hóa Entropy Hai nhánh 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xuất phát từ hàm mục tiêu \(\mathbb{E}[\|\mu(o) - A\|_2^2]\) trên phân phối điều kiện hai điểm \(p(A\mid o) = 0.5\,\delta(A - A_+) + 0.5\,\delta(A - A_-)\), lấy đạo hàm theo \(\mu\) và đặt bằng 0.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu bảng Experiment 1 (artifacts/ch29_lab17_results.json): Deterministic MSE (NFE=1) đạt entropy 0.00 bits, thành công 0.0% và va chạm 100.0%.
Tiêu chí Đáp án & Số đối chứng
Nghiệm tối ưu \(\mu^* = 0.5 (A_+ + A_-)\) nằm đúng trên trục đối xứng \(y = 0\) đi xuyên qua tâm vật cản (entropy = 0.00 bits, va chạm 100.0%). Muốn bảo toàn hai mốt hợp lệ mà không trung bình hóa, cần mô hình sinh liên tục hoặc bộ chọn mode có cấu trúc tiềm ẩn.
Bài tập 2 — So sánh Quỹ đạo Cong v-DDIM và Straight-Path Rectified Flow ở NFE thấp 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra đại lượng \(1/\sqrt{\bar{\alpha}}\) trong src/robotics_action_policy_lab/diffusion_vs_flow.py khi \(\bar{\alpha}_{\min} = 10^{-4}\) so với biểu thức \(v\)-prediction không chia cho \(\sqrt{\bar{\alpha}}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thử bổ sung một lượt Reflow sinh các cặp \((x_0, x_1)\) từ ODE_solve của mô hình CFM đã train rồi đối chiếu với mốc CFM-4 (97.5% thành công, 2.5% va chạm, 3,894 Hz, nhanh hơn 17.23x DDIM-50).
Tiêu chí Đáp án & Số đối chứng
Dự đoán \(v\)-prediction triệt tiêu hệ số khuếch đại nhiễu 100x của \(\epsilon\)-prediction. Đường nội suy thẳng OT của CFM giúp NFE=4 (Heun) đạt 97.5% thành công (2.5% va chạm) ở 3,894 Hz (1.03 ms/chunk vs DDIM-50 87.5% ở 226 Hz / 17.70 ms, tăng tốc 17.23x), và bước Reflow làm thẳng thêm các giao điểm quỹ đạo cho chế độ 1–2 NFE.
Bài tập 3 — Quy hoạch Chân trời Thực thi He và Ngân sách Tần số Robot Công nghiệp 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết công thức chu kỳ lập kế hoạch \(T_{\text{plan}} = T_{\text{vlm}} + T_{\text{expert}}\) rồi giải điều kiện \(f_{\text{ctrl}} = 1000\,H_e / T_{\text{plan}} \ge 50\text{ Hz}\) với \(T_{\text{vlm}} = 18\text{ ms}\), \(T_{\text{expert}} = 1.03\text{ ms}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu bảng Experiment 1B (He in {1, 4, 8}): CFM-8 tăng thành công 47.5% -> 92.5% -> 97.5%, giảm mean_action_jerk 0.784 -> 0.415 -> 0.358, nâng tần số hữu hiệu 396 -> 2,047 -> 4,909 Hz.
Tiêu chí Đáp án & Số đối chứng
Với \(T_{\text{plan}} = 19.03\text{ ms}\), ngay \(H_e = 1\) đạt \(\approx 52.5\text{ Hz}\), nhưng đặt \(H_e = 4\) cắt tải VLM xuống 1/4, cho tần số nội suy/thực thi dư biên an toàn (>210 Hz) và giảm mạnh hiện tượng giật chuyển nhánh (jerk 0.784 -> 0.415 -> 0.358, thành công 47.5% -> 92.5% -> 97.5%) với rủi ro trễ vòng hở chấp nhận được.
Bài tập 4 — Khắc phục Negative Transfer bằng Kiến trúc Modular VLA Adapter 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra biểu thức \(\dot{q}_e = (\hat{J}_e^+(q) + \Delta K_\psi(q))\,\hat{v}_{\text{ee}}\) trong forward_target_adapter (vla_and_sim2real.py) tại giới hạn \(\hat{v}_{\text{ee}} \to 0\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
So sánh bảng Experiment 2 giữa Naive Shared Head (k=24: 31.2%, -21.9pp negative transfer so với Target Scratch 53.1%) và Modular VLA (k=0: 65.6%, k=8: 84.4%, k=24: 84.4%, EE Err 0.0566).
Tiêu chí Đáp án & Số đối chứng
Tính tuyến tính theo \(\hat{v}_{\text{ee}}\) khóa chặt trạng thái cân bằng \(\dot{q}_e = 0\) tại đích, loại bỏ rung trôi. Trong khi đó Naive Shared Head trộn trực tiếp không gian khớp ngược dấu (+1 vs -1) gây xung đột gradient và chuyển giao âm -21.9pp.
Bài tập 5 — Nhận dạng Độ trễ Pipeline và Tham số Vật lý trong SysID 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Mở hàm identify_system_parameters trong src/robotics_action_policy_lab/vla_and_sim2real.py và thử cố định best_lag = 0 trước khi tạo ma trận hồi quy Ridge \(X = [u_t, -v_t]\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu các giá trị SysID chuẩn khi căn lag đúng: \(\hat{m} = 2.4548\) (thực 2.45), \(\hat{b} = 0.2556\) (thực 0.25) và lag = 2 bước.
Tiêu chí Đáp án & Số đối chứng
Do kích thích ngẫu nhiên i.i.d. có \(\mathbb{E}[u_t u_{t-2}] = 0\), việc hồi quy không căn pha làm hệ số trên \(u_t\) (\(1/\hat{m}\)) suy sụp về gần 0 và thổi phồng khối lượng ước lượng \(\hat{m}\) lệch hoàn toàn khỏi 2.45, chứng minh bắt buộc phải ước lượng tương quan chéo độ trễ trước khi chạy Ridge SysID.
Bài tập 6 — Thiết kế Pipeline Triage Cho Kịch bản Thực tế Tổng hợp 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thiết kế quy trình đúng 2 lần chạy cô lập bằng cây chẩn đoán 4 trục ở Trụ cột 4: (1) một lượt kích thích SysID đo \((m, b, \text{lag})\) và (2) một lượt tái chiếu ảnh quan sát thực vào sim danh định.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Đối chiếu bảng 20 ô Experiment 3 (no_adaptation: 100% -> 15% / 0% / 0% -> 0.0% combined, dr_only: 100.0% visual vs dr_history_sysid: 100.0% cả 4 chế độ đơn/danh định và 92.5% combined, 0.0% va chạm).
Tiêu chí Đáp án & Số đối chứng
Chỉ 2 phép thử cô lập đã tách rạch ròi đóng góp của thị giác (dr_only chữa lên 100.0%), động lực học (sysid_only chữa lên 100.0%) và độ trễ điều khiển (lag=2), dẫn tới cấu hình hợp nhất dr_history_sysid đạt 100.0% trên cả 4 chế độ danh định/lệch đơn trục và phục hồi combined_real_world từ 0.0% lên 92.5% với 0.0% va chạm (dist = 0.1444).