rlx-web 0.2.18

WebAssembly entry point for RLX — run models in the browser (CPU backend; WebGPU device bring-up)
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// RLX vision benchmark — live charts + multi-backend training (CPU / WebGPU / WebGL).

import Rlx from "./rlx.js";

const $ = (id) => document.getElementById(id);
const COLORS = {
  cpu: "#2563eb",
  webgpu: "#059669",
  webgl: "#d97706",
  sps: "#7c3aed",
  grid: "#ecece8",
  axis: "#9a9a94",
  text: "#5a5a5a",
};

const maxDiff = (a, b) => {
  let m = 0;
  for (let i = 0; i < a.length; i++) m = Math.max(m, Math.abs(a[i] - b[i]));
  return m;
};

const yieldUi = () => new Promise((r) => setTimeout(r, 0));

/** Lightweight multi-series line chart (no external deps). */
class LineChart {
  constructor(canvas) {
    this.canvas = canvas;
    this.ctx = canvas.getContext("2d");
    this.series = new Map(); // name -> { color, ys: number[] }
  }

  clear() {
    this.series.clear();
    this.draw();
  }

  setSeries(name, color, ys) {
    this.series.set(name, { color, ys: ys.slice() });
    this.draw();
  }

  append(name, color, y) {
    const s = this.series.get(name) || { color, ys: [] };
    s.color = color;
    s.ys.push(y);
    this.series.set(name, s);
    this.draw();
  }

  draw() {
    const ctx = this.ctx;
    const w = this.canvas.width;
    const h = this.canvas.height;
    const pad = { l: 44, r: 12, t: 10, b: 22 };
    ctx.clearRect(0, 0, w, h);

    const all = [];
    for (const s of this.series.values()) all.push(...s.ys);
    if (!all.length) {
      ctx.fillStyle = COLORS.text;
      ctx.font = "12px ui-monospace, monospace";
      ctx.fillText("waiting for steps…", pad.l, h / 2);
      return;
    }

    let ymin = Math.min(...all);
    let ymax = Math.max(...all);
    if (ymin === ymax) {
      ymin -= 1;
      ymax += 1;
    }
    const padY = (ymax - ymin) * 0.08;
    ymin -= padY;
    ymax += padY;
    const xmax = Math.max(1, ...[...this.series.values()].map((s) => s.ys.length - 1));

    const xOf = (i) => pad.l + (i / xmax) * (w - pad.l - pad.r);
    const yOf = (v) => pad.t + (1 - (v - ymin) / (ymax - ymin)) * (h - pad.t - pad.b);

    // grid
    ctx.strokeStyle = COLORS.grid;
    ctx.lineWidth = 1;
    for (let g = 0; g <= 4; g++) {
      const y = pad.t + ((h - pad.t - pad.b) * g) / 4;
      ctx.beginPath();
      ctx.moveTo(pad.l, y);
      ctx.lineTo(w - pad.r, y);
      ctx.stroke();
    }

    // axes labels
    ctx.fillStyle = COLORS.text;
    ctx.font = "11px ui-monospace, monospace";
    ctx.textAlign = "right";
    ctx.fillText(ymax.toFixed(3), pad.l - 6, pad.t + 10);
    ctx.fillText(ymin.toFixed(3), pad.l - 6, h - pad.b);
    ctx.textAlign = "left";
    ctx.fillText("0", pad.l, h - 6);
    ctx.textAlign = "right";
    ctx.fillText(String(xmax), w - pad.r, h - 6);

    for (const [, s] of this.series) {
      if (s.ys.length < 1) continue;
      ctx.strokeStyle = s.color;
      ctx.lineWidth = 2;
      ctx.beginPath();
      s.ys.forEach((v, i) => {
        const x = xOf(i);
        const y = yOf(v);
        if (i === 0) ctx.moveTo(x, y);
        else ctx.lineTo(x, y);
      });
      ctx.stroke();
      // last point
      const li = s.ys.length - 1;
      ctx.fillStyle = s.color;
      ctx.beginPath();
      ctx.arc(xOf(li), yOf(s.ys[li]), 3.2, 0, Math.PI * 2);
      ctx.fill();
    }
  }
}

function setProgress(phase, fraction, meta) {
  $("progress-panel").hidden = false;
  $("phase").textContent = phase;
  $("bar").style.width = `${Math.max(0, Math.min(100, fraction * 100)).toFixed(1)}%`;
  $("progress-meta").textContent = meta || "—";
}

function appendLog(line) {
  const el = $("log");
  if (el.textContent === "—" || el.textContent === "") el.textContent = line;
  else el.textContent += "\n" + line;
  el.scrollTop = el.scrollHeight;
}

function row(backend, fwd, train, bench) {
  const tr = document.createElement("tr");
  tr.innerHTML = `<td>${backend}</td><td>${fwd}</td><td>${train}</td><td>${bench}</td>`;
  $("rows").appendChild(tr);
}

