vpr: VprEncoder TensorRT (chi Jetson, -DVSLAM_WITH_TENSORRT=ON) + vslam_vpr_check + tools/vpr_export_onnx.py

This commit is contained in:
trung09122002
2026-09-30 14:50:47 +07:00
parent cccc048eaf
commit 1552ec2636
9 changed files with 510 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
#include "vslam/vpr_encoder.h"
#include <opencv2/imgproc.hpp>
namespace vslam {
void VprPreprocess(const cv::Mat& gray, const VprConfig& cfg, std::vector<float>* chw) {
static const float kMean[3] = {0.485f, 0.456f, 0.406f};
static const float kStd[3] = {0.229f, 0.224f, 0.225f};
cv::Mat g = gray;
if (g.channels() == 3) cv::cvtColor(gray, g, cv::COLOR_BGR2GRAY);
cv::Mat eq, rs;
cv::createCLAHE(cfg.clahe_clip, cv::Size(cfg.clahe_grid, cfg.clahe_grid))->apply(g, eq);
cv::resize(eq, rs, cv::Size(cfg.width, cfg.height), 0, 0, cv::INTER_LINEAR);
const size_t plane = static_cast<size_t>(cfg.width) * static_cast<size_t>(cfg.height);
chw->resize(3 * plane);
for (int c = 0; c < 3; ++c) {
float* dst = chw->data() + c * plane;
for (int y = 0; y < cfg.height; ++y) {
const uint8_t* src = rs.ptr<uint8_t>(y);
for (int x = 0; x < cfg.width; ++x) {
dst[static_cast<size_t>(y) * cfg.width + x] = (src[x] / 255.0f - kMean[c]) / kStd[c];
}
}
}
}
#ifndef VSLAM_HAVE_TENSORRT
StatusResponse CreateVprEncoder(const VprConfig&, std::unique_ptr<VprEncoder>* out) {
out->reset();
return StatusResponse::Error(StatusCode::kUnavailable,
"VPR can build voi -DVSLAM_WITH_TENSORRT=ON (chi Jetson)");
}
#endif
} // namespace vslam

View File

