Update model.py
Browse files
model.py
CHANGED
|
@@ -1,505 +1,489 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
import
|
| 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 |
-
self.
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
self.
|
| 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 |
-
dim=model_dim,
|
| 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 |
-
input_data:
|
| 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 |
-
if
|
| 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 |
-
else
|
| 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 |
-
attn_weights
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
if
|
| 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 |
-
self
|
| 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 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
if
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 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 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
initial_text_tokens = torch.cat([initial_text_tokens, next_token], dim=1)
|
| 490 |
-
current_tokens = initial_text_tokens
|
| 491 |
-
else:
|
| 492 |
-
current_tokens = next_token
|
| 493 |
-
|
| 494 |
-
# Update unfinished sequences
|
| 495 |
-
unfinished_sequences = unfinished_sequences.mul(
|
| 496 |
-
(next_token.squeeze(-1) != eos_token_id).long()
|
| 497 |
-
)
|
| 498 |
-
|
| 499 |
-
if unfinished_sequences.max() == 0:
|
| 500 |
-
break
|
| 501 |
-
|
| 502 |
-
if not generated_tokens:
|
| 503 |
-
return torch.empty(batch_size, 0, dtype=torch.long, device=device)
|
| 504 |
-
|
| 505 |
return torch.cat(generated_tokens, dim=1)
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from typing import List, Dict, Optional, Tuple
|
| 5 |
+
import math
|
| 6 |
+
from components import RMSNorm
|
| 7 |
+
from transformer import OptimizedTransformerBlock
|
| 8 |
+
from multimodel_fusion import MultiModalFusionModule
|
| 9 |
+
from encoders import (
|
| 10 |
+
ImprovedVisionTransformer,
|
| 11 |
+
ImprovedAudioEncoder,
|
| 12 |
+
ImprovedVideoEncoder
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
class MultiModalDenseTransformer(nn.Module):
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
model_dim: int = 2048,
|
| 19 |
+
vocab_size: int = 30000,
|
| 20 |
+
n_layers: int = 48,
|
| 21 |
+
n_heads: int = 32,
|
| 22 |
+
n_kv_heads: Optional[int] = None,
|
| 23 |
+
head_dim: Optional[int] = None,
|
| 24 |
+
max_seq_len: int = 8192,
|
| 25 |
+
dropout: float = 0.0,
|
| 26 |
+
attn_dropout: float = 0.0,
|
| 27 |
+
|
| 28 |
+
# MoE配置
|
| 29 |
+
use_moe: bool = False,
|
| 30 |
+
num_experts: int = 8,
|
| 31 |
+
moe_top_k: int = 2,
|
| 32 |
+
moe_layers: Optional[List[int]] = None,
|
| 33 |
+
|
| 34 |
+
# PEFT配置
|
| 35 |
+
use_adapter: bool = False,
|
| 36 |
+
adapter_dim: int = 64,
|
| 37 |
+
use_lora: bool = False,
|
| 38 |
+
lora_rank: int = 8,
|
| 39 |
+
|
| 40 |
+
# 训练配置
|
| 41 |
+
use_gradient_checkpointing: bool = False,
|
| 42 |
+
use_parallel_residual: bool = False,
|
| 43 |
+
|
| 44 |
+
# 位置编码
|
| 45 |
+
rope_scaling_factor: float = 1.0,
|
| 46 |
+
rope_scaling_type: str = "yarn",
|
| 47 |
+
sliding_window: Optional[int] = None,
|
| 48 |
+
|
| 49 |
+
# 规范化
|
| 50 |
+
norm_eps: float = 1e-6,
|
| 51 |
+
initializer_range: float = 0.02,
|
| 52 |
+
ffn_dim_multiplier: Optional[float] = None,
|
| 53 |
+
tie_word_embeddings: bool = True,
|
| 54 |
+
|
| 55 |
+
# 多模态配置
|
| 56 |
+
use_multimodal_fusion: bool = True,
|
| 57 |
+
fusion_layers: int = 4,
|
| 58 |
+
use_contrastive: bool = True,
|
| 59 |
+
vision_depth: int = 24,
|
| 60 |
+
audio_depth: int = 12,
|
| 61 |
+
video_spatial_depth: int = 12,
|
| 62 |
+
video_temporal_depth: int = 4
|
| 63 |
+
):
|
| 64 |
+
super().__init__()
|
| 65 |
+
|
| 66 |
+
self.model_dim = model_dim
|
| 67 |
+
self.vocab_size = vocab_size
|
| 68 |
+
self.n_layers = n_layers
|
| 69 |
+
self.max_seq_len = max_seq_len
|
| 70 |
+
self.use_gradient_checkpointing = use_gradient_checkpointing
|
| 71 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 72 |
+
self.use_multimodal_fusion = use_multimodal_fusion
|
| 73 |
+
|
| 74 |
+
# Token embedding
|
| 75 |
+
self.token_embedding = nn.Embedding(vocab_size, model_dim)
|
| 76 |
+
self.modality_embedding = nn.Embedding(4, model_dim)
|
| 77 |
+
self.embed_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
|
| 78 |
+
|
| 79 |
+
self.vision_encoder = ImprovedVisionTransformer(
|
| 80 |
+
embed_dim=model_dim,
|
| 81 |
+
depth=vision_depth,
|
| 82 |
+
n_heads=n_heads,
|
| 83 |
+
dropout=dropout,
|
| 84 |
+
use_adapter=use_adapter,
|
| 85 |
+
adapter_dim=adapter_dim
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
self.audio_encoder = ImprovedAudioEncoder(
|
| 89 |
+
embed_dim=model_dim,
|
| 90 |
+
depth=audio_depth,
|
| 91 |
+
n_heads=n_heads,
|
| 92 |
+
dropout=dropout,
|
| 93 |
+
use_adapter=use_adapter,
|
| 94 |
+
adapter_dim=adapter_dim
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
self.video_encoder = ImprovedVideoEncoder(
|
| 98 |
+
embed_dim=model_dim,
|
| 99 |
+
spatial_depth=video_spatial_depth,
|
| 100 |
+
temporal_depth=video_temporal_depth,
|
| 101 |
+
n_heads=n_heads,
|
| 102 |
+
dropout=dropout,
|
| 103 |
+
use_adapter=use_adapter,
|
| 104 |
+
adapter_dim=adapter_dim
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# 多模态融合模块
|
| 108 |
+
if use_multimodal_fusion:
|
| 109 |
+
self.fusion_module = MultiModalFusionModule(
|
| 110 |
+
dim=model_dim,
|
| 111 |
+
num_fusion_layers=fusion_layers,
|
| 112 |
+
n_heads=n_heads,
|
| 113 |
+
dropout=dropout,
|
| 114 |
+
use_contrastive=use_contrastive
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
if moe_layers is None and use_moe:
|
| 118 |
+
moe_layers = list(range(n_layers // 2, n_layers))
|
| 119 |
+
elif moe_layers is None:
|
| 120 |
+
moe_layers = []
|
| 121 |
+
|
| 122 |
+
self.layers = nn.ModuleList([
|
| 123 |
+
OptimizedTransformerBlock(
|
| 124 |
+
dim=model_dim,
|
| 125 |
+
n_heads=n_heads,
|
| 126 |
+
n_kv_heads=n_kv_heads,
|
| 127 |
+
head_dim=head_dim,
|
| 128 |
+
dropout=dropout,
|
| 129 |
+
attn_dropout=attn_dropout,
|
| 130 |
+
use_moe=(use_moe and i in moe_layers),
|
| 131 |
+
num_experts=num_experts,
|
| 132 |
+
moe_top_k=moe_top_k,
|
| 133 |
+
use_adapter=use_adapter,
|
| 134 |
+
adapter_dim=adapter_dim,
|
| 135 |
+
use_lora=use_lora,
|
| 136 |
+
lora_rank=lora_rank,
|
| 137 |
+
use_parallel_residual=use_parallel_residual,
|
| 138 |
+
norm_eps=norm_eps,
|
| 139 |
+
sliding_window=sliding_window,
|
| 140 |
+
ffn_dim_multiplier=ffn_dim_multiplier,
|
| 141 |
+
layer_idx=i
|
| 142 |
+
)
|
| 143 |
+
for i in range(n_layers)
|
| 144 |
+
])
|
| 145 |
+
|
| 146 |
+
self.norm = RMSNorm(model_dim, eps=norm_eps)
|
| 147 |
+
self.lm_head = nn.Linear(model_dim, vocab_size, bias=False)
|
| 148 |
+
|
| 149 |
+
if tie_word_embeddings:
|
| 150 |
+
self.lm_head.weight = self.token_embedding.weight
|
| 151 |
+
|
| 152 |
+
self.initializer_range = initializer_range
|
| 153 |
+
self.apply(self._init_weights)
|
| 154 |
+
|
| 155 |
+
if not tie_word_embeddings:
|
| 156 |
+
self._init_lm_head()
|
| 157 |
+
|
| 158 |
+
self.n_params = sum(p.numel() for p in self.parameters())
|
| 159 |
+
trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
|
| 160 |
+
|
| 161 |
+
print(f"\n{'='*80}")
|
| 162 |
+
print(f"Improved Model Configuration:")
|
| 163 |
+
print(f" Model Dimension: {model_dim}")
|
| 164 |
+
print(f" Vocab Size: {vocab_size}")
|
| 165 |
+
print(f" Layers: {n_layers}")
|
| 166 |
+
print(f" Attention Heads: {n_heads}")
|
| 167 |
+
print(f" KV Heads: {n_kv_heads if n_kv_heads else n_heads}")
|
| 168 |
+
print(f" Max Sequence Length: {max_seq_len}")
|
| 169 |
+
print(f" Multimodal Fusion: {use_multimodal_fusion}")
|
| 170 |
+
print(f" Contrastive Learning: {use_contrastive}")
|
| 171 |
+
print(f" MoE: {use_moe} (Experts: {num_experts}, Top-K: {moe_top_k})")
|
| 172 |
+
print(f" Total Parameters: {self.n_params / 1e9:.2f}B")
|
| 173 |
+
print(f" Trainable Parameters: {trainable_params / 1e9:.2f}B")
|
| 174 |
+
print(f"{'='*80}\n")
|
| 175 |
+
|
| 176 |
+
def _init_weights(self, module):
|
| 177 |
+
"""权重初始化"""
|
| 178 |
+
if isinstance(module, nn.Linear):
|
| 179 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=self.initializer_range)
|
| 180 |
+
if module.bias is not None:
|
| 181 |
+
torch.nn.init.zeros_(module.bias)
|
| 182 |
+
elif isinstance(module, nn.Embedding):
|
| 183 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=self.initializer_range)
|
| 184 |
+
if hasattr(module, 'padding_idx') and module.padding_idx is not None:
|
| 185 |
+
module.weight.data[module.padding_idx].zero_()
|
| 186 |
+
|
| 187 |
+
def _init_lm_head(self):
|
| 188 |
+
"""初始化LM head"""
|
| 189 |
+
std = self.initializer_range / math.sqrt(2 * self.n_layers)
|
| 190 |
+
torch.nn.init.normal_(self.lm_head.weight, mean=0.0, std=std)
|
| 191 |
+
|
| 192 |
+
def _encode_modality(self, segment: Dict) -> torch.Tensor:
|
| 193 |
+
"""编码单个模态"""
|
| 194 |
+
seg_type = segment['type']
|
| 195 |
+
seg_data = segment['data']
|
| 196 |
+
|
| 197 |
+
if seg_type == 'image':
|
| 198 |
+
return self.vision_encoder(seg_data)
|
| 199 |
+
elif seg_type == 'audio':
|
| 200 |
+
return self.audio_encoder(seg_data)
|
| 201 |
+
elif seg_type == 'video':
|
| 202 |
+
return self.video_encoder(seg_data)
|
| 203 |
+
elif seg_type == 'text':
|
| 204 |
+
return self.token_embedding(seg_data)
|
| 205 |
+
else:
|
| 206 |
+
return seg_data
|
| 207 |
+
|
| 208 |
+
def forward(
|
| 209 |
+
self,
|
| 210 |
+
input_data: Dict,
|
| 211 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 212 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 213 |
+
return_hidden: bool = False,
|
| 214 |
+
use_cache: bool = False,
|
| 215 |
+
past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
|
| 216 |
+
output_attentions: bool = False,
|
| 217 |
+
output_hidden_states: bool = False,
|
| 218 |
+
compute_contrastive: bool = False
|
| 219 |
+
) -> Dict:
|
| 220 |
+
"""前向传播"""
|
| 221 |
+
device = self.token_embedding.weight.device
|
| 222 |
+
|
| 223 |
+
# 编码每个模态
|
| 224 |
+
encoded_segments = []
|
| 225 |
+
for segment in input_data.get('segments', []):
|
| 226 |
+
encoded = self._encode_modality(segment)
|
| 227 |
+
|
| 228 |
+
# 添加模态嵌入
|
| 229 |
+
modality_id = segment.get('modality_id', 0)
|
| 230 |
+
modality_embeds = self.modality_embedding(
|
| 231 |
+
torch.tensor([modality_id], device=device)
|
| 232 |
+
).expand(encoded.shape[0], encoded.shape[1], -1)
|
| 233 |
+
|
| 234 |
+
encoded_segments.append({
|
| 235 |
+
'type': segment['type'],
|
| 236 |
+
'data': encoded + modality_embeds,
|
| 237 |
+
'modality_id': modality_id
|
| 238 |
+
})
|
| 239 |
+
|
| 240 |
+
# 多模态融合
|
| 241 |
+
contrastive_losses = {}
|
| 242 |
+
if self.use_multimodal_fusion and len(encoded_segments) > 1:
|
| 243 |
+
fusion_output = self.fusion_module(
|
| 244 |
+
encoded_segments,
|
| 245 |
+
compute_contrastive=compute_contrastive
|
| 246 |
+
)
|
| 247 |
+
x = fusion_output['fused_features']
|
| 248 |
+
contrastive_losses = fusion_output.get('contrastive_losses', {})
|
| 249 |
+
else:
|
| 250 |
+
# 简单拼接
|
| 251 |
+
all_embeddings = [seg['data'] for seg in encoded_segments]
|
| 252 |
+
x = torch.cat(all_embeddings, dim=1) if all_embeddings else torch.zeros(
|
| 253 |
+
1, 1, self.model_dim, device=device
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
x = self.embed_dropout(x)
|
| 257 |
+
if position_ids is None:
|
| 258 |
+
if past_key_values is not None:
|
| 259 |
+
# 缓存的长度 (KV cache 的 shape 是 [B, H, SeqLen, D])
|
| 260 |
+
past_length = past_key_values[0][0].size(2)
|
| 261 |
+
# 当前输入的长度
|
| 262 |
+
seq_length = x.shape[1]
|
| 263 |
+
# 生成正确的位置索引: [past_length, past_length + 1, ...]
|
| 264 |
+
position_ids = torch.arange(
|
| 265 |
+
past_length, past_length + seq_length, dtype=torch.long, device=device
|
| 266 |
+
).unsqueeze(0).expand(x.shape[0], -1)
|
| 267 |
+
else:
|
| 268 |
+
# 如果没有缓存,从 0 开始
|
| 269 |
+
seq_length = x.shape[1]
|
| 270 |
+
position_ids = torch.arange(
|
| 271 |
+
0, seq_length, dtype=torch.long, device=device
|
| 272 |
+
).unsqueeze(0).expand(x.shape[0], -1)
|
| 273 |
+
# Transformer层
|
| 274 |
+
present_key_values = [] if use_cache else None
|
| 275 |
+
all_hidden_states = [] if output_hidden_states else None
|
| 276 |
+
all_attentions = [] if output_attentions else None
|
| 277 |
+
moe_aux_loss = torch.tensor(0.0, device=device)
|
| 278 |
+
|
| 279 |
+
for idx, layer in enumerate(self.layers):
|
| 280 |
+
if output_hidden_states:
|
| 281 |
+
all_hidden_states.append(x)
|
| 282 |
+
|
| 283 |
+
past_kv = past_key_values[idx] if past_key_values is not None else None
|
| 284 |
+
|
| 285 |
+
if self.use_gradient_checkpointing and self.training:
|
| 286 |
+
def create_custom_forward(module):
|
| 287 |
+
def custom_forward(*inputs):
|
| 288 |
+
return module(
|
| 289 |
+
inputs[0],
|
| 290 |
+
attention_mask=inputs[1],
|
| 291 |
+
position_ids=inputs[2],
|
| 292 |
+
use_cache=False,
|
| 293 |
+
past_kv=None,
|
| 294 |
+
output_attentions=False
|
| 295 |
+
)
|
| 296 |
+
return custom_forward
|
| 297 |
+
|
| 298 |
+
import torch.utils.checkpoint as checkpoint
|
| 299 |
+
layer_outputs = checkpoint.checkpoint(
|
| 300 |
+
create_custom_forward(layer),
|
| 301 |
+
x,
|
| 302 |
+
attention_mask,
|
| 303 |
+
position_ids,
|
| 304 |
+
use_reentrant=False
|
| 305 |
+
)
|
| 306 |
+
x = layer_outputs[0]
|
| 307 |
+
present_kv = None
|
| 308 |
+
attn_weights = None
|
| 309 |
+
else:
|
| 310 |
+
layer_outputs = layer(
|
| 311 |
+
x,
|
| 312 |
+
attention_mask=attention_mask,
|
| 313 |
+
position_ids=position_ids,
|
| 314 |
+
use_cache=use_cache,
|
| 315 |
+
past_kv=past_kv,
|
| 316 |
+
output_attentions=output_attentions
|
| 317 |
+
)
|
| 318 |
+
x, present_kv, attn_weights = layer_outputs
|
| 319 |
+
|
| 320 |
+
if use_cache:
|
| 321 |
+
present_key_values.append(present_kv)
|
| 322 |
+
|
| 323 |
+
if output_attentions:
|
| 324 |
+
all_attentions.append(attn_weights)
|
| 325 |
+
|
| 326 |
+
if hasattr(layer, 'moe_aux_loss'):
|
| 327 |
+
moe_aux_loss += layer.moe_aux_loss
|
| 328 |
+
|
| 329 |
+
hidden_states = self.norm(x)
|
| 330 |
+
logits = self.lm_head(hidden_states)
|
| 331 |
+
|
| 332 |
+
if output_hidden_states:
|
| 333 |
+
all_hidden_states.append(hidden_states)
|
| 334 |
+
|
| 335 |
+
# 组装输出
|
| 336 |
+
outputs = {
|
| 337 |
+
'logits': logits,
|
| 338 |
+
'moe_aux_loss': moe_aux_loss,
|
| 339 |
+
'contrastive_losses': contrastive_losses
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
if use_cache:
|
| 343 |
+
outputs['past_key_values'] = present_key_values
|
| 344 |
+
|
| 345 |
+
if output_hidden_states:
|
| 346 |
+
outputs['hidden_states'] = all_hidden_states
|
| 347 |
+
|
| 348 |
+
if output_attentions:
|
| 349 |
+
outputs['attentions'] = all_attentions
|
| 350 |
+
|
| 351 |
+
if return_hidden:
|
| 352 |
+
outputs['last_hidden_state'] = hidden_states
|
| 353 |
+
|
| 354 |
+
return outputs
|
| 355 |
+
|
| 356 |
+
@torch.no_grad()
|
| 357 |
+
def generate(
|
| 358 |
+
self,
|
| 359 |
+
input_data: Dict,
|
| 360 |
+
max_new_tokens: int = 100,
|
| 361 |
+
temperature: float = 1.0,
|
| 362 |
+
top_k: int = 50,
|
| 363 |
+
top_p: float = 0.9,
|
| 364 |
+
eos_token_id: int = 2,
|
| 365 |
+
pad_token_id: Optional[int] = None,
|
| 366 |
+
use_cache: bool = True,
|
| 367 |
+
repetition_penalty: float = 1.0,
|
| 368 |
+
length_penalty: float = 1.0,
|
| 369 |
+
min_length: int = 0,
|
| 370 |
+
do_sample: bool = True,
|
| 371 |
+
num_beams: int = 1
|
| 372 |
+
) -> torch.Tensor:
|
| 373 |
+
"""改进的生成方法"""
|
| 374 |
+
self.eval()
|
| 375 |
+
device = next(self.parameters()).device
|
| 376 |
+
|
| 377 |
+
if pad_token_id is None:
|
| 378 |
+
pad_token_id = eos_token_id
|
| 379 |
+
|
| 380 |
+
initial_text_tokens = input_data['segments'][0]['data'].to(device)
|
| 381 |
+
batch_size = initial_text_tokens.shape[0]
|
| 382 |
+
|
| 383 |
+
if 'attention_mask' in input_data:
|
| 384 |
+
attention_mask = input_data['attention_mask'].to(device)
|
| 385 |
+
else:
|
| 386 |
+
attention_mask = torch.ones_like(initial_text_tokens)
|
| 387 |
+
initial_seq_len = initial_text_tokens.shape[1]
|
| 388 |
+
position_ids = torch.zeros((batch_size,initial_seq_len),dtype=torch.long,device=device)
|
| 389 |
+
|
| 390 |
+
for i in range(batch_size):
|
| 391 |
+
non_pad_mask = attention_mask[i].bool()
|
| 392 |
+
if non_pad_mask.any():
|
| 393 |
+
positions = torch.cumsum(non_pad_mask.long(),dim=0) -1
|
| 394 |
+
position_ids[i]=positions * non_pad_mask.long()
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
generated_tokens = []
|
| 399 |
+
past_key_values = None
|
| 400 |
+
current_tokens = initial_text_tokens
|
| 401 |
+
unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=device)
|
| 402 |
+
|
| 403 |
+
for step in range(max_new_tokens):
|
| 404 |
+
current_input_data = {
|
| 405 |
+
'segments': [{'type': 'text', 'data': current_tokens, 'modality_id': 0}]
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
if step > 0 and use_cache:
|
| 409 |
+
# 添加当前 token 的 mask (1)
|
| 410 |
+
new_mask = torch.ones(batch_size,1,dtype=torch.long,device=device)
|
| 411 |
+
attention_mask = torch.cat([attention_mask, new_mask], dim=1)
|
| 412 |
+
current_positions = (attention_mask.sum(dim=1 , keepdim=True) -1).clamp(min=0)
|
| 413 |
+
current_positions_ids=current_positions
|
| 414 |
+
else:
|
| 415 |
+
current_positions_ids=position_ids
|
| 416 |
+
outputs = self.forward(
|
| 417 |
+
current_input_data,
|
| 418 |
+
attention_mask=attention_mask, # <--- 传入 Mask
|
| 419 |
+
position_ids=current_positions_ids,
|
| 420 |
+
use_cache=use_cache,
|
| 421 |
+
past_key_values=past_key_values
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
logits = outputs['logits']
|
| 425 |
+
if use_cache:
|
| 426 |
+
past_key_values = outputs['past_key_values']
|
| 427 |
+
|
| 428 |
+
next_token_logits = logits[:, -1, :] / max(temperature, 1e-5)
|
| 429 |
+
|
| 430 |
+
# Repetition penalty
|
| 431 |
+
if repetition_penalty != 1.0 and len(generated_tokens) > 0:
|
| 432 |
+
prev_generated = torch.cat(generated_tokens, dim=1)
|
| 433 |
+
score = torch.gather(next_token_logits, 1, prev_generated)
|
| 434 |
+
score = torch.where(
|
| 435 |
+
score < 0,
|
| 436 |
+
score * repetition_penalty,
|
| 437 |
+
score / repetition_penalty
|
| 438 |
+
)
|
| 439 |
+
next_token_logits.scatter_(1, prev_generated, score)
|
| 440 |
+
|
| 441 |
+
# Min length constraint
|
| 442 |
+
if step < min_length:
|
| 443 |
+
next_token_logits[:, eos_token_id] = float('-inf')
|
| 444 |
+
|
| 445 |
+
# Sampling
|
| 446 |
+
if do_sample:
|
| 447 |
+
if top_k > 0:
|
| 448 |
+
top_k_vals, _ = torch.topk(next_token_logits, top_k)
|
| 449 |
+
min_val_to_keep = top_k_vals[:, -1].unsqueeze(-1)
|
| 450 |
+
next_token_logits[next_token_logits < min_val_to_keep] = float('-inf')
|
| 451 |
+
|
| 452 |
+
if top_p < 1.0:
|
| 453 |
+
sorted_logits, sorted_indices = torch.sort(next_token_logits, descending=True)
|
| 454 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 455 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 456 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 457 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 458 |
+
indices_to_remove = torch.zeros_like(next_token_logits, dtype=torch.bool)
|
| 459 |
+
indices_to_remove.scatter_(1, sorted_indices, sorted_indices_to_remove)
|
| 460 |
+
next_token_logits[indices_to_remove] = float('-inf')
|
| 461 |
+
|
| 462 |
+
probs = F.softmax(next_token_logits, dim=-1)
|
| 463 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 464 |
+
else:
|
| 465 |
+
next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
|
| 466 |
+
|
| 467 |
+
# Apply unfinished mask
|
| 468 |
+
next_token = next_token * unfinished_sequences[:, None] + pad_token_id * (1 - unfinished_sequences[:, None])
|
| 469 |
+
|
| 470 |
+
generated_tokens.append(next_token)
|
| 471 |
+
|
| 472 |
+
if not use_cache:
|
| 473 |
+
initial_text_tokens = torch.cat([initial_text_tokens, next_token], dim=1)
|
| 474 |
+
current_tokens = initial_text_tokens
|
| 475 |
+
else:
|
| 476 |
+
current_tokens = next_token
|
| 477 |
+
|
| 478 |
+
# Update unfinished sequences
|
| 479 |
+
unfinished_sequences = unfinished_sequences.mul(
|
| 480 |
+
(next_token.squeeze(-1) != eos_token_id).long()
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
if unfinished_sequences.max() == 0:
|
| 484 |
+
break
|
| 485 |
+
|
| 486 |
+
if not generated_tokens:
|
| 487 |
+
return torch.empty(batch_size, 0, dtype=torch.long, device=device)
|
| 488 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
return torch.cat(generated_tokens, dim=1)
|