File size: 9,820 Bytes
49ef597
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// cablepilot's world model (the released 28k-parameter model) in plain JS. A line-by-line port of
// cablepilot/model/learned.py: room-free features -> causal TCN encoders -> GRU latent unroll (the JEPA), then the
// prober reads each predicted latent and sets the coefficients of the hand-written physics, integrated 4 substeps per
// 0.1 s model step. Checked against PyTorch by tools/test.mjs.
//
// State x (14): p(3) v(3) swing s(2) s_dot(2) wrist wrist_dot close close_dot.  Action (5): vx vy vz wrist_rate closure.

export const STATE_DIM = 14, ACTION_DIM = 5, FEAT_DIM = 28;
const G = 9.81;

// ---------------------------------------------------------------- small dense helpers (row-major nested arrays -> flat)
function flat(w) { return Float32Array.from(w.flat(Infinity)); }

function conv(w, b) {             // Conv1d weight (out, in, k)
  return { W: flat(w), b: Float32Array.from(b), out: w.length, cin: w[0].length, k: w[0][0].length };
}
function lin(w, b) {              // Linear weight (out, in)
  return { W: flat(w), b: b ? Float32Array.from(b) : new Float32Array(w.length), out: w.length, cin: w[0].length };
}
function linApply(L, x, xo, y) {  // y = W x + b ; x read from offset xo
  const { W, b, out, cin } = L;
  for (let o = 0; o < out; o++) {
    let s = b[o]; const r = o * cin;
    for (let i = 0; i < cin; i++) s += W[r + i] * x[xo + i];
    y[o] = s;
  }
  return y;
}

// causal TCN over a sequence: seq (len * cin) -> (len * out)
function tcnApply(T, seq, len) {
  let cur = seq, c = T.layers[0].cin;
  for (let li = 0; li < T.layers.length; li++) {
    const L = T.layers[li];
    const nxt = new Float32Array(len * L.out);
    for (let t = 0; t < len; t++) {
      for (let o = 0; o < L.out; o++) {
        let s = L.b[o];
        for (let j = 0; j < L.k; j++) {
          const tt = t - (L.k - 1) + j;      // left padding: causal
          if (tt < 0) continue;
          const wr = (o * L.cin) * L.k + j;
          for (let i = 0; i < L.cin; i++) s += L.W[wr + i * L.k] * cur[tt * c + i];
        }
        nxt[t * L.out + o] = s > 0 ? s : 0;   // ReLU after every hidden conv
      }
    }
    cur = nxt; c = L.out;
  }
  const R = T.readout, out = new Float32Array(len * R.out);
  for (let t = 0; t < len; t++)
    for (let o = 0; o < R.out; o++) {
      let s = R.b[o];
      for (let i = 0; i < R.cin; i++) s += R.W[o * R.cin + i] * cur[t * c + i];
      out[t * R.out + o] = s;
    }
  return out;
}

function makeTCN(sd, prefix) {
  const layers = [];
  for (let i = 0; ; i += 2) {
    const k = `${prefix}.tcn.${i}.conv.weight`;
    if (!(k in sd)) break;
    layers.push(conv(sd[k], sd[`${prefix}.tcn.${i}.conv.bias`]));
  }
  const rw = sd[`${prefix}.readout.weight`];
  return { layers, readout: lin(rw.map(r => r.map(c => c[0])), sd[`${prefix}.readout.bias`]) };
}

const sig = x => 1 / (1 + Math.exp(-x));

// ---------------------------------------------------------------- the model
export function loadModel(json) {
  const c = json.config, J = json.jepa, P = json.prober, N = json.norm;
  const m = {
    cfg: c, H: c.H, dtModel: c.dt, latent: c.latent, hidden: c.hidden,
    stateEnc: makeTCN(J, "state_enc"), actionEnc: makeTCN(J, "action_enc"),
    Wih: lin(J["cell.weight_ih"], J["cell.bias_ih"]), Whh: lin(J["cell.weight_hh"], J["cell.bias_hh"]),
    readout: lin(J["readout.weight"], J["readout.bias"]),
    net: [lin(P["net.0.weight"], P["net.0.bias"]), lin(P["net.2.weight"], P["net.2.bias"]), lin(P["net.4.weight"], P["net.4.bias"])],
    logRateV: P.log_rate_v, aMax: P.log_a_max.map(Math.exp), logOmega: P.log_omega, zetaLogit: P.zeta_logit,
    kappa0: P.kappa0, logRateW: P.log_rate_w, logRateC: P.log_rate_c,
    omegaSpan: c.omega_span ?? 0.3,
    sMean: Float32Array.from(N.s_mean), sStd: Float32Array.from(N.s_std),
    aMean: Float32Array.from(N.a_mean), aStd: Float32Array.from(N.a_std),
  };
  m.kappaSpan = Math.max(0.5, 2 * m.omegaSpan);
  return m;
}

