File size: 6,163 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
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
"""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