使用 Torch_TensorRT 量化分割模型
本文使用 Torch_TensorRT 量化 deeplapv3 + 模型,
Torch-TensorRT 是 PyTorch 的推理编译器,通过 NVIDIA 的 TensorRT 深度学习优化器,运行时以 NVIDIA GPU 为目标。 它通过界面支持即时 (JIT) 编译工作流以及预先 (AOT) 工作流。 Torch-TensorRT 无缝集成到 PyTorch 生态系统中,支持将优化的 TensorRT 代码与标准 PyTorch 代码混合执行。
由于 Torch-TensorRT 接受 torchScript 输入,优化后输出 ts 模型,所以下文将从 pytorch\ptq\qat 三个方向测试 Torch-TensorRT
为了评估量化水平,我们定义一个评估函数
1 | # Helper function to benchmark the model |
base->TorchScript->Torch_tensorRT
基于原始的 pth,编译为 torchscript,然后再使用 Torch_tensorRT 优化
首先导入 pth 模型
1 | import torch |
其次,导出为 torchscript
1 | # Exporting to TorchScript |
最后使用 Torch_tensorRT 优化
1 | #Loading the Torchscript model and compiling it into a TensorRT model |
base->ptq->TorchScript->Torch_tensorRT
首先导入 pth 模型,并使用 pytorch_quantization 进行量化
1 | quant_modules.initialize() |
其次,导出为 torchscript
1 | quant_nn.TensorQuantizer.use_fb_fake_quant = True |
最后使用 Torch_tensorRT 优化
1 | #Loading the Torchscript model and compiling it into a TensorRT model |
ptq->qat->TorchScript->Torch_tensorRT
首先使用 qat 优化模型
1 | def train(model, dataloader, crit, opt): |
其次,导出为 torchscript
1 | quant_nn.TensorQuantizer.use_fb_fake_quant = True |
最后使用 Torch_tensorRT 优化
1 | #Loading the Torchscript model and compiling it into a TensorRT model |
耗时汇总
总结以上 3 个流程的耗时如下
实验 | jit 结果情况 | jit 耗时 | Torch_TensorRT 结果 | Torch_TensorRT 耗时 |
---|---|---|---|---|
base | 正确 | 81.43 | 正确 | |
ptq | 正确 | 94.3 | 正确 | |
qat | 正确 | 94.5 | ||