内容创建/渲染

基于 NVIDIA 的 PC 端到端人工智能:从 FP32 过渡到 FP16 优化人工智能

这篇文章是关于人工智能端到端优化。

人工智能模型的性能在很大程度上受到所使用计算资源的精度的影响。较低的精度可以提高处理速度和减少内存使用,而较高的精度可以获得更准确的结果。在精度和性能之间找到正确的平衡对于优化人工智能应用程序至关重要。

NVIDIA GPU 配备了 Tensor Core 等专用硬件,已成为加速人工智能工作负载的关键组件。为了充分利用它们的功能,重要的是要满足某些限制,并基于特定的人工智能应用程序优化硬件。

在这篇文章中,我们讨论了如何通过从 FP32 (单精度浮点格式)转换到 FP16 (半精度浮点数格式)来优化 AI 的 GPU 。我们介绍了使用 FP16 的优势、转换模型的方法,以及这种转换对人工智能应用程序的质量和性能的影响。

初始性能:一个简单的未优化模

An image of a squirrel with a lot of noise.
图 1 。运行模型之前的嘈杂图像

从 ONNX 格式的简单未优化模型开始。 Nsight Systems 的配置文件显示,四次运行的执行时间为 173 毫秒。尽管这可能看起来很快,但这是针对单个图像的。想象一下,如果你像摄影师经常要做的那样,大量处理 500 张图像,这几乎需要一分钟半的时间。

Screenshot of the Nsight Systems profile shows that the execution time for the FP32 model is 173 ms.
图 2 : FP32 型号的 Nsight 系统简介

从 FP32 过渡到 FP16

目前,该模型采用 FP32 精度,每个浮点值使用 32 位。这可能比必要的更精确。通过转换到 FP16 ,您可以启用张量内核并提高浮点吞吐量。

Python ONNX 模块提供两种解决方案:Float_to_float16以及自动混合精度。

Float_to_float16 方法

位于onnxconverter_common这个Float_to_float16方法可以将模型中的所有浮点值转换为 FP16 。

import onnx
from onnxconverter_common.float16 import convert_float_to_float16

model_FP32 = onnx.load("model.onnx")
model_FP16 = convert_float_to_float16(copy.deepcopy(model_FP32))
onnx.save(model_FP16, "model_FP16.onnx")

如果原始模型中的重量超过 FP16 的动态范围,则会出现溢出。

自动混合精度方法

任何不需要的行为都可以通过使用自动混合精度方法来克服。也可在中找到onnxconverter_common,此方法采用混合精度转换。该方法只转换 FP16 不影响输出的层,并且需要测试数据和可选的验证方法。

import onnx
import numpy as np
from onnxconverter_common.auto_mixed_precision import auto_convert_mixed_precision

# Could also use rtol/atol attributes directly instead of this
def validate(res1, res2):
    for r1, r2 in zip(res1, res2):
        if not np.allclose(r1, r2, rtol=0.01, atol=0.001):
            return False
    return True

model_FP32 = onnx.load("model.onnx")
feed_dict = {"input": 2*np.random.rand(1, 3, 128, 128).astype(np.float32)-1.0}
model_amp = auto_convert_mixed_precision(model_FP32, feed_dict, validate)
onnx.save(model_amp, "model_amp.onnx")

FP16 提高了性能

在使用第一种转换方法后,该模型现在只需 42 毫秒即可运行,比以前快了 4 倍。对于 500 张图像,这将花费从接近 90 秒到仅 21 秒的时间。

Screenshot of the Nsight Systems profile shows that the execution time for the FP16 model is 42 ms.
图 3 。 FP16 型号的 Nsight 系统简介

质量比较: FP32 与 FP16

担心精度降低会导致质量下降?从并排图像比较中可以看出(图 4 ), FP32 和 FP16 模型输出的去噪图像是相同的。尽管使用了较低精度的方法,但它们之间没有明显的视觉差异。

Two denoised images of a squirrel, one from the FP32 model and one from the FP16 model.
图 4 。(左) FP32 和(右) FP16 型号的输出

结论

通过只需几行额外的代码转换到 FP16 ,我们实现了 4 倍的加速。这启用了 Tensor 内核,提高了数据吞吐量,同时减少了视频内存的使用。

准备好优化你的人工智能了吗?有关详细信息,请参阅NVIDIA/ProViz-AI-SamplesGitHub 回购并亲自尝试。如果您有任何问题,请联系数据处理开发者论坛

 

Tags