File size: 11,807 Bytes
d45c758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Forward passes of the NetScribe state experts (experts/state/*.safetensors), in plain numpy (float32 arithmetic on
the stored fp16 weights).

Every expert is one line of the manifest; its tensors are stored under '<tag>/<parameter>'. `manifest["network"]`
names the network type and holds the sizes; this file is the reference for what each type computes. All functions
take a batch of observations `obs` of shape (B, obs_dim) (a single observation of shape (obs_dim,) also works) and
return the deterministic action, shape (B, act_dim).

Network types
-------------
mlp_tanh (ManiSkill3, Meta-World, dm_control, robosuite, Gymnasium-Robotics; PPO actors)
    x = clip((obs - mean) / sqrt(var + 1e-8), -10, 10)                     only if network.obs_normalizer (fp32 stats)
    hidden tanh layers actor_mean.0, .2, ...; output = action mean (not clipped). Also used for both parts of the
    ManiSkill3 residual expert (no observation normaliser).

dagger_layernorm_mlp (RoboDojo DAgger students; kmn/policy.py ChunkMLP; also the base of the RoboDojo residual experts)
    x = clip((obs - obs_mean) / obs_std, -10, 10)                         obs_mean, obs_std: fp32
    per hidden layer i (depth = len(hidden)): x = relu(LayerNorm(W x + b))  Linear net.{3i}, LayerNorm net.{3i+1}, eps 1e-5
    y = W x + b                                                           Linear net.{3*depth}, chunk * act_dim outputs
    a = clip(y[:act_dim], -1, 1)                                          chunk is 1 for every released expert
    if binary_gripper: a[6], a[13] = +1 if a >= 0 else -1                 (the two gripper commands)
    The action is RoboDojo's normalised joint-delta action of the two ARX X5 arms (14 numbers): arm joint targets =
    current joints + action_scale * a (manifest args.action_scale), gripper opening = (a + 1) / 2.

rsl_rl_mlp (Isaac Lab rsl-rl 5 actors; the residual part of the RoboDojo residual experts)
    x = (obs - obs_normalizer._mean) / (obs_normalizer._std + 0.01)       only if network.obs_normalizer (fp32 stats)
    hidden layers: x = elu(W x + b)                                       Linear mlp.0, mlp.2, ..., mlp.{2(n-1)}
    action = W x + b                                                      last Linear mlp.{2n}; not clipped
    distribution.std_param is the exploration std of training and is not used. Isaac Lab applies the action through
    the task's action terms (scales / offsets of the registered task); the registered agent configs do not clip it.

rl_games_lstm (Isaac Lab Factory, Forge and AutoMate; rl_games a2c_continuous, shared actor-critic, LSTM before the MLP)
    x_t = clip((obs_t - running_mean_std.running_mean) / sqrt(running_mean_std.running_var + 1e-5), -5, 5)
    h_t, c_t = LSTM(x_t, (h_{t-1}, c_{t-1}))        layers = rnn.layers, PyTorch nn.LSTM equations, gate order i, f, g, o:
        g = W_ih x + b_ih + W_hh h + b_hh; i, f, o = sigmoid(.), g = tanh(.); c' = f c + i g; h' = o tanh(c')
        keys a2c_network.rnn.rnn.{weight_ih,weight_hh,bias_ih,bias_hh}_l{k}; the input of layer k > 0 is h of layer k - 1
    y = LayerNorm(h_t of the last layer)            only if rnn.layer_norm (a2c_network.layer_norm, eps 1e-5)
    y = elu(W y + b) per hidden layer                a2c_network.actor_mlp.0, .2, .4
    action = clip(W y + b, -1, 1)                    a2c_network.mu; rl_games player / Isaac Lab wrapper clip_actions = 1
    The state (h, c) is zero at the start of every episode (reset it per environment when that environment resets).
    a2c_network.sigma (exploration std head) is not used.

residual (a frozen base policy plus a scaled residual policy; both networks are stored under one tag, with the
          prefixes 'base.' and 'residual.', each in the key layout of its own type)
    residual_input == "obs" (ManiSkill3, scripts/train_state_rppo.py; residual_clip false):
        b = clip(base(obs), -1, 1);  action = clip(b + residual_scale * residual(obs), -1, 1)
    residual_input == "obs_and_base_action" (RoboDojo, kmn/robodojo/rl/plug_in_charger.py; residual_clip true):
        b = base(obs)  (a dagger_layernorm_mlp: clipped to [-1, 1], grippers binarised if base.binary_gripper)
        r = residual(concat(obs, b));  action = clip(b + residual_scale * clip(r, -1, 1), -1, 1)
    obs is the plain environment observation (obs_dim numbers, without the base action).

Usage
-----
    from forward import load_expert, ExpertPolicy
    p, m = load_expert("RoboDojo.safetensors", "manifest.jsonl", "rd_push_t")   # the file is m["file"]
    pi = ExpertPolicy(p, m["network"])
    pi.reset(num_envs)            # needed for rl_games_lstm (recurrent); harmless otherwise
    action = pi(obs)              # obs: (num_envs, obs_dim)
    pi.reset_envs(done_mask)      # rl_games_lstm: zero the state of the environments that start a new episode
"""
import json

import numpy as np

GRIPPERS = (6, 13)


# ------------------------------------------------------------------------------------------------ loading
def load_expert(safetensors_path, manifest_path, tag):
    """(params, manifest line) of one expert; params maps '<parameter>' -> float32 array (only this tag is read)."""
    from safetensors import safe_open

    m = next(json.loads(l) for l in open(manifest_path, encoding="utf-8") if l.strip() and json.loads(l)["tag"] == tag)
    p = {}
    with safe_open(safetensors_path, framework="numpy") as f:
        for k in f.keys():
            if k.startswith(tag + "/"):
                p[k.split("/", 1)[1]] = f.get_tensor(k).astype(np.float32)
    return p, m


# ------------------------------------------------------------------------------------------------ building blocks
def _lin(p, name, x):
    return x @ p[name + ".weight"].astype(np.float32).T + p[name + ".bias"].astype(np.float32)


def _elu(x):
    return np.where(x > 0, x, np.expm1(np.minimum(x, 0.0)))


def _sigmoid(x):
    return 0.5 * (1.0 + np.tanh(0.5 * x))


def _layer_norm(x, w, b, eps=1e-5):
    mu = x.mean(-1, keepdims=True)
    var = ((x - mu) ** 2).mean(-1, keepdims=True)
    return (x - mu) / np.sqrt(var + eps) * w + b


def _batch(obs):
    x = np.asarray(obs, dtype=np.float32)
    return x[None] if x.ndim == 1 else x


# ------------------------------------------------------------------------------------------------ network types
def mlp_tanh(p, obs, net, prefix=""):
    """PPO actor: optional observation normaliser, tanh MLP actor_mean.{2i}; output = action mean (unclipped)."""
    x = _batch(obs)
    if net.get("obs_normalizer"):
        x = np.clip((x - p[prefix + "mean"]) / np.sqrt(p[prefix + "var"] + 1e-8), -10.0, 10.0)
    n = len(net["hidden"]) + 1
    for i in range(n):
        x = _lin(p, f"{prefix}actor_mean.{2 * i}", x)
        if i < n - 1:
            x = np.tanh(x)
    return x


def dagger_layernorm_mlp(p, obs, net, prefix=""):
    """RoboDojo DAgger student (ChunkMLP): normalise, [Linear -> LayerNorm -> ReLU] x depth, Linear; clip; binarise grippers."""
    x = _batch(obs)
    x = np.clip((x - p[prefix + "obs_mean"]) / p[prefix + "obs_std"], -10.0, 10.0)
    depth = len(net["hidden"])
    for i in range(depth):
        x = _lin(p, f"{prefix}net.{3 * i}", x)
        x = _layer_norm(x, p[f"{prefix}net.{3 * i + 1}.weight"].astype(np.float32), p[f"{prefix}net.{3 * i + 1}.bias"].astype(np.float32))
        x = np.maximum(x, 0.0)
    y = _lin(p, f"{prefix}net.{3 * depth}", x)
    act_dim = y.shape[-1] // int(net.get("chunk", 1))
    a = np.clip(y[:, :act_dim], -1.0, 1.0)  # first action of the chunk (chunk = 1 here)
    if net.get("binary_gripper"):
        a = a.copy()
        g = list(GRIPPERS)
        a[:, g] = np.where(a[:, g] >= 0, 1.0, -1.0)
    return a


def rsl_rl_mlp(p, obs, net, prefix=""):
    """rsl-rl 5 MLPModel actor, deterministic output: optional empirical normaliser, ELU MLP, linear output."""
    x = _batch(obs)
    if net.get("obs_normalizer"):
        x = (x - p[prefix + "obs_normalizer._mean"]) / (p[prefix + "obs_normalizer._std"] + 0.01)
    n = len(net["hidden"]) + 1
    for i in range(n):
        x = _lin(p, f"{prefix}mlp.{2 * i}", x)
        if i < n - 1:
            x = _elu(x)
    return x


def rl_games_lstm_zero_state(net, batch):
    u, L = int(net["rnn"]["units"]), int(net["rnn"]["layers"])
    return np.zeros((L, batch, u), np.float32), np.zeros((L, batch, u), np.float32)


def rl_games_lstm(p, obs, net, state, prefix=""):
    """One control step of the rl_games LSTM actor. state = (h, c), each (layers, B, units). Returns (action, new state)."""
    x = _batch(obs)
    x = np.clip((x - p[prefix + "running_mean_std.running_mean"]) / np.sqrt(p[prefix + "running_mean_std.running_var"] + 1e-5), -5.0, 5.0)
    h, c = state
    h2, c2 = np.empty_like(h), np.empty_like(c)
    r = prefix + "a2c_network.rnn.rnn."
    for k in range(int(net["rnn"]["layers"])):
        g = (x @ p[f"{r}weight_ih_l{k}"].astype(np.float32).T + p[f"{r}bias_ih_l{k}"].astype(np.float32)
             + h[k] @ p[f"{r}weight_hh_l{k}"].astype(np.float32).T + p[f"{r}bias_hh_l{k}"].astype(np.float32))
        gi, gf, gg, go = np.split(g, 4, axis=-1)
        c2[k] = _sigmoid(gf) * c[k] + _sigmoid(gi) * np.tanh(gg)
        h2[k] = _sigmoid(go) * np.tanh(c2[k])
        x = h2[k]
    if net["rnn"].get("layer_norm"):
        x = _layer_norm(x, p[prefix + "a2c_network.layer_norm.weight"].astype(np.float32), p[prefix + "a2c_network.layer_norm.bias"].astype(np.float32))
    for i in range(len(net["hidden"])):
        x = _elu(_lin(p, f"{prefix}a2c_network.actor_mlp.{2 * i}", x))
    mu = _lin(p, prefix + "a2c_network.mu", x)
    return np.clip(mu, -1.0, 1.0), (h2, c2)


_PLAIN = {"mlp_tanh": mlp_tanh, "dagger_layernorm_mlp": dagger_layernorm_mlp, "rsl_rl_mlp": rsl_rl_mlp}


def residual(p, obs, net):
    """Base policy + residual_scale * residual policy (see the module docstring for the two compositions)."""
    x = _batch(obs)
    base, res, s = net["base"], net["residual"], float(net["residual_scale"])
    b = np.clip(_PLAIN[base["type"]](p, x, base, "base."), -1.0, 1.0)
    if net["residual_input"] == "obs":
        r = _PLAIN[res["type"]](p, x, res, "residual.")
    elif net["residual_input"] == "obs_and_base_action":
        r = _PLAIN[res["type"]](p, np.concatenate([x, b], -1), res, "residual.")
    else:
        raise ValueError(net["residual_input"])
    if net.get("residual_clip"):
        r = np.clip(r, -1.0, 1.0)
    return np.clip(b + s * r, -1.0, 1.0)


def act(p, net, obs):
    """Deterministic action of a non-recurrent expert."""
    t = net["type"]
    if t == "residual":
        return residual(p, obs, net)
    if t == "dagger_layernorm_mlp":
        return dagger_layernorm_mlp(p, obs, net)
    if t in _PLAIN:
        return _PLAIN[t](p, obs, net)
    raise ValueError(f"{t} is recurrent or unknown: use ExpertPolicy")


class ExpertPolicy:
    """Uniform interface for all types; keeps the recurrent state of rl_games_lstm experts."""

    def __init__(self, params, network):
        self.p, self.net, self.state = params, network, None

    def reset(self, num_envs):
        if self.net["type"] == "rl_games_lstm":
            self.state = rl_games_lstm_zero_state(self.net, num_envs)

    def reset_envs(self, mask):
        """Zero the recurrent state of the environments where mask is True (their episode starts)."""
        if self.state is not None:
            m = np.asarray(mask, bool)
            for s in self.state:
                s[:, m] = 0.0

    def __call__(self, obs):
        if self.net["type"] == "rl_games_lstm":
            x = _batch(obs)
            if self.state is None or self.state[0].shape[1] != len(x):
                self.reset(len(x))
            a, self.state = rl_games_lstm(self.p, x, self.net, self.state)
            return a
        return act(self.p, self.net, obs)