VectorW's picture
Unitree G1 walking with an mjlab locomotion policy (ONNX); firmer grasps (noslip while squeezing); kitchen doors, oven, hood and fridge interior
8fdec83 verified
Raw History Blame Contribute Delete
8.31 kB
// The Unitree G1 humanoid, walking with mjswan's locomotion policy (trained with mjlab's velocity task),
// run with ONNX Runtime Web at 50 Hz. tools/make_g1.py writes the robot; the policy's sidecar
// (locomotion.json) gives the joint order, the rest pose and the action scales.
//
// Observation, 99 values in this order, as mjlab's velocity task builds it (no scaling):
// pelvis IMU linear velocity (3) and angular velocity (3), in the IMU frame (velocimeter and gyro);
// gravity direction in the pelvis frame (3);
// joint positions minus the rest pose (29); joint velocities (29); the previous action (29);
// the command: forward and sideways speed (m/s) and turn rate (rad/s) (3).
// Action: 29 values; joint target = rest pose + scale * action, for MuJoCo's position actuators (PD).
/** Keys for the G1, as [keys, what they do]. */
export const G1_KEYS = [
["W / S", "Walk forward / back"],
["A / D", "Turn left / right"],
["Q / E", "Step left / right"],
["Space", "Stand still"],
];
// Command limits, inside the ranges the policy was trained on (speeds +-1 m/s, turning +-0.5 rad/s).
export const G1_LIMITS = { vx: [-0.6, 0.9], vy: [-0.45, 0.45], wz: [-0.5, 0.5] };
const FREE = 0;
export class G1Robot {
/** `meta` is robot.json; `config` the policy's sidecar. The policy session comes later (setPolicy). */
constructor(sim, meta, config) {
this.sim = sim;
this.meta = meta;
const { model } = sim;
this.root = sim.id("body", meta.root);
const j = model.body_jntadr[this.root];
if (j < 0 || model.jnt_type[j] !== FREE) throw new Error("the G1's pelvis has no free joint");
this.rootQ = model.jnt_qposadr[j];
this.rootV = model.jnt_dofadr[j];
this.names = config.policy_joint_names;
this.rest = Float64Array.from(config.default_joint_pos);
const scale = config.actions.joint_pos.scale;
this.scale = Float64Array.from(this.names, (n) => scale[n]);
this.qadr = this.names.map((n) => model.jnt(n).qposadr);
this.vadr = this.names.map((n) => model.jnt(n).dofadr);
this.act = this.names.map((n) => {
const a = sim.id("actuator", n);
if (a < 0) throw new Error(`no actuator for ${n}`);
return a;
});
const sensor = (name) => {
const id = this.sim.mujoco.mj_name2id(model, this.sim.mujoco.mjtObj.mjOBJ_SENSOR.value, name);
if (id < 0) throw new Error(`the G1 has no ${name} sensor`);
return model.sensor_adr[id];
};
this.linVel = sensor("imu_lin_vel");
this.angVel = sensor("imu_ang_vel");
this.n = this.names.length;
this.obs = new Float32Array(9 + 3 * this.n + 3);
this.lastAction = new Float32Array(this.n);
this.command = { vx: 0, vy: 0, wz: 0 };
this.policy = null; // { session, ort, input, output }
this.pending = null;
this.ready = null;
this.fallen = 0;
this.home();
}
/** The policy, once loaded: `session` from ONNX Runtime and the `ort` module that made it. */
setPolicy(ort, session) {
this.policy = { ort, session, input: session.inputNames[0], output: session.outputNames[0] };
}
/** Standing at the rest pose, still, at (x, y) facing `yaw` (by default where the pelvis is now). */
home({ x, y, yaw } = {}) {
const { data } = this.sim;
const q = data.qpos;
// From qpos, not xpos: after a reset or a restore the body positions are not yet computed.
const r = this.rootQ;
x ??= q[r];
y ??= q[r + 1];
yaw ??= Math.atan2(2 * (q[r + 3] * q[r + 6] + q[r + 4] * q[r + 5]), 1 - 2 * (q[r + 5] ** 2 + q[r + 6] ** 2));
q.set([x, y, 0.78, Math.cos(yaw / 2), 0, 0, Math.sin(yaw / 2)], r);
for (let i = 0; i < 6; i++) data.qvel[this.rootV + i] = 0;
for (let k = 0; k < this.n; k++) {
q[this.qadr[k]] = this.rest[k];
data.qvel[this.vadr[k]] = 0;
data.ctrl[this.act[k]] = this.rest[k];
}
this.lastAction.fill(0);
this.command = { vx: 0, vy: 0, wz: 0 };
this.pending = null;
this.ready = null;
this.fallen = 0;
}
/** [x, y, yaw] of the pelvis. */
pose() {
const p = this.sim.data.xpos;
const R = this.sim.data.xmat;
const b = this.root;
return [p[3 * b], p[3 * b + 1], Math.atan2(R[9 * b + 3], R[9 * b])];
}
/** Forward and sideways speed (m/s) and turn rate (rad/s), clamped to what the policy knows. */
setCommand(vx, vy, wz) {
const c = (v, [lo, hi]) => Math.max(lo, Math.min(hi, Number(v) || 0));
this.command = { vx: c(vx, G1_LIMITS.vx), vy: c(vy, G1_LIMITS.vy), wz: c(wz, G1_LIMITS.wz) };
}
/** The policy's input for the current state. */
observation() {
const { data, model } = this.sim;
const o = this.obs;
const s = data.sensordata;
for (let i = 0; i < 3; i++) o[i] = s[this.linVel + i];
for (let i = 0; i < 3; i++) o[3 + i] = s[this.angVel + i];
// Gravity (0, 0, -1) in the pelvis frame: minus the third row of its rotation matrix.
const R = data.xmat;
const b = 9 * this.root;
o[6] = -R[b + 6];
o[7] = -R[b + 7];
o[8] = -R[b + 8];
let k = 9;
for (let j = 0; j < this.n; j++) o[k++] = data.qpos[this.qadr[j]] - this.rest[j];
for (let j = 0; j < this.n; j++) o[k++] = data.qvel[this.vadr[j]];
for (let j = 0; j < this.n; j++) o[k++] = this.lastAction[j];
o[k++] = this.command.vx;
o[k++] = this.command.vy;
o[k++] = this.command.wz;
void model;
return o;
}
/** Runs the policy on the current state; resolves to its action. */
async infer() {
const { ort, session, input, output } = this.policy;
const result = await session.run({ [input]: new ort.Tensor("float32", Float32Array.from(this.observation()), [1, this.obs.length]) });
return result[output].data;
}
/** Joint targets from an action. */
apply(action) {
const ctrl = this.sim.data.ctrl;
for (let j = 0; j < this.n; j++) {
this.lastAction[j] = action[j];
ctrl[this.act[j]] = this.rest[j] + this.scale[j] * action[j];
}
}
/** Whether the robot is down: the pelvis low or tipped more than about 60 degrees. */
isDown() {
const b = this.root;
return this.sim.data.xpos[3 * b + 2] < 0.45 || this.sim.data.xmat[9 * b + 8] < 0.5;
}
/**
* Called at the start of every control period. The action has to come from this period's state, so
* the physics waits (returns false; `pending` resolves when the policy answers) and the action is
* applied when this is called again for the same period. Without the policy yet, it holds the rest pose.
* After a fall it stands back up where it is (after a second, so the fall shows).
*/
update(dt = 0.02) {
if (this.isDown()) {
this.fallen += dt;
if (this.fallen > 1.0) this.home();
return true;
}
this.fallen = 0;
if (!this.policy) return true;
if (this.ready) {
this.apply(this.ready);
this.ready = null;
return true;
}
if (!this.pending) {
this.pending = this.infer().then(
(action) => {
this.ready = action;
this.pending = null;
},
(error) => {
this.pending = null;
console.error(error);
},
);
}
return false;
}
}
/** Keyboard teleop for the G1: held keys set the command, which ramps so the steps stay steady. */
export class G1Teleop {
static codes() {
return new Set(["KeyW", "KeyS", "KeyA", "KeyD", "KeyQ", "KeyE", "Space"]);
}
constructor(robot) {
this.robot = robot;
this.down = new Set();
this.engaged = false;
this.v = { vx: 0, vy: 0, wz: 0 };
}
tick(dt) {
const d = this.down;
const want = {
vx: d.has("KeyW") ? G1_LIMITS.vx[1] : d.has("KeyS") ? G1_LIMITS.vx[0] : 0,
vy: d.has("KeyQ") ? G1_LIMITS.vy[1] : d.has("KeyE") ? G1_LIMITS.vy[0] : 0,
wz: d.has("KeyA") ? G1_LIMITS.wz[1] : d.has("KeyD") ? G1_LIMITS.wz[0] : 0,
};
if (d.has("Space")) want.vx = want.vy = want.wz = 0;
this.engaged = d.size > 0;
const step = (k, rate) => {
const delta = want[k] - this.v[k];
this.v[k] += Math.sign(delta) * Math.min(Math.abs(delta), rate * dt);
};
step("vx", 1.2);
step("vy", 1.2);
step("wz", 1.5);
if (this.engaged || Math.abs(this.v.vx) + Math.abs(this.v.vy) + Math.abs(this.v.wz) > 1e-3) this.robot.setCommand(this.v.vx, this.v.vy, this.v.wz);
}
}