• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2021 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 
16 #ifndef TENSORFLOW_LITE_DELEGATES_FLEX_TRAINING_TRAINING_DELEGATE_H_
17 #define TENSORFLOW_LITE_DELEGATES_FLEX_TRAINING_TRAINING_DELEGATE_H_
18 
19 #include "tensorflow/core/framework/cancellation.h"
20 #include "tensorflow/lite/delegates/flex/delegate.h"
21 
22 namespace tflite {
23 namespace flex {
24 
25 namespace testing {
26 class TrainingDelegateTest;
27 }  // namespace testing
28 
29 // This is an experimental interface that is subject to change.
30 // Delegate that extends the functionality of FlexDelegate and supports
31 // cancellation.
32 //
33 // The interpreter must be constructed after and destructed
34 // before this delegate.
35 //
36 // Usage:
37 //   auto delegate = absl::make_unique<TrainingFlexDelegate>();
38 //   InterpreterBuilder builder;
39 //   builder.AddDelegate(delegate->GetTfLiteDelegate());
40 //   ... build interpreter ...
41 //
42 //   interpreter_->SetCancellationFunction(
43 //     delegate.get(),
44 //     TrainingFlexDelegate::ShouldCancel);
45 //
46 //   ... run inference ...
47 //
48 //   delegate->Cancel();
49 //
50 //   ... destroy interpreter ...
51 //   ... destroy delegate ...
52 class TrainingFlexDelegate {
53  public:
54   friend class testing::TrainingDelegateTest;
55 
56   TrainingFlexDelegate();
57 
58   // This method is thread safe. It does two things:
59   //   1. Calls the CancellationManager of the TF eager runtime to support
60   //      intra-op cancellation in TF.
61   //   2. Uses the CancellationManager to signal TFLite interpreter for inter-op
62   //      cancellation.
63   // Training is non-recoverable after calling this API.
64   void Cancel();
65 
GetTfLiteDelegate()66   TfLiteDelegate* GetTfLiteDelegate() const { return delegate_.get(); }
67 
68   // The param `data` must be a pointer to a TrainingFlexDelegate instance.
69   static bool ShouldCancel(void* data);
70 
71  private:
72   TfLiteDelegateUniquePtr delegate_;
73   std::unique_ptr<tensorflow::CancellationManager> cancellation_manager_;
74 };
75 
76 }  // namespace flex
77 }  // namespace tflite
78 
79 #endif  // TENSORFLOW_LITE_DELEGATES_FLEX_TRAINING_TRAINING_DELEGATE_H_
80