@ohos-ports/sillytavern-transformers 2.17.2-beta.1

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