-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathutils.js
More file actions
1523 lines (1404 loc) · 53.6 KB
/
utils.js
File metadata and controls
1523 lines (1404 loc) · 53.6 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
'use strict';
const operatorToleranceDict = {
argMax: {float32: 0, float16: 0},
argMin: {float32: 0, float16: 0},
batchNormalization: {float32: 6, float16: 6},
clamp: {float32: 0, float16: 0},
// Element-wise binary operations
add: {float32: 1, float16: 1},
sub: {
float32: 1,
float16: 1,
int8: 0,
uint8: 0,
int32: 0,
uint32: 0,
int64: 0,
uint64: 0
},
mul: {float32: 1, float16: 1},
max: {float32: 0, float16: 0},
min: {float32: 0, float16: 0},
// Element-wise binary operations
elu: {float32: 18, float16: 18},
gelu: {float32: 18, float16: 18},
hardSigmoid: {float32: 2, float16: 2},
hardSwish: {float32: 4, float16: 4},
leakyRelu: {float32: 1, float16: 2},
linear: {float32: 2, float16: 2},
prelu: {float32: 1, float16: 1},
relu: {float32: 0, float16: 0, int8: 0, int32: 0},
sigmoid: {float32: 34, float16: 10},
softplus: {float32: 18, float16: 18},
softsign: {float32: 3, float16: 3},
tanh: {float32: 16, float16: 16},
};
const zeroULPToleranceOperatorList = [
// data movement operators
'concat', 'expand', 'gather', 'gatherElements', 'gatherND', 'identity', 'pad',
'reshape', 'reverse', 'scatterElements', 'scatterND', 'slice', 'split',
'tile', 'transpose',
// element-wise logical operators
'equal', 'notEqual', 'greater', 'greaterOrEqual', 'lesser', 'lesserOrEqual',
'logicalNot', 'logicalAnd', 'logicalOr', 'logicalXor'
];
const getZeroULPTolerance = () => {
return {metricType: 'ULP', value: 0};
};
const getSoftmaxPrecisionTolerance =
(op, graphResources, intermediateOperands) => {
const {inputs} = graphResources;
const args = op.arguments;
let inputShape;
const inputIndex = args[0][Object.keys(args[0])[0]];
if (inputs[inputIndex]) {
inputShape = inputs[inputIndex].descriptor.shape;
} else {
inputShape = intermediateOperands[inputIndex].shape;
}
const axis = args.length === 2 ? args[1][Object.keys(args[1])[0]] : 1;
const tolerance = inputShape[axis] * 3 + 3;
const toleranceValueDict = {float32: tolerance, float16: tolerance};
const expectedDataType =
getExpectedDataTypeOfSingleOutput(graphResources.expectedOutputs);
return {metricType: 'ULP', value: toleranceValueDict[expectedDataType]};
};
const getPrecisionTolerance = (graphResources, intermediateOperands) => {
const expectedDataType =
getExpectedDataTypeOfSingleOutput(graphResources.expectedOutputs);
let toleranceValue = 0;
graphResources.operators.forEach(op => {
switch (op.name) {
case 'conv2d':
toleranceValue += getConv2dPrecisionTolerance(op, graphResources,
intermediateOperands).value;
break;
case 'convTranspose2d':
toleranceValue += getConv2dPrecisionTolerance(op, graphResources,
intermediateOperands).value;
break;
case 'gemm':
toleranceValue += getGemmPrecisionTolerance(op, graphResources,
intermediateOperands).value;
break;
case 'matmul':
toleranceValue += getMatmulPrecisionTolerance(op, graphResources,
intermediateOperands).value;
break;
case 'softmax':
toleranceValue += getSoftmaxPrecisionTolerance(
op, graphResources, intermediateOperands)
.value;
break;
case 'averagePool2d':
case 'maxPool2d':
case 'l2Pool2d':
toleranceValue += getPoolingOperatorsPrecisionTolerance(
op, graphResources, intermediateOperands)
.value;
break;
case 'reduceL1':
case 'reduceL2':
case 'reduceLogSum':
case 'reduceLogSumExp':
case 'reduceMax':
case 'reduceMean':
case 'reduceMin':
case 'reduceProduct':
case 'reduceSum':
case 'reduceSumSquare':
toleranceValue += getReductionOperatorsPrecisionTolerance(
op, graphResources, intermediateOperands)
.value;
break;
case 'resample2d':
toleranceValue += getResample2dPrecisionTolerance(
op, graphResources, intermediateOperands)
.value;
break;
default:
if (zeroULPToleranceOperatorList.includes(op.name)) {
toleranceValue += getZeroULPTolerance().value;
} else {
const operatorTolerance =
operatorToleranceDict[op.name]?.[expectedDataType];
if (operatorTolerance !== undefined) {
toleranceValue += operatorTolerance;
}
}
}
});
return {metricType: 'ULP', value: toleranceValue};
};
// https://www.w3.org/TR/webnn/#enumdef-mloperanddatatype
const TypedArrayDict = {
float32: Float32Array,
// Proposal to add float16 TypedArrays to JavaScript.
// URL: https://tc39.es/proposal-float16array/
// Use workaround Uint16 for Float16
float16: Uint16Array,
int64: BigInt64Array,
uint64: BigUint64Array,
int32: Int32Array,
uint32: Uint32Array,
int8: Int8Array,
uint8: Uint8Array,
int4: Uint8Array,
uint4: Uint8Array,
};
const kIntTypes =
['uint4', 'int4', 'uint8', 'int8', 'uint32', 'int32', 'uint64', 'int64'];
const kFloatTypes = ['float16', 'float32'];
const findCompatibleType = (dataType, supportedTypes, castOpSupportLimits) => {
if (!castOpSupportLimits.input.dataTypes.includes(dataType)) {
// Cannot cast from `dataType` to any other type.
return null;
}
for (let supportedType of supportedTypes) {
if (kIntTypes.includes(dataType) &&
castOpSupportLimits.output.dataTypes.includes(dataType) &&
kIntTypes.indexOf(supportedType) > kIntTypes.indexOf(dataType)) {
return supportedType;
}
if (kFloatTypes.includes(dataType)) {
if (kFloatTypes.indexOf(supportedType) > kFloatTypes.indexOf(dataType)) {
return supportedType;
}
}
}
return null;
};
// The maximum index to validate for the output's expected value.
const kMaximumIndexToValidate = 1000;
const kContextOptionsForVariant = {
cpu: {
deviceType: 'cpu',
},
gpu: {
deviceType: 'gpu',
},
npu: {
deviceType: 'npu',
},
};
const searchParams = new URLSearchParams(location.search);
const variant = searchParams.get('device') || location.search.substring(1);
const contextOptions = kContextOptionsForVariant[variant];
async function getContext() {
let context;
try {
context = await navigator.ml.createContext(contextOptions);
} catch (e) {
// A previous test case may kill the GPU process on which the WebNN service
// runs. If you call `createContext` again immediately before the GPU
// process restarts, it will fail again. So wait a moment and retry.
if (e.message.includes('WebNN service connection error.')) {
await new Promise(resolve => setTimeout(resolve, 3000));
try {
context = await navigator.ml.createContext(contextOptions);
} catch (retryError) {
throw new AssertionError(
`Unable to create context for ${variant} variant on retry. ${retryError}`);
}
} else {
throw new AssertionError(
`Unable to create context for ${variant} variant. ${e}`);
}
}
return context;
}
const tcNameArray = searchParams.getAll('tc');
function isTargetTest(test) {
return tcNameArray.length === 0 || tcNameArray.includes(test.name);
}
const assertDescriptorsEquals = (outputOperand, expected) => {
const dataType =
expected.castedType ? expected.castedType : expected.dataType;
assert_equals(
outputOperand.dataType, dataType,
'actual output dataType should be equal to expected output dataType');
assert_array_equals(
outputOperand.shape, expected.shape,
'actual output shape should be equal to expected output shape');
};
// ref:
// http://stackoverflow.com/questions/32633585/how-do-you-convert-to-half-floats-in-javascript
const toHalf = (value) => {
let floatView = new Float32Array(1);
let int32View = new Int32Array(floatView.buffer);
/* This method is faster than the OpenEXR implementation (very often
* used, eg. in Ogre), with the additional benefit of rounding, inspired
* by James Tursa's half-precision code. */
floatView[0] = value;
let x = int32View[0];
let bits = (x >> 16) & 0x8000; /* Get the sign */
let m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
let e = (x >> 23) & 0xff; /* Using int is faster here */
/* If zero, or denormal, or exponent underflows too much for a denormal
* half, return signed zero. */
if (e < 103) {
return bits;
}
/* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
if (e > 142) {
bits |= 0x7c00;
/* If exponent was 0xff and one mantissa bit was set, it means NaN,
* not Inf, so make sure we set one mantissa bit too. */
if (e == 255 && (x & 0x007fffff)) {
bits |= 1;
}
return bits;
}
/* If exponent underflows but not too much, return a denormal */
if (e < 113) {
m |= 0x0800;
/* Extra rounding may overflow and set mantissa to 0 and exponent
* to 1, which is OK. */
bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
return bits;
}
bits |= ((e - 112) << 10) | (m >> 1);
/* Extra rounding. An overflow will set mantissa to 0 and increment
* the exponent, which is OK. */
bits += m & 1;
return bits;
};
const getTypedArrayData = (type, size, data) => {
let outData;
if (type === 'float16') {
if (typeof (data) === 'number' && size > 1) {
return new TypedArrayDict[type](size).fill(toHalf(data));
}
// workaround to convert Float16 to Uint16
outData = new TypedArrayDict[type](data.length);
for (let i = 0; i < data.length; i++) {
outData[i] = toHalf(data[i]);
}
} else if (type === 'int64' || type === 'uint64') {
if (typeof (data) === 'number' && size > 1) {
return new TypedArrayDict[type](size).fill(BigInt(data));
}
outData = new TypedArrayDict[type](data.length);
for (let i = 0; i < data.length; i++) {
outData[i] = BigInt(data[i]);
}
} else if (type === 'uint4' || type === 'int4') {
// The first nybble is stored in the first bits 0-3, and later bits 4-7
// store the later nybble. The data is packed, without any padding between
// dimensions. For example: an array of uint4:
// size = [2,5]
// values = [1,2,3,4,5,6,7,8,9,10]
// Would yield 5 hex bytes:
// Uint8Array.of(0x21, 0x43, 0x65, 0x87, 0xA9);
const array = new TypedArrayDict[type](Math.ceil(size / 2));
let i = 0;
while (i < size - 1) {
const packedByte = ((data[i + 1] & 0xF) << 4) | (data[i] & 0xF);
array[Math.floor(i / 2)] = packedByte;
i = i + 2;
}
// Handle the odd size.
if (i === size - 1) {
const packedByte = data[i] & 0xF;
array[Math.floor(i / 2)] = packedByte;
}
return array;
} else {
if (typeof (data) === 'number' && size > 1) {
return new TypedArrayDict[type](size).fill(data);
}
outData = new TypedArrayDict[type](data);
}
return outData;
};
const sizeOfShape = (array) => {
return array.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
};
/**
* Get bitwise of the given value.
* @param {Number} value
* @param {String} dataType - A data type string; currently only "float32" is
* supported by this function.
* @return {BigInt} A 64-bit signed integer.
*/
const getBitwise = (value, dataType) => {
const buffer = new ArrayBuffer(8);
const int64Array = new BigInt64Array(buffer);
let typedArray;
if (dataType === "float32") {
typedArray = new Float32Array(buffer);
} else {
throw new AssertionError(`Data type ${dataType} is not supported`);
}
typedArray[0] = Math.abs(value);
const int64 = int64Array[0];
return (value < 0) ? -int64 : int64;
};
/**
* Assert that each array property in ``actual`` is a number being close enough
* to the corresponding property in ``expected`` by the acceptable ULP distance
* ``nulp`` with given ``dataType`` data type.
*
* @param {Array} actual - Array of test values.
* @param {Array} expected - Array of values expected to be close to the values
* in ``actual``.
* @param {(Number|BigInt)} nulp - A value indicates acceptable ULP distance.
* @param {String} dataType - A data type string, value: "float32",
* more types, please see:
* https://www.w3.org/TR/webnn/#enumdef-mloperanddatatype
* @param {String} description - Description of the condition being tested.
*/
const assert_array_approx_equals_ulp = (actual, expected, nulp, dataType, description) => {
/*
* Test if two primitive arrays are equal within acceptable ULP distance
*/
assert_equals(
actual.length, expected.length,
`assert_array_approx_equals_ulp: ${description} lengths differ`);
for (let i = 0; i < actual.length; i++) {
if (actual[i] === expected[i]) {
continue;
} else {
let distance = ulpDistance(actual[i], expected[i], dataType);
// TODO: See if callers can be updated to pass matching type.
nulp = typeof distance === 'bigint' ? BigInt(nulp) : Number(nulp);
assert_less_than_equal(distance, nulp,
`assert_array_approx_equals_ulp: ${description} actual ` +
`${
dataType === 'float16' ?
float16AsUint16ToNumber(actual[i]) :
actual[i]} should be close enough to expected ` +
`${expected[i]} by ULP distance:`);
}
}
};
/**
* Compute the ULP distance between ``a`` and ``b`` for the given ``dataType``.
*
* @param {(Number|BigInt)} a - First value.
* @param {(Number|BigInt)} b - Second value.
* @param {String} dataType - A data type string, value: "float32",
* more types, please see:
* https://www.w3.org/TR/webnn/#enumdef-mloperanddatatype
*/
const ulpDistance = (a, b, dataType) => {
let aBitwise, bBitwise;
// measure the ULP distance
if (dataType === 'float32') {
aBitwise = getBitwise(a, dataType);
bBitwise = getBitwise(b, dataType);
} else if (dataType === 'float16') {
aBitwise = a;
// convert b data of Float16 to Uint16
bBitwise = toHalf(b);
// Workaround to use mask to check returned special float16 value -0.0 which
// is 32768 (1000 0000 0000 0000) of uint16
const signExclusionMask = 0x00007FFF;
if ((aBitwise & signExclusionMask) === 0 &&
(bBitwise & signExclusionMask) === 0) {
return 0;
}
} else if (dataType === 'int64' || dataType === 'uint64') {
aBitwise = BigInt(a);
bBitwise = BigInt(b);
} else if (
dataType === 'int8' || dataType === 'uint8' || dataType === 'int32' ||
dataType === 'uint32' || dataType === 'int4' || dataType === 'uint4') {
aBitwise = a;
bBitwise = b;
} else {
throw new AssertionError(`Data type ${dataType} is not supported`);
}
const distance = aBitwise - bBitwise;
return distance >= 0 ? distance : -distance;
};
/**
* This function converts a Float16 stored as the bits of a Uint16 into a
* JavaScript Number.
* @param {Number} uint16 - a Float16 stored as the bits of a Uint16
* @returns An emulated Float16 number.
*/
function float16AsUint16ToNumber(uint16) {
const sign = (uint16 >> 15) & 0x1;
const exponent = (uint16 >> 10) & 0x1F;
const mantissa = uint16 & 0x3FF;
let float16;
if (exponent === 0) {
// Subnormal number
float16 = (mantissa / 1024) * Math.pow(2, -14);
} else if (exponent === 0x1F) {
// NaN or Infinity
float16 = mantissa ? NaN : Infinity;
} else {
// Normalized number
float16 = (1 + mantissa / 1024) * Math.pow(2, exponent - 15);
}
// Apply the sign
return sign ? -float16 : float16;
}
/**
* Assert actual results with expected results.
* @param {String} operatorName
* @param {(Number[]|Number)} actual
* @param {(Number[]|Number)} expected
* @param {String} metricType - Value: 'ULP', 'ATOL'
* @param {Number} toleranceValue
* @param {String} dataType - An operand type string, value: "float32",
* more types, please see:
* https://www.w3.org/TR/webnn/#enumdef-mloperanddatatype
*/
const doAssert =
(operatorName, actual, expected, metricType, toleranceValue, dataType) => {
const description = `test ${operatorName} ${dataType}`;
if (typeof expected === 'number') {
expected = [expected];
actual = [actual];
}
if (metricType === 'ULP') {
assert_array_approx_equals_ulp(
actual, expected, toleranceValue, dataType, description);
} else if (metricType === 'ATOL') {
let actualData;
if (dataType === 'float16') {
// workaround for float16
actualData = new Array(actual.length);
actual.forEach(
(x, index) => actualData[index] = float16AsUint16ToNumber(x));
} else {
actualData = actual;
}
assert_array_approx_equals(
actualData, expected, toleranceValue, description);
} else {
throw new AssertionError(
`Tolerance Metric type '${metricType}' is not supported`);
}
};
/**
* Assert computed results be equal to expected data.
* @param {Object} toleranceFunc
* @param {Map<String, ArrayBufferView> |
* Array[Map<String, ArrayBufferView>]} actual
* @param {Object} graphResources - Resources used for building a graph
*/
const assertResultsEquals =
(toleranceFunc, actual, graphResources, intermediateOperands) => {
const operatorName =
graphResources.operators.map(operator => operator.name).join(' ');
const expectedOutputs = graphResources.expectedOutputs;
const toleranceInfo = toleranceFunc(graphResources, intermediateOperands);
const metricType = toleranceInfo.metricType;
const toleranceValue = toleranceInfo.value;
let outputData;
for (let operandName in actual) {
const expectedSuboutput = expectedOutputs[operandName];
const expectedDescriptor = expectedSuboutput.descriptor;
let expectedData = expectedSuboutput.data;
outputData = actual[operandName];
// If data is scalar and shape is not, it means it's expecting to be
// filled by the scalar value. Also limit the array size so it doesn't
// timeout.
if (typeof (expectedData) === 'number' && expectedDescriptor.shape &&
sizeOfShape(expectedDescriptor.shape) > 1) {
const size = Math.min(
kMaximumIndexToValidate, sizeOfShape(expectedDescriptor.shape));
expectedData = new Array(size).fill(expectedData);
outputData = outputData.subarray(0, kMaximumIndexToValidate);
} else if (
expectedDescriptor.dataType === 'uint4' ||
expectedDescriptor.dataType === 'int4') {
// The int4/uint4 data were packed in Uint8Array.
// The first nybble and later nybble of one int8/uint8 value store two
// consecutive 4-bits values separately. After unpacking each 4-bits
// value, the unpacked int4 value is stored in an element of
// Int8Array, and the unpacked uint4 value is stored in an element of
// Uint8Array. For example: an array of uint4:
// size = [1, 5]
// Uint8Array.of(0x21, 0x43, 0x65, 0x87, 0xA9)
// Would yield 5 * 2 uint4 data:
// Uint8Array.of(1,2,3,4,5,6,7,8,9,10);
// Another example: an array of int4:
// size = [1, 5]
// Uint8Array.of(0xA9, 0xCB, 0xED, 0x0F, 0x21)
// Would yield 5 * 2 int4 data:
// Int8Array.of(-7, -6, -5, -4, -3, -2, -1, 0, 1, 2);
let newOutputData;
if (expectedDescriptor.dataType === 'uint4') {
newOutputData =
new Uint8Array(sizeOfShape(expectedDescriptor.shape));
} else {
newOutputData =
new Int8Array(sizeOfShape(expectedDescriptor.shape));
}
const signMask =
(expectedDescriptor.dataType === 'int4') ? 0x08 : 0x00;
for (let i = 0; i < sizeOfShape(expectedDescriptor.shape); i++) {
const byteIndex = Math.floor(i / 2);
let value = (outputData[byteIndex] >> ((i & 1) << 2)) & 0xF;
// Handle the negative numbers.
if (value & signMask) {
value |= 0xF0;
}
newOutputData[i] = value;
}
outputData = newOutputData;
}
doAssert(
operatorName, outputData, expectedData, metricType, toleranceValue,
expectedDescriptor.dataType);
}
};
const createOperand = (context, builder, operandName, resources) => {
let operand;
const descriptor = resources.descriptor;
const dataType = descriptor.dataType;
const supportedDataTypes = resources.constant ?
context.opSupportLimits().constant.dataTypes :
context.opSupportLimits().input.dataTypes;
// If input data type is not supported on current platform, attempt to use
// a supported type to pass the data, then cast back to original type.
if (!supportedDataTypes.includes(dataType)) {
const compatibleType = findCompatibleType(
dataType, supportedDataTypes, context.opSupportLimits().cast);
if (compatibleType) {
descriptor.castedType = compatibleType;
descriptor.dataType = compatibleType;
}
}
operand = resources.constant ?
builder.constant(
descriptor,
getTypedArrayData(
descriptor.dataType, sizeOfShape(descriptor.shape),
resources.data)) :
builder.input(operandName, descriptor);
if (descriptor.castedType) {
operand = builder.cast(operand, dataType);
}
return operand;
};
/**
* Create inputs or outputs tensor.
* @param {MLContext} context - the context used to create inputs or outputs
* tensor.
* @param {String} dataType - dataType of inputs / outputs operands
* @param {Array} shape - dimensions of inputs / outputs operands
* @param {Object} [data] - optional data for inputs tensor
* @returns {MLTensor}
*/
async function createTensorWithData(context, dataType, shape, data) {
const tensorDesc = {dataType, shape};
if (data) {
tensorDesc.writable = true;
} else {
tensorDesc.readable = true;
}
let tensor = await context.createTensor(tensorDesc);
if (data) {
context.writeTensor(tensor, data);
}
return tensor;
}
async function prepareInputsForGraph(context, resources) {
const inputOperandNameArray = Object.keys(resources).filter(
operandName => !resources[operandName].constant);
const tensors = await Promise.all(inputOperandNameArray.map((operandName) => {
const inputOperandResources = resources[operandName];
const descriptor = inputOperandResources.descriptor;
const targetDataType =
descriptor.castedType ? descriptor.castedType : descriptor.dataType;
const inputBuffer = getTypedArrayData(
targetDataType, sizeOfShape(descriptor.shape),
inputOperandResources.data);
return createTensorWithData(
context, targetDataType, descriptor.shape, inputBuffer);
}));
const inputs = {};
inputOperandNameArray.forEach((name, index) => inputs[name] = tensors[index]);
return inputs;
}
async function prepareOutputsForGraph(context, resources) {
const outputOperandNameArray = Object.keys(resources);
const tensors =
await Promise.all(outputOperandNameArray.map((operandName) => {
const descriptor = resources[operandName].descriptor;
const dataType =
descriptor.castedType ? descriptor.castedType : descriptor.dataType;
return createTensorWithData(context, dataType, descriptor.shape);
}));
const outputs = {};
outputOperandNameArray.forEach(
(name, index) => outputs[name] = tensors[index]);
return outputs;
}
function getInputName(operatorArguments, operandName) {
for (let argument of operatorArguments) {
const name = Object.keys(argument)[0];
if (name === operandName) {
return argument[operandName];
} else if (name === 'options') {
if (Object.keys(argument[name]).includes(operandName)) {
return argument[name][operandName];
}
}
}
return null;
}
// This assert() function is to check whether configurations of test case are
// set correctly.
function assert(condition, message) {
if (!condition) {
throw new Error(`Wrong test case, ${message}`);
}
}
function validateContextSupportsGraph(context, graph) {
const supportLimits = context.opSupportLimits();
const castOpSupportLimits = supportLimits.cast;
const inputDataTypes = supportLimits.input.dataTypes;
const inputRankRange = supportLimits.input.rankRange;
const constantDataTypes = supportLimits.constant.dataTypes;
const constantRankRange = supportLimits.constant.rankRange;
const outputDataTypes = supportLimits.output.dataTypes;
const outputRankRange = supportLimits.output.rankRange;
function validateInputOrConstantDataTypeAndRank(
inputName, operatorSupportLimits, operand) {
const inputDescriptor = graph.inputs[inputName].descriptor;
const inputDataType = inputDescriptor.dataType;
const inputRank = inputDescriptor.shape.length;
if (inputDescriptor.constant) {
// Check graph constant data type
if (!constantDataTypes.includes(inputDataType) &&
!findCompatibleType(
inputDataType, constantDataTypes, castOpSupportLimits)) {
throw new TypeError(
`Unsupported data type, constant '${operand}' data type ${
inputDataType} must be one of [${constantDataTypes}].`);
}
// Check graph constant rank
if (inputRank < constantRankRange.min) {
throw new TypeError(`Unsupported rank ${inputRank} for constant '${
operand}' (must be at least ${constantRankRange.min}).`);
}
if (inputRank > constantRankRange.max) {
throw new TypeError(`Unsupported rank ${inputRank} for constant '${
operand}' (must be at most ${constantRankRange.max}).`);
}
} else {
// Check graph input data type
if (!inputDataTypes.includes(inputDataType) &&
!findCompatibleType(
inputDataType, inputDataTypes, castOpSupportLimits)) {
throw new TypeError(
`Unsupported data type, input '${operand}' data type ${
inputDataType} must be one of [${inputDataTypes}].`);
}
// Check graph input rank
if (inputRank < inputRankRange.min) {
throw new TypeError(`Unsupported rank ${inputRank} for input '${
operand}' (must be at least ${inputRankRange.min}).`);
}
if (inputRank > inputRankRange.max) {
throw new TypeError(`Unsupported rank ${inputRank} for input '${
operand}' (must be at most ${inputRankRange.max}).`);
}
}
const operandSupportLimits = operatorSupportLimits[operand];
// Check operand data type
const inputOperandDataTypes = operandSupportLimits.dataTypes;
if (!inputOperandDataTypes.includes(inputDataType) &&
!findCompatibleType(
inputDataType, inputDataTypes, castOpSupportLimits)) {
throw new TypeError(
`Unsupported data type, input '${operand}' data type ${
inputDataType} must be one of [${inputOperandDataTypes}].`);
}
// Check operand rank
const limitsRankRange = operandSupportLimits.rankRange;
if (inputRank < limitsRankRange.min) {
throw new TypeError(`Unsupported rank ${inputRank} for argument ${
operand} (must be at least ${limitsRankRange.min}).`);
}
if (inputRank > limitsRankRange.max) {
throw new TypeError(`Unsupported rank ${inputRank} for argument ${
operand} (must be at most ${limitsRankRange.max}).`);
}
}
function validateOutputDataTypeAndRank(
outputName, operatorSupportLimits, operand) {
const outputDataType =
graph.expectedOutputs[outputName].descriptor.dataType;
const outputRank =
graph.expectedOutputs[outputName].descriptor.shape.length;
// Check graph output data type
if (!outputDataTypes.includes(outputDataType) &&
!findCompatibleType(
outputDataType, outputDataTypes, castOpSupportLimits)) {
throw new TypeError(
`Unsupported data type, output '${operand}' data type ${
outputDataType} must be one of [${outputDataTypes}].`);
}
// Check graph output rank
if (outputRank < outputRankRange.min) {
throw new TypeError(`Unsupported rank ${outputRank} for output '${
operand}' (must be at least ${outputRankRange.min}).`);
}
if (outputRank > outputRankRange.max) {
throw new TypeError(`Unsupported rank ${outputRank} for output '${
operand}' (must be at most ${outputRankRange.max}).`);
}
// Check output operand data type
const outputOperandDataTypes = operatorSupportLimits[operand].dataTypes;
if (!outputOperandDataTypes.includes(outputDataType) &&
!findCompatibleType(
outputOperandDataTypes, outputDataTypes, castOpSupportLimits)) {
throw new TypeError(
`Unsupported data type, output '${operand}' data type ${
outputDataType} must be one of [${outputOperandDataTypes}].`);
}
// Check output operand rank
const outputOperandRankRange = operatorSupportLimits[operand].rankRange;
if (outputRank < outputOperandRankRange.min) {
throw new TypeError(`Unsupported rank ${outputRank} for output '${
operand}' (must be at least ${outputOperandRankRange.min}).`);
}
if (outputRank > outputOperandRankRange.max) {
throw new TypeError(`Unsupported rank ${outputRank} for output '${
operand}' (must be at most ${outputOperandRankRange.max}).`);
}
}
try {
for (let operator of graph.operators) {
const operatorName = operator.name;
const operatorSupportLimits = supportLimits[operatorName];
for (let operand of Object.keys(operatorSupportLimits)) {
if (operand === 'output') {
// single output operand
assert(
typeof operator.outputs === 'string',
`the outputs of ${operatorName} should be a string.`);
if (!graph.expectedOutputs[operator.outputs]) {
// intermediate output
continue;
}
validateOutputDataTypeAndRank(
operator.outputs, operatorSupportLimits, 'output');
} else if (operand === 'outputs') {
// multiple output operands of split operator
assert(
Array.isArray(operator.outputs),
`the outputs of ${operatorName} should be a string array.`);
for (const outputName of operator.outputs) {
assert(
typeof outputName === 'string',
`the outputs' item of ${operatorName} should be a string.`);
if (!graph.expectedOutputs[outputName]) {
// intermediate output
continue;
}
validateOutputDataTypeAndRank(
outputName, operatorSupportLimits, 'outputs');
}
} else if (/output[0-2]/.test(operand)) {
// multiple output operands of gru/lstm/lstmCell operators
assert(
Array.isArray(operator.outputs),
`the outputs of ${operatorName} should be a string array.`);
const index = parseInt(operand.match(/output([0-2])/)[1]);
if (index < operator.outputs.length) {
validateOutputDataTypeAndRank(
operator.outputs[index], operatorSupportLimits, operand);
}
} else {
// input operand(s)
if (operatorName === 'concat') {
const inputNameArray = operator.arguments[0][operand];
assert(
Array.isArray(inputNameArray),
`the inputs of ${operatorName} should be a string array.`);
for (const inputName of inputNameArray) {
assert(
typeof inputName === 'string',
`the inputs' item of ${operatorName} should be a string.`);
if (!graph.inputs[inputName]) {
// intermediate input
continue;
}
validateInputOrConstantDataTypeAndRank(
inputName, operatorSupportLimits, 'inputs');
}
} else {
const inputName = getInputName(operator.arguments, operand);
if (inputName === null || !graph.inputs[inputName]) {
// default options argument or intermediate input
continue;
}
validateInputOrConstantDataTypeAndRank(
inputName, operatorSupportLimits, operand);
}
}
}
}
return /*supported*/ true;
} catch (error) {
return /*not supported*/ false;
}
}
/**
* This function is to execute the compiled graph.
* @param {MLContext} context
* @param {MLGraph} graph
* @param {Map<String, {
* data: Array.<Number>|Number,
* descriptor: MLOperandDescriptor,
* constant?: Boolean
* }>} graphInputs
* @param {Map<String, {
* data: Array.<Number>|Number,
* descriptor: MLOperandDescriptor,
* }>} expectedOutputs
* @returns A result object.
*/
async function computeGraph(context, graph, graphInputs, expectedOutputs) {
const inputs = await prepareInputsForGraph(context, graphInputs);
const outputs = await prepareOutputsForGraph(context, expectedOutputs);
// Execute the compiled graph.
context.dispatch(graph, inputs, outputs);
const result = {};
const outputNameArray = Object.keys(expectedOutputs);
const outputBuffers = await Promise.all(Object.values(outputs).map(
(tensor) => {return context.readTensor(tensor)}));
outputNameArray.forEach((name, index) => {
const dataType = expectedOutputs[name].descriptor.castedType ?
expectedOutputs[name].descriptor.castedType :
expectedOutputs[name].descriptor.dataType;
result[name] = new TypedArrayDict[dataType](outputBuffers[index])
});
return result;
}
/**
* This function is to compile and execute the constructed graph.
* @param {MLContext} context
* @param {MLGraphBuilder} builder
* @param {{
* inputs: Map<String, {
* data: Array.<Number>|Number,
* descriptor: MLOperandDescriptor,
* constant?: Boolean
* }>,
* operators: Array.<{
* name: String,
* arguments: Array.<Map<String, Object>> ,
* outputs: Array.<String>|String
* }>,
* expectedOutputs: Map<String, {
* data: Array.<Number>|Number,
* descriptor: MLOperandDescriptor,
* }>
* }} graphResources - Resources used for building a graph
* @returns A Promise of MLComputeResult.
*/
const buildAndExecuteGraph = async (context, builder, graphResources) => {
const outputOperands = [];
const graphInputs = graphResources.inputs;
const graphOperators = graphResources.operators;
const intermediateOperands = {};
for (const operator of graphOperators) {
const argumentArray = [];
for (const argument of operator.arguments) {
for (const argumentName in argument) {
if (argumentName !== 'options') {
if (operator.name === 'concat' && argumentName === 'inputs') {
const concatInputs = [];
for (const inputName of argument[argumentName]) {
if (graphInputs.hasOwnProperty(inputName)) {
const operandName = inputName;
const operand = createOperand(
context, builder, operandName, graphInputs[operandName]);
concatInputs.push(operand);
} else if (intermediateOperands.hasOwnProperty(inputName)) {
concatInputs.push(intermediateOperands[inputName]);
}
// concatInputs.push(intermediateOperands[inputName]);
}
argumentArray.push(concatInputs);
} else if (graphInputs.hasOwnProperty(argument[argumentName])) {
const operandName = argument[argumentName];