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 16 #include "tensorflow/lite/delegates/interpreter_utils.h" 17 18 namespace tflite { 19 namespace delegates { InvokeWithCPUFallback(Interpreter * interpreter)20TfLiteStatus InterpreterUtils::InvokeWithCPUFallback(Interpreter* interpreter) { 21 TfLiteStatus status = interpreter->Invoke(); 22 if (status == kTfLiteOk || interpreter->IsCancelled() || 23 !interpreter->HasDelegates()) { 24 return status; 25 } 26 // Retry without delegation. 27 // TODO(b/138706191): retry only if error is due to delegation. 28 TF_LITE_REPORT_ERROR( 29 interpreter->error_reporter(), 30 "Invoke() failed in the presence of delegation. Retrying without."); 31 32 // Copy input data to a buffer. 33 // Input data is safe since Subgraph::PrepareOpsAndTensors() passes 34 // preserve_inputs=true to ArenaPlanner. 35 std::vector<char> buf; 36 size_t input_size = 0; 37 38 for (auto i : interpreter->inputs()) { 39 TF_LITE_ENSURE_STATUS(interpreter->EnsureTensorDataIsReadable(i)); 40 TfLiteTensor* t = interpreter->tensor(i); 41 input_size += t->bytes; 42 } 43 buf.reserve(input_size); 44 for (auto i : interpreter->inputs()) { 45 TfLiteTensor* t = interpreter->tensor(i); 46 buf.insert(buf.end(), t->data.raw, t->data.raw + t->bytes); 47 } 48 49 TF_LITE_ENSURE_STATUS(interpreter->RemoveAllDelegates()); 50 51 // Copy inputs from buffer. 52 auto bufp = buf.begin(); 53 for (auto i : interpreter->inputs()) { 54 TfLiteTensor* t = interpreter->tensor(i); 55 std::copy(bufp, bufp + t->bytes, t->data.raw); 56 bufp += t->bytes; 57 } 58 59 // Invoke again. 60 TF_LITE_ENSURE_STATUS(interpreter->Invoke()); 61 return kTfLiteDelegateError; 62 } 63 64 } // namespace delegates 65 } // namespace tflite 66