vpr: VprEncoder TensorRT (chi Jetson, -DVSLAM_WITH_TENSORRT=ON) + vslam_vpr_check + tools/vpr_export_onnx.py
This commit is contained in:
@@ -39,6 +39,7 @@ vslam_add_library(vslam_slam
|
||||
occupancy_export.h
|
||||
voxel_export.h
|
||||
global_localizer.h
|
||||
vpr_encoder.h
|
||||
FIND_DEPS
|
||||
vslam_common
|
||||
RTABMap
|
||||
@@ -47,3 +48,28 @@ vslam_add_library(vslam_slam
|
||||
|
||||
target_link_libraries(vslam_slam PUBLIC vslam_common rtabmap::core ${OpenCV_LIBS})
|
||||
target_include_directories(vslam_slam SYSTEM PUBLIC ${OpenCV_INCLUDE_DIRS})
|
||||
|
||||
# VPR bang TensorRT -- CHI Jetson (JetPack 6: TensorRT 10 + CUDA). Giong RealSense/CANopen o
|
||||
# vslam_drivers: GLOB_RECURSE gom het src/ nen phai loai vpr_tensorrt.cc khi tat, neu khong
|
||||
# `#include <NvInfer.h>` lam hong build tren may khong co TensorRT. Tat thi
|
||||
# CreateVprEncoder() (vpr_encoder.cc) tra Unavailable va dinh vi lai chay bang LiDAR.
|
||||
option(VSLAM_WITH_TENSORRT "VPR (EigenPlaces) bang TensorRT -- chi Jetson" OFF)
|
||||
get_target_property(_vslam_slam_srcs vslam_slam SOURCES)
|
||||
list(FILTER _vslam_slam_srcs EXCLUDE REGEX "vpr_tensorrt\\.cc$")
|
||||
set_target_properties(vslam_slam PROPERTIES SOURCES "${_vslam_slam_srcs}")
|
||||
if(VSLAM_WITH_TENSORRT)
|
||||
if(NOT DEFINED CUDAToolkit_ROOT AND EXISTS /usr/local/cuda)
|
||||
set(CUDAToolkit_ROOT /usr/local/cuda)
|
||||
endif()
|
||||
find_package(CUDAToolkit REQUIRED)
|
||||
find_path(TENSORRT_INCLUDE_DIR NvInfer.h PATH_SUFFIXES aarch64-linux-gnu x86_64-linux-gnu)
|
||||
find_library(TENSORRT_NVINFER nvinfer)
|
||||
if(NOT TENSORRT_INCLUDE_DIR OR NOT TENSORRT_NVINFER)
|
||||
message(FATAL_ERROR "VSLAM_WITH_TENSORRT=ON nhung khong thay NvInfer.h / libnvinfer "
|
||||
"(JetPack: goi libnvinfer-dev)")
|
||||
endif()
|
||||
target_sources(vslam_slam PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/vpr_tensorrt.cc)
|
||||
target_include_directories(vslam_slam SYSTEM PRIVATE ${TENSORRT_INCLUDE_DIR})
|
||||
target_link_libraries(vslam_slam PRIVATE ${TENSORRT_NVINFER} CUDA::cudart)
|
||||
target_compile_definitions(vslam_slam PRIVATE VSLAM_HAVE_TENSORRT=1)
|
||||
endif()
|
||||
|
||||
51
libs/vslam_slam/include/vslam/vpr_encoder.h
Normal file
51
libs/vslam_slam/include/vslam/vpr_encoder.h
Normal file
@@ -0,0 +1,51 @@
|
||||
#ifndef VSLAM_VPR_ENCODER_H
|
||||
#define VSLAM_VPR_ENCODER_H
|
||||
|
||||
// Nhan dien NOI CHON bang anh (VPR): anh IR -> mo ta 2048 chieu da chuan hoa L2.
|
||||
// Hai anh chup cung mot cho co tich vo huong (cosine) cao.
|
||||
//
|
||||
// Mo hinh: EigenPlaces ResNet50, xuat ONNX bang tools/vpr_export_onnx.py. Chay bang
|
||||
// TensorRT tren Jetson -- do 2026-09-30 (JetPack 6.1): fp16 6.5 ms/anh, OpenCV CPU
|
||||
// 299 ms/anh. Build khong co -DVSLAM_WITH_TENSORRT=ON thi CreateVprEncoder() tra
|
||||
// Unavailable: dinh vi lai van chay bang LiDAR nhu cu.
|
||||
//
|
||||
// Engine TensorRT (.plan) RIENG tung may + phien ban TensorRT. Dung MOT lan tren may do:
|
||||
// /usr/src/tensorrt/bin/trtexec --onnx=resources/vpr/eigenplaces_r50_2048_384x512.onnx \
|
||||
// --fp16 --saveEngine=resources/vpr/eigenplaces_r50_fp16.plan
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <opencv2/core.hpp>
|
||||
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Tien xu ly PHAI giong tools/vpr_export_onnx.py (noi da do 88-89% top-1 tren anh IR).
|
||||
struct VprConfig {
|
||||
std::string engine_path; // .plan cua TensorRT
|
||||
int width = 512;
|
||||
int height = 384;
|
||||
double clahe_clip = 2.0;
|
||||
int clahe_grid = 8;
|
||||
};
|
||||
|
||||
class VprEncoder {
|
||||
public:
|
||||
virtual ~VprEncoder() = default;
|
||||
// Anh IR xam 8 bit, kich thuoc bat ky -> mo ta dim() so, da chuan hoa L2.
|
||||
virtual StatusResponse Describe(const cv::Mat& gray, std::vector<float>* desc) = 0;
|
||||
virtual int dim() const = 0;
|
||||
};
|
||||
|
||||
StatusResponse CreateVprEncoder(const VprConfig& cfg, std::unique_ptr<VprEncoder>* out);
|
||||
|
||||
// Anh xam -> tensor (3, height, width) float32 hang CHW: CLAHE -> resize INTER_LINEAR ->
|
||||
// /255 -> lap 3 kenh -> chuan hoa ImageNet. Tach rieng de dung/test khong can TensorRT.
|
||||
void VprPreprocess(const cv::Mat& gray, const VprConfig& cfg, std::vector<float>* chw);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_VPR_ENCODER_H
|
||||
36
libs/vslam_slam/src/vpr_encoder.cc
Normal file
36
libs/vslam_slam/src/vpr_encoder.cc
Normal 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
|
||||
150
libs/vslam_slam/src/vpr_tensorrt.cc
Normal file
150
libs/vslam_slam/src/vpr_tensorrt.cc
Normal 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
|
||||
Reference in New Issue
Block a user