1 /* Copyright 2017 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 #include "tensorflow/lite/kernels/gemm_support.h" 16 17 #include <memory> 18 19 #include "tensorflow/lite/kernels/op_macros.h" 20 21 namespace tflite { 22 namespace gemm_support { 23 namespace { 24 25 struct RefCountedGemmContext : public TfLiteExternalContext { 26 std::unique_ptr<gemmlowp::GemmContext> gemm_context; 27 int num_references = 0; 28 }; 29 GetGemmLowpContext(TfLiteContext * context)30RefCountedGemmContext* GetGemmLowpContext(TfLiteContext* context) { 31 return reinterpret_cast<RefCountedGemmContext*>( 32 context->GetExternalContext(context, kTfLiteGemmLowpContext)); 33 } 34 Refresh(TfLiteContext * context)35TfLiteStatus Refresh(TfLiteContext* context) { 36 auto* ptr = GetGemmLowpContext(context); 37 if (ptr != nullptr) { 38 ptr->gemm_context->set_max_num_threads(context->recommended_num_threads); 39 } 40 return kTfLiteOk; 41 } 42 43 } // namespace 44 IncrementUsageCounter(TfLiteContext * context)45void IncrementUsageCounter(TfLiteContext* context) { 46 auto* ptr = GetGemmLowpContext(context); 47 if (ptr == nullptr) { 48 ptr = new RefCountedGemmContext; 49 ptr->type = kTfLiteGemmLowpContext; 50 ptr->Refresh = Refresh; 51 ptr->gemm_context.reset(new gemmlowp::GemmContext()); 52 if (context->recommended_num_threads != -1) { 53 ptr->gemm_context->set_max_num_threads(context->recommended_num_threads); 54 } 55 ptr->num_references = 0; 56 context->SetExternalContext(context, kTfLiteGemmLowpContext, ptr); 57 } 58 ptr->num_references++; 59 } 60 DecrementUsageCounter(TfLiteContext * context)61void DecrementUsageCounter(TfLiteContext* context) { 62 auto* ptr = GetGemmLowpContext(context); 63 if (ptr == nullptr) { 64 TF_LITE_FATAL( 65 "Call to DecrementUsageCounter() not preceded by " 66 "IncrementUsageCounter()"); 67 } 68 if (--ptr->num_references == 0) { 69 delete ptr; 70 context->SetExternalContext(context, kTfLiteGemmLowpContext, nullptr); 71 } 72 } 73 GetFromContext(TfLiteContext * context)74gemmlowp::GemmContext* GetFromContext(TfLiteContext* context) { 75 auto* ptr = GetGemmLowpContext(context); 76 if (ptr == nullptr) { 77 TF_LITE_FATAL( 78 "Call to GetFromContext() not preceded by IncrementUsageCounter()"); 79 } 80 return ptr->gemm_context.get(); 81 } 82 83 } // namespace gemm_support 84 } // namespace tflite 85