UNPKG

14.4 kBTypeScriptView Raw
1/**
2 * @license
3 * Copyright 2018 Google LLC. All Rights Reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 * =============================================================================
16 */
17/// <amd-module name="@tensorflow/tfjs-converter/dist/executor/graph_model" />
18import { InferenceModel, io, ModelPredictConfig, NamedTensorMap, Tensor } from '@tensorflow/tfjs-core';
19import { NamedTensorsMap, TensorInfo } from '../data/types';
20export declare const TFHUB_SEARCH_PARAM = "?tfjs-format=file";
21export declare const DEFAULT_MODEL_NAME = "model.json";
22type Url = string | io.IOHandler | io.IOHandlerSync;
23type UrlIOHandler<T extends Url> = T extends string ? io.IOHandler : T;
24/**
25 * A `tf.GraphModel` is a directed, acyclic graph built from a
26 * SavedModel GraphDef and allows inference execution.
27 *
28 * A `tf.GraphModel` can only be created by loading from a model converted from
29 * a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using
30 * the command line converter tool and loaded via `tf.loadGraphModel`.
31 *
32 * @doc {heading: 'Models', subheading: 'Classes'}
33 */
34export declare class GraphModel<ModelURL extends Url = string | io.IOHandler> implements InferenceModel {
35 private modelUrl;
36 private loadOptions;
37 private executor;
38 private version;
39 private handler;
40 private artifacts;
41 private initializer;
42 private resourceIdToCapturedInput;
43 private resourceManager;
44 private signature;
45 private initializerSignature;
46 private structuredOutputKeys;
47 private readonly io;
48 get modelVersion(): string;
49 get inputNodes(): string[];
50 get outputNodes(): string[];
51 get inputs(): TensorInfo[];
52 get outputs(): TensorInfo[];
53 get weights(): NamedTensorsMap;
54 get metadata(): {};
55 get modelSignature(): {};
56 get modelStructuredOutputKeys(): {};
57 /**
58 * @param modelUrl url for the model, or an `io.IOHandler`.
59 * @param weightManifestUrl url for the weight file generated by
60 * scripts/convert.py script.
61 * @param requestOption options for Request, which allows to send credentials
62 * and custom headers.
63 * @param onProgress Optional, progress callback function, fired periodically
64 * before the load is completed.
65 */
66 constructor(modelUrl: ModelURL, loadOptions?: io.LoadOptions, tfio?: typeof io);
67 private findIOHandler;
68 /**
69 * Loads the model and weight files, construct the in memory weight map and
70 * compile the inference graph.
71 */
72 load(): UrlIOHandler<ModelURL> extends io.IOHandlerSync ? boolean : Promise<boolean>;
73 /**
74 * Synchronously construct the in memory weight map and
75 * compile the inference graph.
76 *
77 * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
78 */
79 loadSync(artifacts: io.ModelArtifacts): boolean;
80 /**
81 * Save the configuration and/or weights of the GraphModel.
82 *
83 * An `IOHandler` is an object that has a `save` method of the proper
84 * signature defined. The `save` method manages the storing or
85 * transmission of serialized data ("artifacts") that represent the
86 * model's topology and weights onto or via a specific medium, such as
87 * file downloads, local storage, IndexedDB in the web browser and HTTP
88 * requests to a server. TensorFlow.js provides `IOHandler`
89 * implementations for a number of frequently used saving mediums, such as
90 * `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`
91 * for more details.
92 *
93 * This method also allows you to refer to certain types of `IOHandler`s
94 * as URL-like string shortcuts, such as 'localstorage://' and
95 * 'indexeddb://'.
96 *
97 * Example 1: Save `model`'s topology and weights to browser [local
98 * storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
99 * then load it back.
100 *
101 * ```js
102 * const modelUrl =
103 * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
104 * const model = await tf.loadGraphModel(modelUrl);
105 * const zeros = tf.zeros([1, 224, 224, 3]);
106 * model.predict(zeros).print();
107 *
108 * const saveResults = await model.save('localstorage://my-model-1');
109 *
110 * const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');
111 * console.log('Prediction from loaded model:');
112 * model.predict(zeros).print();
113 * ```
114 *
115 * @param handlerOrURL An instance of `IOHandler` or a URL-like,
116 * scheme-based string shortcut for `IOHandler`.
117 * @param config Options for saving the model.
118 * @returns A `Promise` of `SaveResult`, which summarizes the result of
119 * the saving, such as byte sizes of the saved artifacts for the model's
120 * topology and weight values.
121 *
122 * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
123 */
124 save(handlerOrURL: io.IOHandler | string, config?: io.SaveConfig): Promise<io.SaveResult>;
125 private addStructuredOutputNames;
126 /**
127 * Execute the inference for the input tensors.
128 *
129 * @param input The input tensors, when there is single input for the model,
130 * inputs param should be a `tf.Tensor`. For models with mutliple inputs,
131 * inputs params should be in either `tf.Tensor`[] if the input order is
132 * fixed, or otherwise NamedTensorMap format.
133 *
134 * For model with multiple inputs, we recommend you use NamedTensorMap as the
135 * input type, if you use `tf.Tensor`[], the order of the array needs to
136 * follow the
137 * order of inputNodes array. @see {@link GraphModel.inputNodes}
138 *
139 * You can also feed any intermediate nodes using the NamedTensorMap as the
140 * input type. For example, given the graph
141 * InputNode => Intermediate => OutputNode,
142 * you can execute the subgraph Intermediate => OutputNode by calling
143 * model.execute('IntermediateNode' : tf.tensor(...));
144 *
145 * This is useful for models that uses tf.dynamic_rnn, where the intermediate
146 * state needs to be fed manually.
147 *
148 * For batch inference execution, the tensors for each input need to be
149 * concatenated together. For example with mobilenet, the required input shape
150 * is [1, 244, 244, 3], which represents the [batch, height, width, channel].
151 * If we are provide a batched data of 100 images, the input tensor should be
152 * in the shape of [100, 244, 244, 3].
153 *
154 * @param config Prediction configuration for specifying the batch size.
155 * Currently the batch size option is ignored for graph model.
156 *
157 * @returns Inference result tensors. If the model is converted and it
158 * originally had structured_outputs in tensorflow, then a NamedTensorMap
159 * will be returned matching the structured_outputs. If no structured_outputs
160 * are present, the output will be single `tf.Tensor` if the model has single
161 * output node, otherwise Tensor[].
162 *
163 * @doc {heading: 'Models', subheading: 'Classes'}
164 */
165 predict(inputs: Tensor | Tensor[] | NamedTensorMap, config?: ModelPredictConfig): Tensor | Tensor[] | NamedTensorMap;
166 /**
167 * Execute the inference for the input tensors in async fashion, use this
168 * method when your model contains control flow ops.
169 *
170 * @param input The input tensors, when there is single input for the model,
171 * inputs param should be a `tf.Tensor`. For models with mutliple inputs,
172 * inputs params should be in either `tf.Tensor`[] if the input order is
173 * fixed, or otherwise NamedTensorMap format.
174 *
175 * For model with multiple inputs, we recommend you use NamedTensorMap as the
176 * input type, if you use `tf.Tensor`[], the order of the array needs to
177 * follow the
178 * order of inputNodes array. @see {@link GraphModel.inputNodes}
179 *
180 * You can also feed any intermediate nodes using the NamedTensorMap as the
181 * input type. For example, given the graph
182 * InputNode => Intermediate => OutputNode,
183 * you can execute the subgraph Intermediate => OutputNode by calling
184 * model.execute('IntermediateNode' : tf.tensor(...));
185 *
186 * This is useful for models that uses tf.dynamic_rnn, where the intermediate
187 * state needs to be fed manually.
188 *
189 * For batch inference execution, the tensors for each input need to be
190 * concatenated together. For example with mobilenet, the required input shape
191 * is [1, 244, 244, 3], which represents the [batch, height, width, channel].
192 * If we are provide a batched data of 100 images, the input tensor should be
193 * in the shape of [100, 244, 244, 3].
194 *
195 * @param config Prediction configuration for specifying the batch size.
196 * Currently the batch size option is ignored for graph model.
197 *
198 * @returns A Promise of inference result tensors. If the model is converted
199 * and it originally had structured_outputs in tensorflow, then a
200 * NamedTensorMap will be returned matching the structured_outputs. If no
201 * structured_outputs are present, the output will be single `tf.Tensor` if
202 * the model has single output node, otherwise Tensor[].
203 *
204 * @doc {heading: 'Models', subheading: 'Classes'}
205 */
206 predictAsync(inputs: Tensor | Tensor[] | NamedTensorMap, config?: ModelPredictConfig): Promise<Tensor | Tensor[] | NamedTensorMap>;
207 private normalizeInputs;
208 private normalizeOutputs;
209 private executeInitializerGraph;
210 private executeInitializerGraphAsync;
211 private setResourceIdToCapturedInput;
212 /**
213 * Executes inference for the model for given input tensors.
214 * @param inputs tensor, tensor array or tensor map of the inputs for the
215 * model, keyed by the input node names.
216 * @param outputs output node name from the TensorFlow model, if no
217 * outputs are specified, the default outputs of the model would be used.
218 * You can inspect intermediate nodes of the model by adding them to the
219 * outputs array.
220 *
221 * @returns A single tensor if provided with a single output or no outputs
222 * are provided and there is only one default output, otherwise return a
223 * tensor array. The order of the tensor array is the same as the outputs
224 * if provided, otherwise the order of outputNodes attribute of the model.
225 *
226 * @doc {heading: 'Models', subheading: 'Classes'}
227 */
228 execute(inputs: Tensor | Tensor[] | NamedTensorMap, outputs?: string | string[]): Tensor | Tensor[];
229 /**
230 * Executes inference for the model for given input tensors in async
231 * fashion, use this method when your model contains control flow ops.
232 * @param inputs tensor, tensor array or tensor map of the inputs for the
233 * model, keyed by the input node names.
234 * @param outputs output node name from the TensorFlow model, if no outputs
235 * are specified, the default outputs of the model would be used. You can
236 * inspect intermediate nodes of the model by adding them to the outputs
237 * array.
238 *
239 * @returns A Promise of single tensor if provided with a single output or
240 * no outputs are provided and there is only one default output, otherwise
241 * return a tensor map.
242 *
243 * @doc {heading: 'Models', subheading: 'Classes'}
244 */
245 executeAsync(inputs: Tensor | Tensor[] | NamedTensorMap, outputs?: string | string[]): Promise<Tensor | Tensor[]>;
246 /**
247 * Get intermediate tensors for model debugging mode (flag
248 * KEEP_INTERMEDIATE_TENSORS is true).
249 *
250 * @doc {heading: 'Models', subheading: 'Classes'}
251 */
252 getIntermediateTensors(): NamedTensorsMap;
253 /**
254 * Dispose intermediate tensors for model debugging mode (flag
255 * KEEP_INTERMEDIATE_TENSORS is true).
256 *
257 * @doc {heading: 'Models', subheading: 'Classes'}
258 */
259 disposeIntermediateTensors(): void;
260 private convertTensorMapToTensorsMap;
261 /**
262 * Releases the memory used by the weight tensors and resourceManager.
263 *
264 * @doc {heading: 'Models', subheading: 'Classes'}
265 */
266 dispose(): void;
267}
268/**
269 * Load a graph model given a URL to the model definition.
270 *
271 * Example of loading MobileNetV2 from a URL and making a prediction with a
272 * zeros input:
273 *
274 * ```js
275 * const modelUrl =
276 * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
277 * const model = await tf.loadGraphModel(modelUrl);
278 * const zeros = tf.zeros([1, 224, 224, 3]);
279 * model.predict(zeros).print();
280 * ```
281 *
282 * Example of loading MobileNetV2 from a TF Hub URL and making a prediction
283 * with a zeros input:
284 *
285 * ```js
286 * const modelUrl =
287 * 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';
288 * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});
289 * const zeros = tf.zeros([1, 224, 224, 3]);
290 * model.predict(zeros).print();
291 * ```
292 * @param modelUrl The url or an `io.IOHandler` that loads the model.
293 * @param options Options for the HTTP request, which allows to send
294 * credentials
295 * and custom headers.
296 *
297 * @doc {heading: 'Models', subheading: 'Loading'}
298 */
299export declare function loadGraphModel(modelUrl: string | io.IOHandler, options?: io.LoadOptions, tfio?: typeof io): Promise<GraphModel>;
300/**
301 * Load a graph model given a synchronous IO handler with a 'load' method.
302 *
303 * @param modelSource The `io.IOHandlerSync` that loads the model, or the
304 * `io.ModelArtifacts` that encode the model, or a tuple of
305 * `[io.ModelJSON, ArrayBuffer]` of which the first element encodes the
306 * model and the second contains the weights.
307 *
308 * @doc {heading: 'Models', subheading: 'Loading'}
309 */
310export declare function loadGraphModelSync(modelSource: io.IOHandlerSync | io.ModelArtifacts | [io.ModelJSON, /* Weights */ ArrayBuffer]): GraphModel<io.IOHandlerSync>;
311export {};