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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
|
/**
* AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts
**/import { globalTestConfig } from '../../../../common/framework/test_config.js';import { assert, objectEquals, unreachable } from '../../../../common/util/util.js';
import { compare } from '../../../util/compare.js';
import { kValue } from '../../../util/constants.js';
import {
ScalarType,
Scalar,
TypeVec,
TypeU32,
Vector,
VectorType,
u32,
i32,
Matrix,
MatrixType,
scalarTypeOf } from
'../../../util/conversion.js';
import { FPInterval } from '../../../util/floating_point.js';
import {
cartesianProduct,
quantizeToI32,
quantizeToU32 } from
'../../../util/math.js';
/** @returns if this Expectation actually a Comparator */
export function isComparator(e) {
return !(
e instanceof FPInterval ||
e instanceof Scalar ||
e instanceof Vector ||
e instanceof Matrix ||
e instanceof Array);
}
/** @returns the input if it is already a Comparator, otherwise wraps it in a 'value' comparator */
export function toComparator(input) {
if (isComparator(input)) {
return input;
}
return { compare: (got) => compare(got, input), kind: 'value' };
}
/** Case is a single expression test case. */
/** CaseList is a list of Cases */
/** The input value source */
// Read-write storage buffer
/** All possible input sources */
export const allInputSources = ['const', 'uniform', 'storage_r', 'storage_rw'];
/** Just constant input source */
export const onlyConstInputSource = ['const'];
/** Configuration for running a expression test */
// Helper for returning the stride for a given Type
function valueStride(ty) {
// AbstractFloats are passed out of the shader via a struct of 2x u32s and
// unpacking containers as arrays
if (scalarTypeOf(ty).kind === 'abstract-float') {
if (ty instanceof ScalarType) {
return 16;
}
if (ty instanceof VectorType) {
if (ty.width === 2) {
return 16;
}
// vec3s have padding to make them the same size as vec4s
return 32;
}
if (ty instanceof MatrixType) {
switch (ty.cols) {
case 2:
switch (ty.rows) {
case 2:
return 32;
case 3:
return 64;
case 4:
return 64;
}
break;
case 3:
switch (ty.rows) {
case 2:
return 48;
case 3:
return 96;
case 4:
return 96;
}
break;
case 4:
switch (ty.rows) {
case 2:
return 64;
case 3:
return 128;
case 4:
return 128;
}
break;
}
}
unreachable(`AbstractFloats have not yet been implemented for ${ty.toString()}`);
}
if (ty instanceof MatrixType) {
switch (ty.cols) {
case 2:
switch (ty.rows) {
case 2:
return 16;
case 3:
return 32;
case 4:
return 32;
}
break;
case 3:
switch (ty.rows) {
case 2:
return 32;
case 3:
return 64;
case 4:
return 64;
}
break;
case 4:
switch (ty.rows) {
case 2:
return 32;
case 3:
return 64;
case 4:
return 64;
}
break;
}
unreachable(
`Attempted to get stride length for a matrix with dimensions (${ty.cols}x${ty.rows}), which isn't currently handled`
);
}
// Handles scalars and vectors
return 16;
}
// Helper for summing up all of the stride values for an array of Types
function valueStrides(tys) {
return tys.map(valueStride).reduce((sum, c) => sum + c);
}
// Helper for returning the WGSL storage type for the given Type.
function storageType(ty) {
if (ty instanceof ScalarType) {
assert(ty.kind !== 'f64', `No storage type defined for 'f64' values`);
assert(
ty.kind !== 'abstract-float',
`Custom handling is implemented for 'abstract-float' values`
);
if (ty.kind === 'bool') {
return TypeU32;
}
}
if (ty instanceof VectorType) {
return TypeVec(ty.width, storageType(ty.elementType));
}
return ty;
}
// Helper for converting a value of the type 'ty' from the storage type.
function fromStorage(ty, expr) {
if (ty instanceof ScalarType) {
assert(ty.kind !== 'abstract-float', `AbstractFloat values should not be in input storage`);
assert(ty.kind !== 'f64', `'No storage type defined for 'f64' values`);
if (ty.kind === 'bool') {
return `${expr} != 0u`;
}
}
if (ty instanceof VectorType) {
assert(
ty.elementType.kind !== 'abstract-float',
`AbstractFloat values cannot appear in input storage`
);
assert(ty.elementType.kind !== 'f64', `'No storage type defined for 'f64' values`);
if (ty.elementType.kind === 'bool') {
return `${expr} != vec${ty.width}<u32>(0u)`;
}
}
return expr;
}
// Helper for converting a value of the type 'ty' to the storage type.
function toStorage(ty, expr) {
if (ty instanceof ScalarType) {
assert(
ty.kind !== 'abstract-float',
`AbstractFloat values have custom code for writing to storage`
);
assert(ty.kind !== 'f64', `No storage type defined for 'f64' values`);
if (ty.kind === 'bool') {
return `select(0u, 1u, ${expr})`;
}
}
if (ty instanceof VectorType) {
assert(
ty.elementType.kind !== 'abstract-float',
`AbstractFloat values have custom code for writing to storage`
);
assert(ty.elementType.kind !== 'f64', `'No storage type defined for 'f64' values`);
if (ty.elementType.kind === 'bool') {
return `select(vec${ty.width}<u32>(0u), vec${ty.width}<u32>(1u), ${expr})`;
}
}
return expr;
}
// A Pipeline is a map of WGSL shader source to a built pipeline
/**
* Searches for an entry with the given key, adding and returning the result of calling
* `create` if the entry was not found.
* @param map the cache map
* @param key the entry's key
* @param create the function used to construct a value, if not found in the cache
* @returns the value, either fetched from the cache, or newly built.
*/
function getOrCreate(map, key, create) {
const existing = map.get(key);
if (existing !== undefined) {
return existing;
}
const value = create();
map.set(key, value);
return value;
}
/**
* Runs the list of expression tests, possibly splitting the tests into multiple
* dispatches to keep the input data within the buffer binding limits.
* run() will pack the scalar test cases into smaller set of vectorized tests
* if `cfg.vectorize` is defined.
* @param t the GPUTest
* @param shaderBuilder the shader builder function
* @param parameterTypes the list of expression parameter types
* @param resultType the return type for the expression overload
* @param cfg test configuration values
* @param cases list of test cases
* @param batch_size override the calculated casesPerBatch.
*/
export async function run(
t,
shaderBuilder,
parameterTypes,
resultType,
cfg = { inputSource: 'storage_r' },
cases,
batch_size)
{
// If the 'vectorize' config option was provided, pack the cases into vectors.
if (cfg.vectorize !== undefined) {
const packed = packScalarsToVector(parameterTypes, resultType, cases, cfg.vectorize);
cases = packed.cases;
parameterTypes = packed.parameterTypes;
resultType = packed.resultType;
}
// The size of the input buffer may exceed the maximum buffer binding size,
// so chunk the tests up into batches that fit into the limits. We also split
// the cases into smaller batches to help with shader compilation performance.
const casesPerBatch = function () {
if (batch_size) {
return batch_size;
}
switch (cfg.inputSource) {
case 'const':
// Some drivers are slow to optimize shaders with many constant values,
// or statements. 32 is an empirically picked number of cases that works
// well for most drivers.
return 32;
case 'uniform':
// Some drivers are slow to build pipelines with large uniform buffers.
// 2k appears to be a sweet-spot when benchmarking.
return Math.floor(
Math.min(1024 * 2, t.device.limits.maxUniformBufferBindingSize) /
valueStrides(parameterTypes)
);
case 'storage_r':
case 'storage_rw':
return Math.floor(
t.device.limits.maxStorageBufferBindingSize / valueStrides(parameterTypes)
);
}
}();
// A cache to hold built shader pipelines.
const pipelineCache = new Map();
// Submit all the cases in batches, rate-limiting to ensure not too many
// batches are in flight simultaneously.
const maxBatchesInFlight = 5;
let batchesInFlight = 0;
let resolvePromiseBlockingBatch = undefined;
const batchFinishedCallback = () => {
batchesInFlight -= 1;
// If there is any batch waiting on a previous batch to finish,
// unblock it now, and clear the resolve callback.
if (resolvePromiseBlockingBatch) {
resolvePromiseBlockingBatch();
resolvePromiseBlockingBatch = undefined;
}
};
const processBatch = async (batchCases) => {
const checkBatch = await submitBatch(
t,
shaderBuilder,
parameterTypes,
resultType,
batchCases,
cfg.inputSource,
pipelineCache
);
checkBatch();
void t.queue.onSubmittedWorkDone().finally(batchFinishedCallback);
};
const pendingBatches = [];
for (let i = 0; i < cases.length; i += casesPerBatch) {
const batchCases = cases.slice(i, Math.min(i + casesPerBatch, cases.length));
if (batchesInFlight > maxBatchesInFlight) {
await new Promise((resolve) => {
// There should only be one batch waiting at a time.
assert(resolvePromiseBlockingBatch === undefined);
resolvePromiseBlockingBatch = resolve;
});
}
batchesInFlight += 1;
pendingBatches.push(processBatch(batchCases));
}
await Promise.all(pendingBatches);
}
/**
* Submits the list of expression tests. The input data must fit within the
* buffer binding limits of the given inputSource.
* @param t the GPUTest
* @param shaderBuilder the shader builder function
* @param parameterTypes the list of expression parameter types
* @param resultType the return type for the expression overload
* @param cases list of test cases that fit within the binding limits of the device
* @param inputSource the source of the input values
* @param pipelineCache the cache of compute pipelines, shared between batches
* @returns a function that checks the results are as expected
*/
async function submitBatch(
t,
shaderBuilder,
parameterTypes,
resultType,
cases,
inputSource,
pipelineCache)
{
// Construct a buffer to hold the results of the expression tests
const outputBufferSize = cases.length * valueStride(resultType);
const outputBuffer = t.device.createBuffer({
size: outputBufferSize,
usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE
});
const [pipeline, group] = await buildPipeline(
t,
shaderBuilder,
parameterTypes,
resultType,
cases,
inputSource,
outputBuffer,
pipelineCache
);
const encoder = t.device.createCommandEncoder();
const pass = encoder.beginComputePass();
pass.setPipeline(pipeline);
pass.setBindGroup(0, group);
pass.dispatchWorkgroups(1);
pass.end();
// Heartbeat to ensure CTS runners know we're alive.
globalTestConfig.testHeartbeatCallback();
t.queue.submit([encoder.finish()]);
// Return a function that can check the results of the shader
return () => {
const checkExpectation = (outputData) => {
// Read the outputs from the output buffer
const outputs = new Array(cases.length);
for (let i = 0; i < cases.length; i++) {
outputs[i] = resultType.read(outputData, i * valueStride(resultType));
}
// The list of expectation failures
const errs = [];
// For each case...
for (let caseIdx = 0; caseIdx < cases.length; caseIdx++) {
const c = cases[caseIdx];
const got = outputs[caseIdx];
const cmp = toComparator(c.expected).compare(got);
if (!cmp.matched) {
errs.push(`(${c.input instanceof Array ? c.input.join(', ') : c.input})
returned: ${cmp.got}
expected: ${cmp.expected}`);
}
}
return errs.length > 0 ? new Error(errs.join('\n\n')) : undefined;
};
// Heartbeat to ensure CTS runners know we're alive.
globalTestConfig.testHeartbeatCallback();
t.expectGPUBufferValuesPassCheck(outputBuffer, checkExpectation, {
type: Uint8Array,
typedLength: outputBufferSize
});
};
}
/**
* map is a helper for returning a new array with each element of `v`
* transformed with `fn`.
* If `v` is not an array, then `fn` is called with (v, 0).
*/
function map(v, fn) {
if (v instanceof Array) {
return v.map(fn);
}
return [fn(v, 0)];
}
/**
* ShaderBuilder is a function used to construct the WGSL shader used by an
* expression test.
* @param parameterTypes the list of expression parameter types
* @param resultType the return type for the expression overload
* @param cases list of test cases that fit within the binding limits of the device
* @param inputSource the source of the input values
*/
/**
* Helper that returns the WGSL to declare the output storage buffer for a shader
*/
function wgslOutputs(resultType, count) {
let output_struct = undefined;
if (scalarTypeOf(resultType).kind !== 'abstract-float') {
output_struct = `
struct Output {
@size(${valueStride(resultType)}) value : ${storageType(resultType)}
};`;
} else {
if (resultType instanceof ScalarType) {
output_struct = `struct AF {
low: u32,
high: u32,
};
struct Output {
@size(${valueStride(resultType)}) value: AF,
};`;
}
if (resultType instanceof VectorType) {
const dim = resultType.width;
output_struct = `struct AF {
low: u32,
high: u32,
};
struct Output {
@size(${valueStride(resultType)}) value: array<AF, ${dim}>,
};`;
}
if (resultType instanceof MatrixType) {
const cols = resultType.cols;
const rows = resultType.rows === 2 ? 2 : 4; // 3 element rows have a padding element
output_struct = `struct AF {
low: u32,
high: u32,
};
struct Output {
@size(${valueStride(resultType)}) value: array<array<AF, ${rows}>, ${cols}>,
};`;
}
assert(output_struct !== undefined, `No implementation for result type '${resultType}'`);
}
return `${output_struct}
@group(0) @binding(0) var<storage, read_write> outputs : array<Output, ${count}>;
`;
}
/**
* Helper that returns the WGSL to declare the values array for a shader
*/
function wgslValuesArray(
parameterTypes,
resultType,
cases,
expressionBuilder)
{
return `
const values = array(
${cases.map((c) => expressionBuilder(map(c.input, (v) => v.wgsl()))).join(',\n ')}
);`;
}
/**
* Helper that returns the WGSL 'var' declaration for the given input source
*/
function wgslInputVar(inputSource, count) {
switch (inputSource) {
case 'storage_r':
return `@group(0) @binding(1) var<storage, read> inputs : array<Input, ${count}>;`;
case 'storage_rw':
return `@group(0) @binding(1) var<storage, read_write> inputs : array<Input, ${count}>;`;
case 'uniform':
return `@group(0) @binding(1) var<uniform> inputs : array<Input, ${count}>;`;
}
throw new Error(`InputSource ${inputSource} does not use an input var`);
}
/**
* Helper that returns the WGSL header before any other declaration, currently include f16
* enable directive if necessary.
*/
function wgslHeader(parameterTypes, resultType) {
const usedF16 =
scalarTypeOf(resultType).kind === 'f16' ||
parameterTypes.some((ty) => scalarTypeOf(ty).kind === 'f16');
const header = usedF16 ? 'enable f16;\n' : '';
return header;
}
/**
* ExpressionBuilder returns the WGSL used to evaluate an expression with the
* given input values.
*/
/**
* Returns a ShaderBuilder that builds a basic expression test shader.
* @param expressionBuilder the expression builder
*/
function basicExpressionShaderBody(
expressionBuilder,
parameterTypes,
resultType,
cases,
inputSource)
{
assert(
scalarTypeOf(resultType).kind !== 'abstract-float',
`abstractFloatShaderBuilder should be used when result type is 'abstract-float`
);
if (inputSource === 'const') {
//////////////////////////////////////////////////////////////////////////
// Constant eval
//////////////////////////////////////////////////////////////////////////
let body = '';
if (parameterTypes.some((ty) => scalarTypeOf(ty).kind === 'abstract-float')) {
// Directly assign the expression to the output, to avoid an
// intermediate store, which will concretize the value early
body = cases.
map(
(c, i) =>
` outputs[${i}].value = ${toStorage(
resultType,
expressionBuilder(map(c.input, (v) => v.wgsl()))
)};`
).
join('\n ');
} else if (globalTestConfig.unrollConstEvalLoops) {
body = cases.
map((_, i) => {
const value = `values[${i}]`;
return ` outputs[${i}].value = ${toStorage(resultType, value)};`;
}).
join('\n ');
} else {
body = `
for (var i = 0u; i < ${cases.length}; i++) {
outputs[i].value = ${toStorage(resultType, `values[i]`)};
}`;
}
return `
${wgslOutputs(resultType, cases.length)}
${wgslValuesArray(parameterTypes, resultType, cases, expressionBuilder)}
@compute @workgroup_size(1)
fn main() {
${body}
}`;
} else {
//////////////////////////////////////////////////////////////////////////
// Runtime eval
//////////////////////////////////////////////////////////////////////////
// returns the WGSL expression to load the ith parameter of the given type from the input buffer
const paramExpr = (ty, i) => fromStorage(ty, `inputs[i].param${i}`);
// resolves to the expression that calls the builtin
const expr = toStorage(resultType, expressionBuilder(parameterTypes.map(paramExpr)));
return `
struct Input {
${parameterTypes.
map((ty, i) => ` @size(${valueStride(ty)}) param${i} : ${storageType(ty)},`).
join('\n')}
};
${wgslOutputs(resultType, cases.length)}
${wgslInputVar(inputSource, cases.length)}
@compute @workgroup_size(1)
fn main() {
for (var i = 0; i < ${cases.length}; i++) {
outputs[i].value = ${expr};
}
}
`;
}
}
/**
* Returns a ShaderBuilder that builds a basic expression test shader.
* @param expressionBuilder the expression builder
*/
export function basicExpressionBuilder(expressionBuilder) {
return (
parameterTypes,
resultType,
cases,
inputSource) =>
{
return `\
${wgslHeader(parameterTypes, resultType)}
${basicExpressionShaderBody(expressionBuilder, parameterTypes, resultType, cases, inputSource)}`;
};
}
/**
* Returns a ShaderBuilder that builds a basic expression test shader with given predeclaration
* string goes after WGSL header (i.e. enable directives) if any but before anything else.
* @param expressionBuilder the expression builder
* @param predeclaration the predeclaration string
*/
export function basicExpressionWithPredeclarationBuilder(
expressionBuilder,
predeclaration)
{
return (
parameterTypes,
resultType,
cases,
inputSource) =>
{
return `\
${wgslHeader(parameterTypes, resultType)}
${predeclaration}
${basicExpressionShaderBody(expressionBuilder, parameterTypes, resultType, cases, inputSource)}`;
};
}
/**
* Returns a ShaderBuilder that builds a compound assignment operator test shader.
* @param op the compound operator
*/
export function compoundAssignmentBuilder(op) {
return (
parameterTypes,
resultType,
cases,
inputSource) =>
{
//////////////////////////////////////////////////////////////////////////
// Input validation
//////////////////////////////////////////////////////////////////////////
if (parameterTypes.length !== 2) {
throw new Error(`compoundBinaryOp() requires exactly two parameters values per case`);
}
const lhsType = parameterTypes[0];
const rhsType = parameterTypes[1];
if (!objectEquals(lhsType, resultType)) {
throw new Error(
`compoundBinaryOp() requires result type (${resultType}) to be equal to the LHS type (${lhsType})`
);
}
if (inputSource === 'const') {
//////////////////////////////////////////////////////////////////////////
// Constant eval
//////////////////////////////////////////////////////////////////////////
let body = '';
if (globalTestConfig.unrollConstEvalLoops) {
body = cases.
map((_, i) => {
return `
var ret_${i} = lhs[${i}];
ret_${i} ${op} rhs[${i}];
outputs[${i}].value = ${storageType(resultType)}(ret_${i});`;
}).
join('\n ');
} else {
body = `
for (var i = 0u; i < ${cases.length}; i++) {
var ret = lhs[i];
ret ${op} rhs[i];
outputs[i].value = ${storageType(resultType)}(ret);
}`;
}
const values = cases.map((c) => c.input.map((v) => v.wgsl()));
return `
${wgslHeader(parameterTypes, resultType)}
${wgslOutputs(resultType, cases.length)}
const lhs = array(
${values.map((c) => `${c[0]}`).join(',\n ')}
);
const rhs = array(
${values.map((c) => `${c[1]}`).join(',\n ')}
);
@compute @workgroup_size(1)
fn main() {
${body}
}`;
} else {
//////////////////////////////////////////////////////////////////////////
// Runtime eval
//////////////////////////////////////////////////////////////////////////
return `
${wgslHeader(parameterTypes, resultType)}
${wgslOutputs(resultType, cases.length)}
struct Input {
@size(${valueStride(lhsType)}) lhs : ${storageType(lhsType)},
@size(${valueStride(rhsType)}) rhs : ${storageType(rhsType)},
}
${wgslInputVar(inputSource, cases.length)}
@compute @workgroup_size(1)
fn main() {
for (var i = 0; i < ${cases.length}; i++) {
var ret = ${lhsType}(inputs[i].lhs);
ret ${op} ${rhsType}(inputs[i].rhs);
outputs[i].value = ${storageType(resultType)}(ret);
}
}
`;
}
};
}
/**
* @returns a string that extracts the value of an AbstractFloat into an output
* destination
* @param expr expression for an AbstractFloat value, if working with vectors or
* matrices, this string needs to include indexing into the
* container.
* @param case_idx index in the case output array to assign the result
* @param accessor string representing how access to the AF that needs to be
* operated on.
* For scalars this should be left as ''.
* For vectors this will be an indexing operation,
* i.e. '[i]'
* For matrices this will double indexing operation,
* i.e. '[c][r]'
*/
function abstractFloatSnippet(expr, case_idx, accessor = '') {
// AbstractFloats are f64s under the hood. WebGPU does not support
// putting f64s in buffers, so the result needs to be split up into u32s
// and rebuilt in the test framework.
//
// Since there is no 64-bit data type that can be used as an element for a
// vector or a matrix in WGSL, the testing framework needs to pass the u32s
// via a struct with two u32s, and deconstruct vectors and matrices into
// arrays.
//
// This is complicated by the fact that user defined functions cannot
// take/return AbstractFloats, and AbstractFloats cannot be stored in
// variables, so the code cannot just inject a simple utility function
// at the top of the shader, instead this snippet needs to be inlined
// everywhere the test needs to return an AbstractFloat.
//
// select is used below, since ifs are not available during constant
// eval. This has the side effect of short-circuiting doesn't occur, so
// both sides of the select have to evaluate and be valid.
//
// This snippet implements FTZ for subnormals to bypass the need for
// complex subnormal specific logic.
//
// Expressions resulting in subnormals can still be reasonably tested,
// since this snippet will return 0 with the correct sign, which is
// always in the acceptance interval for a subnormal result, since an
// implementation may FTZ.
//
// Documentation for the snippet working with scalar results is included here
// in this code block, since shader length affects compilation time
// significantly on some backends. The code for vectors and matrices basically
// the same thing, with extra indexing operations.
//
// Snippet with documentation:
// const kExponentBias = 1022;
//
// // Detect if the value is zero or subnormal, so that FTZ behaviour
// // can occur
// const subnormal_or_zero : bool = (${expr} <= ${kValue.f64.positive.subnormal.max}) && (${expr} >= ${kValue.f64.negative.subnormal.min});
//
// // MSB of the upper u32 is 1 if the value is negative, otherwise 0
// // Extract the sign bit early, so that abs() can be used with
// // frexp() so negative cases do not need to be handled
// const sign_bit : u32 = select(0, 0x80000000, ${expr} < 0);
//
// // Use frexp() to obtain the exponent and fractional parts, and
// // then perform FTZ if needed
// const f = frexp(abs(${expr}));
// const f_fract = select(f.fract, 0, subnormal_or_zero);
// const f_exp = select(f.exp, -kExponentBias, subnormal_or_zero);
//
// // Adjust for the exponent bias and shift for storing in bits
// // [20..31] of the upper u32
// const exponent_bits : u32 = (f_exp + kExponentBias) << 20;
//
// // Extract the portion of the mantissa that appears in upper u32 as
// // a float for later use
// const high_mantissa = ldexp(f_fract, 21);
//
// // Extract the portion of the mantissa that appears in upper u32 as
// // as bits. This value is masked, because normals will explicitly
// // have the implicit leading 1 that should not be in the final
// // result.
// const high_mantissa_bits : u32 = u32(ldexp(f_fract, 21)) & 0x000fffff;
//
// // Calculate the mantissa stored in the lower u32 as a float
// const low_mantissa = f_fract - ldexp(floor(high_mantissa), -21);
//
// // Convert the lower u32 mantissa to bits
// const low_mantissa_bits = u32(ldexp(low_mantissa, 53));
//
// outputs[${i}].value.high = sign_bit | exponent_bits | high_mantissa_bits;
// outputs[${i}].value.low = low_mantissa_bits;
return ` {
const kExponentBias = 1022;
const subnormal_or_zero : bool = (${expr}${accessor} <= ${kValue.f64.positive.subnormal.max}) && (${expr}${accessor} >= ${kValue.f64.negative.subnormal.min});
const sign_bit : u32 = select(0, 0x80000000, ${expr}${accessor} < 0);
const f = frexp(abs(${expr}${accessor}));
const f_fract = select(f.fract, 0, subnormal_or_zero);
const f_exp = select(f.exp, -kExponentBias, subnormal_or_zero);
const exponent_bits : u32 = (f_exp + kExponentBias) << 20;
const high_mantissa = ldexp(f_fract, 21);
const high_mantissa_bits : u32 = u32(ldexp(f_fract, 21)) & 0x000fffff;
const low_mantissa = f_fract - ldexp(floor(high_mantissa), -21);
const low_mantissa_bits = u32(ldexp(low_mantissa, 53));
outputs[${case_idx}].value${accessor}.high = sign_bit | exponent_bits | high_mantissa_bits;
outputs[${case_idx}].value${accessor}.low = low_mantissa_bits;
}`;
}
/** @returns a string for a specific case that has a AbstractFloat result */
function abstractFloatCaseBody(expr, resultType, i) {
if (resultType instanceof ScalarType) {
return abstractFloatSnippet(expr, i);
}
if (resultType instanceof VectorType) {
return [...Array(resultType.width).keys()].
map((idx) => abstractFloatSnippet(expr, i, `[${idx}]`)).
join(' \n');
}
if (resultType instanceof MatrixType) {
const cols = resultType.cols;
const rows = resultType.rows;
const results = [...Array(cols * rows)];
for (let c = 0; c < cols; c++) {
for (let r = 0; r < rows; r++) {
results[c * rows + r] = abstractFloatSnippet(expr, i, `[${c}][${r}]`);
}
}
return results.join(' \n');
}
unreachable(`Results of type '${resultType}' not yet implemented`);
}
/**
* @returns a ShaderBuilder that builds a test shader hands AbstractFloat results.
* @param expressionBuilder an expression builder that will return AbstractFloats
*/
export function abstractFloatShaderBuilder(expressionBuilder) {
return (
parameterTypes,
resultType,
cases,
inputSource) =>
{
assert(inputSource === 'const', 'AbstractFloat results are only defined for const-eval');
assert(
scalarTypeOf(resultType).kind === 'abstract-float',
`Expected resultType of 'abstract-float', received '${scalarTypeOf(resultType).kind}' instead`
);
const body = cases.
map((c, i) => {
const expr = `${expressionBuilder(map(c.input, (v) => v.wgsl()))}`;
return abstractFloatCaseBody(expr, resultType, i);
}).
join('\n ');
return `
${wgslHeader(parameterTypes, resultType)}
${wgslOutputs(resultType, cases.length)}
@compute @workgroup_size(1)
fn main() {
${body}
}`;
};
}
/**
* Constructs and returns a GPUComputePipeline and GPUBindGroup for running a
* batch of test cases. If a pre-created pipeline can be found in
* `pipelineCache`, then this may be returned instead of creating a new
* pipeline.
* @param t the GPUTest
* @param shaderBuilder the shader builder
* @param parameterTypes the list of expression parameter types
* @param resultType the return type for the expression overload
* @param cases list of test cases that fit within the binding limits of the device
* @param inputSource the source of the input values
* @param outputBuffer the buffer that will hold the output values of the tests
* @param pipelineCache the cache of compute pipelines, shared between batches
*/
async function buildPipeline(
t,
shaderBuilder,
parameterTypes,
resultType,
cases,
inputSource,
outputBuffer,
pipelineCache)
{
cases.forEach((c) => {
const inputTypes = c.input instanceof Array ? c.input.map((i) => i.type) : [c.input.type];
if (!objectEquals(inputTypes, parameterTypes)) {
const input_str = `[${inputTypes.join(',')}]`;
const param_str = `[${parameterTypes.join(',')}]`;
throw new Error(
`case input types ${input_str} do not match provided runner parameter types ${param_str}`
);
}
});
const source = shaderBuilder(parameterTypes, resultType, cases, inputSource);
switch (inputSource) {
case 'const':{
// build the shader module
const module = t.device.createShaderModule({ code: source });
// build the pipeline
const pipeline = await t.device.createComputePipelineAsync({
layout: 'auto',
compute: { module, entryPoint: 'main' }
});
// build the bind group
const group = t.device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: outputBuffer } }]
});
return [pipeline, group];
}
case 'uniform':
case 'storage_r':
case 'storage_rw':{
// Input values come from a uniform or storage buffer
// size in bytes of the input buffer
const inputSize = cases.length * valueStrides(parameterTypes);
// Holds all the parameter values for all cases
const inputData = new Uint8Array(inputSize);
// Pack all the input parameter values into the inputData buffer
{
const caseStride = valueStrides(parameterTypes);
for (let caseIdx = 0; caseIdx < cases.length; caseIdx++) {
const caseBase = caseIdx * caseStride;
let offset = caseBase;
for (let paramIdx = 0; paramIdx < parameterTypes.length; paramIdx++) {
const params = cases[caseIdx].input;
if (params instanceof Array) {
params[paramIdx].copyTo(inputData, offset);
} else {
params.copyTo(inputData, offset);
}
offset += valueStride(parameterTypes[paramIdx]);
}
}
}
// build the compute pipeline, if the shader hasn't been compiled already.
const pipeline = getOrCreate(pipelineCache, source, () => {
// build the shader module
const module = t.device.createShaderModule({ code: source });
// build the pipeline
return t.device.createComputePipeline({
layout: 'auto',
compute: { module, entryPoint: 'main' }
});
});
// build the input buffer
const inputBuffer = t.makeBufferWithContents(
inputData,
GPUBufferUsage.COPY_SRC | (
inputSource === 'uniform' ? GPUBufferUsage.UNIFORM : GPUBufferUsage.STORAGE)
);
// build the bind group
const group = t.device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: outputBuffer } },
{ binding: 1, resource: { buffer: inputBuffer } }]
});
return [pipeline, group];
}
}
}
/**
* Packs a list of scalar test cases into a smaller list of vector cases.
* Requires that all parameters of the expression overload are of a scalar type,
* and the return type of the expression overload is also a scalar type.
* If `cases.length` is not a multiple of `vectorWidth`, then the last scalar
* test case value is repeated to fill the vector value.
*/
function packScalarsToVector(
parameterTypes,
resultType,
cases,
vectorWidth)
{
// Validate that the parameters and return type are all vectorizable
for (let i = 0; i < parameterTypes.length; i++) {
const ty = parameterTypes[i];
if (!(ty instanceof ScalarType)) {
throw new Error(
`packScalarsToVector() can only be used on scalar parameter types, but the ${i}'th parameter type is a ${ty}'`
);
}
}
if (!(resultType instanceof ScalarType)) {
throw new Error(
`packScalarsToVector() can only be used with a scalar return type, but the return type is a ${resultType}'`
);
}
const packedCases = [];
const packedParameterTypes = parameterTypes.map((p) => TypeVec(vectorWidth, p));
const packedResultType = new VectorType(vectorWidth, resultType);
const clampCaseIdx = (idx) => Math.min(idx, cases.length - 1);
let caseIdx = 0;
while (caseIdx < cases.length) {
// Construct the vectorized inputs from the scalar cases
const packedInputs = new Array(parameterTypes.length);
for (let paramIdx = 0; paramIdx < parameterTypes.length; paramIdx++) {
const inputElements = new Array(vectorWidth);
for (let i = 0; i < vectorWidth; i++) {
const input = cases[clampCaseIdx(caseIdx + i)].input;
inputElements[i] = input instanceof Array ? input[paramIdx] : input;
}
packedInputs[paramIdx] = new Vector(inputElements);
}
// Gather the comparators for the packed cases
const cmp_impls = new Array(vectorWidth);
for (let i = 0; i < vectorWidth; i++) {
cmp_impls[i] = toComparator(cases[clampCaseIdx(caseIdx + i)].expected).compare;
}
const comparators = {
compare: (got) => {
let matched = true;
const gElements = new Array(vectorWidth);
const eElements = new Array(vectorWidth);
for (let i = 0; i < vectorWidth; i++) {
const d = cmp_impls[i](got.elements[i]);
matched = matched && d.matched;
gElements[i] = d.got;
eElements[i] = d.expected;
}
return {
matched,
got: `${packedResultType}(${gElements.join(', ')})`,
expected: `${packedResultType}(${eElements.join(', ')})`
};
},
kind: 'packed'
};
// Append the new packed case
packedCases.push({ input: packedInputs, expected: comparators });
caseIdx += vectorWidth;
}
return {
cases: packedCases,
parameterTypes: packedParameterTypes,
resultType: packedResultType
};
}
/**
* Indicates bounds that acceptance intervals need to be within to avoid inputs
* being filtered out. This is used for const-eval tests, since going OOB will
* cause a validation error not an execution error.
*/
// No expectations
/**
* A function that performs a binary operation on x and y, and returns the expected
* result.
*/
/**
* @returns array of Case for the input params with op applied
* @param param0s array of inputs to try for the first param
* @param param1s array of inputs to try for the second param
* @param op callback called on each pair of inputs to produce each case
* @param quantize function to quantize all values
* @param scalarize function to convert numbers to Scalars
*/
function generateScalarBinaryToScalarCases(
param0s,
param1s,
op,
quantize,
scalarize)
{
param0s = param0s.map(quantize);
param1s = param1s.map(quantize);
return cartesianProduct(param0s, param1s).reduce((cases, e) => {
const expected = op(e[0], e[1]);
if (expected !== undefined) {
cases.push({ input: [scalarize(e[0]), scalarize(e[1])], expected: scalarize(expected) });
}
return cases;
}, new Array());
}
/**
* @returns an array of Cases for operations over a range of inputs
* @param param0s array of inputs to try for the first param
* @param param1s array of inputs to try for the second param
* @param op callback called on each pair of inputs to produce each case
*/
export function generateBinaryToI32Cases(
param0s,
param1s,
op)
{
return generateScalarBinaryToScalarCases(param0s, param1s, op, quantizeToI32, i32);
}
/**
* @returns an array of Cases for operations over a range of inputs
* @param param0s array of inputs to try for the first param
* @param param1s array of inputs to try for the second param
* @param op callback called on each pair of inputs to produce each case
*/
export function generateBinaryToU32Cases(
param0s,
param1s,
op)
{
return generateScalarBinaryToScalarCases(param0s, param1s, op, quantizeToU32, u32);
}
/**
* @returns a Case for the input params with op applied
* @param scalar scalar param
* @param vector vector param (2, 3, or 4 elements)
* @param op the op to apply to scalar and vector
* @param quantize function to quantize all values in vectors and scalars
* @param scalarize function to convert numbers to Scalars
*/
function makeScalarVectorBinaryToVectorCase(
scalar,
vector,
op,
quantize,
scalarize)
{
scalar = quantize(scalar);
vector = vector.map(quantize);
const result = vector.map((v) => op(scalar, v));
if (result.includes(undefined)) {
return undefined;
}
return {
input: [scalarize(scalar), new Vector(vector.map(scalarize))],
expected: new Vector(result.map(scalarize))
};
}
/**
* @returns array of Case for the input params with op applied
* @param scalars array of scalar params
* @param vectors array of vector params (2, 3, or 4 elements)
* @param op the op to apply to each pair of scalar and vector
* @param quantize function to quantize all values in vectors and scalars
* @param scalarize function to convert numbers to Scalars
*/
function generateScalarVectorBinaryToVectorCases(
scalars,
vectors,
op,
quantize,
scalarize)
{
const cases = new Array();
scalars.forEach((s) => {
vectors.forEach((v) => {
const c = makeScalarVectorBinaryToVectorCase(s, v, op, quantize, scalarize);
if (c !== undefined) {
cases.push(c);
}
});
});
return cases;
}
/**
* @returns a Case for the input params with op applied
* @param vector vector param (2, 3, or 4 elements)
* @param scalar scalar param
* @param op the op to apply to vector and scalar
* @param quantize function to quantize all values in vectors and scalars
* @param scalarize function to convert numbers to Scalars
*/
function makeVectorScalarBinaryToVectorCase(
vector,
scalar,
op,
quantize,
scalarize)
{
vector = vector.map(quantize);
scalar = quantize(scalar);
const result = vector.map((v) => op(v, scalar));
if (result.includes(undefined)) {
return undefined;
}
return {
input: [new Vector(vector.map(scalarize)), scalarize(scalar)],
expected: new Vector(result.map(scalarize))
};
}
/**
* @returns array of Case for the input params with op applied
* @param vectors array of vector params (2, 3, or 4 elements)
* @param scalars array of scalar params
* @param op the op to apply to each pair of vector and scalar
* @param quantize function to quantize all values in vectors and scalars
* @param scalarize function to convert numbers to Scalars
*/
function generateVectorScalarBinaryToVectorCases(
vectors,
scalars,
op,
quantize,
scalarize)
{
const cases = new Array();
scalars.forEach((s) => {
vectors.forEach((v) => {
const c = makeVectorScalarBinaryToVectorCase(v, s, op, quantize, scalarize);
if (c !== undefined) {
cases.push(c);
}
});
});
return cases;
}
/**
* @returns array of Case for the input params with op applied
* @param scalars array of scalar params
* @param vectors array of vector params (2, 3, or 4 elements)
* @param op he op to apply to each pair of scalar and vector
*/
export function generateU32VectorBinaryToVectorCases(
scalars,
vectors,
op)
{
return generateScalarVectorBinaryToVectorCases(scalars, vectors, op, quantizeToU32, u32);
}
/**
* @returns array of Case for the input params with op applied
* @param vectors array of vector params (2, 3, or 4 elements)
* @param scalars array of scalar params
* @param op he op to apply to each pair of vector and scalar
*/
export function generateVectorU32BinaryToVectorCases(
vectors,
scalars,
op)
{
return generateVectorScalarBinaryToVectorCases(vectors, scalars, op, quantizeToU32, u32);
}
/**
* @returns array of Case for the input params with op applied
* @param scalars array of scalar params
* @param vectors array of vector params (2, 3, or 4 elements)
* @param op he op to apply to each pair of scalar and vector
*/
export function generateI32VectorBinaryToVectorCases(
scalars,
vectors,
op)
{
return generateScalarVectorBinaryToVectorCases(scalars, vectors, op, quantizeToI32, i32);
}
/**
* @returns array of Case for the input params with op applied
* @param vectors array of vector params (2, 3, or 4 elements)
* @param scalars array of scalar params
* @param op he op to apply to each pair of vector and scalar
*/
export function generateVectorI32BinaryToVectorCases(
vectors,
scalars,
op)
{
return generateVectorScalarBinaryToVectorCases(vectors, scalars, op, quantizeToI32, i32);
}
|