TensorFlow Lite hỗ trợ nhiều tăng tốc phần cứng. Tài liệu này mô tả cách sử dụng phụ trợ GPU bằng API ủy quyền TensorFlow Lite trên Android và iOS.
GPU được thiết kế để có thông lượng cao cho khối lượng công việc có thể song song hóa khối lượng lớn. Do đó, chúng rất phù hợp với mạng nơ-ron sâu, bao gồm một số lượng lớn các toán tử, mỗi toán tử làm việc trên một số tensor đầu vào có thể dễ dàng chia thành các khối lượng công việc nhỏ hơn và thực hiện song song, thường dẫn đến độ trễ thấp hơn. Trong trường hợp tốt nhất, suy luận trên GPU hiện có thể chạy đủ nhanh cho các ứng dụng thời gian thực không khả dụng trước đây.
Không giống như CPU, GPU tính toán với số dấu phẩy động 16 bit hoặc 32 bit và không yêu cầu lượng tử hóa để có hiệu suất tối ưu. Người đại diện chấp nhận các mô hình lượng tử hóa 8-bit, nhưng phép tính sẽ được thực hiện dưới dạng số dấu phẩy động. Tham khảo các tài liệu tiên tiến để biết chi tiết.
Một lợi ích khác với suy luận của GPU là hiệu quả sử dụng năng lượng của nó. GPU thực hiện các tính toán một cách rất hiệu quả và được tối ưu hóa, do đó chúng tiêu thụ ít năng lượng hơn và tạo ra ít nhiệt hơn so với khi chạy cùng một tác vụ trên CPU.
Hướng dẫn ứng dụng demo
Cách dễ nhất để dùng thử GPU ủy quyền là làm theo các hướng dẫn bên dưới, hướng dẫn này qua việc xây dựng các ứng dụng demo phân loại của chúng tôi với sự hỗ trợ của GPU. Mã GPU hiện chỉ là mã nhị phân; nó sẽ sớm có nguồn mở. Sau khi bạn hiểu cách làm cho các bản trình diễn của chúng tôi hoạt động, bạn có thể thử điều này trên các mô hình tùy chỉnh của riêng bạn.
Android (với Android Studio)
Đối với một bước-by-bước hướng dẫn, xem GPU Đại biểu dành cho Android video.
Bước 1. Sao chép mã nguồn TensorFlow và mở nó trong Android Studio
git clone https://github.com/tensorflow/tensorflow
Bước 2. Chỉnh sửa app/build.gradle
sử dụng GPU AAR đêm
Thêm tensorflow-lite-gpu
gói cùng với hiện tensorflow-lite
gói trong hiện tại dependencies
khối.
dependencies {
...
implementation 'org.tensorflow:tensorflow-lite:2.3.0'
implementation 'org.tensorflow:tensorflow-lite-gpu:2.3.0'
}
Bước 3. Xây dựng và chạy
Chạy → Chạy 'ứng dụng'. Khi chạy ứng dụng, bạn sẽ thấy một nút để bật GPU. Thay đổi từ lượng tử hóa thành mô hình float và sau đó nhấp vào GPU để chạy trên GPU.
iOS (với XCode)
Đối với một bước-by-bước hướng dẫn, xem GPU Đại biểu dành cho iOS video.
Bước 1. Lấy mã nguồn demo và đảm bảo rằng nó đã biên dịch.
Làm theo iOS Ứng dụng trình diễn của chúng tôi hướng dẫn . Điều này sẽ đưa bạn đến điểm mà bản demo camera iOS chưa sửa đổi đang hoạt động trên điện thoại của bạn.
Bước 2. Sửa đổi Podfile để sử dụng TensorFlow Lite GPU CocoaPod
Từ bản phát hành 2.3.0, theo mặc định, đại biểu GPU bị loại trừ khỏi nhóm để giảm kích thước nhị phân. Bạn có thể bao gồm chúng bằng cách chỉ định subspec. Đối với TensorFlowLiteSwift
pod:
pod 'TensorFlowLiteSwift/Metal', '~> 0.0.1-nightly',
HOẶC
pod 'TensorFlowLiteSwift', '~> 0.0.1-nightly', :subspecs => ['Metal']
Bạn có thể làm tương tự cho TensorFlowLiteObjC
hoặc TensorFlowLitC
nếu bạn muốn sử dụng Objective-C (từ 2.4.0 phát hành) hoặc C API.
Trước khi phát hành 2.3.0
Cho đến khi TensorFlow Lite 2.0.0
Chúng tôi đã xây dựng CocoaPod nhị phân bao gồm đại biểu GPU. Để chuyển dự án sang sử dụng nó, hãy sửa đổi tệp `tensorflow / tensorflow / lite /amples / ios / camera / Podfile` để sử dụng nhóm` TensorFlowLiteGpuExperimental` thay vì `TensorFlowLite`.
target 'YourProjectName'
# pod 'TensorFlowLite', '1.12.0'
pod 'TensorFlowLiteGpuExperimental'
Cho đến khi TensorFlow Lite 2.2.0
Từ TensorFlow Lite 2.1.0 đến 2.2.0, đại biểu GPU được bao gồm trong nhóm `TensorFlowLiteC`. Bạn có thể chọn giữa `TensorFlowLiteC` và` TensorFlowLiteSwift` tùy thuộc vào ngôn ngữ.
Bước 3. Bật ủy quyền GPU
Để kích hoạt mã mà sẽ sử dụng các đại biểu GPU, bạn sẽ cần phải thay đổi TFLITE_USE_GPU_DELEGATE
0-1 trong CameraExampleViewController.h
.
#define TFLITE_USE_GPU_DELEGATE 1
Bước 4. Xây dựng và chạy ứng dụng demo
Sau khi làm theo bước trước, bạn sẽ có thể chạy ứng dụng.
Bước 5. Chế độ phát hành
Trong khi ở Bước 4, bạn đã chạy ở chế độ gỡ lỗi, để có hiệu suất tốt hơn, bạn nên chuyển sang bản phát hành có cài đặt Metal tối ưu thích hợp. Đặc biệt, Để chỉnh sửa các thiết lập này đi đến Product > Scheme > Edit Scheme...
. Chọn Run
. Trên Info
tab, thay đổi Build Configuration
, từ Debug
để Release
, bỏ chọn Debug executable
.
Sau đó nhấp vào Options
tab và thay đổi GPU Frame Capture
để Disabled
và Metal API Validation
để Disabled
.
Cuối cùng, hãy đảm bảo chọn các bản dựng chỉ Phát hành trên kiến trúc 64-bit. Dưới Project navigator -> tflite_camera_example -> PROJECT -> tflite_camera_example -> Build Settings
thiết Build Active Architecture Only > Release
thành Yes.
Đang thử ủy quyền GPU trên mô hình của riêng bạn
Android
Có hai cách để gọi tăng tốc mô hình tùy thuộc vào nếu bạn đang sử dụng Android Studio ML mẫu Ràng buộc hoặc TensorFlow Lite Interpreter.
Trình thông dịch TensorFlow Lite
Hãy xem bản trình diễn để biết cách thêm đại biểu. Trong ứng dụng của bạn, thêm AAR như trên, nhập khẩu org.tensorflow.lite.gpu.GpuDelegate
mô-đun, và sử dụng addDelegate
chức năng để đăng ký đại biểu GPU để người phiên dịch:
Kotlin
import org.tensorflow.lite.Interpreter import org.tensorflow.lite.gpu.CompatibilityList import org.tensorflow.lite.gpu.GpuDelegate val compatList = CompatibilityList() val options = Interpreter.Options().apply{ if(compatList.isDelegateSupportedOnThisDevice){ // if the device has a supported GPU, add the GPU delegate val delegateOptions = compatList.bestOptionsForThisDevice this.addDelegate(GpuDelegate(delegateOptions)) } else { // if the GPU is not supported, run on 4 threads this.setNumThreads(4) } } val interpreter = Interpreter(model, options) // Run inference writeToInput(input) interpreter.run(input, output) readFromOutput(output)
Java
import org.tensorflow.lite.Interpreter; import org.tensorflow.lite.gpu.CompatibilityList; import org.tensorflow.lite.gpu.GpuDelegate; // Initialize interpreter with GPU delegate Interpreter.Options options = new Interpreter.Options(); CompatibilityList compatList = CompatibilityList(); if(compatList.isDelegateSupportedOnThisDevice()){ // if the device has a supported GPU, add the GPU delegate GpuDelegate.Options delegateOptions = compatList.getBestOptionsForThisDevice(); GpuDelegate gpuDelegate = new GpuDelegate(delegateOptions); options.addDelegate(gpuDelegate); } else { // if the GPU is not supported, run on 4 threads options.setNumThreads(4); } Interpreter interpreter = new Interpreter(model, options); // Run inference writeToInput(input); interpreter.run(input, output); readFromOutput(output);
iOS
Nhanh
import TensorFlowLite // Load model ... // Initialize TensorFlow Lite interpreter with the GPU delegate. let delegate = MetalDelegate() if let interpreter = try Interpreter(modelPath: modelPath, delegates: [delegate]) { // Run inference ... }
Objective-C
// Import module when using CocoaPods with module support @import TFLTensorFlowLite; // Or import following headers manually #import "tensorflow/lite/objc/apis/TFLMetalDelegate.h" #import "tensorflow/lite/objc/apis/TFLTensorFlowLite.h" // Initialize GPU delegate TFLMetalDelegate* metalDelegate = [[TFLMetalDelegate alloc] init]; // Initialize interpreter with model path and GPU delegate TFLInterpreterOptions* options = [[TFLInterpreterOptions alloc] init]; NSError* error = nil; TFLInterpreter* interpreter = [[TFLInterpreter alloc] initWithModelPath:modelPath options:options delegates:@[ metalDelegate ] error:&error]; if (error != nil) { /* Error handling... */ } if (![interpreter allocateTensorsWithError:&error]) { /* Error handling... */ } if (error != nil) { /* Error handling... */ } // Run inference ... ```
C (Cho đến 2.3.0)
#include "tensorflow/lite/c/c_api.h" #include "tensorflow/lite/delegates/gpu/metal_delegate.h" // Initialize model TfLiteModel* model = TfLiteModelCreateFromFile(model_path); // Initialize interpreter with GPU delegate TfLiteInterpreterOptions* options = TfLiteInterpreterOptionsCreate(); TfLiteDelegate* delegate = TFLGPUDelegateCreate(nil); // default config TfLiteInterpreterOptionsAddDelegate(options, metal_delegate); TfLiteInterpreter* interpreter = TfLiteInterpreterCreate(model, options); TfLiteInterpreterOptionsDelete(options); TfLiteInterpreterAllocateTensors(interpreter); NSMutableData *input_data = [NSMutableData dataWithLength:input_size * sizeof(float)]; NSMutableData *output_data = [NSMutableData dataWithLength:output_size * sizeof(float)]; TfLiteTensor* input = TfLiteInterpreterGetInputTensor(interpreter, 0); const TfLiteTensor* output = TfLiteInterpreterGetOutputTensor(interpreter, 0); // Run inference TfLiteTensorCopyFromBuffer(input, inputData.bytes, inputData.length); TfLiteInterpreterInvoke(interpreter); TfLiteTensorCopyToBuffer(output, outputData.mutableBytes, outputData.length); // Clean up TfLiteInterpreterDelete(interpreter); TFLGpuDelegateDelete(metal_delegate); TfLiteModelDelete(model);
## Supported Models and Ops
With the release of the GPU delegate, we included a handful of models that can
be run on the backend:
* [MobileNet v1 (224x224) image classification](https://ai.googleblog.com/2017/06/mobilenets-open-source-models-for.html) [[download]](https://storage.googleapis.com/download.tensorflow.org/models/tflite/gpu/mobilenet_v1_1.0_224.tflite)
<br /><i>(image classification model designed for mobile and embedded based vision applications)</i>
* [DeepLab segmentation (257x257)](https://ai.googleblog.com/2018/03/semantic-image-segmentation-with.html) [[download]](https://storage.googleapis.com/download.tensorflow.org/models/tflite/gpu/deeplabv3_257_mv_gpu.tflite)
<br /><i>(image segmentation model that assigns semantic labels (e.g., dog, cat, car) to every pixel in the input image)</i>
* [MobileNet SSD object detection](https://ai.googleblog.com/2018/07/accelerated-training-and-inference-with.html) [[download]](https://storage.googleapis.com/download.tensorflow.org/models/tflite/gpu/mobile_ssd_v2_float_coco.tflite)
<br /><i>(image classification model that detects multiple objects with bounding boxes)</i>
* [PoseNet for pose estimation](https://github.com/tensorflow/tfjs-models/tree/master/posenet) [[download]](https://storage.googleapis.com/download.tensorflow.org/models/tflite/gpu/multi_person_mobilenet_v1_075_float.tflite)
<br /><i>(vision model that estimates the poses of a person(s) in image or video)</i>
To see a full list of supported ops, please see the
[advanced documentation](gpu_advanced).
## Non-supported models and ops
If some of the ops are not supported by the GPU delegate, the framework will
only run a part of the graph on the GPU and the remaining part on the CPU. Due
to the high cost of CPU/GPU synchronization, a split execution mode like this
will often result in slower performance than when the whole network is run on
the CPU alone. In this case, the user will get a warning like:
```none
WARNING: op code #42 cannot be handled by this delegate.
```
Chúng tôi đã không cung cấp lệnh gọi lại cho lỗi này, vì đây không phải là lỗi thời gian chạy thực sự mà là lỗi mà nhà phát triển có thể quan sát được khi cố gắng đưa mạng chạy trên ủy quyền.
Mẹo để tối ưu hóa
Tối ưu hóa cho thiết bị di động
Một số hoạt động nhỏ trên CPU có thể có chi phí cao cho GPU trên thiết bị di động. Hoạt động Reshape đặc biệt đắt tiền để chạy, trong đó có BATCH_TO_SPACE
, SPACE_TO_BATCH
, SPACE_TO_DEPTH
, và vân vân. Bạn nên kiểm tra chặt chẽ việc sử dụng các hoạt động định hình lại và xem xét điều đó có thể chỉ được áp dụng để khám phá dữ liệu hoặc cho các lần lặp lại đầu tiên của mô hình của bạn. Loại bỏ chúng có thể cải thiện đáng kể hiệu suất.
Trên GPU, dữ liệu tensor được chia thành 4 kênh. Do đó, một tính toán trên một tensor hình dạng [B,H,W,5]
sẽ biểu diễn về giống nhau trên một tensor hình dạng [B,H,W,8]
nhưng tồi tệ hơn đáng kể [B,H,W,4]
. Theo nghĩa đó, nếu phần cứng máy ảnh hỗ trợ khung hình ảnh trong RGBA, việc cấp đầu vào 4 kênh đó nhanh hơn đáng kể vì có thể tránh được bản sao bộ nhớ (từ RGB 3 kênh sang RGBX 4 kênh).
Để có hiệu suất tốt nhất, bạn nên xem xét đào tạo lại bộ phân loại với kiến trúc mạng được tối ưu hóa cho thiết bị di động. Tối ưu hóa cho hội nghị trên thiết bị có thể giảm đáng kể độ trễ và tiêu thụ điện năng bằng cách tận dụng các tính năng phần cứng di động.
Giảm thời gian khởi tạo với tuần tự hóa
Tính năng ủy quyền GPU cho phép bạn tải từ mã nhân được biên dịch trước và dữ liệu mô hình được tuần tự hóa và lưu trên đĩa từ các lần chạy trước. Cách tiếp cận này tránh biên dịch lại và giảm thời gian khởi động lên đến 90%. Để được hướng dẫn về cách áp dụng tuần tự để dự án của bạn, xem GPU Đại biểu serialization .