prlq commited on
Commit
1354b33
·
verified ·
1 Parent(s): 23f5094

536 perturbed collection patch v2

Browse files
debug/536/perturb_v2/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Perturbed collection patch v2 (536 / nova, 2026-11-15)
2
+ Base: MagicSim mobile-ready 7fc2f64009 (any tree with src/magicsim/Env/Environment/SyncRobotEnv.py of that shape).
3
+ 1. `python apply_patch.py <repo root>`: copies `perturb.py` to `src/magicsim/Collect/perturb.py` and hooks it into `SyncRobotEnv.step` (collect path only:
4
+ the recorded L3 `robot_action` stays the expert's; the robot executes it + a temporary offset) and `reset_idx`.
5
+ 2. Enable per kit: `export MMB_COLLECT_PERTURB=1 MMB_PERTURB_SEED=<episode seed>` before the usual collect command (defaults in perturb.py docstring:
6
+ bursts p=0.01/tick, 25-75 ticks, warmup 100; base vx/vy 0.03 m/s, wz 0.06 rad/s only while the expert drives (|cmd| > 0.02); EEF xyz 0.015 m).
7
+ The run log prints `[perturb] ON ...` and `[perturb] env 0: N bursts in T ticks`.
8
+ 3. HF destination (owner): `<task>/<robot>/dr_on_perturb|dr_off_perturb/seed_<n>/` (dr_on/off = visual DR half, as the existing folders). 536 seeds 9001+, 850 seeds 9501+.
9
+ Smoke v2 on 536: N033 go2 4/4 kept (ALL PASS); N010 sawyer 0/3 (violation:furniture_overlap); N025 stretch3 1 fail of 1 so far.
debug/536/perturb_v2/apply_patch.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """apply_patch.py <repo root>: install magicsim/Collect/perturb.py and hook it into SyncRobotEnv.step / reset_idx (collect path only; the L3 replay / eval paths are untouched)."""
2
+ import shutil, sys
3
+ from pathlib import Path
4
+ root = Path(sys.argv[1]); here = Path(__file__).resolve().parent
5
+ shutil.copy(here / "perturb.py", root / "src/magicsim/Collect/perturb.py")
6
+ p = root / "src/magicsim/Env/Environment/SyncRobotEnv.py"; s = p.read_text()
7
+ a = " self.direct_robot_action = False\n"
8
+ a2 = a + " self._l3_perturb = None # Collect.perturb.L3Perturber (MMB_COLLECT_PERTURB=1), built on the first collect-path step\n self._l3_perturb_checked = False\n"
9
+ b = """ step_info = self.robot_manager.step(
10
+ action=action_info["robot_action"], env_ids=env_ids
11
+ )"""
12
+ b2 = """ exec_action = action_info["robot_action"]
13
+ if not self.direct_robot_action:
14
+ # perturbed collection (MMB_COLLECT_PERTURB=1): the recorded L3 stays the expert's; the robot executes it plus a temporary offset (Collect/perturb.py)
15
+ if not self._l3_perturb_checked:
16
+ self._l3_perturb_checked = True
17
+ from magicsim.Collect.perturb import L3Perturber
18
+ rm = self.robot_manager
19
+ hint = ",".join([str(k) for k in (getattr(rm, "robots", None) or {})] + [type(v).__name__ for v in (getattr(rm, "robots", None) or {}).values()])
20
+ self._l3_perturb = L3Perturber.from_env(self.num_envs, int(getattr(rm, "total_action_dim", exec_action.shape[-1])), hint)
21
+ if self._l3_perturb is not None:
22
+ exec_action = self._l3_perturb.apply(exec_action, env_ids)
23
+ step_info = self.robot_manager.step(
24
+ action=exec_action, env_ids=env_ids
25
+ )"""
26
+ c = " super().reset_idx(env_ids=env_id_list, seed=seed, options=options)\n"
27
+ c2 = c + " if getattr(self, \"_l3_perturb\", None) is not None:\n self._l3_perturb.reset(env_id_list)\n"
28
+ for x in (a, b, c):
29
+ assert s.count(x) == 1, ("pattern count", s.count(x), x[:60])
30
+ s = s.replace(a, a2).replace(b, b2).replace(c, c2); p.write_text(s); print("patched", p)
debug/536/perturb_v2/perturb.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Perturbed collection (DART-style), owner 2026-11-15 22:30 CST: "把加扰动采数据这一点带上".
2
+
3
+ The expert's L3 ``robot_action`` (PlannerManager output) is RECORDED unchanged; the robot EXECUTES it plus a temporary offset. The Collect layer is closed loop (it
4
+ re-reads the robot / object state every tick), so after (and during) an offset it drives the robot back: the dataset then holds "off the nominal path -> the expert's
5
+ correction" states, which plain expert data never visits and which a policy needs to recover from its own drift.
6
+
7
+ Off unless ``MMB_COLLECT_PERTURB=1``. Per env, a burst starts with probability ``P`` per control tick (after ``WARMUP`` ticks from the reset, none while one is active);
8
+ a burst lasts ``LEN_MIN..LEN_MAX`` ticks with a constant offset (linear ramp in / out over ``RAMP`` ticks) on
9
+ * the base velocity command (vx, vy, wz): N(0, BASE_V) m/s, N(0, BASE_W) rad/s (stretch3 has no vy: 0), applied only on ticks where the expert itself drives
10
+ the base (max |vx, vy, wz| of its command > BASE_GATE): a parked base (manipulating at a table / rack) is never pushed (v1 pushed a parked Sawyer into the tool rack:
11
+ 2 of 2 N010 runs ended in violation:furniture_overlap),
12
+ * the EEF target position (x, y, z) : N(0, EEF_M) m per axis.
13
+ The gripper, the base height and the EEF rotation are never touched; NaN entries (= "not commanded this tick") stay NaN.
14
+ Environment (defaults in brackets): MMB_PERTURB_P [0.01], MMB_PERTURB_LEN_MIN [25], MMB_PERTURB_LEN_MAX [75], MMB_PERTURB_RAMP [5], MMB_PERTURB_WARMUP [100],
15
+ MMB_PERTURB_BASE_V [0.03], MMB_PERTURB_BASE_W [0.06], MMB_PERTURB_BASE_GATE [0.02], MMB_PERTURB_EEF_M [0.015], MMB_PERTURB_SEED [none].
16
+ L3 layout (canonical_action.join_raw): Go2 [vx vy wz h | x y z | qw qx qy qz | grip] (12), Sawyer / Stretch [vx vy wz | x y z | qw qx qy qz | grip] (11)."""
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from typing import Optional, Sequence
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+ ENV = "MMB_COLLECT_PERTURB"
27
+
28
+
29
+ def _f(name: str, default: float) -> float:
30
+ v = os.environ.get(f"MMB_PERTURB_{name}", "").strip()
31
+ return float(v) if v else default
32
+
33
+
34
+ class L3Perturber:
35
+ def __init__(self, num_envs: int, action_dim: int, robot_hint: str = ""):
36
+ self.n, self.D = int(num_envs), int(action_dim)
37
+ hint = robot_hint.lower()
38
+ self.go2 = self.D == 12 or "go2" in hint
39
+ self.no_vy = ("hello" in hint or "stretch" in hint) and not self.go2
40
+ self.pos = slice(4, 7) if self.go2 else slice(3, 6)
41
+ self.p, self.lmin, self.lmax = _f("P", 0.01), int(_f("LEN_MIN", 25)), int(_f("LEN_MAX", 75))
42
+ self.ramp, self.warmup = max(1, int(_f("RAMP", 5))), int(_f("WARMUP", 100))
43
+ self.sv, self.sw, self.se = _f("BASE_V", 0.03), _f("BASE_W", 0.06), _f("EEF_M", 0.015)
44
+ self.gate = _f("BASE_GATE", 0.02)
45
+ seed = os.environ.get("MMB_PERTURB_SEED", "").strip()
46
+ self.rng = np.random.default_rng(int(seed) if seed else None)
47
+ self.tick = np.zeros(self.n, np.int64) # ticks since the env's last reset
48
+ self.left = np.zeros(self.n, np.int64) # ticks left in the current burst (0 = none)
49
+ self.length = np.ones(self.n, np.int64)
50
+ self.off = np.zeros((self.n, self.D), np.float32)
51
+ self.bursts = np.zeros(self.n, np.int64) # bursts in the current episode (for the log)
52
+ print(f"[perturb] ON: robot={'go2' if self.go2 else ('stretch3' if self.no_vy else 'sawyer/other')} D={self.D} p={self.p} len={self.lmin}-{self.lmax} "
53
+ f"warmup={self.warmup} base_v={self.sv} base_w={self.sw} gate={self.gate} eef_m={self.se}", flush=True)
54
+
55
+ @classmethod
56
+ def from_env(cls, num_envs: int, action_dim: int, robot_hint: str = "") -> Optional["L3Perturber"]:
57
+ if os.environ.get(ENV, "").strip() != "1":
58
+ return None
59
+ return cls(num_envs, action_dim, robot_hint)
60
+
61
+ def reset(self, env_ids: Sequence[int]) -> None:
62
+ for e in env_ids:
63
+ e = int(e)
64
+ if 0 <= e < self.n:
65
+ if self.bursts[e]:
66
+ print(f"[perturb] env {e}: {int(self.bursts[e])} bursts in {int(self.tick[e])} ticks", flush=True)
67
+ self.tick[e] = 0; self.left[e] = 0; self.bursts[e] = 0; self.off[e] = 0
68
+
69
+ def _new_offset(self) -> np.ndarray:
70
+ o = np.zeros(self.D, np.float32)
71
+ o[0], o[1], o[2] = self.rng.normal(0, self.sv), self.rng.normal(0, self.sv), self.rng.normal(0, self.sw)
72
+ if self.no_vy:
73
+ o[1] = 0.0
74
+ o[self.pos] = self.rng.normal(0, self.se, 3)
75
+ return o
76
+
77
+ def apply(self, action: torch.Tensor, env_ids: Sequence[int]) -> torch.Tensor:
78
+ """The tensor to EXECUTE: a copy of ``action`` with the active offsets added (``action`` itself is not modified: it is what gets recorded)."""
79
+ if not isinstance(action, torch.Tensor) or action.dim() != 2 or action.shape[-1] != self.D:
80
+ return action
81
+ add = np.zeros((action.shape[0], self.D), np.float32)
82
+ for e in env_ids:
83
+ e = int(e)
84
+ if not (0 <= e < self.n) or e >= action.shape[0]:
85
+ continue
86
+ self.tick[e] += 1
87
+ if self.left[e] == 0 and self.tick[e] > self.warmup and self.rng.random() < self.p:
88
+ self.length[e] = self.left[e] = int(self.rng.integers(self.lmin, self.lmax + 1))
89
+ self.off[e] = self._new_offset(); self.bursts[e] += 1
90
+ if self.left[e] > 0:
91
+ k = self.length[e] - self.left[e] # ticks into the burst
92
+ g = min(1.0, (k + 1) / self.ramp, self.left[e] / self.ramp)
93
+ add[e] = self.off[e] * g
94
+ cmd = action[e, 0:3].detach().float().cpu().numpy()
95
+ if not np.isfinite(cmd).all() or np.abs(cmd).max() <= self.gate: # parked base: no base push
96
+ add[e, 0:3] = 0.0
97
+ self.left[e] -= 1
98
+ if not add.any():
99
+ return action
100
+ t = torch.as_tensor(add, dtype=action.dtype, device=action.device)
101
+ out = action.clone()
102
+ fin = torch.isfinite(out)
103
+ out[fin] = out[fin] + t[fin] # NaN = not commanded: stays NaN
104
+ return out