File size: 14,212 Bytes
3ffa267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# =====================================================================================
# Minimal dependencies to run this file
# -------------------------------------------------------------------------------------
#   Python           3.10
#   lerobot        == 0.3.3      # MUST be 0.3.3 (CODEBASE_VERSION v2.1);
#   mmengine       == 0.10.7     # DATASETS / TRANSFORMS registry + Compose
#   torch          == 2.7.0      # tensors
#   numpy          == 1.26.4     # index selection / arrays
#   torchcodec     == 0.5        # default video backend for MP4 decoding
#   torchvision    == 0.22.0     # pulled in by lerobot / torchcodec
#
# Quick install (CPU/CUDA torch as appropriate for your machine):
#   pip install "lerobot==0.3.3" "mmengine==0.10.7" \
#               "torch==2.7.0" "numpy==1.26.4" "torchcodec==0.5" "torchvision==0.22.0"
# =====================================================================================

import bisect
import json
import os
import random
import traceback
from pathlib import Path

import numpy as np
import torch
from lerobot.datasets.lerobot_dataset import LeRobotDataset
from mmengine import DATASETS, TRANSFORMS
from mmengine.dataset import Compose


@TRANSFORMS.register_module()
class SelectActionDims:
    """Select a subset of action dimensions from the raw action.

    The action is 89-dim; the model here only consumes 25 of them:
    joints 0:22 plus 83:86. `dims` may be given as an explicit list of
    indices, or as a list of [start, end) slice pairs (default below).
    Works on the ``action`` key whether it is a torch.Tensor or np.ndarray,
    and whether shaped (D,) or (T, D) — the last axis is indexed.
    """

    def __init__(self, key="action", dims=None, slices=((0, 22), (83, 86))):
        self.key = key
        if dims is not None:
            self.indices = list(dims)
        else:
            self.indices = [i for s, e in slices for i in range(s, e)]

    def __call__(self, item):
        value = item[self.key]
        if isinstance(value, torch.Tensor):
            index = torch.as_tensor(self.indices, dtype=torch.long, device=value.device)
            item[self.key] = value.index_select(-1, index)
        else:
            item[self.key] = np.asarray(value)[..., self.indices]
        return item


