shreyansh26 commited on
Commit
e23603a
1 Parent(s): 4ca3145

Add latest version of code

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