File size: 13,317 Bytes
d6b3397 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | # 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
"""Script to profile IsaacLab startup phases with cProfile.
Each startup stage (app launch, python imports, env creation, first step) is
wrapped in its own cProfile session. The top functions by own-time are emitted
as SingleMeasurement entries (both own-time and cumulative time) via the
standard benchmark backend.
"""
import argparse
import cProfile
import os
import sys
import time
from isaaclab.app import AppLauncher
from isaaclab_tasks.utils import setup_preset_cli
# -- CLI arguments -----------------------------------------------------------
parser = argparse.ArgumentParser(description="Profile IsaacLab startup phases.")
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, required=True, help="Name of the task.")
parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment")
parser.add_argument(
"--top_n",
type=int,
default=None,
help="Number of top functions per phase (default: 30, or 5 with --whitelist_config).",
)
parser.add_argument(
"--benchmark_backend",
type=str,
default="omniperf",
choices=[
"json",
"osmo",
"omniperf",
"summary",
"LocalLogMetrics",
"JSONFileMetrics",
"OsmoKPIFile",
"OmniPerfKPIFile",
],
help="Benchmarking backend options, defaults omniperf",
)
parser.add_argument("--output_path", type=str, default=".", help="Path to output benchmark results.")
parser.add_argument(
"--whitelist_config",
type=str,
default=None,
help="Path to YAML file with per-phase function whitelist patterns. Overrides --top_n for listed phases.",
)
# append AppLauncher cli args (provides --device, --headless, etc.)
AppLauncher.add_app_launcher_args(parser)
args_cli, hydra_args = setup_preset_cli(parser)
sys.argv = [sys.argv[0]] + hydra_args
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../.."))
from isaaclab.test.benchmark import BaseIsaacLabBenchmark, SingleMeasurement
from isaaclab.utils.timer import Timer, TimerError
from scripts.benchmarks.utils import (
get_backend_type,
get_preset_string,
parse_cprofile_stats,
)
# -- Python imports (profiled) ------------------------------------------------
imports_profile = cProfile.Profile()
imports_time_begin = time.perf_counter_ns()
imports_profile.enable()
import gymnasium as gym # noqa: E402
import numpy as np # noqa: E402
import torch # noqa: E402
from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg # noqa: E402
from isaaclab_tasks.utils import launch_simulation, resolve_task_config # noqa: E402
imports_profile.disable()
if torch.cuda.is_available() and torch.cuda.is_initialized():
torch.cuda.synchronize()
imports_time_end = time.perf_counter_ns()
# -- Resolve task config (profiled) ------------------------------------------
task_config_profile = cProfile.Profile()
task_config_time_begin = time.perf_counter_ns()
task_config_profile.enable()
env_cfg, _agent_cfg = resolve_task_config(args_cli.task, None)
task_config_profile.disable()
task_config_time_end = time.perf_counter_ns()
# -- Detect IsaacLab source prefixes for filtering ---------------------------
_REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
_source_dir = os.path.join(_REPO_ROOT, "source")
if os.path.isdir(_source_dir):
_ISAACLAB_PREFIXES = [
os.path.join(_source_dir, d) for d in os.listdir(_source_dir) if os.path.isdir(os.path.join(_source_dir, d))
]
else:
print(f"[WARNING] IsaacLab source directory not found at '{_source_dir}'. Function-level profiling will be empty.")
_ISAACLAB_PREFIXES = []
# -- Load whitelist config if provided ---------------------------------------
_WHITELIST: dict[str, list[str]] = {}
if args_cli.whitelist_config is not None:
import yaml
try:
with open(args_cli.whitelist_config) as f:
raw = yaml.safe_load(f)
except OSError as e:
print(f"[ERROR] Cannot read whitelist config '{args_cli.whitelist_config}': {e}")
sys.exit(1)
except yaml.YAMLError as e:
print(f"[ERROR] Invalid YAML in whitelist config '{args_cli.whitelist_config}': {e}")
sys.exit(1)
if raw is None:
_WHITELIST = {}
elif not isinstance(raw, dict):
print(
f"[ERROR] Whitelist config must be a YAML mapping (got {type(raw).__name__})."
" Expected format: phase_name: [pattern, ...]"
)
sys.exit(1)
else:
_VALID_PHASES = {"app_launch", "python_imports", "task_config", "env_creation", "first_step"}
unknown_phases = set(raw.keys()) - _VALID_PHASES
if unknown_phases:
print(
f"[WARNING] Whitelist config contains unknown phase(s): {unknown_phases}. "
f"Valid phases: {_VALID_PHASES}. Check for typos."
)
for phase_name, patterns in raw.items():
if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns):
print(
f"[ERROR] Whitelist phase '{phase_name}' must be a list of strings, "
f"got {type(patterns).__name__}. Check YAML formatting (use '- pattern' syntax)."
)
sys.exit(1)
_WHITELIST = raw
# Resolve top_n default: 5 when using whitelist (fallback phases stay compact), 30 otherwise
if args_cli.top_n is None:
args_cli.top_n = 5 if _WHITELIST else 30
# -- Create the benchmark instance ------------------------------------------
env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed
backend_type = get_backend_type(args_cli.benchmark_backend)
benchmark = BaseIsaacLabBenchmark(
benchmark_name="benchmark_startup",
backend_type=backend_type,
output_path=args_cli.output_path,
use_recorders=True,
output_prefix=f"benchmark_startup_{args_cli.task}",
workflow_metadata={
"metadata": [
{"name": "task", "data": args_cli.task},
{"name": "seed", "data": args_cli.seed},
{"name": "num_envs", "data": args_cli.num_envs},
{"name": "top_n", "data": args_cli.top_n},
{"name": "presets", "data": get_preset_string(hydra_args)},
]
},
)
# -- Main profiling logic ---------------------------------------------------
def main(
env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg,
app_launch_profile: cProfile.Profile,
app_launch_wall_ms: float,
):
"""Profile env creation and first step, then log all phase measurements.
Args:
env_cfg: Resolved environment configuration for the task.
app_launch_profile: cProfile session from the app-launch phase.
app_launch_wall_ms: Wall-clock duration of the app-launch phase [ms].
"""
# Override config with CLI args
env_cfg.scene.num_envs = args_cli.num_envs if args_cli.num_envs is not None else env_cfg.scene.num_envs
env_cfg.sim.device = args_cli.device if args_cli.device is not None else env_cfg.sim.device
env_cfg.seed = args_cli.seed if args_cli.seed is not None else env_cfg.seed
# -- Env creation (gym.make + env.reset) profiled ---------------------------
env = None
env_creation_profile = cProfile.Profile()
env_creation_time_begin = time.perf_counter_ns()
env_creation_profile.enable()
try:
env = gym.make(args_cli.task, cfg=env_cfg)
env.reset()
finally:
env_creation_profile.disable()
try:
if torch.cuda.is_available() and torch.cuda.is_initialized():
torch.cuda.synchronize()
env_creation_time_end = time.perf_counter_ns()
# -- First step profiled ------------------------------------------------
# Sample random actions from the action space directly to support
# Box, Discrete, MultiDiscrete, and Dict spaces.
np_actions = np.stack([env.unwrapped.single_action_space.sample() for _ in range(env.unwrapped.num_envs)])
actions = torch.as_tensor(np_actions, dtype=torch.float32, device=env.unwrapped.device)
first_step_profile = cProfile.Profile()
first_step_time_begin = time.perf_counter_ns()
first_step_profile.enable()
try:
with torch.inference_mode():
env.step(actions)
finally:
first_step_profile.disable()
if torch.cuda.is_available() and torch.cuda.is_initialized():
torch.cuda.synchronize()
first_step_time_end = time.perf_counter_ns()
# -- Parse all profiles and log measurements ----------------------------
imports_wall_ms = (imports_time_end - imports_time_begin) / 1e6
task_config_wall_ms = (task_config_time_end - task_config_time_begin) / 1e6
env_creation_wall_ms = (env_creation_time_end - env_creation_time_begin) / 1e6
first_step_wall_ms = (first_step_time_end - first_step_time_begin) / 1e6
# Collect Timer-based sub-timings for env_creation phase (may not exist for all environment types)
scene_creation_ms = None
try:
scene_creation_ms = Timer.get_timer_info("scene_creation") * 1000
except TimerError:
print("[INFO] Timer 'scene_creation' not available; sub-timing will be omitted.")
simulation_start_ms = None
try:
simulation_start_ms = Timer.get_timer_info("simulation_start") * 1000
except TimerError:
print("[INFO] Timer 'simulation_start' not available; sub-timing will be omitted.")
phases = {
"app_launch": {
"profile": app_launch_profile,
"wall_clock_ms": app_launch_wall_ms,
"extra_measurements": [],
},
"python_imports": {
"profile": imports_profile,
"wall_clock_ms": imports_wall_ms,
"extra_measurements": [],
},
"task_config": {
"profile": task_config_profile,
"wall_clock_ms": task_config_wall_ms,
"extra_measurements": [],
},
"env_creation": {
"profile": env_creation_profile,
"wall_clock_ms": env_creation_wall_ms,
"extra_measurements": [
(name, val)
for name, val in [
("Scene Creation Time", scene_creation_ms),
("Simulation Start Time", simulation_start_ms),
]
if val is not None
],
},
"first_step": {
"profile": first_step_profile,
"wall_clock_ms": first_step_wall_ms,
"extra_measurements": [],
},
}
# Parse profiles and log measurements to benchmark
for phase_name, phase_data in phases.items():
phase_whitelist = _WHITELIST.get(phase_name)
functions = parse_cprofile_stats(
phase_data["profile"], _ISAACLAB_PREFIXES, top_n=args_cli.top_n, whitelist=phase_whitelist
)
wall_ms = phase_data["wall_clock_ms"]
extras = phase_data["extra_measurements"]
# Log wall-clock time
benchmark.add_measurement(
phase_name, measurement=SingleMeasurement(name="Wall Clock Time", value=wall_ms, unit="ms")
)
# Log extra sub-timings
for extra_name, extra_val in extras:
benchmark.add_measurement(
phase_name, measurement=SingleMeasurement(name=extra_name, value=extra_val, unit="ms")
)
# Log per-function measurements (tottime + cumtime)
for label, tottime_ms, cumtime_ms in functions:
benchmark.add_measurement(
phase_name, measurement=SingleMeasurement(name=label, value=round(tottime_ms, 2), unit="ms")
)
benchmark.add_measurement(
phase_name,
measurement=SingleMeasurement(name=f"{label} (cumtime)", value=round(cumtime_ms, 2), unit="ms"),
)
# Finalize benchmark output
benchmark.update_manual_recorders()
benchmark._finalize_impl()
finally:
if env is not None:
env.close()
if __name__ == "__main__":
# -- App launch (profiled) --------------------------------------------------
app_launch_profile = cProfile.Profile()
app_launch_time_begin = time.perf_counter_ns()
app_launch_profile.enable()
with launch_simulation(env_cfg, args_cli):
app_launch_profile.disable()
if torch.cuda.is_available() and torch.cuda.is_initialized():
torch.cuda.synchronize()
app_launch_time_end = time.perf_counter_ns()
app_launch_wall_ms = (app_launch_time_end - app_launch_time_begin) / 1e6
main(env_cfg, app_launch_profile, app_launch_wall_ms)
|