Spaces:
Paused
Paused
Merge branch 'main' into new_dockerfile
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +61 -0
- .idea/.gitignore +8 -0
- .idea/LISA_REFACTOR.iml +15 -0
- .idea/inspectionProfiles/Project_Default.xml +6 -0
- .idea/inspectionProfiles/profiles_settings.xml +6 -0
- .idea/modules.xml +8 -0
- LICENSE +201 -0
- app.py +331 -0
- chat.py +253 -0
- flagged/.gitignore +0 -0
- merge_lora_weights_and_save_hf_model.py +159 -0
- model/LISA.py +427 -0
- model/llava/__init__.py +1 -0
- model/llava/constants.py +12 -0
- model/llava/conversation.py +399 -0
- model/llava/mm_utils.py +88 -0
- model/llava/model/__init__.py +2 -0
- model/llava/model/apply_delta.py +56 -0
- model/llava/model/builder.py +206 -0
- model/llava/model/consolidate.py +31 -0
- model/llava/model/language_model/llava_llama.py +167 -0
- model/llava/model/language_model/llava_mpt.py +174 -0
- model/llava/model/language_model/mpt/adapt_tokenizer.py +46 -0
- model/llava/model/language_model/mpt/attention.py +526 -0
- model/llava/model/language_model/mpt/blocks.py +92 -0
- model/llava/model/language_model/mpt/configuration_mpt.py +199 -0
- model/llava/model/language_model/mpt/custom_embedding.py +11 -0
- model/llava/model/language_model/mpt/flash_attn_triton.py +1087 -0
- model/llava/model/language_model/mpt/hf_prefixlm_converter.py +750 -0
- model/llava/model/language_model/mpt/meta_init_context.py +111 -0
- model/llava/model/language_model/mpt/modeling_mpt.py +538 -0
- model/llava/model/language_model/mpt/norm.py +106 -0
- model/llava/model/language_model/mpt/param_init_fns.py +419 -0
- model/llava/model/llava_arch.py +398 -0
- model/llava/model/make_delta.py +63 -0
- model/llava/model/multimodal_encoder/builder.py +17 -0
- model/llava/model/multimodal_encoder/clip_encoder.py +87 -0
- model/llava/model/utils.py +24 -0
- model/llava/train/llama_flash_attn_monkey_patch.py +126 -0
- model/llava/train/llava_trainer.py +67 -0
- model/llava/train/train.py +1038 -0
- model/llava/train/train_mem.py +14 -0
- model/llava/utils.py +134 -0
- model/segment_anything/__init__.py +10 -0
- model/segment_anything/automatic_mask_generator.py +372 -0
- model/segment_anything/build_sam.py +108 -0
- model/segment_anything/modeling/__init__.py +11 -0
- model/segment_anything/modeling/common.py +43 -0
- model/segment_anything/modeling/image_encoder.py +426 -0
- model/segment_anything/modeling/mask_decoder.py +191 -0
.gitignore
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
**/__pycache__
|
2 |
+
venv/*
|
3 |
+
runs/
|
4 |
+
.vscode/
|
5 |
+
flagged/Input Image/**/*
|
6 |
+
flagged/log.csv
|
7 |
+
.DS_Store
|
8 |
+
|
9 |
+
### JetBrains ###
|
10 |
+
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
|
11 |
+
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
12 |
+
|
13 |
+
# User-specific stuff:
|
14 |
+
.idea/workspace.xml
|
15 |
+
.idea/tasks.xml
|
16 |
+
.idea/dictionaries
|
17 |
+
.idea/vcs.xml
|
18 |
+
.idea/jsLibraryMappings.xml
|
19 |
+
|
20 |
+
# Sensitive or high-churn files:
|
21 |
+
.idea/dataSources.ids
|
22 |
+
.idea/dataSources.xml
|
23 |
+
.idea/dataSources.local.xml
|
24 |
+
.idea/sqlDataSources.xml
|
25 |
+
.idea/dynamic.xml
|
26 |
+
.idea/uiDesigner.xml
|
27 |
+
|
28 |
+
# Gradle:
|
29 |
+
.idea/gradle.xml
|
30 |
+
.idea/libraries
|
31 |
+
|
32 |
+
# Mongo Explorer plugin:
|
33 |
+
.idea/mongoSettings.xml
|
34 |
+
|
35 |
+
## File-based project format:
|
36 |
+
*.iws
|
37 |
+
|
38 |
+
## Plugin-specific files:
|
39 |
+
|
40 |
+
# IntelliJ
|
41 |
+
/out/
|
42 |
+
|
43 |
+
# mpeltonen/sbt-idea plugin
|
44 |
+
.idea_modules/
|
45 |
+
|
46 |
+
# JIRA plugin
|
47 |
+
atlassian-ide-plugin.xml
|
48 |
+
|
49 |
+
# Crashlytics plugin (for Android Studio and IntelliJ)
|
50 |
+
com_crashlytics_export_strings.xml
|
51 |
+
crashlytics.properties
|
52 |
+
crashlytics-build.properties
|
53 |
+
fabric.properties
|
54 |
+
|
55 |
+
### JetBrains Patch ###
|
56 |
+
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
|
57 |
+
|
58 |
+
# *.iml
|
59 |
+
# modules.xml
|
60 |
+
# .idea/misc.xml
|
61 |
+
# *.ipr
|
.idea/.gitignore
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Default ignored files
|
2 |
+
/shelf/
|
3 |
+
/workspace.xml
|
4 |
+
# Editor-based HTTP Client requests
|
5 |
+
/httpRequests/
|
6 |
+
# Datasource local storage ignored files
|
7 |
+
/dataSources/
|
8 |
+
/dataSources.local.xml
|
.idea/LISA_REFACTOR.iml
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<module type="PYTHON_MODULE" version="4">
|
3 |
+
<component name="NewModuleRootManager">
|
4 |
+
<content url="file://$MODULE_DIR$" />
|
5 |
+
<orderEntry type="inheritedJdk" />
|
6 |
+
<orderEntry type="sourceFolder" forTests="false" />
|
7 |
+
</component>
|
8 |
+
<component name="PyDocumentationSettings">
|
9 |
+
<option name="format" value="GOOGLE" />
|
10 |
+
<option name="myDocStringFormat" value="Google" />
|
11 |
+
</component>
|
12 |
+
<component name="SonarLintModuleSettings">
|
13 |
+
<option name="uniqueId" value="875f314e-5ed1-4106-8048-37fa08d9c6e3" />
|
14 |
+
</component>
|
15 |
+
</module>
|
.idea/inspectionProfiles/Project_Default.xml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<component name="InspectionProjectProfileManager">
|
2 |
+
<profile version="1.0">
|
3 |
+
<option name="myName" value="Project Default" />
|
4 |
+
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
5 |
+
</profile>
|
6 |
+
</component>
|
.idea/inspectionProfiles/profiles_settings.xml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<component name="InspectionProjectProfileManager">
|
2 |
+
<settings>
|
3 |
+
<option name="USE_PROJECT_PROFILE" value="false" />
|
4 |
+
<version value="1.0" />
|
5 |
+
</settings>
|
6 |
+
</component>
|
.idea/modules.xml
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
2 |
+
<project version="4">
|
3 |
+
<component name="ProjectModuleManager">
|
4 |
+
<modules>
|
5 |
+
<module fileurl="file://$PROJECT_DIR$/.idea/LISA_REFACTOR.iml" filepath="$PROJECT_DIR$/.idea/LISA_REFACTOR.iml" />
|
6 |
+
</modules>
|
7 |
+
</component>
|
8 |
+
</project>
|
LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [yyyy] [name of copyright owner]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
app.py
ADDED
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import sys
|
5 |
+
|
6 |
+
import bleach
|
7 |
+
import cv2
|
8 |
+
import gradio as gr
|
9 |
+
import numpy as np
|
10 |
+
import torch
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from PIL import Image
|
13 |
+
from transformers import AutoTokenizer, BitsAndBytesConfig, CLIPImageProcessor
|
14 |
+
|
15 |
+
from model.LISA import LISAForCausalLM
|
16 |
+
from model.llava import conversation as conversation_lib
|
17 |
+
from model.llava.mm_utils import tokenizer_image_token
|
18 |
+
from model.segment_anything.utils.transforms import ResizeLongestSide
|
19 |
+
from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
20 |
+
DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEX)
|
21 |
+
|
22 |
+
|
23 |
+
def parse_args(args):
|
24 |
+
parser = argparse.ArgumentParser(description="LISA chat")
|
25 |
+
parser.add_argument("--version", default="xinlai/LISA-13B-llama2-v1")
|
26 |
+
parser.add_argument("--vis_save_path", default="./vis_output", type=str)
|
27 |
+
parser.add_argument(
|
28 |
+
"--precision",
|
29 |
+
default="fp16",
|
30 |
+
type=str,
|
31 |
+
choices=["fp32", "bf16", "fp16"],
|
32 |
+
help="precision for inference",
|
33 |
+
)
|
34 |
+
parser.add_argument("--image_size", default=1024, type=int, help="image size")
|
35 |
+
parser.add_argument("--model_max_length", default=512, type=int)
|
36 |
+
parser.add_argument("--lora_r", default=8, type=int)
|
37 |
+
parser.add_argument(
|
38 |
+
"--vision-tower", default="openai/clip-vit-large-patch14", type=str
|
39 |
+
)
|
40 |
+
parser.add_argument("--local-rank", default=0, type=int, help="node rank")
|
41 |
+
parser.add_argument("--load_in_8bit", action="store_true", default=False)
|
42 |
+
parser.add_argument("--load_in_4bit", action="store_true", default=False)
|
43 |
+
parser.add_argument("--use_mm_start_end", action="store_true", default=True)
|
44 |
+
parser.add_argument(
|
45 |
+
"--conv_type",
|
46 |
+
default="llava_v1",
|
47 |
+
type=str,
|
48 |
+
choices=["llava_v1", "llava_llama_2"],
|
49 |
+
)
|
50 |
+
return parser.parse_args(args)
|
51 |
+
|
52 |
+
|
53 |
+
def preprocess(
|
54 |
+
x,
|
55 |
+
pixel_mean=torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1),
|
56 |
+
pixel_std=torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1),
|
57 |
+
img_size=1024,
|
58 |
+
) -> torch.Tensor:
|
59 |
+
"""Normalize pixel values and pad to a square input."""
|
60 |
+
# Normalize colors
|
61 |
+
x = (x - pixel_mean) / pixel_std
|
62 |
+
# Pad
|
63 |
+
h, w = x.shape[-2:]
|
64 |
+
padh = img_size - h
|
65 |
+
padw = img_size - w
|
66 |
+
x = F.pad(x, (0, padw, 0, padh))
|
67 |
+
return x
|
68 |
+
|
69 |
+
|
70 |
+
args = parse_args(sys.argv[1:])
|
71 |
+
os.makedirs(args.vis_save_path, exist_ok=True)
|
72 |
+
|
73 |
+
# Create model
|
74 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
75 |
+
args.version,
|
76 |
+
cache_dir=None,
|
77 |
+
model_max_length=args.model_max_length,
|
78 |
+
padding_side="right",
|
79 |
+
use_fast=False,
|
80 |
+
)
|
81 |
+
tokenizer.pad_token = tokenizer.unk_token
|
82 |
+
args.seg_token_idx = tokenizer("[SEG]", add_special_tokens=False).input_ids[0]
|
83 |
+
|
84 |
+
torch_dtype = torch.float32
|
85 |
+
if args.precision == "bf16":
|
86 |
+
torch_dtype = torch.bfloat16
|
87 |
+
elif args.precision == "fp16":
|
88 |
+
torch_dtype = torch.half
|
89 |
+
|
90 |
+
kwargs = {"torch_dtype": torch_dtype}
|
91 |
+
if args.load_in_4bit:
|
92 |
+
kwargs.update(
|
93 |
+
{
|
94 |
+
"torch_dtype": torch.half,
|
95 |
+
"load_in_4bit": True,
|
96 |
+
"quantization_config": BitsAndBytesConfig(
|
97 |
+
load_in_4bit=True,
|
98 |
+
bnb_4bit_compute_dtype=torch.float16,
|
99 |
+
bnb_4bit_use_double_quant=True,
|
100 |
+
bnb_4bit_quant_type="nf4",
|
101 |
+
llm_int8_skip_modules=["visual_model"],
|
102 |
+
),
|
103 |
+
}
|
104 |
+
)
|
105 |
+
elif args.load_in_8bit:
|
106 |
+
kwargs.update(
|
107 |
+
{
|
108 |
+
"torch_dtype": torch.half,
|
109 |
+
"quantization_config": BitsAndBytesConfig(
|
110 |
+
llm_int8_skip_modules=["visual_model"],
|
111 |
+
load_in_8bit=True,
|
112 |
+
),
|
113 |
+
}
|
114 |
+
)
|
115 |
+
|
116 |
+
model = LISAForCausalLM.from_pretrained(
|
117 |
+
args.version, low_cpu_mem_usage=True, vision_tower=args.vision_tower, seg_token_idx=args.seg_token_idx, **kwargs
|
118 |
+
)
|
119 |
+
|
120 |
+
model.config.eos_token_id = tokenizer.eos_token_id
|
121 |
+
model.config.bos_token_id = tokenizer.bos_token_id
|
122 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
123 |
+
|
124 |
+
model.get_model().initialize_vision_modules(model.get_model().config)
|
125 |
+
vision_tower = model.get_model().get_vision_tower()
|
126 |
+
vision_tower.to(dtype=torch_dtype)
|
127 |
+
|
128 |
+
if args.precision == "bf16":
|
129 |
+
model = model.bfloat16().cuda()
|
130 |
+
elif (
|
131 |
+
args.precision == "fp16" and (not args.load_in_4bit) and (not args.load_in_8bit)
|
132 |
+
):
|
133 |
+
vision_tower = model.get_model().get_vision_tower()
|
134 |
+
model.model.vision_tower = None
|
135 |
+
import deepspeed
|
136 |
+
|
137 |
+
model_engine = deepspeed.init_inference(
|
138 |
+
model=model,
|
139 |
+
dtype=torch.half,
|
140 |
+
replace_with_kernel_inject=True,
|
141 |
+
replace_method="auto",
|
142 |
+
)
|
143 |
+
model = model_engine.module
|
144 |
+
model.model.vision_tower = vision_tower.half().cuda()
|
145 |
+
elif args.precision == "fp32":
|
146 |
+
model = model.float().cuda()
|
147 |
+
|
148 |
+
vision_tower = model.get_model().get_vision_tower()
|
149 |
+
vision_tower.to(device=args.local_rank)
|
150 |
+
|
151 |
+
clip_image_processor = CLIPImageProcessor.from_pretrained(model.config.vision_tower)
|
152 |
+
transform = ResizeLongestSide(args.image_size)
|
153 |
+
|
154 |
+
model.eval()
|
155 |
+
|
156 |
+
|
157 |
+
# Gradio
|
158 |
+
examples = [
|
159 |
+
[
|
160 |
+
"Where can the driver see the car speed in this image? Please output segmentation mask.",
|
161 |
+
"./resources/imgs/example1.jpg",
|
162 |
+
],
|
163 |
+
[
|
164 |
+
"Can you segment the food that tastes spicy and hot?",
|
165 |
+
"./resources/imgs/example2.jpg",
|
166 |
+
],
|
167 |
+
[
|
168 |
+
"Assuming you are an autonomous driving robot, what part of the diagram would you manipulate to control the direction of travel? Please output segmentation mask and explain why.",
|
169 |
+
"./resources/imgs/example1.jpg",
|
170 |
+
],
|
171 |
+
[
|
172 |
+
"What can make the woman stand higher? Please output segmentation mask and explain why.",
|
173 |
+
"./resources/imgs/example3.jpg",
|
174 |
+
],
|
175 |
+
]
|
176 |
+
output_labels = ["Segmentation Output"]
|
177 |
+
|
178 |
+
title = "LISA: Reasoning Segmentation via Large Language Model"
|
179 |
+
|
180 |
+
description = """
|
181 |
+
<font size=4>
|
182 |
+
This is the online demo of LISA. \n
|
183 |
+
If multiple users are using it at the same time, they will enter a queue, which may delay some time. \n
|
184 |
+
**Note**: **Different prompts can lead to significantly varied results**. \n
|
185 |
+
**Note**: Please try to **standardize** your input text prompts to **avoid ambiguity**, and also pay attention to whether the **punctuations** of the input are correct. \n
|
186 |
+
**Note**: Current model is **LISA-13B-llama2-v0-explanatory**, and 4-bit quantization may impair text-generation quality. \n
|
187 |
+
**Usage**: <br>
|
188 |
+
 (1) To let LISA **segment something**, input prompt like: "Can you segment xxx in this image?", "What is xxx in this image? Please output segmentation mask."; <br>
|
189 |
+
 (2) To let LISA **output an explanation**, input prompt like: "What is xxx in this image? Please output segmentation mask and explain why."; <br>
|
190 |
+
 (3) To obtain **solely language output**, you can input like what you should do in current multi-modal LLM (e.g., LLaVA). <br>
|
191 |
+
Hope you can enjoy our work!
|
192 |
+
</font>
|
193 |
+
"""
|
194 |
+
|
195 |
+
article = """
|
196 |
+
<p style='text-align: center'>
|
197 |
+
<a href='https://arxiv.org/abs/2308.00692' target='_blank'>
|
198 |
+
Preprint Paper
|
199 |
+
</a>
|
200 |
+
\n
|
201 |
+
<p style='text-align: center'>
|
202 |
+
<a href='https://github.com/dvlab-research/LISA' target='_blank'> Github Repo </a></p>
|
203 |
+
"""
|
204 |
+
|
205 |
+
|
206 |
+
## to be implemented
|
207 |
+
def inference(input_str, input_image):
|
208 |
+
## filter out special chars
|
209 |
+
input_str = bleach.clean(input_str)
|
210 |
+
|
211 |
+
print("input_str: ", input_str, "input_image: ", input_image)
|
212 |
+
|
213 |
+
## input valid check
|
214 |
+
if not re.match(r"^[A-Za-z ,.!?\'\"]+$", input_str) or len(input_str) < 1:
|
215 |
+
output_str = "[Error] Invalid input: ", input_str
|
216 |
+
# output_image = np.zeros((128, 128, 3))
|
217 |
+
## error happened
|
218 |
+
output_image = cv2.imread("./resources/error_happened.png")[:, :, ::-1]
|
219 |
+
return output_image, output_str
|
220 |
+
|
221 |
+
# Model Inference
|
222 |
+
conv = conversation_lib.conv_templates[args.conv_type].copy()
|
223 |
+
conv.messages = []
|
224 |
+
|
225 |
+
prompt = input_str
|
226 |
+
prompt = DEFAULT_IMAGE_TOKEN + "\n" + prompt
|
227 |
+
if args.use_mm_start_end:
|
228 |
+
replace_token = (
|
229 |
+
DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
|
230 |
+
)
|
231 |
+
prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
232 |
+
|
233 |
+
conv.append_message(conv.roles[0], prompt)
|
234 |
+
conv.append_message(conv.roles[1], "")
|
235 |
+
prompt = conv.get_prompt()
|
236 |
+
|
237 |
+
image_np = cv2.imread(input_image)
|
238 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
|
239 |
+
original_size_list = [image_np.shape[:2]]
|
240 |
+
|
241 |
+
image_clip = (
|
242 |
+
clip_image_processor.preprocess(image_np, return_tensors="pt")[
|
243 |
+
"pixel_values"
|
244 |
+
][0]
|
245 |
+
.unsqueeze(0)
|
246 |
+
.cuda()
|
247 |
+
)
|
248 |
+
if args.precision == "bf16":
|
249 |
+
image_clip = image_clip.bfloat16()
|
250 |
+
elif args.precision == "fp16":
|
251 |
+
image_clip = image_clip.half()
|
252 |
+
else:
|
253 |
+
image_clip = image_clip.float()
|
254 |
+
|
255 |
+
image = transform.apply_image(image_np)
|
256 |
+
resize_list = [image.shape[:2]]
|
257 |
+
|
258 |
+
image = (
|
259 |
+
preprocess(torch.from_numpy(image).permute(2, 0, 1).contiguous())
|
260 |
+
.unsqueeze(0)
|
261 |
+
.cuda()
|
262 |
+
)
|
263 |
+
if args.precision == "bf16":
|
264 |
+
image = image.bfloat16()
|
265 |
+
elif args.precision == "fp16":
|
266 |
+
image = image.half()
|
267 |
+
else:
|
268 |
+
image = image.float()
|
269 |
+
|
270 |
+
|
271 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
272 |
+
input_ids = input_ids.unsqueeze(0).cuda()
|
273 |
+
|
274 |
+
output_ids, pred_masks = model.evaluate(
|
275 |
+
image_clip,
|
276 |
+
image,
|
277 |
+
input_ids,
|
278 |
+
resize_list,
|
279 |
+
original_size_list,
|
280 |
+
max_new_tokens=512,
|
281 |
+
tokenizer=tokenizer,
|
282 |
+
)
|
283 |
+
output_ids = output_ids[0][output_ids[0] != IMAGE_TOKEN_INDEX]
|
284 |
+
|
285 |
+
text_output = tokenizer.decode(output_ids, skip_special_tokens=False)
|
286 |
+
text_output = text_output.replace("\n", "").replace(" ", " ")
|
287 |
+
text_output = text_output.split("ASSISTANT: ")[-1]
|
288 |
+
|
289 |
+
print("text_output: ", text_output)
|
290 |
+
save_img = None
|
291 |
+
for i, pred_mask in enumerate(pred_masks):
|
292 |
+
if pred_mask.shape[0] == 0:
|
293 |
+
continue
|
294 |
+
|
295 |
+
pred_mask = pred_mask.detach().cpu().numpy()[0]
|
296 |
+
pred_mask = pred_mask > 0
|
297 |
+
|
298 |
+
save_img = image_np.copy()
|
299 |
+
save_img[pred_mask] = (
|
300 |
+
image_np * 0.5
|
301 |
+
+ pred_mask[:, :, None].astype(np.uint8) * np.array([255, 0, 0]) * 0.5
|
302 |
+
)[pred_mask]
|
303 |
+
|
304 |
+
output_str = "ASSITANT: " + text_output # input_str
|
305 |
+
if save_img is not None:
|
306 |
+
output_image = save_img # input_image
|
307 |
+
else:
|
308 |
+
## no seg output
|
309 |
+
output_image = cv2.imread("./resources/no_seg_out.png")[:, :, ::-1]
|
310 |
+
return output_image, output_str
|
311 |
+
|
312 |
+
|
313 |
+
demo = gr.Interface(
|
314 |
+
inference,
|
315 |
+
inputs=[
|
316 |
+
gr.Textbox(lines=1, placeholder=None, label="Text Instruction"),
|
317 |
+
gr.Image(type="filepath", label="Input Image"),
|
318 |
+
],
|
319 |
+
outputs=[
|
320 |
+
gr.Image(type="pil", label="Segmentation Output"),
|
321 |
+
gr.Textbox(lines=1, placeholder=None, label="Text Output"),
|
322 |
+
],
|
323 |
+
title=title,
|
324 |
+
description=description,
|
325 |
+
article=article,
|
326 |
+
examples=examples,
|
327 |
+
allow_flagging="auto",
|
328 |
+
)
|
329 |
+
|
330 |
+
demo.queue()
|
331 |
+
demo.launch()
|
chat.py
ADDED
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
|
5 |
+
import cv2
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
import torch.nn.functional as F
|
9 |
+
from transformers import AutoTokenizer, BitsAndBytesConfig, CLIPImageProcessor
|
10 |
+
|
11 |
+
from model.LISA import LISAForCausalLM
|
12 |
+
from model.llava import conversation as conversation_lib
|
13 |
+
from model.llava.mm_utils import tokenizer_image_token
|
14 |
+
from model.segment_anything.utils.transforms import ResizeLongestSide
|
15 |
+
from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
16 |
+
DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEX)
|
17 |
+
|
18 |
+
|
19 |
+
def parse_args(args):
|
20 |
+
parser = argparse.ArgumentParser(description="LISA chat")
|
21 |
+
parser.add_argument("--version", default="xinlai/LISA-13B-llama2-v1")
|
22 |
+
parser.add_argument("--vis_save_path", default="./vis_output", type=str)
|
23 |
+
parser.add_argument(
|
24 |
+
"--precision",
|
25 |
+
default="bf16",
|
26 |
+
type=str,
|
27 |
+
choices=["fp32", "bf16", "fp16"],
|
28 |
+
help="precision for inference",
|
29 |
+
)
|
30 |
+
parser.add_argument("--image_size", default=1024, type=int, help="image size")
|
31 |
+
parser.add_argument("--model_max_length", default=512, type=int)
|
32 |
+
parser.add_argument("--lora_r", default=8, type=int)
|
33 |
+
parser.add_argument(
|
34 |
+
"--vision-tower", default="openai/clip-vit-large-patch14", type=str
|
35 |
+
)
|
36 |
+
parser.add_argument("--local-rank", default=0, type=int, help="node rank")
|
37 |
+
parser.add_argument("--load_in_8bit", action="store_true", default=False)
|
38 |
+
parser.add_argument("--load_in_4bit", action="store_true", default=False)
|
39 |
+
parser.add_argument("--use_mm_start_end", action="store_true", default=True)
|
40 |
+
parser.add_argument(
|
41 |
+
"--conv_type",
|
42 |
+
default="llava_v1",
|
43 |
+
type=str,
|
44 |
+
choices=["llava_v1", "llava_llama_2"],
|
45 |
+
)
|
46 |
+
return parser.parse_args(args)
|
47 |
+
|
48 |
+
|
49 |
+
def preprocess(
|
50 |
+
x,
|
51 |
+
pixel_mean=torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1),
|
52 |
+
pixel_std=torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1),
|
53 |
+
img_size=1024,
|
54 |
+
) -> torch.Tensor:
|
55 |
+
"""Normalize pixel values and pad to a square input."""
|
56 |
+
# Normalize colors
|
57 |
+
x = (x - pixel_mean) / pixel_std
|
58 |
+
# Pad
|
59 |
+
h, w = x.shape[-2:]
|
60 |
+
padh = img_size - h
|
61 |
+
padw = img_size - w
|
62 |
+
x = F.pad(x, (0, padw, 0, padh))
|
63 |
+
return x
|
64 |
+
|
65 |
+
|
66 |
+
def main(args):
|
67 |
+
args = parse_args(args)
|
68 |
+
os.makedirs(args.vis_save_path, exist_ok=True)
|
69 |
+
|
70 |
+
# Create model
|
71 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
72 |
+
args.version,
|
73 |
+
cache_dir=None,
|
74 |
+
model_max_length=args.model_max_length,
|
75 |
+
padding_side="right",
|
76 |
+
use_fast=False,
|
77 |
+
)
|
78 |
+
tokenizer.pad_token = tokenizer.unk_token
|
79 |
+
args.seg_token_idx = tokenizer("[SEG]", add_special_tokens=False).input_ids[0]
|
80 |
+
|
81 |
+
|
82 |
+
torch_dtype = torch.float32
|
83 |
+
if args.precision == "bf16":
|
84 |
+
torch_dtype = torch.bfloat16
|
85 |
+
elif args.precision == "fp16":
|
86 |
+
torch_dtype = torch.half
|
87 |
+
|
88 |
+
kwargs = {"torch_dtype": torch_dtype}
|
89 |
+
if args.load_in_4bit:
|
90 |
+
kwargs.update(
|
91 |
+
{
|
92 |
+
"torch_dtype": torch.half,
|
93 |
+
"load_in_4bit": True,
|
94 |
+
"quantization_config": BitsAndBytesConfig(
|
95 |
+
load_in_4bit=True,
|
96 |
+
bnb_4bit_compute_dtype=torch.float16,
|
97 |
+
bnb_4bit_use_double_quant=True,
|
98 |
+
bnb_4bit_quant_type="nf4",
|
99 |
+
llm_int8_skip_modules=["visual_model"],
|
100 |
+
),
|
101 |
+
}
|
102 |
+
)
|
103 |
+
elif args.load_in_8bit:
|
104 |
+
kwargs.update(
|
105 |
+
{
|
106 |
+
"torch_dtype": torch.half,
|
107 |
+
"quantization_config": BitsAndBytesConfig(
|
108 |
+
llm_int8_skip_modules=["visual_model"],
|
109 |
+
load_in_8bit=True,
|
110 |
+
),
|
111 |
+
}
|
112 |
+
)
|
113 |
+
|
114 |
+
model = LISAForCausalLM.from_pretrained(
|
115 |
+
args.version, low_cpu_mem_usage=True, vision_tower=args.vision_tower, seg_token_idx=args.seg_token_idx, **kwargs
|
116 |
+
)
|
117 |
+
|
118 |
+
model.config.eos_token_id = tokenizer.eos_token_id
|
119 |
+
model.config.bos_token_id = tokenizer.bos_token_id
|
120 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
121 |
+
|
122 |
+
model.get_model().initialize_vision_modules(model.get_model().config)
|
123 |
+
vision_tower = model.get_model().get_vision_tower()
|
124 |
+
vision_tower.to(dtype=torch_dtype)
|
125 |
+
|
126 |
+
if args.precision == "bf16":
|
127 |
+
model = model.bfloat16().cuda()
|
128 |
+
elif (
|
129 |
+
args.precision == "fp16" and (not args.load_in_4bit) and (not args.load_in_8bit)
|
130 |
+
):
|
131 |
+
vision_tower = model.get_model().get_vision_tower()
|
132 |
+
model.model.vision_tower = None
|
133 |
+
import deepspeed
|
134 |
+
|
135 |
+
model_engine = deepspeed.init_inference(
|
136 |
+
model=model,
|
137 |
+
dtype=torch.half,
|
138 |
+
replace_with_kernel_inject=True,
|
139 |
+
replace_method="auto",
|
140 |
+
)
|
141 |
+
model = model_engine.module
|
142 |
+
model.model.vision_tower = vision_tower.half().cuda()
|
143 |
+
elif args.precision == "fp32":
|
144 |
+
model = model.float().cuda()
|
145 |
+
|
146 |
+
vision_tower = model.get_model().get_vision_tower()
|
147 |
+
vision_tower.to(device=args.local_rank)
|
148 |
+
|
149 |
+
clip_image_processor = CLIPImageProcessor.from_pretrained(model.config.vision_tower)
|
150 |
+
transform = ResizeLongestSide(args.image_size)
|
151 |
+
|
152 |
+
model.eval()
|
153 |
+
|
154 |
+
while True:
|
155 |
+
conv = conversation_lib.conv_templates[args.conv_type].copy()
|
156 |
+
conv.messages = []
|
157 |
+
|
158 |
+
prompt = input("Please input your prompt: ")
|
159 |
+
prompt = DEFAULT_IMAGE_TOKEN + "\n" + prompt
|
160 |
+
if args.use_mm_start_end:
|
161 |
+
replace_token = (
|
162 |
+
DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
|
163 |
+
)
|
164 |
+
prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
165 |
+
|
166 |
+
conv.append_message(conv.roles[0], prompt)
|
167 |
+
conv.append_message(conv.roles[1], "")
|
168 |
+
prompt = conv.get_prompt()
|
169 |
+
|
170 |
+
image_path = input("Please input the image path: ")
|
171 |
+
if not os.path.exists(image_path):
|
172 |
+
print("File not found in {}".format(image_path))
|
173 |
+
continue
|
174 |
+
|
175 |
+
image_np = cv2.imread(image_path)
|
176 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
|
177 |
+
original_size_list = [image_np.shape[:2]]
|
178 |
+
|
179 |
+
image_clip = (
|
180 |
+
clip_image_processor.preprocess(image_np, return_tensors="pt")[
|
181 |
+
"pixel_values"
|
182 |
+
][0]
|
183 |
+
.unsqueeze(0)
|
184 |
+
.cuda()
|
185 |
+
)
|
186 |
+
if args.precision == "bf16":
|
187 |
+
image_clip = image_clip.bfloat16()
|
188 |
+
elif args.precision == "fp16":
|
189 |
+
image_clip = image_clip.half()
|
190 |
+
else:
|
191 |
+
image_clip = image_clip.float()
|
192 |
+
|
193 |
+
image = transform.apply_image(image_np)
|
194 |
+
resize_list = [image.shape[:2]]
|
195 |
+
|
196 |
+
image = (
|
197 |
+
preprocess(torch.from_numpy(image).permute(2, 0, 1).contiguous())
|
198 |
+
.unsqueeze(0)
|
199 |
+
.cuda()
|
200 |
+
)
|
201 |
+
if args.precision == "bf16":
|
202 |
+
image = image.bfloat16()
|
203 |
+
elif args.precision == "fp16":
|
204 |
+
image = image.half()
|
205 |
+
else:
|
206 |
+
image = image.float()
|
207 |
+
|
208 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
209 |
+
input_ids = input_ids.unsqueeze(0).cuda()
|
210 |
+
|
211 |
+
output_ids, pred_masks = model.evaluate(
|
212 |
+
image_clip,
|
213 |
+
image,
|
214 |
+
input_ids,
|
215 |
+
resize_list,
|
216 |
+
original_size_list,
|
217 |
+
max_new_tokens=512,
|
218 |
+
tokenizer=tokenizer,
|
219 |
+
)
|
220 |
+
output_ids = output_ids[0][output_ids[0] != IMAGE_TOKEN_INDEX]
|
221 |
+
|
222 |
+
text_output = tokenizer.decode(output_ids, skip_special_tokens=False)
|
223 |
+
text_output = text_output.replace("\n", "").replace(" ", " ")
|
224 |
+
print("text_output: ", text_output)
|
225 |
+
|
226 |
+
for i, pred_mask in enumerate(pred_masks):
|
227 |
+
if pred_mask.shape[0] == 0:
|
228 |
+
continue
|
229 |
+
|
230 |
+
pred_mask = pred_mask.detach().cpu().numpy()[0]
|
231 |
+
pred_mask = pred_mask > 0
|
232 |
+
|
233 |
+
save_path = "{}/{}_mask_{}.jpg".format(
|
234 |
+
args.vis_save_path, image_path.split("/")[-1].split(".")[0], i
|
235 |
+
)
|
236 |
+
cv2.imwrite(save_path, pred_mask * 100)
|
237 |
+
print("{} has been saved.".format(save_path))
|
238 |
+
|
239 |
+
save_path = "{}/{}_masked_img_{}.jpg".format(
|
240 |
+
args.vis_save_path, image_path.split("/")[-1].split(".")[0], i
|
241 |
+
)
|
242 |
+
save_img = image_np.copy()
|
243 |
+
save_img[pred_mask] = (
|
244 |
+
image_np * 0.5
|
245 |
+
+ pred_mask[:, :, None].astype(np.uint8) * np.array([255, 0, 0]) * 0.5
|
246 |
+
)[pred_mask]
|
247 |
+
save_img = cv2.cvtColor(save_img, cv2.COLOR_RGB2BGR)
|
248 |
+
cv2.imwrite(save_path, save_img)
|
249 |
+
print("{} has been saved.".format(save_path))
|
250 |
+
|
251 |
+
|
252 |
+
if __name__ == "__main__":
|
253 |
+
main(sys.argv[1:])
|
flagged/.gitignore
ADDED
File without changes
|
merge_lora_weights_and_save_hf_model.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import glob
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
|
6 |
+
import cv2
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import torch.nn.functional as F
|
10 |
+
import transformers
|
11 |
+
from peft import LoraConfig, get_peft_model
|
12 |
+
from transformers import AutoTokenizer
|
13 |
+
|
14 |
+
from model.LISA import LISAForCausalLM
|
15 |
+
from utils.utils import DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN
|
16 |
+
|
17 |
+
|
18 |
+
def parse_args(args):
|
19 |
+
parser = argparse.ArgumentParser(
|
20 |
+
description="merge lora weights and save model with hf format"
|
21 |
+
)
|
22 |
+
parser.add_argument(
|
23 |
+
"--version", default="liuhaotian/llava-llama-2-13b-chat-lightning-preview"
|
24 |
+
)
|
25 |
+
parser.add_argument("--vis_save_path", default="./vis_output", type=str)
|
26 |
+
parser.add_argument(
|
27 |
+
"--precision",
|
28 |
+
default="bf16",
|
29 |
+
type=str,
|
30 |
+
choices=["fp32", "bf16", "fp16"],
|
31 |
+
help="precision for inference",
|
32 |
+
)
|
33 |
+
parser.add_argument("--vision_pretrained", default="PATH_TO_SAM_ViT-H", type=str)
|
34 |
+
parser.add_argument("--out_dim", default=256, type=int)
|
35 |
+
parser.add_argument("--image_size", default=1024, type=int, help="image size")
|
36 |
+
parser.add_argument("--model_max_length", default=512, type=int)
|
37 |
+
parser.add_argument(
|
38 |
+
"--vision-tower", default="openai/clip-vit-large-patch14", type=str
|
39 |
+
)
|
40 |
+
parser.add_argument("--lora_r", default=8, type=int)
|
41 |
+
parser.add_argument("--lora_alpha", default=16, type=int)
|
42 |
+
parser.add_argument("--lora_dropout", default=0.05, type=float)
|
43 |
+
parser.add_argument("--lora_target_modules", default="q_proj,v_proj", type=str)
|
44 |
+
parser.add_argument("--local-rank", default=0, type=int, help="node rank")
|
45 |
+
parser.add_argument("--train_mask_decoder", action="store_true", default=True)
|
46 |
+
parser.add_argument("--use_mm_start_end", action="store_true", default=True)
|
47 |
+
parser.add_argument(
|
48 |
+
"--conv_type",
|
49 |
+
default="llava_v1",
|
50 |
+
type=str,
|
51 |
+
choices=["llava_v1", "llava_llama_2"],
|
52 |
+
)
|
53 |
+
parser.add_argument("--weight", default="", type=str, required=True)
|
54 |
+
parser.add_argument("--save_path", default="./lisa_model", type=str, required=True)
|
55 |
+
return parser.parse_args(args)
|
56 |
+
|
57 |
+
|
58 |
+
def main(args):
|
59 |
+
args = parse_args(args)
|
60 |
+
os.makedirs(args.vis_save_path, exist_ok=True)
|
61 |
+
|
62 |
+
# Create model
|
63 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
64 |
+
args.version,
|
65 |
+
cache_dir=None,
|
66 |
+
model_max_length=args.model_max_length,
|
67 |
+
padding_side="right",
|
68 |
+
use_fast=False,
|
69 |
+
)
|
70 |
+
tokenizer.pad_token = tokenizer.unk_token
|
71 |
+
num_added_tokens = tokenizer.add_tokens("[SEG]")
|
72 |
+
args.seg_token_idx = tokenizer("[SEG]", add_special_tokens=False).input_ids[0]
|
73 |
+
|
74 |
+
if args.use_mm_start_end:
|
75 |
+
tokenizer.add_tokens(
|
76 |
+
[DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
|
77 |
+
)
|
78 |
+
|
79 |
+
model_args = {
|
80 |
+
"train_mask_decoder": args.train_mask_decoder,
|
81 |
+
"out_dim": args.out_dim,
|
82 |
+
"seg_token_idx": args.seg_token_idx,
|
83 |
+
"vision_tower": args.vision_tower,
|
84 |
+
}
|
85 |
+
|
86 |
+
torch_dtype = torch.float32
|
87 |
+
if args.precision == "bf16":
|
88 |
+
torch_dtype = torch.bfloat16
|
89 |
+
elif args.precision == "fp16":
|
90 |
+
torch_dtype = torch.half
|
91 |
+
model = LISAForCausalLM.from_pretrained(
|
92 |
+
args.version, torch_dtype=torch_dtype, low_cpu_mem_usage=True, **model_args
|
93 |
+
)
|
94 |
+
model.config.eos_token_id = tokenizer.eos_token_id
|
95 |
+
model.config.bos_token_id = tokenizer.bos_token_id
|
96 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
97 |
+
|
98 |
+
model.get_model().initialize_vision_modules(model.get_model().config)
|
99 |
+
vision_tower = model.get_model().get_vision_tower()
|
100 |
+
vision_tower.to(dtype=torch_dtype)
|
101 |
+
model.get_model().initialize_lisa_modules(model.get_model().config)
|
102 |
+
|
103 |
+
lora_r = args.lora_r
|
104 |
+
if lora_r > 0:
|
105 |
+
|
106 |
+
def find_linear_layers(model, lora_target_modules):
|
107 |
+
cls = torch.nn.Linear
|
108 |
+
lora_module_names = set()
|
109 |
+
for name, module in model.named_modules():
|
110 |
+
if (
|
111 |
+
isinstance(module, cls)
|
112 |
+
and all(
|
113 |
+
[
|
114 |
+
x not in name
|
115 |
+
for x in [
|
116 |
+
"visual_model",
|
117 |
+
"vision_tower",
|
118 |
+
"mm_projector",
|
119 |
+
"text_hidden_fcs",
|
120 |
+
]
|
121 |
+
]
|
122 |
+
)
|
123 |
+
and any([x in name for x in lora_target_modules])
|
124 |
+
):
|
125 |
+
lora_module_names.add(name)
|
126 |
+
return sorted(list(lora_module_names))
|
127 |
+
|
128 |
+
lora_alpha = args.lora_alpha
|
129 |
+
lora_dropout = args.lora_dropout
|
130 |
+
lora_target_modules = find_linear_layers(
|
131 |
+
model, args.lora_target_modules.split(",")
|
132 |
+
)
|
133 |
+
lora_config = LoraConfig(
|
134 |
+
r=lora_r,
|
135 |
+
lora_alpha=lora_alpha,
|
136 |
+
target_modules=lora_target_modules,
|
137 |
+
lora_dropout=lora_dropout,
|
138 |
+
bias="none",
|
139 |
+
task_type="CAUSAL_LM",
|
140 |
+
)
|
141 |
+
model = get_peft_model(model, lora_config)
|
142 |
+
model.print_trainable_parameters()
|
143 |
+
|
144 |
+
model.resize_token_embeddings(len(tokenizer))
|
145 |
+
|
146 |
+
state_dict = torch.load(args.weight, map_location="cpu")
|
147 |
+
model.load_state_dict(state_dict, strict=True)
|
148 |
+
|
149 |
+
model = model.merge_and_unload()
|
150 |
+
state_dict = {}
|
151 |
+
for k, v in model.state_dict().items():
|
152 |
+
if "vision_tower" not in k:
|
153 |
+
state_dict[k] = v
|
154 |
+
model.save_pretrained(args.save_path, state_dict=state_dict)
|
155 |
+
tokenizer.save_pretrained(args.save_path)
|
156 |
+
|
157 |
+
|
158 |
+
if __name__ == "__main__":
|
159 |
+
main(sys.argv[1:])
|
model/LISA.py
ADDED
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
from transformers import BitsAndBytesConfig, CLIPVisionModel
|
7 |
+
|
8 |
+
from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
9 |
+
DEFAULT_IMAGE_PATCH_TOKEN)
|
10 |
+
|
11 |
+
from .llava.model.language_model.llava_llama import (LlavaLlamaForCausalLM,
|
12 |
+
LlavaLlamaModel)
|
13 |
+
from .segment_anything import build_sam_vit_h
|
14 |
+
|
15 |
+
|
16 |
+
def dice_loss(
|
17 |
+
inputs: torch.Tensor,
|
18 |
+
targets: torch.Tensor,
|
19 |
+
num_masks: float,
|
20 |
+
scale=1000, # 100000.0,
|
21 |
+
eps=1e-6,
|
22 |
+
):
|
23 |
+
"""
|
24 |
+
Compute the DICE loss, similar to generalized IOU for masks
|
25 |
+
Args:
|
26 |
+
inputs: A float tensor of arbitrary shape.
|
27 |
+
The predictions for each example.
|
28 |
+
targets: A float tensor with the same shape as inputs. Stores the binary
|
29 |
+
classification label for each element in inputs
|
30 |
+
(0 for the negative class and 1 for the positive class).
|
31 |
+
"""
|
32 |
+
inputs = inputs.sigmoid()
|
33 |
+
inputs = inputs.flatten(1, 2)
|
34 |
+
targets = targets.flatten(1, 2)
|
35 |
+
numerator = 2 * (inputs / scale * targets).sum(-1)
|
36 |
+
denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1)
|
37 |
+
loss = 1 - (numerator + eps) / (denominator + eps)
|
38 |
+
loss = loss.sum() / (num_masks + 1e-8)
|
39 |
+
return loss
|
40 |
+
|
41 |
+
|
42 |
+
def sigmoid_ce_loss(
|
43 |
+
inputs: torch.Tensor,
|
44 |
+
targets: torch.Tensor,
|
45 |
+
num_masks: float,
|
46 |
+
):
|
47 |
+
"""
|
48 |
+
Args:
|
49 |
+
inputs: A float tensor of arbitrary shape.
|
50 |
+
The predictions for each example.
|
51 |
+
targets: A float tensor with the same shape as inputs. Stores the binary
|
52 |
+
classification label for each element in inputs
|
53 |
+
(0 for the negative class and 1 for the positive class).
|
54 |
+
Returns:
|
55 |
+
Loss tensor
|
56 |
+
"""
|
57 |
+
loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
|
58 |
+
loss = loss.flatten(1, 2).mean(1).sum() / (num_masks + 1e-8)
|
59 |
+
return loss
|
60 |
+
|
61 |
+
|
62 |
+
class LisaMetaModel:
|
63 |
+
def __init__(
|
64 |
+
self,
|
65 |
+
config,
|
66 |
+
**kwargs,
|
67 |
+
):
|
68 |
+
super(LisaMetaModel, self).__init__(config)
|
69 |
+
|
70 |
+
self.config = config
|
71 |
+
if not hasattr(self.config, "train_mask_decoder"):
|
72 |
+
self.config.train_mask_decoder = kwargs["train_mask_decoder"]
|
73 |
+
self.config.out_dim = kwargs["out_dim"]
|
74 |
+
self.vision_pretrained = kwargs.get("vision_pretrained", None)
|
75 |
+
else:
|
76 |
+
self.vision_pretrained = kwargs.get("vision_pretrained", None)
|
77 |
+
self.initialize_lisa_modules(self.config)
|
78 |
+
|
79 |
+
def initialize_lisa_modules(self, config):
|
80 |
+
# SAM
|
81 |
+
self.visual_model = build_sam_vit_h(self.vision_pretrained)
|
82 |
+
for param in self.visual_model.parameters():
|
83 |
+
param.requires_grad = False
|
84 |
+
if config.train_mask_decoder:
|
85 |
+
self.visual_model.mask_decoder.train()
|
86 |
+
for param in self.visual_model.mask_decoder.parameters():
|
87 |
+
param.requires_grad = True
|
88 |
+
|
89 |
+
# Projection layer
|
90 |
+
in_dim = config.hidden_size
|
91 |
+
out_dim = config.out_dim
|
92 |
+
text_fc = [
|
93 |
+
nn.Linear(in_dim, in_dim),
|
94 |
+
nn.ReLU(inplace=True),
|
95 |
+
nn.Linear(in_dim, out_dim),
|
96 |
+
nn.Dropout(0.0),
|
97 |
+
]
|
98 |
+
self.text_hidden_fcs = nn.ModuleList([nn.Sequential(*text_fc)])
|
99 |
+
self.text_hidden_fcs.train()
|
100 |
+
for param in self.text_hidden_fcs.parameters():
|
101 |
+
param.requires_grad = True
|
102 |
+
|
103 |
+
|
104 |
+
class LisaModel(LisaMetaModel, LlavaLlamaModel):
|
105 |
+
def __init__(
|
106 |
+
self,
|
107 |
+
config,
|
108 |
+
**kwargs,
|
109 |
+
):
|
110 |
+
super(LisaModel, self).__init__(config, **kwargs)
|
111 |
+
|
112 |
+
self.config.use_cache = False
|
113 |
+
self.config.vision_tower = self.config.mm_vision_tower
|
114 |
+
self.config.mm_vision_select_feature = "patch"
|
115 |
+
self.config.image_aspect_ratio = "square"
|
116 |
+
self.config.image_grid_pinpoints = None
|
117 |
+
self.config.tune_mm_mlp_adapter = False
|
118 |
+
self.config.freeze_mm_mlp_adapter = True
|
119 |
+
self.config.pretrain_mm_mlp_adapter = None
|
120 |
+
self.config.mm_use_im_patch_token = False
|
121 |
+
|
122 |
+
|
123 |
+
class LISAForCausalLM(LlavaLlamaForCausalLM):
|
124 |
+
def __init__(
|
125 |
+
self,
|
126 |
+
config,
|
127 |
+
**kwargs,
|
128 |
+
):
|
129 |
+
if not hasattr(config, "train_mask_decoder"):
|
130 |
+
config.mm_use_im_start_end = kwargs.pop("use_mm_start_end", True)
|
131 |
+
config.mm_vision_tower = kwargs.get(
|
132 |
+
"vision_tower", "openai/clip-vit-large-patch14"
|
133 |
+
)
|
134 |
+
self.ce_loss_weight = kwargs.pop("ce_loss_weight", None)
|
135 |
+
self.dice_loss_weight = kwargs.pop("dice_loss_weight", None)
|
136 |
+
self.bce_loss_weight = kwargs.pop("bce_loss_weight", None)
|
137 |
+
else:
|
138 |
+
config.mm_vision_tower = config.vision_tower
|
139 |
+
|
140 |
+
self.seg_token_idx = kwargs.pop("seg_token_idx")
|
141 |
+
|
142 |
+
super().__init__(config)
|
143 |
+
|
144 |
+
self.model = LisaModel(config, **kwargs)
|
145 |
+
|
146 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
147 |
+
|
148 |
+
# Initialize weights and apply final processing
|
149 |
+
self.post_init()
|
150 |
+
|
151 |
+
def get_visual_embs(self, pixel_values: torch.FloatTensor):
|
152 |
+
with torch.no_grad():
|
153 |
+
image_embeddings_list = []
|
154 |
+
for i in range(pixel_values.shape[0]):
|
155 |
+
torch.cuda.empty_cache()
|
156 |
+
image_embeddings = self.model.visual_model.image_encoder(
|
157 |
+
pixel_values[i].unsqueeze(0)
|
158 |
+
)
|
159 |
+
image_embeddings_list.append(image_embeddings)
|
160 |
+
torch.cuda.empty_cache()
|
161 |
+
image_embeddings = torch.cat(image_embeddings_list, 0)
|
162 |
+
return image_embeddings
|
163 |
+
|
164 |
+
def forward(self, **kwargs):
|
165 |
+
if "past_key_values" in kwargs:
|
166 |
+
return super().forward(**kwargs)
|
167 |
+
return self.model_forward(**kwargs)
|
168 |
+
|
169 |
+
def model_forward(
|
170 |
+
self,
|
171 |
+
images: torch.FloatTensor,
|
172 |
+
images_clip: torch.FloatTensor,
|
173 |
+
input_ids: torch.LongTensor,
|
174 |
+
labels: torch.LongTensor,
|
175 |
+
attention_masks: torch.LongTensor,
|
176 |
+
offset: torch.LongTensor,
|
177 |
+
masks_list: List[torch.FloatTensor],
|
178 |
+
label_list: List[torch.Tensor],
|
179 |
+
resize_list: List[tuple],
|
180 |
+
inference: bool = False,
|
181 |
+
**kwargs,
|
182 |
+
):
|
183 |
+
image_embeddings = self.get_visual_embs(images)
|
184 |
+
batch_size = image_embeddings.shape[0]
|
185 |
+
assert batch_size == len(offset) - 1
|
186 |
+
|
187 |
+
seg_token_mask = input_ids[:, 1:] == self.seg_token_idx
|
188 |
+
seg_token_mask = torch.cat(
|
189 |
+
[
|
190 |
+
seg_token_mask,
|
191 |
+
torch.zeros((seg_token_mask.shape[0], 1)).bool().cuda(),
|
192 |
+
],
|
193 |
+
dim=1,
|
194 |
+
)
|
195 |
+
# hack for IMAGE_TOKEN_INDEX (we suppose that there is only one image, and it is in the front)
|
196 |
+
seg_token_mask = torch.cat(
|
197 |
+
[torch.zeros((seg_token_mask.shape[0], 255)).bool().cuda(), seg_token_mask],
|
198 |
+
dim=1,
|
199 |
+
)
|
200 |
+
|
201 |
+
if inference:
|
202 |
+
n_batch = 1
|
203 |
+
length = input_ids.shape[0]
|
204 |
+
assert images_clip.shape[0] == 1
|
205 |
+
images_clip_extend = images_clip.expand(length, -1, -1, -1).contiguous()
|
206 |
+
|
207 |
+
output_hidden_states = []
|
208 |
+
for i in range(n_batch):
|
209 |
+
start_i, end_i = i * length, min((i + 1) * length, input_ids.shape[0])
|
210 |
+
output_i = super().forward(
|
211 |
+
images=images_clip_extend[: end_i - start_i],
|
212 |
+
attention_mask=attention_masks[start_i:end_i],
|
213 |
+
input_ids=input_ids[start_i:end_i],
|
214 |
+
output_hidden_states=True,
|
215 |
+
)
|
216 |
+
output_hidden_states.append(output_i.hidden_states)
|
217 |
+
torch.cuda.empty_cache()
|
218 |
+
|
219 |
+
output_hidden_states_list = []
|
220 |
+
output_hidden_states_level = torch.cat(output_hidden_states, dim=0)
|
221 |
+
output_hidden_states_list.append(output_hidden_states_level)
|
222 |
+
output_hidden_states = output_hidden_states_list
|
223 |
+
output = None
|
224 |
+
|
225 |
+
else:
|
226 |
+
images_clip_list = []
|
227 |
+
for i in range(len(offset) - 1):
|
228 |
+
start_i, end_i = offset[i], offset[i + 1]
|
229 |
+
images_clip_i = (
|
230 |
+
images_clip[i]
|
231 |
+
.unsqueeze(0)
|
232 |
+
.expand(end_i - start_i, -1, -1, -1)
|
233 |
+
.contiguous()
|
234 |
+
)
|
235 |
+
images_clip_list.append(images_clip_i)
|
236 |
+
images_clip = torch.cat(images_clip_list, dim=0)
|
237 |
+
|
238 |
+
output = super().forward(
|
239 |
+
images=images_clip,
|
240 |
+
attention_mask=attention_masks,
|
241 |
+
input_ids=input_ids,
|
242 |
+
labels=labels,
|
243 |
+
output_hidden_states=True,
|
244 |
+
)
|
245 |
+
output_hidden_states = output.hidden_states
|
246 |
+
|
247 |
+
hidden_states = []
|
248 |
+
|
249 |
+
assert len(self.model.text_hidden_fcs) == 1
|
250 |
+
hidden_states.append(self.model.text_hidden_fcs[0](output_hidden_states[-1]))
|
251 |
+
|
252 |
+
last_hidden_state = torch.stack(hidden_states, dim=-1).sum(dim=-1)
|
253 |
+
pred_embeddings = last_hidden_state[seg_token_mask]
|
254 |
+
seg_token_counts = seg_token_mask.int().sum(-1) # [bs, ]
|
255 |
+
|
256 |
+
seg_token_offset = seg_token_counts.cumsum(-1)
|
257 |
+
seg_token_offset = torch.cat(
|
258 |
+
[torch.zeros(1).long().cuda(), seg_token_offset], dim=0
|
259 |
+
)
|
260 |
+
|
261 |
+
seg_token_offset = seg_token_offset[offset]
|
262 |
+
|
263 |
+
pred_embeddings_ = []
|
264 |
+
for i in range(len(seg_token_offset) - 1):
|
265 |
+
start_i, end_i = seg_token_offset[i], seg_token_offset[i + 1]
|
266 |
+
pred_embeddings_.append(pred_embeddings[start_i:end_i])
|
267 |
+
pred_embeddings = pred_embeddings_
|
268 |
+
|
269 |
+
multimask_output = False
|
270 |
+
pred_masks = []
|
271 |
+
for i in range(len(pred_embeddings)):
|
272 |
+
(
|
273 |
+
sparse_embeddings,
|
274 |
+
dense_embeddings,
|
275 |
+
) = self.model.visual_model.prompt_encoder(
|
276 |
+
points=None,
|
277 |
+
boxes=None,
|
278 |
+
masks=None,
|
279 |
+
text_embeds=pred_embeddings[i].unsqueeze(1),
|
280 |
+
)
|
281 |
+
sparse_embeddings = sparse_embeddings.to(pred_embeddings[i].dtype)
|
282 |
+
low_res_masks, iou_predictions = self.model.visual_model.mask_decoder(
|
283 |
+
image_embeddings=image_embeddings[i].unsqueeze(0),
|
284 |
+
image_pe=self.model.visual_model.prompt_encoder.get_dense_pe(),
|
285 |
+
sparse_prompt_embeddings=sparse_embeddings,
|
286 |
+
dense_prompt_embeddings=dense_embeddings,
|
287 |
+
multimask_output=multimask_output,
|
288 |
+
)
|
289 |
+
pred_mask = self.model.visual_model.postprocess_masks(
|
290 |
+
low_res_masks,
|
291 |
+
input_size=resize_list[i],
|
292 |
+
original_size=label_list[i].shape,
|
293 |
+
)
|
294 |
+
pred_masks.append(pred_mask[:, 0])
|
295 |
+
|
296 |
+
model_output = output
|
297 |
+
gt_masks = masks_list
|
298 |
+
|
299 |
+
if inference:
|
300 |
+
return {
|
301 |
+
"pred_masks": pred_masks,
|
302 |
+
"gt_masks": gt_masks,
|
303 |
+
}
|
304 |
+
|
305 |
+
output = model_output.logits
|
306 |
+
|
307 |
+
ce_loss = model_output.loss
|
308 |
+
ce_loss = ce_loss * self.ce_loss_weight
|
309 |
+
mask_bce_loss = 0
|
310 |
+
mask_dice_loss = 0
|
311 |
+
num_masks = 0
|
312 |
+
for batch_idx in range(len(pred_masks)):
|
313 |
+
gt_mask = gt_masks[batch_idx]
|
314 |
+
pred_mask = pred_masks[batch_idx]
|
315 |
+
|
316 |
+
assert (
|
317 |
+
gt_mask.shape[0] == pred_mask.shape[0]
|
318 |
+
), "gt_mask.shape: {}, pred_mask.shape: {}".format(
|
319 |
+
gt_mask.shape, pred_mask.shape
|
320 |
+
)
|
321 |
+
mask_bce_loss += (
|
322 |
+
sigmoid_ce_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0])
|
323 |
+
* gt_mask.shape[0]
|
324 |
+
)
|
325 |
+
mask_dice_loss += (
|
326 |
+
dice_loss(pred_mask, gt_mask, num_masks=gt_mask.shape[0])
|
327 |
+
* gt_mask.shape[0]
|
328 |
+
)
|
329 |
+
num_masks += gt_mask.shape[0]
|
330 |
+
|
331 |
+
mask_bce_loss = self.bce_loss_weight * mask_bce_loss / (num_masks + 1e-8)
|
332 |
+
mask_dice_loss = self.dice_loss_weight * mask_dice_loss / (num_masks + 1e-8)
|
333 |
+
mask_loss = mask_bce_loss + mask_dice_loss
|
334 |
+
|
335 |
+
loss = ce_loss + mask_loss
|
336 |
+
|
337 |
+
return {
|
338 |
+
"loss": loss,
|
339 |
+
"ce_loss": ce_loss,
|
340 |
+
"mask_bce_loss": mask_bce_loss,
|
341 |
+
"mask_dice_loss": mask_dice_loss,
|
342 |
+
"mask_loss": mask_loss,
|
343 |
+
}
|
344 |
+
|
345 |
+
def evaluate(
|
346 |
+
self,
|
347 |
+
images_clip,
|
348 |
+
images,
|
349 |
+
input_ids,
|
350 |
+
resize_list,
|
351 |
+
original_size_list,
|
352 |
+
max_new_tokens=32,
|
353 |
+
tokenizer=None,
|
354 |
+
):
|
355 |
+
with torch.no_grad():
|
356 |
+
outputs = self.generate(
|
357 |
+
images=images_clip,
|
358 |
+
input_ids=input_ids,
|
359 |
+
max_new_tokens=max_new_tokens,
|
360 |
+
num_beams=1,
|
361 |
+
output_hidden_states=True,
|
362 |
+
return_dict_in_generate=True,
|
363 |
+
)
|
364 |
+
output_hidden_states = outputs.hidden_states[-1]
|
365 |
+
output_ids = outputs.sequences
|
366 |
+
|
367 |
+
seg_token_mask = output_ids[:, 1:] == self.seg_token_idx
|
368 |
+
# hack for IMAGE_TOKEN_INDEX (we suppose that there is only one image, and it is in the front)
|
369 |
+
seg_token_mask = torch.cat(
|
370 |
+
[
|
371 |
+
torch.zeros((seg_token_mask.shape[0], 255)).bool().cuda(),
|
372 |
+
seg_token_mask,
|
373 |
+
],
|
374 |
+
dim=1,
|
375 |
+
)
|
376 |
+
|
377 |
+
hidden_states = []
|
378 |
+
|
379 |
+
assert len(self.model.text_hidden_fcs) == 1
|
380 |
+
hidden_states.append(self.model.text_hidden_fcs[0](output_hidden_states))
|
381 |
+
|
382 |
+
last_hidden_state = torch.stack(hidden_states, dim=-1).sum(dim=-1)
|
383 |
+
pred_embeddings = last_hidden_state[seg_token_mask]
|
384 |
+
|
385 |
+
seg_token_counts = seg_token_mask.int().sum(-1) # [bs, ]
|
386 |
+
seg_token_offset = seg_token_counts.cumsum(-1)
|
387 |
+
seg_token_offset = torch.cat(
|
388 |
+
[torch.zeros(1).long().cuda(), seg_token_offset], dim=0
|
389 |
+
)
|
390 |
+
|
391 |
+
pred_embeddings_ = []
|
392 |
+
for i in range(len(seg_token_offset) - 1):
|
393 |
+
start_i, end_i = seg_token_offset[i], seg_token_offset[i + 1]
|
394 |
+
pred_embeddings_.append(pred_embeddings[start_i:end_i])
|
395 |
+
pred_embeddings = pred_embeddings_
|
396 |
+
|
397 |
+
image_embeddings = self.get_visual_embs(images)
|
398 |
+
|
399 |
+
multimask_output = False
|
400 |
+
pred_masks = []
|
401 |
+
for i in range(len(pred_embeddings)):
|
402 |
+
(
|
403 |
+
sparse_embeddings,
|
404 |
+
dense_embeddings,
|
405 |
+
) = self.model.visual_model.prompt_encoder(
|
406 |
+
points=None,
|
407 |
+
boxes=None,
|
408 |
+
masks=None,
|
409 |
+
text_embeds=pred_embeddings[i].unsqueeze(1),
|
410 |
+
)
|
411 |
+
|
412 |
+
sparse_embeddings = sparse_embeddings.to(pred_embeddings[i].dtype)
|
413 |
+
low_res_masks, iou_predictions = self.model.visual_model.mask_decoder(
|
414 |
+
image_embeddings=image_embeddings[i].unsqueeze(0),
|
415 |
+
image_pe=self.model.visual_model.prompt_encoder.get_dense_pe(),
|
416 |
+
sparse_prompt_embeddings=sparse_embeddings,
|
417 |
+
dense_prompt_embeddings=dense_embeddings,
|
418 |
+
multimask_output=multimask_output,
|
419 |
+
)
|
420 |
+
pred_mask = self.model.visual_model.postprocess_masks(
|
421 |
+
low_res_masks,
|
422 |
+
input_size=resize_list[i],
|
423 |
+
original_size=original_size_list[i],
|
424 |
+
)
|
425 |
+
pred_masks.append(pred_mask[:, 0])
|
426 |
+
|
427 |
+
return output_ids, pred_masks
|
model/llava/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .model import LlavaLlamaForCausalLM
|
model/llava/constants.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
3 |
+
|
4 |
+
LOGDIR = "."
|
5 |
+
|
6 |
+
# Model Constants
|
7 |
+
IGNORE_INDEX = -100
|
8 |
+
IMAGE_TOKEN_INDEX = -200
|
9 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
10 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
11 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
12 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
model/llava/conversation.py
ADDED
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
from enum import Enum, auto
|
3 |
+
from typing import List, Tuple
|
4 |
+
|
5 |
+
|
6 |
+
class SeparatorStyle(Enum):
|
7 |
+
"""Different separator style."""
|
8 |
+
|
9 |
+
SINGLE = auto()
|
10 |
+
TWO = auto()
|
11 |
+
MPT = auto()
|
12 |
+
PLAIN = auto()
|
13 |
+
LLAMA_2 = auto()
|
14 |
+
|
15 |
+
|
16 |
+
@dataclasses.dataclass
|
17 |
+
class Conversation:
|
18 |
+
"""A class that keeps all conversation history."""
|
19 |
+
|
20 |
+
system: str
|
21 |
+
roles: List[str]
|
22 |
+
messages: List[List[str]]
|
23 |
+
offset: int
|
24 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
25 |
+
sep: str = "###"
|
26 |
+
sep2: str = None
|
27 |
+
version: str = "Unknown"
|
28 |
+
|
29 |
+
skip_next: bool = False
|
30 |
+
|
31 |
+
def get_prompt(self):
|
32 |
+
messages = self.messages
|
33 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
34 |
+
messages = self.messages.copy()
|
35 |
+
init_role, init_msg = messages[0].copy()
|
36 |
+
init_msg = init_msg[0].replace("<image>", "").strip()
|
37 |
+
if "mmtag" in self.version:
|
38 |
+
messages[0] = (init_role, init_msg)
|
39 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
40 |
+
messages.insert(1, (self.roles[1], "Received."))
|
41 |
+
else:
|
42 |
+
messages[0] = (init_role, "<image>\n" + init_msg)
|
43 |
+
|
44 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
45 |
+
ret = self.system + self.sep
|
46 |
+
for role, message in messages:
|
47 |
+
if message:
|
48 |
+
if type(message) is tuple:
|
49 |
+
message, _, _ = message
|
50 |
+
ret += role + ": " + message + self.sep
|
51 |
+
else:
|
52 |
+
ret += role + ":"
|
53 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
54 |
+
seps = [self.sep, self.sep2]
|
55 |
+
ret = self.system + seps[0]
|
56 |
+
for i, (role, message) in enumerate(messages):
|
57 |
+
if message:
|
58 |
+
if type(message) is tuple:
|
59 |
+
message, _, _ = message
|
60 |
+
ret += role + ": " + message + seps[i % 2]
|
61 |
+
else:
|
62 |
+
ret += role + ":"
|
63 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
64 |
+
ret = self.system + self.sep
|
65 |
+
for role, message in messages:
|
66 |
+
if message:
|
67 |
+
if type(message) is tuple:
|
68 |
+
message, _, _ = message
|
69 |
+
ret += role + message + self.sep
|
70 |
+
else:
|
71 |
+
ret += role
|
72 |
+
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
73 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
74 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
75 |
+
ret = ""
|
76 |
+
|
77 |
+
for i, (role, message) in enumerate(messages):
|
78 |
+
if i == 0:
|
79 |
+
assert message, "first message should not be none"
|
80 |
+
assert role == self.roles[0], "first message should come from user"
|
81 |
+
if message:
|
82 |
+
if type(message) is tuple:
|
83 |
+
message, _, _ = message
|
84 |
+
if i == 0:
|
85 |
+
message = wrap_sys(self.system) + message
|
86 |
+
if i % 2 == 0:
|
87 |
+
message = wrap_inst(message)
|
88 |
+
ret += self.sep + message
|
89 |
+
else:
|
90 |
+
ret += " " + message + " " + self.sep2
|
91 |
+
else:
|
92 |
+
ret += ""
|
93 |
+
ret = ret.lstrip(self.sep)
|
94 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
95 |
+
seps = [self.sep, self.sep2]
|
96 |
+
ret = self.system
|
97 |
+
for i, (role, message) in enumerate(messages):
|
98 |
+
if message:
|
99 |
+
if type(message) is tuple:
|
100 |
+
message, _, _ = message
|
101 |
+
ret += message + seps[i % 2]
|
102 |
+
else:
|
103 |
+
ret += ""
|
104 |
+
else:
|
105 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
106 |
+
|
107 |
+
return ret
|
108 |
+
|
109 |
+
def append_message(self, role, message):
|
110 |
+
self.messages.append([role, message])
|
111 |
+
|
112 |
+
def get_images(self, return_pil=False):
|
113 |
+
images = []
|
114 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
115 |
+
if i % 2 == 0:
|
116 |
+
if type(msg) is tuple:
|
117 |
+
import base64
|
118 |
+
from io import BytesIO
|
119 |
+
|
120 |
+
from PIL import Image
|
121 |
+
|
122 |
+
msg, image, image_process_mode = msg
|
123 |
+
if image_process_mode == "Pad":
|
124 |
+
|
125 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
126 |
+
width, height = pil_img.size
|
127 |
+
if width == height:
|
128 |
+
return pil_img
|
129 |
+
elif width > height:
|
130 |
+
result = Image.new(
|
131 |
+
pil_img.mode, (width, width), background_color
|
132 |
+
)
|
133 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
134 |
+
return result
|
135 |
+
else:
|
136 |
+
result = Image.new(
|
137 |
+
pil_img.mode, (height, height), background_color
|
138 |
+
)
|
139 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
140 |
+
return result
|
141 |
+
|
142 |
+
image = expand2square(image)
|
143 |
+
elif image_process_mode == "Crop":
|
144 |
+
pass
|
145 |
+
elif image_process_mode == "Resize":
|
146 |
+
image = image.resize((336, 336))
|
147 |
+
else:
|
148 |
+
raise ValueError(
|
149 |
+
f"Invalid image_process_mode: {image_process_mode}"
|
150 |
+
)
|
151 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
152 |
+
aspect_ratio = max_hw / min_hw
|
153 |
+
max_len, min_len = 800, 400
|
154 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
155 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
156 |
+
W, H = image.size
|
157 |
+
if H > W:
|
158 |
+
H, W = longest_edge, shortest_edge
|
159 |
+
else:
|
160 |
+
H, W = shortest_edge, longest_edge
|
161 |
+
image = image.resize((W, H))
|
162 |
+
if return_pil:
|
163 |
+
images.append(image)
|
164 |
+
else:
|
165 |
+
buffered = BytesIO()
|
166 |
+
image.save(buffered, format="PNG")
|
167 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
168 |
+
images.append(img_b64_str)
|
169 |
+
return images
|
170 |
+
|
171 |
+
def to_gradio_chatbot(self):
|
172 |
+
ret = []
|
173 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
174 |
+
if i % 2 == 0:
|
175 |
+
if type(msg) is tuple:
|
176 |
+
import base64
|
177 |
+
from io import BytesIO
|
178 |
+
|
179 |
+
msg, image, image_process_mode = msg
|
180 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
181 |
+
aspect_ratio = max_hw / min_hw
|
182 |
+
max_len, min_len = 800, 400
|
183 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
184 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
185 |
+
W, H = image.size
|
186 |
+
if H > W:
|
187 |
+
H, W = longest_edge, shortest_edge
|
188 |
+
else:
|
189 |
+
H, W = shortest_edge, longest_edge
|
190 |
+
image = image.resize((W, H))
|
191 |
+
buffered = BytesIO()
|
192 |
+
image.save(buffered, format="JPEG")
|
193 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
194 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
195 |
+
ret.append([img_str, None])
|
196 |
+
msg = msg.replace("<image>", "").strip()
|
197 |
+
if len(msg) > 0:
|
198 |
+
ret.append([msg, None])
|
199 |
+
else:
|
200 |
+
ret.append([msg, None])
|
201 |
+
else:
|
202 |
+
ret[-1][-1] = msg
|
203 |
+
return ret
|
204 |
+
|
205 |
+
def copy(self):
|
206 |
+
return Conversation(
|
207 |
+
system=self.system,
|
208 |
+
roles=self.roles,
|
209 |
+
messages=[[x, y] for x, y in self.messages],
|
210 |
+
offset=self.offset,
|
211 |
+
sep_style=self.sep_style,
|
212 |
+
sep=self.sep,
|
213 |
+
sep2=self.sep2,
|
214 |
+
version=self.version,
|
215 |
+
)
|
216 |
+
|
217 |
+
def dict(self):
|
218 |
+
if len(self.get_images()) > 0:
|
219 |
+
return {
|
220 |
+
"system": self.system,
|
221 |
+
"roles": self.roles,
|
222 |
+
"messages": [
|
223 |
+
[x, y[0] if type(y) is tuple else y] for x, y in self.messages
|
224 |
+
],
|
225 |
+
"offset": self.offset,
|
226 |
+
"sep": self.sep,
|
227 |
+
"sep2": self.sep2,
|
228 |
+
}
|
229 |
+
return {
|
230 |
+
"system": self.system,
|
231 |
+
"roles": self.roles,
|
232 |
+
"messages": self.messages,
|
233 |
+
"offset": self.offset,
|
234 |
+
"sep": self.sep,
|
235 |
+
"sep2": self.sep2,
|
236 |
+
}
|
237 |
+
|
238 |
+
|
239 |
+
conv_vicuna_v0 = Conversation(
|
240 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
241 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
242 |
+
roles=("Human", "Assistant"),
|
243 |
+
messages=(
|
244 |
+
(
|
245 |
+
"Human",
|
246 |
+
"What are the key differences between renewable and non-renewable energy sources?",
|
247 |
+
),
|
248 |
+
(
|
249 |
+
"Assistant",
|
250 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
251 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
252 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
253 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
254 |
+
"renewable and non-renewable energy sources:\n"
|
255 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
256 |
+
"energy sources are finite and will eventually run out.\n"
|
257 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
258 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
259 |
+
"and other negative effects.\n"
|
260 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
261 |
+
"have lower operational costs than non-renewable sources.\n"
|
262 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
263 |
+
"locations than non-renewable sources.\n"
|
264 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
265 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
266 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
267 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n",
|
268 |
+
),
|
269 |
+
),
|
270 |
+
offset=2,
|
271 |
+
sep_style=SeparatorStyle.SINGLE,
|
272 |
+
sep="###",
|
273 |
+
)
|
274 |
+
|
275 |
+
conv_vicuna_v1 = Conversation(
|
276 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
277 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
278 |
+
roles=("USER", "ASSISTANT"),
|
279 |
+
version="v1",
|
280 |
+
messages=(),
|
281 |
+
offset=0,
|
282 |
+
sep_style=SeparatorStyle.TWO,
|
283 |
+
sep=" ",
|
284 |
+
sep2="</s>",
|
285 |
+
)
|
286 |
+
|
287 |
+
conv_llama_2 = Conversation(
|
288 |
+
system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
289 |
+
|
290 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
|
291 |
+
roles=("USER", "ASSISTANT"),
|
292 |
+
version="llama_v2",
|
293 |
+
messages=(),
|
294 |
+
offset=0,
|
295 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
296 |
+
sep="<s>",
|
297 |
+
sep2="</s>",
|
298 |
+
)
|
299 |
+
|
300 |
+
conv_llava_llama_2 = Conversation(
|
301 |
+
system="You are a helpful language and vision assistant. "
|
302 |
+
"You are able to understand the visual content that the user provides, "
|
303 |
+
"and assist the user with a variety of tasks using natural language.",
|
304 |
+
roles=("USER", "ASSISTANT"),
|
305 |
+
version="llama_v2",
|
306 |
+
messages=(),
|
307 |
+
offset=0,
|
308 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
309 |
+
sep="<s>",
|
310 |
+
sep2="</s>",
|
311 |
+
)
|
312 |
+
|
313 |
+
conv_mpt = Conversation(
|
314 |
+
system="""<|im_start|>system
|
315 |
+
A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
|
316 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
317 |
+
version="mpt",
|
318 |
+
messages=(),
|
319 |
+
offset=0,
|
320 |
+
sep_style=SeparatorStyle.MPT,
|
321 |
+
sep="<|im_end|>",
|
322 |
+
)
|
323 |
+
|
324 |
+
conv_llava_plain = Conversation(
|
325 |
+
system="",
|
326 |
+
roles=("", ""),
|
327 |
+
messages=(),
|
328 |
+
offset=0,
|
329 |
+
sep_style=SeparatorStyle.PLAIN,
|
330 |
+
sep="\n",
|
331 |
+
)
|
332 |
+
|
333 |
+
conv_llava_v0 = Conversation(
|
334 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
335 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
336 |
+
roles=("Human", "Assistant"),
|
337 |
+
messages=(("Human", "Hi!"), ("Assistant", "Hi there! How can I help you today?")),
|
338 |
+
offset=2,
|
339 |
+
sep_style=SeparatorStyle.SINGLE,
|
340 |
+
sep="###",
|
341 |
+
)
|
342 |
+
|
343 |
+
conv_llava_v0_mmtag = Conversation(
|
344 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
345 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
346 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
347 |
+
roles=("Human", "Assistant"),
|
348 |
+
messages=(),
|
349 |
+
offset=0,
|
350 |
+
sep_style=SeparatorStyle.SINGLE,
|
351 |
+
sep="###",
|
352 |
+
version="v0_mmtag",
|
353 |
+
)
|
354 |
+
|
355 |
+
conv_llava_v1 = Conversation(
|
356 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
357 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
358 |
+
roles=("USER", "ASSISTANT"),
|
359 |
+
version="v1",
|
360 |
+
messages=(),
|
361 |
+
offset=0,
|
362 |
+
sep_style=SeparatorStyle.TWO,
|
363 |
+
sep=" ",
|
364 |
+
sep2="</s>",
|
365 |
+
)
|
366 |
+
|
367 |
+
conv_llava_v1_mmtag = Conversation(
|
368 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
369 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
370 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
371 |
+
roles=("USER", "ASSISTANT"),
|
372 |
+
messages=(),
|
373 |
+
offset=0,
|
374 |
+
sep_style=SeparatorStyle.TWO,
|
375 |
+
sep=" ",
|
376 |
+
sep2="</s>",
|
377 |
+
version="v1_mmtag",
|
378 |
+
)
|
379 |
+
|
380 |
+
default_conversation = conv_vicuna_v0
|
381 |
+
conv_templates = {
|
382 |
+
"default": conv_vicuna_v0,
|
383 |
+
"v0": conv_vicuna_v0,
|
384 |
+
"v1": conv_vicuna_v1,
|
385 |
+
"vicuna_v1": conv_vicuna_v1,
|
386 |
+
"llama_2": conv_llama_2,
|
387 |
+
"plain": conv_llava_plain,
|
388 |
+
"v0_plain": conv_llava_plain,
|
389 |
+
"llava_v0": conv_llava_v0,
|
390 |
+
"v0_mmtag": conv_llava_v0_mmtag,
|
391 |
+
"llava_v1": conv_llava_v1,
|
392 |
+
"v1_mmtag": conv_llava_v1_mmtag,
|
393 |
+
"llava_llama_2": conv_llava_llama_2,
|
394 |
+
"mpt": conv_mpt,
|
395 |
+
}
|
396 |
+
|
397 |
+
|
398 |
+
if __name__ == "__main__":
|
399 |
+
print(default_conversation.get_prompt())
|
model/llava/mm_utils.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
from io import BytesIO
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from PIL import Image
|
6 |
+
from transformers import StoppingCriteria
|
7 |
+
|
8 |
+
from .constants import IMAGE_TOKEN_INDEX
|
9 |
+
|
10 |
+
|
11 |
+
def load_image_from_base64(image):
|
12 |
+
return Image.open(BytesIO(base64.b64decode(image)))
|
13 |
+
|
14 |
+
|
15 |
+
def process_images(images, image_processor, model_cfg):
|
16 |
+
return image_processor(images, return_tensors="pt")["pixel_values"]
|
17 |
+
|
18 |
+
|
19 |
+
def tokenizer_image_token(
|
20 |
+
prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None
|
21 |
+
):
|
22 |
+
prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
|
23 |
+
|
24 |
+
def insert_separator(X, sep):
|
25 |
+
return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
|
26 |
+
|
27 |
+
input_ids = []
|
28 |
+
offset = 0
|
29 |
+
if (
|
30 |
+
len(prompt_chunks) > 0
|
31 |
+
and len(prompt_chunks[0]) > 0
|
32 |
+
and prompt_chunks[0][0] == tokenizer.bos_token_id
|
33 |
+
):
|
34 |
+
offset = 1
|
35 |
+
input_ids.append(prompt_chunks[0][0])
|
36 |
+
|
37 |
+
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
|
38 |
+
input_ids.extend(x[offset:])
|
39 |
+
|
40 |
+
if return_tensors is not None:
|
41 |
+
if return_tensors == "pt":
|
42 |
+
return torch.tensor(input_ids, dtype=torch.long)
|
43 |
+
raise ValueError(f"Unsupported tensor type: {return_tensors}")
|
44 |
+
return input_ids
|
45 |
+
|
46 |
+
|
47 |
+
def get_model_name_from_path(model_path):
|
48 |
+
model_path = model_path.strip("/")
|
49 |
+
model_paths = model_path.split("/")
|
50 |
+
if model_paths[-1].startswith("checkpoint-"):
|
51 |
+
return model_paths[-2] + "_" + model_paths[-1]
|
52 |
+
else:
|
53 |
+
return model_paths[-1]
|
54 |
+
|
55 |
+
|
56 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
57 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
58 |
+
self.keywords = keywords
|
59 |
+
self.keyword_ids = []
|
60 |
+
for keyword in keywords:
|
61 |
+
cur_keyword_ids = tokenizer(keyword).input_ids
|
62 |
+
if (
|
63 |
+
len(cur_keyword_ids) > 1
|
64 |
+
and cur_keyword_ids[0] == tokenizer.bos_token_id
|
65 |
+
):
|
66 |
+
cur_keyword_ids = cur_keyword_ids[1:]
|
67 |
+
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
68 |
+
self.tokenizer = tokenizer
|
69 |
+
self.start_len = input_ids.shape[1]
|
70 |
+
|
71 |
+
def __call__(
|
72 |
+
self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs
|
73 |
+
) -> bool:
|
74 |
+
assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
|
75 |
+
offset = min(output_ids.shape[1] - self.start_len, 3)
|
76 |
+
self.keyword_ids = [
|
77 |
+
keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids
|
78 |
+
]
|
79 |
+
for keyword_id in self.keyword_ids:
|
80 |
+
if output_ids[0, -keyword_id.shape[0] :] == keyword_id:
|
81 |
+
return True
|
82 |
+
outputs = self.tokenizer.batch_decode(
|
83 |
+
output_ids[:, -offset:], skip_special_tokens=True
|
84 |
+
)[0]
|
85 |
+
for keyword in self.keywords:
|
86 |
+
if keyword in outputs:
|
87 |
+
return True
|
88 |
+
return False
|
model/llava/model/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from .language_model.llava_llama import LlavaConfig, LlavaLlamaForCausalLM
|
2 |
+
from .language_model.llava_mpt import LlavaMPTConfig, LlavaMPTForCausalLM
|
model/llava/model/apply_delta.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Usage:
|
3 |
+
python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
|
4 |
+
"""
|
5 |
+
import argparse
|
6 |
+
|
7 |
+
import torch
|
8 |
+
from llava import LlavaLlamaForCausalLM
|
9 |
+
from tqdm import tqdm
|
10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
11 |
+
|
12 |
+
|
13 |
+
def apply_delta(base_model_path, target_model_path, delta_path):
|
14 |
+
print("Loading base model")
|
15 |
+
base = AutoModelForCausalLM.from_pretrained(
|
16 |
+
base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
|
17 |
+
)
|
18 |
+
|
19 |
+
print("Loading delta")
|
20 |
+
delta = LlavaLlamaForCausalLM.from_pretrained(
|
21 |
+
delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
|
22 |
+
)
|
23 |
+
delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
|
24 |
+
|
25 |
+
print("Applying delta")
|
26 |
+
for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
|
27 |
+
if name not in base.state_dict():
|
28 |
+
assert name in [
|
29 |
+
"model.mm_projector.weight",
|
30 |
+
"model.mm_projector.bias",
|
31 |
+
], f"{name} not in base model"
|
32 |
+
continue
|
33 |
+
if param.data.shape == base.state_dict()[name].shape:
|
34 |
+
param.data += base.state_dict()[name]
|
35 |
+
else:
|
36 |
+
assert name in [
|
37 |
+
"model.embed_tokens.weight",
|
38 |
+
"lm_head.weight",
|
39 |
+
], f"{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}"
|
40 |
+
bparam = base.state_dict()[name]
|
41 |
+
param.data[: bparam.shape[0], : bparam.shape[1]] += bparam
|
42 |
+
|
43 |
+
print("Saving target model")
|
44 |
+
delta.save_pretrained(target_model_path)
|
45 |
+
delta_tokenizer.save_pretrained(target_model_path)
|
46 |
+
|
47 |
+
|
48 |
+
if __name__ == "__main__":
|
49 |
+
parser = argparse.ArgumentParser()
|
50 |
+
parser.add_argument("--base-model-path", type=str, required=True)
|
51 |
+
parser.add_argument("--target-model-path", type=str, required=True)
|
52 |
+
parser.add_argument("--delta-path", type=str, required=True)
|
53 |
+
|
54 |
+
args = parser.parse_args()
|
55 |
+
|
56 |
+
apply_delta(args.base_model_path, args.target_model_path, args.delta_path)
|
model/llava/model/builder.py
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Haotian Liu
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
|
16 |
+
import os
|
17 |
+
import shutil
|
18 |
+
|
19 |
+
import torch
|
20 |
+
from llava.constants import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
21 |
+
DEFAULT_IMAGE_PATCH_TOKEN)
|
22 |
+
from llava.model import *
|
23 |
+
from transformers import (AutoConfig, AutoModelForCausalLM, AutoTokenizer,
|
24 |
+
BitsAndBytesConfig)
|
25 |
+
|
26 |
+
|
27 |
+
def load_pretrained_model(
|
28 |
+
model_path,
|
29 |
+
model_base,
|
30 |
+
model_name,
|
31 |
+
load_8bit=False,
|
32 |
+
load_4bit=False,
|
33 |
+
device_map="auto",
|
34 |
+
):
|
35 |
+
kwargs = {"device_map": device_map}
|
36 |
+
|
37 |
+
if load_8bit:
|
38 |
+
kwargs["load_in_8bit"] = True
|
39 |
+
elif load_4bit:
|
40 |
+
kwargs["load_in_4bit"] = True
|
41 |
+
kwargs["quantization_config"] = BitsAndBytesConfig(
|
42 |
+
load_in_4bit=True,
|
43 |
+
bnb_4bit_compute_dtype=torch.float16,
|
44 |
+
bnb_4bit_use_double_quant=True,
|
45 |
+
bnb_4bit_quant_type="nf4",
|
46 |
+
)
|
47 |
+
else:
|
48 |
+
kwargs["torch_dtype"] = torch.float16
|
49 |
+
|
50 |
+
if "llava" in model_name.lower():
|
51 |
+
# Load LLaVA model
|
52 |
+
if "lora" in model_name.lower() and model_base is not None:
|
53 |
+
lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
54 |
+
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
55 |
+
print("Loading LLaVA from base model...")
|
56 |
+
model = LlavaLlamaForCausalLM.from_pretrained(
|
57 |
+
model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs
|
58 |
+
)
|
59 |
+
token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
|
60 |
+
if model.lm_head.weight.shape[0] != token_num:
|
61 |
+
model.lm_head.weight = torch.nn.Parameter(
|
62 |
+
torch.empty(
|
63 |
+
token_num, tokem_dim, device=model.device, dtype=model.dtype
|
64 |
+
)
|
65 |
+
)
|
66 |
+
model.model.embed_tokens.weight = torch.nn.Parameter(
|
67 |
+
torch.empty(
|
68 |
+
token_num, tokem_dim, device=model.device, dtype=model.dtype
|
69 |
+
)
|
70 |
+
)
|
71 |
+
|
72 |
+
print("Loading additional LLaVA weights...")
|
73 |
+
if os.path.exists(os.path.join(model_path, "non_lora_trainables.bin")):
|
74 |
+
non_lora_trainables = torch.load(
|
75 |
+
os.path.join(model_path, "non_lora_trainables.bin"),
|
76 |
+
map_location="cpu",
|
77 |
+
)
|
78 |
+
else:
|
79 |
+
# this is probably from HF Hub
|
80 |
+
from huggingface_hub import hf_hub_download
|
81 |
+
|
82 |
+
def load_from_hf(repo_id, filename, subfolder=None):
|
83 |
+
cache_file = hf_hub_download(
|
84 |
+
repo_id=repo_id, filename=filename, subfolder=subfolder
|
85 |
+
)
|
86 |
+
return torch.load(cache_file, map_location="cpu")
|
87 |
+
|
88 |
+
non_lora_trainables = load_from_hf(
|
89 |
+
model_path, "non_lora_trainables.bin"
|
90 |
+
)
|
91 |
+
non_lora_trainables = {
|
92 |
+
(k[11:] if k.startswith("base_model.") else k): v
|
93 |
+
for k, v in non_lora_trainables.items()
|
94 |
+
}
|
95 |
+
if any(k.startswith("model.model.") for k in non_lora_trainables):
|
96 |
+
non_lora_trainables = {
|
97 |
+
(k[6:] if k.startswith("model.") else k): v
|
98 |
+
for k, v in non_lora_trainables.items()
|
99 |
+
}
|
100 |
+
model.load_state_dict(non_lora_trainables, strict=False)
|
101 |
+
|
102 |
+
from peft import PeftModel
|
103 |
+
|
104 |
+
print("Loading LoRA weights...")
|
105 |
+
model = PeftModel.from_pretrained(model, model_path)
|
106 |
+
print("Merging LoRA weights...")
|
107 |
+
model = model.merge_and_unload()
|
108 |
+
print("Model is loaded...")
|
109 |
+
elif model_base is not None:
|
110 |
+
# this may be mm projector only
|
111 |
+
print("Loading LLaVA from base model...")
|
112 |
+
if "mpt" in model_name.lower():
|
113 |
+
if not os.path.isfile(os.path.join(model_path, "configuration_mpt.py")):
|
114 |
+
shutil.copyfile(
|
115 |
+
os.path.join(model_base, "configuration_mpt.py"),
|
116 |
+
os.path.join(model_path, "configuration_mpt.py"),
|
117 |
+
)
|
118 |
+
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
|
119 |
+
cfg_pretrained = AutoConfig.from_pretrained(
|
120 |
+
model_path, trust_remote_code=True
|
121 |
+
)
|
122 |
+
model = LlavaMPTForCausalLM.from_pretrained(
|
123 |
+
model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
|
124 |
+
)
|
125 |
+
else:
|
126 |
+
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
127 |
+
cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
128 |
+
model = LlavaLlamaForCausalLM.from_pretrained(
|
129 |
+
model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
|
130 |
+
)
|
131 |
+
|
132 |
+
mm_projector_weights = torch.load(
|
133 |
+
os.path.join(model_path, "mm_projector.bin"), map_location="cpu"
|
134 |
+
)
|
135 |
+
mm_projector_weights = {
|
136 |
+
k: v.to(torch.float16) for k, v in mm_projector_weights.items()
|
137 |
+
}
|
138 |
+
model.load_state_dict(mm_projector_weights, strict=False)
|
139 |
+
else:
|
140 |
+
if "mpt" in model_name.lower():
|
141 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
|
142 |
+
model = LlavaMPTForCausalLM.from_pretrained(
|
143 |
+
model_path, low_cpu_mem_usage=True, **kwargs
|
144 |
+
)
|
145 |
+
else:
|
146 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
147 |
+
model = LlavaLlamaForCausalLM.from_pretrained(
|
148 |
+
model_path, low_cpu_mem_usage=True, **kwargs
|
149 |
+
)
|
150 |
+
else:
|
151 |
+
# Load language model
|
152 |
+
if model_base is not None:
|
153 |
+
# PEFT model
|
154 |
+
from peft import PeftModel
|
155 |
+
|
156 |
+
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
157 |
+
model = AutoModelForCausalLM.from_pretrained(
|
158 |
+
model_base,
|
159 |
+
torch_dtype=torch.float16,
|
160 |
+
low_cpu_mem_usage=True,
|
161 |
+
device_map="auto",
|
162 |
+
)
|
163 |
+
print(f"Loading LoRA weights from {model_path}")
|
164 |
+
model = PeftModel.from_pretrained(model, model_path)
|
165 |
+
print(f"Merging weights")
|
166 |
+
model = model.merge_and_unload()
|
167 |
+
print("Convert to FP16...")
|
168 |
+
model.to(torch.float16)
|
169 |
+
else:
|
170 |
+
use_fast = False
|
171 |
+
if "mpt" in model_name.lower():
|
172 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
|
173 |
+
model = AutoModelForCausalLM.from_pretrained(
|
174 |
+
model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs
|
175 |
+
)
|
176 |
+
else:
|
177 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
178 |
+
model = AutoModelForCausalLM.from_pretrained(
|
179 |
+
model_path, low_cpu_mem_usage=True, **kwargs
|
180 |
+
)
|
181 |
+
|
182 |
+
image_processor = None
|
183 |
+
|
184 |
+
if "llava" in model_name.lower():
|
185 |
+
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
|
186 |
+
mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
|
187 |
+
if mm_use_im_patch_token:
|
188 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
189 |
+
if mm_use_im_start_end:
|
190 |
+
tokenizer.add_tokens(
|
191 |
+
[DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
|
192 |
+
)
|
193 |
+
model.resize_token_embeddings(len(tokenizer))
|
194 |
+
|
195 |
+
vision_tower = model.get_vision_tower()
|
196 |
+
if not vision_tower.is_loaded:
|
197 |
+
vision_tower.load_model()
|
198 |
+
vision_tower.to(device="cuda", dtype=torch.float16)
|
199 |
+
image_processor = vision_tower.image_processor
|
200 |
+
|
201 |
+
if hasattr(model.config, "max_sequence_length"):
|
202 |
+
context_len = model.config.max_sequence_length
|
203 |
+
else:
|
204 |
+
context_len = 2048
|
205 |
+
|
206 |
+
return tokenizer, model, image_processor, context_len
|
model/llava/model/consolidate.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Usage:
|
3 |
+
python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
|
4 |
+
"""
|
5 |
+
import argparse
|
6 |
+
|
7 |
+
import torch
|
8 |
+
from llava.model import *
|
9 |
+
from llava.model.utils import auto_upgrade
|
10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
11 |
+
|
12 |
+
|
13 |
+
def consolidate_ckpt(src_path, dst_path):
|
14 |
+
print("Loading model")
|
15 |
+
auto_upgrade(src_path)
|
16 |
+
src_model = AutoModelForCausalLM.from_pretrained(
|
17 |
+
src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
|
18 |
+
)
|
19 |
+
src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
|
20 |
+
src_model.save_pretrained(dst_path)
|
21 |
+
src_tokenizer.save_pretrained(dst_path)
|
22 |
+
|
23 |
+
|
24 |
+
if __name__ == "__main__":
|
25 |
+
parser = argparse.ArgumentParser()
|
26 |
+
parser.add_argument("--src", type=str, required=True)
|
27 |
+
parser.add_argument("--dst", type=str, required=True)
|
28 |
+
|
29 |
+
args = parser.parse_args()
|
30 |
+
|
31 |
+
consolidate_ckpt(args.src, args.dst)
|
model/llava/model/language_model/llava_llama.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Haotian Liu
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
|
16 |
+
from typing import List, Optional, Tuple, Union
|
17 |
+
|
18 |
+
import torch
|
19 |
+
import torch.nn as nn
|
20 |
+
from torch.nn import CrossEntropyLoss
|
21 |
+
from transformers import (AutoConfig, AutoModelForCausalLM, LlamaConfig,
|
22 |
+
LlamaForCausalLM, LlamaModel)
|
23 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
24 |
+
|
25 |
+
from ..llava_arch import LlavaMetaForCausalLM, LlavaMetaModel
|
26 |
+
|
27 |
+
|
28 |
+
class LlavaConfig(LlamaConfig):
|
29 |
+
model_type = "llava"
|
30 |
+
|
31 |
+
|
32 |
+
class LlavaLlamaModel(LlavaMetaModel, LlamaModel):
|
33 |
+
config_class = LlavaConfig
|
34 |
+
|
35 |
+
def __init__(self, config: LlamaConfig):
|
36 |
+
super(LlavaLlamaModel, self).__init__(config)
|
37 |
+
|
38 |
+
|
39 |
+
class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):
|
40 |
+
config_class = LlavaConfig
|
41 |
+
|
42 |
+
def __init__(self, config):
|
43 |
+
super(LlamaForCausalLM, self).__init__(config)
|
44 |
+
|
45 |
+
self.model = LlavaLlamaModel(config)
|
46 |
+
|
47 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
48 |
+
|
49 |
+
# Initialize weights and apply final processing
|
50 |
+
self.post_init()
|
51 |
+
|
52 |
+
def get_model(self):
|
53 |
+
return self.model
|
54 |
+
|
55 |
+
def forward(
|
56 |
+
self,
|
57 |
+
input_ids: torch.LongTensor = None,
|
58 |
+
attention_mask: Optional[torch.Tensor] = None,
|
59 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
60 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
61 |
+
labels: Optional[torch.LongTensor] = None,
|
62 |
+
use_cache: Optional[bool] = None,
|
63 |
+
output_attentions: Optional[bool] = None,
|
64 |
+
output_hidden_states: Optional[bool] = None,
|
65 |
+
images: Optional[torch.FloatTensor] = None,
|
66 |
+
return_dict: Optional[bool] = None,
|
67 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
68 |
+
output_attentions = (
|
69 |
+
output_attentions
|
70 |
+
if output_attentions is not None
|
71 |
+
else self.config.output_attentions
|
72 |
+
)
|
73 |
+
output_hidden_states = (
|
74 |
+
output_hidden_states
|
75 |
+
if output_hidden_states is not None
|
76 |
+
else self.config.output_hidden_states
|
77 |
+
)
|
78 |
+
return_dict = (
|
79 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
80 |
+
)
|
81 |
+
|
82 |
+
(
|
83 |
+
input_ids,
|
84 |
+
attention_mask,
|
85 |
+
past_key_values,
|
86 |
+
inputs_embeds,
|
87 |
+
labels,
|
88 |
+
) = self.prepare_inputs_labels_for_multimodal(
|
89 |
+
input_ids, attention_mask, past_key_values, labels, images
|
90 |
+
)
|
91 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
92 |
+
|
93 |
+
outputs = self.model(
|
94 |
+
input_ids=input_ids,
|
95 |
+
attention_mask=attention_mask,
|
96 |
+
past_key_values=past_key_values,
|
97 |
+
inputs_embeds=inputs_embeds,
|
98 |
+
use_cache=use_cache,
|
99 |
+
output_attentions=output_attentions,
|
100 |
+
output_hidden_states=output_hidden_states,
|
101 |
+
return_dict=return_dict,
|
102 |
+
)
|
103 |
+
|
104 |
+
hidden_states = outputs[0]
|
105 |
+
logits = self.lm_head(hidden_states)
|
106 |
+
|
107 |
+
loss = None
|
108 |
+
if labels is not None:
|
109 |
+
# Shift so that tokens < n predict n
|
110 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
111 |
+
shift_labels = labels[..., 1:].contiguous()
|
112 |
+
# Flatten the tokens
|
113 |
+
loss_fct = CrossEntropyLoss()
|
114 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
115 |
+
shift_labels = shift_labels.view(-1)
|
116 |
+
# Enable model/pipeline parallelism
|
117 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
118 |
+
loss = loss_fct(shift_logits, shift_labels)
|
119 |
+
|
120 |
+
if not return_dict:
|
121 |
+
output = (logits,) + outputs[1:]
|
122 |
+
return (loss,) + output if loss is not None else output
|
123 |
+
|
124 |
+
if self.training:
|
125 |
+
output_hidden_states = outputs.hidden_states
|
126 |
+
else:
|
127 |
+
output_hidden_states = hidden_states
|
128 |
+
|
129 |
+
return CausalLMOutputWithPast(
|
130 |
+
loss=loss,
|
131 |
+
logits=logits,
|
132 |
+
past_key_values=outputs.past_key_values,
|
133 |
+
hidden_states=output_hidden_states, # outputs.hidden_states,
|
134 |
+
attentions=outputs.attentions,
|
135 |
+
)
|
136 |
+
|
137 |
+
def prepare_inputs_for_generation(
|
138 |
+
self,
|
139 |
+
input_ids,
|
140 |
+
past_key_values=None,
|
141 |
+
attention_mask=None,
|
142 |
+
inputs_embeds=None,
|
143 |
+
images=None,
|
144 |
+
**kwargs
|
145 |
+
):
|
146 |
+
if past_key_values:
|
147 |
+
input_ids = input_ids[:, -1:]
|
148 |
+
|
149 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
150 |
+
if inputs_embeds is not None and past_key_values is None:
|
151 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
152 |
+
else:
|
153 |
+
model_inputs = {"input_ids": input_ids}
|
154 |
+
|
155 |
+
model_inputs.update(
|
156 |
+
{
|
157 |
+
"past_key_values": past_key_values,
|
158 |
+
"use_cache": kwargs.get("use_cache"),
|
159 |
+
"attention_mask": attention_mask,
|
160 |
+
"images": images,
|
161 |
+
}
|
162 |
+
)
|
163 |
+
return model_inputs
|
164 |
+
|
165 |
+
|
166 |
+
AutoConfig.register("llava", LlavaConfig)
|
167 |
+
AutoModelForCausalLM.register(LlavaConfig, LlavaLlamaForCausalLM)
|
model/llava/model/language_model/llava_mpt.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Haotian Liu
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
|
16 |
+
import math
|
17 |
+
import warnings
|
18 |
+
from typing import List, Optional, Tuple
|
19 |
+
|
20 |
+
import torch
|
21 |
+
import torch.nn.functional as F
|
22 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
23 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
24 |
+
|
25 |
+
from ..llava_arch import LlavaMetaForCausalLM, LlavaMetaModel
|
26 |
+
from .mpt.modeling_mpt import MPTConfig, MPTForCausalLM, MPTModel
|
27 |
+
|
28 |
+
|
29 |
+
class LlavaMPTConfig(MPTConfig):
|
30 |
+
model_type = "llava_mpt"
|
31 |
+
|
32 |
+
|
33 |
+
class LlavaMPTModel(LlavaMetaModel, MPTModel):
|
34 |
+
config_class = LlavaMPTConfig
|
35 |
+
|
36 |
+
def __init__(self, config: MPTConfig):
|
37 |
+
config.hidden_size = config.d_model
|
38 |
+
super(LlavaMPTModel, self).__init__(config)
|
39 |
+
|
40 |
+
def embed_tokens(self, x):
|
41 |
+
return self.wte(x)
|
42 |
+
|
43 |
+
|
44 |
+
class LlavaMPTForCausalLM(MPTForCausalLM, LlavaMetaForCausalLM):
|
45 |
+
config_class = LlavaMPTConfig
|
46 |
+
supports_gradient_checkpointing = True
|
47 |
+
|
48 |
+
def __init__(self, config):
|
49 |
+
super(MPTForCausalLM, self).__init__(config)
|
50 |
+
|
51 |
+
if not config.tie_word_embeddings:
|
52 |
+
raise ValueError("MPTForCausalLM only supports tied word embeddings")
|
53 |
+
self.transformer = LlavaMPTModel(config)
|
54 |
+
self.logit_scale = None
|
55 |
+
if config.logit_scale is not None:
|
56 |
+
logit_scale = config.logit_scale
|
57 |
+
if isinstance(logit_scale, str):
|
58 |
+
if logit_scale == "inv_sqrt_d_model":
|
59 |
+
logit_scale = 1 / math.sqrt(config.d_model)
|
60 |
+
else:
|
61 |
+
raise ValueError(
|
62 |
+
f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'."
|
63 |
+
)
|
64 |
+
self.logit_scale = logit_scale
|
65 |
+
|
66 |
+
def get_model(self):
|
67 |
+
return self.transformer
|
68 |
+
|
69 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
70 |
+
if isinstance(module, LlavaMPTModel):
|
71 |
+
module.gradient_checkpointing = value
|
72 |
+
|
73 |
+
def forward(
|
74 |
+
self,
|
75 |
+
input_ids: torch.LongTensor,
|
76 |
+
past_key_values: Optional[List[Tuple[torch.FloatTensor]]] = None,
|
77 |
+
attention_mask: Optional[torch.ByteTensor] = None,
|
78 |
+
prefix_mask: Optional[torch.ByteTensor] = None,
|
79 |
+
sequence_id: Optional[torch.LongTensor] = None,
|
80 |
+
labels: Optional[torch.LongTensor] = None,
|
81 |
+
return_dict: Optional[bool] = None,
|
82 |
+
output_attentions: Optional[bool] = None,
|
83 |
+
output_hidden_states: Optional[bool] = None,
|
84 |
+
use_cache: Optional[bool] = None,
|
85 |
+
images=None,
|
86 |
+
):
|
87 |
+
return_dict = (
|
88 |
+
return_dict if return_dict is not None else self.config.return_dict
|
89 |
+
)
|
90 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
91 |
+
|
92 |
+
(
|
93 |
+
input_ids,
|
94 |
+
attention_mask,
|
95 |
+
past_key_values,
|
96 |
+
inputs_embeds,
|
97 |
+
labels,
|
98 |
+
) = self.prepare_inputs_labels_for_multimodal(
|
99 |
+
input_ids, attention_mask, past_key_values, labels, images
|
100 |
+
)
|
101 |
+
outputs = self.transformer(
|
102 |
+
input_ids=input_ids,
|
103 |
+
inputs_embeds=inputs_embeds,
|
104 |
+
past_key_values=past_key_values,
|
105 |
+
attention_mask=attention_mask,
|
106 |
+
prefix_mask=prefix_mask,
|
107 |
+
sequence_id=sequence_id,
|
108 |
+
return_dict=return_dict,
|
109 |
+
output_attentions=output_attentions,
|
110 |
+
output_hidden_states=output_hidden_states,
|
111 |
+
use_cache=use_cache,
|
112 |
+
)
|
113 |
+
# FIXME: this is a hack to fix the multiple gpu inference issue in https://github.com/haotian-liu/LLaVA/issues/338
|
114 |
+
logits = F.linear(
|
115 |
+
outputs.last_hidden_state.to(self.transformer.wte.weight.device),
|
116 |
+
self.transformer.wte.weight,
|
117 |
+
)
|
118 |
+
if self.logit_scale is not None:
|
119 |
+
if self.logit_scale == 0:
|
120 |
+
warnings.warn(
|
121 |
+
f"Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs."
|
122 |
+
)
|
123 |
+
logits *= self.logit_scale
|
124 |
+
loss = None
|
125 |
+
if labels is not None:
|
126 |
+
labels = torch.roll(labels, shifts=-1)
|
127 |
+
labels[:, -1] = -100
|
128 |
+
loss = F.cross_entropy(
|
129 |
+
logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1)
|
130 |
+
)
|
131 |
+
return CausalLMOutputWithPast(
|
132 |
+
loss=loss,
|
133 |
+
logits=logits,
|
134 |
+
past_key_values=outputs.past_key_values,
|
135 |
+
hidden_states=outputs.hidden_states,
|
136 |
+
)
|
137 |
+
|
138 |
+
def prepare_inputs_for_generation(
|
139 |
+
self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
|
140 |
+
):
|
141 |
+
if inputs_embeds is not None:
|
142 |
+
raise NotImplementedError("inputs_embeds is not implemented for MPT yet")
|
143 |
+
attention_mask = kwargs["attention_mask"].bool()
|
144 |
+
if attention_mask[:, -1].sum() != attention_mask.shape[0]:
|
145 |
+
raise NotImplementedError(
|
146 |
+
"MPT does not support generation with right padding."
|
147 |
+
)
|
148 |
+
if self.transformer.attn_uses_sequence_id and self.training:
|
149 |
+
sequence_id = torch.zeros_like(input_ids[:1])
|
150 |
+
else:
|
151 |
+
sequence_id = None
|
152 |
+
if past_key_values is not None:
|
153 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
154 |
+
if self.transformer.prefix_lm:
|
155 |
+
prefix_mask = torch.ones_like(attention_mask)
|
156 |
+
if kwargs.get("use_cache") == False:
|
157 |
+
raise NotImplementedError(
|
158 |
+
"MPT with prefix_lm=True does not support use_cache=False."
|
159 |
+
)
|
160 |
+
else:
|
161 |
+
prefix_mask = None
|
162 |
+
return {
|
163 |
+
"input_ids": input_ids,
|
164 |
+
"attention_mask": attention_mask,
|
165 |
+
"prefix_mask": prefix_mask,
|
166 |
+
"sequence_id": sequence_id,
|
167 |
+
"past_key_values": past_key_values,
|
168 |
+
"use_cache": kwargs.get("use_cache", True),
|
169 |
+
"images": kwargs.get("images", None),
|
170 |
+
}
|
171 |
+
|
172 |
+
|
173 |
+
AutoConfig.register("llava_mpt", LlavaMPTConfig)
|
174 |
+
AutoModelForCausalLM.register(LlavaMPTConfig, LlavaMPTForCausalLM)
|
model/llava/model/language_model/mpt/adapt_tokenizer.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Union
|
2 |
+
|
3 |
+
from transformers import (AutoTokenizer, PreTrainedTokenizer,
|
4 |
+
PreTrainedTokenizerFast)
|
5 |
+
|
6 |
+
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
7 |
+
NUM_SENTINEL_TOKENS: int = 100
|
8 |
+
|
9 |
+
|
10 |
+
def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
|
11 |
+
"""Adds sentinel tokens and padding token (if missing).
|
12 |
+
|
13 |
+
Expands the tokenizer vocabulary to include sentinel tokens
|
14 |
+
used in mixture-of-denoiser tasks as well as a padding token.
|
15 |
+
|
16 |
+
All added tokens are added as special tokens. No tokens are
|
17 |
+
added if sentinel tokens and padding token already exist.
|
18 |
+
"""
|
19 |
+
sentinels_to_add = [f"<extra_id_{i}>" for i in range(NUM_SENTINEL_TOKENS)]
|
20 |
+
tokenizer.add_tokens(sentinels_to_add, special_tokens=True)
|
21 |
+
if tokenizer.pad_token is None:
|
22 |
+
tokenizer.add_tokens("<pad>", special_tokens=True)
|
23 |
+
tokenizer.pad_token = "<pad>"
|
24 |
+
assert tokenizer.pad_token_id is not None
|
25 |
+
sentinels = "".join([f"<extra_id_{i}>" for i in range(NUM_SENTINEL_TOKENS)])
|
26 |
+
_sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids
|
27 |
+
tokenizer.sentinel_token_ids = _sentinel_token_ids
|
28 |
+
|
29 |
+
|
30 |
+
class AutoTokenizerForMOD(AutoTokenizer):
|
31 |
+
"""AutoTokenizer + Adaptation for MOD.
|
32 |
+
|
33 |
+
A simple wrapper around AutoTokenizer to make instantiating
|
34 |
+
an MOD-adapted tokenizer a bit easier.
|
35 |
+
|
36 |
+
MOD-adapted tokenizers have sentinel tokens (e.g., <extra_id_0>),
|
37 |
+
a padding token, and a property to get the token ids of the
|
38 |
+
sentinel tokens.
|
39 |
+
"""
|
40 |
+
|
41 |
+
@classmethod
|
42 |
+
def from_pretrained(cls, *args, **kwargs):
|
43 |
+
"""See `AutoTokenizer.from_pretrained` docstring."""
|
44 |
+
tokenizer = super().from_pretrained(*args, **kwargs)
|
45 |
+
adapt_tokenizer_for_denoising(tokenizer)
|
46 |
+
return tokenizer
|
model/llava/model/language_model/mpt/attention.py
ADDED
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Attention layers."""
|
2 |
+
import math
|
3 |
+
import warnings
|
4 |
+
from typing import Optional
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn as nn
|
8 |
+
from einops import rearrange
|
9 |
+
from packaging import version
|
10 |
+
from torch import nn
|
11 |
+
|
12 |
+
from .norm import LPLayerNorm
|
13 |
+
|
14 |
+
|
15 |
+
def _reset_is_causal(
|
16 |
+
num_query_tokens: int, num_key_tokens: int, original_is_causal: bool
|
17 |
+
):
|
18 |
+
if original_is_causal and num_query_tokens != num_key_tokens:
|
19 |
+
if num_query_tokens != 1:
|
20 |
+
raise NotImplementedError(
|
21 |
+
"MPT does not support query and key with different number of tokens, unless number of query tokens is 1."
|
22 |
+
)
|
23 |
+
else:
|
24 |
+
return False
|
25 |
+
return original_is_causal
|
26 |
+
|
27 |
+
|
28 |
+
def scaled_multihead_dot_product_attention(
|
29 |
+
query,
|
30 |
+
key,
|
31 |
+
value,
|
32 |
+
n_heads,
|
33 |
+
past_key_value=None,
|
34 |
+
softmax_scale=None,
|
35 |
+
attn_bias=None,
|
36 |
+
key_padding_mask=None,
|
37 |
+
is_causal=False,
|
38 |
+
dropout_p=0.0,
|
39 |
+
training=False,
|
40 |
+
needs_weights=False,
|
41 |
+
multiquery=False,
|
42 |
+
):
|
43 |
+
q = rearrange(query, "b s (h d) -> b h s d", h=n_heads)
|
44 |
+
kv_n_heads = 1 if multiquery else n_heads
|
45 |
+
k = rearrange(key, "b s (h d) -> b h d s", h=kv_n_heads)
|
46 |
+
v = rearrange(value, "b s (h d) -> b h s d", h=kv_n_heads)
|
47 |
+
if past_key_value is not None:
|
48 |
+
if len(past_key_value) != 0:
|
49 |
+
k = torch.cat([past_key_value[0], k], dim=3)
|
50 |
+
v = torch.cat([past_key_value[1], v], dim=2)
|
51 |
+
past_key_value = (k, v)
|
52 |
+
(b, _, s_q, d) = q.shape
|
53 |
+
s_k = k.size(-1)
|
54 |
+
if softmax_scale is None:
|
55 |
+
softmax_scale = 1 / math.sqrt(d)
|
56 |
+
attn_weight = q.matmul(k) * softmax_scale
|
57 |
+
if attn_bias is not None:
|
58 |
+
_s_q = max(0, attn_bias.size(2) - s_q)
|
59 |
+
_s_k = max(0, attn_bias.size(3) - s_k)
|
60 |
+
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
61 |
+
if (
|
62 |
+
attn_bias.size(-1) != 1
|
63 |
+
and attn_bias.size(-1) != s_k
|
64 |
+
or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q)
|
65 |
+
):
|
66 |
+
raise RuntimeError(
|
67 |
+
f"attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}."
|
68 |
+
)
|
69 |
+
attn_weight = attn_weight + attn_bias
|
70 |
+
min_val = torch.finfo(q.dtype).min
|
71 |
+
if key_padding_mask is not None:
|
72 |
+
if attn_bias is not None:
|
73 |
+
warnings.warn(
|
74 |
+
"Propogating key_padding_mask to the attention module "
|
75 |
+
+ "and applying it within the attention module can cause "
|
76 |
+
+ "unneccessary computation/memory usage. Consider integrating "
|
77 |
+
+ "into attn_bias once and passing that to each attention "
|
78 |
+
+ "module instead."
|
79 |
+
)
|
80 |
+
attn_weight = attn_weight.masked_fill(
|
81 |
+
~key_padding_mask.view((b, 1, 1, s_k)), min_val
|
82 |
+
)
|
83 |
+
if is_causal and (not q.size(2) == 1):
|
84 |
+
s = max(s_q, s_k)
|
85 |
+
causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
|
86 |
+
causal_mask = causal_mask.tril()
|
87 |
+
causal_mask = causal_mask.to(torch.bool)
|
88 |
+
causal_mask = ~causal_mask
|
89 |
+
causal_mask = causal_mask[-s_q:, -s_k:]
|
90 |
+
attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
|
91 |
+
attn_weight = torch.softmax(attn_weight, dim=-1)
|
92 |
+
if dropout_p:
|
93 |
+
attn_weight = torch.nn.functional.dropout(
|
94 |
+
attn_weight, p=dropout_p, training=training, inplace=True
|
95 |
+
)
|
96 |
+
out = attn_weight.to(v.dtype).matmul(v)
|
97 |
+
out = rearrange(out, "b h s d -> b s (h d)")
|
98 |
+
if needs_weights:
|
99 |
+
return (out, attn_weight, past_key_value)
|
100 |
+
return (out, None, past_key_value)
|
101 |
+
|
102 |
+
|
103 |
+
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
|
104 |
+
for tensor in tensors:
|
105 |
+
if tensor.dtype not in valid_dtypes:
|
106 |
+
raise TypeError(
|
107 |
+
f"tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}."
|
108 |
+
)
|
109 |
+
if not tensor.is_cuda:
|
110 |
+
raise TypeError(
|
111 |
+
f"Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r})."
|
112 |
+
)
|
113 |
+
|
114 |
+
|
115 |
+
def flash_attn_fn(
|
116 |
+
query,
|
117 |
+
key,
|
118 |
+
value,
|
119 |
+
n_heads,
|
120 |
+
past_key_value=None,
|
121 |
+
softmax_scale=None,
|
122 |
+
attn_bias=None,
|
123 |
+
key_padding_mask=None,
|
124 |
+
is_causal=False,
|
125 |
+
dropout_p=0.0,
|
126 |
+
training=False,
|
127 |
+
needs_weights=False,
|
128 |
+
multiquery=False,
|
129 |
+
):
|
130 |
+
try:
|
131 |
+
from flash_attn import bert_padding, flash_attn_interface
|
132 |
+
except:
|
133 |
+
raise RuntimeError("Please install flash-attn==1.0.3.post0")
|
134 |
+
check_valid_inputs(query, key, value)
|
135 |
+
if past_key_value is not None:
|
136 |
+
if len(past_key_value) != 0:
|
137 |
+
key = torch.cat([past_key_value[0], key], dim=1)
|
138 |
+
value = torch.cat([past_key_value[1], value], dim=1)
|
139 |
+
past_key_value = (key, value)
|
140 |
+
if attn_bias is not None:
|
141 |
+
_s_q = max(0, attn_bias.size(2) - query.size(1))
|
142 |
+
_s_k = max(0, attn_bias.size(3) - key.size(1))
|
143 |
+
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
144 |
+
if attn_bias is not None:
|
145 |
+
raise NotImplementedError(f"attn_bias not implemented for flash attn.")
|
146 |
+
(batch_size, seqlen) = query.shape[:2]
|
147 |
+
if key_padding_mask is None:
|
148 |
+
key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
|
149 |
+
query_padding_mask = key_padding_mask[:, -query.size(1) :]
|
150 |
+
(query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(
|
151 |
+
query, query_padding_mask
|
152 |
+
)
|
153 |
+
query_unpad = rearrange(query_unpad, "nnz (h d) -> nnz h d", h=n_heads)
|
154 |
+
(key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(
|
155 |
+
key, key_padding_mask
|
156 |
+
)
|
157 |
+
key_unpad = rearrange(
|
158 |
+
key_unpad, "nnz (h d) -> nnz h d", h=1 if multiquery else n_heads
|
159 |
+
)
|
160 |
+
(value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
|
161 |
+
value_unpad = rearrange(
|
162 |
+
value_unpad, "nnz (h d) -> nnz h d", h=1 if multiquery else n_heads
|
163 |
+
)
|
164 |
+
if multiquery:
|
165 |
+
key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
|
166 |
+
value_unpad = value_unpad.expand(
|
167 |
+
value_unpad.size(0), n_heads, value_unpad.size(-1)
|
168 |
+
)
|
169 |
+
dropout_p = dropout_p if training else 0.0
|
170 |
+
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
171 |
+
output_unpad = flash_attn_interface.flash_attn_unpadded_func(
|
172 |
+
query_unpad,
|
173 |
+
key_unpad,
|
174 |
+
value_unpad,
|
175 |
+
cu_seqlens_q,
|
176 |
+
cu_seqlens_k,
|
177 |
+
max_seqlen_q,
|
178 |
+
max_seqlen_k,
|
179 |
+
dropout_p,
|
180 |
+
softmax_scale=softmax_scale,
|
181 |
+
causal=reset_is_causal,
|
182 |
+
return_attn_probs=needs_weights,
|
183 |
+
)
|
184 |
+
output = bert_padding.pad_input(
|
185 |
+
rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices_q, batch_size, seqlen
|
186 |
+
)
|
187 |
+
return (output, None, past_key_value)
|
188 |
+
|
189 |
+
|
190 |
+
def triton_flash_attn_fn(
|
191 |
+
query,
|
192 |
+
key,
|
193 |
+
value,
|
194 |
+
n_heads,
|
195 |
+
past_key_value=None,
|
196 |
+
softmax_scale=None,
|
197 |
+
attn_bias=None,
|
198 |
+
key_padding_mask=None,
|
199 |
+
is_causal=False,
|
200 |
+
dropout_p=0.0,
|
201 |
+
training=False,
|
202 |
+
needs_weights=False,
|
203 |
+
multiquery=False,
|
204 |
+
):
|
205 |
+
try:
|
206 |
+
from .flash_attn_triton import flash_attn_func
|
207 |
+
except:
|
208 |
+
_installed = False
|
209 |
+
if version.parse(torch.__version__) < version.parse("2.0.0"):
|
210 |
+
_installed = True
|
211 |
+
try:
|
212 |
+
from flash_attn.flash_attn_triton import flash_attn_func
|
213 |
+
except:
|
214 |
+
_installed = False
|
215 |
+
if not _installed:
|
216 |
+
raise RuntimeError(
|
217 |
+
"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."
|
218 |
+
)
|
219 |
+
check_valid_inputs(query, key, value)
|
220 |
+
if past_key_value is not None:
|
221 |
+
if len(past_key_value) != 0:
|
222 |
+
key = torch.cat([past_key_value[0], key], dim=1)
|
223 |
+
value = torch.cat([past_key_value[1], value], dim=1)
|
224 |
+
past_key_value = (key, value)
|
225 |
+
if attn_bias is not None:
|
226 |
+
_s_q = max(0, attn_bias.size(2) - query.size(1))
|
227 |
+
_s_k = max(0, attn_bias.size(3) - key.size(1))
|
228 |
+
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
229 |
+
if dropout_p:
|
230 |
+
raise NotImplementedError(f"Dropout not implemented for attn_impl: triton.")
|
231 |
+
if needs_weights:
|
232 |
+
raise NotImplementedError(f"attn_impl: triton cannot return attn weights.")
|
233 |
+
if key_padding_mask is not None:
|
234 |
+
warnings.warn(
|
235 |
+
"Propagating key_padding_mask to the attention module "
|
236 |
+
+ "and applying it within the attention module can cause "
|
237 |
+
+ "unnecessary computation/memory usage. Consider integrating "
|
238 |
+
+ "into attn_bias once and passing that to each attention "
|
239 |
+
+ "module instead."
|
240 |
+
)
|
241 |
+
(b_size, s_k) = key_padding_mask.shape[:2]
|
242 |
+
if attn_bias is None:
|
243 |
+
attn_bias = query.new_zeros(b_size, 1, 1, s_k)
|
244 |
+
attn_bias = attn_bias.masked_fill(
|
245 |
+
~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min
|
246 |
+
)
|
247 |
+
query = rearrange(query, "b s (h d) -> b s h d", h=n_heads)
|
248 |
+
key = rearrange(key, "b s (h d) -> b s h d", h=1 if multiquery else n_heads)
|
249 |
+
value = rearrange(value, "b s (h d) -> b s h d", h=1 if multiquery else n_heads)
|
250 |
+
if multiquery:
|
251 |
+
key = key.expand(*key.shape[:2], n_heads, key.size(-1))
|
252 |
+
value = value.expand(*value.shape[:2], n_heads, value.size(-1))
|
253 |
+
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
254 |
+
attn_output = flash_attn_func(
|
255 |
+
query, key, value, attn_bias, reset_is_causal, softmax_scale
|
256 |
+
)
|
257 |
+
output = attn_output.view(*attn_output.shape[:2], -1)
|
258 |
+
return (output, None, past_key_value)
|
259 |
+
|
260 |
+
|
261 |
+
class MultiheadAttention(nn.Module):
|
262 |
+
"""Multi-head self attention.
|
263 |
+
|
264 |
+
Using torch or triton attention implemetation enables user to also use
|
265 |
+
additive bias.
|
266 |
+
"""
|
267 |
+
|
268 |
+
def __init__(
|
269 |
+
self,
|
270 |
+
d_model: int,
|
271 |
+
n_heads: int,
|
272 |
+
attn_impl: str = "triton",
|
273 |
+
clip_qkv: Optional[float] = None,
|
274 |
+
qk_ln: bool = False,
|
275 |
+
softmax_scale: Optional[float] = None,
|
276 |
+
attn_pdrop: float = 0.0,
|
277 |
+
low_precision_layernorm: bool = False,
|
278 |
+
verbose: int = 0,
|
279 |
+
device: Optional[str] = None,
|
280 |
+
):
|
281 |
+
super().__init__()
|
282 |
+
self.attn_impl = attn_impl
|
283 |
+
self.clip_qkv = clip_qkv
|
284 |
+
self.qk_ln = qk_ln
|
285 |
+
self.d_model = d_model
|
286 |
+
self.n_heads = n_heads
|
287 |
+
self.softmax_scale = softmax_scale
|
288 |
+
if self.softmax_scale is None:
|
289 |
+
self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
|
290 |
+
self.attn_dropout_p = attn_pdrop
|
291 |
+
self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
|
292 |
+
fuse_splits = (d_model, 2 * d_model)
|
293 |
+
self.Wqkv._fused = (0, fuse_splits)
|
294 |
+
if self.qk_ln:
|
295 |
+
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
296 |
+
self.q_ln = layernorm_class(self.d_model, device=device)
|
297 |
+
self.k_ln = layernorm_class(self.d_model, device=device)
|
298 |
+
if self.attn_impl == "flash":
|
299 |
+
self.attn_fn = flash_attn_fn
|
300 |
+
elif self.attn_impl == "triton":
|
301 |
+
self.attn_fn = triton_flash_attn_fn
|
302 |
+
if verbose:
|
303 |
+
warnings.warn(
|
304 |
+
"While `attn_impl: triton` can be faster than `attn_impl: flash` "
|
305 |
+
+ "it uses more memory. When training larger models this can trigger "
|
306 |
+
+ "alloc retries which hurts performance. If encountered, we recommend "
|
307 |
+
+ "using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`."
|
308 |
+
)
|
309 |
+
elif self.attn_impl == "torch":
|
310 |
+
self.attn_fn = scaled_multihead_dot_product_attention
|
311 |
+
if torch.cuda.is_available() and verbose:
|
312 |
+
warnings.warn(
|
313 |
+
"Using `attn_impl: torch`. If your model does not use `alibi` or "
|
314 |
+
+ "`prefix_lm` we recommend using `attn_impl: flash` otherwise "
|
315 |
+
+ "we recommend using `attn_impl: triton`."
|
316 |
+
)
|
317 |
+
else:
|
318 |
+
raise ValueError(f"attn_impl={attn_impl!r} is an invalid setting.")
|
319 |
+
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
320 |
+
self.out_proj._is_residual = True
|
321 |
+
|
322 |
+
def forward(
|
323 |
+
self,
|
324 |
+
x,
|
325 |
+
past_key_value=None,
|
326 |
+
attn_bias=None,
|
327 |
+
attention_mask=None,
|
328 |
+
is_causal=True,
|
329 |
+
needs_weights=False,
|
330 |
+
):
|
331 |
+
qkv = self.Wqkv(x)
|
332 |
+
if self.clip_qkv:
|
333 |
+
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
334 |
+
(query, key, value) = qkv.chunk(3, dim=2)
|
335 |
+
key_padding_mask = attention_mask
|
336 |
+
if self.qk_ln:
|
337 |
+
dtype = query.dtype
|
338 |
+
query = self.q_ln(query).to(dtype)
|
339 |
+
key = self.k_ln(key).to(dtype)
|
340 |
+
(context, attn_weights, past_key_value) = self.attn_fn(
|
341 |
+
query,
|
342 |
+
key,
|
343 |
+
value,
|
344 |
+
self.n_heads,
|
345 |
+
past_key_value=past_key_value,
|
346 |
+
softmax_scale=self.softmax_scale,
|
347 |
+
attn_bias=attn_bias,
|
348 |
+
key_padding_mask=key_padding_mask,
|
349 |
+
is_causal=is_causal,
|
350 |
+
dropout_p=self.attn_dropout_p,
|
351 |
+
training=self.training,
|
352 |
+
needs_weights=needs_weights,
|
353 |
+
)
|
354 |
+
return (self.out_proj(context), attn_weights, past_key_value)
|
355 |
+
|
356 |
+
|
357 |
+
class MultiQueryAttention(nn.Module):
|
358 |
+
"""Multi-Query self attention.
|
359 |
+
|
360 |
+
Using torch or triton attention implemetation enables user to also use
|
361 |
+
additive bias.
|
362 |
+
"""
|
363 |
+
|
364 |
+
def __init__(
|
365 |
+
self,
|
366 |
+
d_model: int,
|
367 |
+
n_heads: int,
|
368 |
+
attn_impl: str = "triton",
|
369 |
+
clip_qkv: Optional[float] = None,
|
370 |
+
qk_ln: bool = False,
|
371 |
+
softmax_scale: Optional[float] = None,
|
372 |
+
attn_pdrop: float = 0.0,
|
373 |
+
low_precision_layernorm: bool = False,
|
374 |
+
verbose: int = 0,
|
375 |
+
device: Optional[str] = None,
|
376 |
+
):
|
377 |
+
super().__init__()
|
378 |
+
self.attn_impl = attn_impl
|
379 |
+
self.clip_qkv = clip_qkv
|
380 |
+
self.qk_ln = qk_ln
|
381 |
+
self.d_model = d_model
|
382 |
+
self.n_heads = n_heads
|
383 |
+
self.head_dim = d_model // n_heads
|
384 |
+
self.softmax_scale = softmax_scale
|
385 |
+
if self.softmax_scale is None:
|
386 |
+
self.softmax_scale = 1 / math.sqrt(self.head_dim)
|
387 |
+
self.attn_dropout_p = attn_pdrop
|
388 |
+
self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device)
|
389 |
+
fuse_splits = (d_model, d_model + self.head_dim)
|
390 |
+
self.Wqkv._fused = (0, fuse_splits)
|
391 |
+
if self.qk_ln:
|
392 |
+
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
393 |
+
self.q_ln = layernorm_class(d_model, device=device)
|
394 |
+
self.k_ln = layernorm_class(self.head_dim, device=device)
|
395 |
+
if self.attn_impl == "flash":
|
396 |
+
self.attn_fn = flash_attn_fn
|
397 |
+
elif self.attn_impl == "triton":
|
398 |
+
self.attn_fn = triton_flash_attn_fn
|
399 |
+
if verbose:
|
400 |
+
warnings.warn(
|
401 |
+
"While `attn_impl: triton` can be faster than `attn_impl: flash` "
|
402 |
+
+ "it uses more memory. When training larger models this can trigger "
|
403 |
+
+ "alloc retries which hurts performance. If encountered, we recommend "
|
404 |
+
+ "using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`."
|
405 |
+
)
|
406 |
+
elif self.attn_impl == "torch":
|
407 |
+
self.attn_fn = scaled_multihead_dot_product_attention
|
408 |
+
if torch.cuda.is_available() and verbose:
|
409 |
+
warnings.warn(
|
410 |
+
"Using `attn_impl: torch`. If your model does not use `alibi` or "
|
411 |
+
+ "`prefix_lm` we recommend using `attn_impl: flash` otherwise "
|
412 |
+
+ "we recommend using `attn_impl: triton`."
|
413 |
+
)
|
414 |
+
else:
|
415 |
+
raise ValueError(f"attn_impl={attn_impl!r} is an invalid setting.")
|
416 |
+
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
417 |
+
self.out_proj._is_residual = True
|
418 |
+
|
419 |
+
def forward(
|
420 |
+
self,
|
421 |
+
x,
|
422 |
+
past_key_value=None,
|
423 |
+
attn_bias=None,
|
424 |
+
attention_mask=None,
|
425 |
+
is_causal=True,
|
426 |
+
needs_weights=False,
|
427 |
+
):
|
428 |
+
qkv = self.Wqkv(x)
|
429 |
+
if self.clip_qkv:
|
430 |
+
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
431 |
+
(query, key, value) = qkv.split(
|
432 |
+
[self.d_model, self.head_dim, self.head_dim], dim=2
|
433 |
+
)
|
434 |
+
key_padding_mask = attention_mask
|
435 |
+
if self.qk_ln:
|
436 |
+
dtype = query.dtype
|
437 |
+
query = self.q_ln(query).to(dtype)
|
438 |
+
key = self.k_ln(key).to(dtype)
|
439 |
+
(context, attn_weights, past_key_value) = self.attn_fn(
|
440 |
+
query,
|
441 |
+
key,
|
442 |
+
value,
|
443 |
+
self.n_heads,
|
444 |
+
past_key_value=past_key_value,
|
445 |
+
softmax_scale=self.softmax_scale,
|
446 |
+
attn_bias=attn_bias,
|
447 |
+
key_padding_mask=key_padding_mask,
|
448 |
+
is_causal=is_causal,
|
449 |
+
dropout_p=self.attn_dropout_p,
|
450 |
+
training=self.training,
|
451 |
+
needs_weights=needs_weights,
|
452 |
+
multiquery=True,
|
453 |
+
)
|
454 |
+
return (self.out_proj(context), attn_weights, past_key_value)
|
455 |
+
|
456 |
+
|
457 |
+
def attn_bias_shape(
|
458 |
+
attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id
|
459 |
+
):
|
460 |
+
if attn_impl == "flash":
|
461 |
+
return None
|
462 |
+
elif attn_impl in ["torch", "triton"]:
|
463 |
+
if alibi:
|
464 |
+
if (prefix_lm or not causal) or use_sequence_id:
|
465 |
+
return (1, n_heads, seq_len, seq_len)
|
466 |
+
return (1, n_heads, 1, seq_len)
|
467 |
+
elif prefix_lm or use_sequence_id:
|
468 |
+
return (1, 1, seq_len, seq_len)
|
469 |
+
return None
|
470 |
+
else:
|
471 |
+
raise ValueError(f"attn_impl={attn_impl!r} is an invalid setting.")
|
472 |
+
|
473 |
+
|
474 |
+
def build_attn_bias(
|
475 |
+
attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8
|
476 |
+
):
|
477 |
+
if attn_impl == "flash":
|
478 |
+
return None
|
479 |
+
elif attn_impl in ["torch", "triton"]:
|
480 |
+
if alibi:
|
481 |
+
(device, dtype) = (attn_bias.device, attn_bias.dtype)
|
482 |
+
attn_bias = attn_bias.add(
|
483 |
+
build_alibi_bias(
|
484 |
+
n_heads,
|
485 |
+
seq_len,
|
486 |
+
full=not causal,
|
487 |
+
alibi_bias_max=alibi_bias_max,
|
488 |
+
device=device,
|
489 |
+
dtype=dtype,
|
490 |
+
)
|
491 |
+
)
|
492 |
+
return attn_bias
|
493 |
+
else:
|
494 |
+
raise ValueError(f"attn_impl={attn_impl!r} is an invalid setting.")
|
495 |
+
|
496 |
+
|
497 |
+
def gen_slopes(n_heads, alibi_bias_max=8, device=None):
|
498 |
+
_n_heads = 2 ** math.ceil(math.log2(n_heads))
|
499 |
+
m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
|
500 |
+
m = m.mul(alibi_bias_max / _n_heads)
|
501 |
+
slopes = 1.0 / torch.pow(2, m)
|
502 |
+
if _n_heads != n_heads:
|
503 |
+
slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
|
504 |
+
return slopes.view(1, n_heads, 1, 1)
|
505 |
+
|
506 |
+
|
507 |
+
def build_alibi_bias(
|
508 |
+
n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None
|
509 |
+
):
|
510 |
+
alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(
|
511 |
+
1, 1, 1, seq_len
|
512 |
+
)
|
513 |
+
if full:
|
514 |
+
alibi_bias = alibi_bias - torch.arange(
|
515 |
+
1 - seq_len, 1, dtype=torch.int32, device=device
|
516 |
+
).view(1, 1, seq_len, 1)
|
517 |
+
alibi_bias = alibi_bias.abs().mul(-1)
|
518 |
+
slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
|
519 |
+
alibi_bias = alibi_bias * slopes
|
520 |
+
return alibi_bias.to(dtype=dtype)
|
521 |
+
|
522 |
+
|
523 |
+
ATTN_CLASS_REGISTRY = {
|
524 |
+
"multihead_attention": MultiheadAttention,
|
525 |
+
"multiquery_attention": MultiQueryAttention,
|
526 |
+
}
|
model/llava/model/language_model/mpt/blocks.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""GPT Blocks used for the GPT Model."""
|
2 |
+
from typing import Dict, Optional, Tuple
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
|
7 |
+
from .attention import ATTN_CLASS_REGISTRY
|
8 |
+
from .norm import NORM_CLASS_REGISTRY
|
9 |
+
|
10 |
+
|
11 |
+
class MPTMLP(nn.Module):
|
12 |
+
def __init__(
|
13 |
+
self, d_model: int, expansion_ratio: int, device: Optional[str] = None
|
14 |
+
):
|
15 |
+
super().__init__()
|
16 |
+
self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device)
|
17 |
+
self.act = nn.GELU(approximate="none")
|
18 |
+
self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device)
|
19 |
+
self.down_proj._is_residual = True
|
20 |
+
|
21 |
+
def forward(self, x):
|
22 |
+
return self.down_proj(self.act(self.up_proj(x)))
|
23 |
+
|
24 |
+
|
25 |
+
class MPTBlock(nn.Module):
|
26 |
+
def __init__(
|
27 |
+
self,
|
28 |
+
d_model: int,
|
29 |
+
n_heads: int,
|
30 |
+
expansion_ratio: int,
|
31 |
+
attn_config: Dict = {
|
32 |
+
"attn_type": "multihead_attention",
|
33 |
+
"attn_pdrop": 0.0,
|
34 |
+
"attn_impl": "triton",
|
35 |
+
"qk_ln": False,
|
36 |
+
"clip_qkv": None,
|
37 |
+
"softmax_scale": None,
|
38 |
+
"prefix_lm": False,
|
39 |
+
"attn_uses_sequence_id": False,
|
40 |
+
"alibi": False,
|
41 |
+
"alibi_bias_max": 8,
|
42 |
+
},
|
43 |
+
resid_pdrop: float = 0.0,
|
44 |
+
norm_type: str = "low_precision_layernorm",
|
45 |
+
verbose: int = 0,
|
46 |
+
device: Optional[str] = None,
|
47 |
+
**kwargs
|
48 |
+
):
|
49 |
+
del kwargs
|
50 |
+
super().__init__()
|
51 |
+
norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
|
52 |
+
attn_class = ATTN_CLASS_REGISTRY[attn_config["attn_type"]]
|
53 |
+
self.norm_1 = norm_class(d_model, device=device)
|
54 |
+
self.attn = attn_class(
|
55 |
+
attn_impl=attn_config["attn_impl"],
|
56 |
+
clip_qkv=attn_config["clip_qkv"],
|
57 |
+
qk_ln=attn_config["qk_ln"],
|
58 |
+
softmax_scale=attn_config["softmax_scale"],
|
59 |
+
attn_pdrop=attn_config["attn_pdrop"],
|
60 |
+
d_model=d_model,
|
61 |
+
n_heads=n_heads,
|
62 |
+
verbose=verbose,
|
63 |
+
device=device,
|
64 |
+
)
|
65 |
+
self.norm_2 = norm_class(d_model, device=device)
|
66 |
+
self.ffn = MPTMLP(
|
67 |
+
d_model=d_model, expansion_ratio=expansion_ratio, device=device
|
68 |
+
)
|
69 |
+
self.resid_attn_dropout = nn.Dropout(resid_pdrop)
|
70 |
+
self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
|
71 |
+
|
72 |
+
def forward(
|
73 |
+
self,
|
74 |
+
x: torch.Tensor,
|
75 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
76 |
+
attn_bias: Optional[torch.Tensor] = None,
|
77 |
+
attention_mask: Optional[torch.ByteTensor] = None,
|
78 |
+
is_causal: bool = True,
|
79 |
+
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]:
|
80 |
+
a = self.norm_1(x)
|
81 |
+
(b, attn_weights, past_key_value) = self.attn(
|
82 |
+
a,
|
83 |
+
past_key_value=past_key_value,
|
84 |
+
attn_bias=attn_bias,
|
85 |
+
attention_mask=attention_mask,
|
86 |
+
is_causal=is_causal,
|
87 |
+
)
|
88 |
+
x = x + self.resid_attn_dropout(b)
|
89 |
+
m = self.norm_2(x)
|
90 |
+
n = self.ffn(m)
|
91 |
+
x = x + self.resid_ffn_dropout(n)
|
92 |
+
return (x, attn_weights, past_key_value)
|
model/llava/model/language_model/mpt/configuration_mpt.py
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""A HuggingFace-style model configuration."""
|
2 |
+
from typing import Dict, Optional, Union
|
3 |
+
|
4 |
+
from transformers import PretrainedConfig
|
5 |
+
|
6 |
+
attn_config_defaults: Dict = {
|
7 |
+
"attn_type": "multihead_attention",
|
8 |
+
"attn_pdrop": 0.0,
|
9 |
+
"attn_impl": "triton",
|
10 |
+
"qk_ln": False,
|
11 |
+
"clip_qkv": None,
|
12 |
+
"softmax_scale": None,
|
13 |
+
"prefix_lm": False,
|
14 |
+
"attn_uses_sequence_id": False,
|
15 |
+
"alibi": False,
|
16 |
+
"alibi_bias_max": 8,
|
17 |
+
}
|
18 |
+
init_config_defaults: Dict = {
|
19 |
+
"name": "kaiming_normal_",
|
20 |
+
"fan_mode": "fan_in",
|
21 |
+
"init_nonlinearity": "relu",
|
22 |
+
"init_div_is_residual": True,
|
23 |
+
"emb_init_std": None,
|
24 |
+
"emb_init_uniform_lim": None,
|
25 |
+
"init_std": None,
|
26 |
+
"init_gain": 0.0,
|
27 |
+
}
|
28 |
+
|
29 |
+
|
30 |
+
class MPTConfig(PretrainedConfig):
|
31 |
+
model_type = "mpt"
|
32 |
+
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
d_model: int = 2048,
|
36 |
+
n_heads: int = 16,
|
37 |
+
n_layers: int = 24,
|
38 |
+
expansion_ratio: int = 4,
|
39 |
+
max_seq_len: int = 2048,
|
40 |
+
vocab_size: int = 50368,
|
41 |
+
resid_pdrop: float = 0.0,
|
42 |
+
emb_pdrop: float = 0.0,
|
43 |
+
learned_pos_emb: bool = True,
|
44 |
+
attn_config: Dict = attn_config_defaults,
|
45 |
+
init_device: str = "cpu",
|
46 |
+
logit_scale: Optional[Union[float, str]] = None,
|
47 |
+
no_bias: bool = False,
|
48 |
+
verbose: int = 0,
|
49 |
+
embedding_fraction: float = 1.0,
|
50 |
+
norm_type: str = "low_precision_layernorm",
|
51 |
+
use_cache: bool = False,
|
52 |
+
init_config: Dict = init_config_defaults,
|
53 |
+
**kwargs,
|
54 |
+
):
|
55 |
+
"""The MPT configuration class.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
d_model (int): The size of the embedding dimension of the model.
|
59 |
+
n_heads (int): The number of attention heads.
|
60 |
+
n_layers (int): The number of layers in the model.
|
61 |
+
expansion_ratio (int): The ratio of the up/down scale in the MLP.
|
62 |
+
max_seq_len (int): The maximum sequence length of the model.
|
63 |
+
vocab_size (int): The size of the vocabulary.
|
64 |
+
resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
|
65 |
+
emb_pdrop (float): The dropout probability for the embedding layer.
|
66 |
+
learned_pos_emb (bool): Whether to use learned positional embeddings
|
67 |
+
attn_config (Dict): A dictionary used to configure the model's attention module:
|
68 |
+
attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
|
69 |
+
attn_pdrop (float): The dropout probability for the attention layers.
|
70 |
+
attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
|
71 |
+
qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
|
72 |
+
clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
|
73 |
+
this value.
|
74 |
+
softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
|
75 |
+
use the default scale of ``1/sqrt(d_keys)``.
|
76 |
+
prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an
|
77 |
+
extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix
|
78 |
+
can attend to one another bi-directionally. Tokens outside the prefix use causal attention.
|
79 |
+
attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id.
|
80 |
+
When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
|
81 |
+
which sub-sequence each token belongs to.
|
82 |
+
Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
|
83 |
+
alibi (bool): Whether to use the alibi bias instead of position embeddings.
|
84 |
+
alibi_bias_max (int): The maximum value of the alibi bias.
|
85 |
+
init_device (str): The device to use for parameter initialization.
|
86 |
+
logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
|
87 |
+
no_bias (bool): Whether to use bias in all layers.
|
88 |
+
verbose (int): The verbosity level. 0 is silent.
|
89 |
+
embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
|
90 |
+
norm_type (str): choose type of norm to use
|
91 |
+
multiquery_attention (bool): Whether to use multiquery attention implementation.
|
92 |
+
use_cache (bool): Whether or not the model should return the last key/values attentions
|
93 |
+
init_config (Dict): A dictionary used to configure the model initialization:
|
94 |
+
init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
|
95 |
+
'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or
|
96 |
+
'xavier_normal_'. These mimic the parameter initialization methods in PyTorch.
|
97 |
+
init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True.
|
98 |
+
emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer.
|
99 |
+
emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution
|
100 |
+
used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``.
|
101 |
+
init_std (float): The standard deviation of the normal distribution used to initialize the model,
|
102 |
+
if using the baseline_ parameter initialization scheme.
|
103 |
+
init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes.
|
104 |
+
fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes.
|
105 |
+
init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
|
106 |
+
---
|
107 |
+
See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
|
108 |
+
"""
|
109 |
+
self.d_model = d_model
|
110 |
+
self.n_heads = n_heads
|
111 |
+
self.n_layers = n_layers
|
112 |
+
self.expansion_ratio = expansion_ratio
|
113 |
+
self.max_seq_len = max_seq_len
|
114 |
+
self.vocab_size = vocab_size
|
115 |
+
self.resid_pdrop = resid_pdrop
|
116 |
+
self.emb_pdrop = emb_pdrop
|
117 |
+
self.learned_pos_emb = learned_pos_emb
|
118 |
+
self.attn_config = attn_config
|
119 |
+
self.init_device = init_device
|
120 |
+
self.logit_scale = logit_scale
|
121 |
+
self.no_bias = no_bias
|
122 |
+
self.verbose = verbose
|
123 |
+
self.embedding_fraction = embedding_fraction
|
124 |
+
self.norm_type = norm_type
|
125 |
+
self.use_cache = use_cache
|
126 |
+
self.init_config = init_config
|
127 |
+
if "name" in kwargs:
|
128 |
+
del kwargs["name"]
|
129 |
+
if "loss_fn" in kwargs:
|
130 |
+
del kwargs["loss_fn"]
|
131 |
+
super().__init__(**kwargs)
|
132 |
+
self._validate_config()
|
133 |
+
|
134 |
+
def _set_config_defaults(self, config, config_defaults):
|
135 |
+
for k, v in config_defaults.items():
|
136 |
+
if k not in config:
|
137 |
+
config[k] = v
|
138 |
+
return config
|
139 |
+
|
140 |
+
def _validate_config(self):
|
141 |
+
self.attn_config = self._set_config_defaults(
|
142 |
+
self.attn_config, attn_config_defaults
|
143 |
+
)
|
144 |
+
self.init_config = self._set_config_defaults(
|
145 |
+
self.init_config, init_config_defaults
|
146 |
+
)
|
147 |
+
if self.d_model % self.n_heads != 0:
|
148 |
+
raise ValueError("d_model must be divisible by n_heads")
|
149 |
+
if any(
|
150 |
+
(
|
151 |
+
prob < 0 or prob > 1
|
152 |
+
for prob in [
|
153 |
+
self.attn_config["attn_pdrop"],
|
154 |
+
self.resid_pdrop,
|
155 |
+
self.emb_pdrop,
|
156 |
+
]
|
157 |
+
)
|
158 |
+
):
|
159 |
+
raise ValueError(
|
160 |
+
"self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1"
|
161 |
+
)
|
162 |
+
if self.attn_config["attn_impl"] not in ["torch", "flash", "triton"]:
|
163 |
+
raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
|
164 |
+
if self.attn_config["prefix_lm"] and self.attn_config["attn_impl"] not in [
|
165 |
+
"torch",
|
166 |
+
"triton",
|
167 |
+
]:
|
168 |
+
raise NotImplementedError(
|
169 |
+
"prefix_lm only implemented with torch and triton attention."
|
170 |
+
)
|
171 |
+
if self.attn_config["alibi"] and self.attn_config["attn_impl"] not in [
|
172 |
+
"torch",
|
173 |
+
"triton",
|
174 |
+
]:
|
175 |
+
raise NotImplementedError(
|
176 |
+
"alibi only implemented with torch and triton attention."
|
177 |
+
)
|
178 |
+
if self.attn_config["attn_uses_sequence_id"] and self.attn_config[
|
179 |
+
"attn_impl"
|
180 |
+
] not in ["torch", "triton"]:
|
181 |
+
raise NotImplementedError(
|
182 |
+
"attn_uses_sequence_id only implemented with torch and triton attention."
|
183 |
+
)
|
184 |
+
if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
|
185 |
+
raise ValueError(
|
186 |
+
"model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!"
|
187 |
+
)
|
188 |
+
if isinstance(self.logit_scale, str) and self.logit_scale != "inv_sqrt_d_model":
|
189 |
+
raise ValueError(
|
190 |
+
f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'."
|
191 |
+
)
|
192 |
+
if self.init_config.get("name", None) is None:
|
193 |
+
raise ValueError(
|
194 |
+
f"self.init_config={self.init_config!r} 'name' needs to be set."
|
195 |
+
)
|
196 |
+
if not self.learned_pos_emb and (not self.attn_config["alibi"]):
|
197 |
+
raise ValueError(
|
198 |
+
f"Positional information must be provided to the model using either learned_pos_emb or alibi."
|
199 |
+
)
|
model/llava/model/language_model/mpt/custom_embedding.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
def forward(self, input: Tensor, unembed: bool = False) -> Tensor:
|
9 |
+
if unembed:
|
10 |
+
return F.linear(input, self.weight)
|
11 |
+
return super().forward(input)
|
model/llava/model/language_model/mpt/flash_attn_triton.py
ADDED
@@ -0,0 +1,1087 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
|
3 |
+
update imports to use 'triton_pre_mlir'
|
4 |
+
|
5 |
+
*Experimental* implementation of FlashAttention in Triton.
|
6 |
+
Tested with triton==2.0.0.dev20221202.
|
7 |
+
Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
|
8 |
+
other than 64:
|
9 |
+
https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
|
10 |
+
We'll update this implementation with the new Triton backend once this is fixed.
|
11 |
+
|
12 |
+
We use the FlashAttention implementation from Phil Tillet a starting point.
|
13 |
+
https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
|
14 |
+
|
15 |
+
Changes:
|
16 |
+
- Implement both causal and non-causal attention.
|
17 |
+
- Implement both self-attention and cross-attention.
|
18 |
+
- Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
|
19 |
+
- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
|
20 |
+
- Support attention bias.
|
21 |
+
- Speed up the forward pass a bit, and only store the LSE instead of m and l.
|
22 |
+
- Make the backward for d=128 much faster by reducing register spilling.
|
23 |
+
- Optionally parallelize the backward pass across seqlen_k, to deal with the case of
|
24 |
+
small batch size * nheads.
|
25 |
+
|
26 |
+
Caution:
|
27 |
+
- This is an *experimental* implementation. The forward pass should be quite robust but
|
28 |
+
I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
|
29 |
+
- This implementation has only been tested on A100.
|
30 |
+
- If you plan to use headdim other than 64 and 128, you should test for race conditions
|
31 |
+
(due to the Triton compiler), as done in tests/test_flash_attn.py
|
32 |
+
"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
|
33 |
+
for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
|
34 |
+
that there are none left for other head dimensions.
|
35 |
+
|
36 |
+
Differences between this Triton version and the CUDA version:
|
37 |
+
- Triton version doesn't support dropout.
|
38 |
+
- Triton forward is generally faster than CUDA forward, while Triton backward is
|
39 |
+
generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
|
40 |
+
than CUDA forward + backward.
|
41 |
+
- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
|
42 |
+
- Triton version supports attention bias, while CUDA version doesn't.
|
43 |
+
"""
|
44 |
+
import math
|
45 |
+
|
46 |
+
import torch
|
47 |
+
import triton_pre_mlir as triton
|
48 |
+
import triton_pre_mlir.language as tl
|
49 |
+
|
50 |
+
|
51 |
+
@triton.heuristics(
|
52 |
+
{
|
53 |
+
"EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
|
54 |
+
"EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
|
55 |
+
"EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
|
56 |
+
}
|
57 |
+
)
|
58 |
+
@triton.jit
|
59 |
+
def _fwd_kernel(
|
60 |
+
Q,
|
61 |
+
K,
|
62 |
+
V,
|
63 |
+
Bias,
|
64 |
+
Out,
|
65 |
+
Lse,
|
66 |
+
TMP,
|
67 |
+
softmax_scale,
|
68 |
+
stride_qb,
|
69 |
+
stride_qh,
|
70 |
+
stride_qm,
|
71 |
+
stride_kb,
|
72 |
+
stride_kh,
|
73 |
+
stride_kn,
|
74 |
+
stride_vb,
|
75 |
+
stride_vh,
|
76 |
+
stride_vn,
|
77 |
+
stride_bb,
|
78 |
+
stride_bh,
|
79 |
+
stride_bm,
|
80 |
+
stride_ob,
|
81 |
+
stride_oh,
|
82 |
+
stride_om,
|
83 |
+
nheads,
|
84 |
+
seqlen_q,
|
85 |
+
seqlen_k,
|
86 |
+
seqlen_q_rounded,
|
87 |
+
headdim,
|
88 |
+
CACHE_KEY_SEQLEN_Q,
|
89 |
+
CACHE_KEY_SEQLEN_K,
|
90 |
+
BIAS_TYPE: tl.constexpr,
|
91 |
+
IS_CAUSAL: tl.constexpr,
|
92 |
+
BLOCK_HEADDIM: tl.constexpr,
|
93 |
+
EVEN_M: tl.constexpr,
|
94 |
+
EVEN_N: tl.constexpr,
|
95 |
+
EVEN_HEADDIM: tl.constexpr,
|
96 |
+
BLOCK_M: tl.constexpr,
|
97 |
+
BLOCK_N: tl.constexpr,
|
98 |
+
):
|
99 |
+
start_m = tl.program_id(0)
|
100 |
+
off_hb = tl.program_id(1)
|
101 |
+
off_b = off_hb // nheads
|
102 |
+
off_h = off_hb % nheads
|
103 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
104 |
+
offs_n = tl.arange(0, BLOCK_N)
|
105 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
106 |
+
q_ptrs = (
|
107 |
+
Q
|
108 |
+
+ off_b * stride_qb
|
109 |
+
+ off_h * stride_qh
|
110 |
+
+ (offs_m[:, None] * stride_qm + offs_d[None, :])
|
111 |
+
)
|
112 |
+
k_ptrs = (
|
113 |
+
K
|
114 |
+
+ off_b * stride_kb
|
115 |
+
+ off_h * stride_kh
|
116 |
+
+ (offs_n[:, None] * stride_kn + offs_d[None, :])
|
117 |
+
)
|
118 |
+
v_ptrs = (
|
119 |
+
V
|
120 |
+
+ off_b * stride_vb
|
121 |
+
+ off_h * stride_vh
|
122 |
+
+ (offs_n[:, None] * stride_vn + offs_d[None, :])
|
123 |
+
)
|
124 |
+
if BIAS_TYPE == "vector":
|
125 |
+
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
|
126 |
+
elif BIAS_TYPE == "matrix":
|
127 |
+
b_ptrs = (
|
128 |
+
Bias
|
129 |
+
+ off_b * stride_bb
|
130 |
+
+ off_h * stride_bh
|
131 |
+
+ (offs_m[:, None] * stride_bm + offs_n[None, :])
|
132 |
+
)
|
133 |
+
t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
|
134 |
+
lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
|
135 |
+
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
|
136 |
+
acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
|
137 |
+
if EVEN_M & EVEN_N:
|
138 |
+
if EVEN_HEADDIM:
|
139 |
+
q = tl.load(q_ptrs)
|
140 |
+
else:
|
141 |
+
q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
142 |
+
elif EVEN_HEADDIM:
|
143 |
+
q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
|
144 |
+
else:
|
145 |
+
q = tl.load(
|
146 |
+
q_ptrs,
|
147 |
+
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
|
148 |
+
other=0.0,
|
149 |
+
)
|
150 |
+
end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
|
151 |
+
for start_n in range(0, end_n, BLOCK_N):
|
152 |
+
start_n = tl.multiple_of(start_n, BLOCK_N)
|
153 |
+
if EVEN_N & EVEN_M:
|
154 |
+
if EVEN_HEADDIM:
|
155 |
+
k = tl.load(k_ptrs + start_n * stride_kn)
|
156 |
+
else:
|
157 |
+
k = tl.load(
|
158 |
+
k_ptrs + start_n * stride_kn,
|
159 |
+
mask=offs_d[None, :] < headdim,
|
160 |
+
other=0.0,
|
161 |
+
)
|
162 |
+
elif EVEN_HEADDIM:
|
163 |
+
k = tl.load(
|
164 |
+
k_ptrs + start_n * stride_kn,
|
165 |
+
mask=(start_n + offs_n)[:, None] < seqlen_k,
|
166 |
+
other=0.0,
|
167 |
+
)
|
168 |
+
else:
|
169 |
+
k = tl.load(
|
170 |
+
k_ptrs + start_n * stride_kn,
|
171 |
+
mask=((start_n + offs_n)[:, None] < seqlen_k)
|
172 |
+
& (offs_d[None, :] < headdim),
|
173 |
+
other=0.0,
|
174 |
+
)
|
175 |
+
qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
|
176 |
+
qk += tl.dot(q, k, trans_b=True)
|
177 |
+
if not EVEN_N:
|
178 |
+
qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float("-inf"))
|
179 |
+
if IS_CAUSAL:
|
180 |
+
qk += tl.where(
|
181 |
+
offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float("-inf")
|
182 |
+
)
|
183 |
+
if BIAS_TYPE != "none":
|
184 |
+
if BIAS_TYPE == "vector":
|
185 |
+
if EVEN_N:
|
186 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
187 |
+
else:
|
188 |
+
bias = tl.load(
|
189 |
+
b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0
|
190 |
+
).to(tl.float32)
|
191 |
+
bias = bias[None, :]
|
192 |
+
elif BIAS_TYPE == "matrix":
|
193 |
+
if EVEN_M & EVEN_N:
|
194 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
195 |
+
else:
|
196 |
+
bias = tl.load(
|
197 |
+
b_ptrs + start_n,
|
198 |
+
mask=(offs_m[:, None] < seqlen_q)
|
199 |
+
& ((start_n + offs_n)[None, :] < seqlen_k),
|
200 |
+
other=0.0,
|
201 |
+
).to(tl.float32)
|
202 |
+
qk = qk * softmax_scale + bias
|
203 |
+
m_ij = tl.maximum(tl.max(qk, 1), lse_i)
|
204 |
+
p = tl.exp(qk - m_ij[:, None])
|
205 |
+
else:
|
206 |
+
m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
|
207 |
+
p = tl.exp(qk * softmax_scale - m_ij[:, None])
|
208 |
+
l_ij = tl.sum(p, 1)
|
209 |
+
acc_o_scale = tl.exp(m_i - m_ij)
|
210 |
+
tl.store(t_ptrs, acc_o_scale)
|
211 |
+
acc_o_scale = tl.load(t_ptrs)
|
212 |
+
acc_o = acc_o * acc_o_scale[:, None]
|
213 |
+
if EVEN_N & EVEN_M:
|
214 |
+
if EVEN_HEADDIM:
|
215 |
+
v = tl.load(v_ptrs + start_n * stride_vn)
|
216 |
+
else:
|
217 |
+
v = tl.load(
|
218 |
+
v_ptrs + start_n * stride_vn,
|
219 |
+
mask=offs_d[None, :] < headdim,
|
220 |
+
other=0.0,
|
221 |
+
)
|
222 |
+
elif EVEN_HEADDIM:
|
223 |
+
v = tl.load(
|
224 |
+
v_ptrs + start_n * stride_vn,
|
225 |
+
mask=(start_n + offs_n)[:, None] < seqlen_k,
|
226 |
+
other=0.0,
|
227 |
+
)
|
228 |
+
else:
|
229 |
+
v = tl.load(
|
230 |
+
v_ptrs + start_n * stride_vn,
|
231 |
+
mask=((start_n + offs_n)[:, None] < seqlen_k)
|
232 |
+
& (offs_d[None, :] < headdim),
|
233 |
+
other=0.0,
|
234 |
+
)
|
235 |
+
p = p.to(v.dtype)
|
236 |
+
acc_o += tl.dot(p, v)
|
237 |
+
m_i = m_ij
|
238 |
+
l_i_new = tl.exp(lse_i - m_ij) + l_ij
|
239 |
+
lse_i = m_ij + tl.log(l_i_new)
|
240 |
+
o_scale = tl.exp(m_i - lse_i)
|
241 |
+
tl.store(t_ptrs, o_scale)
|
242 |
+
o_scale = tl.load(t_ptrs)
|
243 |
+
acc_o = acc_o * o_scale[:, None]
|
244 |
+
start_m = tl.program_id(0)
|
245 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
246 |
+
lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
|
247 |
+
tl.store(lse_ptrs, lse_i)
|
248 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
249 |
+
out_ptrs = (
|
250 |
+
Out
|
251 |
+
+ off_b * stride_ob
|
252 |
+
+ off_h * stride_oh
|
253 |
+
+ (offs_m[:, None] * stride_om + offs_d[None, :])
|
254 |
+
)
|
255 |
+
if EVEN_M:
|
256 |
+
if EVEN_HEADDIM:
|
257 |
+
tl.store(out_ptrs, acc_o)
|
258 |
+
else:
|
259 |
+
tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
|
260 |
+
elif EVEN_HEADDIM:
|
261 |
+
tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
|
262 |
+
else:
|
263 |
+
tl.store(
|
264 |
+
out_ptrs,
|
265 |
+
acc_o,
|
266 |
+
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
|
267 |
+
)
|
268 |
+
|
269 |
+
|
270 |
+
@triton.jit
|
271 |
+
def _bwd_preprocess_do_o_dot(
|
272 |
+
Out,
|
273 |
+
DO,
|
274 |
+
Delta,
|
275 |
+
stride_ob,
|
276 |
+
stride_oh,
|
277 |
+
stride_om,
|
278 |
+
stride_dob,
|
279 |
+
stride_doh,
|
280 |
+
stride_dom,
|
281 |
+
nheads,
|
282 |
+
seqlen_q,
|
283 |
+
seqlen_q_rounded,
|
284 |
+
headdim,
|
285 |
+
BLOCK_M: tl.constexpr,
|
286 |
+
BLOCK_HEADDIM: tl.constexpr,
|
287 |
+
):
|
288 |
+
start_m = tl.program_id(0)
|
289 |
+
off_hb = tl.program_id(1)
|
290 |
+
off_b = off_hb // nheads
|
291 |
+
off_h = off_hb % nheads
|
292 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
293 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
294 |
+
o = tl.load(
|
295 |
+
Out
|
296 |
+
+ off_b * stride_ob
|
297 |
+
+ off_h * stride_oh
|
298 |
+
+ offs_m[:, None] * stride_om
|
299 |
+
+ offs_d[None, :],
|
300 |
+
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
|
301 |
+
other=0.0,
|
302 |
+
).to(tl.float32)
|
303 |
+
do = tl.load(
|
304 |
+
DO
|
305 |
+
+ off_b * stride_dob
|
306 |
+
+ off_h * stride_doh
|
307 |
+
+ offs_m[:, None] * stride_dom
|
308 |
+
+ offs_d[None, :],
|
309 |
+
mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
|
310 |
+
other=0.0,
|
311 |
+
).to(tl.float32)
|
312 |
+
delta = tl.sum(o * do, axis=1)
|
313 |
+
tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
|
314 |
+
|
315 |
+
|
316 |
+
@triton.jit
|
317 |
+
def _bwd_store_dk_dv(
|
318 |
+
dk_ptrs,
|
319 |
+
dv_ptrs,
|
320 |
+
dk,
|
321 |
+
dv,
|
322 |
+
offs_n,
|
323 |
+
offs_d,
|
324 |
+
seqlen_k,
|
325 |
+
headdim,
|
326 |
+
EVEN_M: tl.constexpr,
|
327 |
+
EVEN_N: tl.constexpr,
|
328 |
+
EVEN_HEADDIM: tl.constexpr,
|
329 |
+
):
|
330 |
+
if EVEN_N & EVEN_M:
|
331 |
+
if EVEN_HEADDIM:
|
332 |
+
tl.store(dv_ptrs, dv)
|
333 |
+
tl.store(dk_ptrs, dk)
|
334 |
+
else:
|
335 |
+
tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
|
336 |
+
tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
|
337 |
+
elif EVEN_HEADDIM:
|
338 |
+
tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
|
339 |
+
tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
|
340 |
+
else:
|
341 |
+
tl.store(
|
342 |
+
dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)
|
343 |
+
)
|
344 |
+
tl.store(
|
345 |
+
dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)
|
346 |
+
)
|
347 |
+
|
348 |
+
|
349 |
+
@triton.jit
|
350 |
+
def _bwd_kernel_one_col_block(
|
351 |
+
start_n,
|
352 |
+
Q,
|
353 |
+
K,
|
354 |
+
V,
|
355 |
+
Bias,
|
356 |
+
DO,
|
357 |
+
DQ,
|
358 |
+
DK,
|
359 |
+
DV,
|
360 |
+
LSE,
|
361 |
+
D,
|
362 |
+
softmax_scale,
|
363 |
+
stride_qm,
|
364 |
+
stride_kn,
|
365 |
+
stride_vn,
|
366 |
+
stride_bm,
|
367 |
+
stride_dom,
|
368 |
+
stride_dqm,
|
369 |
+
stride_dkn,
|
370 |
+
stride_dvn,
|
371 |
+
seqlen_q,
|
372 |
+
seqlen_k,
|
373 |
+
headdim,
|
374 |
+
ATOMIC_ADD: tl.constexpr,
|
375 |
+
BIAS_TYPE: tl.constexpr,
|
376 |
+
IS_CAUSAL: tl.constexpr,
|
377 |
+
BLOCK_HEADDIM: tl.constexpr,
|
378 |
+
EVEN_M: tl.constexpr,
|
379 |
+
EVEN_N: tl.constexpr,
|
380 |
+
EVEN_HEADDIM: tl.constexpr,
|
381 |
+
BLOCK_M: tl.constexpr,
|
382 |
+
BLOCK_N: tl.constexpr,
|
383 |
+
):
|
384 |
+
begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M
|
385 |
+
offs_qm = begin_m + tl.arange(0, BLOCK_M)
|
386 |
+
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
387 |
+
offs_m = tl.arange(0, BLOCK_M)
|
388 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
389 |
+
q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
|
390 |
+
k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
391 |
+
v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
392 |
+
do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
|
393 |
+
dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
|
394 |
+
if BIAS_TYPE == "vector":
|
395 |
+
b_ptrs = Bias + offs_n
|
396 |
+
elif BIAS_TYPE == "matrix":
|
397 |
+
b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
|
398 |
+
dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
399 |
+
dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
400 |
+
if begin_m >= seqlen_q:
|
401 |
+
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
402 |
+
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
403 |
+
_bwd_store_dk_dv(
|
404 |
+
dk_ptrs,
|
405 |
+
dv_ptrs,
|
406 |
+
dk,
|
407 |
+
dv,
|
408 |
+
offs_n,
|
409 |
+
offs_d,
|
410 |
+
seqlen_k,
|
411 |
+
headdim,
|
412 |
+
EVEN_M=EVEN_M,
|
413 |
+
EVEN_N=EVEN_N,
|
414 |
+
EVEN_HEADDIM=EVEN_HEADDIM,
|
415 |
+
)
|
416 |
+
return
|
417 |
+
if EVEN_N & EVEN_M:
|
418 |
+
if EVEN_HEADDIM:
|
419 |
+
k = tl.load(k_ptrs)
|
420 |
+
v = tl.load(v_ptrs)
|
421 |
+
else:
|
422 |
+
k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
423 |
+
v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
424 |
+
elif EVEN_HEADDIM:
|
425 |
+
k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
426 |
+
v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
427 |
+
else:
|
428 |
+
k = tl.load(
|
429 |
+
k_ptrs,
|
430 |
+
mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
|
431 |
+
other=0.0,
|
432 |
+
)
|
433 |
+
v = tl.load(
|
434 |
+
v_ptrs,
|
435 |
+
mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
|
436 |
+
other=0.0,
|
437 |
+
)
|
438 |
+
num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
|
439 |
+
for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
|
440 |
+
start_m = tl.multiple_of(start_m, BLOCK_M)
|
441 |
+
offs_m_curr = start_m + offs_m
|
442 |
+
if EVEN_M & EVEN_HEADDIM:
|
443 |
+
q = tl.load(q_ptrs)
|
444 |
+
elif EVEN_HEADDIM:
|
445 |
+
q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
|
446 |
+
else:
|
447 |
+
q = tl.load(
|
448 |
+
q_ptrs,
|
449 |
+
mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
|
450 |
+
other=0.0,
|
451 |
+
)
|
452 |
+
qk = tl.dot(q, k, trans_b=True)
|
453 |
+
if not EVEN_N:
|
454 |
+
qk = tl.where(offs_n[None, :] < seqlen_k, qk, float("-inf"))
|
455 |
+
if IS_CAUSAL:
|
456 |
+
qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float("-inf"))
|
457 |
+
if BIAS_TYPE != "none":
|
458 |
+
tl.debug_barrier()
|
459 |
+
if BIAS_TYPE == "vector":
|
460 |
+
if EVEN_N:
|
461 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
462 |
+
else:
|
463 |
+
bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(
|
464 |
+
tl.float32
|
465 |
+
)
|
466 |
+
bias = bias[None, :]
|
467 |
+
elif BIAS_TYPE == "matrix":
|
468 |
+
if EVEN_M & EVEN_N:
|
469 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
470 |
+
else:
|
471 |
+
bias = tl.load(
|
472 |
+
b_ptrs,
|
473 |
+
mask=(offs_m_curr[:, None] < seqlen_q)
|
474 |
+
& (offs_n[None, :] < seqlen_k),
|
475 |
+
other=0.0,
|
476 |
+
).to(tl.float32)
|
477 |
+
qk = qk * softmax_scale + bias
|
478 |
+
if not EVEN_M & EVEN_HEADDIM:
|
479 |
+
tl.debug_barrier()
|
480 |
+
lse_i = tl.load(LSE + offs_m_curr)
|
481 |
+
if BIAS_TYPE == "none":
|
482 |
+
p = tl.exp(qk * softmax_scale - lse_i[:, None])
|
483 |
+
else:
|
484 |
+
p = tl.exp(qk - lse_i[:, None])
|
485 |
+
if EVEN_M & EVEN_HEADDIM:
|
486 |
+
do = tl.load(do_ptrs)
|
487 |
+
else:
|
488 |
+
do = tl.load(
|
489 |
+
do_ptrs,
|
490 |
+
mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
|
491 |
+
other=0.0,
|
492 |
+
)
|
493 |
+
dv += tl.dot(p.to(do.dtype), do, trans_a=True)
|
494 |
+
if not EVEN_M & EVEN_HEADDIM:
|
495 |
+
tl.debug_barrier()
|
496 |
+
dp = tl.dot(do, v, trans_b=True)
|
497 |
+
if not EVEN_HEADDIM:
|
498 |
+
tl.debug_barrier()
|
499 |
+
Di = tl.load(D + offs_m_curr)
|
500 |
+
ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
|
501 |
+
dk += tl.dot(ds, q, trans_a=True)
|
502 |
+
if not EVEN_M & EVEN_HEADDIM:
|
503 |
+
tl.debug_barrier()
|
504 |
+
if not ATOMIC_ADD:
|
505 |
+
if EVEN_M & EVEN_HEADDIM:
|
506 |
+
dq = tl.load(dq_ptrs, eviction_policy="evict_last")
|
507 |
+
dq += tl.dot(ds, k)
|
508 |
+
tl.store(dq_ptrs, dq, eviction_policy="evict_last")
|
509 |
+
elif EVEN_HEADDIM:
|
510 |
+
dq = tl.load(
|
511 |
+
dq_ptrs,
|
512 |
+
mask=offs_m_curr[:, None] < seqlen_q,
|
513 |
+
other=0.0,
|
514 |
+
eviction_policy="evict_last",
|
515 |
+
)
|
516 |
+
dq += tl.dot(ds, k)
|
517 |
+
tl.store(
|
518 |
+
dq_ptrs,
|
519 |
+
dq,
|
520 |
+
mask=offs_m_curr[:, None] < seqlen_q,
|
521 |
+
eviction_policy="evict_last",
|
522 |
+
)
|
523 |
+
else:
|
524 |
+
dq = tl.load(
|
525 |
+
dq_ptrs,
|
526 |
+
mask=(offs_m_curr[:, None] < seqlen_q)
|
527 |
+
& (offs_d[None, :] < headdim),
|
528 |
+
other=0.0,
|
529 |
+
eviction_policy="evict_last",
|
530 |
+
)
|
531 |
+
dq += tl.dot(ds, k)
|
532 |
+
tl.store(
|
533 |
+
dq_ptrs,
|
534 |
+
dq,
|
535 |
+
mask=(offs_m_curr[:, None] < seqlen_q)
|
536 |
+
& (offs_d[None, :] < headdim),
|
537 |
+
eviction_policy="evict_last",
|
538 |
+
)
|
539 |
+
else:
|
540 |
+
dq = tl.dot(ds, k)
|
541 |
+
if EVEN_M & EVEN_HEADDIM:
|
542 |
+
tl.atomic_add(dq_ptrs, dq)
|
543 |
+
elif EVEN_HEADDIM:
|
544 |
+
tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
|
545 |
+
else:
|
546 |
+
tl.atomic_add(
|
547 |
+
dq_ptrs,
|
548 |
+
dq,
|
549 |
+
mask=(offs_m_curr[:, None] < seqlen_q)
|
550 |
+
& (offs_d[None, :] < headdim),
|
551 |
+
)
|
552 |
+
dq_ptrs += BLOCK_M * stride_dqm
|
553 |
+
q_ptrs += BLOCK_M * stride_qm
|
554 |
+
do_ptrs += BLOCK_M * stride_dom
|
555 |
+
if BIAS_TYPE == "matrix":
|
556 |
+
b_ptrs += BLOCK_M * stride_bm
|
557 |
+
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
558 |
+
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
559 |
+
_bwd_store_dk_dv(
|
560 |
+
dk_ptrs,
|
561 |
+
dv_ptrs,
|
562 |
+
dk,
|
563 |
+
dv,
|
564 |
+
offs_n,
|
565 |
+
offs_d,
|
566 |
+
seqlen_k,
|
567 |
+
headdim,
|
568 |
+
EVEN_M=EVEN_M,
|
569 |
+
EVEN_N=EVEN_N,
|
570 |
+
EVEN_HEADDIM=EVEN_HEADDIM,
|
571 |
+
)
|
572 |
+
|
573 |
+
|
574 |
+
def init_to_zero(name):
|
575 |
+
return lambda nargs: nargs[name].zero_()
|
576 |
+
|
577 |
+
|
578 |
+
@triton.autotune(
|
579 |
+
configs=[
|
580 |
+
triton.Config(
|
581 |
+
{"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": False},
|
582 |
+
num_warps=8,
|
583 |
+
num_stages=1,
|
584 |
+
pre_hook=init_to_zero("DQ"),
|
585 |
+
),
|
586 |
+
triton.Config(
|
587 |
+
{"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": True},
|
588 |
+
num_warps=8,
|
589 |
+
num_stages=1,
|
590 |
+
pre_hook=init_to_zero("DQ"),
|
591 |
+
),
|
592 |
+
],
|
593 |
+
key=[
|
594 |
+
"CACHE_KEY_SEQLEN_Q",
|
595 |
+
"CACHE_KEY_SEQLEN_K",
|
596 |
+
"BIAS_TYPE",
|
597 |
+
"IS_CAUSAL",
|
598 |
+
"BLOCK_HEADDIM",
|
599 |
+
],
|
600 |
+
)
|
601 |
+
@triton.heuristics(
|
602 |
+
{
|
603 |
+
"EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
|
604 |
+
"EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
|
605 |
+
"EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
|
606 |
+
}
|
607 |
+
)
|
608 |
+
@triton.jit
|
609 |
+
def _bwd_kernel(
|
610 |
+
Q,
|
611 |
+
K,
|
612 |
+
V,
|
613 |
+
Bias,
|
614 |
+
DO,
|
615 |
+
DQ,
|
616 |
+
DK,
|
617 |
+
DV,
|
618 |
+
LSE,
|
619 |
+
D,
|
620 |
+
softmax_scale,
|
621 |
+
stride_qb,
|
622 |
+
stride_qh,
|
623 |
+
stride_qm,
|
624 |
+
stride_kb,
|
625 |
+
stride_kh,
|
626 |
+
stride_kn,
|
627 |
+
stride_vb,
|
628 |
+
stride_vh,
|
629 |
+
stride_vn,
|
630 |
+
stride_bb,
|
631 |
+
stride_bh,
|
632 |
+
stride_bm,
|
633 |
+
stride_dob,
|
634 |
+
stride_doh,
|
635 |
+
stride_dom,
|
636 |
+
stride_dqb,
|
637 |
+
stride_dqh,
|
638 |
+
stride_dqm,
|
639 |
+
stride_dkb,
|
640 |
+
stride_dkh,
|
641 |
+
stride_dkn,
|
642 |
+
stride_dvb,
|
643 |
+
stride_dvh,
|
644 |
+
stride_dvn,
|
645 |
+
nheads,
|
646 |
+
seqlen_q,
|
647 |
+
seqlen_k,
|
648 |
+
seqlen_q_rounded,
|
649 |
+
headdim,
|
650 |
+
CACHE_KEY_SEQLEN_Q,
|
651 |
+
CACHE_KEY_SEQLEN_K,
|
652 |
+
BIAS_TYPE: tl.constexpr,
|
653 |
+
IS_CAUSAL: tl.constexpr,
|
654 |
+
BLOCK_HEADDIM: tl.constexpr,
|
655 |
+
SEQUENCE_PARALLEL: tl.constexpr,
|
656 |
+
EVEN_M: tl.constexpr,
|
657 |
+
EVEN_N: tl.constexpr,
|
658 |
+
EVEN_HEADDIM: tl.constexpr,
|
659 |
+
BLOCK_M: tl.constexpr,
|
660 |
+
BLOCK_N: tl.constexpr,
|
661 |
+
):
|
662 |
+
off_hb = tl.program_id(1)
|
663 |
+
off_b = off_hb // nheads
|
664 |
+
off_h = off_hb % nheads
|
665 |
+
Q += off_b * stride_qb + off_h * stride_qh
|
666 |
+
K += off_b * stride_kb + off_h * stride_kh
|
667 |
+
V += off_b * stride_vb + off_h * stride_vh
|
668 |
+
DO += off_b * stride_dob + off_h * stride_doh
|
669 |
+
DQ += off_b * stride_dqb + off_h * stride_dqh
|
670 |
+
DK += off_b * stride_dkb + off_h * stride_dkh
|
671 |
+
DV += off_b * stride_dvb + off_h * stride_dvh
|
672 |
+
if BIAS_TYPE != "none":
|
673 |
+
Bias += off_b * stride_bb + off_h * stride_bh
|
674 |
+
D += off_hb * seqlen_q_rounded
|
675 |
+
LSE += off_hb * seqlen_q_rounded
|
676 |
+
if not SEQUENCE_PARALLEL:
|
677 |
+
num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
|
678 |
+
for start_n in range(0, num_block_n):
|
679 |
+
_bwd_kernel_one_col_block(
|
680 |
+
start_n,
|
681 |
+
Q,
|
682 |
+
K,
|
683 |
+
V,
|
684 |
+
Bias,
|
685 |
+
DO,
|
686 |
+
DQ,
|
687 |
+
DK,
|
688 |
+
DV,
|
689 |
+
LSE,
|
690 |
+
D,
|
691 |
+
softmax_scale,
|
692 |
+
stride_qm,
|
693 |
+
stride_kn,
|
694 |
+
stride_vn,
|
695 |
+
stride_bm,
|
696 |
+
stride_dom,
|
697 |
+
stride_dqm,
|
698 |
+
stride_dkn,
|
699 |
+
stride_dvn,
|
700 |
+
seqlen_q,
|
701 |
+
seqlen_k,
|
702 |
+
headdim,
|
703 |
+
ATOMIC_ADD=False,
|
704 |
+
BIAS_TYPE=BIAS_TYPE,
|
705 |
+
IS_CAUSAL=IS_CAUSAL,
|
706 |
+
BLOCK_HEADDIM=BLOCK_HEADDIM,
|
707 |
+
EVEN_M=EVEN_M,
|
708 |
+
EVEN_N=EVEN_N,
|
709 |
+
EVEN_HEADDIM=EVEN_HEADDIM,
|
710 |
+
BLOCK_M=BLOCK_M,
|
711 |
+
BLOCK_N=BLOCK_N,
|
712 |
+
)
|
713 |
+
else:
|
714 |
+
start_n = tl.program_id(0)
|
715 |
+
_bwd_kernel_one_col_block(
|
716 |
+
start_n,
|
717 |
+
Q,
|
718 |
+
K,
|
719 |
+
V,
|
720 |
+
Bias,
|
721 |
+
DO,
|
722 |
+
DQ,
|
723 |
+
DK,
|
724 |
+
DV,
|
725 |
+
LSE,
|
726 |
+
D,
|
727 |
+
softmax_scale,
|
728 |
+
stride_qm,
|
729 |
+
stride_kn,
|
730 |
+
stride_vn,
|
731 |
+
stride_bm,
|
732 |
+
stride_dom,
|
733 |
+
stride_dqm,
|
734 |
+
stride_dkn,
|
735 |
+
stride_dvn,
|
736 |
+
seqlen_q,
|
737 |
+
seqlen_k,
|
738 |
+
headdim,
|
739 |
+
ATOMIC_ADD=True,
|
740 |
+
BIAS_TYPE=BIAS_TYPE,
|
741 |
+
IS_CAUSAL=IS_CAUSAL,
|
742 |
+
BLOCK_HEADDIM=BLOCK_HEADDIM,
|
743 |
+
EVEN_M=EVEN_M,
|
744 |
+
EVEN_N=EVEN_N,
|
745 |
+
EVEN_HEADDIM=EVEN_HEADDIM,
|
746 |
+
BLOCK_M=BLOCK_M,
|
747 |
+
BLOCK_N=BLOCK_N,
|
748 |
+
)
|
749 |
+
|
750 |
+
|
751 |
+
def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
|
752 |
+
(batch, seqlen_q, nheads, d) = q.shape
|
753 |
+
(_, seqlen_k, _, _) = k.shape
|
754 |
+
assert k.shape == (batch, seqlen_k, nheads, d)
|
755 |
+
assert v.shape == (batch, seqlen_k, nheads, d)
|
756 |
+
assert d <= 128, "FlashAttention only support head dimensions up to 128"
|
757 |
+
assert q.dtype == k.dtype == v.dtype, "All tensors must have the same type"
|
758 |
+
assert q.dtype in [torch.float16, torch.bfloat16], "Only support fp16 and bf16"
|
759 |
+
assert q.is_cuda and k.is_cuda and v.is_cuda
|
760 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
761 |
+
has_bias = bias is not None
|
762 |
+
bias_type = "none"
|
763 |
+
if has_bias:
|
764 |
+
assert bias.dtype in [q.dtype, torch.float]
|
765 |
+
assert bias.is_cuda
|
766 |
+
assert bias.dim() == 4
|
767 |
+
if bias.stride(-1) != 1:
|
768 |
+
bias = bias.contiguous()
|
769 |
+
if bias.shape[2:] == (1, seqlen_k):
|
770 |
+
bias_type = "vector"
|
771 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
772 |
+
bias_type = "matrix"
|
773 |
+
else:
|
774 |
+
raise RuntimeError(
|
775 |
+
"Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)"
|
776 |
+
)
|
777 |
+
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
778 |
+
bias_strides = (
|
779 |
+
(bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
780 |
+
)
|
781 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
782 |
+
lse = torch.empty(
|
783 |
+
(batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32
|
784 |
+
)
|
785 |
+
tmp = torch.empty(
|
786 |
+
(batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32
|
787 |
+
)
|
788 |
+
o = torch.empty_like(q)
|
789 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
790 |
+
BLOCK = 128
|
791 |
+
num_warps = 4 if d <= 64 else 8
|
792 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads)
|
793 |
+
_fwd_kernel[grid](
|
794 |
+
q,
|
795 |
+
k,
|
796 |
+
v,
|
797 |
+
bias,
|
798 |
+
o,
|
799 |
+
lse,
|
800 |
+
tmp,
|
801 |
+
softmax_scale,
|
802 |
+
q.stride(0),
|
803 |
+
q.stride(2),
|
804 |
+
q.stride(1),
|
805 |
+
k.stride(0),
|
806 |
+
k.stride(2),
|
807 |
+
k.stride(1),
|
808 |
+
v.stride(0),
|
809 |
+
v.stride(2),
|
810 |
+
v.stride(1),
|
811 |
+
*bias_strides,
|
812 |
+
o.stride(0),
|
813 |
+
o.stride(2),
|
814 |
+
o.stride(1),
|
815 |
+
nheads,
|
816 |
+
seqlen_q,
|
817 |
+
seqlen_k,
|
818 |
+
seqlen_q_rounded,
|
819 |
+
d,
|
820 |
+
seqlen_q // 32,
|
821 |
+
seqlen_k // 32,
|
822 |
+
bias_type,
|
823 |
+
causal,
|
824 |
+
BLOCK_HEADDIM,
|
825 |
+
BLOCK_M=BLOCK,
|
826 |
+
BLOCK_N=BLOCK,
|
827 |
+
num_warps=num_warps,
|
828 |
+
num_stages=1
|
829 |
+
)
|
830 |
+
return (o, lse, softmax_scale)
|
831 |
+
|
832 |
+
|
833 |
+
def _flash_attn_backward(
|
834 |
+
do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None
|
835 |
+
):
|
836 |
+
if do.stride(-1) != 1:
|
837 |
+
do = do.contiguous()
|
838 |
+
(batch, seqlen_q, nheads, d) = q.shape
|
839 |
+
(_, seqlen_k, _, _) = k.shape
|
840 |
+
assert d <= 128
|
841 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
842 |
+
assert lse.shape == (batch, nheads, seqlen_q_rounded)
|
843 |
+
assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
|
844 |
+
assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
|
845 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
846 |
+
dq_accum = torch.empty_like(q, dtype=torch.float32)
|
847 |
+
delta = torch.empty_like(lse)
|
848 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
849 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads)
|
850 |
+
_bwd_preprocess_do_o_dot[grid](
|
851 |
+
o,
|
852 |
+
do,
|
853 |
+
delta,
|
854 |
+
o.stride(0),
|
855 |
+
o.stride(2),
|
856 |
+
o.stride(1),
|
857 |
+
do.stride(0),
|
858 |
+
do.stride(2),
|
859 |
+
do.stride(1),
|
860 |
+
nheads,
|
861 |
+
seqlen_q,
|
862 |
+
seqlen_q_rounded,
|
863 |
+
d,
|
864 |
+
BLOCK_M=128,
|
865 |
+
BLOCK_HEADDIM=BLOCK_HEADDIM,
|
866 |
+
)
|
867 |
+
has_bias = bias is not None
|
868 |
+
bias_type = "none"
|
869 |
+
if has_bias:
|
870 |
+
assert bias.dtype in [q.dtype, torch.float]
|
871 |
+
assert bias.is_cuda
|
872 |
+
assert bias.dim() == 4
|
873 |
+
assert bias.stride(-1) == 1
|
874 |
+
if bias.shape[2:] == (1, seqlen_k):
|
875 |
+
bias_type = "vector"
|
876 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
877 |
+
bias_type = "matrix"
|
878 |
+
else:
|
879 |
+
raise RuntimeError(
|
880 |
+
"Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)"
|
881 |
+
)
|
882 |
+
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
883 |
+
bias_strides = (
|
884 |
+
(bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
885 |
+
)
|
886 |
+
grid = lambda META: (
|
887 |
+
triton.cdiv(seqlen_k, META["BLOCK_N"]) if META["SEQUENCE_PARALLEL"] else 1,
|
888 |
+
batch * nheads,
|
889 |
+
)
|
890 |
+
_bwd_kernel[grid](
|
891 |
+
q,
|
892 |
+
k,
|
893 |
+
v,
|
894 |
+
bias,
|
895 |
+
do,
|
896 |
+
dq_accum,
|
897 |
+
dk,
|
898 |
+
dv,
|
899 |
+
lse,
|
900 |
+
delta,
|
901 |
+
softmax_scale,
|
902 |
+
q.stride(0),
|
903 |
+
q.stride(2),
|
904 |
+
q.stride(1),
|
905 |
+
k.stride(0),
|
906 |
+
k.stride(2),
|
907 |
+
k.stride(1),
|
908 |
+
v.stride(0),
|
909 |
+
v.stride(2),
|
910 |
+
v.stride(1),
|
911 |
+
*bias_strides,
|
912 |
+
do.stride(0),
|
913 |
+
do.stride(2),
|
914 |
+
do.stride(1),
|
915 |
+
dq_accum.stride(0),
|
916 |
+
dq_accum.stride(2),
|
917 |
+
dq_accum.stride(1),
|
918 |
+
dk.stride(0),
|
919 |
+
dk.stride(2),
|
920 |
+
dk.stride(1),
|
921 |
+
dv.stride(0),
|
922 |
+
dv.stride(2),
|
923 |
+
dv.stride(1),
|
924 |
+
nheads,
|
925 |
+
seqlen_q,
|
926 |
+
seqlen_k,
|
927 |
+
seqlen_q_rounded,
|
928 |
+
d,
|
929 |
+
seqlen_q // 32,
|
930 |
+
seqlen_k // 32,
|
931 |
+
bias_type,
|
932 |
+
causal,
|
933 |
+
BLOCK_HEADDIM
|
934 |
+
)
|
935 |
+
dq.copy_(dq_accum)
|
936 |
+
|
937 |
+
|
938 |
+
class FlashAttnQKVPackedFunc(torch.autograd.Function):
|
939 |
+
@staticmethod
|
940 |
+
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
|
941 |
+
"""
|
942 |
+
qkv: (batch, seqlen, 3, nheads, headdim)
|
943 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
|
944 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
|
945 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
|
946 |
+
"""
|
947 |
+
if qkv.stride(-1) != 1:
|
948 |
+
qkv = qkv.contiguous()
|
949 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(
|
950 |
+
qkv[:, :, 0],
|
951 |
+
qkv[:, :, 1],
|
952 |
+
qkv[:, :, 2],
|
953 |
+
bias=bias,
|
954 |
+
causal=causal,
|
955 |
+
softmax_scale=softmax_scale,
|
956 |
+
)
|
957 |
+
ctx.save_for_backward(qkv, o, lse, bias)
|
958 |
+
ctx.causal = causal
|
959 |
+
return o
|
960 |
+
|
961 |
+
@staticmethod
|
962 |
+
def backward(ctx, do):
|
963 |
+
(qkv, o, lse, bias) = ctx.saved_tensors
|
964 |
+
assert not ctx.needs_input_grad[
|
965 |
+
1
|
966 |
+
], "FlashAttention does not support bias gradient yet"
|
967 |
+
with torch.inference_mode():
|
968 |
+
dqkv = torch.empty_like(qkv)
|
969 |
+
_flash_attn_backward(
|
970 |
+
do,
|
971 |
+
qkv[:, :, 0],
|
972 |
+
qkv[:, :, 1],
|
973 |
+
qkv[:, :, 2],
|
974 |
+
o,
|
975 |
+
lse,
|
976 |
+
dqkv[:, :, 0],
|
977 |
+
dqkv[:, :, 1],
|
978 |
+
dqkv[:, :, 2],
|
979 |
+
bias=bias,
|
980 |
+
causal=ctx.causal,
|
981 |
+
softmax_scale=ctx.softmax_scale,
|
982 |
+
)
|
983 |
+
return (dqkv, None, None, None)
|
984 |
+
|
985 |
+
|
986 |
+
flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
|
987 |
+
|
988 |
+
|
989 |
+
class FlashAttnKVPackedFunc(torch.autograd.Function):
|
990 |
+
@staticmethod
|
991 |
+
def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
|
992 |
+
"""
|
993 |
+
q: (batch, seqlen_q, nheads, headdim)
|
994 |
+
kv: (batch, seqlen_k, 2, nheads, headdim)
|
995 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
996 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
997 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
998 |
+
"""
|
999 |
+
(q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
|
1000 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(
|
1001 |
+
q,
|
1002 |
+
kv[:, :, 0],
|
1003 |
+
kv[:, :, 1],
|
1004 |
+
bias=bias,
|
1005 |
+
causal=causal,
|
1006 |
+
softmax_scale=softmax_scale,
|
1007 |
+
)
|
1008 |
+
ctx.save_for_backward(q, kv, o, lse, bias)
|
1009 |
+
ctx.causal = causal
|
1010 |
+
return o
|
1011 |
+
|
1012 |
+
@staticmethod
|
1013 |
+
def backward(ctx, do):
|
1014 |
+
(q, kv, o, lse, bias) = ctx.saved_tensors
|
1015 |
+
if len(ctx.needs_input_grad) >= 3:
|
1016 |
+
assert not ctx.needs_input_grad[
|
1017 |
+
2
|
1018 |
+
], "FlashAttention does not support bias gradient yet"
|
1019 |
+
with torch.inference_mode():
|
1020 |
+
dq = torch.empty_like(q)
|
1021 |
+
dkv = torch.empty_like(kv)
|
1022 |
+
_flash_attn_backward(
|
1023 |
+
do,
|
1024 |
+
q,
|
1025 |
+
kv[:, :, 0],
|
1026 |
+
kv[:, :, 1],
|
1027 |
+
o,
|
1028 |
+
lse,
|
1029 |
+
dq,
|
1030 |
+
dkv[:, :, 0],
|
1031 |
+
dkv[:, :, 1],
|
1032 |
+
bias=bias,
|
1033 |
+
causal=ctx.causal,
|
1034 |
+
softmax_scale=ctx.softmax_scale,
|
1035 |
+
)
|
1036 |
+
return (dq, dkv, None, None, None)
|
1037 |
+
|
1038 |
+
|
1039 |
+
flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
|
1040 |
+
|
1041 |
+
|
1042 |
+
class FlashAttnFunc(torch.autograd.Function):
|
1043 |
+
@staticmethod
|
1044 |
+
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
|
1045 |
+
"""
|
1046 |
+
q: (batch_size, seqlen_q, nheads, headdim)
|
1047 |
+
k, v: (batch_size, seqlen_k, nheads, headdim)
|
1048 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
1049 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
1050 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
1051 |
+
"""
|
1052 |
+
(q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
|
1053 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(
|
1054 |
+
q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale
|
1055 |
+
)
|
1056 |
+
ctx.save_for_backward(q, k, v, o, lse, bias)
|
1057 |
+
ctx.causal = causal
|
1058 |
+
return o
|
1059 |
+
|
1060 |
+
@staticmethod
|
1061 |
+
def backward(ctx, do):
|
1062 |
+
(q, k, v, o, lse, bias) = ctx.saved_tensors
|
1063 |
+
assert not ctx.needs_input_grad[
|
1064 |
+
3
|
1065 |
+
], "FlashAttention does not support bias gradient yet"
|
1066 |
+
with torch.inference_mode():
|
1067 |
+
dq = torch.empty_like(q)
|
1068 |
+
dk = torch.empty_like(k)
|
1069 |
+
dv = torch.empty_like(v)
|
1070 |
+
_flash_attn_backward(
|
1071 |
+
do,
|
1072 |
+
q,
|
1073 |
+
k,
|
1074 |
+
v,
|
1075 |
+
o,
|
1076 |
+
lse,
|
1077 |
+
dq,
|
1078 |
+
dk,
|
1079 |
+
dv,
|
1080 |
+
bias=bias,
|
1081 |
+
causal=ctx.causal,
|
1082 |
+
softmax_scale=ctx.softmax_scale,
|
1083 |
+
)
|
1084 |
+
return (dq, dk, dv, None, None, None)
|
1085 |
+
|
1086 |
+
|
1087 |
+
flash_attn_func = FlashAttnFunc.apply
|
model/llava/model/language_model/mpt/hf_prefixlm_converter.py
ADDED
@@ -0,0 +1,750 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Converts Huggingface Causal LM to Prefix LM.
|
2 |
+
|
3 |
+
Conversion does lightweight surgery on a HuggingFace
|
4 |
+
Causal LM to convert it to a Prefix LM.
|
5 |
+
|
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 |
+
|
14 |
+
import torch
|
15 |
+
from transformers.models.bloom.modeling_bloom import (
|
16 |
+
BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel,
|
17 |
+
CausalLMOutputWithCrossAttentions, CrossEntropyLoss)
|
18 |
+
from transformers.models.bloom.modeling_bloom import \
|
19 |
+
_expand_mask as _expand_mask_bloom
|
20 |
+
from transformers.models.bloom.modeling_bloom import \
|
21 |
+
_make_causal_mask as _make_causal_mask_bloom
|
22 |
+
from transformers.models.bloom.modeling_bloom import logging
|
23 |
+
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
|
24 |
+
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
|
25 |
+
from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
|
26 |
+
from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
|
27 |
+
from transformers.models.opt.modeling_opt import OPTForCausalLM
|
28 |
+
from transformers.models.opt.modeling_opt import \
|
29 |
+
_expand_mask as _expand_mask_opt
|
30 |
+
from transformers.models.opt.modeling_opt import \
|
31 |
+
_make_causal_mask as _make_causal_mask_opt
|
32 |
+
|
33 |
+
logger = logging.get_logger(__name__)
|
34 |
+
_SUPPORTED_GPT_MODELS = (
|
35 |
+
GPT2LMHeadModel,
|
36 |
+
GPTJForCausalLM,
|
37 |
+
GPTNeoForCausalLM,
|
38 |
+
GPTNeoXForCausalLM,
|
39 |
+
)
|
40 |
+
CAUSAL_GPT_TYPES = Union[
|
41 |
+
GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM
|
42 |
+
]
|
43 |
+
|
44 |
+
|
45 |
+
def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
|
46 |
+
"""Converts a GPT-style Causal LM to a Prefix LM.
|
47 |
+
|
48 |
+
Supported HuggingFace model classes:
|
49 |
+
- `GPT2LMHeadModel`
|
50 |
+
- `GPTNeoForCausalLM`
|
51 |
+
- `GPTNeoXForCausalLM`
|
52 |
+
- `GPTJForCausalLM`
|
53 |
+
|
54 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
55 |
+
"""
|
56 |
+
if hasattr(model, "_prefix_lm_converted"):
|
57 |
+
return model
|
58 |
+
assert isinstance(model, _SUPPORTED_GPT_MODELS)
|
59 |
+
assert (
|
60 |
+
model.config.add_cross_attention == False
|
61 |
+
), "Only supports GPT-style decoder-only models"
|
62 |
+
|
63 |
+
def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
|
64 |
+
"""Helper that gets a list of the model's attention modules.
|
65 |
+
|
66 |
+
Each module has a `bias` buffer used for causal masking. The Prefix LM
|
67 |
+
conversion adds logic to dynamically manipulate these biases to support
|
68 |
+
Prefix LM attention masking.
|
69 |
+
"""
|
70 |
+
attn_modules = []
|
71 |
+
if isinstance(model, GPTNeoXForCausalLM):
|
72 |
+
blocks = model.gpt_neox.layers
|
73 |
+
else:
|
74 |
+
blocks = model.transformer.h
|
75 |
+
for block in blocks:
|
76 |
+
if isinstance(model, GPTNeoForCausalLM):
|
77 |
+
if block.attn.attention_type != "global":
|
78 |
+
continue
|
79 |
+
attn_module = block.attn.attention
|
80 |
+
elif isinstance(model, GPTNeoXForCausalLM):
|
81 |
+
attn_module = block.attention
|
82 |
+
else:
|
83 |
+
attn_module = block.attn
|
84 |
+
attn_modules.append(attn_module)
|
85 |
+
return attn_modules
|
86 |
+
|
87 |
+
setattr(model, "_original_forward", getattr(model, "forward"))
|
88 |
+
setattr(model, "_original_generate", getattr(model, "generate"))
|
89 |
+
|
90 |
+
def forward(
|
91 |
+
self: CAUSAL_GPT_TYPES,
|
92 |
+
input_ids: Optional[torch.LongTensor] = None,
|
93 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
94 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
95 |
+
bidirectional_mask: Optional[torch.Tensor] = None,
|
96 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
97 |
+
position_ids: Optional[torch.LongTensor] = None,
|
98 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
99 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
100 |
+
labels: Optional[torch.LongTensor] = None,
|
101 |
+
use_cache: Optional[bool] = None,
|
102 |
+
output_attentions: Optional[bool] = None,
|
103 |
+
output_hidden_states: Optional[bool] = None,
|
104 |
+
return_dict: Optional[bool] = None,
|
105 |
+
):
|
106 |
+
"""Wraps original forward to enable PrefixLM attention."""
|
107 |
+
|
108 |
+
def call_og_forward():
|
109 |
+
if isinstance(self, GPTNeoXForCausalLM):
|
110 |
+
return self._original_forward(
|
111 |
+
input_ids=input_ids,
|
112 |
+
past_key_values=past_key_values,
|
113 |
+
attention_mask=attention_mask,
|
114 |
+
head_mask=head_mask,
|
115 |
+
inputs_embeds=inputs_embeds,
|
116 |
+
labels=labels,
|
117 |
+
use_cache=use_cache,
|
118 |
+
output_attentions=output_attentions,
|
119 |
+
output_hidden_states=output_hidden_states,
|
120 |
+
return_dict=return_dict,
|
121 |
+
)
|
122 |
+
else:
|
123 |
+
return self._original_forward(
|
124 |
+
input_ids=input_ids,
|
125 |
+
past_key_values=past_key_values,
|
126 |
+
attention_mask=attention_mask,
|
127 |
+
token_type_ids=token_type_ids,
|
128 |
+
position_ids=position_ids,
|
129 |
+
head_mask=head_mask,
|
130 |
+
inputs_embeds=inputs_embeds,
|
131 |
+
labels=labels,
|
132 |
+
use_cache=use_cache,
|
133 |
+
output_attentions=output_attentions,
|
134 |
+
output_hidden_states=output_hidden_states,
|
135 |
+
return_dict=return_dict,
|
136 |
+
)
|
137 |
+
|
138 |
+
if bidirectional_mask is None:
|
139 |
+
return call_og_forward()
|
140 |
+
assert isinstance(bidirectional_mask, torch.Tensor)
|
141 |
+
attn_modules = _get_attn_modules(model)
|
142 |
+
(b, s) = bidirectional_mask.shape
|
143 |
+
max_length = attn_modules[0].bias.shape[-1]
|
144 |
+
if s > max_length:
|
145 |
+
raise ValueError(
|
146 |
+
f"bidirectional_mask sequence length (={s}) exceeds the "
|
147 |
+
+ f"max length allowed by the model ({max_length})."
|
148 |
+
)
|
149 |
+
assert s <= max_length
|
150 |
+
if s < max_length:
|
151 |
+
pad = torch.zeros(
|
152 |
+
(int(b), int(max_length - s)),
|
153 |
+
dtype=bidirectional_mask.dtype,
|
154 |
+
device=bidirectional_mask.device,
|
155 |
+
)
|
156 |
+
bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
|
157 |
+
bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
|
158 |
+
for attn_module in attn_modules:
|
159 |
+
attn_module.bias.data = torch.logical_or(
|
160 |
+
attn_module.bias.data, bidirectional
|
161 |
+
)
|
162 |
+
output = call_og_forward()
|
163 |
+
for attn_module in attn_modules:
|
164 |
+
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
165 |
+
return output
|
166 |
+
|
167 |
+
def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
|
168 |
+
"""Wraps original generate to enable PrefixLM attention."""
|
169 |
+
attn_modules = _get_attn_modules(model)
|
170 |
+
for attn_module in attn_modules:
|
171 |
+
attn_module.bias.data[:] = 1
|
172 |
+
output = self._original_generate(*args, **kwargs)
|
173 |
+
for attn_module in attn_modules:
|
174 |
+
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
175 |
+
return output
|
176 |
+
|
177 |
+
setattr(model, "forward", MethodType(forward, model))
|
178 |
+
setattr(model, "generate", MethodType(generate, model))
|
179 |
+
setattr(model, "_prefix_lm_converted", True)
|
180 |
+
return model
|
181 |
+
|
182 |
+
|
183 |
+
def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
|
184 |
+
"""Converts a BLOOM Causal LM to a Prefix LM.
|
185 |
+
|
186 |
+
Supported HuggingFace model classes:
|
187 |
+
- `BloomForCausalLM`
|
188 |
+
|
189 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
190 |
+
"""
|
191 |
+
if hasattr(model, "_prefix_lm_converted"):
|
192 |
+
return model
|
193 |
+
assert isinstance(model, BloomForCausalLM)
|
194 |
+
assert (
|
195 |
+
model.config.add_cross_attention == False
|
196 |
+
), "Only supports BLOOM decoder-only models"
|
197 |
+
|
198 |
+
def _prepare_attn_mask(
|
199 |
+
self: BloomModel,
|
200 |
+
attention_mask: torch.Tensor,
|
201 |
+
bidirectional_mask: Optional[torch.Tensor],
|
202 |
+
input_shape: Tuple[int, int],
|
203 |
+
past_key_values_length: int,
|
204 |
+
) -> torch.BoolTensor:
|
205 |
+
combined_attention_mask = None
|
206 |
+
device = attention_mask.device
|
207 |
+
(_, src_length) = input_shape
|
208 |
+
if src_length > 1:
|
209 |
+
combined_attention_mask = _make_causal_mask_bloom(
|
210 |
+
input_shape,
|
211 |
+
device=device,
|
212 |
+
past_key_values_length=past_key_values_length,
|
213 |
+
)
|
214 |
+
if bidirectional_mask is not None:
|
215 |
+
assert attention_mask.shape == bidirectional_mask.shape
|
216 |
+
expanded_bidirectional_mask = _expand_mask_bloom(
|
217 |
+
bidirectional_mask, tgt_length=src_length
|
218 |
+
)
|
219 |
+
combined_attention_mask = torch.logical_and(
|
220 |
+
combined_attention_mask, expanded_bidirectional_mask
|
221 |
+
)
|
222 |
+
expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
|
223 |
+
combined_attention_mask = (
|
224 |
+
expanded_attn_mask
|
225 |
+
if combined_attention_mask is None
|
226 |
+
else expanded_attn_mask | combined_attention_mask
|
227 |
+
)
|
228 |
+
return combined_attention_mask
|
229 |
+
|
230 |
+
def _build_alibi_tensor(
|
231 |
+
self: BloomModel,
|
232 |
+
batch_size: int,
|
233 |
+
query_length: int,
|
234 |
+
key_length: int,
|
235 |
+
dtype: torch.dtype,
|
236 |
+
device: torch.device,
|
237 |
+
) -> torch.Tensor:
|
238 |
+
num_heads = self.config.n_head
|
239 |
+
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
|
240 |
+
base = torch.tensor(
|
241 |
+
2 ** (-(2 ** (-(math.log2(closest_power_of_2) - 3)))),
|
242 |
+
device=device,
|
243 |
+
dtype=torch.float32,
|
244 |
+
)
|
245 |
+
powers = torch.arange(
|
246 |
+
1, 1 + closest_power_of_2, device=device, dtype=torch.int32
|
247 |
+
)
|
248 |
+
slopes = torch.pow(base, powers)
|
249 |
+
if closest_power_of_2 != num_heads:
|
250 |
+
extra_base = torch.tensor(
|
251 |
+
2 ** (-(2 ** (-(math.log2(2 * closest_power_of_2) - 3)))),
|
252 |
+
device=device,
|
253 |
+
dtype=torch.float32,
|
254 |
+
)
|
255 |
+
num_remaining_heads = min(
|
256 |
+
closest_power_of_2, num_heads - closest_power_of_2
|
257 |
+
)
|
258 |
+
extra_powers = torch.arange(
|
259 |
+
1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32
|
260 |
+
)
|
261 |
+
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
|
262 |
+
qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
|
263 |
+
ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
|
264 |
+
diffs = qa - ka + key_length - query_length
|
265 |
+
diffs = -diffs.abs()
|
266 |
+
alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(
|
267 |
+
1, 1, query_length, key_length
|
268 |
+
)
|
269 |
+
alibi = alibi.expand(batch_size, -1, -1, -1).reshape(
|
270 |
+
-1, query_length, key_length
|
271 |
+
)
|
272 |
+
return alibi.to(dtype)
|
273 |
+
|
274 |
+
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
275 |
+
|
276 |
+
def forward(
|
277 |
+
self: BloomModel,
|
278 |
+
input_ids: Optional[torch.LongTensor] = None,
|
279 |
+
past_key_values: Optional[Tuple[KeyValueT, ...]] = None,
|
280 |
+
attention_mask: Optional[torch.Tensor] = None,
|
281 |
+
bidirectional_mask: Optional[torch.Tensor] = None,
|
282 |
+
head_mask: Optional[torch.LongTensor] = None,
|
283 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
284 |
+
use_cache: Optional[bool] = None,
|
285 |
+
output_attentions: Optional[bool] = None,
|
286 |
+
output_hidden_states: Optional[bool] = None,
|
287 |
+
return_dict: Optional[bool] = None,
|
288 |
+
**deprecated_arguments,
|
289 |
+
) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
|
290 |
+
if deprecated_arguments.pop("position_ids", False) is not False:
|
291 |
+
warnings.warn(
|
292 |
+
"`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. "
|
293 |
+
+ "You can safely ignore passing `position_ids`.",
|
294 |
+
FutureWarning,
|
295 |
+
)
|
296 |
+
if len(deprecated_arguments) > 0:
|
297 |
+
raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
|
298 |
+
output_attentions = (
|
299 |
+
output_attentions
|
300 |
+
if output_attentions is not None
|
301 |
+
else self.config.output_attentions
|
302 |
+
)
|
303 |
+
output_hidden_states = (
|
304 |
+
output_hidden_states
|
305 |
+
if output_hidden_states is not None
|
306 |
+
else self.config.output_hidden_states
|
307 |
+
)
|
308 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
309 |
+
return_dict = (
|
310 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
311 |
+
)
|
312 |
+
if input_ids is not None and inputs_embeds is not None:
|
313 |
+
raise ValueError(
|
314 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
315 |
+
)
|
316 |
+
elif input_ids is not None:
|
317 |
+
(batch_size, seq_length) = input_ids.shape
|
318 |
+
elif inputs_embeds is not None:
|
319 |
+
(batch_size, seq_length, _) = inputs_embeds.shape
|
320 |
+
else:
|
321 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
322 |
+
if past_key_values is None:
|
323 |
+
past_key_values = tuple([None] * len(self.h))
|
324 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
325 |
+
if inputs_embeds is None:
|
326 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
327 |
+
hidden_states = self.word_embeddings_layernorm(inputs_embeds)
|
328 |
+
presents = () if use_cache else None
|
329 |
+
all_self_attentions = () if output_attentions else None
|
330 |
+
all_hidden_states = () if output_hidden_states else None
|
331 |
+
seq_length_with_past = seq_length
|
332 |
+
past_key_values_length = 0
|
333 |
+
if past_key_values[0] is not None:
|
334 |
+
tmp = past_key_values[0][0]
|
335 |
+
past_key_values_length = tmp.shape[2]
|
336 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
337 |
+
if attention_mask is None:
|
338 |
+
attention_mask = torch.ones(
|
339 |
+
(batch_size, seq_length_with_past), device=hidden_states.device
|
340 |
+
)
|
341 |
+
else:
|
342 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
343 |
+
alibi = self._build_alibi_tensor(
|
344 |
+
batch_size=batch_size,
|
345 |
+
query_length=seq_length,
|
346 |
+
key_length=seq_length_with_past,
|
347 |
+
dtype=hidden_states.dtype,
|
348 |
+
device=hidden_states.device,
|
349 |
+
)
|
350 |
+
causal_mask = self._prepare_attn_mask(
|
351 |
+
attention_mask,
|
352 |
+
bidirectional_mask,
|
353 |
+
input_shape=(batch_size, seq_length),
|
354 |
+
past_key_values_length=past_key_values_length,
|
355 |
+
)
|
356 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
357 |
+
if output_hidden_states:
|
358 |
+
hst = (hidden_states,)
|
359 |
+
all_hidden_states = all_hidden_states + hst
|
360 |
+
if self.gradient_checkpointing and self.training:
|
361 |
+
if use_cache:
|
362 |
+
logger.warning(
|
363 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
364 |
+
)
|
365 |
+
use_cache = False
|
366 |
+
|
367 |
+
def create_custom_forward(module):
|
368 |
+
def custom_forward(*inputs):
|
369 |
+
return module(
|
370 |
+
*inputs,
|
371 |
+
use_cache=use_cache,
|
372 |
+
output_attentions=output_attentions,
|
373 |
+
)
|
374 |
+
|
375 |
+
return custom_forward
|
376 |
+
|
377 |
+
outputs = torch.utils.checkpoint.checkpoint(
|
378 |
+
create_custom_forward(block),
|
379 |
+
hidden_states,
|
380 |
+
alibi,
|
381 |
+
causal_mask,
|
382 |
+
head_mask[i],
|
383 |
+
)
|
384 |
+
else:
|
385 |
+
outputs = block(
|
386 |
+
hidden_states,
|
387 |
+
layer_past=layer_past,
|
388 |
+
attention_mask=causal_mask,
|
389 |
+
head_mask=head_mask[i],
|
390 |
+
use_cache=use_cache,
|
391 |
+
output_attentions=output_attentions,
|
392 |
+
alibi=alibi,
|
393 |
+
)
|
394 |
+
hidden_states = outputs[0]
|
395 |
+
if use_cache is True:
|
396 |
+
presents = presents + (outputs[1],)
|
397 |
+
if output_attentions:
|
398 |
+
oa = (outputs[2 if use_cache else 1],)
|
399 |
+
all_self_attentions = all_self_attentions + oa
|
400 |
+
hidden_states = self.ln_f(hidden_states)
|
401 |
+
if output_hidden_states:
|
402 |
+
hst = (hidden_states,)
|
403 |
+
all_hidden_states = all_hidden_states + hst
|
404 |
+
if not return_dict:
|
405 |
+
return tuple(
|
406 |
+
(
|
407 |
+
v
|
408 |
+
for v in [
|
409 |
+
hidden_states,
|
410 |
+
presents,
|
411 |
+
all_hidden_states,
|
412 |
+
all_self_attentions,
|
413 |
+
]
|
414 |
+
if v is not None
|
415 |
+
)
|
416 |
+
)
|
417 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
418 |
+
last_hidden_state=hidden_states,
|
419 |
+
past_key_values=presents,
|
420 |
+
hidden_states=all_hidden_states,
|
421 |
+
attentions=all_self_attentions,
|
422 |
+
)
|
423 |
+
|
424 |
+
setattr(
|
425 |
+
model.transformer,
|
426 |
+
"_prepare_attn_mask",
|
427 |
+
MethodType(_prepare_attn_mask, model.transformer),
|
428 |
+
)
|
429 |
+
setattr(
|
430 |
+
model.transformer,
|
431 |
+
"_build_alibi_tensor",
|
432 |
+
MethodType(_build_alibi_tensor, model.transformer),
|
433 |
+
)
|
434 |
+
setattr(model.transformer, "forward", MethodType(forward, model.transformer))
|
435 |
+
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
436 |
+
|
437 |
+
def forward(
|
438 |
+
self: BloomForCausalLM,
|
439 |
+
input_ids: Optional[torch.LongTensor] = None,
|
440 |
+
past_key_values: Optional[Tuple[KeyValueT, ...]] = None,
|
441 |
+
attention_mask: Optional[torch.Tensor] = None,
|
442 |
+
bidirectional_mask: Optional[torch.Tensor] = None,
|
443 |
+
head_mask: Optional[torch.Tensor] = None,
|
444 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
445 |
+
labels: Optional[torch.Tensor] = None,
|
446 |
+
use_cache: Optional[bool] = None,
|
447 |
+
output_attentions: Optional[bool] = None,
|
448 |
+
output_hidden_states: Optional[bool] = None,
|
449 |
+
return_dict: Optional[bool] = None,
|
450 |
+
**deprecated_arguments,
|
451 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
452 |
+
"""Replacement forward method for BloomCausalLM."""
|
453 |
+
if deprecated_arguments.pop("position_ids", False) is not False:
|
454 |
+
warnings.warn(
|
455 |
+
"`position_ids` have no functionality in BLOOM and will be removed "
|
456 |
+
+ "in v5.0.0. You can safely ignore passing `position_ids`.",
|
457 |
+
FutureWarning,
|
458 |
+
)
|
459 |
+
if len(deprecated_arguments) > 0:
|
460 |
+
raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
|
461 |
+
return_dict = (
|
462 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
463 |
+
)
|
464 |
+
transformer_outputs = self.transformer(
|
465 |
+
input_ids,
|
466 |
+
past_key_values=past_key_values,
|
467 |
+
attention_mask=attention_mask,
|
468 |
+
bidirectional_mask=bidirectional_mask,
|
469 |
+
head_mask=head_mask,
|
470 |
+
inputs_embeds=inputs_embeds,
|
471 |
+
use_cache=use_cache,
|
472 |
+
output_attentions=output_attentions,
|
473 |
+
output_hidden_states=output_hidden_states,
|
474 |
+
return_dict=return_dict,
|
475 |
+
)
|
476 |
+
hidden_states = transformer_outputs[0]
|
477 |
+
lm_logits = self.lm_head(hidden_states)
|
478 |
+
loss = None
|
479 |
+
if labels is not None:
|
480 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
481 |
+
shift_labels = labels[..., 1:].contiguous()
|
482 |
+
(batch_size, seq_length, vocab_size) = shift_logits.shape
|
483 |
+
loss_fct = CrossEntropyLoss()
|
484 |
+
loss = loss_fct(
|
485 |
+
shift_logits.view(batch_size * seq_length, vocab_size),
|
486 |
+
shift_labels.view(batch_size * seq_length),
|
487 |
+
)
|
488 |
+
if not return_dict:
|
489 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
490 |
+
return (loss,) + output if loss is not None else output
|
491 |
+
return CausalLMOutputWithCrossAttentions(
|
492 |
+
loss=loss,
|
493 |
+
logits=lm_logits,
|
494 |
+
past_key_values=transformer_outputs.past_key_values,
|
495 |
+
hidden_states=transformer_outputs.hidden_states,
|
496 |
+
attentions=transformer_outputs.attentions,
|
497 |
+
)
|
498 |
+
|
499 |
+
def prepare_inputs_for_generation(
|
500 |
+
self: BloomForCausalLM,
|
501 |
+
input_ids: torch.LongTensor,
|
502 |
+
past: Optional[torch.Tensor] = None,
|
503 |
+
attention_mask: Optional[torch.Tensor] = None,
|
504 |
+
**kwargs,
|
505 |
+
) -> dict:
|
506 |
+
if past:
|
507 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
508 |
+
bidirectional_mask = None
|
509 |
+
if past[0][0].shape[0] == input_ids.shape[0]:
|
510 |
+
past = self._convert_to_bloom_cache(past)
|
511 |
+
else:
|
512 |
+
bidirectional_mask = torch.ones_like(input_ids)
|
513 |
+
return {
|
514 |
+
"input_ids": input_ids,
|
515 |
+
"past_key_values": past,
|
516 |
+
"use_cache": True,
|
517 |
+
"attention_mask": attention_mask,
|
518 |
+
"bidirectional_mask": bidirectional_mask,
|
519 |
+
}
|
520 |
+
|
521 |
+
setattr(model, "forward", MethodType(forward, model))
|
522 |
+
setattr(
|
523 |
+
model,
|
524 |
+
"prepare_inputs_for_generation",
|
525 |
+
MethodType(prepare_inputs_for_generation, model),
|
526 |
+
)
|
527 |
+
setattr(model, "_prefix_lm_converted", True)
|
528 |
+
return model
|
529 |
+
|
530 |
+
|
531 |
+
def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
|
532 |
+
"""Converts an OPT Causal LM to a Prefix LM.
|
533 |
+
|
534 |
+
Supported HuggingFace model classes:
|
535 |
+
- `OPTForCausalLM`
|
536 |
+
|
537 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
538 |
+
"""
|
539 |
+
if hasattr(model, "_prefix_lm_converted"):
|
540 |
+
return model
|
541 |
+
assert isinstance(model, OPTForCausalLM)
|
542 |
+
assert (
|
543 |
+
model.config.add_cross_attention == False
|
544 |
+
), "Only supports OPT decoder-only models"
|
545 |
+
setattr(model, "_original_forward", getattr(model, "forward"))
|
546 |
+
setattr(model, "_original_generate", getattr(model, "generate"))
|
547 |
+
model.model.decoder.bidirectional_mask = None
|
548 |
+
|
549 |
+
def _prepare_decoder_attention_mask(
|
550 |
+
self, attention_mask, input_shape, inputs_embeds, past_key_values_length
|
551 |
+
):
|
552 |
+
combined_attention_mask = None
|
553 |
+
if input_shape[-1] > 1:
|
554 |
+
if self.bidirectional_mask == "g":
|
555 |
+
(bsz, src_length) = input_shape
|
556 |
+
combined_attention_mask = torch.zeros(
|
557 |
+
(bsz, 1, src_length, src_length + past_key_values_length),
|
558 |
+
dtype=inputs_embeds.dtype,
|
559 |
+
device=inputs_embeds.device,
|
560 |
+
)
|
561 |
+
else:
|
562 |
+
combined_attention_mask = _make_causal_mask_opt(
|
563 |
+
input_shape,
|
564 |
+
inputs_embeds.dtype,
|
565 |
+
past_key_values_length=past_key_values_length,
|
566 |
+
).to(inputs_embeds.device)
|
567 |
+
if self.bidirectional_mask is not None:
|
568 |
+
assert attention_mask.shape == self.bidirectional_mask.shape
|
569 |
+
expanded_bidirectional_mask = _expand_mask_opt(
|
570 |
+
self.bidirectional_mask,
|
571 |
+
inputs_embeds.dtype,
|
572 |
+
tgt_len=input_shape[-1],
|
573 |
+
).to(inputs_embeds.device)
|
574 |
+
combined_attention_mask = torch.maximum(
|
575 |
+
expanded_bidirectional_mask, combined_attention_mask
|
576 |
+
)
|
577 |
+
if attention_mask is not None:
|
578 |
+
expanded_attn_mask = _expand_mask_opt(
|
579 |
+
attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
580 |
+
).to(inputs_embeds.device)
|
581 |
+
combined_attention_mask = (
|
582 |
+
expanded_attn_mask
|
583 |
+
if combined_attention_mask is None
|
584 |
+
else expanded_attn_mask + combined_attention_mask
|
585 |
+
)
|
586 |
+
return combined_attention_mask
|
587 |
+
|
588 |
+
setattr(
|
589 |
+
model.model.decoder,
|
590 |
+
"_prepare_decoder_attention_mask",
|
591 |
+
MethodType(_prepare_decoder_attention_mask, model.model.decoder),
|
592 |
+
)
|
593 |
+
|
594 |
+
def forward(
|
595 |
+
self: OPTForCausalLM,
|
596 |
+
input_ids: Optional[torch.LongTensor] = None,
|
597 |
+
attention_mask: Optional[torch.Tensor] = None,
|
598 |
+
bidirectional_mask: Optional[torch.ByteTensor] = None,
|
599 |
+
head_mask: Optional[torch.Tensor] = None,
|
600 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
601 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
602 |
+
labels: Optional[torch.LongTensor] = None,
|
603 |
+
use_cache: Optional[bool] = None,
|
604 |
+
output_attentions: Optional[bool] = None,
|
605 |
+
output_hidden_states: Optional[bool] = None,
|
606 |
+
return_dict: Optional[bool] = None,
|
607 |
+
):
|
608 |
+
def call_og_forward():
|
609 |
+
return self._original_forward(
|
610 |
+
input_ids=input_ids,
|
611 |
+
attention_mask=attention_mask,
|
612 |
+
head_mask=head_mask,
|
613 |
+
past_key_values=past_key_values,
|
614 |
+
inputs_embeds=inputs_embeds,
|
615 |
+
labels=labels,
|
616 |
+
use_cache=use_cache,
|
617 |
+
output_attentions=output_attentions,
|
618 |
+
output_hidden_states=output_hidden_states,
|
619 |
+
return_dict=return_dict,
|
620 |
+
)
|
621 |
+
|
622 |
+
if bidirectional_mask is None:
|
623 |
+
return call_og_forward()
|
624 |
+
self.model.decoder.bidirectional_mask = bidirectional_mask
|
625 |
+
try:
|
626 |
+
outputs = call_og_forward()
|
627 |
+
except:
|
628 |
+
self.model.decoder.bidirectional_mask = None
|
629 |
+
raise
|
630 |
+
self.model.decoder.bidirectional_mask = None
|
631 |
+
return outputs
|
632 |
+
|
633 |
+
def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
|
634 |
+
"""Wraps original generate to enable PrefixLM-style attention."""
|
635 |
+
self.model.decoder.bidirectional_mask = "g"
|
636 |
+
try:
|
637 |
+
output = self._original_generate(*args, **kwargs)
|
638 |
+
except:
|
639 |
+
self.model.decoder.bidirectional_mask = None
|
640 |
+
raise
|
641 |
+
self.model.decoder.bidirectional_mask = None
|
642 |
+
return output
|
643 |
+
|
644 |
+
setattr(model, "forward", MethodType(forward, model))
|
645 |
+
setattr(model, "generate", MethodType(generate, model))
|
646 |
+
setattr(model, "_prefix_lm_converted", True)
|
647 |
+
return model
|
648 |
+
|
649 |
+
|
650 |
+
_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
|
651 |
+
CAUSAL_LM_TYPES = Union[
|
652 |
+
GPT2LMHeadModel,
|
653 |
+
GPTJForCausalLM,
|
654 |
+
GPTNeoForCausalLM,
|
655 |
+
GPTNeoXForCausalLM,
|
656 |
+
BloomForCausalLM,
|
657 |
+
OPTForCausalLM,
|
658 |
+
]
|
659 |
+
|
660 |
+
|
661 |
+
def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
|
662 |
+
"""Converts a HuggingFace Causal LM to a Prefix LM.
|
663 |
+
|
664 |
+
Supported HuggingFace model classes:
|
665 |
+
- `GPT2LMHeadModel`
|
666 |
+
- `GPTNeoForCausalLM`
|
667 |
+
- `GPTNeoXForCausalLM`
|
668 |
+
- `GPTJForCausalLM`
|
669 |
+
- `BloomForCausalLM`
|
670 |
+
- `OPTForCausalLM`
|
671 |
+
|
672 |
+
Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
|
673 |
+
`generate` method and/or select underlying methods depending on the model class.
|
674 |
+
|
675 |
+
These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
|
676 |
+
|
677 |
+
Notes on training:
|
678 |
+
To actually train the converted model as a Prefix LM, training batches will need to indicate
|
679 |
+
the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
|
680 |
+
|
681 |
+
**This is not a standard input and requires custom layers either within or after your dataloader.**
|
682 |
+
|
683 |
+
In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
|
684 |
+
such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
|
685 |
+
That is, the prefix portion of the sequence should not generate any loss. Loss should only be
|
686 |
+
generated by the target portion of the sequence.
|
687 |
+
|
688 |
+
Notes on `GPTNeoForCausalLM`:
|
689 |
+
To simplify the implementation, "global" and "local" attention layers are handled differently.
|
690 |
+
For "global" layers, we handle conversion as described above. For "local" layers, which use a
|
691 |
+
causal attention mask within a restricted local window, we do not alter the masking.
|
692 |
+
|
693 |
+
Notes on `forward` method conversion:
|
694 |
+
After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
|
695 |
+
which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
|
696 |
+
belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
|
697 |
+
0 indicates token positions belonging to the target.
|
698 |
+
|
699 |
+
The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
|
700 |
+
causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
|
701 |
+
the causal masks before returning the result.
|
702 |
+
|
703 |
+
Notes on `generate` method conversion:
|
704 |
+
After conversion, the `generate` method will have the same signature but will internally
|
705 |
+
convert all causal masks to be purely bidirectional, call the original `generate` method, and
|
706 |
+
(where appropriate) reset the causal masks before returning the result.
|
707 |
+
|
708 |
+
This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
|
709 |
+
"prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
|
710 |
+
each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
|
711 |
+
another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
|
712 |
+
previously-generated tokens (also as expected in a Prefix LM).
|
713 |
+
|
714 |
+
To preserve the API, the original methods are renamed to `_original_forward` and
|
715 |
+
`_original_generate`, and replaced with new `forward` and `generate` methods that wrap
|
716 |
+
them, respectively. Although implementation details vary by model class.
|
717 |
+
"""
|
718 |
+
if isinstance(model, _SUPPORTED_GPT_MODELS):
|
719 |
+
return _convert_gpt_causal_lm_to_prefix_lm(model)
|
720 |
+
elif isinstance(model, BloomForCausalLM):
|
721 |
+
return _convert_bloom_causal_lm_to_prefix_lm(model)
|
722 |
+
elif isinstance(model, OPTForCausalLM):
|
723 |
+
return _convert_opt_causal_lm_to_prefix_lm(model)
|
724 |
+
else:
|
725 |
+
raise TypeError(
|
726 |
+
f"Cannot convert model to Prefix LM. "
|
727 |
+
+ f"Model does not belong to set of supported HF models:"
|
728 |
+
+ f"\n{_SUPPORTED_HF_MODELS}"
|
729 |
+
)
|
730 |
+
|
731 |
+
|
732 |
+
def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
|
733 |
+
"""Attempts to add bidirectional_mask to batch if missing.
|
734 |
+
|
735 |
+
Raises:
|
736 |
+
KeyError if bidirectional_mask is missing and can't be inferred
|
737 |
+
"""
|
738 |
+
if "bidirectional_mask" not in batch:
|
739 |
+
if batch.get("mode", None) == "icl_task":
|
740 |
+
batch["bidirectional_mask"] = batch["attention_mask"].clone()
|
741 |
+
for i, continuation_indices in enumerate(batch["continuation_indices"]):
|
742 |
+
batch["bidirectional_mask"][i, continuation_indices] = 0
|
743 |
+
elif "labels" in batch and "attention_mask" in batch:
|
744 |
+
batch["bidirectional_mask"] = torch.logical_and(
|
745 |
+
torch.eq(batch["attention_mask"], 1), torch.eq(batch["labels"], -100)
|
746 |
+
).type_as(batch["attention_mask"])
|
747 |
+
else:
|
748 |
+
raise KeyError(
|
749 |
+
"No bidirectional_mask in batch and not sure how to construct one."
|
750 |
+
)
|
model/llava/model/language_model/mpt/meta_init_context.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import contextmanager
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
|
6 |
+
|
7 |
+
@contextmanager
|
8 |
+
def init_empty_weights(include_buffers: bool = False):
|
9 |
+
"""Meta initialization context manager.
|
10 |
+
|
11 |
+
A context manager under which models are initialized with all parameters
|
12 |
+
on the meta device, therefore creating an empty model. Useful when just
|
13 |
+
initializing the model would blow the available RAM.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
|
17 |
+
not to also put all buffers on the meta device while initializing.
|
18 |
+
|
19 |
+
Example:
|
20 |
+
```python
|
21 |
+
import torch.nn as nn
|
22 |
+
|
23 |
+
# Initialize a model with 100 billions parameters in no time and without using any RAM.
|
24 |
+
with init_empty_weights():
|
25 |
+
tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
|
26 |
+
```
|
27 |
+
|
28 |
+
<Tip warning={true}>
|
29 |
+
|
30 |
+
Any model created under this context manager has no weights. As such you can't do something like
|
31 |
+
`model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
|
32 |
+
|
33 |
+
</Tip>
|
34 |
+
"""
|
35 |
+
with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f:
|
36 |
+
yield f
|
37 |
+
|
38 |
+
|
39 |
+
@contextmanager
|
40 |
+
def init_on_device(device: torch.device, include_buffers: bool = False):
|
41 |
+
"""Device initialization context manager.
|
42 |
+
|
43 |
+
A context manager under which models are initialized with all parameters
|
44 |
+
on the specified device.
|
45 |
+
|
46 |
+
Args:
|
47 |
+
device (`torch.device`): Device to initialize all parameters on.
|
48 |
+
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
|
49 |
+
not to also put all buffers on the meta device while initializing.
|
50 |
+
|
51 |
+
Example:
|
52 |
+
```python
|
53 |
+
import torch.nn as nn
|
54 |
+
|
55 |
+
with init_on_device(device=torch.device("cuda")):
|
56 |
+
tst = nn.Liner(100, 100) # on `cuda` device
|
57 |
+
```
|
58 |
+
"""
|
59 |
+
old_register_parameter = nn.Module.register_parameter
|
60 |
+
if include_buffers:
|
61 |
+
old_register_buffer = nn.Module.register_buffer
|
62 |
+
|
63 |
+
def register_empty_parameter(module, name, param):
|
64 |
+
old_register_parameter(module, name, param)
|
65 |
+
if param is not None:
|
66 |
+
param_cls = type(module._parameters[name])
|
67 |
+
kwargs = module._parameters[name].__dict__
|
68 |
+
module._parameters[name] = param_cls(
|
69 |
+
module._parameters[name].to(device), **kwargs
|
70 |
+
)
|
71 |
+
|
72 |
+
def register_empty_buffer(module, name, buffer):
|
73 |
+
old_register_buffer(module, name, buffer)
|
74 |
+
if buffer is not None:
|
75 |
+
module._buffers[name] = module._buffers[name].to(device)
|
76 |
+
|
77 |
+
if include_buffers:
|
78 |
+
tensor_constructors_to_patch = {
|
79 |
+
torch_function_name: getattr(torch, torch_function_name)
|
80 |
+
for torch_function_name in ["empty", "zeros", "ones", "full"]
|
81 |
+
}
|
82 |
+
else:
|
83 |
+
tensor_constructors_to_patch = {}
|
84 |
+
|
85 |
+
def patch_tensor_constructor(fn):
|
86 |
+
def wrapper(*args, **kwargs):
|
87 |
+
kwargs["device"] = device
|
88 |
+
return fn(*args, **kwargs)
|
89 |
+
|
90 |
+
return wrapper
|
91 |
+
|
92 |
+
try:
|
93 |
+
nn.Module.register_parameter = register_empty_parameter
|
94 |
+
if include_buffers:
|
95 |
+
nn.Module.register_buffer = register_empty_buffer
|
96 |
+
for torch_function_name in tensor_constructors_to_patch.keys():
|
97 |
+
setattr(
|
98 |
+
torch,
|
99 |
+
torch_function_name,
|
100 |
+
patch_tensor_constructor(getattr(torch, torch_function_name)),
|
101 |
+
)
|
102 |
+
yield
|
103 |
+
finally:
|
104 |
+
nn.Module.register_parameter = old_register_parameter
|
105 |
+
if include_buffers:
|
106 |
+
nn.Module.register_buffer = old_register_buffer
|
107 |
+
for (
|
108 |
+
torch_function_name,
|
109 |
+
old_torch_function,
|
110 |
+
) in tensor_constructors_to_patch.items():
|
111 |
+
setattr(torch, torch_function_name, old_torch_function)
|
model/llava/model/language_model/mpt/modeling_mpt.py
ADDED
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""A simple, flexible implementation of a GPT model.
|
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 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from transformers import (PreTrainedModel, PreTrainedTokenizer,
|
13 |
+
PreTrainedTokenizerFast)
|
14 |
+
from transformers.modeling_outputs import (BaseModelOutputWithPast,
|
15 |
+
CausalLMOutputWithPast)
|
16 |
+
|
17 |
+
from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
|
18 |
+
from .attention import attn_bias_shape, build_attn_bias
|
19 |
+
from .blocks import MPTBlock
|
20 |
+
from .configuration_mpt import MPTConfig
|
21 |
+
from .custom_embedding import SharedEmbedding
|
22 |
+
from .hf_prefixlm_converter import (add_bidirectional_mask_if_missing,
|
23 |
+
convert_hf_causal_lm_to_prefix_lm)
|
24 |
+
from .meta_init_context import init_empty_weights
|
25 |
+
from .norm import NORM_CLASS_REGISTRY
|
26 |
+
from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
|
27 |
+
|
28 |
+
try:
|
29 |
+
from .flash_attn_triton import flash_attn_func
|
30 |
+
except:
|
31 |
+
pass
|
32 |
+
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
33 |
+
|
34 |
+
|
35 |
+
class MPTPreTrainedModel(PreTrainedModel):
|
36 |
+
config_class = MPTConfig
|
37 |
+
base_model_prefix = "model"
|
38 |
+
_no_split_modules = ["MPTBlock"]
|
39 |
+
|
40 |
+
|
41 |
+
class MPTModel(MPTPreTrainedModel):
|
42 |
+
def __init__(self, config: MPTConfig):
|
43 |
+
config._validate_config()
|
44 |
+
super().__init__(config)
|
45 |
+
self.attn_impl = config.attn_config["attn_impl"]
|
46 |
+
self.prefix_lm = config.attn_config["prefix_lm"]
|
47 |
+
self.attn_uses_sequence_id = config.attn_config["attn_uses_sequence_id"]
|
48 |
+
self.alibi = config.attn_config["alibi"]
|
49 |
+
self.alibi_bias_max = config.attn_config["alibi_bias_max"]
|
50 |
+
if config.init_device == "mixed":
|
51 |
+
if dist.get_local_rank() == 0:
|
52 |
+
config.init_device = "cpu"
|
53 |
+
else:
|
54 |
+
config.init_device = "meta"
|
55 |
+
if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
|
56 |
+
norm_options = " | ".join(NORM_CLASS_REGISTRY.keys())
|
57 |
+
raise NotImplementedError(
|
58 |
+
f"Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options})."
|
59 |
+
)
|
60 |
+
norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
|
61 |
+
self.embedding_fraction = config.embedding_fraction
|
62 |
+
self.wte = SharedEmbedding(
|
63 |
+
config.vocab_size, config.d_model, device=config.init_device
|
64 |
+
)
|
65 |
+
if not self.alibi:
|
66 |
+
self.wpe = torch.nn.Embedding(
|
67 |
+
config.max_seq_len, config.d_model, device=config.init_device
|
68 |
+
)
|
69 |
+
self.emb_drop = nn.Dropout(config.emb_pdrop)
|
70 |
+
self.blocks = nn.ModuleList(
|
71 |
+
[
|
72 |
+
MPTBlock(device=config.init_device, **config.to_dict())
|
73 |
+
for _ in range(config.n_layers)
|
74 |
+
]
|
75 |
+
)
|
76 |
+
self.norm_f = norm_class(config.d_model, device=config.init_device)
|
77 |
+
if config.init_device != "meta":
|
78 |
+
print(
|
79 |
+
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.'
|
80 |
+
)
|
81 |
+
self.apply(self.param_init_fn)
|
82 |
+
self.is_causal = not self.prefix_lm
|
83 |
+
self._attn_bias_initialized = False
|
84 |
+
self.attn_bias = None
|
85 |
+
self.attn_bias_shape = attn_bias_shape(
|
86 |
+
self.attn_impl,
|
87 |
+
config.n_heads,
|
88 |
+
config.max_seq_len,
|
89 |
+
self.alibi,
|
90 |
+
prefix_lm=self.prefix_lm,
|
91 |
+
causal=self.is_causal,
|
92 |
+
use_sequence_id=self.attn_uses_sequence_id,
|
93 |
+
)
|
94 |
+
if config.no_bias:
|
95 |
+
for module in self.modules():
|
96 |
+
if hasattr(module, "bias") and isinstance(module.bias, nn.Parameter):
|
97 |
+
if config.verbose:
|
98 |
+
warnings.warn(f"Removing bias ({module.bias}) from {module}.")
|
99 |
+
module.register_parameter("bias", None)
|
100 |
+
if config.verbose and config.verbose > 2:
|
101 |
+
print(self)
|
102 |
+
if "verbose" not in self.config.init_config:
|
103 |
+
self.config.init_config["verbose"] = self.config.verbose
|
104 |
+
if self.config.init_config["verbose"] > 1:
|
105 |
+
init_fn_name = self.config.init_config["name"]
|
106 |
+
warnings.warn(f"Using {init_fn_name} initialization.")
|
107 |
+
self.gradient_checkpointing = False
|
108 |
+
|
109 |
+
def get_input_embeddings(self):
|
110 |
+
return self.wte
|
111 |
+
|
112 |
+
def set_input_embeddings(self, value):
|
113 |
+
self.wte = value
|
114 |
+
|
115 |
+
@torch.no_grad()
|
116 |
+
def _attn_bias(
|
117 |
+
self,
|
118 |
+
device,
|
119 |
+
dtype,
|
120 |
+
attention_mask: Optional[torch.ByteTensor] = None,
|
121 |
+
prefix_mask: Optional[torch.ByteTensor] = None,
|
122 |
+
sequence_id: Optional[torch.LongTensor] = None,
|
123 |
+
):
|
124 |
+
if not self._attn_bias_initialized:
|
125 |
+
if self.attn_bias_shape:
|
126 |
+
self.attn_bias = torch.zeros(
|
127 |
+
self.attn_bias_shape, device=device, dtype=dtype
|
128 |
+
)
|
129 |
+
self.attn_bias = build_attn_bias(
|
130 |
+
self.attn_impl,
|
131 |
+
self.attn_bias,
|
132 |
+
self.config.n_heads,
|
133 |
+
self.config.max_seq_len,
|
134 |
+
causal=self.is_causal,
|
135 |
+
alibi=self.alibi,
|
136 |
+
alibi_bias_max=self.alibi_bias_max,
|
137 |
+
)
|
138 |
+
self._attn_bias_initialized = True
|
139 |
+
if self.attn_impl == "flash":
|
140 |
+
return (self.attn_bias, attention_mask)
|
141 |
+
if self.attn_bias is not None:
|
142 |
+
self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)
|
143 |
+
attn_bias = self.attn_bias
|
144 |
+
if self.prefix_lm:
|
145 |
+
assert isinstance(attn_bias, torch.Tensor)
|
146 |
+
assert isinstance(prefix_mask, torch.Tensor)
|
147 |
+
attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
|
148 |
+
if self.attn_uses_sequence_id and sequence_id is not None:
|
149 |
+
assert isinstance(attn_bias, torch.Tensor)
|
150 |
+
attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
|
151 |
+
if attention_mask is not None:
|
152 |
+
s_k = attention_mask.shape[-1]
|
153 |
+
if attn_bias is None:
|
154 |
+
attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)
|
155 |
+
else:
|
156 |
+
_s_k = max(0, attn_bias.size(-1) - s_k)
|
157 |
+
attn_bias = attn_bias[:, :, :, _s_k:]
|
158 |
+
if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:
|
159 |
+
raise ValueError(
|
160 |
+
f"attention_mask shape={attention_mask.shape} "
|
161 |
+
+ f"and prefix_mask shape={prefix_mask.shape} are not equal."
|
162 |
+
)
|
163 |
+
min_val = torch.finfo(attn_bias.dtype).min
|
164 |
+
attn_bias = attn_bias.masked_fill(
|
165 |
+
~attention_mask.view(-1, 1, 1, s_k), min_val
|
166 |
+
)
|
167 |
+
return (attn_bias, None)
|
168 |
+
|
169 |
+
def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):
|
170 |
+
(s_k, s_q) = attn_bias.shape[-2:]
|
171 |
+
if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
|
172 |
+
raise ValueError(
|
173 |
+
"attn_bias does not match the expected shape. "
|
174 |
+
+ f"The last two dimensions should both be {self.config.max_length} "
|
175 |
+
+ f"but are {s_k} and {s_q}."
|
176 |
+
)
|
177 |
+
seq_len = prefix_mask.shape[-1]
|
178 |
+
if seq_len > self.config.max_seq_len:
|
179 |
+
raise ValueError(
|
180 |
+
f"prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}"
|
181 |
+
)
|
182 |
+
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
183 |
+
causal = torch.tril(
|
184 |
+
torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)
|
185 |
+
).view(1, 1, seq_len, seq_len)
|
186 |
+
prefix = prefix_mask.view(-1, 1, 1, seq_len)
|
187 |
+
cannot_attend = ~torch.logical_or(causal, prefix.bool())
|
188 |
+
min_val = torch.finfo(attn_bias.dtype).min
|
189 |
+
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
190 |
+
return attn_bias
|
191 |
+
|
192 |
+
def _apply_sequence_id(
|
193 |
+
self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor
|
194 |
+
):
|
195 |
+
seq_len = sequence_id.shape[-1]
|
196 |
+
if seq_len > self.config.max_seq_len:
|
197 |
+
raise ValueError(
|
198 |
+
f"sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}"
|
199 |
+
)
|
200 |
+
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
201 |
+
cannot_attend = torch.logical_not(
|
202 |
+
torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))
|
203 |
+
).unsqueeze(1)
|
204 |
+
min_val = torch.finfo(attn_bias.dtype).min
|
205 |
+
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
206 |
+
return attn_bias
|
207 |
+
|
208 |
+
def forward(
|
209 |
+
self,
|
210 |
+
input_ids: torch.LongTensor,
|
211 |
+
past_key_values: Optional[List[Tuple[torch.FloatTensor]]] = None,
|
212 |
+
attention_mask: Optional[torch.ByteTensor] = None,
|
213 |
+
prefix_mask: Optional[torch.ByteTensor] = None,
|
214 |
+
sequence_id: Optional[torch.LongTensor] = None,
|
215 |
+
return_dict: Optional[bool] = None,
|
216 |
+
output_attentions: Optional[bool] = None,
|
217 |
+
output_hidden_states: Optional[bool] = None,
|
218 |
+
use_cache: Optional[bool] = None,
|
219 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
220 |
+
):
|
221 |
+
return_dict = (
|
222 |
+
return_dict if return_dict is not None else self.config.return_dict
|
223 |
+
)
|
224 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
225 |
+
if attention_mask is not None:
|
226 |
+
attention_mask = attention_mask.bool()
|
227 |
+
if prefix_mask is not None:
|
228 |
+
prefix_mask = prefix_mask.bool()
|
229 |
+
if not return_dict:
|
230 |
+
raise NotImplementedError(
|
231 |
+
"return_dict False is not implemented yet for MPT"
|
232 |
+
)
|
233 |
+
if output_attentions:
|
234 |
+
if self.attn_impl != "torch":
|
235 |
+
raise NotImplementedError(
|
236 |
+
"output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`."
|
237 |
+
)
|
238 |
+
if (
|
239 |
+
attention_mask is not None
|
240 |
+
and attention_mask[:, 0].sum() != attention_mask.shape[0]
|
241 |
+
and self.training
|
242 |
+
):
|
243 |
+
raise NotImplementedError(
|
244 |
+
"MPT does not support training with left padding."
|
245 |
+
)
|
246 |
+
if self.prefix_lm and prefix_mask is None:
|
247 |
+
raise ValueError(
|
248 |
+
"prefix_mask is a required argument when MPT is configured with prefix_lm=True."
|
249 |
+
)
|
250 |
+
if self.training:
|
251 |
+
if self.attn_uses_sequence_id and sequence_id is None:
|
252 |
+
raise ValueError(
|
253 |
+
"sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True "
|
254 |
+
+ "and the model is in train mode."
|
255 |
+
)
|
256 |
+
elif self.attn_uses_sequence_id is False and sequence_id is not None:
|
257 |
+
warnings.warn(
|
258 |
+
"MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. "
|
259 |
+
+ "This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True."
|
260 |
+
)
|
261 |
+
if input_ids is not None:
|
262 |
+
S = input_ids.size(1)
|
263 |
+
assert (
|
264 |
+
S <= self.config.max_seq_len
|
265 |
+
), f"Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}"
|
266 |
+
tok_emb = self.wte(input_ids)
|
267 |
+
else:
|
268 |
+
assert inputs_embeds is not None
|
269 |
+
assert (
|
270 |
+
self.alibi
|
271 |
+
), "inputs_embeds is not implemented for MPT unless for alibi."
|
272 |
+
S = inputs_embeds.size(1)
|
273 |
+
tok_emb = inputs_embeds
|
274 |
+
if self.alibi:
|
275 |
+
x = tok_emb
|
276 |
+
else:
|
277 |
+
past_position = 0
|
278 |
+
if past_key_values is not None:
|
279 |
+
if len(past_key_values) != self.config.n_layers:
|
280 |
+
raise ValueError(
|
281 |
+
f"past_key_values must provide a past_key_value for each attention "
|
282 |
+
+ f"layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r})."
|
283 |
+
)
|
284 |
+
past_position = past_key_values[0][0].size(1)
|
285 |
+
if self.attn_impl == "torch":
|
286 |
+
past_position = past_key_values[0][0].size(3)
|
287 |
+
if S + past_position > self.config.max_seq_len:
|
288 |
+
raise ValueError(
|
289 |
+
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}."
|
290 |
+
)
|
291 |
+
pos = torch.arange(
|
292 |
+
past_position,
|
293 |
+
S + past_position,
|
294 |
+
dtype=torch.long,
|
295 |
+
device=input_ids.device,
|
296 |
+
).unsqueeze(0)
|
297 |
+
if attention_mask is not None:
|
298 |
+
pos = torch.clamp(
|
299 |
+
pos
|
300 |
+
- torch.cumsum((~attention_mask).to(torch.int32), dim=1)[
|
301 |
+
:, past_position:
|
302 |
+
],
|
303 |
+
min=0,
|
304 |
+
)
|
305 |
+
pos_emb = self.wpe(pos)
|
306 |
+
x = tok_emb + pos_emb
|
307 |
+
if self.embedding_fraction == 1:
|
308 |
+
x = self.emb_drop(x)
|
309 |
+
else:
|
310 |
+
x_shrunk = x * self.embedding_fraction + x.detach() * (
|
311 |
+
1 - self.embedding_fraction
|
312 |
+
)
|
313 |
+
assert isinstance(self.emb_drop, nn.Module)
|
314 |
+
x = self.emb_drop(x_shrunk)
|
315 |
+
(attn_bias, attention_mask) = self._attn_bias(
|
316 |
+
device=x.device,
|
317 |
+
dtype=torch.float32,
|
318 |
+
attention_mask=attention_mask,
|
319 |
+
prefix_mask=prefix_mask,
|
320 |
+
sequence_id=sequence_id,
|
321 |
+
)
|
322 |
+
if use_cache and past_key_values is None:
|
323 |
+
past_key_values = [() for _ in range(self.config.n_layers)]
|
324 |
+
all_hidden_states = () if output_hidden_states else None
|
325 |
+
all_self_attns = () if output_attentions else None
|
326 |
+
for b_idx, block in enumerate(self.blocks):
|
327 |
+
if output_hidden_states:
|
328 |
+
assert all_hidden_states is not None
|
329 |
+
all_hidden_states = all_hidden_states + (x,)
|
330 |
+
past_key_value = (
|
331 |
+
past_key_values[b_idx] if past_key_values is not None else None
|
332 |
+
)
|
333 |
+
if self.gradient_checkpointing and self.training:
|
334 |
+
(x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(
|
335 |
+
block, x, past_key_value, attn_bias, attention_mask, self.is_causal
|
336 |
+
)
|
337 |
+
else:
|
338 |
+
(x, attn_weights, past_key_value) = block(
|
339 |
+
x,
|
340 |
+
past_key_value=past_key_value,
|
341 |
+
attn_bias=attn_bias,
|
342 |
+
attention_mask=attention_mask,
|
343 |
+
is_causal=self.is_causal,
|
344 |
+
)
|
345 |
+
if past_key_values is not None:
|
346 |
+
past_key_values[b_idx] = past_key_value
|
347 |
+
if output_attentions:
|
348 |
+
assert all_self_attns is not None
|
349 |
+
all_self_attns = all_self_attns + (attn_weights,)
|
350 |
+
x = self.norm_f(x)
|
351 |
+
if output_hidden_states:
|
352 |
+
assert all_hidden_states is not None
|
353 |
+
all_hidden_states = all_hidden_states + (x,)
|
354 |
+
return BaseModelOutputWithPast(
|
355 |
+
last_hidden_state=x,
|
356 |
+
past_key_values=past_key_values,
|
357 |
+
hidden_states=all_hidden_states,
|
358 |
+
attentions=all_self_attns,
|
359 |
+
)
|
360 |
+
|
361 |
+
def param_init_fn(self, module):
|
362 |
+
init_fn_name = self.config.init_config["name"]
|
363 |
+
MODEL_INIT_REGISTRY[init_fn_name](
|
364 |
+
module=module,
|
365 |
+
n_layers=self.config.n_layers,
|
366 |
+
d_model=self.config.d_model,
|
367 |
+
**self.config.init_config,
|
368 |
+
)
|
369 |
+
|
370 |
+
def fsdp_wrap_fn(self, module):
|
371 |
+
return isinstance(module, MPTBlock)
|
372 |
+
|
373 |
+
def activation_checkpointing_fn(self, module):
|
374 |
+
return isinstance(module, MPTBlock)
|
375 |
+
|
376 |
+
|
377 |
+
class MPTForCausalLM(MPTPreTrainedModel):
|
378 |
+
def __init__(self, config: MPTConfig):
|
379 |
+
super().__init__(config)
|
380 |
+
if not config.tie_word_embeddings:
|
381 |
+
raise ValueError("MPTForCausalLM only supports tied word embeddings")
|
382 |
+
print(f"Instantiating an MPTForCausalLM model from {__file__}")
|
383 |
+
self.transformer = MPTModel(config)
|
384 |
+
for child in self.transformer.children():
|
385 |
+
if isinstance(child, torch.nn.ModuleList):
|
386 |
+
continue
|
387 |
+
if isinstance(child, torch.nn.Module):
|
388 |
+
child._fsdp_wrap = True
|
389 |
+
self.logit_scale = None
|
390 |
+
if config.logit_scale is not None:
|
391 |
+
logit_scale = config.logit_scale
|
392 |
+
if isinstance(logit_scale, str):
|
393 |
+
if logit_scale == "inv_sqrt_d_model":
|
394 |
+
logit_scale = 1 / math.sqrt(config.d_model)
|
395 |
+
else:
|
396 |
+
raise ValueError(
|
397 |
+
f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'."
|
398 |
+
)
|
399 |
+
self.logit_scale = logit_scale
|
400 |
+
|
401 |
+
def get_input_embeddings(self):
|
402 |
+
return self.transformer.wte
|
403 |
+
|
404 |
+
def set_input_embeddings(self, value):
|
405 |
+
self.transformer.wte = value
|
406 |
+
|
407 |
+
def get_output_embeddings(self):
|
408 |
+
return self.transformer.wte
|
409 |
+
|
410 |
+
def set_output_embeddings(self, new_embeddings):
|
411 |
+
self.transformer.wte = new_embeddings
|
412 |
+
|
413 |
+
def set_decoder(self, decoder):
|
414 |
+
self.transformer = decoder
|
415 |
+
|
416 |
+
def get_decoder(self):
|
417 |
+
return self.transformer
|
418 |
+
|
419 |
+
def forward(
|
420 |
+
self,
|
421 |
+
input_ids: torch.LongTensor,
|
422 |
+
past_key_values: Optional[List[Tuple[torch.FloatTensor]]] = None,
|
423 |
+
attention_mask: Optional[torch.ByteTensor] = None,
|
424 |
+
prefix_mask: Optional[torch.ByteTensor] = None,
|
425 |
+
sequence_id: Optional[torch.LongTensor] = None,
|
426 |
+
labels: Optional[torch.LongTensor] = None,
|
427 |
+
return_dict: Optional[bool] = None,
|
428 |
+
output_attentions: Optional[bool] = None,
|
429 |
+
output_hidden_states: Optional[bool] = None,
|
430 |
+
use_cache: Optional[bool] = None,
|
431 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
432 |
+
):
|
433 |
+
return_dict = (
|
434 |
+
return_dict if return_dict is not None else self.config.return_dict
|
435 |
+
)
|
436 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
437 |
+
if inputs_embeds is not None:
|
438 |
+
raise NotImplementedError(
|
439 |
+
"inputs_embeds has to be None (for hf/peft support)."
|
440 |
+
)
|
441 |
+
outputs = self.transformer(
|
442 |
+
input_ids=input_ids,
|
443 |
+
past_key_values=past_key_values,
|
444 |
+
attention_mask=attention_mask,
|
445 |
+
prefix_mask=prefix_mask,
|
446 |
+
sequence_id=sequence_id,
|
447 |
+
return_dict=return_dict,
|
448 |
+
output_attentions=output_attentions,
|
449 |
+
output_hidden_states=output_hidden_states,
|
450 |
+
use_cache=use_cache,
|
451 |
+
)
|
452 |
+
logits = self.transformer.wte(
|
453 |
+
outputs.last_hidden_state.to(self.transformer.wte.weight.device), True
|
454 |
+
)
|
455 |
+
if self.logit_scale is not None:
|
456 |
+
if self.logit_scale == 0:
|
457 |
+
warnings.warn(
|
458 |
+
f"Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs."
|
459 |
+
)
|
460 |
+
logits *= self.logit_scale
|
461 |
+
loss = None
|
462 |
+
if labels is not None:
|
463 |
+
labels = torch.roll(labels, shifts=-1)
|
464 |
+
labels[:, -1] = -100
|
465 |
+
loss = F.cross_entropy(
|
466 |
+
logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1)
|
467 |
+
)
|
468 |
+
return CausalLMOutputWithPast(
|
469 |
+
loss=loss,
|
470 |
+
logits=logits,
|
471 |
+
past_key_values=outputs.past_key_values,
|
472 |
+
hidden_states=outputs.hidden_states,
|
473 |
+
attentions=outputs.attentions,
|
474 |
+
)
|
475 |
+
|
476 |
+
def param_init_fn(self, module):
|
477 |
+
init_fn_name = self.config.init_config["name"]
|
478 |
+
MODEL_INIT_REGISTRY[init_fn_name](
|
479 |
+
module=module,
|
480 |
+
n_layers=self.config.n_layers,
|
481 |
+
d_model=self.config.d_model,
|
482 |
+
**self.config.init_config,
|
483 |
+
)
|
484 |
+
|
485 |
+
def fsdp_wrap_fn(self, module):
|
486 |
+
return isinstance(module, MPTBlock)
|
487 |
+
|
488 |
+
def activation_checkpointing_fn(self, module):
|
489 |
+
return isinstance(module, MPTBlock)
|
490 |
+
|
491 |
+
def prepare_inputs_for_generation(
|
492 |
+
self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
|
493 |
+
):
|
494 |
+
if inputs_embeds is not None:
|
495 |
+
raise NotImplementedError("inputs_embeds is not implemented for MPT yet")
|
496 |
+
attention_mask = kwargs["attention_mask"].bool()
|
497 |
+
if attention_mask[:, -1].sum() != attention_mask.shape[0]:
|
498 |
+
raise NotImplementedError(
|
499 |
+
"MPT does not support generation with right padding."
|
500 |
+
)
|
501 |
+
if self.transformer.attn_uses_sequence_id and self.training:
|
502 |
+
sequence_id = torch.zeros_like(input_ids[:1])
|
503 |
+
else:
|
504 |
+
sequence_id = None
|
505 |
+
if past_key_values is not None:
|
506 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
507 |
+
if self.transformer.prefix_lm:
|
508 |
+
prefix_mask = torch.ones_like(attention_mask)
|
509 |
+
if kwargs.get("use_cache") == False:
|
510 |
+
raise NotImplementedError(
|
511 |
+
"MPT with prefix_lm=True does not support use_cache=False."
|
512 |
+
)
|
513 |
+
else:
|
514 |
+
prefix_mask = None
|
515 |
+
return {
|
516 |
+
"input_ids": input_ids,
|
517 |
+
"attention_mask": attention_mask,
|
518 |
+
"prefix_mask": prefix_mask,
|
519 |
+
"sequence_id": sequence_id,
|
520 |
+
"past_key_values": past_key_values,
|
521 |
+
"use_cache": kwargs.get("use_cache", True),
|
522 |
+
}
|
523 |
+
|
524 |
+
@staticmethod
|
525 |
+
def _reorder_cache(past_key_values, beam_idx):
|
526 |
+
"""Used by HuggingFace generate when using beam search with kv-caching.
|
527 |
+
|
528 |
+
See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
|
529 |
+
for an example in transformers.
|
530 |
+
"""
|
531 |
+
reordered_past = []
|
532 |
+
for layer_past in past_key_values:
|
533 |
+
reordered_past += [
|
534 |
+
tuple(
|
535 |
+
(past_state.index_select(0, beam_idx) for past_state in layer_past)
|
536 |
+
)
|
537 |
+
]
|
538 |
+
return reordered_past
|
model/llava/model/language_model/mpt/norm.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
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()
|
8 |
+
elif tensor.device.type == "cpu":
|
9 |
+
dtype = torch.get_autocast_cpu_dtype()
|
10 |
+
else:
|
11 |
+
raise NotImplementedError()
|
12 |
+
return tensor.to(dtype=dtype)
|
13 |
+
return tensor
|
14 |
+
|
15 |
+
|
16 |
+
class LPLayerNorm(torch.nn.LayerNorm):
|
17 |
+
def __init__(
|
18 |
+
self,
|
19 |
+
normalized_shape,
|
20 |
+
eps=1e-05,
|
21 |
+
elementwise_affine=True,
|
22 |
+
device=None,
|
23 |
+
dtype=None,
|
24 |
+
):
|
25 |
+
super().__init__(
|
26 |
+
normalized_shape=normalized_shape,
|
27 |
+
eps=eps,
|
28 |
+
elementwise_affine=elementwise_affine,
|
29 |
+
device=device,
|
30 |
+
dtype=dtype,
|
31 |
+
)
|
32 |
+
|
33 |
+
def forward(self, x):
|
34 |
+
module_device = x.device
|
35 |
+
downcast_x = _cast_if_autocast_enabled(x)
|
36 |
+
downcast_weight = (
|
37 |
+
_cast_if_autocast_enabled(self.weight)
|
38 |
+
if self.weight is not None
|
39 |
+
else self.weight
|
40 |
+
)
|
41 |
+
downcast_bias = (
|
42 |
+
_cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
|
43 |
+
)
|
44 |
+
with torch.autocast(enabled=False, device_type=module_device.type):
|
45 |
+
return torch.nn.functional.layer_norm(
|
46 |
+
downcast_x,
|
47 |
+
self.normalized_shape,
|
48 |
+
downcast_weight,
|
49 |
+
downcast_bias,
|
50 |
+
self.eps,
|
51 |
+
)
|
52 |
+
|
53 |
+
|
54 |
+
def rms_norm(x, weight=None, eps=1e-05):
|
55 |
+
output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
|
56 |
+
if weight is not None:
|
57 |
+
return output * weight
|
58 |
+
return output
|
59 |
+
|
60 |
+
|
61 |
+
class RMSNorm(torch.nn.Module):
|
62 |
+
def __init__(
|
63 |
+
self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None
|
64 |
+
):
|
65 |
+
super().__init__()
|
66 |
+
self.eps = eps
|
67 |
+
if weight:
|
68 |
+
self.weight = torch.nn.Parameter(
|
69 |
+
torch.ones(normalized_shape, dtype=dtype, device=device)
|
70 |
+
)
|
71 |
+
else:
|
72 |
+
self.register_parameter("weight", None)
|
73 |
+
|
74 |
+
def forward(self, x):
|
75 |
+
return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
|
76 |
+
|
77 |
+
|
78 |
+
class LPRMSNorm(RMSNorm):
|
79 |
+
def __init__(
|
80 |
+
self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None
|
81 |
+
):
|
82 |
+
super().__init__(
|
83 |
+
normalized_shape=normalized_shape,
|
84 |
+
eps=eps,
|
85 |
+
weight=weight,
|
86 |
+
dtype=dtype,
|
87 |
+
device=device,
|
88 |
+
)
|
89 |
+
|
90 |
+
def forward(self, x):
|
91 |
+
downcast_x = _cast_if_autocast_enabled(x)
|
92 |
+
downcast_weight = (
|
93 |
+
_cast_if_autocast_enabled(self.weight)
|
94 |
+
if self.weight is not None
|
95 |
+
else self.weight
|
96 |
+
)
|
97 |
+
with torch.autocast(enabled=False, device_type=x.device.type):
|
98 |
+
return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
|
99 |
+
|
100 |
+
|
101 |
+
NORM_CLASS_REGISTRY = {
|
102 |
+
"layernorm": torch.nn.LayerNorm,
|
103 |
+
"low_precision_layernorm": LPLayerNorm,
|
104 |
+
"rmsnorm": RMSNorm,
|
105 |
+
"low_precision_rmsnorm": LPRMSNorm,
|
106 |
+
}
|
model/llava/model/language_model/mpt/param_init_fns.py
ADDED
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import warnings
|
3 |
+
from collections.abc import Sequence
|
4 |
+
from functools import partial
|
5 |
+
from typing import Optional, Tuple, Union
|
6 |
+
|
7 |
+
import torch
|
8 |
+
from torch import nn
|
9 |
+
|
10 |
+
from .norm import NORM_CLASS_REGISTRY
|
11 |
+
|
12 |
+
|
13 |
+
def torch_default_param_init_fn_(module: nn.Module, verbose: int = 0, **kwargs):
|
14 |
+
del kwargs
|
15 |
+
if verbose > 1:
|
16 |
+
warnings.warn(f"Initializing network using module's reset_parameters attribute")
|
17 |
+
if hasattr(module, "reset_parameters"):
|
18 |
+
module.reset_parameters()
|
19 |
+
|
20 |
+
|
21 |
+
def fused_init_helper_(module: nn.Module, init_fn_):
|
22 |
+
_fused = getattr(module, "_fused", None)
|
23 |
+
if _fused is None:
|
24 |
+
raise RuntimeError(f"Internal logic error")
|
25 |
+
(dim, splits) = _fused
|
26 |
+
splits = (0, *splits, module.weight.size(dim))
|
27 |
+
for s, e in zip(splits[:-1], splits[1:]):
|
28 |
+
slice_indices = [slice(None)] * module.weight.ndim
|
29 |
+
slice_indices[dim] = slice(s, e)
|
30 |
+
init_fn_(module.weight[slice_indices])
|
31 |
+
|
32 |
+
|
33 |
+
def generic_param_init_fn_(
|
34 |
+
module: nn.Module,
|
35 |
+
init_fn_,
|
36 |
+
n_layers: int,
|
37 |
+
d_model: Optional[int] = None,
|
38 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
39 |
+
emb_init_std: Optional[float] = None,
|
40 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
41 |
+
verbose: int = 0,
|
42 |
+
**kwargs,
|
43 |
+
):
|
44 |
+
del kwargs
|
45 |
+
if verbose > 1:
|
46 |
+
warnings.warn(f"If model has bias parameters they are initialized to 0.")
|
47 |
+
init_div_is_residual = init_div_is_residual
|
48 |
+
if init_div_is_residual is False:
|
49 |
+
div_is_residual = 1.0
|
50 |
+
elif init_div_is_residual is True:
|
51 |
+
div_is_residual = math.sqrt(2 * n_layers)
|
52 |
+
elif isinstance(init_div_is_residual, float) or isinstance(
|
53 |
+
init_div_is_residual, int
|
54 |
+
):
|
55 |
+
div_is_residual = init_div_is_residual
|
56 |
+
elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
|
57 |
+
div_is_residual = float(init_div_is_residual)
|
58 |
+
else:
|
59 |
+
div_is_residual = 1.0
|
60 |
+
raise ValueError(
|
61 |
+
f"Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}"
|
62 |
+
)
|
63 |
+
if init_div_is_residual is not False:
|
64 |
+
if verbose > 1:
|
65 |
+
warnings.warn(
|
66 |
+
f"Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. "
|
67 |
+
+ f"Set `init_div_is_residual: false` in init config to disable this."
|
68 |
+
)
|
69 |
+
if isinstance(module, nn.Linear):
|
70 |
+
if hasattr(module, "_fused"):
|
71 |
+
fused_init_helper_(module, init_fn_)
|
72 |
+
else:
|
73 |
+
init_fn_(module.weight)
|
74 |
+
if module.bias is not None:
|
75 |
+
torch.nn.init.zeros_(module.bias)
|
76 |
+
if init_div_is_residual is not False and getattr(module, "_is_residual", False):
|
77 |
+
with torch.no_grad():
|
78 |
+
module.weight.div_(div_is_residual)
|
79 |
+
elif isinstance(module, nn.Embedding):
|
80 |
+
if emb_init_std is not None:
|
81 |
+
std = emb_init_std
|
82 |
+
if std == 0:
|
83 |
+
warnings.warn(f"Embedding layer initialized to 0.")
|
84 |
+
emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
|
85 |
+
if verbose > 1:
|
86 |
+
warnings.warn(
|
87 |
+
f"Embedding layer initialized using normal distribution with mean=0 and std={std!r}."
|
88 |
+
)
|
89 |
+
elif emb_init_uniform_lim is not None:
|
90 |
+
lim = emb_init_uniform_lim
|
91 |
+
if isinstance(lim, Sequence):
|
92 |
+
if len(lim) > 2:
|
93 |
+
raise ValueError(
|
94 |
+
f"Uniform init requires a min and a max limit. User input: {lim}."
|
95 |
+
)
|
96 |
+
if lim[0] == lim[1]:
|
97 |
+
warnings.warn(f"Embedding layer initialized to {lim[0]}.")
|
98 |
+
else:
|
99 |
+
if lim == 0:
|
100 |
+
warnings.warn(f"Embedding layer initialized to 0.")
|
101 |
+
lim = [-lim, lim]
|
102 |
+
(a, b) = lim
|
103 |
+
emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
|
104 |
+
if verbose > 1:
|
105 |
+
warnings.warn(
|
106 |
+
f"Embedding layer initialized using uniform distribution in range {lim}."
|
107 |
+
)
|
108 |
+
else:
|
109 |
+
emb_init_fn_ = init_fn_
|
110 |
+
emb_init_fn_(module.weight)
|
111 |
+
elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
|
112 |
+
if verbose > 1:
|
113 |
+
warnings.warn(
|
114 |
+
f"Norm weights are set to 1. If norm layer has a bias it is initialized to 0."
|
115 |
+
)
|
116 |
+
if hasattr(module, "weight") and module.weight is not None:
|
117 |
+
torch.nn.init.ones_(module.weight)
|
118 |
+
if hasattr(module, "bias") and module.bias is not None:
|
119 |
+
torch.nn.init.zeros_(module.bias)
|
120 |
+
elif isinstance(module, nn.MultiheadAttention):
|
121 |
+
if module._qkv_same_embed_dim:
|
122 |
+
assert module.in_proj_weight is not None
|
123 |
+
assert (
|
124 |
+
module.q_proj_weight is None
|
125 |
+
and module.k_proj_weight is None
|
126 |
+
and (module.v_proj_weight is None)
|
127 |
+
)
|
128 |
+
assert d_model is not None
|
129 |
+
_d = d_model
|
130 |
+
splits = (0, _d, 2 * _d, 3 * _d)
|
131 |
+
for s, e in zip(splits[:-1], splits[1:]):
|
132 |
+
init_fn_(module.in_proj_weight[s:e])
|
133 |
+
else:
|
134 |
+
assert (
|
135 |
+
module.q_proj_weight is not None
|
136 |
+
and module.k_proj_weight is not None
|
137 |
+
and (module.v_proj_weight is not None)
|
138 |
+
)
|
139 |
+
assert module.in_proj_weight is None
|
140 |
+
init_fn_(module.q_proj_weight)
|
141 |
+
init_fn_(module.k_proj_weight)
|
142 |
+
init_fn_(module.v_proj_weight)
|
143 |
+
if module.in_proj_bias is not None:
|
144 |
+
torch.nn.init.zeros_(module.in_proj_bias)
|
145 |
+
if module.bias_k is not None:
|
146 |
+
torch.nn.init.zeros_(module.bias_k)
|
147 |
+
if module.bias_v is not None:
|
148 |
+
torch.nn.init.zeros_(module.bias_v)
|
149 |
+
init_fn_(module.out_proj.weight)
|
150 |
+
if init_div_is_residual is not False and getattr(
|
151 |
+
module.out_proj, "_is_residual", False
|
152 |
+
):
|
153 |
+
with torch.no_grad():
|
154 |
+
module.out_proj.weight.div_(div_is_residual)
|
155 |
+
if module.out_proj.bias is not None:
|
156 |
+
torch.nn.init.zeros_(module.out_proj.bias)
|
157 |
+
else:
|
158 |
+
for _ in module.parameters(recurse=False):
|
159 |
+
raise NotImplementedError(
|
160 |
+
f"{module.__class__.__name__} parameters are not initialized by param_init_fn."
|
161 |
+
)
|
162 |
+
|
163 |
+
|
164 |
+
def _normal_init_(std, mean=0.0):
|
165 |
+
return partial(torch.nn.init.normal_, mean=mean, std=std)
|
166 |
+
|
167 |
+
|
168 |
+
def _normal_param_init_fn_(
|
169 |
+
module: nn.Module,
|
170 |
+
std: float,
|
171 |
+
n_layers: int,
|
172 |
+
d_model: Optional[int] = None,
|
173 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
174 |
+
emb_init_std: Optional[float] = None,
|
175 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
176 |
+
verbose: int = 0,
|
177 |
+
**kwargs,
|
178 |
+
):
|
179 |
+
del kwargs
|
180 |
+
init_fn_ = _normal_init_(std=std)
|
181 |
+
if verbose > 1:
|
182 |
+
warnings.warn(f"Using torch.nn.init.normal_ init fn mean=0.0, std={std}")
|
183 |
+
generic_param_init_fn_(
|
184 |
+
module=module,
|
185 |
+
init_fn_=init_fn_,
|
186 |
+
d_model=d_model,
|
187 |
+
n_layers=n_layers,
|
188 |
+
init_div_is_residual=init_div_is_residual,
|
189 |
+
emb_init_std=emb_init_std,
|
190 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
191 |
+
verbose=verbose,
|
192 |
+
)
|
193 |
+
|
194 |
+
|
195 |
+
def baseline_param_init_fn_(
|
196 |
+
module: nn.Module,
|
197 |
+
init_std: float,
|
198 |
+
n_layers: int,
|
199 |
+
d_model: Optional[int] = None,
|
200 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
201 |
+
emb_init_std: Optional[float] = None,
|
202 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
203 |
+
verbose: int = 0,
|
204 |
+
**kwargs,
|
205 |
+
):
|
206 |
+
del kwargs
|
207 |
+
if init_std is None:
|
208 |
+
raise ValueError(
|
209 |
+
"You must set model.init_config['init_std'] to a float value to use the default initialization scheme."
|
210 |
+
)
|
211 |
+
_normal_param_init_fn_(
|
212 |
+
module=module,
|
213 |
+
std=init_std,
|
214 |
+
d_model=d_model,
|
215 |
+
n_layers=n_layers,
|
216 |
+
init_div_is_residual=init_div_is_residual,
|
217 |
+
emb_init_std=emb_init_std,
|
218 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
219 |
+
verbose=verbose,
|
220 |
+
)
|
221 |
+
|
222 |
+
|
223 |
+
def small_param_init_fn_(
|
224 |
+
module: nn.Module,
|
225 |
+
n_layers: int,
|
226 |
+
d_model: int,
|
227 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
228 |
+
emb_init_std: Optional[float] = None,
|
229 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
230 |
+
verbose: int = 0,
|
231 |
+
**kwargs,
|
232 |
+
):
|
233 |
+
del kwargs
|
234 |
+
std = math.sqrt(2 / (5 * d_model))
|
235 |
+
_normal_param_init_fn_(
|
236 |
+
module=module,
|
237 |
+
std=std,
|
238 |
+
d_model=d_model,
|
239 |
+
n_layers=n_layers,
|
240 |
+
init_div_is_residual=init_div_is_residual,
|
241 |
+
emb_init_std=emb_init_std,
|
242 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
243 |
+
verbose=verbose,
|
244 |
+
)
|
245 |
+
|
246 |
+
|
247 |
+
def neox_param_init_fn_(
|
248 |
+
module: nn.Module,
|
249 |
+
n_layers: int,
|
250 |
+
d_model: int,
|
251 |
+
emb_init_std: Optional[float] = None,
|
252 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
253 |
+
verbose: int = 0,
|
254 |
+
**kwargs,
|
255 |
+
):
|
256 |
+
"""From section 2.3.1 of GPT-NeoX-20B:
|
257 |
+
|
258 |
+
An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
|
259 |
+
see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151
|
260 |
+
and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
|
261 |
+
"""
|
262 |
+
del kwargs
|
263 |
+
residual_div = n_layers / math.sqrt(10)
|
264 |
+
if verbose > 1:
|
265 |
+
warnings.warn(f"setting init_div_is_residual to {residual_div}")
|
266 |
+
small_param_init_fn_(
|
267 |
+
module=module,
|
268 |
+
d_model=d_model,
|
269 |
+
n_layers=n_layers,
|
270 |
+
init_div_is_residual=residual_div,
|
271 |
+
emb_init_std=emb_init_std,
|
272 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
273 |
+
verbose=verbose,
|
274 |
+
)
|
275 |
+
|
276 |
+
|
277 |
+
def kaiming_uniform_param_init_fn_(
|
278 |
+
module: nn.Module,
|
279 |
+
n_layers: int,
|
280 |
+
d_model: Optional[int] = None,
|
281 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
282 |
+
emb_init_std: Optional[float] = None,
|
283 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
284 |
+
init_gain: float = 0,
|
285 |
+
fan_mode: str = "fan_in",
|
286 |
+
init_nonlinearity: str = "leaky_relu",
|
287 |
+
verbose: int = 0,
|
288 |
+
**kwargs,
|
289 |
+
):
|
290 |
+
del kwargs
|
291 |
+
if verbose > 1:
|
292 |
+
warnings.warn(
|
293 |
+
f"Using nn.init.kaiming_uniform_ init fn with parameters: "
|
294 |
+
+ f"a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}"
|
295 |
+
)
|
296 |
+
kaiming_uniform_ = partial(
|
297 |
+
nn.init.kaiming_uniform_,
|
298 |
+
a=init_gain,
|
299 |
+
mode=fan_mode,
|
300 |
+
nonlinearity=init_nonlinearity,
|
301 |
+
)
|
302 |
+
generic_param_init_fn_(
|
303 |
+
module=module,
|
304 |
+
init_fn_=kaiming_uniform_,
|
305 |
+
d_model=d_model,
|
306 |
+
n_layers=n_layers,
|
307 |
+
init_div_is_residual=init_div_is_residual,
|
308 |
+
emb_init_std=emb_init_std,
|
309 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
310 |
+
verbose=verbose,
|
311 |
+
)
|
312 |
+
|
313 |
+
|
314 |
+
def kaiming_normal_param_init_fn_(
|
315 |
+
module: nn.Module,
|
316 |
+
n_layers: int,
|
317 |
+
d_model: Optional[int] = None,
|
318 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
319 |
+
emb_init_std: Optional[float] = None,
|
320 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
321 |
+
init_gain: float = 0,
|
322 |
+
fan_mode: str = "fan_in",
|
323 |
+
init_nonlinearity: str = "leaky_relu",
|
324 |
+
verbose: int = 0,
|
325 |
+
**kwargs,
|
326 |
+
):
|
327 |
+
del kwargs
|
328 |
+
if verbose > 1:
|
329 |
+
warnings.warn(
|
330 |
+
f"Using nn.init.kaiming_normal_ init fn with parameters: "
|
331 |
+
+ f"a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}"
|
332 |
+
)
|
333 |
+
kaiming_normal_ = partial(
|
334 |
+
torch.nn.init.kaiming_normal_,
|
335 |
+
a=init_gain,
|
336 |
+
mode=fan_mode,
|
337 |
+
nonlinearity=init_nonlinearity,
|
338 |
+
)
|
339 |
+
generic_param_init_fn_(
|
340 |
+
module=module,
|
341 |
+
init_fn_=kaiming_normal_,
|
342 |
+
d_model=d_model,
|
343 |
+
n_layers=n_layers,
|
344 |
+
init_div_is_residual=init_div_is_residual,
|
345 |
+
emb_init_std=emb_init_std,
|
346 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
347 |
+
verbose=verbose,
|
348 |
+
)
|
349 |
+
|
350 |
+
|
351 |
+
def xavier_uniform_param_init_fn_(
|
352 |
+
module: nn.Module,
|
353 |
+
n_layers: int,
|
354 |
+
d_model: Optional[int] = None,
|
355 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
356 |
+
emb_init_std: Optional[float] = None,
|
357 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
358 |
+
init_gain: float = 0,
|
359 |
+
verbose: int = 0,
|
360 |
+
**kwargs,
|
361 |
+
):
|
362 |
+
del kwargs
|
363 |
+
xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
|
364 |
+
if verbose > 1:
|
365 |
+
warnings.warn(
|
366 |
+
f"Using torch.nn.init.xavier_uniform_ init fn with parameters: "
|
367 |
+
+ f"gain={init_gain}"
|
368 |
+
)
|
369 |
+
generic_param_init_fn_(
|
370 |
+
module=module,
|
371 |
+
init_fn_=xavier_uniform_,
|
372 |
+
d_model=d_model,
|
373 |
+
n_layers=n_layers,
|
374 |
+
init_div_is_residual=init_div_is_residual,
|
375 |
+
emb_init_std=emb_init_std,
|
376 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
377 |
+
verbose=verbose,
|
378 |
+
)
|
379 |
+
|
380 |
+
|
381 |
+
def xavier_normal_param_init_fn_(
|
382 |
+
module: nn.Module,
|
383 |
+
n_layers: int,
|
384 |
+
d_model: Optional[int] = None,
|
385 |
+
init_div_is_residual: Union[int, float, str, bool] = True,
|
386 |
+
emb_init_std: Optional[float] = None,
|
387 |
+
emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]] = None,
|
388 |
+
init_gain: float = 0,
|
389 |
+
verbose: int = 0,
|
390 |
+
**kwargs,
|
391 |
+
):
|
392 |
+
xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
|
393 |
+
if verbose > 1:
|
394 |
+
warnings.warn(
|
395 |
+
f"Using torch.nn.init.xavier_normal_ init fn with parameters: "
|
396 |
+
+ f"gain={init_gain}"
|
397 |
+
)
|
398 |
+
generic_param_init_fn_(
|
399 |
+
module=module,
|
400 |
+
init_fn_=xavier_normal_,
|
401 |
+
d_model=d_model,
|
402 |
+
n_layers=n_layers,
|
403 |
+
init_div_is_residual=init_div_is_residual,
|
404 |
+
emb_init_std=emb_init_std,
|
405 |
+
emb_init_uniform_lim=emb_init_uniform_lim,
|
406 |
+
verbose=verbose,
|
407 |
+
)
|
408 |
+
|
409 |
+
|
410 |
+
MODEL_INIT_REGISTRY = {
|
411 |
+
"default_": torch_default_param_init_fn_,
|
412 |
+
"baseline_": baseline_param_init_fn_,
|
413 |
+
"kaiming_uniform_": kaiming_uniform_param_init_fn_,
|
414 |
+
"kaiming_normal_": kaiming_normal_param_init_fn_,
|
415 |
+
"neox_init_": neox_param_init_fn_,
|
416 |
+
"small_init_": small_param_init_fn_,
|
417 |
+
"xavier_uniform_": xavier_uniform_param_init_fn_,
|
418 |
+
"xavier_normal_": xavier_normal_param_init_fn_,
|
419 |
+
}
|
model/llava/model/llava_arch.py
ADDED
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Haotian Liu
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
|
16 |
+
from abc import ABC, abstractmethod
|
17 |
+
|
18 |
+
import torch
|
19 |
+
import torch.nn as nn
|
20 |
+
|
21 |
+
# from llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
|
22 |
+
from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
23 |
+
DEFAULT_IMAGE_PATCH_TOKEN, IGNORE_INDEX,
|
24 |
+
IMAGE_TOKEN_INDEX)
|
25 |
+
|
26 |
+
from .multimodal_encoder.builder import build_vision_tower
|
27 |
+
|
28 |
+
|
29 |
+
class LlavaMetaModel:
|
30 |
+
def __init__(self, config):
|
31 |
+
super(LlavaMetaModel, self).__init__(config)
|
32 |
+
|
33 |
+
if hasattr(config, "mm_vision_tower"):
|
34 |
+
self.vision_tower = build_vision_tower(config, delay_load=True)
|
35 |
+
self.mm_projector = nn.Linear(config.mm_hidden_size, config.hidden_size)
|
36 |
+
|
37 |
+
def get_vision_tower(self):
|
38 |
+
vision_tower = getattr(self, "vision_tower", None)
|
39 |
+
if type(vision_tower) is list:
|
40 |
+
vision_tower = vision_tower[0]
|
41 |
+
return vision_tower
|
42 |
+
|
43 |
+
def initialize_vision_modules(self, model_args, fsdp=None):
|
44 |
+
vision_tower = model_args.vision_tower
|
45 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
46 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
47 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
48 |
+
|
49 |
+
self.config.mm_vision_tower = vision_tower
|
50 |
+
|
51 |
+
vision_tower = build_vision_tower(model_args)
|
52 |
+
|
53 |
+
if fsdp is not None and len(fsdp) > 0:
|
54 |
+
self.vision_tower = [vision_tower]
|
55 |
+
else:
|
56 |
+
self.vision_tower = vision_tower
|
57 |
+
|
58 |
+
self.config.use_mm_proj = True
|
59 |
+
self.config.mm_hidden_size = vision_tower.hidden_size
|
60 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
61 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
62 |
+
|
63 |
+
if not hasattr(self, "mm_projector"):
|
64 |
+
self.mm_projector = nn.Linear(
|
65 |
+
self.config.mm_hidden_size, self.config.hidden_size
|
66 |
+
)
|
67 |
+
|
68 |
+
if pretrain_mm_mlp_adapter is not None:
|
69 |
+
mm_projector_weights = torch.load(
|
70 |
+
pretrain_mm_mlp_adapter, map_location="cpu"
|
71 |
+
)
|
72 |
+
|
73 |
+
def get_w(weights, keyword):
|
74 |
+
return {
|
75 |
+
k.split(keyword + ".")[1]: v
|
76 |
+
for k, v in weights.items()
|
77 |
+
if keyword in k
|
78 |
+
}
|
79 |
+
|
80 |
+
self.mm_projector.load_state_dict(
|
81 |
+
get_w(mm_projector_weights, "mm_projector")
|
82 |
+
)
|
83 |
+
|
84 |
+
|
85 |
+
class LlavaMetaForCausalLM(ABC):
|
86 |
+
@abstractmethod
|
87 |
+
def get_model(self):
|
88 |
+
pass
|
89 |
+
|
90 |
+
def get_vision_tower(self):
|
91 |
+
return self.get_model().get_vision_tower()
|
92 |
+
|
93 |
+
def encode_images(self, images):
|
94 |
+
image_features = self.get_model().get_vision_tower()(images)
|
95 |
+
image_features = self.get_model().mm_projector(image_features)
|
96 |
+
return image_features
|
97 |
+
|
98 |
+
def prepare_inputs_labels_for_multimodal(
|
99 |
+
self, input_ids, attention_mask, past_key_values, labels, images
|
100 |
+
):
|
101 |
+
vision_tower = self.get_vision_tower()
|
102 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
103 |
+
if (
|
104 |
+
past_key_values is not None
|
105 |
+
and vision_tower is not None
|
106 |
+
and images is not None
|
107 |
+
and input_ids.shape[1] == 1
|
108 |
+
):
|
109 |
+
attention_mask = torch.ones(
|
110 |
+
(attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1),
|
111 |
+
dtype=attention_mask.dtype,
|
112 |
+
device=attention_mask.device,
|
113 |
+
)
|
114 |
+
return input_ids, attention_mask, past_key_values, None, labels
|
115 |
+
|
116 |
+
if type(images) is list or images.ndim == 5:
|
117 |
+
concat_images = torch.cat([image for image in images], dim=0)
|
118 |
+
image_features = self.encode_images(concat_images)
|
119 |
+
split_sizes = [image.shape[0] for image in images]
|
120 |
+
image_features = torch.split(image_features, split_sizes, dim=0)
|
121 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
122 |
+
else:
|
123 |
+
image_features = self.encode_images(images)
|
124 |
+
|
125 |
+
new_input_embeds = []
|
126 |
+
new_labels = [] if labels is not None else None
|
127 |
+
cur_image_idx = 0
|
128 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
129 |
+
if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
|
130 |
+
# multimodal LLM, but the current sample is not multimodal
|
131 |
+
cur_input_embeds = self.get_model().embed_tokens(cur_input_ids)
|
132 |
+
cur_input_embeds = (
|
133 |
+
cur_input_embeds
|
134 |
+
+ (
|
135 |
+
0.0 * self.get_model().mm_projector(vision_tower.dummy_feature)
|
136 |
+
).sum()
|
137 |
+
)
|
138 |
+
new_input_embeds.append(cur_input_embeds)
|
139 |
+
if labels is not None:
|
140 |
+
new_labels.append(labels[batch_idx])
|
141 |
+
cur_image_idx += 1
|
142 |
+
continue
|
143 |
+
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
144 |
+
cur_new_input_embeds = []
|
145 |
+
if labels is not None:
|
146 |
+
cur_labels = labels[batch_idx]
|
147 |
+
cur_new_labels = []
|
148 |
+
assert cur_labels.shape == cur_input_ids.shape
|
149 |
+
while image_token_indices.numel() > 0:
|
150 |
+
cur_image_features = image_features[cur_image_idx]
|
151 |
+
image_token_start = image_token_indices[0]
|
152 |
+
if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(
|
153 |
+
self.config, "mm_use_im_start_end", False
|
154 |
+
):
|
155 |
+
cur_new_input_embeds.append(
|
156 |
+
self.get_model()
|
157 |
+
.embed_tokens(cur_input_ids[: image_token_start - 1])
|
158 |
+
.detach()
|
159 |
+
)
|
160 |
+
cur_new_input_embeds.append(
|
161 |
+
self.get_model().embed_tokens(
|
162 |
+
cur_input_ids[image_token_start - 1 : image_token_start]
|
163 |
+
)
|
164 |
+
)
|
165 |
+
cur_new_input_embeds.append(cur_image_features)
|
166 |
+
cur_new_input_embeds.append(
|
167 |
+
self.get_model().embed_tokens(
|
168 |
+
cur_input_ids[image_token_start + 1 : image_token_start + 2]
|
169 |
+
)
|
170 |
+
)
|
171 |
+
if labels is not None:
|
172 |
+
cur_new_labels.append(cur_labels[:image_token_start])
|
173 |
+
cur_new_labels.append(
|
174 |
+
torch.full(
|
175 |
+
(cur_image_features.shape[0],),
|
176 |
+
IGNORE_INDEX,
|
177 |
+
device=labels.device,
|
178 |
+
dtype=labels.dtype,
|
179 |
+
)
|
180 |
+
)
|
181 |
+
cur_new_labels.append(
|
182 |
+
cur_labels[image_token_start : image_token_start + 1]
|
183 |
+
)
|
184 |
+
cur_labels = cur_labels[image_token_start + 2 :]
|
185 |
+
elif getattr(self.config, "mm_use_im_start_end", False):
|
186 |
+
cur_new_input_embeds.append(
|
187 |
+
self.get_model().embed_tokens(cur_input_ids[:image_token_start])
|
188 |
+
)
|
189 |
+
cur_new_input_embeds.append(cur_image_features)
|
190 |
+
cur_new_input_embeds.append(
|
191 |
+
self.get_model().embed_tokens(
|
192 |
+
cur_input_ids[image_token_start + 1 : image_token_start + 2]
|
193 |
+
)
|
194 |
+
)
|
195 |
+
if labels is not None:
|
196 |
+
cur_new_labels.append(cur_labels[:image_token_start])
|
197 |
+
cur_new_labels.append(
|
198 |
+
torch.full(
|
199 |
+
(cur_image_features.shape[0],),
|
200 |
+
IGNORE_INDEX,
|
201 |
+
device=labels.device,
|
202 |
+
dtype=labels.dtype,
|
203 |
+
)
|
204 |
+
)
|
205 |
+
cur_new_labels.append(
|
206 |
+
cur_labels[image_token_start + 1 : image_token_start + 2]
|
207 |
+
)
|
208 |
+
cur_labels = cur_labels[image_token_start + 2 :]
|
209 |
+
else:
|
210 |
+
cur_new_input_embeds.append(
|
211 |
+
self.get_model().embed_tokens(cur_input_ids[:image_token_start])
|
212 |
+
)
|
213 |
+
cur_new_input_embeds.append(cur_image_features)
|
214 |
+
if labels is not None:
|
215 |
+
cur_new_labels.append(cur_labels[:image_token_start])
|
216 |
+
cur_new_labels.append(
|
217 |
+
torch.full(
|
218 |
+
(cur_image_features.shape[0],),
|
219 |
+
IGNORE_INDEX,
|
220 |
+
device=labels.device,
|
221 |
+
dtype=labels.dtype,
|
222 |
+
)
|
223 |
+
)
|
224 |
+
cur_labels = cur_labels[image_token_start + 1 :]
|
225 |
+
cur_image_idx += 1
|
226 |
+
if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(
|
227 |
+
self.config, "mm_use_im_start_end", False
|
228 |
+
):
|
229 |
+
cur_input_ids = cur_input_ids[image_token_start + 2 :]
|
230 |
+
elif getattr(self.config, "mm_use_im_start_end", False):
|
231 |
+
cur_input_ids = cur_input_ids[image_token_start + 2 :]
|
232 |
+
else:
|
233 |
+
cur_input_ids = cur_input_ids[image_token_start + 1 :]
|
234 |
+
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
235 |
+
if cur_input_ids.numel() > 0:
|
236 |
+
if getattr(self.config, "tune_mm_mlp_adapter", False) and getattr(
|
237 |
+
self.config, "mm_use_im_start_end", False
|
238 |
+
):
|
239 |
+
cur_new_input_embeds.append(
|
240 |
+
self.get_model().embed_tokens(cur_input_ids).detach()
|
241 |
+
)
|
242 |
+
elif getattr(self.config, "mm_use_im_start_end", False):
|
243 |
+
cur_new_input_embeds.append(
|
244 |
+
self.get_model().embed_tokens(cur_input_ids)
|
245 |
+
)
|
246 |
+
else:
|
247 |
+
cur_new_input_embeds.append(
|
248 |
+
self.get_model().embed_tokens(cur_input_ids)
|
249 |
+
)
|
250 |
+
if labels is not None:
|
251 |
+
cur_new_labels.append(cur_labels)
|
252 |
+
cur_new_input_embeds = [
|
253 |
+
x.to(device=self.device) for x in cur_new_input_embeds
|
254 |
+
]
|
255 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
|
256 |
+
new_input_embeds.append(cur_new_input_embeds)
|
257 |
+
if labels is not None:
|
258 |
+
cur_new_labels = torch.cat(cur_new_labels, dim=0)
|
259 |
+
new_labels.append(cur_new_labels)
|
260 |
+
|
261 |
+
if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
|
262 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
263 |
+
|
264 |
+
new_input_embeds_align = []
|
265 |
+
for cur_new_embed in new_input_embeds:
|
266 |
+
cur_new_embed = torch.cat(
|
267 |
+
(
|
268 |
+
cur_new_embed,
|
269 |
+
torch.zeros(
|
270 |
+
(max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]),
|
271 |
+
dtype=cur_new_embed.dtype,
|
272 |
+
device=cur_new_embed.device,
|
273 |
+
),
|
274 |
+
),
|
275 |
+
dim=0,
|
276 |
+
)
|
277 |
+
new_input_embeds_align.append(cur_new_embed)
|
278 |
+
new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
|
279 |
+
|
280 |
+
if labels is not None:
|
281 |
+
new_labels_align = []
|
282 |
+
_new_labels = new_labels
|
283 |
+
for cur_new_label in new_labels:
|
284 |
+
cur_new_label = torch.cat(
|
285 |
+
(
|
286 |
+
cur_new_label,
|
287 |
+
torch.full(
|
288 |
+
(max_len - cur_new_label.shape[0],),
|
289 |
+
IGNORE_INDEX,
|
290 |
+
dtype=cur_new_label.dtype,
|
291 |
+
device=cur_new_label.device,
|
292 |
+
),
|
293 |
+
),
|
294 |
+
dim=0,
|
295 |
+
)
|
296 |
+
new_labels_align.append(cur_new_label)
|
297 |
+
new_labels = torch.stack(new_labels_align, dim=0)
|
298 |
+
|
299 |
+
if attention_mask is not None:
|
300 |
+
new_attention_mask = []
|
301 |
+
for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(
|
302 |
+
attention_mask, _new_labels, new_labels
|
303 |
+
):
|
304 |
+
new_attn_mask_pad_left = torch.full(
|
305 |
+
(cur_new_labels.shape[0] - labels.shape[1],),
|
306 |
+
True,
|
307 |
+
dtype=attention_mask.dtype,
|
308 |
+
device=attention_mask.device,
|
309 |
+
)
|
310 |
+
new_attn_mask_pad_right = torch.full(
|
311 |
+
(cur_new_labels_align.shape[0] - cur_new_labels.shape[0],),
|
312 |
+
False,
|
313 |
+
dtype=attention_mask.dtype,
|
314 |
+
device=attention_mask.device,
|
315 |
+
)
|
316 |
+
cur_new_attention_mask = torch.cat(
|
317 |
+
(
|
318 |
+
new_attn_mask_pad_left,
|
319 |
+
cur_attention_mask,
|
320 |
+
new_attn_mask_pad_right,
|
321 |
+
),
|
322 |
+
dim=0,
|
323 |
+
)
|
324 |
+
new_attention_mask.append(cur_new_attention_mask)
|
325 |
+
attention_mask = torch.stack(new_attention_mask, dim=0)
|
326 |
+
assert attention_mask.shape == new_labels.shape
|
327 |
+
else:
|
328 |
+
new_input_embeds = torch.stack(new_input_embeds, dim=0)
|
329 |
+
if labels is not None:
|
330 |
+
new_labels = torch.stack(new_labels, dim=0)
|
331 |
+
|
332 |
+
if attention_mask is not None:
|
333 |
+
new_attn_mask_pad_left = torch.full(
|
334 |
+
(
|
335 |
+
attention_mask.shape[0],
|
336 |
+
new_input_embeds.shape[1] - input_ids.shape[1],
|
337 |
+
),
|
338 |
+
True,
|
339 |
+
dtype=attention_mask.dtype,
|
340 |
+
device=attention_mask.device,
|
341 |
+
)
|
342 |
+
attention_mask = torch.cat(
|
343 |
+
(new_attn_mask_pad_left, attention_mask), dim=1
|
344 |
+
)
|
345 |
+
assert attention_mask.shape == new_input_embeds.shape[:2]
|
346 |
+
|
347 |
+
return None, attention_mask, past_key_values, new_input_embeds, new_labels
|
348 |
+
|
349 |
+
# def initialize_vision_tokenizer(self, model_args, tokenizer):
|
350 |
+
def initialize_vision_tokenizer(self, model_args, num_new_tokens):
|
351 |
+
# if model_args.mm_use_im_patch_token:
|
352 |
+
# tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
353 |
+
# self.resize_token_embeddings(len(tokenizer))
|
354 |
+
|
355 |
+
if model_args.mm_use_im_start_end:
|
356 |
+
# num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
357 |
+
# self.resize_token_embeddings(len(tokenizer))
|
358 |
+
|
359 |
+
# if num_new_tokens > 0:
|
360 |
+
# input_embeddings = self.get_input_embeddings().weight.data
|
361 |
+
# output_embeddings = self.get_output_embeddings().weight.data
|
362 |
+
|
363 |
+
# input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
364 |
+
# dim=0, keepdim=True)
|
365 |
+
# output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
366 |
+
# dim=0, keepdim=True)
|
367 |
+
|
368 |
+
# input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
369 |
+
# output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
370 |
+
|
371 |
+
if model_args.tune_mm_mlp_adapter:
|
372 |
+
for p in self.get_input_embeddings().parameters():
|
373 |
+
p.requires_grad = True
|
374 |
+
for p in self.get_output_embeddings().parameters():
|
375 |
+
p.requires_grad = False
|
376 |
+
|
377 |
+
if model_args.pretrain_mm_mlp_adapter:
|
378 |
+
mm_projector_weights = torch.load(
|
379 |
+
model_args.pretrain_mm_mlp_adapter, map_location="cpu"
|
380 |
+
)
|
381 |
+
embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
|
382 |
+
assert num_new_tokens == 2
|
383 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
384 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[
|
385 |
+
-num_new_tokens:
|
386 |
+
]
|
387 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
388 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
389 |
+
else:
|
390 |
+
raise ValueError(
|
391 |
+
f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}."
|
392 |
+
)
|
393 |
+
elif model_args.mm_use_im_patch_token:
|
394 |
+
if model_args.tune_mm_mlp_adapter:
|
395 |
+
for p in self.get_input_embeddings().parameters():
|
396 |
+
p.requires_grad = False
|
397 |
+
for p in self.get_output_embeddings().parameters():
|
398 |
+
p.requires_grad = False
|
model/llava/model/make_delta.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Usage:
|
3 |
+
python3 -m llava.model.make_delta --base ~/model_weights/llama-7b --target ~/model_weights/llava-7b --delta ~/model_weights/llava-7b-delta --hub-repo-id liuhaotian/llava-7b-delta
|
4 |
+
"""
|
5 |
+
import argparse
|
6 |
+
|
7 |
+
import torch
|
8 |
+
from llava.model.utils import auto_upgrade
|
9 |
+
from tqdm import tqdm
|
10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
11 |
+
|
12 |
+
|
13 |
+
def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id):
|
14 |
+
print("Loading base model")
|
15 |
+
base = AutoModelForCausalLM.from_pretrained(
|
16 |
+
base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
|
17 |
+
)
|
18 |
+
|
19 |
+
print("Loading target model")
|
20 |
+
auto_upgrade(target_model_path)
|
21 |
+
target = AutoModelForCausalLM.from_pretrained(
|
22 |
+
target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
|
23 |
+
)
|
24 |
+
|
25 |
+
print("Calculating delta")
|
26 |
+
for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"):
|
27 |
+
if name not in base.state_dict():
|
28 |
+
assert name in [
|
29 |
+
"model.mm_projector.weight",
|
30 |
+
"model.mm_projector.bias",
|
31 |
+
], f"{name} not in base model"
|
32 |
+
continue
|
33 |
+
if param.data.shape == base.state_dict()[name].shape:
|
34 |
+
param.data -= base.state_dict()[name]
|
35 |
+
else:
|
36 |
+
assert name in [
|
37 |
+
"model.embed_tokens.weight",
|
38 |
+
"lm_head.weight",
|
39 |
+
], f"{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}"
|
40 |
+
bparam = base.state_dict()[name]
|
41 |
+
param.data[: bparam.shape[0], : bparam.shape[1]] -= bparam
|
42 |
+
|
43 |
+
print("Saving delta")
|
44 |
+
if hub_repo_id:
|
45 |
+
kwargs = {"push_to_hub": True, "repo_id": hub_repo_id}
|
46 |
+
else:
|
47 |
+
kwargs = {}
|
48 |
+
target.save_pretrained(delta_path, **kwargs)
|
49 |
+
target_tokenizer = AutoTokenizer.from_pretrained(target_model_path)
|
50 |
+
target_tokenizer.save_pretrained(delta_path, **kwargs)
|
51 |
+
|
52 |
+
|
53 |
+
if __name__ == "__main__":
|
54 |
+
parser = argparse.ArgumentParser()
|
55 |
+
parser.add_argument("--base-model-path", type=str, required=True)
|
56 |
+
parser.add_argument("--target-model-path", type=str, required=True)
|
57 |
+
parser.add_argument("--delta-path", type=str, required=True)
|
58 |
+
parser.add_argument("--hub-repo-id", type=str, default=None)
|
59 |
+
args = parser.parse_args()
|
60 |
+
|
61 |
+
make_delta(
|
62 |
+
args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id
|
63 |
+
)
|
model/llava/model/multimodal_encoder/builder.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .clip_encoder import CLIPVisionTower
|
2 |
+
|
3 |
+
|
4 |
+
def build_vision_tower(vision_tower_cfg, **kwargs):
|
5 |
+
vision_tower = getattr(
|
6 |
+
vision_tower_cfg,
|
7 |
+
"mm_vision_tower",
|
8 |
+
getattr(vision_tower_cfg, "vision_tower", None),
|
9 |
+
)
|
10 |
+
if (
|
11 |
+
vision_tower.startswith("openai")
|
12 |
+
or vision_tower.startswith("laion")
|
13 |
+
or "clip" in vision_tower
|
14 |
+
):
|
15 |
+
return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
16 |
+
|
17 |
+
raise ValueError(f"Unknown vision tower: {vision_tower}")
|
model/llava/model/multimodal_encoder/clip_encoder.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel
|
4 |
+
|
5 |
+
|
6 |
+
class CLIPVisionTower(nn.Module):
|
7 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
8 |
+
super().__init__()
|
9 |
+
|
10 |
+
self.is_loaded = False
|
11 |
+
|
12 |
+
self.vision_tower_name = vision_tower
|
13 |
+
self.select_layer = args.mm_vision_select_layer
|
14 |
+
self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
|
15 |
+
|
16 |
+
if not delay_load:
|
17 |
+
self.load_model()
|
18 |
+
else:
|
19 |
+
self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
20 |
+
|
21 |
+
def load_model(self):
|
22 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(
|
23 |
+
self.vision_tower_name
|
24 |
+
)
|
25 |
+
self.vision_tower = CLIPVisionModel.from_pretrained(
|
26 |
+
self.vision_tower_name, low_cpu_mem_usage=True
|
27 |
+
)
|
28 |
+
self.vision_tower.requires_grad_(False)
|
29 |
+
self.is_loaded = True
|
30 |
+
|
31 |
+
def feature_select(self, image_forward_outs):
|
32 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
33 |
+
if self.select_feature == "patch":
|
34 |
+
image_features = image_features[:, 1:]
|
35 |
+
elif self.select_feature == "cls_patch":
|
36 |
+
image_features = image_features
|
37 |
+
else:
|
38 |
+
raise ValueError(f"Unexpected select feature: {self.select_feature}")
|
39 |
+
return image_features
|
40 |
+
|
41 |
+
@torch.no_grad()
|
42 |
+
def forward(self, images):
|
43 |
+
if type(images) is list:
|
44 |
+
image_features = []
|
45 |
+
for image in images:
|
46 |
+
image_forward_out = self.vision_tower(
|
47 |
+
image.to(device=self.device, dtype=self.dtype).unsqueeze(0),
|
48 |
+
output_hidden_states=True,
|
49 |
+
)
|
50 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
51 |
+
image_features.append(image_feature)
|
52 |
+
else:
|
53 |
+
image_forward_outs = self.vision_tower(
|
54 |
+
images.to(device=self.device, dtype=self.dtype),
|
55 |
+
output_hidden_states=True,
|
56 |
+
)
|
57 |
+
image_features = self.feature_select(image_forward_outs).to(images.dtype)
|
58 |
+
|
59 |
+
torch.cuda.empty_cache()
|
60 |
+
return image_features
|
61 |
+
|
62 |
+
@property
|
63 |
+
def dummy_feature(self):
|
64 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
65 |
+
|
66 |
+
@property
|
67 |
+
def dtype(self):
|
68 |
+
return self.vision_tower.dtype
|
69 |
+
|
70 |
+
@property
|
71 |
+
def device(self):
|
72 |
+
return self.vision_tower.device
|
73 |
+
|
74 |
+
@property
|
75 |
+
def config(self):
|
76 |
+
if self.is_loaded:
|
77 |
+
return self.vision_tower.config
|
78 |
+
else:
|
79 |
+
return self.cfg_only
|
80 |
+
|
81 |
+
@property
|
82 |
+
def hidden_size(self):
|
83 |
+
return self.config.hidden_size
|
84 |
+
|
85 |
+
@property
|
86 |
+
def num_patches(self):
|
87 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
model/llava/model/utils.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoConfig
|
2 |
+
|
3 |
+
|
4 |
+
def auto_upgrade(config):
|
5 |
+
cfg = AutoConfig.from_pretrained(config)
|
6 |
+
if "llava" in config and "llava" not in cfg.model_type:
|
7 |
+
assert cfg.model_type == "llama"
|
8 |
+
print(
|
9 |
+
"You are using newer LLaVA code base, while the checkpoint of v0 is from older code base."
|
10 |
+
)
|
11 |
+
print(
|
12 |
+
"You must upgrade the checkpoint to the new code base (this can be done automatically)."
|
13 |
+
)
|
14 |
+
confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]")
|
15 |
+
if confirm.lower() in ["y", "yes"]:
|
16 |
+
print("Upgrading checkpoint...")
|
17 |
+
assert len(cfg.architectures) == 1
|
18 |
+
setattr(cfg.__class__, "model_type", "llava")
|
19 |
+
cfg.architectures[0] = "LlavaLlamaForCausalLM"
|
20 |
+
cfg.save_pretrained(config)
|
21 |
+
print("Checkpoint upgraded.")
|
22 |
+
else:
|
23 |
+
print("Checkpoint upgrade aborted.")
|
24 |
+
exit(1)
|
model/llava/train/llama_flash_attn_monkey_patch.py
ADDED
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from typing import List, Optional, Tuple
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import transformers
|
6 |
+
from einops import rearrange
|
7 |
+
from torch import nn
|
8 |
+
from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
|
9 |
+
|
10 |
+
try:
|
11 |
+
from flash_attn.flash_attn_interface import \
|
12 |
+
flash_attn_unpadded_qkvpacked_func
|
13 |
+
except ImportError:
|
14 |
+
from flash_attn.flash_attn_interface import (
|
15 |
+
flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func,
|
16 |
+
)
|
17 |
+
|
18 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
19 |
+
|
20 |
+
|
21 |
+
def forward(
|
22 |
+
self,
|
23 |
+
hidden_states: torch.Tensor,
|
24 |
+
attention_mask: Optional[torch.Tensor] = None,
|
25 |
+
position_ids: Optional[torch.Tensor] = None,
|
26 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
27 |
+
output_attentions: bool = False,
|
28 |
+
use_cache: bool = False,
|
29 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
30 |
+
"""Input shape: Batch x Time x Channel
|
31 |
+
|
32 |
+
attention_mask: [bsz, q_len]
|
33 |
+
"""
|
34 |
+
bsz, q_len, _ = hidden_states.size()
|
35 |
+
|
36 |
+
query_states = (
|
37 |
+
self.q_proj(hidden_states)
|
38 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
39 |
+
.transpose(1, 2)
|
40 |
+
)
|
41 |
+
key_states = (
|
42 |
+
self.k_proj(hidden_states)
|
43 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
44 |
+
.transpose(1, 2)
|
45 |
+
)
|
46 |
+
value_states = (
|
47 |
+
self.v_proj(hidden_states)
|
48 |
+
.view(bsz, q_len, self.num_heads, self.head_dim)
|
49 |
+
.transpose(1, 2)
|
50 |
+
)
|
51 |
+
# [bsz, q_len, nh, hd]
|
52 |
+
# [bsz, nh, q_len, hd]
|
53 |
+
|
54 |
+
kv_seq_len = key_states.shape[-2]
|
55 |
+
assert past_key_value is None, "past_key_value is not supported"
|
56 |
+
|
57 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
58 |
+
query_states, key_states = apply_rotary_pos_emb(
|
59 |
+
query_states, key_states, cos, sin, position_ids
|
60 |
+
)
|
61 |
+
# [bsz, nh, t, hd]
|
62 |
+
assert not output_attentions, "output_attentions is not supported"
|
63 |
+
assert not use_cache, "use_cache is not supported"
|
64 |
+
|
65 |
+
# Flash attention codes from
|
66 |
+
# https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/flash_attention.py
|
67 |
+
|
68 |
+
# transform the data into the format required by flash attention
|
69 |
+
qkv = torch.stack(
|
70 |
+
[query_states, key_states, value_states], dim=2
|
71 |
+
) # [bsz, nh, 3, q_len, hd]
|
72 |
+
qkv = qkv.transpose(1, 3) # [bsz, q_len, 3, nh, hd]
|
73 |
+
# We have disabled _prepare_decoder_attention_mask in LlamaModel
|
74 |
+
# the attention_mask should be the same as the key_padding_mask
|
75 |
+
key_padding_mask = attention_mask
|
76 |
+
|
77 |
+
if key_padding_mask is None:
|
78 |
+
qkv = rearrange(qkv, "b s ... -> (b s) ...")
|
79 |
+
max_s = q_len
|
80 |
+
cu_q_lens = torch.arange(
|
81 |
+
0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
|
82 |
+
)
|
83 |
+
output = flash_attn_unpadded_qkvpacked_func(
|
84 |
+
qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
|
85 |
+
)
|
86 |
+
output = rearrange(output, "(b s) ... -> b s ...", b=bsz)
|
87 |
+
else:
|
88 |
+
nheads = qkv.shape[-2]
|
89 |
+
x = rearrange(qkv, "b s three h d -> b s (three h d)")
|
90 |
+
x_unpad, indices, cu_q_lens, max_s = unpad_input(x, key_padding_mask)
|
91 |
+
x_unpad = rearrange(
|
92 |
+
x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads
|
93 |
+
)
|
94 |
+
output_unpad = flash_attn_unpadded_qkvpacked_func(
|
95 |
+
x_unpad, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
|
96 |
+
)
|
97 |
+
output = rearrange(
|
98 |
+
pad_input(
|
99 |
+
rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, bsz, q_len
|
100 |
+
),
|
101 |
+
"b s (h d) -> b s h d",
|
102 |
+
h=nheads,
|
103 |
+
)
|
104 |
+
return self.o_proj(rearrange(output, "b s h d -> b s (h d)")), None, None
|
105 |
+
|
106 |
+
|
107 |
+
# Disable the transformation of the attention mask in LlamaModel as the flash attention
|
108 |
+
# requires the attention mask to be the same as the key_padding_mask
|
109 |
+
def _prepare_decoder_attention_mask(
|
110 |
+
self, attention_mask, input_shape, inputs_embeds, past_key_values_length
|
111 |
+
):
|
112 |
+
# [bsz, seq_len]
|
113 |
+
return attention_mask
|
114 |
+
|
115 |
+
|
116 |
+
def replace_llama_attn_with_flash_attn():
|
117 |
+
cuda_major, cuda_minor = torch.cuda.get_device_capability()
|
118 |
+
if cuda_major < 8:
|
119 |
+
logging.warning(
|
120 |
+
"Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward."
|
121 |
+
"ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593"
|
122 |
+
)
|
123 |
+
transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
|
124 |
+
_prepare_decoder_attention_mask
|
125 |
+
)
|
126 |
+
transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
|
model/llava/train/llava_trainer.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import Optional
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from transformers import Trainer
|
6 |
+
|
7 |
+
|
8 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
9 |
+
from deepspeed import zero
|
10 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
11 |
+
|
12 |
+
if hasattr(param, "ds_id"):
|
13 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
14 |
+
if not ignore_status:
|
15 |
+
print(name, "no ignore status")
|
16 |
+
with zero.GatheredParameters([param]):
|
17 |
+
param = param.data.detach().cpu().clone()
|
18 |
+
else:
|
19 |
+
param = param.detach().cpu().clone()
|
20 |
+
return param
|
21 |
+
|
22 |
+
|
23 |
+
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
|
24 |
+
to_return = {
|
25 |
+
k: t
|
26 |
+
for k, t in named_params
|
27 |
+
if any(key_match in k for key_match in keys_to_match)
|
28 |
+
}
|
29 |
+
to_return = {
|
30 |
+
k: maybe_zero_3(v, ignore_status=True, name=k).cpu()
|
31 |
+
for k, v in to_return.items()
|
32 |
+
}
|
33 |
+
return to_return
|
34 |
+
|
35 |
+
|
36 |
+
class LLaVATrainer(Trainer):
|
37 |
+
def _save_checkpoint(self, model, trial, metrics=None):
|
38 |
+
if getattr(self.args, "tune_mm_mlp_adapter", False):
|
39 |
+
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
|
40 |
+
|
41 |
+
checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
|
42 |
+
|
43 |
+
run_dir = self._get_output_dir(trial=trial)
|
44 |
+
output_dir = os.path.join(run_dir, checkpoint_folder)
|
45 |
+
|
46 |
+
# Only save Adapter
|
47 |
+
keys_to_match = ["mm_projector"]
|
48 |
+
if getattr(self.args, "use_im_start_end", False):
|
49 |
+
keys_to_match.extend(["embed_tokens", "embed_in"])
|
50 |
+
|
51 |
+
weight_to_save = get_mm_adapter_state_maybe_zero_3(
|
52 |
+
self.model.named_parameters(), keys_to_match
|
53 |
+
)
|
54 |
+
|
55 |
+
if self.args.local_rank == 0 or self.args.local_rank == -1:
|
56 |
+
self.model.config.save_pretrained(output_dir)
|
57 |
+
torch.save(
|
58 |
+
weight_to_save, os.path.join(output_dir, f"mm_projector.bin")
|
59 |
+
)
|
60 |
+
else:
|
61 |
+
super(LLaVATrainer, self)._save_checkpoint(model, trial, metrics)
|
62 |
+
|
63 |
+
def _save(self, output_dir: Optional[str] = None, state_dict=None):
|
64 |
+
if getattr(self.args, "tune_mm_mlp_adapter", False):
|
65 |
+
pass
|
66 |
+
else:
|
67 |
+
super(LLaVATrainer, self)._save(output_dir, state_dict)
|
model/llava/train/train.py
ADDED
@@ -0,0 +1,1038 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
|
2 |
+
# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
|
3 |
+
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
|
17 |
+
import copy
|
18 |
+
import json
|
19 |
+
import logging
|
20 |
+
import os
|
21 |
+
import pathlib
|
22 |
+
from dataclasses import dataclass, field
|
23 |
+
from typing import Dict, List, Optional, Sequence
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import transformers
|
27 |
+
from llava import conversation as conversation_lib
|
28 |
+
from llava.constants import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
29 |
+
DEFAULT_IMAGE_TOKEN, IGNORE_INDEX,
|
30 |
+
IMAGE_TOKEN_INDEX)
|
31 |
+
from llava.mm_utils import tokenizer_image_token
|
32 |
+
from llava.model import *
|
33 |
+
from llava.train.llava_trainer import LLaVATrainer
|
34 |
+
from PIL import Image
|
35 |
+
from torch.utils.data import Dataset
|
36 |
+
|
37 |
+
local_rank = None
|
38 |
+
|
39 |
+
|
40 |
+
def rank0_print(*args):
|
41 |
+
if local_rank == 0:
|
42 |
+
print(*args)
|
43 |
+
|
44 |
+
|
45 |
+
@dataclass
|
46 |
+
class ModelArguments:
|
47 |
+
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
|
48 |
+
version: Optional[str] = field(default="v0")
|
49 |
+
freeze_backbone: bool = field(default=False)
|
50 |
+
tune_mm_mlp_adapter: bool = field(default=False)
|
51 |
+
vision_tower: Optional[str] = field(default=None)
|
52 |
+
mm_vision_select_layer: Optional[int] = field(
|
53 |
+
default=-1
|
54 |
+
) # default to the last layer
|
55 |
+
pretrain_mm_mlp_adapter: Optional[str] = field(default=None)
|
56 |
+
mm_use_im_start_end: bool = field(default=False)
|
57 |
+
mm_use_im_patch_token: bool = field(default=True)
|
58 |
+
mm_vision_select_feature: Optional[str] = field(default="patch")
|
59 |
+
|
60 |
+
|
61 |
+
@dataclass
|
62 |
+
class DataArguments:
|
63 |
+
data_path: str = field(
|
64 |
+
default=None, metadata={"help": "Path to the training data."}
|
65 |
+
)
|
66 |
+
lazy_preprocess: bool = False
|
67 |
+
is_multimodal: bool = False
|
68 |
+
image_folder: Optional[str] = field(default=None)
|
69 |
+
image_aspect_ratio: str = "square"
|
70 |
+
image_grid_pinpoints: Optional[str] = field(default=None)
|
71 |
+
|
72 |
+
|
73 |
+
@dataclass
|
74 |
+
class TrainingArguments(transformers.TrainingArguments):
|
75 |
+
cache_dir: Optional[str] = field(default=None)
|
76 |
+
optim: str = field(default="adamw_torch")
|
77 |
+
remove_unused_columns: bool = field(default=False)
|
78 |
+
freeze_mm_mlp_adapter: bool = field(default=False)
|
79 |
+
mpt_attn_impl: Optional[str] = field(default="triton")
|
80 |
+
model_max_length: int = field(
|
81 |
+
default=512,
|
82 |
+
metadata={
|
83 |
+
"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."
|
84 |
+
},
|
85 |
+
)
|
86 |
+
double_quant: bool = field(
|
87 |
+
default=True,
|
88 |
+
metadata={
|
89 |
+
"help": "Compress the quantization statistics through double quantization."
|
90 |
+
},
|
91 |
+
)
|
92 |
+
quant_type: str = field(
|
93 |
+
default="nf4",
|
94 |
+
metadata={
|
95 |
+
"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."
|
96 |
+
},
|
97 |
+
)
|
98 |
+
bits: int = field(default=16, metadata={"help": "How many bits to use."})
|
99 |
+
lora_enable: bool = False
|
100 |
+
lora_r: int = 64
|
101 |
+
lora_alpha: int = 16
|
102 |
+
lora_dropout: float = 0.05
|
103 |
+
lora_weight_path: str = ""
|
104 |
+
lora_bias: str = "none"
|
105 |
+
|
106 |
+
|
107 |
+
def maybe_zero_3(param, ignore_status=False, name=None):
|
108 |
+
from deepspeed import zero
|
109 |
+
from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
|
110 |
+
|
111 |
+
if hasattr(param, "ds_id"):
|
112 |
+
if param.ds_status == ZeroParamStatus.NOT_AVAILABLE:
|
113 |
+
if not ignore_status:
|
114 |
+
logging.warning(
|
115 |
+
f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}"
|
116 |
+
)
|
117 |
+
with zero.GatheredParameters([param]):
|
118 |
+
param = param.data.detach().cpu().clone()
|
119 |
+
else:
|
120 |
+
param = param.detach().cpu().clone()
|
121 |
+
return param
|
122 |
+
|
123 |
+
|
124 |
+
# Borrowed from peft.utils.get_peft_model_state_dict
|
125 |
+
def get_peft_state_maybe_zero_3(named_params, bias):
|
126 |
+
if bias == "none":
|
127 |
+
to_return = {k: t for k, t in named_params if "lora_" in k}
|
128 |
+
elif bias == "all":
|
129 |
+
to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k}
|
130 |
+
elif bias == "lora_only":
|
131 |
+
to_return = {}
|
132 |
+
maybe_lora_bias = {}
|
133 |
+
lora_bias_names = set()
|
134 |
+
for k, t in named_params:
|
135 |
+
if "lora_" in k:
|
136 |
+
to_return[k] = t
|
137 |
+
bias_name = k.split("lora_")[0] + "bias"
|
138 |
+
lora_bias_names.add(bias_name)
|
139 |
+
elif "bias" in k:
|
140 |
+
maybe_lora_bias[k] = t
|
141 |
+
for k, t in maybe_lora_bias:
|
142 |
+
if bias_name in lora_bias_names:
|
143 |
+
to_return[bias_name] = t
|
144 |
+
else:
|
145 |
+
raise NotImplementedError
|
146 |
+
to_return = {k: maybe_zero_3(v, name=k) for k, v in to_return.items()}
|
147 |
+
return to_return
|
148 |
+
|
149 |
+
|
150 |
+
def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True):
|
151 |
+
to_return = {k: t for k, t in named_params if "lora_" not in k}
|
152 |
+
if require_grad_only:
|
153 |
+
to_return = {k: t for k, t in to_return.items() if t.requires_grad}
|
154 |
+
to_return = {
|
155 |
+
k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()
|
156 |
+
}
|
157 |
+
return to_return
|
158 |
+
|
159 |
+
|
160 |
+
def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match):
|
161 |
+
to_return = {
|
162 |
+
k: t
|
163 |
+
for k, t in named_params
|
164 |
+
if any(key_match in k for key_match in keys_to_match)
|
165 |
+
}
|
166 |
+
to_return = {
|
167 |
+
k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()
|
168 |
+
}
|
169 |
+
return to_return
|
170 |
+
|
171 |
+
|
172 |
+
def find_all_linear_names(model):
|
173 |
+
cls = torch.nn.Linear
|
174 |
+
lora_module_names = set()
|
175 |
+
for name, module in model.named_modules():
|
176 |
+
if isinstance(module, cls):
|
177 |
+
names = name.split(".")
|
178 |
+
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
|
179 |
+
|
180 |
+
if "lm_head" in lora_module_names: # needed for 16-bit
|
181 |
+
lora_module_names.remove("lm_head")
|
182 |
+
return list(lora_module_names)
|
183 |
+
|
184 |
+
|
185 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
|
186 |
+
"""Collects the state dict and dump to disk."""
|
187 |
+
|
188 |
+
if getattr(trainer.args, "tune_mm_mlp_adapter", False):
|
189 |
+
# Only save Adapter
|
190 |
+
keys_to_match = ["mm_projector"]
|
191 |
+
if getattr(trainer.args, "use_im_start_end", False):
|
192 |
+
keys_to_match.extend(["embed_tokens", "embed_in"])
|
193 |
+
|
194 |
+
weight_to_save = get_mm_adapter_state_maybe_zero_3(
|
195 |
+
trainer.model.named_parameters(), keys_to_match
|
196 |
+
)
|
197 |
+
trainer.model.config.save_pretrained(output_dir)
|
198 |
+
|
199 |
+
current_folder = output_dir.split("/")[-1]
|
200 |
+
parent_folder = os.path.dirname(output_dir)
|
201 |
+
if trainer.args.local_rank == 0 or trainer.args.local_rank == -1:
|
202 |
+
if current_folder.startswith("checkpoint-"):
|
203 |
+
mm_projector_folder = os.path.join(parent_folder, "mm_projector")
|
204 |
+
os.makedirs(mm_projector_folder, exist_ok=True)
|
205 |
+
torch.save(
|
206 |
+
weight_to_save,
|
207 |
+
os.path.join(mm_projector_folder, f"{current_folder}.bin"),
|
208 |
+
)
|
209 |
+
else:
|
210 |
+
torch.save(
|
211 |
+
weight_to_save, os.path.join(output_dir, f"mm_projector.bin")
|
212 |
+
)
|
213 |
+
return
|
214 |
+
|
215 |
+
if trainer.deepspeed:
|
216 |
+
torch.cuda.synchronize()
|
217 |
+
trainer.save_model(output_dir)
|
218 |
+
return
|
219 |
+
|
220 |
+
state_dict = trainer.model.state_dict()
|
221 |
+
if trainer.args.should_save:
|
222 |
+
cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
|
223 |
+
del state_dict
|
224 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
225 |
+
|
226 |
+
|
227 |
+
def smart_tokenizer_and_embedding_resize(
|
228 |
+
special_tokens_dict: Dict,
|
229 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
230 |
+
model: transformers.PreTrainedModel,
|
231 |
+
):
|
232 |
+
"""Resize tokenizer and embedding.
|
233 |
+
|
234 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
235 |
+
"""
|
236 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
237 |
+
model.resize_token_embeddings(len(tokenizer))
|
238 |
+
|
239 |
+
if num_new_tokens > 0:
|
240 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
241 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
242 |
+
|
243 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
244 |
+
dim=0, keepdim=True
|
245 |
+
)
|
246 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
247 |
+
dim=0, keepdim=True
|
248 |
+
)
|
249 |
+
|
250 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
251 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
252 |
+
|
253 |
+
|
254 |
+
def _tokenize_fn(
|
255 |
+
strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer
|
256 |
+
) -> Dict:
|
257 |
+
"""Tokenize a list of strings."""
|
258 |
+
tokenized_list = [
|
259 |
+
tokenizer(
|
260 |
+
text,
|
261 |
+
return_tensors="pt",
|
262 |
+
padding="longest",
|
263 |
+
max_length=tokenizer.model_max_length,
|
264 |
+
truncation=True,
|
265 |
+
)
|
266 |
+
for text in strings
|
267 |
+
]
|
268 |
+
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
|
269 |
+
input_ids_lens = labels_lens = [
|
270 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item()
|
271 |
+
for tokenized in tokenized_list
|
272 |
+
]
|
273 |
+
return dict(
|
274 |
+
input_ids=input_ids,
|
275 |
+
labels=labels,
|
276 |
+
input_ids_lens=input_ids_lens,
|
277 |
+
labels_lens=labels_lens,
|
278 |
+
)
|
279 |
+
|
280 |
+
|
281 |
+
def _mask_targets(target, tokenized_lens, speakers):
|
282 |
+
# cur_idx = 0
|
283 |
+
cur_idx = tokenized_lens[0]
|
284 |
+
tokenized_lens = tokenized_lens[1:]
|
285 |
+
target[:cur_idx] = IGNORE_INDEX
|
286 |
+
for tokenized_len, speaker in zip(tokenized_lens, speakers):
|
287 |
+
if speaker == "human":
|
288 |
+
target[cur_idx + 2 : cur_idx + tokenized_len] = IGNORE_INDEX
|
289 |
+
cur_idx += tokenized_len
|
290 |
+
|
291 |
+
|
292 |
+
def _add_speaker_and_signal(header, source, get_conversation=True):
|
293 |
+
"""Add speaker and start/end signal on each round."""
|
294 |
+
BEGIN_SIGNAL = "### "
|
295 |
+
END_SIGNAL = "\n"
|
296 |
+
conversation = header
|
297 |
+
for sentence in source:
|
298 |
+
from_str = sentence["from"]
|
299 |
+
if from_str.lower() == "human":
|
300 |
+
from_str = conversation_lib.default_conversation.roles[0]
|
301 |
+
elif from_str.lower() == "gpt":
|
302 |
+
from_str = conversation_lib.default_conversation.roles[1]
|
303 |
+
else:
|
304 |
+
from_str = "unknown"
|
305 |
+
sentence["value"] = (
|
306 |
+
BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL
|
307 |
+
)
|
308 |
+
if get_conversation:
|
309 |
+
conversation += sentence["value"]
|
310 |
+
conversation += BEGIN_SIGNAL
|
311 |
+
return conversation
|
312 |
+
|
313 |
+
|
314 |
+
def preprocess_multimodal(sources: Sequence[str], data_args: DataArguments) -> Dict:
|
315 |
+
is_multimodal = data_args.is_multimodal
|
316 |
+
if not is_multimodal:
|
317 |
+
return sources
|
318 |
+
|
319 |
+
for source in sources:
|
320 |
+
for sentence in source:
|
321 |
+
if DEFAULT_IMAGE_TOKEN in sentence["value"]:
|
322 |
+
sentence["value"] = (
|
323 |
+
sentence["value"].replace(DEFAULT_IMAGE_TOKEN, "").strip()
|
324 |
+
)
|
325 |
+
sentence["value"] = DEFAULT_IMAGE_TOKEN + "\n" + sentence["value"]
|
326 |
+
sentence["value"] = sentence["value"].strip()
|
327 |
+
if "mmtag" in conversation_lib.default_conversation.version:
|
328 |
+
sentence["value"] = sentence["value"].replace(
|
329 |
+
DEFAULT_IMAGE_TOKEN,
|
330 |
+
"<Image>" + DEFAULT_IMAGE_TOKEN + "</Image>",
|
331 |
+
)
|
332 |
+
replace_token = DEFAULT_IMAGE_TOKEN
|
333 |
+
if data_args.mm_use_im_start_end:
|
334 |
+
replace_token = (
|
335 |
+
DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
|
336 |
+
)
|
337 |
+
sentence["value"] = sentence["value"].replace(
|
338 |
+
DEFAULT_IMAGE_TOKEN, replace_token
|
339 |
+
)
|
340 |
+
|
341 |
+
return sources
|
342 |
+
|
343 |
+
|
344 |
+
def preprocess_llama_2(
|
345 |
+
sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False
|
346 |
+
) -> Dict:
|
347 |
+
conv = conversation_lib.default_conversation.copy()
|
348 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
349 |
+
|
350 |
+
# Apply prompt templates
|
351 |
+
conversations = []
|
352 |
+
for i, source in enumerate(sources):
|
353 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
354 |
+
# Skip the first one if it is not from human
|
355 |
+
source = source[1:]
|
356 |
+
|
357 |
+
conv.messages = []
|
358 |
+
for j, sentence in enumerate(source):
|
359 |
+
role = roles[sentence["from"]]
|
360 |
+
assert role == conv.roles[j % 2], f"{i}"
|
361 |
+
conv.append_message(role, sentence["value"])
|
362 |
+
conversations.append(conv.get_prompt())
|
363 |
+
|
364 |
+
# Tokenize conversations
|
365 |
+
|
366 |
+
if has_image:
|
367 |
+
input_ids = torch.stack(
|
368 |
+
[
|
369 |
+
tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
370 |
+
for prompt in conversations
|
371 |
+
],
|
372 |
+
dim=0,
|
373 |
+
)
|
374 |
+
else:
|
375 |
+
input_ids = tokenizer(
|
376 |
+
conversations,
|
377 |
+
return_tensors="pt",
|
378 |
+
padding="longest",
|
379 |
+
max_length=tokenizer.model_max_length,
|
380 |
+
truncation=True,
|
381 |
+
).input_ids
|
382 |
+
|
383 |
+
targets = input_ids.clone()
|
384 |
+
|
385 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2
|
386 |
+
|
387 |
+
# Mask targets
|
388 |
+
sep = "[/INST] "
|
389 |
+
for conversation, target in zip(conversations, targets):
|
390 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
391 |
+
|
392 |
+
rounds = conversation.split(conv.sep2)
|
393 |
+
cur_len = 1
|
394 |
+
target[:cur_len] = IGNORE_INDEX
|
395 |
+
for i, rou in enumerate(rounds):
|
396 |
+
if rou == "":
|
397 |
+
break
|
398 |
+
|
399 |
+
parts = rou.split(sep)
|
400 |
+
if len(parts) != 2:
|
401 |
+
break
|
402 |
+
parts[0] += sep
|
403 |
+
|
404 |
+
if has_image:
|
405 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
406 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
|
407 |
+
else:
|
408 |
+
round_len = len(tokenizer(rou).input_ids)
|
409 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
410 |
+
|
411 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
412 |
+
|
413 |
+
cur_len += round_len
|
414 |
+
target[cur_len:] = IGNORE_INDEX
|
415 |
+
|
416 |
+
if cur_len < tokenizer.model_max_length:
|
417 |
+
if cur_len != total_len:
|
418 |
+
target[:] = IGNORE_INDEX
|
419 |
+
print(
|
420 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
421 |
+
f" (ignored)"
|
422 |
+
)
|
423 |
+
|
424 |
+
return dict(
|
425 |
+
input_ids=input_ids,
|
426 |
+
labels=targets,
|
427 |
+
)
|
428 |
+
|
429 |
+
|
430 |
+
def preprocess_v1(
|
431 |
+
sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False
|
432 |
+
) -> Dict:
|
433 |
+
conv = conversation_lib.default_conversation.copy()
|
434 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
435 |
+
|
436 |
+
# Apply prompt templates
|
437 |
+
conversations = []
|
438 |
+
for i, source in enumerate(sources):
|
439 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
440 |
+
# Skip the first one if it is not from human
|
441 |
+
source = source[1:]
|
442 |
+
|
443 |
+
conv.messages = []
|
444 |
+
for j, sentence in enumerate(source):
|
445 |
+
role = roles[sentence["from"]]
|
446 |
+
assert role == conv.roles[j % 2], f"{i}"
|
447 |
+
conv.append_message(role, sentence["value"])
|
448 |
+
conversations.append(conv.get_prompt())
|
449 |
+
|
450 |
+
# Tokenize conversations
|
451 |
+
|
452 |
+
if has_image:
|
453 |
+
input_ids = torch.stack(
|
454 |
+
[
|
455 |
+
tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
456 |
+
for prompt in conversations
|
457 |
+
],
|
458 |
+
dim=0,
|
459 |
+
)
|
460 |
+
else:
|
461 |
+
input_ids = tokenizer(
|
462 |
+
conversations,
|
463 |
+
return_tensors="pt",
|
464 |
+
padding="longest",
|
465 |
+
max_length=tokenizer.model_max_length,
|
466 |
+
truncation=True,
|
467 |
+
).input_ids
|
468 |
+
|
469 |
+
targets = input_ids.clone()
|
470 |
+
|
471 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.TWO
|
472 |
+
|
473 |
+
# Mask targets
|
474 |
+
sep = conv.sep + conv.roles[1] + ": "
|
475 |
+
for conversation, target in zip(conversations, targets):
|
476 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
477 |
+
|
478 |
+
rounds = conversation.split(conv.sep2)
|
479 |
+
cur_len = 1
|
480 |
+
target[:cur_len] = IGNORE_INDEX
|
481 |
+
for i, rou in enumerate(rounds):
|
482 |
+
if rou == "":
|
483 |
+
break
|
484 |
+
|
485 |
+
parts = rou.split(sep)
|
486 |
+
if len(parts) != 2:
|
487 |
+
break
|
488 |
+
parts[0] += sep
|
489 |
+
|
490 |
+
if has_image:
|
491 |
+
round_len = len(tokenizer_image_token(rou, tokenizer))
|
492 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2
|
493 |
+
else:
|
494 |
+
round_len = len(tokenizer(rou).input_ids)
|
495 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
496 |
+
|
497 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
498 |
+
|
499 |
+
cur_len += round_len
|
500 |
+
target[cur_len:] = IGNORE_INDEX
|
501 |
+
|
502 |
+
if cur_len < tokenizer.model_max_length:
|
503 |
+
if cur_len != total_len:
|
504 |
+
target[:] = IGNORE_INDEX
|
505 |
+
print(
|
506 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
507 |
+
f" (ignored)"
|
508 |
+
)
|
509 |
+
|
510 |
+
return dict(
|
511 |
+
input_ids=input_ids,
|
512 |
+
labels=targets,
|
513 |
+
)
|
514 |
+
|
515 |
+
|
516 |
+
def preprocess_mpt(
|
517 |
+
sources,
|
518 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
519 |
+
) -> Dict:
|
520 |
+
conv = conversation_lib.default_conversation.copy()
|
521 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
522 |
+
|
523 |
+
# Apply prompt templates
|
524 |
+
conversations = []
|
525 |
+
for i, source in enumerate(sources):
|
526 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
527 |
+
# Skip the first one if it is not from human
|
528 |
+
source = source[1:]
|
529 |
+
|
530 |
+
conv.messages = []
|
531 |
+
for j, sentence in enumerate(source):
|
532 |
+
role = roles[sentence["from"]]
|
533 |
+
assert role == conv.roles[j % 2], f"{i}"
|
534 |
+
conv.append_message(role, sentence["value"])
|
535 |
+
conversations.append(conv.get_prompt())
|
536 |
+
|
537 |
+
# Tokenize conversations
|
538 |
+
input_ids = torch.stack(
|
539 |
+
[
|
540 |
+
tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
541 |
+
for prompt in conversations
|
542 |
+
],
|
543 |
+
dim=0,
|
544 |
+
)
|
545 |
+
targets = input_ids.clone()
|
546 |
+
assert conv.sep_style == conversation_lib.SeparatorStyle.MPT
|
547 |
+
|
548 |
+
# Mask targets
|
549 |
+
sep = conv.sep + conv.roles[1]
|
550 |
+
for conversation, target in zip(conversations, targets):
|
551 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
552 |
+
|
553 |
+
rounds = conversation.split(conv.sep)
|
554 |
+
re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt
|
555 |
+
for conv_idx in range(3, len(rounds), 2):
|
556 |
+
re_rounds.append(
|
557 |
+
conv.sep.join(rounds[conv_idx : conv_idx + 2])
|
558 |
+
) # user + gpt
|
559 |
+
cur_len = 0
|
560 |
+
target[:cur_len] = IGNORE_INDEX
|
561 |
+
for i, rou in enumerate(re_rounds):
|
562 |
+
if rou == "":
|
563 |
+
break
|
564 |
+
|
565 |
+
parts = rou.split(sep)
|
566 |
+
if len(parts) != 2:
|
567 |
+
break
|
568 |
+
parts[0] += sep
|
569 |
+
round_len = len(tokenizer_image_token(rou, tokenizer)) + len(
|
570 |
+
tokenizer_image_token(conv.sep, tokenizer)
|
571 |
+
)
|
572 |
+
instruction_len = len(tokenizer_image_token(parts[0], tokenizer))
|
573 |
+
target[cur_len : cur_len + instruction_len] = IGNORE_INDEX
|
574 |
+
|
575 |
+
cur_len += round_len
|
576 |
+
target[cur_len:] = IGNORE_INDEX
|
577 |
+
|
578 |
+
if cur_len < tokenizer.model_max_length:
|
579 |
+
if cur_len != total_len:
|
580 |
+
target[:] = IGNORE_INDEX
|
581 |
+
print(
|
582 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
583 |
+
f" (ignored)"
|
584 |
+
)
|
585 |
+
|
586 |
+
return dict(
|
587 |
+
input_ids=input_ids,
|
588 |
+
labels=targets,
|
589 |
+
)
|
590 |
+
|
591 |
+
|
592 |
+
def preprocess_plain(
|
593 |
+
sources: Sequence[str],
|
594 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
595 |
+
) -> Dict:
|
596 |
+
# add end signal and concatenate together
|
597 |
+
conversations = []
|
598 |
+
for source in sources:
|
599 |
+
assert len(source) == 2
|
600 |
+
assert DEFAULT_IMAGE_TOKEN in source[0]["value"]
|
601 |
+
source[0]["value"] = DEFAULT_IMAGE_TOKEN
|
602 |
+
conversation = (
|
603 |
+
source[0]["value"]
|
604 |
+
+ source[1]["value"]
|
605 |
+
+ conversation_lib.default_conversation.sep
|
606 |
+
)
|
607 |
+
conversations.append(conversation)
|
608 |
+
# tokenize conversations
|
609 |
+
input_ids = [
|
610 |
+
tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
611 |
+
for prompt in conversations
|
612 |
+
]
|
613 |
+
targets = copy.deepcopy(input_ids)
|
614 |
+
for target, source in zip(targets, sources):
|
615 |
+
tokenized_len = len(tokenizer_image_token(source[0]["value"], tokenizer))
|
616 |
+
target[:tokenized_len] = IGNORE_INDEX
|
617 |
+
|
618 |
+
return dict(input_ids=input_ids, labels=targets)
|
619 |
+
|
620 |
+
|
621 |
+
def preprocess(
|
622 |
+
sources: Sequence[str],
|
623 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
624 |
+
has_image: bool = False,
|
625 |
+
) -> Dict:
|
626 |
+
"""
|
627 |
+
Given a list of sources, each is a conversation list. This transform:
|
628 |
+
1. Add signal '### ' at the beginning each sentence, with end signal '\n';
|
629 |
+
2. Concatenate conversations together;
|
630 |
+
3. Tokenize the concatenated conversation;
|
631 |
+
4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX.
|
632 |
+
"""
|
633 |
+
if (
|
634 |
+
conversation_lib.default_conversation.sep_style
|
635 |
+
== conversation_lib.SeparatorStyle.PLAIN
|
636 |
+
):
|
637 |
+
return preprocess_plain(sources, tokenizer)
|
638 |
+
if (
|
639 |
+
conversation_lib.default_conversation.sep_style
|
640 |
+
== conversation_lib.SeparatorStyle.LLAMA_2
|
641 |
+
):
|
642 |
+
return preprocess_llama_2(sources, tokenizer, has_image=has_image)
|
643 |
+
if conversation_lib.default_conversation.version.startswith("v1"):
|
644 |
+
return preprocess_v1(sources, tokenizer, has_image=has_image)
|
645 |
+
if conversation_lib.default_conversation.version == "mpt":
|
646 |
+
return preprocess_mpt(sources, tokenizer)
|
647 |
+
# add end signal and concatenate together
|
648 |
+
conversations = []
|
649 |
+
for source in sources:
|
650 |
+
header = f"{conversation_lib.default_conversation.system}\n\n"
|
651 |
+
conversation = _add_speaker_and_signal(header, source)
|
652 |
+
conversations.append(conversation)
|
653 |
+
|
654 |
+
# tokenize conversations
|
655 |
+
def get_tokenize_len(prompts):
|
656 |
+
return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts]
|
657 |
+
|
658 |
+
if has_image:
|
659 |
+
input_ids = [
|
660 |
+
tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
661 |
+
for prompt in conversations
|
662 |
+
]
|
663 |
+
else:
|
664 |
+
conversations_tokenized = _tokenize_fn(conversations, tokenizer)
|
665 |
+
input_ids = conversations_tokenized["input_ids"]
|
666 |
+
|
667 |
+
targets = copy.deepcopy(input_ids)
|
668 |
+
for target, source in zip(targets, sources):
|
669 |
+
if has_image:
|
670 |
+
tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source])
|
671 |
+
else:
|
672 |
+
tokenized_lens = _tokenize_fn(
|
673 |
+
[header] + [s["value"] for s in source], tokenizer
|
674 |
+
)["input_ids_lens"]
|
675 |
+
speakers = [sentence["from"] for sentence in source]
|
676 |
+
_mask_targets(target, tokenized_lens, speakers)
|
677 |
+
|
678 |
+
return dict(input_ids=input_ids, labels=targets)
|
679 |
+
|
680 |
+
|
681 |
+
class LazySupervisedDataset(Dataset):
|
682 |
+
"""Dataset for supervised fine-tuning."""
|
683 |
+
|
684 |
+
def __init__(
|
685 |
+
self,
|
686 |
+
data_path: str,
|
687 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
688 |
+
data_args: DataArguments,
|
689 |
+
):
|
690 |
+
super(LazySupervisedDataset, self).__init__()
|
691 |
+
list_data_dict = json.load(open(data_path, "r"))
|
692 |
+
|
693 |
+
rank0_print("Formatting inputs...Skip in lazy mode")
|
694 |
+
self.tokenizer = tokenizer
|
695 |
+
self.list_data_dict = list_data_dict
|
696 |
+
self.data_args = data_args
|
697 |
+
|
698 |
+
def __len__(self):
|
699 |
+
return len(self.list_data_dict)
|
700 |
+
|
701 |
+
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
|
702 |
+
sources = self.list_data_dict[i]
|
703 |
+
if isinstance(i, int):
|
704 |
+
sources = [sources]
|
705 |
+
assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME
|
706 |
+
if "image" in sources[0]:
|
707 |
+
image_file = self.list_data_dict[i]["image"]
|
708 |
+
image_folder = self.data_args.image_folder
|
709 |
+
processor = self.data_args.image_processor
|
710 |
+
image = Image.open(os.path.join(image_folder, image_file)).convert("RGB")
|
711 |
+
if self.data_args.image_aspect_ratio == "pad":
|
712 |
+
|
713 |
+
def expand2square(pil_img, background_color):
|
714 |
+
width, height = pil_img.size
|
715 |
+
if width == height:
|
716 |
+
return pil_img
|
717 |
+
elif width > height:
|
718 |
+
result = Image.new(
|
719 |
+
pil_img.mode, (width, width), background_color
|
720 |
+
)
|
721 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
722 |
+
return result
|
723 |
+
else:
|
724 |
+
result = Image.new(
|
725 |
+
pil_img.mode, (height, height), background_color
|
726 |
+
)
|
727 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
728 |
+
return result
|
729 |
+
|
730 |
+
image = expand2square(
|
731 |
+
image, tuple(int(x * 255) for x in processor.image_mean)
|
732 |
+
)
|
733 |
+
image = processor.preprocess(image, return_tensors="pt")[
|
734 |
+
"pixel_values"
|
735 |
+
][0]
|
736 |
+
else:
|
737 |
+
image = processor.preprocess(image, return_tensors="pt")[
|
738 |
+
"pixel_values"
|
739 |
+
][0]
|
740 |
+
sources = preprocess_multimodal(
|
741 |
+
copy.deepcopy([e["conversations"] for e in sources]), self.data_args
|
742 |
+
)
|
743 |
+
else:
|
744 |
+
sources = copy.deepcopy([e["conversations"] for e in sources])
|
745 |
+
data_dict = preprocess(
|
746 |
+
sources, self.tokenizer, has_image=("image" in self.list_data_dict[i])
|
747 |
+
)
|
748 |
+
if isinstance(i, int):
|
749 |
+
data_dict = dict(
|
750 |
+
input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0]
|
751 |
+
)
|
752 |
+
|
753 |
+
# image exist in the data
|
754 |
+
if "image" in self.list_data_dict[i]:
|
755 |
+
data_dict["image"] = image
|
756 |
+
elif self.data_args.is_multimodal:
|
757 |
+
# image does not exist in the data, but the model is multimodal
|
758 |
+
crop_size = self.data_args.image_processor.crop_size
|
759 |
+
data_dict["image"] = torch.zeros(3, crop_size["height"], crop_size["width"])
|
760 |
+
return data_dict
|
761 |
+
|
762 |
+
|
763 |
+
@dataclass
|
764 |
+
class DataCollatorForSupervisedDataset(object):
|
765 |
+
"""Collate examples for supervised fine-tuning."""
|
766 |
+
|
767 |
+
tokenizer: transformers.PreTrainedTokenizer
|
768 |
+
|
769 |
+
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
770 |
+
input_ids, labels = tuple(
|
771 |
+
[instance[key] for instance in instances] for key in ("input_ids", "labels")
|
772 |
+
)
|
773 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
774 |
+
input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id
|
775 |
+
)
|
776 |
+
labels = torch.nn.utils.rnn.pad_sequence(
|
777 |
+
labels, batch_first=True, padding_value=IGNORE_INDEX
|
778 |
+
)
|
779 |
+
input_ids = input_ids[:, : self.tokenizer.model_max_length]
|
780 |
+
labels = labels[:, : self.tokenizer.model_max_length]
|
781 |
+
batch = dict(
|
782 |
+
input_ids=input_ids,
|
783 |
+
labels=labels,
|
784 |
+
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
|
785 |
+
)
|
786 |
+
|
787 |
+
if "image" in instances[0]:
|
788 |
+
images = [instance["image"] for instance in instances]
|
789 |
+
if all(x is not None and x.shape == images[0].shape for x in images):
|
790 |
+
batch["images"] = torch.stack(images)
|
791 |
+
else:
|
792 |
+
batch["images"] = images
|
793 |
+
|
794 |
+
return batch
|
795 |
+
|
796 |
+
|
797 |
+
def make_supervised_data_module(
|
798 |
+
tokenizer: transformers.PreTrainedTokenizer, data_args
|
799 |
+
) -> Dict:
|
800 |
+
"""Make dataset and collator for supervised fine-tuning."""
|
801 |
+
train_dataset = LazySupervisedDataset(
|
802 |
+
tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args
|
803 |
+
)
|
804 |
+
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
805 |
+
return dict(
|
806 |
+
train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator
|
807 |
+
)
|
808 |
+
|
809 |
+
|
810 |
+
def train():
|
811 |
+
global local_rank
|
812 |
+
|
813 |
+
parser = transformers.HfArgumentParser(
|
814 |
+
(ModelArguments, DataArguments, TrainingArguments)
|
815 |
+
)
|
816 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
817 |
+
local_rank = training_args.local_rank
|
818 |
+
compute_dtype = (
|
819 |
+
torch.float16
|
820 |
+
if training_args.fp16
|
821 |
+
else (torch.bfloat16 if training_args.bf16 else torch.float32)
|
822 |
+
)
|
823 |
+
|
824 |
+
bnb_model_from_pretrained_args = {}
|
825 |
+
if training_args.bits in [4, 8]:
|
826 |
+
from transformers import BitsAndBytesConfig
|
827 |
+
|
828 |
+
bnb_model_from_pretrained_args.update(
|
829 |
+
dict(
|
830 |
+
device_map={"": training_args.device},
|
831 |
+
load_in_4bit=training_args.bits == 4,
|
832 |
+
load_in_8bit=training_args.bits == 8,
|
833 |
+
quantization_config=BitsAndBytesConfig(
|
834 |
+
load_in_4bit=training_args.bits == 4,
|
835 |
+
load_in_8bit=training_args.bits == 8,
|
836 |
+
llm_int8_threshold=6.0,
|
837 |
+
llm_int8_has_fp16_weight=False,
|
838 |
+
bnb_4bit_compute_dtype=compute_dtype,
|
839 |
+
bnb_4bit_use_double_quant=training_args.double_quant,
|
840 |
+
bnb_4bit_quant_type=training_args.quant_type, # {'fp4', 'nf4'}
|
841 |
+
),
|
842 |
+
)
|
843 |
+
)
|
844 |
+
|
845 |
+
if model_args.vision_tower is not None:
|
846 |
+
if "mpt" in model_args.model_name_or_path:
|
847 |
+
config = transformers.AutoConfig.from_pretrained(
|
848 |
+
model_args.model_name_or_path, trust_remote_code=True
|
849 |
+
)
|
850 |
+
config.attn_config["attn_impl"] = training_args.mpt_attn_impl
|
851 |
+
model = LlavaMPTForCausalLM.from_pretrained(
|
852 |
+
model_args.model_name_or_path,
|
853 |
+
config=config,
|
854 |
+
cache_dir=training_args.cache_dir,
|
855 |
+
**bnb_model_from_pretrained_args,
|
856 |
+
)
|
857 |
+
else:
|
858 |
+
model = LlavaLlamaForCausalLM.from_pretrained(
|
859 |
+
model_args.model_name_or_path,
|
860 |
+
cache_dir=training_args.cache_dir,
|
861 |
+
**bnb_model_from_pretrained_args,
|
862 |
+
)
|
863 |
+
else:
|
864 |
+
model = transformers.LlamaForCausalLM.from_pretrained(
|
865 |
+
model_args.model_name_or_path,
|
866 |
+
cache_dir=training_args.cache_dir,
|
867 |
+
**bnb_model_from_pretrained_args,
|
868 |
+
)
|
869 |
+
model.config.use_cache = False
|
870 |
+
|
871 |
+
if model_args.freeze_backbone:
|
872 |
+
model.model.requires_grad_(False)
|
873 |
+
|
874 |
+
if training_args.bits in [4, 8]:
|
875 |
+
from peft import prepare_model_for_kbit_training
|
876 |
+
|
877 |
+
model.config.torch_dtype = (
|
878 |
+
torch.float32
|
879 |
+
if training_args.fp16
|
880 |
+
else (torch.bfloat16 if training_args.bf16 else torch.float32)
|
881 |
+
)
|
882 |
+
model = prepare_model_for_kbit_training(
|
883 |
+
model, use_gradient_checkpointing=training_args.gradient_checkpointing
|
884 |
+
)
|
885 |
+
|
886 |
+
if training_args.gradient_checkpointing:
|
887 |
+
if hasattr(model, "enable_input_require_grads"):
|
888 |
+
model.enable_input_require_grads()
|
889 |
+
else:
|
890 |
+
|
891 |
+
def make_inputs_require_grad(module, input, output):
|
892 |
+
output.requires_grad_(True)
|
893 |
+
|
894 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
895 |
+
|
896 |
+
if training_args.lora_enable:
|
897 |
+
from peft import LoraConfig, get_peft_model
|
898 |
+
|
899 |
+
lora_config = LoraConfig(
|
900 |
+
r=training_args.lora_r,
|
901 |
+
lora_alpha=training_args.lora_alpha,
|
902 |
+
target_modules=find_all_linear_names(model),
|
903 |
+
lora_dropout=training_args.lora_dropout,
|
904 |
+
bias=training_args.lora_bias,
|
905 |
+
task_type="CAUSAL_LM",
|
906 |
+
)
|
907 |
+
if training_args.bits == 16:
|
908 |
+
if training_args.bf16:
|
909 |
+
model.to(torch.bfloat16)
|
910 |
+
if training_args.fp16:
|
911 |
+
model.to(torch.float16)
|
912 |
+
rank0_print("Adding LoRA adapters...")
|
913 |
+
model = get_peft_model(model, lora_config)
|
914 |
+
|
915 |
+
if "mpt" in model_args.model_name_or_path:
|
916 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
917 |
+
model_args.model_name_or_path,
|
918 |
+
cache_dir=training_args.cache_dir,
|
919 |
+
model_max_length=training_args.model_max_length,
|
920 |
+
padding_side="right",
|
921 |
+
)
|
922 |
+
else:
|
923 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
924 |
+
model_args.model_name_or_path,
|
925 |
+
cache_dir=training_args.cache_dir,
|
926 |
+
model_max_length=training_args.model_max_length,
|
927 |
+
padding_side="right",
|
928 |
+
use_fast=False,
|
929 |
+
)
|
930 |
+
|
931 |
+
if model_args.version == "v0":
|
932 |
+
if tokenizer.pad_token is None:
|
933 |
+
smart_tokenizer_and_embedding_resize(
|
934 |
+
special_tokens_dict=dict(pad_token="[PAD]"),
|
935 |
+
tokenizer=tokenizer,
|
936 |
+
model=model,
|
937 |
+
)
|
938 |
+
elif model_args.version == "v0.5":
|
939 |
+
tokenizer.pad_token = tokenizer.unk_token
|
940 |
+
else:
|
941 |
+
tokenizer.pad_token = tokenizer.unk_token
|
942 |
+
if model_args.version in conversation_lib.conv_templates:
|
943 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates[
|
944 |
+
model_args.version
|
945 |
+
]
|
946 |
+
else:
|
947 |
+
conversation_lib.default_conversation = conversation_lib.conv_templates[
|
948 |
+
"vicuna_v1"
|
949 |
+
]
|
950 |
+
|
951 |
+
if model_args.vision_tower is not None:
|
952 |
+
model.get_model().initialize_vision_modules(
|
953 |
+
model_args=model_args, fsdp=training_args.fsdp
|
954 |
+
)
|
955 |
+
|
956 |
+
vision_tower = model.get_vision_tower()
|
957 |
+
vision_tower.to(dtype=torch.float16, device=training_args.device)
|
958 |
+
|
959 |
+
data_args.image_processor = vision_tower.image_processor
|
960 |
+
data_args.is_multimodal = True
|
961 |
+
|
962 |
+
model.config.image_aspect_ratio = data_args.image_aspect_ratio
|
963 |
+
model.config.image_grid_pinpoints = data_args.image_grid_pinpoints
|
964 |
+
|
965 |
+
model.config.tune_mm_mlp_adapter = (
|
966 |
+
training_args.tune_mm_mlp_adapter
|
967 |
+
) = model_args.tune_mm_mlp_adapter
|
968 |
+
if model_args.tune_mm_mlp_adapter:
|
969 |
+
model.requires_grad_(False)
|
970 |
+
for p in model.get_model().mm_projector.parameters():
|
971 |
+
p.requires_grad = True
|
972 |
+
|
973 |
+
model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter
|
974 |
+
if training_args.freeze_mm_mlp_adapter:
|
975 |
+
for p in model.get_model().mm_projector.parameters():
|
976 |
+
p.requires_grad = False
|
977 |
+
|
978 |
+
if training_args.bits in [4, 8]:
|
979 |
+
model.get_model().mm_projector.to(
|
980 |
+
dtype=compute_dtype, device=training_args.device
|
981 |
+
)
|
982 |
+
|
983 |
+
model.config.mm_use_im_start_end = (
|
984 |
+
data_args.mm_use_im_start_end
|
985 |
+
) = model_args.mm_use_im_start_end
|
986 |
+
training_args.use_im_start_end = model_args.mm_use_im_start_end
|
987 |
+
model.config.mm_use_im_patch_token = model_args.mm_use_im_patch_token
|
988 |
+
model.initialize_vision_tokenizer(model_args, tokenizer=tokenizer)
|
989 |
+
|
990 |
+
if training_args.bits in [4, 8]:
|
991 |
+
from peft.tuners.lora import LoraLayer
|
992 |
+
|
993 |
+
for name, module in model.named_modules():
|
994 |
+
if isinstance(module, LoraLayer):
|
995 |
+
if training_args.bf16:
|
996 |
+
module = module.to(torch.bfloat16)
|
997 |
+
if "norm" in name:
|
998 |
+
module = module.to(torch.float32)
|
999 |
+
if "lm_head" in name or "embed_tokens" in name:
|
1000 |
+
if hasattr(module, "weight"):
|
1001 |
+
if training_args.bf16 and module.weight.dtype == torch.float32:
|
1002 |
+
module = module.to(torch.bfloat16)
|
1003 |
+
|
1004 |
+
data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
|
1005 |
+
trainer = LLaVATrainer(
|
1006 |
+
model=model, tokenizer=tokenizer, args=training_args, **data_module
|
1007 |
+
)
|
1008 |
+
|
1009 |
+
if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")):
|
1010 |
+
trainer.train(resume_from_checkpoint=True)
|
1011 |
+
else:
|
1012 |
+
trainer.train()
|
1013 |
+
trainer.save_state()
|
1014 |
+
|
1015 |
+
model.config.use_cache = True
|
1016 |
+
|
1017 |
+
if training_args.lora_enable:
|
1018 |
+
state_dict = get_peft_state_maybe_zero_3(
|
1019 |
+
model.named_parameters(), training_args.lora_bias
|
1020 |
+
)
|
1021 |
+
non_lora_state_dict = get_peft_state_non_lora_maybe_zero_3(
|
1022 |
+
model.named_parameters()
|
1023 |
+
)
|
1024 |
+
if training_args.local_rank == 0 or training_args.local_rank == -1:
|
1025 |
+
model.config.save_pretrained(training_args.output_dir)
|
1026 |
+
model.save_pretrained(training_args.output_dir, state_dict=state_dict)
|
1027 |
+
torch.save(
|
1028 |
+
non_lora_state_dict,
|
1029 |
+
os.path.join(training_args.output_dir, "non_lora_trainables.bin"),
|
1030 |
+
)
|
1031 |
+
else:
|
1032 |
+
safe_save_model_for_hf_trainer(
|
1033 |
+
trainer=trainer, output_dir=training_args.output_dir
|
1034 |
+
)
|
1035 |
+
|
1036 |
+
|
1037 |
+
if __name__ == "__main__":
|
1038 |
+
train()
|
model/llava/train/train_mem.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
|
2 |
+
# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
|
3 |
+
# Make it more memory efficient by monkey patching the LLaMA model with FlashAttn.
|
4 |
+
|
5 |
+
# Need to call this before importing transformers.
|
6 |
+
from llava.train.llama_flash_attn_monkey_patch import \
|
7 |
+
replace_llama_attn_with_flash_attn
|
8 |
+
|
9 |
+
replace_llama_attn_with_flash_attn()
|
10 |
+
|
11 |
+
from llava.train.train import train
|
12 |
+
|
13 |
+
if __name__ == "__main__":
|
14 |
+
train()
|
model/llava/utils.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import logging
|
3 |
+
import logging.handlers
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
|
7 |
+
import requests
|
8 |
+
from llava.constants import LOGDIR
|
9 |
+
|
10 |
+
server_error_msg = (
|
11 |
+
"**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
|
12 |
+
)
|
13 |
+
moderation_msg = (
|
14 |
+
"YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
|
15 |
+
)
|
16 |
+
|
17 |
+
handler = None
|
18 |
+
|
19 |
+
|
20 |
+
def build_logger(logger_name, logger_filename):
|
21 |
+
global handler
|
22 |
+
|
23 |
+
formatter = logging.Formatter(
|
24 |
+
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
|
25 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
26 |
+
)
|
27 |
+
|
28 |
+
# Set the format of root handlers
|
29 |
+
if not logging.getLogger().handlers:
|
30 |
+
logging.basicConfig(level=logging.INFO)
|
31 |
+
logging.getLogger().handlers[0].setFormatter(formatter)
|
32 |
+
|
33 |
+
# Redirect stdout and stderr to loggers
|
34 |
+
stdout_logger = logging.getLogger("stdout")
|
35 |
+
stdout_logger.setLevel(logging.INFO)
|
36 |
+
sl = StreamToLogger(stdout_logger, logging.INFO)
|
37 |
+
sys.stdout = sl
|
38 |
+
|
39 |
+
stderr_logger = logging.getLogger("stderr")
|
40 |
+
stderr_logger.setLevel(logging.ERROR)
|
41 |
+
sl = StreamToLogger(stderr_logger, logging.ERROR)
|
42 |
+
sys.stderr = sl
|
43 |
+
|
44 |
+
# Get logger
|
45 |
+
logger = logging.getLogger(logger_name)
|
46 |
+
logger.setLevel(logging.INFO)
|
47 |
+
|
48 |
+
# Add a file handler for all loggers
|
49 |
+
if handler is None:
|
50 |
+
os.makedirs(LOGDIR, exist_ok=True)
|
51 |
+
filename = os.path.join(LOGDIR, logger_filename)
|
52 |
+
handler = logging.handlers.TimedRotatingFileHandler(
|
53 |
+
filename, when="D", utc=True
|
54 |
+
)
|
55 |
+
handler.setFormatter(formatter)
|
56 |
+
|
57 |
+
for name, item in logging.root.manager.loggerDict.items():
|
58 |
+
if isinstance(item, logging.Logger):
|
59 |
+
item.addHandler(handler)
|
60 |
+
|
61 |
+
return logger
|
62 |
+
|
63 |
+
|
64 |
+
class StreamToLogger(object):
|
65 |
+
"""
|
66 |
+
Fake file-like stream object that redirects writes to a logger instance.
|
67 |
+
"""
|
68 |
+
|
69 |
+
def __init__(self, logger, log_level=logging.INFO):
|
70 |
+
self.terminal = sys.stdout
|
71 |
+
self.logger = logger
|
72 |
+
self.log_level = log_level
|
73 |
+
self.linebuf = ""
|
74 |
+
|
75 |
+
def __getattr__(self, attr):
|
76 |
+
return getattr(self.terminal, attr)
|
77 |
+
|
78 |
+
def write(self, buf):
|
79 |
+
temp_linebuf = self.linebuf + buf
|
80 |
+
self.linebuf = ""
|
81 |
+
for line in temp_linebuf.splitlines(True):
|
82 |
+
# From the io.TextIOWrapper docs:
|
83 |
+
# On output, if newline is None, any '\n' characters written
|
84 |
+
# are translated to the system default line separator.
|
85 |
+
# By default sys.stdout.write() expects '\n' newlines and then
|
86 |
+
# translates them so this is still cross platform.
|
87 |
+
if line[-1] == "\n":
|
88 |
+
self.logger.log(self.log_level, line.rstrip())
|
89 |
+
else:
|
90 |
+
self.linebuf += line
|
91 |
+
|
92 |
+
def flush(self):
|
93 |
+
if self.linebuf != "":
|
94 |
+
self.logger.log(self.log_level, self.linebuf.rstrip())
|
95 |
+
self.linebuf = ""
|
96 |
+
|
97 |
+
|
98 |
+
def disable_torch_init():
|
99 |
+
"""
|
100 |
+
Disable the redundant torch default initialization to accelerate model creation.
|
101 |
+
"""
|
102 |
+
import torch
|
103 |
+
|
104 |
+
setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
|
105 |
+
setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
|
106 |
+
|
107 |
+
|
108 |
+
def violates_moderation(text):
|
109 |
+
"""
|
110 |
+
Check whether the text violates OpenAI moderation API.
|
111 |
+
"""
|
112 |
+
url = "https://api.openai.com/v1/moderations"
|
113 |
+
headers = {
|
114 |
+
"Content-Type": "application/json",
|
115 |
+
"Authorization": "Bearer " + os.environ["OPENAI_API_KEY"],
|
116 |
+
}
|
117 |
+
text = text.replace("\n", "")
|
118 |
+
data = "{" + '"input": ' + f'"{text}"' + "}"
|
119 |
+
data = data.encode("utf-8")
|
120 |
+
try:
|
121 |
+
ret = requests.post(url, headers=headers, data=data, timeout=5)
|
122 |
+
flagged = ret.json()["results"][0]["flagged"]
|
123 |
+
except requests.exceptions.RequestException as e:
|
124 |
+
flagged = False
|
125 |
+
except KeyError as e:
|
126 |
+
flagged = False
|
127 |
+
|
128 |
+
return flagged
|
129 |
+
|
130 |
+
|
131 |
+
def pretty_print_semaphore(semaphore):
|
132 |
+
if semaphore is None:
|
133 |
+
return "None"
|
134 |
+
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
|
model/segment_anything/__init__.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from .automatic_mask_generator import SamAutomaticMaskGenerator
|
8 |
+
from .build_sam import (build_sam, build_sam_vit_b, build_sam_vit_h,
|
9 |
+
build_sam_vit_l, sam_model_registry)
|
10 |
+
from .predictor import SamPredictor
|
model/segment_anything/automatic_mask_generator.py
ADDED
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from typing import Any, Dict, List, Optional, Tuple
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
import torch
|
11 |
+
from torchvision.ops.boxes import batched_nms, box_area # type: ignore
|
12 |
+
|
13 |
+
from .modeling import Sam
|
14 |
+
from .predictor import SamPredictor
|
15 |
+
from .utils.amg import (MaskData, area_from_rle, batch_iterator,
|
16 |
+
batched_mask_to_box, box_xyxy_to_xywh,
|
17 |
+
build_all_layer_point_grids, calculate_stability_score,
|
18 |
+
coco_encode_rle, generate_crop_boxes,
|
19 |
+
is_box_near_crop_edge, mask_to_rle_pytorch,
|
20 |
+
remove_small_regions, rle_to_mask, uncrop_boxes_xyxy,
|
21 |
+
uncrop_masks, uncrop_points)
|
22 |
+
|
23 |
+
|
24 |
+
class SamAutomaticMaskGenerator:
|
25 |
+
def __init__(
|
26 |
+
self,
|
27 |
+
model: Sam,
|
28 |
+
points_per_side: Optional[int] = 32,
|
29 |
+
points_per_batch: int = 64,
|
30 |
+
pred_iou_thresh: float = 0.88,
|
31 |
+
stability_score_thresh: float = 0.95,
|
32 |
+
stability_score_offset: float = 1.0,
|
33 |
+
box_nms_thresh: float = 0.7,
|
34 |
+
crop_n_layers: int = 0,
|
35 |
+
crop_nms_thresh: float = 0.7,
|
36 |
+
crop_overlap_ratio: float = 512 / 1500,
|
37 |
+
crop_n_points_downscale_factor: int = 1,
|
38 |
+
point_grids: Optional[List[np.ndarray]] = None,
|
39 |
+
min_mask_region_area: int = 0,
|
40 |
+
output_mode: str = "binary_mask",
|
41 |
+
) -> None:
|
42 |
+
"""
|
43 |
+
Using a SAM model, generates masks for the entire image.
|
44 |
+
Generates a grid of point prompts over the image, then filters
|
45 |
+
low quality and duplicate masks. The default settings are chosen
|
46 |
+
for SAM with a ViT-H backbone.
|
47 |
+
|
48 |
+
Arguments:
|
49 |
+
model (Sam): The SAM model to use for mask prediction.
|
50 |
+
points_per_side (int or None): The number of points to be sampled
|
51 |
+
along one side of the image. The total number of points is
|
52 |
+
points_per_side**2. If None, 'point_grids' must provide explicit
|
53 |
+
point sampling.
|
54 |
+
points_per_batch (int): Sets the number of points run simultaneously
|
55 |
+
by the model. Higher numbers may be faster but use more GPU memory.
|
56 |
+
pred_iou_thresh (float): A filtering threshold in [0,1], using the
|
57 |
+
model's predicted mask quality.
|
58 |
+
stability_score_thresh (float): A filtering threshold in [0,1], using
|
59 |
+
the stability of the mask under changes to the cutoff used to binarize
|
60 |
+
the model's mask predictions.
|
61 |
+
stability_score_offset (float): The amount to shift the cutoff when
|
62 |
+
calculated the stability score.
|
63 |
+
box_nms_thresh (float): The box IoU cutoff used by non-maximal
|
64 |
+
suppression to filter duplicate masks.
|
65 |
+
crop_n_layers (int): If >0, mask prediction will be run again on
|
66 |
+
crops of the image. Sets the number of layers to run, where each
|
67 |
+
layer has 2**i_layer number of image crops.
|
68 |
+
crop_nms_thresh (float): The box IoU cutoff used by non-maximal
|
69 |
+
suppression to filter duplicate masks between different crops.
|
70 |
+
crop_overlap_ratio (float): Sets the degree to which crops overlap.
|
71 |
+
In the first crop layer, crops will overlap by this fraction of
|
72 |
+
the image length. Later layers with more crops scale down this overlap.
|
73 |
+
crop_n_points_downscale_factor (int): The number of points-per-side
|
74 |
+
sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
|
75 |
+
point_grids (list(np.ndarray) or None): A list over explicit grids
|
76 |
+
of points used for sampling, normalized to [0,1]. The nth grid in the
|
77 |
+
list is used in the nth crop layer. Exclusive with points_per_side.
|
78 |
+
min_mask_region_area (int): If >0, postprocessing will be applied
|
79 |
+
to remove disconnected regions and holes in masks with area smaller
|
80 |
+
than min_mask_region_area. Requires opencv.
|
81 |
+
output_mode (str): The form masks are returned in. Can be 'binary_mask',
|
82 |
+
'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
|
83 |
+
For large resolutions, 'binary_mask' may consume large amounts of
|
84 |
+
memory.
|
85 |
+
"""
|
86 |
+
|
87 |
+
assert (points_per_side is None) != (
|
88 |
+
point_grids is None
|
89 |
+
), "Exactly one of points_per_side or point_grid must be provided."
|
90 |
+
if points_per_side is not None:
|
91 |
+
self.point_grids = build_all_layer_point_grids(
|
92 |
+
points_per_side,
|
93 |
+
crop_n_layers,
|
94 |
+
crop_n_points_downscale_factor,
|
95 |
+
)
|
96 |
+
elif point_grids is not None:
|
97 |
+
self.point_grids = point_grids
|
98 |
+
else:
|
99 |
+
raise ValueError("Can't have both points_per_side and point_grid be None.")
|
100 |
+
|
101 |
+
assert output_mode in [
|
102 |
+
"binary_mask",
|
103 |
+
"uncompressed_rle",
|
104 |
+
"coco_rle",
|
105 |
+
], f"Unknown output_mode {output_mode}."
|
106 |
+
if output_mode == "coco_rle":
|
107 |
+
from pycocotools import \
|
108 |
+
mask as mask_utils # type: ignore # noqa: F401
|
109 |
+
|
110 |
+
if min_mask_region_area > 0:
|
111 |
+
import cv2 # type: ignore # noqa: F401
|
112 |
+
|
113 |
+
self.predictor = SamPredictor(model)
|
114 |
+
self.points_per_batch = points_per_batch
|
115 |
+
self.pred_iou_thresh = pred_iou_thresh
|
116 |
+
self.stability_score_thresh = stability_score_thresh
|
117 |
+
self.stability_score_offset = stability_score_offset
|
118 |
+
self.box_nms_thresh = box_nms_thresh
|
119 |
+
self.crop_n_layers = crop_n_layers
|
120 |
+
self.crop_nms_thresh = crop_nms_thresh
|
121 |
+
self.crop_overlap_ratio = crop_overlap_ratio
|
122 |
+
self.crop_n_points_downscale_factor = crop_n_points_downscale_factor
|
123 |
+
self.min_mask_region_area = min_mask_region_area
|
124 |
+
self.output_mode = output_mode
|
125 |
+
|
126 |
+
@torch.no_grad()
|
127 |
+
def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:
|
128 |
+
"""
|
129 |
+
Generates masks for the given image.
|
130 |
+
|
131 |
+
Arguments:
|
132 |
+
image (np.ndarray): The image to generate masks for, in HWC uint8 format.
|
133 |
+
|
134 |
+
Returns:
|
135 |
+
list(dict(str, any)): A list over records for masks. Each record is
|
136 |
+
a dict containing the following keys:
|
137 |
+
segmentation (dict(str, any) or np.ndarray): The mask. If
|
138 |
+
output_mode='binary_mask', is an array of shape HW. Otherwise,
|
139 |
+
is a dictionary containing the RLE.
|
140 |
+
bbox (list(float)): The box around the mask, in XYWH format.
|
141 |
+
area (int): The area in pixels of the mask.
|
142 |
+
predicted_iou (float): The model's own prediction of the mask's
|
143 |
+
quality. This is filtered by the pred_iou_thresh parameter.
|
144 |
+
point_coords (list(list(float))): The point coordinates input
|
145 |
+
to the model to generate this mask.
|
146 |
+
stability_score (float): A measure of the mask's quality. This
|
147 |
+
is filtered on using the stability_score_thresh parameter.
|
148 |
+
crop_box (list(float)): The crop of the image used to generate
|
149 |
+
the mask, given in XYWH format.
|
150 |
+
"""
|
151 |
+
|
152 |
+
# Generate masks
|
153 |
+
mask_data = self._generate_masks(image)
|
154 |
+
|
155 |
+
# Filter small disconnected regions and holes in masks
|
156 |
+
if self.min_mask_region_area > 0:
|
157 |
+
mask_data = self.postprocess_small_regions(
|
158 |
+
mask_data,
|
159 |
+
self.min_mask_region_area,
|
160 |
+
max(self.box_nms_thresh, self.crop_nms_thresh),
|
161 |
+
)
|
162 |
+
|
163 |
+
# Encode masks
|
164 |
+
if self.output_mode == "coco_rle":
|
165 |
+
mask_data["segmentations"] = [
|
166 |
+
coco_encode_rle(rle) for rle in mask_data["rles"]
|
167 |
+
]
|
168 |
+
elif self.output_mode == "binary_mask":
|
169 |
+
mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
|
170 |
+
else:
|
171 |
+
mask_data["segmentations"] = mask_data["rles"]
|
172 |
+
|
173 |
+
# Write mask records
|
174 |
+
curr_anns = []
|
175 |
+
for idx in range(len(mask_data["segmentations"])):
|
176 |
+
ann = {
|
177 |
+
"segmentation": mask_data["segmentations"][idx],
|
178 |
+
"area": area_from_rle(mask_data["rles"][idx]),
|
179 |
+
"bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
|
180 |
+
"predicted_iou": mask_data["iou_preds"][idx].item(),
|
181 |
+
"point_coords": [mask_data["points"][idx].tolist()],
|
182 |
+
"stability_score": mask_data["stability_score"][idx].item(),
|
183 |
+
"crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(),
|
184 |
+
}
|
185 |
+
curr_anns.append(ann)
|
186 |
+
|
187 |
+
return curr_anns
|
188 |
+
|
189 |
+
def _generate_masks(self, image: np.ndarray) -> MaskData:
|
190 |
+
orig_size = image.shape[:2]
|
191 |
+
crop_boxes, layer_idxs = generate_crop_boxes(
|
192 |
+
orig_size, self.crop_n_layers, self.crop_overlap_ratio
|
193 |
+
)
|
194 |
+
|
195 |
+
# Iterate over image crops
|
196 |
+
data = MaskData()
|
197 |
+
for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
|
198 |
+
crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)
|
199 |
+
data.cat(crop_data)
|
200 |
+
|
201 |
+
# Remove duplicate masks between crops
|
202 |
+
if len(crop_boxes) > 1:
|
203 |
+
# Prefer masks from smaller crops
|
204 |
+
scores = 1 / box_area(data["crop_boxes"])
|
205 |
+
scores = scores.to(data["boxes"].device)
|
206 |
+
keep_by_nms = batched_nms(
|
207 |
+
data["boxes"].float(),
|
208 |
+
scores,
|
209 |
+
torch.zeros_like(data["boxes"][:, 0]), # categories
|
210 |
+
iou_threshold=self.crop_nms_thresh,
|
211 |
+
)
|
212 |
+
data.filter(keep_by_nms)
|
213 |
+
|
214 |
+
data.to_numpy()
|
215 |
+
return data
|
216 |
+
|
217 |
+
def _process_crop(
|
218 |
+
self,
|
219 |
+
image: np.ndarray,
|
220 |
+
crop_box: List[int],
|
221 |
+
crop_layer_idx: int,
|
222 |
+
orig_size: Tuple[int, ...],
|
223 |
+
) -> MaskData:
|
224 |
+
# Crop the image and calculate embeddings
|
225 |
+
x0, y0, x1, y1 = crop_box
|
226 |
+
cropped_im = image[y0:y1, x0:x1, :]
|
227 |
+
cropped_im_size = cropped_im.shape[:2]
|
228 |
+
self.predictor.set_image(cropped_im)
|
229 |
+
|
230 |
+
# Get points for this crop
|
231 |
+
points_scale = np.array(cropped_im_size)[None, ::-1]
|
232 |
+
points_for_image = self.point_grids[crop_layer_idx] * points_scale
|
233 |
+
|
234 |
+
# Generate masks for this crop in batches
|
235 |
+
data = MaskData()
|
236 |
+
for (points,) in batch_iterator(self.points_per_batch, points_for_image):
|
237 |
+
batch_data = self._process_batch(
|
238 |
+
points, cropped_im_size, crop_box, orig_size
|
239 |
+
)
|
240 |
+
data.cat(batch_data)
|
241 |
+
del batch_data
|
242 |
+
self.predictor.reset_image()
|
243 |
+
|
244 |
+
# Remove duplicates within this crop.
|
245 |
+
keep_by_nms = batched_nms(
|
246 |
+
data["boxes"].float(),
|
247 |
+
data["iou_preds"],
|
248 |
+
torch.zeros_like(data["boxes"][:, 0]), # categories
|
249 |
+
iou_threshold=self.box_nms_thresh,
|
250 |
+
)
|
251 |
+
data.filter(keep_by_nms)
|
252 |
+
|
253 |
+
# Return to the original image frame
|
254 |
+
data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
|
255 |
+
data["points"] = uncrop_points(data["points"], crop_box)
|
256 |
+
data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))])
|
257 |
+
|
258 |
+
return data
|
259 |
+
|
260 |
+
def _process_batch(
|
261 |
+
self,
|
262 |
+
points: np.ndarray,
|
263 |
+
im_size: Tuple[int, ...],
|
264 |
+
crop_box: List[int],
|
265 |
+
orig_size: Tuple[int, ...],
|
266 |
+
) -> MaskData:
|
267 |
+
orig_h, orig_w = orig_size
|
268 |
+
|
269 |
+
# Run model on this batch
|
270 |
+
transformed_points = self.predictor.transform.apply_coords(points, im_size)
|
271 |
+
in_points = torch.as_tensor(transformed_points, device=self.predictor.device)
|
272 |
+
in_labels = torch.ones(
|
273 |
+
in_points.shape[0], dtype=torch.int, device=in_points.device
|
274 |
+
)
|
275 |
+
masks, iou_preds, _ = self.predictor.predict_torch(
|
276 |
+
in_points[:, None, :],
|
277 |
+
in_labels[:, None],
|
278 |
+
multimask_output=True,
|
279 |
+
return_logits=True,
|
280 |
+
)
|
281 |
+
|
282 |
+
# Serialize predictions and store in MaskData
|
283 |
+
data = MaskData(
|
284 |
+
masks=masks.flatten(0, 1),
|
285 |
+
iou_preds=iou_preds.flatten(0, 1),
|
286 |
+
points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),
|
287 |
+
)
|
288 |
+
del masks
|
289 |
+
|
290 |
+
# Filter by predicted IoU
|
291 |
+
if self.pred_iou_thresh > 0.0:
|
292 |
+
keep_mask = data["iou_preds"] > self.pred_iou_thresh
|
293 |
+
data.filter(keep_mask)
|
294 |
+
|
295 |
+
# Calculate stability score
|
296 |
+
data["stability_score"] = calculate_stability_score(
|
297 |
+
data["masks"],
|
298 |
+
self.predictor.model.mask_threshold,
|
299 |
+
self.stability_score_offset,
|
300 |
+
)
|
301 |
+
if self.stability_score_thresh > 0.0:
|
302 |
+
keep_mask = data["stability_score"] >= self.stability_score_thresh
|
303 |
+
data.filter(keep_mask)
|
304 |
+
|
305 |
+
# Threshold masks and calculate boxes
|
306 |
+
data["masks"] = data["masks"] > self.predictor.model.mask_threshold
|
307 |
+
data["boxes"] = batched_mask_to_box(data["masks"])
|
308 |
+
|
309 |
+
# Filter boxes that touch crop boundaries
|
310 |
+
keep_mask = ~is_box_near_crop_edge(
|
311 |
+
data["boxes"], crop_box, [0, 0, orig_w, orig_h]
|
312 |
+
)
|
313 |
+
if not torch.all(keep_mask):
|
314 |
+
data.filter(keep_mask)
|
315 |
+
|
316 |
+
# Compress to RLE
|
317 |
+
data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w)
|
318 |
+
data["rles"] = mask_to_rle_pytorch(data["masks"])
|
319 |
+
del data["masks"]
|
320 |
+
|
321 |
+
return data
|
322 |
+
|
323 |
+
@staticmethod
|
324 |
+
def postprocess_small_regions(
|
325 |
+
mask_data: MaskData, min_area: int, nms_thresh: float
|
326 |
+
) -> MaskData:
|
327 |
+
"""
|
328 |
+
Removes small disconnected regions and holes in masks, then reruns
|
329 |
+
box NMS to remove any new duplicates.
|
330 |
+
|
331 |
+
Edits mask_data in place.
|
332 |
+
|
333 |
+
Requires open-cv as a dependency.
|
334 |
+
"""
|
335 |
+
if len(mask_data["rles"]) == 0:
|
336 |
+
return mask_data
|
337 |
+
|
338 |
+
# Filter small disconnected regions and holes
|
339 |
+
new_masks = []
|
340 |
+
scores = []
|
341 |
+
for rle in mask_data["rles"]:
|
342 |
+
mask = rle_to_mask(rle)
|
343 |
+
|
344 |
+
mask, changed = remove_small_regions(mask, min_area, mode="holes")
|
345 |
+
unchanged = not changed
|
346 |
+
mask, changed = remove_small_regions(mask, min_area, mode="islands")
|
347 |
+
unchanged = unchanged and not changed
|
348 |
+
|
349 |
+
new_masks.append(torch.as_tensor(mask).unsqueeze(0))
|
350 |
+
# Give score=0 to changed masks and score=1 to unchanged masks
|
351 |
+
# so NMS will prefer ones that didn't need postprocessing
|
352 |
+
scores.append(float(unchanged))
|
353 |
+
|
354 |
+
# Recalculate boxes and remove any new duplicates
|
355 |
+
masks = torch.cat(new_masks, dim=0)
|
356 |
+
boxes = batched_mask_to_box(masks)
|
357 |
+
keep_by_nms = batched_nms(
|
358 |
+
boxes.float(),
|
359 |
+
torch.as_tensor(scores),
|
360 |
+
torch.zeros_like(boxes[:, 0]), # categories
|
361 |
+
iou_threshold=nms_thresh,
|
362 |
+
)
|
363 |
+
|
364 |
+
# Only recalculate RLEs for masks that have changed
|
365 |
+
for i_mask in keep_by_nms:
|
366 |
+
if scores[i_mask] == 0.0:
|
367 |
+
mask_torch = masks[i_mask].unsqueeze(0)
|
368 |
+
mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]
|
369 |
+
mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly
|
370 |
+
mask_data.filter(keep_by_nms)
|
371 |
+
|
372 |
+
return mask_data
|
model/segment_anything/build_sam.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from functools import partial
|
8 |
+
|
9 |
+
import torch
|
10 |
+
|
11 |
+
from .modeling import (ImageEncoderViT, MaskDecoder, PromptEncoder, Sam,
|
12 |
+
TwoWayTransformer)
|
13 |
+
|
14 |
+
|
15 |
+
def build_sam_vit_h(checkpoint=None):
|
16 |
+
return _build_sam(
|
17 |
+
encoder_embed_dim=1280,
|
18 |
+
encoder_depth=32,
|
19 |
+
encoder_num_heads=16,
|
20 |
+
encoder_global_attn_indexes=[7, 15, 23, 31],
|
21 |
+
checkpoint=checkpoint,
|
22 |
+
)
|
23 |
+
|
24 |
+
|
25 |
+
build_sam = build_sam_vit_h
|
26 |
+
|
27 |
+
|
28 |
+
def build_sam_vit_l(checkpoint=None):
|
29 |
+
return _build_sam(
|
30 |
+
encoder_embed_dim=1024,
|
31 |
+
encoder_depth=24,
|
32 |
+
encoder_num_heads=16,
|
33 |
+
encoder_global_attn_indexes=[5, 11, 17, 23],
|
34 |
+
checkpoint=checkpoint,
|
35 |
+
)
|
36 |
+
|
37 |
+
|
38 |
+
def build_sam_vit_b(checkpoint=None):
|
39 |
+
return _build_sam(
|
40 |
+
encoder_embed_dim=768,
|
41 |
+
encoder_depth=12,
|
42 |
+
encoder_num_heads=12,
|
43 |
+
encoder_global_attn_indexes=[2, 5, 8, 11],
|
44 |
+
checkpoint=checkpoint,
|
45 |
+
)
|
46 |
+
|
47 |
+
|
48 |
+
sam_model_registry = {
|
49 |
+
"default": build_sam_vit_h,
|
50 |
+
"vit_h": build_sam_vit_h,
|
51 |
+
"vit_l": build_sam_vit_l,
|
52 |
+
"vit_b": build_sam_vit_b,
|
53 |
+
}
|
54 |
+
|
55 |
+
|
56 |
+
def _build_sam(
|
57 |
+
encoder_embed_dim,
|
58 |
+
encoder_depth,
|
59 |
+
encoder_num_heads,
|
60 |
+
encoder_global_attn_indexes,
|
61 |
+
checkpoint=None,
|
62 |
+
):
|
63 |
+
prompt_embed_dim = 256
|
64 |
+
image_size = 1024
|
65 |
+
vit_patch_size = 16
|
66 |
+
image_embedding_size = image_size // vit_patch_size
|
67 |
+
sam = Sam(
|
68 |
+
image_encoder=ImageEncoderViT(
|
69 |
+
depth=encoder_depth,
|
70 |
+
embed_dim=encoder_embed_dim,
|
71 |
+
img_size=image_size,
|
72 |
+
mlp_ratio=4,
|
73 |
+
norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
|
74 |
+
num_heads=encoder_num_heads,
|
75 |
+
patch_size=vit_patch_size,
|
76 |
+
qkv_bias=True,
|
77 |
+
use_rel_pos=True,
|
78 |
+
global_attn_indexes=encoder_global_attn_indexes,
|
79 |
+
window_size=14,
|
80 |
+
out_chans=prompt_embed_dim,
|
81 |
+
),
|
82 |
+
prompt_encoder=PromptEncoder(
|
83 |
+
embed_dim=prompt_embed_dim,
|
84 |
+
image_embedding_size=(image_embedding_size, image_embedding_size),
|
85 |
+
input_image_size=(image_size, image_size),
|
86 |
+
mask_in_chans=16,
|
87 |
+
),
|
88 |
+
mask_decoder=MaskDecoder(
|
89 |
+
num_multimask_outputs=3,
|
90 |
+
transformer=TwoWayTransformer(
|
91 |
+
depth=2,
|
92 |
+
embedding_dim=prompt_embed_dim,
|
93 |
+
mlp_dim=2048,
|
94 |
+
num_heads=8,
|
95 |
+
),
|
96 |
+
transformer_dim=prompt_embed_dim,
|
97 |
+
iou_head_depth=3,
|
98 |
+
iou_head_hidden_dim=256,
|
99 |
+
),
|
100 |
+
pixel_mean=[123.675, 116.28, 103.53],
|
101 |
+
pixel_std=[58.395, 57.12, 57.375],
|
102 |
+
)
|
103 |
+
sam.eval()
|
104 |
+
if checkpoint is not None:
|
105 |
+
with open(checkpoint, "rb") as f:
|
106 |
+
state_dict = torch.load(f)
|
107 |
+
sam.load_state_dict(state_dict, strict=False)
|
108 |
+
return sam
|
model/segment_anything/modeling/__init__.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from .image_encoder import ImageEncoderViT
|
8 |
+
from .mask_decoder import MaskDecoder
|
9 |
+
from .prompt_encoder import PromptEncoder
|
10 |
+
from .sam import Sam
|
11 |
+
from .transformer import TwoWayTransformer
|
model/segment_anything/modeling/common.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from typing import Type
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
|
12 |
+
|
13 |
+
class MLPBlock(nn.Module):
|
14 |
+
def __init__(
|
15 |
+
self,
|
16 |
+
embedding_dim: int,
|
17 |
+
mlp_dim: int,
|
18 |
+
act: Type[nn.Module] = nn.GELU,
|
19 |
+
) -> None:
|
20 |
+
super().__init__()
|
21 |
+
self.lin1 = nn.Linear(embedding_dim, mlp_dim)
|
22 |
+
self.lin2 = nn.Linear(mlp_dim, embedding_dim)
|
23 |
+
self.act = act()
|
24 |
+
|
25 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
26 |
+
return self.lin2(self.act(self.lin1(x)))
|
27 |
+
|
28 |
+
|
29 |
+
# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
|
30 |
+
# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
|
31 |
+
class LayerNorm2d(nn.Module):
|
32 |
+
def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
|
33 |
+
super().__init__()
|
34 |
+
self.weight = nn.Parameter(torch.ones(num_channels))
|
35 |
+
self.bias = nn.Parameter(torch.zeros(num_channels))
|
36 |
+
self.eps = eps
|
37 |
+
|
38 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
39 |
+
u = x.mean(1, keepdim=True)
|
40 |
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
41 |
+
x = (x - u) / torch.sqrt(s + self.eps)
|
42 |
+
x = self.weight[:, None, None] * x + self.bias[:, None, None]
|
43 |
+
return x
|
model/segment_anything/modeling/image_encoder.py
ADDED
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from typing import Optional, Tuple, Type
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torch.nn.functional as F
|
12 |
+
|
13 |
+
from .common import LayerNorm2d, MLPBlock
|
14 |
+
|
15 |
+
|
16 |
+
# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
|
17 |
+
class ImageEncoderViT(nn.Module):
|
18 |
+
def __init__(
|
19 |
+
self,
|
20 |
+
img_size: int = 1024,
|
21 |
+
patch_size: int = 16,
|
22 |
+
in_chans: int = 3,
|
23 |
+
embed_dim: int = 768,
|
24 |
+
depth: int = 12,
|
25 |
+
num_heads: int = 12,
|
26 |
+
mlp_ratio: float = 4.0,
|
27 |
+
out_chans: int = 256,
|
28 |
+
qkv_bias: bool = True,
|
29 |
+
norm_layer: Type[nn.Module] = nn.LayerNorm,
|
30 |
+
act_layer: Type[nn.Module] = nn.GELU,
|
31 |
+
use_abs_pos: bool = True,
|
32 |
+
use_rel_pos: bool = False,
|
33 |
+
rel_pos_zero_init: bool = True,
|
34 |
+
window_size: int = 0,
|
35 |
+
global_attn_indexes: Tuple[int, ...] = (),
|
36 |
+
) -> None:
|
37 |
+
"""
|
38 |
+
Args:
|
39 |
+
img_size (int): Input image size.
|
40 |
+
patch_size (int): Patch size.
|
41 |
+
in_chans (int): Number of input image channels.
|
42 |
+
embed_dim (int): Patch embedding dimension.
|
43 |
+
depth (int): Depth of ViT.
|
44 |
+
num_heads (int): Number of attention heads in each ViT block.
|
45 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
46 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value.
|
47 |
+
norm_layer (nn.Module): Normalization layer.
|
48 |
+
act_layer (nn.Module): Activation layer.
|
49 |
+
use_abs_pos (bool): If True, use absolute positional embeddings.
|
50 |
+
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
|
51 |
+
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
|
52 |
+
window_size (int): Window size for window attention blocks.
|
53 |
+
global_attn_indexes (list): Indexes for blocks using global attention.
|
54 |
+
"""
|
55 |
+
super().__init__()
|
56 |
+
self.img_size = img_size
|
57 |
+
self.embed_dim = embed_dim
|
58 |
+
self.out_chans = out_chans
|
59 |
+
|
60 |
+
self.patch_embed = PatchEmbed(
|
61 |
+
kernel_size=(patch_size, patch_size),
|
62 |
+
stride=(patch_size, patch_size),
|
63 |
+
in_chans=in_chans,
|
64 |
+
embed_dim=embed_dim,
|
65 |
+
)
|
66 |
+
|
67 |
+
self.pos_embed: Optional[nn.Parameter] = None
|
68 |
+
if use_abs_pos:
|
69 |
+
# Initialize absolute positional embedding with pretrain image size.
|
70 |
+
self.pos_embed = nn.Parameter(
|
71 |
+
torch.zeros(
|
72 |
+
1, img_size // patch_size, img_size // patch_size, embed_dim
|
73 |
+
)
|
74 |
+
)
|
75 |
+
|
76 |
+
self.blocks = nn.ModuleList()
|
77 |
+
for i in range(depth):
|
78 |
+
block = Block(
|
79 |
+
dim=embed_dim,
|
80 |
+
num_heads=num_heads,
|
81 |
+
mlp_ratio=mlp_ratio,
|
82 |
+
qkv_bias=qkv_bias,
|
83 |
+
norm_layer=norm_layer,
|
84 |
+
act_layer=act_layer,
|
85 |
+
use_rel_pos=use_rel_pos,
|
86 |
+
rel_pos_zero_init=rel_pos_zero_init,
|
87 |
+
window_size=window_size if i not in global_attn_indexes else 0,
|
88 |
+
input_size=(img_size // patch_size, img_size // patch_size),
|
89 |
+
)
|
90 |
+
self.blocks.append(block)
|
91 |
+
|
92 |
+
self.neck = nn.Sequential(
|
93 |
+
nn.Conv2d(
|
94 |
+
embed_dim,
|
95 |
+
out_chans,
|
96 |
+
kernel_size=1,
|
97 |
+
bias=False,
|
98 |
+
),
|
99 |
+
LayerNorm2d(out_chans),
|
100 |
+
nn.Conv2d(
|
101 |
+
out_chans,
|
102 |
+
out_chans,
|
103 |
+
kernel_size=3,
|
104 |
+
padding=1,
|
105 |
+
bias=False,
|
106 |
+
),
|
107 |
+
LayerNorm2d(out_chans),
|
108 |
+
)
|
109 |
+
|
110 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
111 |
+
x = self.patch_embed(x)
|
112 |
+
if self.pos_embed is not None:
|
113 |
+
x = x + self.pos_embed
|
114 |
+
|
115 |
+
for blk in self.blocks:
|
116 |
+
x = blk(x)
|
117 |
+
|
118 |
+
dtype = x.dtype
|
119 |
+
if dtype == torch.float16: # prevent overflow
|
120 |
+
with torch.autocast(device_type="cuda", dtype=torch.float32):
|
121 |
+
x = self.neck(x.permute(0, 3, 1, 2))
|
122 |
+
x = x.to(dtype)
|
123 |
+
else:
|
124 |
+
x = self.neck(x.permute(0, 3, 1, 2))
|
125 |
+
return x
|
126 |
+
|
127 |
+
|
128 |
+
class Block(nn.Module):
|
129 |
+
"""Transformer blocks with support of window attention and residual propagation blocks"""
|
130 |
+
|
131 |
+
def __init__(
|
132 |
+
self,
|
133 |
+
dim: int,
|
134 |
+
num_heads: int,
|
135 |
+
mlp_ratio: float = 4.0,
|
136 |
+
qkv_bias: bool = True,
|
137 |
+
norm_layer: Type[nn.Module] = nn.LayerNorm,
|
138 |
+
act_layer: Type[nn.Module] = nn.GELU,
|
139 |
+
use_rel_pos: bool = False,
|
140 |
+
rel_pos_zero_init: bool = True,
|
141 |
+
window_size: int = 0,
|
142 |
+
input_size: Optional[Tuple[int, int]] = None,
|
143 |
+
) -> None:
|
144 |
+
"""
|
145 |
+
Args:
|
146 |
+
dim (int): Number of input channels.
|
147 |
+
num_heads (int): Number of attention heads in each ViT block.
|
148 |
+
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
149 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value.
|
150 |
+
norm_layer (nn.Module): Normalization layer.
|
151 |
+
act_layer (nn.Module): Activation layer.
|
152 |
+
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
|
153 |
+
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
|
154 |
+
window_size (int): Window size for window attention blocks. If it equals 0, then
|
155 |
+
use global attention.
|
156 |
+
input_size (tuple(int, int) or None): Input resolution for calculating the relative
|
157 |
+
positional parameter size.
|
158 |
+
"""
|
159 |
+
super().__init__()
|
160 |
+
self.norm1 = norm_layer(dim)
|
161 |
+
self.attn = Attention(
|
162 |
+
dim,
|
163 |
+
num_heads=num_heads,
|
164 |
+
qkv_bias=qkv_bias,
|
165 |
+
use_rel_pos=use_rel_pos,
|
166 |
+
rel_pos_zero_init=rel_pos_zero_init,
|
167 |
+
input_size=input_size if window_size == 0 else (window_size, window_size),
|
168 |
+
)
|
169 |
+
|
170 |
+
self.norm2 = norm_layer(dim)
|
171 |
+
self.mlp = MLPBlock(
|
172 |
+
embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer
|
173 |
+
)
|
174 |
+
|
175 |
+
self.window_size = window_size
|
176 |
+
|
177 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
178 |
+
shortcut = x
|
179 |
+
x = self.norm1(x)
|
180 |
+
# Window partition
|
181 |
+
if self.window_size > 0:
|
182 |
+
H, W = x.shape[1], x.shape[2]
|
183 |
+
x, pad_hw = window_partition(x, self.window_size)
|
184 |
+
|
185 |
+
x = self.attn(x)
|
186 |
+
# Reverse window partition
|
187 |
+
if self.window_size > 0:
|
188 |
+
x = window_unpartition(x, self.window_size, pad_hw, (H, W))
|
189 |
+
|
190 |
+
x = shortcut + x
|
191 |
+
x = x + self.mlp(self.norm2(x))
|
192 |
+
|
193 |
+
return x
|
194 |
+
|
195 |
+
|
196 |
+
class Attention(nn.Module):
|
197 |
+
"""Multi-head Attention block with relative position embeddings."""
|
198 |
+
|
199 |
+
def __init__(
|
200 |
+
self,
|
201 |
+
dim: int,
|
202 |
+
num_heads: int = 8,
|
203 |
+
qkv_bias: bool = True,
|
204 |
+
use_rel_pos: bool = False,
|
205 |
+
rel_pos_zero_init: bool = True,
|
206 |
+
input_size: Optional[Tuple[int, int]] = None,
|
207 |
+
) -> None:
|
208 |
+
"""
|
209 |
+
Args:
|
210 |
+
dim (int): Number of input channels.
|
211 |
+
num_heads (int): Number of attention heads.
|
212 |
+
qkv_bias (bool): If True, add a learnable bias to query, key, value.
|
213 |
+
rel_pos (bool): If True, add relative positional embeddings to the attention map.
|
214 |
+
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
|
215 |
+
input_size (tuple(int, int) or None): Input resolution for calculating the relative
|
216 |
+
positional parameter size.
|
217 |
+
"""
|
218 |
+
super().__init__()
|
219 |
+
self.num_heads = num_heads
|
220 |
+
head_dim = dim // num_heads
|
221 |
+
self.scale = head_dim**-0.5
|
222 |
+
|
223 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
224 |
+
self.proj = nn.Linear(dim, dim)
|
225 |
+
|
226 |
+
self.use_rel_pos = use_rel_pos
|
227 |
+
if self.use_rel_pos:
|
228 |
+
assert (
|
229 |
+
input_size is not None
|
230 |
+
), "Input size must be provided if using relative positional encoding."
|
231 |
+
# initialize relative positional embeddings
|
232 |
+
self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
|
233 |
+
self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
|
234 |
+
|
235 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
236 |
+
B, H, W, _ = x.shape
|
237 |
+
# qkv with shape (3, B, nHead, H * W, C)
|
238 |
+
qkv = (
|
239 |
+
self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
240 |
+
)
|
241 |
+
# q, k, v with shape (B * nHead, H * W, C)
|
242 |
+
q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
|
243 |
+
|
244 |
+
attn = (q * self.scale) @ k.transpose(-2, -1)
|
245 |
+
|
246 |
+
if self.use_rel_pos:
|
247 |
+
attn = add_decomposed_rel_pos(
|
248 |
+
attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)
|
249 |
+
)
|
250 |
+
|
251 |
+
attn = attn.softmax(dim=-1)
|
252 |
+
x = (
|
253 |
+
(attn @ v)
|
254 |
+
.view(B, self.num_heads, H, W, -1)
|
255 |
+
.permute(0, 2, 3, 1, 4)
|
256 |
+
.reshape(B, H, W, -1)
|
257 |
+
)
|
258 |
+
x = self.proj(x)
|
259 |
+
|
260 |
+
return x
|
261 |
+
|
262 |
+
|
263 |
+
def window_partition(
|
264 |
+
x: torch.Tensor, window_size: int
|
265 |
+
) -> Tuple[torch.Tensor, Tuple[int, int]]:
|
266 |
+
"""
|
267 |
+
Partition into non-overlapping windows with padding if needed.
|
268 |
+
Args:
|
269 |
+
x (tensor): input tokens with [B, H, W, C].
|
270 |
+
window_size (int): window size.
|
271 |
+
|
272 |
+
Returns:
|
273 |
+
windows: windows after partition with [B * num_windows, window_size, window_size, C].
|
274 |
+
(Hp, Wp): padded height and width before partition
|
275 |
+
"""
|
276 |
+
B, H, W, C = x.shape
|
277 |
+
|
278 |
+
pad_h = (window_size - H % window_size) % window_size
|
279 |
+
pad_w = (window_size - W % window_size) % window_size
|
280 |
+
if pad_h > 0 or pad_w > 0:
|
281 |
+
x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
|
282 |
+
Hp, Wp = H + pad_h, W + pad_w
|
283 |
+
|
284 |
+
x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
|
285 |
+
windows = (
|
286 |
+
x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
|
287 |
+
)
|
288 |
+
return windows, (Hp, Wp)
|
289 |
+
|
290 |
+
|
291 |
+
def window_unpartition(
|
292 |
+
windows: torch.Tensor,
|
293 |
+
window_size: int,
|
294 |
+
pad_hw: Tuple[int, int],
|
295 |
+
hw: Tuple[int, int],
|
296 |
+
) -> torch.Tensor:
|
297 |
+
"""
|
298 |
+
Window unpartition into original sequences and removing padding.
|
299 |
+
Args:
|
300 |
+
windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].
|
301 |
+
window_size (int): window size.
|
302 |
+
pad_hw (Tuple): padded height and width (Hp, Wp).
|
303 |
+
hw (Tuple): original height and width (H, W) before padding.
|
304 |
+
|
305 |
+
Returns:
|
306 |
+
x: unpartitioned sequences with [B, H, W, C].
|
307 |
+
"""
|
308 |
+
Hp, Wp = pad_hw
|
309 |
+
H, W = hw
|
310 |
+
B = windows.shape[0] // (Hp * Wp // window_size // window_size)
|
311 |
+
x = windows.view(
|
312 |
+
B, Hp // window_size, Wp // window_size, window_size, window_size, -1
|
313 |
+
)
|
314 |
+
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
|
315 |
+
|
316 |
+
if Hp > H or Wp > W:
|
317 |
+
x = x[:, :H, :W, :].contiguous()
|
318 |
+
return x
|
319 |
+
|
320 |
+
|
321 |
+
def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
|
322 |
+
"""
|
323 |
+
Get relative positional embeddings according to the relative positions of
|
324 |
+
query and key sizes.
|
325 |
+
Args:
|
326 |
+
q_size (int): size of query q.
|
327 |
+
k_size (int): size of key k.
|
328 |
+
rel_pos (Tensor): relative position embeddings (L, C).
|
329 |
+
|
330 |
+
Returns:
|
331 |
+
Extracted positional embeddings according to relative positions.
|
332 |
+
"""
|
333 |
+
max_rel_dist = int(2 * max(q_size, k_size) - 1)
|
334 |
+
# Interpolate rel pos if needed.
|
335 |
+
if rel_pos.shape[0] != max_rel_dist:
|
336 |
+
# Interpolate rel pos.
|
337 |
+
rel_pos_resized = F.interpolate(
|
338 |
+
rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
|
339 |
+
size=max_rel_dist,
|
340 |
+
mode="linear",
|
341 |
+
)
|
342 |
+
rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
|
343 |
+
else:
|
344 |
+
rel_pos_resized = rel_pos
|
345 |
+
|
346 |
+
# Scale the coords with short length if shapes for q and k are different.
|
347 |
+
q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
|
348 |
+
k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
|
349 |
+
relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
|
350 |
+
|
351 |
+
return rel_pos_resized[relative_coords.long()]
|
352 |
+
|
353 |
+
|
354 |
+
def add_decomposed_rel_pos(
|
355 |
+
attn: torch.Tensor,
|
356 |
+
q: torch.Tensor,
|
357 |
+
rel_pos_h: torch.Tensor,
|
358 |
+
rel_pos_w: torch.Tensor,
|
359 |
+
q_size: Tuple[int, int],
|
360 |
+
k_size: Tuple[int, int],
|
361 |
+
) -> torch.Tensor:
|
362 |
+
"""
|
363 |
+
Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
|
364 |
+
https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
|
365 |
+
Args:
|
366 |
+
attn (Tensor): attention map.
|
367 |
+
q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
|
368 |
+
rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
|
369 |
+
rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
|
370 |
+
q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
|
371 |
+
k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
|
372 |
+
|
373 |
+
Returns:
|
374 |
+
attn (Tensor): attention map with added relative positional embeddings.
|
375 |
+
"""
|
376 |
+
q_h, q_w = q_size
|
377 |
+
k_h, k_w = k_size
|
378 |
+
Rh = get_rel_pos(q_h, k_h, rel_pos_h)
|
379 |
+
Rw = get_rel_pos(q_w, k_w, rel_pos_w)
|
380 |
+
|
381 |
+
B, _, dim = q.shape
|
382 |
+
r_q = q.reshape(B, q_h, q_w, dim)
|
383 |
+
rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
|
384 |
+
rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
|
385 |
+
|
386 |
+
attn = (
|
387 |
+
attn.view(B, q_h, q_w, k_h, k_w)
|
388 |
+
+ rel_h[:, :, :, :, None]
|
389 |
+
+ rel_w[:, :, :, None, :]
|
390 |
+
).view(B, q_h * q_w, k_h * k_w)
|
391 |
+
|
392 |
+
return attn
|
393 |
+
|
394 |
+
|
395 |
+
class PatchEmbed(nn.Module):
|
396 |
+
"""
|
397 |
+
Image to Patch Embedding.
|
398 |
+
"""
|
399 |
+
|
400 |
+
def __init__(
|
401 |
+
self,
|
402 |
+
kernel_size: Tuple[int, int] = (16, 16),
|
403 |
+
stride: Tuple[int, int] = (16, 16),
|
404 |
+
padding: Tuple[int, int] = (0, 0),
|
405 |
+
in_chans: int = 3,
|
406 |
+
embed_dim: int = 768,
|
407 |
+
) -> None:
|
408 |
+
"""
|
409 |
+
Args:
|
410 |
+
kernel_size (Tuple): kernel size of the projection layer.
|
411 |
+
stride (Tuple): stride of the projection layer.
|
412 |
+
padding (Tuple): padding size of the projection layer.
|
413 |
+
in_chans (int): Number of input image channels.
|
414 |
+
embed_dim (int): Patch embedding dimension.
|
415 |
+
"""
|
416 |
+
super().__init__()
|
417 |
+
|
418 |
+
self.proj = nn.Conv2d(
|
419 |
+
in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
|
420 |
+
)
|
421 |
+
|
422 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
423 |
+
x = self.proj(x)
|
424 |
+
# B C H W -> B H W C
|
425 |
+
x = x.permute(0, 2, 3, 1)
|
426 |
+
return x
|
model/segment_anything/modeling/mask_decoder.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from typing import List, Tuple, Type
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from torch import nn
|
11 |
+
from torch.nn import functional as F
|
12 |
+
|
13 |
+
from .common import LayerNorm2d
|
14 |
+
|
15 |
+
|
16 |
+
class MaskDecoder(nn.Module):
|
17 |
+
def __init__(
|
18 |
+
self,
|
19 |
+
*,
|
20 |
+
transformer_dim: int,
|
21 |
+
transformer: nn.Module,
|
22 |
+
num_multimask_outputs: int = 3,
|
23 |
+
activation: Type[nn.Module] = nn.GELU,
|
24 |
+
iou_head_depth: int = 3,
|
25 |
+
iou_head_hidden_dim: int = 256,
|
26 |
+
) -> None:
|
27 |
+
"""
|
28 |
+
Predicts masks given an image and prompt embeddings, using a
|
29 |
+
transformer architecture.
|
30 |
+
|
31 |
+
Arguments:
|
32 |
+
transformer_dim (int): the channel dimension of the transformer
|
33 |
+
transformer (nn.Module): the transformer used to predict masks
|
34 |
+
num_multimask_outputs (int): the number of masks to predict
|
35 |
+
when disambiguating masks
|
36 |
+
activation (nn.Module): the type of activation to use when
|
37 |
+
upscaling masks
|
38 |
+
iou_head_depth (int): the depth of the MLP used to predict
|
39 |
+
mask quality
|
40 |
+
iou_head_hidden_dim (int): the hidden dimension of the MLP
|
41 |
+
used to predict mask quality
|
42 |
+
"""
|
43 |
+
super().__init__()
|
44 |
+
self.transformer_dim = transformer_dim
|
45 |
+
self.transformer = transformer
|
46 |
+
|
47 |
+
self.num_multimask_outputs = num_multimask_outputs
|
48 |
+
|
49 |
+
self.iou_token = nn.Embedding(1, transformer_dim)
|
50 |
+
self.num_mask_tokens = num_multimask_outputs + 1
|
51 |
+
self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
|
52 |
+
|
53 |
+
self.output_upscaling = nn.Sequential(
|
54 |
+
nn.ConvTranspose2d(
|
55 |
+
transformer_dim, transformer_dim // 4, kernel_size=2, stride=2
|
56 |
+
),
|
57 |
+
LayerNorm2d(transformer_dim // 4),
|
58 |
+
activation(),
|
59 |
+
nn.ConvTranspose2d(
|
60 |
+
transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2
|
61 |
+
),
|
62 |
+
activation(),
|
63 |
+
)
|
64 |
+
self.output_hypernetworks_mlps = nn.ModuleList(
|
65 |
+
[
|
66 |
+
MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
|
67 |
+
for i in range(self.num_mask_tokens)
|
68 |
+
]
|
69 |
+
)
|
70 |
+
|
71 |
+
self.iou_prediction_head = MLP(
|
72 |
+
transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth
|
73 |
+
)
|
74 |
+
|
75 |
+
def forward(
|
76 |
+
self,
|
77 |
+
image_embeddings: torch.Tensor,
|
78 |
+
image_pe: torch.Tensor,
|
79 |
+
sparse_prompt_embeddings: torch.Tensor,
|
80 |
+
dense_prompt_embeddings: torch.Tensor,
|
81 |
+
multimask_output: bool,
|
82 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
83 |
+
"""
|
84 |
+
Predict masks given image and prompt embeddings.
|
85 |
+
|
86 |
+
Arguments:
|
87 |
+
image_embeddings (torch.Tensor): the embeddings from the image encoder
|
88 |
+
image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
|
89 |
+
sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
|
90 |
+
dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
|
91 |
+
multimask_output (bool): Whether to return multiple masks or a single
|
92 |
+
mask.
|
93 |
+
|
94 |
+
Returns:
|
95 |
+
torch.Tensor: batched predicted masks
|
96 |
+
torch.Tensor: batched predictions of mask quality
|
97 |
+
"""
|
98 |
+
masks, iou_pred = self.predict_masks(
|
99 |
+
image_embeddings=image_embeddings,
|
100 |
+
image_pe=image_pe,
|
101 |
+
sparse_prompt_embeddings=sparse_prompt_embeddings,
|
102 |
+
dense_prompt_embeddings=dense_prompt_embeddings,
|
103 |
+
)
|
104 |
+
|
105 |
+
# Select the correct mask or masks for output
|
106 |
+
if multimask_output:
|
107 |
+
mask_slice = slice(1, None)
|
108 |
+
else:
|
109 |
+
mask_slice = slice(0, 1)
|
110 |
+
masks = masks[:, mask_slice, :, :]
|
111 |
+
iou_pred = iou_pred[:, mask_slice]
|
112 |
+
|
113 |
+
# Prepare output
|
114 |
+
return masks, iou_pred
|
115 |
+
|
116 |
+
def predict_masks(
|
117 |
+
self,
|
118 |
+
image_embeddings: torch.Tensor,
|
119 |
+
image_pe: torch.Tensor,
|
120 |
+
sparse_prompt_embeddings: torch.Tensor,
|
121 |
+
dense_prompt_embeddings: torch.Tensor,
|
122 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
123 |
+
"""Predicts masks. See 'forward' for more details."""
|
124 |
+
# Concatenate output tokens
|
125 |
+
output_tokens = torch.cat(
|
126 |
+
[self.iou_token.weight, self.mask_tokens.weight], dim=0
|
127 |
+
)
|
128 |
+
output_tokens = output_tokens.unsqueeze(0).expand(
|
129 |
+
sparse_prompt_embeddings.size(0), -1, -1
|
130 |
+
)
|
131 |
+
|
132 |
+
tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
|
133 |
+
|
134 |
+
# image_embeddings: [1, C, H, W], tokens: [B, N, C]
|
135 |
+
# dense_prompt_embeddings: [B, C, H, W]
|
136 |
+
# Expand per-image data in batch direction to be per-mask
|
137 |
+
src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
|
138 |
+
src = src + dense_prompt_embeddings
|
139 |
+
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
|
140 |
+
b, c, h, w = src.shape
|
141 |
+
|
142 |
+
# Run the transformer
|
143 |
+
hs, src = self.transformer(src, pos_src, tokens)
|
144 |
+
iou_token_out = hs[:, 0, :]
|
145 |
+
mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :]
|
146 |
+
|
147 |
+
# Upscale mask embeddings and predict masks using the mask tokens
|
148 |
+
src = src.transpose(1, 2).view(b, c, h, w)
|
149 |
+
upscaled_embedding = self.output_upscaling(src)
|
150 |
+
hyper_in_list: List[torch.Tensor] = []
|
151 |
+
for i in range(self.num_mask_tokens):
|
152 |
+
hyper_in_list.append(
|
153 |
+
self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])
|
154 |
+
)
|
155 |
+
hyper_in = torch.stack(hyper_in_list, dim=1)
|
156 |
+
b, c, h, w = upscaled_embedding.shape
|
157 |
+
masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(
|
158 |
+
b, self.num_mask_tokens, h, w
|
159 |
+
)
|
160 |
+
|
161 |
+
# Generate mask quality predictions
|
162 |
+
iou_pred = self.iou_prediction_head(iou_token_out)
|
163 |
+
|
164 |
+
return masks, iou_pred
|
165 |
+
|
166 |
+
|
167 |
+
# Lightly adapted from
|
168 |
+
# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
|
169 |
+
class MLP(nn.Module):
|
170 |
+
def __init__(
|
171 |
+
self,
|
172 |
+
input_dim: int,
|
173 |
+
hidden_dim: int,
|
174 |
+
output_dim: int,
|
175 |
+
num_layers: int,
|
176 |
+
sigmoid_output: bool = False,
|
177 |
+
) -> None:
|
178 |
+
super().__init__()
|
179 |
+
self.num_layers = num_layers
|
180 |
+
h = [hidden_dim] * (num_layers - 1)
|
181 |
+
self.layers = nn.ModuleList(
|
182 |
+
nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
|
183 |
+
)
|
184 |
+
self.sigmoid_output = sigmoid_output
|
185 |
+
|
186 |
+
def forward(self, x):
|
187 |
+
for i, layer in enumerate(self.layers):
|
188 |
+
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
|
189 |
+
if self.sigmoid_output:
|
190 |
+
x = F.sigmoid(x)
|
191 |
+
return x
|