async function trainBackend(model, backend, x, label, params, steps, lr, charts, onTick) {
  let p = params;
  const losses = [];
  const spsHist = [];
  const t0 = performance.now();
  let lastLoss = NaN;
  const color = COLORS[backend] || COLORS.cpu;
  const reportEvery = steps > 80 ? 5 : steps > 40 ? 2 : 1;

  for (let i = 0; i < steps; i++) {
    let step;
    if (backend === "cpu") step = model.trainStepCpu(x, label, p, lr);
    else if (backend === "webgpu") step = await model.trainStepWebgpu(x, label, p, lr);
    else if (backend === "webgl") step = model.trainStepWebgl(x, label, p, lr);
    else throw new Error(`unknown backend ${backend}`);

    p = step.params;
    lastLoss = step.loss;
    losses.push(lastLoss);

    const done = i + 1;
    if (done === 1 || done === steps || done % reportEvery === 0) {
      const elapsed = (performance.now() - t0) / 1000;
      const sps = done / Math.max(elapsed, 1e-6);
      spsHist.push(sps);
      charts.loss.setSeries(backend, color, losses);
      charts.sps.setSeries("sps", COLORS.sps, spsHist);
      onTick({
        backend,
        step: done,
        steps,
        loss: lastLoss,
        initialLoss: losses[0],
        stepsPerSec: sps,
      });
      await yieldUi();
    }
  }

  const elapsed = (performance.now() - t0) / 1000;
  return {
    initialLoss: losses[0],
    finalLoss: lastLoss,
    stepsPerSec: steps / Math.max(elapsed, 1e-6),
    losses,
    params: p,
  };
}

function detectGpu(rlx) {
  const webgpu =
    typeof rlx.wasm.init_webgpu === "function" &&
    typeof rlx.wasm.VisionBench !== "undefined";
  // VisionBench methods appear after construction; check prototype / feature flags via mlp helpers.
  const hasGpuFwd = typeof rlx.wasm.mlp_forward_gpu === "function";
  const hasGlFwd = typeof rlx.wasm.mlp_forward_webgl === "function";
  return {
    webgpuBundle: hasGpuFwd || webgpu,
    webglBundle: hasGlFwd,
  };
}

