vinayh19 commited on
Commit
1346bc8
·
verified ·
1 Parent(s): 2911d17

Upload 4 files

Browse files

Added required files

Files changed (4) hide show
  1. bert_layers.py +973 -0
  2. bert_padding.py +151 -0
  3. configuration_bert.py +26 -0
  4. flash_attn_triton.py +1328 -0
bert_layers.py ADDED
@@ -0,0 +1,973 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 MosaicML Examples authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
5
+ # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
6
+ # Copyright (c) 2022, Tri Dao.
7
+
8
+ import copy
9
+ import logging
10
+ import math
11
+ import warnings
12
+ from typing import List, Optional, Tuple, Union
13
+
14
+ #import bert_padding as bert_padding_module
15
+ import torch
16
+ import torch.nn as nn
17
+ from einops import rearrange
18
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
19
+ from transformers.activations import ACT2FN
20
+ from transformers.modeling_outputs import (MaskedLMOutput,
21
+ SequenceClassifierOutput)
22
+ from transformers.models.bert.modeling_bert import BertPreTrainedModel
23
+ from transformers.modeling_utils import PreTrainedModel
24
+
25
+ from bert_padding import (index_first_axis, index_put_first_axis, pad_input, unpad_input, unpad_input_only)
26
+
27
+ #from bert_padding_module import (index_first_axis, index_put_first_axis, pad_input, unpad_input, unpad_input_only)
28
+
29
+ try:
30
+ from .flash_attn_triton import flash_attn_qkvpacked_func
31
+ #flash_attn_qkvpacked_func = flash_attn_triton.flash_attn_qkvpacked_func
32
+ except ImportError as e:
33
+ flash_attn_qkvpacked_func = None
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ class BertEmbeddings(nn.Module):
39
+
40
+ def __init__(self, config):
41
+ super().__init__()
42
+ self.word_embeddings = nn.Embedding(config.vocab_size,
43
+ config.hidden_size,
44
+ padding_idx=config.pad_token_id)
45
+ # ALiBi doesn't use position embeddings
46
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size,
47
+ config.hidden_size)
48
+
49
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model
50
+ # variable name and be able to load any TensorFlow checkpoint file
51
+ self.LayerNorm = nn.LayerNorm(config.hidden_size,
52
+ eps=config.layer_norm_eps)
53
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
54
+ self.register_buffer('token_type_ids',
55
+ torch.zeros(config.max_position_embeddings,
56
+ dtype=torch.long),
57
+ persistent=False)
58
+
59
+ def forward(
60
+ self,
61
+ input_ids: Optional[torch.LongTensor] = None,
62
+ token_type_ids: Optional[torch.LongTensor] = None,
63
+ position_ids: Optional[torch.LongTensor] = None,
64
+ inputs_embeds: Optional[torch.FloatTensor] = None,
65
+ past_key_values_length: int = 0,
66
+ ) -> torch.Tensor:
67
+ if (input_ids is not None) == (inputs_embeds is not None):
68
+ raise ValueError('Must specify either input_ids or input_embeds!')
69
+ if input_ids is not None:
70
+ input_shape = input_ids.size()
71
+ else:
72
+ assert inputs_embeds is not None # just for type checking
73
+ input_shape = inputs_embeds.size()[:-1]
74
+
75
+ seq_length = input_shape[1]
76
+
77
+ if position_ids is None:
78
+ # great! ALiBi
79
+ pass
80
+
81
+ # Setting the token_type_ids to the registered buffer in constructor
82
+ # where it is all zeros, which usually occurs when it's auto-generated;
83
+ # registered buffer helps users when tracing the model without passing
84
+ # token_type_ids, solves issue #5664
85
+ if token_type_ids is None:
86
+ if hasattr(self, 'token_type_ids'):
87
+ assert isinstance(self.token_type_ids, torch.LongTensor)
88
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
89
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
90
+ input_shape[0], seq_length)
91
+ token_type_ids = buffered_token_type_ids_expanded # type: ignore
92
+ else:
93
+ token_type_ids = torch.zeros(input_shape, # type: ignore
94
+ dtype=torch.long,
95
+ device=self.word_embeddings.device) # type: ignore # yapf: disable
96
+
97
+ if inputs_embeds is None:
98
+ inputs_embeds = self.word_embeddings(input_ids)
99
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
100
+
101
+ embeddings = inputs_embeds + token_type_embeddings
102
+ # no position embeddings! ALiBi
103
+ embeddings = self.LayerNorm(embeddings)
104
+ embeddings = self.dropout(embeddings)
105
+ return embeddings
106
+
107
+
108
+ class BertUnpadSelfAttention(nn.Module):
109
+
110
+ def __init__(self, config):
111
+ super().__init__()
112
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
113
+ config, 'embedding_size'):
114
+ raise ValueError(
115
+ f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention '
116
+ f'heads ({config.num_attention_heads})')
117
+
118
+ self.num_attention_heads = config.num_attention_heads
119
+ self.attention_head_size = int(config.hidden_size /
120
+ config.num_attention_heads)
121
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
122
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
123
+ self.p_dropout = config.attention_probs_dropout_prob
124
+ self.Wqkv = nn.Linear(self.all_head_size, 3 * config.hidden_size)
125
+
126
+ # Warn if defaulting to pytorch because of import issues
127
+ if flash_attn_qkvpacked_func is None:
128
+ warnings.warn(
129
+ 'Unable to import Triton; defaulting MosaicBERT attention implementation to pytorch (this will reduce throughput when using this model).'
130
+ )
131
+
132
+ def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor,
133
+ max_seqlen_in_batch: int, indices: torch.Tensor,
134
+ attn_mask: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
135
+ """Perform self-attention.
136
+
137
+ If dropout is zero, then we can use the Triton kernel, so we do that. However, if not, we send through a standard PyTorch
138
+ implementation of self-attention.
139
+
140
+ The arguments are unpadded, and our implementations of attention require padded arguments,
141
+ so we first call `pad_input`. Once we compute attention, we re-unpad our outputs for the other layers.
142
+ The pad/unpad operations add overhead, but not sending pad tokens through ffs saves compute.
143
+ It is possible to write an unpadded implementation of attention (in Triton and PyTorch), which we will eventually do.
144
+
145
+ Args:
146
+ hidden_states: (total_nnz, dim)
147
+ cu_seqlens: (batch + 1,)
148
+ max_seqlen_in_batch: int
149
+ indices: (total_nnz,)
150
+ attn_mask: (batch, max_seqlen_in_batch)
151
+ bias: (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
152
+
153
+ Returns:
154
+ attention: (total_nnz, dim)
155
+ """
156
+ qkv = self.Wqkv(hidden_states)
157
+ qkv = pad_input(qkv, indices, cu_seqlens.shape[0] - 1,
158
+ max_seqlen_in_batch) # batch, max_seqlen_in_batch, thd
159
+ qkv = rearrange(qkv,
160
+ 'b s (t h d) -> b s t h d',
161
+ t=3,
162
+ h=self.num_attention_heads)
163
+ if self.p_dropout or flash_attn_qkvpacked_func is None:
164
+ # if we have nonzero attention dropout (e.g. during fine-tuning) or no Triton, compute attention in PyTorch
165
+ q = qkv[:, :, 0, :, :].permute(0, 2, 1, 3) # b h s d
166
+ k = qkv[:, :, 1, :, :].permute(0, 2, 3, 1) # b h d s
167
+ v = qkv[:, :, 2, :, :].permute(0, 2, 1, 3) # b h s d
168
+ attention_scores = torch.matmul(q, k) / math.sqrt(
169
+ self.attention_head_size)
170
+ attention_scores = attention_scores + bias
171
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
172
+ attention_probs = self.dropout(attention_probs)
173
+ attention = torch.matmul(attention_probs, v).permute(0, 2, 1,
174
+ 3) # b s h d
175
+ else:
176
+ # Triton implementation only supports 0 attention dropout
177
+ convert_dtype = qkv.dtype not in [torch.float16, torch.bfloat16]
178
+ if convert_dtype:
179
+ # Triton implementation only supports fp16 and bf16
180
+ orig_dtype = qkv.dtype
181
+ qkv = qkv.to(torch.float16)
182
+ bias_dtype = bias.dtype
183
+ bias = bias.to(torch.float16)
184
+ attention = flash_attn_qkvpacked_func(qkv, bias)
185
+ attention = attention.to(orig_dtype)
186
+ bias = bias.to(bias_dtype)
187
+ else:
188
+ attention = flash_attn_qkvpacked_func(qkv, bias)
189
+
190
+ # attn_mask is 1 for attend and 0 for don't
191
+ attention = unpad_input_only(attention, torch.squeeze(attn_mask) == 1)
192
+ return rearrange(attention, 'nnz h d -> nnz (h d)')
193
+
194
+
195
+ # Copy of transformer's library BertSelfOutput that will not be caught by surgery methods looking for HF BERT modules.
196
+ class BertSelfOutput(nn.Module):
197
+
198
+ def __init__(self, config):
199
+ super().__init__()
200
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
201
+ self.LayerNorm = nn.LayerNorm(config.hidden_size,
202
+ eps=config.layer_norm_eps)
203
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
204
+
205
+ def forward(self, hidden_states: torch.Tensor,
206
+ input_tensor: torch.Tensor) -> torch.Tensor:
207
+ hidden_states = self.dense(hidden_states)
208
+ hidden_states = self.dropout(hidden_states)
209
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
210
+ return hidden_states
211
+
212
+
213
+ class BertUnpadAttention(nn.Module):
214
+ """Chains attention, Dropout, and LayerNorm for Mosaic BERT."""
215
+
216
+ def __init__(self, config):
217
+ super().__init__()
218
+ self.self = BertUnpadSelfAttention(config)
219
+ self.output = BertSelfOutput(config)
220
+
221
+ def forward(
222
+ self,
223
+ input_tensor: torch.Tensor,
224
+ cu_seqlens: torch.Tensor,
225
+ max_s: int,
226
+ subset_idx: Optional[torch.Tensor] = None,
227
+ indices: Optional[torch.Tensor] = None,
228
+ attn_mask: Optional[torch.Tensor] = None,
229
+ bias: Optional[torch.Tensor] = None,
230
+ ) -> torch.Tensor:
231
+ """Forward pass for scaled self-attention without padding.
232
+
233
+ Arguments:
234
+ input_tensor: (total_nnz, dim)
235
+ cu_seqlens: (batch + 1,)
236
+ max_s: int
237
+ subset_idx: () set of indices whose values we care about at the end of the layer
238
+ (e.g., the masked tokens, if this is the final layer).
239
+ indices: None or (total_nnz,)
240
+ attn_mask: None or (batch, max_seqlen_in_batch)
241
+ bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
242
+ """
243
+ self_output = self.self(input_tensor, cu_seqlens, max_s, indices,
244
+ attn_mask, bias)
245
+ if subset_idx is not None:
246
+ return self.output(index_first_axis(self_output, subset_idx),
247
+ index_first_axis(input_tensor, subset_idx))
248
+ else:
249
+ return self.output(self_output, input_tensor)
250
+
251
+
252
+ class BertGatedLinearUnitMLP(nn.Module):
253
+ """Applies the FFN at the end of each Mosaic BERT layer.
254
+
255
+ Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate`
256
+ and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar functionality, but
257
+ introduces Gated Linear Units.
258
+
259
+ Note: Mosaic BERT adds parameters in order to implement Gated Linear Units. To keep parameter count consistent with that of a
260
+ standard Hugging Face BERT, scale down `config.intermediate_size` by 2/3. For example, a Mosaic BERT constructed with
261
+ `config.intermediate_size=2048` will have the same parameter footprint as its Hugging Face BERT counterpart constructed
262
+ with the `config.intermediate_size=3072`.
263
+ However, in most cases it will not be necessary to adjust `config.intermediate_size` since, despite the increased
264
+ parameter size, Mosaic BERT typically offers a net higher throughput than a Hugging Face BERT built from the same `config`.
265
+ """
266
+
267
+ def __init__(self, config):
268
+ super().__init__()
269
+ self.config = config
270
+ self.gated_layers = nn.Linear(config.hidden_size,
271
+ config.intermediate_size * 2,
272
+ bias=False)
273
+ self.act = nn.GELU(approximate='none')
274
+ self.wo = nn.Linear(config.intermediate_size, config.hidden_size)
275
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
276
+ self.layernorm = nn.LayerNorm(config.hidden_size,
277
+ eps=config.layer_norm_eps)
278
+
279
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
280
+ """Compute new hidden states from current hidden states.
281
+
282
+ Args:
283
+ hidden_states (torch.Tensor): The (unpadded) hidden states from
284
+ the attention layer [nnz, dim].
285
+ """
286
+ residual_connection = hidden_states
287
+ # compute the activation
288
+ hidden_states = self.gated_layers(hidden_states)
289
+ gated = hidden_states[:, :self.config.intermediate_size]
290
+ non_gated = hidden_states[:, self.config.intermediate_size:]
291
+ hidden_states = self.act(gated) * non_gated
292
+ hidden_states = self.dropout(hidden_states)
293
+ # multiply by the second matrix
294
+ hidden_states = self.wo(hidden_states)
295
+ # add the residual connection and post-LN
296
+ hidden_states = self.layernorm(hidden_states + residual_connection)
297
+ return hidden_states
298
+
299
+
300
+ class BertLayer(nn.Module):
301
+ """Composes the Mosaic BERT attention and FFN blocks into a single layer."""
302
+
303
+ def __init__(self, config):
304
+ super(BertLayer, self).__init__()
305
+ self.attention = BertUnpadAttention(config)
306
+ self.mlp = BertGatedLinearUnitMLP(config)
307
+
308
+ def forward(
309
+ self,
310
+ hidden_states: torch.Tensor,
311
+ cu_seqlens: torch.Tensor,
312
+ seqlen: int,
313
+ subset_idx: Optional[torch.Tensor] = None,
314
+ indices: Optional[torch.Tensor] = None,
315
+ attn_mask: Optional[torch.Tensor] = None,
316
+ bias: Optional[torch.Tensor] = None,
317
+ ) -> torch.Tensor:
318
+ """Forward pass for a BERT layer, including both attention and MLP.
319
+
320
+ Args:
321
+ hidden_states: (total_nnz, dim)
322
+ cu_seqlens: (batch + 1,)
323
+ seqlen: int
324
+ subset_idx: () set of indices whose values we care about at the end of the layer
325
+ (e.g., the masked tokens, if this is the final layer).
326
+ indices: None or (total_nnz,)
327
+ attn_mask: None or (batch, max_seqlen_in_batch)
328
+ bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
329
+ """
330
+ attention_output = self.attention(hidden_states, cu_seqlens, seqlen,
331
+ subset_idx, indices, attn_mask, bias)
332
+ layer_output = self.mlp(attention_output)
333
+ return layer_output
334
+
335
+
336
+ class BertEncoder(nn.Module):
337
+ """A stack of BERT layers providing the backbone of Mosaic BERT.
338
+
339
+ This module is modeled after the Hugging Face BERT's :class:`~transformers.model.bert.modeling_bert.BertEncoder`,
340
+ but with substantial modifications to implement unpadding and ALiBi.
341
+
342
+ Compared to the analogous Hugging Face BERT module, this module handles unpadding to reduce unnecessary computation
343
+ at padded tokens, and pre-computes attention biases to implement ALiBi.
344
+ """
345
+
346
+ def __init__(self, config):
347
+ super().__init__()
348
+ layer = BertLayer(config)
349
+ self.layer = nn.ModuleList(
350
+ [copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
351
+
352
+ self.num_attention_heads = config.num_attention_heads
353
+
354
+ # The alibi mask will be dynamically expanded if it is too small for
355
+ # the input the model receives. But it generally helps to initialize it
356
+ # to a reasonably large size to help pre-allocate CUDA memory.
357
+ # The default `alibi_starting_size` is 512.
358
+ self._current_alibi_size = int(config.alibi_starting_size)
359
+ self.alibi = torch.zeros(
360
+ (1, self.num_attention_heads, self._current_alibi_size,
361
+ self._current_alibi_size))
362
+ self.rebuild_alibi_tensor(size=config.alibi_starting_size)
363
+
364
+ def rebuild_alibi_tensor(self,
365
+ size: int,
366
+ device: Optional[Union[torch.device, str]] = None):
367
+ # Alibi
368
+ # Following https://github.com/ofirpress/attention_with_linear_biases/issues/5 (Implementation 1)
369
+ # In the causal case, you can exploit the fact that softmax is invariant to a uniform translation
370
+ # of the logits, which makes the math work out *after* applying causal masking. If no causal masking
371
+ # will be applied, it is necessary to construct the diagonal mask.
372
+ n_heads = self.num_attention_heads
373
+
374
+ def _get_alibi_head_slopes(n_heads: int) -> List[float]:
375
+
376
+ def get_slopes_power_of_2(n_heads: int) -> List[float]:
377
+ start = (2**(-2**-(math.log2(n_heads) - 3)))
378
+ ratio = start
379
+ return [start * ratio**i for i in range(n_heads)]
380
+
381
+ # In the paper, they only train models that have 2^a heads for some a. This function
382
+ # has some good properties that only occur when the input is a power of 2. To
383
+ # maintain that even when the number of heads is not a power of 2, we use a
384
+ # workaround.
385
+ if math.log2(n_heads).is_integer():
386
+ return get_slopes_power_of_2(n_heads)
387
+
388
+ closest_power_of_2 = 2**math.floor(math.log2(n_heads))
389
+ slopes_a = get_slopes_power_of_2(closest_power_of_2)
390
+ slopes_b = _get_alibi_head_slopes(2 * closest_power_of_2)
391
+ slopes_b = slopes_b[0::2][:n_heads - closest_power_of_2]
392
+ return slopes_a + slopes_b
393
+
394
+ context_position = torch.arange(size, device=device)[:, None]
395
+ memory_position = torch.arange(size, device=device)[None, :]
396
+ relative_position = torch.abs(memory_position - context_position)
397
+ # [n_heads, max_token_length, max_token_length]
398
+ relative_position = relative_position.unsqueeze(0).expand(
399
+ n_heads, -1, -1)
400
+ slopes = torch.Tensor(_get_alibi_head_slopes(n_heads)).to(device)
401
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * -relative_position
402
+ # [1, n_heads, max_token_length, max_token_length]
403
+ alibi = alibi.unsqueeze(0)
404
+ assert alibi.shape == torch.Size([1, n_heads, size, size])
405
+
406
+ self._current_alibi_size = size
407
+ self.alibi = alibi
408
+
409
+ def forward(
410
+ self,
411
+ hidden_states: torch.Tensor,
412
+ attention_mask: torch.Tensor,
413
+ output_all_encoded_layers: Optional[bool] = True,
414
+ subset_mask: Optional[torch.Tensor] = None,
415
+ ) -> List[torch.Tensor]:
416
+
417
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
418
+ extended_attention_mask = extended_attention_mask.to(
419
+ dtype=torch.float32) # fp16 compatibility
420
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
421
+
422
+ attention_mask_bool = attention_mask.bool()
423
+ batch, seqlen = hidden_states.shape[:2]
424
+ # Unpad inputs and mask. It will remove tokens that are padded.
425
+ # Assume ntokens is total number of tokens (padded and non-padded)
426
+ # and ntokens_unpad is total number of non-padded tokens.
427
+ # Then unpadding performs the following compression of the inputs:
428
+ # hidden_states[ntokens,hidden] -> hidden_states[ntokens_unpad,hidden]
429
+ hidden_states, indices, cu_seqlens, _ = unpad_input(
430
+ hidden_states, attention_mask_bool)
431
+
432
+ # Add alibi matrix to extended_attention_mask
433
+ if self._current_alibi_size < seqlen:
434
+ # Rebuild the alibi tensor when needed
435
+ warnings.warn(
436
+ f'Increasing alibi size from {self._current_alibi_size} to {seqlen}'
437
+ )
438
+ self.rebuild_alibi_tensor(size=seqlen, device=hidden_states.device)
439
+ elif self.alibi.device != hidden_states.device:
440
+ # Device catch-up
441
+ self.alibi = self.alibi.to(hidden_states.device)
442
+ alibi_bias = self.alibi[:, :, :seqlen, :seqlen]
443
+ attn_bias = extended_attention_mask[:, :, :seqlen, :seqlen]
444
+ alibi_attn_mask = attn_bias + alibi_bias
445
+
446
+ all_encoder_layers = []
447
+ if subset_mask is None:
448
+ for layer_module in self.layer:
449
+ hidden_states = layer_module(hidden_states,
450
+ cu_seqlens,
451
+ seqlen,
452
+ None,
453
+ indices,
454
+ attn_mask=attention_mask,
455
+ bias=alibi_attn_mask)
456
+ if output_all_encoded_layers:
457
+ all_encoder_layers.append(hidden_states)
458
+ # Pad inputs and mask. It will insert back zero-padded tokens.
459
+ # Assume ntokens is total number of tokens (padded and non-padded)
460
+ # and ntokens_unpad is total number of non-padded tokens.
461
+ # Then padding performs the following de-compression:
462
+ # hidden_states[ntokens_unpad,hidden] -> hidden_states[ntokens,hidden]
463
+ hidden_states = pad_input(hidden_states, indices, batch, seqlen)
464
+ else:
465
+ for i in range(len(self.layer) - 1):
466
+ layer_module = self.layer[i]
467
+ hidden_states = layer_module(hidden_states,
468
+ cu_seqlens,
469
+ seqlen,
470
+ None,
471
+ indices,
472
+ attn_mask=attention_mask,
473
+ bias=alibi_attn_mask)
474
+ if output_all_encoded_layers:
475
+ all_encoder_layers.append(hidden_states)
476
+ subset_idx = torch.nonzero(subset_mask[attention_mask_bool],
477
+ as_tuple=False).flatten()
478
+ hidden_states = self.layer[-1](hidden_states,
479
+ cu_seqlens,
480
+ seqlen,
481
+ subset_idx=subset_idx,
482
+ indices=indices,
483
+ attn_mask=attention_mask,
484
+ bias=alibi_attn_mask)
485
+
486
+ if not output_all_encoded_layers:
487
+ all_encoder_layers.append(hidden_states)
488
+ return all_encoder_layers
489
+
490
+
491
+ class BertPooler(nn.Module):
492
+
493
+ def __init__(self, config):
494
+ super(BertPooler, self).__init__()
495
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
496
+ self.activation = nn.Tanh()
497
+
498
+ def forward(self,
499
+ hidden_states: torch.Tensor,
500
+ pool: Optional[bool] = True) -> torch.Tensor:
501
+ # We "pool" the model by simply taking the hidden state corresponding
502
+ # to the first token.
503
+ first_token_tensor = hidden_states[:, 0] if pool else hidden_states
504
+ pooled_output = self.dense(first_token_tensor)
505
+ pooled_output = self.activation(pooled_output)
506
+ return pooled_output
507
+
508
+
509
+ class BertPredictionHeadTransform(nn.Module):
510
+
511
+ def __init__(self, config):
512
+ super().__init__()
513
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
514
+ if isinstance(config.hidden_act, str):
515
+ self.transform_act_fn = ACT2FN[config.hidden_act]
516
+ else:
517
+ self.transform_act_fn = config.hidden_act
518
+ self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
519
+
520
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
521
+ hidden_states = self.dense(hidden_states)
522
+ hidden_states = self.transform_act_fn(hidden_states)
523
+ hidden_states = self.LayerNorm(hidden_states)
524
+ return hidden_states
525
+
526
+
527
+ class BertModel(BertPreTrainedModel):
528
+ """Overall BERT model.
529
+
530
+ Args:
531
+ config: a BertConfig class instance with the configuration to build a new model
532
+
533
+ Inputs:
534
+ `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
535
+ with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
536
+ `extract_features.py`, `run_classifier.py` and `run_squad.py`)
537
+ `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
538
+ types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
539
+ a `sentence B` token (see BERT paper for more details).
540
+ `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
541
+ selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
542
+ input sequence length in the current batch. It's the mask that we typically use for attention when
543
+ a batch has varying length sentences.
544
+ `output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.
545
+
546
+ Outputs: Tuple of (encoded_layers, pooled_output)
547
+ `encoded_layers`: controlled by `output_all_encoded_layers` argument:
548
+ - `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end
549
+ of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each
550
+ encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],
551
+ - `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding
552
+ to the last attention block of shape [batch_size, sequence_length, hidden_size],
553
+ `pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a
554
+ classifier pretrained on top of the hidden state associated to the first character of the
555
+ input (`CLS`) to train on the Next-Sentence task (see BERT's paper).
556
+
557
+ Example usage:
558
+ ```python
559
+ # Already been converted into WordPiece token ids
560
+ input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
561
+ input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
562
+ token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
563
+ config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
564
+ num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
565
+ model = BertModel(config=config)
566
+ all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
567
+ ```
568
+ """
569
+
570
+ def __init__(self, config, add_pooling_layer=True):
571
+ super(BertModel, self).__init__(config)
572
+ self.embeddings = BertEmbeddings(config)
573
+ self.encoder = BertEncoder(config)
574
+ self.pooler = BertPooler(config) if add_pooling_layer else None
575
+ self.post_init()
576
+
577
+ def get_input_embeddings(self):
578
+ return self.embeddings.word_embeddings
579
+
580
+ def set_input_embeddings(self, value):
581
+ self.embeddings.word_embeddings = value
582
+
583
+ def forward(
584
+ self,
585
+ input_ids: torch.Tensor,
586
+ token_type_ids: Optional[torch.Tensor] = None,
587
+ attention_mask: Optional[torch.Tensor] = None,
588
+ position_ids: Optional[torch.Tensor] = None,
589
+ output_all_encoded_layers: Optional[bool] = False,
590
+ masked_tokens_mask: Optional[torch.Tensor] = None,
591
+ **kwargs
592
+ ) -> Tuple[Union[List[torch.Tensor], torch.Tensor], Optional[torch.Tensor]]:
593
+ if attention_mask is None:
594
+ attention_mask = torch.ones_like(input_ids)
595
+ if token_type_ids is None:
596
+ token_type_ids = torch.zeros_like(input_ids)
597
+
598
+ embedding_output = self.embeddings(input_ids, token_type_ids,
599
+ position_ids)
600
+
601
+ subset_mask = []
602
+ first_col_mask = []
603
+
604
+ if masked_tokens_mask is None:
605
+ subset_mask = None
606
+ else:
607
+ first_col_mask = torch.zeros_like(masked_tokens_mask)
608
+ first_col_mask[:, 0] = True
609
+ subset_mask = masked_tokens_mask | first_col_mask
610
+
611
+ encoder_outputs = self.encoder(
612
+ embedding_output,
613
+ attention_mask,
614
+ output_all_encoded_layers=output_all_encoded_layers,
615
+ subset_mask=subset_mask)
616
+
617
+ if masked_tokens_mask is None:
618
+ sequence_output = encoder_outputs[-1]
619
+ pooled_output = self.pooler(
620
+ sequence_output) if self.pooler is not None else None
621
+ else:
622
+ # TD [2022-03-01]: the indexing here is very tricky.
623
+ attention_mask_bool = attention_mask.bool()
624
+ subset_idx = subset_mask[attention_mask_bool] # type: ignore
625
+ sequence_output = encoder_outputs[-1][
626
+ masked_tokens_mask[attention_mask_bool][subset_idx]]
627
+ if self.pooler is not None:
628
+ pool_input = encoder_outputs[-1][
629
+ first_col_mask[attention_mask_bool][subset_idx]]
630
+ pooled_output = self.pooler(pool_input, pool=False)
631
+ else:
632
+ pooled_output = None
633
+
634
+ if not output_all_encoded_layers:
635
+ encoder_outputs = sequence_output
636
+
637
+ if self.pooler is not None:
638
+ return encoder_outputs, pooled_output
639
+
640
+ return encoder_outputs, None
641
+
642
+
643
+ ###################
644
+ # Bert Heads
645
+ ###################
646
+ class BertLMPredictionHead(nn.Module):
647
+
648
+ def __init__(self, config, bert_model_embedding_weights):
649
+ super().__init__()
650
+ self.transform = BertPredictionHeadTransform(config)
651
+ # The output weights are the same as the input embeddings, but there is
652
+ # an output-only bias for each token.
653
+ self.decoder = nn.Linear(bert_model_embedding_weights.size(1),
654
+ bert_model_embedding_weights.size(0))
655
+ self.decoder.weight = bert_model_embedding_weights
656
+
657
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
658
+ hidden_states = self.transform(hidden_states)
659
+ hidden_states = self.decoder(hidden_states)
660
+ return hidden_states
661
+
662
+
663
+ class BertOnlyMLMHead(nn.Module):
664
+
665
+ def __init__(self, config, bert_model_embedding_weights):
666
+ super().__init__()
667
+ self.predictions = BertLMPredictionHead(config,
668
+ bert_model_embedding_weights)
669
+
670
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
671
+ prediction_scores = self.predictions(sequence_output)
672
+ return prediction_scores
673
+
674
+
675
+ class BertOnlyNSPHead(nn.Module):
676
+
677
+ def __init__(self, config):
678
+ super().__init__()
679
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
680
+
681
+ def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
682
+ seq_relationship_score = self.seq_relationship(pooled_output)
683
+ return seq_relationship_score
684
+
685
+
686
+
687
+ class BertForMaskedLM(BertPreTrainedModel):
688
+
689
+ def __init__(self, config):
690
+ super().__init__(config)
691
+
692
+ if config.is_decoder:
693
+ warnings.warn(
694
+ 'If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for '
695
+ 'bi-directional self-attention.')
696
+
697
+ self.bert = BertModel(config, add_pooling_layer=False)
698
+ self.cls = BertOnlyMLMHead(config,
699
+ self.bert.embeddings.word_embeddings.weight)
700
+
701
+ # Initialize weights and apply final processing
702
+ self.post_init()
703
+
704
+ # @classmethod
705
+ # def from_composer(cls,
706
+ # pretrained_checkpoint,
707
+ # state_dict=None,
708
+ # cache_dir=None,
709
+ # from_tf=False,
710
+ # config=None,
711
+ # *inputs,
712
+ # **kwargs):
713
+ # """Load from pre-trained."""
714
+ # model = cls(config, *inputs, **kwargs)
715
+ # if from_tf:
716
+ # raise ValueError(
717
+ # 'Mosaic BERT does not support loading TensorFlow weights.')
718
+ # state_dict = torch.load(pretrained_checkpoint)
719
+ # # If the state_dict was saved after wrapping with `composer.HuggingFaceModel`, it takes on the `model` prefix
720
+ # consume_prefix_in_state_dict_if_present(state_dict, prefix='model.')
721
+ # missing_keys, unexpected_keys = model.load_state_dict(state_dict,
722
+ # strict=False)
723
+ # if len(missing_keys) > 0:
724
+ # logger.warning(
725
+ # f"Found these missing keys in the checkpoint: {', '.join(missing_keys)}"
726
+ # )
727
+ # if len(unexpected_keys) > 0:
728
+ # logger.warning(
729
+ # f"Found these unexpected keys in the checkpoint: {', '.join(unexpected_keys)}"
730
+ # )
731
+ # return model
732
+
733
+ def get_output_embeddings(self):
734
+ return self.cls.predictions.decoder
735
+
736
+ def set_output_embeddings(self, new_embeddings):
737
+ self.cls.predictions.decoder = new_embeddings
738
+
739
+ def forward(
740
+ self,
741
+ input_ids: Optional[torch.Tensor] = None,
742
+ attention_mask: Optional[torch.Tensor] = None,
743
+ token_type_ids: Optional[torch.Tensor] = None,
744
+ position_ids: Optional[torch.Tensor] = None,
745
+ head_mask: Optional[torch.Tensor] = None,
746
+ inputs_embeds: Optional[torch.Tensor] = None,
747
+ encoder_hidden_states: Optional[torch.Tensor] = None,
748
+ encoder_attention_mask: Optional[torch.Tensor] = None,
749
+ labels: Optional[torch.Tensor] = None,
750
+ output_attentions: Optional[bool] = None,
751
+ output_hidden_states: Optional[bool] = None,
752
+ return_dict: Optional[bool] = None,
753
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
754
+ # labels should be a `torch.LongTensor` of shape
755
+ # `(batch_size, sequence_length)`. These are used for computing the
756
+ # masked language modeling loss.
757
+ #
758
+ # Indices should be in `[-100, 0, ..., config.vocab_size]` (see
759
+ # `input_ids` docstring) Tokens with indices set to `-100` are ignored
760
+ # (masked), the loss is only computed for the tokens with labels in `[0,
761
+ # ..., config.vocab_size]`
762
+ #
763
+ # Prediction scores are only computed for masked tokens and the (bs,
764
+ # seqlen) dimensions are flattened
765
+ if (input_ids is not None) == (inputs_embeds is not None):
766
+ raise ValueError('Must specify either input_ids or input_embeds!')
767
+
768
+ if labels is None:
769
+ masked_tokens_mask = None
770
+ else:
771
+ masked_tokens_mask = labels > 0
772
+
773
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
774
+
775
+ outputs = self.bert(
776
+ input_ids,
777
+ attention_mask=attention_mask,
778
+ token_type_ids=token_type_ids,
779
+ position_ids=position_ids,
780
+ head_mask=head_mask,
781
+ inputs_embeds=inputs_embeds,
782
+ encoder_hidden_states=encoder_hidden_states,
783
+ encoder_attention_mask=encoder_attention_mask,
784
+ output_attentions=output_attentions,
785
+ output_hidden_states=output_hidden_states,
786
+ return_dict=return_dict,
787
+ masked_tokens_mask=masked_tokens_mask,
788
+ )
789
+
790
+ sequence_output = outputs[0]
791
+ prediction_scores = self.cls(sequence_output)
792
+
793
+ loss = None
794
+ if labels is not None:
795
+ # Compute loss
796
+ loss_fct = nn.CrossEntropyLoss()
797
+ masked_token_idx = torch.nonzero(labels.flatten() > 0,
798
+ as_tuple=False).flatten()
799
+ loss = loss_fct(prediction_scores,
800
+ labels.flatten()[masked_token_idx])
801
+
802
+ assert input_ids is not None, 'Coding error; please open an issue'
803
+ batch, seqlen = input_ids.shape[:2]
804
+ prediction_scores = rearrange(index_put_first_axis(
805
+ prediction_scores, masked_token_idx, batch * seqlen),
806
+ '(b s) d -> b s d',
807
+ b=batch)
808
+
809
+ if not return_dict:
810
+ output = (prediction_scores,) + outputs[2:]
811
+ return ((loss,) + output) if loss is not None else output
812
+
813
+ return MaskedLMOutput(
814
+ loss=loss,
815
+ logits=prediction_scores,
816
+ hidden_states=outputs[0],
817
+ attentions=None,
818
+ )
819
+
820
+ def prepare_inputs_for_generation(self, input_ids: torch.Tensor,
821
+ attention_mask: torch.Tensor,
822
+ **model_kwargs):
823
+ input_shape = input_ids.shape
824
+ effective_batch_size = input_shape[0]
825
+
826
+ # add a dummy token
827
+ if self.config.pad_token_id is None:
828
+ raise ValueError('The PAD token should be defined for generation')
829
+
830
+ attention_mask = torch.cat([
831
+ attention_mask,
832
+ attention_mask.new_zeros((attention_mask.shape[0], 1))
833
+ ],
834
+ dim=-1)
835
+ dummy_token = torch.full((effective_batch_size, 1),
836
+ self.config.pad_token_id,
837
+ dtype=torch.long,
838
+ device=input_ids.device)
839
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
840
+
841
+ return {'input_ids': input_ids, 'attention_mask': attention_mask}
842
+
843
+
844
+
845
+ class BertForSequenceClassification(BertPreTrainedModel):
846
+ """Bert Model transformer with a sequence classification/regression head.
847
+
848
+ This head is just a linear layer on top of the pooled output. Used for,
849
+ e.g., GLUE tasks.
850
+ """
851
+
852
+ def __init__(self, config):
853
+ super().__init__(config)
854
+ self.num_labels = config.num_labels
855
+ self.config = config
856
+
857
+ self.bert = BertModel(config)
858
+ classifier_dropout = (config.classifier_dropout
859
+ if config.classifier_dropout is not None else
860
+ config.hidden_dropout_prob)
861
+ self.dropout = nn.Dropout(classifier_dropout)
862
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
863
+
864
+ # Initialize weights and apply final processing
865
+ self.post_init()
866
+
867
+ # @classmethod
868
+ # def from_composer(cls,
869
+ # pretrained_checkpoint,
870
+ # state_dict=None,
871
+ # cache_dir=None,
872
+ # from_tf=False,
873
+ # config=None,
874
+ # *inputs,
875
+ # **kwargs):
876
+ # """Load from pre-trained."""
877
+ # model = cls(config, *inputs, **kwargs)
878
+ # if from_tf:
879
+ # raise ValueError(
880
+ # 'Mosaic BERT does not support loading TensorFlow weights.')#
881
+ #
882
+ # state_dict = torch.load(pretrained_checkpoint)
883
+ # # If the state_dict was saved after wrapping with `composer.HuggingFaceModel`, it takes on the `model` prefix
884
+ # consume_prefix_in_state_dict_if_present(state_dict, prefix='model.')
885
+ # missing_keys, unexpected_keys = model.load_state_dict(state_dict,
886
+ # strict=False)
887
+ #
888
+ # if len(missing_keys) > 0:
889
+ # logger.warning(
890
+ # f"Found these missing keys in the checkpoint: {', '.join(missing_keys)}"
891
+ # )
892
+ # if len(unexpected_keys) > 0:
893
+ # logger.warning(
894
+ # f"Found these unexpected keys in the checkpoint: {', '.join(unexpected_keys)}"
895
+ # )
896
+ # return model
897
+
898
+ def forward(
899
+ self,
900
+ input_ids: Optional[torch.Tensor] = None,
901
+ attention_mask: Optional[torch.Tensor] = None,
902
+ token_type_ids: Optional[torch.Tensor] = None,
903
+ position_ids: Optional[torch.Tensor] = None,
904
+ head_mask: Optional[torch.Tensor] = None,
905
+ inputs_embeds: Optional[torch.Tensor] = None,
906
+ labels: Optional[torch.Tensor] = None,
907
+ output_attentions: Optional[bool] = None,
908
+ output_hidden_states: Optional[bool] = None,
909
+ return_dict: Optional[bool] = None,
910
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
911
+ # labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
912
+ # Labels for computing the sequence classification/regression loss.
913
+ # Indices should be in `[0, ..., config.num_labels - 1]`.
914
+ # If `config.num_labels == 1` a regression loss is computed
915
+ # (mean-square loss). If `config.num_labels > 1` a classification loss
916
+ # is computed (cross-entropy).
917
+
918
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
919
+
920
+ outputs = self.bert(
921
+ input_ids,
922
+ attention_mask=attention_mask,
923
+ token_type_ids=token_type_ids,
924
+ position_ids=position_ids,
925
+ head_mask=head_mask,
926
+ inputs_embeds=inputs_embeds,
927
+ output_attentions=output_attentions,
928
+ output_hidden_states=output_hidden_states,
929
+ return_dict=return_dict,
930
+ )
931
+
932
+ pooled_output = outputs[1]
933
+
934
+ pooled_output = self.dropout(pooled_output)
935
+ logits = self.classifier(pooled_output)
936
+
937
+ loss = None
938
+ if labels is not None:
939
+ # Compute loss
940
+ if self.config.problem_type is None:
941
+ if self.num_labels == 1:
942
+ self.config.problem_type = 'regression'
943
+ elif self.num_labels > 1 and (labels.dtype == torch.long or
944
+ labels.dtype == torch.int):
945
+ self.config.problem_type = 'single_label_classification'
946
+ else:
947
+ self.config.problem_type = 'multi_label_classification'
948
+
949
+ if self.config.problem_type == 'regression':
950
+ loss_fct = nn.MSELoss()
951
+ if self.num_labels == 1:
952
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
953
+ else:
954
+ loss = loss_fct(logits, labels)
955
+ elif self.config.problem_type == 'single_label_classification':
956
+ loss_fct = nn.CrossEntropyLoss()
957
+ loss = loss_fct(logits.view(-1, self.num_labels),
958
+ labels.view(-1))
959
+ elif self.config.problem_type == 'multi_label_classification':
960
+ loss_fct = nn.BCEWithLogitsLoss()
961
+ loss = loss_fct(logits, labels)
962
+
963
+ if not return_dict:
964
+ output = (logits,) + outputs[2:]
965
+ return ((loss,) + output) if loss is not None else output
966
+
967
+ return SequenceClassifierOutput(
968
+ loss=loss,
969
+ logits=logits,
970
+ hidden_states=outputs[0],
971
+ attentions=None,
972
+ )
973
+
bert_padding.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 MosaicML Examples authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # Adapted from https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/bert_padding.py
5
+ # Which was adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py
6
+
7
+ """Helper functions for padding and unpadding batches.
8
+
9
+ These functions are used extensively throughout the Mosaic BERT implementation
10
+ in `bert_layers.py`.
11
+ """
12
+
13
+ from typing import Tuple, cast
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from einops import rearrange, repeat
18
+
19
+
20
+ class IndexFirstAxis(torch.autograd.Function):
21
+
22
+ @staticmethod
23
+ def forward(ctx, input: torch.Tensor,
24
+ indices: torch.Tensor) -> torch.Tensor:
25
+ """Get just the values of `input` which are at `indices`.
26
+ Arguments:
27
+ ctx: the autograd context object
28
+ input: (b, ...) 2+ dimensional tensor
29
+ indices: (num_idx) 1D tensor
30
+ """
31
+ ctx.save_for_backward(indices)
32
+ assert input.ndim >= 2
33
+ ctx.first_axis_dim, other_shape = input.shape[0], input.shape[
34
+ 1:] # type: ignore
35
+ second_dim = other_shape.numel(
36
+ ) # product of sizes of all but first dimension
37
+ # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
38
+ return torch.gather(
39
+ rearrange(input, 'b ... -> b (...)'), # (b, ...) -> (b, second_dim)
40
+ 0,
41
+ repeat(indices, 'z -> z d',
42
+ d=second_dim) # (indices,) -> (indices, second_dim)
43
+ ).reshape(-1, *other_shape) # (num_idx, ...)
44
+
45
+ @staticmethod
46
+ def backward(ctx, grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]:
47
+ indices, = ctx.saved_tensors
48
+ assert grad_output.ndim >= 2
49
+ other_shape = grad_output.shape[1:]
50
+ grad_output = rearrange(grad_output, 'b ... -> b (...)')
51
+ grad_input = torch.zeros([ctx.first_axis_dim, grad_output.shape[1]],
52
+ device=grad_output.device,
53
+ dtype=grad_output.dtype)
54
+ # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
55
+ # grad_input[indices] = grad_output
56
+ grad_input.scatter_(0,
57
+ repeat(indices, 'z -> z d', d=grad_output.shape[1]),
58
+ grad_output)
59
+ return grad_input.reshape(ctx.first_axis_dim, *other_shape), None
60
+
61
+
62
+ index_first_axis = IndexFirstAxis.apply
63
+
64
+
65
+ class IndexPutFirstAxis(torch.autograd.Function):
66
+
67
+ @staticmethod
68
+ def forward(ctx, values: torch.Tensor, indices: torch.Tensor,
69
+ first_axis_dim) -> torch.Tensor:
70
+ ctx.save_for_backward(indices)
71
+ assert indices.ndim == 1
72
+ assert values.ndim >= 2
73
+ output = torch.zeros(first_axis_dim,
74
+ *values.shape[1:],
75
+ device=values.device,
76
+ dtype=values.dtype)
77
+ output[indices] = values
78
+ return output
79
+
80
+ @staticmethod
81
+ def backward(ctx,
82
+ grad_output: torch.Tensor) -> Tuple[torch.Tensor, None, None]:
83
+ indices, = ctx.saved_tensors
84
+ grad_values = grad_output[indices]
85
+ return grad_values, None, None
86
+
87
+
88
+ index_put_first_axis = IndexPutFirstAxis.apply
89
+
90
+
91
+ def unpad_input(
92
+ hidden_states: torch.Tensor,
93
+ attention_mask: torch.Tensor,
94
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
95
+ """Remove padding from input sequences.
96
+ Arguments:
97
+ hidden_states: (batch, seqlen, ...)
98
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
99
+ Returns:
100
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
101
+ indices: (total_nnz)
102
+ cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states.
103
+ max_seqlen_in_batch: int ()
104
+ """
105
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
106
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
107
+ max_seqlen_in_batch = int(seqlens_in_batch.max().item())
108
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32),
109
+ (1, 0))
110
+ # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the
111
+ # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim
112
+ # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to
113
+ # index with integer indices. Moreover, torch's index is a bit slower than it needs to be,
114
+ # so we write custom forward and backward to make it a bit faster.
115
+ hidden_states = cast(
116
+ torch.Tensor,
117
+ index_first_axis(rearrange(hidden_states, 'b s ... -> (b s) ...'),
118
+ indices))
119
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
120
+
121
+
122
+ def unpad_input_only(
123
+ hidden_states: torch.Tensor,
124
+ attention_mask: torch.Tensor,
125
+ ) -> torch.Tensor:
126
+ """Like unpad_input, but only return the unpadded first tensor.
127
+ Save a small amount of overhead.
128
+ Arguments:
129
+ hidden_states: (batch, seqlen, ...)
130
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
131
+ Returns:
132
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
133
+ """
134
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
135
+ return index_first_axis(rearrange(hidden_states, 'b s ... -> (b s) ...'),
136
+ indices)
137
+
138
+
139
+ def pad_input(hidden_states: torch.Tensor, indices: torch.Tensor, batch: int,
140
+ seqlen: int) -> torch.Tensor:
141
+ """Add padding to sequences.
142
+ Arguments:
143
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
144
+ indices: (total_nnz)
145
+ batch: int batch_size
146
+ seqlen: int max sequence length
147
+ Returns:
148
+ hidden_states: (batch, seqlen, ...)
149
+ """
150
+ output = index_put_first_axis(hidden_states, indices, batch * seqlen)
151
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
configuration_bert.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 MosaicML Examples authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ from transformers import BertConfig as TransformersBertConfig
5
+
6
+
7
+ class BertConfig(TransformersBertConfig):
8
+
9
+ def __init__(
10
+ self,
11
+ alibi_starting_size: int = 512,
12
+ attention_probs_dropout_prob: float = 0.0,
13
+ **kwargs,
14
+ ):
15
+ """Configuration class for MosaicBert.
16
+
17
+ Args:
18
+ alibi_starting_size (int): Use `alibi_starting_size` to determine how large of an alibi tensor to
19
+ create when initializing the model. You should be able to ignore this parameter in most cases.
20
+ Defaults to 512.
21
+ attention_probs_dropout_prob (float): By default, turn off attention dropout in Mosaic BERT
22
+ (otherwise, Flash Attention will be off by default). Defaults to 0.0.
23
+ """
24
+ super().__init__(
25
+ attention_probs_dropout_prob=attention_probs_dropout_prob, **kwargs)
26
+ self.alibi_starting_size = alibi_starting_size
flash_attn_triton.py ADDED
@@ -0,0 +1,1328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 MosaicML Examples authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Triton implementation of Flash Attention.
5
+
6
+ # Copyright (c) 2022, Tri Dao.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ *Experimental* implementation of FlashAttention in Triton.
21
+ We use the FlashAttention implementation from Phil Tillet a starting point.
22
+ https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
23
+
24
+ Changes:
25
+ - Implement both causal and non-causal attention.
26
+ - Implement both self-attention and cross-attention.
27
+ - Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
28
+ - Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
29
+ - Support attention bias.
30
+ - Speed up the forward pass a bit, and only store the LSE instead of m and l.
31
+ - Make the backward for d=128 much faster by reducing register spilling.
32
+ - Optionally parallelize the backward pass across seqlen_k, to deal with the case of
33
+ small batch size * nheads.
34
+
35
+ Caution:
36
+ - If you plan to use headdim other than 64 and 128, you should test for race conditions
37
+ (due to the Triton compiler), as done in tests/test_flash_attn.py
38
+ "test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
39
+ for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
40
+ that there are none left for other head dimensions.
41
+ Differences between this Triton version and the CUDA version:
42
+ - Triton version doesn't support dropout.
43
+ - Triton forward is generally faster than CUDA forward.
44
+ - Triton backward is faster than CUDA backward when batch * nheads is small, and when headdim=64.
45
+ It is slightly slower when headdim=128 and batch * nheads is large.
46
+ - Triton version doesn't yet support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
47
+ """
48
+
49
+
50
+ #import triton # type: ignore (reportMissingImports)
51
+ #import triton.language as tl # type: ignore (reportMissingImports)
52
+ from einops import repeat
53
+
54
+ import os
55
+ import torch
56
+ import math
57
+
58
+ #----------------------
59
+
60
+ import os
61
+ import torch
62
+ import math
63
+
64
+ # Check if we should use PyTorch fallback
65
+ USE_PYTORCH_FALLBACK = os.environ.get('USE_PYTORCH_FALLBACK', '1') == '1'
66
+
67
+ if USE_PYTORCH_FALLBACK:
68
+ # Mock triton completely
69
+ class MockTriton:
70
+ @staticmethod
71
+ def autotune(*args, **kwargs):
72
+ def decorator(func):
73
+ return func
74
+ return decorator
75
+
76
+ @staticmethod
77
+ def jit(*args, **kwargs):
78
+ def decorator(func):
79
+ return func
80
+ return decorator
81
+
82
+ @staticmethod
83
+ def heuristics(*args, **kwargs):
84
+ def decorator(func):
85
+ return func
86
+ return decorator
87
+
88
+ @staticmethod
89
+ def next_power_of_2(n):
90
+ return 2 ** math.ceil(math.log2(n))
91
+
92
+ @staticmethod
93
+ def cdiv(x, y):
94
+ return (x + y - 1) // y
95
+
96
+ class Config:
97
+ def __init__(self, *args, **kwargs):
98
+ pass
99
+
100
+ class language:
101
+ pass
102
+
103
+ triton = MockTriton()
104
+ tl = MockTriton.language
105
+
106
+ # Define PyTorch implementation
107
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
108
+ @staticmethod
109
+ def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
110
+ """PyTorch implementation"""
111
+ q, k, v = qkv.unbind(dim=2)
112
+
113
+ if q.dim() == 3:
114
+ q = q.unsqueeze(0).transpose(1, 2)
115
+ k = k.unsqueeze(0).transpose(1, 2)
116
+ v = v.unsqueeze(0).transpose(1, 2)
117
+ squeeze_output = True
118
+ else:
119
+ q = q.transpose(1, 2)
120
+ k = k.transpose(1, 2)
121
+ v = v.transpose(1, 2)
122
+ squeeze_output = False
123
+
124
+ if softmax_scale is None:
125
+ softmax_scale = q.shape[-1] ** (-0.5)
126
+
127
+ attn = torch.matmul(q, k.transpose(-2, -1)) * softmax_scale
128
+
129
+ if bias is not None:
130
+ attn = attn + bias
131
+
132
+ if causal:
133
+ seq_len = q.shape[-2]
134
+ causal_mask = torch.triu(
135
+ torch.ones(seq_len, seq_len, device=q.device, dtype=torch.bool),
136
+ diagonal=1
137
+ )
138
+ attn = attn.masked_fill(causal_mask, float('-inf'))
139
+
140
+ attn_weights = torch.softmax(attn, dim=-1)
141
+ out = torch.matmul(attn_weights, v)
142
+
143
+ ctx.save_for_backward(q, k, v, attn_weights)
144
+ ctx.softmax_scale = softmax_scale
145
+ ctx.causal = causal
146
+ ctx.squeeze_output = squeeze_output
147
+
148
+ if squeeze_output:
149
+ out = out.squeeze(0).transpose(0, 1).contiguous()
150
+ else:
151
+ out = out.transpose(1, 2).contiguous()
152
+
153
+ return out
154
+
155
+ @staticmethod
156
+ def backward(ctx, dout):
157
+ q, k, v, attn_weights = ctx.saved_tensors
158
+ softmax_scale = ctx.softmax_scale
159
+ squeeze_output = ctx.squeeze_output
160
+
161
+ if squeeze_output:
162
+ dout = dout.unsqueeze(0).transpose(1, 2)
163
+ else:
164
+ dout = dout.transpose(1, 2)
165
+
166
+ dv = torch.matmul(attn_weights.transpose(-2, -1), dout)
167
+ d_attn_weights = torch.matmul(dout, v.transpose(-2, -1))
168
+ d_attn = attn_weights * (d_attn_weights - (attn_weights * d_attn_weights).sum(dim=-1, keepdim=True))
169
+ d_attn = d_attn * softmax_scale
170
+
171
+ dq = torch.matmul(d_attn, k)
172
+ dk = torch.matmul(d_attn.transpose(-2, -1), q)
173
+
174
+ if squeeze_output:
175
+ dq = dq.squeeze(0).transpose(0, 1)
176
+ dk = dk.squeeze(0).transpose(0, 1)
177
+ dv = dv.squeeze(0).transpose(0, 1)
178
+ else:
179
+ dq = dq.transpose(1, 2)
180
+ dk = dk.transpose(1, 2)
181
+ dv = dv.transpose(1, 2)
182
+
183
+ dqkv = torch.stack([dq, dk, dv], dim=2)
184
+
185
+ return dqkv, None, None, None
186
+
187
+ class FlashAttnFunc(torch.autograd.Function):
188
+ @staticmethod
189
+ def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
190
+ if softmax_scale is None:
191
+ softmax_scale = q.shape[-1] ** (-0.5)
192
+
193
+ attn = torch.matmul(q, k.transpose(-2, -1)) * softmax_scale
194
+
195
+ if bias is not None:
196
+ attn = attn + bias
197
+
198
+ if causal:
199
+ seq_len = q.shape[-2]
200
+ causal_mask = torch.triu(
201
+ torch.ones(seq_len, seq_len, device=q.device, dtype=torch.bool),
202
+ diagonal=1
203
+ )
204
+ attn = attn.masked_fill(causal_mask, float('-inf'))
205
+
206
+ attn_weights = torch.softmax(attn, dim=-1)
207
+ out = torch.matmul(attn_weights, v)
208
+
209
+ ctx.save_for_backward(q, k, v, attn_weights)
210
+ ctx.softmax_scale = softmax_scale
211
+
212
+ return out
213
+
214
+ @staticmethod
215
+ def backward(ctx, dout):
216
+ q, k, v, attn_weights = ctx.saved_tensors
217
+ softmax_scale = ctx.softmax_scale
218
+
219
+ dv = torch.matmul(attn_weights.transpose(-2, -1), dout)
220
+ d_attn_weights = torch.matmul(dout, v.transpose(-2, -1))
221
+ d_attn = attn_weights * (d_attn_weights - (attn_weights * d_attn_weights).sum(dim=-1, keepdim=True))
222
+ d_attn = d_attn * softmax_scale
223
+
224
+ dq = torch.matmul(d_attn, k)
225
+ dk = torch.matmul(d_attn.transpose(-2, -1), q)
226
+
227
+ return dq, dk, dv, None, None, None
228
+
229
+ def flash_attn_qkvpacked_func(qkv, bias=None, causal=False, softmax_scale=None):
230
+ return FlashAttnQKVPackedFunc.apply(qkv, bias, causal, softmax_scale)
231
+
232
+ def flash_attn_func(q, k, v, bias=None, causal=False, softmax_scale=None):
233
+ return FlashAttnFunc.apply(q, k, v, bias, causal, softmax_scale)
234
+
235
+ # Create dummy functions for anything else that might be imported
236
+ def _flash_attn_forward(*args, **kwargs):
237
+ raise NotImplementedError("Using PyTorch fallback")
238
+
239
+ def _flash_attn_backward(*args, **kwargs):
240
+ raise NotImplementedError("Using PyTorch fallback")
241
+
242
+ # STOP HERE - don't execute the rest of the file
243
+ print("Using PyTorch fallback for Flash Attention")
244
+
245
+ else:
246
+ # Only if NOT using fallback, import triton and continue with original code
247
+ import triton
248
+ import triton.language as tl
249
+
250
+
251
+ #if USE_PYTORCH_FALLBACK:
252
+ # # Override all functions with PyTorch implementations
253
+ # def flash_attn_qkvpacked_func(qkv, bias=None, causal=False, softmax_scale=None):
254
+ # q, k, v = qkv.unbind(dim=2)
255
+ # if softmax_scale is None:
256
+ # softmax_scale = q.shape[-1] ** (-0.5)
257
+ # attn = torch.matmul(q, k.transpose(-2, -1)) * softmax_scale
258
+ # if bias is not None:
259
+ # attn = attn + bias
260
+ # if causal:
261
+ # seq_len = q.shape[-2]
262
+ # mask = torch.triu(torch.ones(seq_len, seq_len, device=q.device, dtype=torch.bool), diagonal=1)
263
+ # attn = attn.masked_fill(mask, float('-inf'))
264
+ # attn = torch.softmax(attn, dim=-1)
265
+ # return torch.matmul(attn, v)
266
+ #----------------------added codde to circumvent triton issue on minerva
267
+
268
+
269
+ if not USE_PYTORCH_FALLBACK:
270
+ @triton.autotune(
271
+ configs=[
272
+ triton.Config({
273
+ 'BLOCK_M': 128,
274
+ 'BLOCK_N': 128
275
+ },
276
+ num_warps=8,
277
+ num_stages=1),
278
+ # This config has a race condition when EVEN_M == False, disabling it for now.
279
+ # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1),
280
+ ],
281
+ key=[
282
+ 'CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL',
283
+ 'BLOCK_HEADDIM'
284
+ ])
285
+ @triton.heuristics({
286
+ 'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0,
287
+ 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0,
288
+ 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM'],
289
+ })
290
+ @triton.jit
291
+ def _fwd_kernel(
292
+ Q,
293
+ K,
294
+ V,
295
+ Bias,
296
+ Out,
297
+ Lse,
298
+ TMP, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug
299
+ softmax_scale,
300
+ stride_qb,
301
+ stride_qh,
302
+ stride_qm,
303
+ stride_kb,
304
+ stride_kh,
305
+ stride_kn,
306
+ stride_vb,
307
+ stride_vh,
308
+ stride_vn,
309
+ stride_bb,
310
+ stride_bh,
311
+ stride_bm,
312
+ stride_ob,
313
+ stride_oh,
314
+ stride_om,
315
+ nheads,
316
+ seqlen_q,
317
+ seqlen_k,
318
+ seqlen_q_rounded,
319
+ headdim,
320
+ CACHE_KEY_SEQLEN_Q,
321
+ CACHE_KEY_SEQLEN_K,
322
+ BIAS_TYPE: tl.constexpr,
323
+ IS_CAUSAL: tl.constexpr,
324
+ BLOCK_HEADDIM: tl.constexpr,
325
+ EVEN_M: tl.constexpr,
326
+ EVEN_N: tl.constexpr,
327
+ EVEN_HEADDIM: tl.constexpr,
328
+ BLOCK_M: tl.constexpr,
329
+ BLOCK_N: tl.constexpr,
330
+ ):
331
+ start_m = tl.program_id(0)
332
+ off_hb = tl.program_id(1)
333
+ off_b = off_hb // nheads
334
+ off_h = off_hb % nheads
335
+ # off_b = tl.program_id(1)
336
+ # off_h = tl.program_id(2)
337
+ # off_hb = off_b * nheads + off_h
338
+ # initialize offsets
339
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
340
+ offs_n = tl.arange(0, BLOCK_N)
341
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
342
+ # Initialize pointers to Q, K, V
343
+ # Adding parenthesis around indexing might use int32 math instead of int64 math?
344
+ # https://github.com/openai/triton/issues/741
345
+ # I'm seeing a tiny bit of difference (5-7us)
346
+ q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (
347
+ offs_m[:, None] * stride_qm + offs_d[None, :])
348
+ k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (
349
+ offs_n[:, None] * stride_kn + offs_d[None, :])
350
+ v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (
351
+ offs_n[:, None] * stride_vn + offs_d[None, :])
352
+ if BIAS_TYPE == 'vector':
353
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
354
+ elif BIAS_TYPE == 'matrix':
355
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (
356
+ offs_m[:, None] * stride_bm + offs_n[None, :])
357
+ else:
358
+ raise ValueError("BIAS_TYPE must be one of {'vector', 'matrix'}")
359
+ # initialize pointer to m and l
360
+ t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
361
+ lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
362
+ m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
363
+ acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
364
+ # load q: it will stay in SRAM throughout
365
+ # [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call
366
+ # tl.load(q_ptrs), we get the wrong output!
367
+ if EVEN_M & EVEN_N:
368
+ if EVEN_HEADDIM:
369
+ q = tl.load(q_ptrs)
370
+ else:
371
+ q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
372
+ else:
373
+ if EVEN_HEADDIM:
374
+ q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
375
+ else:
376
+ q = tl.load(q_ptrs,
377
+ mask=(offs_m[:, None] < seqlen_q) &
378
+ (offs_d[None, :] < headdim),
379
+ other=0.0)
380
+ # loop over k, v and update accumulator
381
+ end_n = seqlen_k if not IS_CAUSAL else tl.minimum(
382
+ (start_m + 1) * BLOCK_M, seqlen_k)
383
+ for start_n in range(0, end_n, BLOCK_N):
384
+ start_n = tl.multiple_of(start_n, BLOCK_N)
385
+ # -- compute qk ----
386
+ if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
387
+ if EVEN_HEADDIM:
388
+ k = tl.load(k_ptrs + start_n * stride_kn)
389
+ else:
390
+ k = tl.load(k_ptrs + start_n * stride_kn,
391
+ mask=offs_d[None, :] < headdim,
392
+ other=0.0)
393
+ else:
394
+ if EVEN_HEADDIM:
395
+ k = tl.load(k_ptrs + start_n * stride_kn,
396
+ mask=(start_n + offs_n)[:, None] < seqlen_k,
397
+ other=0.0)
398
+ else:
399
+ k = tl.load(k_ptrs + start_n * stride_kn,
400
+ mask=((start_n + offs_n)[:, None] < seqlen_k) &
401
+ (offs_d[None, :] < headdim),
402
+ other=0.0)
403
+ qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
404
+ qk += tl.dot(q, k, trans_b=True)
405
+ # Trying to combine the two masks seem to make the result wrong
406
+ if not EVEN_N: # Need to mask out otherwise the softmax is wrong
407
+ qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0,
408
+ float('-inf'))
409
+ if IS_CAUSAL:
410
+ qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0,
411
+ float('-inf'))
412
+ if BIAS_TYPE != 'none':
413
+ if BIAS_TYPE == 'vector':
414
+ if EVEN_N:
415
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
416
+ else:
417
+ bias = tl.load(b_ptrs + start_n,
418
+ mask=(start_n + offs_n) < seqlen_k,
419
+ other=0.0).to(tl.float32)
420
+ bias = bias[None, :]
421
+ elif BIAS_TYPE == 'matrix':
422
+ if EVEN_M & EVEN_N:
423
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
424
+ else:
425
+ bias = tl.load(b_ptrs + start_n,
426
+ mask=(offs_m[:, None] < seqlen_q) &
427
+ ((start_n + offs_n)[None, :] < seqlen_k),
428
+ other=0.0).to(tl.float32)
429
+ else:
430
+ raise ValueError(
431
+ "BIAS_TYPE must be one of {'vector', 'matrix'}")
432
+ # Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler
433
+ # can then fuse the mult and add into an fma instruction. But if we have bias we need to
434
+ # to multiply with softmax_scale here.
435
+ qk = qk * softmax_scale + bias
436
+ m_ij = tl.maximum(tl.max(qk, 1), lse_i)
437
+ p = tl.exp(qk - m_ij[:, None])
438
+ else:
439
+ m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
440
+ p = tl.exp(qk * softmax_scale - m_ij[:, None])
441
+ l_ij = tl.sum(p, 1)
442
+
443
+ # scale acc_o
444
+ acc_o_scale = tl.exp(m_i - m_ij)
445
+
446
+ # # -- update output accumulator --
447
+ # BUG: have to store and immediately load
448
+ tl.store(t_ptrs, acc_o_scale)
449
+ acc_o_scale = tl.load(t_ptrs)
450
+ acc_o = acc_o * acc_o_scale[:, None]
451
+ # update acc_o
452
+ if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
453
+ if EVEN_HEADDIM:
454
+ v = tl.load(v_ptrs + start_n * stride_vn)
455
+ else:
456
+ v = tl.load(v_ptrs + start_n * stride_vn,
457
+ mask=offs_d[None, :] < headdim,
458
+ other=0.0)
459
+ else:
460
+ if EVEN_HEADDIM:
461
+ v = tl.load(v_ptrs + start_n * stride_vn,
462
+ mask=(start_n + offs_n)[:, None] < seqlen_k,
463
+ other=0.0)
464
+ else:
465
+ v = tl.load(v_ptrs + start_n * stride_vn,
466
+ mask=((start_n + offs_n)[:, None] < seqlen_k) &
467
+ (offs_d[None, :] < headdim),
468
+ other=0.0)
469
+ p = p.to(v.dtype)
470
+ acc_o += tl.dot(p, v)
471
+
472
+ # -- update statistics
473
+ m_i = m_ij
474
+ l_i_new = tl.exp(lse_i - m_ij) + l_ij
475
+ lse_i = m_ij + tl.log(l_i_new)
476
+
477
+ o_scale = tl.exp(m_i - lse_i)
478
+ # BUG: have to store and immediately load
479
+ tl.store(t_ptrs, o_scale)
480
+ o_scale = tl.load(t_ptrs)
481
+ acc_o = acc_o * o_scale[:, None]
482
+ # rematerialize offsets to save registers
483
+ start_m = tl.program_id(0)
484
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
485
+ # write back l and m
486
+ lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
487
+ tl.store(lse_ptrs, lse_i)
488
+ # initialize pointers to output
489
+ offs_n = tl.arange(0, BLOCK_HEADDIM)
490
+ out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (
491
+ offs_m[:, None] * stride_om + offs_n[None, :])
492
+ if EVEN_M:
493
+ if EVEN_HEADDIM:
494
+ tl.store(out_ptrs, acc_o)
495
+ else:
496
+ tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
497
+ else:
498
+ if EVEN_HEADDIM:
499
+ tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
500
+ else:
501
+ tl.store(out_ptrs,
502
+ acc_o,
503
+ mask=(offs_m[:, None] < seqlen_q) &
504
+ (offs_d[None, :] < headdim))
505
+
506
+
507
+ @triton.jit
508
+ def _bwd_preprocess_do_o_dot(
509
+ Out,
510
+ DO,
511
+ Delta,
512
+ stride_ob,
513
+ stride_oh,
514
+ stride_om,
515
+ stride_dob,
516
+ stride_doh,
517
+ stride_dom,
518
+ nheads,
519
+ seqlen_q,
520
+ seqlen_q_rounded,
521
+ headdim,
522
+ BLOCK_M: tl.constexpr,
523
+ BLOCK_HEADDIM: tl.constexpr,
524
+ ):
525
+ start_m = tl.program_id(0)
526
+ off_hb = tl.program_id(1)
527
+ off_b = off_hb // nheads
528
+ off_h = off_hb % nheads
529
+ # initialize offsets
530
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
531
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
532
+ # load
533
+ o = tl.load(Out + off_b * stride_ob + off_h * stride_oh +
534
+ offs_m[:, None] * stride_om + offs_d[None, :],
535
+ mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
536
+ other=0.0).to(tl.float32)
537
+ do = tl.load(DO + off_b * stride_dob + off_h * stride_doh +
538
+ offs_m[:, None] * stride_dom + offs_d[None, :],
539
+ mask=(offs_m[:, None] < seqlen_q) &
540
+ (offs_d[None, :] < headdim),
541
+ other=0.0).to(tl.float32)
542
+ delta = tl.sum(o * do, axis=1)
543
+ # write-back
544
+ tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
545
+
546
+
547
+ @triton.jit
548
+ def _bwd_kernel_one_col_block(
549
+ start_n,
550
+ Q,
551
+ K,
552
+ V,
553
+ Bias,
554
+ DO,
555
+ DQ,
556
+ DK,
557
+ DV,
558
+ LSE,
559
+ D,
560
+ softmax_scale,
561
+ stride_qm,
562
+ stride_kn,
563
+ stride_vn,
564
+ stride_bm,
565
+ stride_dom,
566
+ stride_dqm,
567
+ stride_dkn,
568
+ stride_dvn,
569
+ seqlen_q,
570
+ seqlen_k,
571
+ headdim,
572
+ ATOMIC_ADD: tl.constexpr,
573
+ BIAS_TYPE: tl.constexpr,
574
+ IS_CAUSAL: tl.constexpr,
575
+ BLOCK_HEADDIM: tl.constexpr,
576
+ EVEN_M: tl.constexpr,
577
+ EVEN_N: tl.constexpr,
578
+ EVEN_HEADDIM: tl.constexpr,
579
+ BLOCK_M: tl.constexpr,
580
+ BLOCK_N: tl.constexpr,
581
+ ):
582
+ # We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N)
583
+ begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M
584
+ # initialize row/col offsets
585
+ offs_qm = begin_m + tl.arange(0, BLOCK_M)
586
+ offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
587
+ offs_m = tl.arange(0, BLOCK_M)
588
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
589
+ # initialize pointers to value-like data
590
+ q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
591
+ k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
592
+ v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
593
+ do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
594
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
595
+ if BIAS_TYPE == 'vector':
596
+ b_ptrs = Bias + offs_n
597
+ elif BIAS_TYPE == 'matrix':
598
+ b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
599
+ else:
600
+ raise ValueError("BIAS_TYPE must be one of {'vector', 'matrix'}")
601
+ # initialize dv and dk
602
+ dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
603
+ dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
604
+ # k and v stay in SRAM throughout
605
+ # [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False,
606
+ # if we just call tl.load(k_ptrs), we get the wrong output!
607
+ if EVEN_N & EVEN_M:
608
+ if EVEN_HEADDIM:
609
+ k = tl.load(k_ptrs)
610
+ v = tl.load(v_ptrs)
611
+ else:
612
+ k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
613
+ v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
614
+ else:
615
+ if EVEN_HEADDIM:
616
+ k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
617
+ v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
618
+ else:
619
+ k = tl.load(k_ptrs,
620
+ mask=(offs_n[:, None] < seqlen_k) &
621
+ (offs_d[None, :] < headdim),
622
+ other=0.0)
623
+ v = tl.load(v_ptrs,
624
+ mask=(offs_n[:, None] < seqlen_k) &
625
+ (offs_d[None, :] < headdim),
626
+ other=0.0)
627
+ # loop over rows
628
+ num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
629
+ for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
630
+ start_m = tl.multiple_of(start_m, BLOCK_M)
631
+ offs_m_curr = start_m + offs_m
632
+ # load q, k, v, do on-chip
633
+ # Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117)
634
+ if EVEN_M & EVEN_HEADDIM:
635
+ q = tl.load(q_ptrs)
636
+ else:
637
+ if EVEN_HEADDIM:
638
+ q = tl.load(q_ptrs,
639
+ mask=offs_m_curr[:, None] < seqlen_q,
640
+ other=0.0)
641
+ else:
642
+ q = tl.load(q_ptrs,
643
+ mask=(offs_m_curr[:, None] < seqlen_q) &
644
+ (offs_d[None, :] < headdim),
645
+ other=0.0)
646
+ # recompute p = softmax(qk, dim=-1).T
647
+ qk = tl.dot(q, k, trans_b=True)
648
+ # Trying to combine the two masks seem to make the result wrong
649
+ if not EVEN_N: # Need to mask out otherwise the softmax is wrong
650
+ qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
651
+ if IS_CAUSAL:
652
+ qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk,
653
+ float('-inf'))
654
+ if BIAS_TYPE != 'none':
655
+ if BIAS_TYPE == 'vector':
656
+ if EVEN_N:
657
+ bias = tl.load(b_ptrs).to(tl.float32)
658
+ else:
659
+ bias = tl.load(b_ptrs, mask=offs_n < seqlen_k,
660
+ other=0.0).to(tl.float32)
661
+ bias = bias[None, :]
662
+ elif BIAS_TYPE == 'matrix':
663
+ if EVEN_M & EVEN_N:
664
+ bias = tl.load(b_ptrs).to(tl.float32)
665
+ else:
666
+ bias = tl.load(b_ptrs,
667
+ mask=(offs_m_curr[:, None] < seqlen_q) &
668
+ (offs_n[None, :] < seqlen_k),
669
+ other=0.0).to(tl.float32)
670
+ else:
671
+ raise ValueError(
672
+ "BIAS_TYPE must be one of {'vector', 'matrix'}")
673
+ qk = qk * softmax_scale + bias
674
+ # There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong.
675
+ # Also wrong for headdim=64.
676
+ if not (EVEN_M & EVEN_HEADDIM):
677
+ tl.debug_barrier()
678
+ lse_i = tl.load(LSE + offs_m_curr)
679
+ if BIAS_TYPE == 'none':
680
+ p = tl.exp(qk * softmax_scale - lse_i[:, None])
681
+ else:
682
+ p = tl.exp(qk - lse_i[:, None])
683
+ # compute dv
684
+ # [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call
685
+ # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs
686
+ # in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512,
687
+ # the output is correct.
688
+ if EVEN_M & EVEN_HEADDIM:
689
+ do = tl.load(do_ptrs)
690
+ else:
691
+ # [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask.
692
+ do = tl.load(do_ptrs,
693
+ mask=(offs_m_curr[:, None] < seqlen_q) &
694
+ (offs_d[None, :] < headdim),
695
+ other=0.0)
696
+ # if EVEN_M:
697
+ # if EVEN_HEADDIM:
698
+ # do = tl.load(do_ptrs)
699
+ # else:
700
+ # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
701
+ # else:
702
+ # if EVEN_HEADDIM:
703
+ # do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
704
+ # else:
705
+ # do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
706
+ # & (offs_d[None, :] < headdim), other=0.0)
707
+ dv += tl.dot(p.to(do.dtype), do, trans_a=True)
708
+ # compute dp = dot(v, do)
709
+ # There seems to be a race condition when headdim=48/96, and dq, dk are wrong.
710
+ # Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True
711
+ # Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False
712
+ if not (EVEN_M & EVEN_HEADDIM):
713
+ tl.debug_barrier()
714
+ dp = tl.dot(do, v, trans_b=True)
715
+ # There's a race condition for headdim=48
716
+ if not EVEN_HEADDIM:
717
+ tl.debug_barrier()
718
+ # compute ds = p * (dp - delta[:, None])
719
+ # Putting the subtraction after the dp matmul (instead of before) is slightly faster
720
+ Di = tl.load(D + offs_m_curr)
721
+ # Converting ds to q.dtype here reduces register pressure and makes it much faster
722
+ # for BLOCK_HEADDIM=128
723
+ ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
724
+ # compute dk = dot(ds.T, q)
725
+ dk += tl.dot(ds, q, trans_a=True)
726
+ # compute dq
727
+ if not ATOMIC_ADD:
728
+ if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
729
+ dq = tl.load(dq_ptrs, eviction_policy='evict_last')
730
+ dq += tl.dot(ds, k)
731
+ tl.store(dq_ptrs, dq, eviction_policy='evict_last')
732
+ else:
733
+ if EVEN_HEADDIM:
734
+ dq = tl.load(dq_ptrs,
735
+ mask=offs_m_curr[:, None] < seqlen_q,
736
+ other=0.0,
737
+ eviction_policy='evict_last')
738
+ dq += tl.dot(ds, k)
739
+ tl.store(dq_ptrs,
740
+ dq,
741
+ mask=offs_m_curr[:, None] < seqlen_q,
742
+ eviction_policy='evict_last')
743
+ else:
744
+ dq = tl.load(dq_ptrs,
745
+ mask=(offs_m_curr[:, None] < seqlen_q) &
746
+ (offs_d[None, :] < headdim),
747
+ other=0.0,
748
+ eviction_policy='evict_last')
749
+ dq += tl.dot(ds, k)
750
+ tl.store(dq_ptrs,
751
+ dq,
752
+ mask=(offs_m_curr[:, None] < seqlen_q) &
753
+ (offs_d[None, :] < headdim),
754
+ eviction_policy='evict_last')
755
+ else: # If we're parallelizing across the seqlen_k dimension
756
+ dq = tl.dot(ds, k)
757
+ if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
758
+ tl.atomic_add(dq_ptrs, dq)
759
+ else:
760
+ if EVEN_HEADDIM:
761
+ tl.atomic_add(dq_ptrs,
762
+ dq,
763
+ mask=offs_m_curr[:, None] < seqlen_q)
764
+ else:
765
+ tl.atomic_add(dq_ptrs,
766
+ dq,
767
+ mask=(offs_m_curr[:, None] < seqlen_q) &
768
+ (offs_d[None, :] < headdim))
769
+ # increment pointers
770
+ dq_ptrs += BLOCK_M * stride_dqm
771
+ q_ptrs += BLOCK_M * stride_qm
772
+ do_ptrs += BLOCK_M * stride_dom
773
+ if BIAS_TYPE == 'matrix':
774
+ b_ptrs += BLOCK_M * stride_bm
775
+ # write-back
776
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
777
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
778
+ # [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False,
779
+ # if we just call tl.store(dv_ptrs), there's a race condition
780
+ if EVEN_N & EVEN_M:
781
+ if EVEN_HEADDIM:
782
+ tl.store(dv_ptrs, dv)
783
+ tl.store(dk_ptrs, dk)
784
+ else:
785
+ tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
786
+ tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
787
+ else:
788
+ if EVEN_HEADDIM:
789
+ tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
790
+ tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
791
+ else:
792
+ tl.store(dv_ptrs,
793
+ dv,
794
+ mask=(offs_n[:, None] < seqlen_k) &
795
+ (offs_d[None, :] < headdim))
796
+ tl.store(dk_ptrs,
797
+ dk,
798
+ mask=(offs_n[:, None] < seqlen_k) &
799
+ (offs_d[None, :] < headdim))
800
+
801
+
802
+ def init_to_zero(name):
803
+ return lambda nargs: nargs[name].zero_()
804
+
805
+
806
+ @triton.autotune(
807
+ configs=[
808
+ triton.Config(
809
+ {
810
+ 'BLOCK_M': 128,
811
+ 'BLOCK_N': 128,
812
+ 'SEQUENCE_PARALLEL': False
813
+ },
814
+ num_warps=8,
815
+ num_stages=1,
816
+ pre_hook=init_to_zero('DQ')),
817
+ triton.Config(
818
+ {
819
+ 'BLOCK_M': 128,
820
+ 'BLOCK_N': 128,
821
+ 'SEQUENCE_PARALLEL': True
822
+ },
823
+ num_warps=8,
824
+ num_stages=1,
825
+ pre_hook=init_to_zero('DQ')),
826
+ # Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now
827
+ # # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4*
828
+ # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
829
+ # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
830
+ # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
831
+ # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
832
+ ],
833
+ key=[
834
+ 'CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL',
835
+ 'BLOCK_HEADDIM'
836
+ ],
837
+ )
838
+ @triton.heuristics({
839
+ 'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0,
840
+ 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0,
841
+ 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM'],
842
+ })
843
+ @triton.jit
844
+ def _bwd_kernel(
845
+ Q,
846
+ K,
847
+ V,
848
+ Bias,
849
+ DO,
850
+ DQ,
851
+ DK,
852
+ DV,
853
+ LSE,
854
+ D,
855
+ softmax_scale,
856
+ stride_qb,
857
+ stride_qh,
858
+ stride_qm,
859
+ stride_kb,
860
+ stride_kh,
861
+ stride_kn,
862
+ stride_vb,
863
+ stride_vh,
864
+ stride_vn,
865
+ stride_bb,
866
+ stride_bh,
867
+ stride_bm,
868
+ stride_dob,
869
+ stride_doh,
870
+ stride_dom,
871
+ stride_dqb,
872
+ stride_dqh,
873
+ stride_dqm,
874
+ stride_dkb,
875
+ stride_dkh,
876
+ stride_dkn,
877
+ stride_dvb,
878
+ stride_dvh,
879
+ stride_dvn,
880
+ nheads,
881
+ seqlen_q,
882
+ seqlen_k,
883
+ seqlen_q_rounded,
884
+ headdim,
885
+ CACHE_KEY_SEQLEN_Q,
886
+ CACHE_KEY_SEQLEN_K,
887
+ BIAS_TYPE: tl.constexpr,
888
+ IS_CAUSAL: tl.constexpr,
889
+ BLOCK_HEADDIM: tl.constexpr,
890
+ SEQUENCE_PARALLEL: tl.constexpr,
891
+ EVEN_M: tl.constexpr,
892
+ EVEN_N: tl.constexpr,
893
+ EVEN_HEADDIM: tl.constexpr,
894
+ BLOCK_M: tl.constexpr,
895
+ BLOCK_N: tl.constexpr,
896
+ ):
897
+ off_hb = tl.program_id(1)
898
+ off_b = off_hb // nheads
899
+ off_h = off_hb % nheads
900
+ # offset pointers for batch/head
901
+ Q += off_b * stride_qb + off_h * stride_qh
902
+ K += off_b * stride_kb + off_h * stride_kh
903
+ V += off_b * stride_vb + off_h * stride_vh
904
+ DO += off_b * stride_dob + off_h * stride_doh
905
+ DQ += off_b * stride_dqb + off_h * stride_dqh
906
+ DK += off_b * stride_dkb + off_h * stride_dkh
907
+ DV += off_b * stride_dvb + off_h * stride_dvh
908
+ if BIAS_TYPE != 'none':
909
+ Bias += off_b * stride_bb + off_h * stride_bh
910
+ # pointer to row-wise quantities in value-like data
911
+ D += off_hb * seqlen_q_rounded
912
+ LSE += off_hb * seqlen_q_rounded
913
+ if not SEQUENCE_PARALLEL:
914
+ num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
915
+ for start_n in range(0, num_block_n):
916
+ _bwd_kernel_one_col_block(start_n,
917
+ Q,
918
+ K,
919
+ V,
920
+ Bias,
921
+ DO,
922
+ DQ,
923
+ DK,
924
+ DV,
925
+ LSE,
926
+ D,
927
+ softmax_scale,
928
+ stride_qm,
929
+ stride_kn,
930
+ stride_vn,
931
+ stride_bm,
932
+ stride_dom,
933
+ stride_dqm,
934
+ stride_dkn,
935
+ stride_dvn,
936
+ seqlen_q,
937
+ seqlen_k,
938
+ headdim,
939
+ ATOMIC_ADD=False,
940
+ BIAS_TYPE=BIAS_TYPE,
941
+ IS_CAUSAL=IS_CAUSAL,
942
+ BLOCK_HEADDIM=BLOCK_HEADDIM,
943
+ EVEN_M=EVEN_M,
944
+ EVEN_N=EVEN_N,
945
+ EVEN_HEADDIM=EVEN_HEADDIM,
946
+ BLOCK_M=BLOCK_M,
947
+ BLOCK_N=BLOCK_N)
948
+ else:
949
+ start_n = tl.program_id(0)
950
+ _bwd_kernel_one_col_block(start_n,
951
+ Q,
952
+ K,
953
+ V,
954
+ Bias,
955
+ DO,
956
+ DQ,
957
+ DK,
958
+ DV,
959
+ LSE,
960
+ D,
961
+ softmax_scale,
962
+ stride_qm,
963
+ stride_kn,
964
+ stride_vn,
965
+ stride_bm,
966
+ stride_dom,
967
+ stride_dqm,
968
+ stride_dkn,
969
+ stride_dvn,
970
+ seqlen_q,
971
+ seqlen_k,
972
+ headdim,
973
+ ATOMIC_ADD=True,
974
+ BIAS_TYPE=BIAS_TYPE,
975
+ IS_CAUSAL=IS_CAUSAL,
976
+ BLOCK_HEADDIM=BLOCK_HEADDIM,
977
+ EVEN_M=EVEN_M,
978
+ EVEN_N=EVEN_N,
979
+ EVEN_HEADDIM=EVEN_HEADDIM,
980
+ BLOCK_M=BLOCK_M,
981
+ BLOCK_N=BLOCK_N)
982
+
983
+
984
+ def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
985
+ # shape constraints
986
+ batch, seqlen_q, nheads, d = q.shape
987
+ _, seqlen_k, _, _ = k.shape
988
+ assert k.shape == (batch, seqlen_k, nheads, d)
989
+ assert v.shape == (batch, seqlen_k, nheads, d)
990
+ assert d <= 128, 'FlashAttention only support head dimensions up to 128'
991
+ assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
992
+ assert q.dtype in [torch.float16,
993
+ torch.bfloat16], 'Only support fp16 and bf16'
994
+ assert q.is_cuda and k.is_cuda and v.is_cuda
995
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
996
+
997
+ has_bias = bias is not None
998
+ bias_type = 'none'
999
+ if has_bias:
1000
+ assert bias.dtype in [q.dtype, torch.float]
1001
+ assert bias.is_cuda
1002
+ assert bias.dim() == 4
1003
+ if bias.stride(-1) != 1:
1004
+ bias = bias.contiguous()
1005
+ if bias.shape[2:] == (1, seqlen_k):
1006
+ bias_type = 'vector'
1007
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
1008
+ bias_type = 'matrix'
1009
+ else:
1010
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
1011
+ ' or (seqlen_q, seqlen_k)')
1012
+ if bias.shape[:2] == (1, nheads):
1013
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
1014
+ elif bias.shape[:2] == (batch, 1):
1015
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
1016
+ elif bias.shape[:2] == (1, 1):
1017
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
1018
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
1019
+ assert bias.shape[:2] == (
1020
+ batch, nheads
1021
+ ), f'First 2 dimensions of bias must be broadcastible to (batch, nheads) = ({batch, nheads}). Bias has shape: {bias.shape}'
1022
+ assert bias is not None # for type checking
1023
+ bias_strides = (bias.stride(0), bias.stride(1),
1024
+ bias.stride(2)) if has_bias else (0, 0, 0)
1025
+
1026
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
1027
+ lse = torch.empty((batch, nheads, seqlen_q_rounded),
1028
+ device=q.device,
1029
+ dtype=torch.float32)
1030
+ tmp = torch.empty((batch, nheads, seqlen_q_rounded),
1031
+ device=q.device,
1032
+ dtype=torch.float32)
1033
+ o = torch.empty_like(q)
1034
+
1035
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
1036
+ # BLOCK = 128
1037
+ # num_warps = 4 if d <= 64 else 8
1038
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
1039
+ _fwd_kernel[grid]( # type: ignore
1040
+ q,
1041
+ k,
1042
+ v,
1043
+ bias,
1044
+ o,
1045
+ lse,
1046
+ tmp,
1047
+ softmax_scale,
1048
+ q.stride(0),
1049
+ q.stride(2),
1050
+ q.stride(1),
1051
+ k.stride(0),
1052
+ k.stride(2),
1053
+ k.stride(1),
1054
+ v.stride(0),
1055
+ v.stride(2),
1056
+ v.stride(1),
1057
+ *bias_strides,
1058
+ o.stride(0),
1059
+ o.stride(2),
1060
+ o.stride(1),
1061
+ nheads,
1062
+ seqlen_q,
1063
+ seqlen_k,
1064
+ seqlen_q_rounded,
1065
+ d,
1066
+ seqlen_q // 32,
1067
+ seqlen_k // 32, # key for triton cache (limit number of compilations)
1068
+ # Can't use kwargs here because triton autotune expects key to be args, not kwargs
1069
+ # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
1070
+ bias_type,
1071
+ causal,
1072
+ BLOCK_HEADDIM,
1073
+ # BLOCK_M=BLOCK, BLOCK_N=BLOCK,
1074
+ # num_warps=num_warps,
1075
+ # num_stages=1,
1076
+ )
1077
+ return o, lse, softmax_scale # softmax_scale could have been updated
1078
+
1079
+
1080
+ def _flash_attn_backward(do,
1081
+ q,
1082
+ k,
1083
+ v,
1084
+ o,
1085
+ lse,
1086
+ dq,
1087
+ dk,
1088
+ dv,
1089
+ bias=None,
1090
+ causal=False,
1091
+ softmax_scale=None):
1092
+ # Make sure that the last dimension is contiguous
1093
+ if do.stride(-1) != 1:
1094
+ do = do.contiguous()
1095
+ batch, seqlen_q, nheads, d = q.shape
1096
+ _, seqlen_k, _, _ = k.shape
1097
+ # assert d in {16, 32, 64, 128}
1098
+ assert d <= 128
1099
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
1100
+ assert lse.shape == (batch, nheads, seqlen_q_rounded)
1101
+ assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
1102
+ assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
1103
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
1104
+ # dq_accum = torch.zeros_like(q, dtype=torch.float32)
1105
+ dq_accum = torch.empty_like(q, dtype=torch.float32)
1106
+ delta = torch.empty_like(lse)
1107
+ # delta = torch.zeros_like(lse)
1108
+
1109
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
1110
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
1111
+ _bwd_preprocess_do_o_dot[grid]( # type: ignore
1112
+ o,
1113
+ do,
1114
+ delta,
1115
+ o.stride(0),
1116
+ o.stride(2),
1117
+ o.stride(1),
1118
+ do.stride(0),
1119
+ do.stride(2),
1120
+ do.stride(1),
1121
+ nheads,
1122
+ seqlen_q,
1123
+ seqlen_q_rounded,
1124
+ d,
1125
+ BLOCK_M=128,
1126
+ BLOCK_HEADDIM=BLOCK_HEADDIM,
1127
+ )
1128
+
1129
+ has_bias = bias is not None
1130
+ bias_type = 'none'
1131
+ if has_bias:
1132
+ assert bias.dtype in [q.dtype, torch.float]
1133
+ assert bias.is_cuda
1134
+ assert bias.dim() == 4
1135
+ assert bias.stride(-1) == 1
1136
+ if bias.shape[2:] == (1, seqlen_k):
1137
+ bias_type = 'vector'
1138
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
1139
+ bias_type = 'matrix'
1140
+ else:
1141
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
1142
+ ' or (seqlen_q, seqlen_k)')
1143
+ if bias.shape[:2] == (1, nheads):
1144
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
1145
+ elif bias.shape[:2] == (batch, 1):
1146
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
1147
+ elif bias.shape[:2] == (1, 1):
1148
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
1149
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
1150
+ assert bias.shape[:2] == (
1151
+ batch, nheads
1152
+ ), f'First 2 dimensions of bias must be broadcastible to (batch, nheads) = ({batch, nheads}). Bias has shape: {bias.shape}'
1153
+ assert bias is not None # type checking
1154
+ bias_strides = (bias.stride(0), bias.stride(1),
1155
+ bias.stride(2)) if has_bias else (0, 0, 0)
1156
+
1157
+ # BLOCK_M = 128
1158
+ # BLOCK_N = 64
1159
+ # num_warps = 4
1160
+ grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N'])
1161
+ if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
1162
+ _bwd_kernel[grid]( # type: ignore
1163
+ q,
1164
+ k,
1165
+ v,
1166
+ bias,
1167
+ do,
1168
+ dq_accum,
1169
+ dk,
1170
+ dv,
1171
+ lse,
1172
+ delta,
1173
+ softmax_scale,
1174
+ q.stride(0),
1175
+ q.stride(2),
1176
+ q.stride(1),
1177
+ k.stride(0),
1178
+ k.stride(2),
1179
+ k.stride(1),
1180
+ v.stride(0),
1181
+ v.stride(2),
1182
+ v.stride(1),
1183
+ *bias_strides,
1184
+ do.stride(0),
1185
+ do.stride(2),
1186
+ do.stride(1),
1187
+ dq_accum.stride(0),
1188
+ dq_accum.stride(2),
1189
+ dq_accum.stride(1),
1190
+ dk.stride(0),
1191
+ dk.stride(2),
1192
+ dk.stride(1),
1193
+ dv.stride(0),
1194
+ dv.stride(2),
1195
+ dv.stride(1),
1196
+ nheads,
1197
+ seqlen_q,
1198
+ seqlen_k,
1199
+ seqlen_q_rounded,
1200
+ d,
1201
+ seqlen_q // 32,
1202
+ seqlen_k // 32, # key for triton cache (limit number of compilations)
1203
+ # Can't use kwargs here because triton autotune expects key to be args, not kwargs
1204
+ # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
1205
+ bias_type,
1206
+ causal,
1207
+ BLOCK_HEADDIM,
1208
+ # SEQUENCE_PARALLEL=False,
1209
+ # BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N,
1210
+ # num_warps=num_warps,
1211
+ # num_stages=1,
1212
+ )
1213
+ dq.copy_(dq_accum)
1214
+
1215
+
1216
+ class _FlashAttnQKVPackedFunc(torch.autograd.Function):
1217
+
1218
+ @staticmethod
1219
+ def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
1220
+ """Forward pass for packed FlashAttention.
1221
+
1222
+ Args:
1223
+ ctx: autograd context
1224
+ qkv: (batch, seqlen, 3, nheads, headdim)
1225
+ bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
1226
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
1227
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
1228
+ causal (bool): whether to incorporate causal attention masking
1229
+ softmax_scale (float, optional): scale factor for softmax
1230
+ """
1231
+ # Make sure that the last dimension is contiguous
1232
+ if qkv.stride(-1) != 1:
1233
+ qkv = qkv.contiguous()
1234
+ o, lse, ctx.softmax_scale = _flash_attn_forward(
1235
+ qkv[:, :, 0],
1236
+ qkv[:, :, 1],
1237
+ qkv[:, :, 2],
1238
+ bias=bias,
1239
+ causal=causal,
1240
+ softmax_scale=softmax_scale)
1241
+ ctx.save_for_backward(qkv, o, lse, bias)
1242
+ ctx.causal = causal
1243
+ return o
1244
+
1245
+ @staticmethod
1246
+ def backward(ctx, do):
1247
+ qkv, o, lse, bias = ctx.saved_tensors
1248
+ assert not ctx.needs_input_grad[
1249
+ 1], 'FlashAttention does not support bias gradient yet'
1250
+ # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
1251
+ # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
1252
+ with torch.inference_mode():
1253
+ dqkv = torch.empty_like(qkv)
1254
+ _flash_attn_backward(do,
1255
+ qkv[:, :, 0],
1256
+ qkv[:, :, 1],
1257
+ qkv[:, :, 2],
1258
+ o,
1259
+ lse,
1260
+ dqkv[:, :, 0],
1261
+ dqkv[:, :, 1],
1262
+ dqkv[:, :, 2],
1263
+ bias=bias,
1264
+ causal=ctx.causal,
1265
+ softmax_scale=ctx.softmax_scale)
1266
+ return dqkv, None, None, None
1267
+
1268
+
1269
+ flash_attn_qkvpacked_func = _FlashAttnQKVPackedFunc.apply
1270
+
1271
+
1272
+ class _FlashAttnFunc(torch.autograd.Function):
1273
+
1274
+ @staticmethod
1275
+ def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
1276
+ """Forward pass for FlashAttention.
1277
+
1278
+ Args:
1279
+ ctx: autograd context
1280
+ q: (batch_size, seqlen_q, nheads, headdim)
1281
+ k: (batch_size, seqlen_k, nheads, headdim)
1282
+ v: (batch_size, seqlen_k, nheads, headdim)
1283
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
1284
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
1285
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
1286
+ causal (bool): whether to incorporate causal attention masking
1287
+ softmax_scale (float, optional): scale factor for softmax
1288
+ """
1289
+ # Make sure that the last dimension is contiguous
1290
+ q, k, v = [
1291
+ x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]
1292
+ ]
1293
+ o, lse, ctx.softmax_scale = _flash_attn_forward(
1294
+ q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
1295
+ ctx.save_for_backward(q, k, v, o, lse, bias)
1296
+ ctx.causal = causal
1297
+ return o
1298
+
1299
+ @staticmethod
1300
+ def backward(ctx, do):
1301
+ q, k, v, o, lse, bias = ctx.saved_tensors
1302
+ assert not ctx.needs_input_grad[
1303
+ 3], 'FlashAttention does not support bias gradient yet'
1304
+ # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
1305
+ # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
1306
+ with torch.inference_mode():
1307
+ dq = torch.empty_like(q)
1308
+ dk = torch.empty_like(k)
1309
+ dv = torch.empty_like(v)
1310
+ _flash_attn_backward(do,
1311
+ q,
1312
+ k,
1313
+ v,
1314
+ o,
1315
+ lse,
1316
+ dq,
1317
+ dk,
1318
+ dv,
1319
+ bias=bias,
1320
+ causal=ctx.causal,
1321
+ softmax_scale=ctx.softmax_scale)
1322
+ return dq, dk, dv, None, None, None
1323
+
1324
+
1325
+ flash_attn_func = _FlashAttnFunc.apply
1326
+
1327
+ pass
1328
+