-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtf-backend-webgpu.js
14413 lines (14111 loc) · 792 KB
/
tf-backend-webgpu.js
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
/**
* @license
* Copyright 2023 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tensorflow/tfjs-core')) :
typeof define === 'function' && define.amd ? define(['exports', '@tensorflow/tfjs-core'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.tf = global.tf || {}, global.tf));
})(this, (function (exports, tf) { 'use strict';
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return n;
}
var tf__namespace = /*#__PURE__*/_interopNamespaceDefault(tf);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (Object.prototype.hasOwnProperty.call(b, p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var ENV = tf.env();
/** The batched dispatching calls size in the device queue. */
ENV.registerFlag('WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE', function () { return 15; });
/**
* Whether we forward execution to the CPU backend if tensors are small and
* reside on the CPU.
*/
ENV.registerFlag('WEBGPU_CPU_FORWARD', function () { return true; });
/**
* This flag is used to test different types of matmul programs.
*
* See MatMulProgramType in webgpu_util.ts for a list of available values.
*/
ENV.registerFlag('WEBGPU_MATMUL_PROGRAM_TYPE', function () { return -1; });
/**
* Whether to use conv2dTranspose_naive which directly implement the
* conv2dTranspose logic rather than using a matmul to simulate.
*/
ENV.registerFlag('WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE', function () { return true; });
/**
* Whether we use low power GPU. Otherwise, a high performance GPU will be
* requested.
*/
ENV.registerFlag('WEBGPU_USE_LOW_POWER_GPU', function () { return false; });
/**
* Threshold for input tensor size that determines whether WebGPU backend will
* delegate computation to CPU.
*
* Default value is 1000.
*/
ENV.registerFlag('WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD', function () { return 1000; });
/**
* Whether to use a dummy canvas to make profiling tools like PIX work with
* TFJS webgpu backend.
*/
ENV.registerFlag('WEBGPU_USE_PROFILE_TOOL', function () { return false; });
/**
* Whether to use import API.
*/
ENV.registerFlag('WEBGPU_IMPORT_EXTERNAL_TEXTURE', function () { return true; });
/**
* Whether to use conv2dNaive for debugging.
*/
ENV.registerFlag('WEBGPU_USE_NAIVE_CONV2D_DEBUG', function () { return false; });
/**
* Threshold to increase dispatched workgroups for matmul. If too few workgroups
* are dispatched, it means the hardware may be in low occupancy.
* -1 means it's not set by the user. A default strategy will be applied.
*/
ENV.registerFlag('WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL', function () { return -1; });
/**
* Whether we will run im2col as a separate shader for convolution.
*/
ENV.registerFlag('WEBGPU_CONV_SEPARATE_IM2COL_SHADER', function () { return false; });
/**
* A string used to match shader key. If any matches, print the related shader.
* Seperated by comma. 'all' to print all. 'binary' to print binary(add, mul,
* etc.). 'unary,conv2d' to print both unary and conv2d.
*/
ENV.registerFlag('WEBGPU_PRINT_SHADER', function () { return ''; });
/** Experimental flag, whether enter compile only phase. */
ENV.registerFlag('WEBGPU_ENGINE_COMPILE_ONLY', function () { return false; });
/**
* @license
* Copyright 2022 Google LLC.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var AdapterInfo = /** @class */ (function () {
function AdapterInfo(adapterInfo) {
if (adapterInfo) {
this.vendor = adapterInfo.vendor;
this.architecture = adapterInfo.architecture;
this.intelGPUGeneration = this.getIntelGPUGeneration();
}
}
AdapterInfo.prototype.getIntelGPUGeneration = function () {
if (this.isIntel()) {
if (this.architecture.startsWith('gen')) {
return Number(this.architecture.match(/\d+/));
}
else if (this.architecture.startsWith('xe')) {
return 12;
}
}
return 0;
};
AdapterInfo.prototype.isIntel = function () {
return this.vendor === 'intel';
};
return AdapterInfo;
}());
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var BufferManager = /** @class */ (function () {
function BufferManager(device) {
this.device = device;
this.numUsedBuffers = 0;
this.numFreeBuffers = 0;
this.freeBuffers = new Map();
this.usedBuffers = new Map();
this.numBytesUsed = 0;
this.numBytesAllocated = 0;
}
BufferManager.prototype.acquireBuffer = function (size, usage, mappedAtCreation, reuse) {
if (mappedAtCreation === void 0) { mappedAtCreation = false; }
if (reuse === void 0) { reuse = true; }
var buffer;
var key = getBufferKey(size, usage);
if (reuse) {
if (!this.freeBuffers.has(key)) {
this.freeBuffers.set(key, []);
}
if (this.freeBuffers.get(key).length > 0) {
buffer = this.freeBuffers.get(key).pop();
this.numFreeBuffers--;
}
else {
buffer = this.device.createBuffer({ size: size, usage: usage, mappedAtCreation: mappedAtCreation });
this.numBytesAllocated += size;
}
}
else {
buffer = this.device.createBuffer({ size: size, usage: usage, mappedAtCreation: mappedAtCreation });
this.numBytesAllocated += size;
}
if (!this.usedBuffers.has(key)) {
this.usedBuffers.set(key, []);
}
this.usedBuffers.get(key).push(buffer);
this.numUsedBuffers++;
this.numBytesUsed += size;
return buffer;
};
BufferManager.prototype.releaseBuffer = function (buffer, reuse) {
if (reuse === void 0) { reuse = true; }
if (this.freeBuffers.size === 0) {
return;
}
var size = buffer.size;
var usage = buffer.usage;
var key = getBufferKey(size, usage);
var bufferArray = this.usedBuffers.get(key);
var index = bufferArray.indexOf(buffer);
if (index < 0) {
throw new Error('Cannot find the buffer in buffer manager');
}
bufferArray[index] = bufferArray[bufferArray.length - 1];
bufferArray.pop();
this.numUsedBuffers--;
this.numBytesUsed -= size;
if (reuse) {
this.freeBuffers.get(key).push(buffer);
this.numFreeBuffers++;
}
else {
buffer.destroy();
this.numBytesAllocated -= size;
}
};
BufferManager.prototype.getNumUsedBuffers = function () {
return this.numUsedBuffers;
};
BufferManager.prototype.getNumFreeBuffers = function () {
return this.numFreeBuffers;
};
BufferManager.prototype.dispose = function () {
this.freeBuffers.forEach(function (buffers, key) {
buffers.forEach(function (buffer) {
buffer.destroy();
});
});
this.usedBuffers.forEach(function (buffers, key) {
buffers.forEach(function (buffer) {
buffer.destroy();
});
});
this.freeBuffers = new Map();
this.usedBuffers = new Map();
this.numUsedBuffers = 0;
this.numFreeBuffers = 0;
this.numBytesUsed = 0;
this.numBytesAllocated = 0;
};
return BufferManager;
}());
function getBufferKey(size, usage) {
return "".concat(size, "_").concat(usage);
}
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var TextureManager = /** @class */ (function () {
function TextureManager(device) {
this.device = device;
this.numUsedTextures = 0;
this.numFreeTextures = 0;
this.freeTextures = new Map();
this.usedTextures = new Map();
this.numBytesUsed = 0;
this.numBytesAllocated = 0;
}
TextureManager.prototype.acquireTexture = function (width, height, format, usage) {
var bytesPerElement = getBytesPerElement(format);
var byteSize = width * height * bytesPerElement;
var key = getTextureKey(width, height, format, usage);
if (!this.freeTextures.has(key)) {
this.freeTextures.set(key, []);
}
if (!this.usedTextures.has(key)) {
this.usedTextures.set(key, []);
}
this.numBytesUsed += byteSize;
this.numUsedTextures++;
if (this.freeTextures.get(key).length > 0) {
this.numFreeTextures--;
var newTexture_1 = this.freeTextures.get(key).shift();
this.usedTextures.get(key).push(newTexture_1);
return newTexture_1;
}
this.numBytesAllocated += byteSize;
var newTexture = this.device.createTexture({
size: [width, height],
format: format,
usage: usage,
});
this.usedTextures.get(key).push(newTexture);
return newTexture;
};
TextureManager.prototype.releaseTexture = function (texture) {
if (this.freeTextures.size === 0) {
return;
}
var width = texture.width;
var height = texture.height;
var format = texture.format;
var usage = texture.usage;
var key = getTextureKey(width, height, format, usage);
if (!this.freeTextures.has(key)) {
this.freeTextures.set(key, []);
}
this.freeTextures.get(key).push(texture);
this.numFreeTextures++;
this.numUsedTextures--;
var textureList = this.usedTextures.get(key);
var textureIndex = textureList.indexOf(texture);
if (textureIndex < 0) {
throw new Error('Cannot release a texture that was never provided by this ' +
'texture manager');
}
textureList.splice(textureIndex, 1);
var bytesPerElement = getBytesPerElement(format);
var byteSize = width * height * bytesPerElement;
this.numBytesUsed -= byteSize;
};
TextureManager.prototype.getNumUsedTextures = function () {
return this.numUsedTextures;
};
TextureManager.prototype.getNumFreeTextures = function () {
return this.numFreeTextures;
};
TextureManager.prototype.dispose = function () {
this.freeTextures.forEach(function (textures, key) {
textures.forEach(function (texture) {
texture.destroy();
});
});
this.usedTextures.forEach(function (textures, key) {
textures.forEach(function (texture) {
texture.destroy();
});
});
this.freeTextures = new Map();
this.usedTextures = new Map();
this.numUsedTextures = 0;
this.numFreeTextures = 0;
this.numBytesUsed = 0;
this.numBytesAllocated = 0;
};
return TextureManager;
}());
function getTextureKey(width, height, format, usage) {
return "".concat(width, "_").concat(height, "_").concat(format, "_").concat(usage);
}
function getBytesPerElement(format) {
if (format === 'rgba8unorm') {
return 16;
}
else {
throw new Error("".concat(format, " is not supported!"));
}
}
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Generates WGSL that computes strides.
function symbolicallyComputeStrides(indicesArr, variableName) {
if (Math.max.apply(Math, __spreadArray([], __read(indicesArr), false)) > 5) {
throw new Error('Cannot symbolically compute strides for rank > 6 tensor.');
}
var numCoords = indicesArr.length;
var indicesStr = 'xyzwuv';
var shape = indicesArr.map(function (d) { return "".concat(variableName, ".").concat(indicesStr[d]); });
var strides = new Array(numCoords - 1);
strides[numCoords - 2] = shape[numCoords - 1];
for (var i = numCoords - 3; i >= 0; --i) {
strides[i] = "(".concat(strides[i + 1], " * ").concat(shape[i + 1], ")");
}
return strides;
}
var atomicAddSnippet = function (ptr, v, type) {
if (type === 'int32') {
return "atomicAdd(".concat(ptr, ", bitcast<i32>(").concat(v, "));");
}
else {
// atomicAdd only supports uint/int type. For float, we use
// atomicCompareExchangeWeak to simulate.
return "\n {\n var oldValue = 0;\n loop {\n let newValueF32 = bitcast<f32>(oldValue) + (".concat(v, ");\n let newValue = bitcast<i32>(newValueF32);\n let res = atomicCompareExchangeWeak(").concat(ptr, ", oldValue, newValue);\n if res.exchanged {\n break;\n }\n oldValue = res.old_value;\n }\n }");
}
};
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
var PixelsOpType;
(function (PixelsOpType) {
PixelsOpType[PixelsOpType["FROM_PIXELS"] = 0] = "FROM_PIXELS";
PixelsOpType[PixelsOpType["DRAW"] = 1] = "DRAW";
})(PixelsOpType || (PixelsOpType = {}));
var compileProgram = function (device, program, inputsData, output, parallelCompilation) {
var outputData = { dtype: output.dtype, shape: output.shape };
var source = makeShader(inputsData, outputData, program);
var module = device.createShaderModule({ code: source, label: program.constructor.name });
var printShaderString = tf.env().get('WEBGPU_PRINT_SHADER');
if (printShaderString !== '') {
printShaderString = printShaderString.toLowerCase();
var printShaderArray = printShaderString.split(',');
if (printShaderString === 'all' ||
printShaderArray.some(function (item) { return program.shaderKey.toLowerCase().includes(item); })) {
console.group(program.shaderKey);
console.debug(source);
console.groupEnd();
}
}
if (parallelCompilation) {
return device.createComputePipelineAsync({
compute: { module: module, entryPoint: '_start' },
label: program.constructor.name,
layout: 'auto'
});
}
else {
return device.createComputePipeline({
compute: { module: module, entryPoint: '_start' },
label: program.constructor.name,
layout: 'auto'
});
}
};
var typeSnippet = function (component, type) {
if (type === void 0) { type = 'f32'; }
switch (component) {
case 1:
return "".concat(type);
case 2:
return "vec2<".concat(type, ">");
case 3:
return "vec3<".concat(type, ">");
case 4:
return "vec4<".concat(type, ">");
default:
throw new Error("".concat(component, "-component ").concat(type, " is not supported."));
}
};
function getCoordsDataType(rank) {
if (rank <= 1) {
return 'i32';
}
else if (rank === 2) {
return "vec2<i32>";
}
else if (rank === 3) {
return "vec3<i32>";
}
else if (rank === 4) {
return "vec4<i32>";
}
else if (rank === 5) {
return "vec5";
}
else if (rank === 6) {
return "vec6";
}
else {
throw Error("GPU for rank ".concat(rank, " is not yet supported"));
}
}
function getCoordsXYZ(index) {
if (index === 0) {
return 'x';
}
else if (index === 1) {
return 'y';
}
else if (index === 2) {
return 'z';
}
else if (index === 3) {
return 'w';
}
else if (index === 4) {
return 'u';
}
else if (index === 5) {
return 'v';
}
else {
throw Error("Index ".concat(index, " is not yet supported"));
}
}
function getMainHeaderString() {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
var snippet;
switch (params.length) {
case 0:
snippet = "\n fn main()\n ";
break;
case 1:
snippet = "\n fn main(".concat(params[0], " : i32)\n ");
break;
default:
throw Error('Unreachable');
}
return snippet;
}
function getStartHeaderString(useGlobalIndex, program) {
var snippet;
snippet = "\n ".concat(getWorkgroupSizeString(program), "\n fn _start(@builtin(local_invocation_id) LocalId : vec3<u32>,\n @builtin(global_invocation_id) GlobalId : vec3<u32>,\n @builtin(local_invocation_index) LocalIndex: u32,\n @builtin(workgroup_id) WorkgroupId : vec3<u32>,\n @builtin(num_workgroups) NumWorkgroups : vec3<u32>) {\n localId = LocalId;\n localIndex = LocalIndex;\n globalId = GlobalId;\n numWorkgroups = NumWorkgroups;\n workgroupId = WorkgroupId;\n ").concat(useGlobalIndex ? "main(getGlobalIndex());" : "main();", ";\n }\n ");
return snippet;
}
function getWorkgroupSizeString(program) {
return "\n @compute @workgroup_size(".concat(program.workgroupSize[0], ", ").concat(program.workgroupSize[1], ", ").concat(program.workgroupSize[2], ")\n");
}
function makeShader(inputInfo, outputData, program) {
var prefixSnippets = [];
var flatWorkgroupSize = program.workgroupSize[0] *
program.workgroupSize[1] * program.workgroupSize[2];
program.outputComponent =
program.outputComponent ? program.outputComponent : 1;
prefixSnippets.push("\n\n var<private> localId: vec3<u32>;\n var<private> localIndex: u32;\n var<private> globalId: vec3<u32>;\n var<private> numWorkgroups: vec3<u32>;\n var<private> workgroupId: vec3<u32>;\n\n // Only used when the y/z dimension of workgroup size is 1.\n fn getGlobalIndex() -> i32 {\n ".concat(isFlatDispatch(program) ?
" return i32(globalId.x);" :
" return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y +\n workgroupId.y * numWorkgroups.x + workgroupId.x) * ".concat(flatWorkgroupSize, "u +\n localIndex);\n "), "\n }\n "));
if (program.pixelsOpType != null) {
var inoutSnippet = program.pixelsOpType === PixelsOpType.FROM_PIXELS ?
"@group(0) @binding(0) var<storage, read_write> result: array<".concat(dataTypeToGPUType(outputData.dtype, program.outputComponent), ">;") :
"@group(0) @binding(1) var<storage, read> inBuf : array<".concat(dataTypeToGPUType(inputInfo[0].dtype, program.outputComponent), ">;");
var outShapeStridesType = outputData.shape.length === 3 ? 'vec2<i32>' : 'i32';
prefixSnippets.push("\n struct Uniform {\n outShapeStrides : ".concat(outShapeStridesType, ",\n size : i32,\n numChannels : i32,\n alpha : f32,\n };\n\n ").concat(inoutSnippet, "\n @group(0) @binding(2) var<uniform> uniforms: Uniform;\n "));
var useGlobalIndex_1 = isFlatDispatchLayout(program);
return [
commonSnippet,
prefixSnippets.join('\n'),
getCoordsFromIndexSnippet(outputData.shape),
program.getUserCode(),
getStartHeaderString(useGlobalIndex_1, program),
].join('\n');
}
var stridesLength;
var stridesDataType;
var uniformDeclaration = 'struct Uniforms { NAN : f32, INFINITY : f32, ';
program.variableNames.forEach(function (x, i) {
var perDataType = getCoordsDataType(inputInfo[i].shape.length);
uniformDeclaration +=
"".concat(x.charAt(0).toLowerCase() + x.slice(1), "Shape : ").concat(perDataType, ", ");
stridesLength = inputInfo[i].shape.length - 1;
stridesDataType = getCoordsDataType(stridesLength);
uniformDeclaration +=
"".concat(x.charAt(0).toLowerCase() + x.slice(1), "ShapeStrides: ").concat(stridesDataType, ", ");
});
var outputDataType = getCoordsDataType(outputData.shape.length);
uniformDeclaration += "outShape : ".concat(outputDataType, ", ");
stridesLength = outputData.shape.length - 1;
stridesDataType = getCoordsDataType(stridesLength);
uniformDeclaration += "\n outShapeStrides: ".concat(stridesDataType, ", ");
if (program.size) {
uniformDeclaration += 'size : i32, ';
}
if (program.uniforms) {
uniformDeclaration += program.uniforms;
}
uniformDeclaration += '};';
uniformDeclaration = insertAlignment(uniformDeclaration);
prefixSnippets.push(uniformDeclaration);
// Output buffer.
if (program.atomic) {
prefixSnippets.push("\n @group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;\n ");
}
else {
prefixSnippets.push("\n @group(0) @binding(0) var<storage, read_write> result: array<".concat(dataTypeToGPUType(outputData.dtype, program.outputComponent), ">;\n "));
}
program.variableNames.forEach(function (x, i) {
prefixSnippets.push("\n @group(0) @binding(".concat(1 + i, ") var<storage, read> ").concat(x, ": array<").concat(program.variableComponents ?
dataTypeToGPUType(inputInfo[i].dtype, program.variableComponents[i]) :
dataTypeToGPUType(inputInfo[i].dtype, program.outputComponent), ">;\n "));
});
if (uniformDeclaration !== '') {
prefixSnippets.push("\n @group(0) @binding(".concat(1 + program.variableNames.length, ") var<uniform> uniforms: Uniforms;\n "));
}
var coordsSnippet = getOutputCoordsSnippet(outputData.shape, program.dispatchLayout);
var sources = [
commonSnippet, prefixSnippets.join('\n') + isInfSnippet,
getCoordsFromIndexSnippet(outputData.shape), coordsSnippet,
getOutputIndexFromCoordsSnippet(outputData.shape.length)
];
if (!program.atomic) {
sources.push(setOutputSnippet(outputData.shape, outputData.dtype, program.outputComponent));
}
program.variableNames.forEach(function (x, i) {
sources.push("".concat(getCoordsFromIndexSnippet(inputInfo[i].shape, x)));
});
var inputSnippet = inputInfo
.map(function (x, i) { return getInputSnippet(x, outputData.shape, program.variableComponents ? program.variableComponents[i] :
program.outputComponent, program.dispatchLayout.x.length === outputData.shape.length); })
.join('\n');
sources.push(inputSnippet);
sources.push(program.getUserCode());
var useGlobalIndex = isFlatDispatchLayout(program);
sources.push(getStartHeaderString(useGlobalIndex, program));
var source = sources.join('\n');
return source;
}
function makeShaderKey(program, inputsData, output) {
var key = program.shaderKey;
if (program.pixelsOpType != null) {
return key;
}
var shapes = [];
var types = [];
inputsData.forEach(function (element) {
shapes.push(element.shape);
types.push(element.dtype);
});
shapes.push(output.shape);
types.push(output.dtype);
var broadcastDims = inputsData.map(function (d) { return tf.backend_util.getBroadcastDims(d.shape, output.shape); });
var inputShapesEqualsOutShape = inputsData.map(function (d) { return tf.util.arraysEqual(d.shape, output.shape); }).join('_');
var broadcastDimsKey = broadcastDims.map(function (d) { return d.join('_'); }).join(';');
var flatDispatchString = isFlatDispatch(program) ? 'flatDispatch' : '';
key += '_' + (program.workgroupSize ? program.workgroupSize.join(',') : '') +
shapes.map(function (shape) { return shape.length; }).join(',') + types.join(',') +
program.variableNames.join(',') + broadcastDimsKey +
inputShapesEqualsOutShape + flatDispatchString;
return key;
}
var commonSnippet = "\n struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};\n struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};\n\n // Checks whether coordinates lie within the bounds of the shape.\n fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {\n return all(coord >= vec2<i32>(0)) && all(coord < shape);\n }\n fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {\n return all(coord >= vec3<i32>(0)) && all(coord < shape);\n }\n fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {\n return all(coord >= vec4<i32>(0)) && all(coord < shape);\n }\n\n fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {\n return coord;\n }\n fn getIndexFromCoords2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {\n return dot(coords, vec2<i32>(shape.y, 1));\n }\n fn getIndexFromCoords3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {\n return dot(coords, vec3<i32>(shape.y * shape.z, shape.z, 1));\n }\n fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n }\n fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {\n let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);\n return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;\n }\n fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {\n let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);\n return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;\n }\n\n // NaN defination in IEEE 754-1985 is :\n // - sign = either 0 or 1.\n // - biased exponent = all 1 bits.\n // - fraction = anything except all 0 bits (since all 0 bits represents infinity).\n // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers\n fn isnan(val: f32) -> bool {\n let floatToUint: u32 = bitcast<u32>(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n fn isnanVec4(val : vec4<f32>) -> vec4<bool> {\n let floatToUint: vec4<u32> = bitcast<vec4<u32>>(val);\n return (floatToUint & vec4<u32>(0x7fffffffu)) > vec4<u32>(0x7f800000u);\n }\n";
var isInfSnippet = "\n fn isinf(val: f32) -> bool {\n return abs(val) == uniforms.INFINITY;\n }\n";
/**
* Derives logical coordinates from a flat index. Performs integer division
* with each stride and decrements the index until the index equals the final
* dimension coordinate.
*/
function getCoordsFromIndexSnippet(shape, name) {
if (name === void 0) { name = ''; }
var rank = shape.length;
var funcName = name !== '' ?
"get".concat(name.charAt(0).toUpperCase() + name.slice(1), "CoordsFromIndex") :
'getCoordsFromIndex';
var stridesName = name !== '' ?
"".concat(name.charAt(0).toLowerCase() + name.slice(1), "ShapeStrides") :
"outShapeStrides";
if (rank <= 1) {
return "fn ".concat(funcName, "(index : i32) -> i32 { return index; }");
}
var strides = tf.util.computeStrides(shape);
var dtype = getCoordsDataType(rank);
var coords = [];
for (var i = 0; i < rank; i++) {
coords.push("d".concat(i));
}
if (strides.length === 1) {
return " fn ".concat(funcName, "(index : i32) -> vec2<i32> {\n let d0 = index / uniforms.").concat(stridesName, "; let d1 = index - d0 * uniforms.").concat(stridesName, ";\n return vec2<i32>(d0, d1);\n }");
}
var snippet;
snippet = 'var index2 = index;' +
strides
.map(function (_, i) {
var line1 = "let ".concat(coords[i], " = index2 / uniforms.").concat(stridesName, ".").concat(getCoordsXYZ(i));
var line2 = i === strides.length - 1 ?
"let ".concat(coords[i + 1], " = index2 - ").concat(coords[i], " * uniforms.").concat(stridesName, ".").concat(getCoordsXYZ(i)) :
"index2 = index2 - ".concat(coords[i], " * uniforms.").concat(stridesName, ".").concat(getCoordsXYZ(i));
return "".concat(line1, "; ").concat(line2, ";");
})
.join('');
return "\n fn ".concat(funcName, "(index : i32) -> ").concat(dtype, " {\n ").concat(snippet, "\n return ").concat(dtype, "(").concat(coords.join(','), ");\n }\n ");
}
function getInputAtCoordsSnippet(inputInfo, component) {
var texName = inputInfo.name;
var rank = inputInfo.shape.length;
var type = getCoordsDataType(rank);
var funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);
var dims = ['d0', 'd1', 'd2', 'd3', 'd4', 'd5'].slice(0, rank);
var inputs = dims.map(function (d) { return "".concat(d, " : i32"); }).join(', ');
if (rank < 1) {
return "\n fn ".concat(funcName, "() -> ").concat(typeSnippet(component), " {\n return ").concat(typeSnippet(component), "(").concat(texName, "[0]);\n }\n ");
}
var shapeStr = "uniforms.".concat(texName.charAt(0).toLowerCase() + texName.slice(1), "Shape");
var rankStr = "".concat(rank, "D");
if (rank === 0) {
rankStr = '1D';
}
return "\n fn ".concat(funcName, "(").concat(inputs, ") -> ").concat(typeSnippet(component), " {\n return ").concat(typeSnippet(component), "(").concat(texName, "[getIndexFromCoords").concat(rankStr, "(").concat(type, "(").concat(dims.join(','), "),\n ").concat(shapeStr, ")").concat(component === 1 ? '' : " / ".concat(component), "]);\n }\n ");
}
function getInputByOutputSnippet(inputInfo, outShape, component, isFlatDispatchLayout) {
var texName = inputInfo.name;
var texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);
var funcName = 'get' + texFuncSnippet + 'ByOutput';
var inRank = inputInfo.shape.length;
var outRank = outShape.length;
var type = getCoordsDataType(outRank);
// If the inShape equals the outShape and the dispatch layout is flat, we can
// directly use |gl_GlobalInvocationID.x| as the index and don't need coords
// conversion between these two shapes.
if (tf.util.arraysEqual(inputInfo.shape, outShape) && isFlatDispatchLayout) {
return "\n fn ".concat(funcName, "Index(globalIndex : i32) -> ").concat(typeSnippet(component), " {\n return ").concat(typeSnippet(component), "(").concat(texName, "[globalIndex]);\n }\n\n fn ").concat(funcName, "Coords(coords : ").concat(type, ") -> ").concat(typeSnippet(component), " {\n return ").concat(typeSnippet(component), "(").concat(texName, "[").concat(outRank > 1 ? 'getOutputIndexFromCoords(coords)' :
'coords').concat(component === 1 ? '' : " / ".concat(component), "]);\n }\n ");
}
var broadcastDims = tf.backend_util.getBroadcastDims(inputInfo.shape, outShape);
var rankDiff = outRank - inRank;
var coordsSnippet = '';
if (inRank === 0) {
return "\n fn ".concat(funcName, "Index(globalIndex : i32) -> ").concat(typeSnippet(component), "{\n return get").concat(texFuncSnippet, "();\n }\n\n fn ").concat(funcName, "Coords(coords : ").concat(type, ") -> ").concat(typeSnippet(component), "{\n return get").concat(texFuncSnippet, "();\n }\n ");
}
else {
if (outRank < 2 && broadcastDims.length >= 1) {
coordsSnippet = 'coords = 0;';
}
else {
coordsSnippet =
broadcastDims.map(function (d) { return "coords.".concat(getCoordsXYZ(d + rankDiff), " = 0;"); })
.join('\n');
}
}
var unpackedCoordsSnippet = '';
if (outRank < 2 && inRank > 0) {
unpackedCoordsSnippet = 'coords';
}
else {
if (outRank > 1) {
var coordsType = getCoordsDataType(inRank);
var coordsValues = inputInfo.shape.map(function (s, i) { return "coords.".concat(getCoordsXYZ(i + rankDiff)); })
.join(', ');
unpackedCoordsSnippet = "".concat(coordsType, "(").concat(coordsValues, ")");
}
else {
unpackedCoordsSnippet = 'coords';
}
}
var shapeStr = "uniforms.".concat(texName.charAt(0).toLowerCase() + texName.slice(1), "Shape");
var rankStr = "".concat(inRank, "D");
return "\n fn ".concat(funcName, "Index(globalIndex : i32) -> ").concat(typeSnippet(component), " {\n var coords = getCoordsFromIndex(globalIndex);\n ").concat(coordsSnippet, "\n return ").concat(typeSnippet(component), "(").concat(texName, "[getIndexFromCoords").concat(rankStr, "(").concat(unpackedCoordsSnippet, ", ").concat(shapeStr, ")").concat(component === 1 ? '' : " / ".concat(component), "]);\n }\n\n fn ").concat(funcName, "Coords(coordsIn : ").concat(type, ") -> ").concat(typeSnippet(component), " {\n var coords = coordsIn;\n ").concat(coordsSnippet, "\n return ").concat(typeSnippet(component), "(").concat(texName, "[getIndexFromCoords").concat(rankStr, "(").concat(unpackedCoordsSnippet, ", ").concat(shapeStr, ")").concat(component === 1 ? '' : " / ".concat(component), "]);\n }\n");
}
function getInputSnippet(inputInfo, outShape, component, isFlatDispatchLayout) {
var res = getInputAtCoordsSnippet(inputInfo, component);
var inShape = inputInfo.shape;
if (inShape.length <= outShape.length) {
res += getInputByOutputSnippet(inputInfo, outShape, component, isFlatDispatchLayout);
}
return res;
}
/**
* Generates getOutputCoords() function that computes output coordinates
* from dispatch geometry to reduce arithmetic.
*/
function getOutputCoordsSnippet(outShape, dispatchLayout) {
var x = dispatchLayout.x, _a = dispatchLayout.y, y = _a === void 0 ? [] : _a, _b = dispatchLayout.z, z = _b === void 0 ? [] : _b;
var outRank = outShape.length;
var rank = x.length + y.length + z.length;
// getOutputCoords is only meaningful when the output rank is same with
// dispatch layout rank.
if (rank !== outRank) {
return '';
}
if (x.length === outRank) {
var dtype_1 = getCoordsDataType(outRank);
var snippet_1 = "fn getOutputCoords() -> ".concat(dtype_1, "{\n let globalIndex = getGlobalIndex();\n return getCoordsFromIndex(globalIndex);\n }\n ");
return snippet_1;
}
var gatherDimensionsStr = '';
var dims = [x, y, z];
for (var i = 0; i < dims.length; i++) {
var arr = dims[i];
if (arr.length === 0) {
continue;
}
if (arr.length === 1) {
gatherDimensionsStr += "let d".concat(arr[0], " = i32(globalId[").concat(i, "]);");
}
else {
var strides = symbolicallyComputeStrides(arr, 'uniforms.outShape');
gatherDimensionsStr += "var index".concat(i, " = i32(globalId[").concat(i, "]);");
for (var j = 0; j < strides.length; j++) {
gatherDimensionsStr += "let d".concat(arr[j], " = index").concat(i, " / ").concat(strides[j], ";");
if (j === strides.length - 1) {
gatherDimensionsStr += "let d".concat(arr[j + 1], " = ") +
"index".concat(i, " - d").concat(arr[j], " * ").concat(strides[j], ";");