forked from microsoft/onnxruntime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.ts
1255 lines (1134 loc) · 44.2 KB
/
util.ts
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {flatbuffers} from 'flatbuffers';
import Long from 'long';
import {onnx} from 'onnx-proto';
import {Graph} from './graph';
import {onnxruntime} from './ort-schema/ort-generated';
import {Tensor} from './tensor';
// check the inputs shape before running an OP.
// return true when the inputs pass the check
// return false when the inputs do not fit the requirement
// throw exception when fatal error or not implemented
export function checkInputsShape(inputs: Tensor[], ...expectedDimensions: number[]): boolean {
if (!inputs || inputs.length !== expectedDimensions.length) {
return false;
}
for (let i = 0; i < inputs.length; i++) {
if (!inputs[i].dims || inputs[i].dims.length !== expectedDimensions[i]) {
return false;
}
}
return true;
}
// Evaluates the given expression and asserts error message if condition is unmet.
export function assert(expr: boolean, msg: () => string) {
if (!expr) {
throw new Error(typeof msg === 'string' ? msg : msg());
}
}
export class ArrayUtil {
/**
* Verifies if 2 input arrays contain the same elements.
* @param n1 Array 1
* @param n2 Array 2
* @returns Whether these 2 are equal
*/
static arraysEqual(
n1: readonly number[]|Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Uint8ClampedArray|
Float32Array|Float64Array,
n2: readonly number[]|Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Uint8ClampedArray|
Float32Array|Float64Array) {
if (n1.length !== n2.length) {
return false;
}
for (let i = 0; i < n1.length; i++) {
if (n1[i] !== n2[i]) {
return false;
}
}
return true;
}
}
export class MatMulUtil {
/**
* Fix the input shapes for MatMul operation if they need fixing
* @param dimsA The shape of tensor A. Should be an array of positive integers
* @param dimsB The shape of tensor B. Should be an array of positive integers
* @returns A tuple containing the preprocessed input shapes as required by ONNX specifications
*/
static preprocessInputShapes(dimsA: readonly number[], dimsB: readonly number[]):
[readonly number[], readonly number[]] {
// If the first argument is 1-D, it is promoted to a matrix by prepending
// a 1 to its dimensions. After matrix multiplication the prepended 1 is
// removed.
const a = (dimsA.length === 1) ? [1, dimsA[0]] : dimsA;
// If the second argument is 1-D, it is promoted to a matrix by appending
// a 1 to its dimensions. After matrix multiplication the appended 1 is
// removed.
const b = (dimsB.length === 1) ? [dimsB[0], 1] : dimsB;
return [a, b];
}
/**
* Fix the output shape computed for MatMul operation if it needs fixing
* @param outputShape The computed outputShape. Should be an array (atleast of length 2) of positive integers.
* This will be mutated.
* @param aRank The rank of tensor A.
* @param bRank The rank of tensor B.
*/
static postprocessOutputShape(outputShape: number[], aRank: number, bRank: number) {
// Remove prepended dimension if first input is 1d
if (aRank === 1) {
// outputShape = outputShape.slice(0, outputShape.length - 2).concat(outputShape.slice(outputShape.length - 1));
outputShape.splice(outputShape.length - 2, 1);
}
// Remove appended dimension if second input is 1d
if (bRank === 1) {
outputShape.pop();
}
}
/**
* Calculate the expected shape when matrix multiplication
* @param a The shape of tensor A. Should be a tuple of 2 positive integers
* @param b The shape of tensor B. Should be a tuple of 2 positive integers
* @returns The expected shape of the result, or undefined if N/A
*/
static calcMatMulShape(a: [number, number], b: [number, number]): [number, number]|undefined {
return (a[1] !== b[0]) ? undefined : [a[0], b[1]];
}
}
export class BroadcastUtil {
/**
* Calculate the expected shape when broadcasting 2 tensors
* @param a The shape of tensor A. Should be an array of positive integers
* @param b The shape of tensor B. Should be an array of positive integers
* @param isMatMul Whether the operation is MatMul
* @returns The expected shape of the result, or undefined if N/A
*/
static calcShape(adims: readonly number[], bdims: readonly number[], isMatMul = false): readonly number[]|undefined {
const arank = adims.length;
const brank = bdims.length;
if (arank === 0) {
return bdims;
}
if (brank === 0) {
return adims;
}
const crank = Math.max(adims.length, bdims.length);
const cdims = new Array<number>(crank);
// calculate the last 2 dimension if it is MatMul
if (isMatMul) {
if (arank < 2 || brank < 2) {
return undefined;
}
const cShapeMatMul =
MatMulUtil.calcMatMulShape([adims[arank - 2], adims[arank - 1]], [bdims[brank - 2], bdims[brank - 1]]);
if (cShapeMatMul === undefined) {
return undefined;
}
[cdims[crank - 2], cdims[crank - 1]] = cShapeMatMul;
}
for (let i = isMatMul ? 3 : 1; i <= crank; i++) {
const aLen = arank - i < 0 ? 1 : adims[arank - i];
const bLen = brank - i < 0 ? 1 : bdims[brank - i];
if (aLen !== bLen && aLen > 1 && bLen > 1) {
return undefined;
}
cdims[crank - i] = Math.max(aLen, bLen);
}
return cdims;
}
/**
* Given the indices of a broadcasted tensor, calculate the original indices
* @param broadcastedIndices The given indices of the broadcasted tensor.
* @param originalShape The original shape of the tensor before broadcas
* @returns The calculated indices that maps to the original tensor.
*/
static index(broadcastedIndices: readonly number[], originalShape: readonly number[]): number[] {
// NOTE 1: we assume the parameter broadcastedIndices is valid. ie. it should have the same
// length as the broadcasted shape, and for each dimension the index should
// not be out of range.
const originalIndices = new Array(originalShape.length);
BroadcastUtil.fillIndex(broadcastedIndices, originalShape, originalIndices);
return originalIndices;
}
/**
* Given the indices of a broadcasted tensor, calculate the original indices
* @param broadcastedIndices The given indices of the broadcasted tensor.
* @param originalShape The original shape of the tensor before broadcast
* @param originalIndices The mapping of broadcastedIndices to the originalIndices (output parameter - will be
* mutated).
*/
static fillIndex(broadcastedIndices: readonly number[], originalShape: readonly number[], originalIndices: number[]) {
// NOTE 1: we assume the parameter broadcastedIndices is valid. ie. it should have the same length as the
// broadcasted shape, and for each dimension the index should not be out of range.
// NOTE 2: we assume the parameter originalIndices has the same length as the originalShape
const dimOffset = broadcastedIndices.length - originalShape.length;
for (let i = 0; i < originalShape.length; i++) {
originalIndices[i] = broadcastedIndices[dimOffset + i] % originalShape[i];
}
}
/**
* Perform the broadcasting operation on the specific operator
* @param a The input tensor A
* @param b The input tensor B
* @param op The operator lambda function
* @param inplace Whether to write the result back to A.
* @returns The result tensor, or undefined if input not broadcastable.
*/
static calc(
a: Tensor, b: Tensor, op: (a: string|number, b: string|number) => (string | number), inplace: boolean,
resultType?: Tensor.DataType): Tensor|undefined {
const outputShape = BroadcastUtil.calcShape(a.dims, b.dims);
if (outputShape) {
if (inplace && !ShapeUtil.areEqual(outputShape, a.dims)) {
// B is not broadcastable to A, failed to calculate inplace.
return undefined;
}
const size = ShapeUtil.size(outputShape);
const c = inplace ? a : new Tensor(outputShape, resultType || a.type);
// both inputs are scalars
if (outputShape.length === 0) {
c.set([], op(a.get([]), b.get([])));
}
// atleast one input is a non-scalar
else {
const outputIndices = new Array<number>(outputShape.length);
const originalIndicesA = new Array(a.dims.length);
const originalIndicesB = new Array(b.dims.length);
let valA: string|number = 0;
let valB: string|number = 0;
let isAScalar = false;
let isBScalar = false;
if (a.dims.length === 0) {
valA = a.get([]);
isAScalar = true;
}
if (b.dims.length === 0) {
valB = b.get([]);
isBScalar = true;
}
let rest: number;
for (let i = 0; i < size; i++) {
// traversal indices
rest = i;
for (let j = outputShape.length - 1; j >= 0; j--) {
outputIndices[j] = rest % outputShape[j];
rest = Math.floor(rest / outputShape[j]);
}
if (!isAScalar) {
// map outputIndices (which is actually broadcasted) to the originalIndices
BroadcastUtil.fillIndex(outputIndices, a.dims, originalIndicesA);
valA = a.get(originalIndicesA);
}
if (!isBScalar) {
BroadcastUtil.fillIndex(outputIndices, b.dims, originalIndicesB);
valB = b.get(originalIndicesB);
}
c.set(outputIndices, op(valA, valB));
}
}
return c;
}
return undefined;
}
/**
* Determine if a shape is unidirectional broadcastable to another shape
* @param shape The input shape
* @param finalShape The desired shape after broadcasting
*/
static isValidBroadcast(shape: readonly number[], finalShape: readonly number[]): boolean {
// align shape to the right
const inputRank = shape.length;
const finalRank = finalShape.length;
if (inputRank > finalRank) {
return false;
}
for (let i = 1; i <= inputRank; i++) {
if (shape[inputRank - i] !== 1 && shape[inputRank - i] !== finalShape[finalRank - i]) {
return false;
}
}
return true;
}
/**
* Determine the broadcasted dims in input shape based on the given output shape.
* Note that this function only returns the broadcasted dims.
* @param inputShape The input shape
* @param outputShape The output shape
* @returns The broadcasted dims in input shape.
*/
static getBroadcastDims(inputShape: readonly number[], outputShape: readonly number[]): number[] {
const inRank = inputShape.length;
const dims: number[] = [];
for (let i = 0; i < inRank; i++) {
const dim = inRank - 1 - i;
const a = inputShape[dim] || 1;
const b = outputShape[outputShape.length - 1 - i] || 1;
if (b > 1 && a === 1) {
dims.unshift(dim);
}
}
return dims;
}
}
// copy array helper
// mimics memcpy as much as possible
export function arrayCopyHelper(
target: number[]|Tensor.NumberType, source: number[]|Tensor.NumberType, targetIndex: number, sourceIndex: number,
blockSize: number) {
if (sourceIndex < 0 || sourceIndex >= source.length) {
throw new Error('sourceIndex out of bounds');
}
if (targetIndex < 0 || targetIndex >= target.length) {
throw new Error('targetIndex out of bounds');
}
if (sourceIndex + blockSize > source.length) {
throw new Error('source indices to be copied are outside bounds');
}
if (targetIndex + blockSize > target.length) {
throw new Error('target array is too small to hold result');
}
for (let offset = 0; offset < blockSize; offset++) {
target[targetIndex + offset] = source[sourceIndex + offset];
}
}
export class GemmUtil {
// will make sure input shapes are compatible for this op
// and return back the shape of the output in the form of a tuple
// will throw exception if the input shapes are not compatible
static getShapeOfGemmResult(
leftShape: readonly number[], transLeft: boolean, rightShape: readonly number[], transRight: boolean,
biasShape?: readonly number[]): readonly number[] {
if (leftShape.length !== 2 || rightShape.length !== 2) {
throw new Error('shape need to be of size 2');
}
let M: number;
let K: number;
let N: number;
if (transLeft) {
M = leftShape[1];
K = leftShape[0];
} else {
M = leftShape[0];
K = leftShape[1];
}
let kDim = -1;
if (transRight) {
N = rightShape[0];
kDim = 1;
} else {
N = rightShape[1];
kDim = 0;
}
if (rightShape[kDim] !== K) {
throw new Error('dimension mismatch');
}
if (M <= 0 || N <= 0 || K <= 0) {
throw new Error('invalid shape specified');
}
if (biasShape && !BroadcastUtil.isValidBroadcast(biasShape, [M, N])) {
throw new Error('gemm: invalid bias shape for broadcast');
}
return [M, N, K];
}
}
export class ProtoUtil {
static tensorDataTypeFromProto(typeProto: onnx.TensorProto.DataType|
onnxruntime.experimental.fbs.TensorDataType): Tensor.DataType {
switch (typeProto) {
case onnx.TensorProto.DataType.INT8:
return 'int8';
case onnx.TensorProto.DataType.UINT8:
return 'uint8';
case onnx.TensorProto.DataType.BOOL:
return 'bool';
case onnx.TensorProto.DataType.INT16:
return 'int16';
case onnx.TensorProto.DataType.UINT16:
return 'uint16';
case onnx.TensorProto.DataType.INT32:
return 'int32';
case onnx.TensorProto.DataType.UINT32:
return 'uint32';
case onnx.TensorProto.DataType.FLOAT:
return 'float32';
case onnx.TensorProto.DataType.DOUBLE:
return 'float64';
case onnx.TensorProto.DataType.STRING:
return 'string';
// For INT64/UINT64, reduce their value to 32-bits.
// Should throw exception when overflow
case onnx.TensorProto.DataType.INT64:
return 'int32';
case onnx.TensorProto.DataType.UINT64:
return 'uint32';
default:
throw new Error(`unsupported data type: ${onnx.TensorProto.DataType[typeProto]}`);
}
}
static tensorDataTypeStringToEnum(type: string): onnx.TensorProto.DataType {
switch (type) {
case 'int8':
return onnx.TensorProto.DataType.INT8;
case 'uint8':
return onnx.TensorProto.DataType.UINT8;
case 'bool':
return onnx.TensorProto.DataType.BOOL;
case 'int16':
return onnx.TensorProto.DataType.INT16;
case 'uint16':
return onnx.TensorProto.DataType.UINT16;
case 'int32':
return onnx.TensorProto.DataType.INT32;
case 'uint32':
return onnx.TensorProto.DataType.UINT32;
case 'float32':
return onnx.TensorProto.DataType.FLOAT;
case 'float64':
return onnx.TensorProto.DataType.DOUBLE;
case 'string':
return onnx.TensorProto.DataType.STRING;
case 'int64':
return onnx.TensorProto.DataType.INT64;
case 'uint64':
return onnx.TensorProto.DataType.UINT64;
default:
throw new Error(`unsupported data type: ${type}`);
}
}
static tensorDimsFromProto(dims: Array<number|Long>): number[] {
// get rid of Long type for dims
return dims.map(d => Long.isLong(d) ? d.toNumber() : d);
}
static tensorValueTypeFromProto(valueType: onnx.TypeProto.ITensor): Graph.ValueType {
return {
tensorType: ProtoUtil.tensorDataTypeFromProto(valueType.elemType!),
shape: {dims: ProtoUtil.tensorDimsFromProto(valueType.shape!.dim!.map(d => d.dimValue!))}
};
}
static tensorDimsFromORTFormat(tensor: onnxruntime.experimental.fbs.Tensor) {
const dims = [];
for (let i = 0; i < tensor.dimsLength(); i++) {
dims.push(LongUtil.longToNumber(tensor.dims(i)!));
}
return dims;
}
static tensorAttributesFromORTFormat(node: onnxruntime.experimental.fbs.Node) {
const attributes = [];
for (let i = 0; i < node.attributesLength(); i++) {
attributes.push(node.attributes(i)!);
}
return attributes;
}
}
export class LongUtil {
// This function is called to get a number from long type of data for attribute, dim, and ir version,
// which values are signed integers.
// To make it more generic, add an optional paramter to convert to a unsigned number.
static longToNumber(n: Long|flatbuffers.Long|number, unsigned?: boolean) {
if (Long.isLong(n)) {
return n.toNumber();
} else if (n instanceof flatbuffers.Long) {
return Long.fromValue({low: n.low, high: n.high, unsigned: unsigned ?? false}).toNumber();
}
return n;
}
static isLong(n: unknown) {
return Long.isLong(n) || n instanceof flatbuffers.Long;
}
}
export class ShapeUtil {
static size(dims: readonly number[]): number {
return ShapeUtil.getSizeFromDimensionRange(dims, 0, dims.length);
}
// `axis` inclusive
static sizeFromDimension(dims: readonly number[], axis: number): number {
if (axis < 0 || axis > dims.length) {
throw new Error(`invalid dimension of ${axis} for sizeFromDimension as Tensor has ${dims.length} dimensions.`);
}
return ShapeUtil.getSizeFromDimensionRange(dims, axis, dims.length);
}
// `axis` exclusive
static sizeToDimension(dims: readonly number[], axis: number): number {
if (axis < 0 || axis > dims.length) {
throw new Error(`invalid dimension of ${axis} for sizeToDimension as Tensor has ${dims.length} dimensions.`);
}
return ShapeUtil.getSizeFromDimensionRange(dims, 0, axis);
}
static getSizeFromDimensionRange(dims: readonly number[], start: number, end: number): number {
let size = 1;
for (let i = start; i < end; i++) {
// safety check as this method is called by multiple other methods requiring size.
// size cannot be 0 or negative.
if (dims[i] <= 0) {
throw new Error(
// eslint-disable-next-line max-len
'cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.');
}
size *= dims[i];
}
return size;
}
static computeStrides(dims: readonly number[]): readonly number[] {
const rank = dims.length;
if (rank === 0) {
return [];
} else if (rank === 1) {
return [1];
}
const strides = new Array(rank);
strides[rank - 1] = 1;
strides[rank - 2] = dims[rank - 1];
for (let i = rank - 3; i >= 0; --i) {
strides[i] = strides[i + 1] * dims[i + 1];
}
return strides;
}
static transpose(dims: readonly number[]): readonly number[] {
const copy = dims.slice();
return copy.reverse();
}
static indicesToOffset(indices: readonly number[], strides: readonly number[], axis?: number): number {
if (axis === undefined) {
axis = indices.length;
}
let offset = 0;
for (let i = 0; i < axis; ++i) {
offset += strides[i] * indices[i];
}
return offset;
}
static offsetToIndices(offset: number, strides: readonly number[]): readonly number[] {
const rank = strides.length;
if (rank === 0) {
return [];
} else if (rank === 1) {
return [offset * strides[0]];
}
const indices: number[] = new Array(strides.length);
for (let i = 0; i < indices.length - 1; ++i) {
indices[i] = Math.floor(offset / strides[i]);
offset -= indices[i] * strides[i];
}
indices[indices.length - 1] = offset;
return indices;
}
/**
* normailze axis of range [-r, r) into [0, r).
*/
static normalizeAxis(axis: number, tensorRank: number): number {
if (axis < -tensorRank && axis >= tensorRank) {
throw new Error('unsupported axis for this operation.');
}
return axis < 0 ? axis + tensorRank : axis;
}
static normalizeAxes(axes: readonly number[], tensorRank: number): number[] {
return axes.map(x => this.normalizeAxis(x, tensorRank));
}
// Increment an index into a tensor (in lexicographic
// ordering), wrapping around the specified upper_bound.
/**
* Increment an index into a tensor (in lexicographic ordering), wrapping around the specified upper_bound.
* @param index Given index to increment (Will be mutated)
* @param dims The dimensions of the tensor for which the given index corresponds to
* @param axisToIncrementOn The 1-indexed axis to increment on. If undefined, axisToIncrementOn == rank
*/
static incrementIndex(index: number[], dims: readonly number[], axisToIncrementOn?: number) {
if (dims.length === 0 || index.length === 0) {
throw new Error('Index incrementing unsupported for scalar Tensor');
}
if (axisToIncrementOn === undefined) {
axisToIncrementOn = dims.length;
} else {
if (axisToIncrementOn <= 0 || axisToIncrementOn > dims.length) {
throw new Error('Incorrect axis to increment on');
}
}
for (let k = axisToIncrementOn - 1; k >= 0; --k) {
index[k]++;
if (index[k] < dims[k]) {
break;
}
index[k] = 0;
}
}
/**
* Produces a new dimensions array based on the values in the 'originalDimensions' and 'shape' array
* Used in Reshape
* @param originalDims Original Shape array
* @param shapeHints array containing values to compute the new dimensions
* For example:
* originalDims = [2,2] and shapeHints = [0,-1] will return [2,2]
* originalDims = [2,2] and shapeHints = [4] will return [4]
* originalDims = [2,2] and shapeHints = [5] will throw an exception
* https://github.com/onnx/onnx/blob/main/docs/Operators.md#Reshape
*/
static calculateReshapedDims(originalDims: readonly number[], shapeHints: ArrayLike<number>): number[] {
// reshape to a Scalar Tensor
if (shapeHints.length === 0) {
if (originalDims.length === 0 || ShapeUtil.size(originalDims) === 1) {
return [];
} else {
throw new Error('cannot reshape to a scalar Tensor');
}
}
const nDims = shapeHints.length;
const reshapedDims = new Array<number>(nDims);
let unknownDimension = -1;
let newTensorSize = 1;
for (let i = 0; i < nDims; i++) {
if (shapeHints[i] < -1) {
throw new Error('a dimension in shape hints cannot be less than -1');
}
if (shapeHints[i] === -1) {
if (unknownDimension !== -1) {
throw new Error('at most one dimension in shape hints can be -1');
}
unknownDimension = i;
} else {
if (shapeHints[i] === 0) {
if (i >= originalDims.length) {
throw new Error('the dimension with value zero exceeds the dimension size of the input tensor');
}
reshapedDims[i] = originalDims[i];
} else {
reshapedDims[i] = shapeHints[i];
}
newTensorSize *= reshapedDims[i];
}
}
const oldTensorSize = ShapeUtil.size(originalDims);
if (unknownDimension !== -1) {
if (oldTensorSize % newTensorSize !== 0) {
throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${
originalDims}] Output shape: [${shapeHints}]`);
}
reshapedDims[unknownDimension] = oldTensorSize / newTensorSize;
}
// validate sizes from originalDims and reshapedDims match
else {
if (newTensorSize !== oldTensorSize) {
throw new Error('reshapedDims and originalDims don\'t have matching sizes');
}
}
return reshapedDims;
}
/**
* Sorts a given array based on the indices in the Perm array
* Used in Transpose
* @param a Array to be sorted such as dims or strides
* @param perm Perm given; if null a will be reversed
*/
static sortBasedOnPerm(a: readonly number[], perm?: readonly number[]): readonly number[] {
if (perm) {
return perm.map((v) => a[v]);
} else {
return a.slice().reverse();
}
}
/**
* Pads a given shape according to the padding values
* @param dims shape of the Tensor to be padded
* @param pad pad values
*/
static padShape(dims: readonly number[], pad: readonly number[]): readonly number[] {
const rank = dims.length;
return dims.map((v, i) => v + pad[i] + pad[i + rank]);
}
/**
* Determines if the two shapes are identical
* @param shape1
* @param shape2
*/
static areEqual(shape1: readonly number[], shape2: readonly number[]): boolean {
if (shape1.length !== shape2.length) {
return false;
}
return shape1.every((v, i) => v === shape2[i]);
}
/**
* Validates if the given `dims` or `shape` is valid in ONNX.js context and returns data size
* @param dims - input `dims` that needs to be checked
*/
static validateDimsAndCalcSize(dims: readonly number[]): number {
if (dims.length > 6) {
throw new TypeError('Only rank 0 to 6 is supported for tensor shape.');
}
let size = 1;
for (const n of dims) {
if (!Number.isInteger(n)) {
throw new TypeError(`Invalid shape: ${n} is not an integer`);
}
if (n < 0 || n > 2147483647) {
throw new TypeError(`Invalid shape: length ${n} is not allowed`);
}
size *= n;
}
return size;
}
/**
* Determines the shape of output tensor y = flatten(x, axis)
* @param dims - shape of input tensor
* @param axis - flatten axis, in the range [-r, r]
*/
static flattenShape(dims: readonly number[], axis: number): readonly number[] {
if (axis < 0) {
axis += dims.length;
}
const total = dims.reduce((x, y) => x * y, 1);
const right = dims.slice(axis).reduce((x, y) => x * y, 1);
const outputDims = [total / right, right];
return outputDims;
}
/**
* Determines the shape of output tensor y = squeeze(x, axes)
* @param dims - shape of input tensor
* @param axes - squeeze axes
*/
static squeezeShape(dims: readonly number[], axes: readonly number[]): readonly number[] {
const outputDims = new Array<number>();
// sanity check
axes = ShapeUtil.normalizeAxes(axes, dims.length);
for (let i = 0; i < dims.length; i++) {
const inSqueezeList = axes.indexOf(i) >= 0;
if (inSqueezeList && dims[i] !== 1) {
throw new Error('squeeze an axis of size different than 1');
}
if ((axes.length === 0 && dims[i] > 1) || (axes.length > 0 && !inSqueezeList)) {
outputDims.push(dims[i]);
}
}
return outputDims;
}
/**
* Determines the shape of output tensor y = unsqueeze(x, axes)
* @param dims - shape of input tensor
* @param axes - unsqueeze axes
*/
static unsqueezeShape(dims: readonly number[], axes: readonly number[]): readonly number[] {
const outputDims = new Array<number>(dims.length + axes.length);
// initialize the array elements to 0
outputDims.fill(0);
// set all axes indices to 1 in outputDims and check for duplicates
for (let i = 0; i < axes.length; i++) {
const axis = ShapeUtil.normalizeAxis(axes[i], outputDims.length);
if (axis >= outputDims.length) {
throw new Error('\'axes\' has an out of range axis');
}
if (outputDims[axis] !== 0) {
throw new Error('\'axes\' has a duplicate axis');
}
outputDims[axis] = 1;
}
// fill in the zero entries of outputDims with the input tensor's shape
let inputDimsIterator = 0;
for (let i = 0; i < outputDims.length; i++) {
if (outputDims[i] === 0) {
outputDims[i] = dims[inputDimsIterator++];
}
}
// sanity check assertion. 'inputDimsIterator'
// should be equal to the length of 'dims'
if (inputDimsIterator !== dims.length) {
throw new Error('the unsqueezed dimension could not be established');
}
return outputDims;
}
}
// bunch of helper methods that do a variety of math operations
export class MathUtil {
// y = (x*x) + y
static sqr(
target: number[]|Tensor.NumberType, source: number[]|Tensor.NumberType, targetIndex: number, sourceIndex: number,
blockSize: number) {
if (sourceIndex < 0 || sourceIndex >= source.length) {
throw new Error('sourceIndex out of bounds');
}
if (targetIndex < 0 || targetIndex >= target.length) {
throw new Error('targetIndex out of bounds');
}
if (sourceIndex + blockSize > source.length) {
throw new Error('source indices to be copied are outside bounds');
}
if (targetIndex + blockSize > target.length) {
throw new Error('target array is too small to hold result');
}
for (let offset = 0; offset < blockSize; offset++) {
target[targetIndex + offset] += Math.pow(source[sourceIndex + offset], 2);
}
}
// y = ax + y
static axpy(
target: number[]|Tensor.NumberType, source: number[]|Tensor.NumberType, targetIndex: number, sourceIndex: number,
blockSize: number, alpha: number) {
if (sourceIndex < 0 || sourceIndex >= source.length) {
throw new Error('sourceIndex out of bounds');
}
if (targetIndex < 0 || targetIndex >= target.length) {
throw new Error('targetIndex out of bounds');
}
if (sourceIndex + blockSize > source.length) {
throw new Error('source indices to be copied are outside bounds');
}
if (targetIndex + blockSize > target.length) {
throw new Error('target array is too small to hold result');
}
for (let offset = 0; offset < blockSize; offset++) {
target[targetIndex + offset] += (alpha * source[sourceIndex + offset]);
}
}
// y = pow(x, b)
static powx(
target: number[]|Tensor.NumberType, source: number[]|Tensor.NumberType, targetIndex: number, sourceIndex: number,
blockSize: number, b: number) {
if (sourceIndex < 0 || sourceIndex >= source.length) {
throw new Error('sourceIndex out of bounds');
}
if (targetIndex < 0 || targetIndex >= target.length) {
throw new Error('targetIndex out of bounds');
}
if (sourceIndex + blockSize > source.length) {
throw new Error('source indices to be copied are outside bounds');
}
if (targetIndex + blockSize > target.length) {
throw new Error('target array is too small to hold result');
}
for (let offset = 0; offset < blockSize; offset++) {
target[targetIndex + offset] = Math.pow(source[sourceIndex + offset], b);
}
}
// y = x * y
static mul(
target: number[]|Tensor.NumberType, source: number[]|Tensor.NumberType, targetIndex: number, sourceIndex: number,
blockSize: number) {
if (sourceIndex < 0 || sourceIndex >= source.length) {
throw new Error('sourceIndex out of bounds');
}
if (targetIndex < 0 || targetIndex >= target.length) {
throw new Error('targetIndex out of bounds');
}
if (sourceIndex + blockSize > source.length) {
throw new Error('source indices to be copied are outside bounds');
}
if (targetIndex + blockSize > target.length) {
throw new Error('target array is too small to hold result');
}
for (let offset = 0; offset < blockSize; offset++) {
target[targetIndex + offset] = (source[sourceIndex + offset] * target[targetIndex + offset]);
}
}
}
export class SplitUtil {
/**
* Calculates new Shapes from existing one and the splits given along the axis provides
* @param dims Shape of the Tensor to be splitted into two or more Shapes
* @param axis The dimension along which the Tensor will be split
* @param splits Offsets for the start of each split
*/
static splitShape(dims: readonly number[], axis: number, split: number[], numOutputs?: number):
[number[][], number[]] {
if (split.length === 0) {
if (!numOutputs) {
throw new Error('need to know number of outputs when the \'split\' attribute is not specified');
}
SplitUtil.determineSplit(dims[axis], numOutputs, split);
}
const shapes: number[][] = [];
const offsets = [0];
for (let i = 0; i < split.length; ++i) {
if (i !== 0) {
offsets.push(offsets[i - 1] + split[i - 1]);
}
const shape = dims.slice();
shape[axis] = split[i];
shapes.push(shape);
}
return [shapes, offsets];
}
static determineSplit(numElementsAlongAxis: number, numOutputs: number, split: number[]) {
// If 'split' is not specified by the user, we need to partition the number of elements equally among the outputs
if (numElementsAlongAxis % numOutputs !== 0) {
throw new Error('cannot split tensor to equal sized parts');
}
for (let i = 0; i < numOutputs; ++i) {
split.push(numElementsAlongAxis / numOutputs);
}
}
}
export class ReduceUtil {
/**
* Perform reduce operations on the specific operator
* @param a Input tensor data
* @param axes The dimensions along which the Tensor will be reduced
* @param keepdims If set to true, the axes which are reduced are left in the
* result as dimensions with size one.
* @param op1 The operation to be performed on each element in the tensor
* @param op2 The operation to be performed between elements in the tensor
*/
static calcReduce(
a: Tensor, axes: number[], keepdims: boolean, op1: (b: number) => number,
op2: (a: number, b: number) => number): Tensor {
const dims = a.dims.slice(0);
// if axes is not set, perform reduce on all axes
if (axes.length === 0) {
dims.forEach((d, ind) => axes.push(ind));
}
// get a temporary broadcastable output shape
const outputDims = ReduceUtil.calcReduceShape(dims, axes, true);
// loop through the output and calculate result one by one
const size = ShapeUtil.size(outputDims);
const y = new Tensor(outputDims, a.type);
const strides = ShapeUtil.computeStrides(outputDims);
const inputStrides = ShapeUtil.computeStrides(dims);
const indicesY = new Array(dims.length);
for (let i = 0; i < size; i++) {
const indices = ShapeUtil.offsetToIndices(i, strides);
// map index
BroadcastUtil.fillIndex(indices, dims, indicesY);
y.set(
indices,
ReduceUtil.calcReduceByAxis(
a.numberData, axes, dims, 0, ShapeUtil.indicesToOffset(indicesY, inputStrides), op1, op2));
}
if (keepdims) {
return y;
} else {
// keepdims == 0, calculate the expected shape
return new Tensor(
ReduceUtil.calcReduceShape(dims, axes, keepdims), y.type, undefined, undefined, y.data, y.dataId);
}
}
/**