vinayh19 commited on
Commit
acdd4ed
·
verified ·
1 Parent(s): 7f001bb

Upload folder using huggingface_hub

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