File size: 2,802 Bytes
7a35d14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Run an exported policy (train/export_onnx.py) with ONNX Runtime, as LeRobot's ACT does at inference:
// predict a chunk of actions, execute the first `n_action_steps`, then predict again.
// `ort` is onnxruntime-web (browser and Node), passed in so tools can use the same code.
import { applyAction, observe } from "../tasks/pick.js";
import { holding } from "../robots/skills.js";

export class PolicyRunner {
  constructor(ort, session, meta) {
    this.ort = ort;
    this.session = session;
    this.meta = meta;
    this.queue = [];
    this.inferenceMs = 0;
  }

  static async load(ort, modelBytes, meta) {
    const session = await ort.InferenceSession.create(modelBytes, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
    return new PolicyRunner(ort, session, meta);
  }

  reset() {
    this.queue = [];
  }

  /** Predict a chunk from an observation {state, environment}; returns the actions to execute. */
  async predict(obs) {
    const { ort } = this;
    const t0 = performance.now();
    const out = await this.session.run({
      state: new ort.Tensor("float32", Float32Array.from(obs.state), [1, obs.state.length]),
      environment: new ort.Tensor("float32", Float32Array.from(obs.environment), [1, obs.environment.length]),
    });
    this.inferenceMs = performance.now() - t0;
    const data = out.actions.data;
    const dim = out.actions.dims[2];
    const n = Math.min(this.meta.n_action_steps, out.actions.dims[1]);
    const actions = [];
    for (let i = 0; i < n; i++) actions.push(Array.from(data.subarray(i * dim, (i + 1) * dim)));
    return actions;
  }
}

/**
 * The pick policy as a skill: every control period it applies the next queued action; when the queue
 * is empty it yields a promise for the next chunk (the skill runner waits for it with the physics held).
 * Ends when the object has been held 4 cm up for half a second, or after `maxSeconds`.
 */
export function* policyPick(robot, runner, bodyId, side, { maxSeconds = 12 } = {}) {
  runner.reset();
  const startZ = robot.sim.bodyPos(bodyId)[2];
  const dt = robot.sim.controlDt;
  let heldFor = 0;
  try {
    for (let t = 0; t < maxSeconds; t += dt) {
      if (runner.queue.length === 0) {
        const obs = observe(robot, side, bodyId);
        runner.queue = yield runner.predict(obs);
      }
      applyAction(robot, side, runner.queue.shift());
      const up = robot.sim.bodyPos(bodyId)[2] - startZ;
      heldFor = up > 0.04 && holding(robot, side, bodyId) ? heldFor + dt : 0;
      if (heldFor > 0.5) return { ok: true, message: `the policy picked it up with the ${side} arm (${(up * 100).toFixed(0)} cm up)`, seconds: t };
      yield;
    }
    return { ok: false, message: "the policy did not lift it in time" };
  } finally {
    robot.releaseJoints(side);
  }
}