forked from tensorflow/tfjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend_webgl.ts
1286 lines (1132 loc) · 44.2 KB
/
backend_webgl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2017 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.
* =============================================================================
*/
// Import webgl flags.
import './flags_webgl';
import * as tf from '@tensorflow/tfjs-core';
import {backend_util, BackendValues, buffer, DataId, DataStorage, DataToGPUWebGLOption, DataType, engine, env, GPUData, kernel_impls, KernelBackend, MemoryInfo, nextFrame, NumericDataType, Rank, RecursiveArray, scalar, ShapeMap, Tensor, Tensor2D, TensorBuffer, TensorInfo, tidy, TimingInfo, TypedArray, util} from '@tensorflow/tfjs-core';
import {getWebGLContext} from './canvas_util';
import {DecodeMatrixProgram} from './decode_matrix_gpu';
import {DecodeMatrixPackedProgram} from './decode_matrix_packed_gpu';
import {EncodeFloatProgram} from './encode_float_gpu';
import {EncodeFloatPackedProgram} from './encode_float_packed_gpu';
import {EncodeMatrixProgram} from './encode_matrix_gpu';
import {EncodeMatrixPackedProgram} from './encode_matrix_packed_gpu';
import {GPGPUContext} from './gpgpu_context';
import * as gpgpu_math from './gpgpu_math';
import {getUniformLocations, GPGPUBinary, GPGPUProgram, TensorData} from './gpgpu_math';
import {simpleAbsImplCPU} from './kernel_utils/shared';
import {PackProgram} from './pack_gpu';
import {ReshapePackedProgram} from './reshape_packed_gpu';
import * as tex_util from './tex_util';
import {Texture, TextureData, TextureUsage} from './tex_util';
import {TextureManager} from './texture_manager';
import * as unary_op from './unaryop_gpu';
import {UnaryOpProgram} from './unaryop_gpu';
import {UnaryOpPackedProgram} from './unaryop_packed_gpu';
import {UnpackProgram} from './unpack_gpu';
import * as webgl_util from './webgl_util';
const whereImpl = kernel_impls.whereImpl;
export const EPSILON_FLOAT32 = 1e-7;
export const EPSILON_FLOAT16 = 1e-4;
type KernelInfo = {
name: string; query: Promise<number>;
};
export type TimerNode = RecursiveArray<KernelInfo>|KernelInfo;
export interface CPUTimerQuery {
startMs: number;
endMs?: number;
}
export interface WebGLMemoryInfo extends MemoryInfo {
numBytesInGPU: number;
// Tracks the total number of bytes allocated on the GPU, accounting for the
// physical texture type.
numBytesInGPUAllocated: number;
// Tracks byte size of textures that were created and then made available for
// reuse (disposed).
numBytesInGPUFree: number;
unreliable: boolean;
}
export interface WebGLTimingInfo extends TimingInfo {
uploadWaitMs: number;
downloadWaitMs: number;
}
const binaryCaches: {[webGLVersion: string]: {[key: string]: GPGPUBinary}} = {};
export function getBinaryCache(webGLVersion: number) {
if (webGLVersion in binaryCaches) {
return binaryCaches[webGLVersion];
}
binaryCaches[webGLVersion] = {};
return binaryCaches[webGLVersion];
}
// Empirically determined constant used to determine size threshold for handing
// off execution to the CPU.
const CPU_HANDOFF_SIZE_THRESHOLD =
env().getNumber('CPU_HANDOFF_SIZE_THRESHOLD');
// Empirically determined constant used to decide the number of MB on GPU
// before we warn about high memory use. The MB are this constant * screen area
// * dpi / 1024 / 1024.
const BEFORE_PAGING_CONSTANT = 600;
function numMBBeforeWarning(): number {
if (env().global.screen == null) {
return 1024; // 1 GB.
}
return (env().global.screen.height * env().global.screen.width *
window.devicePixelRatio) *
BEFORE_PAGING_CONSTANT / 1024 / 1024;
}
export class MathBackendWebGL extends KernelBackend {
texData: DataStorage<TextureData>;
gpgpu: GPGPUContext;
private static nextDataId = 0;
private nextDataId(): number {
return MathBackendWebGL.nextDataId++;
}
// Maps data ids that have a pending read operation, to list of subscribers.
private pendingRead = new WeakMap<DataId, Array<(arr: TypedArray) => void>>();
// List of data ids that are scheduled for disposal, but are waiting on a
// pending read operation.
private pendingDisposal = new WeakSet<DataId>();
// Used to count the number of 'shallow' sliced tensors that point to the
// same data id.
dataRefCount = new WeakMap<DataId, number>();
private numBytesInGPU = 0;
private canvas: HTMLCanvasElement|OffscreenCanvas;
private programTimersStack: TimerNode[];
private activeTimers: TimerNode[];
// Accumulated time spent (including blocking) in uploading data to webgl.
private uploadWaitMs = 0;
// Accumulated time spent (including blocking in downloading data from webgl.
private downloadWaitMs = 0;
// record the last manual GL Flush time.
private lastGlFlushTime = 0;
// Number of bits of precision of this backend.
private floatPrecisionValue: 32|16;
private textureManager: TextureManager;
private binaryCache: {[key: string]: GPGPUBinary};
private gpgpuCreatedLocally: boolean;
private numMBBeforeWarning: number;
private warnedAboutMemory = false;
constructor(gpuResource?: GPGPUContext|HTMLCanvasElement|OffscreenCanvas) {
super();
if (!env().getBool('HAS_WEBGL')) {
throw new Error('WebGL is not supported on this device');
}
let newGPGPU;
if (gpuResource != null) {
if (gpuResource instanceof GPGPUContext) {
newGPGPU = gpuResource;
} else {
const gl =
getWebGLContext(env().getNumber('WEBGL_VERSION'), gpuResource);
newGPGPU = new GPGPUContext(gl);
}
this.binaryCache = {};
this.gpgpuCreatedLocally = false;
} else {
const gl = getWebGLContext(env().getNumber('WEBGL_VERSION'));
newGPGPU = new GPGPUContext(gl);
this.binaryCache = getBinaryCache(env().getNumber('WEBGL_VERSION'));
this.gpgpuCreatedLocally = true;
}
this.gpgpu = newGPGPU;
this.canvas = this.gpgpu.gl.canvas;
this.textureManager = new TextureManager(this.gpgpu);
this.numMBBeforeWarning = numMBBeforeWarning();
this.texData = new DataStorage(this, engine());
}
numDataIds() {
return this.texData.numDataIds() - this.pendingDeletes;
}
write(values: BackendValues, shape: number[], dtype: DataType): DataId {
if (env().getBool('WEBGL_CHECK_NUMERICAL_PROBLEMS') ||
env().getBool('DEBUG')) {
this.checkNumericalProblems(values);
}
if (dtype === 'complex64' && values != null) {
throw new Error(
`Cannot write to a complex64 dtype. ` +
`Please use tf.complex(real, imag).`);
}
const dataId = {id: this.nextDataId()};
this.texData.set(
dataId,
{shape, dtype, values, usage: TextureUsage.UPLOAD, refCount: 1});
return dataId;
}
/** Return refCount of a `TensorData`. */
refCount(dataId: DataId): number {
if (this.texData.has(dataId)) {
const tensorData = this.texData.get(dataId);
return tensorData.refCount;
}
return 0;
}
/** Increase refCount of a `TextureData`. */
incRef(dataId: DataId): void {
const texData = this.texData.get(dataId);
texData.refCount++;
}
/** Decrease refCount of a `TextureData`. */
decRef(dataId: DataId): void {
if (this.texData.has(dataId)) {
const texData = this.texData.get(dataId);
texData.refCount--;
}
}
move(
dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,
refCount: number): void {
if (env().getBool('DEBUG')) {
this.checkNumericalProblems(values);
}
if (dtype === 'complex64') {
throw new Error(
`Cannot write to a complex64 dtype. ` +
`Please use tf.complex(real, imag).`);
}
this.texData.set(
dataId, {shape, dtype, values, usage: TextureUsage.UPLOAD, refCount});
}
disposeIntermediateTensorInfo(tensorInfo: TensorInfo): void {
this.disposeData(tensorInfo.dataId);
}
readSync(dataId: DataId): BackendValues {
const texData = this.texData.get(dataId);
const {values, dtype, complexTensorInfos, slice, shape, isPacked} = texData;
// The presence of `slice` indicates this tensor is a shallow slice of a
// different tensor, and is using that original tensor's texture. Run
// `clone` in order to copy that texture and read from it.
if (slice != null) {
let program;
if (isPacked) {
program = new UnaryOpPackedProgram(shape, unary_op.CLONE);
} else {
program = new UnaryOpProgram(shape, unary_op.CLONE);
}
const res =
this.runWebGLProgram(program, [{dataId, shape, dtype}], dtype);
const data = this.readSync(res.dataId);
this.disposeIntermediateTensorInfo(res);
return data;
}
if (values != null) {
return this.convertAndCacheOnCPU(dataId);
}
if (dtype === 'string') {
return values;
}
const shouldTimeProgram = this.activeTimers != null;
let start: number;
if (shouldTimeProgram) {
start = util.now();
}
let result: Float32Array;
if (dtype === 'complex64') {
const realValues =
this.readSync(complexTensorInfos.real.dataId) as Float32Array;
const imagValues =
this.readSync(complexTensorInfos.imag.dataId) as Float32Array;
result = backend_util.mergeRealAndImagArrays(realValues, imagValues);
} else {
result = this.getValuesFromTexture(dataId);
}
if (shouldTimeProgram) {
this.downloadWaitMs += util.now() - start;
}
return this.convertAndCacheOnCPU(dataId, result);
}
async read(dataId: DataId): Promise<BackendValues> {
if (this.pendingRead.has(dataId)) {
const subscribers = this.pendingRead.get(dataId);
return new Promise<TypedArray>(resolve => subscribers.push(resolve));
}
const texData = this.texData.get(dataId);
const {values, shape, slice, dtype, complexTensorInfos, isPacked} = texData;
// The presence of `slice` indicates this tensor is a shallow slice of a
// different tensor, and is using that original tensor's texture. Run
// `clone` in order to copy that texture and read from it.
if (slice != null) {
let program;
if (isPacked) {
program = new UnaryOpPackedProgram(shape, unary_op.CLONE);
} else {
program = new UnaryOpProgram(shape, unary_op.CLONE);
}
const res =
this.runWebGLProgram(program, [{dataId, shape, dtype}], dtype);
const data = this.read(res.dataId);
this.disposeIntermediateTensorInfo(res);
return data;
}
if (values != null) {
return this.convertAndCacheOnCPU(dataId);
}
if (env().getBool('DEBUG')) {
// getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED') caused a blocking GPU call.
// For performance reason, only check it for debugging. In production,
// it doesn't handle this use case anyway, so behavior is not changed.
if (!env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED') &&
env().getNumber('WEBGL_VERSION') === 2) {
throw new Error(
`tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and ` +
`WEBGL_VERSION=2 not yet supported.`);
}
}
let buffer: WebGLBuffer = null;
let tmpDownloadTarget: TensorInfo;
if (dtype !== 'complex64' && env().get('WEBGL_BUFFER_SUPPORTED')) {
// Possibly copy the texture into a buffer before inserting a fence.
tmpDownloadTarget = this.decode(dataId);
const tmpData = this.texData.get(tmpDownloadTarget.dataId);
buffer = this.gpgpu.createBufferFromTexture(
tmpData.texture.texture, ...tex_util.getDenseTexShape(shape));
}
this.pendingRead.set(dataId, []);
if (dtype !== 'complex64') {
// Create a fence and wait for it to resolve.
await this.gpgpu.createAndWaitForFence();
}
// Download the values from the GPU.
let vals: Float32Array;
if (dtype === 'complex64') {
const ps = await Promise.all([
this.read(complexTensorInfos.real.dataId),
this.read(complexTensorInfos.imag.dataId)
]);
const realValues = ps[0];
const imagValues = ps[1];
vals = backend_util.mergeRealAndImagArrays(
realValues as Float32Array, imagValues as Float32Array);
} else if (buffer == null) {
vals = this.getValuesFromTexture(dataId);
} else {
const size = util.sizeFromShape(shape);
vals = this.gpgpu.downloadFloat32MatrixFromBuffer(buffer, size);
}
if (tmpDownloadTarget != null) {
this.disposeIntermediateTensorInfo(tmpDownloadTarget);
}
if (buffer != null) {
const gl = this.gpgpu.gl;
webgl_util.callAndCheck(gl, () => gl.deleteBuffer(buffer));
}
const dTypeVals = this.convertAndCacheOnCPU(dataId, vals);
const subscribers = this.pendingRead.get(dataId);
this.pendingRead.delete(dataId);
// Notify all pending reads.
subscribers.forEach(resolve => resolve(dTypeVals));
if (this.pendingDisposal.has(dataId)) {
this.pendingDisposal.delete(dataId);
if (this.disposeData(dataId)) {
engine().removeDataId(dataId, this);
}
this.pendingDeletes--;
}
return dTypeVals;
}
/**
* Read tensor to a new texture that is densely packed for ease of use.
* @param dataId The source tensor.
* @param options
* customTexShape: Optional. If set, will use the user defined texture
* shape to create the texture.
*/
readToGPU(dataId: DataId, options: DataToGPUWebGLOption = {}): GPUData {
const texData = this.texData.get(dataId);
const {values, shape, slice, dtype, isPacked, texture} = texData;
if (dtype === 'complex64') {
throw new Error('Does not support reading texture for complex64 dtype.');
}
// The presence of `slice` indicates this tensor is a shallow slice of a
// different tensor, and is using that original tensor's texture. Run
// `clone` in order to copy that texture and read from it.
if (slice != null) {
let program;
if (isPacked) {
program = new UnaryOpPackedProgram(shape, unary_op.CLONE);
} else {
program = new UnaryOpProgram(shape, unary_op.CLONE);
}
const res =
this.runWebGLProgram(program, [{dataId, shape, dtype}], dtype);
const gpuResouorce = this.readToGPU(res, options);
this.disposeIntermediateTensorInfo(res);
return gpuResouorce;
}
if (texture == null) {
if (values != null) {
throw new Error('Data is not on GPU but on CPU.');
} else {
throw new Error('There is no data on GPU or CPU.');
}
}
// Decode the texture so that it is stored densely (using four channels).
const tmpTarget = this.decode(dataId, options.customTexShape);
// Make engine track this tensor, so that we can dispose it later.
const tensorRef = engine().makeTensorFromTensorInfo(tmpTarget);
const tmpData = this.texData.get(tmpTarget.dataId);
return {tensorRef, ...tmpData.texture};
}
bufferSync<R extends Rank, D extends DataType>(t: TensorInfo):
TensorBuffer<R, D> {
const data = this.readSync(t.dataId);
if (t.dtype === 'string') {
try {
// Decode the bytes into string.
const strings = (data as Uint8Array[]).map(d => util.decodeString(d));
return buffer(t.shape as ShapeMap[R], t.dtype, strings) as
TensorBuffer<R, D>;
} catch {
throw new Error('Failed to decode encoded string bytes into utf-8');
}
}
return buffer(t.shape as ShapeMap[R], t.dtype, data as TypedArray) as
TensorBuffer<R, D>;
}
private checkNumericalProblems(values: BackendValues): void {
if (values == null) {
return;
}
for (let i = 0; i < values.length; i++) {
const num = values[i] as number;
if (!webgl_util.canBeRepresented(num)) {
if (env().getBool('WEBGL_RENDER_FLOAT32_CAPABLE')) {
throw Error(
`The value ${num} cannot be represented with your ` +
`current settings. Consider enabling float32 rendering: ` +
`'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);
}
throw Error(`The value ${num} cannot be represented on this device.`);
}
}
}
private getValuesFromTexture(dataId: DataId): Float32Array {
const {shape, dtype, isPacked} = this.texData.get(dataId);
const size = util.sizeFromShape(shape);
if (env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED')) {
const tmpTarget = this.decode(dataId);
const tmpData = this.texData.get(tmpTarget.dataId);
const vals =
this.gpgpu
.downloadMatrixFromPackedTexture(
tmpData.texture.texture, ...tex_util.getDenseTexShape(shape))
.subarray(0, size);
this.disposeIntermediateTensorInfo(tmpTarget);
return vals;
}
const shouldUsePackedProgram =
env().getBool('WEBGL_PACK') && isPacked === true;
const outputShape =
shouldUsePackedProgram ? webgl_util.getShapeAs3D(shape) : shape;
const program = shouldUsePackedProgram ?
new EncodeFloatPackedProgram(outputShape as [number, number, number]) :
new EncodeFloatProgram(outputShape);
const output = this.runWebGLProgram(
program, [{shape: outputShape, dtype, dataId}], 'float32');
const tmpData = this.texData.get(output.dataId);
const vals = this.gpgpu
.downloadByteEncodedFloatMatrixFromOutputTexture(
tmpData.texture.texture, tmpData.texShape[0],
tmpData.texShape[1])
.subarray(0, size);
this.disposeIntermediateTensorInfo(output);
return vals;
}
timerAvailable(): boolean {
return env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0;
}
time(f: () => void): Promise<WebGLTimingInfo> {
const oldActiveTimers = this.activeTimers;
const newActiveTimers: TimerNode[] = [];
let outerMostTime = false;
if (this.programTimersStack == null) {
this.programTimersStack = newActiveTimers;
outerMostTime = true;
} else {
this.activeTimers.push(newActiveTimers);
}
this.activeTimers = newActiveTimers;
f();
// needing to split these up because util.flatten only accepts certain types
const flattenedActiveTimerQueries =
util.flatten(this.activeTimers.map((d: KernelInfo) => d.query))
.filter(d => d != null);
const flattenedActiveTimerNames =
util.flatten(this.activeTimers.map((d: KernelInfo) => d.name))
.filter(d => d != null);
this.activeTimers = oldActiveTimers;
if (outerMostTime) {
this.programTimersStack = null;
}
const res: WebGLTimingInfo = {
uploadWaitMs: this.uploadWaitMs,
downloadWaitMs: this.downloadWaitMs,
kernelMs: null,
wallMs: null // will be filled by the engine
};
return (async () => {
if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') >
0) {
const kernelMs = await Promise.all(flattenedActiveTimerQueries);
res['kernelMs'] = util.sum(kernelMs);
res['getExtraProfileInfo'] = () =>
kernelMs
.map((d, i) => ({name: flattenedActiveTimerNames[i], ms: d}))
.map(d => `${d.name}: ${d.ms}`)
.join(', ');
} else {
res['kernelMs'] = {
error: 'WebGL query timers are not supported in this environment.'
};
}
this.uploadWaitMs = 0;
this.downloadWaitMs = 0;
return res;
})();
}
memory(): WebGLMemoryInfo {
return {
unreliable: false,
numBytesInGPU: this.numBytesInGPU,
numBytesInGPUAllocated: this.textureManager.numBytesAllocated,
numBytesInGPUFree: this.textureManager.numBytesFree
} as WebGLMemoryInfo;
}
private startTimer(): WebGLQuery|CPUTimerQuery {
if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {
return this.gpgpu.beginQuery();
}
return {startMs: util.now(), endMs: null};
}
private endTimer(query: WebGLQuery|CPUTimerQuery): WebGLQuery|CPUTimerQuery {
if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {
this.gpgpu.endQuery();
return query;
}
(query as CPUTimerQuery).endMs = util.now();
return query;
}
private async getQueryTime(query: WebGLQuery|CPUTimerQuery): Promise<number> {
if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {
return this.gpgpu.waitForQueryAndGetTime(query as WebGLQuery);
}
const timerQuery = query as CPUTimerQuery;
return timerQuery.endMs - timerQuery.startMs;
}
private pendingDeletes = 0;
/**
* Decrease the RefCount on the dataId and dispose the memory if the dataId
* has 0 refCount. If there are pending read on the data, the disposal would
* added to the pending delete queue. Return true if the dataId is removed
* from backend or the backend does not contain the dataId, false if the
* dataId is not removed. Memory may or may not be released even when dataId
* is removed, which also depends on dataRefCount, see `releaseGPU`.
* @param dataId
* @oaram force Optional, remove the data regardless of refCount
*/
disposeData(dataId: DataId, force = false): boolean {
if (this.pendingDisposal.has(dataId)) {
return false;
}
// No-op if already disposed.
if (!this.texData.has(dataId)) {
return true;
}
// if force flag is set, change refCount to 0, this would ensure disposal
// when added to the pendingDisposal queue. Memory may or may not be
// released, which also depends on dataRefCount, see `releaseGPU`.
if (force) {
this.texData.get(dataId).refCount = 0;
} else {
this.texData.get(dataId).refCount--;
}
if (!force && this.texData.get(dataId).refCount > 0) {
return false;
}
if (this.pendingRead.has(dataId)) {
this.pendingDisposal.add(dataId);
this.pendingDeletes++;
return false;
}
this.releaseGPUData(dataId);
const {complexTensorInfos} = this.texData.get(dataId);
if (complexTensorInfos != null) {
this.disposeData(complexTensorInfos.real.dataId, force);
this.disposeData(complexTensorInfos.imag.dataId, force);
}
this.texData.delete(dataId);
return true;
}
private releaseGPUData(dataId: DataId): void {
const {texture, dtype, texShape, usage, isPacked, slice} =
this.texData.get(dataId);
const key = slice && slice.origDataId || dataId;
const refCount = this.dataRefCount.get(key);
if (refCount > 1) {
this.dataRefCount.set(key, refCount - 1);
} else {
this.dataRefCount.delete(key);
if (texture != null) {
this.numBytesInGPU -= this.computeBytes(texShape, dtype);
this.textureManager.releaseTexture(texture, texShape, usage, isPacked);
}
}
const texData = this.texData.get(dataId);
texData.texture = null;
texData.texShape = null;
texData.isPacked = false;
texData.slice = null;
}
getTexture(dataId: DataId): WebGLTexture {
this.uploadToGPU(dataId);
return this.texData.get(dataId).texture.texture;
}
/**
* Returns internal information for the specific data bucket. Used in unit
* tests.
*/
getDataInfo(dataId: DataId): TextureData {
return this.texData.get(dataId);
}
/*
Tests whether all the inputs to an op are small and on the CPU. This heuristic
determines when it would be faster to execute a kernel on the CPU. WebGL
kernels opt into running this check and forwarding when appropriate.
TODO(https://github.com/tensorflow/tfjs/issues/872): Develop a more
sustainable strategy for optimizing backend execution of ops.
*/
shouldExecuteOnCPU(
inputs: TensorInfo[],
sizeThreshold = CPU_HANDOFF_SIZE_THRESHOLD): boolean {
return env().getBool('WEBGL_CPU_FORWARD') &&
inputs.every(
input => this.texData.get(input.dataId).texture == null &&
util.sizeFromShape(input.shape) < sizeThreshold);
}
getGPGPUContext(): GPGPUContext {
return this.gpgpu;
}
where(condition: Tensor): Tensor2D {
backend_util.warn(
'tf.where() in webgl locks the UI thread. ' +
'Call tf.whereAsync() instead');
const condVals = condition.dataSync();
return whereImpl(condition.shape, condVals);
}
private packedUnaryOp(x: TensorInfo, op: string, dtype: DataType) {
const program = new UnaryOpPackedProgram(x.shape, op);
const outInfo = this.compileAndRun(program, [x], dtype);
return engine().makeTensorFromTensorInfo(outInfo);
}
// TODO(msoulanille) remove this once the backend has been modularized
// a copy is needed here to break a circular dependency.
// Also remove the op from unary_op.
abs<T extends Tensor>(x: T): T {
// TODO: handle cases when x is complex.
if (this.shouldExecuteOnCPU([x]) && x.dtype !== 'complex64') {
const outValues =
simpleAbsImplCPU(this.texData.get(x.dataId).values as TypedArray);
return this.makeOutput(x.shape, x.dtype, outValues);
}
if (env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {
return this.packedUnaryOp(x, unary_op.ABS, x.dtype) as T;
}
const program = new UnaryOpProgram(x.shape, unary_op.ABS);
const outInfo = this.compileAndRun(program, [x]);
return engine().makeTensorFromTensorInfo(outInfo) as T;
}
makeTensorInfo(
shape: number[], dtype: DataType,
values?: BackendValues|string[]): TensorInfo {
let dataId;
if (dtype === 'string' && values != null && values.length > 0 &&
util.isString(values[0])) {
const encodedValues =
(values as {} as string[]).map(d => util.encodeString(d));
dataId = this.write(encodedValues, shape, dtype);
} else {
dataId = this.write(values as TypedArray, shape, dtype);
}
this.texData.get(dataId).usage = null;
return {dataId, shape, dtype};
}
private makeOutput<T extends Tensor>(
shape: number[], dtype: DataType, values?: BackendValues): T {
return engine().makeTensorFromTensorInfo(
this.makeTensorInfo(shape, dtype, values), this) as T;
}
unpackTensor(input: TensorInfo): TensorInfo {
const program = new UnpackProgram(input.shape);
return this.runWebGLProgram(program, [input], input.dtype);
}
packTensor(input: TensorInfo): TensorInfo {
const program = new PackProgram(input.shape);
const preventEagerUnpackingOutput = true;
return this.runWebGLProgram(
program, [input], input.dtype, null /* customUniformValues */,
preventEagerUnpackingOutput);
}
private packedReshape(input: TensorInfo, afterShape: number[]): TensorInfo {
const input3DShape = [
webgl_util.getBatchDim(input.shape),
...webgl_util.getRowsCols(input.shape)
] as [number, number, number];
const input3D: TensorInfo = {
dtype: input.dtype,
shape: input3DShape,
dataId: input.dataId
};
const afterShapeAs3D = [
webgl_util.getBatchDim(afterShape), ...webgl_util.getRowsCols(afterShape)
] as [number, number, number];
const program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);
const preventEagerUnpackingOfOutput = true;
const customValues = [input3DShape];
const output = this.runWebGLProgram(
program, [input3D], input.dtype, customValues,
preventEagerUnpackingOfOutput);
return {dataId: output.dataId, shape: afterShape, dtype: output.dtype};
}
private decode(dataId: DataId, customTexShape?: [number, number]):
TensorInfo {
const texData = this.texData.get(dataId);
const {isPacked, shape, dtype} = texData;
if (customTexShape != null) {
const size = util.sizeFromShape(shape);
const texSize = customTexShape[0] * customTexShape[1] * 4;
util.assert(
size <= texSize,
() => 'customTexShape is too small. ' +
'Row * Column * 4 should be equal or larger than the ' +
'size of the tensor data.');
}
const shapeAs3D =
webgl_util.getShapeAs3D(shape) as [number, number, number];
let program;
if (isPacked) {
program = new DecodeMatrixPackedProgram(shapeAs3D);
} else {
program = new DecodeMatrixProgram(shapeAs3D);
}
const preventEagerUnpackingOfOutput = true;
const customValues =
[customTexShape != null ? customTexShape :
tex_util.getDenseTexShape(shapeAs3D)];
const out = this.runWebGLProgram(
program, [{shape: shapeAs3D, dtype, dataId}], dtype, customValues,
preventEagerUnpackingOfOutput, customTexShape);
return {dtype, shape, dataId: out.dataId};
}
runWebGLProgram(
program: GPGPUProgram, inputs: TensorInfo[], outputDtype: DataType,
customUniformValues?: number[][], preventEagerUnpackingOfOutput = false,
customTexShape?: [number, number]): TensorInfo {
const output = this.makeTensorInfo(program.outputShape, outputDtype);
const outData = this.texData.get(output.dataId);
if (program.packedOutput) {
outData.isPacked = true;
}
if (program.outPackingScheme === tex_util.PackingScheme.DENSE) {
const texelShape = customTexShape != null ?
customTexShape :
tex_util.getDenseTexShape(program.outputShape);
// For a densely packed output, we explicitly set texShape
// so it doesn't get assigned later according to our typical packing
// scheme wherein a single texel can only contain values from adjacent
// rows/cols.
outData.texShape = texelShape.map(d => d * 2) as [number, number];
}
if (program.outTexUsage != null) {
outData.usage = program.outTexUsage;
}
if (util.sizeFromShape(output.shape) === 0) {
// Short-circuit the computation since the result is empty (has 0 in its
// shape).
outData.values =
util.getTypedArrayFromDType(output.dtype as 'float32', 0);
return output;
}
const dataToDispose: TensorInfo[] = [];
const inputsData: TensorData[] = inputs.map(input => {
if (input.dtype === 'complex64') {
throw new Error(
`GPGPUProgram does not support complex64 input. For complex64 ` +
`dtypes, please separate the program into real and imaginary ` +
`parts.`);
}
let texData = this.texData.get(input.dataId);
if (texData.texture == null) {
if (!program.packedInputs &&
util.sizeFromShape(input.shape) <=
env().getNumber('WEBGL_SIZE_UPLOAD_UNIFORM')) {
// Upload small tensors that live on the CPU as uniforms, not as
// textures. Do this only when the environment supports 32bit floats
// due to problems when comparing 16bit floats with 32bit floats.
// TODO(https://github.com/tensorflow/tfjs/issues/821): Make it
// possible for packed shaders to sample from uniforms.
return {
shape: input.shape,
texData: null,
isUniform: true,
uniformValues: texData.values as TypedArray
};
}
// This ensures that if a packed program's inputs have not yet been
// uploaded to the GPU, they get uploaded as packed right off the bat.
if (program.packedInputs) {
texData.isPacked = true;
texData.shape = input.shape;
}
}
this.uploadToGPU(input.dataId);
if (!!texData.isPacked !== !!program.packedInputs) {
input = texData.isPacked ? this.unpackTensor(input) :
this.packTensor(input);
dataToDispose.push(input);
texData = this.texData.get(input.dataId);
} else if (
texData.isPacked &&
!webgl_util.isReshapeFree(texData.shape, input.shape)) {
// This is a special case where a texture exists for a tensor
// but the shapes are incompatible (due to packing constraints) because
// the tensor did not have a chance to go through the packed reshape
// shader. This only happens when we reshape the *same* tensor to form
// *distinct* inputs to an op, e.g. dotting a vector with itself. This
// case will disappear once packed uploading is the default.
const savedInput = input;
const targetShape = input.shape;
input.shape = texData.shape;
input = this.packedReshape(input as Tensor, targetShape);
dataToDispose.push(input);
texData = this.texData.get(input.dataId);
savedInput.shape = targetShape;
}
return {shape: input.shape, texData, isUniform: false};
});
this.uploadToGPU(output.dataId);
const outputData:
TensorData = {shape: output.shape, texData: outData, isUniform: false};
const key = gpgpu_math.makeShaderKey(program, inputsData, outputData);
const binary = this.getAndSaveBinary(key, () => {
return gpgpu_math.compileProgram(
this.gpgpu, program, inputsData, outputData);
});
const shouldTimeProgram = this.activeTimers != null;
let query: WebGLQuery|CPUTimerQuery;
if (shouldTimeProgram) {
query = this.startTimer();
}
if (!env().get('ENGINE_COMPILE_ONLY')) {
gpgpu_math.runProgram(
this.gpgpu, binary, inputsData, outputData, customUniformValues);
}
dataToDispose.forEach(info => this.disposeIntermediateTensorInfo(info));
if (shouldTimeProgram) {
query = this.endTimer(query);
this.activeTimers.push(
{name: program.constructor.name, query: this.getQueryTime(query)});
}
const glFlushThreshold = env().get('WEBGL_FLUSH_THRESHOLD');
// Manually GL flush requested
if (glFlushThreshold > 0) {
const time = util.now();
if ((time - this.lastGlFlushTime) > glFlushThreshold) {
this.gpgpu.gl.flush();
this.lastGlFlushTime = time;
}
}
if (!env().getBool('WEBGL_LAZILY_UNPACK') && outData.isPacked &&
preventEagerUnpackingOfOutput === false) {
const unpacked = this.unpackTensor(output);
this.disposeIntermediateTensorInfo(output);
return unpacked;
}
return output;
}
compileAndRun(
program: GPGPUProgram, inputs: TensorInfo[], outputDtype?: DataType,
customUniformValues?: number[][],
preventEagerUnpackingOfOutput = false): TensorInfo {
outputDtype = outputDtype || inputs[0].dtype;
const outInfo = this.runWebGLProgram(
program, inputs, outputDtype, customUniformValues,
preventEagerUnpackingOfOutput);
return outInfo;
}
private getAndSaveBinary(key: string, getBinary: () => GPGPUBinary):
GPGPUBinary {
if (!(key in this.binaryCache)) {
this.binaryCache[key] = getBinary();
}
return this.binaryCache[key];
}