spec-cat 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/_nuxt/{Bqlz6CoK.js → BE_75kPa.js} +1 -1
  3. package/.output/public/_nuxt/{B2wdmh_w.js → BJ7m4fRW.js} +53 -53
  4. package/.output/public/_nuxt/{KNuzSjk0.js → CCNYUZ9m.js} +1 -1
  5. package/.output/public/_nuxt/{BvosqTnx.js → DGtcdWVl.js} +1 -1
  6. package/.output/public/_nuxt/DxEx-kFx.js +1 -0
  7. package/.output/public/_nuxt/{BwcbSlWF.js → DyMq_cQC.js} +2 -2
  8. package/.output/public/_nuxt/{COTT6rNZ.js → _cj5lOdZ.js} +1 -1
  9. package/.output/public/_nuxt/builds/latest.json +1 -1
  10. package/.output/public/_nuxt/builds/meta/3a0aacc1-0bd1-4d15-8b8a-3cee48cbfc69.json +1 -0
  11. package/.output/public/_nuxt/{BUOk7wkI.js → gDut6QrP.js} +1 -1
  12. package/.output/public/_nuxt/{C5wk2twv.js → nJpWpjzg.js} +1 -1
  13. package/.output/public/_nuxt/{DBab5Zcv.js → waQ9fPC1.js} +1 -1
  14. package/.output/server/chunks/_/codexProvider.mjs +64 -18
  15. package/.output/server/chunks/_/codexProvider.mjs.map +1 -1
  16. package/.output/server/chunks/build/client.precomputed.mjs +1 -1
  17. package/.output/server/chunks/build/client.precomputed.mjs.map +1 -1
  18. package/.output/server/chunks/nitro/nitro.mjs +702 -703
  19. package/.output/server/chunks/routes/_ws.mjs +37 -7
  20. package/.output/server/chunks/routes/_ws.mjs.map +1 -1
  21. package/.output/server/node_modules/@huggingface/jinja/dist/index.js +1572 -0
  22. package/.output/server/node_modules/@huggingface/jinja/package.json +55 -0
  23. package/.output/server/node_modules/@xenova/transformers/package.json +84 -0
  24. package/.output/server/node_modules/@xenova/transformers/src/backends/onnx.js +50 -0
  25. package/.output/server/node_modules/@xenova/transformers/src/configs.js +107 -0
  26. package/.output/server/node_modules/@xenova/transformers/src/env.js +128 -0
  27. package/.output/server/node_modules/@xenova/transformers/src/models.js +6267 -0
  28. package/.output/server/node_modules/@xenova/transformers/src/pipelines.js +3287 -0
  29. package/.output/server/node_modules/@xenova/transformers/src/processors.js +2248 -0
  30. package/.output/server/node_modules/@xenova/transformers/src/tokenizers.js +4479 -0
  31. package/.output/server/node_modules/@xenova/transformers/src/transformers.js +24 -0
  32. package/.output/server/node_modules/@xenova/transformers/src/utils/audio.js +672 -0
  33. package/.output/server/node_modules/@xenova/transformers/src/utils/core.js +175 -0
  34. package/.output/server/node_modules/@xenova/transformers/src/utils/data-structures.js +415 -0
  35. package/.output/server/node_modules/@xenova/transformers/src/utils/generation.js +873 -0
  36. package/.output/server/node_modules/@xenova/transformers/src/utils/hub.js +658 -0
  37. package/.output/server/node_modules/@xenova/transformers/src/utils/image.js +731 -0
  38. package/.output/server/node_modules/@xenova/transformers/src/utils/maths.js +985 -0
  39. package/.output/server/node_modules/@xenova/transformers/src/utils/tensor.js +1239 -0
  40. package/.output/server/node_modules/color/index.js +496 -0
  41. package/.output/server/node_modules/color/package.json +47 -0
  42. package/.output/server/node_modules/color-convert/conversions.js +839 -0
  43. package/.output/server/node_modules/color-convert/index.js +81 -0
  44. package/.output/server/node_modules/color-convert/package.json +48 -0
  45. package/.output/server/node_modules/color-convert/route.js +97 -0
  46. package/.output/server/node_modules/color-name/index.js +152 -0
  47. package/.output/server/node_modules/color-name/package.json +28 -0
  48. package/.output/server/node_modules/color-string/index.js +242 -0
  49. package/.output/server/node_modules/color-string/package.json +39 -0
  50. package/.output/server/node_modules/detect-libc/lib/detect-libc.js +313 -0
  51. package/.output/server/node_modules/detect-libc/lib/elf.js +39 -0
  52. package/.output/server/node_modules/detect-libc/lib/filesystem.js +51 -0
  53. package/.output/server/node_modules/detect-libc/lib/process.js +24 -0
  54. package/.output/server/node_modules/detect-libc/package.json +44 -0
  55. package/.output/server/node_modules/is-arrayish/index.js +9 -0
  56. package/.output/server/node_modules/is-arrayish/package.json +45 -0
  57. package/.output/server/node_modules/onnxruntime-common/dist/ort-common.node.js +7 -0
  58. package/.output/server/node_modules/onnxruntime-common/package.json +31 -0
  59. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/darwin/arm64/onnxruntime_binding.node +0 -0
  60. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/darwin/x64/onnxruntime_binding.node +0 -0
  61. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/arm64/libonnxruntime.so.1.14.0 +0 -0
  62. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/arm64/onnxruntime_binding.node +0 -0
  63. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/libonnxruntime.so.1.14.0 +0 -0
  64. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/linux/x64/onnxruntime_binding.node +0 -0
  65. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/win32/arm64/onnxruntime_binding.node +0 -0
  66. package/.output/server/node_modules/onnxruntime-node/bin/napi-v3/win32/x64/onnxruntime_binding.node +0 -0
  67. package/.output/server/node_modules/onnxruntime-node/dist/backend.js +75 -0
  68. package/.output/server/node_modules/onnxruntime-node/dist/binding.js +10 -0
  69. package/.output/server/node_modules/onnxruntime-node/dist/index.js +23 -0
  70. package/.output/server/node_modules/onnxruntime-node/package.json +58 -0
  71. package/.output/server/node_modules/onnxruntime-web/dist/ort-web.node.js +7 -0
  72. package/.output/server/node_modules/onnxruntime-web/package.json +84 -0
  73. package/.output/server/node_modules/semver/classes/semver.js +333 -0
  74. package/.output/server/node_modules/semver/functions/coerce.js +62 -0
  75. package/.output/server/node_modules/semver/functions/compare.js +7 -0
  76. package/.output/server/node_modules/semver/functions/gte.js +5 -0
  77. package/.output/server/node_modules/semver/functions/parse.js +18 -0
  78. package/.output/server/node_modules/semver/internal/constants.js +37 -0
  79. package/.output/server/node_modules/semver/internal/debug.js +11 -0
  80. package/.output/server/node_modules/semver/internal/identifiers.js +29 -0
  81. package/.output/server/node_modules/semver/internal/parse-options.js +17 -0
  82. package/.output/server/node_modules/semver/internal/re.js +223 -0
  83. package/.output/server/node_modules/semver/package.json +78 -0
  84. package/.output/server/node_modules/sharp/build/Release/sharp-linux-x64.node +0 -0
  85. package/.output/server/node_modules/sharp/lib/channel.js +174 -0
  86. package/.output/server/node_modules/sharp/lib/colour.js +184 -0
  87. package/.output/server/node_modules/sharp/lib/composite.js +210 -0
  88. package/.output/server/node_modules/sharp/lib/constructor.js +439 -0
  89. package/.output/server/node_modules/sharp/lib/index.js +16 -0
  90. package/.output/server/node_modules/sharp/lib/input.js +631 -0
  91. package/.output/server/node_modules/sharp/lib/is.js +155 -0
  92. package/.output/server/node_modules/sharp/lib/libvips.js +140 -0
  93. package/.output/server/node_modules/sharp/lib/operation.js +919 -0
  94. package/.output/server/node_modules/sharp/lib/output.js +1413 -0
  95. package/.output/server/node_modules/sharp/lib/platform.js +30 -0
  96. package/.output/server/node_modules/sharp/lib/resize.js +582 -0
  97. package/.output/server/node_modules/sharp/lib/sharp.js +38 -0
  98. package/.output/server/node_modules/sharp/lib/utility.js +287 -0
  99. package/.output/server/node_modules/sharp/package.json +204 -0
  100. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/THIRD-PARTY-NOTICES.md +43 -0
  101. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/lib/libvips-cpp.so.42 +0 -0
  102. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/platform.json +1 -0
  103. package/.output/server/node_modules/sharp/vendor/8.14.5/linux-x64/versions.json +31 -0
  104. package/.output/server/node_modules/simple-swizzle/index.js +29 -0
  105. package/.output/server/node_modules/simple-swizzle/package.json +36 -0
  106. package/.output/server/package.json +15 -1
  107. package/README.md +2 -0
  108. package/package.json +12 -19
  109. package/.output/public/_nuxt/5FxpIoe_.js +0 -1
  110. package/.output/public/_nuxt/builds/meta/21578a05-1b7e-4847-a8ff-7480800ea4a6.json +0 -1
