forked from tensorflow/tfjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend_cpu.ts
232 lines (197 loc) · 7.21 KB
/
backend_cpu.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
/**
* @license
* Copyright 2021 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 {backend_util, BackendTimingInfo, buffer, DataStorage, DataType, engine, env, kernel_impls, KernelBackend, Rank, ShapeMap, Tensor, Tensor2D, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';
const whereImpl = kernel_impls.whereImpl;
import {assertNotComplex} from './cpu_util';
interface DataId {}
export interface TensorData<D extends DataType> {
values?: backend_util.BackendValues;
dtype: D;
// For complex numbers, the real and imaginary parts are stored as their own
// individual tensors, with a parent joining the two with the
// complexTensorInfos field.
complexTensorInfos?: {real: TensorInfo, imag: TensorInfo};
// refCount keeps track of how many tensors reference it. Used for memory
// management.
refCount: number;
}
export class MathBackendCPU extends KernelBackend {
public blockSize = 48;
data: DataStorage<TensorData<DataType>>;
private firstUse = true;
private static nextDataId = 0;
private nextDataId(): number {
return MathBackendCPU.nextDataId++;
}
constructor() {
super();
this.data = new DataStorage(this, engine());
}
override write(values: backend_util.BackendValues, shape: number[],
dtype: DataType): DataId {
if (this.firstUse) {
this.firstUse = false;
if (env().get('IS_NODE')) {
backend_util.warn(
'\n============================\n' +
'Hi, looks like you are running TensorFlow.js in ' +
'Node.js. To speed things up dramatically, install our node ' +
'backend, visit https://github.com/tensorflow/tfjs-node for more details. ' +
'\n============================');
}
}
const dataId = {id: this.nextDataId()};
this.data.set(dataId, {values, dtype, refCount: 1});
return dataId;
}
/**
* Create a data bucket in cpu backend.
* @param shape Shape of the `TensorInfo`.
* @param dtype DType of the `TensorInfo`.
* @param values The value of the `TensorInfo` stored as a flattened array.
*/
makeTensorInfo(
shape: number[], dtype: DataType,
values?: backend_util.BackendValues|string[]): TensorInfo {
let outId;
if (dtype === 'string' && values != null && values.length > 0 &&
util.isString(values[0])) {
const encodedValues =
(values as unknown as string[]).map(d => util.encodeString(d));
outId = this.write(encodedValues, shape, dtype);
} else {
outId = this.write(values as TypedArray, shape, dtype);
}
return {dataId: outId, shape, dtype};
}
/** Return refCount of a `TensorData`. */
override refCount(dataId: DataId): number {
if (this.data.has(dataId)) {
const tensorData = this.data.get(dataId);
return tensorData.refCount;
}
return 0;
}
/** Increase refCount of a `TensorData`. */
override incRef(dataId: DataId): void {
const tensorData = this.data.get(dataId);
tensorData.refCount++;
}
/** Decrease refCount of a `TensorData`. */
decRef(dataId: DataId): void {
if (this.data.has(dataId)) {
const tensorData = this.data.get(dataId);
tensorData.refCount--;
}
}
override move(
dataId: DataId, values: backend_util.BackendValues, shape: number[],
dtype: DataType, refCount: number): void {
this.data.set(dataId, {values, dtype, refCount});
}
override numDataIds(): number {
return this.data.numDataIds();
}
override async read(dataId: DataId): Promise<backend_util.BackendValues> {
return this.readSync(dataId);
}
override readSync(dataId: DataId): backend_util.BackendValues {
const {dtype, complexTensorInfos} = this.data.get(dataId);
if (dtype === 'complex64') {
const realValues =
this.readSync(complexTensorInfos.real.dataId) as Float32Array;
const imagValues =
this.readSync(complexTensorInfos.imag.dataId) as Float32Array;
return backend_util.mergeRealAndImagArrays(realValues, imagValues);
}
return this.data.get(dataId).values;
}
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>;
}
makeOutput<T extends Tensor>(
values: backend_util.BackendValues, shape: number[], dtype: DataType): T {
return engine().makeTensorFromTensorInfo(
this.makeTensorInfo(shape, dtype, values), this) as T;
}
/**
* Dispose the memory if the dataId has 0 refCount. Return true if the memory
* is released or memory is not managed in this backend, false if memory is
* not cleared.
* @param dataId
* @oaram force Optional, remove the data regardless of refCount
*/
override disposeData(dataId: DataId, force = false): boolean {
if (this.data.has(dataId)) {
this.data.get(dataId).refCount--;
if (!force && this.data.get(dataId).refCount > 0) {
return false;
}
const {complexTensorInfos} = this.data.get(dataId);
if (complexTensorInfos != null) {
this.disposeData(complexTensorInfos.real.dataId, true);
this.disposeData(complexTensorInfos.imag.dataId, true);
}
this.data.delete(dataId);
}
return true;
}
disposeIntermediateTensorInfo(tensorInfo: TensorInfo): void {
this.disposeData(tensorInfo.dataId);
}
override async time(f: () => void): Promise<BackendTimingInfo> {
const start = util.now();
f();
const kernelMs = util.now() - start;
return {kernelMs};
}
override memory() {
return {
// Unreliable due to automatic gc. The numbers above are cumulative.
unreliable: true,
reasons:
['The reported memory is an upper bound. Due to automatic garbage ' +
'collection, the true allocated memory may be less.']
};
}
where(condition: Tensor): Tensor2D {
assertNotComplex([condition], 'where');
const condVals = this.readSync(condition.dataId) as TypedArray;
return whereImpl(condition.shape, condVals);
}
override dispose() {}
override floatPrecision(): 16|32 {
return 32;
}
/** Returns the smallest representable number. */
override epsilon(): number {
return super.epsilon();
}
}