训练流水线领域模型¶
训练与机器学习流水线是 WiFi-DensePose 中负责将原始公开 CSI 数据集转化为已训练姿态估计模型及其下游衍生物(对比嵌入、域泛化权重和确定性证明包)的子系统。它是连接研究数据与可部署推理的桥梁。
本文档使用领域驱动设计(DDD)来定义该系统:拥有自身数据和规则的限界上下文、强制不变量的聚合根、承载含义的值对象,以及连接一切的领域事件。目标是让流水线的结构与其实现的物理和数学相匹配——这样任何阅读代码(或修改代码的 AI 代理)的人都能理解每个部分为什么存在,而不仅仅是它做什么。
限界上下文:
| # | 上下文 | 职责 | 关键 ADR | 代码 |
|---|---|---|---|---|
| 1 | 数据集管理 | 加载、验证、归一化并预处理来自 MM-Fi 和 Wi-Pose 的训练数据 | ADR-015 | train/src/dataset.rs, train/src/subcarrier.rs |
| 2 | 模型架构 | 定义神经网络、前向传播、注意力机制和空间解码 | ADR-016, ADR-020 | train/src/model.rs, train/src/graph_transformer.rs |
| 3 | 训练编排 | 运行训练循环、计算复合损失、保存检查点并验证确定性证明 | ADR-015, ADR-016 | train/src/trainer.rs, train/src/losses.rs, train/src/metrics.rs, train/src/proof.rs |
| 4 | 嵌入与迁移 | 生成 AETHER 对比嵌入、MERIDIAN 域泛化特征和 LoRA 适配器 | ADR-024, ADR-027 | train/src/embedding.rs, train/src/domain.rs, train/src/sona.rs |
除非另有说明,所有显示的代码路径均相对于 v2/crates/wifi-densepose-。
领域驱动设计规范¶
通用语言¶
| 术语 | 定义 |
|---|---|
| 训练运行 | 一次完整训练会话:配置、轮次循环、检查点历史和最终模型权重 |
| 轮次 | 对训练数据集的一次完整遍历;产生训练损失和验证指标 |
| 检查点 | 给定轮次的模型权重快照,由 SHA-256 哈希和验证 PCK 标识 |
| CSI 样本 | 单个观测:幅度 + 相位张量、真值关键点以及可见性标志 |
| 子载波插值 | 将 CSI 从源子载波数量重采样到标准 56(MM-Fi 为 114->56,Wi-Pose 为 30->56) |
| 教师-学生 | 一种训练机制,其中基于相机的 RGB 模型生成伪标签;推理时移除相机 |
| 伪标签 | 由 Detectron2 从配对的 RGB 帧生成的 DensePose UV 表面坐标 |
| PCK@0.2 | 在躯干直径 20% 范围内的正确关键点百分比;主要精度指标 |
| OKS | 目标关键点相似度;COCO 评估中使用的按关键点高斯加权距离 |
| MPJPE | 以毫米为单位的每关节平均位置误差;3D 精度指标 |
| 匈牙利分配 | 使用最小代价分配将预测人员匹配到真值的二部匹配 |
| 动态最小割 | 跨帧维护的亚多项式 O(n^1.5 log n) 人员到真值分配 |
| 压缩 CSI 缓冲区 | 分层量化时间窗口:热帧为 8 位,温帧为 5/7 位,冷帧为 3 位 |
| 证明验证 | 确定性检查:固定种子 -> N 个训练步骤 -> 损失下降且 SHA-256 哈希匹配 |
| AETHER 嵌入 | 来自 CsiToPoseTransformer 骨干网络的 128 维 L2 归一化对比向量 |
| InfoNCE 损失 | 一种对比损失,将同一身份的嵌入拉近,将不同身份的嵌入推远 |
| HNSW 索引 | 用于近似最近邻嵌入搜索的分层可导航小世界图 |
| 域分解器 | 将潜在特征拆分为姿态不变(h_pose)和环境特定(h_env)分量 |
| 梯度反转层 | 前向传播中为恒等;反向传播中将梯度乘以 -lambda 以强制域不变性 |
| GRL Lambda | 在前 20 个轮次中从 0.0 退火到 1.0 的对抗权重 |
| FiLM 条件化 | 逐特征线性调制:gamma * features + beta,以几何编码为条件 |
| 硬件归一化器 | 将任意芯片组的 CSI 重采样到标准 56 个子载波,并进行 z-score 幅度归一化 |
| LoRA 适配器 | 用于少样本环境特定微调的低秩适配权重(秩 r,alpha) |
| 快速适配 | 通过对比测试时训练产生每个房间的 LoRA 适配器的 10 秒无标签校准 |
限界上下文¶
1. 数据集管理上下文¶
职责: 从公开数据集(MM-Fi、Wi-Pose)加载原始 CSI 数据,验证结构不变量,将子载波重采样到标准 56,应用相位净化,并向训练循环提供类型化样本。通过分层时间压缩实现内存效率。
+----------------------------------------------------------+
| Dataset Management Context |
+----------------------------------------------------------+
| |
| +---------------+ +---------------+ |
| | MM-Fi Loader | | Wi-Pose | |
| | (.npy files, | | Loader | |
| | 114 sub, | | (.mat files, | |
| | 40 subjects)| | 30 sub, | |
| +-------+-------+ | 12 subjects)| |
| | +-------+-------+ |
| | | |
| +--------+-----------+ |
| v |
| +----------------+ |
| | Subcarrier | |
| | Interpolator | |
| | (114->56 or | |
| | 30->56) | |
| +--------+-------+ |
| v |
| +----------------+ |
| | Phase | |
| | Sanitizer | |
| | (SOTA algs | |
| | from signal) | |
| +--------+-------+ |
| v |
| +----------------+ |
| | Compressed CSI |--> CsiSample |
| | Buffer | |
| | (tiered quant) | |
| +----------------+ |
| |
+----------------------------------------------------------+
聚合根:
- MmFiDataset(聚合根)-- 管理 MM-Fi 数据生命周期
- WiPoseDataset(聚合根)-- 管理 Wi-Pose 数据生命周期
值对象:
- CsiSample -- 单个观测,包含幅度、相位、关键点、可见性
- SubcarrierConfig -- 源数量、目标数量、插值方法
- DatasetSplit -- 训练 / 验证 / 测试受试者划分
- CompressedCsiBuffer -- 由 TemporalTensorCompressor 支持的分级时间窗口
领域服务:
- SubcarrierInterpolationService -- 通过稀疏最小二乘或线性回退对子载波进行重采样
- PhaseSanitizationService -- 应用来自 wifi-densepose-signal 的 SpotFi / MUSIC 相位校正
- TeacherLabelService -- 在配对的 RGB 帧上运行 Detectron2,以生成 DensePose UV 伪标签
- HardwareNormalizerService -- Z-score 归一化 + 芯片组不变相位净化
RuVector 集成:
- ruvector-solver -> NeumannSolver,用于稀疏 O(sqrt(n)) 子载波插值(114->56)
- ruvector-temporal-tensor -> TemporalTensorCompressor,用于 CSI 窗口中 50-75% 的内存减少
2. 模型架构上下文¶
职责: 定义 WiFiDensePoseModel:CSI 嵌入、关键点查询与 CSI 特征之间的交叉注意力、GNN 消息传递、注意力门控模态融合,以及用于关键点和 DensePose UV 的空间解码头。
+----------------------------------------------------------+
| Model Architecture Context |
+----------------------------------------------------------+
| |
| +---------------+ +---------------+ |
| | CSI Embed | | Keypoint | |
| | (Linear | | Queries | |
| | 56 -> d) | | (17 learned | |
| +-------+-------+ | embeddings) | |
| | +-------+-------+ |
| | | |
| +--------+-----------+ |
| v |
| +----------------+ |
| | Cross-Attention| |
| | (Q=queries, | |
| | K,V=csi) | |
| +--------+-------+ |
| v |
| +----------------+ |
| | GNN Stack | |
| | (2-layer GCN | |
| | skeleton | |
| | adjacency) | |
| +--------+-------+ |
| v |
| body_part_features [17 x d_model] |
| | |
| +-------+--------+--------+ |
| v v v v |
| +----------+ +------+ +-----+ +-------+ |
| | Modality | | xyz | | UV | |Spatial| |
| | Transl. | | Head | | Head| |Attn | |
| | (attn | | | | | |Decoder| |
| | mincut) | | | | | | | |
| +----------+ +------+ +-----+ +-------+ |
| |
+----------------------------------------------------------+
聚合根:
- WiFiDensePoseModel(聚合根)-- 完整模型图
实体:
- ModalityTranslator -- 使用最小割的注意力门控 CSI 融合
- CsiToPoseTransformer -- 交叉注意力 + GNN 主干
- KeypointHead -- 从 body_part_features 回归 17 x (x, y, z, confidence)
- DensePoseHead -- 预测身体部位标签和 UV 表面坐标
值对象:
- ModelConfig -- 架构超参数(d_model、n_heads、n_gnn_layers)
- AttentionOutput -- 注意力值 + 来自最小割注意力的门控结果
- BodyPartFeatures -- [17 x d_model] 中间表示
领域服务:
- AttentionGatingService -- 应用 attn_mincut 以剪除无关天线路径
- SpatialDecodingService -- 在特征图位置之间进行基于图的空间注意力
RuVector 集成:
- ruvector-attn-mincut -> attn_mincut,用于 ModalityTranslator 中的天线路径门控
- ruvector-attention -> ScaledDotProductAttention,用于空间解码器的长程依赖
3. 训练编排上下文¶
职责: 跨 epoch 运行训练循环,计算复合损失(关键点 MSE + DensePose 部位 CE + UV Smooth L1 + 迁移 MSE),评估验证指标(PCK@0.2、OKS、MPJPE),管理检查点,并验证确定性证明的正确性。
+----------------------------------------------------------+
| Training Orchestration Context |
+----------------------------------------------------------+
| |
| +---------------+ +---------------+ |
| | Training Loop | | Loss Computer | |
| | (epoch iter, | | (composite: | |
| | batch fwd/ | | kp_mse + | |
| | bwd, optim) | | part_ce + | |
| +-------+-------+ | uv_l1 + | |
| | | transfer) | |
| | +-------+-------+ |
| +--------+-----------+ |
| v |
| +----------------+ |
| | Metric | |
| | Evaluator | |
| | (PCK, OKS, | |
| | MPJPE, | |
| | Hungarian) | |
| +--------+-------+ |
| v |
| +-------------+-------------+ |
| v v |
| +----------------+ +----------------+ |
| | Checkpoint | | Proof Verifier | |
| | Manager | | (fixed seed, | |
| | (best-by-PCK, | | 50 steps, | |
| | SHA-256 hash) | | loss + hash) | |
| +----------------+ +----------------+ |
| |
+----------------------------------------------------------+
聚合:
- TrainingRun(聚合根)-- 完整的训练会话
实体:
- CheckpointManager -- 持久化并选择模型快照
- ProofVerifier -- 针对已存储哈希的确定性验证
值对象:
- TrainingConfig -- 轮数、batch_size、learning_rate、loss_weights、优化器参数
- Checkpoint -- 轮数编号、模型权重 SHA-256、该轮验证 PCK
- LossWeights -- 每个损失分量的相对权重
- CompositeTrainingLoss -- 带各分量分解的组合标量损失
- OksScore -- 每个关键点的目标关键点相似度(含 sigma 值)
- PckScore -- 阈值为 0.2 时的正确关键点百分比
- MpjpeScore -- 以毫米为单位的平均单关节位置误差
- ProofResult -- 种子、步数、loss_decreased 标志、hash_matches 标志
领域服务:
- LossComputationService -- 根据模型输出和真实值计算组合损失
- MetricEvaluationService -- 在验证集上计算 PCK、OKS、MPJPE
- HungarianAssignmentService -- 用于多人评估的二分图匹配
- DynamicPersonMatcherService -- 通过 ruvector-mincut 实现跨帧持久的人员分配
- ProofVerificationService -- 固定种子训练 + SHA-256 验证
RuVector 集成:
- ruvector-mincut -> DynamicMinCut,用于指标中的 O(n^1.5 log n) 多人分配
- 原始 hungarian_assignment 保留用于证明验证中的单帧静态匹配
4. 嵌入与迁移上下文¶
职责: 从模型主干生成 AETHER 对比嵌入,通过 MERIDIAN 训练域对抗特征,管理用于重识别和指纹的 HNSW 嵌入索引,并为少样本环境适应生成 LoRA 适配器。
+----------------------------------------------------------+
| Embedding & Transfer Context |
+----------------------------------------------------------+
| |
| body_part_features [17 x d_model] |
| | |
| +--------+-----------+ |
| v v |
| +---------------+ +---------------+ |
| | AETHER | | MERIDIAN | |
| | Projection | | Domain | |
| | Head | | Factorizer | |
| | (MeanPool -> | | (PoseEncoder | |
| | fc -> 128d) | | + EnvEncoder)| |
| +-------+-------+ +-------+-------+ |
| | | |
| v v |
| +---------------+ +---------------+ |
| | InfoNCE Loss | | Gradient | |
| | + Hard Neg | | Reversal | |
| | Mining (HNSW) | | Layer (GRL) | |
| +-------+-------+ +-------+-------+ |
| | | |
| v v |
| +---------------+ +---------------+ |
| | Embedding | | Geometry | |
| | Index (HNSW) | | Encoder + | |
| | (fingerprint | | FiLM Cond. | |
| | store) | | (zero-shot) | |
| +---------------+ +-------+-------+ |
| | |
| v |
| +---------------+ |
| | Rapid Adapt. | |
| | (LoRA + TTT, | |
| | 10-sec cal.) | |
| +---------------+ |
| |
+----------------------------------------------------------+
聚合:
- EmbeddingIndex(聚合根)-- 基于 HNSW 索引的 AETHER 指纹存储
- DomainAdaptationState(聚合根)-- 跟踪 GRL lambda、域分类器准确率和分解质量
实体:
- ProjectionHead -- 将 body_part_features 映射到 128 维嵌入空间的 MLP
- DomainFactorizer -- 将特征拆分为 h_pose 和 h_env
- DomainClassifier -- 从 h_pose 分类域(通过 GRL 进行对抗训练)
- GeometryEncoder -- 用于 AP 位置的傅里叶位置编码 + DeepSets
- LoraAdapter -- 用于环境特定微调的低秩适配权重
值对象:
- AetherEmbedding -- 128 维 L2 归一化对比向量
- FingerprintType -- ReIdentification / RoomFingerprint / PersonFingerprint
- DomainLabel -- 用于对抗训练的环境标识符
- GrlSchedule -- Lambda 退火参数(max_lambda、warmup_epochs)
- GeometryInput -- 相对于房间原点的 AP 位置(单位:米)
- FilmParameters -- 来自几何条件化的 Gamma(缩放)和 beta(偏移)向量
- LoraConfig -- 秩、alpha、目标层
- AdaptationLoss -- ContrastiveTTT / EntropyMin / Combined
领域服务:
- ContrastiveLossService -- 计算带温度缩放的 InfoNCE 损失
- HardNegativeMiningService -- 用于困难负样本对的 HNSW k-NN 搜索
- DomainAdversarialService -- 管理 GRL 退火和域分类
- GeometryConditioningService -- 编码 AP 布局并生成 FiLM 参数
- VirtualDomainAugmentationService -- 生成合成环境偏移以增强训练多样性
- RapidAdaptationService -- 从 10 秒无标签校准生成 LoRA 适配器
核心领域实体¶
TrainingRun(聚合根)¶
pub struct TrainingRun {
/// Unique run identifier
pub id: TrainingRunId,
/// Full training configuration
pub config: TrainingConfig,
/// Datasets loaded for this run
pub datasets: Vec<DatasetHandle>,
/// Ordered history of per-epoch metrics
pub epoch_history: Vec<EpochRecord>,
/// Best checkpoint by validation PCK
pub best_checkpoint: Option<Checkpoint>,
/// Current epoch (0-indexed)
pub current_epoch: usize,
/// Run status
pub status: RunStatus,
/// Proof verification result (if run)
pub proof_result: Option<ProofResult>,
}
pub enum RunStatus {
Initializing,
Training,
Completed,
Failed { reason: String },
ProofVerified,
}
不变量:
- 在转换到 Training 之前,必须至少加载 1 个数据集
- 仅当新轮次的验证 PCK 超过所有先前轮次时,才更新 best_checkpoint
- proof_result 只能设置一次,且在验证后不可变
MmFiDataset(聚合根)¶
pub struct MmFiDataset {
/// Root directory containing .npy files
pub data_root: PathBuf,
/// Subject IDs in this split
pub subject_ids: Vec<u32>,
/// Number of action classes
pub n_actions: usize, // 27
/// Source subcarrier count
pub source_subcarriers: usize, // 114
/// Target subcarrier count after interpolation
pub target_subcarriers: usize, // 56
/// Antenna configuration: 1 TX x 3 RX
pub antenna_pairs: usize, // 3
/// Sampling rate in Hz
pub sample_rate_hz: f32, // 100.0
/// Temporal window size (frames per sample)
pub window_frames: usize, // 10
/// Compressed buffer for memory-efficient storage
pub buffer: CompressedCsiBuffer,
/// Total loaded samples
pub n_samples: usize,
}
WiPoseDataset(聚合根)¶
pub struct WiPoseDataset {
/// Root directory containing .mat files
pub data_root: PathBuf,
/// Subject IDs in this split
pub subject_ids: Vec<u32>,
/// Source subcarrier count
pub source_subcarriers: usize, // 30
/// Target subcarrier count after zero-padding
pub target_subcarriers: usize, // 56
/// Antenna configuration: 3 TX x 3 RX
pub antenna_pairs: usize, // 9
/// Keypoint count (18 AlphaPose, mapped to 17 COCO)
pub source_keypoints: usize, // 18
/// Compressed buffer
pub buffer: CompressedCsiBuffer,
/// Total loaded samples
pub n_samples: usize,
}
WiFiDensePoseModel(聚合根)¶
pub struct WiFiDensePoseModel {
/// CSI embedding layer: Linear(56, d_model)
pub csi_embed: Linear,
/// Learned keypoint query embeddings [17 x d_model]
pub keypoint_queries: Tensor,
/// Cross-attention: Q=queries, K,V=csi_embed
pub cross_attention: MultiHeadAttention,
/// GNN message passing on skeleton graph
pub gnn_stack: GnnStack,
/// Modality translator with attention-gated fusion
pub modality_translator: ModalityTranslator,
/// Keypoint regression head
pub keypoint_head: KeypointHead,
/// DensePose UV prediction head
pub densepose_head: DensePoseHead,
/// Spatial attention decoder
pub spatial_decoder: SpatialAttentionDecoder,
/// Model dimensionality
pub d_model: usize, // 64
}
EmbeddingIndex(聚合根)¶
pub struct EmbeddingIndex {
/// HNSW graph for approximate nearest-neighbor search
pub hnsw: HnswIndex,
/// Stored embeddings with metadata
pub entries: Vec<EmbeddingEntry>,
/// Embedding dimensionality
pub dim: usize, // 128
/// Number of indexed embeddings
pub count: usize,
/// HNSW construction parameters
pub ef_construction: usize, // 200
pub m_connections: usize, // 16
}
pub struct EmbeddingEntry {
pub id: EmbeddingId,
pub embedding: Vec<f32>, // [128], L2-normalized
pub fingerprint_type: FingerprintType,
pub source_domain: Option<DomainLabel>,
pub created_at: u64,
}
pub enum FingerprintType {
ReIdentification,
RoomFingerprint,
PersonFingerprint,
}
值对象¶
CsiSample¶
pub struct CsiSample {
/// Amplitude tensor [n_antenna_pairs x n_subcarriers x n_time_frames]
pub amplitude: Vec<f32>,
/// Phase tensor [n_antenna_pairs x n_subcarriers x n_time_frames]
pub phase: Vec<f32>,
/// Ground-truth 3D keypoints [17 x 3] (x, y, z in meters)
pub keypoints: [[f32; 3]; 17],
/// Per-keypoint visibility flags
pub visibility: [f32; 17],
/// DensePose UV pseudo-labels (optional, from teacher model)
pub densepose_uv: Option<DensePoseLabels>,
/// Domain label for adversarial training
pub domain_label: Option<DomainLabel>,
/// Hardware source type
pub hardware_type: HardwareType,
}
TrainingConfig¶
pub struct TrainingConfig {
/// Number of training epochs
pub epochs: usize,
/// Mini-batch size
pub batch_size: usize,
/// Initial learning rate
pub learning_rate: f64, // 1e-3
/// Learning rate schedule: step decay at these epochs
pub lr_decay_epochs: Vec<usize>, // [40, 80]
/// Learning rate decay factor
pub lr_decay_factor: f64, // 0.1
/// Loss component weights
pub loss_weights: LossWeights,
/// Optimizer (Adam)
pub optimizer: OptimizerConfig,
/// Validation subject IDs (MM-Fi: 33-40)
pub val_subjects: Vec<u32>,
/// Random seed for reproducibility
pub seed: u64,
/// Enable MERIDIAN domain-adversarial training
pub meridian_enabled: bool,
/// Enable AETHER contrastive learning
pub aether_enabled: bool,
}
pub struct LossWeights {
/// Keypoint heatmap MSE weight
pub keypoint_mse: f32, // 1.0
/// DensePose body part cross-entropy weight
pub densepose_part_ce: f32, // 0.5
/// DensePose UV Smooth L1 weight
pub uv_smooth_l1: f32, // 0.5
/// Teacher-student transfer MSE weight
pub transfer_mse: f32, // 0.2
/// AETHER contrastive loss weight (ADR-024)
pub contrastive: f32, // 0.1
/// MERIDIAN domain adversarial weight (ADR-027)
pub domain_adversarial: f32, // annealed 0.0 -> 1.0
}
检查点¶
pub struct Checkpoint {
/// Epoch at which this checkpoint was saved
pub epoch: usize,
/// SHA-256 hash of serialized model weights
pub weights_hash: String,
/// Validation PCK@0.2 at this epoch
pub validation_pck: f64,
/// Validation OKS at this epoch
pub validation_oks: f64,
/// File path to saved weights
pub path: PathBuf,
/// Timestamp
pub created_at: u64,
}
证明结果¶
pub struct ProofResult {
/// Seed used for model initialization
pub model_seed: u64, // MODEL_SEED = 0
/// Seed used for proof data generation
pub proof_seed: u64, // PROOF_SEED = 42
/// Number of training steps in proof
pub steps: usize, // 50
/// Whether loss decreased monotonically
pub loss_decreased: bool,
/// Whether final weights hash matches stored expected hash
pub hash_matches: bool,
/// The computed SHA-256 hash
pub computed_hash: String,
/// The expected SHA-256 hash (from file)
pub expected_hash: String,
}
LoRA 适配器¶
pub struct LoraAdapter {
/// Low-rank decomposition rank
pub rank: usize, // 4
/// LoRA alpha scaling factor
pub alpha: f32, // 1.0
/// Per-layer weight matrices (A and B for each adapted layer)
pub weights: Vec<LoraLayerWeights>,
/// Source domain this adapter was calibrated for
pub source_domain: DomainLabel,
/// Calibration duration in seconds
pub calibration_duration_secs: f32,
/// Number of calibration frames used
pub calibration_frames: usize,
}
pub struct LoraLayerWeights {
/// Layer name in the model
pub layer_name: String,
/// Down-projection: [d_model x rank]
pub a: Vec<f32>,
/// Up-projection: [rank x d_model]
pub b: Vec<f32>,
}
领域事件¶
数据集事件¶
pub enum DatasetEvent {
/// Dataset loaded and validated
DatasetLoaded {
dataset_type: DatasetType,
n_samples: usize,
n_subjects: u32,
source_subcarriers: usize,
timestamp: u64,
},
/// Subcarrier interpolation completed for a dataset
SubcarrierInterpolationComplete {
dataset_type: DatasetType,
source_count: usize,
target_count: usize,
method: InterpolationMethod,
timestamp: u64,
},
/// Teacher pseudo-labels generated for a batch
PseudoLabelsGenerated {
n_samples: usize,
n_with_uv: usize,
timestamp: u64,
},
}
pub enum DatasetType {
MmFi,
WiPose,
Synthetic,
}
pub enum InterpolationMethod {
/// ruvector-solver NeumannSolver sparse least-squares
SparseNeumannSolver,
/// Fallback linear interpolation
LinearInterpolation,
/// Wi-Pose zero-padding
ZeroPad,
}
训练事件¶
pub enum TrainingEvent {
/// One epoch of training completed
EpochCompleted {
epoch: usize,
train_loss: f64,
val_pck: f64,
val_oks: f64,
val_mpjpe_mm: f64,
learning_rate: f64,
grl_lambda: f32,
timestamp: u64,
},
/// New best checkpoint saved
CheckpointSaved {
epoch: usize,
weights_hash: String,
validation_pck: f64,
path: String,
timestamp: u64,
},
/// Deterministic proof verification completed
ProofVerified {
model_seed: u64,
proof_seed: u64,
steps: usize,
loss_decreased: bool,
hash_matches: bool,
timestamp: u64,
},
/// Training run completed or failed
TrainingRunFinished {
run_id: String,
status: RunStatus,
total_epochs: usize,
best_pck: f64,
best_oks: f64,
timestamp: u64,
},
}
嵌入事件¶
pub enum EmbeddingEvent {
/// New AETHER embedding indexed
EmbeddingIndexed {
embedding_id: String,
fingerprint_type: FingerprintType,
nearest_neighbor_distance: f32,
index_size: usize,
timestamp: u64,
},
/// Hard negative pair discovered during mining
HardNegativeFound {
anchor_id: String,
negative_id: String,
similarity: f32,
timestamp: u64,
},
/// Domain adaptation completed for a target environment
DomainAdaptationComplete {
source_domain: String,
target_domain: String,
pck_before: f64,
pck_after: f64,
adaptation_method: String,
timestamp: u64,
},
/// LoRA adapter generated via rapid calibration
LoraAdapterGenerated {
domain: String,
rank: usize,
calibration_frames: usize,
calibration_seconds: f32,
timestamp: u64,
},
}
不变量¶
数据集管理¶
- MM-Fi 样本在用于训练前必须从 114 个子载波插值到 56 个子载波
- Wi-Pose 样本在用于训练前必须从 30 个子载波零填充到 56 个子载波
- Wi-Pose 关键点必须通过丢弃颈部索引 1,从 18 个(AlphaPose)映射到 17 个(COCO)
- 加载后,所有 CSI 幅度必须有限且非负
- 清洗后,相位值必须位于 [-pi, pi] 区间内
- 验证主体(MM-Fi:33-40)绝不能出现在训练划分中
CompressedCsiBuffer必须在量化误差界限内保持信号保真度(hot:<1% 误差)
模型架构¶
csi_embed的输入维度必须等于规范的 56 个子载波keypoint_queries必须恰好包含 17 个条目(每个 COCO 关键点一个)attn_mincut的 seq_len 必须等于 n_antenna_pairs * n_time_frames- GNN 邻接矩阵必须编码人体骨架拓扑(17 个节点,16 条边)
- 空间注意力解码器必须保持空间分辨率(reshape 过程中无信息损失)
训练编排¶
- 在调用
start()之前,TrainingRun 必须至少加载 1 个数据集 - 证明验证需要固定种子:MODEL_SEED=0、PROOF_SEED=42
- 证明验证在确定性 SyntheticDataset 上恰好使用 50 个训练步骤
- 损失必须在证明步骤中下降(否则证明失败)
- 最终权重的 SHA-256 哈希必须与存储的预期哈希匹配(否则证明失败)
- 当且仅当当前 val_pck 大于所有先前 val_pck 值时,才更新
best_checkpoint - 学习率在第 40 和第 80 个 epoch 按 0.1 的因子衰减(step schedule)
- 在证明验证期间,用于静态单帧匹配的匈牙利分配必须使用确定性实现(而不是 DynamicMinCut)
嵌入与迁移¶
- AETHER 嵌入在索引到 HNSW 之前必须进行 L2 归一化(单位范数)
- InfoNCE 温度必须 > 0(通常为 0.07)
- 对于 k-NN 查询,HNSW 索引的 ef_search 必须 >= k
- MERIDIAN GRL lambda 必须在前 20 个 epoch 内从 0.0 退火到 1.0,使用以下调度:lambda(p) = 2 / (1 + exp(-10 * p)) - 1,其中 p = epoch / 20
- 在任何 epoch 中,GRL lambda 都不得超过 1.0
DomainFactorizer输出维度:h_pose = [17 x 64],h_env = [32]GeometryEncoder必须对 AP 顺序具有置换不变性(由 DeepSets 保证)- LoRA 适配器秩必须 <= d_model / 4(d_model=64 时默认 rank=4)
- 快速适应至少需要 200 个 CSI 帧(20 Hz 下为 10 秒)
领域服务¶
SubcarrierInterpolationService¶
使用基于物理动机的稀疏插值,将 CSI 子载波从源数量重采样到目标数量。
pub trait SubcarrierInterpolationService {
/// Sparse interpolation via NeumannSolver (O(sqrt(n)), preferred)
fn interpolate_sparse(
&self,
source: &[f32],
source_count: usize,
target_count: usize,
tolerance: f64,
) -> Result<Vec<f32>, InterpolationError>;
/// Linear interpolation fallback (O(n))
fn interpolate_linear(
&self,
source: &[f32],
source_count: usize,
target_count: usize,
) -> Vec<f32>;
/// Zero-pad for Wi-Pose (30 -> 56)
fn zero_pad(
&self,
source: &[f32],
target_count: usize,
) -> Vec<f32>;
}
LossComputationService¶
根据模型输出和真实值计算复合训练损失。
pub trait LossComputationService {
/// Compute composite loss with per-component breakdown
fn compute(
&self,
predictions: &ModelOutput,
targets: &GroundTruth,
weights: &LossWeights,
) -> CompositeTrainingLoss;
}
pub struct CompositeTrainingLoss {
/// Total weighted loss (scalar for backprop)
pub total: f64,
/// Keypoint heatmap MSE component
pub keypoint_mse: f64,
/// DensePose body part cross-entropy component
pub densepose_part_ce: f64,
/// DensePose UV Smooth L1 component
pub uv_smooth_l1: f64,
/// Teacher-student transfer MSE component
pub transfer_mse: f64,
/// AETHER contrastive loss (if enabled)
pub contrastive: Option<f64>,
/// MERIDIAN domain adversarial loss (if enabled)
pub domain_adversarial: Option<f64>,
}
MetricEvaluationService¶
使用标准姿态估计指标在验证集上评估模型精度。
pub trait MetricEvaluationService {
/// PCK@0.2: fraction of keypoints within 20% of torso diameter
fn compute_pck(&self, predictions: &[PosePrediction], targets: &[PoseTarget], threshold: f64) -> PckScore;
/// OKS: Object Keypoint Similarity with per-keypoint sigmas
fn compute_oks(&self, predictions: &[PosePrediction], targets: &[PoseTarget]) -> OksScore;
/// MPJPE: Mean Per Joint Position Error in millimeters
fn compute_mpjpe(&self, predictions: &[PosePrediction], targets: &[PoseTarget]) -> MpjpeScore;
/// Multi-person assignment via Hungarian (static, deterministic)
fn assign_hungarian(&self, pred: &[PosePrediction], gt: &[PoseTarget]) -> Vec<(usize, usize)>;
/// Multi-person assignment via DynamicMinCut (persistent, O(n^1.5 log n))
fn assign_dynamic(&mut self, pred: &[PosePrediction], gt: &[PoseTarget]) -> Vec<(usize, usize)>;
}
DomainAdversarialService¶
管理 MERIDIAN 梯度反转训练机制。
pub trait DomainAdversarialService {
/// Compute GRL lambda for the current epoch
fn grl_lambda(&self, epoch: usize, max_warmup_epochs: usize) -> f32;
/// Forward pass through domain classifier with gradient reversal
fn classify_domain(
&self,
h_pose: &Tensor,
lambda: f32,
) -> Tensor;
/// Compute domain adversarial loss (cross-entropy on domain logits)
fn domain_loss(
&self,
domain_logits: &Tensor,
domain_labels: &Tensor,
) -> f64;
}
上下文映射¶
+------------------------------------------------------------------+
| Training Pipeline System |
+------------------------------------------------------------------+
| |
| +------------------+ CsiSample +------------------+ |
| | Dataset |-------------->| Training | |
| | Management | | Orchestration | |
| | Context | | Context | |
| +--------+---------+ +--------+-----------+ |
| | | |
| | Publishes | Publishes |
| | DatasetEvent | TrainingEvent |
| v v |
| +------------------------------------------------------+ |
| | Event Bus (Domain Events) | |
| +------------------------------------------------------+ |
| | | |
| v v |
| +------------------+ +------------------+ |
| | Model |<-------------| Embedding & | |
| | Architecture | body_part_ | Transfer | |
| | Context | features | Context | |
| +------------------+ +------------------+ |
| |
+------------------------------------------------------------------+
| UPSTREAM (Conformist) |
| +--------------+ +--------------+ +--------------+ |
| |wifi-densepose| |wifi-densepose| |wifi-densepose| |
| | -signal | | -nn | | -core | |
| | (phase algs,| | (ONNX, | | (CsiFrame, | |
| | SpotFi) | | Candle) | | error) | |
| +--------------+ +--------------+ +--------------+ |
| |
+------------------------------------------------------------------+
| SIBLING (Partnership) |
| +--------------+ +--------------+ +--------------+ |
| | RuvSense | | MAT | | Sensing | |
| | (pose | | (triage, | | Server | |
| | tracker, | | survivor) | | (inference | |
| | field | | | | deployment) | |
| | model) | | | | | |
| +--------------+ +--------------+ +--------------+ |
| |
+------------------------------------------------------------------+
| EXTERNAL (Published Language) |
| +--------------+ +--------------+ +--------------+ |
| | MM-Fi | | Wi-Pose | | Detectron2 | |
| | (NeurIPS | | (NjtechCV | | (teacher | |
| | dataset) | | dataset) | | labels) | |
| +--------------+ +--------------+ +--------------+ |
+------------------------------------------------------------------+
关系类型: - 数据集管理 -> 训练编排:客户/供应商(数据集管理产生 CsiSamples;训练编排消费) - 模型架构 -> 训练编排:合作伙伴(紧密双向耦合:训练编排驱动前向/反向;模型架构定义计算图) - 模型架构 -> 嵌入与迁移:客户/供应商(模型架构产生 body_part_features;嵌入与迁移消费以服务于对比/对抗头) - 嵌入与迁移 -> 训练编排:合作伙伴(对比损失与对抗损失汇入复合损失) - 训练流水线 -> 上游 crate:顺从者(适配 wifi-densepose-signal、-nn、-core 类型) - 训练流水线 -> RuvSense/MAT/Server:合作伙伴(训练后的模型权重流向下游) - 训练流水线 -> 外部数据集:防腐层(数据集加载器将外部格式转换为领域类型)
防腐层¶
MM-Fi 适配器(数据集管理 -> 外部 MM-Fi 格式)¶
/// Translates raw MM-Fi numpy files into domain CsiSample values.
/// Handles the 114->56 subcarrier interpolation and 1TX/3RX antenna layout.
pub struct MmFiAdapter {
/// Subcarrier interpolation service
interpolator: Box<dyn SubcarrierInterpolationService>,
/// Phase sanitizer from wifi-densepose-signal
phase_sanitizer: PhaseSanitizer,
/// Hardware normalizer for z-score normalization
normalizer: HardwareNormalizer,
}
impl MmFiAdapter {
/// Load a single MM-Fi sample from .npy tensors and produce a CsiSample.
/// Steps:
/// 1. Read amplitude [3, 114, 10] and phase [3, 114, 10]
/// 2. Interpolate 114 -> 56 subcarriers per antenna pair
/// 3. Sanitize phase (remove linear offset, unwrap)
/// 4. Z-score normalize amplitude per frame
/// 5. Read 17-keypoint COCO annotations
pub fn adapt(&self, raw: &MmFiRawSample) -> Result<CsiSample, AdapterError>;
}
Wi-Pose 适配器(数据集管理 -> 外部 Wi-Pose 格式)¶
/// Translates Wi-Pose .mat files into domain CsiSample values.
/// Handles 30->56 zero-padding and 18->17 keypoint mapping.
pub struct WiPoseAdapter {
/// Zero-padding service
interpolator: Box<dyn SubcarrierInterpolationService>,
/// Phase sanitizer
phase_sanitizer: PhaseSanitizer,
}
impl WiPoseAdapter {
/// Load a Wi-Pose sample from .mat format and produce a CsiSample.
/// Steps:
/// 1. Read CSI [9, 30] (3x3 antenna pairs, 30 subcarriers)
/// 2. Zero-pad 30 -> 56 subcarriers (high-frequency padding)
/// 3. Sanitize phase
/// 4. Map 18 AlphaPose keypoints -> 17 COCO (drop neck, index 1)
pub fn adapt(&self, raw: &WiPoseRawSample) -> Result<CsiSample, AdapterError>;
}
教师模型适配器(数据集管理 -> Detectron2)¶
/// Adapts Detectron2 DensePose outputs into domain DensePoseLabels.
/// Used during teacher-student pseudo-label generation.
pub struct TeacherModelAdapter;
impl TeacherModelAdapter {
/// Run Detectron2 DensePose on an RGB frame and produce pseudo-labels.
/// Output: (part_labels [H x W], u_coords [H x W], v_coords [H x W])
pub fn generate_pseudo_labels(
&self,
rgb_frame: &RgbFrame,
) -> Result<DensePoseLabels, AdapterError>;
}
RuVector 适配器(模型架构 -> ruvector crate)¶
/// Adapts ruvector-attn-mincut API to the model's tensor format.
/// Handles the Tensor <-> Vec<f32> conversion overhead per batch element.
pub struct AttnMinCutAdapter;
impl AttnMinCutAdapter {
/// Apply min-cut gated attention to antenna-path features.
/// Converts [B, n_ant, n_sc] tensor to flat Vec<f32> per batch element,
/// calls attn_mincut, and reshapes output back to tensor.
pub fn apply(
&self,
features: &Tensor,
n_antenna_paths: usize,
n_subcarriers: usize,
lambda: f32,
) -> Result<Tensor, AdapterError>;
}
仓储接口¶
/// Persists and retrieves training run state
pub trait TrainingRunRepository {
fn save(&self, run: &TrainingRun) -> Result<(), RepositoryError>;
fn find_by_id(&self, id: &TrainingRunId) -> Result<Option<TrainingRun>, RepositoryError>;
fn find_latest(&self) -> Result<Option<TrainingRun>, RepositoryError>;
fn list_completed(&self) -> Result<Vec<TrainingRun>, RepositoryError>;
}
/// Persists model checkpoints
pub trait CheckpointRepository {
fn save(&self, checkpoint: &Checkpoint) -> Result<(), RepositoryError>;
fn find_best(&self, run_id: &TrainingRunId) -> Result<Option<Checkpoint>, RepositoryError>;
fn find_by_epoch(&self, run_id: &TrainingRunId, epoch: usize) -> Result<Option<Checkpoint>, RepositoryError>;
fn list_all(&self, run_id: &TrainingRunId) -> Result<Vec<Checkpoint>, RepositoryError>;
}
/// Persists AETHER embedding index
pub trait EmbeddingRepository {
fn save_index(&self, index: &EmbeddingIndex) -> Result<(), RepositoryError>;
fn load_index(&self) -> Result<Option<EmbeddingIndex>, RepositoryError>;
fn add_entry(&self, entry: &EmbeddingEntry) -> Result<(), RepositoryError>;
fn search_knn(&self, query: &[f32], k: usize) -> Result<Vec<(EmbeddingEntry, f32)>, RepositoryError>;
}
/// Persists LoRA adapters for environment-specific fine-tuning
pub trait LoraRepository {
fn save(&self, adapter: &LoraAdapter) -> Result<(), RepositoryError>;
fn find_by_domain(&self, domain: &DomainLabel) -> Result<Option<LoraAdapter>, RepositoryError>;
fn list_all(&self) -> Result<Vec<LoraAdapter>, RepositoryError>;
}
参考资料¶
- ADR-015:公共数据集策略(MM-Fi、Wi-Pose、教师-学生训练)
- ADR-016:RuVector 集成(训练流水线中的 5 个 crate 集成点)
- ADR-020:Rust 迁移(wifi-densepose-train crate 中的训练流水线)
- ADR-024:AETHER 对比 CSI 嵌入(128 维指纹、InfoNCE、HNSW)
- ADR-027:MERIDIAN 跨环境领域泛化(GRL、FiLM、LoRA)
- Yang 等,“MM-Fi: Multi-Modal Non-Intrusive 4D Human Dataset”(NeurIPS 2023)
- NjtechCVLab,“Wi-Pose Dataset”(CSI-Former、MDPI Entropy 2023)
- Geng 等,“DensePose From WiFi”(CMU、arXiv:2301.00250、2023)
- Ganin 等,“Domain-Adversarial Training of Neural Networks”(JMLR 2016)
- Perez 等,“FiLM: Visual Reasoning with a General Conditioning Layer”(AAAI 2018)
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 wi/RuView