tract / scripts /test_evaluate2_cpu_usage.py
zhicao's picture
Initial release of TrAct (code only)
4341630 verified
Raw History Blame Contribute Delete
11.7 kB
#!/usr/bin/env python3
"""Compare evaluate2 CPU profiles: single-thread vs auto idle threads.
Runs each profile in a fresh subprocess (OpenBLAS reads OMP_* at import time).
Usage:
cd .
.venv/bin/python scripts/test_evaluate2_cpu_usage.py
.venv/bin/python scripts/test_evaluate2_cpu_usage.py --skip-libero
CUDA_VISIBLE_DEVICES=2 .venv/bin/python scripts/test_evaluate2_cpu_usage.py --suite libero_10_task --task-index 4
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
OPENPI_ROOT = Path(__file__).resolve().parents[1]
def _parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Benchmark evaluate2 CPU auto vs single-thread")
p.add_argument(
"--profiles",
nargs="+",
default=["single", "auto"],
choices=["single", "auto"],
help="Profiles to compare (each in a fresh subprocess)",
)
p.add_argument("--blas-iters", type=int, default=4, help="Large matmul repetitions")
p.add_argument("--libero-steps", type=int, default=40, help="MuJoCo steps per env bench")
p.add_argument("--skip-libero", action="store_true", help="Only run NumPy/BLAS bench (fast)")
p.add_argument("--suite", type=str, default="libero_10_task")
p.add_argument("--task-index", type=int, default=4)
p.add_argument("--resolution", type=int, default=256)
p.add_argument("--bind-numa-to-gpu", action="store_true", help="Match evaluate2 --bind-cpu-numa-to-gpu")
p.add_argument("--worker", choices=["single", "auto"], help=argparse.SUPPRESS)
return p.parse_args()
def _run_worker(
profile: str,
*,
blas_iters: int,
libero_steps: int,
skip_libero: bool,
suite: str,
task_index: int,
resolution: int,
bind_numa: bool,
) -> dict:
cmd = [
sys.executable,
str(Path(__file__).resolve()),
"--worker",
profile,
"--blas-iters",
str(blas_iters),
"--libero-steps",
str(libero_steps),
"--suite",
suite,
"--task-index",
str(task_index),
"--resolution",
str(resolution),
]
if skip_libero:
cmd.append("--skip-libero")
if bind_numa:
cmd.append("--bind-numa-to-gpu")
env = os.environ.copy()
proc = subprocess.run(
cmd,
cwd=str(OPENPI_ROOT),
env=env,
capture_output=True,
text=True,
check=False,
)
if proc.returncode != 0:
sys.stderr.write(proc.stderr)
raise RuntimeError(f"Worker {profile} failed (exit {proc.returncode})")
line = proc.stdout.strip().splitlines()[-1]
return json.loads(line)
def _cpus_allowed() -> list[int]:
if hasattr(os, "sched_getaffinity"):
return sorted(os.sched_getaffinity(0))
n = os.cpu_count() or 1
return list(range(n))
def _estimate_idle(cpus: list[int]) -> int:
n = max(1, len(cpus))
try:
return max(1, n - int(os.getloadavg()[0]))
except OSError:
return n
def _numa_cpus_for_visible_gpu() -> list[int]:
allowed = _cpus_allowed()
visible = os.environ.get("CUDA_VISIBLE_DEVICES", "").strip()
if not visible or not visible.split(",")[0].strip().isdigit():
return allowed
gpu = int(visible.split(",")[0].strip())
half = max(1, (max(allowed) + 1) // 2)
if gpu < 4:
return [c for c in allowed if c < half]
return [c for c in allowed if c >= half]
def _apply_profile(profile: str, *, bind_numa: bool) -> dict[str, int | str]:
cpus = _numa_cpus_for_visible_gpu() if bind_numa else _cpus_allowed()
if bind_numa and hasattr(os, "sched_setaffinity"):
os.sched_setaffinity(0, cpus)
n_allowed = len(cpus)
n_idle = _estimate_idle(cpus)
if profile == "single":
n_threads = 1
else:
n_threads = n_idle
for key in (
"OMP_NUM_THREADS",
"OPENBLAS_NUM_THREADS",
"MKL_NUM_THREADS",
"NUMEXPR_NUM_THREADS",
"VECLIB_MAXIMUM_THREADS",
"OMP_THREAD_LIMIT",
):
os.environ[key] = str(n_threads)
meta = {
"profile": profile,
"threads": n_threads,
"affinity_cpus": n_allowed,
"idle_estimate": n_idle,
"bind_numa_to_gpu": bind_numa,
}
try:
meta["loadavg1"] = round(float(os.getloadavg()[0]), 2)
except OSError:
pass
return meta
def _sample_cpu_percent(duration_s: float = 0.4) -> float:
pid = os.getpid()
samples: list[float] = []
import time
t_end = time.perf_counter() + duration_s
while time.perf_counter() < t_end:
try:
out = subprocess.check_output(
["ps", "-p", str(pid), "-o", "%cpu="],
text=True,
stderr=subprocess.DEVNULL,
)
samples.append(float(out.strip()))
except (subprocess.CalledProcessError, ValueError):
pass
time.sleep(0.05)
return max(samples) if samples else 0.0
def _bench_blas(iters: int) -> tuple[float, float]:
import time
import numpy as np
n = 4096
rng = np.random.default_rng(0)
a = rng.standard_normal((n, n), dtype=np.float32)
b = rng.standard_normal((n, n), dtype=np.float32)
# warmup
_ = a @ b
t0 = time.perf_counter()
cpu_peak = 0.0
for _ in range(iters):
_ = a @ b
cpu_peak = max(cpu_peak, _sample_cpu_percent(0.15))
elapsed = time.perf_counter() - t0
return elapsed, cpu_peak
def _bench_libero(*, suite: str, task_index: int, steps: int, resolution: int) -> tuple[float, float, float]:
import time
import numpy as np
sys.path[:0] = [
str(OPENPI_ROOT / "third_party"),
str(OPENPI_ROOT / "third_party" / "libero"),
]
os.environ.setdefault("LIBERO_CONFIG_PATH", str(OPENPI_ROOT / ".libero_local"))
from libero.libero import benchmark as libero_benchmark
from libero.libero import get_libero_path
from libero.libero.envs import OffScreenRenderEnv
from libero.libero.envs.mesh_vertex_tracker import MeshVertexTracker
from libero.libero.envs.mesh_vertex_wrapper import MeshVertexWrapper
bench = libero_benchmark.get_benchmark_dict()[suite]()
task = bench.get_task(task_index)
bddl = Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file
act = [0.0] * 6 + [-1.0]
def plain_env():
env = OffScreenRenderEnv(
bddl_file_name=bddl,
camera_heights=resolution,
camera_widths=resolution,
)
env.reset()
t0 = time.perf_counter()
for _ in range(steps):
env.step(act)
dt = time.perf_counter() - t0
env.close()
return dt
def mesh_env():
env = OffScreenRenderEnv(
bddl_file_name=bddl,
camera_heights=resolution,
camera_widths=resolution,
)
env = MeshVertexWrapper(env, max_points=10000, include_non_mesh_geoms=True)
env = MeshVertexTracker(
env,
agentview_vertex_ids=[3001, 3004, 3014, 3067, 3040, 3081, 2898],
eye_in_hand_vertex_ids=[2955, 3055, 3040, 2981, 2966, 3052, 3022],
img_height=resolution,
img_width=resolution,
)
env.reset()
t0 = time.perf_counter()
for _ in range(steps):
env.step(act)
dt = time.perf_counter() - t0
env.close()
return dt
t_plain = plain_env()
t_mesh = mesh_env()
# MuJoCo is mostly single-threaded; CPU% during step is a weak signal here.
return t_plain, t_mesh, 0.0
def _worker_main(args: argparse.Namespace) -> None:
meta = _apply_profile(args.worker, bind_numa=args.bind_numa_to_gpu)
blas_s, blas_cpu = _bench_blas(args.blas_iters)
meta["blas_seconds"] = round(blas_s, 3)
meta["blas_peak_cpu_pct"] = round(blas_cpu, 1)
if not args.skip_libero:
plain_s, mesh_s, _ = _bench_libero(
suite=args.suite,
task_index=args.task_index,
steps=args.libero_steps,
resolution=args.resolution,
)
meta["libero_plain_seconds"] = round(plain_s, 3)
meta["libero_mesh_seconds"] = round(mesh_s, 3)
meta["libero_plain_ms_per_step"] = round(1000.0 * plain_s / args.libero_steps, 2)
meta["libero_mesh_ms_per_step"] = round(1000.0 * mesh_s / args.libero_steps, 2)
meta["omp_num_threads"] = os.environ.get("OMP_NUM_THREADS", "")
meta["openblas_num_threads"] = os.environ.get("OPENBLAS_NUM_THREADS", "")
print(json.dumps(meta), flush=True)
def _print_report(rows: list[dict]) -> None:
print("\n=== CPU profile comparison ===\n")
headers = [
"profile",
"threads",
"affinity",
"idle_est",
"loadavg1",
"blas_s",
"blas_peak_cpu%",
]
if rows and "libero_mesh_ms_per_step" in rows[0]:
headers.extend(["plain_ms/step", "mesh_ms/step"])
print(" | ".join(f"{h:>14}" for h in headers))
print("-" * (17 * len(headers)))
for r in rows:
cols = [
r.get("profile", ""),
str(r.get("threads", "")),
str(r.get("affinity_cpus", "")),
str(r.get("idle_estimate", "")),
str(r.get("loadavg1", "")),
str(r.get("blas_seconds", "")),
str(r.get("blas_peak_cpu_pct", "")),
]
if "libero_mesh_ms_per_step" in r:
cols.append(str(r.get("libero_plain_ms_per_step", "")))
cols.append(str(r.get("libero_mesh_ms_per_step", "")))
print(" | ".join(f"{c:>14}" for c in cols))
if len(rows) == 2:
a, b = rows[0], rows[1]
if a.get("profile") == "single":
single, auto = a, b
else:
single, auto = b, a
def speedup(key: str) -> str:
s = float(single.get(key, 0))
t = float(auto.get(key, 0))
if s <= 0 or t <= 0:
return "n/a"
return f"{s / t:.2f}x"
print("\n=== Verdict ===")
print(f"BLAS wall time (auto vs single): {speedup('blas_seconds')} (expect >1 if multi-thread helps)")
print(
f"BLAS peak CPU% (auto): {auto.get('blas_peak_cpu_pct', '?')}% "
f"(rough guide: >>100% means many cores busy)"
)
if "libero_mesh_ms_per_step" in auto:
print(
f"LIBERO mesh ms/step (auto vs single): {speedup('libero_mesh_ms_per_step')} "
"(often ~1x; MuJoCo sim is mostly single-thread)"
)
if int(auto.get("threads", 0)) >= int(auto.get("idle_estimate", 0)) * 0.8:
print("Thread count: OK — auto profile uses most estimated idle CPUs.")
else:
print(
"Thread count: check — auto threads lower than idle estimate "
"(raise load or use --bind-numa-to-gpu?)."
)
def main() -> None:
args = _parse_args()
if args.worker:
_worker_main(args)
return
rows: list[dict] = []
for profile in args.profiles:
print(f"Running profile={profile} ...", flush=True)
rows.append(
_run_worker(
profile,
blas_iters=args.blas_iters,
libero_steps=args.libero_steps,
skip_libero=args.skip_libero,
suite=args.suite,
task_index=args.task_index,
resolution=args.resolution,
bind_numa=args.bind_numa_to_gpu,
)
)
_print_report(rows)
if __name__ == "__main__":
main()