Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
"""Data-generation success-rate perf test for the G1 loco-manipulation pick-place (DexMimicGen) task."""

import os
import tempfile

import pytest

from autodata_tests.utils.constants import TestPaths
from autodata_tests.utils.constants import BENCHMARK_OPTIONAL_METRICS, DEXMIMICGEN_METRICS, TestPaths
from autodata_tests.utils.subprocess import run_subprocess
from autodata_tests.utils.utils import assert_valid_dataset, read_generation_result
from autodata_tests.utils.utils import (
assert_computed_metrics,
assert_valid_dataset,
benchmark_temp_dir,
read_generation_result,
report_metrics,
)

# --- Tunables (change these to adjust the perf test) ---------------------------------------------
SUCCESS_RATE_THRESHOLD = 0.70 # minimum acceptable data-gen success rate
Expand All @@ -24,8 +29,9 @@

@pytest.mark.with_subprocess
def test_dexmimicgen_g1_data_generation_success_rate():
"""Generate NUM_TRIALS demos on NUM_ENVS envs and assert the success rate exceeds the threshold."""
with tempfile.TemporaryDirectory() as temp_dir:
"""Generate NUM_TRIALS demos on NUM_ENVS envs, report their metrics and assert the success rate exceeds the
threshold."""
with benchmark_temp_dir("g1_pick_place_dexmimicgen") as temp_dir:
output_file = os.path.join(temp_dir, "generated.hdf5")
result_file = os.path.join(temp_dir, "generation_result.json")

Expand All @@ -46,6 +52,7 @@ def test_dexmimicgen_g1_data_generation_success_rate():
output_file,
"--result_file",
result_file,
"--record_metric_inputs",
"--generation_num_trials",
str(NUM_TRIALS),
"--num_envs",
Expand All @@ -58,6 +65,7 @@ def test_dexmimicgen_g1_data_generation_success_rate():
run_subprocess(args, timeout_sec=TIMEOUT_SEC)
assert_valid_dataset(output_file, min_num_demos=1)
num_success, num_attempts = read_generation_result(result_file)
report = report_metrics(output_file, result_file)

assert num_attempts > 0, "generation reported zero attempts"
success_rate = num_success / num_attempts
Expand All @@ -66,6 +74,7 @@ def test_dexmimicgen_g1_data_generation_success_rate():
f"data-gen success rate {success_rate:.1%} ({num_success}/{num_attempts}) is below the "
f"required threshold of {SUCCESS_RATE_THRESHOLD:.0%}"
)
assert_computed_metrics(report, DEXMIMICGEN_METRICS, optional=BENCHMARK_OPTIONAL_METRICS)


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
"""Data-generation success-rate perf test for the GR1T2 pick-place (DexMimicGen) task."""

import os
import tempfile

import pytest

from autodata_tests.utils.constants import TestPaths
from autodata_tests.utils.constants import BENCHMARK_OPTIONAL_METRICS, DEXMIMICGEN_METRICS, TestPaths
from autodata_tests.utils.subprocess import run_subprocess
from autodata_tests.utils.utils import assert_valid_dataset, read_generation_result
from autodata_tests.utils.utils import (
assert_computed_metrics,
assert_valid_dataset,
benchmark_temp_dir,
read_generation_result,
report_metrics,
)

# --- Tunables (change these to adjust the perf test) ---------------------------------------------
SUCCESS_RATE_THRESHOLD = 0.70 # minimum acceptable data-gen success rate
Expand All @@ -24,8 +29,9 @@

@pytest.mark.with_subprocess
def test_dexmimicgen_gr1_data_generation_success_rate():
"""Generate NUM_TRIALS demos on NUM_ENVS envs and assert the success rate exceeds the threshold."""
with tempfile.TemporaryDirectory() as temp_dir:
"""Generate NUM_TRIALS demos on NUM_ENVS envs, report their metrics and assert the success rate exceeds the
threshold."""
with benchmark_temp_dir("gr1_pick_place_dexmimicgen") as temp_dir:
output_file = os.path.join(temp_dir, "generated.hdf5")
result_file = os.path.join(temp_dir, "generation_result.json")

