pytorch: cpu,cuda,tensorRt 推理对比学习

news2024/9/21 17:31:19

0:先看结果

针对resnet模型对图片做处理

原图结果

分别使用cpu,cuda,TensorRt做推理,所需要的时间对比

方法时间
cpu13s594ms
cuda711ms
tensorRt

113ms

项目地址:

GitHub - july1992/Pytorch-vily-study: vily 学习pytorch,机器学习,推理加速~

模型地址:

cpu+cuda:

Deeplabv3 | PyTorch

tensorRt:  因为需要数onnx模型文件,所以使用nvida官方的resnet onnx

Quick Start Guide :: NVIDIA Deep Learning TensorRT Documentation

wget https://download.onnxruntime.ai/onnx/models/resnet50.tar.gz

 一:学习历程

因为需要gpu,所以在xxxx宝上买一个带gpu的ubuntu服务器,20.x版本之上(gpu :3060 12g)

1.1 查看服务器的gpu版本

nvidia-smi

1.2: 在linux上安装cuda版本的pytorch,  可选历史版本安装

1.3:  当前安装版本:

Python 3.11.5

cuda_11.7

PyTorch 2.3.0

CUDA available with version: 11.8

cuDNN version: 870

tensor: 10.2.0

1.4:  这里使用resnet50 测试

模型地址;Deeplabv3 | PyTorch

1.5 分析代码:

 import torch

model = torch.hub.load('pytorch/vision:v0.10.0', 'deeplabv3_resnet50', pretrained=True)

model.eval()

这里会将模型下载到/home/wuyou/.cache/torch/hub/  目录下,如果下载失败,可以手动下载,在放入相关位置,要记得改名字

2: cpu和cuda运行对比

2.1 cpu和cuda的代码

import torch
from datetime import datetime

now = datetime.now()
print('0--',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])



model = torch.hub.load('pytorch/vision:v0.10.0', 'deeplabv3_resnet50', pretrained=True)
# or any of these variants
# model = torch.hub.load('pytorch/vision:v0.10.0', 'deeplabv3_resnet101', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.10.0', 'd\eeplabv3_mobilenet_v3_large', pretrained=True)
model.eval()

# print('model:',model)

now = datetime.now()
print('1--',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

# sample execution (requires torchvision)


from PIL import Image
from torchvision import transforms
input_image = Image.open('img/dog.jpg')
input_image = input_image.convert("RGB")

# 定义图像转换(这应该与训练模型时使用的转换相匹配)
preprocess = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

input_tensor = preprocess(input_image)

# 对图像进行转换
input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model


now = datetime.now()
print('2--前',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])


# move the input and model to GPU for speed if available
if torch.cuda.is_available():
    print('走进cuda了')
    input_batch = input_batch.to('cuda')
    model.to('cuda')
# 使用模型进行预测
with torch.no_grad():
    print('走进no_grad了')
    output = model(input_batch)['out'][0]
output_predictions = output.argmax(0)

now = datetime.now()
print('2--后',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])


print(output_predictions[0])

# import numpy as np
# # 使用 np.ndarray
# ## 将预测结果转换为numpy数组
palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
colors = torch.as_tensor([i for i in range(21)])[:, None] * palette
colors = (colors % 255).numpy().astype("uint8")

# # plot the semantic segmentation predictions of 21 classes in each color
r = Image.fromarray(output_predictions.byte().cpu().numpy()).resize(input_image.size)
r.putpalette(colors)

# now = datetime.now()
# print('3--',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

r.save('img1.png')

 

# import matplotlib.pyplot as plt
# plt.imshow(r)
# plt.show()

# input("Press Enter to close...")

 
 

2.2  使用cpu的时候,下面这段代码要隐藏

if torch.cuda.is_available():
    print('走进cuda了')
    input_batch = input_batch.to('cuda')
    model.to('cuda')

2.3 分别执行得到结果

cpu

13s594ms

cuda

711ms

19倍

2: 使用tensor

使用tensor RT的理由, 它可以加速模型推理,榨干你的G PU使用率,官方声称可以提高4-6倍速度。

2.1 安装好tensor环境,查看上一篇文章

Tensor安装和测试-CSDN博客

2.2 下载一个onnx的模型,至于为什么要使用onnx,可以去b站看

Quick Start Guide :: NVIDIA Deep Learning TensorRT Documentation

解压后,进入文件夹得到 model.onnx

2.3 将上面model.onnx 转换成引擎

trtexec --onnx=resnet50/model.onnx --saveEngine=resnet_engine.trt

这里遇到一些bug,放在本文BUG章节描述

2.4  部署模型

参考官方例子


创建py 
import numpy as np
  
PRECISION = np.float32

from onnx_helper import ONNXClassifierWrapper


BATCH_SIZE=32

