Skip to content
Draft
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
@@ -0,0 +1 @@
* Added per-replay control step and OVXR frame submission intervals to the teleoperation replay JSON report.
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
again. The USD stage is loaded only once.

Stats output:
The wall-clock deltas between successive ``env.sim.render()`` calls
For Kit, the wall-clock deltas between successive ``env.sim.render()`` calls
produced during the active window are recorded as a per-rendered-frame
interval series (N gated renders produce N-1 samples). Pre-START
render-only frames, warmup ticks, and post-quit render-only
Expand All @@ -109,10 +109,12 @@
remaining replays never start and no stdout summary or JSON file
is written. Partial reports are never emitted: CI relies on
"no JSON output" as an unambiguous failure signal.
OVXR owns rendering independently, so application render-call timing
statistics remain empty for OVXR replays. A kitless replay without
``--ovxr`` has no application render loop either; it reports its
outcome with the same empty timing statistics.
Every replay reports ``control_frame_time_ms``, measured between
successive completed control steps. OVXR replay also reports
``render_frame_time_ms``, measured between successful frame submissions
on the render worker during the active replay window. Kitless replay
leaves Kit's ``cpu_frame_time_ms`` and ``fps`` series empty. Without
``--ovxr``, the OVXR render series is also empty.

Each active iteration also emits one ``GpuStatsProvider.sample()``
call. The default :class:`NvmlGpuStatsProvider` snapshots GPU
Expand Down Expand Up @@ -183,6 +185,8 @@
"fps": { # per-render rate (matches simulator HUD)
"mean": ..., "min_instantaneous": ..., "max_instantaneous": ...
},
"control_frame_time_ms": {<cpu_frame_time_ms shape>},
"render_frame_time_ms": {<cpu_frame_time_ms shape>},
"gpu_stats": {
"backend": "nvml", "available": True,
"device_index": 0, "device_name": ..., "memory_total_mb": ...,
Expand Down Expand Up @@ -289,10 +293,12 @@
import signal
import statistics
import sys
import threading
import time
from collections.abc import Sequence
from contextlib import contextmanager
from dataclasses import dataclass, field
from itertools import pairwise
from pathlib import Path
from typing import TYPE_CHECKING, Protocol, runtime_checkable

Expand Down Expand Up @@ -552,6 +558,32 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
keys) do not require a bump."""


class _SubmittedFrameTimings:
"""Collect render-worker submission intervals during one replay."""

def __init__(self) -> None:
self._lock = threading.Lock()
self._timestamps: list[float] | None = None

def start(self) -> None:
with self._lock:
self._timestamps = []

def record_submission(self) -> None:
with self._lock:
if self._timestamps is not None:
self._timestamps.append(time.perf_counter())

def finish(self, end_s: float | None) -> list[float]:
# Detach the buffer before calculating intervals so the render worker can continue.
with self._lock:
timestamps, self._timestamps = self._timestamps or [], None
if end_s is None:
return []
active = (timestamp for timestamp in timestamps if timestamp <= end_s)
return [(end - start) * 1000.0 for start, end in pairwise(active)]


@dataclass
class _RunStats:
"""Per-replay performance + outcome record.
Expand All @@ -578,6 +610,8 @@ class _RunStats:

outcome: str = "incomplete" # "success" | "failure" | "incomplete" | "timeout"
active_frame_times_ms: list[float] = field(default_factory=list)
control_frame_times_ms: list[float] = field(default_factory=list)
render_frame_times_ms: list[float] = field(default_factory=list)
active_iterations: int = 0
rejected_action_frames: int = 0
last_action_rejection: str | None = None
Expand All @@ -603,6 +637,8 @@ def to_dict(self, run_index: int) -> dict:
"success_step_count": self.success_step_count,
"cpu_frame_time_ms": _compute_frame_stats(self.active_frame_times_ms),
"fps": _compute_fps_stats(self.active_frame_times_ms),
"control_frame_time_ms": _compute_frame_stats(self.control_frame_times_ms),
"render_frame_time_ms": _compute_frame_stats(self.render_frame_times_ms),
"gpu_stats": self.gpu_stats,
"input_exhausted": self.input_exhausted,
"replay_complete": self.replay_complete,
Expand All @@ -611,7 +647,7 @@ def to_dict(self, run_index: int) -> dict:


def _compute_frame_stats(samples_ms: list[float]) -> dict:
"""Compute summary stats for a list of per-frame CPU times (in ms).
"""Compute summary stats for a list of frame intervals (in ms).

Uses :func:`statistics.quantiles` with ``n=100, method="inclusive"`` so
the result is a stable in-process measurement with no numpy dependency.
Expand Down Expand Up @@ -1436,6 +1472,7 @@ def _run_single_replay( # noqa: C901
teleop_interface: "IsaacTeleopDevice",
presentation: OvxrPresentation | None = None,
recorded_hand_frames: int | None = None,
submitted_frame_timings: _SubmittedFrameTimings | None = None,
) -> _RunStats:
"""Run a single replay pass against ``env`` and return the per-run stats.

Expand Down Expand Up @@ -1466,6 +1503,7 @@ def _run_single_replay( # noqa: C901
recorded_hand_frames: With ``--require_hand_replay_data``, the capture's hand frame count from
:func:`_count_recorded_hand_frames`: the run ends once that many frames were read, which
requires synchronous retargeting. ``None`` disables that end.
submitted_frame_timings: OVXR render worker callback's timestamp collector, if configured.
"""
stats = _RunStats(recorded_hand_frames=recorded_hand_frames)

Expand Down Expand Up @@ -1670,6 +1708,8 @@ def _patched_sim_render():
iter_start_s = time.perf_counter()
if active_start_s is None:
active_start_s = iter_start_s
if submitted_frame_timings is not None:
submitted_frame_timings.start()
if recorded_hand_frames is not None:
# The first applied action has no predecessor and is not a change.
if previous_action is not None and not torch.equal(previous_action, action):
Expand All @@ -1681,7 +1721,10 @@ def _patched_sim_render():
_, _, terminated, truncated, _ = env.step(actions)
finally:
sampling_active[0] = False
last_active_end_s = time.perf_counter()
step_end_s = time.perf_counter()
if last_active_end_s is not None:
stats.control_frame_times_ms.append((step_end_s - last_active_end_s) * 1000.0)
last_active_end_s = step_end_s
stats.active_iterations += 1
if presentation is not None:
presentation.publish(env, changed=True)
Expand Down Expand Up @@ -1750,6 +1793,8 @@ def _patched_sim_render():
# the first active frame).
if active_start_s is not None and last_active_end_s is not None:
stats.active_duration_s = last_active_end_s - active_start_s
if submitted_frame_timings is not None:
stats.render_frame_times_ms = submitted_frame_timings.finish(last_active_end_s)
stats.success_step_count = success_step_count
stats.gpu_stats = gpu_stats_provider.summary()

Expand Down Expand Up @@ -1883,6 +1928,7 @@ def _run_replay_batch(
cloudxr_launcher = None
teleop_interface = None
presentation = None
submitted_frame_timings = None
previous_handlers = {}
shutting_down = False
all_runs: list[_RunStats] = []
Expand All @@ -1906,6 +1952,8 @@ def _run_replay_batch(
application_name=f"isaaclab-ovxr-replay-{args_cli.task}",
camera_feeds=selected_cameras,
)
submitted_frame_timings = _SubmittedFrameTimings()
presentation.session.set_frame_submitted_callback(submitted_frame_timings.record_submission)

def request_shutdown(_signum, _frame):
nonlocal shutting_down
Expand Down Expand Up @@ -1969,6 +2017,7 @@ def install_shutdown_handlers() -> None:
teleop_interface=teleop_interface,
presentation=presentation,
recorded_hand_frames=recorded_hand_frames,
submitted_frame_timings=submitted_frame_timings,
)
all_runs.append(run_stats)
print(f"Replay {run_idx + 1}/{args_cli.num_replays} outcome: {run_stats.outcome}")
Expand Down
17 changes: 16 additions & 1 deletion source/isaaclab_teleop/isaaclab_teleop/ov_libraries_xr.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ def __init__(self, bootstrap: OvxrSessionBootstrap, cfg: OvLibrariesXrCfg) -> No
self._close_started = False
self._stop_handled = False
self._physics_rate = _CounterRate()
self._frame_submitted_callback: Callable[[], None] | None = None

def __enter__(self) -> OvLibrariesXrSession:
self._require_open()
Expand All @@ -145,6 +146,13 @@ def shutdown_requested(self) -> bool:
"""Whether the OVXR session requested application shutdown."""
return self._owner is not None and self._owner.shutdown_requested