async function main() {
  const rlx = await Rlx.init({ webgpu: true });
  $("status").textContent = "wasm ready";
  $("status").className = "ok";
  $("pref").textContent = rlx.preferredBackend();

  const gpu = detectGpu(rlx);
  const feats = [];
  if (gpu.webgpuBundle) feats.push(rlx.webgpuReady ? "webgpu✓" : "webgpu (no adapter)");
  else feats.push("webgpu✗");
  if (gpu.webglBundle) feats.push("webgl✓");
  else feats.push("webgl✗");
  feats.push("cpu✓");
  $("gpu-feat").textContent = feats.join(", ");

  const select = $("model");
  for (const slug of rlx.listVisionModels()) {
    const opt = document.createElement("option");
    opt.value = slug;
    opt.textContent = `${slug} — ${rlx.modelInfo(slug).title}`;
    select.appendChild(opt);
  }

  const lossChart = new LineChart($("loss-chart"));
  const spsChart = new LineChart($("sps-chart"));

  $("run").addEventListener("click", async () => {
    const btn = $("run");
    btn.disabled = true;
    $("rows").innerHTML = "";
    $("log").textContent = "—";
    lossChart.clear();
    spsChart.clear();

    const slug = select.value;
    const model = rlx.vision(slug);
    const steps = Number($("steps").value) || 40;
    const seed = 42;
    const lr = 0.01;
    const mode = $("train-backends").value;
    const charts = { loss: lossChart, sps: spsChart };

    const wantGpu = mode !== "cpu";
    const wantGl = mode === "all";

    try {
      appendLog(`${model.info.title}`);
      appendLog(
        `input=${model.info.inputLen} · params=${model.info.paramFlatLen} · classes=${model.info.numClasses}`,
      );

      setProgress("Initializing…", 0.02, `seed=${seed}`);
      await yieldUi();
      const params0 = model.initParams(seed);
      const { x, label } = model.syntheticBatch(seed);

      setProgress("CPU forward…", 0.06, "compile + run");
      await yieldUi();
      const tFwd = performance.now();
      const cpuLogits = model.forwardCpu(x, params0);
      const fwdMs = (performance.now() - tFwd).toFixed(1);
      appendLog(`CPU forward ${fwdMs} ms`);

      // --- CPU train ---
      setProgress(`CPU training (0/${steps})…`, 0.1, `lr=${lr}`);
      const cpuBench = await trainBackend(
        model,
        "cpu",
        x,
        label,
        params0,
        steps,
        lr,
        charts,
        ({ step, steps: n, loss, initialLoss, stepsPerSec }) => {
          setProgress(
            `CPU training (${step}/${n})…`,
            0.1 + 0.35 * (step / n),
            `loss=${loss.toFixed(6)} · Δ=${(loss - initialLoss).toFixed(6)} · ${stepsPerSec.toFixed(1)}/s`,
          );
          if (step === 1 || step === n || step % 10 === 0) {
            appendLog(`  [cpu] step ${step}/${n}  loss=${loss.toFixed(6)}  (${stepsPerSec.toFixed(1)}/s)`);
          }
        },
      );
      row(
        "cpu",
        `logits[0..2]=[${[...cpuLogits.slice(0, 3)].map((v) => v.toFixed(4)).join(", ")}]`,
        cpuBench.losses[0].toFixed(6),
        `${cpuBench.initialLoss.toFixed(4)} → ${cpuBench.finalLoss.toFixed(4)} @ ${cpuBench.stepsPerSec.toFixed(1)}/s`,
      );

      // --- WebGPU ---
      if (wantGpu && gpu.webgpuBundle && rlx.webgpuReady) {
        try {
          setProgress("WebGPU forward…", 0.5, "async");
          await yieldUi();
          const t0 = performance.now();
          const gpuLogits = await model.forwardWebgpu(x, params0);
          const ms = (performance.now() - t0).toFixed(1);
          appendLog(`WebGPU forward ${ms} ms · max|Δ|=${maxDiff(gpuLogits, cpuLogits).toExponential(2)}`);

          setProgress(`WebGPU training (0/${steps})…`, 0.55, "");
          const gpuBench = await trainBackend(
            model,
            "webgpu",
            x,
            label,
            params0,
            steps,
            lr,
            charts,
            ({ step, steps: n, loss, initialLoss, stepsPerSec }) => {
              setProgress(
                `WebGPU training (${step}/${n})…`,
                0.55 + 0.25 * (step / n),
                `loss=${loss.toFixed(6)} · Δ=${(loss - initialLoss).toFixed(6)} · ${stepsPerSec.toFixed(1)}/s`,
              );
              if (step === 1 || step === n || step % 10 === 0) {
                appendLog(
                  `  [webgpu] step ${step}/${n}  loss=${loss.toFixed(6)}  (${stepsPerSec.toFixed(1)}/s)`,
                );
              }
            },
          );
          row(
            "webgpu",
            `max|Δ|=${maxDiff(gpuLogits, cpuLogits).toExponential(2)} (${ms} ms)`,
            gpuBench.losses[0].toFixed(6),
            `${gpuBench.initialLoss.toFixed(4)} → ${gpuBench.finalLoss.toFixed(4)} @ ${gpuBench.stepsPerSec.toFixed(1)}/s`,
          );
        } catch (e) {
          row("webgpu", "—", String(e), "—");
          appendLog(`WebGPU: ${e}`);
        }
      } else if (wantGpu) {
        const why = !gpu.webgpuBundle
          ? "not built (rebuild with --webgpu / --all)"
          : "no adapter";
        row("webgpu", why, "—", "—");
        appendLog(`WebGPU: ${why}`);
      }

      // --- WebGL ---
      if (wantGl && gpu.webglBundle) {
        try {
          setProgress("WebGL forward…", 0.85, "");
          await yieldUi();
          const glLogits = model.forwardWebgl(x, params0);
          appendLog(`WebGL forward · max|Δ|=${maxDiff(glLogits, cpuLogits).toExponential(2)}`);

          let trainCell = "forward only";
          let benchCell = "—";
          if (model.info.webglTrain) {
            setProgress(`WebGL training (0/${steps})…`, 0.88, "");
            const glBench = await trainBackend(
              model,
              "webgl",
              x,
              label,
              params0,
              steps,
              lr,
              charts,
              ({ step, steps: n, loss, initialLoss, stepsPerSec }) => {
                setProgress(
                  `WebGL training (${step}/${n})…`,
                  0.88 + 0.1 * (step / n),
                  `loss=${loss.toFixed(6)} · Δ=${(loss - initialLoss).toFixed(6)} · ${stepsPerSec.toFixed(1)}/s`,
                );
              },
            );
            trainCell = glBench.losses[0].toFixed(6);
            benchCell = `${glBench.initialLoss.toFixed(4)} → ${glBench.finalLoss.toFixed(4)} @ ${glBench.stepsPerSec.toFixed(1)}/s`;
          }
          row(
            "webgl",
            `max|Δ|=${maxDiff(glLogits, cpuLogits).toExponential(2)}`,
            trainCell,
            benchCell,
          );
        } catch (e) {
          const msg = String(e);
          row("webgl", msg.includes("not enabled") ? "not built" : msg, "—", "—");
          appendLog(`WebGL: ${msg}`);
        }
      } else if (wantGl) {
        row("webgl", "not built (rebuild with --webgl / --all)", "—", "—");
        appendLog("WebGL: not built");
      }

      setProgress("Done", 1, "all selected backends finished");
      $("status").textContent = "bench complete";
      $("status").className = "ok";
    } catch (e) {
      $("status").textContent = "error: " + e;
      $("status").className = "err";
      setProgress("Failed", 0, String(e));
      appendLog(`ERROR: ${e}`);
      console.error(e);
    } finally {
      btn.disabled = false;
    }
  });
}

main().catch((e) => {
  $("status").textContent = "error: " + e;
  $("status").className = "err";
  console.error(e);
});