perf(Point-LIO): iVox 近邻候选压缩 + 逐点观测模型并行化

两处改动共同针对实车持续计算积压:

1) ivox3d_node.hpp get_removed_points/nearby:候选改为 thread_local 的
   {float dist, int index},不再为每个候选构造节点指针;同时删除 INNER_TIMER
   死代码。刻意保留原有的分组/比较顺序(含平局),因为平面拟合消费的是返回序列,
   顺序变了会改变拟合结果。K<=0 直接返回。

2) Estimator.cpp h_model_input/h_model_output:逐点循环加 OpenMP 并行,
   reduction 只作用于整数计数;pabcd 由循环外移入循环内——这是并行化的前提,
   移出后每个线程各自持有,否则是数据竞争。Jacobian 行仍按原顺序组装。

回归:docs/diagnostics/ivox_knn_regression 直接编译生产头、调用实际构建的
point_lio_component,覆盖近邻压缩与并行两处,不启雷达/节点/底盘。
测量工具:docs/diagnostics/profile_pointlio_latency 复用实车构建生成独立诊断
二进制,只往 laserMapping.cpp 副本插入计时,源码结构漂移时拒绝猜测插入。
This commit is contained in:
walunt5
2026-11-19 16:44:37 +08:00
parent 9fdc34321e
commit b875c71e65
9 changed files with 558 additions and 64 deletions
@@ -0,0 +1,42 @@
# IVox 近邻与 Point-LIO 观测模型回归
用于验证近邻候选压缩和逐点匹配并行化,直接编译生产头文件、调用实际构建的
`point_lio_component`;不启动雷达、ROS 节点或底盘。需要先完成实车 Point-LIO 构建。
```bash
cd /home/xie/RC2027_BR_code
source /opt/ros/humble/setup.bash
source minco_ws/install/mission/setup.bash
bash minco_ws/docs/diagnostics/ivox_knn_regression/build_and_run.sh \
minco_ws/log/ivox_knn_regression_01
```
脚本从 `minco_ws/build/mission/point_lio/compile_commands.json` 复用生产编译选项,
并链接该构建目录中的 `libpoint_lio_component.so`。不同构建目录可通过
`BR_KNN_COMPILE_COMMANDS=/absolute/path/compile_commands.json` 指定。
输出目录保存实际编译命令、测试程序和 `matching_order.json`。
两个测试分别覆盖:
- `test_ivox_knn.cpp`:646 个随机、空集、少量点、边界及等距用例;与穷举最近距离
以及旧版完整 DistPoint 的 `nth_element` 选择顺序对照。还验证已有候选前缀、点身份,
并报告 10000 次稠密查询耗时和顺序摘要。耗时只作观察,不作为跨机器通过门槛。
- `test_matching_order.cpp`:调用生产 `h_model_input/output`,覆盖两种外参估计开关、
6 种点数及每组 8 次重复,共每种线程模式 192 次观测模型调用。
两个独立进程分别用 `OMP_THREAD_LIMIT=1/4`,比较 Jacobian、残差、掩码及有序近邻的
完整摘要;共 384 次调用。地图每组重建,重复调用也覆盖线程局部候选缓冲的复用。
只对照冻结的旧版头文件时,可设置 `BR_KNN_ONLY=1` 与
`BR_KNN_HEADER_ROOT=/absolute/path/include`,该根目录应包含 `ivox/ivox3d_node.hpp`。
此模式不运行链接组件的观测模型测试,避免旧头文件与新组件混用。
本机最终结果:646 个近邻用例通过;有序近邻摘要 `90192090487253394` 与旧版一致;
单线程/四线程观测模型摘要均为 `1776722514077682147`。
测试限定于本机编译工具链和这些输入,不能据此承诺所有平台、场景的位级一致。
硬件及相同数据回放是独立验证,记录见 [RAIN_NET_005](../../RAIN_NET_005_2026-11-19.md)。
本次证据位于 `minco_ws/log/rain-net-005/`:
`compact_parallel_regression_final.txt`、`compact_parallel/regression_final/`、
`comparison_contract.json`、`compact_parallel/replay_comparison.json`、
`compact_parallel/live_01/summary.json`。回放用原始时间、完整接收并处理至最后一帧,
比较全部里程计和完整点云;该静止记录通过不代表动态或完整任务验收通过。
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Directly exercise the production voxel node, without ROS or sensor hardware.
set -euo pipefail
BR_KNN_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
BR_KNN_WS=$(cd -- "$BR_KNN_DIR/../../.." && pwd)
BR_KNN_OUT=${1:-"$BR_KNN_WS/log/ivox_knn_regression"}
mkdir -p -- "$BR_KNN_OUT"
BR_KNN_COMPDB=${BR_KNN_COMPILE_COMMANDS:-"$BR_KNN_WS/build/mission/point_lio/compile_commands.json"}
/usr/bin/python3 - "$BR_KNN_COMPDB" "$BR_KNN_DIR/test_ivox_knn.cpp" "$BR_KNN_OUT" "${BR_KNN_HEADER_ROOT:-}" <<'PY'
import json, os, shlex, subprocess, sys
from pathlib import Path
database, source, output = map(Path, sys.argv[1:4])
if sys.argv[4] and os.environ.get('BR_KNN_ONLY') != '1':
raise SystemExit('BR_KNN_HEADER_ROOT requires BR_KNN_ONLY=1; model tests use the built component')
entry = next(e for e in json.loads(database.read_text()) if e['file'].endswith('laserMapping.cpp'))
args = entry.get('arguments') or shlex.split(entry['command'])
command = [args[0]]
if sys.argv[4]:
command.append('-I' + str(Path(sys.argv[4]).resolve()))
i = 1
while i < len(args):
if args[i] == '-o':
i += 2
continue
if args[i] == '-c' or args[i] == entry['file']:
i += 1
continue
command.append(args[i])
i += 1
base_command = list(command)
command += [str(source.resolve()), '-o', str(output.resolve() / 'test_ivox_knn')]
(output / 'compile_command.json').write_text(json.dumps(command, indent=2) + '\n')
subprocess.run(command, cwd=entry['directory'], check=True)
if os.environ.get('BR_KNN_ONLY') != '1':
component = Path(entry['directory']) / 'libpoint_lio_component.so'
model_binary = output.resolve() / 'test_matching_order'
model_command = base_command + ['-I' + str(Path(entry['file']).parent),
str(source.with_name('test_matching_order.cpp').resolve()),
str(component), '-Wl,-rpath,' + str(component.parent),
'-o', str(model_binary)]
(output / 'model_compile_command.json').write_text(json.dumps(model_command, indent=2) + '\n')
subprocess.run(model_command, cwd=entry['directory'], check=True)
results = []
for limit in ('1', '4'):
result = subprocess.run([str(model_binary)], check=True, text=True, capture_output=True,
env=dict(os.environ, OMP_THREAD_LIMIT=limit))
record = json.loads(result.stdout.strip().splitlines()[-1])
results.append(record)
assert results[0]['matching_digest'] == results[1]['matching_digest'], results
(output / 'matching_order.json').write_text(json.dumps(results, indent=2) + '\n')
print(json.dumps({'serial_parallel_matching': 'PASS', 'cases_per_mode': results[0]['model_cases'],
'digest': results[0]['matching_digest']}))
PY
"$BR_KNN_OUT/test_ivox_knn"
@@ -0,0 +1,126 @@
#include <pcl/point_types.h>
#include "ivox/ivox3d_node.hpp"
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <stdexcept>
#include <unordered_set>
using Point = pcl::PointXYZINormal;
using Node = faster_lio::IVoxNode<Point, 3>;
using Candidate = Node::DistPoint;
std::uint64_t ordered_digest = 1469598103934665603ULL;
void require(bool value, const char * message)
{
if (!value) throw std::runtime_error(message);
}
Point point(float x, float y, float z, int id)
{
Point p{}; p.x=x; p.y=y; p.z=z; p.intensity=id; return p;
}
void check(const std::vector<Point> & points, const Point & query, int k, double range)
{
Node node;
for (const auto & p : points) node.InsertPoint(p);
std::vector<Candidate> selected{Candidate(-7.0, nullptr, -123)};
node.KNNPointByCondition(selected, query, k, range);
require(selected.front().node==nullptr && selected.front().idx==-123 &&
selected.front().dist==-7.0, "earlier voxel candidates changed");
std::vector<double> reference;
std::vector<Candidate> legacy_order;
for (std::size_t index=0;index<points.size();++index) {
const auto & p=points[index];
double d=faster_lio::distance2(p, query);
if (d<range*range) {
reference.push_back(d);
legacy_order.emplace_back(d,&node,static_cast<int>(index));
}
}
// Compatibility oracle: the old implementation partitioned full DistPoints.
// Separately compare against exhaustive distances below, so retaining the old
// permutation cannot hide an incorrect nearest-neighbor result.
if (legacy_order.size()>static_cast<std::size_t>(k)) {
std::nth_element(legacy_order.begin(),legacy_order.begin()+k-1,legacy_order.end());
legacy_order.resize(k);
}
std::sort(reference.begin(),reference.end());
reference.resize(std::min(reference.size(),static_cast<std::size_t>(k)));
require(selected.size()==reference.size()+1, "incorrect candidate count");
std::vector<double> actual;
std::unordered_set<int> ids;
for (std::size_t i=1;i<selected.size();++i) {
const auto & c=selected[i];
require(c.node==&node && c.idx>=0 && c.idx<static_cast<int>(points.size()),
"invalid candidate identity");
require(c.idx==legacy_order[i-1].idx, "legacy candidate order changed");
require(ids.insert(c.idx).second, "candidate duplicated");
require(c.dist==faster_lio::distance2(points[c.idx],query), "candidate distance changed");
ordered_digest^=static_cast<std::uint64_t>(c.idx);
ordered_digest*=1099511628211ULL;
actual.push_back(c.dist);
}
std::sort(actual.begin(),actual.end());
require(actual==reference, "nearest distances differ from exhaustive reference");
}
int main()
{
try {
std::mt19937 random(20261119);
std::uniform_real_distribution<float> coordinate(-2.0F,2.0F);
std::size_t cases=0;
for (int count : {0,1,4,5,6,35,500,2000}) {
std::vector<Point> points;
for (int i=0;i<count;++i) points.push_back(point(coordinate(random),coordinate(random),coordinate(random),i));
for (int k : {1,3,5,10,32}) for (double range : {0.0,0.1,1.0,5.0}) {
for (int repeat=0;repeat<4;++repeat) {
check(points,point(coordinate(random),coordinate(random),coordinate(random),-1),k,range);
++cases;
}
}
}
// Equal-distance candidates and the strict range boundary both matter.
std::vector<Point> tied;
for (int i=0;i<100;++i) tied.push_back(point((i%2) ? 1.F : -1.F,0.F,0.F,i));
tied.push_back(point(0.F,0.F,0.F,100));
for (int k : {1,5,32}) for (double range : {1.0,1.01}) {
check(tied,point(0.F,0.F,0.F,-1),k,range); ++cases;
}
// When fewer than K qualify, preserve the original insertion order.
Node small;
small.InsertPoint(point(3,0,0,0));small.InsertPoint(point(1,0,0,1));
std::vector<Candidate> limited;
small.KNNPointByCondition(limited,point(0,0,0,-1),5,5.0);
require(limited.size()==2 && limited[0].idx==0 && limited[1].idx==1,
"small candidate sequence changed");
// Dense-voxel workload with an order-independent identity digest.
Node dense;
for (int i=0;i<1000;++i) dense.InsertPoint(point(coordinate(random),coordinate(random),coordinate(random),i));
std::vector<Point> queries;
for (int i=0;i<2000;++i) queries.push_back(point(coordinate(random),coordinate(random),coordinate(random),-1));
std::uint64_t digest=1469598103934665603ULL;
auto start=std::chrono::steady_clock::now();
for (int repeat=0;repeat<5;++repeat) for (const auto & q : queries) {
std::vector<Candidate> candidates;
candidates.reserve(35);
dense.KNNPointByCondition(candidates,q,5,5.0);
std::vector<int> ids;
for (const auto & c : candidates) ids.push_back(c.idx);
std::sort(ids.begin(),ids.end());
for (int id : ids) {digest^=static_cast<std::uint64_t>(id);digest*=1099511628211ULL;}
}
double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count();
std::cout<<"{\"status\":\"PASS\",\"reference_cases\":"<<cases
<<",\"dense_queries\":10000,\"dense_ms\":"<<ms
<<",\"ordered_reference_digest\":\""<<ordered_digest<<"\""
<<",\"identity_digest\":\""<<digest<<"\"}\n";
} catch (const std::exception & e) {
std::cerr<<"FAIL: "<<e.what()<<'\n';return 1;
}
}
@@ -0,0 +1,67 @@
// Call the production input/output observation models with fresh deterministic maps.
#include "Estimator.h"
#include <omp.h>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <stdexcept>
std::uint64_t digest = 1469598103934665603ULL;
template<typename T> void hash_value(const T & value)
{
unsigned char bytes[sizeof(T)];std::memcpy(bytes,&value,sizeof(T));
for (auto byte : bytes) {digest^=byte;digest*=1099511628211ULL;}
}
int main()
{
try {
std::size_t cases=0;
for (bool input : {false,true}) for (bool extrinsic : {false,true}) {
use_imu_as_input=input;extrinsic_est_en=extrinsic;
Lidar_R_wrt_IMU.setIdentity();Lidar_T_wrt_IMU<<.01,.02,.03;
kf_input.x_.rot=M3D::Identity();kf_output.x_.rot=M3D::Identity();
kf_input.x_.pos=V3D::Zero();kf_output.x_.pos=V3D::Zero();
kf_input.x_.offset_R_L_I=M3D::Identity();kf_output.x_.offset_R_L_I=M3D::Identity();
kf_input.x_.offset_T_L_I=Lidar_T_wrt_IMU;kf_output.x_.offset_T_L_I=Lidar_T_wrt_IMU;
IVoxType::Options options;options.resolution_=2.F;options.point_resolution_=.1F;
ivox_=std::make_shared<IVoxType>(options);
PointVector map;
for (int x=-25;x<=25;++x) for (int y=-25;y<=25;++y) {
PointType body{};body.x=x*.12F;body.y=y*.12F;body.z=1.5F;body.intensity=map.size();
PointType world{};pointBodyToWorld(&body,&world);map.push_back(world);
}
ivox_->AddPoints(map);laser_point_cov=.01;plane_thr=.1;match_s=81.;
for (int count : {1,5,29,30,200,1000}) {
k=0;idx=-1;time_seq={count};feats_down_body->resize(count);feats_down_world->resize(count);
pbody_list.resize(count);crossmat_list.resize(count);Nearest_Points.resize(count);
for (int j=0;j<count;++j) {
auto & p=feats_down_body->points[j];p.x=-2.F+.013F*(j%307);p.y=-2.F+.017F*((j*17)%233);p.z=1.5F+.001F*(j%3);
pbody_list[j]=V3D(p.x,p.y,p.z);
crossmat_list[j]<<0.,-p.z,p.y,p.z,0.,-p.x,-p.y,p.x,0.;
}
// Repeat to exercise reusable per-worker scratch buffers.
for (int repeat=0;repeat<8;++repeat) {
esekfom::dyn_share_modified<double> model;model.valid=true;
if (input) h_model_input(kf_input.x_,M3D::Identity(),M3D::Identity(),model);
else h_model_output(kf_output.x_,M3D::Identity(),M3D::Identity(),model);
if (!model.valid || !model.h_x.allFinite() || !model.z.allFinite())
throw std::runtime_error("invalid observation model");
hash_value(model.h_x.rows());hash_value(model.h_x.cols());
for (Eigen::Index i=0;i<model.h_x.size();++i) hash_value(model.h_x.data()[i]);
for (Eigen::Index i=0;i<model.z.size();++i) hash_value(model.z.data()[i]);
for (int j=0;j<count;++j) {
hash_value(point_selected_surf[j]);
for (const auto & near : Nearest_Points[j]) {
hash_value(near.x);hash_value(near.y);hash_value(near.z);
}
}
++cases;
}
}
}
std::cout<<"{\"status\":\"PASS\",\"model_cases\":"<<cases
<<",\"matching_digest\":\""<<digest<<"\",\"thread_limit\":"
<<omp_get_thread_limit()<<"}\n";
} catch (const std::exception & e) {std::cerr<<e.what()<<'\n';return 1;}
}