def set_frame_submitted_callback(self, callback: Callable[[], None]) -> None:
"""Register before startup. OVXR calls the callback on its render worker after each successful submission."""
self._require_open()
if self._owner is not None:
raise RuntimeError("Frame submission callbacks must be registered before OVXR starts")
self._frame_submitted_callback = callback

def start_render_worker(
self,
env: Any,
Expand Down Expand Up @@ -206,6 +214,7 @@ def start_render_worker(
self._cfg,
excluded_visual_meshes,
external_anchor_state,
on_frame_submitted=self._frame_submitted_callback,
)
self._host = host
self._owner = OvxrSession(
Expand Down Expand Up @@ -673,6 +682,8 @@ def __init__(
cfg: OvLibrariesXrCfg,
excluded_visual_meshes: Iterable[str] = (),
external_anchor_state: OvLibrariesXrSession.ExternalAnchorState | None = None,
*,
on_frame_submitted: Callable[[], None] | None = None,
) -> None:
self._bootstrap = bootstrap
self._env = env
Expand All @@ -685,6 +696,7 @@ def __init__(
self._last_published_ordinal: int | None = None
self._publication_closed = False
self._camera_feeds = cfg.camera_feeds
self._on_frame_submitted = on_frame_submitted
self.desktop_mirror = None
self._external_anchor = external_anchor_state
self._anchor_snapshot: tuple[int, np.ndarray] | None = None
Expand Down Expand Up @@ -774,13 +786,16 @@ def attach_on_render_thread(self, capability: object) -> OvxrSessionBinding:
camera_products=tuple(MirrorProduct(panel.render_product_path, panel.label) for panel in panels),
)
consumers.append(self.desktop_mirror)
return OvxrSessionBinding(
binding = OvxrSessionBinding(
renderer=self._lease.ovrtx_renderer,
stage=self._lease.ovstage,
ordinal_ledger=self._ordinal_ledger,
frame_consumers=tuple(consumers),
prepare_frame_scene=self.prepare_frame_scene if self._external_anchor is not None else None,
)
if self._on_frame_submitted is not None:
binding = replace(binding, on_frame_submitted=self._on_frame_submitted)
return binding

def publication_guard(self) -> contextlib.AbstractContextManager[None]:
return self._publication_lock
Expand Down
33 changes: 31 additions & 2 deletions source/isaaclab_teleop/test/test_teleop_replay_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import builtins
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
from types import ModuleType, SimpleNamespace
from unittest.mock import Mock

Expand Down Expand Up @@ -224,7 +225,9 @@ def clear_context():
monkeypatch.setattr(SimulationContext, "clear_instance", clear_context)
handlers = {}
reports = []
session = SimpleNamespace(shutdown_requested=False, request_shutdown=lambda: None)
session = SimpleNamespace(
shutdown_requested=False, request_shutdown=lambda: None, set_frame_submitted_callback=lambda _: None
)

class Presentation:
@classmethod
Expand Down Expand Up @@ -587,7 +590,33 @@ def run():
else:
stats = run()
assert stats.active_iterations == 3
assert not stats.active_frame_times_ms
report = stats.to_dict(1)
assert report["control_frame_time_ms"]["n"] == 2
assert report["cpu_frame_time_ms"]["n"] == 0
assert report["render_frame_time_ms"]["n"] == 0


def test_render_submissions_are_scoped_to_one_active_replay(monkeypatch):
"""A warmup or late submission cannot skew the current or next replay's render intervals."""
from isaaclab_teleop.entrypoints import teleop_replay_agent as replay

timestamp = 0.0
monkeypatch.setattr(replay, "time", SimpleNamespace(perf_counter=lambda: timestamp))
timings = replay._SubmittedFrameTimings()

with ThreadPoolExecutor(max_workers=1) as render_worker:
render_worker.submit(timings.record_submission).result(timeout=5.0)
timings.start()
for timestamp in (0.125, 0.250, 0.500):
render_worker.submit(timings.record_submission).result(timeout=5.0)
assert timings.finish(0.375) == [125.0]

timestamp = 0.625
render_worker.submit(timings.record_submission).result(timeout=5.0)
timings.start()
timestamp = 0.750
render_worker.submit(timings.record_submission).result(timeout=5.0)
assert timings.finish(1.0) == []


def test_replay_renderer_startup_shares_the_cold_start_bound():
Expand Down
Loading