// iterate by batches
for (size_t imgNum = 0; imgNum < images.size(); ++imgNum)
{
//masks has only 1 channel. To paint the input image, we need a mask with 3 channels
cv::Mat masksTemp = cv::Mat::zeros(masks[imgNum].size(), CV_8UC3);
//set classes to different colors
for (int i = 0; i < numClasses_; ++i)
{
masksTemp.setTo(colors_[i % numClasses_], masks[imgNum] == i + start_channel_);
}
batchCombined.emplace_back(images[imgNum] + masksTemp);
}
return batchCombined;
const auto explicitBatch = 1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH); //we process only one image at a time
nvinfer1::INetworkDefinition *network{builder->createNetworkV2(explicitBatch)};
nvonnxparser::IParser *parser{nvonnxparser::createParser(*network, gLogger_)};
nvinfer1::IBuilderConfig *config{builder->createBuilderConfig()};
//parse ONNX
if (!parser->parseFromFile(modelPath_.c_str(), static_cast<int>(nvinfer1::ILogger::Severity::kINFO)))
{
std::cerr << "ERROR: could not parse the model.\n";
return false;
}
//remove auxilary outputs used only in the training phase
while (network->getNbOutputs() > 1)
{
network->unmarkOutput(*(network->getOutput(1)));
}
// allow TensorRT to use up to 1GB of GPU memory for tactic selection.
config->setMemoryPoolLimit(nvinfer1::MemoryPoolType::kWORKSPACE, 1ULL << 30);
//calibrator needed if int8 is used
nvinfer1::IInt8Calibrator *calibrator;
//fp16 or int8 mode
if (params_.get<std::string>("precision") == "fp16")
{
if (builder->platformHasFastFp16())
{
config->setFlag(nvinfer1::BuilderFlag::kFP16);
}
else
{
std::cerr << "ERROR: your platform does not support fp16. Use fp32 or int8.\n";
return false;
}
}
else if (params_.get<std::string>("precision") == "int8")
{
config->setAvgTimingIterations(1);
config->setFlag(nvinfer1::BuilderFlag::kINT8);
calibrator = new Int8EntropyCalibrator(params_.get<std::string>("calib_images"), tablePath_, h_ * w_ * 3, h_, w_, coef_, mean_, std_);
config->setInt8Calibrator(calibrator);
}
//else fp32 (default precision) is used
std::cout << "building new engine: " << enginePath_ << " ..." << std::endl;
// generate TensorRT engine optimized for the target platform
nvinfer1::IHostMemory *serializedModel = builder->buildSerializedNetwork(*network, *config);
if (!serializedModel)
{
std::cerr << "Serialized engine build failed." << std::endl;
return false;
}
//serialize and save the engine
std::ofstream engineFile(enginePath_, std::ios::binary);
if (!engineFile)
{
std::cerr << "Cannot open engine file: " << enginePath_ << std::endl;
return false;
}
engineFile.write(static_cast<char*>(serializedModel->data()), serializedModel->size());
engineFile.close();
engine_ = std::shared_ptr<nvinfer1::ICudaEngine>(runtime_->deserializeCudaEngine(serializedModel->data(), serializedModel->size()));
if (!engine_)
{
std::cerr << "Unable to build cuda engine." << std::endl;
return false;
}
delete parser;
delete network;
delete config;
delete builder;
delete serializedModel;
return true;
}
void Segmentator::streamAlloc(int n_streams)
{
if (stream_ != nullptr)
{
// if previously allocated, free it to avoid memory leaks
delete stream_;
}
// Allocate and initialize an array of stream handles
stream_ = new cudaStream_t[n_streams * sizeof(cudaStream_t)];
}
Segmentator::~Segmentator()
{
if (stream_ != nullptr)
{
delete[] stream_;
stream_ = nullptr;
}
memoryFree();
//destroy context and engine
if (context_)
{
delete context_;
context_ = nullptr;
}
engine_.reset();
}
" and " //tensorrt engine, context, logger
cudaStream_t *stream_;
std::shared_ptrnvinfer1::ICudaEngine engine_{nullptr}; //The TensorRT engine used to run the network
nvinfer1::IExecutionContext *context_;
nvinfer1::IRuntime *runtime_;
LoggerTrt gLogger_;
"
Your code is generally well-structured, but I noticed some issues and potential improvements, especially concerning CUDA stream allocation and cleanup, memory handling, and TensorRT best practices. Below are detailed points and corrections:
1. CUDA Stream Allocation (streamAlloc)
cpp
void Segmentator::streamAlloc(int n_streams)
{
if (stream_ != nullptr)
{
// if previously allocated, free it to avoid memory leaks
delete stream_;
}
// Allocate and initialize an array of stream handles
stream_ = new cudaStream_t[n_streams * sizeof(cudaStream_t)];
}
Issues:
You use delete instead of delete[] for stream_, which is allocated as an array.
The allocation size is incorrect. new cudaStream_t[n_streams * sizeof(cudaStream_t)] is wrong because new[] already allocates that many elements, no need to multiply by sizeof.
No initialization of streams (the actual CUDA streams need to be created with cudaStreamCreate).
You create streams inside the process() function, so it's unclear what the ownership and lifecycle of streams is.
Corrections:
Use delete[] stream_; to delete array memory properly.
Allocate the array as stream_ = new cudaStream_t[n_streams];
Create streams once (during streamAlloc) using cudaStreamCreate instead of repeatedly creating and destroying in process().
Later, destroy streams during destruction to avoid leaks.
Improved streamAlloc version:
cpp
void Segmentator::streamAlloc(int n_streams)
{
if (stream_ != nullptr)
{
for (int i = 0; i < n_streams; i++)
{
cudaStreamDestroy(stream_[i]);
}
delete[] stream_;
stream_ = nullptr;
}
stream_ = new cudaStream_t[n_streams];
for (int i = 0; i < n_streams; i++)
{
cudaStreamCreate(&stream_[i]);
}
}
Then, in your destructor, destroy and delete[] the streams.
You might consider using smart pointers to prevent leaks on exceptions, but this is not critical.
7. Other Notes
step() function currently just returns the input k; is that intended?
The code uses some classes and functions from your codebase (nutils, LoggerTrt, etc.), ensure those are well defined.
The thread-safety and concurrency of your process() function depends on your CUDA stream handling; fixing streams allocation and usage is critical.
Summary of Key Fixes to Apply:
Fix streamAlloc:
cpp
void Segmentator::streamAlloc(int n_streams)
{
if (stream_ != nullptr)
{
for (int i = 0; i < n_streams; i++)
{
cudaStreamDestroy(stream_[i]);
}
delete[] stream_;
stream_ = nullptr;
}
stream_ = new cudaStream_t[n_streams];
for (int i = 0; i < n_streams; i++)
{
cudaStreamCreate(&stream_[i]);
}
}
Remove stream creation/destruction inside process(). Instead, just use:
cpp
// Inside your for loop
// No cudaStreamCreate/cudaStreamDestroy calls
NV_CUDA_CHECK(cudaMemcpyAsync(inputGpu_, inputCpu_, h_ * w_ * 3 * sizeof(unsigned char), cudaMemcpyHostToDevice, stream_[imgNum]));
// Use stream_[imgNum] for enqueue, synchronize, etc.
if (!context_->enqueueV3(stream_[imgNum]))
{
std::cerr << "Error async enqueue inference." << std::endl;
}
NV_CUDA_CHECK(cudaStreamSynchronize(stream_[imgNum]));
Fix creation of cv::Mat with proper type:
cpp
cv::Mat masks(h_, w_, CV_8UC1, outputMaskCpu_);
Destroy streams during destruction:
cpp
Segmentator::~Segmentator()
{
if (stream_ != nullptr)
{
// Assuming you know number of streams, otherwise store it in a member variable
for (int i = 0; i < n_streams_; i++)
{
cudaStreamDestroy(stream_[i]);
}
delete[] stream_;
stream_ = nullptr;
}
memoryFree();
if (context_)
{
delete context_;
context_ = nullptr;
}
engine_.reset();
}
You'll likely need to store n_streams_ in your class to track the number of streams allocated.
If you want, I can also help refactor other parts or do specific improvements. But the above fixes address the main issues in your posted code.