555
#58
by
sywangyi
- opened
- LICENSE +0 -202
- README.md +6 -20
- adapt_tokenizer.py +5 -4
- attention.py +110 -198
- blocks.py +20 -34
- configuration_mpt.py +18 -83
- custom_embedding.py +3 -1
- fc.py +0 -7
- ffn.py +0 -97
- hf_prefixlm_converter.py +241 -6
- meta_init_context.py +12 -17
- modeling_mpt.py +92 -303
- norm.py +10 -11
- param_init_fns.py +51 -49
- warnings.py +0 -22
LICENSE
DELETED
@@ -1,202 +0,0 @@
|
|
1 |
-
|
2 |
-
Apache License
|
3 |
-
Version 2.0, January 2004
|
4 |
-
http://www.apache.org/licenses/
|
5 |
-
|
6 |
-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
7 |
-
|
8 |
-
1. Definitions.
|
9 |
-
|
10 |
-
"License" shall mean the terms and conditions for use, reproduction,
|
11 |
-
and distribution as defined by Sections 1 through 9 of this document.
|
12 |
-
|
13 |
-
"Licensor" shall mean the copyright owner or entity authorized by
|
14 |
-
the copyright owner that is granting the License.
|
15 |
-
|
16 |
-
"Legal Entity" shall mean the union of the acting entity and all
|
17 |
-
other entities that control, are controlled by, or are under common
|
18 |
-
control with that entity. For the purposes of this definition,
|
19 |
-
"control" means (i) the power, direct or indirect, to cause the
|
20 |
-
direction or management of such entity, whether by contract or
|
21 |
-
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
22 |
-
outstanding shares, or (iii) beneficial ownership of such entity.
|
23 |
-
|
24 |
-
"You" (or "Your") shall mean an individual or Legal Entity
|
25 |
-
exercising permissions granted by this License.
|
26 |
-
|
27 |
-
"Source" form shall mean the preferred form for making modifications,
|
28 |
-
including but not limited to software source code, documentation
|
29 |
-
source, and configuration files.
|
30 |
-
|
31 |
-
"Object" form shall mean any form resulting from mechanical
|
32 |
-
transformation or translation of a Source form, including but
|
33 |
-
not limited to compiled object code, generated documentation,
|
34 |
-
and conversions to other media types.
|
35 |
-
|
36 |
-
"Work" shall mean the work of authorship, whether in Source or
|
37 |
-
Object form, made available under the License, as indicated by a
|
38 |
-
copyright notice that is included in or attached to the work
|
39 |
-
(an example is provided in the Appendix below).
|
40 |
-
|
41 |
-
"Derivative Works" shall mean any work, whether in Source or Object
|
42 |
-
form, that is based on (or derived from) the Work and for which the
|
43 |
-
editorial revisions, annotations, elaborations, or other modifications
|
44 |
-
represent, as a whole, an original work of authorship. For the purposes
|
45 |
-
of this License, Derivative Works shall not include works that remain
|
46 |
-
separable from, or merely link (or bind by name) to the interfaces of,
|
47 |
-
the Work and Derivative Works thereof.
|
48 |
-
|
49 |
-
"Contribution" shall mean any work of authorship, including
|
50 |
-
the original version of the Work and any modifications or additions
|
51 |
-
to that Work or Derivative Works thereof, that is intentionally
|
52 |
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
53 |
-
or by an individual or Legal Entity authorized to submit on behalf of
|
54 |
-
the copyright owner. For the purposes of this definition, "submitted"
|
55 |
-
means any form of electronic, verbal, or written communication sent
|
56 |
-
to the Licensor or its representatives, including but not limited to
|
57 |
-
communication on electronic mailing lists, source code control systems,
|
58 |
-
and issue tracking systems that are managed by, or on behalf of, the
|
59 |
-
Licensor for the purpose of discussing and improving the Work, but
|
60 |
-
excluding communication that is conspicuously marked or otherwise
|
61 |
-
designated in writing by the copyright owner as "Not a Contribution."
|
62 |
-
|
63 |
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
64 |
-
on behalf of whom a Contribution has been received by Licensor and
|
65 |
-
subsequently incorporated within the Work.
|
66 |
-
|
67 |
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
68 |
-
this License, each Contributor hereby grants to You a perpetual,
|
69 |
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
70 |
-
copyright license to reproduce, prepare Derivative Works of,
|
71 |
-
publicly display, publicly perform, sublicense, and distribute the
|
72 |
-
Work and such Derivative Works in Source or Object form.
|
73 |
-
|
74 |
-
3. Grant of Patent License. Subject to the terms and conditions of
|
75 |
-
this License, each Contributor hereby grants to You a perpetual,
|
76 |
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
77 |
-
(except as stated in this section) patent license to make, have made,
|
78 |
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
79 |
-
where such license applies only to those patent claims licensable
|
80 |
-
by such Contributor that are necessarily infringed by their
|
81 |
-
Contribution(s) alone or by combination of their Contribution(s)
|
82 |
-
with the Work to which such Contribution(s) was submitted. If You
|
83 |
-
institute patent litigation against any entity (including a
|
84 |
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
85 |
-
or a Contribution incorporated within the Work constitutes direct
|
86 |
-
or contributory patent infringement, then any patent licenses
|
87 |
-
granted to You under this License for that Work shall terminate
|
88 |
-
as of the date such litigation is filed.
|
89 |
-
|
90 |
-
4. Redistribution. You may reproduce and distribute copies of the
|
91 |
-
Work or Derivative Works thereof in any medium, with or without
|
92 |
-
modifications, and in Source or Object form, provided that You
|
93 |
-
meet the following conditions:
|
94 |
-
|
95 |
-
(a) You must give any other recipients of the Work or
|
96 |
-
Derivative Works a copy of this License; and
|
97 |
-
|
98 |
-
(b) You must cause any modified files to carry prominent notices
|
99 |
-
stating that You changed the files; and
|
100 |
-
|
101 |
-
(c) You must retain, in the Source form of any Derivative Works
|
102 |
-
that You distribute, all copyright, patent, trademark, and
|
103 |
-
attribution notices from the Source form of the Work,
|
104 |
-
excluding those notices that do not pertain to any part of
|
105 |
-
the Derivative Works; and
|
106 |
-
|
107 |
-
(d) If the Work includes a "NOTICE" text file as part of its
|
108 |
-
distribution, then any Derivative Works that You distribute must
|
109 |
-
include a readable copy of the attribution notices contained
|
110 |
-
within such NOTICE file, excluding those notices that do not
|
111 |
-
pertain to any part of the Derivative Works, in at least one
|
112 |
-
of the following places: within a NOTICE text file distributed
|
113 |
-
as part of the Derivative Works; within the Source form or
|
114 |
-
documentation, if provided along with the Derivative Works; or,
|
115 |
-
within a display generated by the Derivative Works, if and
|
116 |
-
wherever such third-party notices normally appear. The contents
|
117 |
-
of the NOTICE file are for informational purposes only and
|
118 |
-
do not modify the License. You may add Your own attribution
|
119 |
-
notices within Derivative Works that You distribute, alongside
|
120 |
-
or as an addendum to the NOTICE text from the Work, provided
|
121 |
-
that such additional attribution notices cannot be construed
|
122 |
-
as modifying the License.
|
123 |
-
|
124 |
-
You may add Your own copyright statement to Your modifications and
|
125 |
-
may provide additional or different license terms and conditions
|
126 |
-
for use, reproduction, or distribution of Your modifications, or
|
127 |
-
for any such Derivative Works as a whole, provided Your use,
|
128 |
-
reproduction, and distribution of the Work otherwise complies with
|
129 |
-
the conditions stated in this License.
|
130 |
-
|
131 |
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
132 |
-
any Contribution intentionally submitted for inclusion in the Work
|
133 |
-
by You to the Licensor shall be under the terms and conditions of
|
134 |
-
this License, without any additional terms or conditions.
|
135 |
-
Notwithstanding the above, nothing herein shall supersede or modify
|
136 |
-
the terms of any separate license agreement you may have executed
|
137 |
-
with Licensor regarding such Contributions.
|
138 |
-
|
139 |
-
6. Trademarks. This License does not grant permission to use the trade
|
140 |
-
names, trademarks, service marks, or product names of the Licensor,
|
141 |
-
except as required for reasonable and customary use in describing the
|
142 |
-
origin of the Work and reproducing the content of the NOTICE file.
|
143 |
-
|
144 |
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
145 |
-
agreed to in writing, Licensor provides the Work (and each
|
146 |
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
147 |
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
148 |
-
implied, including, without limitation, any warranties or conditions
|
149 |
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
150 |
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
151 |
-
appropriateness of using or redistributing the Work and assume any
|
152 |
-
risks associated with Your exercise of permissions under this License.
|
153 |
-
|
154 |
-
8. Limitation of Liability. In no event and under no legal theory,
|
155 |
-
whether in tort (including negligence), contract, or otherwise,
|
156 |
-
unless required by applicable law (such as deliberate and grossly
|
157 |
-
negligent acts) or agreed to in writing, shall any Contributor be
|
158 |
-
liable to You for damages, including any direct, indirect, special,
|
159 |
-
incidental, or consequential damages of any character arising as a
|
160 |
-
result of this License or out of the use or inability to use the
|
161 |
-
Work (including but not limited to damages for loss of goodwill,
|
162 |
-
work stoppage, computer failure or malfunction, or any and all
|
163 |
-
other commercial damages or losses), even if such Contributor
|
164 |
-
has been advised of the possibility of such damages.
|
165 |
-
|
166 |
-
9. Accepting Warranty or Additional Liability. While redistributing
|
167 |
-
the Work or Derivative Works thereof, You may choose to offer,
|
168 |
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
169 |
-
or other liability obligations and/or rights consistent with this
|
170 |
-
License. However, in accepting such obligations, You may act only
|
171 |
-
on Your own behalf and on Your sole responsibility, not on behalf
|
172 |
-
of any other Contributor, and only if You agree to indemnify,
|
173 |
-
defend, and hold each Contributor harmless for any liability
|
174 |
-
incurred by, or claims asserted against, such Contributor by reason
|
175 |
-
of your accepting any such warranty or additional liability.
|
176 |
-
|
177 |
-
END OF TERMS AND CONDITIONS
|
178 |
-
|
179 |
-
APPENDIX: How to apply the Apache License to your work.
|
180 |
-
|
181 |
-
To apply the Apache License to your work, attach the following
|
182 |
-
boilerplate notice, with the fields enclosed by brackets "[]"
|
183 |
-
replaced with your own identifying information. (Don't include
|
184 |
-
the brackets!) The text should be enclosed in the appropriate
|
185 |
-
comment syntax for the file format. We also recommend that a
|
186 |
-
file or class name and description of purpose be included on the
|
187 |
-
same "printed page" as the copyright notice for easier
|
188 |
-
identification within third-party archives.
|
189 |
-
|
190 |
-
Copyright 2024 Databricks
|
191 |
-
|
192 |
-
Licensed under the Apache License, Version 2.0 (the "License");
|
193 |
-
you may not use this file except in compliance with the License.
|
194 |
-
You may obtain a copy of the License at
|
195 |
-
|
196 |
-
http://www.apache.org/licenses/LICENSE-2.0
|
197 |
-
|
198 |
-
Unless required by applicable law or agreed to in writing, software
|
199 |
-
distributed under the License is distributed on an "AS IS" BASIS,
|
200 |
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
201 |
-
See the License for the specific language governing permissions and
|
202 |
-
limitations under the License.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
@@ -50,12 +50,14 @@ We demonstrate generations as long as 80k tokens on a single A100-80GB GPU in ou
|
|
50 |
|
51 |
* [MPT-7B-Instruct](https://huggingface.co/mosaicml/mpt-7b-instruct): a model for short-form instruction following.
|
52 |
Built by finetuning MPT-7B on a [dataset](https://huggingface.co/datasets/mosaicml/dolly_hhrlhf) we also release, derived from the [Databricks Dolly-15k](https://huggingface.co/datasets/databricks/databricks-dolly-15k) and the [Anthropic Helpful and Harmless (HH-RLHF)](https://huggingface.co/datasets/Anthropic/hh-rlhf) datasets.
|
53 |
-
* License:
|
|
|
54 |
|
55 |
* [MPT-7B-Chat](https://huggingface.co/mosaicml/mpt-7b-chat): a chatbot-like model for dialogue generation.
|
56 |
Built by finetuning MPT-7B on the [ShareGPT-Vicuna](https://huggingface.co/datasets/jeffwan/sharegpt_vicuna), [HC3](https://huggingface.co/datasets/Hello-SimpleAI/HC3),
|
57 |
[Alpaca](https://huggingface.co/datasets/tatsu-lab/alpaca), [HH-RLHF](https://huggingface.co/datasets/Anthropic/hh-rlhf), and [Evol-Instruct](https://huggingface.co/datasets/victor123/evol_instruct_70k) datasets.
|
58 |
* License: _CC-By-NC-SA-4.0_
|
|
|
59 |
|
60 |
## Model Date
|
61 |
|
@@ -130,22 +132,6 @@ from transformers import AutoTokenizer
|
|
130 |
tokenizer = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b')
|
131 |
```
|
132 |
|
133 |
-
The model can then be used, for example, within a text-generation pipeline.
|
134 |
-
Note: when running Torch modules in lower precision, it is best practice to use the [torch.autocast context manager](https://pytorch.org/docs/stable/amp.html).
|
135 |
-
|
136 |
-
```python
|
137 |
-
from transformers import pipeline
|
138 |
-
|
139 |
-
pipe = pipeline('text-generation', model=model, tokenizer=tokenizer, device='cuda:0')
|
140 |
-
|
141 |
-
with torch.autocast('cuda', dtype=torch.bfloat16):
|
142 |
-
print(
|
143 |
-
pipe('Here is a recipe for vegan banana bread:\n',
|
144 |
-
max_new_tokens=100,
|
145 |
-
do_sample=True,
|
146 |
-
use_cache=True))
|
147 |
-
```
|
148 |
-
|
149 |
## Model Description
|
150 |
|
151 |
The architecture is a modification of a standard decoder-only transformer.
|
@@ -237,10 +223,10 @@ Please cite this model using the following format:
|
|
237 |
@online{MosaicML2023Introducing,
|
238 |
author = {MosaicML NLP Team},
|
239 |
title = {Introducing MPT-7B: A New Standard for Open-Source,
|
240 |
-
|
241 |
year = {2023},
|
242 |
url = {www.mosaicml.com/blog/mpt-7b},
|
243 |
-
note = {Accessed: 2023-
|
244 |
-
urldate = {2023-
|
245 |
}
|
246 |
```
|
|
|
50 |
|
51 |
* [MPT-7B-Instruct](https://huggingface.co/mosaicml/mpt-7b-instruct): a model for short-form instruction following.
|
52 |
Built by finetuning MPT-7B on a [dataset](https://huggingface.co/datasets/mosaicml/dolly_hhrlhf) we also release, derived from the [Databricks Dolly-15k](https://huggingface.co/datasets/databricks/databricks-dolly-15k) and the [Anthropic Helpful and Harmless (HH-RLHF)](https://huggingface.co/datasets/Anthropic/hh-rlhf) datasets.
|
53 |
+
* License: _CC-By-SA-3.0_
|
54 |
+
* [Demo on Hugging Face Spaces](https://huggingface.co/spaces/mosaicml/mpt-7b-instruct)
|
55 |
|
56 |
* [MPT-7B-Chat](https://huggingface.co/mosaicml/mpt-7b-chat): a chatbot-like model for dialogue generation.
|
57 |
Built by finetuning MPT-7B on the [ShareGPT-Vicuna](https://huggingface.co/datasets/jeffwan/sharegpt_vicuna), [HC3](https://huggingface.co/datasets/Hello-SimpleAI/HC3),
|
58 |
[Alpaca](https://huggingface.co/datasets/tatsu-lab/alpaca), [HH-RLHF](https://huggingface.co/datasets/Anthropic/hh-rlhf), and [Evol-Instruct](https://huggingface.co/datasets/victor123/evol_instruct_70k) datasets.
|
59 |
* License: _CC-By-NC-SA-4.0_
|
60 |
+
* [Demo on Hugging Face Spaces](https://huggingface.co/spaces/mosaicml/mpt-7b-chat)
|
61 |
|
62 |
## Model Date
|
63 |
|
|
|
132 |
tokenizer = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b')
|
133 |
```
|
134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
## Model Description
|
136 |
|
137 |
The architecture is a modification of a standard decoder-only transformer.
|
|
|
223 |
@online{MosaicML2023Introducing,
|
224 |
author = {MosaicML NLP Team},
|
225 |
title = {Introducing MPT-7B: A New Standard for Open-Source,
|
226 |
+
ly Usable LLMs},
|
227 |
year = {2023},
|
228 |
url = {www.mosaicml.com/blog/mpt-7b},
|
229 |
+
note = {Accessed: 2023-03-28}, % change this date
|
230 |
+
urldate = {2023-03-28} % change this date
|
231 |
}
|
232 |
```
|
adapt_tokenizer.py
CHANGED
@@ -1,8 +1,9 @@
|
|
1 |
-
from typing import
|
2 |
-
from transformers import AutoTokenizer,
|
|
|
3 |
NUM_SENTINEL_TOKENS: int = 100
|
4 |
|
5 |
-
def adapt_tokenizer_for_denoising(tokenizer:
|
6 |
"""Adds sentinel tokens and padding token (if missing).
|
7 |
|
8 |
Expands the tokenizer vocabulary to include sentinel tokens
|
@@ -33,7 +34,7 @@ class AutoTokenizerForMOD(AutoTokenizer):
|
|
33 |
"""
|
34 |
|
35 |
@classmethod
|
36 |
-
def from_pretrained(cls, *args
|
37 |
"""See `AutoTokenizer.from_pretrained` docstring."""
|
38 |
tokenizer = super().from_pretrained(*args, **kwargs)
|
39 |
adapt_tokenizer_for_denoising(tokenizer)
|
|
|
1 |
+
from typing import Union
|
2 |
+
from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
|
3 |
+
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
4 |
NUM_SENTINEL_TOKENS: int = 100
|
5 |
|
6 |
+
def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
|
7 |
"""Adds sentinel tokens and padding token (if missing).
|
8 |
|
9 |
Expands the tokenizer vocabulary to include sentinel tokens
|
|
|
34 |
"""
|
35 |
|
36 |
@classmethod
|
37 |
+
def from_pretrained(cls, *args, **kwargs):
|
38 |
"""See `AutoTokenizer.from_pretrained` docstring."""
|
39 |
tokenizer = super().from_pretrained(*args, **kwargs)
|
40 |
adapt_tokenizer_for_denoising(tokenizer)
|
attention.py
CHANGED
@@ -1,42 +1,15 @@
|
|
1 |
"""Attention layers."""
|
2 |
import math
|
3 |
import warnings
|
4 |
-
from typing import
|
5 |
import torch
|
6 |
import torch.nn as nn
|
7 |
-
import transformers
|
8 |
from einops import rearrange
|
9 |
from packaging import version
|
10 |
from torch import nn
|
11 |
-
from .
|
12 |
-
from .norm import NORM_CLASS_REGISTRY
|
13 |
|
14 |
-
def
|
15 |
-
assert version.parse(v2_version) >= version.parse('2.0.0')
|
16 |
-
try:
|
17 |
-
import flash_attn as flash_attn
|
18 |
-
except:
|
19 |
-
return False
|
20 |
-
return version.parse(flash_attn.__version__) >= version.parse(v2_version)
|
21 |
-
|
22 |
-
def is_flash_v1_installed():
|
23 |
-
try:
|
24 |
-
import flash_attn as flash_attn
|
25 |
-
except:
|
26 |
-
return False
|
27 |
-
return version.parse(flash_attn.__version__) < version.parse('2.0.0')
|
28 |
-
|
29 |
-
def is_transformers_version_gte(hf_version: str) -> bool:
|
30 |
-
return version.parse(transformers.__version__) >= version.parse(hf_version)
|
31 |
-
|
32 |
-
def check_alibi_support(attention_impl: str) -> bool:
|
33 |
-
return attention_impl != 'flash' or is_flash_v2_installed(v2_version='v2.4.2')
|
34 |
-
if is_flash_v1_installed():
|
35 |
-
import transformers
|
36 |
-
transformers.utils.is_flash_attn_available = lambda : False
|
37 |
-
from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
|
38 |
-
|
39 |
-
def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool) -> bool:
|
40 |
if original_is_causal and num_query_tokens != num_key_tokens:
|
41 |
if num_query_tokens != 1:
|
42 |
raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
|
@@ -44,21 +17,9 @@ def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_cau
|
|
44 |
return False
|
45 |
return original_is_causal
|
46 |
|
47 |
-
def
|
48 |
-
"""Perform repeat of kv heads along a particular dimension.
|
49 |
-
|
50 |
-
hidden.shape expected to be: (batch size, seq len, kv_n_heads, head_dim)
|
51 |
-
n_rep: amount of repetitions of kv_n_heads
|
52 |
-
Unlike torch.repeat_interleave, this function avoids allocating new memory.
|
53 |
-
"""
|
54 |
-
if n_rep == 1:
|
55 |
-
return hidden
|
56 |
-
(b, s, kv_n_heads, d) = hidden.shape
|
57 |
-
hidden = hidden[:, :, :, None, :].expand(b, s, kv_n_heads, n_rep, d)
|
58 |
-
return hidden.reshape(b, s, kv_n_heads * n_rep, d)
|
59 |
-
|
60 |
-
def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, n_heads: int, kv_n_heads: int, past_key_value: Optional[tuple[torch.Tensor, torch.Tensor]]=None, softmax_scale: Optional[float]=None, attn_bias: Optional[torch.Tensor]=None, key_padding_mask: Optional[torch.Tensor]=None, is_causal: bool=False, dropout_p: float=0.0, training: bool=False, needs_weights: bool=False) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor, torch.Tensor]]]:
|
61 |
q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
|
|
|
62 |
k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
|
63 |
v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
|
64 |
if past_key_value is not None:
|
@@ -68,9 +29,6 @@ def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tenso
|
|
68 |
past_key_value = (k, v)
|
69 |
(b, _, s_q, d) = q.shape
|
70 |
s_k = k.size(-1)
|
71 |
-
if kv_n_heads > 1 and kv_n_heads < n_heads:
|
72 |
-
k = repeat_kv_for_gqa(k.transpose(1, 2), n_heads // kv_n_heads).transpose(1, 2)
|
73 |
-
v = repeat_kv_for_gqa(v.transpose(1, 2), n_heads // kv_n_heads).transpose(1, 2)
|
74 |
if softmax_scale is None:
|
75 |
softmax_scale = 1 / math.sqrt(d)
|
76 |
attn_weight = q.matmul(k) * softmax_scale
|
@@ -84,11 +42,11 @@ def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tenso
|
|
84 |
min_val = torch.finfo(q.dtype).min
|
85 |
if key_padding_mask is not None:
|
86 |
if attn_bias is not None:
|
87 |
-
warnings.warn('
|
88 |
attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
|
89 |
if is_causal and (not q.size(2) == 1):
|
90 |
s = max(s_q, s_k)
|
91 |
-
causal_mask = attn_weight.new_ones(s, s, dtype=torch.
|
92 |
causal_mask = causal_mask.tril()
|
93 |
causal_mask = causal_mask.to(torch.bool)
|
94 |
causal_mask = ~causal_mask
|
@@ -97,79 +55,56 @@ def scaled_multihead_dot_product_attention(query: torch.Tensor, key: torch.Tenso
|
|
97 |
attn_weight = torch.softmax(attn_weight, dim=-1)
|
98 |
if dropout_p:
|
99 |
attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
|
100 |
-
out = attn_weight.
|
101 |
out = rearrange(out, 'b h s d -> b s (h d)')
|
102 |
if needs_weights:
|
103 |
return (out, attn_weight, past_key_value)
|
104 |
return (out, None, past_key_value)
|
105 |
|
106 |
-
def check_valid_inputs(*tensors
|
107 |
-
if valid_dtypes is None:
|
108 |
-
valid_dtypes = [torch.float16, torch.bfloat16]
|
109 |
for tensor in tensors:
|
110 |
if tensor.dtype not in valid_dtypes:
|
111 |
raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
|
112 |
if not tensor.is_cuda:
|
113 |
raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
|
114 |
|
115 |
-
def flash_attn_fn(query
|
116 |
-
if key_padding_mask is not None:
|
117 |
-
raise ValueError('key_padding_mask should be None for flash attn.')
|
118 |
-
del key_padding_mask
|
119 |
-
if flash_attn_padding_info is None:
|
120 |
-
raise ValueError('flash_attn_padding_info is required for flash attn.')
|
121 |
try:
|
122 |
from flash_attn import bert_padding, flash_attn_interface
|
123 |
except:
|
124 |
-
raise RuntimeError('Please install flash-attn==1.0.
|
125 |
check_valid_inputs(query, key, value)
|
126 |
if past_key_value is not None:
|
127 |
if len(past_key_value) != 0:
|
128 |
key = torch.cat([past_key_value[0], key], dim=1)
|
129 |
value = torch.cat([past_key_value[1], value], dim=1)
|
130 |
past_key_value = (key, value)
|
|
|
|
|
|
|
|
|
131 |
if attn_bias is not None:
|
132 |
raise NotImplementedError(f'attn_bias not implemented for flash attn.')
|
133 |
(batch_size, seqlen) = query.shape[:2]
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
cu_seqlens_q =
|
138 |
-
cu_seqlens_k = flash_attn_padding_info['cu_seqlens_k']
|
139 |
-
max_seqlen_q = flash_attn_padding_info['max_seqlen_q']
|
140 |
-
max_seqlen_k = flash_attn_padding_info['max_seqlen_k']
|
141 |
-
query_unpad = bert_padding.index_first_axis(rearrange(query, 'b s ... -> (b s) ...'), indices_q)
|
142 |
query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
|
143 |
-
key_unpad = bert_padding.
|
144 |
-
key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=
|
145 |
-
value_unpad = bert_padding.
|
146 |
-
value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=
|
147 |
-
if
|
148 |
-
|
149 |
-
|
150 |
-
if kv_n_heads == 1:
|
151 |
-
key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
|
152 |
-
value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
|
153 |
-
elif kv_n_heads < n_heads:
|
154 |
-
key_unpad = repeat_kv_for_gqa(key_unpad.view(1, key_unpad.size(0), kv_n_heads, -1), n_heads // kv_n_heads).view(key_unpad.size(0), n_heads, -1)
|
155 |
-
value_unpad = repeat_kv_for_gqa(value_unpad.view(1, value_unpad.size(0), kv_n_heads, -1), n_heads // kv_n_heads).view(value_unpad.size(0), n_heads, -1)
|
156 |
dropout_p = dropout_p if training else 0.0
|
157 |
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
158 |
-
|
159 |
-
output_unpad = flash_attn_interface.flash_attn_unpadded_func(q=query_unpad, k=key_unpad, v=value_unpad, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, dropout_p=dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
|
160 |
-
elif is_flash_v2_installed():
|
161 |
-
alibi_kwargs = {}
|
162 |
-
if check_alibi_support('flash'):
|
163 |
-
alibi_kwargs = {'alibi_slopes': alibi_slopes}
|
164 |
-
elif alibi_slopes is not None:
|
165 |
-
raise ValueError('alibi_slopes is only supported for flash-attn>=2.4.2')
|
166 |
-
output_unpad = flash_attn_interface.flash_attn_varlen_func(q=query_unpad, k=key_unpad, v=value_unpad, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_q, max_seqlen_k=max_seqlen_k, dropout_p=dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights, window_size=(sliding_window_size, sliding_window_size), **alibi_kwargs)
|
167 |
-
else:
|
168 |
-
raise RuntimeError('flash-attn==1.0.9 or flash-attn==2.4.2 is required.')
|
169 |
output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
|
170 |
return (output, None, past_key_value)
|
171 |
|
172 |
-
def triton_flash_attn_fn(query
|
173 |
try:
|
174 |
from .flash_attn_triton import flash_attn_func
|
175 |
except:
|
@@ -181,7 +116,7 @@ def triton_flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Te
|
|
181 |
except:
|
182 |
_installed = False
|
183 |
if not _installed:
|
184 |
-
raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU
|
185 |
check_valid_inputs(query, key, value)
|
186 |
if past_key_value is not None:
|
187 |
if len(past_key_value) != 0:
|
@@ -194,7 +129,6 @@ def triton_flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Te
|
|
194 |
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
195 |
if dropout_p:
|
196 |
raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
|
197 |
-
dropout_p = dropout_p if training else 0.0
|
198 |
if needs_weights:
|
199 |
raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
|
200 |
if key_padding_mask is not None:
|
@@ -204,144 +138,124 @@ def triton_flash_attn_fn(query: torch.Tensor, key: torch.Tensor, value: torch.Te
|
|
204 |
attn_bias = query.new_zeros(b_size, 1, 1, s_k)
|
205 |
attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
|
206 |
query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
|
207 |
-
key = rearrange(key, 'b s (h d) -> b s h d', h=
|
208 |
-
value = rearrange(value, 'b s (h d) -> b s h d', h=
|
209 |
-
if
|
210 |
-
key = key.
|
211 |
-
value = value.
|
212 |
-
elif kv_n_heads < n_heads:
|
213 |
-
key = repeat_kv_for_gqa(key, n_heads // kv_n_heads)
|
214 |
-
value = repeat_kv_for_gqa(value, n_heads // kv_n_heads)
|
215 |
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
216 |
attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
|
217 |
output = attn_output.view(*attn_output.shape[:2], -1)
|
218 |
return (output, None, past_key_value)
|
219 |
|
220 |
-
class
|
221 |
-
"""
|
222 |
-
|
223 |
-
and Multi-query attention (MQA).
|
224 |
|
225 |
-
|
226 |
-
|
227 |
-
implementation enables user to also use additive bias.
|
228 |
"""
|
229 |
|
230 |
-
def __init__(self, d_model: int, n_heads: int,
|
231 |
super().__init__()
|
232 |
self.attn_impl = attn_impl
|
233 |
self.clip_qkv = clip_qkv
|
234 |
self.qk_ln = qk_ln
|
235 |
-
self.qk_gn = qk_gn
|
236 |
self.d_model = d_model
|
237 |
self.n_heads = n_heads
|
238 |
-
self.kv_n_heads = kv_n_heads
|
239 |
-
self.sliding_window_size = sliding_window_size
|
240 |
-
self.head_dim = d_model // n_heads
|
241 |
-
if self.kv_n_heads <= 0:
|
242 |
-
raise ValueError('kv_n_heads should be greater than zero.')
|
243 |
-
if self.kv_n_heads > self.n_heads:
|
244 |
-
raise ValueError('The number of KV heads should be less than or equal to Q heads.')
|
245 |
-
if self.n_heads % self.kv_n_heads != 0:
|
246 |
-
raise ValueError('Each Q head should get the same number of KV heads, so n_heads must be divisible by kv_n_heads.')
|
247 |
-
if qk_ln and qk_gn:
|
248 |
-
raise ValueError('Only one of qk_ln and qk_gn can be set to True.')
|
249 |
self.softmax_scale = softmax_scale
|
250 |
if self.softmax_scale is None:
|
251 |
self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
|
252 |
self.attn_dropout_p = attn_pdrop
|
253 |
-
|
254 |
-
|
255 |
-
fc_kwargs['device'] = device
|
256 |
-
self.Wqkv = FC_CLASS_REGISTRY[fc_type](self.d_model, self.d_model + 2 * self.kv_n_heads * self.head_dim, **fc_kwargs)
|
257 |
-
fuse_splits = [i * self.head_dim for i in range(1, self.n_heads + 2 * self.kv_n_heads)]
|
258 |
self.Wqkv._fused = (0, fuse_splits)
|
259 |
-
if self.qk_ln
|
260 |
-
|
261 |
-
|
262 |
-
self.
|
263 |
-
if qk_ln:
|
264 |
-
norm_size = self.head_dim * kv_n_heads
|
265 |
-
self.k_ln = norm_class(norm_size, device=device)
|
266 |
if self.attn_impl == 'flash':
|
267 |
self.attn_fn = flash_attn_fn
|
268 |
elif self.attn_impl == 'triton':
|
269 |
self.attn_fn = triton_flash_attn_fn
|
|
|
|
|
270 |
elif self.attn_impl == 'torch':
|
271 |
self.attn_fn = scaled_multihead_dot_product_attention
|
|
|
|
|
272 |
else:
|
273 |
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
274 |
-
self.out_proj =
|
275 |
self.out_proj._is_residual = True
|
276 |
|
277 |
-
def forward(self, x
|
278 |
qkv = self.Wqkv(x)
|
279 |
if self.clip_qkv:
|
280 |
-
qkv
|
281 |
-
(query, key, value) = qkv.
|
282 |
key_padding_mask = attention_mask
|
283 |
-
if self.qk_ln
|
284 |
-
(q_shape, k_shape) = (query.shape, key.shape)
|
285 |
-
if self.qk_gn:
|
286 |
-
(b, s) = query.shape[:2]
|
287 |
-
query = query.view(b, s, self.n_heads, -1)
|
288 |
-
key = key.view(b, s, self.kv_n_heads, -1)
|
289 |
dtype = query.dtype
|
290 |
-
query = self.q_ln(query).to(dtype)
|
291 |
-
key = self.k_ln(key).to(dtype)
|
292 |
-
|
293 |
-
rotary_emb = rotary_emb_w_meta_info['rotary_emb']
|
294 |
-
seq_len = rotary_emb_w_meta_info['seq_len']
|
295 |
-
offset_info = rotary_emb_w_meta_info['offset_info']
|
296 |
-
(bsz, seqlen) = query.shape[:2]
|
297 |
-
query = query.view(bsz, seqlen, -1, self.head_dim)
|
298 |
-
key = key.view(bsz, seqlen, -1, self.head_dim)
|
299 |
-
if rotary_emb_w_meta_info['impl'] == 'dail':
|
300 |
-
value = value.view(bsz, seqlen, -1, self.head_dim)
|
301 |
-
kv = torch.stack([key, value], dim=2)
|
302 |
-
(query, kv) = rotary_emb(query, kv, seqlen_offset=offset_info, max_seqlen=seq_len)
|
303 |
-
[key, value] = torch.unbind(kv, dim=2)
|
304 |
-
value = value.view(bsz, seqlen, self.kv_n_heads * self.head_dim)
|
305 |
-
elif rotary_emb_w_meta_info['impl'] == 'hf':
|
306 |
-
(cos, sin) = rotary_emb(value, seq_len)
|
307 |
-
if is_transformers_version_gte('4.36'):
|
308 |
-
(query, key) = apply_rotary_pos_emb(query, key, cos, sin, offset_info, unsqueeze_dim=2)
|
309 |
-
else:
|
310 |
-
query = query.transpose(1, 2)
|
311 |
-
key = key.transpose(1, 2)
|
312 |
-
(query, key) = apply_rotary_pos_emb(query, key, cos, sin, offset_info)
|
313 |
-
query = query.transpose(1, 2)
|
314 |
-
key = key.transpose(1, 2)
|
315 |
-
query = query.view(bsz, seqlen, self.d_model)
|
316 |
-
key = key.view(bsz, seqlen, self.kv_n_heads * self.head_dim)
|
317 |
-
extra_attn_kwargs = {}
|
318 |
-
if self.attn_impl == 'flash':
|
319 |
-
key_padding_mask = None
|
320 |
-
extra_attn_kwargs = {'should_repeat_kv_for_gqa': not is_flash_v2_installed(), 'sliding_window_size': self.sliding_window_size, 'alibi_slopes': alibi_slopes, 'flash_attn_padding_info': flash_attn_padding_info}
|
321 |
-
(context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, self.kv_n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, **extra_attn_kwargs)
|
322 |
return (self.out_proj(context), attn_weights, past_key_value)
|
323 |
|
324 |
-
class
|
325 |
-
"""Multi-head self attention.
|
326 |
-
|
327 |
-
Using torch or triton attention implementation enables user to also use
|
328 |
-
additive bias.
|
329 |
-
"""
|
330 |
-
|
331 |
-
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, qk_gn: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, norm_type: str='low_precision_layernorm', fc_type: str='torch', device: Optional[str]=None, bias: bool=True, sliding_window_size: int=-1):
|
332 |
-
super().__init__(d_model=d_model, n_heads=n_heads, kv_n_heads=n_heads, attn_impl=attn_impl, clip_qkv=clip_qkv, qk_ln=qk_ln, qk_gn=qk_gn, softmax_scale=softmax_scale, attn_pdrop=attn_pdrop, norm_type=norm_type, fc_type=fc_type, device=device, bias=bias, sliding_window_size=sliding_window_size)
|
333 |
-
|
334 |
-
class MultiQueryAttention(GroupedQueryAttention):
|
335 |
"""Multi-Query self attention.
|
336 |
|
337 |
-
Using torch or triton attention
|
338 |
additive bias.
|
339 |
"""
|
340 |
|
341 |
-
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False,
|
342 |
-
super().__init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
343 |
|
344 |
-
def attn_bias_shape(attn_impl
|
345 |
if attn_impl == 'flash':
|
346 |
return None
|
347 |
elif attn_impl in ['torch', 'triton']:
|
@@ -355,7 +269,7 @@ def attn_bias_shape(attn_impl: str, n_heads: int, seq_len: int, alibi: bool, pre
|
|
355 |
else:
|
356 |
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
357 |
|
358 |
-
def build_attn_bias(attn_impl
|
359 |
if attn_impl == 'flash':
|
360 |
return None
|
361 |
elif attn_impl in ['torch', 'triton']:
|
@@ -366,18 +280,16 @@ def build_attn_bias(attn_impl: str, attn_bias: torch.Tensor, n_heads: int, seq_l
|
|
366 |
else:
|
367 |
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
368 |
|
369 |
-
def gen_slopes(n_heads
|
370 |
_n_heads = 2 ** math.ceil(math.log2(n_heads))
|
371 |
m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
|
372 |
m = m.mul(alibi_bias_max / _n_heads)
|
373 |
slopes = 1.0 / torch.pow(2, m)
|
374 |
if _n_heads != n_heads:
|
375 |
slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
|
376 |
-
if return_1d:
|
377 |
-
return slopes
|
378 |
return slopes.view(1, n_heads, 1, 1)
|
379 |
|
380 |
-
def build_alibi_bias(n_heads
|
381 |
alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len)
|
382 |
if full:
|
383 |
alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1)
|
@@ -385,4 +297,4 @@ def build_alibi_bias(n_heads: int, seq_len: int, full: bool=False, alibi_bias_ma
|
|
385 |
slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
|
386 |
alibi_bias = alibi_bias * slopes
|
387 |
return alibi_bias.to(dtype=dtype)
|
388 |
-
ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention
|
|
|
1 |
"""Attention layers."""
|
2 |
import math
|
3 |
import warnings
|
4 |
+
from typing import Optional
|
5 |
import torch
|
6 |
import torch.nn as nn
|
|
|
7 |
from einops import rearrange
|
8 |
from packaging import version
|
9 |
from torch import nn
|
10 |
+
from .norm import LPLayerNorm
|
|
|
11 |
|
12 |
+
def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
if original_is_causal and num_query_tokens != num_key_tokens:
|
14 |
if num_query_tokens != 1:
|
15 |
raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
|
|
|
17 |
return False
|
18 |
return original_is_causal
|
19 |
|
20 |
+
def scaled_multihead_dot_product_attention(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
|
22 |
+
kv_n_heads = 1 if multiquery else n_heads
|
23 |
k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
|
24 |
v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
|
25 |
if past_key_value is not None:
|
|
|
29 |
past_key_value = (k, v)
|
30 |
(b, _, s_q, d) = q.shape
|
31 |
s_k = k.size(-1)
|
|
|
|
|
|
|
32 |
if softmax_scale is None:
|
33 |
softmax_scale = 1 / math.sqrt(d)
|
34 |
attn_weight = q.matmul(k) * softmax_scale
|
|
|
42 |
min_val = torch.finfo(q.dtype).min
|
43 |
if key_padding_mask is not None:
|
44 |
if attn_bias is not None:
|
45 |
+
warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
|
46 |
attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
|
47 |
if is_causal and (not q.size(2) == 1):
|
48 |
s = max(s_q, s_k)
|
49 |
+
causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
|
50 |
causal_mask = causal_mask.tril()
|
51 |
causal_mask = causal_mask.to(torch.bool)
|
52 |
causal_mask = ~causal_mask
|
|
|
55 |
attn_weight = torch.softmax(attn_weight, dim=-1)
|
56 |
if dropout_p:
|
57 |
attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
|
58 |
+
out = attn_weight.matmul(v)
|
59 |
out = rearrange(out, 'b h s d -> b s (h d)')
|
60 |
if needs_weights:
|
61 |
return (out, attn_weight, past_key_value)
|
62 |
return (out, None, past_key_value)
|
63 |
|
64 |
+
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
|
|
|
|
|
65 |
for tensor in tensors:
|
66 |
if tensor.dtype not in valid_dtypes:
|
67 |
raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
|
68 |
if not tensor.is_cuda:
|
69 |
raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
|
70 |
|
71 |
+
def flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
|
|
|
|
|
|
|
|
|
|
72 |
try:
|
73 |
from flash_attn import bert_padding, flash_attn_interface
|
74 |
except:
|
75 |
+
raise RuntimeError('Please install flash-attn==1.0.3.post0')
|
76 |
check_valid_inputs(query, key, value)
|
77 |
if past_key_value is not None:
|
78 |
if len(past_key_value) != 0:
|
79 |
key = torch.cat([past_key_value[0], key], dim=1)
|
80 |
value = torch.cat([past_key_value[1], value], dim=1)
|
81 |
past_key_value = (key, value)
|
82 |
+
if attn_bias is not None:
|
83 |
+
_s_q = max(0, attn_bias.size(2) - query.size(1))
|
84 |
+
_s_k = max(0, attn_bias.size(3) - key.size(1))
|
85 |
+
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
86 |
if attn_bias is not None:
|
87 |
raise NotImplementedError(f'attn_bias not implemented for flash attn.')
|
88 |
(batch_size, seqlen) = query.shape[:2]
|
89 |
+
if key_padding_mask is None:
|
90 |
+
key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
|
91 |
+
query_padding_mask = key_padding_mask[:, -query.size(1):]
|
92 |
+
(query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
|
|
|
|
|
|
|
|
|
93 |
query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
|
94 |
+
(key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
|
95 |
+
key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
|
96 |
+
(value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
|
97 |
+
value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
|
98 |
+
if multiquery:
|
99 |
+
key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
|
100 |
+
value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
dropout_p = dropout_p if training else 0.0
|
102 |
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
103 |
+
output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
|
105 |
return (output, None, past_key_value)
|
106 |
|
107 |
+
def triton_flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
108 |
try:
|
109 |
from .flash_attn_triton import flash_attn_func
|
110 |
except:
|
|
|
116 |
except:
|
117 |
_installed = False
|
118 |
if not _installed:
|
119 |
+
raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed.')
|
120 |
check_valid_inputs(query, key, value)
|
121 |
if past_key_value is not None:
|
122 |
if len(past_key_value) != 0:
|
|
|
129 |
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
130 |
if dropout_p:
|
131 |
raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
|
|
|
132 |
if needs_weights:
|
133 |
raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
|
134 |
if key_padding_mask is not None:
|
|
|
138 |
attn_bias = query.new_zeros(b_size, 1, 1, s_k)
|
139 |
attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
|
140 |
query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
|
141 |
+
key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
|
142 |
+
value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
|
143 |
+
if multiquery:
|
144 |
+
key = key.expand(*key.shape[:2], n_heads, key.size(-1))
|
145 |
+
value = value.expand(*value.shape[:2], n_heads, value.size(-1))
|
|
|
|
|
|
|
146 |
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
147 |
attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
|
148 |
output = attn_output.view(*attn_output.shape[:2], -1)
|
149 |
return (output, None, past_key_value)
|
150 |
|
151 |
+
class MultiheadAttention(nn.Module):
|
152 |
+
"""Multi-head self attention.
|
|
|
|
|
153 |
|
154 |
+
Using torch or triton attention implemetation enables user to also use
|
155 |
+
additive bias.
|
|
|
156 |
"""
|
157 |
|
158 |
+
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
|
159 |
super().__init__()
|
160 |
self.attn_impl = attn_impl
|
161 |
self.clip_qkv = clip_qkv
|
162 |
self.qk_ln = qk_ln
|
|
|
163 |
self.d_model = d_model
|
164 |
self.n_heads = n_heads
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
self.softmax_scale = softmax_scale
|
166 |
if self.softmax_scale is None:
|
167 |
self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
|
168 |
self.attn_dropout_p = attn_pdrop
|
169 |
+
self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
|
170 |
+
fuse_splits = (d_model, 2 * d_model)
|
|
|
|
|
|
|
171 |
self.Wqkv._fused = (0, fuse_splits)
|
172 |
+
if self.qk_ln:
|
173 |
+
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
174 |
+
self.q_ln = layernorm_class(self.d_model, device=device)
|
175 |
+
self.k_ln = layernorm_class(self.d_model, device=device)
|
|
|
|
|
|
|
176 |
if self.attn_impl == 'flash':
|
177 |
self.attn_fn = flash_attn_fn
|
178 |
elif self.attn_impl == 'triton':
|
179 |
self.attn_fn = triton_flash_attn_fn
|
180 |
+
if verbose:
|
181 |
+
warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
|
182 |
elif self.attn_impl == 'torch':
|
183 |
self.attn_fn = scaled_multihead_dot_product_attention
|
184 |
+
if torch.cuda.is_available() and verbose:
|
185 |
+
warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
|
186 |
else:
|
187 |
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
188 |
+
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
189 |
self.out_proj._is_residual = True
|
190 |
|
191 |
+
def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
|
192 |
qkv = self.Wqkv(x)
|
193 |
if self.clip_qkv:
|
194 |
+
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
195 |
+
(query, key, value) = qkv.chunk(3, dim=2)
|
196 |
key_padding_mask = attention_mask
|
197 |
+
if self.qk_ln:
|
|
|
|
|
|
|
|
|
|
|
198 |
dtype = query.dtype
|
199 |
+
query = self.q_ln(query).to(dtype)
|
200 |
+
key = self.k_ln(key).to(dtype)
|
201 |
+
(context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
202 |
return (self.out_proj(context), attn_weights, past_key_value)
|
203 |
|
204 |
+
class MultiQueryAttention(nn.Module):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
"""Multi-Query self attention.
|
206 |
|
207 |
+
Using torch or triton attention implemetation enables user to also use
|
208 |
additive bias.
|
209 |
"""
|
210 |
|
211 |
+
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
|
212 |
+
super().__init__()
|
213 |
+
self.attn_impl = attn_impl
|
214 |
+
self.clip_qkv = clip_qkv
|
215 |
+
self.qk_ln = qk_ln
|
216 |
+
self.d_model = d_model
|
217 |
+
self.n_heads = n_heads
|
218 |
+
self.head_dim = d_model // n_heads
|
219 |
+
self.softmax_scale = softmax_scale
|
220 |
+
if self.softmax_scale is None:
|
221 |
+
self.softmax_scale = 1 / math.sqrt(self.head_dim)
|
222 |
+
self.attn_dropout_p = attn_pdrop
|
223 |
+
self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device)
|
224 |
+
fuse_splits = (d_model, d_model + self.head_dim)
|
225 |
+
self.Wqkv._fused = (0, fuse_splits)
|
226 |
+
if self.qk_ln:
|
227 |
+
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
228 |
+
self.q_ln = layernorm_class(d_model, device=device)
|
229 |
+
self.k_ln = layernorm_class(self.head_dim, device=device)
|
230 |
+
if self.attn_impl == 'flash':
|
231 |
+
self.attn_fn = flash_attn_fn
|
232 |
+
elif self.attn_impl == 'triton':
|
233 |
+
self.attn_fn = triton_flash_attn_fn
|
234 |
+
if verbose:
|
235 |
+
warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
|
236 |
+
elif self.attn_impl == 'torch':
|
237 |
+
self.attn_fn = scaled_multihead_dot_product_attention
|
238 |
+
if torch.cuda.is_available() and verbose:
|
239 |
+
warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
|
240 |
+
else:
|
241 |
+
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
242 |
+
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
243 |
+
self.out_proj._is_residual = True
|
244 |
+
|
245 |
+
def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
|
246 |
+
qkv = self.Wqkv(x)
|
247 |
+
if self.clip_qkv:
|
248 |
+
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
249 |
+
(query, key, value) = qkv.split([self.d_model, self.head_dim, self.head_dim], dim=2)
|
250 |
+
key_padding_mask = attention_mask
|
251 |
+
if self.qk_ln:
|
252 |
+
dtype = query.dtype
|
253 |
+
query = self.q_ln(query).to(dtype)
|
254 |
+
key = self.k_ln(key).to(dtype)
|
255 |
+
(context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, multiquery=True)
|
256 |
+
return (self.out_proj(context), attn_weights, past_key_value)
|
257 |
|
258 |
+
def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):
|
259 |
if attn_impl == 'flash':
|
260 |
return None
|
261 |
elif attn_impl in ['torch', 'triton']:
|
|
|
269 |
else:
|
270 |
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
271 |
|
272 |
+
def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8):
|
273 |
if attn_impl == 'flash':
|
274 |
return None
|
275 |
elif attn_impl in ['torch', 'triton']:
|
|
|
280 |
else:
|
281 |
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
282 |
|
283 |
+
def gen_slopes(n_heads, alibi_bias_max=8, device=None):
|
284 |
_n_heads = 2 ** math.ceil(math.log2(n_heads))
|
285 |
m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
|
286 |
m = m.mul(alibi_bias_max / _n_heads)
|
287 |
slopes = 1.0 / torch.pow(2, m)
|
288 |
if _n_heads != n_heads:
|
289 |
slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
|
|
|
|
|
290 |
return slopes.view(1, n_heads, 1, 1)
|
291 |
|
292 |
+
def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None):
|
293 |
alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len)
|
294 |
if full:
|
295 |
alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1)
|
|
|
297 |
slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
|
298 |
alibi_bias = alibi_bias * slopes
|
299 |
return alibi_bias.to(dtype=dtype)
|
300 |
+
ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention}
|
blocks.py
CHANGED
@@ -1,55 +1,41 @@
|
|
1 |
"""GPT Blocks used for the GPT Model."""
|
2 |
-
from typing import
|
3 |
import torch
|
4 |
import torch.nn as nn
|
5 |
from .attention import ATTN_CLASS_REGISTRY
|
6 |
-
from .ffn import FFN_CLASS_REGISTRY, build_ffn
|
7 |
from .norm import NORM_CLASS_REGISTRY
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
(
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
class MPTBlock(nn.Module):
|
15 |
|
16 |
-
def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config:
|
17 |
-
if attn_config is None:
|
18 |
-
attn_config = attn_config_defaults
|
19 |
-
if ffn_config is None:
|
20 |
-
ffn_config = {'ffn_type': 'mptmlp'}
|
21 |
del kwargs
|
22 |
super().__init__()
|
23 |
norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
|
24 |
-
assert isinstance(attn_config['attn_type'], str)
|
25 |
attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
|
26 |
-
args_to_exclude_in_attn_class = {'attn_type', 'prefix_lm', 'alibi', 'attn_uses_sequence_id', 'alibi_bias_max', 'rope', 'rope_theta', 'rope_impl', 'rope_dail_config', 'rope_hf_config'}
|
27 |
-
attn_config_subset_for_attn_class = {k: v for (k, v) in attn_config.items() if k not in args_to_exclude_in_attn_class}
|
28 |
self.norm_1 = norm_class(d_model, device=device)
|
29 |
-
self.attn = attn_class(d_model=d_model, n_heads=n_heads,
|
30 |
-
self.norm_2 =
|
31 |
-
|
32 |
-
self.norm_2 = norm_class(d_model, device=device)
|
33 |
-
self.ffn = build_ffn(d_model=d_model, expansion_ratio=expansion_ratio, device=device, bias=not no_bias, **ffn_config)
|
34 |
self.resid_attn_dropout = nn.Dropout(resid_pdrop)
|
35 |
self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
|
36 |
-
self.use_pad_tok_in_ffn = use_pad_tok_in_ffn
|
37 |
|
38 |
-
def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor
|
39 |
a = self.norm_1(x)
|
40 |
-
(b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias,
|
41 |
x = x + self.resid_attn_dropout(b)
|
42 |
-
m = x
|
43 |
-
if self.norm_2 is not None:
|
44 |
-
m = self.norm_2(x)
|
45 |
-
(batch_size, seq_len) = m.size()[:2]
|
46 |
-
indices = None
|
47 |
-
if not self.use_pad_tok_in_ffn:
|
48 |
-
assert unpad_input is not None
|
49 |
-
(m, indices, _, _) = unpad_input(m, attention_mask)
|
50 |
n = self.ffn(m)
|
51 |
-
if not self.use_pad_tok_in_ffn:
|
52 |
-
assert pad_input is not None
|
53 |
-
n = pad_input(n, indices, batch_size, seq_len)
|
54 |
x = x + self.resid_ffn_dropout(n)
|
55 |
return (x, attn_weights, past_key_value)
|
|
|
1 |
"""GPT Blocks used for the GPT Model."""
|
2 |
+
from typing import Dict, Optional, Tuple
|
3 |
import torch
|
4 |
import torch.nn as nn
|
5 |
from .attention import ATTN_CLASS_REGISTRY
|
|
|
6 |
from .norm import NORM_CLASS_REGISTRY
|
7 |
+
|
8 |
+
class MPTMLP(nn.Module):
|
9 |
+
|
10 |
+
def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None):
|
11 |
+
super().__init__()
|
12 |
+
self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device)
|
13 |
+
self.act = nn.GELU(approximate='none')
|
14 |
+
self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device)
|
15 |
+
self.down_proj._is_residual = True
|
16 |
+
|
17 |
+
def forward(self, x):
|
18 |
+
return self.down_proj(self.act(self.up_proj(x)))
|
19 |
|
20 |
class MPTBlock(nn.Module):
|
21 |
|
22 |
+
def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', verbose: int=0, device: Optional[str]=None, **kwargs):
|
|
|
|
|
|
|
|
|
23 |
del kwargs
|
24 |
super().__init__()
|
25 |
norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
|
|
|
26 |
attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
|
|
|
|
|
27 |
self.norm_1 = norm_class(d_model, device=device)
|
28 |
+
self.attn = attn_class(attn_impl=attn_config['attn_impl'], clip_qkv=attn_config['clip_qkv'], qk_ln=attn_config['qk_ln'], softmax_scale=attn_config['softmax_scale'], attn_pdrop=attn_config['attn_pdrop'], d_model=d_model, n_heads=n_heads, verbose=verbose, device=device)
|
29 |
+
self.norm_2 = norm_class(d_model, device=device)
|
30 |
+
self.ffn = MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, device=device)
|
|
|
|
|
31 |
self.resid_attn_dropout = nn.Dropout(resid_pdrop)
|
32 |
self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
|
|
|
33 |
|
34 |
+
def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]:
|
35 |
a = self.norm_1(x)
|
36 |
+
(b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal)
|
37 |
x = x + self.resid_attn_dropout(b)
|
38 |
+
m = self.norm_2(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
n = self.ffn(m)
|
|
|
|
|
|
|
40 |
x = x + self.resid_ffn_dropout(n)
|
41 |
return (x, attn_weights, past_key_value)
|
configuration_mpt.py
CHANGED
@@ -1,38 +1,30 @@
|
|
1 |
"""A HuggingFace-style model configuration."""
|
2 |
-
import
|
3 |
-
from typing import Any, Dict, Optional, Union
|
4 |
from transformers import PretrainedConfig
|
5 |
-
|
6 |
-
from .blocks import attn_config_defaults
|
7 |
-
from .fc import FC_CLASS_REGISTRY
|
8 |
-
from .norm import LPLayerNorm
|
9 |
-
from .ffn import FFN_CLASS_REGISTRY
|
10 |
-
from .warnings import VersionedDeprecationWarning
|
11 |
-
ffn_config_defaults: Dict = {'ffn_type': 'mptmlp'}
|
12 |
init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
|
13 |
|
14 |
class MPTConfig(PretrainedConfig):
|
15 |
model_type = 'mpt'
|
16 |
|
17 |
-
def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio:
|
18 |
"""The MPT configuration class.
|
19 |
|
20 |
Args:
|
21 |
d_model (int): The size of the embedding dimension of the model.
|
22 |
n_heads (int): The number of attention heads.
|
23 |
n_layers (int): The number of layers in the model.
|
24 |
-
expansion_ratio (
|
25 |
max_seq_len (int): The maximum sequence length of the model.
|
26 |
vocab_size (int): The size of the vocabulary.
|
27 |
resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
|
28 |
emb_pdrop (float): The dropout probability for the embedding layer.
|
29 |
learned_pos_emb (bool): Whether to use learned positional embeddings
|
30 |
-
attn_config (Dict):
|
31 |
-
attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
|
32 |
attn_pdrop (float): The dropout probability for the attention layers.
|
33 |
attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
|
34 |
qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
|
35 |
-
qk_gn (bool): Whether to apply group normalization to the queries and keys in the attention layer.
|
36 |
clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
|
37 |
this value.
|
38 |
softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
|
@@ -44,27 +36,15 @@ class MPTConfig(PretrainedConfig):
|
|
44 |
When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
|
45 |
which sub-sequence each token belongs to.
|
46 |
Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
|
47 |
-
sliding_window_size (int): Window size for sliding window local attention. Defaults to -1, which means no sliding window. Query at position i will only attend to keys between [i + seqlen_k - seqlen_q - window_size, i + seqlen_k - seqlen_q + window_size] inclusive. Only works for flash attention v2.3.0 or higher.
|
48 |
alibi (bool): Whether to use the alibi bias instead of position embeddings.
|
49 |
alibi_bias_max (int): The maximum value of the alibi bias.
|
50 |
-
rope (bool): Whether to use rotary positional embeddings.
|
51 |
-
rope_theta (int): The base frequency for rope.
|
52 |
-
rope_impl (str): The implementation of rope to use. One of 'hf' (to use the implementation from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py) or 'dail' (to use the implementation from https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/layers/rotary.py).
|
53 |
-
rope_dail_config (Dict): The configuration for the dail implementation of rope.
|
54 |
-
type (str): The type of rotary position embedding to use. Options: 'original' (for https://arxiv.org/pdf/2104.09864.pdf), 'xpos' (for https://arxiv.org/pdf/2212.10554.pdf).
|
55 |
-
pos_idx_in_fp32 (bool): If True, the position indices [0, ..., seqlen - 1] are in fp32, otherwise they might be in lower precision. A consequence could be, for example, that bf16 rounds position 1995 to 2000, which leads to them having the same positional embedding.
|
56 |
-
xpos_scale_base (float): The scale base for XPos (if using XPos).
|
57 |
-
rope_hf_config (Dict): A dictionary used to configure rope's scaling behavior (when scaling beyond the training length).
|
58 |
-
type (str): Can be one of 'no_scaling', 'linear', or 'dynamic'. 'no_scaling' uses the default implementation for rotary embeddings, 'linear' uses linear scaling as proposed by the Reddit user /u/kaiokendev, and 'dynamic' uses Dynamic NTK scaling as proposed by the Reddit users /u/bloc97 and /u/emozilla.
|
59 |
-
factor (float): Scaling factor to use if using 'linear' or 'dynamic' as rope_scaling.type.
|
60 |
-
kv_n_heads (Optional[int]): For grouped_query_attention only, allow user to specify number of kv heads.
|
61 |
-
ffn_config (Dict): A dictionary used to configure the model's ffn module:
|
62 |
-
ffn_type (str): type of ffn to use. Options: mptmlp, mptglu, te_ln_mlp
|
63 |
init_device (str): The device to use for parameter initialization.
|
64 |
logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
|
65 |
no_bias (bool): Whether to use bias in all layers.
|
|
|
66 |
embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
|
67 |
norm_type (str): choose type of norm to use
|
|
|
68 |
use_cache (bool): Whether or not the model should return the last key/values attentions
|
69 |
init_config (Dict): A dictionary used to configure the model initialization:
|
70 |
init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
|
@@ -81,9 +61,6 @@ class MPTConfig(PretrainedConfig):
|
|
81 |
init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
|
82 |
---
|
83 |
See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
|
84 |
-
fc_type (str): choose fc layer implementation. Options: torch and te. te layers support fp8 when using H100 GPUs.
|
85 |
-
tie_word_embeddings (bool): Whether to tie the input embedding and output layers.
|
86 |
-
use_pad_tok_in_ffn (bool): Whether to forward the pad token in the feedforward networks.
|
87 |
"""
|
88 |
self.d_model = d_model
|
89 |
self.n_heads = n_heads
|
@@ -95,37 +72,29 @@ class MPTConfig(PretrainedConfig):
|
|
95 |
self.emb_pdrop = emb_pdrop
|
96 |
self.learned_pos_emb = learned_pos_emb
|
97 |
self.attn_config = attn_config
|
98 |
-
self.ffn_config = ffn_config
|
99 |
self.init_device = init_device
|
100 |
self.logit_scale = logit_scale
|
101 |
self.no_bias = no_bias
|
|
|
102 |
self.embedding_fraction = embedding_fraction
|
103 |
self.norm_type = norm_type
|
104 |
self.use_cache = use_cache
|
105 |
self.init_config = init_config
|
106 |
-
self.fc_type = fc_type
|
107 |
-
self.use_pad_tok_in_ffn = use_pad_tok_in_ffn
|
108 |
if 'name' in kwargs:
|
109 |
del kwargs['name']
|
110 |
if 'loss_fn' in kwargs:
|
111 |
del kwargs['loss_fn']
|
112 |
-
|
113 |
-
self.learned_pos_emb = False
|
114 |
-
warnings.warn(f'alibi or rope is turned on, setting `learned_pos_emb` to `False.`')
|
115 |
-
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
116 |
self._validate_config()
|
117 |
|
118 |
-
def _set_config_defaults(self, config
|
119 |
for (k, v) in config_defaults.items():
|
120 |
if k not in config:
|
121 |
config[k] = v
|
122 |
-
elif isinstance(v, dict):
|
123 |
-
config[k] = self._set_config_defaults(config[k] if config[k] is not None else {}, v)
|
124 |
return config
|
125 |
|
126 |
-
def _validate_config(self)
|
127 |
self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
|
128 |
-
self.ffn_config = self._set_config_defaults(self.ffn_config, ffn_config_defaults)
|
129 |
self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
|
130 |
if self.d_model % self.n_heads != 0:
|
131 |
raise ValueError('d_model must be divisible by n_heads')
|
@@ -135,49 +104,15 @@ class MPTConfig(PretrainedConfig):
|
|
135 |
raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
|
136 |
if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
137 |
raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
|
138 |
-
if self.attn_config['attn_impl']
|
139 |
-
|
140 |
-
if self.attn_config['
|
141 |
-
|
142 |
-
if self.attn_config['alibi'] and (not check_alibi_support(self.attn_config['attn_impl'])):
|
143 |
-
raise NotImplementedError('alibi only implemented with torch, triton, and flash (v2.4.2 or higher) attention.')
|
144 |
-
if self.attn_config['attn_uses_sequence_id'] and (not (self.attn_config['attn_impl'] in ['torch', 'triton'] or (self.attn_config['attn_impl'] == 'flash' and is_flash_v2_installed(v2_version='v2.1.2')))):
|
145 |
-
raise NotImplementedError('attn_uses_sequence_id only implemented with torch, triton, and flash (v2.1.2 or higher) attention.')
|
146 |
-
if self.attn_config['rope'] and self.attn_config['rope_impl'] not in ['dail', 'hf']:
|
147 |
-
raise ValueError('If rope is being used then rope_impl should be either "dail", or "hf".')
|
148 |
-
if self.attn_config['rope'] and self.attn_config['rope_impl'] == 'hf' and (self.attn_config['rope_hf_config']['type'] not in ['no_scaling', 'linear', 'dynamic']):
|
149 |
-
raise ValueError('If using hf implementation of rope, the type should be one of "no_scaling", "linear" or "dynamic".')
|
150 |
-
if self.attn_config['rope'] and self.attn_config['rope_impl'] == 'dail':
|
151 |
-
if self.attn_config['rope_dail_config']['type'] not in ['original', 'xpos']:
|
152 |
-
raise ValueError('If using the dail implementation of rope, the type should be one of "original" or "xpos".')
|
153 |
-
if not is_flash_v2_installed(v2_version='2.0.1'):
|
154 |
-
raise ImportError('If using the dail implementation of rope, the flash_attn library v2.0.1 or higher must be installed. Please check the instructions at https://github.com/mosaicml/llm-foundry/blob/main/TUTORIAL.md#what-kinds-of-positional-embeddings-does-llm-foundry-support')
|
155 |
-
if self.attn_config['sliding_window_size'] != -1 and (not (self.attn_config['attn_impl'] == 'flash' and is_flash_v2_installed(v2_version='v2.3.0'))):
|
156 |
-
raise NotImplementedError('sliding window only implemented with flash attention v2.3.0 or higher.')
|
157 |
if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
|
158 |
raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
|
159 |
if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
|
160 |
raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
161 |
if self.init_config.get('name', None) is None:
|
162 |
raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
|
163 |
-
if not
|
164 |
-
|
165 |
-
if self.fc_type == 'te' or self.ffn_config['ffn_type'] == 'te_ln_mlp':
|
166 |
-
try:
|
167 |
-
import transformer_engine.pytorch as te
|
168 |
-
del te
|
169 |
-
except:
|
170 |
-
raise ImportError('TransformerEngine import fail. `fc_type: te` requires TransformerEngine be installed. ' + 'The required version of transformer_engine also requires FlashAttention v1.0.6 is installed:\n' + 'pip install flash-attn==1.0.6 --no-build-isolation \n' + 'pip install git+https://github.com/NVIDIA/TransformerEngine.git@144e4888b2cdd60bd52e706d5b7a79cb9c1a7156')
|
171 |
-
if self.ffn_config['ffn_type'] == 'mptgeglu':
|
172 |
-
raise ValueError('API CHANGE: `ffn_type=="mptgeglu"` changed to `ffn_type=="mptglu"`. ' + 'See [#829](https://github.com/mosaicml/llm-foundry/pull/829) for details.')
|
173 |
-
elif self.ffn_config['ffn_type'] in ['mptmlp', 'mptglu']:
|
174 |
-
self.ffn_config['fc_type'] = self.fc_type
|
175 |
-
elif self.ffn_config['ffn_type'] == 'te_ln_mlp':
|
176 |
-
self.ffn_config['bias'] = not self.no_bias
|
177 |
-
if 'ffn_act_fn' in self.ffn_config.keys():
|
178 |
-
raise ValueError(f'Transformer Engine block does not support custom activation functions.')
|
179 |
-
if not self.use_pad_tok_in_ffn:
|
180 |
-
try:
|
181 |
-
from flash_attn.bert_padding import unpad_input, pad_input
|
182 |
-
except:
|
183 |
-
raise ImportError('In order to set `use_pad_tok_in_ffn=False`, please install flash-attn==1.0.9 or flash-attn==2.3.6')
|
|
|
1 |
"""A HuggingFace-style model configuration."""
|
2 |
+
from typing import Dict, Optional, Union
|
|
|
3 |
from transformers import PretrainedConfig
|
4 |
+
attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
|
6 |
|
7 |
class MPTConfig(PretrainedConfig):
|
8 |
model_type = 'mpt'
|
9 |
|
10 |
+
def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, verbose: int=0, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, **kwargs):
|
11 |
"""The MPT configuration class.
|
12 |
|
13 |
Args:
|
14 |
d_model (int): The size of the embedding dimension of the model.
|
15 |
n_heads (int): The number of attention heads.
|
16 |
n_layers (int): The number of layers in the model.
|
17 |
+
expansion_ratio (int): The ratio of the up/down scale in the MLP.
|
18 |
max_seq_len (int): The maximum sequence length of the model.
|
19 |
vocab_size (int): The size of the vocabulary.
|
20 |
resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
|
21 |
emb_pdrop (float): The dropout probability for the embedding layer.
|
22 |
learned_pos_emb (bool): Whether to use learned positional embeddings
|
23 |
+
attn_config (Dict): A dictionary used to configure the model's attention module:
|
24 |
+
attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
|
25 |
attn_pdrop (float): The dropout probability for the attention layers.
|
26 |
attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
|
27 |
qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
|
|
|
28 |
clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
|
29 |
this value.
|
30 |
softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
|
|
|
36 |
When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
|
37 |
which sub-sequence each token belongs to.
|
38 |
Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
|
|
|
39 |
alibi (bool): Whether to use the alibi bias instead of position embeddings.
|
40 |
alibi_bias_max (int): The maximum value of the alibi bias.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
init_device (str): The device to use for parameter initialization.
|
42 |
logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
|
43 |
no_bias (bool): Whether to use bias in all layers.
|
44 |
+
verbose (int): The verbosity level. 0 is silent.
|
45 |
embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
|
46 |
norm_type (str): choose type of norm to use
|
47 |
+
multiquery_attention (bool): Whether to use multiquery attention implementation.
|
48 |
use_cache (bool): Whether or not the model should return the last key/values attentions
|
49 |
init_config (Dict): A dictionary used to configure the model initialization:
|
50 |
init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
|
|
|
61 |
init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
|
62 |
---
|
63 |
See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
|
|
|
|
|
|
|
64 |
"""
|
65 |
self.d_model = d_model
|
66 |
self.n_heads = n_heads
|
|
|
72 |
self.emb_pdrop = emb_pdrop
|
73 |
self.learned_pos_emb = learned_pos_emb
|
74 |
self.attn_config = attn_config
|
|
|
75 |
self.init_device = init_device
|
76 |
self.logit_scale = logit_scale
|
77 |
self.no_bias = no_bias
|
78 |
+
self.verbose = verbose
|
79 |
self.embedding_fraction = embedding_fraction
|
80 |
self.norm_type = norm_type
|
81 |
self.use_cache = use_cache
|
82 |
self.init_config = init_config
|
|
|
|
|
83 |
if 'name' in kwargs:
|
84 |
del kwargs['name']
|
85 |
if 'loss_fn' in kwargs:
|
86 |
del kwargs['loss_fn']
|
87 |
+
super().__init__(**kwargs)
|
|
|
|
|
|
|
88 |
self._validate_config()
|
89 |
|
90 |
+
def _set_config_defaults(self, config, config_defaults):
|
91 |
for (k, v) in config_defaults.items():
|
92 |
if k not in config:
|
93 |
config[k] = v
|
|
|
|
|
94 |
return config
|
95 |
|
96 |
+
def _validate_config(self):
|
97 |
self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
|
|
|
98 |
self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
|
99 |
if self.d_model % self.n_heads != 0:
|
100 |
raise ValueError('d_model must be divisible by n_heads')
|
|
|
104 |
raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
|
105 |
if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
106 |
raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
|
107 |
+
if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
108 |
+
raise NotImplementedError('alibi only implemented with torch and triton attention.')
|
109 |
+
if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
110 |
+
raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
|
112 |
raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
|
113 |
if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
|
114 |
raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
115 |
if self.init_config.get('name', None) is None:
|
116 |
raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
|
117 |
+
if not self.learned_pos_emb and (not self.attn_config['alibi']):
|
118 |
+
raise ValueError(f'Positional information must be provided to the model using either learned_pos_emb or alibi.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
custom_embedding.py
CHANGED
@@ -1,10 +1,12 @@
|
|
|
|
1 |
import torch.nn as nn
|
2 |
import torch.nn.functional as F
|
3 |
from torch import Tensor
|
4 |
|
|
|
5 |
class SharedEmbedding(nn.Embedding):
|
6 |
|
7 |
-
def forward(self, input: Tensor, unembed: bool=False) -> Tensor:
|
8 |
if unembed:
|
9 |
return F.linear(input, self.weight)
|
10 |
return super().forward(input)
|
|
|
1 |
+
import torch
|
2 |
import torch.nn as nn
|
3 |
import torch.nn.functional as F
|
4 |
from torch import Tensor
|
5 |
|
6 |
+
|
7 |
class SharedEmbedding(nn.Embedding):
|
8 |
|
9 |
+
def forward(self, input: Tensor, unembed: bool = False) -> Tensor:
|
10 |
if unembed:
|
11 |
return F.linear(input, self.weight)
|
12 |
return super().forward(input)
|
fc.py
DELETED
@@ -1,7 +0,0 @@
|
|
1 |
-
from torch import nn
|
2 |
-
FC_CLASS_REGISTRY = {'torch': nn.Linear}
|
3 |
-
try:
|
4 |
-
import transformer_engine.pytorch as te
|
5 |
-
FC_CLASS_REGISTRY['te'] = te.Linear
|
6 |
-
except:
|
7 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ffn.py
DELETED
@@ -1,97 +0,0 @@
|
|
1 |
-
"""MPT Blocks used for the MPT Model."""
|
2 |
-
import logging
|
3 |
-
from copy import deepcopy
|
4 |
-
from functools import partial
|
5 |
-
from typing import Any, Callable, Optional, Union
|
6 |
-
import torch
|
7 |
-
import torch.nn as nn
|
8 |
-
from .fc import FC_CLASS_REGISTRY
|
9 |
-
try:
|
10 |
-
import transformer_engine.pytorch as te
|
11 |
-
except:
|
12 |
-
te = None
|
13 |
-
log = logging.getLogger(__name__)
|
14 |
-
_FFN_ACT_FN_DEFAULT = {'name': 'gelu', 'approximate': 'none'}
|
15 |
-
|
16 |
-
def resolve_ffn_act_fn(config: Optional[dict]=None) -> Callable[[torch.Tensor], torch.Tensor]:
|
17 |
-
"""Resolve the activation function for the feed-forward network.
|
18 |
-
|
19 |
-
Args:
|
20 |
-
config (Optional[dict]): The configuration dictionary for the activation function.
|
21 |
-
The dict config must specify the 'name' of a torch.nn.functional activation
|
22 |
-
function. All of other key values pairs are bound to the function as a partial.
|
23 |
-
|
24 |
-
Returns:
|
25 |
-
Callable[[torch.Tensor], torch.Tensor]: The activation function.
|
26 |
-
"""
|
27 |
-
if config is None:
|
28 |
-
config = _FFN_ACT_FN_DEFAULT
|
29 |
-
config = deepcopy(config)
|
30 |
-
name = config.pop('name')
|
31 |
-
if not hasattr(torch.nn.functional, name):
|
32 |
-
raise ValueError(f'Unrecognised activation function name ({name}).')
|
33 |
-
act = getattr(torch.nn.functional, name)
|
34 |
-
return partial(act, **config)
|
35 |
-
_DEFAULT_ACT_FN = resolve_ffn_act_fn(_FFN_ACT_FN_DEFAULT)
|
36 |
-
|
37 |
-
def resolve_ffn_hidden_size(d_model: int, expansion_ratio: Union[int, float], ffn_hidden_size: Optional[int]=None) -> int:
|
38 |
-
"""Resolve the hidden size of the feed-forward network.
|
39 |
-
|
40 |
-
Args:
|
41 |
-
d_model (int): The dimension of the input and output of the feed-forward network.
|
42 |
-
expansion_ratio (Union[int, float]): The expansion ratio of the feed-forward network.
|
43 |
-
ffn_hidden_size (Optional[int]): The hidden size of the feed-forward network.
|
44 |
-
|
45 |
-
Returns:
|
46 |
-
int: The hidden size of the feed-forward network.
|
47 |
-
"""
|
48 |
-
if ffn_hidden_size is not None:
|
49 |
-
log.info(f'`expansion_ratio` (={expansion_ratio}) ignored when `ffn_hidden_size` (={ffn_hidden_size}) is specified.')
|
50 |
-
else:
|
51 |
-
ffn_hidden_size = int(d_model * expansion_ratio)
|
52 |
-
if ffn_hidden_size != d_model * expansion_ratio:
|
53 |
-
raise ValueError(f'`d_model * expansion_ratio` must be an integer (d_model={d_model!r}; expansion_ratio={expansion_ratio!r}; d_model * expansion_ratio={d_model * expansion_ratio!r}).')
|
54 |
-
return ffn_hidden_size
|
55 |
-
|
56 |
-
class MPTMLP(nn.Module):
|
57 |
-
|
58 |
-
def __init__(self, d_model: int, expansion_ratio: Union[int, float], fc_type: str='torch', ffn_hidden_size: Optional[int]=None, act_fn: Callable[[torch.Tensor], torch.Tensor]=_DEFAULT_ACT_FN, device: Optional[str]=None, bias: bool=True):
|
59 |
-
super().__init__()
|
60 |
-
ffn_hidden_size = resolve_ffn_hidden_size(d_model, expansion_ratio, ffn_hidden_size)
|
61 |
-
self.fc_kwargs: dict[str, Any] = {'bias': bias}
|
62 |
-
if fc_type != 'te':
|
63 |
-
self.fc_kwargs['device'] = device
|
64 |
-
self.up_proj = FC_CLASS_REGISTRY[fc_type](d_model, ffn_hidden_size, **self.fc_kwargs)
|
65 |
-
self.act = act_fn
|
66 |
-
self.down_proj = FC_CLASS_REGISTRY[fc_type](ffn_hidden_size, d_model, **self.fc_kwargs)
|
67 |
-
self.down_proj._is_residual = True
|
68 |
-
|
69 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
70 |
-
return self.down_proj(self.act(self.up_proj(x)))
|
71 |
-
|
72 |
-
class MPTGLU(MPTMLP):
|
73 |
-
|
74 |
-
def __init__(self, d_model: int, expansion_ratio: Union[int, float], fc_type: str='torch', ffn_hidden_size: Optional[int]=None, act_fn: Callable[[torch.Tensor], torch.Tensor]=_DEFAULT_ACT_FN, device: Optional[str]=None, bias: bool=True):
|
75 |
-
super().__init__(d_model=d_model, expansion_ratio=expansion_ratio, fc_type=fc_type, ffn_hidden_size=ffn_hidden_size, act_fn=act_fn, device=device, bias=bias)
|
76 |
-
self.gate_proj = FC_CLASS_REGISTRY[fc_type](d_model, self.up_proj.out_features, **self.fc_kwargs)
|
77 |
-
|
78 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
79 |
-
return self.down_proj(self.act(self.gate_proj(x)) * self.up_proj(x))
|
80 |
-
FFN_CLASS_REGISTRY = {'mptmlp': MPTMLP, 'mptglu': MPTGLU}
|
81 |
-
if te is not None:
|
82 |
-
te.LayerNormMLP._has_norm = True
|
83 |
-
FFN_CLASS_REGISTRY['te_ln_mlp'] = te.LayerNormMLP
|
84 |
-
|
85 |
-
def build_ffn(d_model: int, expansion_ratio: Union[int, float], fc_type: str='torch', ffn_hidden_size: Optional[int]=None, ffn_act_fn: Optional[dict]=None, device: Optional[str]=None, bias: bool=True, **kwargs: Any) -> nn.Module:
|
86 |
-
ffn_type = kwargs.pop('ffn_type')
|
87 |
-
if ffn_type in ['mptmlp', 'mptglu']:
|
88 |
-
if len(kwargs) > 0:
|
89 |
-
raise ValueError(f'MPTMLP (or MPTGLU) got an unexpected keyword argument: {kwargs}')
|
90 |
-
return FFN_CLASS_REGISTRY[ffn_type](d_model=d_model, expansion_ratio=expansion_ratio, fc_type=fc_type, act_fn=resolve_ffn_act_fn(ffn_act_fn), ffn_hidden_size=ffn_hidden_size, device=device, bias=bias)
|
91 |
-
elif ffn_type == 'te_ln_mlp':
|
92 |
-
assert te is not None
|
93 |
-
ffn_hidden_size = resolve_ffn_hidden_size(d_model, expansion_ratio, ffn_hidden_size)
|
94 |
-
if ffn_act_fn is not None:
|
95 |
-
raise ValueError(f'Transformer Engine block does not support custom activation functions.')
|
96 |
-
return te.LayerNormMLP(hidden_size=d_model, ffn_hidden_size=ffn_hidden_size, bias=bias, **kwargs)
|
97 |
-
raise ValueError(f'ffn_type={ffn_type!r} not recognized.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
hf_prefixlm_converter.py
CHANGED
@@ -6,13 +6,23 @@ Causal LM to convert it to a Prefix LM.
|
|
6 |
Prefix LMs accepts a `bidirectional_mask` input in `forward`
|
7 |
and treat the input prompt as the prefix in `generate`.
|
8 |
"""
|
|
|
|
|
9 |
from types import MethodType
|
10 |
-
from typing import Any,
|
11 |
import torch
|
|
|
|
|
|
|
|
|
12 |
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
|
13 |
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
|
14 |
from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
|
15 |
from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
|
|
|
|
|
|
|
|
|
16 |
_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
|
17 |
CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
|
18 |
|
@@ -80,14 +90,13 @@ def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_T
|
|
80 |
bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
|
81 |
bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
|
82 |
for attn_module in attn_modules:
|
83 |
-
assert isinstance(attn_module.bias, torch.Tensor)
|
84 |
attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
|
85 |
output = call_og_forward()
|
86 |
for attn_module in attn_modules:
|
87 |
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
88 |
return output
|
89 |
|
90 |
-
def generate(self: CAUSAL_GPT_TYPES, *args:
|
91 |
"""Wraps original generate to enable PrefixLM attention."""
|
92 |
attn_modules = _get_attn_modules(model)
|
93 |
for attn_module in attn_modules:
|
@@ -100,8 +109,228 @@ def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_T
|
|
100 |
setattr(model, 'generate', MethodType(generate, model))
|
101 |
setattr(model, '_prefix_lm_converted', True)
|
102 |
return model
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
|
107 |
"""Converts a HuggingFace Causal LM to a Prefix LM.
|
@@ -111,6 +340,8 @@ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES
|
|
111 |
- `GPTNeoForCausalLM`
|
112 |
- `GPTNeoXForCausalLM`
|
113 |
- `GPTJForCausalLM`
|
|
|
|
|
114 |
|
115 |
Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
|
116 |
`generate` method and/or select underlying methods depending on the model class.
|
@@ -160,10 +391,14 @@ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES
|
|
160 |
"""
|
161 |
if isinstance(model, _SUPPORTED_GPT_MODELS):
|
162 |
return _convert_gpt_causal_lm_to_prefix_lm(model)
|
|
|
|
|
|
|
|
|
163 |
else:
|
164 |
raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
|
165 |
|
166 |
-
def add_bidirectional_mask_if_missing(batch:
|
167 |
"""Attempts to add bidirectional_mask to batch if missing.
|
168 |
|
169 |
Raises:
|
|
|
6 |
Prefix LMs accepts a `bidirectional_mask` input in `forward`
|
7 |
and treat the input prompt as the prefix in `generate`.
|
8 |
"""
|
9 |
+
import math
|
10 |
+
import warnings
|
11 |
from types import MethodType
|
12 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
13 |
import torch
|
14 |
+
from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
|
15 |
+
from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
|
16 |
+
from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
|
17 |
+
from transformers.models.bloom.modeling_bloom import logging
|
18 |
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
|
19 |
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
|
20 |
from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
|
21 |
from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
|
22 |
+
from transformers.models.opt.modeling_opt import OPTForCausalLM
|
23 |
+
from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
|
24 |
+
from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
|
27 |
CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
|
28 |
|
|
|
90 |
bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
|
91 |
bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
|
92 |
for attn_module in attn_modules:
|
|
|
93 |
attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
|
94 |
output = call_og_forward()
|
95 |
for attn_module in attn_modules:
|
96 |
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
97 |
return output
|
98 |
|
99 |
+
def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
|
100 |
"""Wraps original generate to enable PrefixLM attention."""
|
101 |
attn_modules = _get_attn_modules(model)
|
102 |
for attn_module in attn_modules:
|
|
|
109 |
setattr(model, 'generate', MethodType(generate, model))
|
110 |
setattr(model, '_prefix_lm_converted', True)
|
111 |
return model
|
112 |
+
|
113 |
+
def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
|
114 |
+
"""Converts a BLOOM Causal LM to a Prefix LM.
|
115 |
+
|
116 |
+
Supported HuggingFace model classes:
|
117 |
+
- `BloomForCausalLM`
|
118 |
+
|
119 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
120 |
+
"""
|
121 |
+
if hasattr(model, '_prefix_lm_converted'):
|
122 |
+
return model
|
123 |
+
assert isinstance(model, BloomForCausalLM)
|
124 |
+
assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
|
125 |
+
|
126 |
+
def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
|
127 |
+
combined_attention_mask = None
|
128 |
+
device = attention_mask.device
|
129 |
+
(_, src_length) = input_shape
|
130 |
+
if src_length > 1:
|
131 |
+
combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
|
132 |
+
if bidirectional_mask is not None:
|
133 |
+
assert attention_mask.shape == bidirectional_mask.shape
|
134 |
+
expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
|
135 |
+
combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
|
136 |
+
expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
|
137 |
+
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
|
138 |
+
return combined_attention_mask
|
139 |
+
|
140 |
+
def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
|
141 |
+
num_heads = self.config.n_head
|
142 |
+
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
|
143 |
+
base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
|
144 |
+
powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
|
145 |
+
slopes = torch.pow(base, powers)
|
146 |
+
if closest_power_of_2 != num_heads:
|
147 |
+
extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
|
148 |
+
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
|
149 |
+
extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
|
150 |
+
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
|
151 |
+
qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
|
152 |
+
ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
|
153 |
+
diffs = qa - ka + key_length - query_length
|
154 |
+
diffs = -diffs.abs()
|
155 |
+
alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
|
156 |
+
alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
|
157 |
+
return alibi.to(dtype)
|
158 |
+
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
159 |
+
|
160 |
+
def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
|
161 |
+
if deprecated_arguments.pop('position_ids', False) is not False:
|
162 |
+
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
|
163 |
+
if len(deprecated_arguments) > 0:
|
164 |
+
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
|
165 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
166 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
167 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
168 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
169 |
+
if input_ids is not None and inputs_embeds is not None:
|
170 |
+
raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
|
171 |
+
elif input_ids is not None:
|
172 |
+
(batch_size, seq_length) = input_ids.shape
|
173 |
+
elif inputs_embeds is not None:
|
174 |
+
(batch_size, seq_length, _) = inputs_embeds.shape
|
175 |
+
else:
|
176 |
+
raise ValueError('You have to specify either input_ids or inputs_embeds')
|
177 |
+
if past_key_values is None:
|
178 |
+
past_key_values = tuple([None] * len(self.h))
|
179 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
180 |
+
if inputs_embeds is None:
|
181 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
182 |
+
hidden_states = self.word_embeddings_layernorm(inputs_embeds)
|
183 |
+
presents = () if use_cache else None
|
184 |
+
all_self_attentions = () if output_attentions else None
|
185 |
+
all_hidden_states = () if output_hidden_states else None
|
186 |
+
seq_length_with_past = seq_length
|
187 |
+
past_key_values_length = 0
|
188 |
+
if past_key_values[0] is not None:
|
189 |
+
tmp = past_key_values[0][0]
|
190 |
+
past_key_values_length = tmp.shape[2]
|
191 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
192 |
+
if attention_mask is None:
|
193 |
+
attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
|
194 |
+
else:
|
195 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
196 |
+
alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
|
197 |
+
causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
|
198 |
+
for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
|
199 |
+
if output_hidden_states:
|
200 |
+
hst = (hidden_states,)
|
201 |
+
all_hidden_states = all_hidden_states + hst
|
202 |
+
if self.gradient_checkpointing and self.training:
|
203 |
+
if use_cache:
|
204 |
+
logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
|
205 |
+
use_cache = False
|
206 |
+
|
207 |
+
def create_custom_forward(module):
|
208 |
+
|
209 |
+
def custom_forward(*inputs):
|
210 |
+
return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
|
211 |
+
return custom_forward
|
212 |
+
outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
|
213 |
+
else:
|
214 |
+
outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
|
215 |
+
hidden_states = outputs[0]
|
216 |
+
if use_cache is True:
|
217 |
+
presents = presents + (outputs[1],)
|
218 |
+
if output_attentions:
|
219 |
+
oa = (outputs[2 if use_cache else 1],)
|
220 |
+
all_self_attentions = all_self_attentions + oa
|
221 |
+
hidden_states = self.ln_f(hidden_states)
|
222 |
+
if output_hidden_states:
|
223 |
+
hst = (hidden_states,)
|
224 |
+
all_hidden_states = all_hidden_states + hst
|
225 |
+
if not return_dict:
|
226 |
+
return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
|
227 |
+
return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
|
228 |
+
setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
|
229 |
+
setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
|
230 |
+
setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
|
231 |
+
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
232 |
+
|
233 |
+
def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
234 |
+
"""Replacement forward method for BloomCausalLM."""
|
235 |
+
if deprecated_arguments.pop('position_ids', False) is not False:
|
236 |
+
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
|
237 |
+
if len(deprecated_arguments) > 0:
|
238 |
+
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
|
239 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
240 |
+
transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
241 |
+
hidden_states = transformer_outputs[0]
|
242 |
+
lm_logits = self.lm_head(hidden_states)
|
243 |
+
loss = None
|
244 |
+
if labels is not None:
|
245 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
246 |
+
shift_labels = labels[..., 1:].contiguous()
|
247 |
+
(batch_size, seq_length, vocab_size) = shift_logits.shape
|
248 |
+
loss_fct = CrossEntropyLoss()
|
249 |
+
loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
|
250 |
+
if not return_dict:
|
251 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
252 |
+
return (loss,) + output if loss is not None else output
|
253 |
+
return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
|
254 |
+
|
255 |
+
def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
|
256 |
+
if past:
|
257 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
258 |
+
bidirectional_mask = None
|
259 |
+
if past[0][0].shape[0] == input_ids.shape[0]:
|
260 |
+
past = self._convert_to_bloom_cache(past)
|
261 |
+
else:
|
262 |
+
bidirectional_mask = torch.ones_like(input_ids)
|
263 |
+
return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
|
264 |
+
setattr(model, 'forward', MethodType(forward, model))
|
265 |
+
setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
|
266 |
+
setattr(model, '_prefix_lm_converted', True)
|
267 |
+
return model
|
268 |
+
|
269 |
+
def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
|
270 |
+
"""Converts an OPT Causal LM to a Prefix LM.
|
271 |
+
|
272 |
+
Supported HuggingFace model classes:
|
273 |
+
- `OPTForCausalLM`
|
274 |
+
|
275 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
276 |
+
"""
|
277 |
+
if hasattr(model, '_prefix_lm_converted'):
|
278 |
+
return model
|
279 |
+
assert isinstance(model, OPTForCausalLM)
|
280 |
+
assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
|
281 |
+
setattr(model, '_original_forward', getattr(model, 'forward'))
|
282 |
+
setattr(model, '_original_generate', getattr(model, 'generate'))
|
283 |
+
model.model.decoder.bidirectional_mask = None
|
284 |
+
|
285 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
286 |
+
combined_attention_mask = None
|
287 |
+
if input_shape[-1] > 1:
|
288 |
+
if self.bidirectional_mask == 'g':
|
289 |
+
(bsz, src_length) = input_shape
|
290 |
+
combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
291 |
+
else:
|
292 |
+
combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
|
293 |
+
if self.bidirectional_mask is not None:
|
294 |
+
assert attention_mask.shape == self.bidirectional_mask.shape
|
295 |
+
expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
|
296 |
+
combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
|
297 |
+
if attention_mask is not None:
|
298 |
+
expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
|
299 |
+
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
300 |
+
return combined_attention_mask
|
301 |
+
setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
|
302 |
+
|
303 |
+
def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
|
304 |
+
|
305 |
+
def call_og_forward():
|
306 |
+
return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
307 |
+
if bidirectional_mask is None:
|
308 |
+
return call_og_forward()
|
309 |
+
self.model.decoder.bidirectional_mask = bidirectional_mask
|
310 |
+
try:
|
311 |
+
outputs = call_og_forward()
|
312 |
+
except:
|
313 |
+
self.model.decoder.bidirectional_mask = None
|
314 |
+
raise
|
315 |
+
self.model.decoder.bidirectional_mask = None
|
316 |
+
return outputs
|
317 |
+
|
318 |
+
def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
|
319 |
+
"""Wraps original generate to enable PrefixLM-style attention."""
|
320 |
+
self.model.decoder.bidirectional_mask = 'g'
|
321 |
+
try:
|
322 |
+
output = self._original_generate(*args, **kwargs)
|
323 |
+
except:
|
324 |
+
self.model.decoder.bidirectional_mask = None
|
325 |
+
raise
|
326 |
+
self.model.decoder.bidirectional_mask = None
|
327 |
+
return output
|
328 |
+
setattr(model, 'forward', MethodType(forward, model))
|
329 |
+
setattr(model, 'generate', MethodType(generate, model))
|
330 |
+
setattr(model, '_prefix_lm_converted', True)
|
331 |
+
return model
|
332 |
+
_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
|
333 |
+
CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
|
334 |
|
335 |
def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
|
336 |
"""Converts a HuggingFace Causal LM to a Prefix LM.
|
|
|
340 |
- `GPTNeoForCausalLM`
|
341 |
- `GPTNeoXForCausalLM`
|
342 |
- `GPTJForCausalLM`
|
343 |
+
- `BloomForCausalLM`
|
344 |
+
- `OPTForCausalLM`
|
345 |
|
346 |
Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
|
347 |
`generate` method and/or select underlying methods depending on the model class.
|
|
|
391 |
"""
|
392 |
if isinstance(model, _SUPPORTED_GPT_MODELS):
|
393 |
return _convert_gpt_causal_lm_to_prefix_lm(model)
|
394 |
+
elif isinstance(model, BloomForCausalLM):
|
395 |
+
return _convert_bloom_causal_lm_to_prefix_lm(model)
|
396 |
+
elif isinstance(model, OPTForCausalLM):
|
397 |
+
return _convert_opt_causal_lm_to_prefix_lm(model)
|
398 |
else:
|
399 |
raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
|
400 |
|
401 |
+
def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
|
402 |
"""Attempts to add bidirectional_mask to batch if missing.
|
403 |
|
404 |
Raises:
|
meta_init_context.py
CHANGED
@@ -1,5 +1,4 @@
|
|
1 |
from contextlib import contextmanager
|
2 |
-
from typing import Any, Callable, Optional
|
3 |
import torch
|
4 |
import torch.nn as nn
|
5 |
|
@@ -58,29 +57,25 @@ def init_on_device(device: torch.device, include_buffers: bool=False):
|
|
58 |
if include_buffers:
|
59 |
old_register_buffer = nn.Module.register_buffer
|
60 |
|
61 |
-
def register_empty_parameter(
|
62 |
-
old_register_parameter(
|
63 |
if param is not None:
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
if tensor is not None:
|
73 |
-
named_buffer = self._buffers[name]
|
74 |
-
assert named_buffer is not None
|
75 |
-
self._buffers[name] = named_buffer.to(device)
|
76 |
if include_buffers:
|
77 |
tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
|
78 |
else:
|
79 |
tensor_constructors_to_patch = {}
|
80 |
|
81 |
-
def patch_tensor_constructor(fn
|
82 |
|
83 |
-
def wrapper(*args
|
84 |
kwargs['device'] = device
|
85 |
return fn(*args, **kwargs)
|
86 |
return wrapper
|
|
|
1 |
from contextlib import contextmanager
|
|
|
2 |
import torch
|
3 |
import torch.nn as nn
|
4 |
|
|
|
57 |
if include_buffers:
|
58 |
old_register_buffer = nn.Module.register_buffer
|
59 |
|
60 |
+
def register_empty_parameter(module, name, param):
|
61 |
+
old_register_parameter(module, name, param)
|
62 |
if param is not None:
|
63 |
+
param_cls = type(module._parameters[name])
|
64 |
+
kwargs = module._parameters[name].__dict__
|
65 |
+
module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
|
66 |
+
|
67 |
+
def register_empty_buffer(module, name, buffer):
|
68 |
+
old_register_buffer(module, name, buffer)
|
69 |
+
if buffer is not None:
|
70 |
+
module._buffers[name] = module._buffers[name].to(device)
|
|
|
|
|
|
|
|
|
71 |
if include_buffers:
|
72 |
tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
|
73 |
else:
|
74 |
tensor_constructors_to_patch = {}
|
75 |
|
76 |
+
def patch_tensor_constructor(fn):
|
77 |
|
78 |
+
def wrapper(*args, **kwargs):
|
79 |
kwargs['device'] = device
|
80 |
return fn(*args, **kwargs)
|
81 |
return wrapper
|
modeling_mpt.py
CHANGED
@@ -2,174 +2,34 @@
|
|
2 |
|
3 |
Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
|
4 |
"""
|
5 |
-
from __future__ import annotations
|
6 |
import math
|
7 |
import warnings
|
8 |
-
from typing import
|
9 |
import torch
|
10 |
import torch.nn as nn
|
11 |
import torch.nn.functional as F
|
12 |
-
from
|
13 |
-
if is_flash_v2_installed():
|
14 |
-
try:
|
15 |
-
from flash_attn import bert_padding
|
16 |
-
from flash_attn.layers.rotary import RotaryEmbedding as DAILRotaryEmbedding
|
17 |
-
except Exception as e:
|
18 |
-
raise e
|
19 |
-
if is_flash_v1_installed():
|
20 |
-
try:
|
21 |
-
from flash_attn import bert_padding
|
22 |
-
except Exception as e:
|
23 |
-
raise e
|
24 |
-
from transformers import PreTrainedModel, PreTrainedTokenizerBase
|
25 |
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
26 |
-
from
|
27 |
-
from transformers.models.llama.modeling_llama import LlamaLinearScalingRotaryEmbedding as HFLinearScalingRotaryEmbedding
|
28 |
-
from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding as HFRotaryEmbedding
|
29 |
-
from .attention import ATTN_CLASS_REGISTRY, attn_bias_shape, build_attn_bias, gen_slopes
|
30 |
from .blocks import MPTBlock
|
31 |
from .custom_embedding import SharedEmbedding
|
32 |
-
from .fc import FC_CLASS_REGISTRY as FC_CLASS_REGISTRY
|
33 |
-
from .ffn import FFN_CLASS_REGISTRY as FFN_CLASS_REGISTRY
|
34 |
-
from .ffn import MPTMLP as MPTMLP
|
35 |
-
from .ffn import build_ffn as build_ffn
|
36 |
from .norm import NORM_CLASS_REGISTRY
|
37 |
from .configuration_mpt import MPTConfig
|
38 |
from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
|
39 |
from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
|
40 |
from .meta_init_context import init_empty_weights
|
41 |
-
from .param_init_fns import
|
42 |
try:
|
43 |
-
from .flash_attn_triton import flash_attn_func
|
44 |
except:
|
45 |
pass
|
46 |
-
|
47 |
-
log = logging.getLogger(__name__)
|
48 |
-
|
49 |
-
def gen_rotary_embedding(rope_head_dim: int, rope_impl: str, rope_theta: int, rope_dail_config: dict, rope_hf_config: dict, max_seq_len: int):
|
50 |
-
if rope_impl == 'dail':
|
51 |
-
return DAILRotaryEmbedding(dim=rope_head_dim, base=rope_theta, interleaved=False, scale_base=rope_dail_config['xpos_scale_base'] if rope_dail_config['type'] == 'xpos' else None, pos_idx_in_fp32=rope_dail_config['pos_idx_in_fp32'], device='cpu')
|
52 |
-
elif rope_impl == 'hf':
|
53 |
-
if rope_hf_config['type'] == 'no_scaling':
|
54 |
-
return HFRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, device='cpu')
|
55 |
-
elif rope_hf_config['type'] == 'linear':
|
56 |
-
return HFLinearScalingRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, scaling_factor=rope_hf_config['factor'], device='cpu')
|
57 |
-
elif rope_hf_config['type'] == 'dynamic':
|
58 |
-
return HFDynamicNTKScalingRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, scaling_factor=rope_hf_config['factor'], device='cpu')
|
59 |
-
raise ValueError('rope_impl needs to be either dail or hf')
|
60 |
-
|
61 |
-
def gen_attention_mask_in_length(sequence_id: Union[None, torch.Tensor], S: int, attn_uses_sequence_id: bool, attn_impl: str, attention_mask: Union[torch.Tensor, None]):
|
62 |
-
"""Generates the attention mask used for sequence masking in FA v2.
|
63 |
-
|
64 |
-
Only supports sequence id based sparse attention for no attention masking or attention masking with right padding.
|
65 |
-
In case of left padding:
|
66 |
-
1. Training with left padding is not supported in MPT (see https://github.com/mosaicml/llm-foundry/blob/1eecd4cb8e734499f77f6a35f657b8b20c0adfcb/llmfoundry/models/mpt/modeling_mpt.py#L407).
|
67 |
-
2. For generation with left padding, we only have a single sequence id per sample, so we don't need sequence id based sparse attention.
|
68 |
-
|
69 |
-
Args:
|
70 |
-
sequence_id (Union[None, torch.Tensor]): Tensor containing the sequence id for each token. Shape (batch_size, seq_len).
|
71 |
-
S (int): Sequence length
|
72 |
-
attn_uses_sequence_id (bool): Whether the attention uses sequence id based masking.
|
73 |
-
attn_impl (str): Attention implementation. This function is only creates attention_mask_in_length for flash attention.
|
74 |
-
attention_mask (Union[torch.Tensor, None]): Attention mask tensor of shape (batch_size, seq_len)
|
75 |
-
|
76 |
-
Returns:
|
77 |
-
attention_mask_in_length: (batch, seqlen), int, a nonzero number (e.g., 1, 2, 3, etc.) means length of concatenated sequence in b-th batch, and 0 means none. For example, if batch = 3 and seqlen = 6, the attention_mask_in_length is:
|
78 |
-
```
|
79 |
-
[
|
80 |
-
[2, 3, 0, 0, 0, 0],
|
81 |
-
[3, 2, 0, 0, 0, 0],
|
82 |
-
[6, 0, 0, 0, 0, 0]
|
83 |
-
]
|
84 |
-
```
|
85 |
-
, which refers to the 3D-attention mask:
|
86 |
-
```
|
87 |
-
[
|
88 |
-
[
|
89 |
-
[1, 0, 0, 0, 0, 0],
|
90 |
-
[1, 1, 0, 0, 0, 0],
|
91 |
-
[0, 0, 1, 0, 0, 0],
|
92 |
-
[0, 0, 1, 1, 0, 0],
|
93 |
-
[0, 0, 1, 1, 1, 0],
|
94 |
-
[0, 0, 0, 0, 0, 1]
|
95 |
-
],
|
96 |
-
[
|
97 |
-
[1, 0, 0, 0, 0, 0],
|
98 |
-
[1, 1, 0, 0, 0, 0],
|
99 |
-
[1, 1, 1, 0, 0, 0],
|
100 |
-
[0, 0, 0, 1, 0, 0],
|
101 |
-
[0, 0, 0, 1, 1, 0],
|
102 |
-
[0, 0, 0, 0, 0, 1]
|
103 |
-
],
|
104 |
-
[
|
105 |
-
[1, 0, 0, 0, 0, 0],
|
106 |
-
[1, 1, 0, 0, 0, 0],
|
107 |
-
[1, 1, 1, 0, 0, 0],
|
108 |
-
[1, 1, 1, 1, 0, 0],
|
109 |
-
[1, 1, 1, 1, 1, 0],
|
110 |
-
[1, 1, 1, 1, 1, 1]
|
111 |
-
]
|
112 |
-
]
|
113 |
-
```.
|
114 |
-
(The description above is taken verbatim from https://github.com/Dao-AILab/flash-attention/blob/9356a1c0389660d7e231ff3163c1ac17d9e3824a/flash_attn/bert_padding.py#L125 .)
|
115 |
-
"""
|
116 |
-
attention_mask_in_length = None
|
117 |
-
if sequence_id is not None and attn_uses_sequence_id and (attn_impl == 'flash'):
|
118 |
-
if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0]:
|
119 |
-
raise NotImplementedError('Left padding is not supported with flash attention when attn_uses_sequence_id is set to True.')
|
120 |
-
if S != sequence_id.shape[-1]:
|
121 |
-
raise ValueError(f'Sequence length ({S}) does not match length of sequences in sequence_id ({sequence_id.shape[-1]}).')
|
122 |
-
if attention_mask is not None:
|
123 |
-
sequence_id = sequence_id.masked_fill(~attention_mask, 0)
|
124 |
-
attention_mask_in_length = torch.nn.functional.one_hot(sequence_id)
|
125 |
-
if attention_mask is not None:
|
126 |
-
attention_mask_in_length = attention_mask_in_length.masked_fill(~attention_mask.unsqueeze(-1), 0)
|
127 |
-
attention_mask_in_length = attention_mask_in_length.sum(dim=1)
|
128 |
-
attention_mask_in_length = torch.nn.functional.pad(attention_mask_in_length, (0, S - attention_mask_in_length.shape[-1]), mode='constant', value=0)
|
129 |
-
return attention_mask_in_length
|
130 |
-
|
131 |
-
def gen_flash_attn_padding_info(bsz: int, S: int, past_key_len: int, device: torch.device, attention_mask_in_length: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None):
|
132 |
-
flash_attn_padding_info = {}
|
133 |
-
if attention_mask_in_length is None:
|
134 |
-
key_padding_mask = attention_mask
|
135 |
-
if key_padding_mask is None:
|
136 |
-
key_padding_mask = torch.ones((bsz, past_key_len + S), dtype=torch.bool, device=device)
|
137 |
-
query_padding_mask = key_padding_mask[:, -S:]
|
138 |
-
unpadding_function = bert_padding.unpad_input
|
139 |
-
else:
|
140 |
-
key_padding_mask = attention_mask_in_length
|
141 |
-
query_padding_mask = attention_mask_in_length
|
142 |
-
unpadding_function = bert_padding.unpad_input_for_concatenated_sequences
|
143 |
-
(_, indices_q, cu_seqlens_q, max_seqlen_q) = unpadding_function(torch.empty(bsz, S, 1, device=device), query_padding_mask)
|
144 |
-
(_, indices_k, cu_seqlens_k, max_seqlen_k) = unpadding_function(torch.empty(bsz, past_key_len + S, 1, device=device), key_padding_mask)
|
145 |
-
(_, indices_v, _, _) = unpadding_function(torch.empty(bsz, past_key_len + S, 1, device=device), key_padding_mask)
|
146 |
-
flash_attn_padding_info['indices_q'] = indices_q
|
147 |
-
flash_attn_padding_info['indices_k'] = indices_k
|
148 |
-
flash_attn_padding_info['indices_v'] = indices_v
|
149 |
-
flash_attn_padding_info['cu_seqlens_q'] = cu_seqlens_q
|
150 |
-
flash_attn_padding_info['cu_seqlens_k'] = cu_seqlens_k
|
151 |
-
flash_attn_padding_info['max_seqlen_q'] = max_seqlen_q
|
152 |
-
flash_attn_padding_info['max_seqlen_k'] = max_seqlen_k
|
153 |
-
return flash_attn_padding_info
|
154 |
-
|
155 |
-
def apply_sequence_id(attn_bias: torch.Tensor, sequence_id: torch.LongTensor, max_seq_len: int) -> torch.Tensor:
|
156 |
-
seq_len = sequence_id.shape[-1]
|
157 |
-
if seq_len > max_seq_len:
|
158 |
-
raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={max_seq_len}')
|
159 |
-
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
160 |
-
cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
|
161 |
-
min_val = torch.finfo(attn_bias.dtype).min
|
162 |
-
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
163 |
-
return attn_bias
|
164 |
|
165 |
class MPTPreTrainedModel(PreTrainedModel):
|
166 |
config_class = MPTConfig
|
167 |
base_model_prefix = 'model'
|
168 |
_no_split_modules = ['MPTBlock']
|
169 |
|
170 |
-
def _fsdp_wrap_fn(self: Union[MPTModel, MPTForCausalLM], module: nn.Module) -> bool:
|
171 |
-
return isinstance(module, MPTBlock)
|
172 |
-
|
173 |
class MPTModel(MPTPreTrainedModel):
|
174 |
|
175 |
def __init__(self, config: MPTConfig):
|
@@ -180,30 +40,19 @@ class MPTModel(MPTPreTrainedModel):
|
|
180 |
self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
|
181 |
self.alibi = config.attn_config['alibi']
|
182 |
self.alibi_bias_max = config.attn_config['alibi_bias_max']
|
183 |
-
self.learned_pos_emb = config.learned_pos_emb
|
184 |
-
if config.init_device == 'mixed':
|
185 |
-
if dist.get_local_rank() == 0:
|
186 |
-
config.init_device = 'cpu'
|
187 |
-
else:
|
188 |
-
config.init_device = 'meta'
|
189 |
if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
|
190 |
norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
|
191 |
raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
|
192 |
norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
|
193 |
self.embedding_fraction = config.embedding_fraction
|
194 |
self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
|
195 |
-
if self.
|
196 |
-
self.wpe =
|
197 |
self.emb_drop = nn.Dropout(config.emb_pdrop)
|
198 |
self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
|
199 |
self.norm_f = norm_class(config.d_model, device=config.init_device)
|
200 |
-
self.rope = config.attn_config['rope']
|
201 |
-
self.rope_impl = None
|
202 |
-
if self.rope:
|
203 |
-
self.rope_impl = config.attn_config['rope_impl']
|
204 |
-
self.rotary_embedding = gen_rotary_embedding(rope_head_dim=config.d_model // config.n_heads, rope_impl=self.rope_impl, rope_theta=config.attn_config['rope_theta'], rope_dail_config=config.attn_config['rope_dail_config'], rope_hf_config=config.attn_config['rope_hf_config'], max_seq_len=self.config.max_seq_len)
|
205 |
if config.init_device != 'meta':
|
206 |
-
|
207 |
self.apply(self.param_init_fn)
|
208 |
self.is_causal = not self.prefix_lm
|
209 |
self._attn_bias_initialized = False
|
@@ -212,22 +61,25 @@ class MPTModel(MPTPreTrainedModel):
|
|
212 |
if config.no_bias:
|
213 |
for module in self.modules():
|
214 |
if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
|
215 |
-
|
|
|
216 |
module.register_parameter('bias', None)
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
|
|
|
|
224 |
return self.wte
|
225 |
|
226 |
-
def set_input_embeddings(self, value
|
227 |
self.wte = value
|
228 |
|
229 |
@torch.no_grad()
|
230 |
-
def _attn_bias(self, device
|
231 |
if not self._attn_bias_initialized:
|
232 |
if self.attn_bias_shape:
|
233 |
self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
|
@@ -244,7 +96,7 @@ class MPTModel(MPTPreTrainedModel):
|
|
244 |
attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
|
245 |
if self.attn_uses_sequence_id and sequence_id is not None:
|
246 |
assert isinstance(attn_bias, torch.Tensor)
|
247 |
-
attn_bias =
|
248 |
if attention_mask is not None:
|
249 |
s_k = attention_mask.shape[-1]
|
250 |
if attn_bias is None:
|
@@ -256,9 +108,9 @@ class MPTModel(MPTPreTrainedModel):
|
|
256 |
raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
|
257 |
min_val = torch.finfo(attn_bias.dtype).min
|
258 |
attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
|
259 |
-
return (attn_bias,
|
260 |
|
261 |
-
def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor)
|
262 |
(s_k, s_q) = attn_bias.shape[-2:]
|
263 |
if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
|
264 |
raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
|
@@ -273,7 +125,17 @@ class MPTModel(MPTPreTrainedModel):
|
|
273 |
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
274 |
return attn_bias
|
275 |
|
276 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
278 |
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
279 |
if attention_mask is not None:
|
@@ -285,7 +147,7 @@ class MPTModel(MPTPreTrainedModel):
|
|
285 |
if output_attentions:
|
286 |
if self.attn_impl != 'torch':
|
287 |
raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
|
288 |
-
if
|
289 |
raise NotImplementedError('MPT does not support training with left padding.')
|
290 |
if self.prefix_lm and prefix_mask is None:
|
291 |
raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
|
@@ -294,42 +156,26 @@ class MPTModel(MPTPreTrainedModel):
|
|
294 |
raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
|
295 |
elif self.attn_uses_sequence_id is False and sequence_id is not None:
|
296 |
warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
|
297 |
-
|
298 |
-
raise ValueError('You cannot specify both input_ids and inputs_embeds.')
|
299 |
-
elif input_ids is not None:
|
300 |
-
bsz = input_ids.size(0)
|
301 |
-
S = input_ids.size(1)
|
302 |
-
x = self.wte(input_ids)
|
303 |
-
input_device = input_ids.device
|
304 |
-
elif inputs_embeds is not None:
|
305 |
-
bsz = inputs_embeds.size(0)
|
306 |
-
S = inputs_embeds.size(1)
|
307 |
-
x = inputs_embeds
|
308 |
-
input_device = inputs_embeds.device
|
309 |
-
else:
|
310 |
-
raise ValueError('You must specify input_ids or inputs_embeds')
|
311 |
assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
if
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': pos, 'seq_len': S + past_position}
|
331 |
-
elif self.rope and self.rope_impl == 'dail':
|
332 |
-
rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': past_position, 'seq_len': S + past_position}
|
333 |
if self.embedding_fraction == 1:
|
334 |
x = self.emb_drop(x)
|
335 |
else:
|
@@ -337,26 +183,18 @@ class MPTModel(MPTPreTrainedModel):
|
|
337 |
assert isinstance(self.emb_drop, nn.Module)
|
338 |
x = self.emb_drop(x_shrunk)
|
339 |
(attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
|
340 |
-
attention_mask_in_length = gen_attention_mask_in_length(sequence_id=sequence_id, S=S, attn_uses_sequence_id=self.attn_uses_sequence_id, attn_impl=self.attn_impl, attention_mask=attention_mask)
|
341 |
-
alibi_slopes = None
|
342 |
-
if self.alibi and self.attn_impl == 'flash':
|
343 |
-
alibi_slopes = gen_slopes(n_heads=self.config.n_heads, alibi_bias_max=self.alibi_bias_max, device=x.device, return_1d=True)
|
344 |
-
presents = () if use_cache else None
|
345 |
if use_cache and past_key_values is None:
|
346 |
past_key_values = [() for _ in range(self.config.n_layers)]
|
347 |
all_hidden_states = () if output_hidden_states else None
|
348 |
all_self_attns = () if output_attentions else None
|
349 |
-
flash_attn_padding_info = {}
|
350 |
-
if self.attn_impl == 'flash':
|
351 |
-
flash_attn_padding_info = gen_flash_attn_padding_info(bsz, S, past_position, x.device, attention_mask_in_length, attention_mask)
|
352 |
for (b_idx, block) in enumerate(self.blocks):
|
353 |
if output_hidden_states:
|
354 |
assert all_hidden_states is not None
|
355 |
all_hidden_states = all_hidden_states + (x,)
|
356 |
past_key_value = past_key_values[b_idx] if past_key_values is not None else None
|
357 |
-
(x, attn_weights,
|
358 |
-
if
|
359 |
-
|
360 |
if output_attentions:
|
361 |
assert all_self_attns is not None
|
362 |
all_self_attns = all_self_attns + (attn_weights,)
|
@@ -364,33 +202,25 @@ class MPTModel(MPTPreTrainedModel):
|
|
364 |
if output_hidden_states:
|
365 |
assert all_hidden_states is not None
|
366 |
all_hidden_states = all_hidden_states + (x,)
|
367 |
-
return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=
|
368 |
|
369 |
-
def param_init_fn(self, module
|
370 |
init_fn_name = self.config.init_config['name']
|
371 |
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
372 |
|
373 |
-
def fsdp_wrap_fn(self, module
|
374 |
-
return
|
375 |
|
376 |
-
def activation_checkpointing_fn(self, module
|
377 |
return isinstance(module, MPTBlock)
|
378 |
|
379 |
class MPTForCausalLM(MPTPreTrainedModel):
|
380 |
|
381 |
def __init__(self, config: MPTConfig):
|
382 |
super().__init__(config)
|
383 |
-
log.info(f'Instantiating an MPTForCausalLM model from {__file__}')
|
384 |
-
self.transformer: MPTModel = MPTModel(config)
|
385 |
-
self.lm_head = None
|
386 |
if not config.tie_word_embeddings:
|
387 |
-
|
388 |
-
|
389 |
-
for child in self.transformer.children():
|
390 |
-
if isinstance(child, torch.nn.ModuleList):
|
391 |
-
continue
|
392 |
-
if isinstance(child, torch.nn.Module):
|
393 |
-
child._fsdp_wrap = True
|
394 |
self.logit_scale = None
|
395 |
if config.logit_scale is not None:
|
396 |
logit_scale = config.logit_scale
|
@@ -401,89 +231,53 @@ class MPTForCausalLM(MPTPreTrainedModel):
|
|
401 |
raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
402 |
self.logit_scale = logit_scale
|
403 |
|
404 |
-
def get_input_embeddings(self)
|
405 |
-
return self.transformer.
|
406 |
|
407 |
-
def set_input_embeddings(self, value
|
408 |
-
self.transformer.
|
409 |
|
410 |
-
def get_output_embeddings(self)
|
411 |
-
|
412 |
-
return self.lm_head
|
413 |
-
return self.transformer.get_input_embeddings()
|
414 |
|
415 |
-
def set_output_embeddings(self, new_embeddings
|
416 |
-
|
417 |
-
self.lm_head = new_embeddings
|
418 |
-
else:
|
419 |
-
if not isinstance(new_embeddings, (SharedEmbedding, nn.Embedding)):
|
420 |
-
raise ValueError('new_embeddings must be an instance of SharedEmbedding ' + f'or nn.Embedding, but got {type(new_embeddings)}.')
|
421 |
-
warnings.warn('Using `set_output_embeddings` to set the embedding layer of ' + 'MPTForCausalLM with tied weights. Given weights are tied, ' + 'using `set_input_embeddings` is recommended over using ' + '`set_output_embeddings`.')
|
422 |
-
self.transformer.set_input_embeddings(new_embeddings)
|
423 |
-
|
424 |
-
def tie_weights(self) -> None:
|
425 |
-
self.lm_head = None
|
426 |
|
427 |
-
def set_decoder(self, decoder
|
428 |
self.transformer = decoder
|
429 |
|
430 |
-
def get_decoder(self)
|
431 |
return self.transformer
|
432 |
|
433 |
-
def forward(self, input_ids:
|
434 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
435 |
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
436 |
-
outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache
|
437 |
-
|
438 |
-
logits = self.lm_head(outputs.last_hidden_state)
|
439 |
-
else:
|
440 |
-
out = outputs.last_hidden_state
|
441 |
-
out = out.to(self.transformer.wte.weight.device)
|
442 |
-
logits = self.transformer.wte(out, True)
|
443 |
if self.logit_scale is not None:
|
444 |
if self.logit_scale == 0:
|
445 |
warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
|
446 |
logits *= self.logit_scale
|
447 |
loss = None
|
448 |
if labels is not None:
|
449 |
-
|
450 |
-
|
451 |
-
loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
|
452 |
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
453 |
|
454 |
-
def param_init_fn(self, module
|
455 |
init_fn_name = self.config.init_config['name']
|
456 |
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
457 |
|
458 |
-
def fsdp_wrap_fn(self, module
|
459 |
-
return
|
460 |
|
461 |
-
def activation_checkpointing_fn(self, module
|
462 |
-
|
463 |
-
if isinstance(act_ckpt_list, str):
|
464 |
-
act_ckpt_list = [act_ckpt_list]
|
465 |
-
elif not isinstance(act_ckpt_list, list):
|
466 |
-
raise ValueError(f'activation_checkpointing_target must be either a single string or a list, but got {type(act_ckpt_list)}')
|
467 |
-
if 'MPTBlock' in act_ckpt_list or 'mptblock' in act_ckpt_list:
|
468 |
-
if len(act_ckpt_list) > 1:
|
469 |
-
log.info('Activation checkpointing MPTBlock only (ignoring other sub-block modules specified in activation_checkpointing_target).')
|
470 |
-
return isinstance(module, MPTBlock)
|
471 |
-
mod_types = ()
|
472 |
-
for mod_name in act_ckpt_list:
|
473 |
-
if mod_name.lower() == 'mptblock':
|
474 |
-
mod_types += (MPTBlock,)
|
475 |
-
elif mod_name in ATTN_CLASS_REGISTRY:
|
476 |
-
mod_types += (ATTN_CLASS_REGISTRY[mod_name],)
|
477 |
-
elif mod_name in FFN_CLASS_REGISTRY:
|
478 |
-
mod_types += (FFN_CLASS_REGISTRY[mod_name],)
|
479 |
-
elif mod_name in NORM_CLASS_REGISTRY:
|
480 |
-
mod_types += (NORM_CLASS_REGISTRY[mod_name],)
|
481 |
-
else:
|
482 |
-
msg = ', '.join(list(ATTN_CLASS_REGISTRY.keys()) + list(FFN_CLASS_REGISTRY.keys()) + list(NORM_CLASS_REGISTRY.keys()) + ['MPTBlock'])
|
483 |
-
raise ValueError(f'{mod_name} (specified in activation_checkpointing_target) is not a recognized option out of available options {msg}.')
|
484 |
-
return isinstance(module, mod_types)
|
485 |
|
486 |
-
def prepare_inputs_for_generation(self, input_ids
|
|
|
|
|
487 |
attention_mask = kwargs['attention_mask'].bool()
|
488 |
if attention_mask[:, -1].sum() != attention_mask.shape[0]:
|
489 |
raise NotImplementedError('MPT does not support generation with right padding.')
|
@@ -499,15 +293,10 @@ class MPTForCausalLM(MPTPreTrainedModel):
|
|
499 |
raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
|
500 |
else:
|
501 |
prefix_mask = None
|
502 |
-
|
503 |
-
model_inputs = {'inputs_embeds': inputs_embeds}
|
504 |
-
else:
|
505 |
-
model_inputs = {'input_ids': input_ids}
|
506 |
-
model_inputs.update({'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)})
|
507 |
-
return model_inputs
|
508 |
|
509 |
@staticmethod
|
510 |
-
def _reorder_cache(past_key_values
|
511 |
"""Used by HuggingFace generate when using beam search with kv-caching.
|
512 |
|
513 |
See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
|
|
|
2 |
|
3 |
Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
|
4 |
"""
|
|
|
5 |
import math
|
6 |
import warnings
|
7 |
+
from typing import List, Optional, Tuple, Union
|
8 |
import torch
|
9 |
import torch.nn as nn
|
10 |
import torch.nn.functional as F
|
11 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
13 |
+
from .attention import attn_bias_shape, build_attn_bias
|
|
|
|
|
|
|
14 |
from .blocks import MPTBlock
|
15 |
from .custom_embedding import SharedEmbedding
|
|
|
|
|
|
|
|
|
16 |
from .norm import NORM_CLASS_REGISTRY
|
17 |
from .configuration_mpt import MPTConfig
|
18 |
from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
|
19 |
from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
|
20 |
from .meta_init_context import init_empty_weights
|
21 |
+
from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
|
22 |
try:
|
23 |
+
from .flash_attn_triton import flash_attn_func
|
24 |
except:
|
25 |
pass
|
26 |
+
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
class MPTPreTrainedModel(PreTrainedModel):
|
29 |
config_class = MPTConfig
|
30 |
base_model_prefix = 'model'
|
31 |
_no_split_modules = ['MPTBlock']
|
32 |
|
|
|
|
|
|
|
33 |
class MPTModel(MPTPreTrainedModel):
|
34 |
|
35 |
def __init__(self, config: MPTConfig):
|
|
|
40 |
self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
|
41 |
self.alibi = config.attn_config['alibi']
|
42 |
self.alibi_bias_max = config.attn_config['alibi_bias_max']
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
|
44 |
norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
|
45 |
raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
|
46 |
norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
|
47 |
self.embedding_fraction = config.embedding_fraction
|
48 |
self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
|
49 |
+
if not self.alibi:
|
50 |
+
self.wpe = nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
|
51 |
self.emb_drop = nn.Dropout(config.emb_pdrop)
|
52 |
self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
|
53 |
self.norm_f = norm_class(config.d_model, device=config.init_device)
|
|
|
|
|
|
|
|
|
|
|
54 |
if config.init_device != 'meta':
|
55 |
+
print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.')
|
56 |
self.apply(self.param_init_fn)
|
57 |
self.is_causal = not self.prefix_lm
|
58 |
self._attn_bias_initialized = False
|
|
|
61 |
if config.no_bias:
|
62 |
for module in self.modules():
|
63 |
if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
|
64 |
+
if config.verbose:
|
65 |
+
warnings.warn(f'Removing bias ({module.bias}) from {module}.')
|
66 |
module.register_parameter('bias', None)
|
67 |
+
if config.verbose and config.verbose > 2:
|
68 |
+
print(self)
|
69 |
+
if 'verbose' not in self.config.init_config:
|
70 |
+
self.config.init_config['verbose'] = self.config.verbose
|
71 |
+
if self.config.init_config['verbose'] > 1:
|
72 |
+
init_fn_name = self.config.init_config['name']
|
73 |
+
warnings.warn(f'Using {init_fn_name} initialization.')
|
74 |
+
|
75 |
+
def get_input_embeddings(self):
|
76 |
return self.wte
|
77 |
|
78 |
+
def set_input_embeddings(self, value):
|
79 |
self.wte = value
|
80 |
|
81 |
@torch.no_grad()
|
82 |
+
def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None):
|
83 |
if not self._attn_bias_initialized:
|
84 |
if self.attn_bias_shape:
|
85 |
self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
|
|
|
96 |
attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
|
97 |
if self.attn_uses_sequence_id and sequence_id is not None:
|
98 |
assert isinstance(attn_bias, torch.Tensor)
|
99 |
+
attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
|
100 |
if attention_mask is not None:
|
101 |
s_k = attention_mask.shape[-1]
|
102 |
if attn_bias is None:
|
|
|
108 |
raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
|
109 |
min_val = torch.finfo(attn_bias.dtype).min
|
110 |
attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
|
111 |
+
return (attn_bias, None)
|
112 |
|
113 |
+
def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):
|
114 |
(s_k, s_q) = attn_bias.shape[-2:]
|
115 |
if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
|
116 |
raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
|
|
|
125 |
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
126 |
return attn_bias
|
127 |
|
128 |
+
def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor):
|
129 |
+
seq_len = sequence_id.shape[-1]
|
130 |
+
if seq_len > self.config.max_seq_len:
|
131 |
+
raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
|
132 |
+
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
133 |
+
cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
|
134 |
+
min_val = torch.finfo(attn_bias.dtype).min
|
135 |
+
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
136 |
+
return attn_bias
|
137 |
+
|
138 |
+
def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None):
|
139 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
140 |
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
141 |
if attention_mask is not None:
|
|
|
147 |
if output_attentions:
|
148 |
if self.attn_impl != 'torch':
|
149 |
raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
|
150 |
+
if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training:
|
151 |
raise NotImplementedError('MPT does not support training with left padding.')
|
152 |
if self.prefix_lm and prefix_mask is None:
|
153 |
raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
|
|
|
156 |
raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
|
157 |
elif self.attn_uses_sequence_id is False and sequence_id is not None:
|
158 |
warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
|
159 |
+
S = input_ids.size(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
|
161 |
+
tok_emb = self.wte(input_ids)
|
162 |
+
if self.alibi:
|
163 |
+
x = tok_emb
|
164 |
+
else:
|
165 |
+
past_position = 0
|
166 |
+
if past_key_values is not None:
|
167 |
+
if len(past_key_values) != self.config.n_layers:
|
168 |
+
raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).')
|
169 |
+
past_position = past_key_values[0][0].size(1)
|
170 |
+
if self.attn_impl == 'torch':
|
171 |
+
past_position = past_key_values[0][0].size(3)
|
172 |
+
if S + past_position > self.config.max_seq_len:
|
173 |
+
raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
|
174 |
+
pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)
|
175 |
+
if attention_mask is not None:
|
176 |
+
pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
|
177 |
+
pos_emb = self.wpe(pos)
|
178 |
+
x = tok_emb + pos_emb
|
|
|
|
|
|
|
179 |
if self.embedding_fraction == 1:
|
180 |
x = self.emb_drop(x)
|
181 |
else:
|
|
|
183 |
assert isinstance(self.emb_drop, nn.Module)
|
184 |
x = self.emb_drop(x_shrunk)
|
185 |
(attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
|
|
|
|
|
|
|
|
|
|
|
186 |
if use_cache and past_key_values is None:
|
187 |
past_key_values = [() for _ in range(self.config.n_layers)]
|
188 |
all_hidden_states = () if output_hidden_states else None
|
189 |
all_self_attns = () if output_attentions else None
|
|
|
|
|
|
|
190 |
for (b_idx, block) in enumerate(self.blocks):
|
191 |
if output_hidden_states:
|
192 |
assert all_hidden_states is not None
|
193 |
all_hidden_states = all_hidden_states + (x,)
|
194 |
past_key_value = past_key_values[b_idx] if past_key_values is not None else None
|
195 |
+
(x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)
|
196 |
+
if past_key_values is not None:
|
197 |
+
past_key_values[b_idx] = past_key_value
|
198 |
if output_attentions:
|
199 |
assert all_self_attns is not None
|
200 |
all_self_attns = all_self_attns + (attn_weights,)
|
|
|
202 |
if output_hidden_states:
|
203 |
assert all_hidden_states is not None
|
204 |
all_hidden_states = all_hidden_states + (x,)
|
205 |
+
return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns)
|
206 |
|
207 |
+
def param_init_fn(self, module):
|
208 |
init_fn_name = self.config.init_config['name']
|
209 |
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
210 |
|
211 |
+
def fsdp_wrap_fn(self, module):
|
212 |
+
return isinstance(module, MPTBlock)
|
213 |
|
214 |
+
def activation_checkpointing_fn(self, module):
|
215 |
return isinstance(module, MPTBlock)
|
216 |
|
217 |
class MPTForCausalLM(MPTPreTrainedModel):
|
218 |
|
219 |
def __init__(self, config: MPTConfig):
|
220 |
super().__init__(config)
|
|
|
|
|
|
|
221 |
if not config.tie_word_embeddings:
|
222 |
+
raise ValueError('MPTForCausalLM only supports tied word embeddings')
|
223 |
+
self.transformer = MPTModel(config)
|
|
|
|
|
|
|
|
|
|
|
224 |
self.logit_scale = None
|
225 |
if config.logit_scale is not None:
|
226 |
logit_scale = config.logit_scale
|
|
|
231 |
raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
232 |
self.logit_scale = logit_scale
|
233 |
|
234 |
+
def get_input_embeddings(self):
|
235 |
+
return self.transformer.wte
|
236 |
|
237 |
+
def set_input_embeddings(self, value):
|
238 |
+
self.transformer.wte = value
|
239 |
|
240 |
+
def get_output_embeddings(self):
|
241 |
+
return self.transformer.wte
|
|
|
|
|
242 |
|
243 |
+
def set_output_embeddings(self, new_embeddings):
|
244 |
+
self.transformer.wte = new_embeddings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
245 |
|
246 |
+
def set_decoder(self, decoder):
|
247 |
self.transformer = decoder
|
248 |
|
249 |
+
def get_decoder(self):
|
250 |
return self.transformer
|
251 |
|
252 |
+
def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None):
|
253 |
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
254 |
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
255 |
+
outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
|
256 |
+
logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True)
|
|
|
|
|
|
|
|
|
|
|
257 |
if self.logit_scale is not None:
|
258 |
if self.logit_scale == 0:
|
259 |
warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
|
260 |
logits *= self.logit_scale
|
261 |
loss = None
|
262 |
if labels is not None:
|
263 |
+
labels = torch.roll(labels, shifts=-1)
|
264 |
+
labels[:, -1] = -100
|
265 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
|
266 |
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
267 |
|
268 |
+
def param_init_fn(self, module):
|
269 |
init_fn_name = self.config.init_config['name']
|
270 |
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
271 |
|
272 |
+
def fsdp_wrap_fn(self, module):
|
273 |
+
return isinstance(module, MPTBlock)
|
274 |
|
275 |
+
def activation_checkpointing_fn(self, module):
|
276 |
+
return isinstance(module, MPTBlock)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
|
278 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
|
279 |
+
if inputs_embeds is not None:
|
280 |
+
raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
|
281 |
attention_mask = kwargs['attention_mask'].bool()
|
282 |
if attention_mask[:, -1].sum() != attention_mask.shape[0]:
|
283 |
raise NotImplementedError('MPT does not support generation with right padding.')
|
|
|
293 |
raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
|
294 |
else:
|
295 |
prefix_mask = None
|
296 |
+
return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)}
|
|
|
|
|
|
|
|
|
|
|
297 |
|
298 |
@staticmethod
|
299 |
+
def _reorder_cache(past_key_values, beam_idx):
|
300 |
"""Used by HuggingFace generate when using beam search with kv-caching.
|
301 |
|
302 |
See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
|
norm.py
CHANGED
@@ -1,7 +1,6 @@
|
|
1 |
-
from typing import Dict, List, Optional, Type, Union
|
2 |
import torch
|
3 |
|
4 |
-
def _cast_if_autocast_enabled(tensor
|
5 |
if torch.is_autocast_enabled():
|
6 |
if tensor.device.type == 'cuda':
|
7 |
dtype = torch.get_autocast_gpu_dtype()
|
@@ -14,10 +13,10 @@ def _cast_if_autocast_enabled(tensor: torch.Tensor) -> torch.Tensor:
|
|
14 |
|
15 |
class LPLayerNorm(torch.nn.LayerNorm):
|
16 |
|
17 |
-
def __init__(self, normalized_shape
|
18 |
super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype)
|
19 |
|
20 |
-
def forward(self, x
|
21 |
module_device = x.device
|
22 |
downcast_x = _cast_if_autocast_enabled(x)
|
23 |
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
@@ -25,15 +24,15 @@ class LPLayerNorm(torch.nn.LayerNorm):
|
|
25 |
with torch.autocast(enabled=False, device_type=module_device.type):
|
26 |
return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps)
|
27 |
|
28 |
-
def rms_norm(x
|
29 |
-
output = x
|
30 |
if weight is not None:
|
31 |
return output * weight
|
32 |
return output
|
33 |
|
34 |
class RMSNorm(torch.nn.Module):
|
35 |
|
36 |
-
def __init__(self, normalized_shape
|
37 |
super().__init__()
|
38 |
self.eps = eps
|
39 |
if weight:
|
@@ -41,17 +40,17 @@ class RMSNorm(torch.nn.Module):
|
|
41 |
else:
|
42 |
self.register_parameter('weight', None)
|
43 |
|
44 |
-
def forward(self, x
|
45 |
return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
|
46 |
|
47 |
class LPRMSNorm(RMSNorm):
|
48 |
|
49 |
-
def __init__(self, normalized_shape
|
50 |
super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device)
|
51 |
|
52 |
-
def forward(self, x
|
53 |
downcast_x = _cast_if_autocast_enabled(x)
|
54 |
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
55 |
with torch.autocast(enabled=False, device_type=x.device.type):
|
56 |
return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
|
57 |
-
NORM_CLASS_REGISTRY
|
|
|
|
|
1 |
import torch
|
2 |
|
3 |
+
def _cast_if_autocast_enabled(tensor):
|
4 |
if torch.is_autocast_enabled():
|
5 |
if tensor.device.type == 'cuda':
|
6 |
dtype = torch.get_autocast_gpu_dtype()
|
|
|
13 |
|
14 |
class LPLayerNorm(torch.nn.LayerNorm):
|
15 |
|
16 |
+
def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None):
|
17 |
super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype)
|
18 |
|
19 |
+
def forward(self, x):
|
20 |
module_device = x.device
|
21 |
downcast_x = _cast_if_autocast_enabled(x)
|
22 |
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
|
|
24 |
with torch.autocast(enabled=False, device_type=module_device.type):
|
25 |
return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps)
|
26 |
|
27 |
+
def rms_norm(x, weight=None, eps=1e-05):
|
28 |
+
output = x / torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
|
29 |
if weight is not None:
|
30 |
return output * weight
|
31 |
return output
|
32 |
|
33 |
class RMSNorm(torch.nn.Module):
|
34 |
|
35 |
+
def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
|
36 |
super().__init__()
|
37 |
self.eps = eps
|
38 |
if weight:
|
|
|
40 |
else:
|
41 |
self.register_parameter('weight', None)
|
42 |
|
43 |
+
def forward(self, x):
|
44 |
return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
|
45 |
|
46 |
class LPRMSNorm(RMSNorm):
|
47 |
|
48 |
+
def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
|
49 |
super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device)
|
50 |
|
51 |
+
def forward(self, x):
|
52 |
downcast_x = _cast_if_autocast_enabled(x)
|
53 |
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
54 |
with torch.autocast(enabled=False, device_type=x.device.type):
|
55 |
return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
|
56 |
+
NORM_CLASS_REGISTRY = {'layernorm': torch.nn.LayerNorm, 'low_precision_layernorm': LPLayerNorm, 'rmsnorm': RMSNorm, 'low_precision_rmsnorm': LPRMSNorm}
|
param_init_fns.py
CHANGED
@@ -2,26 +2,22 @@ import math
|
|
2 |
import warnings
|
3 |
from collections.abc import Sequence
|
4 |
from functools import partial
|
5 |
-
from typing import
|
6 |
import torch
|
7 |
from torch import nn
|
8 |
-
from .fc import FC_CLASS_REGISTRY
|
9 |
from .norm import NORM_CLASS_REGISTRY
|
10 |
-
try:
|
11 |
-
import transformer_engine.pytorch as te
|
12 |
-
except:
|
13 |
-
te = None
|
14 |
|
15 |
-
def torch_default_param_init_fn_(module: nn.Module, **kwargs
|
16 |
del kwargs
|
17 |
-
if
|
|
|
|
|
18 |
module.reset_parameters()
|
19 |
|
20 |
-
def fused_init_helper_(module: nn.Module, init_fn_
|
21 |
_fused = getattr(module, '_fused', None)
|
22 |
if _fused is None:
|
23 |
raise RuntimeError(f'Internal logic error')
|
24 |
-
assert isinstance(module.weight, torch.Tensor)
|
25 |
(dim, splits) = _fused
|
26 |
splits = (0, *splits, module.weight.size(dim))
|
27 |
for (s, e) in zip(splits[:-1], splits[1:]):
|
@@ -29,8 +25,10 @@ def fused_init_helper_(module: nn.Module, init_fn_: Callable) -> None:
|
|
29 |
slice_indices[dim] = slice(s, e)
|
30 |
init_fn_(module.weight[slice_indices])
|
31 |
|
32 |
-
def generic_param_init_fn_(module: nn.Module, init_fn_
|
33 |
del kwargs
|
|
|
|
|
34 |
init_div_is_residual = init_div_is_residual
|
35 |
if init_div_is_residual is False:
|
36 |
div_is_residual = 1.0
|
@@ -38,18 +36,20 @@ def generic_param_init_fn_(module: nn.Module, init_fn_: Callable, n_layers: int,
|
|
38 |
div_is_residual = math.sqrt(2 * n_layers)
|
39 |
elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
|
40 |
div_is_residual = init_div_is_residual
|
41 |
-
elif init_div_is_residual.isnumeric():
|
42 |
div_is_residual = float(init_div_is_residual)
|
43 |
else:
|
44 |
div_is_residual = 1.0
|
45 |
raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
|
46 |
-
if
|
|
|
|
|
|
|
47 |
if hasattr(module, '_fused'):
|
48 |
fused_init_helper_(module, init_fn_)
|
49 |
else:
|
50 |
init_fn_(module.weight)
|
51 |
if module.bias is not None:
|
52 |
-
assert isinstance(module.bias, torch.Tensor)
|
53 |
torch.nn.init.zeros_(module.bias)
|
54 |
if init_div_is_residual is not False and getattr(module, '_is_residual', False):
|
55 |
with torch.no_grad():
|
@@ -60,6 +60,8 @@ def generic_param_init_fn_(module: nn.Module, init_fn_: Callable, n_layers: int,
|
|
60 |
if std == 0:
|
61 |
warnings.warn(f'Embedding layer initialized to 0.')
|
62 |
emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
|
|
|
|
|
63 |
elif emb_init_uniform_lim is not None:
|
64 |
lim = emb_init_uniform_lim
|
65 |
if isinstance(lim, Sequence):
|
@@ -73,13 +75,17 @@ def generic_param_init_fn_(module: nn.Module, init_fn_: Callable, n_layers: int,
|
|
73 |
lim = [-lim, lim]
|
74 |
(a, b) = lim
|
75 |
emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
|
|
|
|
|
76 |
else:
|
77 |
emb_init_fn_ = init_fn_
|
78 |
emb_init_fn_(module.weight)
|
79 |
elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
|
80 |
-
if
|
|
|
|
|
81 |
torch.nn.init.ones_(module.weight)
|
82 |
-
if hasattr(module, 'bias') and
|
83 |
torch.nn.init.zeros_(module.bias)
|
84 |
elif isinstance(module, nn.MultiheadAttention):
|
85 |
if module._qkv_same_embed_dim:
|
@@ -108,45 +114,32 @@ def generic_param_init_fn_(module: nn.Module, init_fn_: Callable, n_layers: int,
|
|
108 |
module.out_proj.weight.div_(div_is_residual)
|
109 |
if module.out_proj.bias is not None:
|
110 |
torch.nn.init.zeros_(module.out_proj.bias)
|
111 |
-
elif te is not None and isinstance(module, te.LayerNormMLP):
|
112 |
-
if isinstance(module.layer_norm_weight, torch.Tensor):
|
113 |
-
torch.nn.init.ones_(module.layer_norm_weight)
|
114 |
-
if isinstance(module.layer_norm_bias, torch.Tensor):
|
115 |
-
torch.nn.init.zeros_(module.layer_norm_bias)
|
116 |
-
init_fn_(module.fc1_weight)
|
117 |
-
if module.fc1_bias is not None:
|
118 |
-
assert isinstance(module.fc1_bias, torch.Tensor)
|
119 |
-
torch.nn.init.zeros_(module.fc1_bias)
|
120 |
-
init_fn_(module.fc2_weight)
|
121 |
-
if module.fc2_bias is not None:
|
122 |
-
assert isinstance(module.fc2_bias, torch.Tensor)
|
123 |
-
torch.nn.init.zeros_(module.fc2_bias)
|
124 |
-
with torch.no_grad():
|
125 |
-
module.fc2_weight.div_(div_is_residual)
|
126 |
else:
|
127 |
for _ in module.parameters(recurse=False):
|
128 |
raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
|
129 |
|
130 |
-
def _normal_init_(std
|
131 |
return partial(torch.nn.init.normal_, mean=mean, std=std)
|
132 |
|
133 |
-
def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, **kwargs
|
134 |
del kwargs
|
135 |
init_fn_ = _normal_init_(std=std)
|
136 |
-
|
|
|
|
|
137 |
|
138 |
-
def baseline_param_init_fn_(module: nn.Module, init_std:
|
139 |
del kwargs
|
140 |
if init_std is None:
|
141 |
raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
|
142 |
-
_normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim)
|
143 |
|
144 |
-
def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, **kwargs
|
145 |
del kwargs
|
146 |
std = math.sqrt(2 / (5 * d_model))
|
147 |
-
_normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim)
|
148 |
|
149 |
-
def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, **kwargs
|
150 |
"""From section 2.3.1 of GPT-NeoX-20B:
|
151 |
|
152 |
An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
|
@@ -155,25 +148,34 @@ def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init
|
|
155 |
"""
|
156 |
del kwargs
|
157 |
residual_div = n_layers / math.sqrt(10)
|
158 |
-
|
|
|
|
|
159 |
|
160 |
-
def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', **kwargs
|
161 |
del kwargs
|
|
|
|
|
162 |
kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
163 |
-
generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim)
|
164 |
|
165 |
-
def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', **kwargs
|
166 |
del kwargs
|
|
|
|
|
167 |
kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
168 |
-
generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim)
|
169 |
|
170 |
-
def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, **kwargs
|
171 |
del kwargs
|
172 |
xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
|
173 |
-
|
|
|
|
|
174 |
|
175 |
-
def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, **kwargs
|
176 |
-
del kwargs
|
177 |
xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
|
178 |
-
|
|
|
|
|
179 |
MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_}
|
|
|
2 |
import warnings
|
3 |
from collections.abc import Sequence
|
4 |
from functools import partial
|
5 |
+
from typing import Optional, Tuple, Union
|
6 |
import torch
|
7 |
from torch import nn
|
|
|
8 |
from .norm import NORM_CLASS_REGISTRY
|
|
|
|
|
|
|
|
|
9 |
|
10 |
+
def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
|
11 |
del kwargs
|
12 |
+
if verbose > 1:
|
13 |
+
warnings.warn(f"Initializing network using module's reset_parameters attribute")
|
14 |
+
if hasattr(module, 'reset_parameters'):
|
15 |
module.reset_parameters()
|
16 |
|
17 |
+
def fused_init_helper_(module: nn.Module, init_fn_):
|
18 |
_fused = getattr(module, '_fused', None)
|
19 |
if _fused is None:
|
20 |
raise RuntimeError(f'Internal logic error')
|
|
|
21 |
(dim, splits) = _fused
|
22 |
splits = (0, *splits, module.weight.size(dim))
|
23 |
for (s, e) in zip(splits[:-1], splits[1:]):
|
|
|
25 |
slice_indices[dim] = slice(s, e)
|
26 |
init_fn_(module.weight[slice_indices])
|
27 |
|
28 |
+
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
29 |
del kwargs
|
30 |
+
if verbose > 1:
|
31 |
+
warnings.warn(f'If model has bias parameters they are initialized to 0.')
|
32 |
init_div_is_residual = init_div_is_residual
|
33 |
if init_div_is_residual is False:
|
34 |
div_is_residual = 1.0
|
|
|
36 |
div_is_residual = math.sqrt(2 * n_layers)
|
37 |
elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
|
38 |
div_is_residual = init_div_is_residual
|
39 |
+
elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
|
40 |
div_is_residual = float(init_div_is_residual)
|
41 |
else:
|
42 |
div_is_residual = 1.0
|
43 |
raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
|
44 |
+
if init_div_is_residual is not False:
|
45 |
+
if verbose > 1:
|
46 |
+
warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
|
47 |
+
if isinstance(module, nn.Linear):
|
48 |
if hasattr(module, '_fused'):
|
49 |
fused_init_helper_(module, init_fn_)
|
50 |
else:
|
51 |
init_fn_(module.weight)
|
52 |
if module.bias is not None:
|
|
|
53 |
torch.nn.init.zeros_(module.bias)
|
54 |
if init_div_is_residual is not False and getattr(module, '_is_residual', False):
|
55 |
with torch.no_grad():
|
|
|
60 |
if std == 0:
|
61 |
warnings.warn(f'Embedding layer initialized to 0.')
|
62 |
emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
|
63 |
+
if verbose > 1:
|
64 |
+
warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
|
65 |
elif emb_init_uniform_lim is not None:
|
66 |
lim = emb_init_uniform_lim
|
67 |
if isinstance(lim, Sequence):
|
|
|
75 |
lim = [-lim, lim]
|
76 |
(a, b) = lim
|
77 |
emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
|
78 |
+
if verbose > 1:
|
79 |
+
warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
|
80 |
else:
|
81 |
emb_init_fn_ = init_fn_
|
82 |
emb_init_fn_(module.weight)
|
83 |
elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
|
84 |
+
if verbose > 1:
|
85 |
+
warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
|
86 |
+
if hasattr(module, 'weight') and module.weight is not None:
|
87 |
torch.nn.init.ones_(module.weight)
|
88 |
+
if hasattr(module, 'bias') and module.bias is not None:
|
89 |
torch.nn.init.zeros_(module.bias)
|
90 |
elif isinstance(module, nn.MultiheadAttention):
|
91 |
if module._qkv_same_embed_dim:
|
|
|
114 |
module.out_proj.weight.div_(div_is_residual)
|
115 |
if module.out_proj.bias is not None:
|
116 |
torch.nn.init.zeros_(module.out_proj.bias)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
else:
|
118 |
for _ in module.parameters(recurse=False):
|
119 |
raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
|
120 |
|
121 |
+
def _normal_init_(std, mean=0.0):
|
122 |
return partial(torch.nn.init.normal_, mean=mean, std=std)
|
123 |
|
124 |
+
def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
125 |
del kwargs
|
126 |
init_fn_ = _normal_init_(std=std)
|
127 |
+
if verbose > 1:
|
128 |
+
warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}')
|
129 |
+
generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
130 |
|
131 |
+
def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
132 |
del kwargs
|
133 |
if init_std is None:
|
134 |
raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
|
135 |
+
_normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
136 |
|
137 |
+
def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
138 |
del kwargs
|
139 |
std = math.sqrt(2 / (5 * d_model))
|
140 |
+
_normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
141 |
|
142 |
+
def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
143 |
"""From section 2.3.1 of GPT-NeoX-20B:
|
144 |
|
145 |
An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
|
|
|
148 |
"""
|
149 |
del kwargs
|
150 |
residual_div = n_layers / math.sqrt(10)
|
151 |
+
if verbose > 1:
|
152 |
+
warnings.warn(f'setting init_div_is_residual to {residual_div}')
|
153 |
+
small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
154 |
|
155 |
+
def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
|
156 |
del kwargs
|
157 |
+
if verbose > 1:
|
158 |
+
warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
|
159 |
kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
160 |
+
generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
161 |
|
162 |
+
def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
|
163 |
del kwargs
|
164 |
+
if verbose > 1:
|
165 |
+
warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
|
166 |
kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
167 |
+
generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
168 |
|
169 |
+
def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
|
170 |
del kwargs
|
171 |
xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
|
172 |
+
if verbose > 1:
|
173 |
+
warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}')
|
174 |
+
generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
175 |
|
176 |
+
def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
|
|
|
177 |
xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
|
178 |
+
if verbose > 1:
|
179 |
+
warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}')
|
180 |
+
generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
181 |
MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_}
|
warnings.py
DELETED
@@ -1,22 +0,0 @@
|
|
1 |
-
class VersionedDeprecationWarning(DeprecationWarning):
|
2 |
-
"""A custom deprecation warning class that includes version information.
|
3 |
-
|
4 |
-
Attributes:
|
5 |
-
message (str): The deprecation message describing why the feature is deprecated.
|
6 |
-
remove_version (str): The version in which the feature will be removed.
|
7 |
-
|
8 |
-
Example:
|
9 |
-
>>> def deprecated_function():
|
10 |
-
... warnings.warn(
|
11 |
-
... VersionedDeprecationWarning(
|
12 |
-
... "Function XYZ is deprecated.",
|
13 |
-
... after_version="2.0.0"
|
14 |
-
... )
|
15 |
-
... )
|
16 |
-
...
|
17 |
-
>>> deprecated_function()
|
18 |
-
DeprecationWarning: Function XYZ is deprecated. It will be removed in version 2.0.0.
|
19 |
-
"""
|
20 |
-
|
21 |
-
def __init__(self, message: str, remove_version: str) -> None:
|
22 |
-
super().__init__(message + f' It will be removed in version {remove_version}.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|