File size: 11,686 Bytes
4341630
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/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()