@huggingface/transformers 3.0.0-alpha.0

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