prlq commited on
Commit
47e8d4e
·
verified ·
1 Parent(s): d63ba71

536 perturbed collection patch v5

Browse files
debug/536/perturb_v5/README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Perturbed collection patch v5 (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); v5: base push relative to the expert base command (r ~ N(0, 0.3))).
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_v5/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_v5/perturb.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ v5 (owner 00:57 CST "扰动肯定是以百分比形式,不能以绝对的形式"): the base offset is RELATIVE to the expert's own base command: vx, vy += r * |v| and
19
+ wz += r * (|wz| + 0.5 |v|) with r ~ N(0, BASE_REL) per burst (|v| = |(vx, vy)| of the command this tick): no push when parked, ~BASE_REL of the speed when driving.
20
+ The EEF offset is relative through the speed scaling above. MMB_PERTURB_BASE_REL [0.3].
21
+ 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],
22
+ 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].
23
+ 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)."""
24
+
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ from typing import Optional, Sequence
29
+
30
+ import numpy as np
31
+ import torch
32
+
33
+ ENV = "MMB_COLLECT_PERTURB"
34
+
35
+
36
+ def _f(name: str, default: float) -> float:
37
+ v = os.environ.get(f"MMB_PERTURB_{name}", "").strip()
38
+ return float(v) if v else default
39
+
40
+
41
+ class L3Perturber:
42
+ def __init__(self, num_envs: int, action_dim: int, robot_hint: str = ""):
43
+ self.n, self.D = int(num_envs), int(action_dim)
44
+ hint = robot_hint.lower()
45
+ self.go2 = self.D == 12 or "go2" in hint
46
+ self.no_vy = ("hello" in hint or "stretch" in hint) and not self.go2
47
+ self.pos = slice(4, 7) if self.go2 else slice(3, 6)
48
+ self.p, self.lmin, self.lmax = _f("P", 0.01), int(_f("LEN_MIN", 15)), int(_f("LEN_MAX", 40))
49
+ self.ramp, self.warmup = max(1, int(_f("RAMP", 5))), int(_f("WARMUP", 100))
50
+ self.sv, self.sw, self.se = _f("BASE_V", 0.03), _f("BASE_W", 0.06), _f("EEF_M", 0.008)
51
+ self.gate = _f("BASE_GATE", 0.02)
52
+ self.vref, self.smin = _f("SPEED_REF", 0.004), _f("SCALE_MIN", 0.15)
53
+ self.brel = _f("BASE_REL", 0.3)
54
+ self.prev_p = np.full((self.n, 3), np.nan, np.float32); self.vel = np.zeros(self.n, np.float32)
55
+ seed = os.environ.get("MMB_PERTURB_SEED", "").strip()
56
+ self.rng = np.random.default_rng(int(seed) if seed else None)
57
+ self.tick = np.zeros(self.n, np.int64) # ticks since the env's last reset
58
+ self.left = np.zeros(self.n, np.int64) # ticks left in the current burst (0 = none)
59
+ self.length = np.ones(self.n, np.int64)
60
+ self.off = np.zeros((self.n, self.D), np.float32)
61
+ self.bursts = np.zeros(self.n, np.int64) # bursts in the current episode (for the log)
62
+ 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} "
63
+ f"warmup={self.warmup} base_rel={self.brel} gate={self.gate} eef_m={self.se} speed_ref={self.vref} scale_min={self.smin}", flush=True)
64
+
65
+ @classmethod
66
+ def from_env(cls, num_envs: int, action_dim: int, robot_hint: str = "") -> Optional["L3Perturber"]:
67
+ if os.environ.get(ENV, "").strip() != "1":
68
+ return None
69
+ return cls(num_envs, action_dim, robot_hint)
70
+
71
+ def reset(self, env_ids: Sequence[int]) -> None:
72
+ for e in env_ids:
73
+ e = int(e)
74
+ if 0 <= e < self.n:
75
+ if self.bursts[e]:
76
+ print(f"[perturb] env {e}: {int(self.bursts[e])} bursts in {int(self.tick[e])} ticks", flush=True)
77
+ 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
78
+
79
+ def _new_offset(self) -> np.ndarray:
80
+ o = np.zeros(self.D, np.float32)
81
+ o[0], o[1], o[2] = self.rng.normal(0, self.brel, 3) # v5: relative factors, scaled by the command in apply()
82
+ if self.no_vy:
83
+ o[1] = 0.0
84
+ o[self.pos] = self.rng.normal(0, self.se, 3)
85
+ return o
86
+
87
+ def apply(self, action: torch.Tensor, env_ids: Sequence[int]) -> torch.Tensor:
88
+ """The tensor to EXECUTE: a copy of ``action`` with the active offsets added (``action`` itself is not modified: it is what gets recorded)."""
89
+ if not isinstance(action, torch.Tensor) or action.dim() != 2 or action.shape[-1] != self.D:
90
+ return action
91
+ add = np.zeros((action.shape[0], self.D), np.float32)
92
+ for e in env_ids:
93
+ e = int(e)
94
+ if not (0 <= e < self.n) or e >= action.shape[0]:
95
+ continue
96
+ self.tick[e] += 1
97
+ p_now = action[e, self.pos].detach().float().cpu().numpy() # expert EEF target position (recorded L3)
98
+ if np.isfinite(p_now).all():
99
+ if np.isfinite(self.prev_p[e]).all():
100
+ self.vel[e] = 0.9 * self.vel[e] + 0.1 * float(np.linalg.norm(p_now - self.prev_p[e]))
101
+ self.prev_p[e] = p_now
102
+ if self.left[e] == 0 and self.tick[e] > self.warmup and self.rng.random() < self.p:
103
+ self.length[e] = self.left[e] = int(self.rng.integers(self.lmin, self.lmax + 1))
104
+ self.off[e] = self._new_offset(); self.bursts[e] += 1
105
+ if self.left[e] > 0:
106
+ k = self.length[e] - self.left[e] # ticks into the burst
107
+ g = min(1.0, (k + 1) / self.ramp, self.left[e] / self.ramp)
108
+ add[e] = self.off[e] * g
109
+ cmd = action[e, 0:3].detach().float().cpu().numpy()
110
+ if not np.isfinite(cmd).all() or np.abs(cmd).max() <= self.gate: # parked base: no base push
111
+ add[e, 0:3] = 0.0
112
+ else: # v5: relative to the expert's base command
113
+ v = float(np.hypot(cmd[0], cmd[1]))
114
+ add[e, 0:2] = self.off[e, 0:2] * g * v
115
+ add[e, 2] = self.off[e, 2] * g * (abs(float(cmd[2])) + 0.5 * v)
116
+ if self.no_vy:
117
+ add[e, 1] = 0.0
118
+ add[e, self.pos] *= min(1.0, max(self.smin, self.vel[e] / self.vref)) # v4: slow expert = fine alignment / insertion -> small push
119
+ grip = float(action[e, -1]) # the gripper command is the last L3 column (closure, > 0.5 = close)
120
+ if np.isfinite(grip) and grip > 0.5: # gripper closed (holding / inserting): no EEF push
121
+ add[e, self.pos] = 0.0
122
+ self.left[e] -= 1
123
+ if not add.any():
124
+ return action
125
+ t = torch.as_tensor(add, dtype=action.dtype, device=action.device)
126
+ out = action.clone()
127
+ fin = torch.isfinite(out)
128
+ out[fin] = out[fin] + t[fin] # NaN = not commanded: stays NaN
129
+ return out