1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
| """ mmMind 核心架构复现
论文 Section 3: Pose-Guided Kinematic Representation Learning - 训练阶段:3D 姿态监督 → 雷达编码器学习运动学表征 - 推理阶段:移除姿态头,纯雷达输入 → 连续运动学 token → LLM 对齐 """
import torch import torch.nn as nn from typing import Tuple
class SpatioTemporalRadarEncoder(nn.Module): """ 时空雷达点云编码器 输入:雷达点云序列 (B, T, N, F) - B: batch size - T: 时间帧数(5秒 clips, 75帧 @ 15fps) - N: 每帧点数(最多192个点, 3帧聚合) - F: 点特征维度 (x, y, z, intensity, vx, vy, vz = 7) 输出:连续运动学 token (B, T, D) - D: token 嵌入维度 """ def __init__( self, point_dim: int = 7, hidden_dim: int = 256, token_dim: int = 512, num_heads: int = 8, num_layers: int = 4 ): super().__init__() self.point_mlp = nn.Sequential( nn.Linear(point_dim, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, hidden_dim), nn.GELU() ) self.spatial_attn = nn.MultiheadAttention( embed_dim=hidden_dim, num_heads=num_heads, batch_first=True ) temporal_layer = nn.TransformerEncoderLayer( d_model=hidden_dim, nhead=num_heads, dim_feedforward=hidden_dim * 4, batch_first=True ) self.temporal_encoder = nn.TransformerEncoder( temporal_layer, num_layers=num_layers ) self.proj = nn.Linear(hidden_dim, token_dim) def forward( self, radar_points: torch.Tensor, point_mask: torch.Tensor = None ) -> torch.Tensor: """ Args: radar_points: (B, T, N, F) 雷达点云 point_mask: (B, T, N) 有效点掩码 Returns: kinematic_tokens: (B, T, D) 运动学 token """ B, T, N, F = radar_points.shape x = self.point_mlp(radar_points) x = x.view(B * T, N, -1) x, _ = self.spatial_attn(x, x, x, key_padding_mask=point_mask) x = x.mean(dim=1) x = x.view(B, T, -1) x = self.temporal_encoder(x) tokens = self.proj(x) return tokens
class PoseHead(nn.Module): """ 3D 姿态预测头(仅训练阶段使用) 监督信号:同步的 3D 姿态序列 训练后移除,推理时仅用雷达编码器 """ def __init__(self, token_dim: int = 512, num_joints: int = 17): super().__init__() self.joint_predictor = nn.Sequential( nn.Linear(token_dim, token_dim // 2), nn.GELU(), nn.Linear(token_dim // 2, num_joints * 3) ) def forward(self, tokens: torch.Tensor) -> torch.Tensor: """ Args: tokens: (B, T, D) Returns: poses: (B, T, J, 3) """ B, T, D = tokens.shape poses = self.joint_predictor(tokens) poses = poses.view(B, T, -1, 3) return poses
class PoseGuidedPretrainLoss(nn.Module): """ 姿态引导预训练损失 组合: 1. 关节位置 MSE 损失 2. 运动学一致性损失(速度平滑) 3. 对比损失(增强鲁棒性) """ def __init__(self, lambda_vel: float = 0.1, lambda_contrast: float = 0.05): super().__init__() self.lambda_vel = lambda_vel self.lambda_contrast = lambda_contrast def forward( self, pred_poses: torch.Tensor, gt_poses: torch.Tensor, tokens: torch.Tensor ) -> Tuple[torch.Tensor, dict]: pos_loss = nn.functional.mse_loss(pred_poses, gt_poses) pred_vel = pred_poses[:, 1:] - pred_poses[:, :-1] gt_vel = gt_poses[:, 1:] - gt_poses[:, :-1] vel_loss = nn.functional.mse_loss(pred_vel, gt_vel) B = tokens.shape[0] if B > 1: sim = torch.cosine_similarity( tokens[::2].flatten(1), tokens[1::2].flatten(1), dim=-1 ) contrast_loss = -sim.mean() else: contrast_loss = torch.tensor(0.0, device=tokens.device) total = pos_loss + self.lambda_vel * vel_loss + self.lambda_contrast * contrast_loss return total, { 'pos_loss': pos_loss.item(), 'vel_loss': vel_loss.item(), 'contrast_loss': contrast_loss.item() }
class mmMindModel(nn.Module): """ 完整 mmMind 模型 训练阶段: radar → encoder → pose_head → loss(3D姿态监督) 推理阶段: radar → encoder → projector → LLM → 行为描述/问答 """ def __init__(self, llm_dim: int = 4096): super().__init__() self.encoder = SpatioTemporalRadarEncoder() self.pose_head = PoseHead() self.pretrain_loss = PoseGuidedPretrainLoss() self.projector = nn.Sequential( nn.Linear(512, llm_dim), nn.GELU(), nn.Linear(llm_dim, llm_dim) ) def train_forward(self, radar_points, gt_poses, point_mask=None): """训练前向""" tokens = self.encoder(radar_points, point_mask) pred_poses = self.pose_head(tokens) loss, metrics = self.pretrain_loss(pred_poses, gt_poses, tokens) return loss, metrics def inference_forward(self, radar_points, llm, point_mask=None): """推理前向(纯雷达输入)""" tokens = self.encoder(radar_points, point_mask) projected = self.projector(tokens) behavior_text = llm.generate( inputs_embeds=projected, max_new_tokens=128 ) return behavior_text
if __name__ == "__main__": torch.manual_seed(42) radar_input = torch.randn(2, 75, 192, 7) pose_gt = torch.randn(2, 75, 17, 3) model = mmMindModel(llm_dim=4096) loss, metrics = model.train_forward(radar_input, pose_gt) print(f"训练损失: {loss.item():.4f}") print(f" 位置: {metrics['pos_loss']:.4f}") print(f" 速度: {metrics['vel_loss']:.4f}") print(f" 对比: {metrics['contrast_loss']:.4f}") tokens = model.encoder(radar_input) print(f"\n运动学 token 形状: {tokens.shape}") print(f" B={tokens.shape[0]}, T={tokens.shape[1]}, D={tokens.shape[2]}")
|