Upload processor
Browse files- modeling_yangjian.py +92 -113
modeling_yangjian.py
CHANGED
|
@@ -26,7 +26,8 @@ class YangJianConfig(Qwen2_5_VLConfig):
|
|
| 26 |
super().__init__(**kwargs)
|
| 27 |
self.vision_config.compare_token_size = 100
|
| 28 |
self.architectures = ["YangJianVLForConditionalGeneration"]
|
| 29 |
-
|
|
|
|
| 30 |
class YangJianProcessor(Qwen2_5_VLProcessor):
|
| 31 |
config_class = YangJianConfig
|
| 32 |
def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
|
|
@@ -152,7 +153,6 @@ class OptimizedCrossAttention(nn.Module):
|
|
| 152 |
self.dim = config.hidden_size
|
| 153 |
self.num_heads = config.num_heads
|
| 154 |
self.head_dim = self.dim // self.num_heads
|
| 155 |
-
self.num_key_value_groups = 1 # 对于 cross attention,通常设为 1
|
| 156 |
self.scaling = self.head_dim**-0.5
|
| 157 |
self.attention_dropout = 0.0
|
| 158 |
self.is_causal = False # cross attention 不需要因果掩码
|
|
@@ -173,103 +173,108 @@ class OptimizedCrossAttention(nn.Module):
|
|
| 173 |
query_states: torch.Tensor,
|
| 174 |
key_value_states: Optional[torch.Tensor] = None,
|
| 175 |
attention_mask: Optional[torch.Tensor] = None,
|
|
|
|
|
|
|
| 176 |
**kwargs,
|
| 177 |
) -> torch.Tensor:
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
query_states: [seq_len_q, hidden_size] 或 [batch_size, seq_len_q, hidden_size]
|
| 181 |
-
key_value_states: [seq_len_kv, hidden_size] 或 [batch_size, seq_len_kv, hidden_size]
|
| 182 |
-
如果为 None,则执行 self attention
|
| 183 |
-
"""
|
| 184 |
-
# 处理输入维度
|
| 185 |
if query_states.dim() == 2:
|
| 186 |
-
query_states = query_states.unsqueeze(0)
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
squeeze_output = False
|
| 190 |
-
|
| 191 |
batch_size, seq_len_q, _ = query_states.shape
|
| 192 |
-
|
|
|
|
| 193 |
if self.is_cross_attention and key_value_states is not None:
|
| 194 |
-
# Cross Attention
|
| 195 |
if key_value_states.dim() == 2:
|
| 196 |
-
key_value_states = key_value_states.unsqueeze(0)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
q = self.q_proj(query_states) # [batch_size, seq_len_q, hidden_size]
|
| 200 |
-
|
| 201 |
-
# 计算 K、V(融合计算)
|
| 202 |
-
kv = self.kv(key_value_states) # [batch_size, seq_len_kv, hidden_size * 2]
|
| 203 |
seq_len_kv = kv.shape[1]
|
| 204 |
-
|
| 205 |
-
# 分离 K、V
|
| 206 |
k, v = kv.reshape(batch_size, seq_len_kv, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4).unbind(0)
|
| 207 |
-
# k, v: [batch_size, num_heads, seq_len_kv, head_dim]
|
| 208 |
-
|
| 209 |
-
# 重塑 Q
|
| 210 |
q = q.reshape(batch_size, seq_len_q, self.num_heads, self.head_dim).transpose(1, 2)
|
| 211 |
-
# q: [batch_size, num_heads, seq_len_q, head_dim]
|
| 212 |
-
|
| 213 |
else:
|
| 214 |
-
# Self Attention
|
| 215 |
if key_value_states is None:
|
| 216 |
key_value_states = query_states
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
-
#
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
# 选择 attention 实现
|
| 226 |
-
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS["sdpa"]
|
| 227 |
-
# if hasattr(self.config, '_attn_implementation') and self.config._attn_implementation != "eager":
|
| 228 |
-
# attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 229 |
-
|
| 230 |
-
# 构造 cu_seqlens 参数(FlashAttention 必需)
|
| 231 |
-
cu_seqlens_q = torch.arange(0, (batch_size*self.num_heads + 1) * seq_len_q, step=seq_len_q, dtype=torch.int32, device=q.device)
|
| 232 |
-
if self.is_cross_attention and key_value_states is not None:
|
| 233 |
-
cu_seqlens_k = torch.arange(0, (batch_size*self.num_heads + 1) * seq_len_kv, step=seq_len_kv, dtype=torch.int32, device=k.device)
|
| 234 |
else:
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
scaling=self.scaling,
|
| 250 |
-
is_causal=False,
|
| 251 |
-
**kwargs,
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
attn_output = attn_output.reshape(batch_size, self.num_heads, seq_len_q, self.head_dim)
|
| 255 |
-
|
| 256 |
-
attn_output = attn_output.transpose(1, 2).contiguous() # [batch_size, seq_len_q, num_heads, head_dim]
|
| 257 |
-
attn_output = attn_output.reshape(batch_size, seq_len_q, self.dim) # [batch_size, seq_len_q, hidden_size]
|
| 258 |
-
|
| 259 |
-
# 输出投影
|
| 260 |
attn_output = self.proj(attn_output)
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
attn_output = attn_output.squeeze(0) # [seq_len_q, hidden_size]
|
| 265 |
-
|
| 266 |
-
return attn_output
|
| 267 |
|
| 268 |
|
| 269 |
class YangJianCompareVisualEncoder(nn.Module):
|
| 270 |
def __init__(self, config):
|
| 271 |
super().__init__()
|
| 272 |
self.config = config
|
|
|
|
| 273 |
self.hidden_size = config.hidden_size
|
| 274 |
# self.token_size = 100 * (config.spatial_merge_size**2) if "compare_token_size" not in config else config.compare_token_size * (config.spatial_merge_size**2)
|
| 275 |
self.token_size = 100 if "compare_token_size" not in config else config.compare_token_size
|
|
@@ -291,7 +296,6 @@ class YangJianCompareVisualEncoder(nn.Module):
|
|
| 291 |
self.query_embeddings = nn.Parameter(
|
| 292 |
torch.empty(self.token_size, self.hidden_size)
|
| 293 |
)
|
| 294 |
-
|
| 295 |
# 只保留 Cross Attention for queries to attend to encoded features
|
| 296 |
self.decoder_cross_attn = OptimizedCrossAttention(config, is_cross_attention=True)
|
| 297 |
|
|
@@ -301,33 +305,8 @@ class YangJianCompareVisualEncoder(nn.Module):
|
|
| 301 |
|
| 302 |
self.compare_projector = nn.Linear(config.hidden_size, config.out_hidden_size)
|
| 303 |
|
| 304 |
-
def
|
| 305 |
-
|
| 306 |
-
确保所有模块组件都在目标张量的设备上并使用相同的数据类型
|
| 307 |
-
"""
|
| 308 |
-
device = target_tensor.device
|
| 309 |
-
dtype = target_tensor.dtype
|
| 310 |
-
|
| 311 |
-
# 移动 attention 模块到正确设备
|
| 312 |
-
self.encoder_cross_attn1 = self.encoder_cross_attn1.to(device=device, dtype=dtype)
|
| 313 |
-
self.encoder_cross_attn2 = self.encoder_cross_attn2.to(device=device, dtype=dtype)
|
| 314 |
-
self.decoder_cross_attn = self.decoder_cross_attn.to(device=device, dtype=dtype)
|
| 315 |
-
|
| 316 |
-
# 移动 norm 层到正确设备
|
| 317 |
-
self.encoder_norm1 = self.encoder_norm1.to(device=device, dtype=dtype)
|
| 318 |
-
self.encoder_norm2 = self.encoder_norm2.to(device=device, dtype=dtype)
|
| 319 |
-
self.encoder_norm3 = self.encoder_norm3.to(device=device, dtype=dtype)
|
| 320 |
-
self.encoder_norm4 = self.encoder_norm4.to(device=device, dtype=dtype)
|
| 321 |
-
self.decoder_norm1 = self.decoder_norm1.to(device=device, dtype=dtype)
|
| 322 |
-
self.decoder_norm2 = self.decoder_norm2.to(device=device, dtype=dtype)
|
| 323 |
-
|
| 324 |
-
# 移动 MLP 到正确设备
|
| 325 |
-
self.encoder_mlp1 = self.encoder_mlp1.to(device=device, dtype=dtype)
|
| 326 |
-
self.encoder_mlp2 = self.encoder_mlp2.to(device=device, dtype=dtype)
|
| 327 |
-
self.decoder_mlp = self.decoder_mlp.to(device=device, dtype=dtype)
|
| 328 |
-
|
| 329 |
-
def _initialize_weights(self):
|
| 330 |
-
nn.init.normal_(self.query_embeddings.weight, mean=0.0, std=0.02)
|
| 331 |
|
| 332 |
def forward(self, images_hidden_states: list) -> torch.Tensor:
|
| 333 |
"""
|
|
@@ -340,13 +319,10 @@ class YangJianCompareVisualEncoder(nn.Module):
|
|
| 340 |
if not images_hidden_states:
|
| 341 |
return torch.empty(0, self.token_size, self.hidden_size)
|
| 342 |
|
| 343 |
-
# 确保所有组件的设备和数据类型一致
|
| 344 |
-
# self._ensure_device_dtype_consistency(images_hidden_states[0])
|
| 345 |
-
|
| 346 |
# 检查 query_embeddings 是否包含 NaN
|
| 347 |
if torch.isnan(self.query_embeddings).any():
|
| 348 |
-
print("警告:query_embeddings 包含 NaN
|
| 349 |
-
nn.init.normal_(self.query_embeddings, mean=0.0, std=0.02)
|
| 350 |
|
| 351 |
# 获取每个图像的序列长度
|
| 352 |
seq_lengths = [state.size(0) for state in images_hidden_states]
|
|
@@ -380,9 +356,11 @@ class YangJianCompareVisualEncoder(nn.Module):
|
|
| 380 |
# 创建循环移位的状态用于对比
|
| 381 |
# 对于第一个图像,使用自身作为previous
|
| 382 |
previous_states = torch.roll(batched_states, shifts=1, dims=0)
|
| 383 |
-
previous_states[0] = batched_states[0]
|
| 384 |
previous_masks = torch.roll(attention_masks, shifts=1, dims=0)
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
# Encoder: 批量处理所有图像
|
| 388 |
encoded_features = self._encoder_forward(
|
|
@@ -759,4 +737,5 @@ class YangJianVLForConditionalGeneration(Qwen2_5_VLForConditionalGeneration):
|
|
| 759 |
|
| 760 |
def __init__(self, config):
|
| 761 |
super().__init__(config)
|
| 762 |
-
self.model = YangJianVLModel(config)
|
|
|
|
|
|
| 26 |
super().__init__(**kwargs)
|
| 27 |
self.vision_config.compare_token_size = 100
|
| 28 |
self.architectures = ["YangJianVLForConditionalGeneration"]
|
| 29 |
+
self.sequence_compare = False
|
| 30 |
+
|
| 31 |
class YangJianProcessor(Qwen2_5_VLProcessor):
|
| 32 |
config_class = YangJianConfig
|
| 33 |
def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
|
|
|
|
| 153 |
self.dim = config.hidden_size
|
| 154 |
self.num_heads = config.num_heads
|
| 155 |
self.head_dim = self.dim // self.num_heads
|
|
|
|
| 156 |
self.scaling = self.head_dim**-0.5
|
| 157 |
self.attention_dropout = 0.0
|
| 158 |
self.is_causal = False # cross attention 不需要因果掩码
|
|
|
|
| 173 |
query_states: torch.Tensor,
|
| 174 |
key_value_states: Optional[torch.Tensor] = None,
|
| 175 |
attention_mask: Optional[torch.Tensor] = None,
|
| 176 |
+
cu_seqlens: Optional[torch.Tensor] = None, # 只FA2用
|
| 177 |
+
kv_cu_seqlens: Optional[torch.Tensor] = None,# 只FA2用
|
| 178 |
**kwargs,
|
| 179 |
) -> torch.Tensor:
|
| 180 |
+
# 允许 query_states [B,T,d] 或 [T,d],自动扩展 batch 维
|
| 181 |
+
orig_2d = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
if query_states.dim() == 2:
|
| 183 |
+
query_states = query_states.unsqueeze(0)
|
| 184 |
+
orig_2d = True
|
| 185 |
+
|
|
|
|
|
|
|
| 186 |
batch_size, seq_len_q, _ = query_states.shape
|
| 187 |
+
|
| 188 |
+
# Q/K/V投影
|
| 189 |
if self.is_cross_attention and key_value_states is not None:
|
|
|
|
| 190 |
if key_value_states.dim() == 2:
|
| 191 |
+
key_value_states = key_value_states.unsqueeze(0)
|
| 192 |
+
q = self.q_proj(query_states)
|
| 193 |
+
kv = self.kv(key_value_states)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
seq_len_kv = kv.shape[1]
|
|
|
|
|
|
|
| 195 |
k, v = kv.reshape(batch_size, seq_len_kv, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4).unbind(0)
|
|
|
|
|
|
|
|
|
|
| 196 |
q = q.reshape(batch_size, seq_len_q, self.num_heads, self.head_dim).transpose(1, 2)
|
|
|
|
|
|
|
| 197 |
else:
|
|
|
|
| 198 |
if key_value_states is None:
|
| 199 |
key_value_states = query_states
|
| 200 |
+
qkv = self.qkv(query_states)
|
| 201 |
+
q, k, v = qkv.reshape(batch_size, seq_len_q, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4).unbind(0)
|
| 202 |
+
|
| 203 |
+
# 选用哪个 attention kernel
|
| 204 |
+
attn_impl = getattr(self.config, '_attn_implementation', 'sdpa')
|
| 205 |
+
attn_impl = 'sdpa'
|
| 206 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS[attn_impl]
|
| 207 |
+
|
| 208 |
+
# ========= 支持 FA2 ==========
|
| 209 |
+
if attn_impl == "flash_attention_2":
|
| 210 |
+
# Qwen2_5 之所以能支持 FA2,是因为准备了 flatten+cu_seqlens
|
| 211 |
+
# 这里假设 query_states/key_value_states 按 batch 维是变长的
|
| 212 |
+
|
| 213 |
+
# 检查 cu_seqlens,有就用,否则尝试自动生成
|
| 214 |
+
if cu_seqlens is None:
|
| 215 |
+
# 默认把每个batch都视为长度=seq_len_q
|
| 216 |
+
cu_seqlens = torch.arange(0, (batch_size + 1) * seq_len_q, step=seq_len_q, dtype=torch.int32, device=q.device)
|
| 217 |
+
if kv_cu_seqlens is None:
|
| 218 |
+
cu_seqlens_k = torch.arange(0, (batch_size + 1) * k.shape[2], step=k.shape[2], dtype=torch.int32, device=k.device)
|
| 219 |
+
else:
|
| 220 |
+
cu_seqlens_k = kv_cu_seqlens
|
| 221 |
+
|
| 222 |
+
# flatten [B, nH, T, d] -> [total_T, nH, d]
|
| 223 |
+
# 注意!FlashAttn2是 (total, nH, d),不是 (nH, total, d),和普通实现不一样
|
| 224 |
+
# 更安全的 flatten 方式
|
| 225 |
+
# [B, nH, T, d] -> [B, T, nH, d] -> [total_T, nH, d]
|
| 226 |
+
q_ = q.transpose(1, 2).contiguous().view(-1, self.num_heads, self.head_dim)
|
| 227 |
+
k_ = k.transpose(1, 2).contiguous().view(-1, self.num_heads, self.head_dim)
|
| 228 |
+
v_ = v.transpose(1, 2).contiguous().view(-1, self.num_heads, self.head_dim)
|
| 229 |
|
| 230 |
+
max_seqlen_q = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
|
| 231 |
+
max_seqlen_k = (cu_seqlens_k[1:] - cu_seqlens_k[:-1]).max().item()
|
| 232 |
+
|
| 233 |
+
attn_output, _ = attention_interface(
|
| 234 |
+
self,
|
| 235 |
+
q_,
|
| 236 |
+
k_,
|
| 237 |
+
v_,
|
| 238 |
+
attention_mask=None,
|
| 239 |
+
scaling=self.scaling,
|
| 240 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 241 |
+
cu_seq_lens_q=cu_seqlens,
|
| 242 |
+
cu_seq_lens_k=cu_seqlens_k,
|
| 243 |
+
max_length_q=max_seqlen_q,
|
| 244 |
+
max_length_k=max_seqlen_k,
|
| 245 |
+
is_causal=self.is_causal,
|
| 246 |
+
**kwargs,
|
| 247 |
+
)
|
| 248 |
|
| 249 |
+
# 更简洁的输出重构
|
| 250 |
+
# [total_q, nH, d] -> [B, seq_len_q, nH, d]
|
| 251 |
+
attn_output = attn_output.view(batch_size, seq_len_q, self.num_heads, self.head_dim).contiguous()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
else:
|
| 253 |
+
# 普通实现,下游实现就是 [B, nH, T, d]
|
| 254 |
+
attn_output, _ = attention_interface(
|
| 255 |
+
self,
|
| 256 |
+
q, k, v,
|
| 257 |
+
attention_mask=attention_mask,
|
| 258 |
+
scaling=self.scaling,
|
| 259 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 260 |
+
is_causal=self.is_causal,
|
| 261 |
+
**kwargs,
|
| 262 |
+
)
|
| 263 |
+
# attn_output: [B, nH, seq_q, d]
|
| 264 |
+
attn_output = attn_output.transpose(1, 2).contiguous() # [B, seq_q, nH, d]
|
| 265 |
+
|
| 266 |
+
attn_output = attn_output.reshape(batch_size, seq_len_q, self.dim) # [B, seq_q, D]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
attn_output = self.proj(attn_output)
|
| 268 |
+
if orig_2d:
|
| 269 |
+
attn_output = attn_output.squeeze(0)
|
| 270 |
+
return attn_output.contiguous()
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
|
| 273 |
class YangJianCompareVisualEncoder(nn.Module):
|
| 274 |
def __init__(self, config):
|
| 275 |
super().__init__()
|
| 276 |
self.config = config
|
| 277 |
+
self.sequence_compare = getattr(config, "sequence_compare", False)
|
| 278 |
self.hidden_size = config.hidden_size
|
| 279 |
# self.token_size = 100 * (config.spatial_merge_size**2) if "compare_token_size" not in config else config.compare_token_size * (config.spatial_merge_size**2)
|
| 280 |
self.token_size = 100 if "compare_token_size" not in config else config.compare_token_size
|
|
|
|
| 296 |
self.query_embeddings = nn.Parameter(
|
| 297 |
torch.empty(self.token_size, self.hidden_size)
|
| 298 |
)
|
|
|
|
| 299 |
# 只保留 Cross Attention for queries to attend to encoded features
|
| 300 |
self.decoder_cross_attn = OptimizedCrossAttention(config, is_cross_attention=True)
|
| 301 |
|
|
|
|
| 305 |
|
| 306 |
self.compare_projector = nn.Linear(config.hidden_size, config.out_hidden_size)
|
| 307 |
|
| 308 |
+
def init_query_embeddings(self):
|
| 309 |
+
nn.init.normal_(self.query_embeddings, mean=0.0, std=0.02)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
def forward(self, images_hidden_states: list) -> torch.Tensor:
|
| 312 |
"""
|
|
|
|
| 319 |
if not images_hidden_states:
|
| 320 |
return torch.empty(0, self.token_size, self.hidden_size)
|
| 321 |
|
|
|
|
|
|
|
|
|
|
| 322 |
# 检查 query_embeddings 是否包含 NaN
|
| 323 |
if torch.isnan(self.query_embeddings).any():
|
| 324 |
+
print("警告:query_embeddings 包含 NaN 值")
|
| 325 |
+
# nn.init.normal_(self.query_embeddings, mean=0.0, std=0.02)
|
| 326 |
|
| 327 |
# 获取每个图像的序列长度
|
| 328 |
seq_lengths = [state.size(0) for state in images_hidden_states]
|
|
|
|
| 356 |
# 创建循环移位的状态用于对比
|
| 357 |
# 对于第一个图像,使用自身作为previous
|
| 358 |
previous_states = torch.roll(batched_states, shifts=1, dims=0)
|
|
|
|
| 359 |
previous_masks = torch.roll(attention_masks, shifts=1, dims=0)
|
| 360 |
+
|
| 361 |
+
if previous_states.size(0) > 1 and self.sequence_compare:
|
| 362 |
+
previous_states[0] = previous_states[1]
|
| 363 |
+
previous_masks[0] = previous_masks[1]
|
| 364 |
|
| 365 |
# Encoder: 批量处理所有图像
|
| 366 |
encoded_features = self._encoder_forward(
|
|
|
|
| 737 |
|
| 738 |
def __init__(self, config):
|
| 739 |
super().__init__(config)
|
| 740 |
+
self.model = YangJianVLModel(config)
|
| 741 |
+
|