FTG64 commited on
Commit
300ee7e
·
verified ·
1 Parent(s): 293e6e5

code: ChunkExecutor subclasses PreTrainedPolicy; per-mode contact timing

Browse files
code/scripts/chunk_eval.py CHANGED
@@ -32,7 +32,9 @@ from pathlib import Path
32
  import gymnasium as gym
33
  import numpy as np
34
  import torch
35
- from torch import nn
 
 
36
 
37
  # Initial cube positions are sampled uniformly from this x/y region (gym_aloha.utils.sample_box_pose).
38
  CUBE_REGION = ((0.0, 0.2), (0.4, 0.6))
@@ -65,7 +67,7 @@ def build_grid(name: str) -> list[Condition]:
65
  raise ValueError(f"unknown grid {name!r}")
66
 
67
 
68
- class ChunkExecutor(nn.Module):
69
  """Runs an ACT policy's action chunks when the newest usable observation is `delay` steps old.
70
 
71
  At control step t the policy sees o_s with s = max(0, t - delay): there is no older frame during
@@ -80,10 +82,16 @@ class ChunkExecutor(nn.Module):
80
 
81
  With delay = 0 these reproduce LeRobot's ACT with n_action_steps = H, n_action_steps = k, and
82
  temporal_ensemble_coeff = te_coeff with n_action_steps = 1.
 
 
 
83
  """
84
 
85
- def __init__(self, policy: nn.Module, mode: str, delay: int = 0, k: int | None = None, te_coeff: float = 0.01):
86
- super().__init__()
 
 
 
87
  horizon = policy.config.chunk_size
88
  if mode not in ("full", "replan", "te"):
89
  raise ValueError(f"unknown mode {mode!r}")
@@ -92,14 +100,20 @@ class ChunkExecutor(nn.Module):
92
  if mode == "replan" and (k is None or k < 1 or delay + k > horizon):
93
  raise ValueError(f"replan needs 1 <= k <= {horizon - delay}, got k={k}")
94
  self.policy = policy
95
- self.config = policy.config
96
  self.mode, self.delay, self.k, self.te_coeff, self.horizon = mode, delay, k, te_coeff, horizon
97
  self.n_predictions = 0
98
  self.reset()
99
 
100
- def reset(self) -> None:
101
- from lerobot.policies.act.modeling_act import ACTTemporalEnsembler
102
 
 
 
 
 
 
 
 
103
  self.policy.reset()
104
  self.t = 0
105
  self.history: deque[tuple[int, dict]] = deque(maxlen=self.delay + 1)
@@ -111,10 +125,10 @@ class ChunkExecutor(nn.Module):
111
  def _predict(self) -> tuple[torch.Tensor, int]:
112
  s, batch = self.history[0]
113
  self.n_predictions += 1
114
- return self.policy.predict_action_chunk(batch), self.t - s
115
 
116
  @torch.no_grad()
117
- def select_action(self, batch: dict) -> torch.Tensor:
118
  self.history.append((self.t, batch))
119
  if self.mode == "te":
120
  chunk, offset = self._predict()
 
32
  import gymnasium as gym
33
  import numpy as np
34
  import torch
35
+ from lerobot.policies.act.configuration_act import ACTConfig
36
+ from lerobot.policies.act.modeling_act import ACTTemporalEnsembler
37
+ from lerobot.policies.pretrained import PreTrainedPolicy
38
 
39
  # Initial cube positions are sampled uniformly from this x/y region (gym_aloha.utils.sample_box_pose).
40
  CUBE_REGION = ((0.0, 0.2), (0.4, 0.6))
 
67
  raise ValueError(f"unknown grid {name!r}")
68
 
69
 
70
+ class ChunkExecutor(PreTrainedPolicy):
71
  """Runs an ACT policy's action chunks when the newest usable observation is `delay` steps old.
72
 
73
  At control step t the policy sees o_s with s = max(0, t - delay): there is no older frame during
 
82
 
83
  With delay = 0 these reproduce LeRobot's ACT with n_action_steps = H, n_action_steps = k, and
84
  temporal_ensemble_coeff = te_coeff with n_action_steps = 1.
85
+
86
+ It subclasses PreTrainedPolicy because LeRobot's eval_policy only accepts PreTrainedPolicy
87
+ instances; training-side methods are passed through to the wrapped policy.
88
  """
89
 
90
+ config_class = ACTConfig
91
+ name = "act_chunk_executor"
92
+
93
+ def __init__(self, policy: PreTrainedPolicy, mode: str, delay: int = 0, k: int | None = None, te_coeff: float = 0.01):
94
+ super().__init__(policy.config)
95
  horizon = policy.config.chunk_size
96
  if mode not in ("full", "replan", "te"):
97
  raise ValueError(f"unknown mode {mode!r}")
 
