@nirs4all/methods 1.2.0 → 1.3.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.
- package/README.md +57 -2
- package/dist/estimatorRolesGenerated.d.ts +17 -0
- package/dist/estimatorRolesGenerated.js +17 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/multimodalPipeline.d.ts +68 -0
- package/dist/multimodalPipeline.js +579 -0
- package/dist/n4m.js +1 -1
- package/dist/n4m.wasm +0 -0
- package/dist/optimization.d.ts +114 -0
- package/dist/optimization.js +637 -0
- package/dist/rolePipeline.d.ts +9 -4
- package/dist/rolePipeline.js +96 -9
- package/dist/spectralEncoding.d.ts +27 -0
- package/dist/spectralEncoding.js +92 -0
- package/package.json +2 -2
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
// SPDX-License-Identifier: CECILL-2.1
|
|
2
|
+
// Raw tensor marshalling only. Learned encoders/fusion/Ridge live in libn4m.
|
|
3
|
+
import { checkStatus, getModule, makeMatrixView } from "./ffi.js";
|
|
4
|
+
import { nativeParams, withContext } from "./estimatorRoles.js";
|
|
5
|
+
const ORDER = ["nir", "image", "series", "metadata"];
|
|
6
|
+
function sourceOrder(value) {
|
|
7
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > ORDER.length ||
|
|
8
|
+
value.some((name) => typeof name !== "string" || !ORDER.includes(name)) ||
|
|
9
|
+
new Set(value).size !== value.length)
|
|
10
|
+
throw new TypeError("source_order must select 1..4 distinct U07 modalities");
|
|
11
|
+
return [...value];
|
|
12
|
+
}
|
|
13
|
+
// wasm32 layouts of multimodal.h (double/int64 align to eight bytes).
|
|
14
|
+
const SPEC_SIZE = 96, RECIPE_SIZE = 40, VIEW_SIZE = 56;
|
|
15
|
+
function utf8(value) {
|
|
16
|
+
if (typeof value !== "string")
|
|
17
|
+
throw new TypeError("expected a Unicode string");
|
|
18
|
+
const encoded = new TextEncoder().encode(value);
|
|
19
|
+
if (new TextDecoder("utf-8", { fatal: true }).decode(encoded) !== value)
|
|
20
|
+
throw new TypeError("string contains an unpaired surrogate");
|
|
21
|
+
return encoded;
|
|
22
|
+
}
|
|
23
|
+
function keys(value, expected, label) {
|
|
24
|
+
if (value === null || typeof value !== "object" ||
|
|
25
|
+
Object.keys(value).sort().join("\0") !== [...expected].sort().join("\0")) {
|
|
26
|
+
throw new TypeError(`${label} has invalid fields`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function integer(value) {
|
|
30
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value))
|
|
31
|
+
throw new TypeError("expected an exact integer");
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
function flag(value) {
|
|
35
|
+
if (typeof value !== "boolean")
|
|
36
|
+
throw new TypeError("expected a boolean");
|
|
37
|
+
return value ? 1 : 0;
|
|
38
|
+
}
|
|
39
|
+
class Arena {
|
|
40
|
+
allocations = [];
|
|
41
|
+
alloc(size) {
|
|
42
|
+
const m = getModule(), p = m._malloc(Math.max(1, size));
|
|
43
|
+
if (p === 0)
|
|
44
|
+
throw new Error("native allocation failed");
|
|
45
|
+
this.allocations.push(p);
|
|
46
|
+
m.HEAPU8.fill(0, p, p + Math.max(1, size));
|
|
47
|
+
return p;
|
|
48
|
+
}
|
|
49
|
+
bytes(bytes) {
|
|
50
|
+
const p = this.alloc(bytes.length);
|
|
51
|
+
getModule().HEAPU8.set(bytes, p);
|
|
52
|
+
return p;
|
|
53
|
+
}
|
|
54
|
+
text(value) {
|
|
55
|
+
if (typeof value !== "string" || value.includes("\0"))
|
|
56
|
+
throw new TypeError("expected a string without NUL");
|
|
57
|
+
return this.bytes(utf8(value + "\0"));
|
|
58
|
+
}
|
|
59
|
+
ints(values) {
|
|
60
|
+
const p = this.alloc(values.length * 8);
|
|
61
|
+
values.forEach((v, i) => i64(p + i * 8, integer(v)));
|
|
62
|
+
return p;
|
|
63
|
+
}
|
|
64
|
+
close() { this.allocations.reverse().forEach((p) => getModule()._free(p)); }
|
|
65
|
+
}
|
|
66
|
+
function i32(p, value) { getModule().setValue(p, value, "i32"); }
|
|
67
|
+
function i64(p, value) {
|
|
68
|
+
new DataView(getModule().HEAPU8.buffer).setBigInt64(p, BigInt(value), true);
|
|
69
|
+
}
|
|
70
|
+
function f64(p, value) {
|
|
71
|
+
if (typeof value !== "number")
|
|
72
|
+
throw new TypeError("expected a number");
|
|
73
|
+
new DataView(getModule().HEAPU8.buffer).setFloat64(p, value, true);
|
|
74
|
+
}
|
|
75
|
+
function schema(p, value, arena) {
|
|
76
|
+
keys(value, ["representation_id", "input_shape", "dtype", "identity"], "source schema");
|
|
77
|
+
i32(p + 8, arena.text(value.representation_id));
|
|
78
|
+
i32(p + 12, arena.text(value.dtype));
|
|
79
|
+
if (typeof value.identity !== "string")
|
|
80
|
+
throw new TypeError("identity must be the original schema string");
|
|
81
|
+
const bytes = utf8(value.identity);
|
|
82
|
+
i32(p + 16, arena.bytes(bytes));
|
|
83
|
+
i32(p + 20, bytes.length);
|
|
84
|
+
}
|
|
85
|
+
function sourceConfiguration(recipe, schemas, arena) {
|
|
86
|
+
keys(recipe, ["schema_version", "fusion", "source_order", "encoders", "source_weights", "model"], "recipe");
|
|
87
|
+
if (recipe.schema_version !== 1 || recipe.fusion !== "early")
|
|
88
|
+
throw new TypeError("expected v1 early-fusion recipe");
|
|
89
|
+
const order = sourceOrder(recipe.source_order);
|
|
90
|
+
keys(recipe.encoders, order, "encoders");
|
|
91
|
+
keys(recipe.source_weights, order, "weights");
|
|
92
|
+
keys(schemas, order, "schemas");
|
|
93
|
+
const sources = arena.alloc(order.length * SPEC_SIZE);
|
|
94
|
+
order.forEach((name, index) => {
|
|
95
|
+
const p = sources + index * SPEC_SIZE, encoder = recipe.encoders[name];
|
|
96
|
+
i32(p, SPEC_SIZE);
|
|
97
|
+
i32(p + 4, arena.text(name));
|
|
98
|
+
schema(p, schemas[name], arena);
|
|
99
|
+
const shape = schemas[name].input_shape;
|
|
100
|
+
i32(p + 24, shape.length);
|
|
101
|
+
i32(p + 28, arena.ints(shape));
|
|
102
|
+
f64(p + 40, recipe.source_weights[name]);
|
|
103
|
+
i64(p + 80, -1);
|
|
104
|
+
i64(p + 88, -1);
|
|
105
|
+
if (encoder.kind === "standard_scaler") {
|
|
106
|
+
keys(encoder, ["kind", "with_mean", "with_std"], "scaler");
|
|
107
|
+
i32(p + 32, 1);
|
|
108
|
+
i32(p + 64, flag(encoder.with_mean));
|
|
109
|
+
i32(p + 68, flag(encoder.with_std));
|
|
110
|
+
}
|
|
111
|
+
else if (encoder.kind === "tensor_pca") {
|
|
112
|
+
keys(encoder, ["kind", "n_components", "random_state", "whiten"], "PCA");
|
|
113
|
+
i32(p + 32, 2);
|
|
114
|
+
i64(p + 48, integer(encoder.n_components));
|
|
115
|
+
i64(p + 56, integer(encoder.random_state));
|
|
116
|
+
i32(p + 72, flag(encoder.whiten));
|
|
117
|
+
}
|
|
118
|
+
else if (encoder.kind === "column_transformer") {
|
|
119
|
+
keys(encoder, ["kind", "numeric_columns", "categorical_columns", "with_mean", "with_std", "handle_unknown", "sparse_output", "drop"], "mixed encoder");
|
|
120
|
+
if (JSON.stringify(encoder.numeric_columns) !== "[0]" || JSON.stringify(encoder.categorical_columns) !== "[1]" ||
|
|
121
|
+
encoder.handle_unknown !== "ignore" || encoder.sparse_output !== false || encoder.drop !== null)
|
|
122
|
+
throw new TypeError("unsupported mixed-column recipe");
|
|
123
|
+
i32(p + 32, 3);
|
|
124
|
+
i32(p + 64, flag(encoder.with_mean));
|
|
125
|
+
i32(p + 68, flag(encoder.with_std));
|
|
126
|
+
i32(p + 76, 1);
|
|
127
|
+
i64(p + 80, 0);
|
|
128
|
+
i64(p + 88, 1);
|
|
129
|
+
}
|
|
130
|
+
else
|
|
131
|
+
throw new TypeError("unsupported encoder");
|
|
132
|
+
});
|
|
133
|
+
return { sources, order };
|
|
134
|
+
}
|
|
135
|
+
function configuration(recipe, schemas, arena) {
|
|
136
|
+
keys(recipe.model, ["method_id", "params"], "model");
|
|
137
|
+
keys(recipe.model.params, ["alpha", "center_x", "center_y", "scale_x"], "Ridge parameters");
|
|
138
|
+
if (recipe.model.method_id !== "models.regularized.ridge")
|
|
139
|
+
throw new TypeError("expected native Ridge");
|
|
140
|
+
const { sources, order } = sourceConfiguration(recipe, schemas, arena);
|
|
141
|
+
const p = arena.alloc(RECIPE_SIZE), params = recipe.model.params;
|
|
142
|
+
i32(p, RECIPE_SIZE);
|
|
143
|
+
i32(p + 4, order.length);
|
|
144
|
+
i32(p + 8, sources);
|
|
145
|
+
f64(p + 16, params.alpha);
|
|
146
|
+
i32(p + 24, flag(params.center_x));
|
|
147
|
+
i32(p + 28, flag(params.center_y));
|
|
148
|
+
i32(p + 32, flag(params.scale_x));
|
|
149
|
+
return p;
|
|
150
|
+
}
|
|
151
|
+
function withClassifierConfiguration(recipe, schemas, arena, ctx, fn) {
|
|
152
|
+
checkStatus(getModule().ccall("n4m_check_abi_compatibility", "number", ["number", "number"], [2, 17]), ctx);
|
|
153
|
+
keys(recipe.model, ["method_id", "params"], "model");
|
|
154
|
+
keys(recipe.model.params, ["n_components", "max_iter"], "classifier parameters");
|
|
155
|
+
if (recipe.model.method_id !== "models.classification.pls_logistic")
|
|
156
|
+
throw new TypeError("expected native PLS-logistic classifier");
|
|
157
|
+
const nComponents = integer(recipe.model.params.n_components), maxIter = integer(recipe.model.params.max_iter);
|
|
158
|
+
if (nComponents < 1 || maxIter < 1)
|
|
159
|
+
throw new RangeError("classifier parameters must be positive integers");
|
|
160
|
+
const { sources, order } = sourceConfiguration(recipe, schemas, arena);
|
|
161
|
+
const head = { methodId: recipe.model.method_id,
|
|
162
|
+
paramTypes: { n_components: "int", max_iter: "int" },
|
|
163
|
+
params: { n_components: nComponents, max_iter: maxIter } };
|
|
164
|
+
const params = nativeParams(ctx, head);
|
|
165
|
+
try {
|
|
166
|
+
// wasm32 classifier recipe: size/count/sources/method_id/params, all four-byte fields.
|
|
167
|
+
const p = arena.alloc(20);
|
|
168
|
+
i32(p, 20);
|
|
169
|
+
i32(p + 4, order.length);
|
|
170
|
+
i32(p + 8, sources);
|
|
171
|
+
i32(p + 12, arena.text(head.methodId));
|
|
172
|
+
i32(p + 16, params);
|
|
173
|
+
return fn(p);
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
getModule().ccall("n4m_params_destroy", null, ["number"], [params]);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function views(blocks, schemas, arena, order) {
|
|
180
|
+
keys(blocks, [...order], "blocks");
|
|
181
|
+
keys(schemas, [...order], "schemas");
|
|
182
|
+
const pointer = arena.alloc(order.length * VIEW_SIZE);
|
|
183
|
+
let rows = -1;
|
|
184
|
+
order.forEach((name, index) => {
|
|
185
|
+
const p = pointer + index * VIEW_SIZE, raw = blocks[name];
|
|
186
|
+
i32(p, VIEW_SIZE);
|
|
187
|
+
i32(p + 4, arena.text(name));
|
|
188
|
+
schema(p, schemas[name], arena);
|
|
189
|
+
let shape, strides, data;
|
|
190
|
+
if (name === "metadata") {
|
|
191
|
+
if (!Array.isArray(raw))
|
|
192
|
+
throw new TypeError("metadata must contain raw [numeric, category] rows");
|
|
193
|
+
shape = [raw.length, 2];
|
|
194
|
+
strides = [1, 1];
|
|
195
|
+
data = new Float64Array(raw.length);
|
|
196
|
+
const offsets = arena.alloc((raw.length + 1) * 8), chunks = [];
|
|
197
|
+
let bytes = 0;
|
|
198
|
+
i64(offsets, 0);
|
|
199
|
+
raw.forEach((row, i) => {
|
|
200
|
+
if (!Array.isArray(row) || row.length !== 2 || typeof row[1] !== "string" ||
|
|
201
|
+
!(typeof row[0] === "number" || typeof row[0] === "string") ||
|
|
202
|
+
(typeof row[0] === "string" && !/^[\t\n\r ]*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[\t\n\r ]*$/.test(row[0])))
|
|
203
|
+
throw new TypeError("invalid declared metadata cells");
|
|
204
|
+
data[i] = Number(row[0]);
|
|
205
|
+
if (!Number.isFinite(data[i]))
|
|
206
|
+
throw new TypeError("metadata numeric cell must be finite");
|
|
207
|
+
const chunk = utf8(row[1]);
|
|
208
|
+
if (chunk.length > 1024 * 1024 || bytes + chunk.length > 64 * 1024 * 1024)
|
|
209
|
+
throw new TypeError("categorical UTF-8 input exceeds native bounds");
|
|
210
|
+
chunks.push(chunk);
|
|
211
|
+
bytes += chunk.length;
|
|
212
|
+
i64(offsets + (i + 1) * 8, bytes);
|
|
213
|
+
});
|
|
214
|
+
const categories = arena.alloc(bytes);
|
|
215
|
+
let position = categories;
|
|
216
|
+
chunks.forEach((chunk) => { getModule().HEAPU8.set(chunk, position); position += chunk.length; });
|
|
217
|
+
i32(p + 44, categories);
|
|
218
|
+
i32(p + 48, bytes);
|
|
219
|
+
i32(p + 52, offsets);
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
if (Array.isArray(raw) || !(raw.data instanceof Float32Array || raw.data instanceof Float64Array))
|
|
223
|
+
throw new TypeError("numeric source needs a typed raw tensor");
|
|
224
|
+
shape = raw.shape.map(integer);
|
|
225
|
+
data = raw.data;
|
|
226
|
+
strides = raw.strides ? raw.strides.map(integer) : shape.map((_, i) => shape.slice(i + 1).reduce((a, b) => a * b, 1));
|
|
227
|
+
if (strides.length !== shape.length || strides.some((s) => s < 0))
|
|
228
|
+
throw new TypeError("invalid tensor strides");
|
|
229
|
+
const last = shape.reduce((n, d, i) => n + Math.max(0, d - 1) * strides[i], 0);
|
|
230
|
+
if (shape.every((d) => d > 0) && last >= data.length)
|
|
231
|
+
throw new TypeError("raw tensor buffer is too short");
|
|
232
|
+
}
|
|
233
|
+
if (shape.slice(1).join("\0") !== schemas[name].input_shape.join("\0"))
|
|
234
|
+
throw new TypeError("raw source shape differs from its schema");
|
|
235
|
+
if (rows !== -1 && rows !== shape[0])
|
|
236
|
+
throw new TypeError("source row counts differ");
|
|
237
|
+
rows = shape[0];
|
|
238
|
+
const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
239
|
+
i32(p + 24, shape.length);
|
|
240
|
+
i32(p + 28, arena.ints(shape));
|
|
241
|
+
i32(p + 32, arena.ints(strides));
|
|
242
|
+
i32(p + 36, arena.bytes(bytes));
|
|
243
|
+
i32(p + 40, data instanceof Float64Array ? 1 : 2);
|
|
244
|
+
});
|
|
245
|
+
return { pointer, rows };
|
|
246
|
+
}
|
|
247
|
+
/** Complete native early-fusion pipeline, portable as a bounded N4MF state. */
|
|
248
|
+
export class MultimodalPipeline {
|
|
249
|
+
ptr = 0;
|
|
250
|
+
sourceOrder;
|
|
251
|
+
recipe;
|
|
252
|
+
sourceSchemas;
|
|
253
|
+
constructor(recipe, sourceSchemas) {
|
|
254
|
+
this.recipe = structuredClone(recipe);
|
|
255
|
+
this.sourceSchemas = structuredClone(sourceSchemas);
|
|
256
|
+
this.sourceOrder = sourceOrder(this.recipe.source_order);
|
|
257
|
+
const arena = new Arena();
|
|
258
|
+
try {
|
|
259
|
+
const config = configuration(this.recipe, this.sourceSchemas, arena), out = arena.alloc(4);
|
|
260
|
+
withContext((ctx) => checkStatus(getModule().ccall("n4m_multimodal_pipeline_create", "number", ["number", "number", "number"], [ctx, config, out]), ctx));
|
|
261
|
+
this.ptr = getModule().getValue(out, "i32");
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
arena.close();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
handle() { if (!this.ptr)
|
|
268
|
+
throw new Error("MultimodalPipeline is closed"); return this.ptr; }
|
|
269
|
+
fit(blocks, y) {
|
|
270
|
+
const arena = new Arena();
|
|
271
|
+
try {
|
|
272
|
+
const x = views(blocks, this.sourceSchemas, arena, this.sourceOrder), target = y instanceof Float64Array ? { data: y, rows: x.rows, cols: 1 } : y;
|
|
273
|
+
if (target.rows !== x.rows || target.cols !== 1)
|
|
274
|
+
throw new TypeError("expected one target per raw source row");
|
|
275
|
+
const matrix = makeMatrixView(target.data, target.rows, 1);
|
|
276
|
+
try {
|
|
277
|
+
withContext((ctx) => checkStatus(getModule().ccall("n4m_multimodal_pipeline_fit", "number", ["number", "number", "number", "number", "number"], [ctx, this.handle(), this.sourceOrder.length, x.pointer, matrix.viewPtr]), ctx));
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
matrix.free();
|
|
281
|
+
}
|
|
282
|
+
return this;
|
|
283
|
+
}
|
|
284
|
+
finally {
|
|
285
|
+
arena.close();
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
predict(blocks, schemas = this.sourceSchemas) { return this.operation(blocks, schemas, false); }
|
|
289
|
+
transform(blocks, schemas = this.sourceSchemas) { return this.operation(blocks, schemas, true); }
|
|
290
|
+
operation(blocks, schemas, transform) {
|
|
291
|
+
const arena = new Arena();
|
|
292
|
+
try {
|
|
293
|
+
const x = views(blocks, schemas, arena, this.sourceOrder);
|
|
294
|
+
let cols = 1;
|
|
295
|
+
if (transform) {
|
|
296
|
+
const out = arena.alloc(8);
|
|
297
|
+
checkStatus(getModule().ccall("n4m_multimodal_pipeline_transform_cols", "number", ["number", "number"], [this.handle(), out]));
|
|
298
|
+
cols = Number(new DataView(getModule().HEAPU8.buffer).getBigInt64(out, true));
|
|
299
|
+
}
|
|
300
|
+
const matrix = makeMatrixView(new Float64Array(x.rows * cols), x.rows, cols);
|
|
301
|
+
try {
|
|
302
|
+
withContext((ctx) => checkStatus(getModule().ccall("n4m_multimodal_pipeline_" + (transform ? "transform" : "predict"), "number", ["number", "number", "number", "number", "number"], [ctx, this.handle(), this.sourceOrder.length, x.pointer, matrix.viewPtr]), ctx));
|
|
303
|
+
return { data: getModule().HEAPF64.slice(matrix.dataPtr / 8, matrix.dataPtr / 8 + x.rows * cols), rows: x.rows, cols };
|
|
304
|
+
}
|
|
305
|
+
finally {
|
|
306
|
+
matrix.free();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
finally {
|
|
310
|
+
arena.close();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
exportState() {
|
|
314
|
+
const arena = new Arena();
|
|
315
|
+
try {
|
|
316
|
+
return withContext((ctx) => {
|
|
317
|
+
const size = arena.alloc(4), m = getModule();
|
|
318
|
+
checkStatus(m.ccall("n4m_multimodal_pipeline_export_size", "number", ["number", "number", "number"], [ctx, this.handle(), size]), ctx);
|
|
319
|
+
const capacity = m.getValue(size, "i32"), buffer = arena.alloc(capacity);
|
|
320
|
+
checkStatus(m.ccall("n4m_multimodal_pipeline_export_to_buffer", "number", ["number", "number", "number", "number", "number"], [ctx, this.handle(), buffer, capacity, size]), ctx);
|
|
321
|
+
return m.HEAPU8.slice(buffer, buffer + m.getValue(size, "i32"));
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
finally {
|
|
325
|
+
arena.close();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
static fromState(state, recipe, sourceSchemas) {
|
|
329
|
+
if (!(state instanceof Uint8Array) || state.length > 64 * 1024 * 1024)
|
|
330
|
+
throw new TypeError("expected bounded N4MF bytes");
|
|
331
|
+
const model = new MultimodalPipeline(recipe, sourceSchemas), arena = new Arena();
|
|
332
|
+
try {
|
|
333
|
+
const config = configuration(recipe, sourceSchemas, arena), buffer = arena.bytes(state), out = arena.alloc(4);
|
|
334
|
+
withContext((ctx) => checkStatus(getModule().ccall("n4m_multimodal_pipeline_import_from_buffer", "number", ["number", "number", "number", "number", "number"], [ctx, config, buffer, state.length, out]), ctx));
|
|
335
|
+
model.dispose();
|
|
336
|
+
model.ptr = getModule().getValue(out, "i32");
|
|
337
|
+
return model;
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
model.dispose();
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
finally {
|
|
344
|
+
arena.close();
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
dispose() { if (this.ptr) {
|
|
348
|
+
getModule().ccall("n4m_multimodal_pipeline_destroy", null, ["number"], [this.ptr]);
|
|
349
|
+
this.ptr = 0;
|
|
350
|
+
} }
|
|
351
|
+
}
|
|
352
|
+
function classifierLabelTable(value) {
|
|
353
|
+
if (!Array.isArray(value) || value.length < 2)
|
|
354
|
+
throw new TypeError("expected at least two class labels");
|
|
355
|
+
if (value.length > 65536)
|
|
356
|
+
throw new RangeError("class count exceeds native bounds");
|
|
357
|
+
const kind = typeof value[0];
|
|
358
|
+
if (kind !== "string" && kind !== "number")
|
|
359
|
+
throw new TypeError("class labels must be strings or integers");
|
|
360
|
+
for (const label of value) {
|
|
361
|
+
if (typeof label !== kind)
|
|
362
|
+
throw new TypeError("class labels must be homogeneous strings or integers");
|
|
363
|
+
if (typeof label === "string") {
|
|
364
|
+
if (utf8(label).length > 1024 * 1024)
|
|
365
|
+
throw new RangeError("class label exceeds the UTF-8 bound");
|
|
366
|
+
}
|
|
367
|
+
else if (!Number.isSafeInteger(label))
|
|
368
|
+
throw new RangeError("numeric class labels must be exact safe integers");
|
|
369
|
+
}
|
|
370
|
+
if (new Set(value).size !== value.length)
|
|
371
|
+
throw new TypeError("class_names must contain unique labels");
|
|
372
|
+
return [...value];
|
|
373
|
+
}
|
|
374
|
+
function classifierLabels(y, rows) {
|
|
375
|
+
if (!Array.isArray(y) || y.length !== rows)
|
|
376
|
+
throw new TypeError("expected one class label per raw source row");
|
|
377
|
+
const names = classifierLabelTable([...new Set(y)]);
|
|
378
|
+
if (typeof names[0] === "number")
|
|
379
|
+
names.sort((a, b) => a - b);
|
|
380
|
+
else
|
|
381
|
+
names.sort((a, b) => {
|
|
382
|
+
// UTF-8/code-point order matches Python and R even for astral Unicode labels.
|
|
383
|
+
const x = utf8(a), z = utf8(b);
|
|
384
|
+
for (let i = 0; i < Math.min(x.length, z.length); ++i)
|
|
385
|
+
if (x[i] !== z[i])
|
|
386
|
+
return x[i] - z[i];
|
|
387
|
+
return x.length - z.length;
|
|
388
|
+
});
|
|
389
|
+
const index = new Map(names.map((label, i) => [label, i]));
|
|
390
|
+
return { names, ids: y.map((label) => index.get(label)) };
|
|
391
|
+
}
|
|
392
|
+
/** Native raw PLS-logistic classifier; N4MC states contain no training rows. */
|
|
393
|
+
export class MultimodalClassifierPipeline {
|
|
394
|
+
ptr = 0;
|
|
395
|
+
classNames;
|
|
396
|
+
sourceOrder;
|
|
397
|
+
recipe;
|
|
398
|
+
sourceSchemas;
|
|
399
|
+
constructor(recipe, sourceSchemas) {
|
|
400
|
+
this.recipe = structuredClone(recipe);
|
|
401
|
+
this.sourceSchemas = structuredClone(sourceSchemas);
|
|
402
|
+
this.sourceOrder = sourceOrder(this.recipe.source_order);
|
|
403
|
+
this.ptr = this.createHandle();
|
|
404
|
+
}
|
|
405
|
+
createHandle() {
|
|
406
|
+
const arena = new Arena();
|
|
407
|
+
try {
|
|
408
|
+
return withContext((ctx) => withClassifierConfiguration(this.recipe, this.sourceSchemas, arena, ctx, (config) => {
|
|
409
|
+
const out = arena.alloc(4);
|
|
410
|
+
checkStatus(getModule().ccall("n4m_multimodal_classifier_create", "number", ["number", "number", "number"], [ctx, config, out]), ctx);
|
|
411
|
+
return getModule().getValue(out, "i32");
|
|
412
|
+
}));
|
|
413
|
+
}
|
|
414
|
+
finally {
|
|
415
|
+
arena.close();
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
handle() { if (!this.ptr)
|
|
419
|
+
throw new Error("MultimodalClassifierPipeline is closed"); return this.ptr; }
|
|
420
|
+
static classIds(handle) {
|
|
421
|
+
const arena = new Arena(), m = getModule();
|
|
422
|
+
try {
|
|
423
|
+
const count = arena.alloc(8);
|
|
424
|
+
checkStatus(m.ccall("n4m_multimodal_classifier_classes", "number", ["number", "number", "i64", "number"], [handle, 0, 0n, count]));
|
|
425
|
+
const n = Number(new DataView(m.HEAPU8.buffer).getBigInt64(count, true));
|
|
426
|
+
if (!Number.isSafeInteger(n) || n < 2 || n > 65536)
|
|
427
|
+
throw new RangeError("native class count exceeds bounds");
|
|
428
|
+
const ids = arena.alloc(n * 8);
|
|
429
|
+
checkStatus(m.ccall("n4m_multimodal_classifier_classes", "number", ["number", "number", "i64", "number"], [handle, ids, BigInt(n), count]));
|
|
430
|
+
return Array.from({ length: n }, (_, i) => {
|
|
431
|
+
const raw = new DataView(m.HEAPU8.buffer).getBigInt64(ids + i * 8, true), id = Number(raw);
|
|
432
|
+
if (!Number.isSafeInteger(id) || BigInt(id) !== raw)
|
|
433
|
+
throw new RangeError("native class ID exceeds lossless JS range");
|
|
434
|
+
return id;
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
finally {
|
|
438
|
+
arena.close();
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
fit(blocks, y) {
|
|
442
|
+
this.handle();
|
|
443
|
+
const arena = new Arena();
|
|
444
|
+
let pending = 0;
|
|
445
|
+
try {
|
|
446
|
+
const x = views(blocks, this.sourceSchemas, arena, this.sourceOrder), labels = classifierLabels(y, x.rows);
|
|
447
|
+
if (x.rows * labels.names.length > 16777216)
|
|
448
|
+
throw new RangeError("classifier fit matrix exceeds native bounds");
|
|
449
|
+
pending = this.createHandle();
|
|
450
|
+
withContext((ctx) => checkStatus(getModule().ccall("n4m_multimodal_classifier_fit", "number", ["number", "number", "number", "number", "number", "i64"], [ctx, pending, this.sourceOrder.length, x.pointer, arena.ints(labels.ids), BigInt(x.rows)]), ctx));
|
|
451
|
+
const ids = MultimodalClassifierPipeline.classIds(pending);
|
|
452
|
+
if (ids.length !== labels.names.length || ids.some((id, i) => id !== i))
|
|
453
|
+
throw new Error("native classifier class order differs from the encoded label table");
|
|
454
|
+
const previous = this.ptr;
|
|
455
|
+
this.ptr = pending;
|
|
456
|
+
pending = 0;
|
|
457
|
+
this.classNames = labels.names;
|
|
458
|
+
getModule().ccall("n4m_multimodal_classifier_destroy", null, ["number"], [previous]);
|
|
459
|
+
return this;
|
|
460
|
+
}
|
|
461
|
+
finally {
|
|
462
|
+
if (pending)
|
|
463
|
+
getModule().ccall("n4m_multimodal_classifier_destroy", null, ["number"], [pending]);
|
|
464
|
+
arena.close();
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
classes() {
|
|
468
|
+
const ids = MultimodalClassifierPipeline.classIds(this.handle());
|
|
469
|
+
return this.classNames === undefined ? ids : [...this.classNames];
|
|
470
|
+
}
|
|
471
|
+
labelNames() { return this.classNames === undefined ? undefined : [...this.classNames]; }
|
|
472
|
+
predict(blocks, schemas = this.sourceSchemas) {
|
|
473
|
+
const handle = this.handle(), arena = new Arena(), m = getModule();
|
|
474
|
+
try {
|
|
475
|
+
const ids = MultimodalClassifierPipeline.classIds(handle), x = views(blocks, schemas, arena, this.sourceOrder);
|
|
476
|
+
if (x.rows * ids.length > 16777216)
|
|
477
|
+
throw new RangeError("classifier prediction matrix exceeds native bounds");
|
|
478
|
+
const out = arena.alloc(x.rows * 8), labels = this.classNames;
|
|
479
|
+
withContext((ctx) => checkStatus(m.ccall("n4m_multimodal_classifier_predict_labels", "number", ["number", "number", "number", "number", "number", "i64"], [ctx, handle, this.sourceOrder.length, x.pointer, out, BigInt(x.rows)]), ctx));
|
|
480
|
+
return Array.from({ length: x.rows }, (_, i) => {
|
|
481
|
+
const raw = new DataView(m.HEAPU8.buffer).getBigInt64(out + i * 8, true), id = Number(raw);
|
|
482
|
+
if (!Number.isSafeInteger(id) || BigInt(id) !== raw)
|
|
483
|
+
throw new RangeError("native prediction exceeds lossless JS range");
|
|
484
|
+
const index = ids.indexOf(id);
|
|
485
|
+
if (index < 0)
|
|
486
|
+
throw new Error("native prediction contains an undeclared class ID");
|
|
487
|
+
return labels === undefined ? id : labels[index];
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
finally {
|
|
491
|
+
arena.close();
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
predictProba(blocks, schemas = this.sourceSchemas) {
|
|
495
|
+
return this.matrixOperation(blocks, schemas, "predict_proba", "n_outputs");
|
|
496
|
+
}
|
|
497
|
+
decisionFunction(blocks, schemas = this.sourceSchemas) {
|
|
498
|
+
return this.matrixOperation(blocks, schemas, "decision_function", "n_outputs");
|
|
499
|
+
}
|
|
500
|
+
transform(blocks, schemas = this.sourceSchemas) {
|
|
501
|
+
return this.matrixOperation(blocks, schemas, "transform", "transform_cols");
|
|
502
|
+
}
|
|
503
|
+
matrixOperation(blocks, schemas, operation, widthSymbol) {
|
|
504
|
+
const handle = this.handle(), arena = new Arena(), m = getModule();
|
|
505
|
+
try {
|
|
506
|
+
const x = views(blocks, schemas, arena, this.sourceOrder), out = arena.alloc(8);
|
|
507
|
+
checkStatus(m.ccall("n4m_multimodal_classifier_" + widthSymbol, "number", ["number", "number"], [handle, out]));
|
|
508
|
+
const cols = Number(new DataView(m.HEAPU8.buffer).getBigInt64(out, true));
|
|
509
|
+
if (!Number.isSafeInteger(cols) || cols < 1 || x.rows * cols > 16777216)
|
|
510
|
+
throw new RangeError("native output shape exceeds bounds");
|
|
511
|
+
const matrix = makeMatrixView(new Float64Array(x.rows * cols), x.rows, cols);
|
|
512
|
+
try {
|
|
513
|
+
withContext((ctx) => checkStatus(m.ccall("n4m_multimodal_classifier_" + operation, "number", ["number", "number", "number", "number", "number"], [ctx, handle, this.sourceOrder.length, x.pointer, matrix.viewPtr]), ctx));
|
|
514
|
+
return { data: m.HEAPF64.slice(matrix.dataPtr / 8, matrix.dataPtr / 8 + x.rows * cols), rows: x.rows, cols };
|
|
515
|
+
}
|
|
516
|
+
finally {
|
|
517
|
+
matrix.free();
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
finally {
|
|
521
|
+
arena.close();
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
exportState() {
|
|
525
|
+
const handle = this.handle(), arena = new Arena();
|
|
526
|
+
try {
|
|
527
|
+
return withContext((ctx) => {
|
|
528
|
+
const m = getModule(), size = arena.alloc(4);
|
|
529
|
+
checkStatus(m.ccall("n4m_multimodal_classifier_export_size", "number", ["number", "number", "number"], [ctx, handle, size]), ctx);
|
|
530
|
+
const capacity = m.getValue(size, "i32");
|
|
531
|
+
if (capacity < 1 || capacity > 64 * 1024 * 1024)
|
|
532
|
+
throw new RangeError("N4MC state exceeds bounds");
|
|
533
|
+
const buffer = arena.alloc(capacity);
|
|
534
|
+
checkStatus(m.ccall("n4m_multimodal_classifier_export_to_buffer", "number", ["number", "number", "number", "number", "number"], [ctx, handle, buffer, capacity, size]), ctx);
|
|
535
|
+
return m.HEAPU8.slice(buffer, buffer + m.getValue(size, "i32"));
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
finally {
|
|
539
|
+
arena.close();
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
static fromState(state, recipe, sourceSchemas, options = {}) {
|
|
543
|
+
if (!(state instanceof Uint8Array) || !state.length || state.length > 64 * 1024 * 1024)
|
|
544
|
+
throw new TypeError("expected bounded N4MC bytes");
|
|
545
|
+
const names = options.classNames === undefined ? undefined : classifierLabelTable(options.classNames);
|
|
546
|
+
const model = new MultimodalClassifierPipeline(recipe, sourceSchemas), arena = new Arena();
|
|
547
|
+
let pending = 0;
|
|
548
|
+
try {
|
|
549
|
+
withContext((ctx) => withClassifierConfiguration(model.recipe, model.sourceSchemas, arena, ctx, (config) => {
|
|
550
|
+
const out = arena.alloc(4), bytes = arena.bytes(state);
|
|
551
|
+
checkStatus(getModule().ccall("n4m_multimodal_classifier_import_from_buffer", "number", ["number", "number", "number", "number", "number"], [ctx, config, bytes, state.length, out]), ctx);
|
|
552
|
+
pending = getModule().getValue(out, "i32");
|
|
553
|
+
}));
|
|
554
|
+
const ids = MultimodalClassifierPipeline.classIds(pending);
|
|
555
|
+
if (names !== undefined && names.length !== ids.length)
|
|
556
|
+
throw new TypeError("class_names length differs from native class columns");
|
|
557
|
+
model.dispose();
|
|
558
|
+
model.ptr = pending;
|
|
559
|
+
pending = 0;
|
|
560
|
+
model.classNames = names;
|
|
561
|
+
return model;
|
|
562
|
+
}
|
|
563
|
+
catch (error) {
|
|
564
|
+
model.dispose();
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
finally {
|
|
568
|
+
if (pending)
|
|
569
|
+
getModule().ccall("n4m_multimodal_classifier_destroy", null, ["number"], [pending]);
|
|
570
|
+
arena.close();
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
dispose() {
|
|
574
|
+
if (this.ptr)
|
|
575
|
+
getModule().ccall("n4m_multimodal_classifier_destroy", null, ["number"], [this.ptr]);
|
|
576
|
+
this.ptr = 0;
|
|
577
|
+
this.classNames = undefined;
|
|
578
|
+
}
|
|
579
|
+
}
|