Burak Aydın commited on
Commit
0931c91
·
1 Parent(s): 9a98e35

Fix non-causal MLA attention when no 4D mask is passed

Browse files

The MLA layers always call eager_attention_forward, which only applied a
mask it was given. Under the default sdpa mode (unpadded input, no cache)
and under flash_attention_2 the model passes no 4D mask, so these layers
attended to future tokens, and a 2D padding mask raised an IndexError.
eager_attention_forward now builds the causal mask itself (offset by the
cached keys) when it gets no 4D mask, and applies a 2D padding mask. The
4D-mask path and one-token decode are unchanged.

Fixes #15.

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)