|
| 1 | +from typing import Optional |
| 2 | +import torch |
| 3 | +import transformers |
| 4 | +from .patch_helper import _has_transformers |
| 5 | + |
| 6 | +patch_sdpa_is_causal = _has_transformers("4.99") |
| 7 | + |
| 8 | + |
| 9 | +def common_eager_attention_forward( |
| 10 | + module: torch.nn.Module, |
| 11 | + query: torch.Tensor, |
| 12 | + key: torch.Tensor, |
| 13 | + value: torch.Tensor, |
| 14 | + attention_mask: Optional[torch.Tensor], |
| 15 | + scaling: Optional[float] = None, |
| 16 | + dropout: float = 0.0, |
| 17 | + head_mask: Optional[torch.Tensor] = None, |
| 18 | + **kwargs, |
| 19 | +): |
| 20 | + if scaling is None: |
| 21 | + scaling = query.size(-1) ** -0.5 |
| 22 | + |
| 23 | + attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling |
| 24 | + if attention_mask is not None: |
| 25 | + # PATCHED |
| 26 | + # The two following lines were added. |
| 27 | + if attention_mask is not None and attention_mask.ndim == 4: |
| 28 | + attention_mask = attention_mask[:, :, :, : key.shape[-2]] |
| 29 | + attn_weights = attn_weights + attention_mask |
| 30 | + |
| 31 | + attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1) |
| 32 | + |
| 33 | + if head_mask is not None: |
| 34 | + attn_weights = attn_weights * head_mask.view(1, -1, 1, 1) |
| 35 | + |
| 36 | + attn_weights = torch.nn.functional.dropout( |
| 37 | + attn_weights, p=dropout, training=module.training |
| 38 | + ) |
| 39 | + attn_output = torch.matmul(attn_weights, value) |
| 40 | + attn_output = attn_output.transpose(1, 2).contiguous() |
| 41 | + |
| 42 | + return attn_output, attn_weights |
| 43 | + |
| 44 | + |
| 45 | +def patched_sdpa_attention_forward( |
| 46 | + module: torch.nn.Module, |
| 47 | + query: torch.Tensor, |
| 48 | + key: torch.Tensor, |
| 49 | + value: torch.Tensor, |
| 50 | + attention_mask: Optional[torch.Tensor], |
| 51 | + dropout: float = 0.0, |
| 52 | + scaling: Optional[float] = None, |
| 53 | + is_causal: Optional[bool] = None, |
| 54 | + **kwargs, |
| 55 | +) -> tuple[torch.Tensor, None]: |
| 56 | + """ |
| 57 | + manual patch for function |
| 58 | + ``transformers.integrations.sdpa_attention.sdpa_attention_forward`` |
| 59 | + """ |
| 60 | + assert not kwargs.get("output_attentions", False), ( |
| 61 | + "`sdpa` attention does not support `output_attentions=True`." |
| 62 | + " Please set your attention to `eager` if you want any of these features." |
| 63 | + ) |
| 64 | + torch._check( |
| 65 | + query.shape[0] == key.shape[0] or query.shape[0] == 1, |
| 66 | + lambda: ( |
| 67 | + f"broadcast issue query (1): {query.shape}, key: {key.shape}, " |
| 68 | + f"value: {value.shape}" |
| 69 | + ), |
| 70 | + ) |
| 71 | + torch._check( |
| 72 | + key.shape[0] == value.shape[0] or key.shape[0] == 1, |
| 73 | + lambda: ( |
| 74 | + f"broadcast issue query (2): {query.shape}, key: {key.shape}, " |
| 75 | + f"value: {value.shape}" |
| 76 | + ), |
| 77 | + ) |
| 78 | + |
| 79 | + sdpa_kwargs = {} |
| 80 | + if hasattr(module, "num_key_value_groups"): |
| 81 | + if not transformers.integrations.sdpa_attention.use_gqa_in_sdpa(attention_mask, key): |
| 82 | + key = transformers.integrations.sdpa_attention.repeat_kv( |
| 83 | + key, module.num_key_value_groups |
| 84 | + ) |
| 85 | + value = transformers.integrations.sdpa_attention.repeat_kv( |
| 86 | + value, module.num_key_value_groups |
| 87 | + ) |
| 88 | + else: |
| 89 | + sdpa_kwargs = {"enable_gqa": True} |
| 90 | + |
| 91 | + if attention_mask is not None and attention_mask.ndim == 4: |
| 92 | + attention_mask = attention_mask[:, :, :, : key.shape[-2]] |
| 93 | + |
| 94 | + torch._check( |
| 95 | + attention_mask is None or attention_mask.shape[3] == key.shape[2], |
| 96 | + lambda: "Attention mask shape incompatible with key shape.", |
| 97 | + ) |
| 98 | + |
| 99 | + if patch_sdpa_is_causal: |
| 100 | + # transformers>=4.55 |
| 101 | + is_causal = is_causal if is_causal is not None else getattr(module, "is_causal", True) |
| 102 | + |
| 103 | + # PATCHED: remove the test query.shape[2] > 1 |
| 104 | + # is_causal = query.shape[2] > 1 and attention_mask is None and is_causal |
| 105 | + # and we split the test to keep the minimum in torch.cond |
| 106 | + is_causal = attention_mask is None and is_causal |
| 107 | + |
| 108 | + if not is_causal: |
| 109 | + torch._check(query.shape[0] > 0) |
| 110 | + torch._check(query.shape[1] > 0) |
| 111 | + torch._check(query.shape[2] > 0) |
| 112 | + torch._check(query.shape[3] > 0) |
| 113 | + torch._check(key.shape[0] > 0) |
| 114 | + torch._check(key.shape[1] > 0) |
| 115 | + torch._check(key.shape[2] > 0) |
| 116 | + torch._check(key.shape[3] > 0) |
| 117 | + torch._check(value.shape[0] > 0) |
| 118 | + torch._check(value.shape[1] > 0) |
| 119 | + torch._check(value.shape[2] > 0) |
| 120 | + torch._check(value.shape[3] > 0) |
| 121 | + return ( |
| 122 | + torch.nn.functional.scaled_dot_product_attention( |
| 123 | + query, |
| 124 | + key, |
| 125 | + value, |
| 126 | + attn_mask=attention_mask, |
| 127 | + dropout_p=dropout, |
| 128 | + scale=scaling, |
| 129 | + is_causal=is_causal, |
| 130 | + **sdpa_kwargs, |
| 131 | + ) |
| 132 | + .transpose(1, 2) |
| 133 | + .contiguous(), |
| 134 | + None, |
| 135 | + ) |
| 136 | + else: |
| 137 | + # transformers<4.55 |
| 138 | + if is_causal is None and attention_mask is not None: |
| 139 | + is_causal = False |
| 140 | + if is_causal is not None: |
| 141 | + return ( |
| 142 | + torch.nn.functional.scaled_dot_product_attention( |
| 143 | + query, |
| 144 | + key, |
| 145 | + value, |
| 146 | + attn_mask=attention_mask, |
| 147 | + dropout_p=dropout, |
| 148 | + scale=scaling, |
| 149 | + is_causal=is_causal, |
| 150 | + **sdpa_kwargs, |
| 151 | + ) |
| 152 | + .transpose(1, 2) |
| 153 | + .contiguous(), |
| 154 | + None, |
| 155 | + ) |
| 156 | + |
| 157 | + # To avoid the following errors: |
| 158 | + # is_causal=query.shape[2] > 1 |
| 159 | + # TypeError: scaled_dot_product_attention(): argument 'is_causal' must be bool, not SymBool |
| 160 | + # is_causal=torch.tensor(query.shape[2] > 1) |
| 161 | + # TypeError: scaled_dot_product_attention(): argument 'is_causal' must be bool, not Tensor |
| 162 | + attn_output = torch.cond( |
| 163 | + query.shape[2] > 1, # distinction between prefill and decoding steps |
| 164 | + lambda query, key, value: torch.nn.functional.scaled_dot_product_attention( |
| 165 | + query, |
| 166 | + key, |
| 167 | + value, |
| 168 | + dropout_p=dropout, |
| 169 | + scale=scaling, |
| 170 | + is_causal=True, |
| 171 | + **sdpa_kwargs, |
| 172 | + ).contiguous(), |
| 173 | + lambda query, key, value: torch.nn.functional.scaled_dot_product_attention( |
| 174 | + query, |
| 175 | + key, |
| 176 | + value, |
| 177 | + dropout_p=dropout, |
| 178 | + scale=scaling, |
| 179 | + is_causal=False, |
| 180 | + **sdpa_kwargs, |
| 181 | + ).contiguous(), |
| 182 | + [query, key, value], |
| 183 | + ) |
| 184 | + attn_output = attn_output.transpose(1, 2).contiguous() |
| 185 | + return attn_output, None |
| 186 | + |
| 187 | + |
| 188 | +def patched_model_bart_eager_attention_forward( |
| 189 | + module: torch.nn.Module, |
| 190 | + query: torch.Tensor, |
| 191 | + key: torch.Tensor, |
| 192 | + value: torch.Tensor, |
| 193 | + attention_mask: Optional[torch.Tensor], |
| 194 | + scaling: Optional[float] = None, |
| 195 | + dropout: float = 0.0, |
| 196 | + head_mask: Optional[torch.Tensor] = None, |
| 197 | + **kwargs, |
| 198 | +): |
| 199 | + """[patch:transformers.models.bart.modeling_bart.eager_attention_forward]""" |
| 200 | + return common_eager_attention_forward( |
| 201 | + module, |
| 202 | + query, |
| 203 | + key, |
| 204 | + value, |
| 205 | + attention_mask=attention_mask, |
| 206 | + scaling=scaling, |
| 207 | + dropout=dropout, |
| 208 | + head_mask=head_mask, |
| 209 | + **kwargs, |
| 210 | + ) |
| 211 | + |
| 212 | + |
| 213 | +def patched_modeling_marian_eager_attention_forward( |
| 214 | + module: torch.nn.Module, |
| 215 | + query: torch.Tensor, |
| 216 | + key: torch.Tensor, |
| 217 | + value: torch.Tensor, |
| 218 | + attention_mask: Optional[torch.Tensor], |
| 219 | + scaling: Optional[float] = None, |
| 220 | + dropout: float = 0.0, |
| 221 | + head_mask: Optional[torch.Tensor] = None, |
| 222 | + **kwargs, |
| 223 | +): |
| 224 | + """[patch:transformers.models.marian.modeling_marian.eager_attention_forward]""" |
| 225 | + return common_eager_attention_forward( |
| 226 | + module, |
| 227 | + query, |
| 228 | + key, |
| 229 | + value, |
| 230 | + attention_mask=attention_mask, |
| 231 | + scaling=scaling, |
| 232 | + dropout=dropout, |
| 233 | + head_mask=head_mask, |
| 234 | + **kwargs, |
| 235 | + ) |
0 commit comments