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
| import torch import torch.nn as nn import torch.nn.functional as F
class SlowWorldModel(nn.Module): """ 慢世界模型 功能: 粗粒度长期未来预测 - 低频更新(每N步一次) - 大时间跨度预测 - 捕获宏观趋势 论文Section 3.1: Slow World Model """ def __init__(self, latent_dim: int = 128, action_dim: int = 3, hidden_dim: int = 256): super().__init__() self.state_encoder = nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, latent_dim) ) self.transition = nn.GRUCell(latent_dim + action_dim, hidden_dim) self.state_head = nn.Linear(hidden_dim, latent_dim) self.future_predictor = nn.Sequential( nn.Linear(latent_dim, 128), nn.ReLU(), nn.Linear(128, latent_dim) ) def forward(self, obs: torch.Tensor, action: torch.Tensor, horizon: int = 10) -> dict: """ Args: obs: (B, 3, H, W) 当前观察 action: (B, action_dim) 当前动作 horizon: 长期预测步数 Returns: dict: { 'latent': 当前latent, 'future_latents': (B, horizon, latent_dim) 预测的未来latent } """ latent = self.state_encoder(obs) h = torch.zeros(obs.size(0), 256, device=obs.device) future_latents = [] current_latent = latent current_action = action for t in range(horizon): h = self.transition( torch.cat([current_latent, current_action], dim=-1), h ) current_latent = self.state_head(h) future_latents.append(current_latent) return { 'latent': latent, 'future_latents': torch.stack(future_latents, dim=1) }
class FastWorldModel(nn.Module): """ 快世界模型 功能: 细粒度短期行动生成 - 高频更新(每步) - 短期精确预测 - 受慢模型指导 论文Section 3.2: Fast World Model """ def __init__(self, latent_dim: int = 128, action_dim: int = 3, hidden_dim: int = 256): super().__init__() self.fast_transition = nn.Sequential( nn.Linear(latent_dim + action_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, latent_dim) ) self.action_generator = nn.Sequential( nn.Linear(latent_dim * 2, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, action_dim), nn.Tanh() ) self.frame_decoder = nn.Sequential( nn.Linear(latent_dim, 128 * 4 * 4), nn.ReLU(), nn.Unflatten(1, (128, 4, 4)), nn.ConvTranspose2d(128, 64, 3, stride=2, padding=1, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(64, 32, 3, stride=2, padding=1, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(32, 3, 3, stride=2, padding=1, output_padding=1) ) def forward(self, latent: torch.Tensor, target_latent: torch.Tensor, prev_action: torch.Tensor) -> dict: """ Args: latent: (B, latent_dim) 当前latent target_latent: (B, latent_dim) 慢模型目标latent prev_action: (B, action_dim) 前一动作 Returns: dict: { 'action': 生成的动作, 'next_latent': 预测的下一latent, 'next_frame': 预测的下一帧 } """ action = self.action_generator( torch.cat([latent, target_latent], dim=-1) ) next_latent = self.fast_transition( torch.cat([latent, action], dim=-1) ) next_frame = self.frame_decoder(next_latent) return { 'action': action, 'next_latent': next_latent, 'next_frame': next_frame }
class DriveHWM(nn.Module): """ Drive-HWM: 完整分层世界模型 架构: [观察] → [慢世界模型] → 长期latent预测 → 指导快模型 ↓ [观察] → [快世界模型] → 短期行动+帧预测 → 执行 论文Section 3: Full Architecture """ def __init__(self, latent_dim: int = 128, action_dim: int = 3): super().__init__() self.slow_model = SlowWorldModel(latent_dim, action_dim) self.fast_model = FastWorldModel(latent_dim, action_dim) def forward(self, obs: torch.Tensor, action: torch.Tensor, horizon: int = 10) -> dict: """ Args: obs: (B, 3, H, W) 当前观察 action: (B, action_dim) 当前动作 horizon: 慢模型预测步数 Returns: dict: { 'slow_latent': 慢模型latent, 'future_latents': 长期latent预测, 'fast_action': 快模型生成的动作, 'fast_next_latent': 快模型预测, 'fast_next_frame': 快模型预测帧 } """ slow_out = self.slow_model(obs, action, horizon) target_latent = slow_out['future_latents'][:, 0] fast_out = self.fast_model( slow_out['latent'], target_latent, action ) return { **slow_out, 'fast_action': fast_out['action'], 'fast_next_latent': fast_out['next_latent'], 'fast_next_frame': fast_out['next_frame'] }
if __name__ == "__main__": import numpy as np import time LATENT_DIM = 128 ACTION_DIM = 3 HORIZON = 10 BATCH_SIZE = 16 model = DriveHWM(latent_dim=LATENT_DIM, action_dim=ACTION_DIM) total_params = sum(p.numel() for p in model.parameters()) print(f"Drive-HWM参数量: {total_params:,}") np.random.seed(42) def generate_driving_scene(scenario: str, batch=1): """生成驾驶场景""" obs = torch.rand(batch, 3, 64, 64) if scenario == 'straight': action = torch.tensor([[0.0, 0.5, 0.0]] * batch) obs[:, :, :, 20:44] += 0.3 elif scenario == 'left_turn': action = torch.tensor([[-0.5, 0.3, 0.0]] * batch) obs[:, :, :, :30] += 0.2 elif scenario == 'brake': action = torch.tensor([[0.0, 0.0, 0.8]] * batch) obs[:, :, :, 20:44] += 0.5 return obs, action print("\n--- 生成场景数据 ---") scenarios = ['straight', 'left_turn', 'brake'] all_obs, all_actions = [], [] for scenario in scenarios: obs, action = generate_driving_scene(scenario, batch=5) all_obs.append(obs) all_actions.append(action) obs_batch = torch.cat(all_obs) action_batch = torch.cat(all_actions) print(f" Observation: {obs_batch.shape}") print(f" Action: {action_batch.shape}") print("\n--- 前向传播 ---") model.eval() with torch.no_grad(): out = model(obs_batch, action_batch, horizon=HORIZON) print(f" Slow latent: {out['latent'].shape}") print(f" Future latents: {out['future_latents'].shape}") print(f" Fast action: {out['fast_action'].shape}") print(f" Fast next frame: {out['fast_next_frame'].shape}") print("\n--- 训练流程 ---") optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) model.train() for epoch in range(3): optimizer.zero_grad() out = model(obs_batch, action_batch, horizon=HORIZON) slow_loss = F.mse_loss(out['future_latents'][:, 0], out['latent'].detach()) fast_loss = F.mse_loss(out['fast_action'], action_batch) recon_loss = F.mse_loss(out['fast_next_frame'], obs_batch) loss = slow_loss + fast_loss + 0.1 * recon_loss loss.backward() optimizer.step() print(f"Epoch {epoch+1}: Total={loss.item():.4f}, " f"Slow={slow_loss.item():.4f}, " f"Fast={fast_loss.item():.4f}, " f"Recon={recon_loss.item():.4f}") model.eval() with torch.no_grad(): start = time.time() for _ in range(50): _ = model(obs_batch[:1], action_batch[:1], horizon=5) elapsed = (time.time() - start) / 50 print(f"\n单样本推理延迟: {elapsed*1000:.1f}ms") print(f"慢模型+快模型总延迟: {elapsed*1000:.1f}ms")
|