tflite_runtime.cc 6.67 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*!
 * \file tflite_runtime.cc
 */
#include <tvm/runtime/registry.h>
#include <tensorflow/lite/interpreter.h>
#include <tensorflow/lite/kernels/register.h>
#include <tensorflow/lite/model.h>


#include "tflite_runtime.h"

namespace tvm {
namespace runtime {

#define TVM_DTYPE_DISPATCH(type, DType, ...)            \
35
  if (type == DataType::Float(64)) {                    \
36 37
    typedef double DType;                               \
    {__VA_ARGS__}                                       \
38
  } else if (type == DataType::Float(32)) {             \
39 40
    typedef float DType;                                \
    {__VA_ARGS__}                                       \
41
  } else if (type == DataType::Float(16)) {             \
42 43
    typedef uint16_t DType;                             \
    {__VA_ARGS__}                                       \
44
  } else if (type == DataType::Int(64)) {               \
45 46
    typedef int64_t DType;                              \
    {__VA_ARGS__}                                       \
47
  } else if (type == DataType::Int(32)) {               \
48 49
    typedef int32_t DType;                              \
    {__VA_ARGS__}                                       \
50
  } else if (type == DataType::Int(16)) {               \
51 52
    typedef int16_t DType;                              \
    {__VA_ARGS__}                                       \
53
  } else if (type == DataType::Int(8)) {                \
54 55
    typedef int8_t DType;                               \
    {__VA_ARGS__}                                       \
56
  } else if (type == DataType::UInt(64)) {              \
57 58
    typedef uint64_t DType;                             \
    {__VA_ARGS__}                                       \
59
  } else if (type == DataType::UInt(32)) {              \
60 61
    typedef uint32_t DType;                             \
    {__VA_ARGS__}                                       \
62
  } else if (type == DataType::UInt(16)) {              \
63 64
    typedef uint16_t DType;                             \
    {__VA_ARGS__}                                       \
65
  } else if (type == DataType::UInt(8)) {               \
66 67 68 69 70 71 72 73 74
    typedef uint8_t DType;                              \
    {__VA_ARGS__}                                       \
  } else {                                              \
    LOG(FATAL) << "unknown data type " << type;         \
  }

DataType TfLiteDType2TVMDType(TfLiteType dtype) {
  switch (dtype) {
    case kTfLiteFloat32:
75
      return DataType::Float(32);
76
    case kTfLiteInt32:
77
      return DataType::Int(32);
78
    case kTfLiteInt64:
79
      return DataType::Int(64);
80
    case kTfLiteInt16:
81
      return DataType::Int(16);
82
    case kTfLiteInt8:
83
      return DataType::Int(8);
84
    case kTfLiteUInt8:
85
      return DataType::UInt(8);
86
    case kTfLiteFloat16:
87
      return DataType::Float(16);
88 89
    default:
      LOG(FATAL) << "tflite data type not support yet: " << dtype;
90
      return DataType::Float(32);
91 92 93 94 95 96 97 98 99 100
  }
}

void TFLiteRuntime::Init(const std::string& tflite_model_bytes,
                         TVMContext ctx) {
  const char* buffer = tflite_model_bytes.c_str();
  size_t buffer_size = tflite_model_bytes.size();
  std::unique_ptr<tflite::FlatBufferModel> model =
    tflite::FlatBufferModel::BuildFromBuffer(buffer, buffer_size);
  tflite::ops::builtin::BuiltinOpResolver resolver;
101 102 103 104 105 106
  // Build interpreter
  TfLiteStatus status = tflite::InterpreterBuilder(*model, resolver)(&interpreter_);
  CHECK_TFLITE_STATUS(status) << "Failed to build interpreter.";
  // Allocate tensors
  status = interpreter_->AllocateTensors();
  CHECK_TFLITE_STATUS(status) << "Failed to allocate tensors.";
107

108
  ctx_ = ctx;
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
}

void TFLiteRuntime::Invoke() {
  interpreter_->Invoke();
}

void TFLiteRuntime::SetInput(int index, DLTensor* data_in) {
  DataType dtype(data_in->dtype);
  TVM_DTYPE_DISPATCH(dtype, DType, {
      DType* dest = interpreter_->typed_input_tensor<DType>(index);
      DType* src = static_cast<DType*>(data_in->data);
      CHECK(data_in->strides == NULL);
      int64_t size = 1;
      for (int64_t i = 0; i < data_in->ndim; ++i) {
        size *= data_in->shape[i];
      }
      for (int64_t i = 0; i < size; ++i) {
        dest[i] = src[i];
      }
    });
}

NDArray TFLiteRuntime::GetOutput(int index) const {
132
  TfLiteTensor* output = interpreter_->tensor(interpreter_->outputs()[index]);
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  DataType dtype = TfLiteDType2TVMDType(output->type);
  TfLiteIntArray* dims = output->dims;
  int64_t size = 1;
  std::vector<int64_t> shape;
  for (int i = 0; i < dims->size; ++i) {
    shape.push_back(dims->data[i]);
    size *= dims->data[i];
  }
  NDArray ret = NDArray::Empty(shape, dtype, ctx_);
  TVM_DTYPE_DISPATCH(dtype, DType, {
      DType* dest = static_cast<DType*>(ret->data);
      DType* src = interpreter_->typed_output_tensor<DType>(index);
      for (int64_t i = 0; i < size; ++i) {
        dest[i] = src[i];
      }
    });
  return ret;
}

PackedFunc TFLiteRuntime::GetFunction(
    const std::string& name,
    const ObjectPtr<Object>& sptr_to_self) {
  // Return member functions during query.
  if (name == "set_input") {
    return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {
        int in_idx = args[0];
        CHECK_GE(in_idx, 0);
        this->SetInput(in_idx, args[1]);
      });
  } else if (name == "get_output") {
    return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {
        *rv = this->GetOutput(args[0]);
      });
  } else if (name == "invoke") {
    return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) {
        this->Invoke();
      });
  } else {
    return PackedFunc();
  }
}

Module TFLiteRuntimeCreate(const std::string& tflite_model_bytes,
                           TVMContext ctx) {
  auto exec = make_object<TFLiteRuntime>();
  exec->Init(tflite_model_bytes, ctx);
  return Module(exec);
}

TVM_REGISTER_GLOBAL("tvm.tflite_runtime.create")
  .set_body([](TVMArgs args, TVMRetValue* rv) {
    *rv = TFLiteRuntimeCreate(args[0], args[1]);
  });
}  // namespace runtime
}  // namespace tvm