Expand All @@ -46,6 +52,7 @@ def test_dexmimicgen_gr1_data_generation_success_rate():
output_file,
"--result_file",
result_file,
"--record_metric_inputs",
"--generation_num_trials",
str(NUM_TRIALS),
"--num_envs",
Expand All @@ -58,6 +65,7 @@ def test_dexmimicgen_gr1_data_generation_success_rate():
run_subprocess(args, timeout_sec=TIMEOUT_SEC)
assert_valid_dataset(output_file, min_num_demos=1)
num_success, num_attempts = read_generation_result(result_file)
report = report_metrics(output_file, result_file)

assert num_attempts > 0, "generation reported zero attempts"
success_rate = num_success / num_attempts
Expand All @@ -66,6 +74,7 @@ def test_dexmimicgen_gr1_data_generation_success_rate():
f"data-gen success rate {success_rate:.1%} ({num_success}/{num_attempts}) is below the "
f"required threshold of {SUCCESS_RATE_THRESHOLD:.0%}"
)
assert_computed_metrics(report, DEXMIMICGEN_METRICS, optional=BENCHMARK_OPTIONAL_METRICS)


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
"""Data-generation success-rate perf test for the Franka cube-stack (MimicGen) task."""

import os
import tempfile

import pytest

from autodata_tests.utils.constants import TestPaths
from autodata_tests.utils.constants import BENCHMARK_OPTIONAL_METRICS, MIMICGEN_FRANKA_METRICS, TestPaths
from autodata_tests.utils.subprocess import run_subprocess
from autodata_tests.utils.utils import assert_valid_dataset, read_generation_result
from autodata_tests.utils.utils import (
assert_computed_metrics,
assert_valid_dataset,
benchmark_temp_dir,
read_generation_result,
report_metrics,
)

# --- Tunables (change these to adjust the perf test) ---------------------------------------------
SUCCESS_RATE_THRESHOLD = 0.30 # minimum acceptable data-gen success rate
Expand All @@ -24,8 +29,9 @@

@pytest.mark.with_subprocess
def test_mimicgen_franka_data_generation_success_rate():
"""Generate NUM_TRIALS demos on NUM_ENVS envs and assert the success rate exceeds the threshold."""
with tempfile.TemporaryDirectory() as temp_dir:
"""Generate NUM_TRIALS demos on NUM_ENVS envs, report their metrics and assert the success rate exceeds the
threshold."""
with benchmark_temp_dir("franka_cube_stack_mimicgen") as temp_dir:
output_file = os.path.join(temp_dir, "generated.hdf5")
result_file = os.path.join(temp_dir, "generation_result.json")

Expand All @@ -46,6 +52,7 @@ def test_mimicgen_franka_data_generation_success_rate():
output_file,
"--result_file",
result_file,
"--record_metric_inputs",
"--generation_num_trials",
str(NUM_TRIALS),
"--num_envs",
Expand All @@ -58,6 +65,7 @@ def test_mimicgen_franka_data_generation_success_rate():
run_subprocess(args, timeout_sec=TIMEOUT_SEC)
assert_valid_dataset(output_file, min_num_demos=1)
num_success, num_attempts = read_generation_result(result_file)
report = report_metrics(output_file, result_file)

assert num_attempts > 0, "generation reported zero attempts"
success_rate = num_success / num_attempts
Expand All @@ -66,6 +74,7 @@ def test_mimicgen_franka_data_generation_success_rate():
f"data-gen success rate {success_rate:.1%} ({num_success}/{num_attempts}) is below the "
f"required threshold of {SUCCESS_RATE_THRESHOLD:.0%}"
)
assert_computed_metrics(report, MIMICGEN_FRANKA_METRICS, optional=BENCHMARK_OPTIONAL_METRICS)


if __name__ == "__main__":
Expand Down
18 changes: 2 additions & 16 deletions autodata_tests/e2e/test_mimicgen_data_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,12 @@

import pytest

from autodata_tests.utils.constants import TestPaths
from autodata_tests.utils.constants import MIMICGEN_FRANKA_METRICS, TestPaths
from autodata_tests.utils.subprocess import run_subprocess
from autodata_tests.utils.utils import assert_ok_metrics, assert_recorded_run, assert_valid_dataset

