warpvector 0.1.0 → 0.1.1

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