File size: 16,638 Bytes
dddb933
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""LAP annotation on a prepared dataset (default zheyuan ABC-130k; --dataset molmo_yam for MolmoAct
YAM): tool-frame action windows plus per-arm text.

No model is called: the text is computed from the actions. For every episode in the prepared
chunk_index.jsonl (the episodes IDM annotated), up to CHUNKS_PER_EPISODE non-overlapping one-second
chunks [t, t+1] with integer t are sampled (seeded by split and UUID; short episodes give every chunk
that fits; independent of the IDM chunks). Each chunk gets:

  actions.npy row   (61, 16) float16 cartesian_tool window: the 60 training samples at 60 Hz plus the
                    exact t+1 sample, used only for labels. Same Loong path (CartesianEpisode) as the
                    reasoning and pretraining assets, so rows [:60] equal their action windows.
  a2l               one horizon h in {1/8, ..., 8/8} s (seeded per chunk) and the pose at t+h,
                    described separately for the left and the right arm.
  l2a               one K in {2, 4, 8} (seeded per chunk) and the pose at t+i/K for i = 0..K,
                    described separately for each arm.

The two arms are stored separately and in no order: the SFT loader chooses which arm comes first.
Poses are relative to the measured start pose with the tool axes fixed at t (translation linear,
rotation SLERP and gripper held between samples), and are rounded to 1 cm, 5 degrees and 10% of
aperture. The gripper is an absolute fraction-open target. Splits are not decided here; see
convert_annotation_lap_to_sft_json.py.

Output (<output-root>):
  actions.npy     (N, 61, 16) float16, one row per chunk
  episodes.jsonl  one line per episode (schema lap-episode-v1); chunks point at their action_row
  meta.json       settings, the action store's shape and sha256, counts
Every file is written to a temporary name and renamed at the end.