100
  if mode == "replan" and (k is None or k < 1 or delay + k > horizon):
101
  raise ValueError(f"replan needs 1 <= k <= {horizon - delay}, got k={k}")
102
  self.policy = policy
 
103
  self.mode, self.delay, self.k, self.te_coeff, self.horizon = mode, delay, k, te_coeff, horizon
104
  self.n_predictions = 0
105
  self.reset()
106
 
107
+ def get_optim_params(self):
108
+ return self.policy.get_optim_params()
109
 
110
+ def forward(self, batch: dict):
111
+ return self.policy.forward(batch)
112
+
113
+ def predict_action_chunk(self, batch: dict, **kwargs) -> torch.Tensor:
114
+ return self.policy.predict_action_chunk(batch)
115
+
116
+ def reset(self) -> None:
117
  self.policy.reset()
118
  self.t = 0
119
  self.history: deque[tuple[int, dict]] = deque(maxlen=self.delay + 1)
 
125
  def _predict(self) -> tuple[torch.Tensor, int]:
126
  s, batch = self.history[0]
127
  self.n_predictions += 1
128
+ return self.predict_action_chunk(batch), self.t - s
129
 
130
  @torch.no_grad()
131
+ def select_action(self, batch: dict, **kwargs) -> torch.Tensor:
132
  self.history.append((self.t, batch))
133
  if self.mode == "te":
134
  chunk, offset = self._predict()
code/scripts/jobs/validate_harness.sh CHANGED
@@ -58,9 +58,12 @@ out = Path(sys.argv[1])
58
  def episodes(folder):
59
  return [e for f in sorted(folder.glob("seeds_*.json")) for e in json.loads(f.read_text())["episodes"]]
60
 
61
- touch = [e["first_step_at_reward"]["1"] for e in episodes(out / "harness" / "full_d00_m0") if "1" in e["first_step_at_reward"]]
62
- print(f"first right-gripper contact, full mode, n={len(touch)}: min {min(touch)}, "
63
- f"p10 {np.percentile(touch, 10):.0f}, median {np.median(touch):.0f}")
 
 
 
64
  for e in episodes(out / "displacement_check" / "full_d00_m4"):
65
  print(f"seed {e['seed']}: move at step {e['t_move']}, moved {e['moved_m']} m, arms unchanged "
66
  f"{e['arms_unchanged_by_move']}, reward before move {e['reward_before_move']}, success {e['success']}")
 
58
  def episodes(folder):
59
  return [e for f in sorted(folder.glob("seeds_*.json")) for e in json.loads(f.read_text())["episodes"]]
60
 
61
+ for cond in ("full_d00_m0", "replan25_d00_m0", "replan10_d00_m0", "te_d00_m0"):
62
+ eps = episodes(out / "harness" / cond)
63
+ touch = sorted(e["first_step_at_reward"]["1"] for e in eps if "1" in e["first_step_at_reward"])
64
+ print(f"first right-gripper contact, {cond}: {len(touch)}/{len(eps)} episodes touch; min {touch[0]}, "
65
+ f"p5 {np.percentile(touch, 5):.0f}, p10 {np.percentile(touch, 10):.0f}, median {np.median(touch):.0f}; "
66
+ f"before step 70: {sum(t < 70 for t in touch)}, before step 100: {sum(t < 100 for t in touch)}")
67
  for e in episodes(out / "displacement_check" / "full_d00_m4"):
68
  print(f"seed {e['seed']}: move at step {e['t_move']}, moved {e['moved_m']} m, arms unchanged "
69
  f"{e['arms_unchanged_by_move']}, reward before move {e['reward_before_move']}, success {e['success']}")
code/scripts/test_chunk_executor.py CHANGED
@@ -10,9 +10,9 @@ Run: python scripts/test_chunk_executor.py
10
 
11
  import sys
12
  from pathlib import Path
13
- from types import SimpleNamespace
14
 
15
  import torch
 
16
  from torch import nn
17
 
18
  sys.path.insert(0, str(Path(__file__).parent))
@@ -24,7 +24,7 @@ H = 100
24
  class FakeACT(nn.Module):
25
  def __init__(self) -> None:
26
  super().__init__()
27
- self.config = SimpleNamespace(chunk_size=H)
28
  self.seen: list[int] = []
29
 
30
  def reset(self) -> None:
 
10
 
11
  import sys
12
  from pathlib import Path
 
13
 
14
  import torch
15
+ from lerobot.policies.act.configuration_act import ACTConfig
16
  from torch import nn
17
 
18
  sys.path.insert(0, str(Path(__file__).parent))
 
24
  class FakeACT(nn.Module):
25
  def __init__(self) -> None:
26
  super().__init__()
27
+ self.config = ACTConfig(chunk_size=H, n_action_steps=H)
28
  self.seen: list[int] = []
29
 
30
  def reset(self) -> None: