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

@@ -45,6 +45,12 @@ if(VSLAM_BUILD_SLAM)
# hoi la scan cua DB lan chay khac, dap an la pose da toi uu.
add_executable(vslam_reloc_bench vslam_reloc_bench.cc)
target_link_libraries(vslam_reloc_bench PRIVATE vslam_slam vslam_common)
# vslam_vpr_check: doi chieu VPR TensorRT (C++) voi PyTorch -- chi khi co TensorRT.
if(VSLAM_WITH_TENSORRT)
add_executable(vslam_vpr_check vslam_vpr_check.cc)
target_link_libraries(vslam_vpr_check PRIVATE vslam_slam vslam_common)
endif()
endif()
# vslam_record: ghi .vsr tu bo mo phong theo kich ban co ten. Hat giong co

97
tools/vpr_export_onnx.py Normal file
View File

@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Xuat mo hinh VPR (EigenPlaces ResNet50, 2048 chieu) sang ONNX cho vslam_node, kem file mo ta
tien xu ly; tuy chon tinh mo ta THAM CHIEU bang PyTorch cho mot DB de doi chieu ban TensorRT.
Tien xu ly PHAI giong het tools/vpr_eval.py bien the +clahe (noi da do 88-89% top-1 tren anh IR):
anh IR xam -> CLAHE (clip 2.0, luoi 8x8) -> resize 512x384 (INTER_LINEAR) -> /255 -> lap 3 kenh
-> chuan hoa ImageNet -> mo hinh (da L2 o lop cuoi).
Do tren Jetson (JetPack 6.1, 2026-09-30): TensorRT fp16 6.5 ms/anh, OpenCV CPU 299 ms/anh.
OpenCV 4.2 (may dev) KHONG doc duoc ONNX nay (ReduceL2) -- khong sao: VPR chi can tren robot
(anh mo phong den het).
python3 tools/vpr_export_onnx.py --out resources/vpr/eigenplaces_r50_2048_384x512.onnx
python3 tools/vpr_export_onnx.py --out ... --ref-db DB --ref-out logs/vpr_ref.npz
"""
import argparse
import json
import os
import sys
import time
import cv2
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from vpr_eval import clahe, load_db # noqa: E402 -- CUNG tien xu ly noi da do
W, H = 512, 384
MEAN = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
def load_model():
import torch
# skip_validation: khong goi API GitHub (gioi han 60 lan/gio -> 403).
return torch.hub.load("gmberton/eigenplaces", "get_trained_model", backbone="ResNet50",
fc_output_dim=2048, trust_repo=True, skip_validation=True).eval()
def preprocess(img_gray):
"""Anh IR xam uint8 -> (3, H, W) float32, y nhu vpr_eval.torch_desc voi bien the +clahe."""
x = cv2.resize(clahe(img_gray), (W, H), interpolation=cv2.INTER_LINEAR).astype(np.float32) / 255.0
x = np.repeat(x[None], 3, axis=0)
return (x - np.array(MEAN, np.float32)[:, None, None]) / np.array(STD, np.float32)[:, None, None]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True, help="duong dan .onnx (vd resources/vpr/eigenplaces_r50_2048_384x512.onnx)")
ap.add_argument("--ref-db", default="", help="DB: tinh mo ta THAM CHIEU (PyTorch fp32) cho moi anh")
ap.add_argument("--ref-out", default="", help=".npz: ids (int32), desc (float32 N x 2048)")
ap.add_argument("--device", default="cuda")
a = ap.parse_args()
import onnx
import torch
m = load_model()
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
x = torch.from_numpy(np.random.RandomState(0).rand(1, 3, H, W).astype(np.float32))
torch.onnx.export(m, x, a.out, input_names=["image"], output_names=["desc"], opset_version=13)
mo = onnx.load(a.out)
onnx.checker.check_model(mo)
meta = dict(model="EigenPlaces ResNet50 fc 2048 (gmberton/eigenplaces, torch.hub)", input="image",
output="desc", shape=[1, 3, H, W], clahe_clip=2.0, clahe_grid=8, resize="INTER_LINEAR",
scale=1.0 / 255.0, mean=MEAN, std=STD, gray_to_rgb="lap 3 kenh", l2_normalized=True)
with open(os.path.splitext(a.out)[0] + ".json", "w") as f:
json.dump(meta, f, indent=2)
print(f"ONNX: {a.out} ({os.path.getsize(a.out) / 1e6:.0f} MB), phep toan: "
f"{sorted({n.op_type for n in mo.graph.node})}")
if a.ref_db:
dev = a.device if torch.cuda.is_available() else "cpu"
m = m.to(dev)
nodes = load_db(a.ref_db)
out, t0 = [], time.time()
with torch.no_grad():
for i in range(0, len(nodes), 32):
b = np.stack([preprocess(n["img"]) for n in nodes[i:i + 32]])
out.append(m(torch.from_numpy(b).to(dev)).float().cpu().numpy())
desc = np.concatenate(out)
ref_out = a.ref_out or os.path.splitext(a.out)[0] + "_ref.npz"
np.savez_compressed(ref_out, ids=np.array([n["id"] for n in nodes], np.int32),
desc=desc.astype(np.float32))
print(f"mo ta tham chieu: {len(nodes)} anh tu {a.ref_db} trong {time.time() - t0:.1f} s -> {ref_out}")
# Cung du lieu, dang nhi phan tho cho C++ (tools/vslam_vpr_check):
# int32 N, int32 D, int32 ids[N], float32 desc[N*D].
bin_out = os.path.splitext(ref_out)[0] + ".bin"
with open(bin_out, "wb") as f:
np.array([len(nodes), desc.shape[1]], np.int32).tofile(f)
np.array([n["id"] for n in nodes], np.int32).tofile(f)
desc.astype(np.float32).tofile(f)
print(f" + ban nhi phan cho C++: {bin_out}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

141
tools/vslam_vpr_check.cc Normal file
View File

@@ -0,0 +1,141 @@
// Doi chieu mo ta VPR cua TensorRT (C++, vslam/vpr_encoder.h) voi PyTorch
// (tools/vpr_export_onnx.py --ref-db). CHI build voi -DVSLAM_WITH_TENSORRT=ON.
//
// vslam_vpr_check --db DB --engine PLAN --ref REF.bin [--split-id N]
//
// DAT khi: cosine voi PyTorch trung vi >= 0.999 va nho nhat >= 0.99; va (neu co
// --split-id) anh ban do giong nhat (id < N) cua moi anh hoi (id >= N) trung PyTorch >= 98%.
#include <rtabmap/core/DBDriver.h>
#include <rtabmap/core/SensorData.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include "vslam/vpr_encoder.h"
namespace {
// .bin cua vpr_export_onnx.py: int32 N, int32 D, int32 ids[N], float32 desc[N*D].
bool ReadRef(const std::string& p, std::vector<int>* ids, std::vector<float>* desc, int* dim) {
FILE* f = std::fopen(p.c_str(), "rb");
if (f == nullptr) return false;
int32_t hdr[2] = {0, 0};
bool ok = std::fread(hdr, sizeof(int32_t), 2, f) == 2 && hdr[0] > 0 && hdr[1] > 0;
if (ok) {
ids->resize(hdr[0]);
desc->resize(static_cast<size_t>(hdr[0]) * hdr[1]);
ok = std::fread(ids->data(), sizeof(int32_t), hdr[0], f) == static_cast<size_t>(hdr[0]) &&
std::fread(desc->data(), sizeof(float), desc->size(), f) == desc->size();
*dim = hdr[1];
}
std::fclose(f);
return ok;
}
float Dot(const float* a, const float* b, int n) {
double s = 0.0;
for (int i = 0; i < n; ++i) s += static_cast<double>(a[i]) * b[i];
return static_cast<float>(s);
}
} // namespace
int main(int argc, char** argv) {
std::string db, ref_path;
vslam::VprConfig cfg;
int split = -1;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--db") db = next();
else if (a == "--engine") cfg.engine_path = next();
else if (a == "--ref") ref_path = next();
else if (a == "--split-id") split = std::atoi(next().c_str());
}
if (db.empty() || cfg.engine_path.empty() || ref_path.empty()) {
std::fprintf(stderr, "cach dung: %s --db DB --engine PLAN --ref REF.bin [--split-id N]\n", argv[0]);
return 2;
}
std::vector<int> ids;
std::vector<float> ref;
int dim = 0;
if (!ReadRef(ref_path, &ids, &ref, &dim)) {
std::fprintf(stderr, "khong doc duoc %s\n", ref_path.c_str());
return 1;
}
std::unique_ptr<vslam::VprEncoder> enc;
const vslam::StatusResponse st = vslam::CreateVprEncoder(cfg, &enc);
if (!st.ok()) {
std::fprintf(stderr, "%s\n", st.message.c_str());
return 1;
}
if (enc->dim() != dim) {
std::fprintf(stderr, "engine ra %d chieu, tham chieu %d chieu\n", enc->dim(), dim);
return 1;
}
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
if (!driver->openConnection(db, false)) {
std::fprintf(stderr, "khong mo duoc %s\n", db.c_str());
return 1;
}
std::vector<float> trt(ref.size(), 0.0f);
std::vector<char> have(ids.size(), 0);
std::vector<float> cosv;
double ms_sum = 0.0;
for (size_t k = 0; k < ids.size(); ++k) {
rtabmap::SensorData data;
driver->getNodeData(ids[k], data, true, false, false, false);
data.uncompressData();
if (data.imageRaw().empty()) continue;
std::vector<float> d;
const auto t0 = std::chrono::steady_clock::now();
if (!enc->Describe(data.imageRaw(), &d).ok()) continue;
ms_sum += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
std::copy(d.begin(), d.end(), trt.begin() + static_cast<long>(k) * dim);
have[k] = 1;
cosv.push_back(Dot(d.data(), ref.data() + k * dim, dim));
}
driver->closeConnection(false);
if (cosv.empty()) {
std::fprintf(stderr, "khong tinh duoc anh nao\n");
return 1;
}
std::vector<float> s = cosv;
std::sort(s.begin(), s.end());
const float cmin = s.front(), cp1 = s[s.size() / 100], cmed = s[s.size() / 2];
std::printf("%zu/%zu anh: cosine TensorRT vs PyTorch min %.5f p1 %.5f trung vi %.5f;"
" %.1f ms/anh (ca tien xu ly)\n",
cosv.size(), ids.size(), cmin, cp1, cmed, ms_sum / cosv.size());
bool pass = cmed >= 0.999f && cmin >= 0.99f;
if (split > 0) {
int nq = 0, same = 0;
for (size_t q = 0; q < ids.size(); ++q) {
if (ids[q] < split || !have[q]) continue;
int best_r = -1, best_t = -1;
float sr = -2.0f, stt = -2.0f;
for (size_t m = 0; m < ids.size(); ++m) {
if (ids[m] >= split || !have[m]) continue;
const float a = Dot(ref.data() + q * dim, ref.data() + m * dim, dim);
const float b = Dot(trt.data() + q * dim, trt.data() + m * dim, dim);
if (a > sr) { sr = a; best_r = ids[m]; }
if (b > stt) { stt = b; best_t = ids[m]; }
}
++nq;
if (best_r == best_t) ++same;
}
const double agree = nq > 0 ? 100.0 * same / nq : 0.0;
std::printf("anh giong nhat trong ban do (id < %d): trung PyTorch %d/%d = %.1f%%\n", split,
same, nq, agree);
pass = pass && agree >= 98.0;
}
std::printf("%s\n", pass ? "DAT" : "KHONG DAT");
return pass ? 0 : 3;
}