UNPKG

23.8 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright 2019 Google Inc. All Rights Reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 * =============================================================================
17 */
18var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19 return new (P || (P = Promise))(function (resolve, reject) {
20 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
23 step((generator = generator.apply(thisArg, _arguments || [])).next());
24 });
25};
26var __generator = (this && this.__generator) || function (thisArg, body) {
27 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29 function verb(n) { return function (v) { return step([n, v]); }; }
30 function step(op) {
31 if (f) throw new TypeError("Generator is already executing.");
32 while (_) try {
33 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34 if (y = 0, t) op = [op[0] & 2, t.value];
35 switch (op[0]) {
36 case 0: case 1: t = op; break;
37 case 4: _.label++; return { value: op[1], done: false };
38 case 5: _.label++; y = op[1]; op = [0]; continue;
39 case 7: op = _.ops.pop(); _.trys.pop(); continue;
40 default:
41 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45 if (t[2]) _.ops.pop();
46 _.trys.pop(); continue;
47 }
48 op = body.call(thisArg, _);
49 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51 }
52};
53Object.defineProperty(exports, "__esModule", { value: true });
54var tfjs_1 = require("@tensorflow/tfjs");
55var fs = require("fs");
56var util_1 = require("util");
57var nodejs_kernel_backend_1 = require("./nodejs_kernel_backend");
58var readFile = util_1.promisify(fs.readFile);
59// tslint:disable-next-line:no-require-imports
60var messages = require('./proto/api_pb');
61var SAVED_MODEL_FILE_NAME = '/saved_model.pb';
62var SAVED_MODEL_INIT_OP_KEY = '__saved_model_init_op';
63// This map is used to keep track of loaded SavedModel metagraph mapping
64// information. The map key is TFSavedModel id in JavaScript, value is
65// an object of path to the SavedModel, metagraph tags, and loaded Session ID in
66// the c++ bindings. When user loads a SavedModel signature, it will go through
67// entries in this map to find if the corresponding SavedModel session has
68// already been loaded in C++ addon and will reuse it if existing.
69var loadedSavedModelPathMap = new Map();
70// The ID of loaded TFSavedModel. This ID is used to keep track of loaded
71// TFSavedModel, so the loaded session in c++ bindings for the corresponding
72// TFSavedModel can be properly reused/disposed.
73var nextTFSavedModelId = 0;
74/**
75 * Get a key in an object by its value. This is used to get protobuf enum value
76 * from index.
77 *
78 * @param object
79 * @param value
80 */
81// tslint:disable-next-line:no-any
82function getEnumKeyFromValue(object, value) {
83 return Object.keys(object).find(function (key) { return object[key] === value; });
84}
85exports.getEnumKeyFromValue = getEnumKeyFromValue;
86/**
87 * Read SavedModel proto message from path.
88 *
89 * @param path Path to SavedModel folder.
90 */
91function readSavedModelProto(path) {
92 return __awaiter(this, void 0, void 0, function () {
93 var modelFile, array;
94 return __generator(this, function (_a) {
95 switch (_a.label) {
96 case 0:
97 // Load the SavedModel pb file and deserialize it into message.
98 try {
99 fs.accessSync(path + SAVED_MODEL_FILE_NAME, fs.constants.R_OK);
100 }
101 catch (error) {
102 throw new Error('There is no saved_model.pb file in the directory: ' + path);
103 }
104 return [4 /*yield*/, readFile(path + SAVED_MODEL_FILE_NAME)];
105 case 1:
106 modelFile = _a.sent();
107 array = new Uint8Array(modelFile);
108 return [2 /*return*/, messages.SavedModel.deserializeBinary(array)];
109 }
110 });
111 });
112}
113exports.readSavedModelProto = readSavedModelProto;
114/**
115 * Inspect the MetaGraphs of the SavedModel from the provided path. This
116 * function will return an array of `MetaGraphInfo` objects.
117 *
118 * @param path Path to SavedModel folder.
119 */
120/**
121 * @doc {heading: 'Models', subheading: 'SavedModel', namespace: 'node'}
122 */
123function getMetaGraphsFromSavedModel(path) {
124 return __awaiter(this, void 0, void 0, function () {
125 var result, modelMessage, metaGraphList, i, metaGraph, tags, signatureDef, signatureDefMap, signatureDefKeys, key, signatureDefEntry, inputsMapMessage, inputsMapKeys, inputs, inputsMapKey, inputTensor, inputTensorInfo, outputsMapMessage, outputsMapKeys, outputs, outputsMapKey, outputTensor, outputTensorInfo;
126 return __generator(this, function (_a) {
127 switch (_a.label) {
128 case 0:
129 result = [];
130 return [4 /*yield*/, readSavedModelProto(path)];
131 case 1:
132 modelMessage = _a.sent();
133 metaGraphList = modelMessage.getMetaGraphsList();
134 for (i = 0; i < metaGraphList.length; i++) {
135 metaGraph = {};
136 tags = metaGraphList[i].getMetaInfoDef().getTagsList();
137 metaGraph.tags = tags;
138 signatureDef = {};
139 signatureDefMap = metaGraphList[i].getSignatureDefMap();
140 signatureDefKeys = signatureDefMap.keys();
141 // Go through all signatureDefs
142 while (true) {
143 key = signatureDefKeys.next();
144 if (key.done) {
145 break;
146 }
147 // Skip TensorFlow internal Signature '__saved_model_init_op'.
148 if (key.value === SAVED_MODEL_INIT_OP_KEY) {
149 continue;
150 }
151 signatureDefEntry = signatureDefMap.get(key.value);
152 inputsMapMessage = signatureDefEntry.getInputsMap();
153 inputsMapKeys = inputsMapMessage.keys();
154 inputs = {};
155 while (true) {
156 inputsMapKey = inputsMapKeys.next();
157 if (inputsMapKey.done) {
158 break;
159 }
160 inputTensor = inputsMapMessage.get(inputsMapKey.value);
161 inputTensorInfo = {};
162 inputTensorInfo.dtype = mapTFDtypeToJSDtype(getEnumKeyFromValue(messages.DataType, inputTensor.getDtype()));
163 inputTensorInfo.name = inputTensor.getName();
164 inputTensorInfo.shape = inputTensor.getTensorShape().getDimList();
165 inputs[inputsMapKey.value] = inputTensorInfo;
166 }
167 outputsMapMessage = signatureDefEntry.getOutputsMap();
168 outputsMapKeys = outputsMapMessage.keys();
169 outputs = {};
170 while (true) {
171 outputsMapKey = outputsMapKeys.next();
172 if (outputsMapKey.done) {
173 break;
174 }
175 outputTensor = outputsMapMessage.get(outputsMapKey.value);
176 outputTensorInfo = {};
177 outputTensorInfo.dtype = mapTFDtypeToJSDtype(getEnumKeyFromValue(messages.DataType, outputTensor.getDtype()));
178 outputTensorInfo.name = outputTensor.getName();
179 outputTensorInfo.shape = outputTensor.getTensorShape().getDimList();
180 outputs[outputsMapKey.value] = outputTensorInfo;
181 }
182 signatureDef[key.value] = { inputs: inputs, outputs: outputs };
183 }
184 metaGraph.signatureDefs = signatureDef;
185 result.push(metaGraph);
186 }
187 return [2 /*return*/, result];
188 }
189 });
190 });
191}
192exports.getMetaGraphsFromSavedModel = getMetaGraphsFromSavedModel;
193/**
194 * Get input and output node names from SavedModel metagraphs info. The
195 * input.output node names will be used when executing a SavedModel signature.
196 *
197 * @param savedModelInfo The MetaGraphInfo array loaded through
198 * getMetaGraphsFromSavedModel().
199 * @param tags The tags of the MetaGraph to get input/output node names from.
200 * @param signature The signature to get input/output node names from.
201 */
202function getInputAndOutputNodeNameFromMetaGraphInfo(savedModelInfo, tags, signature) {
203 for (var i = 0; i < savedModelInfo.length; i++) {
204 var metaGraphInfo = savedModelInfo[i];
205 if (stringArraysHaveSameElements(tags, metaGraphInfo.tags)) {
206 if (metaGraphInfo.signatureDefs[signature] == null) {
207 throw new Error('The SavedModel does not have signature: ' + signature);
208 }
209 var inputNodeNames = {};
210 var outputNodeNames = {};
211 for (var _i = 0, _a = Object.keys(metaGraphInfo.signatureDefs); _i < _a.length; _i++) {
212 var signatureDef = _a[_i];
213 if (signatureDef === signature) {
214 for (var _b = 0, _c = Object.keys(metaGraphInfo.signatureDefs[signature].inputs); _b < _c.length; _b++) {
215 var tensorName = _c[_b];
216 inputNodeNames[tensorName] =
217 metaGraphInfo.signatureDefs[signature].inputs[tensorName].name;
218 }
219 for (var _d = 0, _e = Object.keys(metaGraphInfo.signatureDefs[signature].outputs); _d < _e.length; _d++) {
220 var tensorName = _e[_d];
221 outputNodeNames[tensorName] =
222 metaGraphInfo.signatureDefs[signature].outputs[tensorName].name;
223 }
224 }
225 }
226 return [inputNodeNames, outputNodeNames];
227 }
228 }
229 throw new Error("The SavedModel does not have tags: " + tags);
230}
231exports.getInputAndOutputNodeNameFromMetaGraphInfo = getInputAndOutputNodeNameFromMetaGraphInfo;
232/**
233 * A `tf.TFSavedModel` is a signature loaded from a SavedModel
234 * metagraph, and allows inference execution.
235 */
236/**
237 * @doc {heading: 'Models', subheading: 'SavedModel', namespace: 'node'}
238 */
239var TFSavedModel = /** @class */ (function () {
240 function TFSavedModel(sessionId, jsid, inputNodeNames, outputNodeNames, backend) {
241 this.sessionId = sessionId;
242 this.jsid = jsid;
243 this.inputNodeNames = inputNodeNames;
244 this.outputNodeNames = outputNodeNames;
245 this.backend = backend;
246 this.disposed = false;
247 }
248 Object.defineProperty(TFSavedModel.prototype, "inputs", {
249 /**
250 * Return the array of input tensor info.
251 */
252 /** @doc {heading: 'Models', subheading: 'SavedModel'} */
253 get: function () {
254 throw new Error('SavedModel inputs information is not available yet.');
255 },
256 enumerable: true,
257 configurable: true
258 });
259 Object.defineProperty(TFSavedModel.prototype, "outputs", {
260 /**
261 * Return the array of output tensor info.
262 */
263 /** @doc {heading: 'Models', subheading: 'SavedModel'} */
264 get: function () {
265 throw new Error('SavedModel outputs information is not available yet.');
266 },
267 enumerable: true,
268 configurable: true
269 });
270 /**
271 * Delete the SavedModel from nodeBackend and delete corresponding session in
272 * the C++ backend if the session is only used by this TFSavedModel.
273 */
274 /** @doc {heading: 'Models', subheading: 'SavedModel'} */
275 TFSavedModel.prototype.dispose = function () {
276 if (!this.disposed) {
277 this.disposed = true;
278 loadedSavedModelPathMap.delete(this.jsid);
279 for (var _i = 0, _a = Array.from(loadedSavedModelPathMap.keys()); _i < _a.length; _i++) {
280 var id = _a[_i];
281 var value = loadedSavedModelPathMap.get(id);
282 if (value.sessionId === this.sessionId) {
283 return;
284 }
285 }
286 this.backend.deleteSavedModel(this.sessionId);
287 }
288 else {
289 throw new Error('This SavedModel has already been deleted.');
290 }
291 };
292 /**
293 * Execute the inference for the input tensors.
294 *
295 * @param input The input tensors, when there is single input for the model,
296 * inputs param should be a Tensor. For models with multiple inputs, inputs
297 * params should be in either Tensor[] if the input order is fixed, or
298 * otherwise NamedTensorMap format. The keys in the NamedTensorMap are the
299 * name of input tensors in SavedModel signatureDef. It can be found through
300 * `tf.node.getMetaGraphsFromSavedModel()`.
301 *
302 * For batch inference execution, the tensors for each input need to be
303 * concatenated together. For example with mobilenet, the required input shape
304 * is [1, 244, 244, 3], which represents the [batch, height, width, channel].
305 * If we are provide a batched data of 100 images, the input tensor should be
306 * in the shape of [100, 244, 244, 3].
307 *
308 * @param config Prediction configuration for specifying the batch size.
309 *
310 * @returns Inference result tensors. The output would be single Tensor if
311 * model has single output node, otherwise Tensor[] or NamedTensorMap[] will
312 * be returned for model with multiple outputs.
313 */
314 /** @doc {heading: 'Models', subheading: 'SavedModel'} */
315 TFSavedModel.prototype.predict = function (inputs, config) {
316 var _this = this;
317 if (this.disposed) {
318 throw new Error('The TFSavedModel has already been deleted!');
319 }
320 else {
321 var inputTensors = [];
322 if (inputs instanceof tfjs_1.Tensor) {
323 inputTensors.push(inputs);
324 var result = this.backend.runSavedModel(this.sessionId, inputTensors, Object.values(this.inputNodeNames), Object.values(this.outputNodeNames));
325 return result.length > 1 ? result : result[0];
326 }
327 else if (Array.isArray(inputs)) {
328 inputTensors = inputs;
329 return this.backend.runSavedModel(this.sessionId, inputTensors, Object.values(this.inputNodeNames), Object.values(this.outputNodeNames));
330 }
331 else {
332 var inputTensorNames = Object.keys(this.inputNodeNames);
333 var providedInputNames = Object.keys(inputs);
334 if (!stringArraysHaveSameElements(inputTensorNames, providedInputNames)) {
335 throw new Error("The model signatureDef input names are " + inputTensorNames.join() + ", however the provided input names are " + providedInputNames.join() + ".");
336 }
337 var inputNodeNamesArray = [];
338 for (var i = 0; i < inputTensorNames.length; i++) {
339 inputTensors.push(inputs[inputTensorNames[i]]);
340 inputNodeNamesArray.push(this.inputNodeNames[inputTensorNames[i]]);
341 }
342 var outputTensorNames = Object.keys(this.outputNodeNames);
343 var outputNodeNamesArray = [];
344 for (var i = 0; i < outputTensorNames.length; i++) {
345 outputNodeNamesArray.push(this.outputNodeNames[outputTensorNames[i]]);
346 }
347 var outputTensors_1 = this.backend.runSavedModel(this.sessionId, inputTensors, inputNodeNamesArray, outputNodeNamesArray);
348 tfjs_1.util.assert(outputTensors_1.length === outputNodeNamesArray.length, function () { return 'Output tensors do not match output node names, ' +
349 ("receive " + outputTensors_1.length + ") output tensors but ") +
350 ("there are " + _this.outputNodeNames.length + " output nodes."); });
351 var outputMap = {};
352 for (var i = 0; i < outputTensorNames.length; i++) {
353 outputMap[outputTensorNames[i]] = outputTensors_1[i];
354 }
355 return outputMap;
356 }
357 }
358 };
359 /**
360 * Execute the inference for the input tensors and return activation
361 * values for specified output node names without batching.
362 *
363 * @param input The input tensors, when there is single input for the model,
364 * inputs param should be a Tensor. For models with multiple inputs, inputs
365 * params should be in either Tensor[] if the input order is fixed, or
366 * otherwise NamedTensorMap format.
367 *
368 * @param outputs string|string[]. List of output node names to retrieve
369 * activation from.
370 *
371 * @returns Activation values for the output nodes result tensors. The return
372 * type matches specified parameter outputs type. The output would be single
373 * Tensor if single output is specified, otherwise Tensor[] for multiple
374 * outputs.
375 */
376 /** @doc {heading: 'Models', subheading: 'SavedModel'} */
377 TFSavedModel.prototype.execute = function (inputs, outputs) {
378 throw new Error('execute() of TFSavedModel is not supported yet.');
379 };
380 return TFSavedModel;
381}());
382exports.TFSavedModel = TFSavedModel;
383/**
384 * Load a TensorFlow SavedModel from disk. TensorFlow SavedModel is different
385 * from TensorFlow.js model format. A SavedModel is a directory containing
386 * serialized signatures and the states needed to run them. The directory has a
387 * saved_model.pb (or saved_model.pbtxt) file storing the actual TensorFlow
388 * program, or model, and a set of named signatures, each identifying a
389 * function. The directory also has a variables directory contains a standard
390 * training checkpoint. The directory may also has a assets directory contains
391 * files used by the TensorFlow graph, for example text files used to initialize
392 * vocabulary tables. These are supported datatypes: float32, int32, complex64,
393 * string.For more information, see this guide:
394 * https://www.tensorflow.org/guide/saved_model.
395 *
396 * @param path The path to the SavedModel.
397 * @param tags The tags of the MetaGraph to load. The available tags of a
398 * SavedModel can be retrieved through tf.node.getMetaGraphsFromSavedModel()
399 * API. Defaults to ['serve'].
400 * @param signature The name of the SignatureDef to load. The available
401 * SignatureDefs of a SavedModel can be retrieved through
402 * tf.node.getMetaGraphsFromSavedModel() API. Defaults to 'serving_default'.
403 */
404/** @doc {heading: 'Models', subheading: 'SavedModel', namespace: 'node'} */
405function loadSavedModel(path, tags, signature) {
406 if (tags === void 0) { tags = ['serve']; }
407 if (signature === void 0) { signature = 'serving_default'; }
408 return __awaiter(this, void 0, void 0, function () {
409 var backend, savedModelInfo, _a, inputNodeNames, outputNodeNames, sessionId, _i, _b, id_1, modelInfo, tagsString, id, savedModel;
410 return __generator(this, function (_c) {
411 switch (_c.label) {
412 case 0:
413 nodejs_kernel_backend_1.ensureTensorflowBackend();
414 backend = nodejs_kernel_backend_1.nodeBackend();
415 return [4 /*yield*/, getMetaGraphsFromSavedModel(path)];
416 case 1:
417 savedModelInfo = _c.sent();
418 _a = getInputAndOutputNodeNameFromMetaGraphInfo(savedModelInfo, tags, signature), inputNodeNames = _a[0], outputNodeNames = _a[1];
419 for (_i = 0, _b = Array.from(loadedSavedModelPathMap.keys()); _i < _b.length; _i++) {
420 id_1 = _b[_i];
421 modelInfo = loadedSavedModelPathMap.get(id_1);
422 if (modelInfo.path === path &&
423 stringArraysHaveSameElements(modelInfo.tags, tags)) {
424 sessionId = modelInfo.sessionId;
425 }
426 }
427 if (sessionId == null) {
428 tagsString = tags.join(',');
429 sessionId = backend.loadSavedModelMetaGraph(path, tagsString);
430 }
431 id = nextTFSavedModelId++;
432 savedModel = new TFSavedModel(sessionId, id, inputNodeNames, outputNodeNames, backend);
433 loadedSavedModelPathMap.set(id, { path: path, tags: tags, sessionId: sessionId });
434 return [2 /*return*/, savedModel];
435 }
436 });
437 });
438}
439exports.loadSavedModel = loadSavedModel;
440/**
441 * Compare if two unsorted arrays of string have the same elements.
442 * @param arrayA
443 * @param arrayB
444 */
445function stringArraysHaveSameElements(arrayA, arrayB) {
446 if (arrayA.length === arrayB.length &&
447 arrayA.sort().join() === arrayB.sort().join()) {
448 return true;
449 }
450 return false;
451}
452function mapTFDtypeToJSDtype(tfDtype) {
453 switch (tfDtype) {
454 case 'DT_FLOAT':
455 return 'float32';
456 case 'DT_INT32':
457 return 'int32';
458 case 'DT_BOOL':
459 return 'bool';
460 case 'DT_COMPLEX64':
461 return 'complex64';
462 case 'DT_STRING':
463 return 'string';
464 default:
465 throw new Error('Unsupported tensor DataType: ' + tfDtype +
466 ', try to modify the model in python to convert the datatype');
467 }
468}
469function getNumOfSavedModels() {
470 nodejs_kernel_backend_1.ensureTensorflowBackend();
471 var backend = nodejs_kernel_backend_1.nodeBackend();
472 return backend.getNumOfSavedModels();
473}
474exports.getNumOfSavedModels = getNumOfSavedModels;