-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtypes.ts
More file actions
1413 lines (1283 loc) · 37.5 KB
/
Copy pathtypes.ts
File metadata and controls
1413 lines (1283 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {CPUTensor} from './tensor/cpu/tensor';
import {compareShapes, getSize} from './util/shape';
export type PadMode = 'constant' | 'reflect' | 'edge';
/**
* Type that is returned when calling `tensor.getValues()`
*/
export type TensorValues = {
float64: Float64Array;
float32: Float32Array;
float16: Float32Array;
int32: Int32Array;
int16: Int16Array;
int8: Int8Array;
uint32: Uint32Array;
uint16: Uint16Array;
uint8: Uint8Array;
};
export const tensorValuesConstructor = {
float64: Float64Array,
float32: Float32Array,
float16: Float32Array,
int32: Int32Array,
int16: Int16Array,
int8: Int8Array,
uint32: Uint32Array,
uint16: Uint16Array,
uint8: Uint8Array,
};
/**
* Tensor data types available in tensor-js
*/
export type DType =
| 'float64'
| 'float32'
| 'float16'
| 'int32'
| 'int16'
| 'int8'
| 'uint32'
| 'uint16'
| 'uint8';
/**
* Activation functions supported in some operators
*/
export type Activation = 'id' | 'relu' | 'relu6';
/**
* Multi-dimensional array ala numpy.
*
* A tensor is any multidimensional array. The number of
* dimensions is called the rank, and the size of all dimensions the shape.
*
* @example
* ```typescript
* const a = [[1,2,3],[4,5,6]];
* ```
* here a has rank 2 and shape [2,3].
*
* Tensors store values of a particular data type like floats or integers.
* The datatype can be accessed via the dtype property.
*
* Many operations can be done on tensors. For fast execution, three different
* backends exist:
* - CPU: Simple to use and works in any browser, but not particularly fast
* - WebAssembly: Reasonably fast and works in most modern browsers
* - WebGL: Very fast when a GPU is available, but comes with some restrictions
*/
export default abstract class Tensor<DTpe extends DType = 'float32'> {
/**
* Data type of the tensor
*/
public dtype: DTpe;
constructor(dtype: DTpe) {
this.dtype = dtype;
}
/**
* Gets the values of the tensor as a Float32 or Int32 Array
*
* @example
* ```typescript
* const t = new CPUTensor([2,2], [1,2,3,4]);
* t.getValues().then(values => {
* //values will be a Float32Array with values [1,2,3,4]
* });
* ```
*/
abstract getValues(): Promise<TensorValues[DTpe]>;
/**
* Get the shape of the tensor
*/
abstract getShape(): ReadonlyArray<number>;
/**
* Constructs a tensor with the same shape and the given value everywhere
*/
abstract constantLike(value: number): Tensor<DTpe>;
/**
* Constructs a tensor with shape [1] and the given value everywhere
*/
abstract singleConstant(value: number): Tensor<DTpe>;
abstract cast<DTpe2 extends DType>(dtype: DTpe2): Tensor<DTpe2>;
/**
* Deletes the tensor. Has the following effects depending on the backend
* of the tensor:
*
* - CPU: Deletes the values
* - WASM: Releases all memory back to the WASM runtime
* - GPU: Releases the associated framebuffer back to the gpu memory allocator
*/
abstract delete(): void;
/**
* Compares this tensor to another tensor.
*
* @param tensor Tensor to compare to
* @param epsilon Optional maximum difference between the tensors. If not specified the tensors have to be exactly equal
*
* @example
* ```typescript
* const a = new CPUTensor([2,2], [1,2,3,4]);
* const b = new CPUTensor([2,2], [1.1,2.1,2.9,4.05]);
* const c = new CPUTensor([4], [1,2,3,4]);
* a.compare(b, 0.5).then(equal => {
* //equal will be true
* });
*
* a.compare(b).then(equal => {
* //equal will be false
* });
*
* a.compare(c).then(equal => {
* //equal will be false since the shapes of the tensors do not match
* });
* ```
*/
async compare(tensor: Tensor<DTpe>, epsilon?: number): Promise<boolean> {
if (!compareShapes(this.getShape(), tensor.getShape())) {
return false;
}
const arrA = await this.getValues();
const arrB = await tensor.getValues();
if (epsilon !== undefined) {
for (let i = 0; i < arrA.length; i += 1) {
if (Math.abs(arrA[i] - arrB[i]) > epsilon) {
return false;
}
}
} else {
for (let i = 0; i < arrA.length; i += 1) {
if (arrA[i] !== arrB[i]) {
return false;
}
}
}
return true;
}
protected getAxes(axes?: number | number[]) {
let ax: number[];
const sh = this.getShape();
if (axes === undefined) {
ax = [];
for (let i = 0; i < sh.length; i++) {
ax.push(i);
}
} else if (!(axes instanceof Array)) {
ax = [axes];
} else {
ax = axes;
for (let i = 0; i < ax.length; i++) {
if (ax[i] < 0) {
ax[i] += this.getShape().length;
}
}
}
return ax;
}
/**
* Sums over the specified axis/axes.
*
* @param axes One or multiple axes to sum over. If not specified this will sum over all axes
* @param keepDims Wether the summation axes will be kept with size 1
*
* @example
* ```typescript
* const a = new CPUTensor([2,3], [1,2,3,4,5,6]);
*
* a.sum(); //Will be [21]
* a.sum(0); //Will be [5,7,9]
* a.sum(1); //Will [6,15]
* a.sum(0, true); //Will be [[5,7,9]]
* ```
*/
sum(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.sum_impl(ax, keepDims);
}
/**
* Sums over the specified axis/axes with the entries of the tensor squared.
* This is equal to `a.multiply(a).sum(axes, keepDims)` but faster
*
* @param axes One or multiple axes to sum over. If not specified this will sum over all axes
* @param keepDims Wether the summation axes will be kept with size 1
*
*/
sumSquare(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.sumSquare_impl(ax, keepDims);
}
/**
* Takes the product over specified axis/axes.
*
* @param axes One or multiple axes to take the product over. If not specified this will be all axes
* @param keepDims Wether the product axes will be kept with size 1
*
* @example
* ```typescript
* const a = new CPUTensor([2,3], [1,2,3,4,5,6]);
*
* a.product(); //Will be [720]
* a.product(0); //Will be [4,10,18]
* a.product(1); //Will [6,120]
* a.product(0, true); //Will be [[4,10,18]]
* ```
*/
product(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.product_impl(ax, keepDims);
}
/**
* Takes the maximum over specified axis/axes.
*
* @param axes One or multiple axes to take the maximum over. If not specified this will be all axes
* @param keepDims Wether the maximum axes will be kept with size 1
*
* @example
* ```typescript
* const a = new CPUTensor([2,3], [1,2,3,4,5,6]);
*
* a.max(); //Will be [6]
* a.max(0); //Will be [4,5,6]
* a.max(1); //Will [3,6]
* a.max(0, true); //Will be [[4,5,6]]
* ```
*/
max(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.max_impl(ax, keepDims);
}
/**
* Takes the minimum over specified axis/axes.
*
* @param axes One or multiple axes to take the minimum over. If not specified this will be all axes
* @param keepDims Wether the minimum axes will be kept with size 1
*
* @example
* ```typescript
* const a = new CPUTensor([2,3], [1,2,3,4,5,6]);
*
* a.min(); //Will be [1]
* a.min(0); //Will be [1,2,3]
* a.min(1); //Will [1,4]
* a.min(0, true); //Will be [[1,2,3]]
* ```
*/
min(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.min_impl(ax, keepDims);
}
/**
* Takes the mean over the specified axis/axes.
* This is equal to `a.sum(axes, keepDims).divide(sumSize)` (where sumSize is the number
* of entries in the summation axes) but faster.
*
* @param axes One or multiple axes to take the mean over. If not specified this will take the mean over all axes
* @param keepDims Wether the mean axes will be kept with size 1
*
*/
reduceMean(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.reduceMean_impl(ax, keepDims);
}
/**
* Takes the log of the sum over the specified axis
* This is equal to `a.sum(axes, keepDims).log()` (where sumSize is the number
* of entries in the summation axes) but faster.
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*
* @param axes One or multiple axes to take the mean over. If not specified this will take the mean over all axes
* @param keepDims Wether the mean axes will be kept with size 1
*
*/
reduceLogSum(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.reduceLogSum_impl(ax.sort(), keepDims);
}
/**
* Takes the log of the sum over the exp of the specified axis
* This is equal to `a.sum(axes, keepDims).log()` (where sumSize is the number
* of entries in the summation axes) but faster.
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*
* @param axes One or multiple axes to take the mean over. If not specified this will take the mean over all axes
* @param keepDims Wether the mean axes will be kept with size 1
*
*/
reduceLogSumExp(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.reduceLogSumExp_impl(ax, keepDims);
}
/**
* Takes the mean over the specified axis/axes with the entries of the tensor squared.
* This is equal to `a.multiply(a).sum(axes, keepDims).divide(sumSize)` (where sumSize is the number
* of entries in the summation axes) but faster.
*
* @param axes One or multiple axes to take the mean over. If not specified this will take the mean over all axes
* @param keepDims Wether the mean axes will be kept with size 1
*
*/
reduceMeanSquare(axes?: number | number[], keepDims?: boolean): Tensor<DTpe> {
const ax = this.getAxes(axes);
keepDims = keepDims || false;
return this.reduceMeanSquare_impl(ax, keepDims);
}
/**
* Convolves this tensor with the specified kernel.
*
* This tensor should have shape [N,C,D1,D2,...] where D1,D2,... are the spatial dimensions.
*
* Behaves according to https://github.com/onnx/onnx/blob/master/docs/Operators.md#Conv
*
* @param kernel Convolution kernel with shape [M,C/G,K1,K2] where G is the group parameter
* @param bias Optional bias to add to the result with shape [M]
* @param dilations Per axis dilations for the spatial dimension. Defaults to 1 for all axes
* @param group Group parameter
* @param pads Padding to add to the input for each spatial dimension. Defaults to 0 for all axes
* @param strides Convolution stride for each spatial dimension. Defaults to 1 for all axes
* @param activation Optional activation to apply. Defaults to the identity (so no activation)
*/
conv(
kernel: Tensor<DTpe>,
bias?: Tensor<DTpe>,
dilations?: number[],
group?: number,
pads?: number[],
strides?: number[],
activation?: Activation
): Tensor<DTpe> {
const sh = this.getShape();
const dataRank = sh.length - 2;
dilations = dilations || new Array(dataRank).fill(1);
group = group || 1;
pads = pads || new Array(dataRank * 2).fill(0);
strides = strides || new Array(dataRank).fill(1);
if (activation === undefined) {
activation = 'id';
}
return this.conv_impl(
kernel,
dilations,
group,
pads,
strides,
activation,
bias
);
}
/**
* Calculates the transpose convolution
*
* This tensor should have shape [N,C,D1,D2,...] where D1,D2,... are the spatial dimensions.
*
* @param kernel Convolution kernel with shape [M,C/G,K1,K2] where G is the group parameter
* @param dilations Per axis dilations for the spatial dimension. Defaults to 1 for all axes
* @param group Group parameter
* @param pads Padding to add to the input for each spatial dimension. Defaults to 0 for all axes
* @param strides Convolution stride for each spatial dimension. Defaults to 1 for all axes
*/
convTranspose(
kernel: Tensor<DTpe>,
dilations?: number[],
group?: number,
pads?: number[],
strides?: number[]
): Tensor<DTpe> {
const sh = this.getShape();
const dataRank = sh.length - 2;
dilations = dilations || new Array(dataRank).fill(1);
group = group || 1;
pads = pads || new Array(dataRank * 2).fill(0);
strides = strides || new Array(dataRank).fill(1);
return this.convTranspose_impl(kernel, dilations, group, pads, strides);
}
/**
* Pads the input according to the padding mode. The input has shape [D1,D2,..]
*
* @example
* ```typescript
* const a = new CPUTensor([2,2],[1,2,3,4]);
* a.pad([1,1,1,1],'constant',5);
* //Result will be:
* // [[5,5,5,5],
* // [5,1,2,5],
* // [5,3,4,5],
* // [5,5,5,5]]
* a.pad([1,1,1,1],'edge');
* //Result will be:
* // [[1,1,2,2],
* // [1,1,2,2],
* // [3,3,4,4],
* // [3,3,4,4]]
*
* a.pad([2,2,2,2],'reflect');
* //Result will be:
* // [[4,3,3,4,4,3],
* // [2,1,1,2,2,1],
* // [2,1,1,2,2,1],
* // [4,3,3,4,4,3],
* // [4,3,3,4,4,3],
* // [2,1,1,2,2,1]]
* ```
*
* @param pads Padding size of each input. Specified as [startpad_D1,startpad_D2,...,startpad_DN,endpad_D1,endpad_D2,...]
* @param mode Padding mode. One of 'constant', 'edge', 'reflect'. Defaults to 'constant'
* @param value Value for constant padding. Defaults to 0.0
*/
pad(pads: number[], mode?: PadMode, value?: number): Tensor<DTpe> {
if (mode === undefined) {
mode = 'constant';
}
if (value === undefined) {
value = 0;
}
return this.pad_impl(pads, mode, value);
}
/**
* Performs average pooling over the spatial dimensions of this tensor with
* shape [N,C,D1,D2,..]
* @param kernelShape Size of the average pooling dimension
* @param pads Padding of the input specified as [startpad_D1,startpad_D2,...,startpad_DN,endpad_D1,endpad_D2,...]
* Padding value will be 0. Defaults to 0 for all axes
* @param strides Stride size of the average pooling kernel. Defaults to 1 for all axes
* @param includePad Wether padded values should be included in the average (or masked out). Defaults to false
*/
averagePool(
kernelShape: number[],
pads?: number[],
strides?: number[],
includePad?: boolean
): Tensor<DTpe> {
const sh = this.getShape();
const dataRank = sh.length - 2;
pads = pads || new Array(dataRank * 2).fill(0);
strides = strides || new Array(dataRank).fill(1);
includePad = includePad || false;
return this.averagePool_impl(kernelShape, pads, strides, includePad);
}
/**
* Reshape the tensor to the specified shape
*
* At most one value in the shape can be -1, which will be replaced by the inferred size for this dimension.
*
* @param shape New shape of the tensor
* @param copy Wether the tensor values should be copied. Only has an effect on GPU tensors
*/
reshape(shape: readonly number[], copy?: boolean): Tensor<DTpe> {
let shSize = 1;
let negIndex = -1;
for (let i = 0; i < shape.length; i++) {
if (shape[i] === -1) {
negIndex = i;
} else {
shSize *= shape[i];
}
}
if (copy === undefined) {
copy = true;
}
if (negIndex !== -1) {
const currShape = this.getShape();
const currSize = getSize(currShape);
const _shape = [...shape];
_shape[negIndex] = currSize / shSize;
return this.reshape_impl(_shape, copy);
}
return this.reshape_impl(shape, copy);
}
protected abstract reshape_impl(
shape: readonly number[],
copy: boolean
): Tensor<DTpe>;
/**
* Takes the exponential of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract exp(): Tensor<DTpe>;
/**
* Takes the natural logarithm of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract log(): Tensor<DTpe>;
/**
* Takes the square root of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract sqrt(): Tensor<DTpe>;
/**
* Takes the absolute of each value of the tensor
*
* Note that this can only be called on tensors with a signed data type (float*, int32, int16, int8)
*/
abstract abs(): Tensor<DTpe>;
/**
* Takes the sinus of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract sin(): Tensor<DTpe>;
/**
* Takes the cosine of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract cos(): Tensor<DTpe>;
/**
* Takes the tangens of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract tan(): Tensor<DTpe>;
/**
* Takes the arcus sinus of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract asin(): Tensor<DTpe>;
/**
* Takes the arcus cosine of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract acos(): Tensor<DTpe>;
/**
* Takes the arcus tangens of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract atan(): Tensor<DTpe>;
/**
* Takes the hyperbolic sinus of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract sinh(): Tensor<DTpe>;
/**
* Takes the hyperbolic cosine of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract cosh(): Tensor<DTpe>;
/**
* Takes the hyperbolic tangens of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract tanh(): Tensor<DTpe>;
/**
* Takes the inverse hyperbolic sinus of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract asinh(): Tensor<DTpe>;
/**
* Takes the inverse hyperbolic cosine of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract acosh(): Tensor<DTpe>;
/**
* Takes the inverse hyperbolic tangens of each value of the tensor
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract atanh(): Tensor<DTpe>;
/**
* Negates all entries of the tensor
*
* Note that this can only be called on tensors with a signed data type (float*, int32, int16, int8)
*/
abstract negate(): Tensor<DTpe>;
/**
* Takes element wise power and multiplies with the given factor
*/
abstract powerScalar(power: number, factor: number): Tensor<DTpe>;
/**
* Computes the element wise sigmoid of all values
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract sigmoid(): Tensor<DTpe>;
/**
* Computes the element wise hard sigmoid of all values given
* by `y = max(0, min(1, alpha * x + beta))`
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
abstract hardSigmoid(alpha: number, beta: number): Tensor<DTpe>;
/**
* Computes the value-wise sign which is:
* - (-1) if x < 0
* - 0 if x == 0
* - 1 otherwise
*
* Note that this can only be called on tensors with a signed data type (float*, int32, int16, int8)
*/
abstract sign(): Tensor<DTpe>;
alignShapes(
shape1: readonly number[],
shape2: readonly number[]
): (readonly number[])[] {
if (compareShapes(shape1, shape2)) {
return [shape1, shape2, shape1];
}
if (shape1.length < shape2.length) {
shape1 = [...shape1];
const prepend = shape2.length - shape1.length;
(shape1 as number[]).unshift(...new Array(prepend).fill(1));
} else if (shape2.length < shape1.length) {
shape2 = [...shape2];
const prepend = shape1.length - shape2.length;
(shape2 as number[]).unshift(...new Array(prepend).fill(1));
}
const resultShape = new Array(shape1.length).fill(1);
for (let i = 0; i < shape1.length; i++) {
resultShape[i] = Math.max(shape1[i], shape2[i]);
}
return [shape1, shape2, resultShape];
}
/**
* Align the shapes of this tensor and the given tensor according to
* the broadcasting rules:
* https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md
*
* @param tensor Tensor of which the shapes should be aligned
*/
alignTensor(tensor: Tensor<DTpe>) {
let thisShape = this.getShape();
let thatShape = tensor.getShape();
if (compareShapes(thisShape, thatShape)) {
return [this, tensor, thisShape];
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
let th: Tensor<DTpe> = this;
if (thisShape.length < thatShape.length) {
thisShape = [...thisShape];
const prepend = thatShape.length - thisShape.length;
(thisShape as number[]).unshift(...new Array(prepend).fill(1));
th = this.reshape(thisShape, false);
} else if (thatShape.length < thisShape.length) {
thatShape = [...thatShape];
const prepend = thisShape.length - thatShape.length;
(thatShape as number[]).unshift(...new Array(prepend).fill(1));
tensor = tensor.reshape(thatShape, false);
}
const resultShape = new Array(thisShape.length).fill(1);
for (let i = 0; i < thisShape.length; i++) {
resultShape[i] = Math.max(thisShape[i], thatShape[i]);
}
return [th, tensor, resultShape];
}
/**
* Adds two tensors. Supports broadcasting
*
* @example
* ```typescript
* const a = new CPUTensor([2,2],[1,2,3,4]);
* const b = new CPUTensor([2,2],[5,6,7,8]);
* const c = new CPUTensor([1],[2]);
*
* a.add(b);
* //Will be
* // [[6,8],
* // [10,12]]
*
* a.add(c);
* //Will be
* // [[3,4],
* // [5,6]]
* ```
*/
add(tensor: Tensor<DTpe>, alpha?: number, beta?: number) {
if (alpha === undefined) {
alpha = 1;
}
if (beta === undefined) {
beta = 1;
}
const [th, tens, resultShape] = this.alignTensor(tensor);
return this.add_impl(
th as Tensor<DTpe>,
tens as Tensor<DTpe>,
resultShape as number[],
alpha,
beta
);
}
/**
* Subtracts two tensors. Supports broadcasting
*
* @example
* ```typescript
* const a = new CPUTensor([2,2],[5,6,7,8]);
* const b = new CPUTensor([2,2],[1,2,3,4]);
* const c = new CPUTensor([1],[2]);
*
* a.subtract(b);
* //Will be
* // [[4,4],
* // [4,4]]
*
* a.subtract(c);
* //Will be
* // [[3,4],
* // [5,6]]
* ```
*/
subtract(tensor: Tensor<DTpe>, alpha?: number, beta?: number) {
if (alpha === undefined) {
alpha = 1;
}
if (beta === undefined) {
beta = 1;
}
const [th, tens, resultShape] = this.alignTensor(tensor);
return this.subtract_impl(
th as Tensor<DTpe>,
tens as Tensor<DTpe>,
resultShape as number[],
alpha,
beta
);
}
/**
* Multiplies two tensors. Supports broadcasting
*
* @example
* ```typescript
* const a = new CPUTensor([2,2],[1,2,3,4]);
* const b = new CPUTensor([2,2],[5,6,7,8]);
* const c = new CPUTensor([1],[2]);
*
* a.multiply(b);
* //Will be
* // [[5,12],
* // [21,32]]
*
* a.multiply(c);
* //Will be
* // [[2,4]
* [6,8]]
* ```
*/
multiply(tensor: Tensor<DTpe>, alpha?: number) {
if (alpha === undefined) {
alpha = 1;
}
const [th, tens, resultShape] = this.alignTensor(tensor);
return this.multiply_impl(
th as Tensor<DTpe>,
tens as Tensor<DTpe>,
resultShape as number[],
alpha
);
}
multiplyScalar(value: number) {
return this.addMultiplyScalar(value, 0);
}
addScalar(value: number) {
return this.addMultiplyScalar(1, value);
}
abstract addMultiplyScalar(factor: number, add: number): Tensor<DTpe>;
/**
* Divides two tensors. Supports broadcasting
*
* @example
* ```typescript
* const a = new CPUTensor([2,2],[5,6,7,8]);
* const b = new CPUTensor([2,2],[1,2,3,4]);
* const c = new CPUTensor([1],[2]);
*
* a.divide(b);
* //Will be
* // [[5,3],
* // [2.333,2]]
*
* a.divide(c);
* //Will be
* // [[2.5,3],
* // [3.5,4]]
* ```
*/
divide(tensor: Tensor<DTpe>, alpha?: number) {
if (alpha === undefined) {
alpha = 1;
}
const [th, tens, resultShape] = this.alignTensor(tensor);
return this.divide_impl(
th as Tensor<DTpe>,
tens as Tensor<DTpe>,
resultShape as number[],
alpha
);
}
/**
* Takes the positionwise power. Supports broadcasting
*
* @example
* ```typescript
* const a = new CPUTensor([2,2],[5,6,7,8]);
* const b = new CPUTensor([2,2],[2,3,2,3]);
* const c = new CPUTensor([1],[2]);
*
* a.power(b);
* //Will be
* // [[25,216],
* // [49,512]]
*
* a.power(c);
* //Will be
* // [[25,36],
* // [49,64]]
* ```
*/
power(tensor: Tensor<DTpe>) {
const [th, tens, resultShape] = this.alignTensor(tensor);
return this.power_impl(
th as Tensor<DTpe>,
tens as Tensor<DTpe>,
resultShape as number[]
);
}
/**
* Transposes the tensor according to the given permutation
*
* @example
* ```typescript
* const a = new CPUTensor([2,2],[5,6,7,8]);
*
* a.transpose();
* //Will be
* // [[5,7],
* // [6,8]]
* ```
* @param permutation Permutation for the axes. Default is the reverse axis order
*/
transpose(permutation?: number[]): Tensor<DTpe> {
if (permutation === undefined) {
const shape = this.getShape();
const rank = shape.length;
permutation = [];
for (let i = 0; i < rank; i++) {
permutation.push(rank - i - 1);
}
}
return this.transpose_impl(permutation);
}
/**
* Takes the softmax along the given axis
* https://en.wikipedia.org/wiki/Softmax_function
*
* Note that this can only be called on tensors with a float data type (float64, float32, float16)
*/
softmax(axis: number) {
const max = this.max(axis, true);
const normalized = this.subtract(max);
const exp = normalized.exp();
const sum = exp.sum(axis, true);
const result = exp.divide(sum);
max.delete();
normalized.delete();
exp.delete();
sum.delete();
return result;
}
/**
* Calculates the general matrix product.
* https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms#Level_3
*
* A and B can have batch dimensions. Their last two dimensions should
* correspond to the dimensions for the matrix product
*
* @param b Second matrix for the matrix product
* @param aTranspose If the last two dimensions of a are transposed. Defaults to false
* @param bTranspose If the last two dimensions of a are transposed. Defaults to false
* @param alpha Alpha parameter. Defaults to 1.0
* @param c Optional tensor to add to the result.
* @param beta Beta parameter, only used if c is specified. Defaults to 1.0
*/
gemm(
b: Tensor<DTpe>,
aTranspose?: boolean,