Spaces:
Running
on
Zero
Running
on
Zero
derektan
commited on
Commit
·
1faad26
0
Parent(s):
Initial clean commit for Hugging Face
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +6 -0
- .gitignore +4 -0
- LICENSE +201 -0
- README.md +339 -0
- app.py +359 -0
- chat.py +359 -0
- imgs/blackpink.jpg +3 -0
- imgs/camera_lens.jpg +3 -0
- imgs/car_speed.jpg +3 -0
- imgs/dog_with_horn.jpg +3 -0
- imgs/example1.jpg +3 -0
- imgs/example2.jpg +3 -0
- imgs/fig_overview.jpg +3 -0
- imgs/jackma.jpg +3 -0
- imgs/obama.jpg +3 -0
- imgs/stand_higher.jpg +3 -0
- imgs/table1.jpg +3 -0
- imgs/teaser.jpg +3 -0
- imgs/trump.jpg +3 -0
- imgs/wash_hands.jpg +3 -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
.gitattributes
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
**/__pycache__
|
| 2 |
+
runs/
|
| 3 |
+
.vscode/
|
| 4 |
+
|
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,339 @@
|
|
|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://103.170.5.190:7860/)
|
| 2 |
+
[](https://openxlab.org.cn/apps/detail/openxlab-app/LISA)
|
| 3 |
+
|
| 4 |
+
# LISA: Reasoning Segmentation via Large Language Model
|
| 5 |
+
|
| 6 |
+
Note: This is fork from the [original LISA webpage](https://github.com/dvlab-research/LISA), finetuned on visual search ([AVS-Bench](https://huggingface.co/datasets/derektan95/avs-bench)) remote sensing dataset as a baseline to [Search-TTA](https://search-tta.github.io/). To run the finetuned LISA model on the AVS-Bench dataset, please run the following:
|
| 7 |
+
```
|
| 8 |
+
CUDA_VISIBLE_DEVICES=0 python chat.py --version='derektan95/LISA-RS' --precision='bf16'
|
| 9 |
+
CUDA_VISIBLE_DEVICES=0 python app.py --version='derektan95/LISA-RS' --precision='bf16'
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
<font size=7><div align='center'><b>LISA</b>: Large <b>L</b>anguage <b>I</b>nstructed <b>S</b>egmentation <b>A</b>ssistant</div></font>
|
| 13 |
+
|
| 14 |
+
<font size=7><div align='center'>
|
| 15 |
+
<a href="https://arxiv.org/pdf/2308.00692.pdf"><strong>Paper</strong></a> |
|
| 16 |
+
<a href="https://huggingface.co/xinlai"><strong>Models</strong></a> |
|
| 17 |
+
<a href="#training"><strong>Training</strong></a> |
|
| 18 |
+
<a href="#inference"><strong>Inference</strong></a> |
|
| 19 |
+
<a href="#deployment"><strong>Local Deployment</strong></a> |
|
| 20 |
+
<a href="#dataset"><strong>Dataset</strong></a> |
|
| 21 |
+
<a href=""><strong>Online Demo</strong></a> |
|
| 22 |
+
<a href="https://huggingface.co/collections/Senqiao/lisa-67713837a32d6abf516a162e"><strong>LISA++ Dataset</strong></a> |
|
| 23 |
+
<a href="https://huggingface.co/Senqiao/LISA_Plus_7b"><strong>LISA++ Model</strong></a>
|
| 24 |
+
</div></font>
|
| 25 |
+
|
| 26 |
+
<!-- <p align="center"> <img src="imgs/teaser.jpg" width="100%"> </p> -->
|
| 27 |
+
|
| 28 |
+
<table class="center">
|
| 29 |
+
<tr>
|
| 30 |
+
<td style="text-align:center;"><b>Input</b></td>
|
| 31 |
+
<td style="text-align:center;"><b>Output</b></td>
|
| 32 |
+
<td style="text-align:center;"><b>Input</b></td>
|
| 33 |
+
<td style="text-align:center;"><b>Output</b></td>
|
| 34 |
+
</tr>
|
| 35 |
+
<tr>
|
| 36 |
+
<td><img src="imgs/obama.jpg"></td>
|
| 37 |
+
<td><img src="vis_output/obama.jpg"></td>
|
| 38 |
+
<td><img src="imgs/trump.jpg"></td>
|
| 39 |
+
<td><img src="vis_output/trump.jpg"></td>
|
| 40 |
+
</tr>
|
| 41 |
+
<tr>
|
| 42 |
+
<td width=25% style="text-align:center;color:gray;">"Who was <ins>the president of the US</ins> in this image? Please output segmentation mask and explain the reason."</td>
|
| 43 |
+
<td width=25% style="text-align:center;">"Sure, the segmentation result is [SEG]. The President of the United States in the image is <ins>President Obama.</ins>”</td>
|
| 44 |
+
<td width=25% style="text-align:center;color:gray">"Who was <ins>the president of the US</ins> in this image? Please output segmentation mask and explain why."</td>
|
| 45 |
+
<td width=25% style="text-align:center;">"Sure, [SEG]. In the image, the President of the United States is <ins>President Trump.</ins>"</td>
|
| 46 |
+
</tr>
|
| 47 |
+
|
| 48 |
+
<tr>
|
| 49 |
+
<td><img src="imgs/stand_higher.jpg"></td>
|
| 50 |
+
<td><img src="vis_output/stand_higher.jpg"></td>
|
| 51 |
+
<td><img src="imgs/camera_lens.jpg"></td>
|
| 52 |
+
<td><img src="vis_output/camera_lens.jpg"></td>
|
| 53 |
+
</tr>
|
| 54 |
+
<tr>
|
| 55 |
+
<td width=25% style="text-align:center;color:gray;">"What can <ins>make the woman stand higher</ins>? Please output segmentation mask and explain why."</td>
|
| 56 |
+
<td width=25% style="text-align:center;">"Sure, [SEG]. The woman is <ins>standing higher by using a ladder</ins>..."</td>
|
| 57 |
+
<td width=25% style="text-align:center;color:gray">"Can you segment <ins>the camera lens that is more suitable for photographing nearby objects</ins> in this image?"</td>
|
| 58 |
+
<td width=25% style="text-align:center;">"Sure, [SEG]."</td>
|
| 59 |
+
</tr>
|
| 60 |
+
|
| 61 |
+
<tr>
|
| 62 |
+
<td><img src="imgs/dog_with_horn.jpg"></td>
|
| 63 |
+
<td><img src="vis_output/dog_with_horn.jpg"></td>
|
| 64 |
+
<td><img src="imgs/wash_hands.jpg"></td>
|
| 65 |
+
<td><img src="vis_output/wash_hands.jpg"></td>
|
| 66 |
+
</tr>
|
| 67 |
+
<tr>
|
| 68 |
+
<td width=25% style="text-align:center;color:gray;">"Can you segment <ins>the unusual part</ins> in this image and explain why."</td>
|
| 69 |
+
<td width=25% style="text-align:center;">"Sure, it is [SEG]. In the image, the unusual part is <ins>the dog wearing a reindeer antler headband</ins>..."</td>
|
| 70 |
+
<td width=25% style="text-align:center;color:gray">"Where to <ins>wash hands</ins> in this image? Please output segmentation mask."</td>
|
| 71 |
+
<td width=25% style="text-align:center;">"Sure, [SEG]."</td>
|
| 72 |
+
</tr>
|
| 73 |
+
|
| 74 |
+
<tr>
|
| 75 |
+
<td><img src="imgs/jackma.jpg"></td>
|
| 76 |
+
<td><img src="vis_output/jackma.jpg"></td>
|
| 77 |
+
<td><img src="imgs/blackpink.jpg"></td>
|
| 78 |
+
<td><img src="vis_output/blackpink.jpg"></td>
|
| 79 |
+
</tr>
|
| 80 |
+
<tr>
|
| 81 |
+
<td width=25% style="text-align:center;color:gray;">"Can you segment <ins>the founder of Alibaba</ins> in this image and explain why?"</td>
|
| 82 |
+
<td width=25% style="text-align:center;">"Sure, it is [SEG]. In the image, the man wearing a red tie and sitting on one of the chairs is <ins>Jack Ma</ins>, the co-founder of Alibaba Group..."</td>
|
| 83 |
+
<td width=25% style="text-align:center;color:gray">"Please segment <ins>Lisa</ins> in this figure."</td>
|
| 84 |
+
<td width=25% style="text-align:center;">"Sure, [SEG]."</td>
|
| 85 |
+
</tr>
|
| 86 |
+
</table>
|
| 87 |
+
|
| 88 |
+
<p align="center"> <img src="imgs/fig_overview.jpg" width="100%"> </p>
|
| 89 |
+
|
| 90 |
+
## News
|
| 91 |
+
- [x] [2024.12.30] We released the [LISA++](https://arxiv.org/abs/2312.17240) model and datasets, available [here](https://huggingface.co/collections/Senqiao/lisa-67713837a32d6abf516a162e). Our findings show that incorporating Visual COT data can further enhance the model’s global understanding. We will update the paper soon, stay tuned!
|
| 92 |
+
- [x] [2024.6.21] LISA is selected as Oral Presentation in CVPR 2024!
|
| 93 |
+
- [x] [2023.8.30] Release three new models [LISA-7B-v1](https://huggingface.co/xinlai/LISA-7B-v1), [LISA-7B-v1-explanatory](https://huggingface.co/xinlai/LISA-7B-v1-explanatory), and [LISA-13B-llama2-v1-explanatory](https://huggingface.co/xinlai/LISA-13B-llama2-v1-explanatory). Welcome to check them out!
|
| 94 |
+
- [x] [2023.8.23] Refactor code, and release new model [LISA-13B-llama2-v1](https://huggingface.co/xinlai/LISA-13B-llama2-v1). Welcome to check it out!
|
| 95 |
+
- [x] [2023.8.9] Training code is released!
|
| 96 |
+
- [x] [2023.8.4] [Online Demo](http://103.170.5.190:7860/) is released!
|
| 97 |
+
- [x] [2023.8.4] [*ReasonSeg* Dataset](https://drive.google.com/drive/folders/125mewyg5Ao6tZ3ZdJ-1-E3n04LGVELqy?usp=sharing) and the [LISA-13B-llama2-v0-explanatory](https://huggingface.co/xinlai/LISA-13B-llama2-v0-explanatory) model are released!
|
| 98 |
+
- [x] [2023.8.3] Inference code and the [LISA-13B-llama2-v0](https://huggingface.co/xinlai/LISA-13B-llama2-v0) model are released. Welcome to check them out!
|
| 99 |
+
- [x] [2023.8.2] [Paper](https://arxiv.org/pdf/2308.00692.pdf) is released and GitHub repo is created.
|
| 100 |
+
|
| 101 |
+
**LISA: Reasoning Segmentation via Large Language Model [[Paper](https://arxiv.org/abs/2308.00692)]** <br />
|
| 102 |
+
[Xin Lai](https://scholar.google.com/citations?user=tqNDPA4AAAAJ&hl=zh-CN),
|
| 103 |
+
[Zhuotao Tian](https://scholar.google.com/citations?user=mEjhz-IAAAAJ&hl=en),
|
| 104 |
+
[Yukang Chen](https://scholar.google.com/citations?user=6p0ygKUAAAAJ&hl=en),
|
| 105 |
+
[Yanwei Li](https://scholar.google.com/citations?user=I-UCPPcAAAAJ&hl=zh-CN),
|
| 106 |
+
[Yuhui Yuan](https://scholar.google.com/citations?user=PzyvzksAAAAJ&hl=en),
|
| 107 |
+
[Shu Liu](https://scholar.google.com.hk/citations?user=BUEDUFkAAAAJ&hl=zh-CN),
|
| 108 |
+
[Jiaya Jia](https://scholar.google.com/citations?user=XPAkzTEAAAAJ&hl=en)<br />
|
| 109 |
+
|
| 110 |
+
**LISA++: An Improved Baseline for Reasoning Segmentation with Large Language Model [[Paper](https://arxiv.org/abs/2312.17240)]** <br />
|
| 111 |
+
[Senqiao Yang](https://scholar.google.com/citations?user=NcJc-RwAAAAJ),
|
| 112 |
+
Tianyuan Qu,
|
| 113 |
+
[Xin Lai](https://scholar.google.com/citations?user=tqNDPA4AAAAJ&hl=zh-CN),
|
| 114 |
+
[Zhuotao Tian](https://scholar.google.com/citations?user=mEjhz-IAAAAJ&hl=en),
|
| 115 |
+
[Bohao Peng](https://scholar.google.com.hk/citations?user=9xcCm1oAAAAJ),
|
| 116 |
+
[Shu Liu](https://scholar.google.com.hk/citations?user=BUEDUFkAAAAJ&hl=zh-CN),
|
| 117 |
+
[Jiaya Jia](https://scholar.google.com/citations?user=XPAkzTEAAAAJ&hl=en)<br />
|
| 118 |
+
|
| 119 |
+
## Abstract
|
| 120 |
+
In this work, we propose a new segmentation task --- ***reasoning segmentation***. The task is designed to output a segmentation mask given a complex and implicit query text. We establish a benchmark comprising over one thousand image-instruction pairs, incorporating intricate reasoning and world knowledge for evaluation purposes. Finally, we present LISA: Large-language Instructed Segmentation Assistant, which inherits the language generation capabilities of the multi-modal Large Language Model (LLM) while also possessing the ability to produce segmentation masks.
|
| 121 |
+
For more details, please refer to the [paper](https://arxiv.org/abs/2308.00692).
|
| 122 |
+
|
| 123 |
+
## Highlights
|
| 124 |
+
**LISA** unlocks the new segmentation capabilities of multi-modal LLMs, and can handle cases involving:
|
| 125 |
+
1. complex reasoning;
|
| 126 |
+
2. world knowledge;
|
| 127 |
+
3. explanatory answers;
|
| 128 |
+
4. multi-turn conversation.
|
| 129 |
+
|
| 130 |
+
**LISA** also demonstrates robust zero-shot capability when trained exclusively on reasoning-free datasets. In addition, fine-tuning the model with merely 239 reasoning segmentation image-instruction pairs results in further performance enhancement.
|
| 131 |
+
|
| 132 |
+
## Experimental results
|
| 133 |
+
<p align="center"> <img src="imgs/table1.jpg" width="80%"> </p>
|
| 134 |
+
|
| 135 |
+
## Installation
|
| 136 |
+
```
|
| 137 |
+
pip install -r requirements.txt
|
| 138 |
+
pip install flash-attn --no-build-isolation
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
## Training
|
| 142 |
+
### Training Data Preparation
|
| 143 |
+
The training data consists of 4 types of data:
|
| 144 |
+
|
| 145 |
+
1. Semantic segmentation datasets: [ADE20K](http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip), [COCO-Stuff](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip), [Mapillary](https://www.mapillary.com/dataset/vistas), [PACO-LVIS](https://github.com/facebookresearch/paco/tree/main#dataset-setup), [PASCAL-Part](https://github.com/facebookresearch/VLPart/tree/main/datasets#pascal-part), [COCO Images](http://images.cocodataset.org/zips/train2017.zip)
|
| 146 |
+
|
| 147 |
+
Note: For COCO-Stuff, we use the annotation file stuffthingmaps_trainval2017.zip. We only use the PACO-LVIS part in PACO. COCO Images should be put into the `dataset/coco/` directory.
|
| 148 |
+
|
| 149 |
+
3. Referring segmentation datasets: [refCOCO](https://web.archive.org/web/20220413011718/https://bvisionweb1.cs.unc.edu/licheng/referit/data/refcoco.zip), [refCOCO+](https://web.archive.org/web/20220413011656/https://bvisionweb1.cs.unc.edu/licheng/referit/data/refcoco+.zip), [refCOCOg](https://web.archive.org/web/20220413012904/https://bvisionweb1.cs.unc.edu/licheng/referit/data/refcocog.zip), [refCLEF](https://web.archive.org/web/20220413011817/https://bvisionweb1.cs.unc.edu/licheng/referit/data/refclef.zip) ([saiapr_tc-12](https://web.archive.org/web/20220515000000/http://bvisionweb1.cs.unc.edu/licheng/referit/data/images/saiapr_tc-12.zip))
|
| 150 |
+
|
| 151 |
+
Note: the original links of refCOCO series data are down, and we update them with new ones. If the download speed is super slow or unstable, we also provide a [OneDrive link](https://mycuhk-my.sharepoint.com/:f:/g/personal/1155154502_link_cuhk_edu_hk/Em5yELVBvfREodKC94nOFLoBLro_LPxsOxNV44PHRWgLcA?e=zQPjsc) to download. **You must also follow the rules that the original datasets require.**
|
| 152 |
+
|
| 153 |
+
4. Visual Question Answering dataset: [LLaVA-Instruct-150k](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/blob/main/llava_instruct_150k.json)
|
| 154 |
+
|
| 155 |
+
5. Reasoning segmentation dataset: [ReasonSeg](https://github.com/dvlab-research/LISA#dataset)
|
| 156 |
+
|
| 157 |
+
Download them from the above links, and organize them as follows.
|
| 158 |
+
|
| 159 |
+
```
|
| 160 |
+
├── dataset
|
| 161 |
+
│ ├── ade20k
|
| 162 |
+
│ │ ├── annotations
|
| 163 |
+
│ │ └── images
|
| 164 |
+
│ ├── coco
|
| 165 |
+
│ │ └── train2017
|
| 166 |
+
│ │ ├── 000000000009.jpg
|
| 167 |
+
│ │ └── ...
|
| 168 |
+
│ ├── cocostuff
|
| 169 |
+
│ │ └── train2017
|
| 170 |
+
│ │ ├── 000000000009.png
|
| 171 |
+
│ │ └── ...
|
| 172 |
+
│ ├── llava_dataset
|
| 173 |
+
│ │ └── llava_instruct_150k.json
|
| 174 |
+
│ ├── mapillary
|
| 175 |
+
│ │ ├── config_v2.0.json
|
| 176 |
+
│ │ ├── testing
|
| 177 |
+
│ │ ├── training
|
| 178 |
+
│ │ └── validation
|
| 179 |
+
│ ├── reason_seg
|
| 180 |
+
│ │ └── ReasonSeg
|
| 181 |
+
│ │ ├── train
|
| 182 |
+
│ │ ├── val
|
| 183 |
+
│ │ └── explanatory
|
| 184 |
+
│ ├── refer_seg
|
| 185 |
+
│ │ ├── images
|
| 186 |
+
│ │ | ├── saiapr_tc-12
|
| 187 |
+
│ │ | └── mscoco
|
| 188 |
+
│ │ | └── images
|
| 189 |
+
│ │ | └── train2014
|
| 190 |
+
│ │ ├── refclef
|
| 191 |
+
│ │ ├── refcoco
|
| 192 |
+
│ │ ├── refcoco+
|
| 193 |
+
│ │ └── refcocog
|
| 194 |
+
│ └── vlpart
|
| 195 |
+
│ ├── paco
|
| 196 |
+
│ │ └── annotations
|
| 197 |
+
│ └── pascal_part
|
| 198 |
+
│ ├── train.json
|
| 199 |
+
│ └── VOCdevkit
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
### Pre-trained weights
|
| 203 |
+
|
| 204 |
+
#### LLaVA
|
| 205 |
+
To train LISA-7B or 13B, you need to follow the [instruction](https://github.com/haotian-liu/LLaVA/blob/main/docs/MODEL_ZOO.md) to merge the LLaVA delta weights. Typically, we use the final weights `LLaVA-Lightning-7B-v1-1` and `LLaVA-13B-v1-1` merged from `liuhaotian/LLaVA-Lightning-7B-delta-v1-1` and `liuhaotian/LLaVA-13b-delta-v1-1`, respectively. For Llama2, we can directly use the LLaVA full weights `liuhaotian/llava-llama-2-13b-chat-lightning-preview`.
|
| 206 |
+
|
| 207 |
+
#### SAM ViT-H weights
|
| 208 |
+
Download SAM ViT-H pre-trained weights from the [link](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth).
|
| 209 |
+
|
| 210 |
+
### Training
|
| 211 |
+
```
|
| 212 |
+
deepspeed --master_port=24999 train_ds.py \
|
| 213 |
+
--version="PATH_TO_LLaVA" \
|
| 214 |
+
--dataset_dir='./dataset' \
|
| 215 |
+
--vision_pretrained="PATH_TO_SAM" \
|
| 216 |
+
--dataset="sem_seg||refer_seg||vqa||reason_seg" \
|
| 217 |
+
--sample_rates="9,3,3,1" \
|
| 218 |
+
--exp_name="lisa-7b"
|
| 219 |
+
```
|
| 220 |
+
When training is finished, to get the full model weight:
|
| 221 |
+
```
|
| 222 |
+
cd ./runs/lisa-7b/ckpt_model && python zero_to_fp32.py . ../pytorch_model.bin
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
### Merge LoRA Weight
|
| 226 |
+
Merge the LoRA weights of `pytorch_model.bin`, save the resulting model into your desired path in the Hugging Face format:
|
| 227 |
+
```
|
| 228 |
+
CUDA_VISIBLE_DEVICES="" python merge_lora_weights_and_save_hf_model.py \
|
| 229 |
+
--version="PATH_TO_LLaVA" \
|
| 230 |
+
--weight="PATH_TO_pytorch_model.bin" \
|
| 231 |
+
--save_path="PATH_TO_SAVED_MODEL"
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
For example:
|
| 235 |
+
```
|
| 236 |
+
CUDA_VISIBLE_DEVICES="" python3 merge_lora_weights_and_save_hf_model.py \
|
| 237 |
+
--version="./LLaVA/LLaVA-Lightning-7B-v1-1" \
|
| 238 |
+
--weight="lisa-7b/pytorch_model.bin" \
|
| 239 |
+
--save_path="./LISA-7B"
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
### Validation
|
| 243 |
+
```
|
| 244 |
+
deepspeed --master_port=24999 train_ds.py \
|
| 245 |
+
--version="PATH_TO_LISA_HF_Model_Directory" \
|
| 246 |
+
--dataset_dir='./dataset' \
|
| 247 |
+
--vision_pretrained="PATH_TO_SAM" \
|
| 248 |
+
--exp_name="lisa-7b" \
|
| 249 |
+
--eval_only
|
| 250 |
+
```
|
| 251 |
+
|
| 252 |
+
Note: the `v1` model is trained using both `train+val` sets, so please use the `v0` model to reproduce the validation results. (To use the `v0` models, please first checkout to the legacy version repo with `git checkout 0e26916`.)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
## Inference
|
| 256 |
+
|
| 257 |
+
To chat with [LISA-13B-llama2-v1](https://huggingface.co/xinlai/LISA-13B-llama2-v1) or [LISA-13B-llama2-v1-explanatory](https://huggingface.co/xinlai/LISA-13B-llama2-v1-explanatory):
|
| 258 |
+
(Note that `chat.py` currently does not support `v0` models (i.e., `LISA-13B-llama2-v0` and `LISA-13B-llama2-v0-explanatory`), if you want to use the `v0` models, please first checkout to the legacy version repo `git checkout 0e26916`.)
|
| 259 |
+
```
|
| 260 |
+
CUDA_VISIBLE_DEVICES=0 python chat.py --version='xinlai/LISA-13B-llama2-v1'
|
| 261 |
+
CUDA_VISIBLE_DEVICES=0 python chat.py --version='xinlai/LISA-13B-llama2-v1-explanatory'
|
| 262 |
+
```
|
| 263 |
+
To use `bf16` or `fp16` data type for inference:
|
| 264 |
+
```
|
| 265 |
+
CUDA_VISIBLE_DEVICES=0 python chat.py --version='xinlai/LISA-13B-llama2-v1' --precision='bf16'
|
| 266 |
+
```
|
| 267 |
+
To use `8bit` or `4bit` data type for inference (this enables running 13B model on a single 24G or 12G GPU at some cost of generation quality):
|
| 268 |
+
```
|
| 269 |
+
CUDA_VISIBLE_DEVICES=0 python chat.py --version='xinlai/LISA-13B-llama2-v1' --precision='fp16' --load_in_8bit
|
| 270 |
+
CUDA_VISIBLE_DEVICES=0 python chat.py --version='xinlai/LISA-13B-llama2-v1' --precision='fp16' --load_in_4bit
|
| 271 |
+
```
|
| 272 |
+
Hint: for 13B model, 16-bit inference consumes 30G VRAM with a single GPU, 8-bit inference consumes 16G, and 4-bit inference consumes 9G.
|
| 273 |
+
|
| 274 |
+
After that, input the text prompt and then the image path. For example,
|
| 275 |
+
```
|
| 276 |
+
- Please input your prompt: Where can the driver see the car speed in this image? Please output segmentation mask.
|
| 277 |
+
- Please input the image path: imgs/example1.jpg
|
| 278 |
+
|
| 279 |
+
- Please input your prompt: Can you segment the food that tastes spicy and hot?
|
| 280 |
+
- Please input the image path: imgs/example2.jpg
|
| 281 |
+
```
|
| 282 |
+
The results should be like:
|
| 283 |
+
<p align="center"> <img src="imgs/example1.jpg" width="22%"> <img src="vis_output/example1_masked_img_0.jpg" width="22%"> <img src="imgs/example2.jpg" width="25%"> <img src="vis_output/example2_masked_img_0.jpg" width="25%"> </p>
|
| 284 |
+
|
| 285 |
+
## Deployment
|
| 286 |
+
```
|
| 287 |
+
CUDA_VISIBLE_DEVICES=0 python app.py --version='xinlai/LISA-13B-llama2-v1 --load_in_4bit'
|
| 288 |
+
CUDA_VISIBLE_DEVICES=0 python app.py --version='xinlai/LISA-13B-llama2-v1-explanatory --load_in_4bit'
|
| 289 |
+
```
|
| 290 |
+
By default, we use 4-bit quantization. Feel free to delete the `--load_in_4bit` argument for 16-bit inference or replace it with `--load_in_8bit` argument for 8-bit inference.
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
## Dataset
|
| 294 |
+
In ReasonSeg, we have collected 1218 images (239 train, 200 val, and 779 test). The training and validation sets can be download from <a href="https://drive.google.com/drive/folders/125mewyg5Ao6tZ3ZdJ-1-E3n04LGVELqy?usp=sharing">**this link**</a>.
|
| 295 |
+
|
| 296 |
+
Each image is provided with an annotation JSON file:
|
| 297 |
+
```
|
| 298 |
+
image_1.jpg, image_1.json
|
| 299 |
+
image_2.jpg, image_2.json
|
| 300 |
+
...
|
| 301 |
+
image_n.jpg, image_n.json
|
| 302 |
+
```
|
| 303 |
+
Important keys contained in JSON files:
|
| 304 |
+
```
|
| 305 |
+
- "text": text instructions.
|
| 306 |
+
- "is_sentence": whether the text instructions are long sentences.
|
| 307 |
+
- "shapes": target polygons.
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
The elements of the "shapes" exhibit two categories, namely **"target"** and **"ignore"**. The former category is indispensable for evaluation, while the latter category denotes the ambiguous region and hence disregarded during the evaluation process.
|
| 311 |
+
|
| 312 |
+
We provide a <a href="https://github.com/dvlab-research/LISA/blob/main/utils/data_processing.py">**script**</a> that demonstrates how to process the annotations:
|
| 313 |
+
```
|
| 314 |
+
python3 utils/data_processing.py
|
| 315 |
+
```
|
| 316 |
+
|
| 317 |
+
Besides, we leveraged GPT-3.5 for rephrasing instructions, so images in the training set may have **more than one instructions (but fewer than six)** in the "text" field. During training, users may randomly select one as the text query to obtain a better model.
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
## Citation
|
| 321 |
+
If you find this project useful in your research, please consider citing:
|
| 322 |
+
|
| 323 |
+
```
|
| 324 |
+
@article{lai2023lisa,
|
| 325 |
+
title={LISA: Reasoning Segmentation via Large Language Model},
|
| 326 |
+
author={Lai, Xin and Tian, Zhuotao and Chen, Yukang and Li, Yanwei and Yuan, Yuhui and Liu, Shu and Jia, Jiaya},
|
| 327 |
+
journal={arXiv preprint arXiv:2308.00692},
|
| 328 |
+
year={2023}
|
| 329 |
+
}
|
| 330 |
+
@article{yang2023improved,
|
| 331 |
+
title={An Improved Baseline for Reasoning Segmentation with Large Language Model},
|
| 332 |
+
author={Yang, Senqiao and Qu, Tianyuan and Lai, Xin and Tian, Zhuotao and Peng, Bohao and Liu, Shu and Jia, Jiaya},
|
| 333 |
+
journal={arXiv preprint arXiv:2312.17240},
|
| 334 |
+
year={2023}
|
| 335 |
+
}
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
## Acknowledgement
|
| 339 |
+
- This work is built upon the [LLaVA](https://github.com/haotian-liu/LLaVA) and [SAM](https://github.com/facebookresearch/segment-anything).
|
app.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from matplotlib import pyplot as plt
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from PIL import Image
|
| 14 |
+
from transformers import AutoTokenizer, BitsAndBytesConfig, CLIPImageProcessor
|
| 15 |
+
|
| 16 |
+
from model.LISA import LISAForCausalLM
|
| 17 |
+
from model.llava import conversation as conversation_lib
|
| 18 |
+
from model.llava.mm_utils import tokenizer_image_token
|
| 19 |
+
from model.segment_anything.utils.transforms import ResizeLongestSide
|
| 20 |
+
from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
| 21 |
+
DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEX)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def parse_args(args):
|
| 25 |
+
parser = argparse.ArgumentParser(description="LISA chat")
|
| 26 |
+
parser.add_argument("--version", default="xinlai/LISA-13B-llama2-v1")
|
| 27 |
+
parser.add_argument("--vis_save_path", default="./vis_output", type=str)
|
| 28 |
+
parser.add_argument(
|
| 29 |
+
"--precision",
|
| 30 |
+
default="fp16",
|
| 31 |
+
type=str,
|
| 32 |
+
choices=["fp32", "bf16", "fp16"],
|
| 33 |
+
help="precision for inference",
|
| 34 |
+
)
|
| 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("--lora_r", default=8, type=int)
|
| 38 |
+
parser.add_argument(
|
| 39 |
+
"--vision-tower", default="openai/clip-vit-large-patch14", type=str
|
| 40 |
+
)
|
| 41 |
+
parser.add_argument("--local-rank", default=0, type=int, help="node rank")
|
| 42 |
+
parser.add_argument("--load_in_8bit", action="store_true", default=False)
|
| 43 |
+
parser.add_argument("--load_in_4bit", action="store_true", default=False)
|
| 44 |
+
parser.add_argument("--use_mm_start_end", action="store_true", default=True)
|
| 45 |
+
parser.add_argument(
|
| 46 |
+
"--conv_type",
|
| 47 |
+
default="llava_v1",
|
| 48 |
+
type=str,
|
| 49 |
+
choices=["llava_v1", "llava_llama_2"],
|
| 50 |
+
)
|
| 51 |
+
return parser.parse_args(args)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def preprocess(
|
| 55 |
+
x,
|
| 56 |
+
pixel_mean=torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1),
|
| 57 |
+
pixel_std=torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1),
|
| 58 |
+
img_size=1024,
|
| 59 |
+
) -> torch.Tensor:
|
| 60 |
+
"""Normalize pixel values and pad to a square input."""
|
| 61 |
+
# Normalize colors
|
| 62 |
+
x = (x - pixel_mean) / pixel_std
|
| 63 |
+
# Pad
|
| 64 |
+
h, w = x.shape[-2:]
|
| 65 |
+
padh = img_size - h
|
| 66 |
+
padw = img_size - w
|
| 67 |
+
x = F.pad(x, (0, padw, 0, padh))
|
| 68 |
+
return x
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
args = parse_args(sys.argv[1:])
|
| 72 |
+
os.makedirs(args.vis_save_path, exist_ok=True)
|
| 73 |
+
|
| 74 |
+
# Create model
|
| 75 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 76 |
+
args.version,
|
| 77 |
+
cache_dir=None,
|
| 78 |
+
model_max_length=args.model_max_length,
|
| 79 |
+
padding_side="right",
|
| 80 |
+
use_fast=False,
|
| 81 |
+
)
|
| 82 |
+
tokenizer.pad_token = tokenizer.unk_token
|
| 83 |
+
args.seg_token_idx = tokenizer("[SEG]", add_special_tokens=False).input_ids[0]
|
| 84 |
+
|
| 85 |
+
torch_dtype = torch.float32
|
| 86 |
+
if args.precision == "bf16":
|
| 87 |
+
torch_dtype = torch.bfloat16
|
| 88 |
+
elif args.precision == "fp16":
|
| 89 |
+
torch_dtype = torch.half
|
| 90 |
+
|
| 91 |
+
kwargs = {"torch_dtype": torch_dtype}
|
| 92 |
+
if args.load_in_4bit:
|
| 93 |
+
kwargs.update(
|
| 94 |
+
{
|
| 95 |
+
"torch_dtype": torch.half,
|
| 96 |
+
"load_in_4bit": True,
|
| 97 |
+
"quantization_config": BitsAndBytesConfig(
|
| 98 |
+
load_in_4bit=True,
|
| 99 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 100 |
+
bnb_4bit_use_double_quant=True,
|
| 101 |
+
bnb_4bit_quant_type="nf4",
|
| 102 |
+
llm_int8_skip_modules=["visual_model"],
|
| 103 |
+
),
|
| 104 |
+
}
|
| 105 |
+
)
|
| 106 |
+
elif args.load_in_8bit:
|
| 107 |
+
kwargs.update(
|
| 108 |
+
{
|
| 109 |
+
"torch_dtype": torch.half,
|
| 110 |
+
"quantization_config": BitsAndBytesConfig(
|
| 111 |
+
llm_int8_skip_modules=["visual_model"],
|
| 112 |
+
load_in_8bit=True,
|
| 113 |
+
),
|
| 114 |
+
}
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
model = LISAForCausalLM.from_pretrained(
|
| 118 |
+
args.version, low_cpu_mem_usage=True, vision_tower=args.vision_tower, seg_token_idx=args.seg_token_idx, **kwargs
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
model.config.eos_token_id = tokenizer.eos_token_id
|
| 122 |
+
model.config.bos_token_id = tokenizer.bos_token_id
|
| 123 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
| 124 |
+
|
| 125 |
+
model.get_model().initialize_vision_modules(model.get_model().config)
|
| 126 |
+
vision_tower = model.get_model().get_vision_tower()
|
| 127 |
+
vision_tower.to(dtype=torch_dtype)
|
| 128 |
+
|
| 129 |
+
if args.precision == "bf16":
|
| 130 |
+
model = model.bfloat16().cuda()
|
| 131 |
+
elif (
|
| 132 |
+
args.precision == "fp16" and (not args.load_in_4bit) and (not args.load_in_8bit)
|
| 133 |
+
):
|
| 134 |
+
vision_tower = model.get_model().get_vision_tower()
|
| 135 |
+
model.model.vision_tower = None
|
| 136 |
+
import deepspeed
|
| 137 |
+
|
| 138 |
+
model_engine = deepspeed.init_inference(
|
| 139 |
+
model=model,
|
| 140 |
+
dtype=torch.half,
|
| 141 |
+
replace_with_kernel_inject=True,
|
| 142 |
+
replace_method="auto",
|
| 143 |
+
)
|
| 144 |
+
model = model_engine.module
|
| 145 |
+
model.model.vision_tower = vision_tower.half().cuda()
|
| 146 |
+
elif args.precision == "fp32":
|
| 147 |
+
model = model.float().cuda()
|
| 148 |
+
|
| 149 |
+
vision_tower = model.get_model().get_vision_tower()
|
| 150 |
+
vision_tower.to(device=args.local_rank)
|
| 151 |
+
|
| 152 |
+
clip_image_processor = CLIPImageProcessor.from_pretrained(model.config.vision_tower)
|
| 153 |
+
transform = ResizeLongestSide(args.image_size)
|
| 154 |
+
|
| 155 |
+
model.eval()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# Gradio
|
| 159 |
+
examples = [
|
| 160 |
+
[
|
| 161 |
+
"Where can the driver see the car speed in this image? Please output segmentation mask.",
|
| 162 |
+
"./resources/imgs/example1.jpg",
|
| 163 |
+
],
|
| 164 |
+
[
|
| 165 |
+
"Can you segment the food that tastes spicy and hot?",
|
| 166 |
+
"./resources/imgs/example2.jpg",
|
| 167 |
+
],
|
| 168 |
+
[
|
| 169 |
+
"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.",
|
| 170 |
+
"./resources/imgs/example1.jpg",
|
| 171 |
+
],
|
| 172 |
+
[
|
| 173 |
+
"What can make the woman stand higher? Please output segmentation mask and explain why.",
|
| 174 |
+
"./resources/imgs/example3.jpg",
|
| 175 |
+
],
|
| 176 |
+
]
|
| 177 |
+
output_labels = ["Segmentation Output"]
|
| 178 |
+
|
| 179 |
+
title = "LISA: Reasoning Segmentation via Large Language Model"
|
| 180 |
+
|
| 181 |
+
description = """
|
| 182 |
+
<font size=4>
|
| 183 |
+
This is the online demo of LISA. \n
|
| 184 |
+
If multiple users are using it at the same time, they will enter a queue, which may delay some time. \n
|
| 185 |
+
**Note**: **Different prompts can lead to significantly varied results**. \n
|
| 186 |
+
**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
|
| 187 |
+
**Note**: Current model is **LISA-13B-llama2-v0-explanatory**, and 4-bit quantization may impair text-generation quality. \n
|
| 188 |
+
**Usage**: <br>
|
| 189 |
+
 (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>
|
| 190 |
+
 (2) To let LISA **output an explanation**, input prompt like: "What is xxx in this image? Please output segmentation mask and explain why."; <br>
|
| 191 |
+
 (3) To obtain **solely language output**, you can input like what you should do in current multi-modal LLM (e.g., LLaVA). <br>
|
| 192 |
+
Hope you can enjoy our work!
|
| 193 |
+
</font>
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
article = """
|
| 197 |
+
<p style='text-align: center'>
|
| 198 |
+
<a href='https://arxiv.org/abs/2308.00692' target='_blank'>
|
| 199 |
+
Preprint Paper
|
| 200 |
+
</a>
|
| 201 |
+
\n
|
| 202 |
+
<p style='text-align: center'>
|
| 203 |
+
<a href='https://github.com/dvlab-research/LISA' target='_blank'> Github Repo </a></p>
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
## to be implemented
|
| 208 |
+
def inference(input_str, input_image):
|
| 209 |
+
## filter out special chars
|
| 210 |
+
input_str = bleach.clean(input_str)
|
| 211 |
+
|
| 212 |
+
print("input_str: ", input_str, "input_image: ", input_image)
|
| 213 |
+
|
| 214 |
+
## input valid check
|
| 215 |
+
if not re.match(r"^[A-Za-z ,.!?\'\"]+$", input_str) or len(input_str) < 1:
|
| 216 |
+
output_str = "[Error] Invalid input: ", input_str
|
| 217 |
+
# output_image = np.zeros((128, 128, 3))
|
| 218 |
+
## error happened
|
| 219 |
+
output_image = cv2.imread("./resources/error_happened.png")[:, :, ::-1]
|
| 220 |
+
return output_image, output_str
|
| 221 |
+
|
| 222 |
+
# Model Inference
|
| 223 |
+
conv = conversation_lib.conv_templates[args.conv_type].copy()
|
| 224 |
+
conv.messages = []
|
| 225 |
+
|
| 226 |
+
prompt = input_str
|
| 227 |
+
prompt = DEFAULT_IMAGE_TOKEN + "\n" + prompt
|
| 228 |
+
if args.use_mm_start_end:
|
| 229 |
+
replace_token = (
|
| 230 |
+
DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
|
| 231 |
+
)
|
| 232 |
+
prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
| 233 |
+
|
| 234 |
+
conv.append_message(conv.roles[0], prompt)
|
| 235 |
+
conv.append_message(conv.roles[1], "")
|
| 236 |
+
prompt = conv.get_prompt()
|
| 237 |
+
|
| 238 |
+
image_np = cv2.imread(input_image)
|
| 239 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
|
| 240 |
+
original_size_list = [image_np.shape[:2]]
|
| 241 |
+
|
| 242 |
+
image_clip = (
|
| 243 |
+
clip_image_processor.preprocess(image_np, return_tensors="pt")[
|
| 244 |
+
"pixel_values"
|
| 245 |
+
][0]
|
| 246 |
+
.unsqueeze(0)
|
| 247 |
+
.cuda()
|
| 248 |
+
)
|
| 249 |
+
if args.precision == "bf16":
|
| 250 |
+
image_clip = image_clip.bfloat16()
|
| 251 |
+
elif args.precision == "fp16":
|
| 252 |
+
image_clip = image_clip.half()
|
| 253 |
+
else:
|
| 254 |
+
image_clip = image_clip.float()
|
| 255 |
+
|
| 256 |
+
image = transform.apply_image(image_np)
|
| 257 |
+
resize_list = [image.shape[:2]]
|
| 258 |
+
|
| 259 |
+
image = (
|
| 260 |
+
preprocess(torch.from_numpy(image).permute(2, 0, 1).contiguous())
|
| 261 |
+
.unsqueeze(0)
|
| 262 |
+
.cuda()
|
| 263 |
+
)
|
| 264 |
+
if args.precision == "bf16":
|
| 265 |
+
image = image.bfloat16()
|
| 266 |
+
elif args.precision == "fp16":
|
| 267 |
+
image = image.half()
|
| 268 |
+
else:
|
| 269 |
+
image = image.float()
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
| 273 |
+
input_ids = input_ids.unsqueeze(0).cuda()
|
| 274 |
+
|
| 275 |
+
output_ids, pred_masks = model.evaluate(
|
| 276 |
+
image_clip,
|
| 277 |
+
image,
|
| 278 |
+
input_ids,
|
| 279 |
+
resize_list,
|
| 280 |
+
original_size_list,
|
| 281 |
+
max_new_tokens=512,
|
| 282 |
+
tokenizer=tokenizer,
|
| 283 |
+
)
|
| 284 |
+
output_ids = output_ids[0][output_ids[0] != IMAGE_TOKEN_INDEX]
|
| 285 |
+
|
| 286 |
+
text_output = tokenizer.decode(output_ids, skip_special_tokens=False)
|
| 287 |
+
text_output = text_output.replace("\n", "").replace(" ", " ")
|
| 288 |
+
text_output = text_output.split("ASSISTANT: ")[-1]
|
| 289 |
+
|
| 290 |
+
print("text_output: ", text_output)
|
| 291 |
+
save_img = None
|
| 292 |
+
for i, pred_mask in enumerate(pred_masks):
|
| 293 |
+
if pred_mask.shape[0] == 0:
|
| 294 |
+
continue
|
| 295 |
+
|
| 296 |
+
pred_mask_np = pred_mask.detach().cpu().numpy()[0]
|
| 297 |
+
|
| 298 |
+
# Normalize the continuous score mask to 0-255 range for visualization
|
| 299 |
+
min_val = float(pred_mask_np.min())
|
| 300 |
+
max_val = float(pred_mask_np.max())
|
| 301 |
+
# Avoid division by zero if min_val == max_val
|
| 302 |
+
denom = (max_val - min_val) if (max_val - min_val) != 0 else 1e-8
|
| 303 |
+
|
| 304 |
+
# Normalize to [0, 255] for image display
|
| 305 |
+
normalized_mask = ((pred_mask_np - min_val) / denom * 255).astype(np.uint8)
|
| 306 |
+
|
| 307 |
+
# Apply colormap (jet) to create a colored visualization
|
| 308 |
+
save_img = cv2.applyColorMap(normalized_mask, cv2.COLORMAP_VIRIDIS)
|
| 309 |
+
save_img = cv2.cvtColor(save_img, cv2.COLOR_BGR2RGB)
|
| 310 |
+
|
| 311 |
+
# -------------------------------------------------------------
|
| 312 |
+
# Add a vertical legend (color bar) to the right of save_img
|
| 313 |
+
# -------------------------------------------------------------
|
| 314 |
+
legend_width = 30
|
| 315 |
+
legend_height = save_img.shape[0]
|
| 316 |
+
# Create vertical gradient from 255 (top) to 0 (bottom)
|
| 317 |
+
gradient = np.linspace(255, 0, legend_height, dtype=np.uint8).reshape(-1, 1)
|
| 318 |
+
gradient = np.repeat(gradient, legend_width, axis=1)
|
| 319 |
+
legend_color = cv2.applyColorMap(gradient, cv2.COLORMAP_VIRIDIS)
|
| 320 |
+
legend_color = cv2.cvtColor(legend_color, cv2.COLOR_BGR2RGB)
|
| 321 |
+
|
| 322 |
+
# Put min / max text on legend
|
| 323 |
+
font = cv2.FONT_HERSHEY_SIMPLEX
|
| 324 |
+
font_scale = 0.4
|
| 325 |
+
thickness = 1
|
| 326 |
+
cv2.putText(legend_color, f"{max_val:.2f}", (2, 12), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
|
| 327 |
+
cv2.putText(legend_color, f"{min_val:.2f}", (2, legend_height - 4), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
|
| 328 |
+
|
| 329 |
+
# Concatenate original visualization with legend
|
| 330 |
+
save_img = np.concatenate([save_img, legend_color], axis=1)
|
| 331 |
+
|
| 332 |
+
output_str = "ASSISTANT: " + text_output # input_str
|
| 333 |
+
if save_img is not None:
|
| 334 |
+
output_image = save_img # input_image
|
| 335 |
+
else:
|
| 336 |
+
## no seg output
|
| 337 |
+
output_image = cv2.imread("./resources/no_seg_out.png")[:, :, ::-1]
|
| 338 |
+
return output_image, output_str
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
demo = gr.Interface(
|
| 342 |
+
inference,
|
| 343 |
+
inputs=[
|
| 344 |
+
gr.Textbox(lines=1, placeholder=None, label="Text Instruction"),
|
| 345 |
+
gr.Image(type="filepath", label="Input Image"),
|
| 346 |
+
],
|
| 347 |
+
outputs=[
|
| 348 |
+
gr.Image(type="pil", label="Segmentation Output"),
|
| 349 |
+
gr.Textbox(lines=1, placeholder=None, label="Text Output"),
|
| 350 |
+
],
|
| 351 |
+
title=title,
|
| 352 |
+
description=description,
|
| 353 |
+
article=article,
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################
|
| 2 |
+
# chat.py
|
| 3 |
+
# Inference for LISA (terminal-based)
|
| 4 |
+
###############################
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
import cv2
|
| 11 |
+
from matplotlib import pyplot as plt
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from transformers import AutoTokenizer, BitsAndBytesConfig, CLIPImageProcessor
|
| 16 |
+
|
| 17 |
+
from model.LISA import LISAForCausalLM
|
| 18 |
+
from model.llava import conversation as conversation_lib
|
| 19 |
+
from model.llava.mm_utils import tokenizer_image_token
|
| 20 |
+
from model.segment_anything.utils.transforms import ResizeLongestSide
|
| 21 |
+
from utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN,
|
| 22 |
+
DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEX)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def parse_args(args):
|
| 26 |
+
parser = argparse.ArgumentParser(description="LISA chat")
|
| 27 |
+
parser.add_argument("--version", default="xinlai/LISA-13B-llama2-v1")
|
| 28 |
+
parser.add_argument("--vis_save_path", default="./vis_output", type=str)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--precision",
|
| 31 |
+
default="bf16",
|
| 32 |
+
type=str,
|
| 33 |
+
choices=["fp32", "bf16", "fp16"],
|
| 34 |
+
help="precision for inference",
|
| 35 |
+
)
|
| 36 |
+
parser.add_argument("--image_size", default=1024, type=int, help="image size")
|
| 37 |
+
parser.add_argument("--model_max_length", default=512, type=int)
|
| 38 |
+
parser.add_argument("--lora_r", default=8, type=int)
|
| 39 |
+
parser.add_argument(
|
| 40 |
+
"--vision-tower", default="openai/clip-vit-large-patch14", type=str
|
| 41 |
+
)
|
| 42 |
+
parser.add_argument("--local-rank", default=0, type=int, help="node rank")
|
| 43 |
+
parser.add_argument("--load_in_8bit", action="store_true", default=False)
|
| 44 |
+
parser.add_argument("--load_in_4bit", action="store_true", default=False)
|
| 45 |
+
parser.add_argument("--use_mm_start_end", action="store_true", default=True)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--conv_type",
|
| 48 |
+
default="llava_v1",
|
| 49 |
+
type=str,
|
| 50 |
+
choices=["llava_v1", "llava_llama_2"],
|
| 51 |
+
)
|
| 52 |
+
return parser.parse_args(args)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def preprocess(
|
| 56 |
+
x,
|
| 57 |
+
pixel_mean=torch.Tensor([123.675, 116.28, 103.53]).view(-1, 1, 1),
|
| 58 |
+
pixel_std=torch.Tensor([58.395, 57.12, 57.375]).view(-1, 1, 1),
|
| 59 |
+
img_size=1024,
|
| 60 |
+
) -> torch.Tensor:
|
| 61 |
+
"""Normalize pixel values and pad to a square input."""
|
| 62 |
+
# Normalize colors
|
| 63 |
+
x = (x - pixel_mean) / pixel_std
|
| 64 |
+
# Pad
|
| 65 |
+
h, w = x.shape[-2:]
|
| 66 |
+
padh = img_size - h
|
| 67 |
+
padw = img_size - w
|
| 68 |
+
x = F.pad(x, (0, padw, 0, padh))
|
| 69 |
+
return x
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def main(args):
|
| 73 |
+
args = parse_args(args)
|
| 74 |
+
os.makedirs(args.vis_save_path, exist_ok=True)
|
| 75 |
+
|
| 76 |
+
# NOTE: NO NEED?
|
| 77 |
+
# if args.version == "BigData-KSU/RS-llava-v1.5-7b-LoRA":
|
| 78 |
+
# tokenizer_base = 'Intel/neural-chat-7b-v3-3'
|
| 79 |
+
# else:
|
| 80 |
+
# tokenizer_base = args.version
|
| 81 |
+
|
| 82 |
+
# Create model
|
| 83 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 84 |
+
args.version, # tokenizer_base?
|
| 85 |
+
cache_dir=None,
|
| 86 |
+
model_max_length=args.model_max_length,
|
| 87 |
+
padding_side="right",
|
| 88 |
+
use_fast=False,
|
| 89 |
+
)
|
| 90 |
+
tokenizer.pad_token = tokenizer.unk_token
|
| 91 |
+
# num_added_tokens = tokenizer.add_tokens("[SEG]") # NOTE: NO NEED?
|
| 92 |
+
args.seg_token_idx = tokenizer("[SEG]", add_special_tokens=False).input_ids[0]
|
| 93 |
+
|
| 94 |
+
# NOTE: NO NEED?
|
| 95 |
+
# if args.use_mm_start_end:
|
| 96 |
+
# tokenizer.add_tokens(
|
| 97 |
+
# [DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
|
| 98 |
+
# )
|
| 99 |
+
|
| 100 |
+
torch_dtype = torch.float32
|
| 101 |
+
if args.precision == "bf16":
|
| 102 |
+
torch_dtype = torch.bfloat16
|
| 103 |
+
elif args.precision == "fp16":
|
| 104 |
+
torch_dtype = torch.half
|
| 105 |
+
|
| 106 |
+
kwargs = {"torch_dtype": torch_dtype}
|
| 107 |
+
if args.load_in_4bit:
|
| 108 |
+
kwargs.update(
|
| 109 |
+
{
|
| 110 |
+
"torch_dtype": torch.half,
|
| 111 |
+
"load_in_4bit": True,
|
| 112 |
+
"quantization_config": BitsAndBytesConfig(
|
| 113 |
+
load_in_4bit=True,
|
| 114 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 115 |
+
bnb_4bit_use_double_quant=True,
|
| 116 |
+
bnb_4bit_quant_type="nf4",
|
| 117 |
+
llm_int8_skip_modules=["visual_model"],
|
| 118 |
+
),
|
| 119 |
+
}
|
| 120 |
+
)
|
| 121 |
+
elif args.load_in_8bit:
|
| 122 |
+
kwargs.update(
|
| 123 |
+
{
|
| 124 |
+
"torch_dtype": torch.half,
|
| 125 |
+
"quantization_config": BitsAndBytesConfig(
|
| 126 |
+
llm_int8_skip_modules=["visual_model"],
|
| 127 |
+
load_in_8bit=True,
|
| 128 |
+
),
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
model = LISAForCausalLM.from_pretrained(
|
| 133 |
+
args.version, low_cpu_mem_usage=True, vision_tower=args.vision_tower, seg_token_idx=args.seg_token_idx, **kwargs
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
model.config.eos_token_id = tokenizer.eos_token_id
|
| 137 |
+
model.config.bos_token_id = tokenizer.bos_token_id
|
| 138 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
| 139 |
+
|
| 140 |
+
model.get_model().initialize_vision_modules(model.get_model().config)
|
| 141 |
+
vision_tower = model.get_model().get_vision_tower()
|
| 142 |
+
vision_tower.to(dtype=torch_dtype)
|
| 143 |
+
|
| 144 |
+
if args.precision == "bf16":
|
| 145 |
+
model = model.bfloat16().cuda()
|
| 146 |
+
elif (
|
| 147 |
+
args.precision == "fp16" and (not args.load_in_4bit) and (not args.load_in_8bit)
|
| 148 |
+
):
|
| 149 |
+
vision_tower = model.get_model().get_vision_tower()
|
| 150 |
+
model.model.vision_tower = None
|
| 151 |
+
import deepspeed
|
| 152 |
+
|
| 153 |
+
model_engine = deepspeed.init_inference(
|
| 154 |
+
model=model,
|
| 155 |
+
dtype=torch.half,
|
| 156 |
+
replace_with_kernel_inject=True,
|
| 157 |
+
replace_method="auto",
|
| 158 |
+
)
|
| 159 |
+
model = model_engine.module
|
| 160 |
+
model.model.vision_tower = vision_tower.half().cuda()
|
| 161 |
+
elif args.precision == "fp32":
|
| 162 |
+
model = model.float().cuda()
|
| 163 |
+
|
| 164 |
+
vision_tower = model.get_model().get_vision_tower()
|
| 165 |
+
vision_tower.to(device=args.local_rank)
|
| 166 |
+
|
| 167 |
+
clip_image_processor = CLIPImageProcessor.from_pretrained(model.config.vision_tower)
|
| 168 |
+
transform = ResizeLongestSide(args.image_size)
|
| 169 |
+
|
| 170 |
+
model.eval()
|
| 171 |
+
|
| 172 |
+
while True:
|
| 173 |
+
conv = conversation_lib.conv_templates[args.conv_type].copy()
|
| 174 |
+
conv.messages = []
|
| 175 |
+
|
| 176 |
+
question = input("Please input your prompt: ")
|
| 177 |
+
prompt = DEFAULT_IMAGE_TOKEN + "\n" + question
|
| 178 |
+
if args.use_mm_start_end:
|
| 179 |
+
replace_token = (
|
| 180 |
+
DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN
|
| 181 |
+
)
|
| 182 |
+
prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, replace_token)
|
| 183 |
+
|
| 184 |
+
conv.append_message(conv.roles[0], prompt)
|
| 185 |
+
conv.append_message(conv.roles[1], "")
|
| 186 |
+
prompt = conv.get_prompt()
|
| 187 |
+
|
| 188 |
+
image_path = input("Please input the image path: ")
|
| 189 |
+
if not os.path.exists(image_path):
|
| 190 |
+
print("File not found in {}".format(image_path))
|
| 191 |
+
continue
|
| 192 |
+
|
| 193 |
+
image_np = cv2.imread(image_path)
|
| 194 |
+
image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
|
| 195 |
+
original_size_list = [image_np.shape[:2]]
|
| 196 |
+
|
| 197 |
+
image_clip = (
|
| 198 |
+
clip_image_processor.preprocess(image_np, return_tensors="pt")[
|
| 199 |
+
"pixel_values"
|
| 200 |
+
][0]
|
| 201 |
+
.unsqueeze(0)
|
| 202 |
+
.cuda()
|
| 203 |
+
)
|
| 204 |
+
if args.precision == "bf16":
|
| 205 |
+
image_clip = image_clip.bfloat16()
|
| 206 |
+
elif args.precision == "fp16":
|
| 207 |
+
image_clip = image_clip.half()
|
| 208 |
+
else:
|
| 209 |
+
image_clip = image_clip.float()
|
| 210 |
+
|
| 211 |
+
image = transform.apply_image(image_np)
|
| 212 |
+
resize_list = [image.shape[:2]]
|
| 213 |
+
|
| 214 |
+
image = (
|
| 215 |
+
preprocess(torch.from_numpy(image).permute(2, 0, 1).contiguous())
|
| 216 |
+
.unsqueeze(0)
|
| 217 |
+
.cuda()
|
| 218 |
+
)
|
| 219 |
+
if args.precision == "bf16":
|
| 220 |
+
image = image.bfloat16()
|
| 221 |
+
elif args.precision == "fp16":
|
| 222 |
+
image = image.half()
|
| 223 |
+
else:
|
| 224 |
+
image = image.float()
|
| 225 |
+
|
| 226 |
+
input_ids = tokenizer_image_token(prompt, tokenizer, return_tensors="pt")
|
| 227 |
+
input_ids = input_ids.unsqueeze(0).cuda()
|
| 228 |
+
|
| 229 |
+
output_ids, pred_masks = model.evaluate(
|
| 230 |
+
image_clip,
|
| 231 |
+
image,
|
| 232 |
+
input_ids,
|
| 233 |
+
resize_list,
|
| 234 |
+
original_size_list,
|
| 235 |
+
max_new_tokens=512,
|
| 236 |
+
tokenizer=tokenizer,
|
| 237 |
+
)
|
| 238 |
+
output_ids = output_ids[0][output_ids[0] != IMAGE_TOKEN_INDEX]
|
| 239 |
+
|
| 240 |
+
text_output = tokenizer.decode(output_ids, skip_special_tokens=False)
|
| 241 |
+
text_output = text_output.replace("\n", "").replace(" ", " ")
|
| 242 |
+
print("text_output: ", text_output)
|
| 243 |
+
|
| 244 |
+
# for i, pred_mask in enumerate(pred_masks):
|
| 245 |
+
# if pred_mask.shape[0] == 0:
|
| 246 |
+
# continue
|
| 247 |
+
|
| 248 |
+
# print("min pre_mask: ", pred_mask.min())
|
| 249 |
+
# print("max pre_mask: ", pred_mask.max())
|
| 250 |
+
|
| 251 |
+
# pred_mask = pred_mask.detach().cpu().numpy()[0]
|
| 252 |
+
# pred_mask = pred_mask > 0
|
| 253 |
+
|
| 254 |
+
# save_path = "{}/{}_mask_{}.jpg".format(
|
| 255 |
+
# args.vis_save_path, image_path.split("/")[-1].split(".")[0], i
|
| 256 |
+
# )
|
| 257 |
+
# cv2.imwrite(save_path, pred_mask * 100)
|
| 258 |
+
# print("{} has been saved.".format(save_path))
|
| 259 |
+
|
| 260 |
+
# save_path = "{}/{}_masked_img_{}.jpg".format(
|
| 261 |
+
# args.vis_save_path, image_path.split("/")[-1].split(".")[0], i
|
| 262 |
+
# )
|
| 263 |
+
# save_img = image_np.copy()
|
| 264 |
+
# save_img[pred_mask] = (
|
| 265 |
+
# image_np * 0.5
|
| 266 |
+
# + pred_mask[:, :, None].astype(np.uint8) * np.array([255, 0, 0]) * 0.5
|
| 267 |
+
# )[pred_mask]
|
| 268 |
+
# save_img = cv2.cvtColor(save_img, cv2.COLOR_RGB2BGR)
|
| 269 |
+
# cv2.imwrite(save_path, save_img)
|
| 270 |
+
# print("{} has been saved.".format(save_path))
|
| 271 |
+
|
| 272 |
+
for i, pred_mask in enumerate(pred_masks):
|
| 273 |
+
if pred_mask.shape[0] == 0:
|
| 274 |
+
continue
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------------
|
| 277 |
+
# 1) Prepare / detach / copy stuff
|
| 278 |
+
# ------------------------------------------------------------------
|
| 279 |
+
# Convert torch tensor -> NumPy
|
| 280 |
+
pred_mask_np = pred_mask.detach().cpu().numpy()[0]
|
| 281 |
+
# Convert your image from RGB to a float NumPy array if needed
|
| 282 |
+
# (Adjust as necessary depending on your original image data type)
|
| 283 |
+
image_rgb = image_np.astype(np.float32) # shape (H, W, 3)
|
| 284 |
+
|
| 285 |
+
# ------------------------------------------------------------------
|
| 286 |
+
# 2) Create the Binary Mask & Overlaid Image (subplot #2)
|
| 287 |
+
# ------------------------------------------------------------------
|
| 288 |
+
# Binary threshold (> 0)
|
| 289 |
+
binary_mask = pred_mask_np > 0
|
| 290 |
+
|
| 291 |
+
# Make a copy of the original image for overlaying
|
| 292 |
+
masked_image = image_rgb.copy()
|
| 293 |
+
|
| 294 |
+
# Option A: Simple half-blend with red for the masked area
|
| 295 |
+
# We only modify pixels where binary_mask is True
|
| 296 |
+
red_color = np.array([255, 0, 0], dtype=np.float32)
|
| 297 |
+
blended_red = image_rgb[binary_mask] * 0.5 + red_color * 0.5
|
| 298 |
+
masked_image[binary_mask] = blended_red
|
| 299 |
+
|
| 300 |
+
# ------------------------------------------------------------------
|
| 301 |
+
# 3) Create the Raw Mask (subplot #3) + Colorbar
|
| 302 |
+
# ------------------------------------------------------------------
|
| 303 |
+
min_val = float(pred_mask_np.min())
|
| 304 |
+
max_val = float(pred_mask_np.max())
|
| 305 |
+
# Avoid division by zero if min_val == max_val
|
| 306 |
+
denom = (max_val - min_val) if (max_val - min_val) != 0 else 1e-8
|
| 307 |
+
|
| 308 |
+
# Normalize to [0, 1]
|
| 309 |
+
normalized_mask = (pred_mask_np - min_val) / denom
|
| 310 |
+
|
| 311 |
+
# ------------------------------------------------------------------
|
| 312 |
+
# 4) Plot everything with Matplotlib
|
| 313 |
+
# ------------------------------------------------------------------
|
| 314 |
+
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))
|
| 315 |
+
|
| 316 |
+
# (Left) Original Image
|
| 317 |
+
ax1.imshow(image_rgb.astype(np.uint8))
|
| 318 |
+
ax1.set_title("Original Image")
|
| 319 |
+
ax1.axis("off")
|
| 320 |
+
|
| 321 |
+
# (Middle) Binary Mask Overlaid
|
| 322 |
+
ax2.imshow(masked_image.astype(np.uint8))
|
| 323 |
+
ax2.set_title("Binary Mask (>0) in Red")
|
| 324 |
+
ax2.axis("off")
|
| 325 |
+
|
| 326 |
+
# (Right) Raw Mask with Colorbar
|
| 327 |
+
# Show the normalized mask in [0..1] range, but apply a color map
|
| 328 |
+
im3 = ax3.imshow(normalized_mask, cmap='jet', vmin=0, vmax=1)
|
| 329 |
+
ax3.set_title("Raw Mask (Continuous)")
|
| 330 |
+
ax3.axis("off")
|
| 331 |
+
|
| 332 |
+
# Add a colorbar to the third subplot
|
| 333 |
+
cbar = fig.colorbar(im3, ax=ax3, fraction=0.046, pad=0.04)
|
| 334 |
+
cbar.set_label("Normalized Mask Value")
|
| 335 |
+
|
| 336 |
+
# Add a main title (optional)
|
| 337 |
+
fig.suptitle(f"Question: {question}")
|
| 338 |
+
answer = text_output[text_output.find("ASSISTANT"):]
|
| 339 |
+
fig.text(0.5, 0.05, f"{answer}", ha='center', va='center')
|
| 340 |
+
|
| 341 |
+
# ------------------------------------------------------------------
|
| 342 |
+
# 5) Show the figure, then save after it’s closed
|
| 343 |
+
# ------------------------------------------------------------------
|
| 344 |
+
# When plt.show() returns, the figure is closed if interactive mode is off.
|
| 345 |
+
plt.show(block=True) # This pauses execution until the window is closed.
|
| 346 |
+
|
| 347 |
+
# Now save the figure
|
| 348 |
+
save_path = "{}/{}_matplotlib_{}.png".format(
|
| 349 |
+
args.vis_save_path, image_path.split("/")[-1].split(".")[0], i
|
| 350 |
+
)
|
| 351 |
+
fig.savefig(save_path)
|
| 352 |
+
print(f"Figure saved to: {save_path}")
|
| 353 |
+
|
| 354 |
+
# Finally close the figure to free memory
|
| 355 |
+
plt.close(fig)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
if __name__ == "__main__":
|
| 359 |
+
main(sys.argv[1:])
|
imgs/blackpink.jpg
ADDED
|
Git LFS Details
|
imgs/camera_lens.jpg
ADDED
|
Git LFS Details
|
imgs/car_speed.jpg
ADDED
|
Git LFS Details
|
imgs/dog_with_horn.jpg
ADDED
|
Git LFS Details
|
imgs/example1.jpg
ADDED
|
Git LFS Details
|
imgs/example2.jpg
ADDED
|
Git LFS Details
|
imgs/fig_overview.jpg
ADDED
|
Git LFS Details
|
imgs/jackma.jpg
ADDED
|
Git LFS Details
|
imgs/obama.jpg
ADDED
|
Git LFS Details
|
imgs/stand_higher.jpg
ADDED
|
Git LFS Details
|
imgs/table1.jpg
ADDED
|
Git LFS Details
|
imgs/teaser.jpg
ADDED
|
Git LFS Details
|
imgs/trump.jpg
ADDED
|
Git LFS Details
|
imgs/wash_hands.jpg
ADDED
|
Git LFS Details
|
merge_lora_weights_and_save_hf_model.py
ADDED
|
@@ -0,0 +1,159 @@
|
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|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 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 = "<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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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=None, # outputs.past_key_values, https://github.com/dvlab-research/LISA/issues/117
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 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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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
N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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|