Update model.py
Browse files
model.py
CHANGED
|
@@ -13,6 +13,7 @@ from encoders import (
|
|
| 13 |
)
|
| 14 |
|
| 15 |
class MultiModalDenseTransformer(nn.Module):
|
|
|
|
| 16 |
def __init__(
|
| 17 |
self,
|
| 18 |
model_dim: int = 2048,
|
|
@@ -25,37 +26,31 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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 =
|
| 59 |
vision_depth: int = 24,
|
| 60 |
audio_depth: int = 12,
|
| 61 |
video_spatial_depth: int = 12,
|
|
@@ -71,7 +66,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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()
|
|
@@ -104,7 +98,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 104 |
adapter_dim=adapter_dim
|
| 105 |
)
|
| 106 |
|
| 107 |
-
# 多模态融合模块
|
| 108 |
if use_multimodal_fusion:
|
| 109 |
self.fusion_module = MultiModalFusionModule(
|
| 110 |
dim=model_dim,
|
|
@@ -157,24 +150,8 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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:
|
|
@@ -185,12 +162,10 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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 |
|
|
@@ -217,15 +192,11 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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)
|
|
@@ -237,7 +208,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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(
|
|
@@ -247,7 +217,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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
|
|
@@ -256,21 +225,16 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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
|
|
@@ -332,7 +296,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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,
|
|
@@ -370,7 +333,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 370 |
do_sample: bool = True,
|
| 371 |
num_beams: int = 1
|
| 372 |
) -> torch.Tensor:
|
| 373 |
-
"""改进的生成方法"""
|
| 374 |
self.eval()
|
| 375 |
device = next(self.parameters()).device
|
| 376 |
|
|
@@ -406,7 +368,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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)
|
|
@@ -415,7 +376,7 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 415 |
current_positions_ids=position_ids
|
| 416 |
outputs = self.forward(
|
| 417 |
current_input_data,
|
| 418 |
-
attention_mask=attention_mask,
|
| 419 |
position_ids=current_positions_ids,
|
| 420 |
use_cache=use_cache,
|
| 421 |
past_key_values=past_key_values
|
|
@@ -427,7 +388,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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)
|
|
@@ -438,11 +398,9 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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)
|
|
@@ -464,7 +422,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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)
|
|
@@ -475,7 +432,6 @@ class MultiModalDenseTransformer(nn.Module):
|
|
| 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 |
)
|
|
|
|
| 13 |
)
|
| 14 |
|
| 15 |
class MultiModalDenseTransformer(nn.Module):
|
| 16 |
+
|
| 17 |
def __init__(
|
| 18 |
self,
|
| 19 |
model_dim: int = 2048,
|
|
|
|
| 26 |
dropout: float = 0.0,
|
| 27 |
attn_dropout: float = 0.0,
|
| 28 |
|
|
|
|
| 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 |
use_adapter: bool = False,
|
| 35 |
adapter_dim: int = 64,
|
| 36 |
use_lora: bool = False,
|
| 37 |
lora_rank: int = 8,
|
| 38 |
|
|
|
|
| 39 |
use_gradient_checkpointing: bool = False,
|
| 40 |
use_parallel_residual: bool = False,
|
| 41 |
|
|
|
|
| 42 |
rope_scaling_factor: float = 1.0,
|
| 43 |
rope_scaling_type: str = "yarn",
|
| 44 |
sliding_window: Optional[int] = None,
|
| 45 |
|
|
|
|
| 46 |
norm_eps: float = 1e-6,
|
| 47 |
initializer_range: float = 0.02,
|
| 48 |
ffn_dim_multiplier: Optional[float] = None,
|
| 49 |
tie_word_embeddings: bool = True,
|
| 50 |
|
| 51 |
+
use_multimodal_fusion: bool = False,
|
|
|
|
| 52 |
fusion_layers: int = 4,
|
| 53 |
+
use_contrastive: bool = False,
|
| 54 |
vision_depth: int = 24,
|
| 55 |
audio_depth: int = 12,
|
| 56 |
video_spatial_depth: int = 12,
|
|
|
|
| 66 |
self.tie_word_embeddings = tie_word_embeddings
|
| 67 |
self.use_multimodal_fusion = use_multimodal_fusion
|
| 68 |
|
|
|
|
| 69 |
self.token_embedding = nn.Embedding(vocab_size, model_dim)
|
| 70 |
self.modality_embedding = nn.Embedding(4, model_dim)
|
| 71 |
self.embed_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
|
|
|
|
| 98 |
adapter_dim=adapter_dim
|
| 99 |
)
|
| 100 |
|
|
|
|
| 101 |
if use_multimodal_fusion:
|
| 102 |
self.fusion_module = MultiModalFusionModule(
|
| 103 |
dim=model_dim,
|
|
|
|
| 150 |
|
| 151 |
self.n_params = sum(p.numel() for p in self.parameters())
|
| 152 |
trainable_params = sum(p.numel() for p in self.parameters() if p.requires_grad)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
def _init_weights(self, module):
|
|
|
|
| 155 |
if isinstance(module, nn.Linear):
|
| 156 |
torch.nn.init.normal_(module.weight, mean=0.0, std=self.initializer_range)
|
| 157 |
if module.bias is not None:
|
|
|
|
| 162 |
module.weight.data[module.padding_idx].zero_()
|
| 163 |
|
| 164 |
def _init_lm_head(self):
|
|
|
|
| 165 |
std = self.initializer_range / math.sqrt(2 * self.n_layers)
|
| 166 |
torch.nn.init.normal_(self.lm_head.weight, mean=0.0, std=std)
|
| 167 |
|
| 168 |
def _encode_modality(self, segment: Dict) -> torch.Tensor:
|
|
|
|
| 169 |
seg_type = segment['type']
|
| 170 |
seg_data = segment['data']
|
| 171 |
|
|
|
|
| 192 |
output_hidden_states: bool = False,
|
| 193 |
compute_contrastive: bool = False
|
| 194 |
) -> Dict:
|
|
|
|
| 195 |
device = self.token_embedding.weight.device
|
| 196 |
|
|
|
|
| 197 |
encoded_segments = []
|
| 198 |
for segment in input_data.get('segments', []):
|
| 199 |
encoded = self._encode_modality(segment)
|
|
|
|
|
|
|
| 200 |
modality_id = segment.get('modality_id', 0)
|
| 201 |
modality_embeds = self.modality_embedding(
|
| 202 |
torch.tensor([modality_id], device=device)
|
|
|
|
| 208 |
'modality_id': modality_id
|
| 209 |
})
|
| 210 |
|
|
|
|
| 211 |
contrastive_losses = {}
|
| 212 |
if self.use_multimodal_fusion and len(encoded_segments) > 1:
|
| 213 |
fusion_output = self.fusion_module(
|
|
|
|
| 217 |
x = fusion_output['fused_features']
|
| 218 |
contrastive_losses = fusion_output.get('contrastive_losses', {})
|
| 219 |
else:
|
|
|
|
| 220 |
all_embeddings = [seg['data'] for seg in encoded_segments]
|
| 221 |
x = torch.cat(all_embeddings, dim=1) if all_embeddings else torch.zeros(
|
| 222 |
1, 1, self.model_dim, device=device
|
|
|
|
| 225 |
x = self.embed_dropout(x)
|
| 226 |
if position_ids is None:
|
| 227 |
if past_key_values is not None:
|
|
|
|
| 228 |
past_length = past_key_values[0][0].size(2)
|
|
|
|
| 229 |
seq_length = x.shape[1]
|
|
|
|
| 230 |
position_ids = torch.arange(
|
| 231 |
past_length, past_length + seq_length, dtype=torch.long, device=device
|
| 232 |
).unsqueeze(0).expand(x.shape[0], -1)
|
| 233 |
else:
|
|
|
|
| 234 |
seq_length = x.shape[1]
|
| 235 |
position_ids = torch.arange(
|
| 236 |
0, seq_length, dtype=torch.long, device=device
|
| 237 |
).unsqueeze(0).expand(x.shape[0], -1)
|
|
|
|
| 238 |
present_key_values = [] if use_cache else None
|
| 239 |
all_hidden_states = [] if output_hidden_states else None
|
| 240 |
all_attentions = [] if output_attentions else None
|
|
|
|
| 296 |
if output_hidden_states:
|
| 297 |
all_hidden_states.append(hidden_states)
|
| 298 |
|
|
|
|
| 299 |
outputs = {
|
| 300 |
'logits': logits,
|
| 301 |
'moe_aux_loss': moe_aux_loss,
|
|
|
|
| 333 |
do_sample: bool = True,
|
| 334 |
num_beams: int = 1
|
| 335 |
) -> torch.Tensor:
|
|
|
|
| 336 |
self.eval()
|
| 337 |
device = next(self.parameters()).device
|
| 338 |
|
|
|
|
| 368 |
}
|
| 369 |
|
| 370 |
if step > 0 and use_cache:
|
|
|
|
| 371 |
new_mask = torch.ones(batch_size,1,dtype=torch.long,device=device)
|
| 372 |
attention_mask = torch.cat([attention_mask, new_mask], dim=1)
|
| 373 |
current_positions = (attention_mask.sum(dim=1 , keepdim=True) -1).clamp(min=0)
|
|
|
|
| 376 |
current_positions_ids=position_ids
|
| 377 |
outputs = self.forward(
|
| 378 |
current_input_data,
|
| 379 |
+
attention_mask=attention_mask,
|
| 380 |
position_ids=current_positions_ids,
|
| 381 |
use_cache=use_cache,
|
| 382 |
past_key_values=past_key_values
|
|
|
|
| 388 |
|
| 389 |
next_token_logits = logits[:, -1, :] / max(temperature, 1e-5)
|
| 390 |
|
|
|
|
| 391 |
if repetition_penalty != 1.0 and len(generated_tokens) > 0:
|
| 392 |
prev_generated = torch.cat(generated_tokens, dim=1)
|
| 393 |
score = torch.gather(next_token_logits, 1, prev_generated)
|
|
|
|
| 398 |
)
|
| 399 |
next_token_logits.scatter_(1, prev_generated, score)
|
| 400 |
|
|
|
|
| 401 |
if step < min_length:
|
| 402 |
next_token_logits[:, eos_token_id] = float('-inf')
|
| 403 |
|
|
|
|
| 404 |
if do_sample:
|
| 405 |
if top_k > 0:
|
| 406 |
top_k_vals, _ = torch.topk(next_token_logits, top_k)
|
|
|
|
| 422 |
else:
|
| 423 |
next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
|
| 424 |
|
|
|
|
| 425 |
next_token = next_token * unfinished_sequences[:, None] + pad_token_id * (1 - unfinished_sequences[:, None])
|
| 426 |
|
| 427 |
generated_tokens.append(next_token)
|
|
|
|
| 432 |
else:
|
| 433 |
current_tokens = next_token
|
| 434 |
|
|
|
|
| 435 |
unfinished_sequences = unfinished_sequences.mul(
|
| 436 |
(next_token.squeeze(-1) != eos_token_id).long()
|
| 437 |
)
|