prlq commited on
Commit
d63ba71
·
verified ·
1 Parent(s): 308b8d4

536 perturbed collection patch v4

Browse files
debug/536/perturb_v4/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Perturbed collection patch v4 (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.008 m, bursts 15-40 ticks, no EEF push while the gripper is commanded closed; v4: EEF push scaled by the expert EEF speed (down to 15% in slow final alignment)).
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_v4/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_v4/perturb.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, only while the expert commands the gripper OPEN (v3, 2026-11-16: an offset while the
13
+ gripper is closed = carrying / inserting jammed the N025 insertions and broke grasp servos: N025 sawyer 0/3 kept vs 97 % unperturbed).
14
+ The gripper, the base height and the EEF rotation are never touched; NaN entries (= "not commanded this tick") stay NaN.
15
+ v4 (owner 2026-11-16 00:56 CST "越到接近插桩的时候,扰动就越小"): the EEF offset is scaled by the expert's own EEF target speed, clip(|dp| / SPEED_REF, SCALE_MIN, 1)
16
+ per tick (|dp| = change of the expert EEF target position since the last tick, smoothed over ~10 ticks): fast reaching moves get the full offset, the slow final
17
+ alignment / insertion approach gets down to SCALE_MIN of it. MMB_PERTURB_SPEED_REF [0.004 m/tick = 0.2 m/s], MMB_PERTURB_SCALE_MIN [0.15].
18
+ Environment (defaults in brackets): MMB_PERTURB_P [0.01], MMB_PERTURB_LEN_MIN [15], MMB_PERTURB_LEN_MAX [40], MMB_PERTURB_RAMP [5], MMB_PERTURB_WARMUP [100],
19
+ MMB_PERTURB_BASE_V [0.03], MMB_PERTURB_BASE_W [0.06], MMB_PERTURB_BASE_GATE [0.02], MMB_PERTURB_EEF_M [0.008], MMB_PERTURB_SEED [none].
20
+ 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)."""
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ from typing import Optional, Sequence
26
+
27
+ import numpy as np
28
+ import torch
29
+
30
+ ENV = "MMB_COLLECT_PERTURB"
31
+
32
+
33
+ def _f(name: str, default: float) -> float:
34
+ v = os.environ.get(f"MMB_PERTURB_{name}", "").strip()
35
+ return float(v) if v else default
36
+
37
+
38
+ class L3Perturber:
39
+ def __init__(self, num_envs: int, action_dim: int, robot_hint: str = ""):
40
+ self.n, self.D = int(num_envs), int(action_dim)
41
+ hint = robot_hint.lower()
42
+ self.go2 = self.D == 12 or "go2" in hint
43
+ self.no_vy = ("hello" in hint or "stretch" in hint) and not self.go2
44
+ self.pos = slice(4, 7) if self.go2 else slice(3, 6)
45
+ self.p, self.lmin, self.lmax = _f("P", 0.01), int(_f("LEN_MIN", 15)), int(_f("LEN_MAX", 40))
46
+ self.ramp, self.warmup = max(1, int(_f("RAMP", 5))), int(_f("WARMUP", 100))
47
+ self.sv, self.sw, self.se = _f("BASE_V", 0.03), _f("BASE_W", 0.06), _f("EEF_M", 0.008)
48
+ self.gate = _f("BASE_GATE", 0.02)
49
+ self.vref, self.smin = _f("SPEED_REF", 0.004), _f("SCALE_MIN", 0.15)
50
+ self.prev_p = np.full((self.n, 3), np.nan, np.float32); self.vel = np.zeros(self.n, np.float32)
51
+ seed = os.environ.get("MMB_PERTURB_SEED", "").strip()
52
+ self.rng = np.random.default_rng(int(seed) if seed else None)
53
+ self.tick = np.zeros(self.n, np.int64) # ticks since the env's last reset
54
+ self.left = np.zeros(self.n, np.int64) # ticks left in the current burst (0 = none)
55
+ self.length = np.ones(self.n, np.int64)
56
+ self.off = np.zeros((self.n, self.D), np.float32)
57
+ self.bursts = np.zeros(self.n, np.int64) # bursts in the current episode (for the log)
58
+ 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} "
59
+ f"warmup={self.warmup} base_v={self.sv} base_w={self.sw} gate={self.gate} eef_m={self.se} speed_ref={self.vref} scale_min={self.smin}", flush=True)
60
+
61
+ @classmethod
62
+ def from_env(cls, num_envs: int, action_dim: int, robot_hint: str = "") -> Optional["L3Perturber"]:
63
+ if os.environ.get(ENV, "").strip() != "1":
64
+ return None
65
+ return cls(num_envs, action_dim, robot_hint)
66
+
67
+ def reset(self, env_ids: Sequence[int]) -> None:
68
+ for e in env_ids:
69
+ e = int(e)
70
+ if 0 <= e < self.n:
71
+ if self.bursts[e]:
72
+ print(f"[perturb] env {e}: {int(self.bursts[e])} bursts in {int(self.tick[e])} ticks", flush=True)
73
+ self.tick[e] = 0; self.left[e] = 0; self.bursts[e] = 0; self.off[e] = 0; self.prev_p[e] = np.nan; self.vel[e] = 0
74
+
75
+ def _new_offset(self) -> np.ndarray:
76
+ o = np.zeros(self.D, np.float32)
77
+ o[0], o[1], o[2] = self.rng.normal(0, self.sv), self.rng.normal(0, self.sv), self.rng.normal(0, self.sw)
78
+ if self.no_vy:
79
+ o[1] = 0.0
80
+ o[self.pos] = self.rng.normal(0, self.se, 3)
81
+ return o
82
+
83
+ def apply(self, action: torch.Tensor, env_ids: Sequence[int]) -> torch.Tensor:
84
+ """The tensor to EXECUTE: a copy of ``action`` with the active offsets added (``action`` itself is not modified: it is what gets recorded)."""
85
+ if not isinstance(action, torch.Tensor) or action.dim() != 2 or action.shape[-1] != self.D:
86
+ return action
87
+ add = np.zeros((action.shape[0], self.D), np.float32)
88
+ for e in env_ids:
89
+ e = int(e)
90
+ if not (0 <= e < self.n) or e >= action.shape[0]:
91
+ continue
92
+ self.tick[e] += 1
93
+ p_now = action[e, self.pos].detach().float().cpu().numpy() # expert EEF target position (recorded L3)
94
+ if np.isfinite(p_now).all():
95
+ if np.isfinite(self.prev_p[e]).all():
96
+ self.vel[e] = 0.9 * self.vel[e] + 0.1 * float(np.linalg.norm(p_now - self.prev_p[e]))
97
+ self.prev_p[e] = p_now
98
+ if self.left[e] == 0 and self.tick[e] > self.warmup and self.rng.random() < self.p:
99
+ self.length[e] = self.left[e] = int(self.rng.integers(self.lmin, self.lmax + 1))
100
+ self.off[e] = self._new_offset(); self.bursts[e] += 1
101
+ if self.left[e] > 0:
102
+ k = self.length[e] - self.left[e] # ticks into the burst
103
+ g = min(1.0, (k + 1) / self.ramp, self.left[e] / self.ramp)
104
+ add[e] = self.off[e] * g
105
+ cmd = action[e, 0:3].detach().float().cpu().numpy()
106
+ if not np.isfinite(cmd).all() or np.abs(cmd).max() <= self.gate: # parked base: no base push
107
+ add[e, 0:3] = 0.0
108
+ add[e, self.pos] *= min(1.0, max(self.smin, self.vel[e] / self.vref)) # v4: slow expert = fine alignment / insertion -> small push
109
+ grip = float(action[e, -1]) # the gripper command is the last L3 column (closure, > 0.5 = close)
110
+ if np.isfinite(grip) and grip > 0.5: # gripper closed (holding / inserting): no EEF push
111
+ add[e, self.pos] = 0.0
112
+ self.left[e] -= 1
113
+ if not add.any():
114
+ return action
115
+ t = torch.as_tensor(add, dtype=action.dtype, device=action.device)
116
+ out = action.clone()
117
+ fin = torch.isfinite(out)
118
+ out[fin] = out[fin] + t[fin] # NaN = not commanded: stays NaN
119
+ return out