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