实现自定义委托

借助 TensorFlow Lite 委托,您可以在其他执行器上运行您的模型(部分或全部)。这种机制可以利用各种设备端加速器,例如 GPU 或 Edge TPU(张量处理单元)进行推理。这为开发者提供了一种从默认 TFLite 中分离出来的灵活方法,以加快推理速度。

下图总结了受托人,请参阅以下部分了解详情。

TFLite 委托

何时应创建自定义委托?

TensorFlow Lite 为目标加速器(如 GPU、DSP 和 EdgeTPU)提供了各种代理。

在以下情况下,创建自己的委托会非常有用:

  • 您想要集成任何现有代理不支持的新机器学习推断引擎。
  • 您有一个自定义硬件加速器,它可以针对已知场景改进运行时。
  • 您正在开发 CPU 优化(例如运算符融合)可以加快某些模型的速度。

受托人是如何运作的?

假设有一个简单的模型图(如下所示),以及一个可以更快地实现 Conv2D 和 Mean 操作的代理“MyDelegate”。

原始图表

应用此“MyDelegate”后,原始 TensorFlow Lite 图将会更新,如下所示:

包含委托的图表

上图通过 TensorFlow Lite 将原始图拆分为以下两条规则而获得:

  • 可由委托处理的特定操作会被放入分区中,同时仍满足操作之间的原始计算工作流依赖关系。
  • 每个要委托的分区只有不由该委托处理的输入和输出节点。

委托处理的每个分区都被原始图中的委托节点(也称为委托内核)替换,而委托节点会在调用调用时评估分区。

根据模型的不同,最终图最终可以有一个或多个节点,后者意味着代理不支持某些操作。通常,您不希望委托处理多个分区,因为每次从委托切换到主图时,因内存副本(例如 GPU 到 CPU)而将结果从委托子图传递到主图都会产生开销。这种开销可能会抵消性能提升,尤其是在存在大量内存副本时。

实现您自己的自定义委托

添加委托的首选方法是使用 SimpleDelegate API

如需创建新的委托,您需要实现 2 个接口,并为接口方法提供您自己的实现。

1 - SimpleDelegateInterface

此类表示代理的功能(支持哪些操作),以及用于创建封装委派图的内核的工厂类。如需了解详情,请参阅此 C++ 头文件中定义的接口。代码中的注释详细介绍了每个 API。

2 - SimpleDelegateKernelInterface

此类封装了初始化 / 准备 / 运行委托分区的逻辑。

