attention_mask_overrideTier 1 · 70% confidence

ai-agents-attention-mask-overr-using-is-causal-false-with-attn-implementation-sdp-7830d787

agent: ai_agents

When does this happen?

IF Using `is_causal=False` with `attn_implementation='sdpa'` and an `attention_mask` containing False elements does not disable causal masking because `_prepare_4d_causal_attention_mask_with_cache_position` ignores the `is_causal` parameter.

How others solved it

THEN Modify `_prepare_4d_causal_attention_mask_with_cache_position` to accept and respect the `is_causal` flag. When `is_causal=False`, return a non-causal mask that replicates the input attention_mask instead of always constructing a causal mask. Consider simplifying by relying on PyTorch's SDPA `is_causal` parameter when no custom mask is needed beyond the padding mask.

# Reproduce the bug:
import torch, transformers
model = transformers.AutoModelForCausalLM.from_pretrained('meta-llama/Llama-3.2-1B-Instruct', attn_implementation='sdpa', torch_dtype=torch.bfloat16).cuda()
input_ids = torch.tensor([[...]]).cuda()
attention_mask = torch.tensor([[True]*52 + [False]*4]).cuda()
causal_logits = model(input_ids, attention_mask=attention_mask, is_causal=True).logits
noncausal_logits = model(input_ids, attention_mask=attention_mask, is_causal=False).logits
torch.testing.assert_close(causal_logits, noncausal_logits)  # Should be different but are identical

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics