Skip to content
Closed
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
45 changes: 45 additions & 0 deletions docs/source/testing/micro_benchmarks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Run benchmarks using the Isaac Lab launcher:

# Run Articulation method benchmarks
uv run python source/isaaclab_physx/benchmark/assets/benchmark_articulation.py
uv run python source/isaaclab_newton/benchmark/assets/benchmark_articulation.py
uv run python source/isaaclab_ovphysx/benchmark/assets/benchmark_articulation.py

# With custom parameters
uv run python source/isaaclab_physx/benchmark/assets/benchmark_articulation.py \
Expand All @@ -50,6 +52,8 @@ Run benchmarks using the Isaac Lab launcher:

# Run Articulation method benchmarks
./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation.py
./isaaclab.sh -p source/isaaclab_newton/benchmark/assets/benchmark_articulation.py
./isaaclab.sh -p source/isaaclab_ovphysx/benchmark/assets/benchmark_articulation.py

# With custom parameters
./isaaclab.sh -p source/isaaclab_physx/benchmark/assets/benchmark_articulation.py \
Expand Down Expand Up @@ -107,6 +111,47 @@ These benchmark property accessors on data classes:

All benchmarks are located in ``source/isaaclab_physx/benchmark/assets/``.

Sensor Update Benchmarks
~~~~~~~~~~~~~~~~~~~~~~~~

The PhysX and OVPhysX sensor benchmarks build simulation scenes and measure sensor
updates separately from physics stepping:

.. list-table::
:header-rows: 1
:widths: 40 60

* - Benchmark File
- Sensor Path
* - ``benchmark_contact_sensor.py``
- Contact force collection
* - ``benchmark_frame_transformer.py``
- Source and target frame transforms
* - ``benchmark_imu_pva.py``
- IMU or PVA state estimation
* - ``benchmark_joint_wrench.py``
- Incoming joint wrench transforms
* - ``benchmark_ray_caster.py``
- Rigid-body tracking and ray casting

They are located in the ``benchmark/sensors/`` directories of ``isaaclab_physx``
and ``isaaclab_ovphysx``. Each script reports synchronized completion latency,
host submission latency, and a synchronized no-op observer floor. OVPhysX scripts
also isolate supported native reads and report the full-update-minus-read result
as an estimate. Physics ``sim.step()`` calls occur outside all timed regions.

The default ``summary`` formatter prints the aggregate results and writes a JSON
file containing the mean, sample standard deviation, sample count, p50, and p95.
The observer floor is reported but is not subtracted from the measurements.

For example:

.. code-block:: bash

./isaaclab.sh -p source/isaaclab_ovphysx/benchmark/sensors/benchmark_contact_sensor.py \
--num_envs 4096 --warmup_steps 50 --num_steps 500 \
--benchmark_formatter summary --output_path artifacts/micro_benchmarks

Command Line Arguments
----------------------

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Added
^^^^^

