具有委托 gpu 的 TFlite 给出错误的结果

Posted

技术标签:

【中文标题】具有委托 gpu 的 TFlite 给出错误的结果【英文标题】:TFlite with delegate gpu is give wrong result 【发布时间】:2021-12-22 00:26:34 【问题描述】:

我正在尝试根据嵌入式设备上的 c++ 代码推断我的 tflite 模型。 因此,我输入了使用 GPU 的简单 tflite 推理代码。 我在我的 PC 中交叉编译并在运行 android 的嵌入式设备上运行。

但是,(1) 如果我使用委托 gpu 选项,c++ 代码会给出随机结果。 (2) 它给出了相同的输入,但结果发生了变化每次。(3) 当我关闭 gpu 选项时,它会给我一个正确的结果。

当我在 python 中测试我的 tflite 模型时,它给出了正确的输出。 所以我认为模型文件没有问题。

我应该重新构建 TensorFlow-lite,因为我使用的是预构建的 .so 文件吗?还是我应该更改 GPU 选项? 我不知道我应该检查更多。 请帮忙!

这是我的 C++ 代码

// Load model
std::unique_ptr<tflite::FlatBufferModel> model = 
tflite::FlatBufferModel::BuildFromFile(model_file.c_str());

// Build the interpreter
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder(*model, resolver)(&interpreter);

// set delegate option
bool use_gpu = true;
if(use_gpu)

  TfLiteDelegate* delegate;
  auto options = TfLiteGpuDelegateOptionsV2Default();
  options.inference_preference = TFLITE_GPU_INFERENCE_PREFERENCE_FAST_SINGLE_ANSWER; 
  options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_AUTO;
  delegate = TfLiteGpuDelegateV2Create(&options);
  interpreter->ModifyGraphWithDelegate(delegate);


interpreter->AllocateTensors();

// set input
float* input = interpreter->typed_input_tensor<float>(0);
for(int i=0; i<width*height*channel; i++)
  *(input+i) = 1;

TfLiteTensor* output_tensor = nullptr;
    
// Inference
interpreter->Invoke();

// Check output
output_tensor = interpreter->tensor(interpreter->outputs()[0]);
printf("Result : %f\n",output_tensor->data.f[0]);
    
//float* output = interpreter->typed_output_tensor<float>(0);
//printf("output : %f\n",*(output));    

【问题讨论】:

我会在这里寻找 2 个潜在问题:GPU 计算问题本身和精度问题。第一个可以用简单的模型处理:比如一个 conv 层并比较 CPU/GPU 结果,第二个可能是一个问题,如果你有一些强大的操作:将你的模型剪切到那个操作并比较 cpu/gpu 输出 能否请您在 github 上向团队提交一个 [bug](github.com/tensorflow/tensorflow/issues/…。 【参考方案1】:

幸运的是,我找到了答案。 这是由于 NDK 版本不匹配造成的。 (我使用的预建so文件是另一个版本) 统一NDK版本到21后,再次测试,正常运行。

【讨论】:

以上是关于具有委托 gpu 的 TFlite 给出错误的结果的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 Python 在 GPU (Jetson Nano) 上运行 tflite 模型

Flutter tflite图像分类如何不显示错误结果

如何使用相同的测试数据测试 .tflite 模型以证明它的行为与原始模型相同?

SYCL/DPC++ cpu 版本给出了正确的结果,但 gpu 给出了不正确的数据

条件表达式中的 zipmap 函数给出真假结果表达式必须具有一致的类型错误

TfLite 模型与量化前模型的不同结果