@@ -0,0 +1,150 @@
// CHI bien dich voi -DVSLAM_WITH_TENSORRT=ON (xem CMakeLists.txt).
#include "vslam/vpr_encoder.h"
#include <NvInfer.h>
#include <cuda_runtime_api.h>
#include <cmath>
#include <fstream>
#include <iterator>
#include <mutex>
#include "vslam/log.h"
namespace vslam {
namespace {
class TrtLogger : public nvinfer1::ILogger {
public:
void log(Severity s, const char* msg) noexcept override {
if (s <= Severity::kWARNING) VSLAM_WARN("tensorrt: " << msg);
}
};
// IRuntime giu tham chieu toi logger suot doi -> logger tinh.
TrtLogger& Logger() {
static TrtLogger l;
return l;
}
size_t Volume(const nvinfer1::Dims& d) {
size_t v = 1;
for (int i = 0; i < d.nbDims; ++i) v *= static_cast<size_t>(d.d[i]);
return v;
}
class TrtVprEncoder : public VprEncoder {
public:
~TrtVprEncoder() override {
if (d_in_ != nullptr) cudaFree(d_in_);
if (d_out_ != nullptr) cudaFree(d_out_);
if (stream_ != nullptr) cudaStreamDestroy(stream_);
// ctx_ -> engine_ -> runtime_ huy theo thu tu nguoc khai bao: dung thu tu TensorRT can.
}
StatusResponse Init(const VprConfig& cfg) {
cfg_ = cfg;
std::ifstream f(cfg.engine_path, std::ios::binary);
if (!f) {
return StatusResponse::Error(StatusCode::kNotFound,
"vpr: khong mo duoc engine " + cfg.engine_path +
" -- dung bang trtexec (xem vpr_encoder.h)");
}
const std::vector<char> blob((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
runtime_.reset(nvinfer1::createInferRuntime(Logger()));
if (!runtime_) return Err("createInferRuntime");
engine_.reset(runtime_->deserializeCudaEngine(blob.data(), blob.size()));
if (!engine_) return Err("deserializeCudaEngine -- engine dung cho may/TensorRT khac?");
ctx_.reset(engine_->createExecutionContext());
if (!ctx_) return Err("createExecutionContext");
for (int i = 0; i < engine_->getNbIOTensors(); ++i) {
const char* name = engine_->getIOTensorName(i);
if (engine_->getTensorDataType(name) != nvinfer1::DataType::kFLOAT) {
return Err(std::string("tensor ") + name + " khong phai float32");
}
const size_t n = Volume(engine_->getTensorShape(name));
if (engine_->getTensorIOMode(name) == nvinfer1::TensorIOMode::kINPUT) {
in_name_ = name;
in_elems_ = n;
} else {
out_name_ = name;
out_elems_ = n;
}
}
const size_t want = 3u * static_cast<size_t>(cfg.width) * static_cast<size_t>(cfg.height);
if (in_name_.empty() || out_name_.empty() || in_elems_ != want) {
return Err("engine co dau vao " + std::to_string(in_elems_) + " so, can " +
std::to_string(want) + " (3x" + std::to_string(cfg.height) + "x" +
std::to_string(cfg.width) + ")");
}
if (cudaStreamCreate(&stream_) != cudaSuccess ||
cudaMalloc(&d_in_, in_elems_ * sizeof(float)) != cudaSuccess ||
cudaMalloc(&d_out_, out_elems_ * sizeof(float)) != cudaSuccess) {
return Err("cap phat bo nho GPU");
}
if (!ctx_->setTensorAddress(in_name_.c_str(), d_in_) ||
!ctx_->setTensorAddress(out_name_.c_str(), d_out_)) {
return Err("setTensorAddress");
}
VSLAM_INFO("vpr: TensorRT engine " << cfg.engine_path << " -- vao " << in_name_ << " ("
<< in_elems_ << " so), ra " << out_name_ << " (" << out_elems_ << " chieu)");
return StatusResponse::Ok();
}
StatusResponse Describe(const cv::Mat& gray, std::vector<float>* desc) override {
if (gray.empty()) return StatusResponse::Error(StatusCode::kInvalidArgument, "vpr: anh rong");
std::lock_guard<std::mutex> lk(mu_);
VprPreprocess(gray, cfg_, &host_in_);
desc->resize(out_elems_);
if (cudaMemcpyAsync(d_in_, host_in_.data(), in_elems_ * sizeof(float),
cudaMemcpyHostToDevice, stream_) != cudaSuccess ||
!ctx_->enqueueV3(stream_) ||
cudaMemcpyAsync(desc->data(), d_out_, out_elems_ * sizeof(float),
cudaMemcpyDeviceToHost, stream_) != cudaSuccess ||
cudaStreamSynchronize(stream_) != cudaSuccess) {
return StatusResponse::Error(StatusCode::kInternal, "vpr: suy luan TensorRT loi");
}
// Mo hinh da L2 o lop cuoi, nhung fp16 lam lech chuan chut it -> chuan hoa lai.
double n2 = 0.0;
for (float v : *desc) n2 += static_cast<double>(v) * v;
const float inv = n2 > 0.0 ? static_cast<float>(1.0 / std::sqrt(n2)) : 0.0f;
for (float& v : *desc) v *= inv;
return StatusResponse::Ok();
}
int dim() const override { return static_cast<int>(out_elems_); }
private:
static StatusResponse Err(const std::string& m) {
return StatusResponse::Error(StatusCode::kInternal, "vpr: " + m);
}
VprConfig cfg_;
std::unique_ptr<nvinfer1::IRuntime> runtime_;
std::unique_ptr<nvinfer1::ICudaEngine> engine_;
std::unique_ptr<nvinfer1::IExecutionContext> ctx_;
std::string in_name_, out_name_;
size_t in_elems_ = 0, out_elems_ = 0;
void* d_in_ = nullptr;
void* d_out_ = nullptr;
cudaStream_t stream_ = nullptr;
std::vector<float> host_in_;
std::mutex mu_;
};
} // namespace
StatusResponse CreateVprEncoder(const VprConfig& cfg, std::unique_ptr<VprEncoder>* out) {
std::unique_ptr<TrtVprEncoder> e(new TrtVprEncoder);
const StatusResponse st = e->Init(cfg);
if (!st.ok()) {
out->reset();
return st;
}
*out = std::move(e);
return StatusResponse::Ok();
}
} // namespace vslam