* Added shared synchronized latency sampling and structured reporting utilities
for micro-benchmarks.
14 changes: 14 additions & 0 deletions source/isaaclab/isaaclab/benchmark/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ __all__ = [
"MethodBenchmarkDefinition",
"MethodBenchmarkRunner",
"MethodBenchmarkRunnerConfig",
"LatencyBenchmarkRunner",
"LatencySample",
"LatencyStatistics",
"add_latency_measurements",
"measure_latency",
"summarize_latency",
"BooleanMeasurement",
"DictMeasurement",
"DictMetadata",
Expand Down Expand Up @@ -97,6 +103,14 @@ from .method_benchmark import (
MethodBenchmarkRunner,
MethodBenchmarkRunnerConfig,
)
from .micro import (
LatencyBenchmarkRunner,
LatencySample,
LatencyStatistics,
add_latency_measurements,
measure_latency,
summarize_latency,
)
from .measurements import (
BooleanMeasurement,
DictMeasurement,
Expand Down
232 changes: 232 additions & 0 deletions source/isaaclab/isaaclab/benchmark/micro.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause

"""Shared latency sampling and reporting for micro-benchmarks."""

from __future__ import annotations

import statistics
import time
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol

from .benchmark_core import BaseIsaacLabBenchmark
from .measurements import Measurement, SingleMeasurement, StatisticalMeasurement


class _MeasurementSink(Protocol):
"""Benchmark object that accepts measurements grouped by phase."""

def add_measurement(self, phase_name: str, measurement: Measurement | Sequence[Measurement]) -> None:
"""Add one or more measurements to a phase."""


@dataclass(frozen=True)
class LatencySample:
"""One host-submission and device-synchronized latency sample.

Attributes:
submission_s: Time [s] until the operation returned to the host.
synchronized_s: Time [s] until all submitted device work completed.
"""

submission_s: float
synchronized_s: float


@dataclass(frozen=True)
class LatencyStatistics:
"""Aggregate statistics for a latency sample series.

Attributes:
mean_s: Arithmetic mean latency [s].
std_s: Sample standard deviation [s], or zero for one sample.
p50_s: Linearly interpolated 50th percentile latency [s].
p95_s: Linearly interpolated 95th percentile latency [s].
n: Number of samples.
"""

mean_s: float
std_s: float
p50_s: float
p95_s: float
n: int


def measure_latency(
operation: Callable[[], None],
synchronize: Callable[[], None],
*,
clock_ns: Callable[[], int] | None = None,
) -> LatencySample:
"""Measure host submission and synchronized completion latency.

The pre-boundary synchronization prevents asynchronous work submitted before
:paramref:`operation` from being charged to the sample. The post-boundary
synchronization includes all device work submitted by the operation.

Args:
operation: Workload to measure.
synchronize: Function that blocks until pending device work completes.
clock_ns: Monotonic nanosecond clock. Defaults to :func:`time.perf_counter_ns`.

Returns:
Host-submission and device-synchronized latency [s].
"""
if clock_ns is None:
clock_ns = time.perf_counter_ns

synchronize()
start_ns = clock_ns()
operation()
submitted_ns = clock_ns()
synchronize()
finished_ns = clock_ns()
return LatencySample(
submission_s=(submitted_ns - start_ns) / 1e9,
synchronized_s=(finished_ns - start_ns) / 1e9,
)


def summarize_latency(samples_s: Sequence[float]) -> LatencyStatistics:
"""Summarize a non-empty latency sample series.

Args:
samples_s: Latency samples [s].

Returns:
Mean, sample standard deviation, and interpolated percentiles [s].

Raises:
ValueError: If :paramref:`samples_s` is empty.
"""
if not samples_s:
raise ValueError("Latency statistics require at least one sample.")
return LatencyStatistics(
mean_s=statistics.mean(samples_s),
std_s=statistics.stdev(samples_s) if len(samples_s) > 1 else 0.0,
p50_s=_percentile(samples_s, 0.50),
p95_s=_percentile(samples_s, 0.95),
n=len(samples_s),
)


def add_latency_measurements(
benchmark: _MeasurementSink,
phase_name: str,
name: str,
samples_s: Sequence[float],
) -> LatencyStatistics:
"""Add latency mean, standard deviation, and percentiles to a benchmark.

Args:
benchmark: Benchmark receiving the measurements.
phase_name: Phase that owns the measurements.
name: Base measurement name.
samples_s: Latency samples [s].

Returns:
Computed latency statistics [s].
"""
stats = summarize_latency(samples_s)
benchmark.add_measurement(
phase_name,
measurement=StatisticalMeasurement(
name=name,
mean=stats.mean_s * 1000.0,
std=stats.std_s * 1000.0,
n=stats.n,
unit="ms",
),
)
benchmark.add_measurement(
phase_name,
measurement=SingleMeasurement(name=f"{name} p50", value=stats.p50_s * 1000.0, unit="ms"),
)
benchmark.add_measurement(
phase_name,
measurement=SingleMeasurement(name=f"{name} p95", value=stats.p95_s * 1000.0, unit="ms"),
)
return stats


def _percentile(samples: Sequence[float], fraction: float) -> float:
"""Return a linearly interpolated percentile from a non-empty series."""
ordered = sorted(samples)
position = (len(ordered) - 1) * fraction
lower = int(position)
upper = min(lower + 1, len(ordered) - 1)
return ordered[lower] + (position - lower) * (ordered[upper] - ordered[lower])


class LatencyBenchmarkRunner(BaseIsaacLabBenchmark):
"""One-shot runner for latency micro-benchmarks.

Args:
benchmark_name: Name used in output metadata and filenames.
formatter_type: Formatter used to report results.
output_path: Directory for result files.
metadata: Workload metadata stored with the result.
use_recorders: Whether to collect hardware and version information.
"""

def __init__(
self,
benchmark_name: str,
formatter_type: str,
output_path: str,
metadata: dict[str, str | int | float | dict] | None = None,
use_recorders: bool = True,
) -> None:
workflow_metadata = {"metadata": [{"name": name, "data": value} for name, value in (metadata or {}).items()]}
super().__init__(
benchmark_name=benchmark_name,
formatter_type=formatter_type,
output_path=output_path,
output_prefix=benchmark_name,
workflow_metadata=workflow_metadata,
use_recorders=use_recorders,
)

def add_latency_samples(self, phase_name: str, samples: Sequence[LatencySample]) -> LatencyStatistics:
"""Add synchronized completion and host submission latency series.

Args:
phase_name: Phase that owns the measurements.
samples: Paired host and synchronized latency samples [s].

Returns:
Synchronized completion latency statistics [s].
"""
synchronized_stats = add_latency_measurements(
self, phase_name, "Synchronized Completion", [sample.synchronized_s for sample in samples]
)
add_latency_measurements(self, phase_name, "Host Submission", [sample.submission_s for sample in samples])
return synchronized_stats

def add_synchronized_samples(self, phase_name: str, name: str, samples_s: Sequence[float]) -> LatencyStatistics:
"""Add a synchronized-only latency series.

Args:
phase_name: Phase that owns the measurements.
name: Measurement name.
samples_s: Synchronized latency samples [s].

Returns:
Synchronized latency statistics [s].
"""
return add_latency_measurements(self, phase_name, name, samples_s)

def finalize(self) -> tuple[Path, ...]:
"""Sample recorders and write results.

Returns:
Paths written by the selected formatters.
"""
if self._use_recorders:
self.update_manual_recorders()
return super().finalize()
Loading
Loading