@DATASETS.register_module()
class CustomLerobotDataset(LeRobotDataset):
    def __init__(
        self,
        repo_id: str,
        root=None,
        action_source="action",
        action_len=50,
        action_dim=25,
        action_type="absolute",
        action_mode="joint",
        info_json=None,
        pipeline=None,
        skip_instructions=("Keep still.",),
        max_retries=10,
        delta_timestamps=None,
        *args,
        **kwargs,
    ):
        super().__init__(
            repo_id=repo_id,
            root=root,
            image_transforms=None,
            delta_timestamps=delta_timestamps,
        )
        self.action_source = action_source
        self.action_len = action_len
        self.action_dim = action_dim
        self.action_type = action_type
        self.action_mode = action_mode
        assert self.action_mode == "joint", "ee action not implementation."
        self.pipeline = Compose(pipeline) if pipeline is not None else Compose([])
        self.skip_instructions = set(skip_instructions or ())
        self.max_retries = max_retries

        json_path = Path(info_json)
        if not json_path.exists():
            raise FileNotFoundError(f"Dataset info file not found: {info_json}")
        with json_path.open() as f:
            info_data = json.load(f)

        episodes = info_data.get("instruction_segments")
        if not isinstance(episodes, dict):
            raise ValueError(f"instruction_segments missing or invalid in {info_json}")

        self._subepisode_info: dict[int, dict[str, list]] = {}
        for episode_idx_str, episode_data in episodes.items():
            episode_idx = int(episode_idx_str)
            if not isinstance(episode_data, list):
                raise TypeError("episode_data must be list type.")
            starts = []
            ends = []
            instrs = []
            infos = []
            for seg in episode_data:
                if not isinstance(seg, dict):
                    raise TypeError("segment in episode_data must be list type.")

                start = seg.get("start_frame_index")
                end = seg.get("end_frame_index")
                instr = seg.get("instruction")
                info = seg.get("episode_status", "success")
                if isinstance(start, int) and isinstance(end, int) and isinstance(instr, str):
                    starts.append(start)
                    ends.append(end)
                    instrs.append(instr)
                    infos.append(info)
                else:
                    raise ValueError("start/end_frame_index must be int, instruction must be string.")

            sorted_indices = sorted(range(len(starts)), key=lambda i: starts[i])
            starts = [starts[i] for i in sorted_indices]
            ends = [ends[i] for i in sorted_indices]
            instrs = [instrs[i] for i in sorted_indices]
            infos = [infos[i] for i in sorted_indices]

            # Build logical segments:
            #   1. drop segments whose instruction is in skip_instructions (e.g. "Keep still.")
            #   2. merge consecutive *kept* segments that share the same instruction.
            # Because skip segments are removed first, "Do A / Keep still / Do A" collapses to
            # a single logical segment whose usable-frame list is [A1 frames] + [A2 frames] with
            # the still frames dropped in between — so an action chunk drawn from it is naturally
            # continuous and skips the still region. "Do A / Keep still / Do B" stays as two
            # separate segments (different instruction), so a chunk never crosses into Do B.
            # end_frame_index is treated as exclusive: a segment covers range(start, end).
            seg_starts = []
            seg_ends = []
            seg_instrs = []
            seg_infos = []
            seg_frames = []
            for i in range(len(starts)):
                if instrs[i] in self.skip_instructions:
                    continue
                cur_frames = list(range(starts[i], ends[i]))
                if not cur_frames:
                    continue
                if seg_instrs and instrs[i] == seg_instrs[-1]:
                    seg_frames[-1].extend(cur_frames)
                    seg_ends[-1] = ends[i]
                else:
                    seg_starts.append(starts[i])
                    seg_ends.append(ends[i])
                    seg_instrs.append(instrs[i])
                    seg_infos.append(infos[i])
                    seg_frames.append(cur_frames)

            if not seg_instrs:
                continue

            self._subepisode_info[episode_idx] = {
                "starts": seg_starts,
                "ends": seg_ends,
                "instrs": seg_instrs,
                "infos": seg_infos,
                "frames": [np.asarray(f, dtype=np.int64) for f in seg_frames],
            }

        if not self._subepisode_info:
            raise ValueError(f"No valid episode instructions found in {info_json}")

        self.usable_indices = self._build_usable_indices()

    def _build_usable_indices(self) -> list:
        """Global frame indices that participate in training."""
        usable = []
        for episode_idx, seg in self._subepisode_info.items():
            ep_from = self.episode_data_index["from"][episode_idx].item()
            ep_len = self.episode_data_index["to"][episode_idx].item() - ep_from
            for frames in seg["frames"]:
                frames = frames[frames < ep_len]
                usable.extend((frames + ep_from).tolist())
        usable.sort()
        return usable

    def _get_prompt(self, episode_idx, frame_index):
        episode_data = self._subepisode_info.get(episode_idx)
        if episode_data is None:
            raise ValueError(f"No instruction found for episode {episode_idx}")

        starts = episode_data["starts"]
        pos = bisect.bisect_right(starts, frame_index) - 1
        if pos < 0:
            raise ValueError(f"Frame {frame_index} precedes the first valid segment of episode {episode_idx}.")
        prompt = episode_data["instrs"][pos]
        traj_info = episode_data["infos"][pos]
        seg_frames = episode_data["frames"][pos]
        if prompt is None:
            raise ValueError(f"No exact instruction found for episode {episode_idx}, frame {frame_index}")
        return prompt, traj_info, seg_frames

    def __getitem__(self, idx, pipeline=None) -> dict:
        last_exc = None
        for attempt in range(self.max_retries):
            try:
                return self._build_item(idx, pipeline=pipeline)
            except Exception as e:
                last_exc = e
                if attempt == 0:
                    print(
                        f"[CustomLerobotDataset] failed on index {idx} "
                        f"(episode data error), resampling. First error: {repr(e)}"
                    )
                    traceback.print_exc()
                idx = random.choice(self.usable_indices)

        raise RuntimeError(
            f"Failed to load a usable sample after {self.max_retries} resampling attempts. "
            f"Last error: {repr(last_exc)}"
        ) from last_exc

    def _build_item(self, idx, pipeline=None) -> dict:
        pipeline = pipeline if pipeline is not None else self.pipeline
        item = self.hf_dataset[idx]
        episode_idx = item["episode_index"].item()
        frame_idx = item["frame_index"].item()
        item["text"], item["traj_info"], seg_frames = self._get_prompt(episode_idx, frame_idx)
        curr_item = self._get_frame(item, episode_idx, pipeline=pipeline)
        return curr_item

    def _get_frame(self, item, episode_idx, pipeline=None) -> dict:
        pipeline = pipeline if pipeline is not None else self.pipeline
        query_indices, padding = self._get_query_indices(item["index"].item(), episode_idx)
        query_timestamps = self._get_query_timestamps(item["timestamp"].item(), query_indices)
        query_result = self._query_hf_dataset(query_indices)
        item = {**item, **padding, **query_result}

        if len(self.meta.video_keys) > 0:
            video_frames = self._query_videos(query_timestamps, episode_idx)
            item = {**video_frames, **item}

        return pipeline(item)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description="Smoke test: read samples from a LeRobot V2.1 dataset via CustomLerobotDataset."
    )
    parser.add_argument(
        "--root",
        default="/mnt/pfs/dataset/lerobot_data/challenge_data/upload/validation_data/fold_cloth_calib_valid_noise",
        help="LeRobot dataset root (contains data/ meta/ videos/).",
    )
    parser.add_argument(
        "--repo-id",
        default="example_data",
        help="repo_id identifier (arbitrary when loading from a local root).",
    )
    parser.add_argument(
        "--info-json",
        default=None,
        help="Path to info.json holding instruction_segments. Defaults to <root>/meta/info.json.",
    )
    parser.add_argument("--num-samples", type=int, default=3, help="How many usable frames to read.")
    args = parser.parse_args()

    info_json = args.info_json or os.path.join(args.root, "meta", "info.json")

    # _get_frame() always calls _get_query_indices(), which needs self.delta_indices
    # (built from delta_timestamps). Build a minimal "current frame only" ([0.0])
    # delta_timestamps for every temporal feature (observation.* / action) so the
    # query path runs; a real training config would pass action-chunk offsets here.
    with open(info_json) as f:
        _features = json.load(f).get("features", {})
    delta_timestamps = {key: [0.0] for key in _features if key == "action" or key.startswith("observation.")}

    skip_instructions=("Start remote operation.", "Invalid", "End remote operation.")

    print("=" * 70)
    print("Building CustomLerobotDataset")
    print(f"  root              = {args.root}")
    print(f"  repo_id           = {args.repo_id}")
    print(f"  info_json         = {info_json}")
    print(f"  delta_timestamps  = {{{', '.join(delta_timestamps)}}} -> [0.0]")
    print(f"  pipeline          = [SelectActionDims]  (89 -> 25: dims 0:22 + 83:86)")
    print(f"  skip_instructions = {skip_instructions}")
    print("=" * 70)

    dataset = CustomLerobotDataset(
        repo_id=args.repo_id,
        root=args.root,
        info_json=info_json,
        pipeline=[dict(type="SelectActionDims")],
        skip_instructions=skip_instructions,
        delta_timestamps=delta_timestamps,
    )

    print(f"\nlen(dataset) (raw frames)      : {len(dataset)}")
    print(f"len(dataset.usable_indices)    : {len(dataset.usable_indices)}")
    print(f"num sub-episodes               : {len(dataset._subepisode_info)}")
    if dataset.usable_indices:
        print(f"usable index range             : " f"[{dataset.usable_indices[0]}, {dataset.usable_indices[-1]}]")

    def describe(value):
        if isinstance(value, torch.Tensor):
            return f"Tensor shape={tuple(value.shape)} dtype={value.dtype}"
        if isinstance(value, np.ndarray):
            return f"ndarray shape={value.shape} dtype={value.dtype}"
        if isinstance(value, (str, int, float, bool)):
            return f"{type(value).__name__}={value!r}"
        return f"{type(value).__name__}"

    n = min(args.num_samples, len(dataset.usable_indices))
    print(f"\nReading {n} usable sample(s):")
    for i in range(n):
        idx = dataset.usable_indices[i * (len(dataset.usable_indices) // max(n, 1))]
        print("\n" + "-" * 70)
        print(f"sample {i}: global frame index = {idx}")
        item = dataset[idx]
        for key in sorted(item.keys()):
            print(f"  {key:45s}: {describe(item[key])}")

    print("\n" + "=" * 70)
    print("OK: dataset built and samples read successfully.")
    print("=" * 70)