无法使用来自 'CUDA' 后端的参数 运行 'aten::empty_strided'

Could not run 'aten::empty_strided' with arguments from the 'CUDA' backend

我正在尝试将 pytorch 模型保存到 .ptl 文件中并将其加载到 android 但它一直抛出此错误并让我抓狂。

Could not run 'aten::empty_strided' with arguments from the 'CUDA' backend. This could be because the operator doesn't exist for this backend, or was omitted during the selective/custom build process (if using custom build). If you are a Facebook employee using PyTorch on mobile, please visit https://fburl.com/ptmfixes for possible resolutions. 'aten::empty_strided' is only available for these backends: [CPU, Vulkan, BackendSelect, ADInplaceOrView, AutogradOther, AutogradCPU, AutogradCUDA, AutogradXLA, AutogradLazy, AutogradXPU, AutogradMLC].

但问题是我在保存之前将我的模型转移到 cpu。所以错误甚至没有意义。

example = torch.rand(1, 3, 224, 224)
model_conv = model_conv.to("cpu")

for param in model_conv.parameters():
    if param.is_cuda:
        print("Tensor on cuda")
        break
else:
    print("No tensor on cuda.")

# move model back to cpu, do tracing, and optimize
traced_script_module = torch.jit.trace(model_conv, example)
torchscript_model_optimized = optimize_for_mobile(traced_script_module)

# save optimized model for mobile
PATH = 'model.ptl'
torchscript_model_optimized._save_for_lite_interpreter(PATH)
print(f"optimized model saved to {PATH}")

for循环的输出是No tensor on cuda。这就是我在 android 中加载模型的方式。我从他们的 github 加载了一个示例模型并且它有效,所以我怀疑 android 代码存在问题。

module = LiteModuleLoader.load(MainActivity.assetFilePath(getApplicationContext(), "model.ptl"));

旁白:保存模型的方法有很多种。为什么 Pytorch Mobile 没有好的文档。 Tflite 有比这更好的文档。

原来是 Android 问题。 Android 不会更新资产文件,即使它们已更改,对我来说它使用的是未转换为 cpu.

的旧模型

如果您遇到类似问题或您的准确性没有提高,请尝试在模拟或应用设置中清除应用数据。

Phone/emulator 设置 -> 应用菜单

这个 github 问题最终帮助了我:https://github.com/pytorch/pytorch/issues/53650