The joint streams come from the mirrored parquet (the prepared lowdim.npz only has the IDM rows);
prepared_datasets.py knows each dataset's mirror and parquet layout. A non-default --dataset reads
its own chunk_index.jsonl unless --chunk-index is given, and needs an explicit --output-root.
Needs numpy, scipy, torch, mujoco, pyarrow and huggingface_hub (Loong's environment), e.g.
  uv run --no-project --python 3.12 --with numpy --with scipy --with mujoco --with pyarrow \\
      --with huggingface_hub --with torch --index https://download.pytorch.org/whl/cpu \\
      --index-strategy unsafe-best-match python annotate_lap.py
"""

import argparse
from collections import Counter, defaultdict
from concurrent.futures import ProcessPoolExecutor
import hashlib
import json
import math
import multiprocessing
import os
from pathlib import Path
import random
import sys
import time

import numpy as np

WORKSPACE = Path(__file__).resolve().parents[2]
for path in (WORKSPACE, WORKSPACE / "external/Loong/src"):
    if str(path) not in sys.path:
        sys.path.insert(0, str(path))

from action_language_alignment.vllm_action_annotation import prepared_datasets  # noqa: E402

DATASET = prepared_datasets.DEFAULT
DATASET_ROOT = Path("/data/group_data/rl/lehongw2/abc130k_zheyuan")  # mirrored parquet: full joint streams
PREPARED_DIR = Path("/data/group_data/rl/lehongw2/abc130k_zheyuan_prepared_1028")
CHUNK_INDEX = PREPARED_DIR / "chunk_index.jsonl"  # the episodes IDM annotated
OUTPUT_ROOT = WORKSPACE / "data/abc130k_zheyuan/annotate_lap-tool-32chunks-261106"
SCHEMA = "lap-episode-v1"
FPS = 30
CHUNKS_PER_EPISODE = 32  # IDM has 16 per episode, so LAP has twice as many chunks
CHUNK_SEED = 43
HORIZON_SEED = 0
L2A_SEED = 0
HORIZONS = tuple(i / 8 for i in range(1, 9))
L2A_FPS = (2, 4, 8)
STORE_SAMPLES = 61  # 60 training samples plus the exact t+1 sample for labels
TRAINING_SAMPLES = 60
LABEL_PRECISION = {"translation_resolution_cm": 1.0, "rotation_resolution_deg": 5.0, "gripper_resolution": 0.1}
ARMS = (("left", 0), ("right", 8))
WORKERS = 16


def sample_starts(length, count, rng):
    """Sorted integer starts t, sampled without overlap, whose 61-sample window needs no padding.

    Resampling 61 samples at 60 Hz reads native rows 30t..30t+31 (Loong's native_window_rows), so
    frame 30t+31 must exist.
    """
    capacity = max(0, (length - 2) // FPS)
    return sorted(rng.sample(range(capacity), min(count, capacity)))


def chunk_key(seed, uuid, start, mode):
    return hashlib.sha256(json.dumps([seed, uuid, start, mode]).encode()).digest()


def choose_horizon(uuid, start, seed=HORIZON_SEED):
    return HORIZONS[int.from_bytes(chunk_key(seed, uuid, start, "LAP-A2L")[:8], "big") % len(HORIZONS)]


def choose_l2a_fps(uuid, start, seed=L2A_SEED):
    return L2A_FPS[int.from_bytes(chunk_key(seed, uuid, start, "LAP-L2A")[:8], "big") % len(L2A_FPS)]


def describe_timestamp(values, seconds):
    """{arm: (text, static)} at offset `seconds`: linear translation, SO(3) SLERP, held gripper."""
    from scipy.spatial.transform import Rotation, Slerp
    from action_language_alignment import abc130k_actions as actions

    position = seconds * 60
    lo, hi = math.floor(position), math.ceil(position)
    delta = values[lo].astype(np.float64).copy()
    if lo != hi:
        alpha = position - lo
        for _, offset in ARMS:
            delta[offset:offset + 3] = ((1 - alpha) * values[lo, offset:offset + 3].astype(np.float64)
                                        + alpha * values[hi, offset:offset + 3].astype(np.float64))
            rotations = Rotation.from_rotvec(values[[lo, hi], offset + 3:offset + 6].astype(np.float64))
            delta[offset + 3:offset + 6] = Slerp([0, 1], rotations)(alpha).as_rotvec()
    pose = {"position_m": [0, 0, 0], "rotation_matrix": np.eye(3), "gripper_fraction_open": 0}
    labels = {}
    for side, offset in ARMS:
        target = pose | {"gripper_fraction_open": float(delta[offset + 6])}
        arm = actions.describe_arm(pose, target, "tool", LABEL_PRECISION, prepared_delta=delta[offset:offset + 7],
                                   start_command_gripper=float(values[0, offset + 6]))
        labels[side] = (arm["text"], arm["is_static"])
    return labels


def chunk_record(uuid, start, row, values):
    horizon, fps = choose_horizon(uuid, start), choose_l2a_fps(uuid, start)
    times = [i / fps for i in range(fps + 1)]
    labels = {h: describe_timestamp(values, h) for h in {*times, horizon}}
    return {
        "start_seconds": start,
        "duration_seconds": 1,
        "action_row": row,
        "a2l": {"horizon_seconds": horizon,
                **{side: labels[horizon][side][0] for side, _ in ARMS},
                "static": all(labels[horizon][side][1] for side, _ in ARMS)},
        "l2a": {"description_fps": fps,
                **{side: [labels[h][side][0] for h in times] for side, _ in ARMS},
                "static": all(labels[h][side][1] for h in times for side, _ in ARMS)},
    }


def validate_window(values):
    if (values.shape != (STORE_SAMPLES, 16) or not np.isfinite(values).all() or np.any(values[:, [7, 15]] != 0)
            or np.any((values[:, [6, 14]] < 0) | (values[:, [6, 14]] > 1))):
        raise ValueError("Expected finite (61, 16) tool actions with zero padding and grippers in [0, 1]")


def episode_header(row, dataset=DATASET):
    return {"annotation_schema": SCHEMA, "dataset": dataset, "fps": FPS, "split": row["split"],
            "episode_index": row["episode_index"], "episode_uuid": row["uuid"], "task": row["task"],
            "task_index": row["task_index"], "length": row["length"], "annotation_frame": "tool"}


def init_worker():
    import torch
    torch.set_num_threads(1)


def run_file(job):
    """One parquet file: (windows (n, 61, 16) float16 in plan order, episode records)."""
    import pyarrow.parquet as pq
    from action_language_alignment.abc130k_actions import CartesianEpisode

    dataset, dataset_root, split, chunk, file, plans = job
    path = prepared_datasets.get(dataset).parquet_path(split, chunk, file, dataset_root)
    table = pq.read_table(path, columns=["episode_index", "frame_index", "timestamp", "joint_state", "joint_action"])
    episode_column = table["episode_index"].to_numpy()
    windows, records = [], []
    for row, starts, first_row in plans:
        header = episode_header(row, dataset)
        try:
            part = table.take(np.flatnonzero(episode_column == row["episode_index"]))
            frames = part["frame_index"].to_numpy()
            if not np.array_equal(frames, np.arange(row["length"])):
                raise ValueError("frame_index is not 0..length-1")
            if np.abs(part["timestamp"].to_numpy() - frames / FPS).max() > 1e-3:
                raise ValueError(f"timestamps are off the {FPS} FPS grid")
            states = np.asarray(part["joint_state"].to_pylist(), np.float64)
            commands = np.asarray(part["joint_action"].to_pylist(), np.float64)
            episode = CartesianEpisode(commands, states, FPS, STORE_SAMPLES, ["cartesian_tool"])
            values = [episode.window(start * FPS, "cartesian_tool").astype(np.float16) for start in starts]
            for window in values:
                validate_window(window)
            chunks = [chunk_record(row["uuid"], start, first_row + i, window)
                      for i, (start, window) in enumerate(zip(starts, values))]
        except Exception as exc:  # keep the run going; the converter skips episodes with an error
            values = [np.zeros((STORE_SAMPLES, 16), np.float16)] * len(starts)
            header["error"] = f"{type(exc).__name__}: {exc}"
            chunks = []
        windows.extend(values)
        records.append({**header, "chunks": chunks})
    return np.stack(windows) if windows else np.zeros((0, STORE_SAMPLES, 16), np.float16), records


def file_sha256(path):
    digest = hashlib.sha256()
    with open(path, "rb") as stream:
        for block in iter(lambda: stream.read(8 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def plan(chunk_index, splits, chunks_per_episode, seed, limit_files=None):
    """Parquet-file jobs in sorted order, each with (row, starts, first action row) per episode."""
    groups = defaultdict(list)
    with open(chunk_index, encoding="utf-8") as stream:
        for line in stream:
            row = json.loads(line)
            if row["split"] in splits:
                groups[row["split"], row["data"]["chunk_index"], row["data"]["file_index"]].append(row)
    jobs, rows, seen = [], 0, set()
    for key in sorted(groups)[:limit_files]:
        plans = []
        for row in sorted(groups[key], key=lambda r: r["episode_index"]):
            if row["uuid"] in seen:
                raise ValueError(f"Duplicate episode uuid {row['uuid']}")
            seen.add(row["uuid"])
            row = {k: row[k] for k in ("split", "episode_index", "uuid", "task", "task_index", "length")}
            starts = sample_starts(row["length"], chunks_per_episode,
                                   random.Random(f"{seed}:{row['split']}:{row['uuid']}"))
            plans.append((row, starts, rows))
            rows += len(starts)
        jobs.append(key + (plans,))
    return jobs, rows


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    prepared_datasets.add_argument(parser)
    parser.add_argument("--dataset-root", type=Path, default=DATASET_ROOT,
                        help="Source parquet mirror (default: the dataset's lowdim_root)")
    parser.add_argument("--chunk-index", type=Path, default=CHUNK_INDEX)
    parser.add_argument("--output-root", type=Path, default=OUTPUT_ROOT)
    parser.add_argument("--splits", nargs="+", default=["train", "val"])
    parser.add_argument("--chunks-per-episode", type=int, default=CHUNKS_PER_EPISODE)
    parser.add_argument("--chunk-seed", type=int, default=CHUNK_SEED)
    parser.add_argument("--workers", type=int, default=WORKERS)
    parser.add_argument("--limit-files", type=int, default=None, help="Only the first N parquet files (for testing)")
    args = parser.parse_args(argv)
    argv = sys.argv[1:] if argv is None else argv
    spec = prepared_datasets.resolve(parser, args, argv, "--chunk-index", "--output-root")
    if "--dataset-root" not in argv:
        args.dataset_root = spec.lowdim_root
    for name in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
        os.environ[name] = "1"
    jobs, total = plan(args.chunk_index, args.splits, args.chunks_per_episode, args.chunk_seed, args.limit_files)
    episodes_total = sum(len(job[-1]) for job in jobs)
    root = args.output_root.resolve()
    root.mkdir(parents=True, exist_ok=True)
    actions_tmp, records_tmp = root / "actions.tmp.npy", root / "episodes.jsonl.tmp"
    print(f"[lap] {episodes_total:,} episodes, {total:,} chunks from {len(jobs)} parquet files; "
          f"{args.workers} workers -> {root}", flush=True)
    store = np.lib.format.open_memmap(actions_tmp, mode="w+", dtype=np.float16, shape=(total, STORE_SAMPLES, 16))
    counts = {"episodes": Counter(), "chunks": Counter(), "errors": Counter()}
    started = last = time.monotonic()
    done_episodes = row = 0
    try:
        with open(records_tmp, "w", encoding="utf-8") as stream, ProcessPoolExecutor(
                args.workers, mp_context=multiprocessing.get_context("spawn"), initializer=init_worker) as pool:
            for windows, records in pool.map(run_file, [(spec.name, args.dataset_root, *job) for job in jobs]):
                store[row:row + len(windows)] = windows
                row += len(windows)
                for record in records:
                    stream.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n")
                    counts["episodes"][record["split"]] += 1
                    counts["chunks"][record["split"]] += len(record["chunks"])
                    if "error" in record:
                        counts["errors"][record["split"]] += 1
                        print(f"[lap] error {record['split']} {record['episode_index']}: {record['error']}", flush=True)
                done_episodes += len(records)
                now = time.monotonic()
                if now - last >= 30 or done_episodes == episodes_total:
                    last = now
                    rate = done_episodes / max(now - started, 1e-3)
                    eta = (episodes_total - done_episodes) / rate if rate else float("nan")
                    print(f"[lap] {done_episodes:,}/{episodes_total:,} episodes, {row:,}/{total:,} chunks, "
                          f"{rate:.1f} episodes/s, elapsed {now - started:.0f}s, ETA {eta:.0f}s", flush=True)
        if row != total:
            raise RuntimeError(f"Wrote {row} action rows, planned {total}")
        store.flush()
        del store
        digest = file_sha256(actions_tmp)
        actions_tmp.replace(root / "actions.npy")
        records_tmp.replace(root / "episodes.jsonl")
        metadata = {
            "annotation_schema": SCHEMA, "dataset": spec.name, "frame": "tool", "fps": FPS,
            "chunk_index": str(args.chunk_index.resolve()), "chunk_index_sha256": file_sha256(args.chunk_index),
            "dataset_root": str(args.dataset_root.resolve()), "splits": args.splits,
            "chunks_per_episode": args.chunks_per_episode, "chunk_seed": args.chunk_seed,
            "chunk_rule": "non-overlapping one-second chunks with integer start t and frame 30t+31 in the episode; "
                          "random.Random(f'{chunk_seed}:{split}:{uuid}').sample, sorted",
            "horizons_seconds": list(HORIZONS), "horizon_seed": HORIZON_SEED,
            "l2a_fps": list(L2A_FPS), "l2a_seed": L2A_SEED, "label_precision": LABEL_PRECISION,
            "label_reference": "measured-start", "label_timestamps": "exact-offset-seconds",
            "gripper": "absolute fraction-open target", "training_samples": TRAINING_SAMPLES,
            "action_store": {"file": "actions.npy", "shape": [total, STORE_SAMPLES, 16], "valid_rows": total,
                             "dtype": "float16", "fps": 60, "normalized": False, "sha256": digest},
            "counts": {name: dict(value) for name, value in counts.items()},
            "elapsed_seconds": round(time.monotonic() - started, 1),
        }
        (root / "meta.json").write_text(json.dumps(metadata, indent=2) + "\n")
        print(f"[lap] COMPLETE: {json.dumps(metadata['counts'])} -> {root}", flush=True)
    finally:
        actions_tmp.unlink(missing_ok=True)
        records_tmp.unlink(missing_ok=True)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())