跳转至

ADR-004:信号指纹的 HNSW 向量搜索

状态

由 ADR-024 部分实现;由 ADR-027 扩展

注意: ADR-024(AETHER)实现了与 HNSW 兼容的指纹索引,包含 4 种索引类型。ADR-027(MERIDIAN)通过域解耦嵌入对此进行扩展,使指纹能够跨环境匹配,而不仅仅在单个房间内匹配。

日期

2026-02-28

背景

当前信号匹配的限制

WiFi-DensePose 系统需要将传入的 CSI 模式与已知签名进行匹配,用于:

  1. 环境识别:基于 CSI 特征识别设备所在的房间/区域
  2. 活动分类:将当前 CSI 模式与已知人类活动(行走、坐着、跌倒)匹配
  3. 异常检测:判断当前读数是否显著偏离基线
  4. 幸存者再识别(MAT 模块):跨扫描会话跟踪单个幸存者

当前 CSIProcessor._calculate_detection_confidence() 中的方法:

# Fixed thresholds, no similarity search
amplitude_indicator = np.mean(features.amplitude_mean) > 0.1
phase_indicator = np.std(features.phase_difference) > 0.05
motion_indicator = motion_score > 0.3
confidence = (0.4 * amplitude_indicator + 0.3 * phase_indicator + 0.3 * motion_indicator)

这是一种 O(1) 固定阈值检查,它: - 无法从过去观测中学习 - 没有“之前见过的相似模式”的概念 - 需要针对每个环境手动调整阈值 - 产生二元指示器(高于/低于阈值),丢失梯度信息

HNSW 提供的能力

分层可导航小世界(HNSW)图支持在高维向量空间中进行近似最近邻搜索,具有以下特点:

  • O(log n) 查询时间,相比 O(n) 暴力搜索
  • 高召回率:在精确搜索 10 倍速度下实现 >95% 召回率
  • 动态插入:无需完全重建即可添加新向量
  • SIMD 加速:RuVector 的实现使用 AVX2/NEON 进行距离计算

RuVector 通过以下方式扩展标准 HNSW: - 双曲 HNSW:在 Poincaré 球空间中进行搜索,以获得层级感知结果(例如,在活动层级中,“行走”比“坐着”更接近“跑步”) - GNN 增强:图神经网络在查询后细化邻居连接 - 分层压缩:通过自适应量化实现 2-32 倍内存缩减

决策

我们将集成 RuVector 的 HNSW 实现,作为所有 CSI 模式匹配操作的主要相似性搜索引擎,用基于相似性的检索取代固定阈值检测。

架构

┌─────────────────────────────────────────────────────────────────┐
│                    HNSW Search Pipeline                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  CSI Input     Feature           Vector         HNSW            │
│  ────────▶    Extraction   ────▶ Encode   ────▶ Search          │
│              (existing)        (new)          (new)             │
│                                                  │              │
│                                    ┌─────────────┤              │
│                                    ▼             ▼              │
│                              Top-K Results    Confidence        │
│                              [vec_id, dist,   Score from        │
│                               metadata]       Distance Dist.   │
│                                    │                            │
│                                    ▼                            │
│                              ┌────────────┐                     │
│                              │ Decision   │                     │
│                              │ Fusion     │                     │
│                              └────────────┘                     │
│                               Combines HNSW similarity with     │
│                               existing threshold-based logic    │
└─────────────────────────────────────────────────────────────────┘

索引配置

/// HNSW configuration tuned for CSI vector characteristics
pub struct CsiHnswConfig {
    /// Vector dimensionality (matches CsiFeatures encoding)
    dim: usize,  // 329 for 64 subcarriers

    /// Maximum number of connections per node per layer
    /// Higher M = better recall, more memory
    /// CSI vectors are moderately dimensional; M=16 balances well
    m: usize,  // 16

    /// Size of dynamic candidate list during construction
    /// ef_construction = 200 gives >99% recall for 329-dim vectors
    ef_construction: usize,  // 200

    /// Size of dynamic candidate list during search
    /// ef_search = 64 gives >95% recall with <1ms latency at 100K vectors
    ef_search: usize,  // 64

    /// Distance metric
    /// Cosine similarity works best for normalized CSI features
    metric: DistanceMetric,  // Cosine

    /// Maximum elements (pre-allocated for performance)
    max_elements: usize,  // 1_000_000

    /// Enable SIMD acceleration
    simd: bool,  // true

    /// Quantization level for memory reduction
    quantization: Quantization,  // PQ8 (product quantization, 8-bit)
}

多索引策略

不同用例需要不同的索引配置:

索引名称 向量 维度 距离 用例
env_fingerprint 10K-1M 329 余弦 环境/房间识别
activity_pattern 1K-50K 329 欧氏 活动分类
temporal_pattern 10K-500K 329 余弦 时序异常检测
survivor_track 100-10K 329 余弦 MAT 幸存者再识别

基于相似性的检测增强

用基于距离的置信度取代固定阈值:

