-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtf-backend-wasm.js
3770 lines (3676 loc) · 252 KB
/
tf-backend-wasm.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 2020 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'), require('path'), require('fs'), require('worker_threads'), require('perf_hooks')) :
typeof define === 'function' && define.amd ? define(['exports', '@tensorflow/tfjs-core', 'path', 'fs', 'worker_threads', 'perf_hooks'], factory) :
(global = global || self, factory((global.tf = global.tf || {}, global.tf.wasm = global.tf.wasm || {}), global.tf, global.path, global.fs, global.worker_threads, global.perf_hooks));
}(this, (function (exports, tfjsCore, path, fs, worker_threads, perf_hooks) { 'use strict';
path = path && path.hasOwnProperty('default') ? path['default'] : path;
fs = fs && fs.hasOwnProperty('default') ? fs['default'] : fs;
worker_threads = worker_threads && worker_threads.hasOwnProperty('default') ? worker_threads['default'] : worker_threads;
perf_hooks = perf_hooks && perf_hooks.hasOwnProperty('default') ? perf_hooks['default'] : perf_hooks;
/**
* @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.
* =============================================================================
*/
// This enum must align with the enum defined in cc/backend.h.
var CppDType;
(function (CppDType) {
CppDType[CppDType["float32"] = 0] = "float32";
CppDType[CppDType["int32"] = 1] = "int32";
CppDType[CppDType["bool"] = 2] = "bool";
CppDType[CppDType["string"] = 3] = "string";
CppDType[CppDType["complex64"] = 4] = "complex64";
})(CppDType || (CppDType = {}));
// Must match enum in cc/fusable_activations.h.
var FusableActivation;
(function (FusableActivation) {
FusableActivation[FusableActivation["linear"] = 0] = "linear";
FusableActivation[FusableActivation["relu"] = 1] = "relu";
FusableActivation[FusableActivation["relu6"] = 2] = "relu6";
FusableActivation[FusableActivation["prelu"] = 3] = "prelu";
})(FusableActivation || (FusableActivation = {}));
/**
* @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.
* =============================================================================
*/
let wasmFusedMatMul;
function setup(backend) {
wasmFusedMatMul = backend.wasm.cwrap(tfjsCore._FusedMatMul, null /* void */, [
'number',
'array',
'number',
'number',
'array',
'number',
'number',
'number',
'number',
'number',
'number',
'number' // out_id
]);
}
function fusedBatchMatMul(args) {
const { inputs, backend, attrs } = args;
const { a, b, bias, preluActivationWeights } = inputs;
if (a.dtype !== 'float32' || b.dtype !== 'float32') {
throw new Error(`_FusedMatMul for non non-float32 tensors not yet supported.`);
}
const { transposeA, transposeB, activation } = attrs;
const aId = backend.dataIdMap.get(a.dataId).id;
const bId = backend.dataIdMap.get(b.dataId).id;
let biasId = 0;
if (bias != null) {
const biasData = backend.dataIdMap.get(bias.dataId);
if (biasData.shape.length !== 1) {
throw new Error(`_FusedMatMul only supports rank-1 bias but got ` +
`rank ${biasData.shape.length}.`);
}
biasId = biasData.id;
}
const preluActivationWeightsId = preluActivationWeights == null ?
0 :
backend.dataIdMap.get(preluActivationWeights.dataId).id;
const fusedActivation = FusableActivation[activation];
if (fusedActivation == null) {
throw new Error(`${activation} activation not yet supported for FusedConv2D ` +
`in the wasm backend.`);
}
const leftDim = transposeA ? a.shape[2] : a.shape[1];
const rightDim = transposeB ? b.shape[1] : b.shape[2];
const batchDim = a.shape[0];
const out = backend.makeOutput([batchDim, leftDim, rightDim], a.dtype);
const outId = backend.dataIdMap.get(out.dataId).id;
const aShapeBytes = new Uint8Array(new Int32Array(a.shape).buffer);
const bShapeBytes = new Uint8Array(new Int32Array(b.shape).buffer);
wasmFusedMatMul(aId, aShapeBytes, a.shape.length, bId, bShapeBytes, b.shape.length, transposeA, transposeB, fusedActivation, biasId, preluActivationWeightsId, outId);
return out;
}
const fusedMatMulConfig = {
kernelName: tfjsCore._FusedMatMul,
backendName: 'wasm',
setupFunc: setup,
kernelFunc: fusedBatchMatMul
};
/**
* @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.
* =============================================================================
*/
function createUnaryKernelConfig(kernelName) {
let wasmFunc;
function setupFunc(backend) {
wasmFunc =
backend.wasm.cwrap(kernelName, null /* void */, ['number', 'number']);
}
function kernelFunc(args) {
const { backend, inputs: { x } } = args;
const xId = backend.dataIdMap.get(x.dataId).id;
const out = backend.makeOutput(x.shape, x.dtype);
const outId = backend.dataIdMap.get(out.dataId).id;
// Short-circuit zero-sized tensors.
if (tfjsCore.util.sizeFromShape(out.shape) === 0) {
return out;
}
wasmFunc(xId, outId);
return out;
}
return { kernelName, backendName: 'wasm', setupFunc, kernelFunc };
}
/**
* @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.
* =============================================================================
*/
const absConfig = createUnaryKernelConfig(tfjsCore.Abs);
/**
* @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.
* =============================================================================
*/
function createBinaryKernelConfig(kernelName, supportsFullBroadcast, dtype) {
let wasmFunc;
function setupFunc(backend) {
wasmFunc = backend.wasm.cwrap(kernelName, null /* void */, [
'number',
'array',
'number',
'number',
'array',
'number',
'number',
'number' // out_id
]);
}
function kernelFunc(args) {
const { backend, inputs } = args;
const { a, b } = inputs;
const aId = backend.dataIdMap.get(a.dataId).id;
const bId = backend.dataIdMap.get(b.dataId).id;
const outputType = dtype != null ? dtype : a.dtype;
const newShape = tfjsCore.backend_util.assertAndGetBroadcastShape(a.shape, b.shape);
const out = backend.makeOutput(newShape, outputType);
// Short-circuit zero-sized tensors.
if (tfjsCore.util.sizeFromShape(newShape) === 0) {
return out;
}
const aShapeBytes = new Uint8Array(new Int32Array(a.shape).buffer);
const bShapeBytes = new Uint8Array(new Int32Array(b.shape).buffer);
const outId = backend.dataIdMap.get(out.dataId).id;
const kernelFunc = () => wasmFunc(aId, aShapeBytes, a.shape.length, bId, bShapeBytes, b.shape.length, CppDType[a.dtype], outId);
// Currently only some float operations support full broadcast.
if (supportsFullBroadcast && a.dtype === 'float32') {
kernelFunc();
return out;
}
const aBroadcastDims = tfjsCore.backend_util.getBroadcastDims(a.shape, newShape);
const bBroadcastDims = tfjsCore.backend_util.getBroadcastDims(b.shape, newShape);
const loopsOverAllOfA = aBroadcastDims.every((v, i) => v === i);
const loopsOverAllOfB = bBroadcastDims.every((v, i) => v === i);
if (loopsOverAllOfA && loopsOverAllOfB) {
kernelFunc();
return out;
}
else {
throw new Error(`Broadcasting along outer dims is not yet ` +
`supported for ${a.dtype} ${kernelName}.`);
}
}
return { kernelName, backendName: 'wasm', setupFunc, kernelFunc };
}
/**
* @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.
* =============================================================================
*/
const supportsFullBroadcast = true;
const addConfig = createBinaryKernelConfig(tfjsCore.Add, supportsFullBroadcast);
/**
* @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.
* =============================================================================
*/
let wasmFunc;
function setupFunc(backend) {
wasmFunc = backend.wasm.cwrap(tfjsCore.AddN, null /* void */, [
'array',
'number',
'number',
'number',
]);
}
function addn(args) {
const { inputs, backend } = args;
const out = backend.makeOutput(inputs[0].shape, inputs[0].dtype);
// Short-circuit zero-sized tensors.
if (tfjsCore.util.sizeFromShape(out.shape) === 0) {
return out;
}
const inputIds = inputs.map(x => backend.dataIdMap.get(x.dataId).id);
const inputIdsBytes = new Uint8Array(new Int32Array(inputIds).buffer);
const outId = backend.dataIdMap.get(out.dataId).id;
wasmFunc(inputIdsBytes, inputIds.length, CppDType[out.dtype], outId);
return out;
}
const addNConfig = {
kernelName: tfjsCore.AddN,
backendName: 'wasm',
setupFunc,
kernelFunc: addn,
};
/**
* @license
* Copyright 2020 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 identity(args) {
const { inputs: { x }, backend } = args;
const out = backend.makeOutput(x.shape, x.dtype);
const inVals = backend.typedArrayFromHeap(x);
const outVals = backend.typedArrayFromHeap(out);
outVals.set(inVals);
return out;
}
const identityConfig = {
kernelName: tfjsCore.Identity,
backendName: 'wasm',
kernelFunc: identity,
};
/**
* @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.
* =============================================================================
*/
let wasmTranspose;
function setup$1(backend) {
wasmTranspose = backend.wasm.cwrap(tfjsCore.Transpose, null /* void */, [
'number',
'array',
'number',
'number',
'number',
'array',
'number',
]);
}
function transpose(args) {
const { inputs, backend, attrs } = args;
// Reduce any dimensions with size one. Lower-rank transpose kernel performs
// better due to simpler memory access pattern.
const [reducedShape, perm] = removeOneSizeDims(inputs.x.shape, attrs.perm);
let permIsNoOp = true;
for (let i = 0; i < perm.length; i++) {
if (perm[i] !== i) {
permIsNoOp = false;
}
}
const outShape = computeOutShape(inputs.x.shape, attrs.perm);
const x = {
dataId: inputs.x.dataId,
shape: reducedShape,
dtype: inputs.x.dtype
};
if (permIsNoOp) {
const cloned = identity({ inputs, backend });
cloned.shape = outShape;
return cloned;
}
const out = backend.makeOutput(outShape, x.dtype);
const xId = backend.dataIdMap.get(x.dataId).id;
const outId = backend.dataIdMap.get(out.dataId).id;
const permBytes = new Uint8Array(new Int32Array(perm).buffer);
const xShapeBytes = new Uint8Array(new Int32Array(x.shape).buffer);
wasmTranspose(xId, xShapeBytes, x.shape.length, CppDType[x.dtype], outId, permBytes, perm.length);
return out;
}
function computeOutShape(inShape, perm) {
const outShape = new Array(inShape.length);
for (let i = 0; i < outShape.length; i++) {
outShape[i] = inShape[perm[i]];
}
return outShape;
}
function removeOneSizeDims(shape, perm) {
const newShape = [];
const newPerm = [];
for (let i = 0; i < shape.length; ++i) {
if (shape[i] !== 1) {
newShape.push(shape[i]);
}
if (shape[perm[i]] !== 1) {
newPerm.push(perm[i]);
}
}
for (let i = 0; i < newPerm.length; ++i) {
let minValIdx = -1;
for (let j = 0; j < newPerm.length; ++j) {
if (newPerm[j] >= i &&
(minValIdx === -1 || newPerm[minValIdx] > newPerm[j])) {
minValIdx = j;
}
}
newPerm[minValIdx] = i;
}
return [newShape, newPerm];
}
const transposeConfig = {
kernelName: tfjsCore.Transpose,
backendName: 'wasm',
kernelFunc: transpose,
setupFunc: setup$1,
};
/**
* @license
* Copyright 2020 Google Inc. 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.
* =============================================================================
*/
/**
* Compute permutation axes and do a transpose if necessary.
*
* Used by reduction ops.
* @param x input TensorInfo
* @param axis reduction axes
* @param backend wasm backend instance
*/
function permuteAxesAndTranspose(x, axis, backend) {
const xShape = x.shape;
const xRank = x.shape.length;
const originalAxes = tfjsCore.util.parseAxisParam(axis, xShape);
let axes = originalAxes;
const permutedAxes = tfjsCore.backend_util.getAxesPermutation(axes, xRank);
let xTransposed = null;
let inputWasTransposed = false;
if (permutedAxes != null) {
const newShape = new Array(xRank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = xShape[permutedAxes[i]];
}
axes = tfjsCore.backend_util.getInnerMostAxes(axes.length, xRank);
xTransposed =
transpose({ inputs: { x }, attrs: { perm: permutedAxes }, backend });
const xId = backend.dataIdMap.get(x.dataId).id;
const transposedId = backend.dataIdMap.get(xTransposed.dataId).id;
if (transposedId !== xId) {
inputWasTransposed = true;
}
}
return { transposed: xTransposed, originalAxes, axes, inputWasTransposed };
}
/**
* @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.
* =============================================================================
*/
let wasmFunc$1;
function setup$2(backend) {
wasmFunc$1 = backend.wasm.cwrap(tfjsCore.ArgMax, null /* void */, [
'number',
'number',
'number',
'number',
'number' // out_id
]);
}
function argmax(args) {
const { backend, inputs, attrs } = args;
const { axis } = attrs;
const { x } = inputs;
const xId = backend.dataIdMap.get(x.dataId).id;
let inputId = xId;
let input = x;
const { transposed, axes, inputWasTransposed } = permuteAxesAndTranspose(x, axis, backend);
if (inputWasTransposed) {
const transposedId = backend.dataIdMap.get(transposed.dataId).id;
if (transposedId !== xId) {
// transpose was not a no-op. We will need to dispose of this
// once we are done.
input = transposed;
inputId = transposedId;
}
}
const outShape = input.shape.slice(0, -1);
const out = backend.makeOutput(outShape, 'int32');
const outId = backend.dataIdMap.get(out.dataId).id;
const outerSize = tfjsCore.util.sizeFromShape(out.shape);
const innerSize = input.shape[axes[0]];
wasmFunc$1(inputId, CppDType[input.dtype], outerSize, innerSize, outId);
if (inputWasTransposed) {
// dispose of the transposed tensor.
backend.disposeData(transposed.dataId);
}
return out;
}
const argMaxConfig = {
kernelName: tfjsCore.ArgMax,
backendName: 'wasm',
kernelFunc: argmax,
setupFunc: setup$2
};
/**
* @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.
* =============================================================================
*/
let wasmAvgPool;
function setup$3(backend) {
wasmAvgPool = backend.wasm.cwrap(tfjsCore.AvgPool, null /* void */, [
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
]);
}
function avgPool(args) {
const { inputs, attrs, backend } = args;
const x = inputs.x;
const xId = backend.dataIdMap.get(x.dataId).id;
const { filterSize, strides, pad, dimRoundingMode } = attrs;
const convInfo = tfjsCore.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */, pad, dimRoundingMode);
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const padTop = convInfo.padInfo.top;
const padRight = convInfo.padInfo.right;
const padBottom = convInfo.padInfo.bottom;
const padLeft = convInfo.padInfo.left;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const channels = convInfo.inChannels;
if (convInfo.dataFormat !== 'channelsLast') {
throw new Error(`wasm backend does not support dataFormat:'` +
`${convInfo.dataFormat}'. Please use 'channelsLast'.`);
}
if (convInfo.dilationWidth !== 1 || convInfo.dilationHeight !== 1) {
throw new Error(`was backend only supports average pooling with dilation = [1, 1], ` +
`got [${convInfo.dilationHeight}, ${convInfo.dilationWidth}].`);
}
const out = backend.makeOutput(convInfo.outShape, 'float32');
const outId = backend.dataIdMap.get(out.dataId).id;
wasmAvgPool(xId, x.shape[0], x.shape[1], x.shape[2], filterHeight, filterWidth, padTop, padRight, padBottom, padLeft, strideHeight, strideWidth, channels, outId);
return out;
}
const avgPoolConfig = {
kernelName: tfjsCore.AvgPool,
backendName: 'wasm',
setupFunc: setup$3,
kernelFunc: avgPool
};
/**
* @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.
* =============================================================================
*/
let wasmBatchMatMul;
function setup$4(backend) {
wasmBatchMatMul = backend.wasm.cwrap(tfjsCore.BatchMatMul, null /* void */, [
'number',
'array',
'number',
'number',
'array',
'number',
'number',
'number',
'number' // out_id
]);
}
function batchMatMul(args) {
const { inputs, backend, attrs } = args;
const { a, b } = inputs;
if (a.dtype !== 'float32' || b.dtype !== 'float32') {
throw new Error(`BatchMatMul for non non-float32 tensors not yet supported.`);
}
const { transposeA, transposeB } = attrs;
const aId = backend.dataIdMap.get(a.dataId).id;
const bId = backend.dataIdMap.get(b.dataId).id;
const leftDim = transposeA ? a.shape[2] : a.shape[1];
const rightDim = transposeB ? b.shape[1] : b.shape[2];
const batchDim = a.shape[0];
const out = backend.makeOutput([batchDim, leftDim, rightDim], a.dtype);
const outId = backend.dataIdMap.get(out.dataId).id;
const aShapeBytes = new Uint8Array(new Int32Array(a.shape).buffer);
const bShapeBytes = new Uint8Array(new Int32Array(b.shape).buffer);
wasmBatchMatMul(aId, aShapeBytes, a.shape.length, bId, bShapeBytes, b.shape.length, transposeA, transposeB, outId);
return out;
}
const batchMatMulConfig = {
kernelName: tfjsCore.BatchMatMul,
backendName: 'wasm',
setupFunc: setup$4,
kernelFunc: batchMatMul
};
/**
* @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.
* =============================================================================
*/
function cast(args) {
const { inputs: { x }, attrs: { dtype }, backend } = args;
const out = backend.makeOutput(x.shape, dtype);
const inVals = backend.typedArrayFromHeap(x);
const outVals = backend.typedArrayFromHeap(out);
outVals.set(inVals);
return out;
}
const castConfig = {
kernelName: tfjsCore.Cast,
backendName: 'wasm',
kernelFunc: cast,
};
/**
* @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.
* =============================================================================
*/
let wasmClip;
function setup$5(backend) {
wasmClip = backend.wasm.cwrap(tfjsCore.ClipByValue, null /* void */, [
'number',
'number',
'number',
'number' // out_id
]);
}
function clip(args) {
const { inputs, backend, attrs } = args;
const { x } = inputs;
const { clipValueMin, clipValueMax } = attrs;
const xId = backend.dataIdMap.get(x.dataId).id;
const out = backend.makeOutput(x.shape, 'float32');
const outId = backend.dataIdMap.get(out.dataId).id;
wasmClip(xId, clipValueMin, clipValueMax, outId);
return out;
}
const clipByValueConfig = {
kernelName: tfjsCore.ClipByValue,
backendName: 'wasm',
setupFunc: setup$5,
kernelFunc: clip
};
/**
* @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.
* =============================================================================
*/
function concat(args) {
const { inputs, backend } = args;
const axis = tfjsCore.util.parseAxisParam(args.attrs.axis, inputs[0].shape)[0];
const outShape = tfjsCore.backend_util.computeOutShape(inputs.map(t => t.shape), axis);
const out = backend.makeOutput(outShape, inputs[0].dtype);
const batchDim = tfjsCore.util.sizeFromShape(inputs[0].shape.slice(0, axis));
let sumInnerDims = 0;
const innerDims = inputs.map(input => {
const innerDim = tfjsCore.util.sizeFromShape(input.shape.slice(axis));
sumInnerDims += innerDim;
return innerDim;
});
const inVals = inputs.map(input => backend.typedArrayFromHeap(input));
const outVals = backend.typedArrayFromHeap(out);
for (let b = 0; b < batchDim; b++) {
let outOffset = b * sumInnerDims;
for (let i = 0; i < inVals.length; i++) {
const innerDim = innerDims[i];
const inOffset = b * innerDim;
const vals = inVals[i].subarray(inOffset, inOffset + innerDim);
outVals.set(vals, outOffset);
outOffset += innerDim;
}
}
return out;
}
const concatConfig = {
kernelName: tfjsCore.Concat,
backendName: 'wasm',
kernelFunc: concat,
};
/**
* @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.
* =============================================================================
*/
let wasmConv2d;
function setup$6(backend) {
wasmConv2d = backend.wasm.cwrap(tfjsCore.Conv2D, null /* void */, [
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
]);
}
function conv2d(args) {
const { inputs, attrs, backend } = args;
const { x, filter } = inputs;
const xId = backend.dataIdMap.get(x.dataId).id;
const filterId = backend.dataIdMap.get(filter.dataId).id;
const { strides, dilations, pad, dimRoundingMode, dataFormat } = attrs;
const $dataFormat = tfjsCore.backend_util.convertConv2DDataFormat(dataFormat);
const convInfo = tfjsCore.backend_util.computeConv2DInfo(x.shape, filter.shape, strides, dilations, pad, dimRoundingMode, false, $dataFormat);
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const padTop = convInfo.padInfo.top;
const padRight = convInfo.padInfo.right;
const padBottom = convInfo.padInfo.bottom;
const padLeft = convInfo.padInfo.left;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const inputChannels = convInfo.inChannels;
const outputChannels = convInfo.outChannels;
const isSamePad = convInfo.padInfo.type === 'SAME' ? 1 : 0;
if (convInfo.dataFormat !== 'channelsLast') {
throw new Error(`wasm backend Conv2D does not support dataFormat:'` +
`${convInfo.dataFormat}'. Please use 'channelsLast'.`);
}
const out = backend.makeOutput(convInfo.outShape, 'float32');
const outId = backend.dataIdMap.get(out.dataId).id;
wasmConv2d(xId, x.shape[0], x.shape[1], x.shape[2], filterId, filterHeight, filterWidth, padTop, padRight, padBottom, padLeft, isSamePad, dilationHeight, dilationWidth, strideHeight, strideWidth, inputChannels, outputChannels, outId);
return out;
}
const conv2DConfig = {
kernelName: tfjsCore.Conv2D,
backendName: 'wasm',
setupFunc: setup$6,
kernelFunc: conv2d
};
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
let wasmConv2DBackpropInput;
function setup$7(backend) {
wasmConv2DBackpropInput = backend.wasm.cwrap(tfjsCore.Conv2DBackpropInput, null, [
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
'number',
]);
}
function conv2DBackpropInput(args) {
const { backend, inputs, attrs } = args;
const { dy, filter } = inputs;
const { strides, pad, dataFormat, dimRoundingMode, inputShape } = attrs;
const dilations = 1;
const $dataFormat = tfjsCore.backend_util.convertConv2DDataFormat(dataFormat);
const convInfo = tfjsCore.backend_util.computeConv2DInfo(inputShape, filter.shape, strides, dilations, pad, dimRoundingMode, false /* depthwise */, $dataFormat);
const { batchSize, filterHeight, filterWidth, inChannels, inHeight, inWidth, outChannels, outHeight, outWidth, strideHeight, strideWidth } = convInfo;
const topPad = filterHeight - 1 - convInfo.padInfo.top;
const leftPad = filterWidth - 1 - convInfo.padInfo.left;
const isChannelsLast = convInfo.dataFormat === 'channelsLast';
const dxStrides = tfjsCore.util.computeStrides(convInfo.inShape);
const dyStrides = tfjsCore.util.computeStrides(dy.shape);
const [fltS0, fltS1, fltS2] = tfjsCore.util.computeStrides(filter.shape);
const xBatchStride = dxStrides[0];
const xRowStride = isChannelsLast ? dxStrides[1] : dxStrides[2];
const xColStride = isChannelsLast ? dxStrides[2] : 1;
const xChannelStride = isChannelsLast ? 1 : dxStrides[1];
const yBatchStride = dyStrides[0];
const yRowStride = isChannelsLast ? dyStrides[1] : dyStrides[2];
const yColStride = isChannelsLast ? dyStrides[2] : 1;
const yChannelStride = isChannelsLast ? 1 : dyStrides[1];
const out = backend.makeOutput(convInfo.inShape, 'float32');
const outId = backend.dataIdMap.get(out.dataId).id;
const dyId = backend.dataIdMap.get(dy.dataId).id;
const filterId = backend.dataIdMap.get(filter.dataId).id;
wasmConv2DBackpropInput(dyId, filterId, batchSize, filterHeight, filterWidth, inHeight, inWidth, inChannels, outHeight, outWidth, outChannels, strideHeight, strideWidth, topPad, leftPad, fltS0, fltS1, fltS2, xBatchStride, xRowStride, xColStride, xChannelStride, yBatchStride, yRowStride, yColStride, yChannelStride, outId);
return out;
}
const conv2DBackpropInputConfig = {
kernelName: tfjsCore.Conv2DBackpropInput,
backendName: 'wasm',
setupFunc: setup$7,
kernelFunc: conv2DBackpropInput
};
/**
* @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.
* =============================================================================
*/
const cosConfig = createUnaryKernelConfig(tfjsCore.Cos);
/**
* @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.
* =============================================================================
*/