问题描述
在不涉及多线程时,使用TensorRT模型推理,如下在开头import即可自动创建上下文:
import pycuda.driver as cuda
import pycuda.autoinit
而当TensorRT在线程中运行时(比如写在软件中、或者通过多个线程使模型并行推理),代码会报错:
pycuda._driver.LogicError: explicit_context_dependent failed: invalid device context - no currently active context?
报错显示在工作线程中没有建立上下文context,原因是import pycuda.autoinit
在线程中不起作用。
解决办法
在TensorRT的工作线程中手动创建context上下文即可:
(1)删掉import pycuda.autoinit
,添加cuda.init()
:
(2)在调用TensorRT的类的__init__()的首行加入下面语句:
# 1. 手动创建context上下文
self.cfx = cuda.Devvice(0).make_context()
# 2. 模型预加载[可选]
# 3. 执行self.cfx.pop(),否则会报错
self.cfx.pop()
(3)在进行推理前加上self.cfx.push()
,推理结束后加上self.cfx.pop()
: