warpvector 0.1.0 → 0.1.2

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/dist/index.mjs CHANGED
@@ -1,3 +1,598 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+
31
+ // node_modules/eventemitter3/index.js
32
+ var require_eventemitter3 = __commonJS({
33
+ "node_modules/eventemitter3/index.js"(exports, module) {
34
+ "use strict";
35
+ var has = Object.prototype.hasOwnProperty;
36
+ var prefix = "~";
37
+ function Events() {
38
+ }
39
+ if (Object.create) {
40
+ Events.prototype = /* @__PURE__ */ Object.create(null);
41
+ if (!new Events().__proto__) prefix = false;
42
+ }
43
+ function EE(fn, context, once) {
44
+ this.fn = fn;
45
+ this.context = context;
46
+ this.once = once || false;
47
+ }
48
+ function addListener(emitter, event, fn, context, once) {
49
+ if (typeof fn !== "function") {
50
+ throw new TypeError("The listener must be a function");
51
+ }
52
+ var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
53
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
54
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
55
+ else emitter._events[evt] = [emitter._events[evt], listener];
56
+ return emitter;
57
+ }
58
+ function clearEvent(emitter, evt) {
59
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
60
+ else delete emitter._events[evt];
61
+ }
62
+ function EventEmitter() {
63
+ this._events = new Events();
64
+ this._eventsCount = 0;
65
+ }
66
+ EventEmitter.prototype.eventNames = function eventNames() {
67
+ var names = [], events, name;
68
+ if (this._eventsCount === 0) return names;
69
+ for (name in events = this._events) {
70
+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
71
+ }
72
+ if (Object.getOwnPropertySymbols) {
73
+ return names.concat(Object.getOwnPropertySymbols(events));
74
+ }
75
+ return names;
76
+ };
77
+ EventEmitter.prototype.listeners = function listeners(event) {
78
+ var evt = prefix ? prefix + event : event, handlers = this._events[evt];
79
+ if (!handlers) return [];
80
+ if (handlers.fn) return [handlers.fn];
81
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
82
+ ee[i] = handlers[i].fn;
83
+ }
84
+ return ee;
85
+ };
86
+ EventEmitter.prototype.listenerCount = function listenerCount(event) {
87
+ var evt = prefix ? prefix + event : event, listeners = this._events[evt];
88
+ if (!listeners) return 0;
89
+ if (listeners.fn) return 1;
90
+ return listeners.length;
91
+ };
92
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
93
+ var evt = prefix ? prefix + event : event;
94
+ if (!this._events[evt]) return false;
95
+ var listeners = this._events[evt], len = arguments.length, args, i;
96
+ if (listeners.fn) {
97
+ if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
98
+ switch (len) {
99
+ case 1:
100
+ return listeners.fn.call(listeners.context), true;
101
+ case 2:
102
+ return listeners.fn.call(listeners.context, a1), true;
103
+ case 3:
104
+ return listeners.fn.call(listeners.context, a1, a2), true;
105
+ case 4:
106
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
107
+ case 5:
108
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
109
+ case 6:
110
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
111
+ }
112
+ for (i = 1, args = new Array(len - 1); i < len; i++) {
113
+ args[i - 1] = arguments[i];
114
+ }
115
+ listeners.fn.apply(listeners.context, args);
116
+ } else {
117
+ var length = listeners.length, j;
118
+ for (i = 0; i < length; i++) {
119
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
120
+ switch (len) {
121
+ case 1:
122
+ listeners[i].fn.call(listeners[i].context);
123
+ break;
124
+ case 2:
125
+ listeners[i].fn.call(listeners[i].context, a1);
126
+ break;
127
+ case 3:
128
+ listeners[i].fn.call(listeners[i].context, a1, a2);
129
+ break;
130
+ case 4:
131
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
132
+ break;
133
+ default:
134
+ if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
135
+ args[j - 1] = arguments[j];
136
+ }
137
+ listeners[i].fn.apply(listeners[i].context, args);
138
+ }
139
+ }
140
+ }
141
+ return true;
142
+ };
143
+ EventEmitter.prototype.on = function on(event, fn, context) {
144
+ return addListener(this, event, fn, context, false);
145
+ };
146
+ EventEmitter.prototype.once = function once(event, fn, context) {
147
+ return addListener(this, event, fn, context, true);
148
+ };
149
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
150
+ var evt = prefix ? prefix + event : event;
151
+ if (!this._events[evt]) return this;
152
+ if (!fn) {
153
+ clearEvent(this, evt);
154
+ return this;
155
+ }
156
+ var listeners = this._events[evt];
157
+ if (listeners.fn) {
158
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
159
+ clearEvent(this, evt);
160
+ }
161
+ } else {
162
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
163
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
164
+ events.push(listeners[i]);
165
+ }
166
+ }
167
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
168
+ else clearEvent(this, evt);
169
+ }
170
+ return this;
171
+ };
172
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
173
+ var evt;
174
+ if (event) {
175
+ evt = prefix ? prefix + event : event;
176
+ if (this._events[evt]) clearEvent(this, evt);
177
+ } else {
178
+ this._events = new Events();
179
+ this._eventsCount = 0;
180
+ }
181
+ return this;
182
+ };
183
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
184
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
185
+ EventEmitter.prefixed = prefix;
186
+ EventEmitter.EventEmitter = EventEmitter;
187
+ if ("undefined" !== typeof module) {
188
+ module.exports = EventEmitter;
189
+ }
190
+ }
191
+ });
192
+
193
+ // node_modules/p-finally/index.js
194
+ var require_p_finally = __commonJS({
195
+ "node_modules/p-finally/index.js"(exports, module) {
196
+ "use strict";
197
+ module.exports = (promise, onFinally) => {
198
+ onFinally = onFinally || (() => {
199
+ });
200
+ return promise.then(
201
+ (val) => new Promise((resolve) => {
202
+ resolve(onFinally());
203
+ }).then(() => val),
204
+ (err) => new Promise((resolve) => {
205
+ resolve(onFinally());
206
+ }).then(() => {
207
+ throw err;
208
+ })
209
+ );
210
+ };
211
+ }
212
+ });
213
+
214
+ // node_modules/p-timeout/index.js
215
+ var require_p_timeout = __commonJS({
216
+ "node_modules/p-timeout/index.js"(exports, module) {
217
+ "use strict";
218
+ var pFinally = require_p_finally();
219
+ var TimeoutError = class extends Error {
220
+ constructor(message) {
221
+ super(message);
222
+ this.name = "TimeoutError";
223
+ }
224
+ };
225
+ var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject2) => {
226
+ if (typeof milliseconds !== "number" || milliseconds < 0) {
227
+ throw new TypeError("Expected `milliseconds` to be a positive number");
228
+ }
229
+ if (milliseconds === Infinity) {
230
+ resolve(promise);
231
+ return;
232
+ }
233
+ const timer = setTimeout(() => {
234
+ if (typeof fallback === "function") {
235
+ try {
236
+ resolve(fallback());
237
+ } catch (error) {
238
+ reject2(error);
239
+ }
240
+ return;
241
+ }
242
+ const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
243
+ const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
244
+ if (typeof promise.cancel === "function") {
245
+ promise.cancel();
246
+ }
247
+ reject2(timeoutError);
248
+ }, milliseconds);
249
+ pFinally(
250
+ // eslint-disable-next-line promise/prefer-await-to-then
251
+ promise.then(resolve, reject2),
252
+ () => {
253
+ clearTimeout(timer);
254
+ }
255
+ );
256
+ });
257
+ module.exports = pTimeout;
258
+ module.exports.default = pTimeout;
259
+ module.exports.TimeoutError = TimeoutError;
260
+ }
261
+ });
262
+
263
+ // node_modules/p-queue/dist/lower-bound.js
264
+ var require_lower_bound = __commonJS({
265
+ "node_modules/p-queue/dist/lower-bound.js"(exports) {
266
+ "use strict";
267
+ Object.defineProperty(exports, "__esModule", { value: true });
268
+ function lowerBound(array, value, comparator) {
269
+ let first = 0;
270
+ let count = array.length;
271
+ while (count > 0) {
272
+ const step = count / 2 | 0;
273
+ let it = first + step;
274
+ if (comparator(array[it], value) <= 0) {
275
+ first = ++it;
276
+ count -= step + 1;
277
+ } else {
278
+ count = step;
279
+ }
280
+ }
281
+ return first;
282
+ }
283
+ exports.default = lowerBound;
284
+ }
285
+ });
286
+
287
+ // node_modules/p-queue/dist/priority-queue.js
288
+ var require_priority_queue = __commonJS({
289
+ "node_modules/p-queue/dist/priority-queue.js"(exports) {
290
+ "use strict";
291
+ Object.defineProperty(exports, "__esModule", { value: true });
292
+ var lower_bound_1 = require_lower_bound();
293
+ var PriorityQueue = class {
294
+ constructor() {
295
+ this._queue = [];
296
+ }
297
+ enqueue(run, options) {
298
+ options = Object.assign({ priority: 0 }, options);
299
+ const element = {
300
+ priority: options.priority,
301
+ run
302
+ };
303
+ if (this.size && this._queue[this.size - 1].priority >= options.priority) {
304
+ this._queue.push(element);
305
+ return;
306
+ }
307
+ const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority);
308
+ this._queue.splice(index, 0, element);
309
+ }
310
+ dequeue() {
311
+ const item = this._queue.shift();
312
+ return item === null || item === void 0 ? void 0 : item.run;
313
+ }
314
+ filter(options) {
315
+ return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);
316
+ }
317
+ get size() {
318
+ return this._queue.length;
319
+ }
320
+ };
321
+ exports.default = PriorityQueue;
322
+ }
323
+ });
324
+
325
+ // node_modules/p-queue/dist/index.js
326
+ var require_dist = __commonJS({
327
+ "node_modules/p-queue/dist/index.js"(exports) {
328
+ "use strict";
329
+ Object.defineProperty(exports, "__esModule", { value: true });
330
+ var EventEmitter = require_eventemitter3();
331
+ var p_timeout_1 = require_p_timeout();
332
+ var priority_queue_1 = require_priority_queue();
333
+ var empty = () => {
334
+ };
335
+ var timeoutError = new p_timeout_1.TimeoutError();
336
+ var PQueue = class extends EventEmitter {
337
+ constructor(options) {
338
+ var _a, _b, _c, _d;
339
+ super();
340
+ this._intervalCount = 0;
341
+ this._intervalEnd = 0;
342
+ this._pendingCount = 0;
343
+ this._resolveEmpty = empty;
344
+ this._resolveIdle = empty;
345
+ options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options);
346
+ if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
347
+ throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`);
348
+ }
349
+ if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
350
+ throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`);
351
+ }
352
+ this._carryoverConcurrencyCount = options.carryoverConcurrencyCount;
353
+ this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0;
354
+ this._intervalCap = options.intervalCap;
355
+ this._interval = options.interval;
356
+ this._queue = new options.queueClass();
357
+ this._queueClass = options.queueClass;
358
+ this.concurrency = options.concurrency;
359
+ this._timeout = options.timeout;
360
+ this._throwOnTimeout = options.throwOnTimeout === true;
361
+ this._isPaused = options.autoStart === false;
362
+ }
363
+ get _doesIntervalAllowAnother() {
364
+ return this._isIntervalIgnored || this._intervalCount < this._intervalCap;
365
+ }
366
+ get _doesConcurrentAllowAnother() {
367
+ return this._pendingCount < this._concurrency;
368
+ }
369
+ _next() {
370
+ this._pendingCount--;
371
+ this._tryToStartAnother();
372
+ this.emit("next");
373
+ }
374
+ _resolvePromises() {
375
+ this._resolveEmpty();
376
+ this._resolveEmpty = empty;
377
+ if (this._pendingCount === 0) {
378
+ this._resolveIdle();
379
+ this._resolveIdle = empty;
380
+ this.emit("idle");
381
+ }
382
+ }
383
+ _onResumeInterval() {
384
+ this._onInterval();
385
+ this._initializeIntervalIfNeeded();
386
+ this._timeoutId = void 0;
387
+ }
388
+ _isIntervalPaused() {
389
+ const now = Date.now();
390
+ if (this._intervalId === void 0) {
391
+ const delay = this._intervalEnd - now;
392
+ if (delay < 0) {
393
+ this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
394
+ } else {
395
+ if (this._timeoutId === void 0) {
396
+ this._timeoutId = setTimeout(() => {
397
+ this._onResumeInterval();
398
+ }, delay);
399
+ }
400
+ return true;
401
+ }
402
+ }
403
+ return false;
404
+ }
405
+ _tryToStartAnother() {
406
+ if (this._queue.size === 0) {
407
+ if (this._intervalId) {
408
+ clearInterval(this._intervalId);
409
+ }
410
+ this._intervalId = void 0;
411
+ this._resolvePromises();
412
+ return false;
413
+ }
414
+ if (!this._isPaused) {
415
+ const canInitializeInterval = !this._isIntervalPaused();
416
+ if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) {
417
+ const job = this._queue.dequeue();
418
+ if (!job) {
419
+ return false;
420
+ }
421
+ this.emit("active");
422
+ job();
423
+ if (canInitializeInterval) {
424
+ this._initializeIntervalIfNeeded();
425
+ }
426
+ return true;
427
+ }
428
+ }
429
+ return false;
430
+ }
431
+ _initializeIntervalIfNeeded() {
432
+ if (this._isIntervalIgnored || this._intervalId !== void 0) {
433
+ return;
434
+ }
435
+ this._intervalId = setInterval(() => {
436
+ this._onInterval();
437
+ }, this._interval);
438
+ this._intervalEnd = Date.now() + this._interval;
439
+ }
440
+ _onInterval() {
441
+ if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) {
442
+ clearInterval(this._intervalId);
443
+ this._intervalId = void 0;
444
+ }
445
+ this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;
446
+ this._processQueue();
447
+ }
448
+ /**
449
+ Executes all queued functions until it reaches the limit.
450
+ */
451
+ _processQueue() {
452
+ while (this._tryToStartAnother()) {
453
+ }
454
+ }
455
+ get concurrency() {
456
+ return this._concurrency;
457
+ }
458
+ set concurrency(newConcurrency) {
459
+ if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
460
+ throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
461
+ }
462
+ this._concurrency = newConcurrency;
463
+ this._processQueue();
464
+ }
465
+ /**
466
+ Adds a sync or async task to the queue. Always returns a promise.
467
+ */
468
+ async add(fn, options = {}) {
469
+ return new Promise((resolve, reject2) => {
470
+ const run = async () => {
471
+ this._pendingCount++;
472
+ this._intervalCount++;
473
+ try {
474
+ const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => {
475
+ if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) {
476
+ reject2(timeoutError);
477
+ }
478
+ return void 0;
479
+ });
480
+ resolve(await operation);
481
+ } catch (error) {
482
+ reject2(error);
483
+ }
484
+ this._next();
485
+ };
486
+ this._queue.enqueue(run, options);
487
+ this._tryToStartAnother();
488
+ this.emit("add");
489
+ });
490
+ }
491
+ /**
492
+ Same as `.add()`, but accepts an array of sync or async functions.
493
+
494
+ @returns A promise that resolves when all functions are resolved.
495
+ */
496
+ async addAll(functions, options) {
497
+ return Promise.all(functions.map(async (function_) => this.add(function_, options)));
498
+ }
499
+ /**
500
+ Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
501
+ */
502
+ start() {
503
+ if (!this._isPaused) {
504
+ return this;
505
+ }
506
+ this._isPaused = false;
507
+ this._processQueue();
508
+ return this;
509
+ }
510
+ /**
511
+ Put queue execution on hold.
512
+ */
513
+ pause() {
514
+ this._isPaused = true;
515
+ }
516
+ /**
517
+ Clear the queue.
518
+ */
519
+ clear() {
520
+ this._queue = new this._queueClass();
521
+ }
522
+ /**
523
+ Can be called multiple times. Useful if you for example add additional items at a later time.
524
+
525
+ @returns A promise that settles when the queue becomes empty.
526
+ */
527
+ async onEmpty() {
528
+ if (this._queue.size === 0) {
529
+ return;
530
+ }
531
+ return new Promise((resolve) => {
532
+ const existingResolve = this._resolveEmpty;
533
+ this._resolveEmpty = () => {
534
+ existingResolve();
535
+ resolve();
536
+ };
537
+ });
538
+ }
539
+ /**
540
+ The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
541
+
542
+ @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
543
+ */
544
+ async onIdle() {
545
+ if (this._pendingCount === 0 && this._queue.size === 0) {
546
+ return;
547
+ }
548
+ return new Promise((resolve) => {
549
+ const existingResolve = this._resolveIdle;
550
+ this._resolveIdle = () => {
551
+ existingResolve();
552
+ resolve();
553
+ };
554
+ });
555
+ }
556
+ /**
557
+ Size of the queue.
558
+ */
559
+ get size() {
560
+ return this._queue.size;
561
+ }
562
+ /**
563
+ Size of the queue, filtered by the given options.
564
+
565
+ For example, this can be used to find the number of items remaining in the queue with a specific priority level.
566
+ */
567
+ sizeBy(options) {
568
+ return this._queue.filter(options).length;
569
+ }
570
+ /**
571
+ Number of pending promises.
572
+ */
573
+ get pending() {
574
+ return this._pendingCount;
575
+ }
576
+ /**
577
+ Whether the queue is currently paused.
578
+ */
579
+ get isPaused() {
580
+ return this._isPaused;
581
+ }
582
+ get timeout() {
583
+ return this._timeout;
584
+ }
585
+ /**
586
+ Set the timeout for future operations.
587
+ */
588
+ set timeout(milliseconds) {
589
+ this._timeout = milliseconds;
590
+ }
591
+ };
592
+ exports.default = PQueue;
593
+ }
594
+ });
595
+
1
596
  // src/utils.ts
2
597
  function normalize(vector) {
3
598
  const dim = vector.length;
@@ -66,6 +661,15 @@ function innerProduct(v1, v2) {
66
661
  }
67
662
  return dot;
68
663
  }
664
+ function addScaledVector(target, source, scale = 1) {
665
+ const dim = target.length;
666
+ if (dim !== source.length) {
667
+ throw new Error("Vectors must have the same dimension.");
668
+ }
669
+ for (let i = 0; i < dim; i++) {
670
+ target[i] += scale * source[i];
671
+ }
672
+ }
69
673
  function cosineSimilarity(v1, v2) {
70
674
  const dim = v1.length;
71
675
  if (dim !== v2.length) {
@@ -109,7 +713,7 @@ function reject(baseVector, negativeVector) {
109
713
  return result;
110
714
  }
111
715
  function applyActivationToVector(vector, activation) {
112
- if (!activation) return;
716
+ if (!activation || activation === "linear") return;
113
717
  const dim = vector.length;
114
718
  if (activation === "relu") {
115
719
  for (let i = 0; i < dim; i++) {
@@ -162,17 +766,34 @@ function assertDimension(vector, expectedDimension, contextName = "Vector") {
162
766
  );
163
767
  }
164
768
  }
769
+ function getFlatMatrixAndBias(weights, dim, contextName = "Weights") {
770
+ let flatMatrix;
771
+ if (weights.matrix instanceof Float32Array) {
772
+ flatMatrix = new Float32Array(weights.matrix);
773
+ } else {
774
+ flatMatrix = flattenMatrix(weights.matrix, dim, dim, contextName);
775
+ }
776
+ const bias = new Float32Array(weights.bias);
777
+ return { flatMatrix, bias };
778
+ }
779
+ function applyAffine(matrix, bias, vector, result, inDim, outDim = inDim) {
780
+ for (let i = 0; i < outDim; i++) {
781
+ let sum = bias ? bias[i] : 0;
782
+ const rowOffset = i * inDim;
783
+ for (let j = 0; j < inDim; j++) {
784
+ sum += matrix[rowOffset + j] * vector[j];
785
+ }
786
+ result[i] = sum;
787
+ }
788
+ }
165
789
 
166
790
  // src/wasm/wasm-binary.ts
167
- var wasmBase64 = "AGFzbQEAAAABGQJgBn9/f39/fwBgDH9/f39/f319fX9/fwADAwIAAQUDAQAABzADDXR1bmVCYXRjaFdhc20AABNzZ2RNb21lbnR1bVN0ZXBXYXNtAAEGbWVtb3J5AgAK4QMCoAECBX8BfQNAIAUgCEoEQEEAIQYDQCAEIAZKBEBDAAAAACELIAQgBmwhCSAEIAhsIQpBACEHA0AgBCAHSgRAIAsgACAHIAlqQQJ0aioCACACIAcgCmpBAnRqKgIAlJIhCyAHQQFqIQcMAQsLIAMgBCAIbCAGakECdGogCyABIAZBAnRqKgIAkjgCACAGQQFqIQYMAQsLIAhBAWohCAwBCwsLvAICBX8DfQNAIAogDUoEQEMAAAAAIREgCSANbCEPQQAhDANAIAkgDEoEQCARIAAgDCAPakECdGoqAgAgBCAMQQJ0aioCAJSSIREgDEEBaiEMDAELCyANQQJ0IgwgC2ogESABIAxqKgIAkjgCACANQQFqIQ0MAQsLA0AgCiAOSgRAIA5BAnQiDCALaioCACAFIAxqKgIAkyERIAggAyAMaiINKgIAlCAGIBGUkyESIA0gEjgCACABIAxqIgwgDCoCACASkjgCACAJIA5sIQ9BACEMA0AgCSAMSgRAIAwgD2pBAnQiECAAaiINKgIAIRIgCCACIBBqIhAqAgCUIAYgESAEIAxBAnRqKgIAlCAHIBKUkpSTIRMgECATOAIAIA0gEiATkjgCACAMQQFqIQwMAQsLIA5BAWohDgwBCwsL";
791
+ var wasmBase64 = "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";
168
792
 
169
793
  // src/wasm/wasm-loader.ts
170
794
  var wasmInstance = null;
171
795
  var wasmMemory = null;
172
796
  var initPromise = null;
173
- function getWasmMemory() {
174
- return wasmMemory;
175
- }
176
797
  function getWasmInstance() {
177
798
  return wasmInstance;
178
799
  }
@@ -205,9 +826,37 @@ function ensureWasmMemory(requiredBytes) {
205
826
  return false;
206
827
  }
207
828
  }
829
+ var globalOffset = 65536;
830
+ function allocateWasmMemory(bytes) {
831
+ const ptr = globalOffset;
832
+ globalOffset += bytes;
833
+ if (globalOffset % 4 !== 0) {
834
+ globalOffset += 4 - globalOffset % 4;
835
+ }
836
+ ensureWasmMemory(globalOffset);
837
+ return ptr;
838
+ }
839
+ function getWasmAllocatorOffset() {
840
+ return globalOffset;
841
+ }
842
+ function setWasmAllocatorOffset(offset) {
843
+ globalOffset = offset;
844
+ }
845
+ function writeFloat32ArrayToWasm(memory, data, byteOffset) {
846
+ const f32 = new Float32Array(memory.buffer);
847
+ const floatOffset = byteOffset / 4;
848
+ if (data instanceof Float32Array) {
849
+ f32.set(data, floatOffset);
850
+ } else {
851
+ for (let i = 0; i < data.length; i++) {
852
+ f32[floatOffset + i] = data[i];
853
+ }
854
+ }
855
+ }
208
856
 
209
857
  // src/IntentAdapter.ts
210
- var IntentAdapter = class {
858
+ var IntentAdapter = class _IntentAdapter {
859
+ weightsMap = /* @__PURE__ */ new Map();
211
860
  dimension;
212
861
  matrices;
213
862
  biases;
@@ -250,6 +899,7 @@ var IntentAdapter = class {
250
899
  */
251
900
  addIntent(intentName, weights) {
252
901
  const { matrix, bias, routingVector } = weights;
902
+ this.weightsMap.set(intentName, weights);
253
903
  assertDimension(bias, this.dimension, `Intent '${intentName}' Bias`);
254
904
  let flatMatrix;
255
905
  if (matrix instanceof Float32Array) {
@@ -288,27 +938,9 @@ var IntentAdapter = class {
288
938
  this.matrices.delete(intentName);
289
939
  this.biases.delete(intentName);
290
940
  this.routingVectors.delete(intentName);
941
+ this.weightsMap.delete(intentName);
291
942
  }
292
- /**
293
- * 行列とバイアスを用いてベクトルにアフィン変換を適用する内部関数 (x' = W * x + b)
294
- *
295
- * @param {Float32Array} matrix - フラット化された変換行列
296
- * @param {Float32Array} bias - バイアスベクトル
297
- * @param {number[] | Float32Array} vector - 変換元の入力ベクトル
298
- * @param {Float32Array} result - 計算結果を格納する配列 (出力先)
299
- * @returns {void}
300
- */
301
- applyAffine(matrix, bias, vector, result) {
302
- const dim = this.dimension;
303
- for (let i = 0; i < dim; i++) {
304
- let sum = 0;
305
- const rowOffset = i * dim;
306
- for (let j = 0; j < dim; j++) {
307
- sum += matrix[rowOffset + j] * vector[j];
308
- }
309
- result[i] = sum + bias[i];
310
- }
311
- }
943
+ // (Private applyAffine was removed in favor of utils.ts applyAffine)
312
944
  /**
313
945
  * 複数の意図を指定された重みでブレンドした一時的な行列とバイアスを計算します。
314
946
  * W_blend = Σ(w_i * W_i), b_blend = Σ(w_i * b_i)
@@ -327,13 +959,8 @@ var IntentAdapter = class {
327
959
  if (!matrix || !bias) {
328
960
  throw new Error(`Intent '${intentName}' not found during blending.`);
329
961
  }
330
- for (let i = 0; i < dim; i++) {
331
- blendedBias[i] += bias[i] * weight;
332
- const rowOffset = i * dim;
333
- for (let j = 0; j < dim; j++) {
334
- blendedMatrix[rowOffset + j] += matrix[rowOffset + j] * weight;
335
- }
336
- }
962
+ addScaledVector(blendedBias, bias, weight);
963
+ addScaledVector(blendedMatrix, matrix, weight);
337
964
  }
338
965
  return { matrix: blendedMatrix, bias: blendedBias };
339
966
  }
@@ -355,7 +982,7 @@ var IntentAdapter = class {
355
982
  throw new Error(`Intent '${intent}' not found.`);
356
983
  }
357
984
  const result = new Float32Array(this.dimension);
358
- this.applyAffine(matrix, bias, baseVector, result);
985
+ applyAffine(matrix, bias, baseVector, result, this.dimension);
359
986
  applyActivationToVector(result, activation);
360
987
  return result;
361
988
  }
@@ -379,35 +1006,39 @@ var IntentAdapter = class {
379
1006
  const instance = getWasmInstance();
380
1007
  const requiredBytes = (this.dimension * this.dimension + this.dimension + batchSize * this.dimension * 2) * 4;
381
1008
  if (instance && ensureWasmMemory(requiredBytes)) {
382
- const wasmMem = getWasmMemory();
383
- const f32Mem = new Float32Array(wasmMem.buffer);
1009
+ const memory = instance.exports.memory;
384
1010
  let ptr = 0;
385
1011
  const matrixPtr = ptr;
386
- f32Mem.set(matrix, ptr);
387
- ptr += this.dimension * this.dimension;
1012
+ writeFloat32ArrayToWasm(memory, matrix, ptr);
1013
+ ptr += this.dimension * this.dimension * 4;
388
1014
  const biasPtr = ptr;
389
- f32Mem.set(bias, ptr);
390
- ptr += this.dimension;
1015
+ writeFloat32ArrayToWasm(memory, bias, ptr);
1016
+ ptr += this.dimension * 4;
391
1017
  const vectorsPtr = ptr;
392
1018
  for (let k = 0; k < batchSize; k++) {
393
- f32Mem.set(baseVectors[k], ptr + k * this.dimension);
1019
+ writeFloat32ArrayToWasm(
1020
+ memory,
1021
+ baseVectors[k],
1022
+ ptr + k * this.dimension * 4
1023
+ );
394
1024
  }
395
- ptr += batchSize * this.dimension;
1025
+ ptr += batchSize * this.dimension * 4;
396
1026
  const resultsPtr = ptr;
397
1027
  const tuneBatchWasm = instance.exports.tuneBatchWasm;
398
1028
  tuneBatchWasm(
399
- matrixPtr * 4,
400
- biasPtr * 4,
401
- vectorsPtr * 4,
402
- resultsPtr * 4,
1029
+ matrixPtr,
1030
+ biasPtr,
1031
+ vectorsPtr,
1032
+ resultsPtr,
403
1033
  this.dimension,
404
1034
  batchSize
405
1035
  );
406
1036
  const results2 = new Array(batchSize);
1037
+ const outF32Mem = new Float32Array(memory.buffer);
407
1038
  for (let k = 0; k < batchSize; k++) {
408
- const res = f32Mem.slice(
409
- resultsPtr + k * this.dimension,
410
- resultsPtr + (k + 1) * this.dimension
1039
+ const res = outF32Mem.slice(
1040
+ resultsPtr / 4 + k * this.dimension,
1041
+ resultsPtr / 4 + (k + 1) * this.dimension
411
1042
  );
412
1043
  applyActivationToVector(res, activation);
413
1044
  results2[k] = res;
@@ -419,7 +1050,7 @@ var IntentAdapter = class {
419
1050
  const baseVector = baseVectors[k];
420
1051
  assertDimension(baseVector, this.dimension, `Base vector at index ${k}`);
421
1052
  const result = new Float32Array(this.dimension);
422
- this.applyAffine(matrix, bias, baseVector, result);
1053
+ applyAffine(matrix, bias, baseVector, result, this.dimension);
423
1054
  applyActivationToVector(result, activation);
424
1055
  results[k] = result;
425
1056
  }
@@ -438,7 +1069,7 @@ var IntentAdapter = class {
438
1069
  assertDimension(baseVector, this.dimension, "Base vector");
439
1070
  const { matrix, bias } = this.computeBlendedWeights(blendWeights);
440
1071
  const result = new Float32Array(this.dimension);
441
- this.applyAffine(matrix, bias, baseVector, result);
1072
+ applyAffine(matrix, bias, baseVector, result, this.dimension);
442
1073
  applyActivationToVector(result, activation);
443
1074
  return result;
444
1075
  }
@@ -458,35 +1089,39 @@ var IntentAdapter = class {
458
1089
  const instance = getWasmInstance();
459
1090
  const requiredBytes = (this.dimension * this.dimension + this.dimension + batchSize * this.dimension * 2) * 4;
460
1091
  if (instance && ensureWasmMemory(requiredBytes)) {
461
- const wasmMem = getWasmMemory();
462
- const f32Mem = new Float32Array(wasmMem.buffer);
1092
+ const memory = instance.exports.memory;
463
1093
  let ptr = 0;
464
1094
  const matrixPtr = ptr;
465
- f32Mem.set(matrix, ptr);
466
- ptr += this.dimension * this.dimension;
1095
+ writeFloat32ArrayToWasm(memory, matrix, ptr);
1096
+ ptr += this.dimension * this.dimension * 4;
467
1097
  const biasPtr = ptr;
468
- f32Mem.set(bias, ptr);
469
- ptr += this.dimension;
1098
+ writeFloat32ArrayToWasm(memory, bias, ptr);
1099
+ ptr += this.dimension * 4;
470
1100
  const vectorsPtr = ptr;
471
1101
  for (let k = 0; k < batchSize; k++) {
472
- f32Mem.set(baseVectors[k], ptr + k * this.dimension);
1102
+ writeFloat32ArrayToWasm(
1103
+ memory,
1104
+ baseVectors[k],
1105
+ ptr + k * this.dimension * 4
1106
+ );
473
1107
  }
474
- ptr += batchSize * this.dimension;
1108
+ ptr += batchSize * this.dimension * 4;
475
1109
  const resultsPtr = ptr;
476
1110
  const tuneBatchWasm = instance.exports.tuneBatchWasm;
477
1111
  tuneBatchWasm(
478
- matrixPtr * 4,
479
- biasPtr * 4,
480
- vectorsPtr * 4,
481
- resultsPtr * 4,
1112
+ matrixPtr,
1113
+ biasPtr,
1114
+ vectorsPtr,
1115
+ resultsPtr,
482
1116
  this.dimension,
483
1117
  batchSize
484
1118
  );
485
1119
  const results2 = new Array(batchSize);
1120
+ const outF32Mem = new Float32Array(memory.buffer);
486
1121
  for (let k = 0; k < batchSize; k++) {
487
- const res = f32Mem.slice(
488
- resultsPtr + k * this.dimension,
489
- resultsPtr + (k + 1) * this.dimension
1122
+ const res = outF32Mem.slice(
1123
+ resultsPtr / 4 + k * this.dimension,
1124
+ resultsPtr / 4 + (k + 1) * this.dimension
490
1125
  );
491
1126
  applyActivationToVector(res, activation);
492
1127
  results2[k] = res;
@@ -498,7 +1133,7 @@ var IntentAdapter = class {
498
1133
  const baseVector = baseVectors[k];
499
1134
  assertDimension(baseVector, this.dimension, `Base vector at index ${k}`);
500
1135
  const result = new Float32Array(this.dimension);
501
- this.applyAffine(matrix, bias, baseVector, result);
1136
+ applyAffine(matrix, bias, baseVector, result, this.dimension);
502
1137
  applyActivationToVector(result, activation);
503
1138
  results[k] = result;
504
1139
  }
@@ -629,10 +1264,42 @@ var IntentAdapter = class {
629
1264
  this.routingVectors.set(intentName, routingVector);
630
1265
  }
631
1266
  }
1267
+ /**
1268
+ * 現在の IntentAdapter の全状態(全インテント)を JSON としてシリアライズしてエクスポートします。
1269
+ * (WarpPipeline 等の統合管理用)
1270
+ */
1271
+ exportState() {
1272
+ const intents = {};
1273
+ for (const [name, matrix] of this.matrices.entries()) {
1274
+ const bias = this.biases.get(name);
1275
+ const routing = this.routingVectors.get(name);
1276
+ intents[name] = {
1277
+ matrix: Array.from(matrix),
1278
+ bias: Array.from(bias),
1279
+ routingVector: routing ? Array.from(routing) : void 0
1280
+ };
1281
+ }
1282
+ return JSON.stringify({ dimension: this.dimension, intents });
1283
+ }
1284
+ /**
1285
+ * エクスポートされた JSON 状態から IntentAdapter を復元します。
1286
+ */
1287
+ static importState(stateJson) {
1288
+ const data = JSON.parse(stateJson);
1289
+ const adapter = new _IntentAdapter(data.dimension);
1290
+ for (const [name, intent] of Object.entries(data.intents)) {
1291
+ adapter.addIntent(name, {
1292
+ matrix: new Float32Array(intent.matrix),
1293
+ bias: new Float32Array(intent.bias),
1294
+ routingVector: intent.routingVector ? new Float32Array(intent.routingVector) : void 0
1295
+ });
1296
+ }
1297
+ return adapter;
1298
+ }
632
1299
  };
633
1300
 
634
1301
  // src/LoraIntentAdapter.ts
635
- var LoraIntentAdapter = class {
1302
+ var LoraIntentAdapter = class _LoraIntentAdapter {
636
1303
  dimension;
637
1304
  rank;
638
1305
  // フラット化されたAとBの行列、およびバイアスを保存
@@ -719,30 +1386,114 @@ var LoraIntentAdapter = class {
719
1386
  }
720
1387
  const result = new Float32Array(this.dimension);
721
1388
  const y = new Float32Array(this.rank);
722
- for (let i = 0; i < this.rank; i++) {
723
- let sum = 0;
724
- const rowOffset = i * this.dimension;
725
- for (let j = 0; j < this.dimension; j++) {
726
- sum += matB[rowOffset + j] * baseVector[j];
1389
+ applyAffine(matB, null, baseVector, y, this.dimension, this.rank);
1390
+ applyAffine(matA, bias, y, result, this.rank, this.dimension);
1391
+ addScaledVector(result, baseVector, 1);
1392
+ return result;
1393
+ }
1394
+ /**
1395
+ * 現在の LoraIntentAdapter の全状態を JSON としてエクスポートします。
1396
+ */
1397
+ exportState() {
1398
+ const intents = {};
1399
+ for (const [name, flatA] of this.matricesA.entries()) {
1400
+ const flatB = this.matricesB.get(name);
1401
+ const bias = this.biases.get(name);
1402
+ intents[name] = {
1403
+ matrixA: Array.from(flatA),
1404
+ // export as flattened for simplicity during import
1405
+ matrixB: Array.from(flatB),
1406
+ bias: Array.from(bias)
1407
+ };
1408
+ }
1409
+ return JSON.stringify({
1410
+ dimension: this.dimension,
1411
+ rank: this.rank,
1412
+ intents
1413
+ });
1414
+ }
1415
+ /**
1416
+ * エクスポートされた JSON 状態から LoraIntentAdapter を復元します。
1417
+ */
1418
+ static importState(stateJson) {
1419
+ const data = JSON.parse(stateJson);
1420
+ const adapter = new _LoraIntentAdapter(data.dimension, data.rank);
1421
+ for (const [name, intent] of Object.entries(data.intents)) {
1422
+ adapter.matricesA.set(name, new Float32Array(intent.matrixA));
1423
+ adapter.matricesB.set(name, new Float32Array(intent.matrixB));
1424
+ adapter.biases.set(name, new Float32Array(intent.bias));
1425
+ }
1426
+ return adapter;
1427
+ }
1428
+ };
1429
+
1430
+ // src/fusion/rrf.ts
1431
+ function rrf(resultSets, k = 60) {
1432
+ const scoreMap = /* @__PURE__ */ new Map();
1433
+ for (const resultSet of resultSets) {
1434
+ for (let i = 0; i < resultSet.length; i++) {
1435
+ const item = resultSet[i];
1436
+ const rank = item.rank !== void 0 ? item.rank : i + 1;
1437
+ const rrfScore = 1 / (k + rank);
1438
+ if (scoreMap.has(item.id)) {
1439
+ const existing = scoreMap.get(item.id);
1440
+ existing.score += rrfScore;
1441
+ existing.metadata = { ...existing.metadata, ...item.metadata };
1442
+ } else {
1443
+ scoreMap.set(item.id, {
1444
+ id: item.id,
1445
+ score: rrfScore,
1446
+ metadata: item.metadata
1447
+ });
727
1448
  }
728
- y[i] = sum;
729
1449
  }
730
- for (let i = 0; i < this.dimension; i++) {
731
- let sum = 0;
732
- const rowOffset = i * this.rank;
733
- for (let j = 0; j < this.rank; j++) {
734
- sum += matA[rowOffset + j] * y[j];
1450
+ }
1451
+ return Array.from(scoreMap.values()).sort((a, b) => b.score - a.score);
1452
+ }
1453
+
1454
+ // src/fusion/rsf.ts
1455
+ function rsf(resultSets, weights) {
1456
+ if (weights && weights.length !== resultSets.length) {
1457
+ throw new Error("Weights array length must match resultSets length");
1458
+ }
1459
+ const scoreMap = /* @__PURE__ */ new Map();
1460
+ for (let sIdx = 0; sIdx < resultSets.length; sIdx++) {
1461
+ const resultSet = resultSets[sIdx];
1462
+ const weight = weights ? weights[sIdx] : 1;
1463
+ if (resultSet.length === 0) continue;
1464
+ let min = Infinity;
1465
+ let max = -Infinity;
1466
+ for (const item of resultSet) {
1467
+ const score = item.score !== void 0 ? item.score : 0;
1468
+ if (score < min) min = score;
1469
+ if (score > max) max = score;
1470
+ }
1471
+ const range = max - min;
1472
+ for (const item of resultSet) {
1473
+ const score = item.score !== void 0 ? item.score : 0;
1474
+ const normalizedScore = range === 0 ? 1 : (score - min) / range;
1475
+ const weightedScore = normalizedScore * weight;
1476
+ if (scoreMap.has(item.id)) {
1477
+ const existing = scoreMap.get(item.id);
1478
+ existing.score += weightedScore;
1479
+ existing.metadata = { ...existing.metadata, ...item.metadata };
1480
+ } else {
1481
+ scoreMap.set(item.id, {
1482
+ id: item.id,
1483
+ score: weightedScore,
1484
+ metadata: item.metadata
1485
+ });
735
1486
  }
736
- result[i] = baseVector[i] + sum + bias[i];
737
1487
  }
738
- return result;
739
1488
  }
740
- };
1489
+ return Array.from(scoreMap.values()).sort((a, b) => b.score - a.score);
1490
+ }
741
1491
 
742
1492
  // src/ProjectionAdapter.ts
743
- var ProjectionAdapter = class {
1493
+ var ProjectionAdapter = class _ProjectionAdapter {
744
1494
  inDimension;
745
1495
  outDimension;
1496
+ wasmInstance = null;
746
1497
  // フラット化された射影行列とバイアスを保存
747
1498
  matrices;
748
1499
  biases;
@@ -804,112 +1555,1340 @@ var ProjectionAdapter = class {
804
1555
  this.biases.delete(name);
805
1556
  }
806
1557
  /**
807
- * ベクトルに射影変換を適用し、次元を変更した新しいベクトルを返します。
808
- * 数式: y = W * x
1558
+ * ベクトルの次元削減(射影)を実行します。
1559
+ * (WarpAdapter の実装として project の代わりに tune を提供します)
809
1560
  *
810
- * @param {number[] | Float32Array} baseVector - 変換元の入力ベクトル
811
- * @param {string} projectionName - 適用する射影設定の名前
812
- * @returns {Float32Array} 射影変換適用後の新しいベクトル
813
- * @throws {Error} ベクトルの次元数が inDimension と一致しない場合、または射影設定が存在しない場合にエラーをスローします。
814
- */
815
- project(baseVector, projectionName) {
816
- assertDimension(baseVector, this.inDimension, "Base vector");
817
- const matrix = this.matrices.get(projectionName);
1561
+ * @param vector 変換前のベクトル (例: 1536次元)
1562
+ * @param version 適用する変換バージョンの識別子 (オプション)
1563
+ * @returns 変換後のベクトル (例: 512次元)
1564
+ */
1565
+ tune(vector, version = "default") {
1566
+ assertDimension(vector, this.inDimension, "Base vector");
1567
+ const matrix = this.matrices.get(version);
1568
+ const bias = this.biases.get(version);
818
1569
  if (!matrix) {
819
- throw new Error(`Projection '${projectionName}' not found.`);
1570
+ throw new Error(`Projection '${version}' not found.`);
820
1571
  }
821
- const result = new Float32Array(this.outDimension);
822
- const bias = this.biases.get(projectionName);
823
- for (let i = 0; i < this.outDimension; i++) {
824
- let sum = bias ? bias[i] : 0;
825
- const rowOffset = i * this.inDimension;
826
- for (let j = 0; j < this.inDimension; j++) {
827
- sum += matrix[rowOffset + j] * baseVector[j];
1572
+ const instance = getWasmInstance();
1573
+ const matrixSize = this.inDimension * this.outDimension * 4;
1574
+ const biasSize = bias ? this.outDimension * 4 : 0;
1575
+ const vectorSize = this.inDimension * 4;
1576
+ const outputSize = this.outDimension * 4;
1577
+ const requiredBytes = matrixSize + biasSize + vectorSize + outputSize;
1578
+ if (instance && instance.exports.projectWasm && ensureWasmMemory(requiredBytes)) {
1579
+ const memory = instance.exports.memory;
1580
+ let offset = 0;
1581
+ const matrixPtr = offset;
1582
+ offset += matrixSize;
1583
+ const biasPtr = bias ? offset : 0;
1584
+ if (bias) offset += biasSize;
1585
+ const inputPtr = offset;
1586
+ offset += vectorSize;
1587
+ const outputPtr = offset;
1588
+ offset += outputSize;
1589
+ writeFloat32ArrayToWasm(memory, matrix, matrixPtr);
1590
+ if (bias) writeFloat32ArrayToWasm(memory, bias, biasPtr);
1591
+ writeFloat32ArrayToWasm(memory, vector, inputPtr);
1592
+ const projectWasm = instance.exports.projectWasm;
1593
+ projectWasm(
1594
+ matrixPtr,
1595
+ biasPtr,
1596
+ inputPtr,
1597
+ outputPtr,
1598
+ this.inDimension,
1599
+ this.outDimension
1600
+ );
1601
+ const result2 = new Float32Array(this.outDimension);
1602
+ const outF32 = new Float32Array(memory.buffer);
1603
+ const outIdx = outputPtr / 4;
1604
+ for (let i = 0; i < this.outDimension; i++) {
1605
+ result2[i] = outF32[outIdx + i];
828
1606
  }
829
- result[i] = sum;
1607
+ return result2;
830
1608
  }
1609
+ const result = new Float32Array(this.outDimension);
1610
+ applyAffine(
1611
+ matrix,
1612
+ bias,
1613
+ vector,
1614
+ result,
1615
+ this.inDimension,
1616
+ this.outDimension
1617
+ );
831
1618
  return result;
832
1619
  }
833
- };
834
-
835
- // src/BaseTrainer.ts
836
- var BaseTrainer = class {
837
- /** 学習用サンプルの配列 */
838
- examples = [];
839
1620
  /**
840
- * 学習用のサンプルデータを追加します。
841
- * 次元数がソース/ターゲットと一致しない場合はエラーとなります。
842
- *
843
- * @param {TExample} example 追加するサンプルデータ
844
- * @throws {Error} 次元数が一致しない場合にスローされます。
1621
+ * 現在の射影行列の状態をシリアライズしてエクスポートします。
845
1622
  */
846
- addExample(example) {
847
- const { source, target } = this.getInputs(example);
848
- if (source.length !== this.sourceDimension) {
849
- throw new Error(
850
- `Source dimension mismatch. Expected ${this.sourceDimension}.`
851
- );
1623
+ exportState() {
1624
+ const projections = {};
1625
+ for (const [name, matrix] of this.matrices.entries()) {
1626
+ const bias = this.biases.get(name);
1627
+ projections[name] = {
1628
+ matrix: Array.from(matrix),
1629
+ bias: bias ? Array.from(bias) : void 0
1630
+ };
852
1631
  }
853
- if (target.length !== this.targetDimension) {
854
- throw new Error(
855
- `Target dimension mismatch. Expected ${this.targetDimension}.`
856
- );
857
- }
858
- this.examples.push(example);
1632
+ return JSON.stringify({
1633
+ inDimension: this.inDimension,
1634
+ outDimension: this.outDimension,
1635
+ projections
1636
+ });
859
1637
  }
860
1638
  /**
861
- * 追加されたサンプルデータを用いて学習を実行します。
862
- * 指定されたエポック数だけ SGD + Momentum によるパラメータ更新を行います。
863
- * パフォーマンスのため、可能であれば内部で WebAssembly (WASM) を使用します。
864
- *
865
- * @param {BaseTrainingOptions} [options={}] 学習のハイパーパラメータオプション
866
- * @returns {Promise<TResult>} 学習済みの重みを返します。
867
- * @throws {Error} サンプルデータが追加されていない場合にスローされます。
1639
+ * エクスポートされた状態から ProjectionAdapter を復元します。
1640
+ * 注意: 保存されている matrix は既にフラット化された 1D 配列であることを前提としています。
868
1641
  */
869
- async train(options = {}) {
870
- await initWasm();
871
- if (this.examples.length === 0) {
872
- throw new Error("No training examples provided.");
1642
+ static importState(stateJson) {
1643
+ const data = JSON.parse(stateJson);
1644
+ const adapter = new _ProjectionAdapter(data.inDimension, data.outDimension);
1645
+ for (const [name, proj] of Object.entries(data.projections)) {
1646
+ adapter.matrices.set(name, new Float32Array(proj.matrix));
1647
+ if (proj.bias) {
1648
+ adapter.biases.set(name, new Float32Array(proj.bias));
1649
+ }
873
1650
  }
874
- if (options.autoTune) {
875
- options.learningRate = this.findBestLearningRate(options);
876
- options.autoTune = false;
1651
+ return adapter;
1652
+ }
1653
+ };
1654
+
1655
+ // src/MlpAdapter.ts
1656
+ function getActivationId(activation) {
1657
+ switch (activation) {
1658
+ case "linear":
1659
+ return 0;
1660
+ case "relu":
1661
+ return 1;
1662
+ case "sigmoid":
1663
+ return 2;
1664
+ case "tanh":
1665
+ return 3;
1666
+ default:
1667
+ return 0;
1668
+ }
1669
+ }
1670
+ var MlpAdapter = class _MlpAdapter {
1671
+ layers;
1672
+ wasmInstance = null;
1673
+ // WASMのポインタと設定値
1674
+ isWasmReady = false;
1675
+ inputDim = 0;
1676
+ outputDim = 0;
1677
+ numLayers = 0;
1678
+ inputPtr = 0;
1679
+ outputPtr = 0;
1680
+ weightsPtr = 0;
1681
+ layerDimsPtr = 0;
1682
+ activationsPtr = 0;
1683
+ bufferPtr = 0;
1684
+ bufBPtr = 0;
1685
+ constructor(layers) {
1686
+ if (layers.length === 0) {
1687
+ throw new Error("MlpAdapter requires at least one layer.");
877
1688
  }
878
- const lr = options.learningRate ?? 0.01;
879
- const epochs = options.epochs ?? 100;
880
- const reg = options.regularization ?? 1e-3;
881
- const momentum = options.momentum ?? 0.9;
882
- const sDim = this.sourceDimension;
883
- const tDim = this.targetDimension;
884
- const flatMatrix = new Float32Array(tDim * sDim);
885
- for (let i = 0; i < tDim; i++) {
886
- if (i < sDim) {
887
- flatMatrix[i * sDim + i] = 1;
888
- }
1689
+ this.layers = layers;
1690
+ this.numLayers = layers.length;
1691
+ }
1692
+ /**
1693
+ * WASMの初期化と、MLP構造をWASMメモリに書き込む準備を行います。
1694
+ * インスタンス作成後に必ず呼び出してください。
1695
+ */
1696
+ async init() {
1697
+ this.wasmInstance = await initWasm();
1698
+ if (!this.wasmInstance) {
1699
+ throw new Error("Failed to initialize WASM for MlpAdapter.");
889
1700
  }
890
- const bias = new Float32Array(tDim);
891
- const vMatrix = new Float32Array(tDim * sDim);
892
- const vBias = new Float32Array(tDim);
893
- for (let epoch = 0; epoch < epochs; epoch++) {
894
- for (const example of this.examples) {
895
- const { source, target } = this.getInputs(example);
896
- this.sgdMomentumStep(
897
- flatMatrix,
898
- bias,
899
- vMatrix,
900
- vBias,
901
- source,
902
- target,
903
- lr,
904
- reg,
905
- momentum
1701
+ const memory = this.wasmInstance.exports.memory;
1702
+ let sDim = 0;
1703
+ let tDim = 0;
1704
+ let maxDim = 0;
1705
+ let totalWeights = 0;
1706
+ const layerDims = [];
1707
+ const activations = [];
1708
+ for (let i = 0; i < this.layers.length; i++) {
1709
+ const layer = this.layers[i];
1710
+ let rows, cols;
1711
+ if (layer.matrix instanceof Float32Array) {
1712
+ rows = layer.bias.length;
1713
+ cols = layer.matrix.length / rows;
1714
+ } else {
1715
+ rows = layer.matrix.length;
1716
+ cols = layer.matrix[0].length;
1717
+ }
1718
+ if (i === 0) {
1719
+ sDim = cols;
1720
+ layerDims.push(sDim);
1721
+ } else if (cols !== tDim) {
1722
+ throw new Error(
1723
+ `Dimension mismatch at layer ${i}: expected input dim ${tDim}, got ${cols}`
906
1724
  );
907
1725
  }
1726
+ tDim = rows;
1727
+ layerDims.push(tDim);
1728
+ if (sDim > maxDim) maxDim = sDim;
1729
+ if (tDim > maxDim) maxDim = tDim;
1730
+ totalWeights += rows * cols + rows;
1731
+ activations.push(getActivationId(layer.activation));
908
1732
  }
909
- return this.toWeights(flatMatrix, bias);
1733
+ this.inputDim = layerDims[0];
1734
+ this.outputDim = layerDims[layerDims.length - 1];
1735
+ this.inputPtr = allocateWasmMemory(this.inputDim * 4);
1736
+ this.outputPtr = allocateWasmMemory(this.outputDim * 4);
1737
+ this.layerDimsPtr = allocateWasmMemory((this.numLayers + 1) * 4);
1738
+ this.activationsPtr = allocateWasmMemory(this.numLayers * 4);
1739
+ this.weightsPtr = allocateWasmMemory(totalWeights * 4);
1740
+ this.bufferPtr = allocateWasmMemory(maxDim * 4);
1741
+ this.bufBPtr = allocateWasmMemory(maxDim * 4);
1742
+ const memoryBuffer = memory.buffer;
1743
+ const f32 = new Float32Array(memoryBuffer);
1744
+ const i32 = new Int32Array(memoryBuffer);
1745
+ for (let i = 0; i < layerDims.length; i++) {
1746
+ i32[this.layerDimsPtr / 4 + i] = layerDims[i];
1747
+ }
1748
+ for (let i = 0; i < activations.length; i++) {
1749
+ i32[this.activationsPtr / 4 + i] = activations[i];
1750
+ }
1751
+ let wIdx = this.weightsPtr / 4;
1752
+ for (let i = 0; i < this.numLayers; i++) {
1753
+ const layer = this.layers[i];
1754
+ let rows, cols;
1755
+ if (layer.matrix instanceof Float32Array) {
1756
+ rows = layer.bias.length;
1757
+ cols = layer.matrix.length / rows;
1758
+ for (let r = 0; r < rows; r++) {
1759
+ for (let c = 0; c < cols; c++) {
1760
+ f32[wIdx++] = layer.matrix[r * cols + c];
1761
+ }
1762
+ f32[wIdx++] = layer.bias[r];
1763
+ }
1764
+ } else {
1765
+ rows = layer.matrix.length;
1766
+ cols = layer.matrix[0].length;
1767
+ for (let r = 0; r < rows; r++) {
1768
+ for (let c = 0; c < cols; c++) {
1769
+ f32[wIdx++] = layer.matrix[r][c];
1770
+ }
1771
+ f32[wIdx++] = layer.bias[r];
1772
+ }
1773
+ }
1774
+ }
1775
+ this.isWasmReady = true;
910
1776
  }
911
1777
  /**
912
- * サンプルデータに対する短時間のテストランを行い、最も損失(Loss)が小さくなる最適な学習率を自動探索します。
1778
+ * ニューラルネットワークの順伝播を実行し、結果を返します。
1779
+ * (WarpAdapter の実装として、predict の代わりに tune を提供します)
1780
+ *
1781
+ * @param input 入力ベクトル
1782
+ * @returns 推論結果ベクトル
1783
+ */
1784
+ tune(input) {
1785
+ if (!this.isWasmReady || !this.wasmInstance) {
1786
+ throw new Error(
1787
+ "MlpAdapter is not initialized. Call await init() first."
1788
+ );
1789
+ }
1790
+ assertDimension(input, this.inputDim, "MlpAdapter.tune");
1791
+ const memory = this.wasmInstance.exports.memory;
1792
+ writeFloat32ArrayToWasm(memory, input, this.inputPtr);
1793
+ const mlpInferenceWasm = this.wasmInstance.exports.mlpInferenceWasm;
1794
+ mlpInferenceWasm(
1795
+ this.inputPtr,
1796
+ this.outputPtr,
1797
+ this.weightsPtr,
1798
+ this.layerDimsPtr,
1799
+ this.activationsPtr,
1800
+ this.numLayers,
1801
+ this.bufferPtr,
1802
+ this.bufBPtr
1803
+ );
1804
+ const result = new Float32Array(this.outputDim);
1805
+ const outF32 = new Float32Array(memory.buffer);
1806
+ const outIdx = this.outputPtr / 4;
1807
+ for (let i = 0; i < this.outputDim; i++) {
1808
+ result[i] = outF32[outIdx + i];
1809
+ }
1810
+ return result;
1811
+ }
1812
+ /**
1813
+ * 現在のMLP構造と重みをシリアライズして出力します。
1814
+ */
1815
+ exportState() {
1816
+ return JSON.stringify({
1817
+ layers: this.layers.map((layer) => {
1818
+ let matrix;
1819
+ if (layer.matrix instanceof Float32Array) {
1820
+ matrix = Array.from(layer.matrix);
1821
+ } else {
1822
+ matrix = layer.matrix;
1823
+ }
1824
+ return {
1825
+ matrix,
1826
+ bias: Array.from(layer.bias),
1827
+ activation: layer.activation
1828
+ };
1829
+ })
1830
+ });
1831
+ }
1832
+ /**
1833
+ * シリアライズされた状態から MlpAdapter を復元します。
1834
+ * 注意: 復元後、再度 `await init()` を呼び出してWASMメモリを初期化する必要があります。
1835
+ */
1836
+ static importState(stateJson) {
1837
+ const data = JSON.parse(stateJson);
1838
+ const layers = data.layers.map((l) => ({
1839
+ // Float32Array に戻すか、そのまま2D配列として扱う
1840
+ matrix: Array.isArray(l.matrix[0]) ? l.matrix : new Float32Array(l.matrix),
1841
+ bias: new Float32Array(l.bias),
1842
+ activation: l.activation
1843
+ }));
1844
+ return new _MlpAdapter(layers);
1845
+ }
1846
+ };
1847
+
1848
+ // src/WhiteningAdapter.ts
1849
+ var WhiteningAdapter = class _WhiteningAdapter {
1850
+ dim;
1851
+ mean;
1852
+ components;
1853
+ count = 0;
1854
+ learningRate;
1855
+ numComponents;
1856
+ componentsPtr = 0;
1857
+ xResidualPtr = 0;
1858
+ isWasmReady = false;
1859
+ async init() {
1860
+ const instance = await initWasm();
1861
+ if (instance) {
1862
+ const componentsSize = this.numComponents * this.dim * 4;
1863
+ const xResidualSize = this.dim * 4;
1864
+ this.componentsPtr = allocateWasmMemory(componentsSize);
1865
+ this.xResidualPtr = allocateWasmMemory(xResidualSize);
1866
+ this.isWasmReady = true;
1867
+ }
1868
+ }
1869
+ /**
1870
+ * 新しい WhiteningAdapter を作成します。
1871
+ * @param dim ベクトルの次元数
1872
+ * @param config 設定オプション
1873
+ */
1874
+ constructor(dim, config = {}) {
1875
+ this.dim = dim;
1876
+ this.learningRate = config.learningRate ?? 0.01;
1877
+ this.numComponents = config.numComponents ?? 1;
1878
+ this.mean = new Float32Array(dim);
1879
+ this.components = [];
1880
+ for (let k = 0; k < this.numComponents; k++) {
1881
+ const pc = new Float32Array(dim);
1882
+ for (let i = 0; i < dim; i++) {
1883
+ pc[i] = Math.random() * 2 - 1;
1884
+ }
1885
+ this.components.push(normalize(pc));
1886
+ }
1887
+ }
1888
+ /**
1889
+ * 入力ベクトルを用いて、平均と主成分をオンライン更新します。
1890
+ * (Oja's Rule + Generalized Hebbian Algorithm)
1891
+ *
1892
+ * @param vector 学習用の入力ベクトル
1893
+ */
1894
+ update(vector) {
1895
+ assertDimension(vector, this.dim, "WhiteningAdapter.update");
1896
+ if (this.count === 0) {
1897
+ for (let i = 0; i < this.dim; i++) {
1898
+ this.mean[i] = vector[i];
1899
+ }
1900
+ } else {
1901
+ for (let i = 0; i < this.dim; i++) {
1902
+ this.mean[i] = (1 - this.learningRate) * this.mean[i] + this.learningRate * vector[i];
1903
+ }
1904
+ }
1905
+ this.count++;
1906
+ const x = new Float32Array(this.dim);
1907
+ for (let i = 0; i < this.dim; i++) {
1908
+ x[i] = vector[i] - this.mean[i];
1909
+ }
1910
+ const x_residual = new Float32Array(x);
1911
+ const instance = getWasmInstance();
1912
+ if (instance && instance.exports.sangerUpdateWasm) {
1913
+ if (!this.isWasmReady) {
1914
+ const componentsSize = this.numComponents * this.dim * 4;
1915
+ const xResidualSize = this.dim * 4;
1916
+ this.componentsPtr = allocateWasmMemory(componentsSize);
1917
+ this.xResidualPtr = allocateWasmMemory(xResidualSize);
1918
+ this.isWasmReady = true;
1919
+ }
1920
+ const memory = instance.exports.memory;
1921
+ const componentsPtr = this.componentsPtr;
1922
+ const xResidualPtr = this.xResidualPtr;
1923
+ const f32 = new Float32Array(memory.buffer);
1924
+ for (let k = 0; k < this.numComponents; k++) {
1925
+ const comp = this.components[k];
1926
+ for (let i = 0; i < this.dim; i++) {
1927
+ f32[componentsPtr / 4 + k * this.dim + i] = comp[i];
1928
+ }
1929
+ }
1930
+ writeFloat32ArrayToWasm(memory, x_residual, xResidualPtr);
1931
+ const sangerUpdateWasm = instance.exports.sangerUpdateWasm;
1932
+ sangerUpdateWasm(
1933
+ componentsPtr,
1934
+ xResidualPtr,
1935
+ this.dim,
1936
+ this.numComponents,
1937
+ this.learningRate
1938
+ );
1939
+ for (let k = 0; k < this.numComponents; k++) {
1940
+ for (let i = 0; i < this.dim; i++) {
1941
+ this.components[k][i] = f32[componentsPtr / 4 + k * this.dim + i];
1942
+ }
1943
+ }
1944
+ } else {
1945
+ for (let k = 0; k < this.numComponents; k++) {
1946
+ const w = this.components[k];
1947
+ let y = innerProduct(w, x_residual);
1948
+ addScaledVector(w, x_residual, this.learningRate * y);
1949
+ addScaledVector(w, w, -this.learningRate * y * y);
1950
+ this.components[k] = normalize(w);
1951
+ addScaledVector(x_residual, this.components[k], -y);
1952
+ }
1953
+ }
1954
+ }
1955
+ /**
1956
+ * 推論 (Whitening の適用):
1957
+ * 入力ベクトルから平均を引き、偏りの原因である上位主成分を除去します (All-but-the-Top)。
1958
+ *
1959
+ * @param vector 推論・補正対象のベクトル
1960
+ * @returns 等方化・ゼロセンタリングされた新しいベクトル
1961
+ */
1962
+ tune(vector) {
1963
+ assertDimension(vector, this.dim, "WhiteningAdapter.tune");
1964
+ let result = new Float32Array(this.dim);
1965
+ for (let i = 0; i < this.dim; i++) {
1966
+ result[i] = vector[i] - this.mean[i];
1967
+ }
1968
+ for (let k = 0; k < this.numComponents; k++) {
1969
+ const w = this.components[k];
1970
+ let dot = innerProduct(result, w);
1971
+ addScaledVector(result, w, -dot);
1972
+ }
1973
+ return result;
1974
+ }
1975
+ /**
1976
+ * 現在の学習状態(平均ベクトル、主成分ベクトルなど)をシリアライズして出力します。
1977
+ * エッジ環境でのインスタンス再構築時に役立ちます。
1978
+ */
1979
+ exportState() {
1980
+ return JSON.stringify({
1981
+ dim: this.dim,
1982
+ count: this.count,
1983
+ learningRate: this.learningRate,
1984
+ numComponents: this.numComponents,
1985
+ mean: Array.from(this.mean),
1986
+ components: this.components.map((c) => Array.from(c))
1987
+ });
1988
+ }
1989
+ /**
1990
+ * シリアライズされた学習状態から WhiteningAdapter を復元します。
1991
+ */
1992
+ static importState(stateJson) {
1993
+ const data = JSON.parse(stateJson);
1994
+ const adapter = new _WhiteningAdapter(data.dim, {
1995
+ learningRate: data.learningRate,
1996
+ numComponents: data.numComponents
1997
+ });
1998
+ adapter.count = data.count;
1999
+ adapter.mean = new Float32Array(data.mean);
2000
+ adapter.components = data.components.map(
2001
+ (c) => new Float32Array(c)
2002
+ );
2003
+ return adapter;
2004
+ }
2005
+ };
2006
+
2007
+ // src/ColbertAdapter.ts
2008
+ var ColbertAdapter = class {
2009
+ wasm;
2010
+ constructor() {
2011
+ this.wasm = getWasmInstance();
2012
+ }
2013
+ /**
2014
+ * 単一のクエリと単一のドキュメント間の Late Interaction (MaxSim) スコアを計算します。
2015
+ *
2016
+ * @param queryTokens クエリのトークンベクトル行列 (要素数 = queryLength * dim の平坦化された配列)
2017
+ * @param documentTokens ドキュメントのトークンベクトル行列
2018
+ * @param dim ベクトルの次元数
2019
+ * @returns MaxSimスコア
2020
+ */
2021
+ score(queryTokens, documentTokens, dim) {
2022
+ const numQueryTokens = queryTokens.length / dim;
2023
+ const numDocTokens = documentTokens.length / dim;
2024
+ if (numQueryTokens % 1 !== 0) {
2025
+ throw new Error(
2026
+ `Invalid queryTokens length. Must be a multiple of dim (${dim})`
2027
+ );
2028
+ }
2029
+ if (numDocTokens % 1 !== 0) {
2030
+ throw new Error(
2031
+ `Invalid documentTokens length. Must be a multiple of dim (${dim})`
2032
+ );
2033
+ }
2034
+ const { memory, colbertMaxSimWasm } = this.wasm.exports;
2035
+ const queryBytes = queryTokens.byteLength;
2036
+ const docBytes = documentTokens.byteLength;
2037
+ const initialOffset = getWasmAllocatorOffset();
2038
+ try {
2039
+ const queryPtr = allocateWasmMemory(queryBytes);
2040
+ const docPtr = allocateWasmMemory(docBytes);
2041
+ writeFloat32ArrayToWasm(memory, queryTokens, queryPtr);
2042
+ writeFloat32ArrayToWasm(memory, documentTokens, docPtr);
2043
+ return colbertMaxSimWasm(
2044
+ queryPtr,
2045
+ docPtr,
2046
+ numQueryTokens,
2047
+ numDocTokens,
2048
+ dim
2049
+ );
2050
+ } finally {
2051
+ setWasmAllocatorOffset(initialOffset);
2052
+ }
2053
+ }
2054
+ /**
2055
+ * クエリと複数のドキュメント間の MaxSim スコアを計算し、スコアの降順にソートして返します。
2056
+ *
2057
+ * @param queryTokens クエリのトークンベクトル行列
2058
+ * @param documentTokensArray ドキュメントのトークンベクトル行列の配列
2059
+ * @param dim ベクトルの次元数
2060
+ * @returns スコアの降順にソートされたドキュメントのインデックスとスコアの配列
2061
+ */
2062
+ rank(queryTokens, documentTokensArray, dim) {
2063
+ const numQueryTokens = queryTokens.length / dim;
2064
+ if (numQueryTokens % 1 !== 0) {
2065
+ throw new Error(
2066
+ `Invalid queryTokens length. Must be a multiple of dim (${dim})`
2067
+ );
2068
+ }
2069
+ const { memory, colbertMaxSimWasm } = this.wasm.exports;
2070
+ let maxDocLen = 0;
2071
+ for (const doc of documentTokensArray) {
2072
+ if (doc.length > maxDocLen) maxDocLen = doc.length;
2073
+ }
2074
+ const queryBytes = queryTokens.byteLength;
2075
+ const maxDocBytes = maxDocLen * Float32Array.BYTES_PER_ELEMENT;
2076
+ const initialOffset = getWasmAllocatorOffset();
2077
+ try {
2078
+ const queryPtr = allocateWasmMemory(queryBytes);
2079
+ const docPtr = allocateWasmMemory(maxDocBytes);
2080
+ writeFloat32ArrayToWasm(memory, queryTokens, queryPtr);
2081
+ const results = documentTokensArray.map((doc, index) => {
2082
+ const numDocTokens = doc.length / dim;
2083
+ if (numDocTokens % 1 !== 0) {
2084
+ throw new Error(`Invalid documentTokens length at index ${index}`);
2085
+ }
2086
+ writeFloat32ArrayToWasm(memory, doc, docPtr);
2087
+ const score = colbertMaxSimWasm(
2088
+ queryPtr,
2089
+ docPtr,
2090
+ numQueryTokens,
2091
+ numDocTokens,
2092
+ dim
2093
+ );
2094
+ return { index, score };
2095
+ });
2096
+ return results.sort((a, b) => b.score - a.score);
2097
+ } finally {
2098
+ setWasmAllocatorOffset(initialOffset);
2099
+ }
2100
+ }
2101
+ };
2102
+
2103
+ // src/integrations/prisma.ts
2104
+ import { Prisma } from "@prisma/client/extension";
2105
+
2106
+ // src/db.ts
2107
+ var VectorDBAdapter = class {
2108
+ /**
2109
+ * PostgreSQL (pgvector) 用のクエリ文字列表現を生成します。
2110
+ * INSERT や SELECT の際に使用できる形式です。
2111
+ *
2112
+ * @example
2113
+ * const sql = `SELECT * FROM items ORDER BY embedding <-> '${VectorDBAdapter.toPgvector(warpedVector)}' LIMIT 5`;
2114
+ *
2115
+ * @param {number[] | Float32Array} vector ワープ変換後のベクトル
2116
+ * @returns {string} `'[0.1, 0.2, 0.3]'` のような文字列表現
2117
+ */
2118
+ static toPgvector(vector) {
2119
+ if (vector instanceof Uint8Array) {
2120
+ let bitString = "";
2121
+ for (let i = 0; i < vector.length; i++) {
2122
+ bitString += vector[i].toString(2).padStart(8, "0");
2123
+ }
2124
+ return bitString;
2125
+ }
2126
+ return `[${Array.from(vector).join(", ")}]`;
2127
+ }
2128
+ /**
2129
+ * Pinecone 用のクエリオブジェクトを生成します。
2130
+ * Pinecone クライアントに直接渡せる形式のオブジェクトを返します。
2131
+ *
2132
+ * @example
2133
+ * const query = VectorDBAdapter.toPineconeQuery(warpedVector, 10, { genre: "comedy" });
2134
+ * await index.query(query);
2135
+ *
2136
+ * @param {number[] | Float32Array} vector 検索クエリベクトル
2137
+ * @param {number} topK 取得する件数 (デフォルト: 10)
2138
+ * @param {Record<string, any>} [filter] メタデータフィルタ(オプション)
2139
+ * @returns {Record<string, any>} Pineconeのqueryメソッド用オブジェクト
2140
+ */
2141
+ static toPineconeQuery(vector, topK = 10, filter) {
2142
+ return {
2143
+ vector: Array.from(vector),
2144
+ topK,
2145
+ ...filter ? { filter } : {}
2146
+ };
2147
+ }
2148
+ /**
2149
+ * Redis (RediSearch) のベクトルフィールド用に、
2150
+ * Float32Array をバイナリ(Uint8Array)に変換します。
2151
+ * Node.js環境では Buffer.from() を使って Buffer に変換して渡してください。
2152
+ *
2153
+ * @example
2154
+ * const blob = Buffer.from(VectorDBAdapter.toRedis(warpedVector));
2155
+ * await redis.call('FT.SEARCH', 'idx', '*=>[KNN 5 @embedding $BLOB]', 'PARAMS', '2', 'BLOB', blob, 'DIALECT', '2');
2156
+ *
2157
+ * @param {number[] | Float32Array} vector ワープ変換後のベクトル
2158
+ * @returns {Uint8Array} バイナリデータ (Float32のバイト表現)
2159
+ */
2160
+ static toRedis(vector) {
2161
+ const f32Array = vector instanceof Float32Array ? vector : new Float32Array(Array.from(vector));
2162
+ return new Uint8Array(
2163
+ f32Array.buffer.slice(
2164
+ f32Array.byteOffset,
2165
+ f32Array.byteOffset + f32Array.byteLength
2166
+ )
2167
+ );
2168
+ }
2169
+ };
2170
+
2171
+ // src/integrations/prisma.ts
2172
+ var withWarpVector = (config) => {
2173
+ const vectorField = config.vectorField ?? "embedding";
2174
+ const distanceOp = config.distanceOperator ?? "<->";
2175
+ return Prisma.defineExtension((client) => {
2176
+ return client.$extends({
2177
+ name: "warpvector",
2178
+ model: {
2179
+ $allModels: {
2180
+ /**
2181
+ * 生のベクトルを受け取り、WarpVectorで変換した後に pgvector 検索を行います。
2182
+ *
2183
+ * @param args.vector 生のベクトル (変換前)
2184
+ * @param args.topK 取得する最大件数 (デフォルト: 10)
2185
+ * @param args.where 追加のフィルタリング条件 (例: "category = 'science'")
2186
+ */
2187
+ async searchByVector(args) {
2188
+ const context = Prisma.getExtensionContext(this);
2189
+ const tableName = context.$name || "document";
2190
+ if (!/^[a-zA-Z0-9_]+$/.test(tableName)) {
2191
+ throw new Error(`Invalid table name: ${tableName}`);
2192
+ }
2193
+ if (!/^[a-zA-Z0-9_]+$/.test(vectorField)) {
2194
+ throw new Error(`Invalid vector field name: ${vectorField}`);
2195
+ }
2196
+ if (!["<->", "<#>", "<=>"].includes(distanceOp)) {
2197
+ throw new Error(`Invalid distance operator: ${distanceOp}`);
2198
+ }
2199
+ let whereClause = "";
2200
+ if (args.where) {
2201
+ const trimmedWhere = args.where.trim();
2202
+ if (/;|--|\/\*/.test(trimmedWhere)) {
2203
+ throw new Error("Potential SQL injection detected in where clause.");
2204
+ }
2205
+ whereClause = `WHERE ${trimmedWhere}`;
2206
+ }
2207
+ const limit = args.topK ?? 10;
2208
+ if (typeof limit !== "number" || isNaN(limit) || limit < 0) {
2209
+ throw new Error("Invalid topK value.");
2210
+ }
2211
+ const tunedVector = config.adapter.tune(args.vector);
2212
+ const pgVectorStr = VectorDBAdapter.toPgvector(tunedVector);
2213
+ const sql = `
2214
+ SELECT *
2215
+ FROM "${tableName}"
2216
+ ${whereClause}
2217
+ ORDER BY "${vectorField}" ${distanceOp} '${pgVectorStr}'::vector
2218
+ LIMIT ${limit};
2219
+ `.trim();
2220
+ return client.$queryRawUnsafe(sql);
2221
+ }
2222
+ }
2223
+ }
2224
+ });
2225
+ });
2226
+ };
2227
+
2228
+ // node_modules/@langchain/core/dist/utils/signal.js
2229
+ function getAbortSignalError(signal) {
2230
+ if (signal?.reason instanceof Error) return signal.reason;
2231
+ if (typeof signal?.reason === "string") return new Error(signal.reason);
2232
+ return /* @__PURE__ */ new Error("Aborted");
2233
+ }
2234
+
2235
+ // node_modules/@langchain/core/dist/utils/is-network-error/index.js
2236
+ var objectToString = Object.prototype.toString;
2237
+ var isError = (value) => objectToString.call(value) === "[object Error]";
2238
+ var errorMessages = /* @__PURE__ */ new Set([
2239
+ "network error",
2240
+ "Failed to fetch",
2241
+ "NetworkError when attempting to fetch resource.",
2242
+ "The Internet connection appears to be offline.",
2243
+ "Network request failed",
2244
+ "fetch failed",
2245
+ "terminated",
2246
+ " A network error occurred.",
2247
+ "Network connection lost"
2248
+ ]);
2249
+ function isNetworkError(error) {
2250
+ if (!(error && isError(error) && error.name === "TypeError" && typeof error.message === "string")) return false;
2251
+ const { message, stack } = error;
2252
+ if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error;
2253
+ if (message.startsWith("error sending request for url")) return true;
2254
+ return errorMessages.has(message);
2255
+ }
2256
+
2257
+ // node_modules/@langchain/core/dist/utils/p-retry/index.js
2258
+ function validateRetries(retries) {
2259
+ if (typeof retries === "number") {
2260
+ if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number.");
2261
+ if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
2262
+ } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity.");
2263
+ }
2264
+ function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) {
2265
+ if (value === void 0) return;
2266
+ if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
2267
+ if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`);
2268
+ if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`);
2269
+ }
2270
+ var AbortError = class extends Error {
2271
+ constructor(message) {
2272
+ super();
2273
+ if (message instanceof Error) {
2274
+ this.originalError = message;
2275
+ ({ message } = message);
2276
+ } else {
2277
+ this.originalError = new Error(message);
2278
+ this.originalError.stack = this.stack;
2279
+ }
2280
+ this.name = "AbortError";
2281
+ this.message = message;
2282
+ }
2283
+ };
2284
+ function calculateDelay(retriesConsumed, options) {
2285
+ const attempt = Math.max(1, retriesConsumed + 1);
2286
+ const random = options.randomize ? Math.random() + 1 : 1;
2287
+ let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1));
2288
+ timeout = Math.min(timeout, options.maxTimeout);
2289
+ return timeout;
2290
+ }
2291
+ function calculateRemainingTime(start, max) {
2292
+ if (!Number.isFinite(max)) return max;
2293
+ return max - (performance.now() - start);
2294
+ }
2295
+ async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) {
2296
+ const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
2297
+ if (normalizedError instanceof AbortError) throw normalizedError.originalError;
2298
+ const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
2299
+ const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
2300
+ const context = Object.freeze({
2301
+ error: normalizedError,
2302
+ attemptNumber,
2303
+ retriesLeft,
2304
+ retriesConsumed
2305
+ });
2306
+ await options.onFailedAttempt(context);
2307
+ if (calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError;
2308
+ const consumeRetry = await options.shouldConsumeRetry(context);
2309
+ const remainingTime = calculateRemainingTime(startTime, maxRetryTime);
2310
+ if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError;
2311
+ if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {
2312
+ if (consumeRetry) throw normalizedError;
2313
+ options.signal?.throwIfAborted();
2314
+ return false;
2315
+ }
2316
+ if (!await options.shouldRetry(context)) throw normalizedError;
2317
+ if (!consumeRetry) {
2318
+ options.signal?.throwIfAborted();
2319
+ return false;
2320
+ }
2321
+ const delayTime = calculateDelay(retriesConsumed, options);
2322
+ const finalDelay = Math.min(delayTime, remainingTime);
2323
+ if (finalDelay > 0) await new Promise((resolve, reject2) => {
2324
+ const onAbort = () => {
2325
+ clearTimeout(timeoutToken);
2326
+ options.signal?.removeEventListener("abort", onAbort);
2327
+ reject2(options.signal.reason);
2328
+ };
2329
+ const timeoutToken = setTimeout(() => {
2330
+ options.signal?.removeEventListener("abort", onAbort);
2331
+ resolve();
2332
+ }, finalDelay);
2333
+ if (options.unref) timeoutToken.unref?.();
2334
+ options.signal?.addEventListener("abort", onAbort, { once: true });
2335
+ });
2336
+ options.signal?.throwIfAborted();
2337
+ return true;
2338
+ }
2339
+ async function pRetry(input, options = {}) {
2340
+ options = { ...options };
2341
+ validateRetries(options.retries);
2342
+ if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
2343
+ options.retries ??= 10;
2344
+ options.factor ??= 2;
2345
+ options.minTimeout ??= 1e3;
2346
+ options.maxTimeout ??= Number.POSITIVE_INFINITY;
2347
+ options.maxRetryTime ??= Number.POSITIVE_INFINITY;
2348
+ options.randomize ??= false;
2349
+ options.onFailedAttempt ??= () => {
2350
+ };
2351
+ options.shouldRetry ??= () => true;
2352
+ options.shouldConsumeRetry ??= () => true;
2353
+ validateNumberOption("factor", options.factor, {
2354
+ min: 0,
2355
+ allowInfinity: false
2356
+ });
2357
+ validateNumberOption("minTimeout", options.minTimeout, {
2358
+ min: 0,
2359
+ allowInfinity: false
2360
+ });
2361
+ validateNumberOption("maxTimeout", options.maxTimeout, {
2362
+ min: 0,
2363
+ allowInfinity: true
2364
+ });
2365
+ validateNumberOption("maxRetryTime", options.maxRetryTime, {
2366
+ min: 0,
2367
+ allowInfinity: true
2368
+ });
2369
+ if (!(options.factor > 0)) options.factor = 1;
2370
+ options.signal?.throwIfAborted();
2371
+ let attemptNumber = 0;
2372
+ let retriesConsumed = 0;
2373
+ const startTime = performance.now();
2374
+ while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {
2375
+ attemptNumber++;
2376
+ try {
2377
+ options.signal?.throwIfAborted();
2378
+ const result = await input(attemptNumber);
2379
+ options.signal?.throwIfAborted();
2380
+ return result;
2381
+ } catch (error) {
2382
+ if (await onAttemptFailure({
2383
+ error,
2384
+ attemptNumber,
2385
+ retriesConsumed,
2386
+ startTime,
2387
+ options
2388
+ })) retriesConsumed++;
2389
+ }
2390
+ }
2391
+ throw new Error("Retry attempts exhausted without throwing an error.");
2392
+ }
2393
+
2394
+ // node_modules/@langchain/core/dist/utils/async_caller.js
2395
+ var import_p_queue = __toESM(require_dist(), 1);
2396
+ var STATUS_NO_RETRY = [
2397
+ 400,
2398
+ 401,
2399
+ 402,
2400
+ 403,
2401
+ 404,
2402
+ 405,
2403
+ 406,
2404
+ 407,
2405
+ 409
2406
+ ];
2407
+ var defaultFailedAttemptHandler = (error) => {
2408
+ if (typeof error !== "object" || error === null) return;
2409
+ if ("message" in error && typeof error.message === "string" && (error.message.startsWith("Cancel") || error.message.startsWith("AbortError")) || "name" in error && typeof error.name === "string" && error.name === "AbortError") throw error;
2410
+ if ("code" in error && typeof error.code === "string" && error.code === "ECONNABORTED") throw error;
2411
+ const responseStatus = "response" in error && typeof error.response === "object" && error.response !== null && "status" in error.response && typeof error.response.status === "number" ? error.response.status : void 0;
2412
+ const directStatus = "status" in error && typeof error.status === "number" ? error.status : void 0;
2413
+ const status = responseStatus ?? directStatus;
2414
+ if (status && STATUS_NO_RETRY.includes(+status)) throw error;
2415
+ if (("error" in error && typeof error.error === "object" && error.error !== null && "code" in error.error && typeof error.error.code === "string" ? error.error.code : void 0) === "insufficient_quota") {
2416
+ const err = new Error("message" in error && typeof error.message === "string" ? error.message : "Insufficient quota");
2417
+ err.name = "InsufficientQuotaError";
2418
+ throw err;
2419
+ }
2420
+ };
2421
+ var AsyncCaller = class {
2422
+ maxConcurrency;
2423
+ maxRetries;
2424
+ onFailedAttempt;
2425
+ queue;
2426
+ constructor(params) {
2427
+ this.maxConcurrency = params.maxConcurrency ?? Infinity;
2428
+ this.maxRetries = params.maxRetries ?? 6;
2429
+ this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler;
2430
+ const PQueue = "default" in import_p_queue.default ? import_p_queue.default.default : import_p_queue.default;
2431
+ this.queue = new PQueue({ concurrency: this.maxConcurrency });
2432
+ }
2433
+ async call(callable, ...args) {
2434
+ return this.queue.add(() => pRetry(() => callable(...args).catch((error) => {
2435
+ if (error instanceof Error) throw error;
2436
+ else throw new Error(error);
2437
+ }), {
2438
+ onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error),
2439
+ retries: this.maxRetries,
2440
+ randomize: true
2441
+ }), { throwOnTimeout: true });
2442
+ }
2443
+ callWithOptions(options, callable, ...args) {
2444
+ if (options.signal) {
2445
+ let listener;
2446
+ return Promise.race([this.call(callable, ...args), new Promise((_, reject2) => {
2447
+ listener = () => {
2448
+ reject2(getAbortSignalError(options.signal));
2449
+ };
2450
+ options.signal?.addEventListener("abort", listener, { once: true });
2451
+ })]).finally(() => {
2452
+ if (options.signal && listener) options.signal.removeEventListener("abort", listener);
2453
+ });
2454
+ }
2455
+ return this.call(callable, ...args);
2456
+ }
2457
+ fetch(...args) {
2458
+ return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res)));
2459
+ }
2460
+ };
2461
+
2462
+ // node_modules/@langchain/core/dist/embeddings.js
2463
+ var Embeddings = class {
2464
+ /**
2465
+ * The async caller should be used by subclasses to make any async calls,
2466
+ * which will thus benefit from the concurrency and retry logic.
2467
+ */
2468
+ caller;
2469
+ constructor(params) {
2470
+ this.caller = new AsyncCaller(params ?? {});
2471
+ }
2472
+ };
2473
+
2474
+ // src/integrations/langchain.ts
2475
+ var WarpEmbeddings = class extends Embeddings {
2476
+ baseEmbeddings;
2477
+ adapter;
2478
+ intentName;
2479
+ activation;
2480
+ autoBlend;
2481
+ constructor(options) {
2482
+ super(options);
2483
+ this.baseEmbeddings = options.baseEmbeddings;
2484
+ this.adapter = options.adapter;
2485
+ this.intentName = options.intentName;
2486
+ this.activation = options.activation;
2487
+ this.autoBlend = options.autoBlend ?? false;
2488
+ }
2489
+ /**
2490
+ * 実行時にアクティブな意図(インテント)を動的に切り替えます。
2491
+ */
2492
+ setIntent(intentName, activation) {
2493
+ this.intentName = intentName;
2494
+ this.activation = activation;
2495
+ this.autoBlend = false;
2496
+ }
2497
+ /**
2498
+ * 自己アテンション型の動的意図合成(Auto-blending)を有効化または無効化します。
2499
+ */
2500
+ setAutoBlend(enabled) {
2501
+ this.autoBlend = enabled;
2502
+ }
2503
+ /**
2504
+ * ベースの embeddings モデルを使用して、ドキュメントを通常通り埋め込みます。
2505
+ * VectorDB には客観的な空間データを含める必要があるため、インデックスされるドキュメントはワープ(変換)しません。
2506
+ */
2507
+ async embedDocuments(documents) {
2508
+ return this.baseEmbeddings.embedDocuments(documents);
2509
+ }
2510
+ /**
2511
+ * ユーザーのクエリを埋め込み、WarpVector によるアフィン変換を適用します。
2512
+ */
2513
+ async embedQuery(document) {
2514
+ const baseVector = await this.baseEmbeddings.embedQuery(document);
2515
+ let warped;
2516
+ if (this.autoBlend) {
2517
+ warped = this.adapter.tuneAutoBlended(baseVector, this.activation);
2518
+ } else {
2519
+ if (!this.intentName) {
2520
+ throw new Error(
2521
+ "WarpEmbeddings: intentName \u304C\u8A2D\u5B9A\u3055\u308C\u3066\u304A\u3089\u305A\u3001autoBlend \u3082 false \u3067\u3059\u3002setIntent() \u3092\u547C\u3073\u51FA\u3059\u304B autoBlend \u3092\u6709\u52B9\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002"
2522
+ );
2523
+ }
2524
+ warped = this.adapter.tune(baseVector, this.intentName, this.activation);
2525
+ }
2526
+ return Array.from(warped);
2527
+ }
2528
+ };
2529
+
2530
+ // src/integrations/llama-index.ts
2531
+ var WarpLlamaIndexEmbeddings = class {
2532
+ baseEmbeddings;
2533
+ adapter;
2534
+ intentName;
2535
+ activation;
2536
+ autoBlend;
2537
+ constructor(options) {
2538
+ this.baseEmbeddings = options.baseEmbeddings;
2539
+ this.adapter = options.adapter;
2540
+ this.intentName = options.intentName;
2541
+ this.activation = options.activation;
2542
+ this.autoBlend = options.autoBlend ?? false;
2543
+ }
2544
+ setIntent(intentName, activation) {
2545
+ this.intentName = intentName;
2546
+ this.activation = activation;
2547
+ this.autoBlend = false;
2548
+ }
2549
+ setAutoBlend(enabled) {
2550
+ this.autoBlend = enabled;
2551
+ }
2552
+ /**
2553
+ * ドキュメントの埋め込み(インデックス作成用)は変換を行いません。
2554
+ */
2555
+ async getTextEmbedding(text) {
2556
+ return this.baseEmbeddings.getTextEmbedding(text);
2557
+ }
2558
+ /**
2559
+ * 複数ドキュメントの埋め込み
2560
+ */
2561
+ async getTextEmbeddings(texts) {
2562
+ if (this.baseEmbeddings.getTextEmbeddings) {
2563
+ return this.baseEmbeddings.getTextEmbeddings(texts);
2564
+ }
2565
+ return Promise.all(texts.map((t) => this.getTextEmbedding(t)));
2566
+ }
2567
+ /**
2568
+ * クエリの埋め込み(検索用)にのみ WarpVector 変換を適用します。
2569
+ */
2570
+ async getQueryEmbedding(query) {
2571
+ const baseVector = await this.baseEmbeddings.getQueryEmbedding(query);
2572
+ let warped;
2573
+ if (this.autoBlend) {
2574
+ warped = this.adapter.tuneAutoBlended(baseVector, this.activation);
2575
+ } else {
2576
+ if (!this.intentName) {
2577
+ throw new Error(
2578
+ "WarpLlamaIndexEmbeddings: intentName \u304C\u8A2D\u5B9A\u3055\u308C\u3066\u304A\u3089\u305A\u3001autoBlend \u3082 false \u3067\u3059\u3002"
2579
+ );
2580
+ }
2581
+ warped = this.adapter.tune(baseVector, this.intentName, this.activation);
2582
+ }
2583
+ return Array.from(warped);
2584
+ }
2585
+ };
2586
+
2587
+ // src/QuantizationAdapter.ts
2588
+ var QuantizationAdapter = class _QuantizationAdapter {
2589
+ type;
2590
+ dim;
2591
+ dynamic;
2592
+ constructor(config) {
2593
+ this.type = config.type;
2594
+ this.dim = config.dim;
2595
+ this.dynamic = config.dynamic ?? false;
2596
+ if (this.type === "binary" && this.dim % 8 !== 0) {
2597
+ throw new Error(
2598
+ `Binary quantization requires dimension to be a multiple of 8. Got ${this.dim}`
2599
+ );
2600
+ }
2601
+ }
2602
+ tune(vector) {
2603
+ assertDimension(vector, this.dim, "QuantizationAdapter.tune");
2604
+ if (this.type === "int8") {
2605
+ if (this.dynamic) {
2606
+ let maxVal = 1e-8;
2607
+ for (let i = 0; i < this.dim; i++) {
2608
+ const abs = Math.abs(vector[i]);
2609
+ if (abs > maxVal) maxVal = abs;
2610
+ }
2611
+ const scale = 127 / maxVal;
2612
+ const result = new Int8Array(this.dim + 4);
2613
+ for (let i = 0; i < this.dim; i++) {
2614
+ let val = Math.round(vector[i] * scale);
2615
+ if (val > 127) val = 127;
2616
+ if (val < -128) val = -128;
2617
+ result[i] = val;
2618
+ }
2619
+ const view = new DataView(result.buffer, result.byteOffset, result.byteLength);
2620
+ view.setFloat32(this.dim, maxVal, true);
2621
+ return result;
2622
+ } else {
2623
+ const result = new Int8Array(this.dim);
2624
+ for (let i = 0; i < this.dim; i++) {
2625
+ let val = Math.round(vector[i] * 127);
2626
+ if (val > 127) val = 127;
2627
+ if (val < -128) val = -128;
2628
+ result[i] = val;
2629
+ }
2630
+ return result;
2631
+ }
2632
+ } else if (this.type === "binary") {
2633
+ const bytesLength = this.dim / 8;
2634
+ const result = new Uint8Array(bytesLength);
2635
+ for (let i = 0; i < this.dim; i++) {
2636
+ if (vector[i] > 0) {
2637
+ const byteIndex = Math.floor(i / 8);
2638
+ const bitIndex = i % 8;
2639
+ result[byteIndex] |= 1 << 7 - bitIndex;
2640
+ }
2641
+ }
2642
+ return result;
2643
+ }
2644
+ throw new Error(`Unknown quantization type: ${this.type}`);
2645
+ }
2646
+ /**
2647
+ * Binary量子化された2つのベクトル間のハミング距離を計算します。
2648
+ * ハミング距離が小さいほど類似度が高いことを意味します。
2649
+ */
2650
+ static hammingDistance(a, b) {
2651
+ if (a.length !== b.length) throw new Error("Length mismatch");
2652
+ let distance = 0;
2653
+ for (let i = 0; i < a.length; i++) {
2654
+ let xor = a[i] ^ b[i];
2655
+ while (xor > 0) {
2656
+ distance++;
2657
+ xor &= xor - 1;
2658
+ }
2659
+ }
2660
+ return distance;
2661
+ }
2662
+ /**
2663
+ * Int8量子化された2つのベクトル間のドット積(内積)を計算します。
2664
+ * 動的スケーリングが埋め込まれている場合はスケールを戻して計算します。
2665
+ */
2666
+ static int8DotProduct(a, b) {
2667
+ if (a.length !== b.length) throw new Error("Length mismatch");
2668
+ const hasScaleBytes = a.length > 4;
2669
+ let isDynamic = false;
2670
+ let maxA = 1;
2671
+ let maxB = 1;
2672
+ if (hasScaleBytes) {
2673
+ const dim = a.length - 4;
2674
+ try {
2675
+ const viewA = new DataView(a.buffer, a.byteOffset, a.byteLength);
2676
+ const viewB = new DataView(b.buffer, b.byteOffset, b.byteLength);
2677
+ maxA = viewA.getFloat32(dim, true);
2678
+ maxB = viewB.getFloat32(dim, true);
2679
+ if (!isNaN(maxA) && !isNaN(maxB) && maxA > 0 && maxA < 1e3 && maxB > 0 && maxB < 1e3) {
2680
+ isDynamic = true;
2681
+ }
2682
+ } catch (e) {
2683
+ isDynamic = false;
2684
+ }
2685
+ }
2686
+ if (isDynamic) {
2687
+ const dim = a.length - 4;
2688
+ let dot = 0;
2689
+ for (let i = 0; i < dim; i++) {
2690
+ dot += a[i] * b[i];
2691
+ }
2692
+ return dot * (maxA / 127) * (maxB / 127);
2693
+ } else {
2694
+ let dot = 0;
2695
+ for (let i = 0; i < a.length; i++) {
2696
+ dot += a[i] * b[i];
2697
+ }
2698
+ return dot;
2699
+ }
2700
+ }
2701
+ exportState() {
2702
+ return JSON.stringify({ type: this.type, dim: this.dim, dynamic: this.dynamic });
2703
+ }
2704
+ static importState(stateJson) {
2705
+ const config = JSON.parse(stateJson);
2706
+ return new _QuantizationAdapter(config);
2707
+ }
2708
+ };
2709
+
2710
+ // src/BaseTrainer.ts
2711
+ var AbstractAdamTrainer = class {
2712
+ t = 0;
2713
+ mW;
2714
+ vW;
2715
+ mb;
2716
+ vb;
2717
+ initAdamState(sDim, tDim) {
2718
+ if (!this.mW || this.mW.length !== sDim * tDim) {
2719
+ this.mW = new Float32Array(sDim * tDim);
2720
+ this.vW = new Float32Array(sDim * tDim);
2721
+ this.mb = new Float32Array(tDim);
2722
+ this.vb = new Float32Array(tDim);
2723
+ this.t = 0;
2724
+ }
2725
+ assertDimension(this.mW, sDim * tDim, "AdamState mW");
2726
+ }
2727
+ /**
2728
+ * アフィンレイヤー (matrix, bias) に対する Adam のパラメータ更新を適用します。
2729
+ * InfoNCE や Triplet など、様々な損失関数で計算された勾配(outputGradients)を元に更新を行います。
2730
+ */
2731
+ applyAdamToAffine(matrix, bias, mMatrix, vMatrix, mBias, vBias, input, outputGradients, lr, reg, t) {
2732
+ const tDim = bias.length;
2733
+ const sDim = input.length;
2734
+ const beta1 = 0.9;
2735
+ const beta2 = 0.999;
2736
+ const epsilon = 1e-8;
2737
+ const instance = getWasmInstance();
2738
+ if (instance && instance.exports.adamUpdateWasm) {
2739
+ const memory = instance.exports.memory;
2740
+ const matrixBytes = matrix.byteLength;
2741
+ const biasBytes = bias.byteLength;
2742
+ const inputBytes = sDim * 4;
2743
+ const gradBytes = tDim * 4;
2744
+ const initialOffset = getWasmAllocatorOffset();
2745
+ try {
2746
+ const matrixPtr = allocateWasmMemory(matrixBytes);
2747
+ const biasPtr = allocateWasmMemory(biasBytes);
2748
+ const mMatrixPtr = allocateWasmMemory(matrixBytes);
2749
+ const vMatrixPtr = allocateWasmMemory(matrixBytes);
2750
+ const mBiasPtr = allocateWasmMemory(biasBytes);
2751
+ const vBiasPtr = allocateWasmMemory(biasBytes);
2752
+ const inputPtr = allocateWasmMemory(inputBytes);
2753
+ const gradPtr = allocateWasmMemory(gradBytes);
2754
+ writeFloat32ArrayToWasm(memory, matrix, matrixPtr);
2755
+ writeFloat32ArrayToWasm(memory, bias, biasPtr);
2756
+ writeFloat32ArrayToWasm(memory, mMatrix, mMatrixPtr);
2757
+ writeFloat32ArrayToWasm(memory, vMatrix, vMatrixPtr);
2758
+ writeFloat32ArrayToWasm(memory, mBias, mBiasPtr);
2759
+ writeFloat32ArrayToWasm(memory, vBias, vBiasPtr);
2760
+ writeFloat32ArrayToWasm(memory, input, inputPtr);
2761
+ writeFloat32ArrayToWasm(memory, outputGradients, gradPtr);
2762
+ const adamUpdateWasm = instance.exports.adamUpdateWasm;
2763
+ adamUpdateWasm(
2764
+ matrixPtr,
2765
+ biasPtr,
2766
+ mMatrixPtr,
2767
+ vMatrixPtr,
2768
+ mBiasPtr,
2769
+ vBiasPtr,
2770
+ inputPtr,
2771
+ gradPtr,
2772
+ lr,
2773
+ reg,
2774
+ beta1,
2775
+ beta2,
2776
+ epsilon,
2777
+ t,
2778
+ sDim,
2779
+ tDim
2780
+ );
2781
+ const f32 = new Float32Array(memory.buffer);
2782
+ matrix.set(f32.subarray(matrixPtr / 4, matrixPtr / 4 + matrix.length));
2783
+ bias.set(f32.subarray(biasPtr / 4, biasPtr / 4 + bias.length));
2784
+ mMatrix.set(f32.subarray(mMatrixPtr / 4, mMatrixPtr / 4 + mMatrix.length));
2785
+ vMatrix.set(f32.subarray(vMatrixPtr / 4, vMatrixPtr / 4 + vMatrix.length));
2786
+ mBias.set(f32.subarray(mBiasPtr / 4, mBiasPtr / 4 + mBias.length));
2787
+ vBias.set(f32.subarray(vBiasPtr / 4, vBiasPtr / 4 + vBias.length));
2788
+ } finally {
2789
+ setWasmAllocatorOffset(initialOffset);
2790
+ }
2791
+ } else {
2792
+ for (let i = 0; i < tDim; i++) {
2793
+ const bGrad = outputGradients[i];
2794
+ mBias[i] = beta1 * mBias[i] + (1 - beta1) * bGrad;
2795
+ vBias[i] = beta2 * vBias[i] + (1 - beta2) * (bGrad * bGrad);
2796
+ const mHatB = mBias[i] / (1 - Math.pow(beta1, t));
2797
+ const vHatB = vBias[i] / (1 - Math.pow(beta2, t));
2798
+ bias[i] -= lr * mHatB / (Math.sqrt(vHatB) + epsilon);
2799
+ const rowOffset = i * sDim;
2800
+ for (let j = 0; j < sDim; j++) {
2801
+ const wIdx = rowOffset + j;
2802
+ const wGrad = bGrad * input[j] + reg * matrix[wIdx];
2803
+ mMatrix[wIdx] = beta1 * mMatrix[wIdx] + (1 - beta1) * wGrad;
2804
+ vMatrix[wIdx] = beta2 * vMatrix[wIdx] + (1 - beta2) * (wGrad * wGrad);
2805
+ const mHatW = mMatrix[wIdx] / (1 - Math.pow(beta1, t));
2806
+ const vHatW = vMatrix[wIdx] / (1 - Math.pow(beta2, t));
2807
+ matrix[wIdx] -= lr * mHatW / (Math.sqrt(vHatW) + epsilon);
2808
+ }
2809
+ }
2810
+ }
2811
+ }
2812
+ };
2813
+ var BaseTrainer = class extends AbstractAdamTrainer {
2814
+ /** 学習用サンプルの配列 */
2815
+ examples = [];
2816
+ /**
2817
+ * 学習用のサンプルデータを追加します。
2818
+ * 次元数がソース/ターゲットと一致しない場合はエラーとなります。
2819
+ *
2820
+ * @param {TExample} example 追加するサンプルデータ
2821
+ * @throws {Error} 次元数が一致しない場合にスローされます。
2822
+ */
2823
+ addExample(example) {
2824
+ const { source, target } = this.getInputs(example);
2825
+ assertDimension(
2826
+ source,
2827
+ this.sourceDimension,
2828
+ "BaseTrainer.addExample source"
2829
+ );
2830
+ assertDimension(
2831
+ target,
2832
+ this.targetDimension,
2833
+ "BaseTrainer.addExample target"
2834
+ );
2835
+ this.examples.push(example);
2836
+ }
2837
+ /**
2838
+ * 追加されたサンプルデータを用いて学習を実行します。
2839
+ * 指定されたエポック数だけ SGD + Momentum によるパラメータ更新を行います。
2840
+ * パフォーマンスのため、可能であれば内部で WebAssembly (WASM) を使用します。
2841
+ *
2842
+ * @param {BaseTrainingOptions} [options={}] 学習のハイパーパラメータオプション
2843
+ * @returns {Promise<TResult>} 学習済みの重みを返します。
2844
+ * @throws {Error} サンプルデータが追加されていない場合にスローされます。
2845
+ */
2846
+ async train(options = {}) {
2847
+ await initWasm();
2848
+ if (this.examples.length === 0) {
2849
+ throw new Error("No training examples provided.");
2850
+ }
2851
+ if (options.autoTune) {
2852
+ options.learningRate = this.findBestLearningRate(options);
2853
+ options.autoTune = false;
2854
+ }
2855
+ const lr = options.learningRate ?? 0.01;
2856
+ const epochs = options.epochs ?? 100;
2857
+ const reg = options.regularization ?? 1e-3;
2858
+ const momentum = options.momentum ?? 0.9;
2859
+ const sDim = this.sourceDimension;
2860
+ const tDim = this.targetDimension;
2861
+ const flatMatrix = new Float32Array(tDim * sDim);
2862
+ for (let i = 0; i < tDim; i++) {
2863
+ if (i < sDim) {
2864
+ flatMatrix[i * sDim + i] = 1;
2865
+ }
2866
+ }
2867
+ const bias = new Float32Array(tDim);
2868
+ this.initAdamState(sDim, tDim);
2869
+ for (let epoch = 0; epoch < epochs; epoch++) {
2870
+ for (const example of this.examples) {
2871
+ this.t++;
2872
+ const { source, target } = this.getInputs(example);
2873
+ this.adamStep(
2874
+ flatMatrix,
2875
+ bias,
2876
+ this.mW,
2877
+ this.vW,
2878
+ this.mb,
2879
+ this.vb,
2880
+ source,
2881
+ target,
2882
+ lr,
2883
+ reg,
2884
+ this.t
2885
+ );
2886
+ }
2887
+ }
2888
+ return this.toWeights(flatMatrix, bias);
2889
+ }
2890
+ /**
2891
+ * サンプルデータに対する短時間のテストランを行い、最も損失(Loss)が小さくなる最適な学習率を自動探索します。
913
2892
  * `options.autoTune` が true の場合に `train` メソッド内で自動的に呼び出されます。
914
2893
  *
915
2894
  * @param {BaseTrainingOptions} options 現在の学習オプション
@@ -930,21 +2909,27 @@ var BaseTrainer = class {
930
2909
  if (i < sDim) flatMatrix[i * sDim + i] = 1;
931
2910
  }
932
2911
  const bias = new Float32Array(tDim);
2912
+ const mMatrix = new Float32Array(tDim * sDim);
933
2913
  const vMatrix = new Float32Array(tDim * sDim);
2914
+ const mBias = new Float32Array(tDim);
934
2915
  const vBias = new Float32Array(tDim);
2916
+ let t = 0;
935
2917
  for (let epoch = 0; epoch < testEpochs; epoch++) {
936
2918
  for (const example of this.examples) {
2919
+ t++;
937
2920
  const { source, target } = this.getInputs(example);
938
- this.sgdMomentumStep(
2921
+ this.adamStep(
939
2922
  flatMatrix,
940
2923
  bias,
2924
+ mMatrix,
941
2925
  vMatrix,
2926
+ mBias,
942
2927
  vBias,
943
2928
  source,
944
2929
  target,
945
2930
  lr,
946
2931
  reg,
947
- momentum
2932
+ t
948
2933
  );
949
2934
  }
950
2935
  }
@@ -952,12 +2937,8 @@ var BaseTrainer = class {
952
2937
  for (const example of this.examples) {
953
2938
  const { source, target } = this.getInputs(example);
954
2939
  const pred = new Float32Array(tDim);
2940
+ applyAffine(flatMatrix, bias, source, pred, sDim, tDim);
955
2941
  for (let i = 0; i < tDim; i++) {
956
- let sum = 0;
957
- for (let j = 0; j < sDim; j++) {
958
- sum += flatMatrix[i * sDim + j] * source[j];
959
- }
960
- pred[i] = sum + bias[i];
961
2942
  const diff = pred[i] - target[i];
962
2943
  currentLoss += diff * diff;
963
2944
  }
@@ -967,170 +2948,304 @@ var BaseTrainer = class {
967
2948
  bestLr = lr;
968
2949
  }
969
2950
  }
970
- return bestLr;
2951
+ return bestLr;
2952
+ }
2953
+ /**
2954
+ * Adam オプティマイザによる1ステップのパラメータ更新を実行します。
2955
+ * In-place (破壊的) に `matrix` と `bias` を更新します。
2956
+ * WASM 版の Adam 実装ができるまではネイティブ JS で処理します。
2957
+ */
2958
+ adamStep(matrix, bias, mMatrix, vMatrix, mBias, vBias, x, y, lr, reg, t) {
2959
+ const sDim = this.sourceDimension;
2960
+ const tDim = this.targetDimension;
2961
+ const beta1 = 0.9;
2962
+ const beta2 = 0.999;
2963
+ const epsilon = 1e-8;
2964
+ const pred = new Float32Array(tDim);
2965
+ applyAffine(matrix, bias, x, pred, sDim, tDim);
2966
+ const outputGradients = new Float32Array(tDim);
2967
+ for (let i = 0; i < tDim; i++) {
2968
+ outputGradients[i] = pred[i] - y[i];
2969
+ }
2970
+ this.applyAdamToAffine(
2971
+ matrix,
2972
+ bias,
2973
+ mMatrix,
2974
+ vMatrix,
2975
+ mBias,
2976
+ vBias,
2977
+ x,
2978
+ outputGradients,
2979
+ lr,
2980
+ reg,
2981
+ t
2982
+ );
2983
+ }
2984
+ };
2985
+
2986
+ // src/trainer.ts
2987
+ var IntentTrainer = class extends BaseTrainer {
2988
+ dimension;
2989
+ /**
2990
+ * IntentTrainer のインスタンスを作成します。
2991
+ * @param {number} dimension ベクトルの次元数(入力・出力ともに同じ次元数となります)
2992
+ */
2993
+ constructor(dimension) {
2994
+ super();
2995
+ this.dimension = dimension;
2996
+ this.initAdamState(dimension, dimension);
2997
+ }
2998
+ get sourceDimension() {
2999
+ return this.dimension;
3000
+ }
3001
+ get targetDimension() {
3002
+ return this.dimension;
3003
+ }
3004
+ getInputs(example) {
3005
+ return { source: example.input, target: example.target };
3006
+ }
3007
+ toWeights(flatMatrix, bias) {
3008
+ return {
3009
+ matrix: flatMatrix,
3010
+ // 変換のオーバーヘッドを避けるためネイティブ配列のまま返す
3011
+ bias
3012
+ };
3013
+ }
3014
+ /**
3015
+ * オンライン学習 (フィードバックループ) 用のメソッド。
3016
+ * ユーザーのクリックなどの 1 回のフィードバックからリアルタイムに重みを微調整します。
3017
+ *
3018
+ * @param {IntentWeights} currentWeights - 現在の重み
3019
+ * @param {TrainingExample} example - アンカー、正解を含む学習データ
3020
+ * @param {IntentOnlineOptions} [options={}] - 学習オプション
3021
+ * @returns {IntentWeights} 微調整された新しい重み
3022
+ */
3023
+ async updateOnline(currentWeights, example, options = {}) {
3024
+ const learningRate = options.learningRate ?? 0.01;
3025
+ const regularization = options.regularization ?? 1e-3;
3026
+ await initWasm();
3027
+ assertDimension(
3028
+ example.input,
3029
+ this.dimension,
3030
+ "IntentTrainer.addExample input"
3031
+ );
3032
+ assertDimension(
3033
+ example.target,
3034
+ this.dimension,
3035
+ "IntentTrainer.addExample target"
3036
+ );
3037
+ const dim = this.dimension;
3038
+ const { flatMatrix, bias } = getFlatMatrixAndBias(
3039
+ currentWeights,
3040
+ dim,
3041
+ "updateOnline Matrix"
3042
+ );
3043
+ const warpedInput = new Float32Array(dim);
3044
+ applyAffine(flatMatrix, bias, example.input, warpedInput, dim);
3045
+ const outputGradients = new Float32Array(dim);
3046
+ for (let i = 0; i < dim; i++) {
3047
+ outputGradients[i] = warpedInput[i] - example.target[i];
3048
+ }
3049
+ this.t++;
3050
+ this.applyAdamToAffine(
3051
+ flatMatrix,
3052
+ bias,
3053
+ this.mW,
3054
+ this.vW,
3055
+ this.mb,
3056
+ this.vb,
3057
+ example.input,
3058
+ outputGradients,
3059
+ learningRate,
3060
+ regularization,
3061
+ this.t
3062
+ );
3063
+ const newWeights = this.toWeights(flatMatrix, bias);
3064
+ if (currentWeights.routingVector) {
3065
+ newWeights.routingVector = [...currentWeights.routingVector];
3066
+ }
3067
+ return newWeights;
971
3068
  }
3069
+ };
3070
+
3071
+ // src/TripletTrainer.ts
3072
+ var TripletTrainer = class extends AbstractAdamTrainer {
3073
+ dimension;
972
3074
  /**
973
- * SGD + Momentum アルゴリズムによる1ステップのパラメータ更新を実行します。
974
- * In-place (破壊的) `matrix` と `bias` を更新します。
3075
+ * TripletTrainer のインスタンスを作成します。
3076
+ * @param {number} dimension ベクトルの次元数
3077
+ */
3078
+ constructor(dimension) {
3079
+ super();
3080
+ this.dimension = dimension;
3081
+ this.initAdamState(dimension, dimension);
3082
+ }
3083
+ toWeights(flatMatrix, bias) {
3084
+ return {
3085
+ matrix: flatMatrix,
3086
+ // 変換のオーバーヘッドを避けるためネイティブ配列のまま返す
3087
+ bias
3088
+ };
3089
+ }
3090
+ /**
3091
+ * オンライン学習 (フィードバックループ) 用のメソッド。
3092
+ * 1つのトリプレットデータからリアルタイムに重みを微調整します。
975
3093
  *
976
- * @param {Float32Array} matrix 現在の変換行列 (1次元フラット配列)
977
- * @param {Float32Array} bias 現在のバイアスベクトル
978
- * @param {Float32Array} vMatrix 行列のモメンタム (速度)
979
- * @param {Float32Array} vBias バイアスのモメンタム (速度)
980
- * @param {number[] | Float32Array} x 入力ベクトル (ソース)
981
- * @param {number[] | Float32Array} y 理想の出力ベクトル (ターゲット)
982
- * @param {number} lr 学習率
983
- * @param {number} reg L2正則化係数
984
- * @param {number} momentum モメンタム係数
985
- */
986
- sgdMomentumStep(matrix, bias, vMatrix, vBias, x, y, lr, reg, momentum) {
987
- const sDim = this.sourceDimension;
988
- const tDim = this.targetDimension;
989
- const instance = getWasmInstance();
990
- const requiredBytes = sDim * tDim * 4 + tDim * 4 + sDim * tDim * 4 + tDim * 4 + sDim * 4 + tDim * 4 + tDim * 4;
991
- if (instance && ensureWasmMemory(requiredBytes)) {
992
- const wasmMemory2 = getWasmMemory();
993
- const f32Mem = new Float32Array(wasmMemory2.buffer);
994
- let offset = 0;
995
- const matrixOffset = offset;
996
- offset += sDim * tDim;
997
- const biasOffset = offset;
998
- offset += tDim;
999
- const vMatrixOffset = offset;
1000
- offset += sDim * tDim;
1001
- const vBiasOffset = offset;
1002
- offset += tDim;
1003
- const xOffset = offset;
1004
- offset += sDim;
1005
- const yOffset = offset;
1006
- offset += tDim;
1007
- const predOffset = offset;
1008
- offset += tDim;
1009
- f32Mem.set(matrix, matrixOffset);
1010
- f32Mem.set(bias, biasOffset);
1011
- f32Mem.set(vMatrix, vMatrixOffset);
1012
- f32Mem.set(vBias, vBiasOffset);
1013
- f32Mem.set(x, xOffset);
1014
- f32Mem.set(y, yOffset);
1015
- const sgdMomentumStepWasm = instance.exports.sgdMomentumStepWasm;
1016
- sgdMomentumStepWasm(
1017
- matrixOffset * 4,
1018
- biasOffset * 4,
1019
- vMatrixOffset * 4,
1020
- vBiasOffset * 4,
1021
- xOffset * 4,
1022
- yOffset * 4,
1023
- lr,
1024
- reg,
1025
- momentum,
1026
- sDim,
1027
- tDim,
1028
- predOffset * 4
1029
- );
1030
- matrix.set(f32Mem.subarray(matrixOffset, matrixOffset + sDim * tDim));
1031
- bias.set(f32Mem.subarray(biasOffset, biasOffset + tDim));
1032
- vMatrix.set(f32Mem.subarray(vMatrixOffset, vMatrixOffset + sDim * tDim));
1033
- vBias.set(f32Mem.subarray(vBiasOffset, vBiasOffset + tDim));
1034
- return;
1035
- }
1036
- const pred = new Float32Array(tDim);
1037
- for (let i = 0; i < tDim; i++) {
1038
- let sum = 0;
1039
- const rowOffset = i * sDim;
1040
- for (let j = 0; j < sDim; j++) {
1041
- sum += matrix[rowOffset + j] * x[j];
3094
+ * @param {IntentWeights} currentWeights - 現在の重み
3095
+ * @param {TripletExample} example - アンカー、正解、不正解を含むトリプレットデータ
3096
+ * @param {TripletOnlineOptions} [options={}] - 学習オプション
3097
+ * @returns {Promise<IntentWeights>} 微調整された新しい重み
3098
+ */
3099
+ async updateOnline(currentWeights, example, options = {}) {
3100
+ const learningRate = options.learningRate ?? 0.01;
3101
+ const margin = options.margin ?? 0.1;
3102
+ const regularization = options.regularization ?? 1e-3;
3103
+ assertDimension(
3104
+ example.anchor,
3105
+ this.dimension,
3106
+ "TripletTrainer.train anchor"
3107
+ );
3108
+ assertDimension(
3109
+ example.positive,
3110
+ this.dimension,
3111
+ "TripletTrainer.train positive"
3112
+ );
3113
+ assertDimension(
3114
+ example.negative,
3115
+ this.dimension,
3116
+ "TripletTrainer.train negative"
3117
+ );
3118
+ const dim = this.dimension;
3119
+ const { flatMatrix, bias } = getFlatMatrixAndBias(
3120
+ currentWeights,
3121
+ dim,
3122
+ "updateOnline Matrix"
3123
+ );
3124
+ const warpedAnchor = new Float32Array(dim);
3125
+ applyAffine(flatMatrix, bias, example.anchor, warpedAnchor, dim);
3126
+ const posScore = innerProduct(warpedAnchor, example.positive);
3127
+ const negScore = innerProduct(warpedAnchor, example.negative);
3128
+ const loss = margin + negScore - posScore;
3129
+ if (loss > 0) {
3130
+ this.t += 1;
3131
+ const outputGradients = new Float32Array(dim);
3132
+ for (let i = 0; i < dim; i++) {
3133
+ outputGradients[i] = example.negative[i] - example.positive[i];
1042
3134
  }
1043
- pred[i] = sum + bias[i];
3135
+ this.applyAdamToAffine(
3136
+ flatMatrix,
3137
+ bias,
3138
+ this.mW,
3139
+ this.vW,
3140
+ this.mb,
3141
+ this.vb,
3142
+ example.anchor,
3143
+ outputGradients,
3144
+ learningRate,
3145
+ regularization,
3146
+ this.t
3147
+ );
1044
3148
  }
1045
- for (let i = 0; i < tDim; i++) {
1046
- const error = pred[i] - y[i];
1047
- const bGrad = error;
1048
- vBias[i] = momentum * vBias[i] - lr * bGrad;
1049
- bias[i] += vBias[i];
1050
- const rowOffset = i * sDim;
1051
- for (let j = 0; j < sDim; j++) {
1052
- const wIdx = rowOffset + j;
1053
- const wGrad = error * x[j] + reg * matrix[wIdx];
1054
- vMatrix[wIdx] = momentum * vMatrix[wIdx] - lr * wGrad;
1055
- matrix[wIdx] += vMatrix[wIdx];
1056
- }
3149
+ const newWeights = this.toWeights(flatMatrix, bias);
3150
+ if (currentWeights.routingVector) {
3151
+ newWeights.routingVector = [...currentWeights.routingVector];
1057
3152
  }
3153
+ return newWeights;
1058
3154
  }
1059
3155
  };
1060
3156
 
1061
- // src/trainer.ts
1062
- var IntentTrainer = class extends BaseTrainer {
3157
+ // src/InfoNCETrainer.ts
3158
+ var InfoNCETrainer = class extends AbstractAdamTrainer {
1063
3159
  dimension;
1064
3160
  /**
1065
- * IntentTrainer のインスタンスを作成します。
1066
- * @param {number} dimension ベクトルの次元数(入力・出力ともに同じ次元数となります)
3161
+ * InfoNCETrainer のインスタンスを作成します。
3162
+ * @param {number} dimension ベクトルの次元数
1067
3163
  */
1068
3164
  constructor(dimension) {
1069
3165
  super();
1070
3166
  this.dimension = dimension;
1071
- }
1072
- get sourceDimension() {
1073
- return this.dimension;
1074
- }
1075
- get targetDimension() {
1076
- return this.dimension;
1077
- }
1078
- getInputs(example) {
1079
- return { source: example.input, target: example.target };
3167
+ this.initAdamState(dimension, dimension);
1080
3168
  }
1081
3169
  toWeights(flatMatrix, bias) {
1082
- const dim = this.dimension;
1083
- const outMatrix = new Array(dim);
1084
- for (let i = 0; i < dim; i++) {
1085
- const row = new Array(dim);
1086
- const rowOffset = i * dim;
1087
- for (let j = 0; j < dim; j++) {
1088
- row[j] = flatMatrix[rowOffset + j];
1089
- }
1090
- outMatrix[i] = row;
1091
- }
1092
3170
  return {
1093
- matrix: outMatrix,
1094
- bias: Array.from(bias)
3171
+ matrix: flatMatrix,
3172
+ // ネイティブ配列のまま返す
3173
+ bias
1095
3174
  };
1096
3175
  }
1097
3176
  /**
1098
3177
  * オンライン学習 (フィードバックループ) 用のメソッド。
1099
- * ユーザーのクリックなどの 1 回のフィードバックからリアルタイムに重みを微調整します。
3178
+ * 1つのクエリ(Anchor)、1つのクリック(Positive)、複数のスルー(Negatives)から重みを微調整します。
1100
3179
  *
1101
3180
  * @param {IntentWeights} currentWeights - 現在の重み
1102
- * @param {number[] | Float32Array} input - 検索されたクエリベクトル
1103
- * @param {number[] | Float32Array} target - クリックされた(理想の)ドキュメントのベクトル
1104
- * @param {number} learningRate - 1ステップの学習率 (デフォルト: 0.01)
1105
- * @param {number} regularization - L2正則化の強さ (デフォルト: 0.001)
1106
- * @returns {IntentWeights} 微調整された新しい重み
3181
+ * @param {InfoNCEExample} example - アンカー、正解、複数の不正解を含むデータ
3182
+ * @param {InfoNCEOnlineOptions} [options={}] - 学習オプション
3183
+ * @returns {Promise<IntentWeights>} 微調整された新しい重み
1107
3184
  */
1108
- async updateOnline(currentWeights, input, target, learningRate = 0.01, regularization = 1e-3) {
1109
- await initWasm();
1110
- if (input.length !== this.dimension || target.length !== this.dimension) {
1111
- throw new Error(`Dimension mismatch. Expected ${this.dimension}`);
1112
- }
3185
+ async updateOnline(currentWeights, example, options = {}) {
3186
+ const learningRate = options.learningRate ?? 0.01;
3187
+ const temperature = options.temperature ?? 0.1;
3188
+ const regularization = options.regularization ?? 1e-3;
1113
3189
  const dim = this.dimension;
1114
- let flatMatrix;
1115
- if (currentWeights.matrix instanceof Float32Array) {
1116
- flatMatrix = new Float32Array(currentWeights.matrix);
1117
- } else {
1118
- flatMatrix = flattenMatrix(currentWeights.matrix, dim, dim, "updateOnline Matrix");
3190
+ assertDimension(example.anchor, dim, "InfoNCETrainer.train anchor");
3191
+ assertDimension(example.positive, dim, "InfoNCETrainer.train positive");
3192
+ if (example.negatives.length === 0) {
3193
+ throw new Error("InfoNCETrainer requires at least one negative example.");
1119
3194
  }
1120
- const bias = new Float32Array(currentWeights.bias);
1121
- const vMatrix = new Float32Array(dim * dim);
1122
- const vBias = new Float32Array(dim);
1123
- this.sgdMomentumStep(
3195
+ for (const neg of example.negatives) {
3196
+ assertDimension(neg, dim, "InfoNCETrainer.train negative");
3197
+ }
3198
+ const { flatMatrix, bias } = getFlatMatrixAndBias(
3199
+ currentWeights,
3200
+ dim,
3201
+ "updateOnline Matrix"
3202
+ );
3203
+ const warpedAnchor = new Float32Array(dim);
3204
+ applyAffine(flatMatrix, bias, example.anchor, warpedAnchor, dim);
3205
+ const posScore = innerProduct(warpedAnchor, example.positive);
3206
+ const negScores = new Float32Array(example.negatives.length);
3207
+ for (let n = 0; n < example.negatives.length; n++) {
3208
+ negScores[n] = innerProduct(warpedAnchor, example.negatives[n]);
3209
+ }
3210
+ let maxScore = posScore / temperature;
3211
+ for (let n = 0; n < example.negatives.length; n++) {
3212
+ const s = negScores[n] / temperature;
3213
+ if (s > maxScore) maxScore = s;
3214
+ }
3215
+ const expPos = Math.exp(posScore / temperature - maxScore);
3216
+ const expNegs = new Float32Array(example.negatives.length);
3217
+ let sumExp = expPos;
3218
+ for (let n = 0; n < example.negatives.length; n++) {
3219
+ const expN = Math.exp(negScores[n] / temperature - maxScore);
3220
+ expNegs[n] = expN;
3221
+ sumExp += expN;
3222
+ }
3223
+ const pPos = expPos / sumExp;
3224
+ const pNegs = new Float32Array(example.negatives.length);
3225
+ for (let n = 0; n < example.negatives.length; n++) {
3226
+ pNegs[n] = expNegs[n] / sumExp;
3227
+ }
3228
+ this.t += 1;
3229
+ const outputGradients = new Float32Array(dim);
3230
+ for (let i = 0; i < dim; i++) {
3231
+ let gradA_i = (pPos - 1) * example.positive[i];
3232
+ for (let n = 0; n < example.negatives.length; n++) {
3233
+ gradA_i += pNegs[n] * example.negatives[n][i];
3234
+ }
3235
+ outputGradients[i] = gradA_i / temperature;
3236
+ }
3237
+ this.applyAdamToAffine(
1124
3238
  flatMatrix,
1125
3239
  bias,
1126
- vMatrix,
1127
- vBias,
1128
- input,
1129
- target,
3240
+ this.mW,
3241
+ this.vW,
3242
+ this.mb,
3243
+ this.vb,
3244
+ example.anchor,
3245
+ outputGradients,
1130
3246
  learningRate,
1131
3247
  regularization,
1132
- 0
1133
- // no momentum for 1-shot online update
3248
+ this.t
1134
3249
  );
1135
3250
  const newWeights = this.toWeights(flatMatrix, bias);
1136
3251
  if (currentWeights.routingVector) {
@@ -1181,77 +3296,519 @@ var MigrationTrainer = class extends BaseTrainer {
1181
3296
  }
1182
3297
  };
1183
3298
 
1184
- // src/db.ts
1185
- var VectorDBAdapter = class {
3299
+ // src/integrations/index.ts
3300
+ var integrations_exports = {};
3301
+ __export(integrations_exports, {
3302
+ WarpEmbeddings: () => WarpEmbeddings,
3303
+ withWarpVector: () => withWarpVector
3304
+ });
3305
+
3306
+ // src/VsaAdapter.ts
3307
+ var VsaAdapter = class _VsaAdapter {
1186
3308
  /**
1187
- * PostgreSQL (pgvector) 用のクエリ文字列表現を生成します。
1188
- * INSERT や SELECT の際に使用できる形式です。
3309
+ * ベクトルのバンドリング (Bundling / Superposition)
3310
+ * 複数のベクトルを足し合わせ(重ね合わせ)て1つのベクトルに統合します。
3311
+ * 「A と B の両方の概念を含む」ベクトルを作成する際に使用します。
1189
3312
  *
1190
- * @example
1191
- * const sql = `SELECT * FROM items ORDER BY embedding <-> '${VectorDBAdapter.toPgvector(warpedVector)}' LIMIT 5`;
3313
+ * @param vectors 束ねるベクトルの配列
3314
+ * @param options 演算オプション
3315
+ * @returns 束ねられた新しいベクトル
3316
+ */
3317
+ static bundle(vectors, options = {}) {
3318
+ if (vectors.length === 0) {
3319
+ throw new Error("Cannot bundle an empty array of vectors.");
3320
+ }
3321
+ const dim = vectors[0].length;
3322
+ const result = new Float32Array(dim);
3323
+ for (let i = 0; i < vectors.length; i++) {
3324
+ const vec = vectors[i];
3325
+ assertDimension(vec, dim, `Vector at index ${i}`);
3326
+ addScaledVector(result, vec, 1);
3327
+ }
3328
+ const shouldNormalize = options.shouldNormalize ?? true;
3329
+ if (shouldNormalize) {
3330
+ return normalize(result);
3331
+ }
3332
+ return result;
3333
+ }
3334
+ /**
3335
+ * ベクトルのバインディング (Binding / Hadamard Product)
3336
+ * アダマール積(要素ごとの積)を用いて、2つのベクトルを「結合」します。
3337
+ * 例: キー(ユーザーID)と値(好み)を掛け合わせ、特有の「ユーザーの好み」ベクトルを生成します。
1192
3338
  *
1193
- * @param {number[] | Float32Array} vector ワープ変換後のベクトル
1194
- * @returns {string} `'[0.1, 0.2, 0.3]'` のような文字列表現
3339
+ * @param vec1 バインドするベクトル1
3340
+ * @param vec2 バインドするベクトル2
3341
+ * @param options 演算オプション
3342
+ * @returns バインドされた新しいベクトル
1195
3343
  */
1196
- static toPgvector(vector) {
1197
- return `[${Array.from(vector).join(", ")}]`;
3344
+ static bind(vec1, vec2, options = {}) {
3345
+ const dim = vec1.length;
3346
+ assertDimension(vec2, dim, "Vector 2");
3347
+ const result = new Float32Array(dim);
3348
+ for (let i = 0; i < dim; i++) {
3349
+ result[i] = vec1[i] * vec2[i];
3350
+ }
3351
+ const shouldNormalize = options.shouldNormalize ?? true;
3352
+ if (shouldNormalize) {
3353
+ return normalize(result);
3354
+ }
3355
+ return result;
1198
3356
  }
1199
3357
  /**
1200
- * Pinecone 用のクエリオブジェクトを生成します。
1201
- * Pinecone クライアントに直接渡せる形式のオブジェクトを返します。
3358
+ * ベクトルのアンバインディング (Unbinding)
3359
+ * バインドされたベクトルから、片方のベクトル(キー)を使って元の値(バリュー)を取り出します。
3360
+ * アダマール積によるバインディングの逆演算(要素ごとの除算)を行います。
1202
3361
  *
1203
- * @example
1204
- * const query = VectorDBAdapter.toPineconeQuery(warpedVector, 10, { genre: "comedy" });
1205
- * await index.query(query);
3362
+ * @param boundVec バインド済みのベクトル
3363
+ * @param keyVec 抽出に使用するキーベクトル
3364
+ * @param options 演算オプション
3365
+ * @returns アンバインドされて抽出されたベクトル
3366
+ */
3367
+ static unbind(boundVec, keyVec, options = {}) {
3368
+ const dim = boundVec.length;
3369
+ assertDimension(keyVec, dim, "Key Vector");
3370
+ const result = new Float32Array(dim);
3371
+ for (let i = 0; i < dim; i++) {
3372
+ const val = keyVec[i] === 0 ? 1e-8 : keyVec[i];
3373
+ result[i] = boundVec[i] / val;
3374
+ }
3375
+ const shouldNormalize = options.shouldNormalize ?? true;
3376
+ if (shouldNormalize) {
3377
+ return normalize(result);
3378
+ }
3379
+ return result;
3380
+ }
3381
+ /**
3382
+ * ---------------------------------------------------------
3383
+ * Binary VSA (バイナリベクトル・シンボリック・アーキテクチャ)
3384
+ * ---------------------------------------------------------
3385
+ * QuantizationAdapter で 1-bit (Binary) 量子化された Uint8Array ベクトルに
3386
+ * 対する超次元計算を行います。XOR 演算により、超高速・極小メモリでの処理が可能です。
3387
+ */
3388
+ /**
3389
+ * バイナリベクトルのバインディング (Binary Binding / XOR)
3390
+ * XOR (排他的論理和) を用いて2つのバイナリベクトルを結合します。
3391
+ * Binary VSA において、XOR は情報を結合するための標準的な演算です。
1206
3392
  *
1207
- * @param {number[] | Float32Array} vector 検索クエリベクトル
1208
- * @param {number} topK 取得する件数 (デフォルト: 10)
1209
- * @param {Record<string, any>} [filter] メタデータフィルタ(オプション)
1210
- * @returns {Record<string, any>} Pineconeのqueryメソッド用オブジェクト
3393
+ * @param bin1 バインドするバイナリベクトル1 (Uint8Array)
3394
+ * @param bin2 バインドするバイナリベクトル2 (Uint8Array)
3395
+ * @returns バインドされた新しいバイナリベクトル (Uint8Array)
1211
3396
  */
1212
- static toPineconeQuery(vector, topK = 10, filter) {
3397
+ static bindBinary(bin1, bin2) {
3398
+ if (bin1.length !== bin2.length) {
3399
+ throw new Error("Binary vectors must have the same length in bytes.");
3400
+ }
3401
+ const len = bin1.length;
3402
+ const result = new Uint8Array(len);
3403
+ for (let i = 0; i < len; i++) {
3404
+ result[i] = bin1[i] ^ bin2[i];
3405
+ }
3406
+ return result;
3407
+ }
3408
+ /**
3409
+ * バイナリベクトルのアンバインディング (Binary Unbinding / XOR)
3410
+ * XOR の自己逆性 (A ^ B ^ B = A) を利用して、キーを用いて元の値を抽出します。
3411
+ * 内部的には bindBinary と全く同じ処理です。
3412
+ *
3413
+ * @param boundBin バインド済みのバイナリベクトル (Uint8Array)
3414
+ * @param keyBin 抽出に使用するキーバイナリベクトル (Uint8Array)
3415
+ * @returns アンバインドされて抽出されたバイナリベクトル (Uint8Array)
3416
+ */
3417
+ static unbindBinary(boundBin, keyBin) {
3418
+ return _VsaAdapter.bindBinary(boundBin, keyBin);
3419
+ }
3420
+ /**
3421
+ * バイナリベクトルのバンドリング (Binary Bundling / Majority Vote)
3422
+ * 複数のバイナリベクトルを重ね合わせます。各ビット位置で 1 と 0 の出現回数をカウントし、
3423
+ * 多数決 (Majority Vote) で最終的なビットを決定します。
3424
+ *
3425
+ * @param bins 束ねるバイナリベクトルの配列 (Uint8Arrayの配列)
3426
+ * @returns 束ねられた新しいバイナリベクトル (Uint8Array)
3427
+ */
3428
+ static bundleBinary(bins) {
3429
+ if (bins.length === 0) {
3430
+ throw new Error("Cannot bundle an empty array of binary vectors.");
3431
+ }
3432
+ const numVectors = bins.length;
3433
+ const len = bins[0].length;
3434
+ const result = new Uint8Array(len);
3435
+ for (let i = 0; i < len; i++) {
3436
+ let resultByte = 0;
3437
+ for (let bit = 0; bit < 8; bit++) {
3438
+ let onesCount = 0;
3439
+ const mask = 1 << bit;
3440
+ for (let v = 0; v < numVectors; v++) {
3441
+ if (bins[v].length !== len) {
3442
+ throw new Error(
3443
+ `Binary vector at index ${v} has mismatched length.`
3444
+ );
3445
+ }
3446
+ if ((bins[v][i] & mask) !== 0) {
3447
+ onesCount++;
3448
+ }
3449
+ }
3450
+ if (onesCount > numVectors / 2) {
3451
+ resultByte |= mask;
3452
+ } else if (onesCount === numVectors / 2) {
3453
+ resultByte |= mask;
3454
+ }
3455
+ }
3456
+ result[i] = resultByte;
3457
+ }
3458
+ return result;
3459
+ }
3460
+ };
3461
+
3462
+ // src/TaskArithmetic.ts
3463
+ var TaskArithmetic = class {
3464
+ /**
3465
+ * 複数のタスク(IntentWeights)を合成し、新しい IntentWeights を作成します。
3466
+ * 数式: W_new = W_base + Σ scale_i * (W_i - W_base)
3467
+ *
3468
+ * @param tasks 合成するタスクのリスト(IntentWeights と スケールのペア)
3469
+ * @param baseIntent 基準となる IntentWeights。省略された場合は恒等行列(Identity)とゼロバイアスがベースになります。
3470
+ * @returns 完全にマージされた新しい IntentWeights
3471
+ */
3472
+ static merge(tasks, baseIntent) {
3473
+ if (tasks.length === 0) {
3474
+ throw new Error("No tasks provided to merge.");
3475
+ }
3476
+ const dim = tasks[0].weights.bias.length;
3477
+ let baseMatrix;
3478
+ let baseBias;
3479
+ if (baseIntent) {
3480
+ assertDimension(baseIntent.bias, dim, "Base bias");
3481
+ baseBias = new Float32Array(baseIntent.bias);
3482
+ if (baseIntent.matrix instanceof Float32Array) {
3483
+ assertDimension(baseIntent.matrix, dim * dim, "Base matrix");
3484
+ baseMatrix = new Float32Array(baseIntent.matrix);
3485
+ } else {
3486
+ baseMatrix = flattenMatrix(baseIntent.matrix, dim, dim, "Base matrix");
3487
+ }
3488
+ } else {
3489
+ baseMatrix = new Float32Array(dim * dim);
3490
+ for (let i = 0; i < dim; i++) {
3491
+ baseMatrix[i * dim + i] = 1;
3492
+ }
3493
+ baseBias = new Float32Array(dim);
3494
+ }
3495
+ const newMatrix = new Float32Array(baseMatrix);
3496
+ const newBias = new Float32Array(baseBias);
3497
+ for (let t = 0; t < tasks.length; t++) {
3498
+ const { weights, scale } = tasks[t];
3499
+ assertDimension(weights.bias, dim, `Task ${t} bias`);
3500
+ const taskBias = new Float32Array(weights.bias);
3501
+ let taskMatrix;
3502
+ if (weights.matrix instanceof Float32Array) {
3503
+ assertDimension(weights.matrix, dim * dim, `Task ${t} matrix`);
3504
+ taskMatrix = weights.matrix;
3505
+ } else {
3506
+ taskMatrix = flattenMatrix(
3507
+ weights.matrix,
3508
+ dim,
3509
+ dim,
3510
+ `Task ${t} matrix`
3511
+ );
3512
+ }
3513
+ addScaledVector(newMatrix, taskMatrix, scale);
3514
+ addScaledVector(newMatrix, baseMatrix, -scale);
3515
+ addScaledVector(newBias, taskBias, scale);
3516
+ addScaledVector(newBias, baseBias, -scale);
3517
+ }
1213
3518
  return {
1214
- vector: Array.from(vector),
1215
- topK,
1216
- ...filter ? { filter } : {}
3519
+ matrix: newMatrix,
3520
+ bias: newBias
1217
3521
  };
1218
3522
  }
3523
+ };
3524
+
3525
+ // src/WarpPipeline.ts
3526
+ var WarpPipeline = class _WarpPipeline {
3527
+ constructor(inputDim) {
3528
+ this.inputDim = inputDim;
3529
+ }
3530
+ inputDim;
3531
+ steps = [];
1219
3532
  /**
1220
- * Redis (RediSearch) のベクトルフィールド用に、
1221
- * Float32Array をバイナリ(Uint8Array)に変換します。
1222
- * Node.js環境では Buffer.from() を使って Buffer に変換して渡してください。
3533
+ * アダプタの復元関数を保持するレジストリ。
3534
+ * カスタムアダプタをパイプラインで利用・復元可能にするために使用します。
3535
+ */
3536
+ static adapterRegistry = /* @__PURE__ */ new Map();
3537
+ /**
3538
+ * カスタムアダプタをパイプラインのレジストリに登録します。
3539
+ * これにより importState でカスタムアダプタを復元可能になります。
1223
3540
  *
1224
- * @example
1225
- * const blob = Buffer.from(VectorDBAdapter.toRedis(warpedVector));
1226
- * await redis.call('FT.SEARCH', 'idx', '*=>[KNN 5 @embedding $BLOB]', 'PARAMS', '2', 'BLOB', blob, 'DIALECT', '2');
3541
+ * @param type アダプタの識別子 (例: "MyCustomAdapter")
3542
+ * @param importFn 状態オブジェクトからアダプタインスタンスを復元する関数
3543
+ */
3544
+ static registerAdapter(type, importFn) {
3545
+ _WarpPipeline.adapterRegistry.set(type, importFn);
3546
+ }
3547
+ /**
3548
+ * フォーマット変換ロジックを保持するレジストリ。
3549
+ */
3550
+ static formatRegistry = /* @__PURE__ */ new Map();
3551
+ /**
3552
+ * カスタムの出力フォーマットを登録します。
3553
+ * これにより、ユーザー独自のDB形式(Milvus, Weaviateなど)への変換を動的に追加できます。
1227
3554
  *
1228
- * @param {number[] | Float32Array} vector ワープ変換後のベクトル
1229
- * @returns {Uint8Array} バイナリデータ (Float32のバイト表現)
3555
+ * @param format フォーマット名 (例: "pgvector")
3556
+ * @param formatFn 変換を行うコールバック関数
1230
3557
  */
1231
- static toRedis(vector) {
1232
- const f32Array = vector instanceof Float32Array ? vector : new Float32Array(vector);
1233
- return new Uint8Array(
1234
- f32Array.buffer.slice(
1235
- f32Array.byteOffset,
1236
- f32Array.byteOffset + f32Array.byteLength
1237
- )
3558
+ static registerFormat(format, formatFn) {
3559
+ _WarpPipeline.formatRegistry.set(format, formatFn);
3560
+ }
3561
+ /**
3562
+ * IntentAdapter (意図による線形変換) をパイプラインに追加します。
3563
+ */
3564
+ addIntent(intents) {
3565
+ const adapter = new IntentAdapter(intents || this.inputDim);
3566
+ this.steps.push({ type: "IntentAdapter", adapter });
3567
+ return this;
3568
+ }
3569
+ /**
3570
+ * LoraIntentAdapter (低ランク適応による線形変換) をパイプラインに追加します。
3571
+ */
3572
+ addLoraIntent(rank, intents) {
3573
+ const adapter = new LoraIntentAdapter(this.inputDim, rank, intents);
3574
+ this.steps.push({ type: "LoraIntentAdapter", adapter });
3575
+ return this;
3576
+ }
3577
+ /**
3578
+ * WhiteningAdapter (PCAによる空間的偏りの除去) をパイプラインに追加します。
3579
+ */
3580
+ addWhitening(options) {
3581
+ const adapter = new WhiteningAdapter(this.inputDim, options);
3582
+ this.steps.push({ type: "WhiteningAdapter", adapter });
3583
+ return this;
3584
+ }
3585
+ /**
3586
+ * ProjectionAdapter (次元圧縮) をパイプラインに追加します。
3587
+ */
3588
+ addProjection(outputDim, projections) {
3589
+ const adapter = new ProjectionAdapter(
3590
+ this.inputDim,
3591
+ outputDim,
3592
+ projections
1238
3593
  );
3594
+ this.steps.push({ type: "ProjectionAdapter", adapter });
3595
+ this.inputDim = outputDim;
3596
+ return this;
3597
+ }
3598
+ /**
3599
+ * MlpAdapter (多層ニューラルネットワーク / 非線形推論) をパイプラインに追加します。
3600
+ */
3601
+ addMlp(layers) {
3602
+ const adapter = new MlpAdapter(layers);
3603
+ this.steps.push({ type: "MlpAdapter", adapter });
3604
+ const lastLayer = layers[layers.length - 1];
3605
+ if (lastLayer.matrix instanceof Float32Array) {
3606
+ this.inputDim = lastLayer.bias.length;
3607
+ } else {
3608
+ this.inputDim = lastLayer.matrix.length;
3609
+ }
3610
+ return this;
3611
+ }
3612
+ /**
3613
+ * QuantizationAdapter (ベクトル量子化 / 圧縮) をパイプラインに追加します。
3614
+ * これは通常、パイプラインの最後のステップとして使用されます。
3615
+ */
3616
+ quantize(type) {
3617
+ const adapter = new QuantizationAdapter({ type, dim: this.inputDim });
3618
+ this.steps.push({ type: "QuantizationAdapter", adapter });
3619
+ return this;
3620
+ }
3621
+ /**
3622
+ * カスタムアダプタを直接パイプラインの末尾に追加します。
3623
+ * (ビルダーパターンで独自の拡張アダプタを組み込む際に使用します)
3624
+ *
3625
+ * @param type アダプタの識別子(レジストリ登録名と一致させることを推奨)
3626
+ * @param adapter WarpAdapterを実装したインスタンス
3627
+ */
3628
+ addStep(type, adapter) {
3629
+ this.steps.push({ type, adapter });
3630
+ return this;
3631
+ }
3632
+ /**
3633
+ * パイプライン内に WASM などの非同期初期化を必要とするアダプタが含まれている場合、
3634
+ * それらを一括でセットアップします。
3635
+ */
3636
+ async init() {
3637
+ for (const step of this.steps) {
3638
+ if (typeof step.adapter.init === "function") {
3639
+ await step.adapter.init();
3640
+ }
3641
+ }
3642
+ }
3643
+ /**
3644
+ * パイプラインを順次実行し、入力ベクトルを最終的な表現に変換します。
3645
+ *
3646
+ * @param vector 変換元のベースベクトル
3647
+ * @param context インテントやバージョンなどのコンテキスト情報
3648
+ * @returns パイプラインを通過した最終的なベクトル (Float32Array または Uint8Array/Int8Array)
3649
+ */
3650
+ run(vector, context) {
3651
+ let currentVector = vector;
3652
+ for (const step of this.steps) {
3653
+ currentVector = step.adapter.tune(
3654
+ currentVector,
3655
+ context?.intent || "default"
3656
+ );
3657
+ }
3658
+ return currentVector;
3659
+ }
3660
+ /**
3661
+ * 複数のベクトル(バッチ)を一括でパイプラインに通します。
3662
+ * 内部の tuneBatch が実装されているアダプタでは WASM/SIMD による高速処理が適用されます。
3663
+ *
3664
+ * @param vectors 変換元のベースベクトルの配列
3665
+ * @param context インテントやバージョンなどのコンテキスト情報
3666
+ * @returns 変換されたベクトルの配列
3667
+ */
3668
+ runBatch(vectors, context) {
3669
+ let currentVectors = vectors;
3670
+ for (const step of this.steps) {
3671
+ if (typeof step.adapter.tuneBatch === "function") {
3672
+ currentVectors = step.adapter.tuneBatch(
3673
+ currentVectors,
3674
+ context?.intent || "default"
3675
+ );
3676
+ } else {
3677
+ currentVectors = currentVectors.map(
3678
+ (vec) => step.adapter.tune(vec, context?.intent || "default")
3679
+ );
3680
+ }
3681
+ }
3682
+ return currentVectors;
3683
+ }
3684
+ /**
3685
+ * ベクトル変換から特定データベース向けのフォーマットまでを1回の呼び出しで行います。
3686
+ *
3687
+ * @param vector 変換元のベースベクトル
3688
+ * @param dbOptions フォーマットの指定オプション
3689
+ * @param context パイプラインのコンテキスト
3690
+ * @returns 指定されたデータベース形式のオブジェクトや文字列
3691
+ */
3692
+ runAndFormat(vector, dbOptions, context) {
3693
+ const tunedVector = this.run(vector, context);
3694
+ const formatFn = _WarpPipeline.formatRegistry.get(dbOptions.format);
3695
+ if (!formatFn) {
3696
+ throw new Error(
3697
+ `Unknown format: ${dbOptions.format}. Did you forget to register it?`
3698
+ );
3699
+ }
3700
+ return formatFn(tunedVector, dbOptions);
3701
+ }
3702
+ /**
3703
+ * パイプライン内の全アダプタの状態(学習済みの重みなど)を JSON 化可能な配列として出力します。
3704
+ * これにより、DBやRedis等への永続化が容易になります。
3705
+ */
3706
+ exportState() {
3707
+ return this.steps.map((step) => {
3708
+ const state = typeof step.adapter.exportState === "function" ? step.adapter.exportState() : null;
3709
+ return {
3710
+ type: step.type,
3711
+ state
3712
+ };
3713
+ });
3714
+ }
3715
+ /**
3716
+ * エクスポートされた JSON 状態から、パイプラインを完全に復元(再構築)します。
3717
+ * @param states exportState で出力された配列
3718
+ * @returns 復元された新しい WarpPipeline インスタンス
3719
+ */
3720
+ static importState(states) {
3721
+ if (!states || states.length === 0) {
3722
+ throw new Error("No states provided to import.");
3723
+ }
3724
+ const pipeline = new _WarpPipeline(0);
3725
+ for (const step of states) {
3726
+ const importFn = _WarpPipeline.adapterRegistry.get(step.type);
3727
+ if (!importFn) {
3728
+ throw new Error(
3729
+ `Unknown adapter type: ${step.type}. Did you forget to register it via WarpPipeline.registerAdapter?`
3730
+ );
3731
+ }
3732
+ const adapter = importFn(step.state);
3733
+ pipeline.steps.push({ type: step.type, adapter });
3734
+ }
3735
+ if (pipeline.steps.length > 0) {
3736
+ }
3737
+ return pipeline;
1239
3738
  }
1240
3739
  };
3740
+ WarpPipeline.registerAdapter(
3741
+ "IntentAdapter",
3742
+ (state) => IntentAdapter.importState(state)
3743
+ );
3744
+ WarpPipeline.registerAdapter(
3745
+ "LoraIntentAdapter",
3746
+ (state) => LoraIntentAdapter.importState(state)
3747
+ );
3748
+ WarpPipeline.registerAdapter(
3749
+ "WhiteningAdapter",
3750
+ (state) => WhiteningAdapter.importState(state)
3751
+ );
3752
+ WarpPipeline.registerAdapter(
3753
+ "ProjectionAdapter",
3754
+ (state) => ProjectionAdapter.importState(state)
3755
+ );
3756
+ WarpPipeline.registerAdapter(
3757
+ "MlpAdapter",
3758
+ (state) => MlpAdapter.importState(state)
3759
+ );
3760
+ WarpPipeline.registerAdapter(
3761
+ "QuantizationAdapter",
3762
+ (state) => QuantizationAdapter.importState(state)
3763
+ );
3764
+ WarpPipeline.registerFormat(
3765
+ "pgvector",
3766
+ (vec, _opts) => VectorDBAdapter.toPgvector(vec)
3767
+ );
3768
+ WarpPipeline.registerFormat(
3769
+ "pinecone",
3770
+ (vec, opts) => VectorDBAdapter.toPineconeQuery(
3771
+ vec,
3772
+ opts.topK,
3773
+ opts.filter
3774
+ )
3775
+ );
3776
+ WarpPipeline.registerFormat(
3777
+ "redis",
3778
+ (vec, _opts) => VectorDBAdapter.toRedis(vec)
3779
+ );
1241
3780
  export {
3781
+ ColbertAdapter,
3782
+ InfoNCETrainer,
1242
3783
  IntentAdapter,
1243
3784
  IntentTrainer,
1244
3785
  LoraIntentAdapter,
1245
3786
  MigrationTrainer,
3787
+ MlpAdapter,
1246
3788
  ProjectionAdapter,
3789
+ QuantizationAdapter,
3790
+ TaskArithmetic,
3791
+ TripletTrainer,
1247
3792
  VectorDBAdapter,
3793
+ VsaAdapter,
3794
+ WarpEmbeddings,
3795
+ WarpLlamaIndexEmbeddings,
3796
+ WarpPipeline,
3797
+ WhiteningAdapter,
3798
+ addScaledVector,
1248
3799
  applyActivationToVector,
3800
+ applyAffine,
1249
3801
  assertDimension,
1250
3802
  cosineSimilarity,
1251
3803
  flattenMatrix,
3804
+ getFlatMatrixAndBias,
1252
3805
  innerProduct,
3806
+ integrations_exports as integrations,
1253
3807
  normalize,
1254
3808
  reject,
3809
+ rrf,
3810
+ rsf,
1255
3811
  slerp,
1256
- softmax
3812
+ softmax,
3813
+ withWarpVector
1257
3814
  };