Skip to content

Commit 41dbc66

Browse files
authored
Add the metrics registry and the run report (#90)
* feat: record metric inputs and run metadata during generation Generation, annotation and retargeting now record what dataset metrics need, without computing any metric: - Every producer records step_success from the task's success term. Generation also records the per-step EEF and commanded target poses, but not object poses, which annotation keeps for the source pool. - Each exported dataset gets an autodata entry in env_args: run id, exported count, pose-action layout, robot joint names with simulator limits, and optional datasheet hardware_limits from the embodiment. - --result_file adds a run block (run id, seed, revision, input digests, hardware, setup and generation time) and an attempt log, one line per attempt with its failure cause and algorithm extras. - GenerationAlgorithm.attempt_extras() lets an algorithm report per-attempt facts; SkillGen reports its motion-planning time. * docs: describe what generation records per step, attempt and run * feat: add the autodata_metrics registry and the run report Metrics are plain functions registered with @Metric. Each declares the evidence it requires (an HDF5 path, an env_args, run or attempt-log field, or the source dataset); without it the report says which key is missing instead of computing anything. A metric that raises is reported as an error without hiding the others. The report refuses a dataset and run record whose run ids or exported counts differ. validate_dataset.py --report computes every registered metric, --metrics loads more from a module, and --gate fails the command when a gated metric is out of bounds, not applicable or at another version. Built-in run metrics: generation success rate (stop-corrected, Wilson interval), demos per GPU-hour, time to dataset, annotation pass rate, and the failure-share and planning-time diagnostics. * docs: add the metrics reference page with a table generated from the metric declarations * fix: keep earlier runs' records and label only this run's datasets - Each run writes its own attempt log, <stem>.<run_id>.attempts.jsonl, so rerunning with the same --result_file keeps earlier logs, and an interrupted rerun leaves the earlier result and its log consistent. - A _failed dataset gets this run's autodata entry only when this run kept failed episodes, so one left by an earlier run is not relabelled. - The e2e helper checks the logged successes against the result. - Docs: only generated datasets have a result file and attempt log. * fix: report a run from the attempt log of the dataset's own run Each run now writes its own attempt log. The report reads the log named by the result when the result belongs to the dataset's run; otherwise it sets the result aside with a warning and reads the log named by the dataset's run id, so an interrupted rerun is still reported and runs are never mixed. * docs: say the result file and attempt log come with --result_file * feat: make metric recording opt-in and keep algorithm diagnostics in extras - Metric recording is off by default, so datasets and result files are unchanged unless --record_metric_inputs is given to generation, annotation or retargeting. It records the per-step poses and task success, the autodata entry and, with --result_file, the run block and attempt log. - GenerationResult no longer has failure_cause; SkillGen reports planning_failed in its attempt extras, next to planning_time_s. - metric_context() docstrings say what they record; the pose-action entry's columns key is now action_slice. - Docs: the run linkage holds once the run completes. * fix: reject non-finite values, require --report for report options, run metrics tests in CI - The report marks a metric whose value is not a finite number as an error, and the gate counts a missing or non-numeric value as a violation. - validate_dataset.py errors when --result_file, --source, --metrics, --gate or --report_file is given without --report. - failure_share is replaced by planning_failure_rate, read from SkillGen's planning_failed attempt extra. - CI runs autodata_tests/metrics/. - Docs: metrics need --record_metric_inputs at recording time. * fix: record metric inputs with a custom recorder and without a success term - With --record_metric_inputs, the per-step pose term is added to a custom --recorder_cfg too, unless it already records datagen info. - Without a success term, step_success is not recorded instead of failing on the first step. * fix: check the attempt log against its result and keep reports valid JSON - The report refuses a result whose attempt and success counts differ from its attempt log. - Run and gate input checks raise ValueError, so they also hold under python -O. - Non-finite numbers in a metric's details are reported as null. - A dataset whose env_args are not a JSON object reads as having none. - An empty metrics mapping computes no metrics instead of all of them. - Docs: how the report treats a result from another run; the example metric gets its own name; joint-limit metrics are not mentioned yet. - The end-to-end tests run the report through assert_ok_metrics.
1 parent 4d7419d commit 41dbc66

18 files changed

Lines changed: 993 additions & 5 deletions

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ jobs:
6262
# trials each) are heavy and run in the nightly instead. No marker filter, so
6363
# both subprocess and unit tests run.
6464
env:
65-
TEST_PATH: "autodata_tests/e2e/ autodata_tests/interfaces/ autodata_tests/core/ autodata_tests/utils/ autodata_tests/retargeting/"
65+
TEST_PATH: "autodata_tests/e2e/ autodata_tests/interfaces/ autodata_tests/core/ autodata_tests/utils/ autodata_tests/retargeting/ autodata_tests/metrics/"
6666

6767
steps:
6868
- name: nvidia-smi

‎autodata_metrics/__init__.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Offline metrics of AutoData datasets and generation runs.
5+
6+
Producers record evidence; :func:`build_report` computes every registered metric from it without a simulator.
7+
Importing this package registers the built-in metrics.
8+
"""
9+
10+
from autodata_metrics import viability
11+
from autodata_metrics.evidence import Episode, Evidence
12+
from autodata_metrics.registry import AREAS, REGISTERED_METRICS, MetricSpec, NotApplicable, Value, metric
13+
from autodata_metrics.report import build_report, format_report, gate_violations

‎autodata_metrics/evidence.py‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""What a metric reads: a dataset's episodes and ``env_args``, and its generation run's record and attempt log."""
5+
6+
from __future__ import annotations
7+
8+
import h5py
9+
import json
10+
import numpy as np
11+
from collections.abc import Mapping
12+
from typing import Any
13+
14+
15+
def _has_path(record: Any, dotted_key: str) -> bool:
16+
"""Whether ``record[a][b]`` exists for ``dotted_key`` ``"a.b"``."""
17+
for part in dotted_key.split("."):
18+
if not isinstance(record, Mapping) or part not in record:
19+
return False
20+
record = record[part]
21+
return True
22+
23+
24+
def read_env_args(h5_file: h5py.File) -> dict[str, Any]:
25+
"""The dataset's ``env_args``, or empty when they are not a JSON object."""
26+
raw_env_args = h5_file["data"].attrs.get("env_args", "{}")
27+
env_args = json.loads(raw_env_args.decode() if isinstance(raw_env_args, bytes) else raw_env_args)
28+
return env_args if isinstance(env_args, dict) else {}
29+
30+
31+
class Episode:
32+
"""One episode of a dataset; arrays are read when accessed."""
33+
34+
def __init__(self, group: h5py.Group) -> None:
35+
self.name = group.name.rsplit("/", 1)[-1]
36+
self._group = group
37+
38+
def __contains__(self, key: str) -> bool:
39+
return key in self._group
40+
41+
def __getitem__(self, key: str) -> np.ndarray:
42+
return self._group[key][()]
43+
44+
45+
class Evidence:
46+
"""A dataset, and optionally the generation run that produced it, as metrics read them.
47+
48+
Attributes:
49+
episodes: The dataset's episodes.
50+
env_args: The dataset's ``env_args``; its ``autodata`` entry was written by the producer.
51+
result: Generation result, or None for a dataset without a run record or an interrupted run.
52+
run: The result's ``run`` block, or empty.
53+
attempts: Attempt-log lines, or None.
54+
source: Evidence of the source dataset the run started from, or None.
55+
"""
56+
57+
def __init__(
58+
self,
59+
h5_file: h5py.File,
60+
result: Mapping[str, Any] | None = None,
61+
attempts: list[dict[str, Any]] | None = None,
62+
source: Evidence | None = None,
63+
) -> None:
64+
self.env_args = read_env_args(h5_file)
65+
self.episodes = [Episode(group) for group in h5_file["data"].values()]
66+
self.result = result
67+
self.run: Mapping[str, Any] = (result or {}).get("run", {})
68+
self.attempts = attempts
69+
self.source = source
70+
71+
def has(self, key: str) -> bool:
72+
"""Whether the evidence key ``key`` is present.
73+
74+
A key is one of:
75+
76+
- an HDF5 path present in every episode, such as ``step_success``;
77+
- ``env_args.<path>`` or ``run.<path>``, a dotted path into ``env_args`` or the run block;
78+
- ``attempts``, the attempt log, or ``attempts.<path>``, a dotted path present in every attempt line;
79+
- ``source``, the source dataset, or ``source.<key>``, a key of the source dataset.
80+
"""
81+
head, _, rest = key.partition(".")
82+
if head == "source":
83+
return self.source is not None and (not rest or self.source.has(rest))
84+
if head == "attempts":
85+
return bool(self.attempts) and (not rest or all(_has_path(line, rest) for line in self.attempts))
86+
if head == "env_args":
87+
return _has_path(self.env_args, rest)
88+
if head == "run":
89+
return _has_path(self.run, rest)
90+
return bool(self.episodes) and all(key in episode for episode in self.episodes)

‎autodata_metrics/registry.py‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
"""Registry of dataset and run metrics.
5+
6+
A metric is a function of :class:`~autodata_metrics.evidence.Evidence` registered with :func:`metric`. It declares
7+
the evidence it ``requires``; the runner reports it as not applicable, naming the missing key, instead of calling it
8+
without that evidence.
9+
"""
10+
11+
from __future__ import annotations
12+
13+
from collections.abc import Callable, Mapping
14+
from dataclasses import dataclass, field
15+
from typing import TYPE_CHECKING, Any, Literal
16+
17+
if TYPE_CHECKING:
18+
from autodata_metrics.evidence import Evidence
19+
20+
AREAS = ("validity", "diversity", "viability", "diagnostics")
21+
22+
23+
class NotApplicable(Exception):
24+
"""Raised by a metric whose evidence is present but does not let it apply."""
25+
26+
27+
@dataclass(frozen=True)
28+
class Value:
29+
"""What a metric computed.
30+
31+
Attributes:
32+
value: A number, or named numbers such as percentiles.
33+
n: Sample count the value rests on.
34+
details: Context a reader needs to interpret the value.
35+
"""
36+
37+
value: float | dict[str, float]
38+
n: int
39+
details: Mapping[str, Any] = field(default_factory=dict)
40+
41+
42+
@dataclass(frozen=True)
43+
class MetricSpec:
44+
"""A registered metric and how to report it."""
45+
46+
name: str
47+
compute: Callable[[Evidence], Value]
48+
area: str
49+
signal: str
50+
scope: Literal["dataset", "run"]
51+
unit: str
52+
better: Literal["higher", "lower"] | None
53+
requires: tuple[str, ...]
54+
primary: str | None
55+
version: int
56+
57+
58+
REGISTERED_METRICS: dict[str, MetricSpec] = {}
59+
60+
61+
def metric(
62+
name: str,
63+
*,
64+
area: str,
65+
signal: str,
66+
scope: Literal["dataset", "run"],
67+
unit: str,
68+
better: Literal["higher", "lower"] | None = None,
69+
requires: tuple[str, ...] | list[str] = (),
70+
primary: str | None = None,
71+
version: int = 1,
72+
) -> Callable[[Callable[[Evidence], Value]], Callable[[Evidence], Value]]:
73+
"""Register the decorated function as the metric ``name``.
74+
75+
Args:
76+
name: Unique metric name, used in reports and gates.
77+
area: One of :data:`AREAS`.
78+
signal: What the metric measures within its area, e.g. ``"task correctness"``.
79+
scope: ``"dataset"`` metrics read episodes; ``"run"`` metrics read attempts and the run record.
80+
unit: Unit of the value.
81+
better: Which direction is better, if either.
82+
requires: Evidence keys; see :meth:`~autodata_metrics.evidence.Evidence.has`.
83+
primary: For a dict value, the entry a gate checks by default.
84+
version: Raise it whenever the definition changes, so gates pinned to the old one fail.
85+
"""
86+
assert area in AREAS, f"Metric {name!r} has area {area!r}; expected one of {AREAS}."
87+
88+
def register(compute: Callable[[Evidence], Value]) -> Callable[[Evidence], Value]:
89+
assert name not in REGISTERED_METRICS, f"Metric {name!r} is already registered."
90+
REGISTERED_METRICS[name] = MetricSpec(
91+
name=name,
92+
compute=compute,
93+
area=area,
94+
signal=signal,
95+
scope=scope,
96+
unit=unit,
97+
better=better,
98+
requires=tuple(requires),
99+
primary=primary,
100+
version=version,
101+
)
102+
return compute
103+
104+
return register

0 commit comments

Comments
 (0)