UNPKG

11.7 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";
22declare type Url = string | io.IOHandler | io.IOHandlerSync;
23declare type 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 resourceManager;
43 private signature;
44 private structuredOutputKeys;
45 private readonly io;
46 readonly modelVersion: string;
47 readonly inputNodes: string[];
48 readonly outputNodes: string[];
49 readonly inputs: TensorInfo[];
50 readonly outputs: TensorInfo[];
51 readonly weights: NamedTensorsMap;
52 readonly metadata: {};
53 readonly modelSignature: {};
54 readonly modelStructuredOutputKeys: {};
55 /**
56 * @param modelUrl url for the model, or an `io.IOHandler`.
57 * @param weightManifestUrl url for the weight file generated by
58 * scripts/convert.py script.
59 * @param requestOption options for Request, which allows to send credentials
60 * and custom headers.
61 * @param onProgress Optional, progress callback function, fired periodically
62 * before the load is completed.
63 */
64 constructor(modelUrl: ModelURL, loadOptions?: io.LoadOptions, tfio?: typeof io);
65 private findIOHandler;
66 /**
67 * Loads the model and weight files, construct the in memory weight map and
68 * compile the inference graph.
69 */
70 load(): UrlIOHandler<ModelURL> extends io.IOHandlerSync ? boolean : Promise<boolean>;
71 /**
72 * Synchronously construct the in memory weight map and
73 * compile the inference graph. Also initialize hashtable if any.
74 *
75 * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
76 */
77 loadSync(artifacts: io.ModelArtifacts): boolean;
78 /**
79 * Save the configuration and/or weights of the GraphModel.
80 *
81 * An `IOHandler` is an object that has a `save` method of the proper
82 * signature defined. The `save` method manages the storing or
83 * transmission of serialized data ("artifacts") that represent the
84 * model's topology and weights onto or via a specific medium, such as
85 * file downloads, local storage, IndexedDB in the web browser and HTTP
86 * requests to a server. TensorFlow.js provides `IOHandler`
87 * implementations for a number of frequently used saving mediums, such as
88 * `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`
89 * for more details.
90 *
91 * This method also allows you to refer to certain types of `IOHandler`s
92 * as URL-like string shortcuts, such as 'localstorage://' and
93 * 'indexeddb://'.
94 *
95 * Example 1: Save `model`'s topology and weights to browser [local
96 * storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);
97 * then load it back.
98 *
99 * ```js
100 * const modelUrl =
101 * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
102 * const model = await tf.loadGraphModel(modelUrl);
103 * const zeros = tf.zeros([1, 224, 224, 3]);
104 * model.predict(zeros).print();
105 *
106 * const saveResults = await model.save('localstorage://my-model-1');
107 *
108 * const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');
109 * console.log('Prediction from loaded model:');
110 * model.predict(zeros).print();
111 * ```
112 *
113 * @param handlerOrURL An instance of `IOHandler` or a URL-like,
114 * scheme-based string shortcut for `IOHandler`.
115 * @param config Options for saving the model.
116 * @returns A `Promise` of `SaveResult`, which summarizes the result of
117 * the saving, such as byte sizes of the saved artifacts for the model's
118 * topology and weight values.
119 *
120 * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}
121 */
122 save(handlerOrURL: io.IOHandler | string, config?: io.SaveConfig): Promise<io.SaveResult>;
123 /**
124 * Execute the inference for the input tensors.
125 *
126 * @param input The input tensors, when there is single input for the model,
127 * inputs param should be a `tf.Tensor`. For models with mutliple inputs,
128 * inputs params should be in either `tf.Tensor`[] if the input order is
129 * fixed, or otherwise NamedTensorMap format.
130 *
131 * For model with multiple inputs, we recommend you use NamedTensorMap as the
132 * input type, if you use `tf.Tensor`[], the order of the array needs to
133 * follow the
134 * order of inputNodes array. @see {@link GraphModel.inputNodes}
135 *
136 * You can also feed any intermediate nodes using the NamedTensorMap as the
137 * input type. For example, given the graph
138 * InputNode => Intermediate => OutputNode,
139 * you can execute the subgraph Intermediate => OutputNode by calling
140 * model.execute('IntermediateNode' : tf.tensor(...));
141 *
142 * This is useful for models that uses tf.dynamic_rnn, where the intermediate
143 * state needs to be fed manually.
144 *
145 * For batch inference execution, the tensors for each input need to be
146 * concatenated together. For example with mobilenet, the required input shape
147 * is [1, 244, 244, 3], which represents the [batch, height, width, channel].
148 * If we are provide a batched data of 100 images, the input tensor should be
149 * in the shape of [100, 244, 244, 3].
150 *
151 * @param config Prediction configuration for specifying the batch size.
152 * Currently the batch size option is ignored for graph model.
153 *
154 * @returns Inference result tensors. If the model is converted and it
155 * originally had structured_outputs in tensorflow, then a NamedTensorMap
156 * will be returned matching the structured_outputs. If no structured_outputs
157 * are present, the output will be single `tf.Tensor` if the model has single
158 * output node, otherwise Tensor[].
159 *
160 * @doc {heading: 'Models', subheading: 'Classes'}
161 */
162 predict(inputs: Tensor | Tensor[] | NamedTensorMap, config?: ModelPredictConfig): Tensor | Tensor[] | NamedTensorMap;
163 private normalizeInputs;
164 private normalizeOutputs;
165 /**
166 * Executes inference for the model for given input tensors.
167 * @param inputs tensor, tensor array or tensor map of the inputs for the
168 * model, keyed by the input node names.
169 * @param outputs output node name from the Tensorflow model, if no
170 * outputs are specified, the default outputs of the model would be used.
171 * You can inspect intermediate nodes of the model by adding them to the
172 * outputs array.
173 *
174 * @returns A single tensor if provided with a single output or no outputs
175 * are provided and there is only one default output, otherwise return a
176 * tensor array. The order of the tensor array is the same as the outputs
177 * if provided, otherwise the order of outputNodes attribute of the model.
178 *
179 * @doc {heading: 'Models', subheading: 'Classes'}
180 */
181 execute(inputs: Tensor | Tensor[] | NamedTensorMap, outputs?: string | string[]): Tensor | Tensor[];
182 /**
183 * Executes inference for the model for given input tensors in async
184 * fashion, use this method when your model contains control flow ops.
185 * @param inputs tensor, tensor array or tensor map of the inputs for the
186 * model, keyed by the input node names.
187 * @param outputs output node name from the Tensorflow model, if no outputs
188 * are specified, the default outputs of the model would be used. You can
189 * inspect intermediate nodes of the model by adding them to the outputs
190 * array.
191 *
192 * @returns A Promise of single tensor if provided with a single output or
193 * no outputs are provided and there is only one default output, otherwise
194 * return a tensor map.
195 *
196 * @doc {heading: 'Models', subheading: 'Classes'}
197 */
198 executeAsync(inputs: Tensor | Tensor[] | NamedTensorMap, outputs?: string | string[]): Promise<Tensor | Tensor[]>;
199 /**
200 * Get intermediate tensors for model debugging mode (flag
201 * KEEP_INTERMEDIATE_TENSORS is true).
202 *
203 * @doc {heading: 'Models', subheading: 'Classes'}
204 */
205 getIntermediateTensors(): NamedTensorsMap;
206 /**
207 * Dispose intermediate tensors for model debugging mode (flag
208 * KEEP_INTERMEDIATE_TENSORS is true).
209 *
210 * @doc {heading: 'Models', subheading: 'Classes'}
211 */
212 disposeIntermediateTensors(): void;
213 private convertTensorMapToTensorsMap;
214 /**
215 * Releases the memory used by the weight tensors and resourceManager.
216 *
217 * @doc {heading: 'Models', subheading: 'Classes'}
218 */
219 dispose(): void;
220}
221/**
222 * Load a graph model given a URL to the model definition.
223 *
224 * Example of loading MobileNetV2 from a URL and making a prediction with a
225 * zeros input:
226 *
227 * ```js
228 * const modelUrl =
229 * 'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';
230 * const model = await tf.loadGraphModel(modelUrl);
231 * const zeros = tf.zeros([1, 224, 224, 3]);
232 * model.predict(zeros).print();
233 * ```
234 *
235 * Example of loading MobileNetV2 from a TF Hub URL and making a prediction
236 * with a zeros input:
237 *
238 * ```js
239 * const modelUrl =
240 * 'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';
241 * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});
242 * const zeros = tf.zeros([1, 224, 224, 3]);
243 * model.predict(zeros).print();
244 * ```
245 * @param modelUrl The url or an `io.IOHandler` that loads the model.
246 * @param options Options for the HTTP request, which allows to send
247 * credentials
248 * and custom headers.
249 *
250 * @doc {heading: 'Models', subheading: 'Loading'}
251 */
252export declare function loadGraphModel(modelUrl: string | io.IOHandler, options?: io.LoadOptions, tfio?: typeof io): Promise<GraphModel>;
253/**
254 * Load a graph model given a synchronous IO handler with a 'load' method.
255 *
256 * @param modelSource The `io.IOHandlerSync` that loads the model.
257 *
258 * @doc {heading: 'Models', subheading: 'Loading'}
259 */
260export declare function loadGraphModelSync(modelSource: io.IOHandlerSync): GraphModel<io.IOHandlerSync>;
261export {};