CPU Pytorch 上的 fp16 推理

问题描述 投票:0回答:3

我有一个

pretrained pytorch
模型,我想在
fp16
而不是
fp32
上进行推断,我已经在使用
gpu
时尝试过这个,但是当我在
cpu
上尝试时,我得到:
"sum_cpu" not implemented for 'Half' torch
。 有修复吗?

python pytorch eval cpu half-precision-float
3个回答
1
投票

据我所知,Pytorch 中很多基于 CPU 的操作都没有实现支持 FP16;相反,NVIDIA GPU 具有对 FP16 的硬件支持(例如 Turing arch GPU 中的张量核心),而 PyTorch 自 CUDA 7.0(ish)起跟进。要通过量化到 FP16 来加速 CPU 上的推理,您可能需要尝试 torch.bfloat16 dtype(https://github.com/pytorch/pytorch/issues/23509)。


1
投票

如果您有 Intel 的 CPU,您可以尝试 OpenVINO。它允许您将模型转换为中间表示 (IR),然后在支持 FP16 的 CPU 上运行。我不能保证您的模型是可转换的(这取决于您是否有精美的自定义图层),但值得一试。您可以在此处找到有关如何转换 PyTorch 模型的完整教程。 下面是一些片段。

安装 OpenVINO

最简单的方法是使用 PIP。或者,您可以使用此工具找到适合您情况的最佳方法。

pip install openvino-dev[pytorch,onnx]

将模型保存到 ONNX

OpenVINO 目前无法直接转换 PyTorch 模型,但可以使用 ONNX 模型进行转换。此示例代码假设该模型用于计算机视觉。

dummy_input = torch.randn(1, 3, IMAGE_HEIGHT, IMAGE_WIDTH)
torch.onnx.export(model, dummy_input, "model.onnx", opset_version=11)

使用模型优化器转换ONNX模型

模型优化器是一个命令行工具,来自 OpenVINO 开发包,因此请确保您已安装它。它将 ONNX 模型转换为 IR,这是 OpenVINO 的默认格式。它还将精度更改为 FP16。在命令行中运行:

mo --input_model "model.onnx" --input_shape "[1,3, 224, 224]" --mean_values="[123.675, 116.28 , 103.53]" --scale_values="[58.395, 57.12 , 57.375]" --data_type FP16 --output_dir "model_ir"

在CPU上运行推理

转换后的模型可以由运行时加载并针对特定设备进行编译,例如中央处理器。

# Load the network
ie = Core()
model_ir = ie.read_model(model="model_ir/model.xml")
compiled_model_ir = ie.compile_model(model=model_ir, device_name="CPU")

# Get output layer
output_layer_ir = compiled_model_ir.output(0)

# Run inference on the input image
result = compiled_model_ir([input_image])[output_layer_ir]

免责声明:我从事 OpenVINO 工作。


1
投票

查看此文档 - https://intel.github.io/intel-extension-for-pytorch/latest/tutorials/features/amp.html。 Intel Extension for PyTorch 支持 CPU 的自动混合精度功能。 在代码中,我们需要更改为 torch.cpu.amp.autocast() 而不是 torch.autocast(device_name="cpu")。 torch.cpu.amp 支持 BFloat16 数据类型。

© www.soinside.com 2019 - 2024. All rights reserved.