tflite 源码解读

本文详细解读了TensorFlow Lite的源码,重点介绍了多线程执行的过程,包括如何设置线程数、CPU后台上下文的线程管理、RUY库的线程分配策略以及模型执行过程中的线程使用。通过对`Interpreter`类、`Subgraph`、`TfLiteContext`、`CpuBackendContext`、`Ruy::Context`等关键组件的分析,揭示了Lite中线程管理的实现细节。
摘要由CSDN通过智能技术生成

以下为鄙人读源码时做的一些粗略记录,如有不当望请多多指教(抱拳)

一、源码解读(主要为多线程执行过程)。从C++ 模型声明tflite::Interpreter类型做入口

1、tensorflow\lite\interpreter.cc

void Interpreter::SetNumThreads(int num_threads) {
  for (auto& subgraph : subgraphs_) {
    subgraph->context()->recommended_num_threads = num_threads;
  }

  for (int i = 0; i < kTfLiteMaxExternalContexts; ++i) {
    auto* c = external_contexts_[i];
    if (c && c->Refresh) {
      c->Refresh(context_);
    }
  }
}

(a)、void SetNumThreads(int num_threads) ;  线程数设置   最新github上改了函数名字,改成void cpus(int num_threads);

(b)、顺着函数里面subgraph找到, tensorflow\lite\core\subgraph.h  里面的class Subgraph{} 以及里面的成员TfLiteContext* context()

(c)、TfLiteContext 在tensorflow\lite\c\c_api_internal.h  里面定义typedef struct TfLiteContext {} 以及成员变量recommended_num_threads

2、根据recommended_num_threads 找到tensorflow\lite\kernels\cpu_backend_context.cc 

CpuBackendContext* CpuBackendContext::GetFromContext(TfLiteContext* context) {
  auto* external_context = static_cast<ExternalCpuBackendContext*>(
      context->GetExternalContext(context, kTfLiteCpuBackendContext));

  if (external_context == nullptr) {
    TF_LITE_FATAL(
        "ExternalCpuBackendContext isn't properly initialized during TFLite "
        "interpreter initialization.");
  }

  auto* cpu_backend_context = static_cast<CpuBackendContext*>(
      external_context->internal_backend_context());
  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值