HEADLESS = True
GENERATION_NUM_TRIALS = 2
# Metrics a MimicGen run recorded with --record_metric_inputs must compute; no camera, so no image checks.
METRICS = {
"generation_success_rate",
"demos_per_gpu_hour",
"time_to_dataset",
"correctness_pass_rate",
"final_success_rate",
"action_rotation_error",
"action_saturation",
"motion_smoothness",
"joint_limit_ratio",
"start_layout_spread",
"workspace_spread",
}


def _run_franka_cube_stack_mimicgen(num_envs: int, device: str) -> None:
Expand Down Expand Up @@ -66,7 +52,7 @@ def _run_franka_cube_stack_mimicgen(num_envs: int, device: str) -> None:

assert_valid_dataset(output_file, min_num_demos=GENERATION_NUM_TRIALS)
assert_recorded_run(output_file, result_file)
assert_ok_metrics(output_file, result_file, METRICS)
assert_ok_metrics(output_file, result_file, MIMICGEN_FRANKA_METRICS)


@pytest.mark.with_subprocess
Expand Down
28 changes: 28 additions & 0 deletions autodata_tests/utils/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,31 @@ def __init__(self):


TestPaths = _TestPaths()

# Metrics a run recorded with --record_metric_inputs must compute, per workflow, besides start_layout_spread and
# workspace_spread, which need two valid episodes. No workflow here records a camera, so no image checks.
MIMICGEN_FRANKA_METRICS = {
"generation_success_rate",
"demos_per_gpu_hour",
"time_to_dataset",
"correctness_pass_rate",
"final_success_rate",
"action_rotation_error",
"action_saturation",
"motion_smoothness",
"joint_limit_ratio",
}
# Absolute pose actions are not clipped (no action_saturation) and the GR1 and G1 configs give no hardware_limits
# (no joint_limit_ratio).
DEXMIMICGEN_METRICS = {
"generation_success_rate",
"demos_per_gpu_hour",
"time_to_dataset",
"correctness_pass_rate",
"final_success_rate",
"action_rotation_error",
"tracking_error",
"motion_smoothness",
}
# One hand step of over 8 cm in any of a benchmark's hundreds of episodes makes workspace_spread not applicable.
BENCHMARK_OPTIONAL_METRICS = frozenset({"workspace_spread"})
9 changes: 8 additions & 1 deletion autodata_tests/utils/test_generation_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import json
from pathlib import Path

from autodata_utils.generation_result import AttemptLog, attempts_file_for, write_generation_result
from autodata_utils.generation_result import AttemptLog, attempts_file_for, code_revision, write_generation_result


