Skip to content

Commit 4e7369c

Browse files
authored
Add the diversity metrics (#93)
* Add the start layout and workspace diversity metrics start_layout_spread averages, over pairs of episodes, the root-sum-square of each rigid, articulated and deformable object's horizontal start distance, so an object that never moves adds nothing and pinning one can only lower it. workspace_spread averages how far one episode's hands pass from where the other's went: each recorded end-effector path is sampled every 2.5 mm between recorded steps and keeps one point per 5 mm cell, so retracing a path adds nothing, and a hand that moves more than 8 cm in one recorded step makes it not applicable. Both read at most 1,000 episodes in an order their actions set, with names ordering episodes whose actions repeat exactly, and the workspace measures at most 2,000 pairs. An object or a hand missing from an episode is named. The end-to-end metric checks expect both spreads once a run exports two episodes. * Document the diversity metrics and when they compare The metrics reference defines both spreads and says when two values compare: same task and objects, same hands recorded in the same frames. It gives the measured effect of the end-effector frame, the first recorded step and the recording rate on the test datasets and runs, and its console example is a real report that shows both. * docs: clarify spread diagnostics and exercise paired reports
1 parent 4a3d1f3 commit 4e7369c

6 files changed

Lines changed: 443 additions & 18 deletions

File tree

‎autodata_metrics/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
Importing this package registers the built-in metrics.
88
"""
99

10-
from autodata_metrics import validity, viability
10+
from autodata_metrics import diversity, validity, viability
1111
from autodata_metrics.evidence import Episode, Evidence
1212
from autodata_metrics.registry import (
1313
AREAS,

‎autodata_metrics/diversity.py‎

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Supporting dispersion diagnostics: how different recorded demonstrations are from one another.
5+
6+
Each spread averages a distance over pairs of episodes:
7+
8+
- ``start_layout_spread``: how far apart two episodes' starting scenes are [mm].
9+
- ``workspace_spread``: how far one episode's hands pass from where the other's went [mm].
10+
11+
An average over pairs estimates how different two demonstrations from the same producer are, so it does not grow with
12+
the number of episodes. These spreads do not measure target coverage, behavioral novelty or policy learning value.
13+
A larger spread is not necessarily better. The metrics reference page defines when two values compare.
14+
"""
15+
16+
from __future__ import annotations
17+
18+
import hashlib
19+
import numpy as np
20+
21+
from autodata_metrics.evidence import Episode, Evidence
22+
from autodata_metrics.registry import NotApplicable, Value, metric
23+
24+
MAX_EPISODES = 1000
25+
"""Episodes a spread reads at most."""
26+
MAX_WORKSPACE_PAIRS = 2000
27+
"""Episode pairs the workspace measures at most; the start layout uses every pair."""
28+
WORKSPACE_GRID_M = 0.005
29+
"""Grid in which a hand's path keeps one point per cell, so a path weighs the space it visits, not its length [m]."""
30+
MAX_WORKSPACE_STEP_M = 0.08
31+
"""A hand's move in one recorded step above which the workspace does not apply [m]."""
32+
START_GROUPS = ("rigid_object", "articulation", "deformable_object")
33+
"""``initial_state`` groups whose entities make up a start layout."""
34+
35+
36+
@metric(
37+
"start_layout_spread",
38+
area="diversity",
39+
signal="start layouts",
40+
scope="dataset",
41+
unit="mm",
42+
sample="episodes",
43+
requires=["actions", "initial_state"],
44+
baseline=True,
45+
)
46+
def start_layout_spread(ev: Evidence) -> Value:
47+
"""Average distance between two episodes' starting scenes, counting every object.
48+
49+
For each pair of episodes, each object's horizontal start distance is combined with the others' as a
50+
root-sum-square: an object that never moves adds nothing, one that moves more adds more. Robots and deformable
51+
objects count by their root and their nodes' centroid. 0 means every object starts at the same xy in every
52+
episode.
53+
"""
54+
episodes = _sample(ev)
55+
names, layouts = _start_layouts(episodes)
56+
entities = {name: _pair_mean(1000 * layouts[:, k]) for k, name in enumerate(names)}
57+
return Value(_pair_mean(1000 * layouts), n=len(episodes), details={"entities_mm": entities})
58+
59+
60+
@metric(
61+
"workspace_spread",
62+
area="diversity",
63+
signal="hand workspace",
64+
scope="dataset",
65+
unit="mm",
66+
sample="episodes",
67+
requires=["actions", "obs/datagen_info/eef_pose"],
68+
baseline=True,
69+
)
70+
def workspace_spread(ev: Evidence) -> Value:
71+
"""Average distance from where one episode's hands pass to where the other's went.
72+
73+
A hand is each recorded end effector, followed by the origin of its frame as the embodiment records it, from the
74+
episode's first recorded step. Its path keeps one point per :data:`WORKSPACE_GRID_M` cell, so retracing a path adds
75+
nothing. Each kept point's distance to the nearest kept point of the other episode's path is averaged, both ways,
76+
and halved; hands are averaged. 0 means the hands pass through the same space.
77+
"""
78+
episodes = _sample(ev)
79+
hands = sorted(set().union(*(episode.children("obs/datagen_info/eef_pose") for episode in episodes)))
80+
if not hands:
81+
raise NotApplicable("records no end-effector poses")
82+
hand_paths = [_hand_paths(episode, hands) for episode in episodes]
83+
for k, hand in enumerate(hands):
84+
move = max(np.linalg.norm(np.diff(paths[k], axis=0), axis=1).max(initial=0.0) for paths in hand_paths)
85+
if move > MAX_WORKSPACE_STEP_M:
86+
raise NotApplicable(
87+
f"{hand} moves {100 * move:g} cm in one recorded step, over the {100 * MAX_WORKSPACE_STEP_M:g} cm limit"
88+
)
89+
kept = [[_grid_points(path) for path in paths] for paths in hand_paths]
90+
first, second = _workspace_pairs(len(episodes))
91+
gaps = 1000 * np.array([[_mean_gap(a, b) for a, b in zip(kept[i], kept[j])] for i, j in zip(first, second)])
92+
hands_mm = {hand: float(gaps[:, k].mean()) for k, hand in enumerate(hands)}
93+
return Value(float(gaps.mean()), n=len(episodes), details={"pairs": len(first), "hands_mm": hands_mm})
94+
95+
96+
def _digest(episode: Episode) -> bytes:
97+
actions = np.ascontiguousarray(episode["actions"])
98+
return hashlib.sha256(f"{actions.dtype.str}{actions.shape}".encode() + actions.tobytes()).digest()
99+
100+
101+
def _sample(ev: Evidence) -> list[Episode]:
102+
"""The episodes a spread reads, at least two: the first :data:`MAX_EPISODES` in a ranking by a digest of each
103+
episode's actions and how many episodes before it, by name, repeat them. Repeats spread through the ranking, and
104+
file order matters only between episodes whose actions repeat exactly."""
105+
copies: dict[bytes, int] = {}
106+
ranked = []
107+
for episode in sorted(ev.episodes, key=lambda episode: episode.name):
108+
digest = _digest(episode)
109+
copies[digest] = copies.get(digest, -1) + 1
110+
ranked.append((hashlib.sha256(digest + copies[digest].to_bytes(8, "little")).digest(), episode))
111+
episodes = [episode for _, episode in sorted(ranked, key=lambda item: item[0])[:MAX_EPISODES]]
112+
if len(episodes) < 2:
113+
raise NotApplicable("needs two episodes")
114+
return episodes
115+
116+
117+
def _pair_mean(rows: np.ndarray) -> float:
118+
"""The mean Euclidean distance between two rows, over every pair of rows."""
119+
rows = rows.reshape(len(rows), -1)
120+
return float(np.concatenate([np.linalg.norm(rows[k + 1 :] - rows[k], axis=1) for k in range(len(rows) - 1)]).mean())
121+
122+
123+
def _starts(episode: Episode) -> dict[str, np.ndarray]:
124+
"""Each scene entity's start xy in the episode: rigid objects and articulations by their root, deformable objects
125+
by their nodes' centroid [m]."""
126+
found = {}
127+
for group in START_GROUPS:
128+
prefix = f"initial_state/{group}"
129+
for name in episode.children(prefix) if prefix in episode else ():
130+
if group == "deformable_object":
131+
found[f"{group}/{name}"] = episode[f"{prefix}/{name}/nodal_position"][0].mean(axis=0)[:2]
132+
else:
133+
found[f"{group}/{name}"] = episode[f"{prefix}/{name}/root_pose"][0, :2]
134+
return found
135+
136+
137+
def _start_layouts(episodes: list[Episode]) -> tuple[list[str], np.ndarray]:
138+
"""The entities with a start pose, and each episode's start xy of each [m]."""
139+
starts = [_starts(episode) for episode in episodes]
140+
names = sorted(set().union(*starts))
141+
if not names:
142+
raise NotApplicable("no start poses recorded")
143+
for episode, found in zip(episodes, starts):
144+
if missing := sorted(set(names) - set(found)):
145+
raise NotApplicable(f"{missing[0]} has no start pose in episode {episode.name}")
146+
return names, np.array([[found[name] for name in names] for found in starts], dtype=float)
147+
148+
149+
def _hand_paths(episode: Episode, hands: list[str]) -> list[np.ndarray]:
150+
"""Each hand's position at each recorded step [m]."""
151+
paths = []
152+
for hand in hands:
153+
key = f"obs/datagen_info/eef_pose/{hand}"
154+
if key not in episode:
155+
raise NotApplicable(f"episode {episode.name} records no pose of {hand}")
156+
paths.append(np.asarray(episode[key], dtype=float)[:, :3, 3])
157+
return paths
158+
159+
160+
def _grid_points(path: np.ndarray) -> np.ndarray:
161+
"""The path sampled every half :data:`WORKSPACE_GRID_M` along its segments, keeping the first sample in each grid
162+
cell, so every kept point lies on the path."""
163+
steps = np.diff(path, axis=0)
164+
counts = np.maximum(1, np.ceil(np.linalg.norm(steps, axis=1) / (WORKSPACE_GRID_M / 2))).astype(int)
165+
segment = np.repeat(np.arange(len(steps)), counts)
166+
fraction = (np.arange(counts.sum()) - np.repeat(np.cumsum(counts) - counts, counts)) / np.repeat(counts, counts)
167+
samples = np.concatenate([path[segment] + fraction[:, None] * steps[segment], path[-1:]])
168+
_, first = np.unique(np.floor(samples / WORKSPACE_GRID_M).astype(np.int64), axis=0, return_index=True)
169+
return samples[np.sort(first)]
170+
171+
172+
def _mean_gap(a: np.ndarray, b: np.ndarray) -> float:
173+
"""Half the sum of each path's mean distance from its kept points to the other's nearest kept point [m]."""
174+
distances = np.linalg.norm(a[:, None] - b[None], axis=2)
175+
return 0.5 * float(distances.min(axis=1).mean() + distances.min(axis=0).mean())
176+
177+
178+
def _workspace_pairs(count: int) -> tuple[np.ndarray, np.ndarray]:
179+
"""Index pairs of distinct episodes: all, or :data:`MAX_WORKSPACE_PAIRS` drawn with a fixed seed."""
180+
first, second = np.triu_indices(count, 1)
181+
if len(first) <= MAX_WORKSPACE_PAIRS:
182+
return first, second
183+
chosen = np.sort(np.random.default_rng(0).choice(len(first), MAX_WORKSPACE_PAIRS, replace=False))
184+
return first[chosen], second[chosen]

‎autodata_tests/e2e/test_mimicgen_data_generation.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from autodata_tests.utils.utils import assert_ok_metrics, assert_recorded_run, assert_valid_dataset
1212

1313
HEADLESS = True
14-
GENERATION_NUM_TRIALS = 1
14+
GENERATION_NUM_TRIALS = 2
1515
# Metrics a MimicGen run recorded with --record_metric_inputs must compute; no camera, so no image checks.
1616
METRICS = {
1717
"generation_success_rate",
@@ -23,6 +23,8 @@
2323
"action_saturation",
2424
"motion_smoothness",
2525
"joint_limit_ratio",
26+
"start_layout_spread",
27+
"workspace_spread",
2628
}
2729

2830

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Known-answer tests of the diversity metrics."""
5+
6+
import h5py
7+
import json
8+
import numpy as np
9+
from pathlib import Path
10+
11+
import pytest
12+
13+
from autodata_metrics import REGISTERED_METRICS, build_report
14+
from autodata_metrics.diversity import _digest, _sample
15+
from autodata_metrics.evidence import Evidence
16+
17+
18+
def _write(path: Path, episodes: list[dict[str, np.ndarray]]) -> str:
19+
with h5py.File(path, "w") as h5_file:
20+
data = h5_file.create_group("data")
21+
data.attrs["env_args"] = json.dumps({"env_name": "Test-v0"})
22+
for index, arrays in enumerate(episodes):
23+
for key, array in arrays.items():
24+
data.create_dataset(f"demo_{index}/{key}", data=array)
25+
return str(path)
26+
27+
28+
def _row(dataset: str, name: str) -> dict:
29+
return build_report(dataset, metrics={name: REGISTERED_METRICS[name]})["metrics"][name]
30+
31+
32+
def _starts(**positions: list[float]) -> dict[str, np.ndarray]:
33+
"""An episode whose objects start at the given xy, or xyz."""
34+
poses = {
35+
f"initial_state/rigid_object/{name}/root_pose": [[*position, *[0.0] * (3 - len(position)), 1.0, 0.0, 0.0, 0.0]]
36+
for name, position in positions.items()
37+
}
38+
return {"actions": np.zeros((2, 7)), **poses}
39+
40+
41+
def _poses(positions: np.ndarray) -> np.ndarray:
42+
poses = np.tile(np.eye(4), (len(positions), 1, 1))
43+
poses[:, :3, 3] = positions
44+
return poses
45+
46+
47+
def _moving(**tracks: np.ndarray) -> dict[str, np.ndarray]:
48+
"""An episode whose hands follow the given tracks."""
49+
first = next(iter(tracks.values()))
50+
return {
51+
"actions": np.pad(first, ((0, 0), (0, 4))),
52+
**{f"obs/datagen_info/eef_pose/{hand}": _poses(track) for hand, track in tracks.items()},
53+
}
54+
55+
56+
def test_start_layout_spread_counts_every_object_so_pinning_one_lowers_it(tmp_path):
57+
# x moves 2 cm and rises 10 cm, which does not count, and y moves 10 cm per episode while the table stays; a pair's
58+
# distance is the root-sum-square of the objects' horizontal ones.
59+
varied = [_starts(x=[0.02 * i, 0.0, 0.1 * i], y=[0.0, 0.1 * i], table=[0.5, 0.5]) for i in range(4)]
60+
pinned = [_starts(x=[0.0, 0.0], y=[0.0, 0.1 * i], table=[0.5, 0.5]) for i in range(4)]
61+
mean_step = np.mean([j - i for i in range(4) for j in range(i + 1, 4)])
62+
63+
varied_row = _row(_write(tmp_path / "varied.hdf5", varied), "start_layout_spread")
64+
pinned_row = _row(_write(tmp_path / "pinned.hdf5", pinned), "start_layout_spread")
65+
66+
assert varied_row["value"] == pytest.approx(1000 * np.hypot(0.02, 0.1) * mean_step)
67+
assert pinned_row["value"] == pytest.approx(1000 * 0.1 * mean_step)
68+
69+
70+
def test_a_deformable_object_starts_at_its_nodes_centroid(tmp_path):
71+
# A rope's first node stays at the origin while its second lies 0, 10 and 20 cm away: its centroid moves 5 cm a step.
72+
episodes = [
73+
{
74+
"actions": np.zeros((2, 7)),
75+
"initial_state/deformable_object/rope/nodal_position": [[[0.0] * 3, [0.1 * i, 0, 0]]],
76+
}
77+
for i in range(3)
78+
]
79+
80+
row = _row(_write(tmp_path / "d.hdf5", episodes), "start_layout_spread")
81+
82+
assert row["value"] == pytest.approx((50.0 + 100.0 + 50.0) / 3)
83+
84+
85+
_LINE = np.linspace([0.0, 0.0, 0.0], [0.1, 0.0, 0.0], 11)
86+
_WITH_BALL, _WITHOUT_BALL = _starts(cube=[0.0, 0.0], ball=[0.1, 0.0]), _starts(cube=[0.1, 0.0])
87+
_TWO_HANDS, _ONE_HAND = _moving(left=_LINE, right=_LINE), _moving(left=_LINE)
88+
89+
90+
@pytest.mark.parametrize(
91+
"name, episodes, reason",
92+
[
93+
("start_layout_spread", [_WITH_BALL], "needs two episodes"),
94+
("start_layout_spread", [_WITH_BALL, _WITHOUT_BALL], "rigid_object/ball has no start pose in episode demo_1"),
95+
("start_layout_spread", [_WITHOUT_BALL, _WITH_BALL], "rigid_object/ball has no start pose in episode demo_0"),
96+
("workspace_spread", [_TWO_HANDS, _ONE_HAND], "episode demo_1 records no pose of right"),
97+
("workspace_spread", [_ONE_HAND, _TWO_HANDS], "episode demo_0 records no pose of right"),
98+
],
99+
)
100+
def test_a_spread_says_why_it_does_not_apply(tmp_path, name, episodes, reason):
101+
# Two episodes that hold the same actions are read in the opposite order once reversed, so in one of the two orders
102+
# a spread reads first the episode missing what the other records.
103+
row = _row(_write(tmp_path / "d.hdf5", episodes), name)
104+
105+
assert row["status"] == "not_applicable" and row["reason"] == reason
106+
107+
108+
def test_repeated_episodes_spread_through_the_episodes_a_spread_reads(tmp_path):
109+
# 40 distinct episodes, 30 copies each: the 1,000 read include every one.
110+
episodes = [{"actions": np.full((2, 7), float(k))} for k in range(40) for _ in range(30)]
111+
path = _write(tmp_path / "d.hdf5", episodes)
112+
113+
with h5py.File(path, "r") as h5_file:
114+
sample = _sample(Evidence(h5_file))
115+
distinct = {_digest(episode) for episode in sample}
116+
117+
assert len(sample) == 1000 and len(distinct) == 40
118+
119+
120+
def test_the_workspace_refuses_a_hand_that_moves_more_than_8_cm_in_one_step(tmp_path):
121+
# The right hand moves 1 mm a step but once 9 cm, 0.5% of its steps; the left, which sorts first, stands still.
122+
steps = np.array([0.001] * 199 + [0.09])
123+
episodes = [
124+
_moving(right=np.stack([np.concatenate([[0.0], np.cumsum(steps)]), np.full(201, side), np.zeros(201)], axis=1))
125+
| _moving(left=np.zeros((201, 3)))
126+
for side in (0.0, 0.1)
127+
]
128+
129+
row = _row(_write(tmp_path / "d.hdf5", episodes), "workspace_spread")
130+
131+
assert row["status"] == "not_applicable" and "right moves 9 cm in one recorded step" in row["reason"]
132+
133+
134+
def test_workspace_counts_a_retraced_path_once(tmp_path):
135+
# Against a 30 cm line, the line with a 10 cm branch and the line traced five times with the same branch visit the
136+
# same space.
137+
line = np.linspace([0.0, 0.0, 0.0], [0.3, 0.0, 0.0], 31)
138+
branch = np.linspace([0.3, 0.0, 0.0], [0.3, 0.1, 0.0], 11)[1:]
139+
once = np.concatenate([line, branch])
140+
retraced = np.concatenate([line, line[-2::-1], line[1:], line[-2::-1], line[1:], branch])
141+
142+
values = [
143+
_row(_write(tmp_path / f"{i}.hdf5", [_moving(arm=line), _moving(arm=other)]), "workspace_spread")
144+
for i, other in enumerate((once, retraced))
145+
]
146+
147+
assert values[0]["value"] == pytest.approx(values[1]["value"], abs=0.01)
148+
149+
150+
def test_the_workspace_is_how_far_apart_two_episodes_hands_run(tmp_path):
151+
# In one episode both hands sweep 10 cm along x, recorded at 0, 5 and 10 cm; in the other, the left hand rests
152+
# 10 cm beyond the sweep's end and the right 3 cm beside its middle. An offset of 1.25 mm keeps the sweep's 2.5 mm
153+
# samples off the 5 mm cell edges, so it keeps a point every 5 mm. The left sweep's points lie 150 mm from the
154+
# resting hand on average, which lies 100 mm from the nearest of them: 125 mm. The right sweep's points at x [mm] lie
155+
# hypot(30, x - 52.5) mm from the resting hand, which lies hypot(30, 2.5) mm from the nearest of them.
156+
offset = np.full(3, 0.00125)
157+
sweep = offset + [[0.0, 0.0, 0.0], [0.05, 0.0, 0.0], [0.1, 0.0, 0.0]]
158+
beyond = np.tile(offset + [0.2, 0.0, 0.0], (3, 1))
159+
beside = np.tile(offset + [0.0525, 0.03, 0.0], (3, 1))
160+
right = 0.5 * (np.mean([np.hypot(30.0, x - 52.5) for x in range(0, 101, 5)]) + np.hypot(30.0, 2.5))
161+
episodes = [_moving(left=sweep, right=sweep), _moving(left=beyond, right=beside)]
162+
163+
row = _row(_write(tmp_path / "d.hdf5", episodes), "workspace_spread")
164+
165+
assert row["value"] == pytest.approx(0.5 * (125.0 + right), rel=1e-9)
166+
167+
168+
def test_the_workspace_does_not_depend_on_the_order_of_episodes(tmp_path):
169+
# 64 episodes make 2,016 pairs, more than the workspace measures; which ones depends on content, not order.
170+
starts = np.random.default_rng(0).uniform(-0.3, 0.3, (64, 3))
171+
episodes = [_moving(arm=np.linspace(start, start + [0.1, 0.0, 0.0], 6)) for start in starts]
172+
173+
values = [
174+
_row(_write(tmp_path / f"{label}.hdf5", ordered), "workspace_spread")["value"]
175+
for label, ordered in (("forward", episodes), ("reversed", episodes[::-1]))
176+
]
177+
178+
assert values[0] == pytest.approx(values[1], rel=1e-12)

0 commit comments

Comments
 (0)