N_CLASSES = 1000 # Our ResNet-50 is trained on a 1000 class ImageNet task
trt_model = ONNXClassifierWrapper("resnet_engine.trt", [BATCH_SIZE, N_CLASSES], target_dtype = PRECISION)


dummy_input_batch = np.zeros((BATCH_SIZE, 224, 224, 3), dtype = PRECISION)
predictions = trt_model.predict(dummy_input_batch)


print('结果:',predictions[0])

这里报错找不到onnx_help ,等等一些bug,放在本文bug章节。

 2.5 运行结果:

2.6 修改demo,引入图片,

import numpy as np

import torch

PRECISION = np.float32

from onnx_helper import ONNXClassifierWrapper

from datetime import datetime

BATCH_SIZE=32

N_CLASSES = 1000 # Our ResNet-50 is trained on a 1000 class ImageNet task



# 获取当前时间
now = datetime.now()
 
# 格式化输出当前时间,包括毫秒
print('1--',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

trt_model = ONNXClassifierWrapper("resnet_engine.trt", [BATCH_SIZE, N_CLASSES], target_dtype = PRECISION)


# dummy_input_batch = np.zeros((BATCH_SIZE, 224, 224, 3), dtype = PRECISION)
from PIL import Image
from torchvision import transforms
input_image = Image.open('dog.jpg')
input_image = input_image.convert("RGB")
preprocess = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
# print(dummy_input_batch[0])


now = datetime.now()

# 格式化输出当前时间,包括毫秒
print('2--前',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

dummy_input_batch=input_batch.numpy()
predictions = trt_model.predict(dummy_input_batch)


now = datetime.now()

# 格式化输出当前时间,包括毫秒
print('3--后',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

#print('结果:',predictions[0])

output_predictions = predictions


import numpy as np

# plot the semantic segmentation predictions of 21 classes in each color
r = Image.fromarray(output_predictions,'L').resize(input_image.size)


# 获取当前时间
now = datetime.now()

# 格式化输出当前时间,包括毫秒
#print('4--',now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

r.save('img1.png')



2.7。结果 , 113ms

三 bugs

3.1 执行trtexec --onnx=resnet50/model.onnx --saveEngine=resnet_engine.trt 报错

TensorTR trtexec:未找到命令

解决:

解决: 在~/.bashrc下添加新环境变量

export LD_LIBRARY_PATH=/vily/TensorRT-10.2.0.19/lib:$LD_LIBRARY_PATH

export PATH=/vily/TensorRT-10.2.0.19/bin:$PATH

3.2 Onnx 已经下载了,还提示 没有onnx-help

or

No matching distribution found for onnx_helper

解决:

找到官方的onyx-help

TensorRT/quickstart/IntroNotebooks/onnx_helper.py at release/10.0 · NVIDIA/TensorRT · GitHub

将文件下载下来,放在当前目录下

3.3。执行报错 找不到v2

解决:

找到代码 将

self.context.execute_async_v2(self.bindings, self.stream.handle, None)

改成

self.context.execute_async_v3( self.stream.handle)

3.4  报错

or

解决onnx_help: Pytorch-vily-study/onxx/onnx_helper.py at base-platform · july1992/Pytorch-vily-study · GitHub

#
# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import numpy as np
#import tensorflow as tf
import tensorrt as trt

import pycuda.driver as cuda
import pycuda.autoinit

# For ONNX:

class ONNXClassifierWrapper():
    def __init__(self, file, num_classes, target_dtype = np.float32):
        
        self.target_dtype = target_dtype
        self.num_classes = num_classes
        self.load(file)
        
        self.stream = None
      
    def load(self, file):
        f = open(file, "rb")
        runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING)) 

        # 修改了这里
        self.engine = runtime.deserialize_cuda_engine(f.read())
        self.context = self.engine.create_execution_context()
    
    def allocate_memory(self, batch):
        self.output = np.empty(self.num_classes, dtype = self.target_dtype) # Need to set both input and output precisions to FP16 to fully enable FP16

        # Allocate device memory
        self.d_input = cuda.mem_alloc(1 * batch.nbytes)
        self.d_output = cuda.mem_alloc(1 * self.output.nbytes)

        self.bindings = [int(self.d_input), int(self.d_output)]

        self.stream = cuda.Stream()
        
    def predict(self, batch): # result gets copied into output
        if self.stream is None:
            self.allocate_memory(batch)
        print('1--')
        # Transfer input data to device
        cuda.memcpy_htod_async(self.d_input, batch, self.stream)
        # Execute model
        print('2--')
        
        # 这里修改了
        self.context.set_tensor_address(self.engine.get_tensor_name(0), int(self.d_input))
        self.context.set_tensor_address(self.engine.get_tensor_name(1), int(self.d_output))
        # 这里也修改了
        self.context.execute_async_v3(self.stream.handle)
        # Transfer predictions back
        print('3--')
        cuda.memcpy_dtoh_async(self.output, self.d_output, self.stream)
        # Syncronize threads
        print('4--')
        self.stream.synchronize()
        
        return self.output

def convert_onnx_to_engine(onnx_filename, engine_filename = None, max_batch_size = 32, max_workspace_size = 1 << 30, fp16_mode = True):
    logger = trt.Logger(trt.Logger.WARNING)
    with trt.Builder(logger) as builder, builder.create_network() as network, trt.OnnxParser(network, logger) as parser:
        builder.max_workspace_size = max_workspace_size
        builder.fp16_mode = fp16_mode
        builder.max_batch_size = max_batch_size

        print("Parsing ONNX file.")
        with open(onnx_filename, 'rb') as model:
            if not parser.parse(model.read()):
                for error in range(parser.num_errors):
                    print(parser.get_error(error))

        print("Building TensorRT engine. This may take a few minutes.")
        engine = builder.build_cuda_engine(network)

        if engine_filename:
            with open(engine_filename, 'wb') as f:
                f.write(engine.serialize())

        return engine, logger

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1972607.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

KubeVirt虚拟机存储及网络卸载加速解决方案

1. 方案背景 1.1. KubeVirt介绍 随着云计算和容器技术的飞速发展&#xff0c;Kubernetes已成为业界公认的容器编排标准&#xff0c;为用户提供了强大、灵活且可扩展的平台来部署和管理各类应用。然而&#xff0c;在企业的实际应用中&#xff0c;仍有许多传统应用或遗留系统难…

电脑缺少directx怎么办?电脑dll修复详细教程!7种方法!

DLL&#xff08;动态链接库&#xff09;文件是Windows操作系统中非常重要的组成部分&#xff0c;它们包含了程序运行所需的代码和数据。然而&#xff0c;由于各种原因&#xff0c;如系统更新、软件卸载不当或病毒感染&#xff0c;DLL文件有时会丢失或损坏&#xff0c;导致程序无…

day18 Java流程控制——Scanner进阶使用

day18 Java流程控制——Scanner进阶使用 本章目录 day18 Java流程控制——Scanner进阶使用1. 什么是Scanner&#xff1f;2. Scanner进阶使用&#xff08;实例&#xff09;2.1 整数&小数的输入输出2.2 我们可以输入多个数字&#xff0c;并求其总和与平均数&#xff0c;每输入…

96年高中程序员年收入30万

互联网创业交流群&#xff0c;从昨天晚上8.1建军节开始建群&#xff0c;到今天中午已经突破200人了。 这里面有我的朋友&#xff0c;也有马总的朋友&#xff0c;当然不管是谁的朋友&#xff0c;进来了大家都是一家人。 以后在不违反原则的情况下&#xff0c;希望大家能和谐相…

建筑业数据挖掘:Scala爬虫在大数据分析中的作用

数据的挖掘和分析对于市场趋势预测、资源配置优化、风险管理等方面具有重要意义&#xff0c;特别是在建筑业这一传统行业中。Scala&#xff0c;作为一种强大的多范式编程语言&#xff0c;提供了丰富的库和框架&#xff0c;使其成为开发高效爬虫的理想选择。本文将探讨Scala爬虫…

《Cloud Native Data Center Networking》(云原生数据中心网络设计)读书笔记 -- 03 云原生网络操作系统

本章要回答的问题&#xff1a; 云原生网络操作系统的主要需求是什么?什么是 OpenFlow 和软件定义网络? 它们适用什么样的场景?网络解耦中网络操作系统有哪些可能的选择?这些模型与云原生 NOS 的需求相比是怎样的? 网络设备的新需求 云原生时代中网络设备需要满足以下要求…

揭秘对话式搜索中的广告检测——Detecting Generated Native Ads in Conversational Search

Detecting Generated Native Ads in Conversational Search | Companion Proceedings of the ACM on Web Conference 2024https://dl.acm.org/doi/abs/10.1145/3589335.3651489 1. 概述 大型语言模型(LLMs)已成为构建对话式搜索引擎与检索增强生成系统的主流标准。然而,在大…

python packages是什么意思

package指的就是包&#xff0c;它是一个有层次的文件目录结构&#xff0c;它定义了由n个模块或n个子包组成的python应用程序执行环境。通俗一点&#xff1a;包是一个包含__init__.py 文件的目录&#xff0c;该目录下一定得有这个__init__.py文件和其它模块或子包。 但是这会分…

【传知代码】疯狂交互学习的BM3推荐算法(论文复现)

在当今信息爆炸的时代&#xff0c;我们每天接触的数据量已经超出我们大脑的处理能力。在这个背景下&#xff0c;个性化推荐系统以其独特的能力和智能化的算法引起了广泛关注。其中&#xff0c;基于行为的推荐系统成为了引领潮流的前沿技术之一&#xff0c;本文将深入探讨疯狂交…

未来已来:AI在提升企业客户服务质量与效率中的应用

随着人工智能&#xff08;AI&#xff09;技术的飞速发展&#xff0c;其在企业客户服务领域的应用正以前所未有的速度改变着我们的服务模式。AI技术的引入&#xff0c;不仅极大地提升了客户服务的效率&#xff0c;还显著提高了客户满意度&#xff0c;为企业创造了新的竞争优势。…

【kubernetes】kubeadm部署k8s集群

1、环境准备 master01: 192.168.10.25master02: 192.168.10.26master03: 192.168.10.27node01: 192.168.10.28node02: 192.168.10.29负载均衡器1&#xff1a;192.168.10.30负载均衡器2&#xff1a;192.168.10.31 //所有节点&#xff0c;关闭防火墙规则&#xff0c;关闭selinu…

秋招突击——算法训练——8/1——用友集团笔试

文章目录 引言正文小友的生产线个人实现参考实现 小友策划游戏人物个人实现参考实现 最佳工作任务安排个人实现参考实现 大众评分最高的一次旅程 总结 引言 今天晚上七点钟到九点钟是用友集团的笔试&#xff0c;作为今天算法练习的主要内容&#xff01;具体怎么样&#xff0c;…

MinIO DataPod:百亿亿次级计算的参考架构

现代企业通过其数据来定义自己。这需要用于 AI/ML 的数据基础设施&#xff0c;以及作为现代数据湖基础的数据基础设施&#xff0c;该数据基础设施能够支持商业智能、数据分析和数据科学。如果他们落后、起步或使用 AI 获得高级见解&#xff0c;则情况确实如此。在可预见的未来&…

又一个GPT4级的模型免费了?MiniMax史诗级更新

又有一个超性价比的国产大模型出现了&#xff01;这里是智匠AI&#xff0c;MiniMax刚刚对他们的主力模型abab6.5s&#xff0c;进行了大幅降价&#xff0c;输入和输出成本都达到了1元/百万tokens。我们今天就来进行评测这款abab6.5s。 abab6.5s在文科任务、内容理解、文字生成及…

WebKit引擎:探索现代网页渲染的幕后魔法!

WebKit 是一个开源的浏览器引擎&#xff0c;它负责解析和渲染网页内容&#xff0c;包括HTML、CSS和JavaScript。WebKit的工作流程涵盖了加载资源、解析文档、应用样式、布局渲染树等一系列步骤&#xff0c;最终将网页内容呈现在用户的屏幕上。 WebKit简介 WebKit是一个开源的浏…

Python在气象与海洋中的应用

Python是功能强大、免费、开源&#xff0c;实现面向对象的编程语言&#xff0c;能够在不同操作系统和平台使用&#xff0c;简洁的语法和解释性语言使其成为理想的脚本语言。除了标准库&#xff0c;还有丰富的第三方库&#xff0c;并且能够把用其他语言&#xff08;C/C、Fortran…

Python SyntaxError: unexpected EOF while parsing

Python SyntaxError: unexpected EOF while parsing 在Python编程中&#xff0c;SyntaxError: unexpected EOF while parsing是一个常见的错误&#xff0c;通常发生在Python解释器在源代码中找到意外的文件结尾&#xff08;EOF&#xff0c;即End Of File&#xff09;时。这个错…

大模型LLM关键技术手段

大语言模型&#xff08;LLM&#xff09;是人工智能领域的一个突破性进展&#xff0c;它通过多种技术手段实现对自然语言的理解和生成。用比较通俗的话来列举一些我认为比较关键的技术手段&#xff1a; 深度学习技术&#xff1a;就像我们通过不断学习来掌握知识一样&#xff0c;…

SRM供应商管理系统有哪些实际用处?

随着供应商数量的不断增加&#xff0c;订单处理的复杂性与日俱增&#xff0c;传统的采购模式让订单的生成、跟踪到交货的每一个环节都可能成为潜在的瓶颈。在这样的背景下&#xff0c;SRM供应商管理系统的出现&#xff0c;为采购商提供了一个全面、高效的解决方案。 我想以真实…

白盒测试基础与实践:Python示例及流程图设计

文章目录 前言一、白盒测试是什么&#xff1f;主要特点常用方法优点缺点 二、白盒测试常用技术语句覆盖判定覆盖条件覆盖判定/条件覆盖条件组合覆盖路径覆盖 三、程序流程图设计四、测试用例设计1. 基本路径法2. 语句覆盖3. 判断覆盖4. 条件覆盖5. 判断/条件覆盖6. 条件组合覆盖…