Fix non-causal MLA attention under the default sdpa (and flash_attention_2) mode

#20
Files changed (1) hide show
  1. modeling_bailing_moe_v3.py +12 -1
modeling_bailing_moe_v3.py CHANGED
@@ -526,9 +526,20 @@ def eager_attention_forward(
526
  value_states = repeat_kv2(value, module.num_key_value_groups)
527
 
528
  attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
529
- if attention_mask is not None:
530
  causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
531
  attn_weights = attn_weights + causal_mask
 
 
 
 
 
 
 
 
 
 
 
532
 
533
  attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
534
  attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
 
526
  value_states = repeat_kv2(value, module.num_key_value_groups)
527
 
528
  attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
529
+ if attention_mask is not None and attention_mask.dim() == 4:
530
  causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
531
  attn_weights = attn_weights + causal_mask
532
+ else:
533
+ # No 4D mask (sdpa without padding, or flash_attention_2): build the causal mask here, plus any 2D padding mask.
534
+ q_len, k_len = query.shape[-2], key_states.shape[-2]
535
+ min_value = torch.finfo(attn_weights.dtype).min
536
+ if getattr(module, "is_causal", True) and q_len > 1:
537
+ causal = torch.ones(q_len, k_len, dtype=torch.bool, device=attn_weights.device)
538
+ causal = causal.tril(diagonal=k_len - q_len)
539
+ attn_weights = attn_weights.masked_fill(~causal, min_value)
540
+ if attention_mask is not None and attention_mask.dim() == 2:
541
+ padded = attention_mask[:, None, None, :k_len] == 0
542
+ attn_weights = attn_weights.masked_fill(padded, min_value)
543
 
544
  attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
545
  attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)