challenge-2026 commited on
Commit
3ffa267
·
1 Parent(s): 4f19068

update dataloader

Browse files
Files changed (2) hide show
  1. .gitignore +3 -0
  2. dataloader/custom_lerobot_dataset.py +334 -0
.gitignore CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  upload/*
2
  example_data/*
3
  official_data/*
 
1
+ __pycache__/
2
+ cache/
3
+ *.pyc
4
  upload/*
5
  example_data/*
6
  official_data/*
dataloader/custom_lerobot_dataset.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =====================================================================================
2
+ # Minimal dependencies to run this file
3
+ # -------------------------------------------------------------------------------------
4
+ # Python 3.10
5
+ # lerobot == 0.3.3 # MUST be 0.3.3 (CODEBASE_VERSION v2.1);
6
+ # mmengine == 0.10.7 # DATASETS / TRANSFORMS registry + Compose
7
+ # torch == 2.7.0 # tensors
8
+ # numpy == 1.26.4 # index selection / arrays
9
+ # torchcodec == 0.5 # default video backend for MP4 decoding
10
+ # torchvision == 0.22.0 # pulled in by lerobot / torchcodec
11
+ #
12
+ # Quick install (CPU/CUDA torch as appropriate for your machine):
13
+ # pip install "lerobot==0.3.3" "mmengine==0.10.7" \
14
+ # "torch==2.7.0" "numpy==1.26.4" "torchcodec==0.5" "torchvision==0.22.0"
15
+ # =====================================================================================
16
+
17
+ import bisect
18
+ import json
19
+ import os
20
+ import random
21
+ import traceback
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+ import torch
26
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
27
+ from mmengine import DATASETS, TRANSFORMS
28
+ from mmengine.dataset import Compose
29
+
30
+
31
+ @TRANSFORMS.register_module()
32
+ class SelectActionDims:
33
+ """Select a subset of action dimensions from the raw action.
34
+
35
+ The action is 89-dim; the model here only consumes 25 of them:
36
+ joints 0:22 plus 83:86. `dims` may be given as an explicit list of
37
+ indices, or as a list of [start, end) slice pairs (default below).
38
+ Works on the ``action`` key whether it is a torch.Tensor or np.ndarray,
39
+ and whether shaped (D,) or (T, D) — the last axis is indexed.
40
+ """
41
+
42
+ def __init__(self, key="action", dims=None, slices=((0, 22), (83, 86))):
43
+ self.key = key
44
+ if dims is not None:
45
+ self.indices = list(dims)
46
+ else:
47
+ self.indices = [i for s, e in slices for i in range(s, e)]
48
+
49
+ def __call__(self, item):
50
+ value = item[self.key]
51
+ if isinstance(value, torch.Tensor):
52
+ index = torch.as_tensor(self.indices, dtype=torch.long, device=value.device)
53
+ item[self.key] = value.index_select(-1, index)
54
+ else:
55
+ item[self.key] = np.asarray(value)[..., self.indices]
56
+ return item
57
+
58
+
59
+ @DATASETS.register_module()
60
+ class CustomLerobotDataset(LeRobotDataset):
61
+ def __init__(
62
+ self,
63
+ repo_id: str,
64
+ root=None,
65
+ action_source="action",
66
+ action_len=50,
67
+ action_dim=25,
68
+ action_type="absolute",
69
+ action_mode="joint",
70
+ info_json=None,
71
+ pipeline=None,
72
+ skip_instructions=("Keep still.",),
73
+ max_retries=10,
74
+ delta_timestamps=None,
75
+ *args,
76
+ **kwargs,
77
+ ):
78
+ super().__init__(
79
+ repo_id=repo_id,
80
+ root=root,
81
+ image_transforms=None,
82
+ delta_timestamps=delta_timestamps,
83
+ )
84
+ self.action_source = action_source
85
+ self.action_len = action_len
86
+ self.action_dim = action_dim
87
+ self.action_type = action_type
88
+ self.action_mode = action_mode
89
+ assert self.action_mode == "joint", "ee action not implementation."
90
+ self.pipeline = Compose(pipeline) if pipeline is not None else Compose([])
91
+ self.skip_instructions = set(skip_instructions or ())
92
+ self.max_retries = max_retries
93
+
94
+ json_path = Path(info_json)
95
+ if not json_path.exists():
96
+ raise FileNotFoundError(f"Dataset info file not found: {info_json}")
97
+ with json_path.open() as f:
98
+ info_data = json.load(f)
99
+
100
+ episodes = info_data.get("instruction_segments")
101
+ if not isinstance(episodes, dict):
102
+ raise ValueError(f"instruction_segments missing or invalid in {info_json}")
103
+
104
+ self._subepisode_info: dict[int, dict[str, list]] = {}
105
+ for episode_idx_str, episode_data in episodes.items():
106
+ episode_idx = int(episode_idx_str)
107
+ if not isinstance(episode_data, list):
108
+ raise TypeError("episode_data must be list type.")
109
+ starts = []
110
+ ends = []
111
+ instrs = []
112
+ infos = []
113
+ for seg in episode_data:
114
+ if not isinstance(seg, dict):
115
+ raise TypeError("segment in episode_data must be list type.")
116
+
117
+ start = seg.get("start_frame_index")
118
+ end = seg.get("end_frame_index")
119
+ instr = seg.get("instruction")
120
+ info = seg.get("episode_status", "success")
121
+ if isinstance(start, int) and isinstance(end, int) and isinstance(instr, str):
122
+ starts.append(start)
123
+ ends.append(end)
124
+ instrs.append(instr)
125
+ infos.append(info)
126
+ else:
127
+ raise ValueError("start/end_frame_index must be int, instruction must be string.")
128
+
129
+ sorted_indices = sorted(range(len(starts)), key=lambda i: starts[i])
130
+ starts = [starts[i] for i in sorted_indices]
131
+ ends = [ends[i] for i in sorted_indices]
132
+ instrs = [instrs[i] for i in sorted_indices]
133
+ infos = [infos[i] for i in sorted_indices]
134
+
135
+ # Build logical segments:
136
+ # 1. drop segments whose instruction is in skip_instructions (e.g. "Keep still.")
137
+ # 2. merge consecutive *kept* segments that share the same instruction.
138
+ # Because skip segments are removed first, "Do A / Keep still / Do A" collapses to
139
+ # a single logical segment whose usable-frame list is [A1 frames] + [A2 frames] with
140
+ # the still frames dropped in between — so an action chunk drawn from it is naturally
141
+ # continuous and skips the still region. "Do A / Keep still / Do B" stays as two
142
+ # separate segments (different instruction), so a chunk never crosses into Do B.
143
+ # end_frame_index is treated as exclusive: a segment covers range(start, end).
144
+ seg_starts = []
145
+ seg_ends = []
146
+ seg_instrs = []
147
+ seg_infos = []
148
+ seg_frames = []
149
+ for i in range(len(starts)):
150
+ if instrs[i] in self.skip_instructions:
151
+ continue
152
+ cur_frames = list(range(starts[i], ends[i]))
153
+ if not cur_frames:
154
+ continue
155
+ if seg_instrs and instrs[i] == seg_instrs[-1]:
156
+ seg_frames[-1].extend(cur_frames)
157
+ seg_ends[-1] = ends[i]
158
+ else:
159
+ seg_starts.append(starts[i])
160
+ seg_ends.append(ends[i])
161
+ seg_instrs.append(instrs[i])
162
+ seg_infos.append(infos[i])
163
+ seg_frames.append(cur_frames)
164
+
165
+ if not seg_instrs:
166
+ continue
167
+
168
+ self._subepisode_info[episode_idx] = {
169
+ "starts": seg_starts,
170
+ "ends": seg_ends,
171
+ "instrs": seg_instrs,
172
+ "infos": seg_infos,
173
+ "frames": [np.asarray(f, dtype=np.int64) for f in seg_frames],
174
+ }
175
+
176
+ if not self._subepisode_info:
177
+ raise ValueError(f"No valid episode instructions found in {info_json}")
178
+
179
+ self.usable_indices = self._build_usable_indices()
180
+
181
+ def _build_usable_indices(self) -> list:
182
+ """Global frame indices that participate in training."""
183
+ usable = []
184
+ for episode_idx, seg in self._subepisode_info.items():
185
+ ep_from = self.episode_data_index["from"][episode_idx].item()
186
+ ep_len = self.episode_data_index["to"][episode_idx].item() - ep_from
187
+ for frames in seg["frames"]:
188
+ frames = frames[frames < ep_len]
189
+ usable.extend((frames + ep_from).tolist())
190
+ usable.sort()
191
+ return usable
192
+
193
+ def _get_prompt(self, episode_idx, frame_index):
194
+ episode_data = self._subepisode_info.get(episode_idx)
195
+ if episode_data is None:
196
+ raise ValueError(f"No instruction found for episode {episode_idx}")
197
+
198
+ starts = episode_data["starts"]
199
+ pos = bisect.bisect_right(starts, frame_index) - 1
200
+ if pos < 0:
201
+ raise ValueError(f"Frame {frame_index} precedes the first valid segment of episode {episode_idx}.")
202
+ prompt = episode_data["instrs"][pos]
203
+ traj_info = episode_data["infos"][pos]
204
+ seg_frames = episode_data["frames"][pos]
205
+ if prompt is None:
206
+ raise ValueError(f"No exact instruction found for episode {episode_idx}, frame {frame_index}")
207
+ return prompt, traj_info, seg_frames
208
+
209
+ def __getitem__(self, idx, pipeline=None) -> dict:
210
+ last_exc = None
211
+ for attempt in range(self.max_retries):
212
+ try:
213
+ return self._build_item(idx, pipeline=pipeline)
214
+ except Exception as e:
215
+ last_exc = e
216
+ if attempt == 0:
217
+ print(
218
+ f"[CustomLerobotDataset] failed on index {idx} "
219
+ f"(episode data error), resampling. First error: {repr(e)}"
220
+ )
221
+ traceback.print_exc()
222
+ idx = random.choice(self.usable_indices)
223
+
224
+ raise RuntimeError(
225
+ f"Failed to load a usable sample after {self.max_retries} resampling attempts. "
226
+ f"Last error: {repr(last_exc)}"
227
+ ) from last_exc
228
+
229
+ def _build_item(self, idx, pipeline=None) -> dict:
230
+ pipeline = pipeline if pipeline is not None else self.pipeline
231
+ item = self.hf_dataset[idx]
232
+ episode_idx = item["episode_index"].item()
233
+ frame_idx = item["frame_index"].item()
234
+ item["text"], item["traj_info"], seg_frames = self._get_prompt(episode_idx, frame_idx)
235
+ curr_item = self._get_frame(item, episode_idx, pipeline=pipeline)
236
+ return curr_item
237
+
238
+ def _get_frame(self, item, episode_idx, pipeline=None) -> dict:
239
+ pipeline = pipeline if pipeline is not None else self.pipeline
240
+ query_indices, padding = self._get_query_indices(item["index"].item(), episode_idx)
241
+ query_timestamps = self._get_query_timestamps(item["timestamp"].item(), query_indices)
242
+ query_result = self._query_hf_dataset(query_indices)
243
+ item = {**item, **padding, **query_result}
244
+
245
+ if len(self.meta.video_keys) > 0:
246
+ video_frames = self._query_videos(query_timestamps, episode_idx)
247
+ item = {**video_frames, **item}
248
+
249
+ return pipeline(item)
250
+
251
+
252
+ if __name__ == "__main__":
253
+ import argparse
254
+
255
+ parser = argparse.ArgumentParser(
256
+ description="Smoke test: read samples from a LeRobot V2.1 dataset via CustomLerobotDataset."
257
+ )
258
+ parser.add_argument(
259
+ "--root",
260
+ default="/mnt/pfs/dataset/lerobot_data/challenge_data/upload/validation_data/fold_cloth_calib_valid_noise",
261
+ help="LeRobot dataset root (contains data/ meta/ videos/).",
262
+ )
263
+ parser.add_argument(
264
+ "--repo-id",
265
+ default="example_data",
266
+ help="repo_id identifier (arbitrary when loading from a local root).",
267
+ )
268
+ parser.add_argument(
269
+ "--info-json",
270
+ default=None,
271
+ help="Path to info.json holding instruction_segments. Defaults to <root>/meta/info.json.",
272
+ )
273
+ parser.add_argument("--num-samples", type=int, default=3, help="How many usable frames to read.")
274
+ args = parser.parse_args()
275
+
276
+ info_json = args.info_json or os.path.join(args.root, "meta", "info.json")
277
+
278
+ # _get_frame() always calls _get_query_indices(), which needs self.delta_indices
279
+ # (built from delta_timestamps). Build a minimal "current frame only" ([0.0])
280
+ # delta_timestamps for every temporal feature (observation.* / action) so the
281
+ # query path runs; a real training config would pass action-chunk offsets here.
282
+ with open(info_json) as f:
283
+ _features = json.load(f).get("features", {})
284
+ delta_timestamps = {key: [0.0] for key in _features if key == "action" or key.startswith("observation.")}
285
+
286
+ skip_instructions=("Start remote operation.", "Invalid", "End remote operation.")
287
+
288
+ print("=" * 70)
289
+ print("Building CustomLerobotDataset")
290
+ print(f" root = {args.root}")
291
+ print(f" repo_id = {args.repo_id}")
292
+ print(f" info_json = {info_json}")
293
+ print(f" delta_timestamps = {{{', '.join(delta_timestamps)}}} -> [0.0]")
294
+ print(f" pipeline = [SelectActionDims] (89 -> 25: dims 0:22 + 83:86)")
295
+ print(f" skip_instructions = {skip_instructions}")
296
+ print("=" * 70)
297
+
298
+ dataset = CustomLerobotDataset(
299
+ repo_id=args.repo_id,
300
+ root=args.root,
301
+ info_json=info_json,
302
+ pipeline=[dict(type="SelectActionDims")],
303
+ skip_instructions=skip_instructions,
304
+ delta_timestamps=delta_timestamps,
305
+ )
306
+
307
+ print(f"\nlen(dataset) (raw frames) : {len(dataset)}")
308
+ print(f"len(dataset.usable_indices) : {len(dataset.usable_indices)}")
309
+ print(f"num sub-episodes : {len(dataset._subepisode_info)}")
310
+ if dataset.usable_indices:
311
+ print(f"usable index range : " f"[{dataset.usable_indices[0]}, {dataset.usable_indices[-1]}]")
312
+
313
+ def describe(value):
314
+ if isinstance(value, torch.Tensor):
315
+ return f"Tensor shape={tuple(value.shape)} dtype={value.dtype}"
316
+ if isinstance(value, np.ndarray):
317
+ return f"ndarray shape={value.shape} dtype={value.dtype}"
318
+ if isinstance(value, (str, int, float, bool)):
319
+ return f"{type(value).__name__}={value!r}"
320
+ return f"{type(value).__name__}"
321
+
322
+ n = min(args.num_samples, len(dataset.usable_indices))
323
+ print(f"\nReading {n} usable sample(s):")
324
+ for i in range(n):
325
+ idx = dataset.usable_indices[i * (len(dataset.usable_indices) // max(n, 1))]
326
+ print("\n" + "-" * 70)
327
+ print(f"sample {i}: global frame index = {idx}")
328
+ item = dataset[idx]
329
+ for key in sorted(item.keys()):
330
+ print(f" {key:45s}: {describe(item[key])}")
331
+
332
+ print("\n" + "=" * 70)
333
+ print("OK: dataset built and samples read successfully.")
334
+ print("=" * 70)