@hackbuild/motion-net 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,203 @@
1
+ // Weight loading: a JSON manifest and a flat little endian blob. Either
2
+ // part can come from a URL, an ArrayBuffer (or view), or a File or Blob.
3
+ // Every tensor is checked against the dimensions before anything runs.
4
+ import { BONES, BONE_COUNT, STYLES } from "./layout.js";
5
+ export const WEIGHT_LICENCE = "motion-net weights: cc by-nc 4.0, paul starke and sebastian starke, meta, ai4animationpy. fetched at run time, never bundled, not for commercial use.";
6
+ /** One public copy of the weights, pinned to a commit. Configuration only. */
7
+ export const UPSTREAM = {
8
+ manifest: "https://raw.githubusercontent.com/sweriko/ai4anim-webgpu/b539455f849f284a1e814eb11ab649eb594319dc/public/quadruped.json",
9
+ bin: "https://raw.githubusercontent.com/sweriko/ai4anim-webgpu/b539455f849f284a1e814eb11ab649eb594319dc/public/quadruped.bin",
10
+ /** SHA-256 of that binary, computed from a downloaded copy. */
11
+ binSha256: "9568debf4a41da54f62d19bd7a29fbaf7dcc34c32d4ee472ab8560caefbcb372",
12
+ /** Bytes of that binary (vendor). */
13
+ binBytes: 17_704_644,
14
+ };
15
+ let licenceShown = false;
16
+ /** The tensors the network reads and the dtype the format fixes for each. */
17
+ export function requiredTensors(d) {
18
+ const c = d.hidden + d.dIn;
19
+ const h = d.hidden;
20
+ const out = [];
21
+ const lin = (p, rows, cols) => {
22
+ out.push({ key: `${p}.weight`, dtype: "f16", shape: [rows, cols] });
23
+ out.push({ key: `${p}.bias`, dtype: "f32", shape: [rows] });
24
+ };
25
+ lin("estimator.l1", h, d.dIn);
26
+ lin("estimator.l2", h, h);
27
+ lin("estimator.l3", h, h);
28
+ lin("denoiser.l1", h, c);
29
+ lin("denoiser.l2", h, h);
30
+ lin("denoiser.l3", h, h);
31
+ lin("decoder.l1.linear", h, c);
32
+ lin("decoder.l2.linear", h, h);
33
+ lin("decoder.l3.linear", d.dOut, h);
34
+ [c, h, h].forEach((n, i) => {
35
+ for (const part of ["scale", "shift"]) {
36
+ out.push({ key: `decoder.l${i + 1}.film.${part}.weight`, dtype: "f32", shape: [n, 1] });
37
+ out.push({ key: `decoder.l${i + 1}.film.${part}.bias`, dtype: "f32", shape: [n] });
38
+ }
39
+ });
40
+ out.push({ key: "input_stats.mean", dtype: "f32", shape: [d.dIn] }, { key: "input_stats.std", dtype: "f32", shape: [d.dIn] });
41
+ out.push({ key: "output_stats.mean", dtype: "f32", shape: [d.dOut] }, { key: "output_stats.std", dtype: "f32", shape: [d.dOut] });
42
+ out.push({ key: "time_stats.mean", dtype: "f32", shape: [1] }, { key: "time_stats.std", dtype: "f32", shape: [1] });
43
+ out.push({ key: "timing", dtype: "f32", shape: [d.frames] });
44
+ return out;
45
+ }
46
+ const fail = (msg) => {
47
+ throw new Error(`motion-net: ${msg}`);
48
+ };
49
+ /** Dimensions from the manifest `model` section, checked for consistency. */
50
+ export function dimsOf(m) {
51
+ const md = m.model ?? fail("manifest has no model section");
52
+ const num = (k) => {
53
+ const v = md[k];
54
+ if (typeof v !== "number" || !Number.isInteger(v) || v <= 0)
55
+ fail(`model.${String(k)} is missing or not a positive integer`);
56
+ return v;
57
+ };
58
+ const d = {
59
+ dIn: num("input_dim"),
60
+ dOut: num("output_dim"),
61
+ hidden: num("latent_dim"),
62
+ group: num("codebook_dims"),
63
+ frames: num("sequence_length"),
64
+ passes: num("denoiser_iterations"),
65
+ };
66
+ if (num("codebook_channels") * d.group !== d.hidden)
67
+ fail("codebook_channels times codebook_dims is not latent_dim");
68
+ return d;
69
+ }
70
+ /** Checks a manifest against a binary of `binBytes` bytes. Returns the problems, empty when fine. */
71
+ export function validate(m, binBytes) {
72
+ const errs = [];
73
+ let d;
74
+ try {
75
+ d = dimsOf(m);
76
+ }
77
+ catch (e) {
78
+ return [e.message];
79
+ }
80
+ const bin = m.bin ?? {};
81
+ const size = { f16: 2, f32: 4 };
82
+ const check = (key, dtype, shape) => {
83
+ const t = bin[key];
84
+ if (!t)
85
+ return void errs.push(`tensor ${key} is missing`);
86
+ if (t.dtype !== dtype)
87
+ errs.push(`tensor ${key} is ${t.dtype}, expected ${dtype}`);
88
+ if (!Array.isArray(t.shape) || t.shape.join(",") !== shape.join(","))
89
+ errs.push(`tensor ${key} has shape [${t.shape}], expected [${shape}]`);
90
+ const n = shape.reduce((a, b) => a * b, 1);
91
+ if (t.count !== n)
92
+ errs.push(`tensor ${key} has ${t.count} elements, expected ${n}`);
93
+ if (t.offset % 4 !== 0)
94
+ errs.push(`tensor ${key} offset ${t.offset} is not a multiple of 4`);
95
+ const s = size[t.dtype];
96
+ if (s && t.offset + t.count * s > binBytes)
97
+ errs.push(`tensor ${key} runs past the end of the ${binBytes} byte binary`);
98
+ };
99
+ for (const t of requiredTensors(d))
100
+ check(t.key, t.dtype, t.shape);
101
+ const names = m.skeleton?.bone_names ?? [];
102
+ if (names.length !== BONE_COUNT || names.some((n, i) => n !== BONES[i]))
103
+ errs.push("skeleton.bone_names differ from the 27 bone order");
104
+ if (d.dIn === 339)
105
+ for (const s of STYLES)
106
+ check(`guidance.${s}`, "f32", [27, 3]);
107
+ return errs;
108
+ }
109
+ async function bytesOf(src, opts) {
110
+ if (src instanceof ArrayBuffer)
111
+ return src;
112
+ if (ArrayBuffer.isView(src))
113
+ return src.buffer.slice(src.byteOffset, src.byteOffset + src.byteLength);
114
+ if (typeof Blob !== "undefined" && src instanceof Blob)
115
+ return src.arrayBuffer();
116
+ const f = opts.fetch ?? globalThis.fetch;
117
+ let res;
118
+ try {
119
+ res = await f(String(src));
120
+ }
121
+ catch (e) {
122
+ return fail(`could not fetch ${String(src)}: ${e.message}`);
123
+ }
124
+ if (!res.ok)
125
+ fail(`fetch ${String(src)} answered ${res.status}`);
126
+ // with a content-encoding the length header is the compressed size; report no total
127
+ const total = res.headers.get("content-encoding") ? 0 : Number(res.headers.get("content-length") ?? 0);
128
+ if (!opts.onProgress || !res.body)
129
+ return res.arrayBuffer();
130
+ const reader = res.body.getReader();
131
+ const parts = [];
132
+ let loaded = 0;
133
+ for (;;) {
134
+ const { done, value } = await reader.read();
135
+ if (done)
136
+ break;
137
+ parts.push(value);
138
+ loaded += value.byteLength;
139
+ opts.onProgress(loaded, total);
140
+ }
141
+ const out = new Uint8Array(loaded);
142
+ let o = 0;
143
+ for (const p of parts) {
144
+ out.set(p, o);
145
+ o += p.byteLength;
146
+ }
147
+ return out.buffer;
148
+ }
149
+ export async function sha256Hex(buf) {
150
+ const d = await crypto.subtle.digest("SHA-256", buf);
151
+ return Array.from(new Uint8Array(d), (b) => b.toString(16).padStart(2, "0")).join("");
152
+ }
153
+ function f32At(bin, t) {
154
+ // offsets are multiples of 4, so an aligned view is safe; copy so the result outlives the blob
155
+ return new Float32Array(bin, t.offset, t.count).slice();
156
+ }
157
+ /** Fetches or reads both parts, checks them, and states the licence once per page. */
158
+ export async function loadWeights(opts) {
159
+ if (!licenceShown) {
160
+ licenceShown = true;
161
+ (opts.onLicence ?? ((t) => console.info(t)))(WEIGHT_LICENCE);
162
+ }
163
+ let manifest;
164
+ const ms = opts.manifest;
165
+ if (typeof ms === "object" && ms !== null && "bin" in ms && "model" in ms)
166
+ manifest = ms;
167
+ else {
168
+ const text = new TextDecoder().decode(await bytesOf(ms, opts));
169
+ try {
170
+ manifest = JSON.parse(text);
171
+ }
172
+ catch {
173
+ return fail("the manifest is not JSON");
174
+ }
175
+ }
176
+ const bin = await bytesOf(opts.bin, opts);
177
+ let sha = null;
178
+ if (opts.sha256) {
179
+ sha = await sha256Hex(bin);
180
+ if (sha !== opts.sha256.toLowerCase())
181
+ fail(`sha-256 of the binary is ${sha}, expected ${opts.sha256}`);
182
+ }
183
+ const errs = validate(manifest, bin.byteLength);
184
+ if (errs.length)
185
+ fail(`the weights do not match the format: ${errs.slice(0, 4).join("; ")}${errs.length > 4 ? `; and ${errs.length - 4} more` : ""}`);
186
+ const dims = dimsOf(manifest);
187
+ const tensors = requiredTensors(dims).map((t) => {
188
+ const e = manifest.bin[t.key];
189
+ return { key: t.key, dtype: t.dtype, offset: e.offset, count: e.count };
190
+ });
191
+ const styles = Object.fromEntries(STYLES.map((s) => [s, manifest.bin[`guidance.${s}`] ? f32At(bin, manifest.bin[`guidance.${s}`]) : new Float32Array(81)]));
192
+ return {
193
+ manifest,
194
+ bin,
195
+ dims,
196
+ tensors,
197
+ styles,
198
+ inputMean: f32At(bin, manifest.bin["input_stats.mean"]),
199
+ inputStd: f32At(bin, manifest.bin["input_stats.std"]),
200
+ sha256: sha,
201
+ licence: WEIGHT_LICENCE,
202
+ };
203
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@hackbuild/motion-net",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Runtime and quadruped gait host for a categorical codebook matching motion network. Loads external CC BY-NC 4.0 weights at run time. Rust core on wasm SIMD128, worker with an in-page fallback.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Moheeb Zara <hackbuildvideo@gmail.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/hackbuild/hackbuild-motion.git",
11
+ "directory": "packages/motion-net"
12
+ },
13
+ "engines": {
14
+ "node": "^22.18.0 || >=24.11.0"
15
+ },
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./inline": {
23
+ "types": "./dist/wasm/inline.d.ts",
24
+ "import": "./dist/wasm/inline.js"
25
+ },
26
+ "./wasm": "./dist/wasm/motion_net_bg.wasm",
27
+ "./iife": "./dist/motion-net.iife.js"
28
+ },
29
+ "unpkg": "dist/motion-net.iife.js",
30
+ "jsdelivr": "dist/motion-net.iife.js",
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "scripts": {
37
+ "build": "node ../../tools/build-package.mjs motion-net"
38
+ }
39
+ }