File size: 3,301 Bytes
3f4bb1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Measure batched SONIC inference throughput, CPU vs CUDA.

An RL rollout evaluates SONIC once per environment per control tick, so the
number that matters is env-steps/s = batch / seconds-per-tick. Isaac Lab at 50 Hz
with N envs needs 50*N env-steps/s just to keep up with physics.

    python scripts/bench_sonic_batch.py                # CPU and CUDA if available
    python scripts/bench_sonic_batch.py --batch 128 512
"""

from __future__ import annotations

import argparse
import importlib.util
import os
import time
from pathlib import Path

import numpy as np

_ROOT = Path(__file__).resolve().parents[1]
_DEFAULT_CKPT = _ROOT.parent / "checkpoints" / "sonic" / "sonic_v1_1"


def _load_policy_module():
    """Import ``sonic/policy.py`` alone; ``v2d_sim`` itself needs Isaac Lab."""
    path = _ROOT / "source" / "v2d_sim" / "sonic" / "policy.py"
    spec = importlib.util.spec_from_file_location("sonic_policy", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def bench(ckpt: Path, batches: list[int], repeats: int, use_cuda: bool) -> None:
    os.environ["SONIC_ORT_CUDA"] = "1" if use_cuda else "0"
    SonicOnnxAgent = _load_policy_module().SonicOnnxAgent

    try:
        agent = SonicOnnxAgent(ckpt, batched=True)
    except Exception as exc:  # noqa: BLE001
        print(f"  could not load ({exc})")
        return
    providers = agent.encoder.get_providers()
    print(f"  providers in use: {providers}")
    if use_cuda and not any("CUDA" in p or "Tensorrt" in p for p in providers):
        print("  CUDA provider did not attach; skipping")
        return

    rng = np.random.default_rng(0)
    for n in batches:
        enc = rng.normal(size=(n, 1751)).astype(np.float32)
        enc[:, 0] = 1.0  # teleop
        dec = rng.normal(size=(n, 994)).astype(np.float32)
        for _ in range(3):
            dec[:, :64] = agent.encode(enc)
            agent.decode(dec)
        t0 = time.perf_counter()
        for _ in range(repeats):
            dec[:, :64] = agent.encode(enc)
            agent.decode(dec)
        dt = (time.perf_counter() - t0) / repeats
        envs_at_50hz = int(1.0 / dt / 50 * n) if dt > 0 else 0
        print(
            f"    N={n:5d}  {dt * 1000:8.2f} ms/tick  {n / dt:10.0f} env-steps/s"
            f"   -> sustains {envs_at_50hz:6d} envs at 50 Hz"
        )


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--checkpoint", type=Path, default=_DEFAULT_CKPT)
    ap.add_argument("--batch", type=int, nargs="+", default=[64, 256, 1024, 4096])
    ap.add_argument("--repeats", type=int, default=10)
    args = ap.parse_args()

    if not (args.checkpoint / "model_encoder_batch.onnx").is_file():
        raise SystemExit(
            f"no dynamic-batch graphs in {args.checkpoint}; "
            "run scripts/export_sonic_dynamic_batch.py first"
        )

    import onnxruntime as ort

    print(f"onnxruntime {ort.__version__}  built-in providers: {ort.get_available_providers()}\n")
    print("CPU:")
    bench(args.checkpoint, args.batch, args.repeats, use_cuda=False)
    print("\nCUDA:")
    bench(args.checkpoint, args.batch, args.repeats, use_cuda=True)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())