TensorRT 如何关联 cuda 流和 Tensorrt 上下文?
如前所述,您不必这样做。但是,如果您希望使用 CUDA 流来执行此操作,则关联是您可以将相同的 CUDA 流作为参数传递给所有函数调用。以下 c++ 代码将说明这一点:
void infer(std::vector<void*>& deviceMemory, void* hostInputMemory, size_t hostInputMemorySizeBytes, cudaStream_t& cudaStream)
{
auto success = cudaMemcpyAsync(deviceMemory, hostInputMemory, hostInputMemorySizeBytes, cudaMemcpyHostToDevice, cudaStream)
if (not success) {... handle errors...}
if (not executionContext.enqueueV2(static_cast<void**>(deviceMemory.data()), cudaStream, nullptr)
{ ... handle errors...}
void* outputHostMemory; // allocate size for all bindings
size_t outputMemorySizeBytes;
auto success2 = cudaMemcpyAsync(&outputHostMemory, &deviceMemory.at(0), outputMemorySizeBytes, cudaMemcpyDeviceToHost, cudaStream);
if (not success2) {... error handling ...}
cudaStream.waitForCompletion();
}
如果您想要 C++ 中的完整工作示例,您可以查看 this 存储库。我上面的代码只是一个例子。
我们可以在一个 Tensorrt 上下文中使用多个流吗?
如果我正确理解了您的问题,根据this 文档,答案是否定的。
在多线程 C++ 应用程序中,每个线程使用一个模型进行推理,一个模型可能在多个线程中加载;那么,在一个线程中,我们只需要 1 个引擎、1 个上下文和 1 个流还是多个流?
one model might be loaded in more than 1 thread
这听起来不对。
引擎 (nvinfer1::ICudaEngine) 是从 TensorRT 引擎文件创建的。引擎创建用于推理的执行上下文。
This TensorRT 开发人员指南的一部分说明了哪些操作是线程安全的。其余的可以被认为是非线程安全的。