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
| """ Cosmos3-Edge 座舱场景部署示例 基于 NVIDIA 官方 cookbook 适配
场景: 座舱数据合成 + 边缘推理 1. 生成合成驾驶场景视频(数据增强) 2. 在 Jetson 上运行实时推理 """
import subprocess import torch from diffusers import Cosmos3OmniPipeline from diffusers.utils import export_to_video
""" #!/bin/bash # Jetson AGX Thor 环境搭建 sudo apt-get update sudo apt-get install -y python3.13 python3.13-venv
# 创建虚拟环境 uv venv --python 3.13 --seed --managed-python source .venv/bin/activate
# 安装依赖 uv pip install --torch-backend=auto \ "diffusers @ git+https://github.com/huggingface/diffusers.git" \ accelerate av cosmos_guardrail huggingface_hub \ imageio imageio-ffmpeg \ torch torchvision transformers
# HuggingFace 认证 huggingface-cli login # 使用 read token """
def generate_cabin_scenarios(): """ 使用 Cosmos3-Edge 生成合成座舱场景 用于 DMS/OMS 训练数据增强 生成场景: 1. 不同光照条件的座舱(白天/黄昏/夜间) 2. 不同乘员组合(成人/儿童/宠物) 3. 异常姿态(前倾/侧倾/低头) 4. 不同遮挡程度 """ pipe = Cosmos3OmniPipeline.from_pretrained( "nvidia/Cosmos3-Edge", torch_dtype=torch.bfloat16, device_map="cuda" ) scenarios = [ "A rear-facing infant car seat in the back seat of a vehicle, " "covered with a thin blanket, dim interior lighting, " "viewed from the overhead cabin camera", "A passenger leaning forward at 45 degrees in the front passenger seat, " "reaching toward the dashboard, daytime, bright interior", "A driver looking down at their phone while driving, " "highway scene visible through windshield, golden hour lighting", "Two adults in front seats and one child in rear seat, " "normal driving posture, overcast day, cabin interior", "A tired driver yawning at night, dark cabin interior, " "only instrument panel illumination, infrared camera view", ] generated_videos = [] for i, prompt in enumerate(scenarios): print(f"生成场景 {i+1}/{len(scenarios)}: {prompt[:50]}...") result = pipe(prompt=prompt) video = result.video filename = f"cabin_synthetic_{i:03d}.mp4" export_to_video(video, filename, fps=24) generated_videos.append(filename) print(f" → {filename} ({video.shape[0]} frames)") return generated_videos
class CosmosEdgeInference: """ Cosmos3-Edge 边缘推理引擎 用于座舱实时场景理解 """ def __init__(self, model_path: str = "nvidia/Cosmos3-Edge"): self.pipe = Cosmos3OmniPipeline.from_pretrained( model_path, torch_dtype=torch.bfloat16, device_map="cuda" ) self.pipe.enable_model_cpu_offload() def understand_scene(self, image: torch.Tensor, question: str = "") -> str: """ 使用 Reasoner 模式理解当前座舱场景 Args: image: 座舱摄像头帧 (C, H, W) question: 查询问题 Returns: 场景理解文本 """ prompt = ( f"Analyze this in-cabin camera image. {question}\n" "Describe: occupant count, posture, attention state, " "potential safety risks." ) with torch.inference_mode(): output = self.pipe.reason( image=image, prompt=prompt ) return output.text def predict_future(self, image: torch.Tensor, action: str = "continue_driving") -> torch.Tensor: """ 使用 Generator 模式预测未来场景 Args: image: 当前座舱帧 action: 预设动作 Returns: future_video: 预测的未来视频片段 """ prompt = f"Given this cabin scene, predict the next 2 seconds " f"if the action is: {action}" with torch.inference_mode(): result = self.pipe(prompt=prompt, image=image) return result.video
class ActionChunkController: """ Cosmos3-Edge Action Chunk 控制器 论文/技术报告关键概念: - 每次推理生成一段动作序列(chunk) - 而非单步动作 - action chunk 覆盖约 2.13 秒机器人运动 - 生成时间约 1.53 秒 → 可在当前动作完成前准备好下一chunk 座舱场景适配: - 将 "机器人动作" 替换为 "座舱控制" - 如: 座椅调整、氛围灯、空调、安全带预紧 """ CHUNK_DURATION_SEC = 2.13 INFERENCE_TIME_SEC = 1.53 def __init__(self): self.current_chunk = None self.chunk_start_time = 0 self.next_chunk_ready = False def generate_action_chunk(self, observation: dict) -> list: """ 生成座舱控制 action chunk Args: observation: 当前座舱状态 - occupant_state: 乘员状态 - environment: 环境信息 - vehicle_state: 车辆状态 Returns: action_chunk: 控制动作序列 """ actions = [] state = observation.get('occupant_state', {}) if state.get('fatigue_level', 0) > 0.7: actions.extend([ {'time': 0.0, 'action': 'seat_vibrate', 'level': 3}, {'time': 0.5, 'action': 'audio_alert', 'type': 'fatigue_warning'}, {'time': 1.0, 'action': 'window_ventilate', 'level': 0.7}, {'time': 1.5, 'action': 'ac_temperature', 'value': 22}, ]) elif state.get('is_oop', False): actions.extend([ {'time': 0.0, 'action': 'seatbelt_pretension', 'force': 0.3}, {'time': 0.3, 'action': 'audio_alert', 'type': 'posture_warning'}, {'time': 0.6, 'action': 'airbag_suppress'}, ]) elif state.get('emotion', 'neutral') == 'sad': actions.extend([ {'time': 0.0, 'action': 'ambient_light', 'color': 'warm'}, {'time': 0.5, 'action': 'music_recommended', 'genre': 'uplifting'}, {'time': 1.0, 'action': 'cabin_temperature', 'value': 24}, ]) return actions def should_generate_next(self, current_time: float) -> bool: """ 是否需要生成下一chunk 关键: 在当前chunk执行完之前生成下一个 """ if self.current_chunk is None: return True elapsed = current_time - self.chunk_start_time return elapsed > self.CHUNK_DURATION_SEC * 0.6
if __name__ == "__main__": print("=== Cosmos3-Edge 座舱部署框架 ===") print() controller = ActionChunkController() observation = { 'occupant_state': { 'fatigue_level': 0.85, 'is_oop': False, 'emotion': 'neutral', }, 'environment': {'temperature': 26, 'humidity': 0.6}, 'vehicle_state': {'speed': 80, 'lane': 'highway'}, } print("观察数据:", observation) print() actions = controller.generate_action_chunk(observation) print(f"Action Chunk ({len(actions)} 个动作, {controller.CHUNK_DURATION_SEC}s):") for a in actions: print(f" [{a['time']:.1f}s] {a['action']}: " f"{', '.join(f'{k}={v}' for k,v in a.items() if k not in ['time','action'])}") print(f"\n推理时间: {controller.INFERENCE_TIME_SEC}s") print(f"执行时间: {controller.CHUNK_DURATION_SEC}s") print(f"重叠时间: {controller.CHUNK_DURATION_SEC - controller.INFERENCE_TIME_SEC:.2f}s") print(f"→ 下一chunk可在当前chunk完成前 {controller.CHUNK_DURATION_SEC - controller.INFERENCE_TIME_SEC:.2f}s 准备好")
|