tensorrt指定使用显卡

在使用 TensorRT 进行模型推理时,确保使用 GPU 并指定具体的 GPU 设备可以通过以下步骤实现:

1. 确保 TensorRT 使用 GPU

TensorRT 会默认使用 能用的GPU 进行推理,只要你的环境中有可用的 GPU 并且你正确安装了 CUDA 和 cuDNN。用下面代码可以验证是否有gpu可用。

import tensorrt as trt

# 检查是否有可用的 GPU
def check_available_gpus():
    import pycuda.driver as cuda
    cuda.init()
    gpu_count = cuda.Device.count()
    print(f"Available GPUs: {gpu_count}")
    for i in range(gpu_count):
        gpu = cuda.Device(i)
        print(f"GPU {i}: {gpu.name()}")

check_available_gpus()

2. 设置 CUDA 环境变量

你可以通过设置 CUDA_VISIBLE_DEVICES 环境变量来指定 TensorRT 使用哪个 GPU。例如:

export CUDA_VISIBLE_DEVICES=0  # 使用第0块GPU

或者在你的 Python 代码中:

import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'  # 使用第0块GPU

3.使用cudart来指定显卡

from cuda import cudart
#确保在 TensorRT 运行时设置 CUDA 设备
cudart.cudaSetDevice(0)

注意

如果不通过上面方式指定显卡,tensorrt会默认使用能用的显卡,如果指定了则使用指定的显卡

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TensorRT是英伟达(NVIDIA)专门为深度学习模型推理(inference)而开发的高性能推理引擎。TensorRT可以优化和加速深度学习推理,并提供支持各种深度学习框架的API,例如 TensorFlow,PyTorch,Caffe 等等。 使用TensorRT进行推理可以大幅度提高推理速度,因为它采用了多项技术优化,包括半精度计算(half precision),kernel融合(kernel fusion),动态tensor缓冲区等等。 TensorRT使用流程一般如下: 1. 用深度学习框架训练好模型,如TensorFlow、PyTorch等等。 2. 导出训练好的模型为ONNX或UFF格式。 3. 用TensorRT API读取ONNX或UFF格式的模型,创建推理引擎。 4. 将待推理的数据输入到引擎中,进行推理计算。 5. 获取结果并输出。 以下是一个简单的使用TensorRT API进行推理的示例代码: ```python import tensorrt as trt # Load the serialized TensorRT model from disk. with open('model.engine', 'rb') as f: engine_data = f.read() # Create a TensorRT engine from the serialized data. trt_runtime = trt.Logger(trt.Logger.WARNING) engine = trt_runtime.deserialize_cuda_engine(engine_data) # Allocate memory for input and output tensors. input_shape = (1, 3, 224, 224) output_shape = (1, 1000) input_tensor = cuda.mem_alloc(np.prod(input_shape) * np.dtype(np.float32).itemsize) output_tensor = cuda.mem_alloc(np.prod(output_shape) * np.dtype(np.float32).itemsize) # Create a CUDA stream for the engine to execute on. stream = cuda.Stream() # Create a bindings object that maps the input and output tensors to memory. bindings = [int(input_tensor), int(output_tensor)] # Create a Python context object that can execute the engine. context = engine.create_execution_context() # Perform inference on a batch of data. input_data = np.random.rand(*input_shape).astype(np.float32) cuda.memcpy_htod_async(input_tensor, input_data, stream) context.execute_async_v2(bindings=bindings, stream_handle=stream.handle) cuda.memcpy_dtoh_async(output_data, output_tensor, stream) stream.synchronize() # Print the inference result. print(output_data) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值