czl commited on
Commit
71b4e8a
1 Parent(s): 8354041

Upload folder using huggingface_hub

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ metrics:
3
+ - matthews_correlation
4
+ - f1
5
+ tags:
6
+ - biology
7
+ - medical
8
+ ---
9
+ # DNABERT-2 (modified)
10
+
11
+ Modified to configure the use of flash attention.
12
+
13
+ ## Below are works from the original repository and jaandoui.
14
+
15
+ This version of DNABERT2 has been changed to be able to output the attention too, for attention analysis.
16
+
17
+ **To the author of DNABERT2, feel free to use those modifications.**
18
+
19
+ Use ```--model_name_or_path jaandoui/DNABERT2-AttentionExtracted``` instead of the original repository to have access to the attention.
20
+
21
+ Most of the modifications were done in Bert_Layer.py.
22
+ It has been modified especially for fine tuning and hasn't been tried for pretraining.
23
+ Before or next to each modification, you can find ```"JAANDOUI"``` so to see al modifications, search for ```"JAANDOUI"```.
24
+ ```"JAANDOUI TODO"``` means that if that part is going to be used, maybe something might be missing.
25
+
26
+ Now in ```Trainer``` (or ```CustomTrainer``` if overwritten) in ```compute_loss(..)``` when defining the model:
27
+ ```outputs = model(**inputs, return_dict=True, output_attentions=True)```
28
+ activate the extraction of attention: ```output_attentions=True``` (and ```return_dict=True``` (optional)).
29
+ You can now extract the attention in ```outputs.attentions```
30
+ Note than the output has a third dimension, mostly of value 12, referring to the layer ```outputs.attentions[-1]``` refers to the attention of the last layer.
31
+ Read more about model outputs here: https://huggingface.co/docs/transformers/v4.40.2/en/main_classes/output#transformers.utils.ModelOutput
32
+
33
+ I'm also not using Triton, therefore cannot guarantee that it will work with it.
34
+
35
+ I also read that there were some problems with extracting attention when using Flash Attention here: https://github.com/huggingface/transformers/issues/28903
36
+ Not sure if that is relevant for us, since it's about Mistral models.
37
+
38
+ I'm still exploring this attention, please don't take it as if it works 100%. I'll update the repository when I'm sure.
39
+
40
+ The official link to DNABERT2 [DNABERT-2: Efficient Foundation Model and Benchmark For Multi-Species Genome
41
+ ](https://arxiv.org/pdf/2306.15006.pdf).
42
+
43
+ READ ME OF THE OFFICIAL DNABERT2:
44
+ We sincerely appreciate the MosaicML team for the [MosaicBERT](https://openreview.net/forum?id=5zipcfLC2Z) implementation, which serves as the base of DNABERT-2 development.
45
+
46
+ DNABERT-2 is a transformer-based genome foundation model trained on multi-species genome.
47
+
48
+ To load the model from huggingface:
49
+ ```
50
+ import torch
51
+ from transformers import AutoTokenizer, AutoModel
52
+
53
+ tokenizer = AutoTokenizer.from_pretrained("zhihan1996/DNABERT-2-117M", trust_remote_code=True)
54
+ model = AutoModel.from_pretrained("zhihan1996/DNABERT-2-117M", trust_remote_code=True)
55
+ ```
56
+
57
+ To calculate the embedding of a dna sequence
58
+ ```
59
+ dna = "ACGTAGCATCGGATCTATCTATCGACACTTGGTTATCGATCTACGAGCATCTCGTTAGC"
60
+ inputs = tokenizer(dna, return_tensors = 'pt')["input_ids"]
61
+ hidden_states = model(inputs)[0] # [1, sequence_length, 768]
62
+
63
+ # embedding with mean pooling
64
+ embedding_mean = torch.mean(hidden_states[0], dim=0)
65
+ print(embedding_mean.shape) # expect to be 768
66
+
67
+ # embedding with max pooling
68
+ embedding_max = torch.max(hidden_states[0], dim=0)[0]
69
+ print(embedding_max.shape) # expect to be 768
70
+ ```
bert_layers.py ADDED
@@ -0,0 +1,1016 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # search for JAANDOUI for the parts I have modified, and for JAANDOUI TODO for the parts that might need to be changed.
2
+
3
+ # Copyright 2022 MosaicML Examples authors
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
7
+ # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
8
+ # Copyright (c) 2022, Tri Dao.
9
+
10
+ import copy
11
+ import logging
12
+ import math
13
+ import warnings
14
+ from typing import List, Optional, Tuple, Union
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ from einops import rearrange
19
+ from transformers.activations import ACT2FN
20
+ from transformers.modeling_outputs import MaskedLMOutput, SequenceClassifierOutput
21
+ from transformers.models.bert.modeling_bert import BertPreTrainedModel
22
+
23
+ from .bert_padding import (
24
+ index_first_axis,
25
+ index_put_first_axis,
26
+ pad_input,
27
+ unpad_input,
28
+ unpad_input_only,
29
+ )
30
+
31
+ try:
32
+ from .flash_attn_triton import flash_attn_qkvpacked_func
33
+ except ImportError:
34
+ flash_attn_qkvpacked_func = None
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+
39
+ class BertEmbeddings(nn.Module):
40
+
41
+ def __init__(self, config):
42
+ super().__init__()
43
+ self.word_embeddings = nn.Embedding(config.vocab_size,
44
+ config.hidden_size,
45
+ padding_idx=config.pad_token_id)
46
+ # ALiBi doesn't use position embeddings
47
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size,
48
+ config.hidden_size)
49
+
50
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model
51
+ # variable name and be able to load any TensorFlow checkpoint file
52
+ self.LayerNorm = nn.LayerNorm(config.hidden_size,
53
+ eps=config.layer_norm_eps)
54
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
55
+ self.register_buffer('token_type_ids',
56
+ torch.zeros(config.max_position_embeddings,
57
+ dtype=torch.long),
58
+ persistent=False)
59
+
60
+ def forward(
61
+ self,
62
+ input_ids: Optional[torch.LongTensor] = None,
63
+ token_type_ids: Optional[torch.LongTensor] = None,
64
+ position_ids: Optional[torch.LongTensor] = None,
65
+ inputs_embeds: Optional[torch.FloatTensor] = None,
66
+ past_key_values_length: int = 0,
67
+ ) -> torch.Tensor:
68
+ if (input_ids is not None) == (inputs_embeds is not None):
69
+ raise ValueError('Must specify either input_ids or input_embeds!')
70
+ if input_ids is not None:
71
+ input_shape = input_ids.size()
72
+ else:
73
+ assert inputs_embeds is not None # just for type checking
74
+ input_shape = inputs_embeds.size()[:-1]
75
+
76
+ seq_length = input_shape[1]
77
+
78
+ if position_ids is None:
79
+ # great! ALiBi
80
+ pass
81
+
82
+ # Setting the token_type_ids to the registered buffer in constructor
83
+ # where it is all zeros, which usually occurs when it's auto-generated;
84
+ # registered buffer helps users when tracing the model without passing
85
+ # token_type_ids, solves issue #5664
86
+ if token_type_ids is None:
87
+ if hasattr(self, 'token_type_ids'):
88
+ assert isinstance(self.token_type_ids, torch.LongTensor)
89
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
90
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
91
+ input_shape[0], seq_length)
92
+ token_type_ids = buffered_token_type_ids_expanded # type: ignore
93
+ else:
94
+ token_type_ids = torch.zeros(input_shape, # type: ignore
95
+ dtype=torch.long,
96
+ device=self.word_embeddings.device) # type: ignore # yapf: disable
97
+
98
+ if inputs_embeds is None:
99
+ inputs_embeds = self.word_embeddings(input_ids)
100
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
101
+
102
+ embeddings = inputs_embeds + token_type_embeddings
103
+ # no position embeddings! ALiBi
104
+ embeddings = self.LayerNorm(embeddings)
105
+ embeddings = self.dropout(embeddings)
106
+ return embeddings
107
+
108
+
109
+ class BertUnpadSelfAttention(nn.Module):
110
+
111
+ def __init__(self, config):
112
+ super().__init__()
113
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
114
+ config, 'embedding_size'):
115
+ raise ValueError(
116
+ f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention '
117
+ f'heads ({config.num_attention_heads})')
118
+
119
+ self.num_attention_heads = config.num_attention_heads
120
+ self.attention_head_size = int(config.hidden_size /
121
+ config.num_attention_heads)
122
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
123
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
124
+ self.p_dropout = config.attention_probs_dropout_prob
125
+ self.Wqkv = nn.Linear(self.all_head_size, 3 * config.hidden_size)
126
+ self.fa = config.flash_attn
127
+
128
+ # Warn if defaulting to pytorch because of import issues
129
+ if flash_attn_qkvpacked_func is None:
130
+ warnings.warn(
131
+ 'Unable to import Triton; defaulting MosaicBERT attention implementation to pytorch (this will reduce throughput when using this model).'
132
+ )
133
+
134
+ def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor,
135
+ max_seqlen_in_batch: int, indices: torch.Tensor,
136
+ attn_mask: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:
137
+ """Perform self-attention.
138
+
139
+ If dropout is zero, then we can use the Triton kernel, so we do that. However, if not, we send through a standard PyTorch
140
+ implementation of self-attention.
141
+
142
+ The arguments are unpadded, and our implementations of attention require padded arguments,
143
+ so we first call `pad_input`. Once we compute attention, we re-unpad our outputs for the other layers.
144
+ The pad/unpad operations add overhead, but not sending pad tokens through ffs saves compute.
145
+ It is possible to write an unpadded implementation of attention (in Triton and PyTorch), which we will eventually do.
146
+
147
+ Args:
148
+ hidden_states: (total_nnz, dim)
149
+ cu_seqlens: (batch + 1,)
150
+ max_seqlen_in_batch: int
151
+ indices: (total_nnz,)
152
+ attn_mask: (batch, max_seqlen_in_batch)
153
+ bias: (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
154
+
155
+ Returns:
156
+ attention: (total_nnz, dim)
157
+ """
158
+ qkv = self.Wqkv(hidden_states)
159
+ qkv = pad_input(qkv, indices, cu_seqlens.shape[0] - 1,
160
+ max_seqlen_in_batch) # batch, max_seqlen_in_batch, thd
161
+ qkv = rearrange(qkv,
162
+ 'b s (t h d) -> b s t h d',
163
+ t=3,
164
+ h=self.num_attention_heads)
165
+ if self.p_dropout or flash_attn_qkvpacked_func is None or not self.fa:
166
+ # if we have nonzero attention dropout (e.g. during fine-tuning) or no Triton, compute attention in PyTorch
167
+ q = qkv[:, :, 0, :, :].permute(0, 2, 1, 3) # b h s d
168
+ k = qkv[:, :, 1, :, :].permute(0, 2, 3, 1) # b h d s
169
+ v = qkv[:, :, 2, :, :].permute(0, 2, 1, 3) # b h s d
170
+ attention_scores = torch.matmul(q, k) / math.sqrt(
171
+ self.attention_head_size)
172
+ attention_scores = attention_scores + bias
173
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
174
+ # print(f'BUSA: attention_probs 1 shape: {attention_probs.shape}')
175
+ attention_probs = self.dropout(attention_probs)
176
+ # print(f'BUSA: attention_probs 2 shape: {attention_probs.shape}')
177
+ attention = torch.matmul(attention_probs, v).permute(0, 2, 1,
178
+ 3) # b s h d
179
+ # print(f'BUSA: attention shape: {attention.shape}')
180
+ else:
181
+ # Triton implementation only supports 0 attention dropout
182
+ convert_dtype = qkv.dtype not in [torch.float16, torch.bfloat16]
183
+ if convert_dtype:
184
+ # Triton implementation only supports fp16 and bf16
185
+ orig_dtype = qkv.dtype
186
+ qkv = qkv.to(torch.float16)
187
+ bias_dtype = bias.dtype
188
+ bias = bias.to(torch.float16)
189
+ attention = flash_attn_qkvpacked_func(qkv, bias)
190
+ # print(f'BUSA Triton: attention 0 shape: {attention_probs.shape}')
191
+ attention = attention.to(orig_dtype)
192
+ # print(f'BUSA Triton: attention 1 shape: {attention_probs.shape}')
193
+ bias = bias.to(bias_dtype)
194
+ else:
195
+ attention = flash_attn_qkvpacked_func(qkv, bias)
196
+ # print(f'BUSA Triton: attention 2 shape: {attention_probs.shape}')
197
+ # attn_mask is 1 for attend and 0 for don't
198
+ attention = unpad_input_only(attention, torch.squeeze(attn_mask) == 1)
199
+ # print(f'BUSA unpadded final attention shape: {attention_probs.shape}')
200
+ # print(f'ATTENTION: {attention.shape}')
201
+
202
+ # print(f'PROBLEM HERE: UNDERSTAND IT!!')
203
+ rearranged_attention = rearrange(attention, 'nnz h d -> nnz (h d)')
204
+ # try:
205
+ # print(f'REARRANGED ATTENTION: {rearranged_attention.shape}')
206
+ # except:
207
+ # print(f'REARRANGED ATTENTION: {rearranged_attention[0].shape}')
208
+ return rearrange(attention, 'nnz h d -> nnz (h d)'), attention_probs
209
+
210
+
211
+ # Copy of transformer's library BertSelfOutput that will not be caught by surgery methods looking for HF BERT modules.
212
+ class BertSelfOutput(nn.Module):
213
+
214
+ def __init__(self, config):
215
+ super().__init__()
216
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
217
+ self.LayerNorm = nn.LayerNorm(config.hidden_size,
218
+ eps=config.layer_norm_eps)
219
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
220
+
221
+ def forward(self, hidden_states: torch.Tensor,
222
+ input_tensor: torch.Tensor) -> torch.Tensor:
223
+ hidden_states = self.dense(hidden_states)
224
+ hidden_states = self.dropout(hidden_states)
225
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
226
+ return hidden_states
227
+
228
+
229
+ class BertUnpadAttention(nn.Module):
230
+ """Chains attention, Dropout, and LayerNorm for Mosaic BERT."""
231
+
232
+ def __init__(self, config):
233
+ super().__init__()
234
+ self.self = BertUnpadSelfAttention(config)
235
+ self.output = BertSelfOutput(config)
236
+
237
+ def forward(
238
+ self,
239
+ input_tensor: torch.Tensor,
240
+ cu_seqlens: torch.Tensor,
241
+ max_s: int,
242
+ subset_idx: Optional[torch.Tensor] = None,
243
+ indices: Optional[torch.Tensor] = None,
244
+ attn_mask: Optional[torch.Tensor] = None,
245
+ bias: Optional[torch.Tensor] = None,
246
+ ) -> torch.Tensor:
247
+ """Forward pass for scaled self-attention without padding.
248
+
249
+ Arguments:
250
+ input_tensor: (total_nnz, dim)
251
+ cu_seqlens: (batch + 1,)
252
+ max_s: int
253
+ subset_idx: () set of indices whose values we care about at the end of the layer
254
+ (e.g., the masked tokens, if this is the final layer).
255
+ indices: None or (total_nnz,)
256
+ attn_mask: None or (batch, max_seqlen_in_batch)
257
+ bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
258
+ """
259
+ self_output, attention_probs = self.self(input_tensor, cu_seqlens, max_s, indices,
260
+ attn_mask, bias)
261
+
262
+ # try:
263
+ # print(f'IMPORTANT: {self_output.shape}')
264
+ # except:
265
+ # print(f'IMPORTANT2: {self_output[0].shape}')
266
+
267
+ if subset_idx is not None:
268
+ return self.output(index_first_axis(self_output, subset_idx),
269
+ index_first_axis(input_tensor, subset_idx))
270
+ else:
271
+ return self.output(self_output, input_tensor), attention_probs
272
+
273
+
274
+ class BertGatedLinearUnitMLP(nn.Module):
275
+ """Applies the FFN at the end of each Mosaic BERT layer.
276
+
277
+ Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate`
278
+ and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar functionality, but
279
+ introduces Gated Linear Units.
280
+
281
+ Note: Mosaic BERT adds parameters in order to implement Gated Linear Units. To keep parameter count consistent with that of a
282
+ standard Hugging Face BERT, scale down `config.intermediate_size` by 2/3. For example, a Mosaic BERT constructed with
283
+ `config.intermediate_size=2048` will have the same parameter footprint as its Hugging Face BERT counterpart constructed
284
+ with the `config.intermediate_size=3072`.
285
+ However, in most cases it will not be necessary to adjust `config.intermediate_size` since, despite the increased
286
+ parameter size, Mosaic BERT typically offers a net higher throughput than a Hugging Face BERT built from the same `config`.
287
+ """
288
+
289
+ def __init__(self, config):
290
+ super().__init__()
291
+ self.config = config
292
+ self.gated_layers = nn.Linear(config.hidden_size,
293
+ config.intermediate_size * 2,
294
+ bias=False)
295
+ self.act = nn.GELU(approximate='none')
296
+ self.wo = nn.Linear(config.intermediate_size, config.hidden_size)
297
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
298
+ self.layernorm = nn.LayerNorm(config.hidden_size,
299
+ eps=config.layer_norm_eps)
300
+
301
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
302
+ """Compute new hidden states from current hidden states.
303
+
304
+ Args:
305
+ hidden_states (torch.Tensor): The (unpadded) hidden states from
306
+ the attention layer [nnz, dim].
307
+ """
308
+ residual_connection = hidden_states
309
+ # compute the activation
310
+ hidden_states = self.gated_layers(hidden_states)
311
+ gated = hidden_states[:, :self.config.intermediate_size]
312
+ non_gated = hidden_states[:, self.config.intermediate_size:]
313
+ hidden_states = self.act(gated) * non_gated
314
+ hidden_states = self.dropout(hidden_states)
315
+ # multiply by the second matrix
316
+ hidden_states = self.wo(hidden_states)
317
+ # add the residual connection and post-LN
318
+ hidden_states = self.layernorm(hidden_states + residual_connection)
319
+ return hidden_states
320
+
321
+
322
+ class BertLayer(nn.Module):
323
+ """Composes the Mosaic BERT attention and FFN blocks into a single layer."""
324
+
325
+ def __init__(self, config):
326
+ super(BertLayer, self).__init__()
327
+ self.attention = BertUnpadAttention(config)
328
+ self.mlp = BertGatedLinearUnitMLP(config)
329
+
330
+ def forward(
331
+ self,
332
+ hidden_states: torch.Tensor,
333
+ cu_seqlens: torch.Tensor,
334
+ seqlen: int,
335
+ subset_idx: Optional[torch.Tensor] = None,
336
+ indices: Optional[torch.Tensor] = None,
337
+ attn_mask: Optional[torch.Tensor] = None,
338
+ bias: Optional[torch.Tensor] = None,
339
+ ) -> torch.Tensor:
340
+ """Forward pass for a BERT layer, including both attention and MLP.
341
+
342
+ Args:
343
+ hidden_states: (total_nnz, dim)
344
+ cu_seqlens: (batch + 1,)
345
+ seqlen: int
346
+ subset_idx: () set of indices whose values we care about at the end of the layer
347
+ (e.g., the masked tokens, if this is the final layer).
348
+ indices: None or (total_nnz,)
349
+ attn_mask: None or (batch, max_seqlen_in_batch)
350
+ bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
351
+ """
352
+ attention_output, attention_probs = self.attention(hidden_states, cu_seqlens, seqlen,
353
+ subset_idx, indices, attn_mask, bias)
354
+ # print(f'BertLayer attention_output shape: {attention_output.shape}')
355
+ layer_output = self.mlp(attention_output)
356
+ # print(f'BertLayer layer_output shape: {layer_output.shape}')
357
+ return layer_output, attention_output, attention_probs # JAANDOUI: this only returns layer_output in the original work.
358
+
359
+
360
+ class BertEncoder(nn.Module):
361
+ """A stack of BERT layers providing the backbone of Mosaic BERT.
362
+
363
+ This module is modeled after the Hugging Face BERT's :class:`~transformers.model.bert.modeling_bert.BertEncoder`,
364
+ but with substantial modifications to implement unpadding and ALiBi.
365
+
366
+ Compared to the analogous Hugging Face BERT module, this module handles unpadding to reduce unnecessary computation
367
+ at padded tokens, and pre-computes attention biases to implement ALiBi.
368
+ """
369
+
370
+ def __init__(self, config):
371
+ super().__init__()
372
+ layer = BertLayer(config) # JAANDOUI: In this line we define the BertLayer, note that now the forward of this class returns attention too!! 2 values instead of 1
373
+ self.layer = nn.ModuleList(
374
+ [copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
375
+
376
+ self.num_attention_heads = config.num_attention_heads
377
+ # print(f'nbr of attention heads: {self.num_attention_heads}')
378
+ # The alibi mask will be dynamically expanded if it is too small for
379
+ # the input the model receives. But it generally helps to initialize it
380
+ # to a reasonably large size to help pre-allocate CUDA memory.
381
+ # The default `alibi_starting_size` is 512.
382
+ self._current_alibi_size = int(config.alibi_starting_size)
383
+ self.alibi = torch.zeros(
384
+ (1, self.num_attention_heads, self._current_alibi_size,
385
+ self._current_alibi_size))
386
+ self.rebuild_alibi_tensor(size=config.alibi_starting_size)
387
+
388
+ def rebuild_alibi_tensor(self,
389
+ size: int,
390
+ device: Optional[Union[torch.device, str]] = None):
391
+ # Alibi
392
+ # Following https://github.com/ofirpress/attention_with_linear_biases/issues/5 (Implementation 1)
393
+ # In the causal case, you can exploit the fact that softmax is invariant to a uniform translation
394
+ # of the logits, which makes the math work out *after* applying causal masking. If no causal masking
395
+ # will be applied, it is necessary to construct the diagonal mask.
396
+ n_heads = self.num_attention_heads
397
+
398
+ def _get_alibi_head_slopes(n_heads: int) -> List[float]:
399
+
400
+ def get_slopes_power_of_2(n_heads: int) -> List[float]:
401
+ start = (2**(-2**-(math.log2(n_heads) - 3)))
402
+ ratio = start
403
+ return [start * ratio**i for i in range(n_heads)]
404
+
405
+ # In the paper, they only train models that have 2^a heads for some a. This function
406
+ # has some good properties that only occur when the input is a power of 2. To
407
+ # maintain that even when the number of heads is not a power of 2, we use a
408
+ # workaround.
409
+ if math.log2(n_heads).is_integer():
410
+ return get_slopes_power_of_2(n_heads)
411
+
412
+ closest_power_of_2 = 2**math.floor(math.log2(n_heads))
413
+ slopes_a = get_slopes_power_of_2(closest_power_of_2)
414
+ slopes_b = _get_alibi_head_slopes(2 * closest_power_of_2)
415
+ slopes_b = slopes_b[0::2][:n_heads - closest_power_of_2]
416
+ return slopes_a + slopes_b
417
+
418
+ context_position = torch.arange(size, device=device)[:, None]
419
+ memory_position = torch.arange(size, device=device)[None, :]
420
+ relative_position = torch.abs(memory_position - context_position)
421
+ # [n_heads, max_token_length, max_token_length]
422
+ relative_position = relative_position.unsqueeze(0).expand(
423
+ n_heads, -1, -1)
424
+ slopes = torch.Tensor(_get_alibi_head_slopes(n_heads)).to(device)
425
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * -relative_position
426
+ # [1, n_heads, max_token_length, max_token_length]
427
+ alibi = alibi.unsqueeze(0)
428
+ assert alibi.shape == torch.Size([1, n_heads, size, size])
429
+
430
+ self._current_alibi_size = size
431
+ self.alibi = alibi
432
+
433
+ def forward(
434
+ self,
435
+ hidden_states: torch.Tensor,
436
+ attention_mask: torch.Tensor,
437
+ output_all_encoded_layers: Optional[bool] = True,
438
+ subset_mask: Optional[torch.Tensor] = None,
439
+ ) -> Tuple[List[torch.Tensor], torch.Tensor]: # Modify return type to include attention weights
440
+
441
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
442
+ extended_attention_mask = extended_attention_mask.to(
443
+ dtype=torch.float32) # fp16 compatibility
444
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
445
+
446
+ attention_mask_bool = attention_mask.bool()
447
+ batch, seqlen = hidden_states.shape[:2]
448
+ # Unpad inputs and mask. It will remove tokens that are padded.
449
+ # Assume ntokens is total number of tokens (padded and non-padded)
450
+ # and ntokens_unpad is total number of non-padded tokens.
451
+ # Then unpadding performs the following compression of the inputs:
452
+ # hidden_states[ntokens,hidden] -> hidden_states[ntokens_unpad,hidden]
453
+ hidden_states, indices, cu_seqlens, _ = unpad_input(
454
+ hidden_states, attention_mask_bool)
455
+
456
+ # Add alibi matrix to extended_attention_mask
457
+ if self._current_alibi_size < seqlen:
458
+ # Rebuild the alibi tensor when needed
459
+ warnings.warn(
460
+ f'Increasing alibi size from {self._current_alibi_size} to {seqlen}'
461
+ )
462
+ self.rebuild_alibi_tensor(size=seqlen, device=hidden_states.device)
463
+ elif self.alibi.device != hidden_states.device:
464
+ # Device catch-up
465
+ self.alibi = self.alibi.to(hidden_states.device)
466
+ alibi_bias = self.alibi[:, :, :seqlen, :seqlen]
467
+ attn_bias = extended_attention_mask[:, :, :seqlen, :seqlen]
468
+ alibi_attn_mask = attn_bias + alibi_bias
469
+
470
+ all_encoder_layers = []
471
+ all_attention_weights = [] # List to store attention weights
472
+ all_attention_probs = []
473
+
474
+ if subset_mask is None:
475
+ for layer_module in self.layer:
476
+ # JAANDOUI: Since we get now attention too, we need to unpack 2 elements instead of 1.
477
+ hidden_states, attention_weights, attention_probs = layer_module(hidden_states,
478
+ cu_seqlens,
479
+ seqlen,
480
+ None,
481
+ indices,
482
+ attn_mask=attention_mask,
483
+ bias=alibi_attn_mask)
484
+ # JAANDOUI
485
+ # print(f'Inner Attention: {attention_weights}')
486
+ # print(f'Inner Attention shape: {attention_weights.shape}')
487
+ all_attention_weights.append(attention_weights) # Store attention weights
488
+ all_attention_probs.append(attention_probs) # Store attention probs
489
+
490
+ if output_all_encoded_layers:
491
+ all_encoder_layers.append(hidden_states)
492
+ # Pad inputs and mask. It will insert back zero-padded tokens.
493
+ # Assume ntokens is total number of tokens (padded and non-padded)
494
+ # and ntokens_unpad is total number of non-padded tokens.
495
+ # Then padding performs the following de-compression:
496
+ # hidden_states[ntokens_unpad,hidden] -> hidden_states[ntokens,hidden]
497
+ hidden_states = pad_input(hidden_states, indices, batch, seqlen)
498
+ else:
499
+ for i in range(len(self.layer) - 1):
500
+ layer_module = self.layer[i]
501
+ # JAANDOUI: Since we get now attention too, we need to unpack 2 elements instead of 1.
502
+ hidden_states, attention_weights, attention_probs = layer_module(hidden_states,
503
+ cu_seqlens,
504
+ seqlen,
505
+ None,
506
+ indices,
507
+ attn_mask=attention_mask,
508
+ bias=alibi_attn_mask)
509
+ all_attention_weights.append(attention_weights) # JAANDOUI: Store attention weights
510
+ all_attention_probs.append(attention_probs) # Store attention probs
511
+
512
+ if output_all_encoded_layers:
513
+ all_encoder_layers.append(hidden_states)
514
+ subset_idx = torch.nonzero(subset_mask[attention_mask_bool],
515
+ as_tuple=False).flatten()
516
+ # JAANDOUI: Since we get now attention too, we need to unpack 2 elements instead of 1.
517
+ hidden_states, attention_weights, attention_probs = self.layer[-1](hidden_states,
518
+ cu_seqlens,
519
+ seqlen,
520
+ subset_idx=subset_idx,
521
+ indices=indices,
522
+ attn_mask=attention_mask,
523
+ bias=alibi_attn_mask)
524
+ all_attention_weights.append(attention_weights) # JAANDOUI: appending the attention of different layers together.
525
+ all_attention_probs.append(attention_probs) # Store attention probs
526
+
527
+ # print(f'here is the matrix of attentions inside encoder: \n {all_attention_weights}')
528
+ # print(f'and this is the [0]shape inside encoder: \n {all_attention_weights[0].shape}')
529
+ # print(f'NUMBER6: {all_attention_weights}')
530
+ if not output_all_encoded_layers:
531
+ all_encoder_layers.append(hidden_states)
532
+
533
+ # JAANDOUI: Since we now return both, we need to handle them wherever BertEncoder forward is called.
534
+ return all_encoder_layers, all_attention_weights, all_attention_probs # Return both hidden states and attention weights
535
+ # return all_encoder_layers # JAANDOUI: original return.
536
+
537
+
538
+
539
+ class BertPooler(nn.Module):
540
+
541
+ def __init__(self, config):
542
+ super(BertPooler, self).__init__()
543
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
544
+ self.activation = nn.Tanh()
545
+
546
+ def forward(self,
547
+ hidden_states: torch.Tensor,
548
+ pool: Optional[bool] = True) -> torch.Tensor:
549
+ # We "pool" the model by simply taking the hidden state corresponding
550
+ # to the first token.
551
+ first_token_tensor = hidden_states[:, 0] if pool else hidden_states
552
+ pooled_output = self.dense(first_token_tensor)
553
+ pooled_output = self.activation(pooled_output)
554
+ return pooled_output
555
+
556
+
557
+ class BertPredictionHeadTransform(nn.Module):
558
+
559
+ def __init__(self, config):
560
+ super().__init__()
561
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
562
+ if isinstance(config.hidden_act, str):
563
+ self.transform_act_fn = ACT2FN[config.hidden_act]
564
+ else:
565
+ self.transform_act_fn = config.hidden_act
566
+ self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
567
+
568
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
569
+ hidden_states = self.dense(hidden_states)
570
+ hidden_states = self.transform_act_fn(hidden_states)
571
+ hidden_states = self.LayerNorm(hidden_states)
572
+ return hidden_states
573
+
574
+
575
+ class BertModel(BertPreTrainedModel):
576
+ """Overall BERT model.
577
+
578
+ Args:
579
+ config: a BertConfig class instance with the configuration to build a new model
580
+
581
+ Inputs:
582
+ `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
583
+ with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
584
+ `extract_features.py`, `run_classifier.py` and `run_squad.py`)
585
+ `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
586
+ types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
587
+ a `sentence B` token (see BERT paper for more details).
588
+ `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
589
+ selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
590
+ input sequence length in the current batch. It's the mask that we typically use for attention when
591
+ a batch has varying length sentences.
592
+ `output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.
593
+
594
+ Outputs: Tuple of (encoded_layers, pooled_output)
595
+ `encoded_layers`: controlled by `output_all_encoded_layers` argument:
596
+ - `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end
597
+ of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each
598
+ encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],
599
+ - `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding
600
+ to the last attention block of shape [batch_size, sequence_length, hidden_size],
601
+ `pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a
602
+ classifier pretrained on top of the hidden state associated to the first character of the
603
+ input (`CLS`) to train on the Next-Sentence task (see BERT's paper).
604
+
605
+ Example usage:
606
+ ```python
607
+ # Already been converted into WordPiece token ids
608
+ input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
609
+ input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
610
+ token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
611
+ config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
612
+ num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
613
+ model = BertModel(config=config)
614
+ all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
615
+ ```
616
+ """
617
+
618
+ def __init__(self, config, add_pooling_layer=True):
619
+ super(BertModel, self).__init__(config)
620
+ self.embeddings = BertEmbeddings(config)
621
+ self.encoder = BertEncoder(config)
622
+ self.pooler = BertPooler(config) if add_pooling_layer else None
623
+ self.post_init()
624
+
625
+ def get_input_embeddings(self):
626
+ return self.embeddings.word_embeddings
627
+
628
+ def set_input_embeddings(self, value):
629
+ self.embeddings.word_embeddings = value
630
+
631
+ def forward(
632
+ self,
633
+ input_ids: torch.Tensor,
634
+ token_type_ids: Optional[torch.Tensor] = None,
635
+ attention_mask: Optional[torch.Tensor] = None,
636
+ position_ids: Optional[torch.Tensor] = None,
637
+ output_all_encoded_layers: Optional[bool] = False,
638
+ masked_tokens_mask: Optional[torch.Tensor] = None,
639
+ **kwargs
640
+ ) -> Tuple[Union[List[torch.Tensor], torch.Tensor], Optional[torch.Tensor]]:
641
+ if attention_mask is None:
642
+ attention_mask = torch.ones_like(input_ids)
643
+ if token_type_ids is None:
644
+ token_type_ids = torch.zeros_like(input_ids)
645
+
646
+ embedding_output = self.embeddings(input_ids, token_type_ids,
647
+ position_ids)
648
+
649
+ subset_mask = []
650
+ first_col_mask = []
651
+
652
+ if masked_tokens_mask is None:
653
+ subset_mask = None
654
+ else:
655
+ first_col_mask = torch.zeros_like(masked_tokens_mask)
656
+ first_col_mask[:, 0] = True
657
+ subset_mask = masked_tokens_mask | first_col_mask
658
+
659
+ # JAANDOUI: first part where we call self.encoder (which is the instance of BertEncoder defined here)
660
+ # JAANDOUI: need to return the attention weights here too.
661
+ encoder_outputs, all_attention_weights, all_attention_probs = self.encoder(
662
+ embedding_output,
663
+ attention_mask,
664
+ output_all_encoded_layers=output_all_encoded_layers,
665
+ subset_mask=subset_mask)
666
+ # print(f'NUMBER7: {all_attention_weights}')
667
+ # print(f'here is the matrix of attentions in BERT: \n {all_attention_weights}')
668
+ # print(f'and this is the [0]shape in BERT: \n {all_attention_weights[0].shape}')
669
+
670
+ if masked_tokens_mask is None:
671
+ sequence_output = encoder_outputs[-1]
672
+ pooled_output = self.pooler(
673
+ sequence_output) if self.pooler is not None else None
674
+ else:
675
+ # TD [2022-03-01]: the indexing here is very tricky.
676
+ attention_mask_bool = attention_mask.bool()
677
+ subset_idx = subset_mask[attention_mask_bool] # type: ignore
678
+ sequence_output = encoder_outputs[-1][
679
+ masked_tokens_mask[attention_mask_bool][subset_idx]]
680
+ if self.pooler is not None:
681
+ pool_input = encoder_outputs[-1][
682
+ first_col_mask[attention_mask_bool][subset_idx]]
683
+ pooled_output = self.pooler(pool_input, pool=False)
684
+ else:
685
+ pooled_output = None
686
+
687
+ if not output_all_encoded_layers:
688
+ encoder_outputs = sequence_output
689
+
690
+ # JAANDOUI: returning all_attention_weights too
691
+ if self.pooler is not None:
692
+ # print(f'NUMBER8: {all_attention_weights}')
693
+ return encoder_outputs, pooled_output, all_attention_weights, all_attention_probs
694
+
695
+ # JAANDOUI: returning all_attention_weights too
696
+ # print(f'NUMBER9: {all_attention_weights}')
697
+ return encoder_outputs, None, all_attention_weights, all_attention_probs
698
+ # JAANDOUI: need to handle the returned elements wherever BertModel is instantiated.
699
+
700
+ ###################
701
+ # Bert Heads
702
+ ###################
703
+ class BertLMPredictionHead(nn.Module):
704
+
705
+ def __init__(self, config, bert_model_embedding_weights):
706
+ super().__init__()
707
+ self.transform = BertPredictionHeadTransform(config)
708
+ # The output weights are the same as the input embeddings, but there is
709
+ # an output-only bias for each token.
710
+ self.decoder = nn.Linear(bert_model_embedding_weights.size(1),
711
+ bert_model_embedding_weights.size(0))
712
+ self.decoder.weight = bert_model_embedding_weights
713
+
714
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
715
+ hidden_states = self.transform(hidden_states)
716
+ hidden_states = self.decoder(hidden_states)
717
+ return hidden_states
718
+
719
+
720
+ class BertOnlyMLMHead(nn.Module):
721
+
722
+ def __init__(self, config, bert_model_embedding_weights):
723
+ super().__init__()
724
+ self.predictions = BertLMPredictionHead(config,
725
+ bert_model_embedding_weights)
726
+
727
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
728
+ prediction_scores = self.predictions(sequence_output)
729
+ return prediction_scores
730
+
731
+
732
+ class BertOnlyNSPHead(nn.Module):
733
+
734
+ def __init__(self, config):
735
+ super().__init__()
736
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
737
+
738
+ def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
739
+ seq_relationship_score = self.seq_relationship(pooled_output)
740
+ return seq_relationship_score
741
+
742
+
743
+
744
+ class BertForMaskedLM(BertPreTrainedModel):
745
+
746
+ def __init__(self, config):
747
+ super().__init__(config)
748
+
749
+ if config.is_decoder:
750
+ warnings.warn(
751
+ 'If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for '
752
+ 'bi-directional self-attention.')
753
+
754
+ # JAANDOUI: this part is only for the pretraining, I don't think it is called if we finetune
755
+ # there handle the returned elements (we now get 3 elements) of BertModel if pretraining
756
+ self.bert = BertModel(config, add_pooling_layer=False)
757
+ self.cls = BertOnlyMLMHead(config,
758
+ self.bert.embeddings.word_embeddings.weight)
759
+
760
+ # Initialize weights and apply final processing
761
+ self.post_init()
762
+
763
+ def get_output_embeddings(self):
764
+ return self.cls.predictions.decoder
765
+
766
+ def set_output_embeddings(self, new_embeddings):
767
+ self.cls.predictions.decoder = new_embeddings
768
+
769
+ def forward(
770
+ self,
771
+ input_ids: Optional[torch.Tensor] = None,
772
+ attention_mask: Optional[torch.Tensor] = None,
773
+ token_type_ids: Optional[torch.Tensor] = None,
774
+ position_ids: Optional[torch.Tensor] = None,
775
+ head_mask: Optional[torch.Tensor] = None,
776
+ inputs_embeds: Optional[torch.Tensor] = None,
777
+ encoder_hidden_states: Optional[torch.Tensor] = None,
778
+ encoder_attention_mask: Optional[torch.Tensor] = None,
779
+ labels: Optional[torch.Tensor] = None,
780
+ output_attentions: Optional[bool] = None,
781
+ output_hidden_states: Optional[bool] = None,
782
+ return_dict: Optional[bool] = None,
783
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
784
+ # labels should be a `torch.LongTensor` of shape
785
+ # `(batch_size, sequence_length)`. These are used for computing the
786
+ # masked language modeling loss.
787
+ #
788
+ # Indices should be in `[-100, 0, ..., config.vocab_size]` (see
789
+ # `input_ids` docstring) Tokens with indices set to `-100` are ignored
790
+ # (masked), the loss is only computed for the tokens with labels in `[0,
791
+ # ..., config.vocab_size]`
792
+ #
793
+ # Prediction scores are only computed for masked tokens and the (bs,
794
+ # seqlen) dimensions are flattened
795
+ if (input_ids is not None) == (inputs_embeds is not None):
796
+ raise ValueError('Must specify either input_ids or input_embeds!')
797
+
798
+ if labels is None:
799
+ masked_tokens_mask = None
800
+ else:
801
+ masked_tokens_mask = labels > 0
802
+
803
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
804
+
805
+ # JAANDOUI: for the pretraining: return handled here.
806
+ outputs = self.bert(
807
+ input_ids,
808
+ attention_mask=attention_mask,
809
+ token_type_ids=token_type_ids,
810
+ position_ids=position_ids,
811
+ head_mask=head_mask,
812
+ inputs_embeds=inputs_embeds,
813
+ encoder_hidden_states=encoder_hidden_states,
814
+ encoder_attention_mask=encoder_attention_mask,
815
+ output_attentions=output_attentions,
816
+ output_hidden_states=output_hidden_states,
817
+ return_dict=return_dict,
818
+ masked_tokens_mask=masked_tokens_mask,
819
+ )
820
+
821
+ sequence_output = outputs[0]
822
+ prediction_scores = self.cls(sequence_output)
823
+
824
+ loss = None
825
+ if labels is not None:
826
+ # Compute loss
827
+ loss_fct = nn.CrossEntropyLoss()
828
+ masked_token_idx = torch.nonzero(labels.flatten() > 0,
829
+ as_tuple=False).flatten()
830
+ loss = loss_fct(prediction_scores,
831
+ labels.flatten()[masked_token_idx])
832
+
833
+ assert input_ids is not None, 'Coding error; please open an issue'
834
+ batch, seqlen = input_ids.shape[:2]
835
+ prediction_scores = rearrange(index_put_first_axis(
836
+ prediction_scores, masked_token_idx, batch * seqlen),
837
+ '(b s) d -> b s d',
838
+ b=batch)
839
+
840
+ if not return_dict:
841
+ output = (prediction_scores,) + outputs[2:] # JAANDOUI TODO: might need to handle this part and everywhere where we get outputs (now outputs has 3 elements not 2)
842
+ return ((loss,) + output) if loss is not None else output
843
+
844
+ return MaskedLMOutput(
845
+ loss=loss,
846
+ logits=prediction_scores,
847
+ hidden_states=outputs[0],
848
+ attentions=None,
849
+ )
850
+
851
+ def prepare_inputs_for_generation(self, input_ids: torch.Tensor,
852
+ attention_mask: torch.Tensor,
853
+ **model_kwargs):
854
+ input_shape = input_ids.shape
855
+ effective_batch_size = input_shape[0]
856
+
857
+ # add a dummy token
858
+ if self.config.pad_token_id is None:
859
+ raise ValueError('The PAD token should be defined for generation')
860
+
861
+ attention_mask = torch.cat([
862
+ attention_mask,
863
+ attention_mask.new_zeros((attention_mask.shape[0], 1))
864
+ ],
865
+ dim=-1)
866
+ dummy_token = torch.full((effective_batch_size, 1),
867
+ self.config.pad_token_id,
868
+ dtype=torch.long,
869
+ device=input_ids.device)
870
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
871
+
872
+ return {'input_ids': input_ids, 'attention_mask': attention_mask}
873
+
874
+
875
+ # JAANDOUI: this model is the one used for finetuning.
876
+ class BertForSequenceClassification(BertPreTrainedModel):
877
+ """Bert Model transformer with a sequence classification/regression head.
878
+
879
+ This head is just a linear layer on top of the pooled output. Used for,
880
+ e.g., GLUE tasks.
881
+ """
882
+
883
+ def __init__(self, config):
884
+ super().__init__(config)
885
+ self.num_labels = config.num_labels
886
+ self.config = config
887
+
888
+ self.bert = BertModel(config)
889
+ classifier_dropout = (config.classifier_dropout
890
+ if config.classifier_dropout is not None else
891
+ config.hidden_dropout_prob)
892
+ self.dropout = nn.Dropout(classifier_dropout)
893
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
894
+
895
+ # Initialize weights and apply final processing
896
+ self.post_init()
897
+
898
+
899
+ def forward(
900
+ self,
901
+ input_ids: Optional[torch.Tensor] = None,
902
+ attention_mask: Optional[torch.Tensor] = None,
903
+ token_type_ids: Optional[torch.Tensor] = None,
904
+ position_ids: Optional[torch.Tensor] = None,
905
+ head_mask: Optional[torch.Tensor] = None,
906
+ inputs_embeds: Optional[torch.Tensor] = None,
907
+ labels: Optional[torch.Tensor] = None,
908
+ output_attentions: Optional[bool] = None,
909
+ output_hidden_states: Optional[bool] = None,
910
+ return_dict: Optional[bool] = None,
911
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
912
+ # labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
913
+ # Labels for computing the sequence classification/regression loss.
914
+ # Indices should be in `[0, ..., config.num_labels - 1]`.
915
+ # If `config.num_labels == 1` a regression loss is computed
916
+ # (mean-square loss). If `config.num_labels > 1` a classification loss
917
+ # is computed (cross-entropy).
918
+
919
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
920
+
921
+ outputs = self.bert(
922
+ input_ids,
923
+ attention_mask=attention_mask,
924
+ token_type_ids=token_type_ids,
925
+ position_ids=position_ids,
926
+ head_mask=head_mask,
927
+ inputs_embeds=inputs_embeds,
928
+ output_attentions=output_attentions,
929
+ output_hidden_states=output_hidden_states,
930
+ return_dict=return_dict,
931
+ )
932
+
933
+ pooled_output = outputs[1]
934
+
935
+ # try:
936
+ # print(f'outputs[2] before reassignment SHAPE: {outputs[3][0].shape} ')
937
+ # except:
938
+ # print(print(f'outputs[2] before reassignment LENGTH: {len(outputs[3][0])} '))
939
+
940
+ # JAANDOUI:
941
+ all_attention_probs = outputs[3]
942
+
943
+ # try:
944
+ # print(f'outputs[2] AFTER reassignment probsss SHAPE: {outputs[3][0].shape} ')
945
+ # except:
946
+ # print(print(f'outputs[2] AFTER reassignment probsss LENGTH: {len(outputs[3][0])} '))
947
+
948
+
949
+
950
+ # try:
951
+ # print(f'all_attention_weights probsss last: {all_attention_probs.shape}')
952
+ # except:
953
+ # try:
954
+ # print(f'last first except probsss: {all_attention_probs[0].shape}')
955
+ # except:
956
+ # print(f'last second except probsss: {len(all_attention_probs[0])}')
957
+
958
+
959
+ pooled_output = self.dropout(pooled_output)
960
+ logits = self.classifier(pooled_output)
961
+
962
+ loss = None
963
+ if labels is not None:
964
+ # Compute loss
965
+ if self.config.problem_type is None:
966
+ if self.num_labels == 1:
967
+ self.config.problem_type = 'regression'
968
+ elif self.num_labels > 1 and (labels.dtype == torch.long or
969
+ labels.dtype == torch.int):
970
+ self.config.problem_type = 'single_label_classification'
971
+ else:
972
+ self.config.problem_type = 'multi_label_classification'
973
+
974
+ if self.config.problem_type == 'regression':
975
+ loss_fct = nn.MSELoss()
976
+ if self.num_labels == 1:
977
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
978
+ else:
979
+ loss = loss_fct(logits, labels)
980
+ elif self.config.problem_type == 'single_label_classification':
981
+ loss_fct = nn.CrossEntropyLoss()
982
+ loss = loss_fct(logits.view(-1, self.num_labels),
983
+ labels.view(-1))
984
+ elif self.config.problem_type == 'multi_label_classification':
985
+ loss_fct = nn.BCEWithLogitsLoss()
986
+ loss = loss_fct(logits, labels)
987
+
988
+ if not return_dict:
989
+ # JAANDOUI TODO maybe.
990
+ # print(f'return_dict is {return_dict}')
991
+ output = (logits,) + outputs[2:]
992
+ return ((loss,) + output) if loss is not None else output
993
+
994
+ # print(outputs.attentions)
995
+ # try:
996
+ # print(f'not stacked final attention probsss SHAPE: {outputs[3][0].shape}')
997
+ # except:
998
+ # print(f'not stacked final attention probsss LEN: {len(outputs[3])}')
999
+
1000
+ # try:
1001
+ # print(f'STACKED final attention SHAPE: {(outputs.attentions).shape}')
1002
+ # except:
1003
+ # try:
1004
+ # print(f'STACKED final attention LEN: {(outputs.attentions)[0].shape}')
1005
+ # except:
1006
+ # print(f'STACKED final attention LEN 2: {len(outputs.attentions)}')
1007
+
1008
+ return SequenceClassifierOutput(
1009
+ loss=loss,
1010
+ logits=logits,
1011
+ hidden_states=outputs[0],
1012
+ #JAANDOUI: returning all_attention_weights here
1013
+ # attentions=torch.stack(outputs[2], dim=0),
1014
+ attentions=outputs[3], # JAANDOUI TODO: should I stack here ????
1015
+ )
1016
+
bert_padding.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ from typing import Tuple, cast
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from einops import rearrange, repeat
13
+
14
+
15
+ class IndexFirstAxis(torch.autograd.Function):
16
+
17
+ @staticmethod
18
+ def forward(ctx, input: torch.Tensor,
19
+ indices: torch.Tensor) -> torch.Tensor:
20
+ """Get just the values of `input` which are at `indices`.
21
+
22
+ Arguments:
23
+ ctx: the autograd context object
24
+ input: (b, ...) 2+ dimensional tensor
25
+ indices: (num_idx) 1D tensor
26
+ """
27
+ ctx.save_for_backward(indices)
28
+ assert input.ndim >= 2
29
+ ctx.first_axis_dim, other_shape = input.shape[0], input.shape[
30
+ 1:] # type: ignore
31
+ second_dim = other_shape.numel(
32
+ ) # product of sizes of all but first dimension
33
+ # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
34
+ return torch.gather(
35
+ rearrange(input, 'b ... -> b (...)'), # (b, ...) -> (b, second_dim)
36
+ 0,
37
+ repeat(indices, 'z -> z d',
38
+ d=second_dim) # (indices,) -> (indices, second_dim)
39
+ ).reshape(-1, *other_shape) # (num_idx, ...)
40
+
41
+ @staticmethod
42
+ def backward(ctx, grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]:
43
+ indices, = ctx.saved_tensors
44
+ assert grad_output.ndim >= 2
45
+ other_shape = grad_output.shape[1:]
46
+ grad_output = rearrange(grad_output, 'b ... -> b (...)')
47
+ grad_input = torch.zeros([ctx.first_axis_dim, grad_output.shape[1]],
48
+ device=grad_output.device,
49
+ dtype=grad_output.dtype)
50
+ # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
51
+ # grad_input[indices] = grad_output
52
+ grad_input.scatter_(0,
53
+ repeat(indices, 'z -> z d', d=grad_output.shape[1]),
54
+ grad_output)
55
+ return grad_input.reshape(ctx.first_axis_dim, *other_shape), None
56
+
57
+
58
+ index_first_axis = IndexFirstAxis.apply
59
+
60
+
61
+ class IndexPutFirstAxis(torch.autograd.Function):
62
+
63
+ @staticmethod
64
+ def forward(ctx, values: torch.Tensor, indices: torch.Tensor,
65
+ first_axis_dim) -> torch.Tensor:
66
+ ctx.save_for_backward(indices)
67
+ assert indices.ndim == 1
68
+ assert values.ndim >= 2
69
+ output = torch.zeros(first_axis_dim,
70
+ *values.shape[1:],
71
+ device=values.device,
72
+ dtype=values.dtype)
73
+ output[indices] = values
74
+ return output
75
+
76
+ @staticmethod
77
+ def backward(ctx,
78
+ grad_output: torch.Tensor) -> Tuple[torch.Tensor, None, None]:
79
+ indices, = ctx.saved_tensors
80
+ grad_values = grad_output[indices]
81
+ return grad_values, None, None
82
+
83
+
84
+ index_put_first_axis = IndexPutFirstAxis.apply
85
+
86
+
87
+ def unpad_input(
88
+ hidden_states: torch.Tensor,
89
+ attention_mask: torch.Tensor,
90
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
91
+ """Remove padding from input sequences.
92
+
93
+ Arguments:
94
+ hidden_states: (batch, seqlen, ...)
95
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
96
+
97
+ Returns:
98
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
99
+ indices: (total_nnz)
100
+ cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states.
101
+ max_seqlen_in_batch: int ()
102
+ """
103
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
104
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
105
+ max_seqlen_in_batch = int(seqlens_in_batch.max().item())
106
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32),
107
+ (1, 0))
108
+ # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the
109
+ # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim
110
+ # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to
111
+ # index with integer indices. Moreover, torch's index is a bit slower than it needs to be,
112
+ # so we write custom forward and backward to make it a bit faster.
113
+ hidden_states = cast(
114
+ torch.Tensor,
115
+ index_first_axis(rearrange(hidden_states, 'b s ... -> (b s) ...'),
116
+ indices))
117
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
118
+
119
+
120
+ def unpad_input_only(
121
+ hidden_states: torch.Tensor,
122
+ attention_mask: torch.Tensor,
123
+ ) -> torch.Tensor:
124
+ """Like unpad_input, but only return the unpadded first tensor.
125
+
126
+ Save a small amount of overhead.
127
+
128
+ Arguments:
129
+ hidden_states: (batch, seqlen, ...)
130
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
131
+
132
+ Returns:
133
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
134
+ """
135
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
136
+ return index_first_axis(rearrange(hidden_states, 'b s ... -> (b s) ...'),
137
+ indices)
138
+
139
+
140
+ def pad_input(hidden_states: torch.Tensor, indices: torch.Tensor, batch: int,
141
+ seqlen: int) -> torch.Tensor:
142
+ """Add padding to sequences.
143
+
144
+ Arguments:
145
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
146
+ indices: (total_nnz)
147
+ batch: int batch_size
148
+ seqlen: int max sequence length
149
+
150
+ Returns:
151
+ hidden_states: (batch, seqlen, ...)
152
+ """
153
+ output = index_put_first_axis(hidden_states, indices, batch * seqlen)
154
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"_name_or_path": "zhihan1996/DNABERT-2-117M",
2
+ "alibi_starting_size": 512,
3
+ "attention_probs_dropout_prob": 0.0,
4
+ "auto_map":
5
+ {"AutoConfig": "configuration_bert.BertConfig",
6
+ "AutoModel": "bert_layers.BertModel",
7
+ "AutoModelForMaskedLM": "bert_layers.BertForMaskedLM",
8
+ "AutoModelForSequenceClassification": "bert_layers.BertForSequenceClassification"
9
+ },
10
+ "classifier_dropout": null,
11
+ "gradient_checkpointing": false,
12
+ "hidden_act": "gelu",
13
+ "hidden_dropout_prob": 0.1,
14
+ "hidden_size": 768,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 3072,
17
+ "layer_norm_eps": 1e-12,
18
+ "max_position_embeddings": 512,
19
+ "num_attention_heads": 12,
20
+ "num_hidden_layers": 12,
21
+ "position_embedding_type": "absolute",
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.28.0",
24
+ "type_vocab_size": 2,
25
+ "use_cache": true,
26
+ "vocab_size": 4096,
27
+ "flash_attn": false
28
+ }
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.configuration_utils import PretrainedConfig
5
+
6
+
7
+ class BertConfig(PretrainedConfig):
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,1112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import math
50
+
51
+ import torch
52
+ import triton # type: ignore (reportMissingImports)
53
+ import triton.language as tl # type: ignore (reportMissingImports)
54
+ from einops import repeat
55
+
56
+
57
+ @triton.autotune(
58
+ configs=[
59
+ triton.Config({
60
+ 'BLOCK_M': 128,
61
+ 'BLOCK_N': 128
62
+ },
63
+ num_warps=8,
64
+ num_stages=1),
65
+ # This config has a race condition when EVEN_M == False, disabling it for now.
66
+ # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1),
67
+ ],
68
+ key=[
69
+ 'CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL',
70
+ 'BLOCK_HEADDIM'
71
+ ])
72
+ @triton.heuristics({
73
+ 'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0,
74
+ 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0,
75
+ 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM'],
76
+ })
77
+ @triton.jit
78
+ def _fwd_kernel(
79
+ Q,
80
+ K,
81
+ V,
82
+ Bias,
83
+ Out,
84
+ Lse,
85
+ TMP, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug
86
+ softmax_scale,
87
+ stride_qb,
88
+ stride_qh,
89
+ stride_qm,
90
+ stride_kb,
91
+ stride_kh,
92
+ stride_kn,
93
+ stride_vb,
94
+ stride_vh,
95
+ stride_vn,
96
+ stride_bb,
97
+ stride_bh,
98
+ stride_bm,
99
+ stride_ob,
100
+ stride_oh,
101
+ stride_om,
102
+ nheads,
103
+ seqlen_q,
104
+ seqlen_k,
105
+ seqlen_q_rounded,
106
+ headdim,
107
+ CACHE_KEY_SEQLEN_Q,
108
+ CACHE_KEY_SEQLEN_K,
109
+ BIAS_TYPE: tl.constexpr,
110
+ IS_CAUSAL: tl.constexpr,
111
+ BLOCK_HEADDIM: tl.constexpr,
112
+ EVEN_M: tl.constexpr,
113
+ EVEN_N: tl.constexpr,
114
+ EVEN_HEADDIM: tl.constexpr,
115
+ BLOCK_M: tl.constexpr,
116
+ BLOCK_N: tl.constexpr,
117
+ ):
118
+ start_m = tl.program_id(0)
119
+ off_hb = tl.program_id(1)
120
+ off_b = off_hb // nheads
121
+ off_h = off_hb % nheads
122
+ # off_b = tl.program_id(1)
123
+ # off_h = tl.program_id(2)
124
+ # off_hb = off_b * nheads + off_h
125
+ # initialize offsets
126
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
127
+ offs_n = tl.arange(0, BLOCK_N)
128
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
129
+ # Initialize pointers to Q, K, V
130
+ # Adding parenthesis around indexing might use int32 math instead of int64 math?
131
+ # https://github.com/openai/triton/issues/741
132
+ # I'm seeing a tiny bit of difference (5-7us)
133
+ q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (
134
+ offs_m[:, None] * stride_qm + offs_d[None, :])
135
+ k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (
136
+ offs_n[:, None] * stride_kn + offs_d[None, :])
137
+ v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (
138
+ offs_n[:, None] * stride_vn + offs_d[None, :])
139
+ if BIAS_TYPE == 'vector':
140
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
141
+ elif BIAS_TYPE == 'matrix':
142
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (
143
+ offs_m[:, None] * stride_bm + offs_n[None, :])
144
+ else:
145
+ raise ValueError("BIAS_TYPE must be one of {'vector', 'matrix'}")
146
+ # initialize pointer to m and l
147
+ t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
148
+ lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
149
+ m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
150
+ acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
151
+ # load q: it will stay in SRAM throughout
152
+ # [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call
153
+ # tl.load(q_ptrs), we get the wrong output!
154
+ if EVEN_M & EVEN_N:
155
+ if EVEN_HEADDIM:
156
+ q = tl.load(q_ptrs)
157
+ else:
158
+ q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
159
+ else:
160
+ if EVEN_HEADDIM:
161
+ q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
162
+ else:
163
+ q = tl.load(q_ptrs,
164
+ mask=(offs_m[:, None] < seqlen_q) &
165
+ (offs_d[None, :] < headdim),
166
+ other=0.0)
167
+ # loop over k, v and update accumulator
168
+ end_n = seqlen_k if not IS_CAUSAL else tl.minimum(
169
+ (start_m + 1) * BLOCK_M, seqlen_k)
170
+ for start_n in range(0, end_n, BLOCK_N):
171
+ start_n = tl.multiple_of(start_n, BLOCK_N)
172
+ # -- compute qk ----
173
+ if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
174
+ if EVEN_HEADDIM:
175
+ k = tl.load(k_ptrs + start_n * stride_kn)
176
+ else:
177
+ k = tl.load(k_ptrs + start_n * stride_kn,
178
+ mask=offs_d[None, :] < headdim,
179
+ other=0.0)
180
+ else:
181
+ if EVEN_HEADDIM:
182
+ k = tl.load(k_ptrs + start_n * stride_kn,
183
+ mask=(start_n + offs_n)[:, None] < seqlen_k,
184
+ other=0.0)
185
+ else:
186
+ k = tl.load(k_ptrs + start_n * stride_kn,
187
+ mask=((start_n + offs_n)[:, None] < seqlen_k) &
188
+ (offs_d[None, :] < headdim),
189
+ other=0.0)
190
+ qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
191
+ qk += tl.dot(q, k, trans_b=True)
192
+ # Trying to combine the two masks seem to make the result wrong
193
+ if not EVEN_N: # Need to mask out otherwise the softmax is wrong
194
+ qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0,
195
+ float('-inf'))
196
+ if IS_CAUSAL:
197
+ qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0,
198
+ float('-inf'))
199
+ if BIAS_TYPE != 'none':
200
+ if BIAS_TYPE == 'vector':
201
+ if EVEN_N:
202
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
203
+ else:
204
+ bias = tl.load(b_ptrs + start_n,
205
+ mask=(start_n + offs_n) < seqlen_k,
206
+ other=0.0).to(tl.float32)
207
+ bias = bias[None, :]
208
+ elif BIAS_TYPE == 'matrix':
209
+ if EVEN_M & EVEN_N:
210
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
211
+ else:
212
+ bias = tl.load(b_ptrs + start_n,
213
+ mask=(offs_m[:, None] < seqlen_q) &
214
+ ((start_n + offs_n)[None, :] < seqlen_k),
215
+ other=0.0).to(tl.float32)
216
+ else:
217
+ raise ValueError(
218
+ "BIAS_TYPE must be one of {'vector', 'matrix'}")
219
+ # Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler
220
+ # can then fuse the mult and add into an fma instruction. But if we have bias we need to
221
+ # to multiply with softmax_scale here.
222
+ qk = qk * softmax_scale + bias
223
+ m_ij = tl.maximum(tl.max(qk, 1), lse_i)
224
+ p = tl.exp(qk - m_ij[:, None])
225
+ else:
226
+ m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
227
+ p = tl.exp(qk * softmax_scale - m_ij[:, None])
228
+ l_ij = tl.sum(p, 1)
229
+
230
+ # scale acc_o
231
+ acc_o_scale = tl.exp(m_i - m_ij)
232
+
233
+ # # -- update output accumulator --
234
+ # BUG: have to store and immediately load
235
+ tl.store(t_ptrs, acc_o_scale)
236
+ acc_o_scale = tl.load(t_ptrs)
237
+ acc_o = acc_o * acc_o_scale[:, None]
238
+ # update acc_o
239
+ if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
240
+ if EVEN_HEADDIM:
241
+ v = tl.load(v_ptrs + start_n * stride_vn)
242
+ else:
243
+ v = tl.load(v_ptrs + start_n * stride_vn,
244
+ mask=offs_d[None, :] < headdim,
245
+ other=0.0)
246
+ else:
247
+ if EVEN_HEADDIM:
248
+ v = tl.load(v_ptrs + start_n * stride_vn,
249
+ mask=(start_n + offs_n)[:, None] < seqlen_k,
250
+ other=0.0)
251
+ else:
252
+ v = tl.load(v_ptrs + start_n * stride_vn,
253
+ mask=((start_n + offs_n)[:, None] < seqlen_k) &
254
+ (offs_d[None, :] < headdim),
255
+ other=0.0)
256
+ p = p.to(v.dtype)
257
+ acc_o += tl.dot(p, v)
258
+
259
+ # -- update statistics
260
+ m_i = m_ij
261
+ l_i_new = tl.exp(lse_i - m_ij) + l_ij
262
+ lse_i = m_ij + tl.log(l_i_new)
263
+
264
+ o_scale = tl.exp(m_i - lse_i)
265
+ # BUG: have to store and immediately load
266
+ tl.store(t_ptrs, o_scale)
267
+ o_scale = tl.load(t_ptrs)
268
+ acc_o = acc_o * o_scale[:, None]
269
+ # rematerialize offsets to save registers
270
+ start_m = tl.program_id(0)
271
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
272
+ # write back l and m
273
+ lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
274
+ tl.store(lse_ptrs, lse_i)
275
+ # initialize pointers to output
276
+ offs_n = tl.arange(0, BLOCK_HEADDIM)
277
+ out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (
278
+ offs_m[:, None] * stride_om + offs_n[None, :])
279
+ if EVEN_M:
280
+ if EVEN_HEADDIM:
281
+ tl.store(out_ptrs, acc_o)
282
+ else:
283
+ tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
284
+ else:
285
+ if EVEN_HEADDIM:
286
+ tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
287
+ else:
288
+ tl.store(out_ptrs,
289
+ acc_o,
290
+ mask=(offs_m[:, None] < seqlen_q) &
291
+ (offs_d[None, :] < headdim))
292
+
293
+
294
+ @triton.jit
295
+ def _bwd_preprocess_do_o_dot(
296
+ Out,
297
+ DO,
298
+ Delta,
299
+ stride_ob,
300
+ stride_oh,
301
+ stride_om,
302
+ stride_dob,
303
+ stride_doh,
304
+ stride_dom,
305
+ nheads,
306
+ seqlen_q,
307
+ seqlen_q_rounded,
308
+ headdim,
309
+ BLOCK_M: tl.constexpr,
310
+ BLOCK_HEADDIM: tl.constexpr,
311
+ ):
312
+ start_m = tl.program_id(0)
313
+ off_hb = tl.program_id(1)
314
+ off_b = off_hb // nheads
315
+ off_h = off_hb % nheads
316
+ # initialize offsets
317
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
318
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
319
+ # load
320
+ o = tl.load(Out + off_b * stride_ob + off_h * stride_oh +
321
+ offs_m[:, None] * stride_om + offs_d[None, :],
322
+ mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
323
+ other=0.0).to(tl.float32)
324
+ do = tl.load(DO + off_b * stride_dob + off_h * stride_doh +
325
+ offs_m[:, None] * stride_dom + offs_d[None, :],
326
+ mask=(offs_m[:, None] < seqlen_q) &
327
+ (offs_d[None, :] < headdim),
328
+ other=0.0).to(tl.float32)
329
+ delta = tl.sum(o * do, axis=1)
330
+ # write-back
331
+ tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
332
+
333
+
334
+ @triton.jit
335
+ def _bwd_kernel_one_col_block(
336
+ start_n,
337
+ Q,
338
+ K,
339
+ V,
340
+ Bias,
341
+ DO,
342
+ DQ,
343
+ DK,
344
+ DV,
345
+ LSE,
346
+ D,
347
+ softmax_scale,
348
+ stride_qm,
349
+ stride_kn,
350
+ stride_vn,
351
+ stride_bm,
352
+ stride_dom,
353
+ stride_dqm,
354
+ stride_dkn,
355
+ stride_dvn,
356
+ seqlen_q,
357
+ seqlen_k,
358
+ headdim,
359
+ ATOMIC_ADD: tl.constexpr,
360
+ BIAS_TYPE: tl.constexpr,
361
+ IS_CAUSAL: tl.constexpr,
362
+ BLOCK_HEADDIM: tl.constexpr,
363
+ EVEN_M: tl.constexpr,
364
+ EVEN_N: tl.constexpr,
365
+ EVEN_HEADDIM: tl.constexpr,
366
+ BLOCK_M: tl.constexpr,
367
+ BLOCK_N: tl.constexpr,
368
+ ):
369
+ # We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N)
370
+ begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M
371
+ # initialize row/col offsets
372
+ offs_qm = begin_m + tl.arange(0, BLOCK_M)
373
+ offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
374
+ offs_m = tl.arange(0, BLOCK_M)
375
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
376
+ # initialize pointers to value-like data
377
+ q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
378
+ k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
379
+ v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
380
+ do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
381
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
382
+ if BIAS_TYPE == 'vector':
383
+ b_ptrs = Bias + offs_n
384
+ elif BIAS_TYPE == 'matrix':
385
+ b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
386
+ else:
387
+ raise ValueError("BIAS_TYPE must be one of {'vector', 'matrix'}")
388
+ # initialize dv and dk
389
+ dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
390
+ dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
391
+ # k and v stay in SRAM throughout
392
+ # [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False,
393
+ # if we just call tl.load(k_ptrs), we get the wrong output!
394
+ if EVEN_N & EVEN_M:
395
+ if EVEN_HEADDIM:
396
+ k = tl.load(k_ptrs)
397
+ v = tl.load(v_ptrs)
398
+ else:
399
+ k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
400
+ v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
401
+ else:
402
+ if EVEN_HEADDIM:
403
+ k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
404
+ v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
405
+ else:
406
+ k = tl.load(k_ptrs,
407
+ mask=(offs_n[:, None] < seqlen_k) &
408
+ (offs_d[None, :] < headdim),
409
+ other=0.0)
410
+ v = tl.load(v_ptrs,
411
+ mask=(offs_n[:, None] < seqlen_k) &
412
+ (offs_d[None, :] < headdim),
413
+ other=0.0)
414
+ # loop over rows
415
+ num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
416
+ for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
417
+ start_m = tl.multiple_of(start_m, BLOCK_M)
418
+ offs_m_curr = start_m + offs_m
419
+ # load q, k, v, do on-chip
420
+ # Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117)
421
+ if EVEN_M & EVEN_HEADDIM:
422
+ q = tl.load(q_ptrs)
423
+ else:
424
+ if EVEN_HEADDIM:
425
+ q = tl.load(q_ptrs,
426
+ mask=offs_m_curr[:, None] < seqlen_q,
427
+ other=0.0)
428
+ else:
429
+ q = tl.load(q_ptrs,
430
+ mask=(offs_m_curr[:, None] < seqlen_q) &
431
+ (offs_d[None, :] < headdim),
432
+ other=0.0)
433
+ # recompute p = softmax(qk, dim=-1).T
434
+ qk = tl.dot(q, k, trans_b=True)
435
+ # Trying to combine the two masks seem to make the result wrong
436
+ if not EVEN_N: # Need to mask out otherwise the softmax is wrong
437
+ qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
438
+ if IS_CAUSAL:
439
+ qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk,
440
+ float('-inf'))
441
+ if BIAS_TYPE != 'none':
442
+ if BIAS_TYPE == 'vector':
443
+ if EVEN_N:
444
+ bias = tl.load(b_ptrs).to(tl.float32)
445
+ else:
446
+ bias = tl.load(b_ptrs, mask=offs_n < seqlen_k,
447
+ other=0.0).to(tl.float32)
448
+ bias = bias[None, :]
449
+ elif BIAS_TYPE == 'matrix':
450
+ if EVEN_M & EVEN_N:
451
+ bias = tl.load(b_ptrs).to(tl.float32)
452
+ else:
453
+ bias = tl.load(b_ptrs,
454
+ mask=(offs_m_curr[:, None] < seqlen_q) &
455
+ (offs_n[None, :] < seqlen_k),
456
+ other=0.0).to(tl.float32)
457
+ else:
458
+ raise ValueError(
459
+ "BIAS_TYPE must be one of {'vector', 'matrix'}")
460
+ qk = qk * softmax_scale + bias
461
+ # There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong.
462
+ # Also wrong for headdim=64.
463
+ if not (EVEN_M & EVEN_HEADDIM):
464
+ tl.debug_barrier()
465
+ lse_i = tl.load(LSE + offs_m_curr)
466
+ if BIAS_TYPE == 'none':
467
+ p = tl.exp(qk * softmax_scale - lse_i[:, None])
468
+ else:
469
+ p = tl.exp(qk - lse_i[:, None])
470
+ # compute dv
471
+ # [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call
472
+ # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs
473
+ # in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512,
474
+ # the output is correct.
475
+ if EVEN_M & EVEN_HEADDIM:
476
+ do = tl.load(do_ptrs)
477
+ else:
478
+ # [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask.
479
+ do = tl.load(do_ptrs,
480
+ mask=(offs_m_curr[:, None] < seqlen_q) &
481
+ (offs_d[None, :] < headdim),
482
+ other=0.0)
483
+ # if EVEN_M:
484
+ # if EVEN_HEADDIM:
485
+ # do = tl.load(do_ptrs)
486
+ # else:
487
+ # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
488
+ # else:
489
+ # if EVEN_HEADDIM:
490
+ # do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
491
+ # else:
492
+ # do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
493
+ # & (offs_d[None, :] < headdim), other=0.0)
494
+ dv += tl.dot(p.to(do.dtype), do, trans_a=True)
495
+ # compute dp = dot(v, do)
496
+ # There seems to be a race condition when headdim=48/96, and dq, dk are wrong.
497
+ # Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True
498
+ # Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False
499
+ if not (EVEN_M & EVEN_HEADDIM):
500
+ tl.debug_barrier()
501
+ dp = tl.dot(do, v, trans_b=True)
502
+ # There's a race condition for headdim=48
503
+ if not EVEN_HEADDIM:
504
+ tl.debug_barrier()
505
+ # compute ds = p * (dp - delta[:, None])
506
+ # Putting the subtraction after the dp matmul (instead of before) is slightly faster
507
+ Di = tl.load(D + offs_m_curr)
508
+ # Converting ds to q.dtype here reduces register pressure and makes it much faster
509
+ # for BLOCK_HEADDIM=128
510
+ ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
511
+ # compute dk = dot(ds.T, q)
512
+ dk += tl.dot(ds, q, trans_a=True)
513
+ # compute dq
514
+ if not ATOMIC_ADD:
515
+ if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
516
+ dq = tl.load(dq_ptrs, eviction_policy='evict_last')
517
+ dq += tl.dot(ds, k)
518
+ tl.store(dq_ptrs, dq, eviction_policy='evict_last')
519
+ else:
520
+ if EVEN_HEADDIM:
521
+ dq = tl.load(dq_ptrs,
522
+ mask=offs_m_curr[:, None] < seqlen_q,
523
+ other=0.0,
524
+ eviction_policy='evict_last')
525
+ dq += tl.dot(ds, k)
526
+ tl.store(dq_ptrs,
527
+ dq,
528
+ mask=offs_m_curr[:, None] < seqlen_q,
529
+ eviction_policy='evict_last')
530
+ else:
531
+ dq = tl.load(dq_ptrs,
532
+ mask=(offs_m_curr[:, None] < seqlen_q) &
533
+ (offs_d[None, :] < headdim),
534
+ other=0.0,
535
+ eviction_policy='evict_last')
536
+ dq += tl.dot(ds, k)
537
+ tl.store(dq_ptrs,
538
+ dq,
539
+ mask=(offs_m_curr[:, None] < seqlen_q) &
540
+ (offs_d[None, :] < headdim),
541
+ eviction_policy='evict_last')
542
+ else: # If we're parallelizing across the seqlen_k dimension
543
+ dq = tl.dot(ds, k)
544
+ if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
545
+ tl.atomic_add(dq_ptrs, dq)
546
+ else:
547
+ if EVEN_HEADDIM:
548
+ tl.atomic_add(dq_ptrs,
549
+ dq,
550
+ mask=offs_m_curr[:, None] < seqlen_q)
551
+ else:
552
+ tl.atomic_add(dq_ptrs,
553
+ dq,
554
+ mask=(offs_m_curr[:, None] < seqlen_q) &
555
+ (offs_d[None, :] < headdim))
556
+ # increment pointers
557
+ dq_ptrs += BLOCK_M * stride_dqm
558
+ q_ptrs += BLOCK_M * stride_qm
559
+ do_ptrs += BLOCK_M * stride_dom
560
+ if BIAS_TYPE == 'matrix':
561
+ b_ptrs += BLOCK_M * stride_bm
562
+ # write-back
563
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
564
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
565
+ # [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False,
566
+ # if we just call tl.store(dv_ptrs), there's a race condition
567
+ if EVEN_N & EVEN_M:
568
+ if EVEN_HEADDIM:
569
+ tl.store(dv_ptrs, dv)
570
+ tl.store(dk_ptrs, dk)
571
+ else:
572
+ tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
573
+ tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
574
+ else:
575
+ if EVEN_HEADDIM:
576
+ tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
577
+ tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
578
+ else:
579
+ tl.store(dv_ptrs,
580
+ dv,
581
+ mask=(offs_n[:, None] < seqlen_k) &
582
+ (offs_d[None, :] < headdim))
583
+ tl.store(dk_ptrs,
584
+ dk,
585
+ mask=(offs_n[:, None] < seqlen_k) &
586
+ (offs_d[None, :] < headdim))
587
+
588
+
589
+ def init_to_zero(name):
590
+ return lambda nargs: nargs[name].zero_()
591
+
592
+
593
+ @triton.autotune(
594
+ configs=[
595
+ triton.Config(
596
+ {
597
+ 'BLOCK_M': 128,
598
+ 'BLOCK_N': 128,
599
+ 'SEQUENCE_PARALLEL': False
600
+ },
601
+ num_warps=8,
602
+ num_stages=1,
603
+ pre_hook=init_to_zero('DQ')),
604
+ triton.Config(
605
+ {
606
+ 'BLOCK_M': 128,
607
+ 'BLOCK_N': 128,
608
+ 'SEQUENCE_PARALLEL': True
609
+ },
610
+ num_warps=8,
611
+ num_stages=1,
612
+ pre_hook=init_to_zero('DQ')),
613
+ # Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now
614
+ # # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4*
615
+ # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
616
+ # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
617
+ # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
618
+ # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
619
+ ],
620
+ key=[
621
+ 'CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL',
622
+ 'BLOCK_HEADDIM'
623
+ ],
624
+ )
625
+ @triton.heuristics({
626
+ 'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0,
627
+ 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0,
628
+ 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM'],
629
+ })
630
+ @triton.jit
631
+ def _bwd_kernel(
632
+ Q,
633
+ K,
634
+ V,
635
+ Bias,
636
+ DO,
637
+ DQ,
638
+ DK,
639
+ DV,
640
+ LSE,
641
+ D,
642
+ softmax_scale,
643
+ stride_qb,
644
+ stride_qh,
645
+ stride_qm,
646
+ stride_kb,
647
+ stride_kh,
648
+ stride_kn,
649
+ stride_vb,
650
+ stride_vh,
651
+ stride_vn,
652
+ stride_bb,
653
+ stride_bh,
654
+ stride_bm,
655
+ stride_dob,
656
+ stride_doh,
657
+ stride_dom,
658
+ stride_dqb,
659
+ stride_dqh,
660
+ stride_dqm,
661
+ stride_dkb,
662
+ stride_dkh,
663
+ stride_dkn,
664
+ stride_dvb,
665
+ stride_dvh,
666
+ stride_dvn,
667
+ nheads,
668
+ seqlen_q,
669
+ seqlen_k,
670
+ seqlen_q_rounded,
671
+ headdim,
672
+ CACHE_KEY_SEQLEN_Q,
673
+ CACHE_KEY_SEQLEN_K,
674
+ BIAS_TYPE: tl.constexpr,
675
+ IS_CAUSAL: tl.constexpr,
676
+ BLOCK_HEADDIM: tl.constexpr,
677
+ SEQUENCE_PARALLEL: tl.constexpr,
678
+ EVEN_M: tl.constexpr,
679
+ EVEN_N: tl.constexpr,
680
+ EVEN_HEADDIM: tl.constexpr,
681
+ BLOCK_M: tl.constexpr,
682
+ BLOCK_N: tl.constexpr,
683
+ ):
684
+ off_hb = tl.program_id(1)
685
+ off_b = off_hb // nheads
686
+ off_h = off_hb % nheads
687
+ # offset pointers for batch/head
688
+ Q += off_b * stride_qb + off_h * stride_qh
689
+ K += off_b * stride_kb + off_h * stride_kh
690
+ V += off_b * stride_vb + off_h * stride_vh
691
+ DO += off_b * stride_dob + off_h * stride_doh
692
+ DQ += off_b * stride_dqb + off_h * stride_dqh
693
+ DK += off_b * stride_dkb + off_h * stride_dkh
694
+ DV += off_b * stride_dvb + off_h * stride_dvh
695
+ if BIAS_TYPE != 'none':
696
+ Bias += off_b * stride_bb + off_h * stride_bh
697
+ # pointer to row-wise quantities in value-like data
698
+ D += off_hb * seqlen_q_rounded
699
+ LSE += off_hb * seqlen_q_rounded
700
+ if not SEQUENCE_PARALLEL:
701
+ num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
702
+ for start_n in range(0, num_block_n):
703
+ _bwd_kernel_one_col_block(start_n,
704
+ Q,
705
+ K,
706
+ V,
707
+ Bias,
708
+ DO,
709
+ DQ,
710
+ DK,
711
+ DV,
712
+ LSE,
713
+ D,
714
+ softmax_scale,
715
+ stride_qm,
716
+ stride_kn,
717
+ stride_vn,
718
+ stride_bm,
719
+ stride_dom,
720
+ stride_dqm,
721
+ stride_dkn,
722
+ stride_dvn,
723
+ seqlen_q,
724
+ seqlen_k,
725
+ headdim,
726
+ ATOMIC_ADD=False,
727
+ BIAS_TYPE=BIAS_TYPE,
728
+ IS_CAUSAL=IS_CAUSAL,
729
+ BLOCK_HEADDIM=BLOCK_HEADDIM,
730
+ EVEN_M=EVEN_M,
731
+ EVEN_N=EVEN_N,
732
+ EVEN_HEADDIM=EVEN_HEADDIM,
733
+ BLOCK_M=BLOCK_M,
734
+ BLOCK_N=BLOCK_N)
735
+ else:
736
+ start_n = tl.program_id(0)
737
+ _bwd_kernel_one_col_block(start_n,
738
+ Q,
739
+ K,
740
+ V,
741
+ Bias,
742
+ DO,
743
+ DQ,
744
+ DK,
745
+ DV,
746
+ LSE,
747
+ D,
748
+ softmax_scale,
749
+ stride_qm,
750
+ stride_kn,
751
+ stride_vn,
752
+ stride_bm,
753
+ stride_dom,
754
+ stride_dqm,
755
+ stride_dkn,
756
+ stride_dvn,
757
+ seqlen_q,
758
+ seqlen_k,
759
+ headdim,
760
+ ATOMIC_ADD=True,
761
+ BIAS_TYPE=BIAS_TYPE,
762
+ IS_CAUSAL=IS_CAUSAL,
763
+ BLOCK_HEADDIM=BLOCK_HEADDIM,
764
+ EVEN_M=EVEN_M,
765
+ EVEN_N=EVEN_N,
766
+ EVEN_HEADDIM=EVEN_HEADDIM,
767
+ BLOCK_M=BLOCK_M,
768
+ BLOCK_N=BLOCK_N)
769
+
770
+
771
+ def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
772
+ # shape constraints
773
+ batch, seqlen_q, nheads, d = q.shape
774
+ _, seqlen_k, _, _ = k.shape
775
+ assert k.shape == (batch, seqlen_k, nheads, d)
776
+ assert v.shape == (batch, seqlen_k, nheads, d)
777
+ assert d <= 128, 'FlashAttention only support head dimensions up to 128'
778
+ assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
779
+ assert q.dtype in [torch.float16,
780
+ torch.bfloat16], 'Only support fp16 and bf16'
781
+ assert q.is_cuda and k.is_cuda and v.is_cuda
782
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
783
+
784
+ has_bias = bias is not None
785
+ bias_type = 'none'
786
+ if has_bias:
787
+ assert bias.dtype in [q.dtype, torch.float]
788
+ assert bias.is_cuda
789
+ assert bias.dim() == 4
790
+ if bias.stride(-1) != 1:
791
+ bias = bias.contiguous()
792
+ if bias.shape[2:] == (1, seqlen_k):
793
+ bias_type = 'vector'
794
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
795
+ bias_type = 'matrix'
796
+ else:
797
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
798
+ ' or (seqlen_q, seqlen_k)')
799
+ if bias.shape[:2] == (1, nheads):
800
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
801
+ elif bias.shape[:2] == (batch, 1):
802
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
803
+ elif bias.shape[:2] == (1, 1):
804
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
805
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
806
+ assert bias.shape[:2] == (
807
+ batch, nheads
808
+ ), f'First 2 dimensions of bias must be broadcastible to (batch, nheads) = ({batch, nheads}). Bias has shape: {bias.shape}'
809
+ assert bias is not None # for type checking
810
+ bias_strides = (bias.stride(0), bias.stride(1),
811
+ bias.stride(2)) if has_bias else (0, 0, 0)
812
+
813
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
814
+ lse = torch.empty((batch, nheads, seqlen_q_rounded),
815
+ device=q.device,
816
+ dtype=torch.float32)
817
+ tmp = torch.empty((batch, nheads, seqlen_q_rounded),
818
+ device=q.device,
819
+ dtype=torch.float32)
820
+ o = torch.empty_like(q)
821
+
822
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
823
+ # BLOCK = 128
824
+ # num_warps = 4 if d <= 64 else 8
825
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
826
+ _fwd_kernel[grid]( # type: ignore
827
+ q,
828
+ k,
829
+ v,
830
+ bias,
831
+ o,
832
+ lse,
833
+ tmp,
834
+ softmax_scale,
835
+ q.stride(0),
836
+ q.stride(2),
837
+ q.stride(1),
838
+ k.stride(0),
839
+ k.stride(2),
840
+ k.stride(1),
841
+ v.stride(0),
842
+ v.stride(2),
843
+ v.stride(1),
844
+ *bias_strides,
845
+ o.stride(0),
846
+ o.stride(2),
847
+ o.stride(1),
848
+ nheads,
849
+ seqlen_q,
850
+ seqlen_k,
851
+ seqlen_q_rounded,
852
+ d,
853
+ seqlen_q // 32,
854
+ seqlen_k // 32, # key for triton cache (limit number of compilations)
855
+ # Can't use kwargs here because triton autotune expects key to be args, not kwargs
856
+ # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
857
+ bias_type,
858
+ causal,
859
+ BLOCK_HEADDIM,
860
+ # BLOCK_M=BLOCK, BLOCK_N=BLOCK,
861
+ # num_warps=num_warps,
862
+ # num_stages=1,
863
+ )
864
+ return o, lse, softmax_scale # softmax_scale could have been updated
865
+
866
+
867
+ def _flash_attn_backward(do,
868
+ q,
869
+ k,
870
+ v,
871
+ o,
872
+ lse,
873
+ dq,
874
+ dk,
875
+ dv,
876
+ bias=None,
877
+ causal=False,
878
+ softmax_scale=None):
879
+ # Make sure that the last dimension is contiguous
880
+ if do.stride(-1) != 1:
881
+ do = do.contiguous()
882
+ batch, seqlen_q, nheads, d = q.shape
883
+ _, seqlen_k, _, _ = k.shape
884
+ # assert d in {16, 32, 64, 128}
885
+ assert d <= 128
886
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
887
+ assert lse.shape == (batch, nheads, seqlen_q_rounded)
888
+ assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
889
+ assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
890
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
891
+ # dq_accum = torch.zeros_like(q, dtype=torch.float32)
892
+ dq_accum = torch.empty_like(q, dtype=torch.float32)
893
+ delta = torch.empty_like(lse)
894
+ # delta = torch.zeros_like(lse)
895
+
896
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
897
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
898
+ _bwd_preprocess_do_o_dot[grid]( # type: ignore
899
+ o,
900
+ do,
901
+ delta,
902
+ o.stride(0),
903
+ o.stride(2),
904
+ o.stride(1),
905
+ do.stride(0),
906
+ do.stride(2),
907
+ do.stride(1),
908
+ nheads,
909
+ seqlen_q,
910
+ seqlen_q_rounded,
911
+ d,
912
+ BLOCK_M=128,
913
+ BLOCK_HEADDIM=BLOCK_HEADDIM,
914
+ )
915
+
916
+ has_bias = bias is not None
917
+ bias_type = 'none'
918
+ if has_bias:
919
+ assert bias.dtype in [q.dtype, torch.float]
920
+ assert bias.is_cuda
921
+ assert bias.dim() == 4
922
+ assert bias.stride(-1) == 1
923
+ if bias.shape[2:] == (1, seqlen_k):
924
+ bias_type = 'vector'
925
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
926
+ bias_type = 'matrix'
927
+ else:
928
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
929
+ ' or (seqlen_q, seqlen_k)')
930
+ if bias.shape[:2] == (1, nheads):
931
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
932
+ elif bias.shape[:2] == (batch, 1):
933
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
934
+ elif bias.shape[:2] == (1, 1):
935
+ bias = repeat(bias, '1 h ... -> b h ...', b=batch)
936
+ bias = repeat(bias, 'b 1 ... -> b h ...', h=nheads)
937
+ assert bias.shape[:2] == (
938
+ batch, nheads
939
+ ), f'First 2 dimensions of bias must be broadcastible to (batch, nheads) = ({batch, nheads}). Bias has shape: {bias.shape}'
940
+ assert bias is not None # type checking
941
+ bias_strides = (bias.stride(0), bias.stride(1),
942
+ bias.stride(2)) if has_bias else (0, 0, 0)
943
+
944
+ # BLOCK_M = 128
945
+ # BLOCK_N = 64
946
+ # num_warps = 4
947
+ grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N'])
948
+ if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
949
+ _bwd_kernel[grid]( # type: ignore
950
+ q,
951
+ k,
952
+ v,
953
+ bias,
954
+ do,
955
+ dq_accum,
956
+ dk,
957
+ dv,
958
+ lse,
959
+ delta,
960
+ softmax_scale,
961
+ q.stride(0),
962
+ q.stride(2),
963
+ q.stride(1),
964
+ k.stride(0),
965
+ k.stride(2),
966
+ k.stride(1),
967
+ v.stride(0),
968
+ v.stride(2),
969
+ v.stride(1),
970
+ *bias_strides,
971
+ do.stride(0),
972
+ do.stride(2),
973
+ do.stride(1),
974
+ dq_accum.stride(0),
975
+ dq_accum.stride(2),
976
+ dq_accum.stride(1),
977
+ dk.stride(0),
978
+ dk.stride(2),
979
+ dk.stride(1),
980
+ dv.stride(0),
981
+ dv.stride(2),
982
+ dv.stride(1),
983
+ nheads,
984
+ seqlen_q,
985
+ seqlen_k,
986
+ seqlen_q_rounded,
987
+ d,
988
+ seqlen_q // 32,
989
+ seqlen_k // 32, # key for triton cache (limit number of compilations)
990
+ # Can't use kwargs here because triton autotune expects key to be args, not kwargs
991
+ # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
992
+ bias_type,
993
+ causal,
994
+ BLOCK_HEADDIM,
995
+ # SEQUENCE_PARALLEL=False,
996
+ # BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N,
997
+ # num_warps=num_warps,
998
+ # num_stages=1,
999
+ )
1000
+ dq.copy_(dq_accum)
1001
+
1002
+
1003
+ class _FlashAttnQKVPackedFunc(torch.autograd.Function):
1004
+
1005
+ @staticmethod
1006
+ def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
1007
+ """Forward pass for packed FlashAttention.
1008
+
1009
+ Args:
1010
+ ctx: autograd context
1011
+ qkv: (batch, seqlen, 3, nheads, headdim)
1012
+ bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
1013
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
1014
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
1015
+ causal (bool): whether to incorporate causal attention masking
1016
+ softmax_scale (float, optional): scale factor for softmax
1017
+ """
1018
+ # Make sure that the last dimension is contiguous
1019
+ if qkv.stride(-1) != 1:
1020
+ qkv = qkv.contiguous()
1021
+ o, lse, ctx.softmax_scale = _flash_attn_forward(
1022
+ qkv[:, :, 0],
1023
+ qkv[:, :, 1],
1024
+ qkv[:, :, 2],
1025
+ bias=bias,
1026
+ causal=causal,
1027
+ softmax_scale=softmax_scale)
1028
+ ctx.save_for_backward(qkv, o, lse, bias)
1029
+ ctx.causal = causal
1030
+ return o
1031
+
1032
+ @staticmethod
1033
+ def backward(ctx, do):
1034
+ qkv, o, lse, bias = ctx.saved_tensors
1035
+ assert not ctx.needs_input_grad[
1036
+ 1], 'FlashAttention does not support bias gradient yet'
1037
+ # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
1038
+ # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
1039
+ with torch.inference_mode():
1040
+ dqkv = torch.empty_like(qkv)
1041
+ _flash_attn_backward(do,
1042
+ qkv[:, :, 0],
1043
+ qkv[:, :, 1],
1044
+ qkv[:, :, 2],
1045
+ o,
1046
+ lse,
1047
+ dqkv[:, :, 0],
1048
+ dqkv[:, :, 1],
1049
+ dqkv[:, :, 2],
1050
+ bias=bias,
1051
+ causal=ctx.causal,
1052
+ softmax_scale=ctx.softmax_scale)
1053
+ return dqkv, None, None, None
1054
+
1055
+
1056
+ flash_attn_qkvpacked_func = _FlashAttnQKVPackedFunc.apply
1057
+
1058
+
1059
+ class _FlashAttnFunc(torch.autograd.Function):
1060
+
1061
+ @staticmethod
1062
+ def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
1063
+ """Forward pass for FlashAttention.
1064
+
1065
+ Args:
1066
+ ctx: autograd context
1067
+ q: (batch_size, seqlen_q, nheads, headdim)
1068
+ k: (batch_size, seqlen_k, nheads, headdim)
1069
+ v: (batch_size, seqlen_k, nheads, headdim)
1070
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
1071
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
1072
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
1073
+ causal (bool): whether to incorporate causal attention masking
1074
+ softmax_scale (float, optional): scale factor for softmax
1075
+ """
1076
+ # Make sure that the last dimension is contiguous
1077
+ q, k, v = [
1078
+ x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]
1079
+ ]
1080
+ o, lse, ctx.softmax_scale = _flash_attn_forward(
1081
+ q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
1082
+ ctx.save_for_backward(q, k, v, o, lse, bias)
1083
+ ctx.causal = causal
1084
+ return o
1085
+
1086
+ @staticmethod
1087
+ def backward(ctx, do):
1088
+ q, k, v, o, lse, bias = ctx.saved_tensors
1089
+ assert not ctx.needs_input_grad[
1090
+ 3], 'FlashAttention does not support bias gradient yet'
1091
+ # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
1092
+ # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
1093
+ with torch.inference_mode():
1094
+ dq = torch.empty_like(q)
1095
+ dk = torch.empty_like(k)
1096
+ dv = torch.empty_like(v)
1097
+ _flash_attn_backward(do,
1098
+ q,
1099
+ k,
1100
+ v,
1101
+ o,
1102
+ lse,
1103
+ dq,
1104
+ dk,
1105
+ dv,
1106
+ bias=bias,
1107
+ causal=ctx.causal,
1108
+ softmax_scale=ctx.softmax_scale)
1109
+ return dq, dk, dv, None, None, None
1110
+
1111
+
1112
+ flash_attn_func = _FlashAttnFunc.apply
generation_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "pad_token_id": 0,
4
+ "transformers_version": "4.28.0"
5
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ff39ec77a484dd01070a41bfd6e95cdd7247bec80fe357ab43a4be33687aeba
3
+ size 468354983
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"tokenizer_class": "PreTrainedTokenizerFast", "unk_token": "[UNK]", "cls_token": "[CLS]", "sep_token": "[SEP]", "pad_token": "[PAD]", "mask_token": "[MASK]"}