@@ -0,0 +1,1239 @@
1
+ /**
2
+ * @file Helper module for `Tensor` processing.
3
+ *
4
+ * These functions and classes are only used internally,
5
+ * meaning an end-user shouldn't need to access anything here.
6
+ *
7
+ * @module utils/tensor
8
+ */
9
+
10
+ import { ONNX } from '../backends/onnx.js';
11
+
12
+ import {
13
+ interpolate_data,
14
+ permute_data
15
+ } from './maths.js';
16
+
17
+
18
+ const DataTypeMap = Object.freeze({
19
+ float32: Float32Array,
20
+ float64: Float64Array,
21
+ string: Array, // string[]
22
+ int8: Int8Array,
23
+ uint8: Uint8Array,
24
+ int16: Int16Array,
25
+ uint16: Uint16Array,
26
+ int32: Int32Array,
27
+ uint32: Uint32Array,
28
+ int64: BigInt64Array,
29
+ uint64: BigUint64Array,
30
+ bool: Uint8Array,
31
+ });
32
+
33
+ /**
34
+ * @typedef {keyof typeof DataTypeMap} DataType
35
+ * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray
36
+ */
37
+
38
+ const ONNXTensor = ONNX.Tensor;
39
+
40
+ export class Tensor {
41
+ /** @type {number[]} Dimensions of the tensor. */
42
+ dims;
43
+
44
+ /** @type {DataType} Type of the tensor. */
45
+ type;
46
+
47
+ /** @type {DataArray} The data stored in the tensor. */
48
+ data;
49
+
50
+ /** @type {number} The number of elements in the tensor. */
51
+ size;
52
+
53
+ /**
54
+ * Create a new Tensor or copy an existing Tensor.
55
+ * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
56
+ */
57
+ constructor(...args) {
58
+ if (args[0] instanceof ONNXTensor) {
59
+ // Create shallow copy
60
+ Object.assign(this, args[0]);
61
+
62
+ } else {
63
+ // Create new tensor
64
+ Object.assign(this, new ONNXTensor(
65
+ /** @type {DataType} */(args[0]),
66
+ /** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */(args[1]),
67
+ args[2]
68
+ ));
69
+ }
70
+
71
+ return new Proxy(this, {
72
+ get: (obj, key) => {
73
+ if (typeof key === 'string') {
74
+ let index = Number(key);
75
+ if (Number.isInteger(index)) {
76
+ // key is an integer (i.e., index)
77
+ return obj._getitem(index);
78
+ }
79
+ }
80
+ // @ts-ignore
81
+ return obj[key];
82
+ },
83
+ set: (obj, key, value) => {
84
+ // TODO allow setting of data
85
+
86
+ // @ts-ignore
87
+ return obj[key] = value;
88
+ }
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Returns an iterator object for iterating over the tensor data in row-major order.
94
+ * If the tensor has more than one dimension, the iterator will yield subarrays.
95
+ * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
96
+ */
97
+ *[Symbol.iterator]() {
98
+ const [iterLength, ...iterDims] = this.dims;
99
+
100
+ if (iterDims.length > 0) {
101
+ const iterSize = iterDims.reduce((a, b) => a * b);
102
+ for (let i = 0; i < iterLength; ++i) {
103
+ yield this._subarray(i, iterSize, iterDims);
104
+ }
105
+ } else {
106
+ yield* this.data
107
+ }
108
+
109
+ }
110
+
111
+ /**
112
+ * Index into a Tensor object.
113
+ * @param {number} index The index to access.
114
+ * @returns {Tensor} The data at the specified index.
115
+ */
116
+ _getitem(index) {
117
+ const [iterLength, ...iterDims] = this.dims;
118
+
119
+ index = safeIndex(index, iterLength);
120
+
121
+ if (iterDims.length > 0) {
122
+ const iterSize = iterDims.reduce((a, b) => a * b);
123
+ return this._subarray(index, iterSize, iterDims);
124
+ } else {
125
+ return new Tensor(this.type, [this.data[index]], iterDims);
126
+ }
127
+ }
128
+
129
+ /**
130
+ * @param {number|bigint} item The item to search for in the tensor
131
+ * @returns {number} The index of the first occurrence of item in the tensor data.
132
+ */
133
+ indexOf(item) {
134
+ for (let index = 0; index < this.data.length; ++index) {
135
+ // Note: == instead of === so we can match Ints with BigInts
136
+ if (this.data[index] == item) {
137
+ return index;
138
+ }
139
+ }
140
+ return -1;
141
+ }
142
+
143
+ /**
144
+ * @param {number} index
145
+ * @param {number} iterSize
146
+ * @param {any} iterDims
147
+ * @returns {Tensor}
148
+ */
149
+ _subarray(index, iterSize, iterDims) {
150
+ const o1 = index * iterSize;
151
+ const o2 = (index + 1) * iterSize;
152
+
153
+ // We use subarray if available (typed array), otherwise we use slice (normal array)
154
+ const data =
155
+ ('subarray' in this.data)
156
+ ? this.data.subarray(o1, o2)
157
+ : this.data.slice(o1, o2);
158
+ return new Tensor(this.type, data, iterDims);
159
+ }
160
+
161
+ /**
162
+ * Returns the value of this tensor as a standard JavaScript Number. This only works
163
+ * for tensors with one element. For other cases, see `Tensor.tolist()`.
164
+ * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
165
+ * @throws {Error} If the tensor has more than one element.
166
+ */
167
+ item() {
168
+ if (this.data.length !== 1) {
169
+ throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`);
170
+ }
171
+ return this.data[0];
172
+ }
173
+
174
+ /**
175
+ * Convert tensor data to a n-dimensional JS list
176
+ * @returns {Array}
177
+ */
178
+ tolist() {
179
+ return reshape(this.data, this.dims)
180
+ }
181
+
182
+ /**
183
+ * Return a new Tensor with the sigmoid function applied to each element.
184
+ * @returns {Tensor} The tensor with the sigmoid function applied.
185
+ */
186
+ sigmoid() {
187
+ return this.clone().sigmoid_();
188
+ }
189
+
190
+ /**
191
+ * Applies the sigmoid function to the tensor in place.
192
+ * @returns {Tensor} Returns `this`.
193
+ */
194
+ sigmoid_() {
195
+ for (let i = 0; i < this.data.length; ++i) {
196
+ this.data[i] = 1 / (1 + Math.exp(-this.data[i]));
197
+ }
198
+ return this;
199
+ }
200
+
201
+ /**
202
+ * Return a new Tensor with every element multiplied by a constant.
203
+ * @param {number} val The value to multiply by.
204
+ * @returns {Tensor} The new tensor.
205
+ */
206
+ mul(val) {
207
+ return this.clone().mul_(val);
208
+ }
209
+
210
+ /**
211
+ * Multiply the tensor by a constant in place.
212
+ * @param {number} val The value to multiply by.
213
+ * @returns {Tensor} Returns `this`.
214
+ */
215
+ mul_(val) {
216
+ for (let i = 0; i < this.data.length; ++i) {
217
+ this.data[i] *= val;
218
+ }
219
+ return this;
220
+ }
221
+
222
+
223
+ /**
224
+ * Return a new Tensor with every element added by a constant.
225
+ * @param {number} val The value to add by.
226
+ * @returns {Tensor} The new tensor.
227
+ */
228
+ add(val) {
229
+ return this.clone().add_(val);
230
+ }
231
+
232
+ /**
233
+ * Add the tensor by a constant in place.
234
+ * @param {number} val The value to add by.
235
+ * @returns {Tensor} Returns `this`.
236
+ */
237
+ add_(val) {
238
+ for (let i = 0; i < this.data.length; ++i) {
239
+ this.data[i] += val;
240
+ }
241
+ return this;
242
+ }
243
+ clone() {
244
+ return new Tensor(this.type, this.data.slice(), this.dims.slice());
245
+ }
246
+
247
+ slice(...slices) {
248
+ // This allows for slicing with ranges and numbers
249
+ let newTensorDims = [];
250
+ let newOffsets = [];
251
+
252
+ // slices is an array of numbers or arrays of numbers
253
+ // e.g., slices = [0, [1, 3], null, [0, 3]]
254
+ for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {
255
+ let slice = slices[sliceIndex];
256
+
257
+ if (slice === null || slice === undefined) {
258
+ // null or undefined means take the whole dimension
259
+ newOffsets.push([0, this.dims[sliceIndex]]);
260
+ newTensorDims.push(this.dims[sliceIndex]);
261
+
262
+ } else if (typeof slice === 'number') {
263
+ slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);
264
+
265
+ // A number means take a single element
266
+ newOffsets.push([slice, slice + 1]);
267
+
268
+ } else if (Array.isArray(slice) && slice.length === 2) {
269
+ // An array of length 2 means take a range of elements
270
+
271
+ if (slice[0] > slice[1]) {
272
+ throw new Error(`Invalid slice: ${slice}`);
273
+ }
274
+
275
+ let offsets = [
276
+ Math.max(slice[0], 0),
277
+ Math.min(slice[1], this.dims[sliceIndex])
278
+ ];
279
+
280
+ newOffsets.push(offsets);
281
+ newTensorDims.push(offsets[1] - offsets[0]);
282
+
283
+ } else {
284
+ throw new Error(`Invalid slice: ${slice}`);
285
+ }
286
+ }
287
+
288
+ let newDims = newOffsets.map(([start, end]) => end - start);
289
+ let newBufferSize = newDims.reduce((a, b) => a * b);
290
+
291
+ // Allocate memory
292
+ // @ts-ignore
293
+ let data = new this.data.constructor(newBufferSize);
294
+
295
+ // Precompute strides
296
+ const stride = this.stride();
297
+
298
+ for (let i = 0; i < newBufferSize; ++i) {
299
+ let originalIndex = 0;
300
+ for (let j = newDims.length - 1, num = i; j >= 0; --j) {
301
+ const size = newDims[j];
302
+ originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];
303
+ num = Math.floor(num / size);
304
+ }
305
+ data[i] = this.data[originalIndex];
306
+ }
307
+ return new Tensor(this.type, data, newTensorDims);
308
+
309
+ }
310
+
311
+ /**
312
+ * Return a permuted version of this Tensor, according to the provided dimensions.
313
+ * @param {...number} dims Dimensions to permute.
314
+ * @returns {Tensor} The permuted tensor.
315
+ */
316
+ permute(...dims) {
317
+ return permute(this, dims);
318
+ }
319
+
320
+ // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()
321
+ transpose(...dims) {
322
+ return this.permute(...dims);
323
+ }
324
+
325
+ // TODO add .max() and .min() methods
326
+
327
+ /**
328
+ * Returns the sum of each row of the input tensor in the given dimension dim.
329
+ *
330
+ * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
331
+ * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
332
+ * @returns The summed tensor
333
+ */
334
+ sum(dim = null, keepdim = false) {
335
+ return this.norm(1, dim, keepdim);
336
+ }
337
+
338
+ /**
339
+ * Returns the matrix norm or vector norm of a given tensor.
340
+ * @param {number|string} [p='fro'] The order of norm
341
+ * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
342
+ * If dim is None, the norm will be calculated across all dimensions of input.
343
+ * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
344
+ * @returns {Tensor} The norm of the tensor.
345
+ */
346
+ norm(p = 'fro', dim = null, keepdim = false) {
347
+ if (p === 'fro') {
348
+ // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.
349
+ p = 2;
350
+ } else if (typeof p === 'string') {
351
+ throw Error(`Unsupported norm: ${p}`);
352
+ }
353
+
354
+ if (dim === null) {
355
+ // @ts-ignore
356
+ let val = this.data.reduce((a, b) => a + (b ** p), 0) ** (1 / p);
357
+ return new Tensor(this.type, [val], []);
358
+ }
359
+
360
+ // Negative indexing
361
+ dim = safeIndex(dim, this.dims.length);
362
+
363
+ // Calculate the shape of the resulting array after summation
364
+ const resultDims = this.dims.slice(); // Copy the original dimensions
365
+ resultDims[dim] = 1; // Remove the specified axis
366
+
367
+ // Create a new array to store the accumulated values
368
+ // @ts-ignore
369
+ const result = new this.data.constructor(this.data.length / this.dims[dim]);
370
+
371
+ // Iterate over the data array
372
+ for (let i = 0; i < this.data.length; ++i) {
373
+
374
+ // Calculate the index in the resulting array
375
+ let resultIndex = 0;
376
+
377
+ for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
378
+ const size = this.dims[j];
379
+ if (j !== dim) {
380
+ const index = num % size;
381
+ resultIndex += index * resultMultiplier;
382
+ resultMultiplier *= resultDims[j];
383
+ }
384
+ num = Math.floor(num / size);
385
+ }
386
+
387
+ // Accumulate the value at the current index
388
+ result[resultIndex] += (this.data[i]) ** p;
389
+ }
390
+
391
+ if (p !== 1) {
392
+ for (let i = 0; i < result.length; ++i) {
393
+ result[i] = result[i] ** (1 / p);
394
+ }
395
+ }
396
+
397
+ if (!keepdim) {
398
+ resultDims.splice(dim, 1);
399
+ }
400
+
401
+ return new Tensor(this.type, result, resultDims);
402
+ }
403
+
404
+ /**
405
+ * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
406
+ * @param {number} [p=2] The exponent value in the norm formulation
407
+ * @param {number} [dim=1] The dimension to reduce
408
+ * @returns {Tensor} `this` for operation chaining.
409
+ */
410
+ normalize_(p = 2.0, dim = 1) {
411
+ dim = safeIndex(dim, this.dims.length);
412
+
413
+ const norm = this.norm(p, dim, true);
414
+
415
+ for (let i = 0; i < this.data.length; ++i) {
416
+
417
+ // Calculate the index in the resulting array
418
+ let resultIndex = 0;
419
+
420
+ for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
421
+ const size = this.dims[j];
422
+ if (j !== dim) {
423
+ const index = num % size;
424
+ resultIndex += index * resultMultiplier;
425
+ resultMultiplier *= this.dims[j];
426
+ }
427
+ num = Math.floor(num / size);
428
+ }
429
+
430
+ // Divide by normalized value
431
+ this.data[i] /= norm.data[resultIndex];
432
+ }
433
+
434
+ return this;
435
+ }
436
+
437
+ /**
438
+ * Performs `L_p` normalization of inputs over specified dimension.
439
+ * @param {number} [p=2] The exponent value in the norm formulation
440
+ * @param {number} [dim=1] The dimension to reduce
441
+ * @returns {Tensor} The normalized tensor.
442
+ */
443
+ normalize(p = 2.0, dim = 1) {
444
+ return this.clone().normalize_(p, dim);
445
+ }
446
+
447
+ /**
448
+ * Compute and return the stride of this tensor.
449
+ * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
450
+ * @returns {number[]} The stride of this tensor.
451
+ */
452
+ stride() {
453
+ return dimsToStride(this.dims);
454
+ }
455
+
456
+ /**
457
+ * Returns a tensor with all specified dimensions of input of size 1 removed.
458
+ *
459
+ * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
460
+ * If you would like a copy, use `tensor.clone()` before squeezing.
461
+ *
462
+ * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
463
+ * @returns The squeezed tensor
464
+ */
465
+ squeeze(dim = null) {
466
+ return new Tensor(
467
+ this.type,
468
+ this.data,
469
+ calc_squeeze_dims(this.dims, dim)
470
+ )
471
+ }
472
+
473
+ /**
474
+ * In-place version of @see {@link Tensor.squeeze}
475
+ */
476
+ squeeze_(dim = null) {
477
+ this.dims = calc_squeeze_dims(this.dims, dim);
478
+ return this;
479
+ }
480
+
481
+ /**
482
+ * Returns a new tensor with a dimension of size one inserted at the specified position.
483
+ *
484
+ * NOTE: The returned tensor shares the same underlying data with this tensor.
485
+ *
486
+ * @param {number} dim The index at which to insert the singleton dimension
487
+ * @returns The unsqueezed tensor
488
+ */
489
+ unsqueeze(dim = null) {
490
+ return new Tensor(
491
+ this.type,
492
+ this.data,
493
+ calc_unsqueeze_dims(this.dims, dim)
494
+ );
495
+ }
496
+
497
+ /**
498
+ * In-place version of @see {@link Tensor.unsqueeze}
499
+ */
500
+ unsqueeze_(dim = null) {
501
+ this.dims = calc_unsqueeze_dims(this.dims, dim);
502
+ return this;
503
+ }
504
+
505
+ /**
506
+ * In-place version of @see {@link Tensor.flatten}
507
+ */
508
+ flatten_(start_dim = 0, end_dim = -1) {
509
+ // TODO validate inputs
510
+ end_dim = (end_dim + this.dims.length) % this.dims.length;
511
+
512
+ let dimsToKeepBefore = this.dims.slice(0, start_dim);
513
+ let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);
514
+ let dimsToKeepAfter = this.dims.slice(end_dim + 1);
515
+
516
+ this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]
517
+ return this;
518
+ }
519
+
520
+ /**
521
+ * Flattens input by reshaping it into a one-dimensional tensor.
522
+ * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
523
+ * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
524
+ * @param {number} start_dim the first dim to flatten
525
+ * @param {number} end_dim the last dim to flatten
526
+ * @returns The flattened tensor.
527
+ */
528
+ flatten(start_dim = 0, end_dim = -1) {
529
+ return this.clone().flatten_(start_dim, end_dim);
530
+ }
531
+
532
+ /**
533
+ * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
534
+ * @param {...number} dims the desired size
535
+ * @returns {Tensor} The tensor with the same data but different shape
536
+ */
537
+ view(...dims) {
538
+ // TODO: validate dims
539
+ let inferredIndex = -1;
540
+ for (let i = 0; i < dims.length; ++i) {
541
+ if (dims[i] === -1) {
542
+ if (inferredIndex !== -1) {
543
+ throw new Error("Only one dimension can be inferred");
544
+ }
545
+ inferredIndex = i;
546
+ }
547
+ }
548
+
549
+ if (inferredIndex !== -1) {
550
+ // Some dimension must be inferred
551
+ const productOther = dims.reduce((product, curr, index) => {
552
+ return index !== inferredIndex ? product * curr : product
553
+ }, 1);
554
+
555
+ dims[inferredIndex] = this.data.length / productOther;
556
+ }
557
+ return new Tensor(this.type, this.data, dims); // NOTE: uses same underlying storage
558
+ }
559
+
560
+ neg_() {
561
+ for (let i = 0; i < this.data.length; ++i) {
562
+ this.data[i] = -this.data[i];
563
+ }
564
+ return this;
565
+ }
566
+ neg() {
567
+ return this.clone().neg_();
568
+ }
569
+
570
+ /**
571
+ * In-place version of @see {@link Tensor.clamp}
572
+ */
573
+ clamp_(min, max) {
574
+ for (let i = 0; i < this.data.length; ++i) {
575
+ this.data[i] = Math.min(Math.max(this.data[i], min), max);
576
+ }
577
+ return this;
578
+ }
579
+
580
+ /**
581
+ * Clamps all elements in input into the range [ min, max ]
582
+ * @param {number} min lower-bound of the range to be clamped to
583
+ * @param {number} max upper-bound of the range to be clamped to
584
+ * @returns the output tensor.
585
+ */
586
+ clamp(min, max) {
587
+ return this.clone().clamp_(min, max);
588
+ }
589
+
590
+ /**
591
+ * In-place version of @see {@link Tensor.round}
592
+ */
593
+ round_() {
594
+ for (let i = 0; i < this.data.length; ++i) {
595
+ this.data[i] = Math.round(this.data[i]);
596
+ }
597
+ return this;
598
+ }
599
+
600
+ /**
601
+ * Rounds elements of input to the nearest integer.
602
+ * @returns the output tensor.
603
+ */
604
+ round() {
605
+ return this.clone().round_();
606
+ }
607
+
608
+ /**
609
+ * Performs Tensor dtype conversion.
610
+ * @param {DataType} type The desired data type.
611
+ * @returns {Tensor} The converted tensor.
612
+ */
613
+ to(type) {
614
+ // If the self Tensor already has the correct dtype, then self is returned.
615
+ if (this.type === type) return this;
616
+
617
+ // Otherwise, the returned tensor is a copy of self with the desired dtype.
618
+ if (!DataTypeMap.hasOwnProperty(type)) {
619
+ throw new Error(`Unsupported type: ${type}`);
620
+ }
621
+ // @ts-ignore
622
+ return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);
623
+ }
624
+ }
625
+
626
+ /**
627
+ * This creates a nested array of a given type and depth (see examples).
628
+ *
629
+ * @example
630
+ * NestArray<string, 1>; // string[]
631
+ * @example
632
+ * NestArray<number, 2>; // number[][]
633
+ * @example
634
+ * NestArray<string, 3>; // string[][][] etc.
635
+ * @template T
636
+ * @template {number} Depth
637
+ * @template {never[]} [Acc=[]]
638
+ * @typedef {Acc['length'] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>} NestArray
639
+ */
640
+
641
+ /**
642
+ * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.
643
+ *
644
+ * @example
645
+ * reshape([10 ], [1 ]); // Type: number[] Value: [10]
646
+ * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]]
647
+ * reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
648
+ * reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]]
649
+ * @param {T[]|DataArray} data The input array to reshape.
650
+ * @param {DIM} dimensions The target shape/dimensions.
651
+ * @template T
652
+ * @template {[number]|number[]} DIM
653
+ * @returns {NestArray<T, DIM["length"]>} The reshaped array.
654
+ */
655
+ function reshape(data, dimensions) {
656
+
657
+ const totalElements = data.length;
658
+ const dimensionSize = dimensions.reduce((a, b) => a * b);
659
+
660
+ if (totalElements !== dimensionSize) {
661
+ throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);
662
+ }
663
+
664
+ /** @type {any} */
665
+ let reshapedArray = data;
666
+
667
+ for (let i = dimensions.length - 1; i >= 0; i--) {
668
+ reshapedArray = reshapedArray.reduce((acc, val) => {
669
+ let lastArray = acc[acc.length - 1];
670
+
671
+ if (lastArray.length < dimensions[i]) {
672
+ lastArray.push(val);
673
+ } else {
674
+ acc.push([val]);
675
+ }
676
+
677
+ return acc;
678
+ }, [[]]);
679
+ }
680
+
681
+ return reshapedArray[0];
682
+ }
683
+
684
+ /**
685
+ * Permutes a tensor according to the provided axes.
686
+ * @param {any} tensor The input tensor to permute.
687
+ * @param {Array} axes The axes to permute the tensor along.
688
+ * @returns {Tensor} The permuted tensor.
689
+ */
690
+ export function permute(tensor, axes) {
691
+ const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);
692
+ return new Tensor(tensor.type, permutedData, shape);
693
+ }
694
+
695
+
696
+ /**
697
+ * Interpolates an Tensor to the given size.
698
+ * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])
699
+ * @param {number[]} size The output size of the image
700
+ * @param {string} mode The interpolation mode
701
+ * @param {boolean} align_corners Whether to align corners.
702
+ * @returns {Tensor} The interpolated tensor.
703
+ */
704
+ export function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {
705
+
706
+ // Input image dimensions
707
+ const in_channels = input.dims.at(-3) ?? 1;
708
+ const in_height = input.dims.at(-2);
709
+ const in_width = input.dims.at(-1);
710
+
711
+ let output = interpolate_data(
712
+ /** @type {import('./maths.js').TypedArray}*/(input.data),
713
+ [in_channels, in_height, in_width],
714
+ [out_height, out_width],
715
+ mode,
716
+ align_corners
717
+ );
718
+ return new Tensor(input.type, output, [in_channels, out_height, out_width]);
719
+ }
720
+
721
+ /**
722
+ * Perform mean pooling of the last hidden state followed by a normalization step.
723
+ * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]
724
+ * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]
725
+ * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].
726
+ */
727
+ export function mean_pooling(last_hidden_state, attention_mask) {
728
+ // last_hidden_state: [batchSize, seqLength, embedDim]
729
+ // attention_mask: [batchSize, seqLength]
730
+
731
+ let shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];
732
+ // @ts-ignore
733
+ let returnedData = new last_hidden_state.data.constructor(shape[0] * shape[1]);
734
+ let [batchSize, seqLength, embedDim] = last_hidden_state.dims;
735
+
736
+ let outIndex = 0;
737
+ for (let i = 0; i < batchSize; ++i) {
738
+ let offset = i * embedDim * seqLength;
739
+
740
+ for (let k = 0; k < embedDim; ++k) {
741
+ let sum = 0;
742
+ let count = 0;
743
+
744
+ let attnMaskOffset = i * seqLength;
745
+ let offset2 = offset + k;
746
+ // Pool over all words in sequence
747
+ for (let j = 0; j < seqLength; ++j) {
748
+ // index into attention mask
749
+ let attn = Number(attention_mask.data[attnMaskOffset + j]);
750
+
751
+ count += attn;
752
+ sum += last_hidden_state.data[offset2 + j * embedDim] * attn;
753
+ }
754
+
755
+ let avg = sum / count;
756
+ returnedData[outIndex++] = avg;
757
+ }
758
+ }
759
+
760
+ return new Tensor(
761
+ last_hidden_state.type,
762
+ returnedData,
763
+ shape
764
+ )
765
+ }
766
+
767
+ /**
768
+ * Apply Layer Normalization for last certain number of dimensions.
769
+ * @param {Tensor} input The input tensor
770
+ * @param {number[]} normalized_shape input shape from an expected input of size
771
+ * @param {Object} options The options for the layer normalization
772
+ * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.
773
+ * @returns {Tensor} The normalized tensor.
774
+ */
775
+ export function layer_norm(input, normalized_shape, {
776
+ eps = 1e-5,
777
+ } = {}) {
778
+ if (input.dims.length !== 2) {
779
+ throw new Error('`layer_norm` currently only supports 2D input.');
780
+ }
781
+
782
+ const [batchSize, featureDim] = input.dims;
783
+
784
+ if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {
785
+ throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');
786
+ }
787
+
788
+ const [std, mean] = std_mean(input, 1, 0, true);
789
+
790
+ // @ts-ignore
791
+ const returnedData = new input.data.constructor(input.data.length);
792
+
793
+ for (let i = 0; i < batchSize; ++i) {
794
+ const offset = i * featureDim;
795
+ for (let j = 0; j < featureDim; ++j) {
796
+ const offset2 = offset + j;
797
+ returnedData[offset2] = (input.data[offset2] - mean.data[i]) / (std.data[i] + eps);
798
+ }
799
+ }
800
+ return new Tensor(input.type, returnedData, input.dims);
801
+ }
802
+
803
+ /**
804
+ * Helper function to calculate new dimensions when performing a squeeze operation.
805
+ * @param {number[]} dims The dimensions of the tensor.
806
+ * @param {number|number[]|null} dim The dimension(s) to squeeze.
807
+ * @returns The new dimensions.
808
+ * @private
809
+ */
810
+ function calc_squeeze_dims(dims, dim) {
811
+ dims = dims.slice();
812
+ if (dim === null) {
813
+ dims = dims.filter((d) => d !== 1);
814
+ } else if (typeof dim === 'number') {
815
+ if (dims[dim] === 1) {
816
+ dims.splice(dim, 1);
817
+ }
818
+ } else if (Array.isArray(dim)) {
819
+ dims = dims.filter((x, i) => {
820
+ return x !== 1 || !dim.includes(i);
821
+ });
822
+ }
823
+ return dims;
824
+ }
825
+
826
+ /**
827
+ * Helper function to calculate new dimensions when performing an unsqueeze operation.
828
+ * @param {number[]} dims The dimensions of the tensor.
829
+ * @param {number} dim The dimension to unsqueeze.
830
+ * @returns The new dimensions.
831
+ * @private
832
+ */
833
+ function calc_unsqueeze_dims(dims, dim) {
834
+ // Dimension out of range (e.g., "expected to be in range of [-4, 3], but got 4")
835
+ // + 1 since we allow inserting at the end (i.e. dim = -1)
836
+ dim = safeIndex(dim, dims.length + 1);
837
+ dims = dims.slice();
838
+ // Insert 1 into specified dimension
839
+ dims.splice(dim, 0, 1);
840
+ return dims;
841
+ }
842
+
843
+ /**
844
+ * Safely calculate the index for an array of a given size, allowing negative indexing.
845
+ * @param {number} index The index that will be used.
846
+ * @param {number} size The size of the array.
847
+ * @param {number} [dimension=null] The dimension that the index is for (optional).
848
+ * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.
849
+ *
850
+ * @throws {Error} If the index is out of range.
851
+ * @private
852
+ */
853
+ function safeIndex(index, size, dimension = null) {
854
+ if (index < -size || index >= size) {
855
+ throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);
856
+ }
857
+
858
+ if (index < 0) {
859
+ // Negative indexing, ensuring positive index
860
+ index = ((index % size) + size) % size;
861
+ }
862
+ return index;
863
+ }
864
+
865
+ /**
866
+ * Concatenates an array of tensors along a specified dimension.
867
+ * @param {Tensor[]} tensors The array of tensors to concatenate.
868
+ * @param {number} dim The dimension to concatenate along.
869
+ * @returns {Tensor} The concatenated tensor.
870
+ */
871
+ export function cat(tensors, dim = 0) {
872
+ dim = safeIndex(dim, tensors[0].dims.length);
873
+
874
+ // TODO do validation of shapes
875
+
876
+ const resultDims = tensors[0].dims.slice();
877
+ resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);
878
+
879
+ // Create a new array to store the accumulated values
880
+ const resultSize = resultDims.reduce((a, b) => a * b, 1);
881
+ // @ts-ignore
882
+ const result = new tensors[0].data.constructor(resultSize);
883
+
884
+ // Create output tensor of same type as first
885
+ const resultType = tensors[0].type;
886
+
887
+ if (dim === 0) {
888
+ // Handle special case for performance reasons
889
+
890
+ let offset = 0;
891
+ for (let t of tensors) {
892
+ result.set(t.data, offset);
893
+ offset += t.data.length;
894
+ }
895
+
896
+ } else {
897
+
898
+ let currentDim = 0;
899
+
900
+ for (let t = 0; t < tensors.length; ++t) {
901
+ let tensor = tensors[t];
902
+
903
+ // Iterate over the data array
904
+ for (let i = 0; i < tensor.data.length; ++i) {
905
+ // Calculate the index in the resulting array
906
+ let resultIndex = 0;
907
+
908
+ for (let j = tensor.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
909
+ const size = tensor.dims[j];
910
+ let index = num % size;
911
+ if (j === dim) {
912
+ index += currentDim;
913
+ }
914
+ resultIndex += index * resultMultiplier;
915
+ resultMultiplier *= resultDims[j];
916
+ num = Math.floor(num / size);
917
+ }
918
+ // Accumulate the value at the current index
919
+ result[resultIndex] = tensor.data[i];
920
+ }
921
+
922
+ currentDim += tensor.dims[dim];
923
+ }
924
+ }
925
+ return new Tensor(resultType, result, resultDims);
926
+ }
927
+
928
+ /**
929
+ * Stack an array of tensors along a specified dimension.
930
+ * @param {Tensor[]} tensors The array of tensors to stack.
931
+ * @param {number} dim The dimension to stack along.
932
+ * @returns {Tensor} The stacked tensor.
933
+ */
934
+ export function stack(tensors, dim = 0) {
935
+ // TODO do validation of shapes
936
+ // NOTE: stack expects each tensor to be equal size
937
+ return cat(tensors.map(t => t.unsqueeze(dim)), dim);
938
+ }
939
+
940
+
941
+ /**
942
+ * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.
943
+ * @param {Tensor} input the input tenso
944
+ * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.
945
+ * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.
946
+ * @param {boolean} keepdim whether the output tensor has dim retained or not.
947
+ * @returns {Tensor[]} A tuple of (std, mean) tensors.
948
+ */
949
+ export function std_mean(input, dim = null, correction = 1, keepdim = false) {
950
+
951
+ if (dim === null) {
952
+ // None to reduce over all dimensions.
953
+ // @ts-ignore
954
+ const sum = input.data.reduce((a, b) => a + b, 0);
955
+ const mean = sum / input.data.length;
956
+ // @ts-ignore
957
+ const std = Math.sqrt(input.data.reduce((a, b) => a + (b - mean) ** 2, 0) / (input.data.length - correction));
958
+
959
+ const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);
960
+ const stdTensor = new Tensor(input.type, [std], [/* scalar */]);
961
+
962
+ return [stdTensor, meanTensor];
963
+ }
964
+
965
+ // Negative indexing
966
+ dim = safeIndex(dim, input.dims.length);
967
+
968
+ const meanTensor = mean(input, dim, keepdim);
969
+
970
+ // Calculate the shape of the resulting array after summation
971
+ const resultDims = input.dims.slice(); // Copy the original dimensions
972
+ resultDims[dim] = 1; // Remove the specified axis
973
+
974
+ // Create a new array to store the accumulated values
975
+ // @ts-ignore
976
+ const result = new input.data.constructor(input.data.length / input.dims[dim]);
977
+
978
+ // Iterate over the data array
979
+ for (let i = 0; i < input.data.length; ++i) {
980
+
981
+ // Calculate the index in the resulting array
982
+ let resultIndex = 0;
983
+
984
+ for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
985
+ const size = input.dims[j];
986
+ if (j !== dim) {
987
+ const index = num % size;
988
+ resultIndex += index * resultMultiplier;
989
+ resultMultiplier *= resultDims[j];
990
+ }
991
+ num = Math.floor(num / size);
992
+ }
993
+
994
+ // Accumulate the value at the current index
995
+ result[resultIndex] += (input.data[i] - meanTensor.data[resultIndex]) ** 2;
996
+ }
997
+
998
+ for (let i = 0; i < result.length; ++i) {
999
+ result[i] = Math.sqrt(result[i] / (input.dims[dim] - correction));
1000
+ }
1001
+
1002
+ if (!keepdim) {
1003
+ resultDims.splice(dim, 1);
1004
+ }
1005
+
1006
+ const stdTensor = new Tensor(input.type, result, resultDims);
1007
+
1008
+ return [stdTensor, meanTensor];
1009
+ }
1010
+
1011
+
1012
+ /**
1013
+ * Returns the mean value of each row of the input tensor in the given dimension dim.
1014
+ * @param {Tensor} input the input tensor.
1015
+ * @param {number|null} dim the dimension to reduce.
1016
+ * @param {boolean} keepdim whether the output tensor has dim retained or not.
1017
+ * @returns A new tensor with means taken along the specified dimension.
1018
+ */
1019
+ export function mean(input, dim = null, keepdim = false) {
1020
+
1021
+ if (dim === null) {
1022
+ // None to reduce over all dimensions.
1023
+ // @ts-ignore
1024
+ let val = input.data.reduce((a, b) => a + b, 0);
1025
+ return new Tensor(input.type, [val / input.data.length], [/* scalar */]);
1026
+ }
1027
+
1028
+ // Negative indexing
1029
+ dim = safeIndex(dim, input.dims.length);
1030
+
1031
+ // Calculate the shape of the resulting array after summation
1032
+ const resultDims = input.dims.slice(); // Copy the original dimensions
1033
+ resultDims[dim] = 1; // Remove the specified axis
1034
+
1035
+ // Create a new array to store the accumulated values
1036
+ // @ts-ignore
1037
+ const result = new input.data.constructor(input.data.length / input.dims[dim]);
1038
+
1039
+ // Iterate over the data array
1040
+ for (let i = 0; i < input.data.length; ++i) {
1041
+
1042
+ // Calculate the index in the resulting array
1043
+ let resultIndex = 0;
1044
+
1045
+ for (let j = input.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {
1046
+ const size = input.dims[j];
1047
+ if (j !== dim) {
1048
+ const index = num % size;
1049
+ resultIndex += index * resultMultiplier;
1050
+ resultMultiplier *= resultDims[j];
1051
+ }
1052
+ num = Math.floor(num / size);
1053
+ }
1054
+
1055
+ // Accumulate the value at the current index
1056
+ result[resultIndex] += input.data[i];
1057
+ }
1058
+
1059
+ if (input.dims[dim] !== 1) {
1060
+ for (let i = 0; i < result.length; ++i) {
1061
+ result[i] = result[i] / input.dims[dim];
1062
+ }
1063
+ }
1064
+
1065
+ if (!keepdim) {
1066
+ resultDims.splice(dim, 1);
1067
+ }
1068
+
1069
+ return new Tensor(input.type, result, resultDims);
1070
+ }
1071
+
1072
+
1073
+ /**
1074
+ *
1075
+ * Measures similarity between two temporal sequences (e.g., input audio and output tokens
1076
+ * to generate token-level timestamps).
1077
+ * @param {Tensor} matrix
1078
+ * @returns {number[][]}
1079
+ */
1080
+ export function dynamicTimeWarping(matrix) {
1081
+ const [output_length, input_length] = matrix.dims;
1082
+
1083
+ const outputShape = [output_length + 1, input_length + 1];
1084
+
1085
+ const cost = new Tensor(
1086
+ 'float32',
1087
+ new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity),
1088
+ outputShape
1089
+ );
1090
+
1091
+ const trace = new Tensor(
1092
+ 'float32',
1093
+ new Float32Array(outputShape[0] * outputShape[1]).fill(-1),
1094
+ outputShape
1095
+ )
1096
+
1097
+ // same as `cost[0][0] = 0`;
1098
+ cost[0].data[0] = 0;
1099
+
1100
+ for (let j = 1; j < input_length + 1; ++j) {
1101
+ for (let i = 1; i < output_length + 1; ++i) {
1102
+
1103
+ const c0 = cost[i - 1][j - 1].item();
1104
+ const c1 = cost[i - 1][j].item();
1105
+ const c2 = cost[i][j - 1].item();
1106
+
1107
+ let c, t;
1108
+ if (c0 < c1 && c0 < c2) {
1109
+ c = c0;
1110
+ t = 0;
1111
+ } else if (c1 < c0 && c1 < c2) {
1112
+ c = c1;
1113
+ t = 1;
1114
+ } else {
1115
+ c = c2;
1116
+ t = 2;
1117
+ }
1118
+
1119
+ cost[i].data[j] = matrix[i - 1][j - 1].item() + c;
1120
+ trace[i].data[j] = t;
1121
+ }
1122
+ }
1123
+
1124
+ // backtrace
1125
+ let i = output_length;
1126
+ let j = input_length;
1127
+
1128
+ // @ts-ignore
1129
+ trace.data.fill(2, 0, outputShape[1]) // trace[0, :] = 2
1130
+ for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1
1131
+ trace[i].data[0] = 1;
1132
+ }
1133
+
1134
+ let text_indices = [];
1135
+ let time_indices = [];
1136
+
1137
+ while (i > 0 || j > 0) {
1138
+ text_indices.push(i - 1);
1139
+ time_indices.push(j - 1);
1140
+
1141
+ const t = trace[i][j].item();
1142
+ switch (t) {
1143
+ case 0:
1144
+ --i; --j;
1145
+ break;
1146
+ case 1:
1147
+ --i;
1148
+ break;
1149
+ case 2:
1150
+ --j;
1151
+ break;
1152
+ default:
1153
+ throw new Error(
1154
+ `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`
1155
+ )
1156
+ }
1157
+ }
1158
+
1159
+ text_indices.reverse();
1160
+ time_indices.reverse();
1161
+
1162
+ return [text_indices, time_indices];
1163
+
1164
+ }
1165
+
1166
+ function dimsToStride(dims) {
1167
+ const stride = new Array(dims.length);
1168
+ for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {
1169
+ stride[i] = s2;
1170
+ s2 *= dims[i];
1171
+ }
1172
+ return stride;
1173
+ }
1174
+
1175
+ /**
1176
+ * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.
1177
+ * @param {number[]} size A sequence of integers defining the shape of the output tensor.
1178
+ */
1179
+ export function ones(size) {
1180
+ const numElements = size.reduce((a, b) => a * b, 1);
1181
+ return new Tensor(
1182
+ 'int64',
1183
+ new BigInt64Array(numElements).fill(1n),
1184
+ size
1185
+ )
1186
+ }
1187
+
1188
+ /**
1189
+ * Returns a tensor filled with the scalar value 1, with the same size as input.
1190
+ * @param {Tensor} tensor The size of input will determine size of the output tensor.
1191
+ * @returns The ones tensor.
1192
+ */
1193
+ export function ones_like(tensor) {
1194
+ return ones(tensor.dims);
1195
+ }
1196
+
1197
+ /**
1198
+ * Quantizes the embeddings tensor to binary or unsigned binary precision.
1199
+ * @param {Tensor} tensor The tensor to quantize.
1200
+ * @param {'binary'|'ubinary'} precision The precision to use for quantization.
1201
+ * @returns {Tensor} The quantized tensor.
1202
+ */
1203
+ export function quantize_embeddings(tensor, precision) {
1204
+ if (tensor.dims.length !== 2) {
1205
+ throw new Error("The tensor must have 2 dimensions");
1206
+ }
1207
+ if (tensor.dims.at(-1) % 8 !== 0) {
1208
+ throw new Error("The last dimension of the tensor must be a multiple of 8");
1209
+ }
1210
+ if (!['binary', 'ubinary'].includes(precision)) {
1211
+ throw new Error("The precision must be either 'binary' or 'ubinary'");
1212
+ }
1213
+
1214
+ const signed = precision === 'binary';
1215
+ const dtype = signed ? 'int8' : 'uint8';
1216
+
1217
+ // Create a typed array to store the packed bits
1218
+ const cls = signed ? Int8Array : Uint8Array;
1219
+ const inputData = tensor.data;
1220
+ const outputData = new cls(inputData.length / 8);
1221
+
1222
+ // Iterate over each number in the array
1223
+ for (let i = 0; i < inputData.length; ++i) {
1224
+ // Determine if the number is greater than 0
1225
+ const bit = inputData[i] > 0 ? 1 : 0;
1226
+
1227
+ // Calculate the index in the typed array and the position within the byte
1228
+ const arrayIndex = Math.floor(i / 8);
1229
+ const bitPosition = i % 8;
1230
+
1231
+ // Pack the bit into the typed array
1232
+ outputData[arrayIndex] |= bit << (7 - bitPosition);
1233
+ if (signed && bitPosition === 0) {
1234
+ outputData[arrayIndex] -= 128;
1235
+ }
1236
+ };
1237
+
1238
+ return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);
1239
+ }