def test_write_generation_result_writes_completed_stats_atomically(tmp_path):
Expand Down Expand Up @@ -63,3 +63,10 @@ def test_rerun_with_the_same_result_file_keeps_the_earlier_attempt_log(tmp_path:

earlier = Path(attempts_file_for(result_file, "run-a")).read_text().splitlines()
assert [json.loads(line)["run_id"] for line in earlier] == ["run-a"]


def test_code_revision_without_git_is_the_image_revision(monkeypatch) -> None:
monkeypatch.setenv("PATH", "")
monkeypatch.setenv("AUTODATA_REVISION", "0123abcd")

assert code_revision() == "0123abcd"
71 changes: 62 additions & 9 deletions autodata_tests/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@

"""Shared assertion helpers for the AutoData test suite."""

import contextlib
import h5py
import json
import os
import shutil
import tempfile
from collections.abc import Iterator

from autodata_metrics.records import ATTEMPT, RESULT, parse, parse_env_args
from autodata_tests.utils.constants import TestPaths
Expand Down Expand Up @@ -92,13 +96,11 @@ def assert_recorded_run(dataset_file: str, result_file: str) -> list[dict]:
return attempts


def assert_ok_metrics(dataset_file: str, result_file: str, expected_ok: set[str]) -> None:
"""Report a generation run's metrics with ``validate_dataset.py``; assert every episode passes the checks and
exactly ``expected_ok`` computed a value, with ``start_layout_spread`` and ``workspace_spread`` too when the run
exported two episodes or more.
def report_metrics(dataset_file: str, result_file: str) -> dict:
"""Report a generation run's metrics with ``validate_dataset.py`` into ``report.json`` beside the dataset.

A renamed recorded key or an adapter that stops recording a stream turns a metric not applicable, which
this catches.
Returns:
The report.
"""

report_file = os.path.join(os.path.dirname(dataset_file), "report.json")
Expand All @@ -113,17 +115,68 @@ def assert_ok_metrics(dataset_file: str, result_file: str, expected_ok: set[str]
report_file,
])
with open(report_file, encoding="utf-8") as report_handle:
report = json.load(report_handle)
return json.load(report_handle)


def assert_ok_metrics(dataset_file: str, result_file: str, expected_ok: set[str]) -> None:
"""Report a generation run's metrics, assert every episode passes the checks, then
:func:`assert_computed_metrics`."""

report = report_metrics(dataset_file, result_file)
assert (
report["num_valid_episodes"] == report["num_episodes"]
), f"{report['num_episodes'] - report['num_valid_episodes']} episodes failed checks: {report['check_failures']}"
assert_computed_metrics(report, expected_ok)


def assert_computed_metrics(report: dict, expected_ok: set[str], optional: frozenset[str] = frozenset()) -> None:
"""Assert exactly ``expected_ok`` computed a value, with ``start_layout_spread`` and ``workspace_spread`` too when
two episodes or more are valid; the metrics in ``optional`` may compute or not.

A renamed recorded key or an adapter that stops recording a stream turns a metric not applicable, which
this catches.
"""

rows = report["metrics"]
ok = {name for name, row in rows.items() if row["status"] == "ok"}
ok = {name for name, row in rows.items() if row["status"] == "ok"} - optional
spreads = {"start_layout_spread", "workspace_spread"} if report["num_valid_episodes"] >= 2 else set()
expected = expected_ok | spreads
expected = (expected_ok | spreads) - optional
assert ok == expected, f"Computed {sorted(ok)}, expected {sorted(expected)}: {rows}"


@contextlib.contextmanager
def benchmark_temp_dir(name: str) -> Iterator[str]:
"""Yield a temporary directory for the benchmark ``name``. On exit, also after a failure, export its files other than
HDF5 datasets (the generation result, its attempt log and the metrics report) to ``$AUTODATA_BENCHMARK_DIR/<name>``
when that variable is set. A failed export fails a passing benchmark, but does not replace a failing one's error.
"""

with tempfile.TemporaryDirectory() as temp_dir:
try:
yield temp_dir
except BaseException:
with contextlib.suppress(OSError):
_export_benchmark_files(temp_dir, name)
raise
_export_benchmark_files(temp_dir, name)


def _export_benchmark_files(source_dir: str, name: str) -> None:
"""Replace ``$AUTODATA_BENCHMARK_DIR/<name>``, if that variable is set, with the files of ``source_dir`` other than
HDF5 datasets, so the directory never mixes two runs."""

if not os.environ.get("AUTODATA_BENCHMARK_DIR"):
return
export_dir = os.path.join(os.environ["AUTODATA_BENCHMARK_DIR"], name)
shutil.rmtree(export_dir, ignore_errors=True)
os.makedirs(export_dir)
for file_name in os.listdir(source_dir):
path = os.path.join(source_dir, file_name)
if os.path.isfile(path) and not file_name.endswith(".hdf5"):
# copyfile, not copy2: the result file is written 0600, and another user may upload the copy.
shutil.copyfile(path, os.path.join(export_dir, file_name))


def assert_no_metric_inputs(dataset_file: str) -> None:
"""Assert a dataset recorded without ``--record_metric_inputs`` has no metric inputs, as before they existed."""

Expand Down
22 changes: 12 additions & 10 deletions autodata_utils/generation_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,15 @@ def input_record(path: str | None) -> dict[str, str] | None:


def code_revision() -> str | None:
"""Git commit of the AutoData checkout, or None without git or outside a checkout."""
if shutil.which("git") is None:
return None
result = subprocess.run(
["git", "-C", str(Path(__file__).resolve().parent), "rev-parse", "HEAD"],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip() if result.returncode == 0 else None
"""Git commit of the AutoData checkout; without git or outside a checkout, ``$AUTODATA_REVISION`` (the commit an
image was built from), else None."""
if shutil.which("git") is not None:
result = subprocess.run(
["git", "-C", str(Path(__file__).resolve().parent), "rev-parse", "HEAD"],
capture_output=True,
text=True,
check=False,
)
if result.returncode == 0:
return result.stdout.strip()
return os.environ.get("AUTODATA_REVISION") or None
Loading
Loading