/// Enhanced detection using HNSW similarity search
pub struct SimilarityDetector {
    /// HNSW index of known human-present CSI patterns
    human_patterns: HnswIndex,

    /// HNSW index of known empty-room CSI patterns
    empty_patterns: HnswIndex,

    /// Fusion weight between similarity and threshold methods
    fusion_alpha: f64,  // 0.7 = 70% similarity, 30% threshold
}

impl SimilarityDetector {
    /// Detect human presence using similarity search + threshold fusion
    pub fn detect(&self, features: &CsiFeatures) -> DetectionResult {
        let query_vec = features.to_rvf_vector();

        // Search both indices
        let human_neighbors = self.human_patterns.search(&query_vec, k=5);
        let empty_neighbors = self.empty_patterns.search(&query_vec, k=5);

        // Distance-based confidence
        let avg_human_dist = human_neighbors.mean_distance();
        let avg_empty_dist = empty_neighbors.mean_distance();

        // Similarity confidence: how much closer to human patterns vs empty
        let similarity_confidence = avg_empty_dist / (avg_human_dist + avg_empty_dist);

        // Fuse with traditional threshold-based confidence
        let threshold_confidence = self.traditional_threshold_detect(features);
        let fused_confidence = self.fusion_alpha * similarity_confidence
                             + (1.0 - self.fusion_alpha) * threshold_confidence;

        DetectionResult {
            human_detected: fused_confidence > 0.5,
            confidence: fused_confidence,
            similarity_confidence,
            threshold_confidence,
            nearest_human_pattern: human_neighbors[0].metadata.clone(),
            nearest_empty_pattern: empty_neighbors[0].metadata.clone(),
        }
    }
}

增量学习循环

每次确认的检测都会丰富索引:

1. CSI captured → features extracted → vector encoded
2. HNSW search returns top-K neighbors + distances
3. Detection decision made (similarity + threshold fusion)
4. If confirmed (by temporal consistency or ground truth):
   a. Insert vector into appropriate index (human/empty)
   b. GNN layer updates neighbor relationships (ADR-006)
   c. SONA adapts fusion weights (ADR-005)
5. Periodically: prune stale vectors, rebuild index layers

性能分析

内存需求(PQ8 量化):

向量数量 原始大小 PQ8 压缩 HNSW 开销 总计
10,000 12.9 MB 1.6 MB 2.5 MB 4.1 MB
100,000 129 MB 16 MB 25 MB 41 MB
1,000,000 1.29 GB 160 MB 250 MB 410 MB

延迟预期(329 维向量,ef_search=64):

向量数量 暴力搜索 HNSW 加速比
10,000 3.2 ms 0.08 ms 40x
100,000 32 ms 0.3 ms 107x
1,000,000 320 ms 0.9 ms 356x

用于活动层级的双曲扩展

WiFi 感知活动具有自然层级:

                    motion
                   /      \
              locomotion   stationary
              /    \         /    \
         walking  running  sitting  lying
         /    \
      normal  shuffling

庞加莱球空间中的双曲 HNSW 在搜索过程中保留这种层级关系,因此对 “shuffling” 的查询会先返回 “walking”,再返回 “sitting”,即使欧几里得距离相似。

/// Hyperbolic HNSW for hierarchy-aware activity matching
pub struct HyperbolicActivityIndex {
    index: HnswIndex,
    curvature: f64,  // -1.0 for unit Poincaré ball
}

impl HyperbolicActivityIndex {
    pub fn search(&self, query: &[f32], k: usize) -> Vec<SearchResult> {
        // Uses Poincaré distance: d(u,v) = arcosh(1 + 2||u-v||²/((1-||u||²)(1-||v||²)))
        self.index.search_hyperbolic(query, k, self.curvature)
    }
}

影响

正面影响

  • 自适应检测:系统随更多数据而改进;无需手动调优阈值
  • 亚毫秒搜索:即使在 100 万向量下,HNSW 也能提供 <1ms 查询
  • 内存高效:PQ8 将存储减少 8 倍,召回损失 <5%
  • 层级感知:双曲模式尊重活动关系
  • 增量式:新模式无需完整重建索引即可添加
  • 可解释:“该检测匹配了房间 Y 在时间 Z 的模式 X”

负面影响

  • 冷启动问题:在相似性搜索有用之前需要初始指纹数据
  • 索引维护:需要定期修剪和层再平衡
  • 近似性:HNSW 是近似的;可能遗漏精确最近邻(通过较高的 ef_search 缓解)
  • 索引内存:HNSW 图结构在向量之上增加 2.5 倍开销

迁移策略

  1. 阶段 1:将 HNSW 搜索与现有阈值检测并行运行,记录两者结果
  2. 阶段 2:在标注数据上对融合权重(alpha 参数)进行 A/B 测试
  3. 阶段 3:逐步将 fusion_alpha 从 0.0(纯阈值)增加到 0.7(以相似性为主)
  4. 阶段 4:阈值检测成为冷启动/空索引场景的回退方案

参考资料

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 wi/RuView