// (14) state + mounts [[x,y,z] x4] -> normalised (28) features written into out
export function featuresNorm(m, x, xo, M, out) {
  let j = 0;
  out[j++] = x[xo + 2];
  const ln = [0, 0, 0, 0];
  for (let i = 0; i < 4; i++) {
    const rx = M[i][0] - x[xo], ry = M[i][1] - x[xo + 1], rz = M[i][2] - x[xo + 2];
    const l = Math.hypot(rx, ry, rz); ln[i] = l;
    out[j++] = rx / l; out[j++] = ry / l; out[j++] = rz / l;
  }
  for (let i = 0; i < 4; i++) out[j++] = ln[i];
  for (let i = 3; i < 14; i++) out[j++] = x[xo + i];
  for (let i = 0; i < FEAT_DIM; i++) out[i] = (out[i] - m.sMean[i]) / m.sStd[i];
  return out;
}

// GRUCell (PyTorch gate order r, z, n)
function gru(m, inp, h, gi, gh, hn) {
  linApply(m.Wih, inp, 0, gi); linApply(m.Whh, h, 0, gh);
  const H = m.hidden;
  for (let i = 0; i < H; i++) {
    const r = sig(gi[i] + gh[i]), z = sig(gi[H + i] + gh[H + i]);
    const n = Math.tanh(gi[2 * H + i] + r * gh[2 * H + i]);
    hn[i] = (1 - z) * n + z * h[i];
  }
  return hn;
}

/** The model's prediction, as LearnedCDPRModel.rollout: the shared history (H+1 states, H commands) and S candidate
 *  plans of T planner steps (each held for `stream` model steps) -> Float32Array (S * T * 14) at the planner steps. */
export function rollout(m, M, xHist, cHist, plans, S, T, stream = 2) {
  const H = m.H, L = T * stream, D = m.latent, A = ACTION_DIM;
  // 1. state encoder ONCE over the measured history (causal: its summary at H reads only the past)
  const hf = new Float32Array((H + 1) * FEAT_DIM), tmp = new Float32Array(FEAT_DIM);
  for (let t = 0; t <= H; t++) { featuresNorm(m, xHist[t], 0, M, tmp); hf.set(tmp, t * FEAT_DIM); }
  const s0 = tcnApply(m.stateEnc, hf, H + 1).subarray(H * D, (H + 1) * D);
  const out = new Float32Array(S * T * STATE_DIM);
  const seq = new Float32Array((H + L) * A);
  const inp = new Float32Array(D + m.actionEnc.readout.out);
  const gi = new Float32Array(3 * m.hidden), gh = new Float32Array(3 * m.hidden);
  let h = new Float32Array(m.hidden), hn = new Float32Array(m.hidden);
  const lat = new Float32Array(L * D), s = new Float32Array(D);
  const x = new Float32Array(STATE_DIM), cmds = new Float32Array(L * A);
  for (let b = 0; b < S; b++) {
    // 2. the action sequence: history commands then this plan, normalised
    for (let t = 0; t < H; t++) for (let i = 0; i < A; i++) seq[t * A + i] = (cHist[t][i] - m.aMean[i]) / m.aStd[i];
    for (let k = 0; k < L; k++) {
      const pk = (b * T + Math.floor(k / stream)) * A;
      for (let i = 0; i < A; i++) {
        cmds[k * A + i] = plans[pk + i];
        seq[(H + k) * A + i] = (plans[pk + i] - m.aMean[i]) / m.aStd[i];
      }
    }
    const al = tcnApply(m.actionEnc, seq, H + L), AL = m.actionEnc.readout.out;
    // 3. GRU unroll of the latent
    h.fill(0); s.set(s0);
    for (let k = 0; k < L; k++) {
      inp.set(s, 0); inp.set(al.subarray((H + k) * AL, (H + k + 1) * AL), D);
      gru(m, inp, h, gi, gh, hn); [h, hn] = [hn, h];
      linApply(m.readout, h, 0, s); lat.set(s, k * D);
    }
    // 4. the prober sets the physics, integrated from the true current state
    x.set(xHist[H]);
    integrate(m, M, x, cmds, cHist[H - 1], lat, L, (k, xx) => {
      if ((k + 1) % stream === 0) out.set(xx, (b * T + (k + 1) / stream - 1) * STATE_DIM);
    });
  }
  return out;
}

