-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathsaved_model.ts
396 lines (364 loc) · 15.3 KB
/
saved_model.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
/**
* @license
* Copyright 2019 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.
* =============================================================================
*/
import {InferenceModel, MetaGraphInfo, ModelPredictConfig, ModelTensorInfo, NamedTensorMap, SavedModelTensorInfo, SignatureDefInfo, Tensor, util} from '@tensorflow/tfjs';
import * as fs from 'fs';
import {promisify} from 'util';
import {ensureTensorflowBackend, nodeBackend, NodeJSKernelBackend} from './nodejs_kernel_backend';
const readFile = promisify(fs.readFile);
// tslint:disable-next-line:no-require-imports
const messages = require('./proto/api_pb');
const SAVED_MODEL_FILE_NAME = '/saved_model.pb';
// This map is used to keep track of loaded SavedModel metagraph mapping
// information. The map key is TFSavedModel id in JavaScript, value is
// an object of path to the SavedModel, metagraph tags, and loaded Session ID in
// the c++ bindings. When user loads a SavedModel signature, it will go through
// entries in this map to find if the corresponding SavedModel session has
// already been loaded in C++ addon and will reuse it if existing.
const loadedSavedModelPathMap =
new Map<number, {path: string, tags: string[], sessionId: number}>();
// The ID of loaded TFSavedModel. This ID is used to keep track of loaded
// TFSavedModel, so the loaded session in c++ bindings for the corresponding
// TFSavedModel can be properly reused/disposed.
let nextTFSavedModelId = 0;
/**
* Get a key in an object by its value. This is used to get protobuf enum value
* from index.
*
* @param object
* @param value
*/
// tslint:disable-next-line:no-any
export function getEnumKeyFromValue(object: any, value: number): string {
return Object.keys(object).find(key => object[key] === value);
}
/**
* Read SavedModel proto message from path.
*
* @param path Path to SavedModel folder.
*/
export async function readSavedModelProto(path: string) {
// Load the SavedModel pb file and deserialize it into message.
try {
fs.accessSync(path + SAVED_MODEL_FILE_NAME, fs.constants.R_OK);
} catch (error) {
throw new Error(
'There is no saved_model.pb file in the directory: ' + path);
}
const modelFile = await readFile(path + SAVED_MODEL_FILE_NAME);
const array = new Uint8Array(modelFile);
return messages.SavedModel.deserializeBinary(array);
}
/**
* Inspect the MetaGraphs of the SavedModel from the provided path. This
* function will return an array of `MetaGraphInfo` objects.
*
* @param path Path to SavedModel folder.
*/
/**
* @doc {heading: 'Models', subheading: 'SavedModel', namespace: 'node'}
*/
export async function getMetaGraphsFromSavedModel(path: string):
Promise<MetaGraphInfo[]> {
const result: MetaGraphInfo[] = [];
// Get SavedModel proto message
const modelMessage = await readSavedModelProto(path);
// A SavedModel might have multiple MetaGraphs, identified by tags. Each
// MetaGraph also has it's own signatureDefs.
const metaGraphList = modelMessage.getMetaGraphsList();
for (let i = 0; i < metaGraphList.length; i++) {
const metaGraph = {} as MetaGraphInfo;
const tags = metaGraphList[i].getMetaInfoDef().getTagsList();
metaGraph.tags = tags;
// Each MetaGraph has it's own signatureDefs map.
const signatureDef: SignatureDefInfo = {};
const signatureDefMap = metaGraphList[i].getSignatureDefMap();
const signatureDefKeys = signatureDefMap.keys();
// Go through all signatureDefs
while (true) {
const key = signatureDefKeys.next();
if (key.done) {
break;
}
const signatureDefEntry = signatureDefMap.get(key.value);
// Get all input tensors information
const inputsMapMessage = signatureDefEntry.getInputsMap();
const inputsMapKeys = inputsMapMessage.keys();
const inputs: {[key: string]: SavedModelTensorInfo} = {};
while (true) {
const inputsMapKey = inputsMapKeys.next();
if (inputsMapKey.done) {
break;
}
const inputTensor = inputsMapMessage.get(inputsMapKey.value);
const inputTensorInfo = {} as SavedModelTensorInfo;
inputTensorInfo.dtype =
getEnumKeyFromValue(messages.DataType, inputTensor.getDtype());
inputTensorInfo.name = inputTensor.getName();
inputTensorInfo.shape = inputTensor.getTensorShape().getDimList();
inputs[inputsMapKey.value] = inputTensorInfo;
}
// Get all output tensors information
const outputsMapMessage = signatureDefEntry.getOutputsMap();
const outputsMapKeys = outputsMapMessage.keys();
const outputs: {[key: string]: SavedModelTensorInfo} = {};
while (true) {
const outputsMapKey = outputsMapKeys.next();
if (outputsMapKey.done) {
break;
}
const outputTensor = outputsMapMessage.get(outputsMapKey.value);
const outputTensorInfo = {} as SavedModelTensorInfo;
outputTensorInfo.dtype =
getEnumKeyFromValue(messages.DataType, outputTensor.getDtype());
outputTensorInfo.name = outputTensor.getName();
outputTensorInfo.shape = outputTensor.getTensorShape().getDimList();
outputs[outputsMapKey.value] = outputTensorInfo;
}
signatureDef[key.value] = {inputs, outputs};
}
metaGraph.signatureDefs = signatureDef;
result.push(metaGraph);
}
return result;
}
/**
* Get input and output node names from SavedModel metagraphs info. The
* input.output node names will be used when executing a SavedModel signature.
*
* @param savedModelInfo The MetaGraphInfo array loaded through
* getMetaGraphsFromSavedModel().
* @param tags The tags of the MetaGraph to get input/output node names from.
* @param signature The signature to get input/output node names from.
*/
export function getInputAndOutputNodeNameFromMetaGraphInfo(
savedModelInfo: MetaGraphInfo[], tags: string[], signature: string) {
for (let i = 0; i < savedModelInfo.length; i++) {
const metaGraphInfo = savedModelInfo[i];
if (stringArraysHaveSameElements(tags, metaGraphInfo.tags)) {
if (metaGraphInfo.signatureDefs[signature] == null) {
throw new Error('The SavedModel does not have signature: ' + signature);
}
const inputNodeNames: string[] = [];
const outputNodeNames: string[] = [];
for (const signatureDef of Object.keys(metaGraphInfo.signatureDefs)) {
if (signatureDef === signature) {
for (const tensorName of Object.keys(
metaGraphInfo.signatureDefs[signature].inputs)) {
inputNodeNames.push(
metaGraphInfo.signatureDefs[signature].inputs[tensorName].name);
}
for (const tensorName of Object.keys(
metaGraphInfo.signatureDefs[signature].outputs)) {
outputNodeNames.push(metaGraphInfo.signatureDefs[signature]
.outputs[tensorName]
.name);
}
}
}
return [inputNodeNames, outputNodeNames];
}
}
throw new Error(`The SavedModel does not have tags: ${tags}`);
}
/**
* A `tf.TFSavedModel` is a signature loaded from a SavedModel
* metagraph, and allows inference exeuction.
*/
/**
* @doc {heading: 'Models', subheading: 'SavedModel', namespace: 'node'}
*/
export class TFSavedModel implements InferenceModel {
private disposed = false;
constructor(
private sessionId: number, private jsid: number,
private inputNodeNames: string[], private outputNodeNames: string[],
private backend: NodeJSKernelBackend) {}
/**
* Return the array of input tensor info.
*/
/** @doc {heading: 'Models', subheading: 'SavedModel'} */
get inputs(): ModelTensorInfo[] {
throw new Error('SavedModel inputs information is not available yet.');
}
/**
* Return the array of output tensor info.
*/
/** @doc {heading: 'Models', subheading: 'SavedModel'} */
get outputs(): ModelTensorInfo[] {
throw new Error('SavedModel outputs information is not available yet.');
}
/**
* Delete the SavedModel from nodeBackend and delete corresponding session in
* the C++ backend if the session is only used by this TFSavedModel.
*/
/** @doc {heading: 'Models', subheading: 'SavedModel'} */
dispose() {
if (!this.disposed) {
this.disposed = true;
loadedSavedModelPathMap.delete(this.jsid);
for (const id of Array.from(loadedSavedModelPathMap.keys())) {
const value = loadedSavedModelPathMap.get(id);
if (value.sessionId === this.sessionId) {
return;
}
}
this.backend.deleteSavedModel(this.sessionId);
} else {
throw new Error('This SavedModel has already been deleted.');
}
}
/**
* Execute the inference for the input tensors.
*
* @param input The input tensors, when there is single input for the model,
* inputs param should be a Tensor. For models with multiple inputs, inputs
* params should be in either Tensor[] if the input order is fixed, or
* otherwise NamedTensorMap format.
* For batch inference execution, the tensors for each input need to be
* concatenated together. For example with mobilenet, the required input shape
* is [1, 244, 244, 3], which represents the [batch, height, width, channel].
* If we are provide a batched data of 100 images, the input tensor should be
* in the shape of [100, 244, 244, 3].
*
* @param config Prediction configuration for specifying the batch size.
*
* @returns Inference result tensors. The output would be single Tensor if
* model has single output node, otherwise Tensor[] or NamedTensorMap[] will
* be returned for model with multiple outputs.
*/
/** @doc {heading: 'Models', subheading: 'SavedModel'} */
predict(inputs: Tensor|Tensor[]|NamedTensorMap, config?: ModelPredictConfig):
Tensor|Tensor[]|NamedTensorMap {
if (this.disposed) {
throw new Error('The TFSavedModel has already been deleted!');
} else {
let inputTensors: Tensor[] = [];
if (inputs instanceof Tensor) {
inputTensors.push(inputs);
return this.backend.runSavedModel(
this.sessionId, inputTensors, this.inputNodeNames.join(),
this.outputNodeNames.join())[0];
} else if (Array.isArray(inputs)) {
inputTensors = inputs;
return this.backend.runSavedModel(
this.sessionId, inputTensors, this.inputNodeNames.join(),
this.outputNodeNames.join());
} else {
for (let i = 0; i < this.inputNodeNames.length; i++) {
inputTensors.push(inputs[this.inputNodeNames[i]]);
}
const outputTensors = this.backend.runSavedModel(
this.sessionId, inputTensors, this.inputNodeNames.join(),
this.outputNodeNames.join());
util.assert(
outputTensors.length === this.outputNodeNames.length,
() => 'Output tensors do not match output node names, ' +
`receive ${outputTensors.length}) output tensors but ` +
`there are ${this.outputNodeNames.length} output nodes.`);
const outputMap: NamedTensorMap = {};
for (let i = 0; i < this.outputNodeNames.length; i++) {
outputMap[this.outputNodeNames[i]] = outputTensors[i];
}
return outputMap;
}
}
}
/**
* Execute the inference for the input tensors and return activation
* values for specified output node names without batching.
*
* @param input The input tensors, when there is single input for the model,
* inputs param should be a Tensor. For models with multiple inputs, inputs
* params should be in either Tensor[] if the input order is fixed, or
* otherwise NamedTensorMap format.
*
* @param outputs string|string[]. List of output node names to retrieve
* activation from.
*
* @returns Activation values for the output nodes result tensors. The return
* type matches specified parameter outputs type. The output would be single
* Tensor if single output is specified, otherwise Tensor[] for multiple
* outputs.
*/
/** @doc {heading: 'Models', subheading: 'SavedModel'} */
execute(inputs: Tensor|Tensor[]|NamedTensorMap, outputs: string|string[]):
Tensor|Tensor[] {
throw new Error('execute() of TFSavedModel is not supported yet.');
}
}
/**
* Load a TensorFlow SavedModel from disk. TensorFlow SavedModel is different
* from TensorFlow.js model format. A SavedModel is a directory containing
* serialized signatures and the states needed to run them. The directory has a
* saved_model.pb (or saved_model.pbtxt) file storing the actual TensorFlow
* program, or model, and a set of named signatures, each identifying a
* function. The directory also has a variables directory contains a standard
* training checkpoint. The directory may also has a assets directory contains
* files used by the TensorFlow graph, for example text files used to initialize
* vocabulary tables. For more information, see this guide:
* https://www.tensorflow.org/guide/saved_model.
*
* @param path The path to the SavedModel.
* @param tags The tags of the MetaGraph to load. The available tags of a
* SavedModel can be retrieved through tf.node.getMetaGraphsFromSavedModel()
* API. Defaults to ['serve'].
* @param signature The name of the SignatureDef to load. The available
* SignatureDefs of a SavedModel can be retrieved through
* tf.node.getMetaGraphsFromSavedModel() API. Defaults to 'serving_default'.
*/
/** @doc {heading: 'Models', subheading: 'SavedModel', namespace: 'node'} */
export async function loadSavedModel(
path: string, tags = ['serve'],
signature = 'serving_default'): Promise<TFSavedModel> {
ensureTensorflowBackend();
const backend = nodeBackend();
const savedModelInfo = await getMetaGraphsFromSavedModel(path);
const [inputNodeNames, outputNodeNames] =
getInputAndOutputNodeNameFromMetaGraphInfo(
savedModelInfo, tags, signature);
let sessionId: number;
for (const id of Array.from(loadedSavedModelPathMap.keys())) {
const modelInfo = loadedSavedModelPathMap.get(id);
if (modelInfo.path === path &&
stringArraysHaveSameElements(modelInfo.tags, tags)) {
sessionId = modelInfo.sessionId;
}
}
if (sessionId == null) {
// Convert metagraph tags string array to a string.
const tagsString = tags.join();
sessionId = backend.loadSavedModelMetaGraph(path, tagsString);
}
const id = nextTFSavedModelId++;
const savedModel =
new TFSavedModel(sessionId, id, inputNodeNames, outputNodeNames, backend);
loadedSavedModelPathMap.set(id, {path, tags, sessionId});
return savedModel;
}
/**
* Compare if two unsorted arrays of string have the same elements.
* @param arrayA
* @param arrayB
*/
function stringArraysHaveSameElements(
arrayA: string[], arrayB: string[]): boolean {
if (arrayA.length === arrayB.length &&
arrayA.sort().join() === arrayB.sort().join()) {
return true;
}
return false;
}