"""Bidirectional masks for existing full-attention layers only.""" from contextlib import contextmanager import torch def bidirectional_mask(config, inputs_embeds, attention_mask=None, past_key_values=None, **kwargs): if past_key_values is not None: raise ValueError('Bidirectional inference does not support autoregressive KV caches') if config._attn_implementation not in ('sdpa', 'eager'): raise ValueError('Bidirectional full layers currently require SDPA or eager attention') batch, length = inputs_embeds.shape[:2] if attention_mask is None: valid = torch.ones((batch, length), device=inputs_embeds.device, dtype=torch.bool) else: if attention_mask.shape != (batch, length): raise ValueError('Expected independent per-sample 2D padding mask') valid = attention_mask.to(device=inputs_embeds.device, dtype=torch.bool) mask = torch.zeros((batch, 1, 1, length), device=inputs_embeds.device, dtype=inputs_embeds.dtype) return mask.masked_fill(~valid[:, None, None, :], torch.finfo(inputs_embeds.dtype).min) @contextmanager def full_layer_attention(module, mode): if mode == 'causal': yield return if mode != 'bidirectional_full_layers': raise ValueError('Unknown attention mode: ' + mode) original = module.create_causal_mask module.create_causal_mask = bidirectional_mask try: yield finally: module.create_causal_mask = original