它具有以下特点:(请参阅定义

  • Init(...):将被调用一次以执行任何一次性初始化。
  • Prepare(...):针对此节点的每个不同实例调用 - 如果您有多个委派分区,就会发生这种情况。通常情况下,您需要在此处进行内存分配,因为每次调整张量的大小时都会调用该函数。
  • Invoke(...):为进行推理而调用。

示例

在此示例中,您将创建一个非常简单的委托,它仅支持使用 float32 张量的 2 种操作 (ADD) 和 (SUB)。

// MyDelegate implements the interface of SimpleDelegateInterface.
// This holds the Delegate capabilities.
class MyDelegate : public SimpleDelegateInterface {
 public:
  bool IsNodeSupportedByDelegate(const TfLiteRegistration* registration,
                                 const TfLiteNode* node,
                                 TfLiteContext* context) const override {
    // Only supports Add and Sub ops.
    if (kTfLiteBuiltinAdd != registration->builtin_code &&
        kTfLiteBuiltinSub != registration->builtin_code)
      return false;
    // This delegate only supports float32 types.
    for (int i = 0; i < node->inputs->size; ++i) {
      auto& tensor = context->tensors[node->inputs->data[i]];
      if (tensor.type != kTfLiteFloat32) return false;
    }
    return true;
  }

  TfLiteStatus Initialize(TfLiteContext* context) override { return kTfLiteOk; }

  const char* Name() const override {
    static constexpr char kName[] = "MyDelegate";
    return kName;
  }

  std::unique_ptr<SimpleDelegateKernelInterface> CreateDelegateKernelInterface()
      override {
    return std::make_unique<MyDelegateKernel>();
  }
};

接下来,通过继承 SimpleDelegateKernelInterface 创建自己的委托内核

// My delegate kernel.
class MyDelegateKernel : public SimpleDelegateKernelInterface {
 public:
  TfLiteStatus Init(TfLiteContext* context,
                    const TfLiteDelegateParams* params) override {
    // Save index to all nodes which are part of this delegate.
    inputs_.resize(params->nodes_to_replace->size);
    outputs_.resize(params->nodes_to_replace->size);
    builtin_code_.resize(params->nodes_to_replace->size);
    for (int i = 0; i < params->nodes_to_replace->size; ++i) {
      const int node_index = params->nodes_to_replace->data[i];
      // Get this node information.
      TfLiteNode* delegated_node = nullptr;
      TfLiteRegistration* delegated_node_registration = nullptr;
      TF_LITE_ENSURE_EQ(
          context,
          context->GetNodeAndRegistration(context, node_index, &delegated_node,
                                          &delegated_node_registration),
          kTfLiteOk);
      inputs_[i].push_back(delegated_node->inputs->data[0]);
      inputs_[i].push_back(delegated_node->inputs->data[1]);
      outputs_[i].push_back(delegated_node->outputs->data[0]);
      builtin_code_[i] = delegated_node_registration->builtin_code;
    }
    return kTfLiteOk;
  }

  TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) override {
    return kTfLiteOk;
  }

  TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) override {
    // Evaluate the delegated graph.
    // Here we loop over all the delegated nodes.
    // We know that all the nodes are either ADD or SUB operations and the
    // number of nodes equals ''inputs_.size()'' and inputs[i] is a list of
    // tensor indices for inputs to node ''i'', while outputs_[i] is the list of
    // outputs for node
    // ''i''. Note, that it is intentional we have simple implementation as this
    // is for demonstration.

    for (int i = 0; i < inputs_.size(); ++i) {
      // Get the node input tensors.
      // Add/Sub operation accepts 2 inputs.
      auto& input_tensor_1 = context->tensors[inputs_[i][0]];
      auto& input_tensor_2 = context->tensors[inputs_[i][1]];
      auto& output_tensor = context->tensors[outputs_[i][0]];
      TF_LITE_ENSURE_EQ(
          context,
          ComputeResult(context, builtin_code_[i], &input_tensor_1,
                        &input_tensor_2, &output_tensor),
          kTfLiteOk);
    }
    return kTfLiteOk;
  }

 private:
  // Computes the result of addition of 'input_tensor_1' and 'input_tensor_2'
  // and store the result in 'output_tensor'.
  TfLiteStatus ComputeResult(TfLiteContext* context, int builtin_code,
                             const TfLiteTensor* input_tensor_1,
                             const TfLiteTensor* input_tensor_2,
                             TfLiteTensor* output_tensor) {
    if (NumElements(input_tensor_1) != NumElements(input_tensor_2) ||
        NumElements(input_tensor_1) != NumElements(output_tensor)) {
      return kTfLiteDelegateError;
    }
    // This code assumes no activation, and no broadcasting needed (both inputs
    // have the same size).
    auto* input_1 = GetTensorData<float>(input_tensor_1);
    auto* input_2 = GetTensorData<float>(input_tensor_2);
    auto* output = GetTensorData<float>(output_tensor);
    for (int i = 0; i < NumElements(input_tensor_1); ++i) {
      if (builtin_code == kTfLiteBuiltinAdd)
        output[i] = input_1[i] + input_2[i];
      else
        output[i] = input_1[i] - input_2[i];
    }
    return kTfLiteOk;
  }

  // Holds the indices of the input/output tensors.
  // inputs_[i] is list of all input tensors to node at index 'i'.
  // outputs_[i] is list of all output tensors to node at index 'i'.
  std::vector<std::vector<int>> inputs_, outputs_;
  // Holds the builtin code of the ops.
  // builtin_code_[i] is the type of node at index 'i'
  std::vector<int> builtin_code_;
};


对新委托进行基准化分析和评估

TFLite 提供一系列工具,可用于针对 TFLite 模型快速测试。

  • 模型基准工具:该工具采用 TFLite 模型,生成随机输入,然后重复运行该模型以进行指定的次数。它会在最后输出汇总的延迟时间统计信息。
  • 推断差异工具:对于给定的模型,该工具会生成随机高斯数据,并通过两个不同的 TFLite 解释器传递这些数据,其中一个运行单线程 CPU 内核,另一个使用用户定义的规范。它会按元素测量每个解释器的输出张量之间的绝对差异。此工具还有助于调试准确性问题。
  • 还有一些针对特定任务的评估工具,用于图片分类和对象检测。您可以在此处找到这些工具

此外,TFLite 具有大量内核和操作单元测试,可以重复使用这些测试,以测试新的代理并扩大其覆盖范围,并确保常规 TFLite 执行路径不会损坏。

如需为新委托实现重复使用 TFLite 测试和工具,您可以使用以下两个选项之一:

选择最佳方法

这两种方法都需要进行一些更改,如下所述。不过,第一种方法是以静态方式链接委托,并且需要重新构建测试、基准化分析和评估工具。第二种方法将委托设为共享库,并要求您公开共享库中的 create/delete 方法。

因此,外部委托机制将适用于 TFLite 的预构建 Tensorflow Lite 工具二进制文件。但其定义不太明确,并且在自动集成测试中设置可能更复杂。使用委托注册商的方法更加清晰明确。

方法 1:利用委托注册商

代理注册商保留一个代理提供方列表,其中每个代理提供方都可让您根据命令行标志轻松创建 TFLite 代理,因此方便使用工具。如需将新的委托插入到上述所有 Tensorflow Lite 工具,您需要先创建新的委托提供程序,然后对 BUILD 规则进行少量更改。下面显示了此集成过程的完整示例(可以在此处找到代码)。

假设您有一个实现 SimpleDelegate API 的委托,以及用于创建/删除此“虚拟”代理的外部“C”API,如下所示:

// Returns default options for DummyDelegate.
DummyDelegateOptions TfLiteDummyDelegateOptionsDefault();

// Creates a new delegate instance that need to be destroyed with
// `TfLiteDummyDelegateDelete` when delegate is no longer used by TFLite.
// When `options` is set to `nullptr`, the above default values are used:
TfLiteDelegate* TfLiteDummyDelegateCreate(const DummyDelegateOptions* options);

// Destroys a delegate created with `TfLiteDummyDelegateCreate` call.
void TfLiteDummyDelegateDelete(TfLiteDelegate* delegate);

如需将“DummyDelegate”与基准工具和推断工具集成,请定义一个 DelegateProvider,如下所示:

class DummyDelegateProvider : public DelegateProvider {
 public:
  DummyDelegateProvider() {
    default_params_.AddParam("use_dummy_delegate",
                             ToolParam::Create<bool>(false));
  }

  std::vector<Flag> CreateFlags(ToolParams* params) const final;

  void LogParams(const ToolParams& params) const final;

  TfLiteDelegatePtr CreateTfLiteDelegate(const ToolParams& params) const final;

  std::string GetName() const final { return "DummyDelegate"; }
};
REGISTER_DELEGATE_PROVIDER(DummyDelegateProvider);

std::vector<Flag> DummyDelegateProvider::CreateFlags(ToolParams* params) const {
  std::vector<Flag> flags = {CreateFlag<bool>("use_dummy_delegate", params,
                                              "use the dummy delegate.")};
  return flags;
}

void DummyDelegateProvider::LogParams(const ToolParams& params) const {
  TFLITE_LOG(INFO) << "Use dummy test delegate : ["
                   << params.Get<bool>("use_dummy_delegate") << "]";
}

TfLiteDelegatePtr DummyDelegateProvider::CreateTfLiteDelegate(
    const ToolParams& params) const {
  if (params.Get<bool>("use_dummy_delegate")) {
    auto default_options = TfLiteDummyDelegateOptionsDefault();
    return TfLiteDummyDelegateCreateUnique(&default_options);
  }
  return TfLiteDelegatePtr(nullptr, [](TfLiteDelegate*) {});
}

BUILD 规则定义非常重要,因为您需要确保库始终处于关联状态,且不会被优化器丢弃。

#### The following are for using the dummy test delegate in TFLite tooling ####
cc_library(
    name = "dummy_delegate_provider",
    srcs = ["dummy_delegate_provider.cc"],
    copts = tflite_copts(),
    deps = [
        ":dummy_delegate",
        "//tensorflow/lite/tools/delegates:delegate_provider_hdr",
    ],
    alwayslink = 1, # This is required so the optimizer doesn't optimize the library away.
)

现在,在 BUILD 文件中添加这两个封装容器规则,以创建基准工具和推断工具以及其他评估工具版本,以便使用您自己的代理运行。

cc_binary(
    name = "benchmark_model_plus_dummy_delegate",
    copts = tflite_copts(),
    linkopts = task_linkopts(),
    deps = [
        ":dummy_delegate_provider",
        "//tensorflow/lite/tools/benchmark:benchmark_model_main",
    ],
)

cc_binary(
    name = "inference_diff_plus_dummy_delegate",
    copts = tflite_copts(),
    linkopts = task_linkopts(),
    deps = [
        ":dummy_delegate_provider",
        "//tensorflow/lite/tools/evaluation/tasks:task_executor_main",
        "//tensorflow/lite/tools/evaluation/tasks/inference_diff:run_eval_lib",
    ],
)

cc_binary(
    name = "imagenet_classification_eval_plus_dummy_delegate",
    copts = tflite_copts(),
    linkopts = task_linkopts(),
    deps = [
        ":dummy_delegate_provider",
        "//tensorflow/lite/tools/evaluation/tasks:task_executor_main",
        "//tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification:run_eval_lib",
    ],
)

cc_binary(
    name = "coco_object_detection_eval_plus_dummy_delegate",
    copts = tflite_copts(),
    linkopts = task_linkopts(),
    deps = [
        ":dummy_delegate_provider",
        "//tensorflow/lite/tools/evaluation/tasks:task_executor_main",
        "//tensorflow/lite/tools/evaluation/tasks/coco_object_detection:run_eval_lib",
    ],
)

您还可以将此代理提供程序插入到 TFLite 内核测试中,如此处所述。

方法 2:利用外部受托人

在此替代方案中,您需要先在 external_delegate_adaptor.cc 中创建一个外部代理适配器,如下所示。请注意,与上述方法 1 相比,此方法的首选方法不是那么首选。

TfLiteDelegate* CreateDummyDelegateFromOptions(char** options_keys,
                                               char** options_values,
                                               size_t num_options) {
  DummyDelegateOptions options = TfLiteDummyDelegateOptionsDefault();

  // Parse key-values options to DummyDelegateOptions.
  // You can achieve this by mimicking them as command-line flags.
  std::unique_ptr<const char*> argv =
      std::unique_ptr<const char*>(new const char*[num_options + 1]);
  constexpr char kDummyDelegateParsing[] = "dummy_delegate_parsing";
  argv.get()[0] = kDummyDelegateParsing;

  std::vector<std::string> option_args;
  option_args.reserve(num_options);
  for (int i = 0; i < num_options; ++i) {
    option_args.emplace_back("--");
    option_args.rbegin()->append(options_keys[i]);
    option_args.rbegin()->push_back('=');
    option_args.rbegin()->append(options_values[i]);
    argv.get()[i + 1] = option_args.rbegin()->c_str();
  }

  // Define command-line flags.
  // ...
  std::vector<tflite::Flag> flag_list = {
      tflite::Flag::CreateFlag(...),
      ...,
      tflite::Flag::CreateFlag(...),
  };

  int argc = num_options + 1;
  if (!tflite::Flags::Parse(&argc, argv.get(), flag_list)) {
    return nullptr;
  }

  return TfLiteDummyDelegateCreate(&options);
}

#ifdef __cplusplus
extern "C" {
#endif  // __cplusplus

// Defines two symbols that need to be exported to use the TFLite external
// delegate. See tensorflow/lite/delegates/external for details.
TFL_CAPI_EXPORT TfLiteDelegate* tflite_plugin_create_delegate(
    char** options_keys, char** options_values, size_t num_options,
    void (*report_error)(const char*)) {
  return tflite::tools::CreateDummyDelegateFromOptions(
      options_keys, options_values, num_options);
}

TFL_CAPI_EXPORT void tflite_plugin_destroy_delegate(TfLiteDelegate* delegate) {
  TfLiteDummyDelegateDelete(delegate);
}

#ifdef __cplusplus
}
#endif  // __cplusplus

现在,创建相应的 build 目标以构建动态库,如下所示:

cc_binary(
    name = "dummy_external_delegate.so",
    srcs = [
        "external_delegate_adaptor.cc",
    ],
    linkshared = 1,
    linkstatic = 1,
    deps = [
        ":dummy_delegate",
        "//tensorflow/lite/c:common",
        "//tensorflow/lite/tools:command_line_flags",
        "//tensorflow/lite/tools:logging",
    ],
)

创建此外部委托 .so 文件后,您就可以构建二进制文件或使用预构建的文件来与新的委托一起运行,前提是二进制文件与支持命令行标志的 external_delegate_provider 库相关联,如此处所述。注意:此外部委托提供程序已关联到现有的测试和工具二进制文件。

请参阅此处的说明,了解如何通过这种外部委托方法对虚拟代理进行基准测试。您可以对前面提到的测试和评估工具使用类似命令。

值得注意的是,“外部委托”是 Tensorflow Lite Python 绑定中委托的相应 C++ 实现,如此处所示。因此,此处创建的动态外部代理适配器库可以直接用于 Tensorflow Lite Python API。

资源

操作系统 归档 BINARY_NAME
Linux x86_64
arm
aarch64
Android arm
aarch64