Add 7-D Cartesian state and action columns (observation.state.cartesian, action.cartesian)

#11
by hzhang86 - opened

Add 7-D Cartesian state and action columns

Two new per-frame features, each a float32 vector of 7 with names [x, y, z, roll, pitch, yaw, gripper]:

  • observation.state.cartesian = observation.state.cartesian_position (6) followed by observation.state.gripper_position (1)
  • action.cartesian = action.cartesian_position (6) followed by action.gripper_position (1)

They carry no new information: they are the existing Cartesian columns pre-assembled into the 7-D vector that Cartesian end-effector policies consume as observation.state / action (Praxis-1, FLUX 3 Action's DROID checkpoint, ...), so those policies map the columns with a rename instead of each carrying its own concatenation step. The DROID conventions are kept: metres and radians in the robot base frame, extrinsic x-y-z Euler angles, gripper in [0, 1].

What changed

  • data/**/*.parquet: the two columns appended to every row of all 156 files. All existing columns are unchanged.
  • Note for the maintainers: only 86 of the 156 files (file-000 to file-085, 27,630,375 frames) are referenced by meta/episodes. The other 70 (file-086 to file-155, 12.4 M rows) carry an older episode numbering and are not read by LeRobotDataset, but the README's data_files: data/*/*.parquet exposes them to the dataset viewer and to datasets.load_dataset. This PR adds the columns to them too so every file keeps the same schema, and computes no statistics from them. They look like leftovers of an earlier packing; deleting them is a separate decision for you.
  • meta/info.json: the two feature entries.
  • meta/episodes/**/*.parquet: per-episode statistics for the two features (stats/<feature>/{min,max,mean,std,count,q01,q10,q50,q90,q99}), computed with lerobot.datasets.compute_stats.compute_episode_stats from the referenced files only; every episode's row count was checked against its length.
  • meta/stats.json: the dataset-level statistics of the two features, aggregated from the per-episode ones with aggregate_stats, as for the existing features.
  • Videos are untouched. The 8-D joint-space observation.state and action stay as they are, so current users are unaffected.

Validation

  • Every new column is bitwise equal to the concatenation of its two source columns; row counts and all other columns unchanged (checked on all 156 files).
  • The new features' dataset-level min/max/mean/std equal the source features' stats; count = 27,630,375.
  • LeRobotDatasetMetadata loads the new metadata; the new features appear in features and stats.

After merging

LeRobotDataset loads the v3.0 tag, not main, so please move the v3.0 tag to the merge commit for the columns to be visible to LeRobotDataset("lerobot/droid_1.0.1").

Script: add_cartesian_columns.py (attached in the discussion), run against revision main (0eabc778).

Ready for review.

hzhang86 changed pull request status to open

The script that produced this PR (run against main at 0eabc778 with LeRobot's compute_episode_stats / aggregate_stats), and the check that was run on the result.

add_cartesian_columns.py
"""Add 7-D Cartesian state and action columns to a local copy of lerobot/droid_1.0.1 (LeRobot v3).

observation.state.cartesian = observation.state.cartesian_position (6) + observation.state.gripper_position (1)
action.cartesian            = action.cartesian_position (6)            + action.gripper_position (1)

Writes data/**, meta/info.json, meta/stats.json and meta/episodes/** to OUT; everything else is untouched.
Statistics are computed with LeRobot's own functions (per episode, then aggregated), like the existing ones.
"""
import json
import shutil
import sys
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq

from lerobot.datasets.compute_stats import aggregate_stats, compute_episode_stats

SRC = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/root/droid_cartesian/src")
OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("/root/droid_cartesian/out")
NEW = {
    "observation.state.cartesian": ("observation.state.cartesian_position", "observation.state.gripper_position"),
    "action.cartesian": ("action.cartesian_position", "action.gripper_position"),
}
NAMES = ["x", "y", "z", "roll", "pitch", "yaw", "gripper"]
FEATURE = {"dtype": "float32", "shape": [7], "names": {"axes": NAMES}}
STAT_KEYS = ["min", "max", "mean", "std", "count", "q01", "q10", "q50", "q90", "q99"]


def concat_columns(table: pa.Table, pos_key: str, grip_key: str) -> tuple[pa.Array, np.ndarray]:
    pos = np.stack(table[pos_key].to_numpy(zero_copy_only=False)).astype(np.float32)  # (N, 6)
    grip = table[grip_key].to_numpy(zero_copy_only=False).astype(np.float32)[:, None]  # (N, 1)
    values = np.concatenate([pos, grip], axis=1)  # (N, 7)
    offsets = pa.array(np.arange(0, 7 * (len(values) + 1), 7, dtype=np.int32))
    column = pa.ListArray.from_arrays(offsets, pa.array(values.reshape(-1), type=pa.float32()))
    return column, values


def referenced_files() -> dict[tuple[int, int], dict[int, int]]:
    """{(chunk, file): {episode_index: length}} for the data files the episode metadata points at."""
    out: dict[tuple[int, int], dict[int, int]] = {}
    for p in sorted((SRC / "meta/episodes").rglob("*.parquet")):
        t = pq.read_table(p, columns=["episode_index", "length", "data/chunk_index", "data/file_index"]).to_pydict()
        for ep, n, c, f in zip(t["episode_index"], t["length"], t["data/chunk_index"], t["data/file_index"], strict=True):
            out.setdefault((int(c), int(f)), {})[int(ep)] = int(n)
    return out


REFERENCED = referenced_files()


def chunk_file(rel: str) -> tuple[int, int]:
    p = Path(rel)
    return int(p.parent.name.split("-")[1]), int(p.stem.split("-")[1])


def process_data_file(rel: str) -> tuple[str, dict[int, dict[str, dict[str, np.ndarray]]]]:
    """Add the columns to one file. Episode statistics only for files the metadata references:
    the repo also holds unreferenced parquet files with a stale episode numbering."""
    src, dst = SRC / rel, OUT / rel
    table = pq.read_table(src)
    expected = REFERENCED.get(chunk_file(rel))
    arrays: dict[str, np.ndarray] = {}
    for new, (pos_key, grip_key) in NEW.items():
        column, values = concat_columns(table, pos_key, grip_key)
        table = table.append_column(new, column)
        arrays[new] = values
    stats: dict[int, dict] = {}
    if expected is not None:
        episode_index = table["episode_index"].to_numpy()
        boundaries = np.flatnonzero(np.diff(episode_index)) + 1
        for start, stop in zip(np.r_[0, boundaries], np.r_[boundaries, len(episode_index)], strict=True):
            ep = int(episode_index[start])
            assert ep not in stats, f"episode {ep} is not contiguous in {rel}"
            assert expected.get(ep) == stop - start, f"episode {ep} in {rel}: {stop - start} rows, metadata says {expected.get(ep)}"
            stats[ep] = compute_episode_stats({k: v[start:stop] for k, v in arrays.items()}, {k: FEATURE for k in NEW})
        assert set(stats) == set(expected), f"{rel}: episodes differ from the metadata"
    dst.parent.mkdir(parents=True, exist_ok=True)
    pq.write_table(table, dst, compression="snappy")
    return rel, stats


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    data_files = sorted(str(p.relative_to(SRC)) for p in (SRC / "data").rglob("*.parquet"))
    print(f"{len(data_files)} data files", flush=True)
    orphans = [rel for rel in data_files if chunk_file(rel) not in REFERENCED]
    print(f"{len(REFERENCED)} files referenced by the metadata, {len(orphans)} unreferenced (columns added, no statistics)", flush=True)
    episode_stats: dict[int, dict] = {}
    with ProcessPoolExecutor(max_workers=16) as pool:
        for i, (rel, stats) in enumerate(pool.map(process_data_file, data_files), 1):
            assert not (set(stats) & set(episode_stats)), f"{rel}: episode seen twice"
            episode_stats.update(stats)
            if i % 20 == 0 or i == len(data_files):
                print(f"  {i}/{len(data_files)} files, {len(episode_stats)} episodes", flush=True)

    # meta/info.json: the two features
    info = json.loads((SRC / "meta/info.json").read_text())
    assert info["total_episodes"] == len(episode_stats), (info["total_episodes"], len(episode_stats))
    for new in NEW:
        assert new not in info["features"], new
        info["features"][new] = FEATURE
    (OUT / "meta").mkdir(exist_ok=True)
    (OUT / "meta/info.json").write_text(json.dumps(info, indent=4) + "\n")

    # meta/episodes/**: per-episode stats columns
    for src in sorted((SRC / "meta/episodes").rglob("*.parquet")):
        rel = src.relative_to(SRC)
        table = pq.read_table(src)
        eps = table["episode_index"].to_pylist()
        for new in NEW:
            for key in STAT_KEYS:
                typ = pa.list_(pa.int64()) if key == "count" else pa.list_(pa.float64())
                col = pa.array([np.asarray(episode_stats[ep][new][key]).reshape(-1).tolist() for ep in eps], type=typ)
                table = table.append_column(f"stats/{new}/{key}", col)
        (OUT / rel).parent.mkdir(parents=True, exist_ok=True)
        pq.write_table(table, OUT / rel, compression="snappy")

    # meta/stats.json: aggregate over the episodes, LeRobot's way
    stats = json.loads((SRC / "meta/stats.json").read_text())
    aggregated = aggregate_stats([episode_stats[ep] for ep in sorted(episode_stats)])
    for new in NEW:
        stats[new] = {k: np.asarray(v).tolist() for k, v in aggregated[new].items()}
    (OUT / "meta/stats.json").write_text(json.dumps(stats, indent=4) + "\n")
    shutil.copy2(SRC / "meta/tasks.parquet", OUT / "meta/tasks.parquet")  # unchanged, for local validation
    print("done:", {new: {k: np.round(v, 3).tolist() for k, v in stats[new].items() if k in ("min", "max", "mean")} for new in NEW})


if __name__ == "__main__":
    main()
validate_cartesian_columns.py
"""Check OUT against SRC: new columns bitwise equal to their sources, everything else unchanged, metadata loads."""
import json
import sys
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq

SRC, OUT = Path(sys.argv[1]), Path(sys.argv[2])
NEW = {
    "observation.state.cartesian": ("observation.state.cartesian_position", "observation.state.gripper_position"),
    "action.cartesian": ("action.cartesian_position", "action.gripper_position"),
}


def check(rel: str) -> tuple[str, int]:
    a, b = pq.read_table(SRC / rel), pq.read_table(OUT / rel)
    assert b.num_rows == a.num_rows, rel
    assert b.column_names == a.column_names + list(NEW), rel
    for name in a.column_names:
        assert b[name].equals(a[name]), (rel, name)
    for new, (pos_key, grip_key) in NEW.items():
        got = np.stack(b[new].to_numpy(zero_copy_only=False)).astype(np.float32)
        pos = np.stack(a[pos_key].to_numpy(zero_copy_only=False)).astype(np.float32)
        grip = a[grip_key].to_numpy(zero_copy_only=False).astype(np.float32)[:, None]
        assert got.shape == (a.num_rows, 7) and np.array_equal(got, np.concatenate([pos, grip], 1)), (rel, new)
        assert str(b.schema.field(new).type) == "list<element: float>", str(b.schema.field(new).type)
    return rel, a.num_rows


files = sorted(str(p.relative_to(SRC)) for p in (SRC / "data").rglob("*.parquet"))
with ProcessPoolExecutor(16) as pool:
    rows = sum(n for _, n in pool.map(check, files))
info = json.loads((OUT / "meta/info.json").read_text())
src_rows = sum(pq.ParquetFile(SRC / f).metadata.num_rows for f in files)
assert rows == src_rows, (rows, src_rows)
ref = set()
for p in sorted((SRC / "meta/episodes").rglob("*.parquet")):
    t = pq.read_table(p, columns=["data/chunk_index", "data/file_index"]).to_pydict()
    ref |= {f"data/chunk-{c:03d}/file-{f:03d}.parquet" for c, f in zip(t["data/chunk_index"], t["data/file_index"], strict=True)}
ref_rows = sum(pq.ParquetFile(OUT / f).metadata.num_rows for f in files if f in ref)
assert ref_rows == info["total_frames"], (ref_rows, info["total_frames"])
print(f"data: {len(files)} files, {rows:,} rows ({len(ref)} referenced files = {ref_rows:,} frames = info.total_frames; {len(files) - len(ref)} unreferenced files left in place), new columns bitwise equal to their sources, other columns unchanged")

from lerobot.datasets.dataset_metadata import LeRobotDatasetMetadata  # noqa: E402

meta = LeRobotDatasetMetadata("lerobot/droid_1.0.1", root=OUT)
for new in NEW:
    assert tuple(meta.features[new]["shape"]) == (7,), meta.features[new]
    assert new in meta.stats, (new, sorted(meta.stats)[:5])
    s = meta.stats[new]
    assert all(np.asarray(s[k]).shape == (7,) for k in ("min", "max", "mean", "std", "q01", "q99")), {k: np.asarray(v).shape for k, v in s.items()}
    assert int(np.asarray(s["count"]).reshape(-1)[0]) == info["total_frames"]
    print(f"{new}: mean {np.round(s['mean'], 3).tolist()} | std {np.round(s['std'], 3).tolist()} | count {int(np.asarray(s['count']).reshape(-1)[0]):,}")
# stats consistency: the 7-D stats must equal the source features' stats
src_stats = json.loads((SRC / "meta/stats.json").read_text())
for new, (pos_key, grip_key) in NEW.items():
    for k in ("min", "max", "mean", "std"):
        ref = np.concatenate([np.asarray(src_stats[pos_key][k]).reshape(-1), np.asarray(src_stats[grip_key][k]).reshape(-1)])
        got = np.asarray(meta.stats[new][k]).reshape(-1)
        assert np.allclose(got, ref, rtol=1e-4, atol=1e-5), (new, k, got, ref)
print("meta: info.json and stats.json load through LeRobotDatasetMetadata; min/max/mean/std match the source features' stats")
ep = pq.read_table(OUT / "meta/episodes/chunk-000/file-000.parquet")
print("episodes: new stats columns", sum(c.startswith(("stats/observation.state.cartesian/", "stats/action.cartesian/")) for c in ep.column_names), "| rows", ep.num_rows)
pepijn223 changed pull request status to merged

Sign up or log in to comment