const fbuf = new Float32Array(FEAT_DIM), pin = new Float32Array(24 + FEAT_DIM + 3);
const h1 = new Float32Array(64), h2 = new Float32Array(64), po = new Float32Array(18);

function integrate(m, M, x, cmds, cmdPrev, lat, L, emit, nSub = 4) {
  const h = m.dtModel / nSub, D = m.latent;
  let prev = cmdPrev;
  const ce = new Float32Array(5);
  for (let k = 0; k < L; k++) {
    // prober(latent, normalised features, command error)
    pin.set(lat.subarray(k * D, (k + 1) * D), 0);
    pin.set(featuresNorm(m, x, 0, M, fbuf), D);
    for (let i = 0; i < 3; i++) pin[D + FEAT_DIM + i] = cmds[k * 5 + i] - x[3 + i];
    linApply(m.net[0], pin, 0, h1); for (let i = 0; i < 64; i++) h1[i] = h1[i] > 0 ? h1[i] : 0;
    linApply(m.net[1], h1, 0, h2); for (let i = 0; i < 64; i++) h2[i] = h2[i] > 0 ? h2[i] : 0;
    linApply(m.net[2], h2, 0, po);
    const rateV = [0, 1, 2].map(i => Math.exp(m.logRateV[i] + Math.tanh(po[i])));
    const rV = [po[3], po[4], po[5]];
    const beta = sig(po[6]);
    const omega = Math.exp(m.logOmega + m.omegaSpan * Math.tanh(po[7]));
    const zeta = 0.5 * sig(m.zetaLogit + po[8]);
    const kappa = m.kappa0 * Math.exp(m.kappaSpan * Math.tanh(po[9]));
    const sEq = [0.15 * Math.tanh(po[10]), 0.15 * Math.tanh(po[11])];
    const rS = [po[12], po[13]];
    const rateW = Math.exp(m.logRateW + Math.tanh(po[14])), rW = po[15];
    const rateC = Math.exp(m.logRateC + Math.tanh(po[16])), rC = 0.1 * po[17];
    for (let i = 0; i < 5; i++) ce[i] = beta * cmds[k * 5 + i] + (1 - beta) * prev[i];
    physicsSubsteps(x, ce, h, nSub, { rateV, rV, aMax: m.aMax, omega, zeta, kappa, sEq, rS, rateW, rW, rateC, rC });
    prev = cmds.subarray(k * 5, k * 5 + 5);
    emit(k, x);
  }
}

/** The hand-written physics (slot 3): gantry behind acceleration-limited spools, a damped pendulum driven by the gantry's
 *  horizontal acceleration, the wrist and finger servos. Mutates x. */
export function physicsSubsteps(x, ce, h, nSub, c) {
  const a = [0, 0, 0];
  for (let n = 0; n < nSub; n++) {
    for (let i = 0; i < 3; i++) {
      a[i] = c.aMax[i] * Math.tanh(c.rateV[i] * (ce[i] - x[3 + i]) / c.aMax[i]) + c.rV[i];
      x[3 + i] += a[i] * h; x[i] += x[3 + i] * h;
    }
    for (let i = 0; i < 2; i++) {
      const sdd = -c.omega * c.omega * (x[6 + i] - c.sEq[i]) - 2 * c.zeta * c.omega * x[8 + i] + c.kappa * a[i] + c.rS[i];
      x[8 + i] += sdd * h; x[6 + i] += x[8 + i] * h;
    }
    x[11] += (c.rateW * (ce[3] - x[11]) + c.rW) * h; x[10] += x[11] * h;
    x[13] = Math.max(-1.2, Math.min(1.2, c.rateC * (ce[4] - x[12]))) + c.rC; x[12] += x[13] * h;
  }
}