• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// This schema defines how to configure TFLite for delegation. These
16// definitions can be used in multiple ways: as output of a compatibility list,
17// in benchmarking tools and to decouple delegate instantiation from code.
18//
19// The schema is work-in-progress, covering the most broadly used delegates and
20// options.
21
22syntax = "proto2";
23
24package tflite.proto;
25
26// ExecutionPreference is used to match accelerators against the preferences of
27// the current application or usecase. Some of the values here can appear both
28// in the compatibility list and as input, some only as input.
29//
30// These are separate from NNAPIExecutionPreference - the compatibility list
31// design doesn't assume a one-to-one mapping between which usecases
32// compatibility list entries have been developed for and what settings are used
33// for NNAPI.
34enum ExecutionPreference {
35  // Match any selected preference. Allowlist (semantically - value is same as
36  // on input).
37  ANY = 0;
38  // Match low latency preference. Both compatibility list and input.
39  LOW_LATENCY = 1;
40  // Math low power preference. Both compatibility list and input.
41  LOW_POWER = 2;
42  // Never accelerate. Can be used for input to compatibility list or for
43  // standalone Acceleration configuration.
44  FORCE_CPU = 3;
45}
46
47// TFLite accelerator to use.
48enum Delegate {
49  NONE = 0;
50
51  NNAPI = 1;
52  GPU = 2;
53  HEXAGON = 3;
54  XNNPACK = 4;
55  // The EdgeTpu in Pixel devices.
56  EDGETPU = 5;
57  // The Coral EdgeTpu Dev Board / USB accelerator.
58  EDGETPU_CORAL = 6;
59}
60
61enum NNAPIExecutionPreference {
62  // Undefined.
63  UNDEFINED = 0;
64  // Prefer executing in a way that minimizes battery drain.
65  NNAPI_LOW_POWER = 1;
66  // Prefer returning a single answer as fast as possible, even if this causes
67  // more power consumption.
68  NNAPI_FAST_SINGLE_ANSWER = 2;
69  // Prefer maximizing the throughput of successive frames, for example when
70  // processing successive frames coming from the camera.
71  NNAPI_SUSTAINED_SPEED = 3;
72}
73
74enum NNAPIExecutionPriority {
75  NNAPI_PRIORITY_UNDEFINED = 0;
76  NNAPI_PRIORITY_LOW = 1;
77  NNAPI_PRIORITY_MEDIUM = 2;
78  NNAPI_PRIORITY_HIGH = 3;
79}
80
81// One possible acceleration configuration.
82message ComputeSettings {
83  // Which preference to use this accelerator for.
84  optional ExecutionPreference preference = 1;
85  // How to configure TFLite
86  optional TFLiteSettings tflite_settings = 2;
87  // Identifiers to use for instrumentation and telemetry.
88  optional string model_namespace_for_statistics = 3;
89  optional string model_identifier_for_statistics = 4;
90}
91
92// NNAPI delegate settings.
93message NNAPISettings {
94  // Which instance (NNAPI accelerator) to use. One driver may provide several
95  // accelerators (though a driver may also hide several back-ends behind one
96  // name, at the choice of the driver vendor).
97  // Note that driver introspection is only available in Android Q and later.
98  optional string accelerator_name = 1;
99
100  // NNAPI model compilation caching settings to be passed to
101  // tflite::StatefulNnApiDelegate
102  optional string cache_directory = 2;
103  optional string model_token = 3;
104
105  // NNAPI execution preference to pass. See
106  // https://developer.android.com/ndk/reference/group/neural-networks.html
107  optional NNAPIExecutionPreference execution_preference = 4;
108
109  // Number of instances to cache for the same model (for input size
110  // changes). This is mandatory for getting reasonable performance in that
111  // case.
112  optional int32 no_of_nnapi_instances_to_cache = 5;
113
114  // Deprecated; use the fallback_settings in TFLiteSettings.
115  //
116  // Whether to automatically fall back to TFLite CPU path.
117  optional FallbackSettings fallback_settings = 6 [deprecated = true];
118
119  // Whether to allow use of NNAPI CPU (nnapi-reference accelerator) on Android
120  // 10+ when an accelerator name is not specified. The NNAPI CPU typically
121  // performs less well than the TfLite built-in kernels; but allowing allows a
122  // model to be partially accelerated which may be a win.
123  optional bool allow_nnapi_cpu_on_android_10_plus = 7;
124
125  optional NNAPIExecutionPriority execution_priority = 8;
126
127  // Whether to allow dynamic dimension sizes without re-compilation.
128  // A tensor of with dynamic dimension must have a valid dims_signature
129  // defined.
130  // Only supported in NNAPI 1.1 and newer versions.
131  // WARNING: Setting this flag to true may result in model being rejected by
132  // accelerator. This should only be enabled if the target device supports
133  // dynamic dimensions of the model.
134  // By default this is set to false.
135  optional bool allow_dynamic_dimensions = 9;
136
137  // Whether to allow the NNAPI accelerator to optionally use lower-precision
138  // float16 (16-bit floating point) arithmetic when doing calculations on
139  // float32 (32-bit floating point).
140  optional bool allow_fp16_precision_for_fp32 = 10;
141}
142
143// Which GPU backend to select. Default behaviour on Android is to try OpenCL
144// and if it's not available fall back to OpenGL.
145enum GPUBackend {
146  UNSET = 0;
147  OPENCL = 1;
148  OPENGL = 2;
149  // Not yet supported.
150  // VULKAN = 3;
151  // METAL = 4;
152}
153
154// GPU Delegate settings.
155//
156// See
157// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/delegates/gpu/delegate.h
158message GPUSettings {
159  optional bool is_precision_loss_allowed = 1;
160  optional bool enable_quantized_inference = 2 [default = true];
161  optional GPUBackend force_backend = 3;
162  // TODO(b/152019007): add remaining options.
163}
164
165// Hexagon Delegate settings.
166//
167// See
168// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/delegates/hexagon/hexagon_delegate.h
169message HexagonSettings {
170  optional int32 debug_level = 1;
171  optional int32 powersave_level = 2;
172  optional bool print_graph_profile = 3;
173  optional bool print_graph_debug = 4;
174}
175
176// XNNPack Delegate settings.
177//
178// See
179// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/delegates/xnnpack/xnnpack_delegate.h
180message XNNPackSettings {
181  optional int32 num_threads = 1;
182}
183
184// EdgeTPU device spec.
185//
186message EdgeTpuDeviceSpec {
187  // EdgeTPU platform types.
188  enum PlatformType {
189    MMIO = 0;
190    REFERENCE = 1;
191    SIMULATOR = 2;
192    REMOTE_SIMULATOR = 3;
193  }
194
195  // Execution platform for the EdgeTPU device.
196  optional PlatformType platform_type = 1;
197
198  // Number of chips to use for the EdgeTPU device.
199  optional int32 num_chips = 2;
200
201  // Paths to the EdgeTPU devices;
202  repeated string device_paths = 3;
203
204  // Chip family used by the EdgeTpu device.
205  optional int32 chip_family = 4;
206}
207
208// Generic definitions of EdgeTPU power states.
209enum EdgeTpuPowerState {
210  // Undefined power state.
211  UNDEFINED_POWERSTATE = 0;
212
213  // TPU core is off but control cluster is on.
214  TPU_CORE_OFF = 1;
215
216  // A non-active low-power state that has much smaller transition time to
217  // active compared to off.
218  READY = 2;
219
220  // Minimum power active state.
221  ACTIVE_MIN_POWER = 3;
222
223  // Very low performance, very low power.
224  ACTIVE_VERY_LOW_POWER = 4;
225
226  // Low performance, low power.
227  ACTIVE_LOW_POWER = 5;
228
229  // The normal performance and power. This setting usually provides the
230  // optimal perf/power trade-off for the average use-case.
231  ACTIVE = 6;
232
233  // Maximum performance level. Potentially higher power and thermal. This
234  // setting may not be allowed in production depending on the system.
235  OVER_DRIVE = 7;
236}
237
238message EdgeTpuInactivePowerConfig {
239  // Inactive power states between inferences.
240  optional EdgeTpuPowerState inactive_power_state = 1;
241
242  // Inactive timeout in microseconds between inferences.
243  optional int64 inactive_timeout_us = 2;
244}
245
246// EdgeTPU Delegate settings.
247//
248message EdgeTpuSettings {
249  // Target inference power state for running the model.
250  optional EdgeTpuPowerState inference_power_state = 1;
251
252  // Inactive power states between inferences.
253  repeated EdgeTpuInactivePowerConfig inactive_power_configs = 2;
254
255  // Priority for the inference request.
256  optional int32 inference_priority = 3 [default = -1];
257
258  // Device spec for creating the EdgeTpu device.
259  optional EdgeTpuDeviceSpec edgetpu_device_spec = 4;
260}
261
262// Coral Dev Board / USB accelerator delegate settings.
263//
264// See
265// https://github.com/google-coral/edgetpu/blob/master/libedgetpu/edgetpu_c.h
266message CoralSettings {
267  enum Performance {
268    UNDEFINED = 0;
269    MAXIMUM = 1;
270    HIGH = 2;
271    MEDIUM = 3;
272    LOW = 4;
273  }
274
275  // The Edge Tpu device to be used. See
276  // https://github.com/google-coral/libcoral/blob/982426546dfa10128376d0c24fd8a8b161daac97/coral/tflite_utils.h#L131-L137
277  optional string device = 1;
278  // The desired performance level. This setting adjusts the internal clock
279  // rate to achieve different performance / power balance. Higher performance
280  // values improve speed, but increase power usage.
281  optional Performance performance = 2 [default = MAXIMUM];
282  // If true, always perform device firmware update (DFU) after reset. DFU is
283  // usually only necessary after power cycle.
284  optional bool usb_always_dfu = 3;
285  // The maximum bulk in queue length. Larger queue length may improve USB
286  // performance on the direction from device to host. When not specified (or
287  // zero), `usb_max_bulk_in_queue_length` will default to 32 according to the
288  // current EdgeTpu Coral implementation.
289  optional int32 usb_max_bulk_in_queue_length = 4;
290}
291
292message CPUSettings {
293  optional int32 num_threads = 1;
294}
295
296// How to configure TFLite.
297message TFLiteSettings {
298  // Which delegate to use.
299  optional Delegate delegate = 1;
300
301  // How to configure the chosen delegate.
302  // (In principle we would like to use 'oneof', but flatc turns that into an
303  // nested anonymous table rather than a union. See
304  // https://github.com/google/flatbuffers/issues/4628).
305  optional NNAPISettings nnapi_settings = 2;
306  optional GPUSettings gpu_settings = 3;
307  optional HexagonSettings hexagon_settings = 4;
308  optional XNNPackSettings xnnpack_settings = 5;
309
310  // How to configure CPU execution.
311  optional CPUSettings cpu_settings = 6;
312
313  // Shared delegation settings.
314  optional int32 max_delegated_partitions = 7;
315
316  // For configuring the EdgeTpuDelegate.
317  optional EdgeTpuSettings edgetpu_settings = 8;
318
319  // For configuring the Coral EdgeTpu Delegate.
320  optional CoralSettings coral_settings = 10;
321
322  // Whether to automatically fall back to TFLite CPU path.
323  optional FallbackSettings fallback_settings = 9;
324}
325
326// Whether to automatically fallback to TFLite CPU path on delegation errors.
327//
328// Typically fallback is enabled in production use but disabled in tests and
329// benchmarks to ensure they test the intended path.
330message FallbackSettings {
331  // Whether to allow automatically falling back to TfLite CPU path on
332  // compilation failure. Default is not allowing automatic fallback.
333  //
334  // This is useful in naive production usecases where the caller would prefer
335  // for the model to run even if it's not accelerated. More advanced users will
336  // implement fallback themselves; e.g., by using a different model on CPU.
337  //
338  // Note that compilation errors may occur either at initial
339  // ModifyGraphWithDelegate() time, or when calling AllocateTensors() after
340  // resizing.
341  optional bool allow_automatic_fallback_on_compilation_error = 7;
342  // Whether to allow automatically falling back to TfLite CPU path on
343  // execution error. Default is not allowing automatic fallback.
344  //
345  // Experimental, use with care (only when you have complete control over the
346  // client code).
347  //
348  // The caveat above for compilation error holds.  Additionally, execution-time
349  // errors are harder to handle automatically as they require invalidating the
350  // TfLite interpreter which most client code has not been designed to deal
351  // with.
352  optional bool allow_automatic_fallback_on_execution_error = 8;
353}
354
355// On-device mini-benchmark result storage. The following definitions are used
356// to keep an append-only log of benchmark results on-device. (Hence there is
357// single top-level event that is used for all data).
358//
359// These definitions don't need a proto-to-flatbuffer conversion, since they are
360// not used for specifying configuration in the Tasks library.
361
362// Which stage of benchmarking the event is for.
363// There might be multiple events with the same type, if a benchmark is run
364// multiple times.
365enum BenchmarkEventType {
366  UNDEFINED_BENCHMARK_EVENT_TYPE = 0;
367  // Benchmark start. A start without an end can be interpreted as a test that
368  // has crashed or hung.
369  START = 1;
370  // Benchmarking completion. A model was successfully loaded, acceleration
371  // configured and inference run without errors. There may still be an issue
372  // with correctness of results, or with performance.
373  END = 2;
374  // Benchmark was not completed due to an error. The error may be a handled
375  // error (e.g., failure in a delegate), or a crash.
376  ERROR = 3;
377  // Benchmark data has been sent for logging.
378  LOGGED = 4;
379}
380
381// A correctness metric from a benchmark, for example KL-divergence between
382// known-good CPU output and on-device output. These are primarily used for
383// telemetry and monitored server-side.
384message BenchmarkMetric {
385  optional string name = 1;
386  repeated float values = 2 [packed = true];
387}
388
389// Outcome of a successfully complete benchmark run. This information is
390// intended to both be used on-device to select best compute configuration as
391// well as sent to server for monitoring.
392//
393// Used with event type END.
394message BenchmarkResult {
395  // Time to load model and apply acceleration. Initialization may get run
396  // multiple times to get information on variance.
397  repeated int64 initialization_time_us = 1 [packed = true];
398  // Time to run inference (call Invoke()). Inference may get run multiple times
399  // to get information on variance.
400  repeated int64 inference_time_us = 2 [packed = true];
401  // Maximum memory used. Measures size of application heap (does not
402  // necessarily take into account driver-side allocation.
403  optional int32 max_memory_kb = 3;
404  // Whether the inference produced correct results (validation graph output
405  // 'ok' for all test inputs). Used on-device to disallow configurations that
406  // produce incorrect results (e.g., due to OpenCL driver bugs).
407  optional bool ok = 4;
408  // Metrics that were used to determine the 'ok' status.
409  repeated BenchmarkMetric metrics = 5;
410}
411
412// A handled error.
413message ErrorCode {
414  // Which delegate the error comes from (or NONE, if it comes from the tflite
415  // framework).
416  optional Delegate source = 1;
417  // What the tflite level error is.
418  optional int32 tflite_error = 2;
419  // What the underlying error is (e.g., NNAPI or OpenGL error).
420  optional int64 underlying_api_error = 3;
421}
422
423// When during benchmark execution an error occurred.
424enum BenchmarkStage {
425  UNKNOWN = 0;
426  // During model loading or delegation.
427  INITIALIZATION = 1;
428  // During inference.
429  INFERENCE = 2;
430}
431
432// An error that occurred during benchmarking.
433//
434// Used with event type ERROR.
435message BenchmarkError {
436  // How far benchmarking got.
437  optional BenchmarkStage stage = 1;
438  // Process exit code.
439  optional int32 exit_code = 2;
440  // Signal the process received.
441  optional int32 signal = 3;
442  // Handled error.
443  repeated ErrorCode error_code = 4;
444}
445
446// Top-level benchmarking event stored on-device. All events for a model are
447// parsed to detect the status.
448message BenchmarkEvent {
449  // Which settings were used for benchmarking.
450  optional TFLiteSettings tflite_settings = 1;
451  // Type of the event.
452  optional BenchmarkEventType event_type = 2;
453  // Result of benchmark, used when type is END.
454  optional BenchmarkResult result = 3;
455  // Error during benchmark, used when type is ERROR.
456  optional BenchmarkError error = 4;
457}
458