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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
| """ OmniDreams 座舱数据合成管道 基于: NVIDIA Cosmos + OmniDreams 架构思路
适用场景: - IMS/DMS 训练数据合成 - 座舱场景生成 (多姿态/多光照/多人) - 长尾场景补充 (罕见姿态/异常情况)
依赖: pip install numpy torch torchvision matplotlib """
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, List, Optional, Dict from dataclasses import dataclass import json
@dataclass class CabinScenario: """座舱场景配置""" num_occupants: int = 1 positions: List[str] = None postures: List[str] = None ages: List[str] = None sizes: List[str] = None weather: str = 'clear' lighting: str = 'day' vehicle_type: str = 'sedan' camera_view: str = 'dashboard' resolution: Tuple[int, int] = (720, 1280) fps: int = 30 scenario_type: str = 'normal' risk_level: str = 'safe'
class CabinWorldModel(nn.Module): """ 座舱世界模型 (简化版 OmniDreams 架构) 输入: 场景配置 + 前帧 输出: 下一帧座舱图像 """ def __init__(self, latent_dim: int = 256, num_actions: int = 9, resolution: Tuple[int, int] = (720, 1280)): super().__init__() self.latent_dim = latent_dim self.resolution = resolution self.scene_encoder = SceneEncoder(latent_dim) self.action_encoder = nn.Linear(num_actions, latent_dim) self.memory = nn.LSTMCell(latent_dim, latent_dim) self.decoder = FrameDecoder(latent_dim, resolution) self.policy_head = nn.Linear(latent_dim, num_actions) self.collision_head = nn.Linear(latent_dim, 4) def forward(self, scene_config: Dict, prev_frame: Optional[torch.Tensor] = None, action: Optional[torch.Tensor] = None, hidden: Optional[Tuple] = None) -> Dict: """ 前向传播 Args: scene_config: 场景配置 prev_frame: 前一帧 (可选) action: 驾驶动作 (9D) hidden: LSTM 隐状态 Returns: dict: 生成帧 + 策略 + 碰撞预测 """ scene_latent = self.scene_encoder(scene_config) if action is not None: action_latent = self.action_encoder(action) latent = scene_latent + action_latent else: latent = scene_latent if hidden is None: h = torch.zeros(1, self.latent_dim) c = torch.zeros(1, self.latent_dim) else: h, c = hidden h_new, c_new = self.memory(latent.unsqueeze(0), (h, c)) frame = self.decoder(h_new) policy_action = self.policy_head(h_new) collision_risk = torch.sigmoid(self.collision_head(h_new)) return { 'frame': frame, 'action': policy_action, 'collision_risk': collision_risk, 'hidden': (h_new, c_new) }
class SceneEncoder(nn.Module): """场景配置编码器""" def __init__(self, latent_dim: int = 256): super().__init__() self.occupant_encoder = nn.Embedding(10, 64) self.posture_encoder = nn.Embedding(10, 64) self.age_encoder = nn.Embedding(5, 32) self.size_encoder = nn.Embedding(5, 32) self.weather_encoder = nn.Embedding(10, 32) self.lighting_encoder = nn.Embedding(10, 32) total = 64*2*4 + 32*2 + 32*2 self.fc = nn.Sequential( nn.Linear(total, latent_dim), nn.ReLU(), nn.Linear(latent_dim, latent_dim) ) def forward(self, config: Dict) -> torch.Tensor: occupant_ids = torch.tensor([1]) posture_ids = torch.tensor([config.get('posture_id', 0)]) occ_feat = self.occupant_encoder(occupant_ids) post_feat = self.posture_encoder(posture_ids) feat = torch.cat([occ_feat.flatten(), post_feat.flatten()]) total_dim = self.fc[0].in_features if len(feat) < total_dim: feat = torch.cat([feat, torch.zeros(total_dim - len(feat))]) return self.fc(feat)
class FrameDecoder(nn.Module): """帧解码器 (简化版)""" def __init__(self, latent_dim: int, resolution: Tuple[int, int]): super().__init__() self.h, self.w = resolution self.latent = latent_dim self.init_size = (self.h // 32, self.w // 32) self.fc = nn.Linear(latent_dim, 512 * self.init_size[0] * self.init_size[1]) self.up = nn.Sequential( nn.ConvTranspose2d(512, 256, 4, 2, 1), nn.BatchNorm2d(256), nn.ReLU(), nn.ConvTranspose2d(256, 128, 4, 2, 1), nn.BatchNorm2d(128), nn.ReLU(), nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.BatchNorm2d(64), nn.ReLU(), nn.ConvTranspose2d(64, 32, 4, 2, 1), nn.BatchNorm2d(32), nn.ReLU(), nn.ConvTranspose2d(32, 3, 4, 2, 1), nn.Sigmoid() ) def forward(self, latent: torch.Tensor) -> torch.Tensor: x = self.fc(latent) x = x.view(-1, 512, self.init_size[0], self.init_size[1]) return self.up(x)
class CabinDataPipeline: """ 座舱训练数据合成管道 功能: 1. 批量生成座舱场景配置 2. 世界模型生成图像 3. 自动标注 4. 数据集管理 """ def __init__(self, model: CabinWorldModel): self.model = model def generate_scenario_batch(self, n_scenarios: int = 100, focus: str = 'cpd') -> List[CabinScenario]: """ 批量生成场景配置 Args: n_scenarios: 场景数 focus: 'cpd'/'oop'/'drowsy'/'distraction' Returns: scenarios: 场景配置列表 """ scenarios = [] for i in range(n_scenarios): if focus == 'cpd': sc = CabinScenario( num_occupants=np.random.choice([1, 2, 3]), positions=['rear_left', 'rear_right'], postures=['sleeping', 'curled'], ages=['child', 'infant'], sizes=['small'], weather=np.random.choice(['clear', 'rain', 'night']), lighting=np.random.choice(['day', 'night']), scenario_type='cpd_check', risk_level='safe' if np.random.random() > 0.3 else 'medium' ) elif focus == 'oop': sc = CabinScenario( num_occupants=1, positions=['driver'], postures=np.random.choice([ 'normal', 'reclined_30', 'reclined_45', 'reclined_60', 'leaning_left', 'leaning_right', 'forward_lean', 'sideways' ]), ages=['adult'], sizes=np.random.choice(['small', 'average', 'large']), weather='clear', lighting='day', scenario_type='oop_detection', risk_level=np.random.choice(['safe', 'low', 'medium', 'high', 'critical']) ) elif focus == 'drowsy': sc = CabinScenario( num_occupants=1, positions=['driver'], postures=['drowsy_level1', 'drowsy_level2', 'drowsy_level3'], ages=['adult'], sizes=['average'], weather=np.random.choice(['clear', 'night', 'sunset']), lighting=np.random.choice(['day', 'dusk', 'night']), scenario_type='drowsiness', risk_level=np.random.choice(['safe', 'low', 'medium', 'high']) ) else: sc = CabinScenario() scenarios.append(sc) return scenarios def generate_frame(self, scenario: CabinScenario) -> Dict: """生成单帧""" config = { 'posture_id': hash(scenario.postures[0] if scenario.postures else 'normal') % 10 } with torch.no_grad(): result = self.model(config) return { 'frame': result['frame'], 'action': result['action'], 'collision_risk': result['collision_risk'], 'scenario': scenario } def generate_dataset(self, n_scenarios: int = 1000, focus: str = 'cpd', output_dir: str = 'synthetic_cabin_data') -> Dict: """ 生成完整数据集 Returns: stats: 数据集统计 """ scenarios = self.generate_scenario_batch(n_scenarios, focus) stats = { 'total': len(scenarios), 'by_risk': {}, 'by_posture': {}, 'by_age': {}, 'by_weather': {}, } for sc in scenarios: risk = sc.risk_level stats['by_risk'][risk] = stats['by_risk'].get(risk, 0) + 1 posture = sc.postures[0] if sc.postures else 'unknown' stats['by_posture'][posture] = stats['by_posture'].get(posture, 0) + 1 age = sc.ages[0] if sc.ages else 'unknown' stats['by_age'][age] = stats['by_age'].get(age, 0) + 1 weather = sc.weather stats['by_weather'][weather] = stats['by_weather'].get(weather, 0) + 1 return stats
if __name__ == "__main__": print("=" * 70) print("NVIDIA OmniDreams 座舱数据合成管道") print("基于: Cosmos 世界基础模型") print("=" * 70) model = CabinWorldModel( latent_dim=128, num_actions=9, resolution=(64, 64) ) total_params = sum(p.numel() for p in model.parameters()) print(f"\n模型参数量: {total_params:,} ({total_params/1e6:.2f}M)") print(f"OmniDreams 实际: 2B 参数, 720p, 68FPS") pipeline = CabinDataPipeline(model) print("\n=== CPD 数据合成 ===") cpd_stats = pipeline.generate_dataset(n_scenarios=500, focus='cpd') print(f"总场景: {cpd_stats['total']}") print(f"风险分布: {cpd_stats['by_risk']}") print(f"姿态分布: {cpd_stats['by_posture']}") print(f"年龄分布: {cpd_stats['by_age']}") print(f"天气分布: {cpd_stats['by_weather']}") print("\n=== OOP 数据合成 ===") oop_stats = pipeline.generate_dataset(n_scenarios=500, focus='oop') print(f"总场景: {oop_stats['total']}") print(f"姿态分布: {oop_stats['by_posture']}") print(f"体型分布: {oop_stats['by_age']}") print(f"风险分布: {oop_stats['by_risk']}") print(f"\n=== 碰撞预测对比 (论文数据) ===") print(f"{'模型':<20s} {'参数':>8s} {'总碰撞':>8s} {'前向':>8s} {'侧向':>8s} {'后向':>8s}") print(f"{'Alpamayo 1.5 (VLA)':<20s} {'~10B':>8s} {'6.9%':>8s} {'1.0%':>8s} {'0.6%':>8s} {'5.3%':>8s}") print(f"{'OmniDreams WAM':<20s} {'~2B':>8s} {'4.2%':>8s} {'0.9%':>8s} {'0.4%':>8s} {'3.0%':>8s}") print(f"{'改善':<20s} {'5x更小':>8s} {'-39%':>8s} {'-10%':>8s} {'-33%':>8s} {'-43%':>8s}") print(f"\n=== 仿真器能力对比 ===") print(f"{'能力':<25s} {'重建型':>10s} {'OmniDreams':>12s}") print(f"{'照片级真实度':<25s} {'✅':>10s} {'✅':>12s}") print(f"{'闭环交互':<25s} {'✅':>10s} {'✅':>12s}") print(f"{'极端天气生成':<25s} {'❌':>10s} {'✅':>12s}") print(f"{'异常物体':<25s} {'❌':>10s} {'✅':>12s}") print(f"{'场景编辑':<25s} {'⚠️':>10s} {'✅':>12s}") print(f"{'分布外场景':<25s} {'❌':>10s} {'✅':>12s}") print(f"{'实时性':<25s} {'✅':>10s} {'✅':>12s}") print(f"{'长程一致性':<25s} {'✅':>10s} {'✅':>12s}") print(f"{'策略训练':<25s} {'❌':>10s} {'✅':>12s}")
|