@hackbuild/humanoid 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sonic.js ADDED
@@ -0,0 +1,349 @@
1
+ /**
2
+ * GEAR-SONIC, NVIDIA's whole body controller for the Unitree G1, run in the
3
+ * page: an encoder turns a reference motion into a 64 number token, a decoder
4
+ * turns the token and ten ticks of the robot's state into 29 joint actions,
5
+ * 50 times a second; a PD loop here turns actions into motor torques at every
6
+ * MuJoCo step. Written for this library from the published deployment
7
+ * description and parameters (observation names, sizes and order, joint
8
+ * orders, gains from motor armature, action scale, default angles). The
9
+ * details the description leaves open were settled by trial on the deploy
10
+ * model: joint positions relative to the default angles, the reference in
11
+ * absolute angles, histories oldest first, a rotation's first two columns
12
+ * row by row, and the anchor as the base's tilt against an upright reference
13
+ * that follows the robot's heading (measured: only that combination stands).
14
+ * The weights are NVIDIA's, under the NVIDIA Open Model License, and load at
15
+ * run time; onnxruntime-web is an optional peer, passed in or loaded from a URL.
16
+ */
17
+ import { G1 } from "./g1.js";
18
+ import { HumanoidError } from "./runtime.js";
19
+ /** The policy files and their terms. */
20
+ export const SONIC = {
21
+ name: "gear-sonic, the default g1 controller",
22
+ /** Hugging Face revision the URLs pin. */
23
+ revision: "6733128a3d8a523b1418b06bca3cdf61c8b0987f",
24
+ encoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_encoder.onnx",
25
+ decoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_decoder.onnx",
26
+ /** Encoder and decoder together, in bytes (vendor: Hugging Face's sizes). */
27
+ bytes: 50_100_513 + 40_900_688,
28
+ hz: 50,
29
+ licence: "gear-sonic weights by nvidia. licensed by nvidia corporation under the nvidia open model license (https://huggingface.co/nvidia/GEAR-SONIC/blob/main/LICENSE). they load at run time and are not part of this library.",
30
+ };
31
+ /** The G1 model the policy was deployed on: motor actuators, its own joint damping, armature and friction. */
32
+ export const G1_SONIC = {
33
+ name: "unitree g1, 29 joints, the gear-sonic deploy model",
34
+ /** The scene, at GR00T-WholeBodyControl commit 2a5e6a1; it includes the robot file beside it. */
35
+ url: "https://raw.githubusercontent.com/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/scene_29dof.xml",
36
+ /** The meshes are in Git LFS; pass this as `assetBase` to `fetchModel`. */
37
+ assetBase: "https://media.githubusercontent.com/media/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/",
38
+ licence: "g1 deploy model from nvidia's gr00t-wholebodycontrol (apache-2.0), meshes copyright unitree robotics (bsd-3-clause). they load at run time and are not part of this library.",
39
+ };
40
+ // motor constants of the deployment parameters: armature (kg m2), effort limit (N m)
41
+ const MOTORS = { m22: [0.025101925, 139], m14: [0.01017752, 88], m5020: [0.003609725, 25], m4010: [0.00425, 5] };
42
+ // each joint's motor, in the model's order (G1.joints)
43
+ const MOTOR_OF = [
44
+ "m22", "m22", "m14", "m22", "m5020", "m5020", "m22", "m22", "m14", "m22", "m5020", "m5020",
45
+ "m14", "m5020", "m5020",
46
+ "m5020", "m5020", "m5020", "m5020", "m5020", "m4010", "m4010",
47
+ "m5020", "m5020", "m5020", "m5020", "m5020", "m4010", "m4010",
48
+ ];
49
+ // ankles and waist roll and pitch run at twice their motor's gains
50
+ const DOUBLED = new Set([4, 5, 10, 11, 13, 14]);
51
+ const OMEGA = 10 * 2 * Math.PI;
52
+ const ZETA = 2;
53
+ /** The deployment's joint tables, each in the model's joint order (`G1.joints`). */
54
+ export const SONIC_JOINTS = {
55
+ /** Standing angles, radians. */
56
+ defaults: [-0.312, 0, 0, 0.669, -0.363, 0, -0.312, 0, 0, 0.669, -0.363, 0, 0, 0, 0, 0.2, 0.2, 0, 0.6, 0, 0, 0, 0.2, -0.2, 0, 0.6, 0, 0, 0],
57
+ /** Position gain, N m per rad: armature times (10 Hz in rad/s) squared (computed). */
58
+ kp: MOTOR_OF.map((m, j) => MOTORS[m][0] * OMEGA * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
59
+ /** Velocity gain, N m s per rad: 2 times damping ratio 2 times armature times omega (computed). */
60
+ kd: MOTOR_OF.map((m, j) => 2 * ZETA * MOTORS[m][0] * OMEGA * (DOUBLED.has(j) ? 2 : 1)),
61
+ /** Torque limit, N m. */
62
+ effort: MOTOR_OF.map((m) => MOTORS[m][1]),
63
+ /** Radians per unit of action: 0.25 times effort over stiffness (computed). */
64
+ scale: MOTOR_OF.map((m) => (0.25 * MOTORS[m][1]) / (MOTORS[m][0] * OMEGA * OMEGA)),
65
+ /** The policy's (IsaacLab) index of each joint. */
66
+ policyIndex: [0, 3, 6, 9, 13, 17, 1, 4, 7, 10, 14, 18, 2, 5, 8, 11, 15, 19, 21, 23, 25, 27, 12, 16, 20, 22, 24, 26, 28],
67
+ };
68
+ /** A model order array (29) in the policy's order. */
69
+ export function toPolicyOrder(v) {
70
+ const out = new Array(29).fill(0);
71
+ for (let j = 0; j < 29; j++)
72
+ out[SONIC_JOINTS.policyIndex[j]] = v[j];
73
+ return out;
74
+ }
75
+ /** Rotates world vector v into the frame of quaternion q (w x y z): R(q) transposed times v. */
76
+ export function intoBody(q, v) {
77
+ const [w, x, y, z] = q;
78
+ const r = [
79
+ [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
80
+ [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
81
+ [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
82
+ ];
83
+ return [0, 1, 2].map((i) => r[0][i] * v[0] + r[1][i] * v[1] + r[2][i] * v[2]);
84
+ }
85
+ /**
86
+ * The anchor observation for an upright reference: the base's tilt with its heading removed (heading is
87
+ * the normalized (w, 0, 0, z) of the quaternion), as the first two columns of the rotation from base to
88
+ * reference, read row by row.
89
+ */
90
+ export function anchorSix(base) {
91
+ const [w, x, y, z] = base;
92
+ const n = Math.max(Math.hypot(w, z), 1e-9);
93
+ const hw = w / n, hz = z / n;
94
+ // base without heading: conj(h) * q; the relative rotation is its conjugate
95
+ const rw = hw * w + hz * z, rx = -(hw * x + hz * y), ry = -(hw * y - hz * x), rz = -(hw * z - hz * w);
96
+ const r00 = 1 - 2 * (ry * ry + rz * rz), r01 = 2 * (rx * ry - rw * rz);
97
+ const r10 = 2 * (rx * ry + rw * rz), r11 = 1 - 2 * (rx * rx + rz * rz);
98
+ const r20 = 2 * (rx * rz - rw * ry), r21 = 2 * (ry * rz + rw * rx);
99
+ return [r00, r01, r10, r11, r20, r21];
100
+ }
101
+ /**
102
+ * The encoder's 1762 inputs in its g1 mode: mode 0, then ten reference frames 0.1 s apart of joint
103
+ * angles (absolute, policy order) and velocities, then ten anchor observations; the other modes' parts
104
+ * stay zero. `ref` holds 10 frames, or 1 repeated.
105
+ */
106
+ export function encoderInput(ref, anchor) {
107
+ const e = new Float32Array(1762);
108
+ const frame = (f) => ref[Math.min(f, ref.length - 1)];
109
+ let o = 4; // mode id 0, three zeros
110
+ for (let f = 0; f < 10; f++)
111
+ for (let k = 0; k < 29; k++)
112
+ e[o++] = frame(f).q[k];
113
+ for (let f = 0; f < 10; f++)
114
+ for (let k = 0; k < 29; k++)
115
+ e[o++] = frame(f).dq?.[k] ?? 0;
116
+ o += 10 + 1 + 6; // root height windows and the single anchor belong to other modes
117
+ for (let f = 0; f < 10; f++)
118
+ for (let k = 0; k < 6; k++)
119
+ e[o++] = anchor[k];
120
+ return e;
121
+ }
122
+ /** Ten ticks of state and actions, oldest first, laid out as the decoder reads them. */
123
+ export class SonicHistory {
124
+ av = [];
125
+ q = [];
126
+ dq = [];
127
+ act = [];
128
+ g = [];
129
+ /** Fills all ten ticks with one state and zero actions. */
130
+ prime(s) {
131
+ for (const k of ["av", "q", "dq", "act", "g"])
132
+ this[k] = [];
133
+ for (let i = 0; i < 10; i++)
134
+ this.add(s, new Array(29).fill(0));
135
+ }
136
+ /** Adds a tick's state, with the actions the last tick produced. */
137
+ add(s, lastAction) {
138
+ const keep = (a, v) => {
139
+ a.push(v);
140
+ if (a.length > 10)
141
+ a.shift();
142
+ };
143
+ keep(this.av, s.angularVelocity);
144
+ keep(this.q, s.q);
145
+ keep(this.dq, s.dq);
146
+ keep(this.act, Array.from(lastAction));
147
+ keep(this.g, s.gravity);
148
+ }
149
+ /** The decoder's 994 inputs: the token, then each history oldest first. */
150
+ decoderInput(token) {
151
+ const d = new Float32Array(994);
152
+ let p = 0;
153
+ for (let k = 0; k < 64; k++)
154
+ d[p++] = token[k];
155
+ for (const h of [this.av, this.q, this.dq, this.act, this.g])
156
+ for (const tick of h)
157
+ for (const v of tick)
158
+ d[p++] = v;
159
+ return d;
160
+ }
161
+ }
162
+ /** Where onnxruntime-web loads from when no module is given. */
163
+ export const ORT_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs";
164
+ async function bytesOf(src, f, progress) {
165
+ if (typeof src !== "string")
166
+ return src instanceof Uint8Array ? src : new Uint8Array(src);
167
+ const r = await f(src);
168
+ if (!r.ok || !r.body)
169
+ throw new HumanoidError(`the policy file ${src} answered ${r.status}.`);
170
+ const reader = r.body.getReader();
171
+ const parts = [];
172
+ let n = 0;
173
+ for (;;) {
174
+ const { done, value } = await reader.read();
175
+ if (done)
176
+ break;
177
+ parts.push(value);
178
+ n += value.byteLength;
179
+ progress(value.byteLength);
180
+ }
181
+ const out = new Uint8Array(n);
182
+ let o = 0;
183
+ for (const p of parts)
184
+ (out.set(p, o), (o += p.byteLength));
185
+ return out;
186
+ }
187
+ /** The loaded policy: an encoder and a decoder session. Drive a G1 with {@link Sonic.drive}. */
188
+ export class Sonic {
189
+ ort;
190
+ encoder;
191
+ decoder;
192
+ constructor(ort, encoder, decoder) {
193
+ this.ort = ort;
194
+ this.encoder = encoder;
195
+ this.decoder = decoder;
196
+ }
197
+ /** Loads onnxruntime-web and both policy files. */
198
+ static async load(o = {}) {
199
+ let ort = o.ort;
200
+ if (!ort) {
201
+ // a relative url resolves against the page, not against this file
202
+ const url = new URL(o.ortUrl ?? ORT_URL, globalThis.location?.href).href;
203
+ try {
204
+ ort = (await import(/* @vite-ignore */ /* webpackIgnore: true */ url));
205
+ }
206
+ catch (e) {
207
+ throw new HumanoidError(`onnxruntime-web did not load from ${url}: ${e instanceof Error ? e.message : String(e)}.`);
208
+ }
209
+ ort.env.wasm.wasmPaths = new URL("./", url).href;
210
+ }
211
+ ort.env.wasm.numThreads = 1;
212
+ const f = o.fetch ?? globalThis.fetch.bind(globalThis);
213
+ let loaded = 0;
214
+ const tick = (n) => o.onProgress?.((loaded += n), SONIC.bytes);
215
+ const [eb, db] = await Promise.all([bytesOf(o.encoder ?? SONIC.encoder, f, tick), bytesOf(o.decoder ?? SONIC.decoder, f, tick)]);
216
+ const [encoder, decoder] = await Promise.all([ort.InferenceSession.create(eb), ort.InferenceSession.create(db)]);
217
+ o.onLicence?.(SONIC.licence);
218
+ return new Sonic(ort, encoder, decoder);
219
+ }
220
+ /** The decoder's actions (policy order) for one tick. */
221
+ async act(encoderIn, history) {
222
+ const T = this.ort.Tensor;
223
+ const token = (await this.encoder.run({ obs_dict: new T("float32", encoderIn, [1, 1762]) })).encoded_tokens.data;
224
+ return (await this.decoder.run({ obs_dict: new T("float32", history.decoderInput(token), [1, 994]) })).action.data;
225
+ }
226
+ /** A driver for a G1 whose 29 joints are on motor actuators (the {@link G1_SONIC} model). */
227
+ drive(sim) {
228
+ return new SonicDriver(this, sim);
229
+ }
230
+ async dispose() {
231
+ await Promise.all([this.encoder.release?.(), this.decoder.release?.()]);
232
+ }
233
+ }
234
+ /** Runs the policy on one robot: 50 ticks a second, the PD loop at every timestep between. */
235
+ export class SonicDriver {
236
+ sonic;
237
+ sim;
238
+ /** The reference pose the policy tracks, absolute angles in the model's joint order. Default the standing angles. */
239
+ reference = SONIC_JOINTS.defaults.slice();
240
+ /** Milliseconds the last tick's inference took (measured). */
241
+ inferenceMs = 0;
242
+ adr;
243
+ act;
244
+ history = new SonicHistory();
245
+ targets = SONIC_JOINTS.defaults.slice();
246
+ last = new Float32Array(29);
247
+ carry = 0;
248
+ busy = false;
249
+ perTick;
250
+ /** Bumped by reset, so a tick that awaited inference across a reset drops its result. */
251
+ generation = 0;
252
+ constructor(sonic, sim) {
253
+ this.sonic = sonic;
254
+ this.sim = sim;
255
+ this.adr = G1.joints.map((j) => {
256
+ const a = sim.address(j);
257
+ if (!a)
258
+ throw new HumanoidError(`the robot has no joint ${j}; the policy drives the unitree g1.`);
259
+ return a;
260
+ });
261
+ this.act = G1.joints.map((j) => {
262
+ const i = sim.actuated.indexOf(j);
263
+ if (i < 0)
264
+ throw new HumanoidError(`no actuator drives ${j}; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
265
+ // a position or velocity servo would read the torques as targets
266
+ if (sim.model.actuator_biastype[i] !== 0)
267
+ throw new HumanoidError(`${j} is on a servo actuator, not a motor; load the g1 deploy model (G1_SONIC), whose joints are on motors.`);
268
+ return i;
269
+ });
270
+ this.perTick = Math.max(1, Math.round(1 / SONIC.hz / sim.timestep));
271
+ this.reset();
272
+ }
273
+ /** The robot back at the standing angles, upright at the origin, and the history primed. */
274
+ reset() {
275
+ const { sim } = this;
276
+ if (sim.disposed)
277
+ return;
278
+ this.generation++;
279
+ sim.reset();
280
+ const d = sim.data;
281
+ d.qpos[2] = 0.79;
282
+ for (let j = 0; j < 29; j++)
283
+ d.qpos[this.adr[j].qpos] = SONIC_JOINTS.defaults[j];
284
+ sim.forward();
285
+ this.targets = SONIC_JOINTS.defaults.slice();
286
+ this.last.fill(0);
287
+ this.carry = 0;
288
+ this.history.prime(this.state());
289
+ }
290
+ /** The robot's state this tick, in the policy's order. */
291
+ state() {
292
+ const d = this.sim.data;
293
+ const quat = [d.qpos[3], d.qpos[4], d.qpos[5], d.qpos[6]];
294
+ return {
295
+ angularVelocity: [d.qvel[3], d.qvel[4], d.qvel[5]],
296
+ q: toPolicyOrder(this.adr.map((a, j) => d.qpos[a.qpos] - SONIC_JOINTS.defaults[j])),
297
+ dq: toPolicyOrder(this.adr.map((a) => d.qvel[a.qvel])),
298
+ gravity: intoBody(quat, [0, 0, -1]),
299
+ };
300
+ }
301
+ /** One control tick: the policy's actions to joint targets, then the PD loop for one tick of timesteps. A tick that a reset or dispose overtakes does nothing more. */
302
+ async tick() {
303
+ if (this.sim.disposed)
304
+ return;
305
+ const d = this.sim.data;
306
+ const gen = this.generation;
307
+ const t0 = performance.now();
308
+ this.history.add(this.state(), this.last);
309
+ const anchor = anchorSix([d.qpos[3], d.qpos[4], d.qpos[5], d.qpos[6]]);
310
+ const a = await this.sonic.act(encoderInput([{ q: toPolicyOrder(this.reference) }], anchor), this.history);
311
+ if (gen !== this.generation || this.sim.disposed)
312
+ return;
313
+ this.inferenceMs = performance.now() - t0;
314
+ this.last = Float32Array.from(a);
315
+ const pi = SONIC_JOINTS.policyIndex;
316
+ for (let j = 0; j < 29; j++)
317
+ this.targets[j] = SONIC_JOINTS.defaults[j] + a[pi[j]] * SONIC_JOINTS.scale[j];
318
+ const { kp, kd, effort } = SONIC_JOINTS;
319
+ this.sim.run(this.perTick, () => {
320
+ for (let j = 0; j < 29; j++) {
321
+ const tau = kp[j] * (this.targets[j] - d.qpos[this.adr[j].qpos]) - kd[j] * d.qvel[this.adr[j].qvel];
322
+ d.ctrl[this.act[j]] = Math.max(-effort[j], Math.min(effort[j], tau));
323
+ }
324
+ });
325
+ }
326
+ /**
327
+ * Advances by `seconds` in whole ticks, carrying the rest, at most 0.1 s of carry. A call while a tick
328
+ * runs adds its time to the carry and returns 0. Returns the ticks run; 0 once the robot is disposed.
329
+ */
330
+ async advance(seconds) {
331
+ if (this.sim.disposed)
332
+ return 0;
333
+ const per = 1 / SONIC.hz;
334
+ this.carry = Math.min(this.carry + (Number.isFinite(seconds) ? Math.max(0, seconds) : 0), 0.1);
335
+ if (this.busy)
336
+ return 0;
337
+ this.busy = true;
338
+ try {
339
+ const n = Math.floor(this.carry / per + 1e-6);
340
+ for (let i = 0; i < n; i++)
341
+ await this.tick();
342
+ this.carry = Math.max(0, this.carry - n * per);
343
+ return n;
344
+ }
345
+ finally {
346
+ this.busy = false;
347
+ }
348
+ }
349
+ }
package/dist/three.d.ts CHANGED
@@ -27,7 +27,7 @@ export declare class HumanoidView {
27
27
  private owned;
28
28
  constructor(sim: Humanoid, o?: HumanoidViewOptions);
29
29
  private geometry;
30
- /** Moves every mesh to its geom's pose after the last step. */
30
+ /** Moves every mesh to its geom's pose after the last step; does nothing once the robot is disposed. */
31
31
  update(): void;
32
32
  /** Meshes drawn. */
33
33
  get count(): number;
package/dist/three.js CHANGED
@@ -32,8 +32,11 @@ export class HumanoidView {
32
32
  const geo = this.geometry(g, type);
33
33
  if (!geo)
34
34
  continue;
35
+ // a geom's own rgba wins; MuJoCo's default rgba (0.5 0.5 0.5 1) gives way to the geom's material
35
36
  const mat = m.geom_matid?.[g] ?? -1;
36
- const rgba = mat >= 0 && m.mat_rgba ? m.mat_rgba.subarray(mat * 4, mat * 4 + 4) : m.geom_rgba.subarray(g * 4, g * 4 + 4);
37
+ const own = m.geom_rgba.subarray(g * 4, g * 4 + 4);
38
+ const plain = own[0] === 0.5 && own[1] === 0.5 && own[2] === 0.5 && own[3] === 1;
39
+ const rgba = plain && mat >= 0 && m.mat_rgba ? m.mat_rgba.subarray(mat * 4, mat * 4 + 4) : own;
37
40
  const material = new MeshStandardMaterial({ roughness: 0.6, metalness: 0.1, transparent: rgba[3] < 1, opacity: rgba[3] });
38
41
  material.color.setRGB(rgba[0], rgba[1], rgba[2]);
39
42
  this.owned.push(material);
@@ -81,8 +84,10 @@ export class HumanoidView {
81
84
  return null;
82
85
  }
83
86
  }
84
- /** Moves every mesh to its geom's pose after the last step. */
87
+ /** Moves every mesh to its geom's pose after the last step; does nothing once the robot is disposed. */
85
88
  update() {
89
+ if (this.sim.disposed)
90
+ return;
86
91
  const p = this.sim.data.geom_xpos, r = this.sim.data.geom_xmat;
87
92
  for (const { mesh, geom: g } of this.meshes) {
88
93
  const a = g * 9, b = g * 3;
package/how.ts CHANGED
@@ -7,6 +7,7 @@ const how: HowDoc = {
7
7
  "mujoco, google deepmind's webassembly build, loads at run time from a factory or a url and is never bundled; it is single threaded, so the page needs no cross-origin isolation.",
8
8
  "the robot's mjcf and every file it names (includes, meshes, textures) are read from a url or a dropped folder into mujoco's virtual file system, and the model compiles there.",
9
9
  "each frame runs whole timesteps of the model and carries the rest; targets go to the position actuators, a keyframe resets the pose, and the view moves one mesh per visible geom.",
10
+ "nvidia's gear-sonic policy can drive the g1 instead: an encoder and a decoder 50 times a second turn a reference pose and the robot's recent state into joint targets, and a pd loop turns those into motor torques at every step, so it balances and catches a shove.",
10
11
  ],
11
12
  packages: ["@hackbuild/humanoid"],
12
13
  install: "npm install @hackbuild/humanoid",
package/llms.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @hackbuild/humanoid
2
2
 
3
- > Run a physics humanoid in the page: MuJoCo simulates a robot from its MJCF files, and you set its joint targets, shove it and draw it.
3
+ > Run a physics humanoid in the page: MuJoCo simulates a robot from its MJCF files, NVIDIA's GEAR-SONIC policy balances the Unitree G1, and you pose it, shove it and draw it.
4
4
 
5
5
  Generated by tools/llms.mjs from the TypeDoc JSON, the README and the examples of hackbuild-motion. Human docs: https://hackbuild.github.io/hackbuild-motion/docs/humanoid/
6
6
 
@@ -11,6 +11,7 @@ Generated by tools/llms.mjs from the TypeDoc JSON, the README and the examples o
11
11
  - Steps the robot at the model's own timestep however the page's frames fall, resets it to a keyframe, writes joint targets to its position actuators, holds its current pose, shoves it, and reads any body's world pose.
12
12
  - Draws it in three.js from the `./three` subpath: one mesh per visible geom, MuJoCo's meshes shared, turned from MuJoCo's z up into y up with the robot facing +Z.
13
13
  - Names the Unitree G1 (29 joints) from MuJoCo Menagerie, pinned to one commit, as a ready robot; its files load from GitHub at run time.
14
+ - Runs GEAR-SONIC, NVIDIA's whole body controller for the G1, from the `./sonic` subpath: an encoder and a decoder 50 times a second through onnxruntime-web and a PD loop at every MuJoCo step, so the G1 stands, holds a crouch or a raised arm, and steps to catch a shove. The weights load from Hugging Face at run time.
14
15
 
15
16
  ## Install
16
17
 
@@ -18,28 +19,31 @@ Generated by tools/llms.mjs from the TypeDoc JSON, the README and the examples o
18
19
  npm install @hackbuild/humanoid
19
20
  ```
20
21
 
21
- It has no dependencies. MuJoCo and three.js are optional peers: install `@mujoco/mujoco` to import its factory, or let `loadMujoco` load it from `https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js`, with `mujoco.wasm` read beside it. `onLicence` receives the line to show. The G1's files come from GitHub when you load it.
22
+ It has no dependencies. MuJoCo, onnxruntime-web and three.js are optional peers: install `@mujoco/mujoco` to import its factory, or let `loadMujoco` load it from `https://cdn.jsdelivr.net/npm/@mujoco/mujoco@4.0.1/mujoco.js`, with `mujoco.wasm` read beside it. `onLicence` receives the line to show. The G1's files come from GitHub when you load it.
22
23
 
23
24
  | download | size |
24
25
  |---|---|
25
26
  | mujoco.wasm | 11.2 MB, 2.8 MB gzip (measured) |
26
27
  | the G1's meshes | 19.7 MB (vendor) |
28
+ | GEAR-SONIC encoder and decoder | 91.0 MB (vendor), from Hugging Face, pinned to one revision |
29
+
30
+ `Sonic.load` loads onnxruntime-web from jsDelivr when you pass no `ort` module, and the policy files from their pinned URLs when you pass no bytes.
27
31
 
28
32
  ## Exports
29
33
 
30
34
  ### @hackbuild/humanoid
31
35
 
32
36
  ```ts
33
- function fetchModel(url: string, o?: { fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>; onFile?: (path: string, done: number, of: number) => void }): Promise<ModelFiles>
37
+ function fetchModel(url: string, o?: { assetBase?: string; fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>; onFile?: (path: string, done: number, of: number) => void }): Promise<ModelFiles>
34
38
  ```
35
39
 
36
- A robot from the URL of its main MJCF; every file it names is fetched beside it.
40
+ A robot from the URL of its main MJCF; every file it names is fetched beside it, or for files that are not MJCF beside `assetBase` when given (a repository whose meshes live on another host, such as Git LFS).
37
41
 
38
42
  ```ts
39
43
  function filesFrom(list: Iterable<File>): Promise<ModelFiles>
40
44
  ```
41
45
 
42
- A robot from dropped files (a folder keeps its paths): the main MJCF is the one with a worldbody that no other file includes.
46
+ A robot from a file list: an `<input type="file" webkitdirectory>` keeps each file's path in the folder; loose files are keyed by name only, so a model whose meshes sit in a folder needs the folder picked.
43
47
 
44
48
  ```ts
45
49
  const G1: { readonly bytes: 19666440; readonly joints: readonly ["left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", "left_knee_joint", "left_ankle_pitch_joint", "left_ankle_roll_joint", "right_hip_pitch_joint", "right_hip_roll_joint", "right_hip_yaw_joint", "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint", "waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint", "left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint", "left_wrist_pitch_joint", "left_wrist_yaw_joint", "right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint", "right_wrist_pitch_joint", "right_wrist_yaw_joint"]; readonly keyframe: "stand"; readonly licence: "unitree g1 model and meshes from mujoco menagerie, bsd-3-clause, copyright unitree robotics. they load at run time and are not part of this library."; readonly name: "unitree g1, 29 joints"; readonly url: "https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/98a70c569c4c1b6da467a20012f766ee1f8dc521/unitree_g1/scene.xml" }
@@ -57,17 +61,21 @@ class Humanoid {
57
61
  readonly missing: string[];
58
62
  readonly model: MjModel;
59
63
  readonly timestep: number;
64
+ readonly disposed: boolean;
60
65
  readonly moving: boolean;
61
66
  readonly rootBody: string | null;
62
67
  readonly targets: Float64Array;
63
68
  readonly time: number;
69
+ address(joint: string): { qpos: number; qvel: number } | null;
64
70
  dispose(): void;
71
+ forward(): void;
65
72
  hold(): void;
66
73
  joint(name: string): { dq: number; q: number } | null;
67
- moveTo(targets: Record<string, number> | ArrayLike<number>, seconds?: number): void;
74
+ moveTo(targets: ArrayLike<number> | Record<string, number>, seconds?: number): void;
68
75
  pose(body: string | number): Pose | null;
69
76
  push(vx: number, vy: number, vz?: number): boolean;
70
77
  reset(key?: string | number): void;
78
+ run(n: number, control?: (sim: Humanoid) => void): void;
71
79
  step(seconds: number, max?: number): number;
72
80
  static open(mj: Mujoco, files: Pick<ModelFiles, "xml" | "assets"> & { missing?: string[] }): Humanoid;
73
81
  }
@@ -107,7 +115,9 @@ A model's state; the arrays are views on the wasm heap, live after each step.
107
115
 
108
116
  ```ts
109
117
  interface MjModel {
118
+ actuator_biastype: Int32Array;
110
119
  actuator_trnid: Int32Array;
120
+ actuator_trntype: Int32Array;
111
121
  geom_dataid: Int32Array;
112
122
  geom_group: Int32Array;
113
123
  geom_rgba: Float32Array;
@@ -123,6 +133,11 @@ interface MjModel {
123
133
  mesh_vert: Float32Array;
124
134
  mesh_vertadr: Int32Array;
125
135
  mesh_vertnum: Int32Array;
136
+ name_actuatoradr: Int32Array;
137
+ name_bodyadr: Int32Array;
138
+ name_jntadr: Int32Array;
139
+ name_keyadr: Int32Array;
140
+ names: Int8Array;
126
141
  nbody: number;
127
142
  ngeom: number;
128
143
  njnt: number;
@@ -212,11 +227,143 @@ interface Pose {
212
227
  A body's world pose: position x y z and quaternion w x y z, in MuJoCo's frame.
213
228
 
214
229
  ```ts
215
- function referencedFiles(xml: string, dirs?: { assetdir?: string; meshdir?: string; texturedir?: string }): { files: string[]; includes: string[] }
230
+ function referencedFiles(text: string, dirs?: { assetdir?: string; meshdir?: string; texturedir?: string }): { files: string[]; includes: string[] }
216
231
  ```
217
232
 
218
233
  The files one MJCF names, split into includes and the rest, joined onto its compiler's directories.
219
234
 
235
+ ### @hackbuild/humanoid/sonic
236
+
237
+ ```ts
238
+ function anchorSix(base: Q): number[]
239
+ ```
240
+
241
+ The anchor observation for an upright reference: the base's tilt with its heading removed (heading is the normalized (w, 0, 0, z) of the quaternion), as the first two columns of the rotation from base to reference, read row by row.
242
+
243
+ ```ts
244
+ function encoderInput(ref: { dq?: ArrayLike<number>; q: ArrayLike<number> }[], anchor: number[]): Float32Array
245
+ ```
246
+
247
+ The encoder's 1762 inputs in its g1 mode: mode 0, then ten reference frames 0.1 s apart of joint angles (absolute, policy order) and velocities, then ten anchor observations; the other modes' parts stay zero.
248
+
249
+ ```ts
250
+ const G1_SONIC: { readonly assetBase: "https://media.githubusercontent.com/media/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/"; readonly licence: "g1 deploy model from nvidia's gr00t-wholebodycontrol (apache-2.0), meshes copyright unitree robotics (bsd-3-clause). they load at run time and are not part of this library."; readonly name: "unitree g1, 29 joints, the gear-sonic deploy model"; readonly url: "https://raw.githubusercontent.com/NVlabs/GR00T-WholeBodyControl/2a5e6a1b55d9d0205a96e757b86007ec020cf589/gear_sonic_deploy/g1/scene_29dof.xml" }
251
+ ```
252
+
253
+ The G1 model the policy was deployed on: motor actuators, its own joint damping, armature and friction.
254
+
255
+ ```ts
256
+ function intoBody(q: Q, v: [number, number, number]): [number, number, number]
257
+ ```
258
+
259
+ Rotates world vector v into the frame of quaternion q (w x y z): R(q) transposed times v.
260
+
261
+ ```ts
262
+ interface Ort {
263
+ env: { wasm: { numThreads?: number; wasmPaths?: string } };
264
+ InferenceSession: { create(model: Uint8Array, options?: Record<string, unknown>): Promise<OrtSession> };
265
+ Tensor: new (type: "float32", data: Float32Array, dims: number[]) => unknown;
266
+ }
267
+ ```
268
+
269
+ The parts of onnxruntime-web this library calls.
270
+
271
+ ```ts
272
+ const ORT_URL: "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.23.2/dist/ort.wasm.min.mjs"
273
+ ```
274
+
275
+ Where onnxruntime-web loads from when no module is given.
276
+
277
+ ```ts
278
+ interface OrtSession {
279
+ release?(): Promise<void>;
280
+ run(feeds: Record<string, unknown>): Promise<Record<string, { data: unknown }>>;
281
+ }
282
+ ```
283
+
284
+ An onnxruntime session.
285
+
286
+ ```ts
287
+ class Sonic {
288
+ readonly ort: Ort;
289
+ act(encoderIn: Float32Array, history: SonicHistory): Promise<Float32Array<ArrayBufferLike>>;
290
+ dispose(): Promise<void>;
291
+ drive(sim: Humanoid): SonicDriver;
292
+ static load(o?: SonicOptions): Promise<Sonic>;
293
+ }
294
+ ```
295
+
296
+ The loaded policy: an encoder and a decoder session.
297
+
298
+ ```ts
299
+ const SONIC: { readonly bytes: number; readonly decoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_decoder.onnx"; readonly encoder: "https://huggingface.co/nvidia/GEAR-SONIC/resolve/6733128a3d8a523b1418b06bca3cdf61c8b0987f/model_encoder.onnx"; readonly hz: 50; readonly licence: "gear-sonic weights by nvidia. licensed by nvidia corporation under the nvidia open model license (https://huggingface.co/nvidia/GEAR-SONIC/blob/main/LICENSE). they load at run time and are not part of this library."; readonly name: "gear-sonic, the default g1 controller"; readonly revision: "6733128a3d8a523b1418b06bca3cdf61c8b0987f" }
300
+ ```
301
+
302
+ The policy files and their terms.
303
+
304
+ ```ts
305
+ const SONIC_JOINTS: { defaults: number[]; effort: (5 | 25 | 88 | 139)[]; kd: number[]; kp: number[]; policyIndex: number[]; scale: number[] }
306
+ ```
307
+
308
+ The deployment's joint tables, each in the model's joint order (`G1.joints`).
309
+
310
+ ```ts
311
+ class SonicDriver {
312
+ constructor(sonic: Sonic, sim: Humanoid);
313
+ inferenceMs: number;
314
+ reference: number[];
315
+ readonly sim: Humanoid;
316
+ advance(seconds: number): Promise<number>;
317
+ reset(): void;
318
+ state(): SonicState;
319
+ tick(): Promise<void>;
320
+ }
321
+ ```
322
+
323
+ Runs the policy on one robot: 50 ticks a second, the PD loop at every timestep between.
324
+
325
+ ```ts
326
+ class SonicHistory {
327
+ constructor();
328
+ add(s: SonicState, lastAction: ArrayLike<number>): void;
329
+ decoderInput(token: ArrayLike<number>): Float32Array;
330
+ prime(s: SonicState): void;
331
+ }
332
+ ```
333
+
334
+ Ten ticks of state and actions, oldest first, laid out as the decoder reads them.
335
+
336
+ ```ts
337
+ interface SonicOptions {
338
+ decoder?: string | ArrayBuffer | Uint8Array<ArrayBufferLike>;
339
+ encoder?: string | ArrayBuffer | Uint8Array<ArrayBufferLike>;
340
+ fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
341
+ onLicence?: (line: string) => void;
342
+ onProgress?: (loaded: number, total: number) => void;
343
+ ort?: Ort;
344
+ ortUrl?: string;
345
+ }
346
+ ```
347
+
348
+ Options for Sonic.load.
349
+
350
+ ```ts
351
+ interface SonicState {
352
+ angularVelocity: number[];
353
+ dq: number[];
354
+ gravity: number[];
355
+ q: number[];
356
+ }
357
+ ```
358
+
359
+ One control tick of robot state, in the policy's order.
360
+
361
+ ```ts
362
+ function toPolicyOrder(v: ArrayLike<number>): number[]
363
+ ```
364
+
365
+ A model order array (29) in the policy's order.
366
+
220
367
  ### @hackbuild/humanoid/three
221
368
 
222
369
  ```ts
@@ -274,11 +421,15 @@ renderer.setAnimationLoop(() => (robot.step(1 / 60), view.update(), renderer.ren
274
421
  - Do not commit the G1's meshes or any robot's files to an app; load them from `G1.url` or from a drop, and show the robot's licence.
275
422
  - Call `dispose()` on a Humanoid you are done with; MuJoCo's model and data live on the wasm heap and are not garbage collected.
276
423
  - Read poses after `step()`; they are MuJoCo's frame (z up), and the three.js view turns them to y up for you.
424
+ - Do not give the GEAR-SONIC driver the menagerie G1; it needs the deploy model (`G1_SONIC.url` with `assetBase: G1_SONIC.assetBase`), whose joints are on motors.
425
+ - Do not bundle or commit the GEAR-SONIC weights; load them from their pinned Hugging Face URLs and show `SONIC.licence`.
277
426
  - Write targets in the actuators' order (`actuated`), not the model's joint order; for the G1 they are the same 29 joints in `G1.joints`.
278
427
 
279
428
  ## Errors this package throws
280
429
 
281
430
  - `mujoco did not load from ...` (offline, or the URL is blocked): install `@mujoco/mujoco` and pass its factory, or serve it and pass `url`
431
+ - `no actuator drives ... load the g1 deploy model` (the policy was given the menagerie G1): load `G1_SONIC.url` with `assetBase: G1_SONIC.assetBase`
432
+ - `onnxruntime-web did not load from ...` (offline, or jsDelivr is blocked): install `onnxruntime-web` and pass the module as `ort`
282
433
  - `mujoco could not compile the model: ...` (a named file is missing or the MJCF is invalid): keep the robot's folder structure; the message names files that did not arrive
283
434
  - `the model has no keyframe ...` (a keyframe name the model lacks): use one from `keyframes`
284
435
  - `no mjcf here` (the drop holds no MJCF with a worldbody): drop the robot's whole folder