v2d / simulation /source /v2d_sim /sonic /policy.py
hk239's picture
Upload v2d project (excluding data and .venv) (part 18)
3f4bb1d verified
Raw History Blame Contribute Delete
6.16 kB
"""SONIC v1.1 ONNX encoder + decoder.
The checkpoints NVIDIA ships are traced at batch 1. ``scripts/export_sonic_dynamic_batch.py``
writes ``model_*_batch.onnx`` alongside them; those are preferred when present so
an RL rollout can evaluate every environment in one call.
"""
from __future__ import annotations
import os
from pathlib import Path
import numpy as np
def _allowed_cpus() -> int:
try:
return max(1, len(os.sched_getaffinity(0)))
except (AttributeError, OSError):
return max(1, os.cpu_count() or 4)
def _session_options():
import onnxruntime as ort
# PBS/cgroup jobs do not own the host's full CPU set. ORT's default
# affinity (pthread_setaffinity_np) then fails with EINVAL unless the
# thread count is set explicitly.
n = min(8, _allowed_cpus())
if os.environ.get("SONIC_ORT_THREADS"):
n = max(1, min(_allowed_cpus(), int(os.environ["SONIC_ORT_THREADS"])))
opts = ort.SessionOptions()
opts.intra_op_num_threads = n
opts.inter_op_num_threads = 1
opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
return opts
# DT_NEEDED of libonnxruntime_providers_cuda.so, minus libcuda.so.1 (driver).
_CUDA13_LIBS = ("libcudart.so.13", "libcublas.so.13", "libcublasLt.so.13", "libcurand.so.10")
def _preload_cuda13() -> list[str]:
"""dlopen the CUDA 13 runtime that onnxruntime-gpu 1.29 links against.
The wheels are installed under ``nvidia/cu13/lib``, but nothing puts that
directory on the loader path, so ORT's provider .so fails on
``libcublasLt.so.13``. Preloading satisfies the SONAME lookup without
exporting LD_LIBRARY_PATH, which would also shadow the CUDA 12 libraries
that torch and Isaac Lab are built against.
RTLD_LOCAL is deliberate and sufficient: the loader resolves DT_NEEDED by
SONAME against everything already mapped, so the provider still finds these,
but their symbols stay out of the global namespace where torch's CUDA 12
cuBLAS could otherwise bind to them.
"""
import ctypes
import sysconfig
lib_dir = Path(sysconfig.get_paths()["purelib"]) / "nvidia" / "cu13" / "lib"
missing = []
for name in _CUDA13_LIBS:
try:
ctypes.CDLL(str(lib_dir / name), mode=ctypes.RTLD_LOCAL)
except OSError:
missing.append(name)
return missing
def _providers() -> list[str]:
import onnxruntime as ort
# CUDA is opt-in: it costs a host<->device copy per call, so it only pays
# off for batched rollouts, not the single-env replay path.
want_cuda = os.environ.get("SONIC_ORT_CUDA", "").strip() in ("1", "true", "yes")
if want_cuda and "CUDAExecutionProvider" in ort.get_available_providers():
missing = _preload_cuda13()
if missing:
print(f"[sonic] CUDA preload missing {missing}; provider will fall back", flush=True)
return ["CUDAExecutionProvider", "CPUExecutionProvider"]
return ["CPUExecutionProvider"]
def _pick_models(policy_dir: Path, batched: bool | None) -> tuple[Path, Path, bool]:
"""Prefer the dynamic-batch graphs, falling back to the shipped batch-1 pair."""
pairs = {
True: (policy_dir / "model_encoder_batch.onnx", policy_dir / "model_decoder_batch.onnx"),
False: (policy_dir / "model_encoder.onnx", policy_dir / "model_decoder.onnx"),
}
order = [True, False] if batched is None else [batched]
for want in order:
enc, dec = pairs[want]
if enc.is_file() and dec.is_file():
return enc, dec, want
if batched:
raise FileNotFoundError(
f"no dynamic-batch SONIC ONNX under {policy_dir}; "
"run scripts/export_sonic_dynamic_batch.py"
)
raise FileNotFoundError(f"missing SONIC ONNX under {policy_dir}")
class SonicOnnxAgent:
"""Load the SONIC encoder/decoder pair from a checkpoint dir.
Accepts a single observation ``(D,)`` or a batch ``(N, D)``; the batch form
needs the dynamic-batch graphs, otherwise it falls back to one call per row.
"""
def __init__(self, policy_dir: str | Path, *, batched: bool | None = None) -> None:
import onnxruntime as ort
policy_dir = Path(policy_dir)
enc_path, dec_path, self.batched = _pick_models(policy_dir, batched)
opts = _session_options()
providers = _providers()
print(
f"[sonic] onnxruntime threads={opts.intra_op_num_threads} providers={providers} "
f"graph={'dynamic-batch' if self.batched else 'batch-1'}",
flush=True,
)
self.encoder = ort.InferenceSession(str(enc_path), sess_options=opts, providers=providers)
self.decoder = ort.InferenceSession(str(dec_path), sess_options=opts, providers=providers)
self.enc_in = self.encoder.get_inputs()[0].name
self.dec_in = self.decoder.get_inputs()[0].name
self.policy_dir = policy_dir
def _run(self, session, name: str, obs: np.ndarray) -> np.ndarray:
x = np.asarray(obs, dtype=np.float32)
flat = x.ndim == 1
x = x.reshape(-1, x.shape[-1])
if self.batched or x.shape[0] == 1:
(out,) = session.run(None, {name: x})
else: # batch-1 graph: one call per row
out = np.concatenate(
[session.run(None, {name: x[i : i + 1]})[0] for i in range(x.shape[0])], axis=0
)
out = np.asarray(out, dtype=np.float32)
return out.reshape(-1) if flat else out
def encode(self, encoder_obs: np.ndarray) -> np.ndarray:
"""(1751,) -> (64,), or (N, 1751) -> (N, 64)."""
return self._run(self.encoder, self.enc_in, encoder_obs)
def decode(self, decoder_obs: np.ndarray) -> np.ndarray:
"""(994,) -> (29,), or (N, 994) -> (N, 29)."""
return self._run(self.decoder, self.dec_in, decoder_obs)
def act(self, encoder_obs: np.ndarray, decoder_hist_obs: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
token = self.encode(encoder_obs)
action = self.decode(decoder_hist_obs)
return action, token