Update multimodel_fusion.py
Browse files- multimodel_fusion.py +474 -521
multimodel_fusion.py
CHANGED
|
@@ -1,522 +1,475 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
dim
|
| 21 |
-
n_heads
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
self.
|
| 28 |
-
self.
|
| 29 |
-
self.
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
self.
|
| 34 |
-
|
| 35 |
-
self.
|
| 36 |
-
self.
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
self
|
| 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 |
-
attn_output =
|
| 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 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
if
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
#
|
| 409 |
-
if
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
#
|
| 416 |
-
fused_features =
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
def forward(self, segments: List[Dict]) -> torch.Tensor:
|
| 476 |
-
"""简单拼接所有模态"""
|
| 477 |
-
all_features = [seg['data'] for seg in segments]
|
| 478 |
-
fused = torch.cat(all_features, dim=1)
|
| 479 |
-
fused = self.fusion_proj(fused)
|
| 480 |
-
return self.norm(fused)
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
class LateFusionModule(nn.Module):
|
| 484 |
-
"""晚期融合 - 在深层才融合模态"""
|
| 485 |
-
def __init__(
|
| 486 |
-
self,
|
| 487 |
-
dim: int = 2048,
|
| 488 |
-
num_modalities: int = 4,
|
| 489 |
-
fusion_method: str = 'concat' # 'concat', 'attention', 'average'
|
| 490 |
-
):
|
| 491 |
-
super().__init__()
|
| 492 |
-
self.fusion_method = fusion_method
|
| 493 |
-
|
| 494 |
-
if fusion_method == 'concat':
|
| 495 |
-
self.fusion_proj = nn.Linear(dim * num_modalities, dim)
|
| 496 |
-
elif fusion_method == 'attention':
|
| 497 |
-
self.attention_weights = nn.Linear(dim, 1)
|
| 498 |
-
|
| 499 |
-
self.norm = RMSNorm(dim)
|
| 500 |
-
|
| 501 |
-
def forward(self, modality_outputs: List[torch.Tensor]) -> torch.Tensor:
|
| 502 |
-
"""
|
| 503 |
-
Args:
|
| 504 |
-
modality_outputs: 每个模态独立处理后的输出列表 [B, T, D]
|
| 505 |
-
"""
|
| 506 |
-
if self.fusion_method == 'concat':
|
| 507 |
-
# 拼接并投影
|
| 508 |
-
pooled = [x.mean(dim=1) for x in modality_outputs]
|
| 509 |
-
fused = torch.cat(pooled, dim=-1)
|
| 510 |
-
fused = self.fusion_proj(fused)
|
| 511 |
-
|
| 512 |
-
elif self.fusion_method == 'attention':
|
| 513 |
-
# 注意力加权
|
| 514 |
-
stacked = torch.stack([x.mean(dim=1) for x in modality_outputs], dim=1)
|
| 515 |
-
weights = F.softmax(self.attention_weights(stacked), dim=1)
|
| 516 |
-
fused = (stacked * weights).sum(dim=1)
|
| 517 |
-
|
| 518 |
-
else: # average
|
| 519 |
-
stacked = torch.stack([x.mean(dim=1) for x in modality_outputs], dim=1)
|
| 520 |
-
fused = stacked.mean(dim=1)
|
| 521 |
-
|
| 522 |
return self.norm(fused)
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 5 |
+
from components import RMSNorm
|
| 6 |
+
from transformer import GroupedQueryAttention
|
| 7 |
+
import math
|
| 8 |
+
from contrastive_learning import MultiModalContrastiveLoss
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CrossModalAttention(nn.Module):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
dim: int,
|
| 15 |
+
n_heads: int = 16,
|
| 16 |
+
dropout: float = 0.1,
|
| 17 |
+
qkv_bias: bool = True
|
| 18 |
+
):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.dim = dim
|
| 21 |
+
self.n_heads = n_heads
|
| 22 |
+
self.head_dim = dim // n_heads
|
| 23 |
+
self.scale = self.head_dim ** -0.5
|
| 24 |
+
|
| 25 |
+
assert dim % n_heads == 0, f"dim {dim} must be divisible by n_heads {n_heads}"
|
| 26 |
+
|
| 27 |
+
self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)
|
| 28 |
+
self.k_proj = nn.Linear(dim, dim, bias=qkv_bias)
|
| 29 |
+
self.v_proj = nn.Linear(dim, dim, bias=qkv_bias)
|
| 30 |
+
self.o_proj = nn.Linear(dim, dim)
|
| 31 |
+
|
| 32 |
+
self.attn_dropout = nn.Dropout(dropout)
|
| 33 |
+
self.resid_dropout = nn.Dropout(dropout)
|
| 34 |
+
|
| 35 |
+
self.norm_q = RMSNorm(dim)
|
| 36 |
+
self.norm_k = RMSNorm(dim)
|
| 37 |
+
|
| 38 |
+
def forward(
|
| 39 |
+
self,
|
| 40 |
+
query: torch.Tensor,
|
| 41 |
+
key: torch.Tensor,
|
| 42 |
+
value: torch.Tensor,
|
| 43 |
+
attention_mask: Optional[torch.Tensor] = None
|
| 44 |
+
) -> torch.Tensor:
|
| 45 |
+
B, T_q, D = query.shape
|
| 46 |
+
T_k = key.shape[1]
|
| 47 |
+
|
| 48 |
+
# 归一化
|
| 49 |
+
query = self.norm_q(query)
|
| 50 |
+
key = self.norm_k(key)
|
| 51 |
+
|
| 52 |
+
# 投影并重塑
|
| 53 |
+
q = self.q_proj(query).view(B, T_q, self.n_heads, self.head_dim).transpose(1, 2)
|
| 54 |
+
k = self.k_proj(key).view(B, T_k, self.n_heads, self.head_dim).transpose(1, 2)
|
| 55 |
+
v = self.v_proj(value).view(B, T_k, self.n_heads, self.head_dim).transpose(1, 2)
|
| 56 |
+
|
| 57 |
+
# 使用Flash Attention或手动实现
|
| 58 |
+
if hasattr(F, 'scaled_dot_product_attention'):
|
| 59 |
+
dropout_p = self.attn_dropout.p if self.training else 0.0
|
| 60 |
+
attn_output = F.scaled_dot_product_attention(
|
| 61 |
+
q, k, v,
|
| 62 |
+
attn_mask=attention_mask,
|
| 63 |
+
dropout_p=dropout_p,
|
| 64 |
+
is_causal=False
|
| 65 |
+
)
|
| 66 |
+
else:
|
| 67 |
+
attn_scores = (q @ k.transpose(-2, -1)) * self.scale
|
| 68 |
+
if attention_mask is not None:
|
| 69 |
+
attn_scores = attn_scores + attention_mask
|
| 70 |
+
attn_weights = F.softmax(attn_scores, dim=-1)
|
| 71 |
+
attn_weights = self.attn_dropout(attn_weights)
|
| 72 |
+
attn_output = attn_weights @ v
|
| 73 |
+
|
| 74 |
+
# 重塑并投影输出
|
| 75 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(B, T_q, D)
|
| 76 |
+
output = self.resid_dropout(self.o_proj(attn_output))
|
| 77 |
+
|
| 78 |
+
return output
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ModalityProjector(nn.Module):
|
| 82 |
+
"""模态投影器 - 将不同模态投影到统一空间"""
|
| 83 |
+
def __init__(
|
| 84 |
+
self,
|
| 85 |
+
input_dim: int,
|
| 86 |
+
output_dim: int,
|
| 87 |
+
hidden_dim: Optional[int] = None,
|
| 88 |
+
num_layers: int = 2,
|
| 89 |
+
use_layer_norm: bool = True
|
| 90 |
+
):
|
| 91 |
+
super().__init__()
|
| 92 |
+
if hidden_dim is None:
|
| 93 |
+
hidden_dim = (input_dim + output_dim) // 2
|
| 94 |
+
|
| 95 |
+
layers = []
|
| 96 |
+
for i in range(num_layers):
|
| 97 |
+
if i == 0:
|
| 98 |
+
layers.append(nn.Linear(input_dim, hidden_dim))
|
| 99 |
+
elif i == num_layers - 1:
|
| 100 |
+
layers.append(nn.Linear(hidden_dim, output_dim))
|
| 101 |
+
else:
|
| 102 |
+
layers.append(nn.Linear(hidden_dim, hidden_dim))
|
| 103 |
+
|
| 104 |
+
if i < num_layers - 1:
|
| 105 |
+
if use_layer_norm:
|
| 106 |
+
layers.append(RMSNorm(hidden_dim))
|
| 107 |
+
layers.append(nn.GELU())
|
| 108 |
+
|
| 109 |
+
self.projector = nn.Sequential(*layers)
|
| 110 |
+
|
| 111 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 112 |
+
return self.projector(x)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class ModalityAdapter(nn.Module):
|
| 116 |
+
"""模态适配器 - 为每个模态学习特定的适配参数"""
|
| 117 |
+
def __init__(
|
| 118 |
+
self,
|
| 119 |
+
dim: int,
|
| 120 |
+
bottleneck_dim: int = 64,
|
| 121 |
+
num_modalities: int = 4
|
| 122 |
+
):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.adapters = nn.ModuleList([
|
| 125 |
+
nn.Sequential(
|
| 126 |
+
nn.Linear(dim, bottleneck_dim),
|
| 127 |
+
nn.GELU(),
|
| 128 |
+
nn.Linear(bottleneck_dim, dim)
|
| 129 |
+
)
|
| 130 |
+
for _ in range(num_modalities)
|
| 131 |
+
])
|
| 132 |
+
for adapter in self.adapters:
|
| 133 |
+
nn.init.zeros_(adapter[-1].weight)
|
| 134 |
+
nn.init.zeros_(adapter[-1].bias)
|
| 135 |
+
|
| 136 |
+
def forward(self, x: torch.Tensor, modality_id: int) -> torch.Tensor:
|
| 137 |
+
if modality_id >= len(self.adapters):
|
| 138 |
+
return x
|
| 139 |
+
return x + self.adapters[modality_id](x)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class CrossModalFusionLayer(nn.Module):
|
| 143 |
+
"""跨模态融合层"""
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
dim: int,
|
| 147 |
+
n_heads: int = 16,
|
| 148 |
+
dropout: float = 0.1,
|
| 149 |
+
use_adapter: bool = True,
|
| 150 |
+
adapter_dim: int = 64
|
| 151 |
+
):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.dim = dim
|
| 154 |
+
self.use_adapter = use_adapter
|
| 155 |
+
|
| 156 |
+
# 自注意力
|
| 157 |
+
self.self_attn = GroupedQueryAttention(
|
| 158 |
+
dim=dim,
|
| 159 |
+
n_heads=n_heads,
|
| 160 |
+
dropout=dropout,
|
| 161 |
+
attn_dropout=dropout
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# 跨模态注意力
|
| 165 |
+
self.cross_attn = CrossModalAttention(
|
| 166 |
+
dim=dim,
|
| 167 |
+
n_heads=n_heads,
|
| 168 |
+
dropout=dropout
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# 前馈网络
|
| 172 |
+
self.ffn = nn.Sequential(
|
| 173 |
+
nn.Linear(dim, dim * 4),
|
| 174 |
+
nn.GELU(),
|
| 175 |
+
nn.Dropout(dropout),
|
| 176 |
+
nn.Linear(dim * 4, dim),
|
| 177 |
+
nn.Dropout(dropout)
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# 归一化层
|
| 181 |
+
self.norm1 = RMSNorm(dim)
|
| 182 |
+
self.norm2 = RMSNorm(dim)
|
| 183 |
+
self.norm3 = RMSNorm(dim)
|
| 184 |
+
|
| 185 |
+
# 模态适配器
|
| 186 |
+
if use_adapter:
|
| 187 |
+
self.adapter = ModalityAdapter(dim, adapter_dim)
|
| 188 |
+
else:
|
| 189 |
+
self.adapter = None
|
| 190 |
+
|
| 191 |
+
def forward(
|
| 192 |
+
self,
|
| 193 |
+
x: torch.Tensor,
|
| 194 |
+
context: Optional[torch.Tensor] = None,
|
| 195 |
+
modality_id: Optional[int] = None,
|
| 196 |
+
attention_mask: Optional[torch.Tensor] = None
|
| 197 |
+
) -> torch.Tensor:
|
| 198 |
+
attn_out = self.self_attn(
|
| 199 |
+
self.norm1(x),
|
| 200 |
+
attention_mask=attention_mask
|
| 201 |
+
)[0] # 只取输出
|
| 202 |
+
x = x + attn_out
|
| 203 |
+
|
| 204 |
+
if context is not None:
|
| 205 |
+
cross_attn_out = self.cross_attn(
|
| 206 |
+
self.norm2(x),
|
| 207 |
+
context,
|
| 208 |
+
context,
|
| 209 |
+
attention_mask=None
|
| 210 |
+
)
|
| 211 |
+
x = x + cross_attn_out
|
| 212 |
+
|
| 213 |
+
# 前馈网络
|
| 214 |
+
x = x + self.ffn(self.norm3(x))
|
| 215 |
+
|
| 216 |
+
# 模态适配器
|
| 217 |
+
if self.use_adapter and modality_id is not None and self.adapter is not None:
|
| 218 |
+
x = self.adapter(x, modality_id)
|
| 219 |
+
|
| 220 |
+
return x
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class PerceiverResampler(nn.Module):
|
| 224 |
+
"""Perceiver Resampler - 压缩模态特征到固定数量的tokens"""
|
| 225 |
+
def __init__(
|
| 226 |
+
self,
|
| 227 |
+
dim: int,
|
| 228 |
+
depth: int = 6,
|
| 229 |
+
num_latents: int = 64,
|
| 230 |
+
n_heads: int = 16,
|
| 231 |
+
dropout: float = 0.0
|
| 232 |
+
):
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.num_latents = num_latents
|
| 235 |
+
self.latents = nn.Parameter(torch.randn(num_latents, dim))
|
| 236 |
+
|
| 237 |
+
self.layers = nn.ModuleList([
|
| 238 |
+
CrossModalFusionLayer(
|
| 239 |
+
dim=dim,
|
| 240 |
+
n_heads=n_heads,
|
| 241 |
+
dropout=dropout,
|
| 242 |
+
use_adapter=False
|
| 243 |
+
)
|
| 244 |
+
for _ in range(depth)
|
| 245 |
+
])
|
| 246 |
+
|
| 247 |
+
self.norm = RMSNorm(dim)
|
| 248 |
+
|
| 249 |
+
# 初始化latents
|
| 250 |
+
nn.init.trunc_normal_(self.latents, std=0.02)
|
| 251 |
+
|
| 252 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 253 |
+
B = x.shape[0]
|
| 254 |
+
latents = self.latents.unsqueeze(0).expand(B, -1, -1)
|
| 255 |
+
|
| 256 |
+
# 通过多层交叉注意力处理
|
| 257 |
+
for layer in self.layers:
|
| 258 |
+
latents = layer(latents, context=x)
|
| 259 |
+
|
| 260 |
+
return self.norm(latents)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class MultiModalFusionModule(nn.Module):
|
| 264 |
+
"""多模态融合模块 - 整合所有融合策略"""
|
| 265 |
+
def __init__(
|
| 266 |
+
self,
|
| 267 |
+
dim: int = 2048,
|
| 268 |
+
num_fusion_layers: int = 4,
|
| 269 |
+
n_heads: int = 16,
|
| 270 |
+
dropout: float = 0.1,
|
| 271 |
+
use_perceiver: bool = True,
|
| 272 |
+
num_latents: int = 64,
|
| 273 |
+
use_contrastive: bool = True,
|
| 274 |
+
contrastive_loss_type: str = 'siglip',
|
| 275 |
+
contrastive_embed_dim: int = 512
|
| 276 |
+
):
|
| 277 |
+
super().__init__()
|
| 278 |
+
self.dim = dim
|
| 279 |
+
self.use_perceiver = use_perceiver
|
| 280 |
+
self.use_contrastive = use_contrastive
|
| 281 |
+
|
| 282 |
+
# 模态投影器
|
| 283 |
+
self.modality_projectors = nn.ModuleDict({
|
| 284 |
+
'image': ModalityProjector(dim, dim),
|
| 285 |
+
'audio': ModalityProjector(dim, dim),
|
| 286 |
+
'video': ModalityProjector(dim, dim),
|
| 287 |
+
'text': ModalityProjector(dim, dim)
|
| 288 |
+
})
|
| 289 |
+
|
| 290 |
+
# 跨模态融合层
|
| 291 |
+
self.fusion_layers = nn.ModuleList([
|
| 292 |
+
CrossModalFusionLayer(
|
| 293 |
+
dim=dim,
|
| 294 |
+
n_heads=n_heads,
|
| 295 |
+
dropout=dropout,
|
| 296 |
+
use_adapter=True
|
| 297 |
+
)
|
| 298 |
+
for _ in range(num_fusion_layers)
|
| 299 |
+
])
|
| 300 |
+
|
| 301 |
+
# Perceiver Resampler
|
| 302 |
+
if use_perceiver:
|
| 303 |
+
self.perceiver = PerceiverResampler(
|
| 304 |
+
dim=dim,
|
| 305 |
+
depth=4,
|
| 306 |
+
num_latents=num_latents,
|
| 307 |
+
n_heads=n_heads,
|
| 308 |
+
dropout=dropout
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# 对比学习模块
|
| 312 |
+
if use_contrastive:
|
| 313 |
+
# 定义每个模态的输入维度和池化类型
|
| 314 |
+
modality_config = {
|
| 315 |
+
'text': 'cls',
|
| 316 |
+
'image': 'cls',
|
| 317 |
+
'audio': 'mean',
|
| 318 |
+
'video': 'mean'
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
input_dims = {k: dim for k in modality_config.keys()}
|
| 322 |
+
|
| 323 |
+
self.contrastive_module = MultiModalContrastiveLoss(
|
| 324 |
+
embed_dim=contrastive_embed_dim,
|
| 325 |
+
input_dims=input_dims,
|
| 326 |
+
temperature=0.07,
|
| 327 |
+
loss_type=contrastive_loss_type,
|
| 328 |
+
modality_config=modality_config
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
self.final_norm = RMSNorm(dim)
|
| 332 |
+
|
| 333 |
+
def _pool_features(self, features: torch.Tensor) -> torch.Tensor:
|
| 334 |
+
"""池化特征到单一向量 [B, T, D] -> [B, D]"""
|
| 335 |
+
if features.dim() == 3:
|
| 336 |
+
return features.mean(dim=1)
|
| 337 |
+
return features
|
| 338 |
+
|
| 339 |
+
def forward(
|
| 340 |
+
self,
|
| 341 |
+
segments: List[Dict],
|
| 342 |
+
compute_contrastive: bool = False
|
| 343 |
+
) -> Dict:
|
| 344 |
+
# 分离不同模态
|
| 345 |
+
modality_features = {}
|
| 346 |
+
modality_ids = {}
|
| 347 |
+
|
| 348 |
+
for seg in segments:
|
| 349 |
+
mod_type = seg['type']
|
| 350 |
+
mod_data = seg['data']
|
| 351 |
+
mod_id = seg['modality_id']
|
| 352 |
+
|
| 353 |
+
# 检查数据维度
|
| 354 |
+
if mod_data.dim() != 3:
|
| 355 |
+
raise ValueError(
|
| 356 |
+
f"Expected 3D tensor [B, T, D] for modality {mod_type}, "
|
| 357 |
+
f"got shape {mod_data.shape}"
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
# 投影到统一空间
|
| 361 |
+
if mod_type in self.modality_projectors:
|
| 362 |
+
projected = self.modality_projectors[mod_type](mod_data)
|
| 363 |
+
else:
|
| 364 |
+
projected = mod_data
|
| 365 |
+
|
| 366 |
+
# 使用Perceiver压缩(可选,非text模态)
|
| 367 |
+
if self.use_perceiver and mod_type != 'text':
|
| 368 |
+
projected = self.perceiver(projected)
|
| 369 |
+
|
| 370 |
+
modality_features[mod_type] = projected
|
| 371 |
+
modality_ids[mod_type] = mod_id
|
| 372 |
+
|
| 373 |
+
# 跨模态融合
|
| 374 |
+
fused_features = {}
|
| 375 |
+
|
| 376 |
+
for mod_type, features in modality_features.items():
|
| 377 |
+
# 创建不包含当前模态的上下文
|
| 378 |
+
if len(modality_features) > 1:
|
| 379 |
+
other_features = torch.cat([
|
| 380 |
+
f for k, f in modality_features.items() if k != mod_type
|
| 381 |
+
], dim=1)
|
| 382 |
+
else:
|
| 383 |
+
other_features = None
|
| 384 |
+
|
| 385 |
+
# 通过融合层
|
| 386 |
+
fused = features
|
| 387 |
+
for layer in self.fusion_layers:
|
| 388 |
+
fused = layer(
|
| 389 |
+
fused,
|
| 390 |
+
context=other_features,
|
| 391 |
+
modality_id=modality_ids[mod_type]
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
fused_features[mod_type] = self.final_norm(fused)
|
| 395 |
+
|
| 396 |
+
# 计算对比学习损失(如果需要)
|
| 397 |
+
contrastive_losses = {}
|
| 398 |
+
if compute_contrastive and self.use_contrastive:
|
| 399 |
+
pooled_features = fused_features
|
| 400 |
+
|
| 401 |
+
# 定义需要对比的模态对
|
| 402 |
+
modality_pairs = []
|
| 403 |
+
if 'text' in pooled_features:
|
| 404 |
+
for mod in pooled_features.keys():
|
| 405 |
+
if mod != 'text':
|
| 406 |
+
modality_pairs.append((mod, 'text'))
|
| 407 |
+
|
| 408 |
+
# 调用对比学习模块
|
| 409 |
+
if modality_pairs:
|
| 410 |
+
contrastive_losses = self.contrastive_module(
|
| 411 |
+
pooled_features,
|
| 412 |
+
modality_pairs=modality_pairs
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
# 拼接所有融合后的特征
|
| 416 |
+
fused_sequence = torch.cat(list(fused_features.values()), dim=1)
|
| 417 |
+
|
| 418 |
+
return {
|
| 419 |
+
'fused_features': fused_sequence,
|
| 420 |
+
'modality_features': fused_features,
|
| 421 |
+
'contrastive_losses': contrastive_losses
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
class EarlyFusionModule(nn.Module):
|
| 426 |
+
"""早期融合 - 在浅层就融合模态"""
|
| 427 |
+
def __init__(self, dim: int = 2048):
|
| 428 |
+
super().__init__()
|
| 429 |
+
self.fusion_proj = nn.Linear(dim, dim)
|
| 430 |
+
self.norm = RMSNorm(dim)
|
| 431 |
+
|
| 432 |
+
def forward(self, segments: List[Dict]) -> torch.Tensor:
|
| 433 |
+
"""简单拼接所有模态"""
|
| 434 |
+
all_features = [seg['data'] for seg in segments]
|
| 435 |
+
fused = torch.cat(all_features, dim=1)
|
| 436 |
+
fused = self.fusion_proj(fused)
|
| 437 |
+
return self.norm(fused)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
class LateFusionModule(nn.Module):
|
| 441 |
+
"""晚期融合 - 在深层才融合模态"""
|
| 442 |
+
def __init__(
|
| 443 |
+
self,
|
| 444 |
+
dim: int = 2048,
|
| 445 |
+
num_modalities: int = 4,
|
| 446 |
+
fusion_method: str = 'concat' # 'concat', 'attention', 'average'
|
| 447 |
+
):
|
| 448 |
+
super().__init__()
|
| 449 |
+
self.fusion_method = fusion_method
|
| 450 |
+
|
| 451 |
+
if fusion_method == 'concat':
|
| 452 |
+
self.fusion_proj = nn.Linear(dim * num_modalities, dim)
|
| 453 |
+
elif fusion_method == 'attention':
|
| 454 |
+
self.attention_weights = nn.Linear(dim, 1)
|
| 455 |
+
|
| 456 |
+
self.norm = RMSNorm(dim)
|
| 457 |
+
|
| 458 |
+
def forward(self, modality_outputs: List[torch.Tensor]) -> torch.Tensor:
|
| 459 |
+
if self.fusion_method == 'concat':
|
| 460 |
+
# 拼接并投影
|
| 461 |
+
pooled = [x.mean(dim=1) for x in modality_outputs]
|
| 462 |
+
fused = torch.cat(pooled, dim=-1)
|
| 463 |
+
fused = self.fusion_proj(fused)
|
| 464 |
+
|
| 465 |
+
elif self.fusion_method == 'attention':
|
| 466 |
+
# 注意力加权
|
| 467 |
+
stacked = torch.stack([x.mean(dim=1) for x in modality_outputs], dim=1)
|
| 468 |
+
weights = F.softmax(self.attention_weights(stacked), dim=1)
|
| 469 |
+
fused = (stacked * weights).sum(dim=1)
|
| 470 |
+
|
| 471 |
+
else: # average
|
| 472 |
+
stacked = torch.stack([x.mean(dim=1) for x in modality_outputs], dim=1)
|
| 473 |
+
fused = stacked.mean(dim=1)
|
| 474 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
return self.norm(fused)
|